text
stringlengths
54
60.6k
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/robot_model/robot_model.h> #include <moveit/robot_state/robot_state.h> #include <moveit/robot_state/conversions.h> #include <urdf_parser/urdf_parser.h> #include <fstream> #include <gtest/gtest.h> #include <boost/filesystem/path.hpp> #include <geometric_shapes/shapes.h> #include <moveit/profiler/profiler.h> #include <moveit_resources/config.h> class LoadPlanningModelsPr2 : public testing::Test { protected: virtual void SetUp() { boost::filesystem::path res_path(MOVEIT_TEST_RESOURCES_DIR); srdf_model.reset(new srdf::Model()); std::string xml_string; std::fstream xml_file((res_path / "pr2_description/urdf/robot.xml").string().c_str(), std::fstream::in); if (xml_file.is_open()) { while (xml_file.good()) { std::string line; std::getline(xml_file, line); xml_string += (line + "\n"); } xml_file.close(); urdf_model = urdf::parseURDF(xml_string); } srdf_model->initFile(*urdf_model, (res_path / "pr2_description/srdf/robot.xml").string()); robot_model.reset(new moveit::core::RobotModel(urdf_model, srdf_model)); }; virtual void TearDown() { } protected: urdf::ModelInterfaceSharedPtr urdf_model; srdf::ModelSharedPtr srdf_model; moveit::core::RobotModelConstPtr robot_model; }; TEST_F(LoadPlanningModelsPr2, InitOK) { ASSERT_EQ(urdf_model->getName(), "pr2"); ASSERT_EQ(srdf_model->getName(), "pr2"); } TEST_F(LoadPlanningModelsPr2, ModelInit) { srdf::ModelSharedPtr srdfModel(new srdf::Model()); // with no world multidof we should get a fixed joint moveit::core::RobotModel robot_model0(urdf_model, srdfModel); EXPECT_TRUE(robot_model0.getRootJoint()->getVariableCount() == 0); static const std::string SMODEL1 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"base_joint\" child_link=\"base_footprint\" " "parent_frame=\"base_footprint\" type=\"planar\"/>" "</robot>"; srdfModel->initString(*urdf_model, SMODEL1); moveit::core::RobotModel robot_model1(urdf_model, srdfModel); ASSERT_TRUE(robot_model1.getRootJoint() != NULL); EXPECT_EQ(robot_model1.getModelFrame(), "/base_footprint"); static const std::string SMODEL2 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"world_joint\" child_link=\"base_footprint\" " "parent_frame=\"odom_combined\" type=\"floating\"/>" "</robot>"; srdfModel->initString(*urdf_model, SMODEL2); moveit::core::RobotModel robot_model2(urdf_model, srdfModel); ASSERT_TRUE(robot_model2.getRootJoint() != NULL); EXPECT_EQ(robot_model2.getModelFrame(), "/odom_combined"); } TEST_F(LoadPlanningModelsPr2, GroupInit) { static const std::string SMODEL1 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"base_joint\" child_link=\"base_footprint\" " "parent_frame=\"base_footprint\" type=\"planar\"/>" "<group name=\"left_arm_base_tip\">" "<chain base_link=\"monkey_base\" tip_link=\"monkey_tip\"/>" "</group>" "<group name=\"left_arm_joints\">" "<joint name=\"l_monkey_pan_joint\"/>" "<joint name=\"l_monkey_fles_joint\"/>" "</group>" "</robot>"; srdf::ModelSharedPtr srdfModel(new srdf::Model()); srdfModel->initString(*urdf_model, SMODEL1); moveit::core::RobotModel robot_model1(urdf_model, srdfModel); const moveit::core::JointModelGroup* left_arm_base_tip_group = robot_model1.getJointModelGroup("left_arm_base_tip"); ASSERT_TRUE(left_arm_base_tip_group == NULL); const moveit::core::JointModelGroup* left_arm_joints_group = robot_model1.getJointModelGroup("left_arm_joints"); ASSERT_TRUE(left_arm_joints_group == NULL); static const std::string SMODEL2 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"base_joint\" child_link=\"base_footprint\" " "parent_frame=\"base_footprint\" type=\"planar\"/>" "<group name=\"left_arm_base_tip\">" "<chain base_link=\"torso_lift_link\" tip_link=\"l_wrist_roll_link\"/>" "</group>" "<group name=\"left_arm_joints\">" "<joint name=\"l_shoulder_pan_joint\"/>" "<joint name=\"l_shoulder_lift_joint\"/>" "<joint name=\"l_upper_arm_roll_joint\"/>" "<joint name=\"l_elbow_flex_joint\"/>" "<joint name=\"l_forearm_roll_joint\"/>" "<joint name=\"l_wrist_flex_joint\"/>" "<joint name=\"l_wrist_roll_joint\"/>" "</group>" "</robot>"; srdfModel->initString(*urdf_model, SMODEL2); moveit::core::RobotModelPtr robot_model2(new moveit::core::RobotModel(urdf_model, srdfModel)); left_arm_base_tip_group = robot_model2->getJointModelGroup("left_arm_base_tip"); ASSERT_TRUE(left_arm_base_tip_group != NULL); left_arm_joints_group = robot_model2->getJointModelGroup("left_arm_joints"); ASSERT_TRUE(left_arm_joints_group != NULL); EXPECT_EQ(left_arm_base_tip_group->getJointModels().size(), 9); EXPECT_EQ(left_arm_joints_group->getJointModels().size(), 7); EXPECT_EQ(left_arm_joints_group->getVariableNames().size(), left_arm_joints_group->getVariableCount()); EXPECT_EQ(left_arm_joints_group->getVariableCount(), 7); EXPECT_EQ(robot_model2->getVariableNames().size(), robot_model2->getVariableCount()); bool found_shoulder_pan_link = false; bool found_wrist_roll_link = false; for (unsigned int i = 0; i < left_arm_base_tip_group->getLinkModels().size(); i++) { if (left_arm_base_tip_group->getLinkModels()[i]->getName() == "l_shoulder_pan_link") { EXPECT_TRUE(found_shoulder_pan_link == false); found_shoulder_pan_link = true; } if (left_arm_base_tip_group->getLinkModels()[i]->getName() == "l_wrist_roll_link") { EXPECT_TRUE(found_wrist_roll_link == false); found_wrist_roll_link = true; } EXPECT_TRUE(left_arm_base_tip_group->getLinkModels()[i]->getName() != "torso_lift_link"); } EXPECT_TRUE(found_shoulder_pan_link); EXPECT_TRUE(found_wrist_roll_link); moveit::core::RobotState ks(robot_model2); ks.setToDefaultValues(); std::map<std::string, double> jv; jv["base_joint/x"] = 0.433; jv["base_joint/theta"] = -0.5; ks.setVariablePositions(jv); moveit_msgs::RobotState robot_state; moveit::core::robotStateToRobotStateMsg(ks, robot_state); moveit::core::RobotState ks2(robot_model2); moveit::core::robotStateMsgToRobotState(robot_state, ks2); const double* v1 = ks.getVariablePositions(); const double* v2 = ks2.getVariablePositions(); for (std::size_t i = 0; i < ks.getVariableCount(); ++i) EXPECT_NEAR(v1[i], v2[i], 1e-5); } TEST_F(LoadPlanningModelsPr2, SubgroupInit) { moveit::core::RobotModel robot_model(urdf_model, srdf_model); const moveit::core::JointModelGroup* jmg = robot_model.getJointModelGroup("arms"); ASSERT_TRUE(jmg); EXPECT_EQ(jmg->getSubgroupNames().size(), 2); EXPECT_TRUE(jmg->isSubgroup("right_arm")); const moveit::core::JointModelGroup* jmg2 = robot_model.getJointModelGroup("whole_body"); EXPECT_EQ(jmg2->getSubgroupNames().size(), 5); EXPECT_TRUE(jmg2->isSubgroup("arms")); EXPECT_TRUE(jmg2->isSubgroup("right_arm")); } TEST_F(LoadPlanningModelsPr2, AssociatedFixedLinks) { moveit::core::RobotModelPtr model(new moveit::core::RobotModel(urdf_model, srdf_model)); EXPECT_TRUE(model->getLinkModel("r_gripper_palm_link")->getAssociatedFixedTransforms().size() > 1); } TEST_F(LoadPlanningModelsPr2, FullTest) { moveit::core::RobotModelPtr robot_model(new moveit::core::RobotModel(urdf_model, srdf_model)); moveit::core::RobotState ks(robot_model); ks.setToDefaultValues(); moveit::core::RobotState ks2(robot_model); ks2.setToDefaultValues(); std::vector<shapes::ShapeConstPtr> shapes; EigenSTL::vector_Affine3d poses; shapes::Shape* shape = new shapes::Box(.1, .1, .1); shapes.push_back(shapes::ShapeConstPtr(shape)); poses.push_back(Eigen::Affine3d::Identity()); std::set<std::string> touch_links; trajectory_msgs::JointTrajectory empty_state; moveit::core::AttachedBody* attached_body = new moveit::core::AttachedBody( robot_model->getLinkModel("r_gripper_palm_link"), "box", shapes, poses, touch_links, empty_state); ks.attachBody(attached_body); std::vector<const moveit::core::AttachedBody*> attached_bodies_1; ks.getAttachedBodies(attached_bodies_1); ASSERT_EQ(attached_bodies_1.size(), 1); std::vector<const moveit::core::AttachedBody*> attached_bodies_2; ks2 = ks; ks2.getAttachedBodies(attached_bodies_2); ASSERT_EQ(attached_bodies_2.size(), 1); ks.clearAttachedBody("box"); attached_bodies_1.clear(); ks.getAttachedBodies(attached_bodies_1); ASSERT_EQ(attached_bodies_1.size(), 0); ks2 = ks; attached_bodies_2.clear(); ks2.getAttachedBodies(attached_bodies_2); ASSERT_EQ(attached_bodies_2.size(), 0); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>adapt unittests after update to tf2<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/robot_model/robot_model.h> #include <moveit/robot_state/robot_state.h> #include <moveit/robot_state/conversions.h> #include <urdf_parser/urdf_parser.h> #include <fstream> #include <gtest/gtest.h> #include <boost/filesystem/path.hpp> #include <geometric_shapes/shapes.h> #include <moveit/profiler/profiler.h> #include <moveit_resources/config.h> class LoadPlanningModelsPr2 : public testing::Test { protected: virtual void SetUp() { boost::filesystem::path res_path(MOVEIT_TEST_RESOURCES_DIR); srdf_model.reset(new srdf::Model()); std::string xml_string; std::fstream xml_file((res_path / "pr2_description/urdf/robot.xml").string().c_str(), std::fstream::in); if (xml_file.is_open()) { while (xml_file.good()) { std::string line; std::getline(xml_file, line); xml_string += (line + "\n"); } xml_file.close(); urdf_model = urdf::parseURDF(xml_string); } srdf_model->initFile(*urdf_model, (res_path / "pr2_description/srdf/robot.xml").string()); robot_model.reset(new moveit::core::RobotModel(urdf_model, srdf_model)); }; virtual void TearDown() { } protected: urdf::ModelInterfaceSharedPtr urdf_model; srdf::ModelSharedPtr srdf_model; moveit::core::RobotModelConstPtr robot_model; }; TEST_F(LoadPlanningModelsPr2, InitOK) { ASSERT_EQ(urdf_model->getName(), "pr2"); ASSERT_EQ(srdf_model->getName(), "pr2"); } TEST_F(LoadPlanningModelsPr2, ModelInit) { srdf::ModelSharedPtr srdfModel(new srdf::Model()); // with no world multidof we should get a fixed joint moveit::core::RobotModel robot_model0(urdf_model, srdfModel); EXPECT_TRUE(robot_model0.getRootJoint()->getVariableCount() == 0); static const std::string SMODEL1 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"base_joint\" child_link=\"base_footprint\" " "parent_frame=\"base_footprint\" type=\"planar\"/>" "</robot>"; srdfModel->initString(*urdf_model, SMODEL1); moveit::core::RobotModel robot_model1(urdf_model, srdfModel); ASSERT_TRUE(robot_model1.getRootJoint() != NULL); EXPECT_EQ(robot_model1.getModelFrame(), "base_footprint"); static const std::string SMODEL2 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"world_joint\" child_link=\"base_footprint\" " "parent_frame=\"odom_combined\" type=\"floating\"/>" "</robot>"; srdfModel->initString(*urdf_model, SMODEL2); moveit::core::RobotModel robot_model2(urdf_model, srdfModel); ASSERT_TRUE(robot_model2.getRootJoint() != NULL); EXPECT_EQ(robot_model2.getModelFrame(), "odom_combined"); } TEST_F(LoadPlanningModelsPr2, GroupInit) { static const std::string SMODEL1 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"base_joint\" child_link=\"base_footprint\" " "parent_frame=\"base_footprint\" type=\"planar\"/>" "<group name=\"left_arm_base_tip\">" "<chain base_link=\"monkey_base\" tip_link=\"monkey_tip\"/>" "</group>" "<group name=\"left_arm_joints\">" "<joint name=\"l_monkey_pan_joint\"/>" "<joint name=\"l_monkey_fles_joint\"/>" "</group>" "</robot>"; srdf::ModelSharedPtr srdfModel(new srdf::Model()); srdfModel->initString(*urdf_model, SMODEL1); moveit::core::RobotModel robot_model1(urdf_model, srdfModel); const moveit::core::JointModelGroup* left_arm_base_tip_group = robot_model1.getJointModelGroup("left_arm_base_tip"); ASSERT_TRUE(left_arm_base_tip_group == NULL); const moveit::core::JointModelGroup* left_arm_joints_group = robot_model1.getJointModelGroup("left_arm_joints"); ASSERT_TRUE(left_arm_joints_group == NULL); static const std::string SMODEL2 = "<?xml version=\"1.0\" ?>" "<robot name=\"pr2\">" "<virtual_joint name=\"base_joint\" child_link=\"base_footprint\" " "parent_frame=\"base_footprint\" type=\"planar\"/>" "<group name=\"left_arm_base_tip\">" "<chain base_link=\"torso_lift_link\" tip_link=\"l_wrist_roll_link\"/>" "</group>" "<group name=\"left_arm_joints\">" "<joint name=\"l_shoulder_pan_joint\"/>" "<joint name=\"l_shoulder_lift_joint\"/>" "<joint name=\"l_upper_arm_roll_joint\"/>" "<joint name=\"l_elbow_flex_joint\"/>" "<joint name=\"l_forearm_roll_joint\"/>" "<joint name=\"l_wrist_flex_joint\"/>" "<joint name=\"l_wrist_roll_joint\"/>" "</group>" "</robot>"; srdfModel->initString(*urdf_model, SMODEL2); moveit::core::RobotModelPtr robot_model2(new moveit::core::RobotModel(urdf_model, srdfModel)); left_arm_base_tip_group = robot_model2->getJointModelGroup("left_arm_base_tip"); ASSERT_TRUE(left_arm_base_tip_group != NULL); left_arm_joints_group = robot_model2->getJointModelGroup("left_arm_joints"); ASSERT_TRUE(left_arm_joints_group != NULL); EXPECT_EQ(left_arm_base_tip_group->getJointModels().size(), 9); EXPECT_EQ(left_arm_joints_group->getJointModels().size(), 7); EXPECT_EQ(left_arm_joints_group->getVariableNames().size(), left_arm_joints_group->getVariableCount()); EXPECT_EQ(left_arm_joints_group->getVariableCount(), 7); EXPECT_EQ(robot_model2->getVariableNames().size(), robot_model2->getVariableCount()); bool found_shoulder_pan_link = false; bool found_wrist_roll_link = false; for (unsigned int i = 0; i < left_arm_base_tip_group->getLinkModels().size(); i++) { if (left_arm_base_tip_group->getLinkModels()[i]->getName() == "l_shoulder_pan_link") { EXPECT_TRUE(found_shoulder_pan_link == false); found_shoulder_pan_link = true; } if (left_arm_base_tip_group->getLinkModels()[i]->getName() == "l_wrist_roll_link") { EXPECT_TRUE(found_wrist_roll_link == false); found_wrist_roll_link = true; } EXPECT_TRUE(left_arm_base_tip_group->getLinkModels()[i]->getName() != "torso_lift_link"); } EXPECT_TRUE(found_shoulder_pan_link); EXPECT_TRUE(found_wrist_roll_link); moveit::core::RobotState ks(robot_model2); ks.setToDefaultValues(); std::map<std::string, double> jv; jv["base_joint/x"] = 0.433; jv["base_joint/theta"] = -0.5; ks.setVariablePositions(jv); moveit_msgs::RobotState robot_state; moveit::core::robotStateToRobotStateMsg(ks, robot_state); moveit::core::RobotState ks2(robot_model2); moveit::core::robotStateMsgToRobotState(robot_state, ks2); const double* v1 = ks.getVariablePositions(); const double* v2 = ks2.getVariablePositions(); for (std::size_t i = 0; i < ks.getVariableCount(); ++i) EXPECT_NEAR(v1[i], v2[i], 1e-5); } TEST_F(LoadPlanningModelsPr2, SubgroupInit) { moveit::core::RobotModel robot_model(urdf_model, srdf_model); const moveit::core::JointModelGroup* jmg = robot_model.getJointModelGroup("arms"); ASSERT_TRUE(jmg); EXPECT_EQ(jmg->getSubgroupNames().size(), 2); EXPECT_TRUE(jmg->isSubgroup("right_arm")); const moveit::core::JointModelGroup* jmg2 = robot_model.getJointModelGroup("whole_body"); EXPECT_EQ(jmg2->getSubgroupNames().size(), 5); EXPECT_TRUE(jmg2->isSubgroup("arms")); EXPECT_TRUE(jmg2->isSubgroup("right_arm")); } TEST_F(LoadPlanningModelsPr2, AssociatedFixedLinks) { moveit::core::RobotModelPtr model(new moveit::core::RobotModel(urdf_model, srdf_model)); EXPECT_TRUE(model->getLinkModel("r_gripper_palm_link")->getAssociatedFixedTransforms().size() > 1); } TEST_F(LoadPlanningModelsPr2, FullTest) { moveit::core::RobotModelPtr robot_model(new moveit::core::RobotModel(urdf_model, srdf_model)); moveit::core::RobotState ks(robot_model); ks.setToDefaultValues(); moveit::core::RobotState ks2(robot_model); ks2.setToDefaultValues(); std::vector<shapes::ShapeConstPtr> shapes; EigenSTL::vector_Affine3d poses; shapes::Shape* shape = new shapes::Box(.1, .1, .1); shapes.push_back(shapes::ShapeConstPtr(shape)); poses.push_back(Eigen::Affine3d::Identity()); std::set<std::string> touch_links; trajectory_msgs::JointTrajectory empty_state; moveit::core::AttachedBody* attached_body = new moveit::core::AttachedBody( robot_model->getLinkModel("r_gripper_palm_link"), "box", shapes, poses, touch_links, empty_state); ks.attachBody(attached_body); std::vector<const moveit::core::AttachedBody*> attached_bodies_1; ks.getAttachedBodies(attached_bodies_1); ASSERT_EQ(attached_bodies_1.size(), 1); std::vector<const moveit::core::AttachedBody*> attached_bodies_2; ks2 = ks; ks2.getAttachedBodies(attached_bodies_2); ASSERT_EQ(attached_bodies_2.size(), 1); ks.clearAttachedBody("box"); attached_bodies_1.clear(); ks.getAttachedBodies(attached_bodies_1); ASSERT_EQ(attached_bodies_1.size(), 0); ks2 = ks; attached_bodies_2.clear(); ks2.getAttachedBodies(attached_bodies_2); ASSERT_EQ(attached_bodies_2.size(), 0); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_META_REF_TYPE_HPP #define STAN_MATH_PRIM_META_REF_TYPE_HPP #include <stan/math/prim/meta/is_eigen.hpp> #include <stan/math/prim/meta/is_arena_matrix.hpp> #include <stan/math/prim/meta/is_vector.hpp> #include <stan/math/prim/meta/plain_type.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <type_traits> namespace stan { /** * If the condition is true determines appropriate type for assigning expression * of given type to, to evaluate expensive expressions, but not make a copy if T * involves no calculations. This works similarly as `Eigen::Ref`. It also * handles rvalue references, so it can be used with perfect forwarding. If the * condition is false the expression will never be evaluated. * * Warning: if a variable of this type could be assigned a rvalue, make sure * template parameter `T` is of correct reference type (rvalue). * @tparam T type to determine reference for */ template <bool Condition, typename T, typename = void> struct ref_type_if { using T_plain = plain_type_t<T>; using T_optionally_ref = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; using type = std::conditional_t< Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain>>>:: template match<std::decay_t<T>>::MatchAtCompileTime || !Condition, T_optionally_ref, T_plain>; }; template <bool Condition, typename T> struct ref_type_if<Condition, T, require_t<bool_constant<!is_eigen<T>::value || is_arena_matrix<T>::value>>> { using type = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; }; template <typename T> using ref_type_t = typename ref_type_if<true, T>::type; template <bool Condition, typename T> using ref_type_if_t = typename ref_type_if<Condition, T>::type; /** * Determines appropriate type for assigning expression of given type to, so * that the resulting type has directly accessible contiguous colum-major data, * which is needed to copy to OpenCL device for construction of matrix_cl. * * THis is similar to `ref_type` except this also copies expressions, which do * not have contiguous data (in both dimensions) or have row major storage * order. * * Warning: if a variable of this type could be assigned a rvalue, make sure * template parameter `T` is of correct reference type (rvalue). * @tparam T type to determine reference for */ template <typename T, typename = void> struct ref_type_for_opencl { using T_val = std::remove_reference_t<T>; using T_plain_col_major = std::conditional_t< std::is_same<typename Eigen::internal::traits<T_val>::XprKind, Eigen::MatrixXpr>::value, Eigen::Matrix<value_type_t<T>, T_val::RowsAtCompileTime, T_val::ColsAtCompileTime>, Eigen::Array<value_type_t<T>, T_val::RowsAtCompileTime, T_val::ColsAtCompileTime>>; using T_optionally_ref = std::conditional_t<std::is_rvalue_reference<T>::value, T_val, const T&>; // Setting Outer stride of Ref to 0 (default) won't actually check that // expression has contiguous outer stride. Instead we need to check that // evaluator flags contain LinearAccessBit and PacketAccessBit. using type = std::conditional_t< Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain_col_major>>>:: template match<T_val>::MatchAtCompileTime && (Eigen::internal::evaluator<T_val>::Flags & Eigen::LinearAccessBit) && (Eigen::internal::evaluator<T_val>::Flags & Eigen::PacketAccessBit), T_optionally_ref, T_plain_col_major>; }; template <typename T> struct ref_type_for_opencl<T, require_t<bool_constant<!is_eigen<T>::value || is_arena_matrix<T>::value>>> { using type = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; }; template <typename T> using ref_type_for_opencl_t = typename ref_type_for_opencl<T>::type; } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.1-14 (tags/RELEASE_601/final)<commit_after>#ifndef STAN_MATH_PRIM_META_REF_TYPE_HPP #define STAN_MATH_PRIM_META_REF_TYPE_HPP #include <stan/math/prim/meta/is_eigen.hpp> #include <stan/math/prim/meta/is_arena_matrix.hpp> #include <stan/math/prim/meta/is_vector.hpp> #include <stan/math/prim/meta/plain_type.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <type_traits> namespace stan { /** * If the condition is true determines appropriate type for assigning expression * of given type to, to evaluate expensive expressions, but not make a copy if T * involves no calculations. This works similarly as `Eigen::Ref`. It also * handles rvalue references, so it can be used with perfect forwarding. If the * condition is false the expression will never be evaluated. * * Warning: if a variable of this type could be assigned a rvalue, make sure * template parameter `T` is of correct reference type (rvalue). * @tparam T type to determine reference for */ template <bool Condition, typename T, typename = void> struct ref_type_if { using T_plain = plain_type_t<T>; using T_optionally_ref = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; using type = std::conditional_t< Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain>>>:: template match<std::decay_t<T>>::MatchAtCompileTime || !Condition, T_optionally_ref, T_plain>; }; template <bool Condition, typename T> struct ref_type_if<Condition, T, require_t<bool_constant<!is_eigen<T>::value || is_arena_matrix<T>::value>>> { using type = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; }; template <typename T> using ref_type_t = typename ref_type_if<true, T>::type; template <bool Condition, typename T> using ref_type_if_t = typename ref_type_if<Condition, T>::type; /** * Determines appropriate type for assigning expression of given type to, so * that the resulting type has directly accessible contiguous colum-major data, * which is needed to copy to OpenCL device for construction of matrix_cl. * * THis is similar to `ref_type` except this also copies expressions, which do * not have contiguous data (in both dimensions) or have row major storage * order. * * Warning: if a variable of this type could be assigned a rvalue, make sure * template parameter `T` is of correct reference type (rvalue). * @tparam T type to determine reference for */ template <typename T, typename = void> struct ref_type_for_opencl { using T_val = std::remove_reference_t<T>; using T_plain_col_major = std::conditional_t< std::is_same<typename Eigen::internal::traits<T_val>::XprKind, Eigen::MatrixXpr>::value, Eigen::Matrix<value_type_t<T>, T_val::RowsAtCompileTime, T_val::ColsAtCompileTime>, Eigen::Array<value_type_t<T>, T_val::RowsAtCompileTime, T_val::ColsAtCompileTime>>; using T_optionally_ref = std::conditional_t<std::is_rvalue_reference<T>::value, T_val, const T&>; // Setting Outer stride of Ref to 0 (default) won't actually check that // expression has contiguous outer stride. Instead we need to check that // evaluator flags contain LinearAccessBit and PacketAccessBit. using type = std::conditional_t< Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain_col_major>>>:: template match<T_val>::MatchAtCompileTime && (Eigen::internal::evaluator<T_val>::Flags & Eigen::LinearAccessBit) && (Eigen::internal::evaluator<T_val>::Flags & Eigen::PacketAccessBit), T_optionally_ref, T_plain_col_major>; }; template <typename T> struct ref_type_for_opencl< T, require_t< bool_constant<!is_eigen<T>::value || is_arena_matrix<T>::value>>> { using type = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; }; template <typename T> using ref_type_for_opencl_t = typename ref_type_for_opencl<T>::type; } // namespace stan #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_META_REF_TYPE_HPP #define STAN_MATH_PRIM_META_REF_TYPE_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/meta/is_eigen.hpp> #include <stan/math/prim/meta/is_eigen_map_base.hpp> #include <stan/math/prim/meta/is_arena_matrix.hpp> #include <stan/math/prim/meta/is_vector.hpp> #include <stan/math/prim/meta/plain_type.hpp> #include <type_traits> namespace stan { /** * If the condition is true determines appropriate type for assigning expression * of given type to, to evaluate expensive expressions, but not make a copy if T * involves no calculations. This works similarly as `Eigen::Ref`. It also * handles rvalue references, so it can be used with perfect forwarding. If the * condition is false the expression will never be evaluated. * * Warning: if a variable of this type could be assigned a rvalue, make sure * template parameter `T` is of correct reference type (rvalue). * @tparam T type to determine reference for */ template <bool Condition, typename T, typename = void> struct ref_type_if { using T_plain = plain_type_t<T>; using T_optionally_ref = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; using type = std::conditional_t< Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain>>>:: template match<std::decay_t<T>>::MatchAtCompileTime || !Condition, T_optionally_ref, T_plain>; }; template <bool Condition, typename T> struct ref_type_if<Condition, T, require_not_eigen_t<T>> { using type = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; }; template <bool Condition, typename T> struct ref_type_if<Condition, T, require_arena_matrix_t<T>> { using type = typename ref_type_if<Condition, typename std::decay_t<T>::Base>::type; }; template <typename T> using ref_type_t = typename ref_type_if<true, T>::type; template <bool Condition, typename T> using ref_type_if_t = typename ref_type_if<Condition, T>::type; /** * Determines appropriate type for assigning expression of given type to, so * that the resulting type has directly accessible contiguous colum-major data, * which is needed to copy to OpenCL device for construction of matrix_cl. * * THis is similar to `ref_type` except this also copies expressions, which do * not have contiguous data (in both dimensions) or have row major storage * order. * * Warning: if a variable of this type could be assigned a rvalue, make sure * template parameter `T` is of correct reference type (rvalue). * @tparam T type to determine reference for */ template <typename T, typename = void> struct ref_type_for_opencl { using T_val = std::remove_reference_t<T>; using T_plain_col_major = std::conditional_t< std::is_same<typename Eigen::internal::traits<T_val>::XprKind, Eigen::MatrixXpr>::value, Eigen::Matrix<value_type_t<T>, T_val::RowsAtCompileTime, T_val::ColsAtCompileTime>, Eigen::Array<value_type_t<T>, T_val::RowsAtCompileTime, T_val::ColsAtCompileTime>>; using T_optionally_ref = std::conditional_t<std::is_rvalue_reference<T>::value, T_val, const T&>; // Setting Outer stride of Ref to 0 (default) won't actually check that // expression has contiguous outer stride. Instead we need to check that // evaluator flags contain LinearAccessBit and PacketAccessBit. using type = std::conditional_t< Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain_col_major>>>:: template match<T_val>::MatchAtCompileTime && (Eigen::internal::evaluator<T_val>::Flags & Eigen::LinearAccessBit) && (Eigen::internal::evaluator<T_val>::Flags & Eigen::PacketAccessBit), T_optionally_ref, T_plain_col_major>; }; template <typename T> struct ref_type_for_opencl<T, require_not_eigen_t<T>> { using type = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; }; template <typename T> struct ref_type_for_opencl<T, require_arena_matrix_t<T>> { using type = typename ref_type_for_opencl<typename std::decay_t<T>::Base>::type; }; template <typename T> using ref_type_for_opencl_t = typename ref_type_for_opencl<T>::type; } // namespace stan #endif <commit_msg>remove include for is_eigen_map_base in ref_type<commit_after>#ifndef STAN_MATH_PRIM_META_REF_TYPE_HPP #define STAN_MATH_PRIM_META_REF_TYPE_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/meta/is_eigen.hpp> #include <stan/math/prim/meta/is_arena_matrix.hpp> #include <stan/math/prim/meta/is_vector.hpp> #include <stan/math/prim/meta/plain_type.hpp> #include <type_traits> namespace stan { /** * If the condition is true determines appropriate type for assigning expression * of given type to, to evaluate expensive expressions, but not make a copy if T * involves no calculations. This works similarly as `Eigen::Ref`. It also * handles rvalue references, so it can be used with perfect forwarding. If the * condition is false the expression will never be evaluated. * * Warning: if a variable of this type could be assigned a rvalue, make sure * template parameter `T` is of correct reference type (rvalue). * @tparam T type to determine reference for */ template <bool Condition, typename T, typename = void> struct ref_type_if { using T_plain = plain_type_t<T>; using T_optionally_ref = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; using type = std::conditional_t< Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain>>>:: template match<std::decay_t<T>>::MatchAtCompileTime || !Condition, T_optionally_ref, T_plain>; }; template <bool Condition, typename T> struct ref_type_if<Condition, T, require_not_eigen_t<T>> { using type = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; }; template <bool Condition, typename T> struct ref_type_if<Condition, T, require_arena_matrix_t<T>> { using type = typename ref_type_if<Condition, typename std::decay_t<T>::Base>::type; }; template <typename T> using ref_type_t = typename ref_type_if<true, T>::type; template <bool Condition, typename T> using ref_type_if_t = typename ref_type_if<Condition, T>::type; /** * Determines appropriate type for assigning expression of given type to, so * that the resulting type has directly accessible contiguous colum-major data, * which is needed to copy to OpenCL device for construction of matrix_cl. * * THis is similar to `ref_type` except this also copies expressions, which do * not have contiguous data (in both dimensions) or have row major storage * order. * * Warning: if a variable of this type could be assigned a rvalue, make sure * template parameter `T` is of correct reference type (rvalue). * @tparam T type to determine reference for */ template <typename T, typename = void> struct ref_type_for_opencl { using T_val = std::remove_reference_t<T>; using T_plain_col_major = std::conditional_t< std::is_same<typename Eigen::internal::traits<T_val>::XprKind, Eigen::MatrixXpr>::value, Eigen::Matrix<value_type_t<T>, T_val::RowsAtCompileTime, T_val::ColsAtCompileTime>, Eigen::Array<value_type_t<T>, T_val::RowsAtCompileTime, T_val::ColsAtCompileTime>>; using T_optionally_ref = std::conditional_t<std::is_rvalue_reference<T>::value, T_val, const T&>; // Setting Outer stride of Ref to 0 (default) won't actually check that // expression has contiguous outer stride. Instead we need to check that // evaluator flags contain LinearAccessBit and PacketAccessBit. using type = std::conditional_t< Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain_col_major>>>:: template match<T_val>::MatchAtCompileTime && (Eigen::internal::evaluator<T_val>::Flags & Eigen::LinearAccessBit) && (Eigen::internal::evaluator<T_val>::Flags & Eigen::PacketAccessBit), T_optionally_ref, T_plain_col_major>; }; template <typename T> struct ref_type_for_opencl<T, require_not_eigen_t<T>> { using type = std::conditional_t<std::is_rvalue_reference<T>::value, std::remove_reference_t<T>, const T&>; }; template <typename T> struct ref_type_for_opencl<T, require_arena_matrix_t<T>> { using type = typename ref_type_for_opencl<typename std::decay_t<T>::Base>::type; }; template <typename T> using ref_type_for_opencl_t = typename ref_type_for_opencl<T>::type; } // namespace stan #endif <|endoftext|>
<commit_before>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/tools/iree_translate_lib.h" #include <functional> #include <memory> #include <string> #include <type_traits> #include "iree/compiler/Dialect/VM/Target/init_targets.h" #include "iree/tools/init_compiler_modules.h" #include "iree/tools/init_iree_dialects.h" #include "iree/tools/init_mlir_dialects.h" #include "iree/tools/init_passes.h" #include "iree/tools/init_targets.h" #include "iree/tools/init_translations.h" #include "iree/tools/init_xla_dialects.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SMLoc.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/raw_ostream.h" #include "mlir/IR/AsmState.h" #include "mlir/IR/Diagnostics.h" #include "mlir/IR/Dialect.h" #include "mlir/IR/MLIRContext.h" #include "mlir/Pass/PassManager.h" #include "mlir/Support/FileUtilities.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Support/Timing.h" #include "mlir/Support/ToolUtilities.h" #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" #include "mlir/Translation.h" int mlir::iree_compiler::runIreeTranslateMain(int argc, char **argv) { llvm::InitLLVM y(argc, argv); mlir::DialectRegistry registry; mlir::registerMlirDialects(registry); mlir::registerLLVMDialectTranslation(registry); mlir::registerXLADialects(registry); mlir::iree_compiler::registerAllPasses(); mlir::iree_compiler::registerIreeDialects(registry); mlir::iree_compiler::registerIreeCompilerModuleDialects(registry); mlir::iree_compiler::registerHALTargetBackends(); mlir::iree_compiler::registerVMTargets(); mlir::registerMlirTranslations(); mlir::iree_compiler::registerIreeTranslations(); // Make sure command line options are registered. (void)mlir::iree_compiler::IREE::HAL::getTargetOptionsFromFlags(); // Register MLIRContext command-line options like // -mlir-print-op-on-diagnostic. mlir::registerMLIRContextCLOptions(); // Register assembly printer command-line options like // -mlir-print-op-generic. mlir::registerAsmPrinterCLOptions(); // Register pass manager command-line options like -print-ir-*. mlir::registerPassManagerCLOptions(); mlir::registerDefaultTimingManagerCLOptions(); // General command line flags. llvm::cl::opt<std::string> inputFilename(llvm::cl::Positional, llvm::cl::desc("<input file>"), llvm::cl::init("-")); llvm::cl::opt<std::string> outputFilename( "o", llvm::cl::desc("Output filename"), llvm::cl::value_desc("filename"), llvm::cl::init("-")); llvm::cl::opt<bool> splitInputFile( "split-input-file", llvm::cl::desc("Split the input file into pieces and " "process each chunk independently"), llvm::cl::init(false)); llvm::cl::opt<bool> printMainAddress( "print-main-address", llvm::cl::desc( "Print the address of main to stderr to aid in symbolizing " "stack traces after the fact"), llvm::cl::init(false)); // Add flags for all the registered translations. llvm::cl::opt<const mlir::TranslateFunction *, false, mlir::TranslationParser> translationRequested("", llvm::cl::desc("Translation to perform"), llvm::cl::Optional); llvm::cl::ParseCommandLineOptions(argc, argv, "IREE translation driver\n"); if (printMainAddress) { llvm::errs() << "iree-translate main is at " << reinterpret_cast<void *>(&runIreeTranslateMain) << "\n"; } std::string errorMessage; auto input = mlir::openInputFile(inputFilename, &errorMessage); if (!input) { llvm::errs() << errorMessage << "\n"; return 1; } auto output = mlir::openOutputFile(outputFilename, &errorMessage); if (!output) { llvm::errs() << errorMessage << "\n"; return 1; } /// Processes the memory buffer with a new MLIRContext. auto processBuffer = [&](std::unique_ptr<llvm::MemoryBuffer> ownedBuffer, llvm::raw_ostream &os) { mlir::MLIRContext context; context.allowUnregisteredDialects(); context.appendDialectRegistry(registry); llvm::SourceMgr sourceMgr; sourceMgr.AddNewSourceBuffer(std::move(ownedBuffer), llvm::SMLoc()); mlir::SourceMgrDiagnosticHandler diagHandler(sourceMgr, &context); return (*translationRequested)(sourceMgr, os, &context); }; if (splitInputFile) { if (failed(mlir::splitAndProcessBuffer(std::move(input), processBuffer, output->os()))) return 1; } else { if (failed(processBuffer(std::move(input), output->os()))) return 1; } output->keep(); return 0; } <commit_msg>Remove option to print address of main from iree-translate (#7262)<commit_after>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/tools/iree_translate_lib.h" #include <functional> #include <memory> #include <string> #include <type_traits> #include "iree/compiler/Dialect/VM/Target/init_targets.h" #include "iree/tools/init_compiler_modules.h" #include "iree/tools/init_iree_dialects.h" #include "iree/tools/init_mlir_dialects.h" #include "iree/tools/init_passes.h" #include "iree/tools/init_targets.h" #include "iree/tools/init_translations.h" #include "iree/tools/init_xla_dialects.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SMLoc.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/raw_ostream.h" #include "mlir/IR/AsmState.h" #include "mlir/IR/Diagnostics.h" #include "mlir/IR/Dialect.h" #include "mlir/IR/MLIRContext.h" #include "mlir/Pass/PassManager.h" #include "mlir/Support/FileUtilities.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Support/Timing.h" #include "mlir/Support/ToolUtilities.h" #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" #include "mlir/Translation.h" int mlir::iree_compiler::runIreeTranslateMain(int argc, char **argv) { llvm::InitLLVM y(argc, argv); mlir::DialectRegistry registry; mlir::registerMlirDialects(registry); mlir::registerLLVMDialectTranslation(registry); mlir::registerXLADialects(registry); mlir::iree_compiler::registerAllPasses(); mlir::iree_compiler::registerIreeDialects(registry); mlir::iree_compiler::registerIreeCompilerModuleDialects(registry); mlir::iree_compiler::registerHALTargetBackends(); mlir::iree_compiler::registerVMTargets(); mlir::registerMlirTranslations(); mlir::iree_compiler::registerIreeTranslations(); // Make sure command line options are registered. (void)mlir::iree_compiler::IREE::HAL::getTargetOptionsFromFlags(); // Register MLIRContext command-line options like // -mlir-print-op-on-diagnostic. mlir::registerMLIRContextCLOptions(); // Register assembly printer command-line options like // -mlir-print-op-generic. mlir::registerAsmPrinterCLOptions(); // Register pass manager command-line options like -print-ir-*. mlir::registerPassManagerCLOptions(); mlir::registerDefaultTimingManagerCLOptions(); // General command line flags. llvm::cl::opt<std::string> inputFilename(llvm::cl::Positional, llvm::cl::desc("<input file>"), llvm::cl::init("-")); llvm::cl::opt<std::string> outputFilename( "o", llvm::cl::desc("Output filename"), llvm::cl::value_desc("filename"), llvm::cl::init("-")); llvm::cl::opt<bool> splitInputFile( "split-input-file", llvm::cl::desc("Split the input file into pieces and " "process each chunk independently"), llvm::cl::init(false)); // Add flags for all the registered translations. llvm::cl::opt<const mlir::TranslateFunction *, false, mlir::TranslationParser> translationRequested("", llvm::cl::desc("Translation to perform"), llvm::cl::Optional); llvm::cl::ParseCommandLineOptions(argc, argv, "IREE translation driver\n"); std::string errorMessage; auto input = mlir::openInputFile(inputFilename, &errorMessage); if (!input) { llvm::errs() << errorMessage << "\n"; return 1; } auto output = mlir::openOutputFile(outputFilename, &errorMessage); if (!output) { llvm::errs() << errorMessage << "\n"; return 1; } /// Processes the memory buffer with a new MLIRContext. auto processBuffer = [&](std::unique_ptr<llvm::MemoryBuffer> ownedBuffer, llvm::raw_ostream &os) { mlir::MLIRContext context; context.allowUnregisteredDialects(); context.appendDialectRegistry(registry); llvm::SourceMgr sourceMgr; sourceMgr.AddNewSourceBuffer(std::move(ownedBuffer), llvm::SMLoc()); mlir::SourceMgrDiagnosticHandler diagHandler(sourceMgr, &context); return (*translationRequested)(sourceMgr, os, &context); }; if (splitInputFile) { if (failed(mlir::splitAndProcessBuffer(std::move(input), processBuffer, output->os()))) return 1; } else { if (failed(processBuffer(std::move(input), output->os()))) return 1; } output->keep(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <SimpleITKTestHarness.h> #include <SimpleITK.h> #include "itkImage.h" #include "itkVectorImage.h" #include <memory> TEST(LabelStatistics,Simple) { itk::simple::ImageFileReader reader; //By using the same image, the label min/max values should equal the label itself. itk::simple::Image intensityImage = reader.SetFileName ( dataFinder.GetFile ( "Input/2th_cthead1.png" ) ).Execute(); itk::simple::Image labelImage = reader.SetFileName ( dataFinder.GetFile ( "Input/2th_cthead1.png" ) ).Execute(); itk::simple::LabelStatisticsImageFilter lsFilter; EXPECT_TRUE(lsFilter.GetUseHistograms()); lsFilter.UseHistogramsOff(); EXPECT_FALSE(lsFilter.GetUseHistograms()); lsFilter.UseHistogramsOn(); EXPECT_TRUE(lsFilter.GetUseHistograms()); lsFilter.SetUseHistograms(false); EXPECT_FALSE(lsFilter.GetUseHistograms()); lsFilter.SetUseHistograms(true); EXPECT_TRUE(lsFilter.GetUseHistograms()); try { lsFilter.Execute ( intensityImage, labelImage ); } catch ( itk::ExceptionObject e ) { std::cout << "LabelStatistics failed: " << e.what() << std::endl; } std::vector<int64_t> labels = lsFilter.GetLabels(); for(std::vector<int64_t>::const_iterator i = labels.begin(); i != labels.end(); ++i) { //By using the same image, the label min/max/mean values should equal the label itself. ASSERT_EQ(lsFilter.GetMinimum (*i) , *i); ASSERT_EQ(lsFilter.GetMaximum (*i) , *i); ASSERT_EQ(lsFilter.GetMean (*i) , *i); ASSERT_EQ(lsFilter.GetMedian (*i) , *i); //By using the same image, the label variance values should equal to Zero. ASSERT_EQ(lsFilter.GetSigma (*i) , 0.0 ); ASSERT_EQ(lsFilter.GetVariance(*i) , 0.0 ); } ASSERT_EQ(lsFilter.GetSum (0) , 0 ); ASSERT_EQ(lsFilter.GetCount(0) , 33390u ); } TEST(LabelStatistics,Commands) { namespace sitk = itk::simple; sitk::Image image = sitk::ReadImage ( dataFinder.GetFile ( "Input/cthead1.png" ) ); sitk::Image labels = sitk::ReadImage ( dataFinder.GetFile ( "Input/2th_cthead1.mha" ) ); sitk::LabelStatisticsImageFilter stats; ProgressUpdate progressCmd(stats); stats.AddCommand(sitk::sitkProgressEvent, progressCmd); CountCommand abortCmd(stats); stats.AddCommand(sitk::sitkAbortEvent, abortCmd); CountCommand deleteCmd(stats); stats.AddCommand(sitk::sitkDeleteEvent, deleteCmd); CountCommand endCmd(stats); stats.AddCommand(sitk::sitkEndEvent, endCmd); CountCommand iterCmd(stats); stats.AddCommand(sitk::sitkIterationEvent, iterCmd); CountCommand startCmd(stats); stats.AddCommand(sitk::sitkStartEvent, startCmd); CountCommand userCmd(stats); stats.AddCommand(sitk::sitkUserEvent, userCmd); stats.DebugOn(); stats.Execute ( image, labels ); EXPECT_EQ( stats.GetName(), "LabelStatisticsImageFilter" ); EXPECT_NO_THROW( stats.ToString() ); EXPECT_TRUE ( stats.HasLabel ( 0 ) ); EXPECT_TRUE ( stats.HasLabel ( 1 ) ); EXPECT_TRUE ( stats.HasLabel ( 2 ) ); EXPECT_FALSE ( stats.HasLabel ( 99 ) ); EXPECT_FALSE ( stats.HasLabel ( 1024 ) ); EXPECT_NEAR ( stats.GetMinimum ( 0 ), 0, 0.01 ); EXPECT_NEAR ( stats.GetMaximum ( 0 ), 99, 0.01 ); EXPECT_NEAR ( stats.GetMean ( 0 ), 13.0911, 0.001 ); EXPECT_NEAR ( stats.GetSigma ( 0 ), 16.4065, 0.01 ); EXPECT_NEAR ( stats.GetVariance ( 0 ), 269.173, 0.01 ); EXPECT_NEAR ( stats.GetCount ( 0 ), 36172, 0.01 ); EXPECT_NEAR ( stats.GetSum ( 0 ), 473533, 0.01 ); EXPECT_NEAR ( stats.GetMedian ( 0 ), 12.0, 0.001 ); ASSERT_EQ( 4u, stats.GetBoundingBox(0).size() ); EXPECT_EQ( 0u, stats.GetBoundingBox(0)[0] ); EXPECT_EQ( 255u, stats.GetBoundingBox(0)[1] ); EXPECT_EQ( 0u, stats.GetBoundingBox(0)[2] ); EXPECT_EQ( 255u, stats.GetBoundingBox(0)[3] ); ASSERT_EQ( 4u, stats.GetRegion(0).size() ); EXPECT_EQ( 0u, stats.GetRegion(0)[0] ); EXPECT_EQ( 0u, stats.GetRegion(0)[1] ); EXPECT_EQ( 256u, stats.GetRegion(0)[2] ); EXPECT_EQ( 256u, stats.GetRegion(0)[3] ); EXPECT_EQ ( 1.0f, stats.GetProgress() ); EXPECT_EQ ( 1.0f, progressCmd.m_Progress ); EXPECT_EQ ( 0, abortCmd.m_Count ); EXPECT_EQ ( 1, endCmd.m_Count ); EXPECT_EQ ( 0, iterCmd.m_Count ); EXPECT_EQ ( 1, startCmd.m_Count ); EXPECT_EQ ( 0, userCmd.m_Count ); // internal filter does not get deleted since there are active measurements EXPECT_EQ ( 0, deleteCmd.m_Count ); const std::vector<int64_t> myLabels = stats.GetLabels(); EXPECT_EQ ( myLabels.size() , 3u); // const sitk::LabelStatisticsImageFilter::LabelStatisticsMap myMap = stats.GetLabelStatisticsMap(); // EXPECT_EQ( myLabels.size() , myMap.size() ); // const sitk::MeasurementMap myMeasurementMap = stats.GetMeasurementMap(0); // EXPECT_EQ( myMeasurementMap.size(), 8u ); //4 measurements produced // const sitk::BasicMeasurementMap myBasicMeasurementMap = // myMeasurementMap.GetBasicMeasurementMap(); // EXPECT_EQ( myBasicMeasurementMap.size(), 8u ); //4 measurements produced // EXPECT_EQ ( myMeasurementMap.ToString(), "Count, Maximum, Mean, Minimum, Sigma, Sum, Variance, approxMedian, \n36172, 99, 13.0911, 0, 16.4065, 473533, 269.173, 12, \n" ); } <commit_msg>Fix sign/unsigned comparison warning.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <SimpleITKTestHarness.h> #include <SimpleITK.h> #include "itkImage.h" #include "itkVectorImage.h" #include <memory> TEST(LabelStatistics,Simple) { itk::simple::ImageFileReader reader; //By using the same image, the label min/max values should equal the label itself. itk::simple::Image intensityImage = reader.SetFileName ( dataFinder.GetFile ( "Input/2th_cthead1.png" ) ).Execute(); itk::simple::Image labelImage = reader.SetFileName ( dataFinder.GetFile ( "Input/2th_cthead1.png" ) ).Execute(); itk::simple::LabelStatisticsImageFilter lsFilter; EXPECT_TRUE(lsFilter.GetUseHistograms()); lsFilter.UseHistogramsOff(); EXPECT_FALSE(lsFilter.GetUseHistograms()); lsFilter.UseHistogramsOn(); EXPECT_TRUE(lsFilter.GetUseHistograms()); lsFilter.SetUseHistograms(false); EXPECT_FALSE(lsFilter.GetUseHistograms()); lsFilter.SetUseHistograms(true); EXPECT_TRUE(lsFilter.GetUseHistograms()); try { lsFilter.Execute ( intensityImage, labelImage ); } catch ( itk::ExceptionObject e ) { std::cout << "LabelStatistics failed: " << e.what() << std::endl; } std::vector<int64_t> labels = lsFilter.GetLabels(); for(std::vector<int64_t>::const_iterator i = labels.begin(); i != labels.end(); ++i) { //By using the same image, the label min/max/mean values should equal the label itself. ASSERT_EQ(lsFilter.GetMinimum (*i) , *i); ASSERT_EQ(lsFilter.GetMaximum (*i) , *i); ASSERT_EQ(lsFilter.GetMean (*i) , *i); ASSERT_EQ(lsFilter.GetMedian (*i) , *i); //By using the same image, the label variance values should equal to Zero. ASSERT_EQ(lsFilter.GetSigma (*i) , 0.0 ); ASSERT_EQ(lsFilter.GetVariance(*i) , 0.0 ); } ASSERT_EQ(lsFilter.GetSum (0) , 0 ); ASSERT_EQ(lsFilter.GetCount(0) , 33390u ); } TEST(LabelStatistics,Commands) { namespace sitk = itk::simple; sitk::Image image = sitk::ReadImage ( dataFinder.GetFile ( "Input/cthead1.png" ) ); sitk::Image labels = sitk::ReadImage ( dataFinder.GetFile ( "Input/2th_cthead1.mha" ) ); sitk::LabelStatisticsImageFilter stats; ProgressUpdate progressCmd(stats); stats.AddCommand(sitk::sitkProgressEvent, progressCmd); CountCommand abortCmd(stats); stats.AddCommand(sitk::sitkAbortEvent, abortCmd); CountCommand deleteCmd(stats); stats.AddCommand(sitk::sitkDeleteEvent, deleteCmd); CountCommand endCmd(stats); stats.AddCommand(sitk::sitkEndEvent, endCmd); CountCommand iterCmd(stats); stats.AddCommand(sitk::sitkIterationEvent, iterCmd); CountCommand startCmd(stats); stats.AddCommand(sitk::sitkStartEvent, startCmd); CountCommand userCmd(stats); stats.AddCommand(sitk::sitkUserEvent, userCmd); stats.DebugOn(); stats.Execute ( image, labels ); EXPECT_EQ( stats.GetName(), "LabelStatisticsImageFilter" ); EXPECT_NO_THROW( stats.ToString() ); EXPECT_TRUE ( stats.HasLabel ( 0 ) ); EXPECT_TRUE ( stats.HasLabel ( 1 ) ); EXPECT_TRUE ( stats.HasLabel ( 2 ) ); EXPECT_FALSE ( stats.HasLabel ( 99 ) ); EXPECT_FALSE ( stats.HasLabel ( 1024 ) ); EXPECT_NEAR ( stats.GetMinimum ( 0 ), 0, 0.01 ); EXPECT_NEAR ( stats.GetMaximum ( 0 ), 99, 0.01 ); EXPECT_NEAR ( stats.GetMean ( 0 ), 13.0911, 0.001 ); EXPECT_NEAR ( stats.GetSigma ( 0 ), 16.4065, 0.01 ); EXPECT_NEAR ( stats.GetVariance ( 0 ), 269.173, 0.01 ); EXPECT_NEAR ( stats.GetCount ( 0 ), 36172, 0.01 ); EXPECT_NEAR ( stats.GetSum ( 0 ), 473533, 0.01 ); EXPECT_NEAR ( stats.GetMedian ( 0 ), 12.0, 0.001 ); ASSERT_EQ( 4u, stats.GetBoundingBox(0).size() ); EXPECT_EQ( 0, stats.GetBoundingBox(0)[0] ); EXPECT_EQ( 255, stats.GetBoundingBox(0)[1] ); EXPECT_EQ( 0, stats.GetBoundingBox(0)[2] ); EXPECT_EQ( 255, stats.GetBoundingBox(0)[3] ); ASSERT_EQ( 4u, stats.GetRegion(0).size() ); EXPECT_EQ( 0u, stats.GetRegion(0)[0] ); EXPECT_EQ( 0u, stats.GetRegion(0)[1] ); EXPECT_EQ( 256u, stats.GetRegion(0)[2] ); EXPECT_EQ( 256u, stats.GetRegion(0)[3] ); EXPECT_EQ ( 1.0f, stats.GetProgress() ); EXPECT_EQ ( 1.0f, progressCmd.m_Progress ); EXPECT_EQ ( 0, abortCmd.m_Count ); EXPECT_EQ ( 1, endCmd.m_Count ); EXPECT_EQ ( 0, iterCmd.m_Count ); EXPECT_EQ ( 1, startCmd.m_Count ); EXPECT_EQ ( 0, userCmd.m_Count ); // internal filter does not get deleted since there are active measurements EXPECT_EQ ( 0, deleteCmd.m_Count ); const std::vector<int64_t> myLabels = stats.GetLabels(); EXPECT_EQ ( myLabels.size() , 3u); // const sitk::LabelStatisticsImageFilter::LabelStatisticsMap myMap = stats.GetLabelStatisticsMap(); // EXPECT_EQ( myLabels.size() , myMap.size() ); // const sitk::MeasurementMap myMeasurementMap = stats.GetMeasurementMap(0); // EXPECT_EQ( myMeasurementMap.size(), 8u ); //4 measurements produced // const sitk::BasicMeasurementMap myBasicMeasurementMap = // myMeasurementMap.GetBasicMeasurementMap(); // EXPECT_EQ( myBasicMeasurementMap.size(), 8u ); //4 measurements produced // EXPECT_EQ ( myMeasurementMap.ToString(), "Count, Maximum, Mean, Minimum, Sigma, Sum, Variance, approxMedian, \n36172, 99, 13.0911, 0, 16.4065, 473533, 269.173, 12, \n" ); } <|endoftext|>
<commit_before>#ifndef JARNGREIPR_MODEL_CARBON_ALPHA_HPP #define JARNGREIPR_MODEL_CARBON_ALPHA_HPP #include <jarngreipr/model/Bead.hpp> #include <mjolnir/util/throw_exception.hpp> #include <algorithm> #include <stdexcept> #include <string> namespace jarngreipr { /*! @brief carbon alpha 1 beads per amino acid model */ template<typename realT> class CarbonAlpha final : public Bead<realT> { public: typedef Bead<realT> base_type; typedef typename base_type::real_type real_type; typedef typename base_type::coordinate_type coordinate_type; typedef typename base_type::atom_type atom_type; typedef typename base_type::container_type container_type; public: CarbonAlpha(container_type atoms, std::string name) : base_type(std::move(atoms), std::move(name)) { if(!this->atoms_.empty()) { const auto is_ca = [](const atom_type& a){return a.atom_name==" CA ";}; const std::size_t num_ca = std::count_if( this->atoms_.cbegin(), this->atoms_.cend(), is_ca); if(num_ca == 0) { mjolnir::throw_exception<std::runtime_error>("jarngreipr::" "model::CarbonAlpha: no c-alpha atom in this residue: \n", this->atoms_.front()); } if(num_ca > 1) { mjolnir::throw_exception<std::runtime_error>("jarngreipr::" "model::CarbonAlpha: multiple c-alpha in this residue: \n", this->atoms_.front()); } this->position_ = std::find_if( this->atoms_.cbegin(), this->atoms_.cend(), is_ca)->position; } } ~CarbonAlpha() override = default; CarbonAlpha(const CarbonAlpha&) = default; CarbonAlpha(CarbonAlpha&&) = default; CarbonAlpha& operator=(const CarbonAlpha&) = default; CarbonAlpha& operator=(CarbonAlpha&&) = default; std::string attribute(const std::string& n) const override {return "";} std::string kind() const override {return "CarbonAlpha";} coordinate_type position() const override {return this->position_;} private: coordinate_type position_; }; } // jarngreipr #endif /*JARNGREIPR_CARBON_ALPHA*/ <commit_msg>add make_carbon_alpha<commit_after>#ifndef JARNGREIPR_MODEL_CARBON_ALPHA_HPP #define JARNGREIPR_MODEL_CARBON_ALPHA_HPP #include <jarngreipr/model/Bead.hpp> #include <mjolnir/util/throw_exception.hpp> #include <algorithm> #include <stdexcept> #include <string> namespace jarngreipr { /*! @brief carbon alpha 1 beads per amino acid model */ template<typename realT> class CarbonAlpha final : public Bead<realT> { public: typedef Bead<realT> base_type; typedef typename base_type::real_type real_type; typedef typename base_type::coordinate_type coordinate_type; typedef typename base_type::atom_type atom_type; typedef typename base_type::container_type container_type; public: CarbonAlpha(container_type atoms, std::string name) : base_type(std::move(atoms), std::move(name)) { if(!this->atoms_.empty()) { const auto is_ca = [](const atom_type& a){return a.atom_name==" CA ";}; const std::size_t num_ca = std::count_if( this->atoms_.cbegin(), this->atoms_.cend(), is_ca); if(num_ca == 0) { mjolnir::throw_exception<std::runtime_error>("jarngreipr::" "model::CarbonAlpha: no c-alpha atom in this residue: \n", this->atoms_.front()); } if(num_ca > 1) { mjolnir::throw_exception<std::runtime_error>("jarngreipr::" "model::CarbonAlpha: multiple c-alpha in this residue: \n", this->atoms_.front()); } this->position_ = std::find_if( this->atoms_.cbegin(), this->atoms_.cend(), is_ca)->position; } } ~CarbonAlpha() override = default; CarbonAlpha(const CarbonAlpha&) = default; CarbonAlpha(CarbonAlpha&&) = default; CarbonAlpha& operator=(const CarbonAlpha&) = default; CarbonAlpha& operator=(CarbonAlpha&&) = default; std::string attribute(const std::string& n) const override {return "";} std::string kind() const override {return "CarbonAlpha";} coordinate_type position() const override {return this->position_;} private: coordinate_type position_; }; template<typename realT> std::vector<std::unique_ptr<Bead<realT>>> make_carbon_alpha(const PDBChain<realT>& chain) { std::vector<std::unique_ptr<Bead<realT>>> retval; for(std::size_t i=0; i<chain.residues_size(); ++i) { const auto res = chain.residue_at(i); std::vector<PDBAtom<realT>> atoms(res.begin(), res.end()); const auto name = atoms.front().residue_name; retval.push_back( mjolnir::make_unique<CarbonAlpha<realT>>(std::move(atoms), name)); } return retval; } } // jarngreipr #endif /*JARNGREIPR_CARBON_ALPHA*/ <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2022 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 2.1 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, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh/elem.h" #include "libmesh/enum_to_string.h" #include "libmesh/fe.h" #include "libmesh/fe_interface.h" #include "libmesh/fe_macro.h" namespace libMesh { // ------------------------------------------------------------ // Hierarchic-specific implementations // Anonymous namespace for local helper functions namespace { void side_hierarchic_nodal_soln(const Elem * elem, const Order /* order */, const std::vector<Number> & /* elem_soln */, std::vector<Number> & nodal_soln) { const unsigned int n_nodes = elem->n_nodes(); nodal_soln.resize(n_nodes); libmesh_warning("Nodal solution requested for a side element; this makes no sense."); } // side_hierarchic_nodal_soln() unsigned int side_hierarchic_n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { switch (t) { case EDGE2: case EDGE3: case EDGE4: if (n < 2) return 1; // One per side else return 0; case QUAD8: case QUADSHELL8: case QUAD9: if (n > 3 && n < 8) return o+1; else return 0; case HEX27: if (n > 19 && n < 26) return (o+1)*(o+1); // (o+1)^2 per side else return 0; case TRI6: case TRI7: if (n > 2 && n < 6) return o+1; else return 0; case TET14: if (n > 9) return (o+1)*(o+2)/2; else return 0; case INVALID_ELEM: return 0; // Without side nodes on all sides we can't support side elements default: libmesh_error_msg("ERROR: Invalid ElemType " << Utility::enum_to_string(t) << " selected for SIDE_HIERARCHIC FE family!"); } } // side_hierarchic_n_dofs() unsigned int side_hierarchic_n_dofs(const ElemType t, const Order o) { switch (t) { case EDGE2: case EDGE3: case EDGE4: return 2; // One per side libmesh_assert_less (o, 2); libmesh_fallthrough(); case QUAD8: case QUADSHELL8: case QUAD9: return ((o+1)*4); // o+1 per side case HEX27: return ((o+1)*(o+1)*6); // (o+1)^2 per side case TRI6: case TRI7: return ((o+1)*3); // o+1 per side case TET14: return (o+1)*(o+2)*2; // 4 sides, each (o+1)(o+2)/2 case INVALID_ELEM: return 0; // Without side nodes on all sides we can't support side elements default: libmesh_error_msg("ERROR: Invalid ElemType " << Utility::enum_to_string(t) << " selected for HIERARCHIC FE family!"); } } // side_hierarchic_n_dofs() } // anonymous namespace // Instantiate nodal_soln() function for every dimension LIBMESH_FE_NODAL_SOLN(SIDE_HIERARCHIC, side_hierarchic_nodal_soln) // Full specialization of n_dofs() function for every dimension template <> unsigned int FE<0,SIDE_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return side_hierarchic_n_dofs(t, o); } template <> unsigned int FE<1,SIDE_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return side_hierarchic_n_dofs(t, o); } template <> unsigned int FE<2,SIDE_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return side_hierarchic_n_dofs(t, o); } template <> unsigned int FE<3,SIDE_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return side_hierarchic_n_dofs(t, o); } // Full specialization of n_dofs_at_node() function for every dimension. template <> unsigned int FE<0,SIDE_HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return side_hierarchic_n_dofs_at_node(t, o, n); } template <> unsigned int FE<1,SIDE_HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return side_hierarchic_n_dofs_at_node(t, o, n); } template <> unsigned int FE<2,SIDE_HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return side_hierarchic_n_dofs_at_node(t, o, n); } template <> unsigned int FE<3,SIDE_HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return side_hierarchic_n_dofs_at_node(t, o, n); } // Full specialization of n_dofs_per_elem() function for every dimension. template <> unsigned int FE<0,SIDE_HIERARCHIC>::n_dofs_per_elem(const ElemType, const Order) { return 0; } template <> unsigned int FE<1,SIDE_HIERARCHIC>::n_dofs_per_elem(const ElemType, const Order) { return 0; } template <> unsigned int FE<2,SIDE_HIERARCHIC>::n_dofs_per_elem(const ElemType, const Order) { return 0; } template <> unsigned int FE<3,SIDE_HIERARCHIC>::n_dofs_per_elem(const ElemType, const Order) { return 0; } // Side FEMs are discontinuous from side to side template <> FEContinuity FE<0,SIDE_HIERARCHIC>::get_continuity() const { return SIDE_DISCONTINUOUS; } template <> FEContinuity FE<1,SIDE_HIERARCHIC>::get_continuity() const { return SIDE_DISCONTINUOUS; } template <> FEContinuity FE<2,SIDE_HIERARCHIC>::get_continuity() const { return SIDE_DISCONTINUOUS; } template <> FEContinuity FE<3,SIDE_HIERARCHIC>::get_continuity() const { return SIDE_DISCONTINUOUS; } // Side Hierarchic FEMs are hierarchic (duh!) template <> bool FE<0,SIDE_HIERARCHIC>::is_hierarchic() const { return true; } template <> bool FE<1,SIDE_HIERARCHIC>::is_hierarchic() const { return true; } template <> bool FE<2,SIDE_HIERARCHIC>::is_hierarchic() const { return true; } template <> bool FE<3,SIDE_HIERARCHIC>::is_hierarchic() const { return true; } #ifdef LIBMESH_ENABLE_AMR // compute_constraints() specializations are only needed for 2 and 3D template <> void FE<2,SIDE_HIERARCHIC>::compute_constraints (DofConstraints & constraints, DofMap & dof_map, const unsigned int variable_number, const Elem * elem) { compute_proj_constraints(constraints, dof_map, variable_number, elem); } template <> void FE<3,SIDE_HIERARCHIC>::compute_constraints (DofConstraints & constraints, DofMap & dof_map, const unsigned int variable_number, const Elem * elem) { compute_proj_constraints(constraints, dof_map, variable_number, elem); } #endif // #ifdef LIBMESH_ENABLE_AMR // Hierarchic FEM shapes need reinit template <> bool FE<0,SIDE_HIERARCHIC>::shapes_need_reinit() const { return true; } template <> bool FE<1,SIDE_HIERARCHIC>::shapes_need_reinit() const { return true; } template <> bool FE<2,SIDE_HIERARCHIC>::shapes_need_reinit() const { return true; } template <> bool FE<3,SIDE_HIERARCHIC>::shapes_need_reinit() const { return true; } } // namespace libMesh <commit_msg>Fix SIDE_HIERARCHIC nodal_soln<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2022 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 2.1 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, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh/elem.h" #include "libmesh/enum_to_string.h" #include "libmesh/fe.h" #include "libmesh/fe_interface.h" #include "libmesh/fe_macro.h" namespace libMesh { // ------------------------------------------------------------ // Hierarchic-specific implementations // Anonymous namespace for local helper functions namespace { void side_hierarchic_nodal_soln(const Elem * elem, const Order /* order */, const std::vector<Number> & /* elem_soln */, std::vector<Number> & nodal_soln) { const unsigned int n_nodes = elem->n_nodes(); std::fill(nodal_soln.begin(), nodal_soln.end(), 0); nodal_soln.resize(n_nodes, 0); // We request nodal solutions when plotting, for consistency with // other elements; plotting 0 on non-sides makes sense in that // context. // libmesh_warning("Nodal solution requested for a side element; this makes no sense."); } // side_hierarchic_nodal_soln() unsigned int side_hierarchic_n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { switch (t) { case EDGE2: case EDGE3: case EDGE4: if (n < 2) return 1; // One per side else return 0; case QUAD8: case QUADSHELL8: case QUAD9: if (n > 3 && n < 8) return o+1; else return 0; case HEX27: if (n > 19 && n < 26) return (o+1)*(o+1); // (o+1)^2 per side else return 0; case TRI6: case TRI7: if (n > 2 && n < 6) return o+1; else return 0; case TET14: if (n > 9) return (o+1)*(o+2)/2; else return 0; case INVALID_ELEM: return 0; // Without side nodes on all sides we can't support side elements default: libmesh_error_msg("ERROR: Invalid ElemType " << Utility::enum_to_string(t) << " selected for SIDE_HIERARCHIC FE family!"); } } // side_hierarchic_n_dofs() unsigned int side_hierarchic_n_dofs(const ElemType t, const Order o) { switch (t) { case EDGE2: case EDGE3: case EDGE4: return 2; // One per side libmesh_assert_less (o, 2); libmesh_fallthrough(); case QUAD8: case QUADSHELL8: case QUAD9: return ((o+1)*4); // o+1 per side case HEX27: return ((o+1)*(o+1)*6); // (o+1)^2 per side case TRI6: case TRI7: return ((o+1)*3); // o+1 per side case TET14: return (o+1)*(o+2)*2; // 4 sides, each (o+1)(o+2)/2 case INVALID_ELEM: return 0; // Without side nodes on all sides we can't support side elements default: libmesh_error_msg("ERROR: Invalid ElemType " << Utility::enum_to_string(t) << " selected for HIERARCHIC FE family!"); } } // side_hierarchic_n_dofs() } // anonymous namespace // Instantiate nodal_soln() function for every dimension LIBMESH_FE_NODAL_SOLN(SIDE_HIERARCHIC, side_hierarchic_nodal_soln) // Full specialization of n_dofs() function for every dimension template <> unsigned int FE<0,SIDE_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return side_hierarchic_n_dofs(t, o); } template <> unsigned int FE<1,SIDE_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return side_hierarchic_n_dofs(t, o); } template <> unsigned int FE<2,SIDE_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return side_hierarchic_n_dofs(t, o); } template <> unsigned int FE<3,SIDE_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return side_hierarchic_n_dofs(t, o); } // Full specialization of n_dofs_at_node() function for every dimension. template <> unsigned int FE<0,SIDE_HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return side_hierarchic_n_dofs_at_node(t, o, n); } template <> unsigned int FE<1,SIDE_HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return side_hierarchic_n_dofs_at_node(t, o, n); } template <> unsigned int FE<2,SIDE_HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return side_hierarchic_n_dofs_at_node(t, o, n); } template <> unsigned int FE<3,SIDE_HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return side_hierarchic_n_dofs_at_node(t, o, n); } // Full specialization of n_dofs_per_elem() function for every dimension. template <> unsigned int FE<0,SIDE_HIERARCHIC>::n_dofs_per_elem(const ElemType, const Order) { return 0; } template <> unsigned int FE<1,SIDE_HIERARCHIC>::n_dofs_per_elem(const ElemType, const Order) { return 0; } template <> unsigned int FE<2,SIDE_HIERARCHIC>::n_dofs_per_elem(const ElemType, const Order) { return 0; } template <> unsigned int FE<3,SIDE_HIERARCHIC>::n_dofs_per_elem(const ElemType, const Order) { return 0; } // Side FEMs are discontinuous from side to side template <> FEContinuity FE<0,SIDE_HIERARCHIC>::get_continuity() const { return SIDE_DISCONTINUOUS; } template <> FEContinuity FE<1,SIDE_HIERARCHIC>::get_continuity() const { return SIDE_DISCONTINUOUS; } template <> FEContinuity FE<2,SIDE_HIERARCHIC>::get_continuity() const { return SIDE_DISCONTINUOUS; } template <> FEContinuity FE<3,SIDE_HIERARCHIC>::get_continuity() const { return SIDE_DISCONTINUOUS; } // Side Hierarchic FEMs are hierarchic (duh!) template <> bool FE<0,SIDE_HIERARCHIC>::is_hierarchic() const { return true; } template <> bool FE<1,SIDE_HIERARCHIC>::is_hierarchic() const { return true; } template <> bool FE<2,SIDE_HIERARCHIC>::is_hierarchic() const { return true; } template <> bool FE<3,SIDE_HIERARCHIC>::is_hierarchic() const { return true; } #ifdef LIBMESH_ENABLE_AMR // compute_constraints() specializations are only needed for 2 and 3D template <> void FE<2,SIDE_HIERARCHIC>::compute_constraints (DofConstraints & constraints, DofMap & dof_map, const unsigned int variable_number, const Elem * elem) { compute_proj_constraints(constraints, dof_map, variable_number, elem); } template <> void FE<3,SIDE_HIERARCHIC>::compute_constraints (DofConstraints & constraints, DofMap & dof_map, const unsigned int variable_number, const Elem * elem) { compute_proj_constraints(constraints, dof_map, variable_number, elem); } #endif // #ifdef LIBMESH_ENABLE_AMR // Hierarchic FEM shapes need reinit template <> bool FE<0,SIDE_HIERARCHIC>::shapes_need_reinit() const { return true; } template <> bool FE<1,SIDE_HIERARCHIC>::shapes_need_reinit() const { return true; } template <> bool FE<2,SIDE_HIERARCHIC>::shapes_need_reinit() const { return true; } template <> bool FE<3,SIDE_HIERARCHIC>::shapes_need_reinit() const { return true; } } // namespace libMesh <|endoftext|>
<commit_before>#include "encoder.h" vsize_t* Encoder::encode(size_t value, size_t width=1) { vsize_t result = this->size_tToByteArray(value); vsize_t* val; if width < 4: val.= new vsize_t(4-width); for (size_t i = 0; i < val.size(); ++i) { (*val)[i] = result[i+4-width]; } else { val = new vsize_t(width - 4 + result.size(), 0); for (size_t i = width - 4; i < val.size(); ++i) { val[i] = result[i-width - 4]; } } return val; } size_t Encoder::decode(size_t value) { return this->byteArrayToSize_t(value); } vsize_t* Encoder::size_tToByteArray(size_t pValue) { vsize_t* byteArray = new vsize_t(4); (*byteArray)[0] = value >> 24 & 0x000000FF; (*byteArray)[1] = value >> 16 & 0x000000FF; (*byteArray)[2] = value >> 8 & 0x000000FF; (*byteArray)[3] = value >> 0 & 0x000000FF; return byteArray; } size_t Encoder::byteArrayToSize_t(vsize_t* pArray) { vsize_t* val; if (pArray->size() < 4) { val = new vsize_t(4, 0); for (size_t i = 4 - pArray->size(); i < val.size(); ++i) { val[i] = (*pArray)[i-pArray->size()]; } } else { val = pArray; } return (*val)[0] << 24 + (*val)[1] << 16 + (*val)[2] << 8 + (*val)[3]; }<commit_msg>New constructor, new implementation of encode and decode, deleted others functions<commit_after>#include "encoder.h" Encoder::Encoder(size_t pBitVectorSize) { mBitVectorSize = pBitVectorSize; mMaskingValues = new vsize_t(pBitVectorSize); size_t mask = 0b11111111; for (size_t i = 0; i < mBitVectorSize; ++i) { (*mMaskingValues)[i] = mask << (8*i); } } bitVector* Encoder::encode(size_t pValue) { bitVector value = new bitVector(mBitVectorSize); for (size_t i = 0; i < mBitVectorSize; ++i) { value[i] = pValue & mMaskingValues[i]; } return value; } size_t Encoder::decode(bitVector* pValue) { size_t value = 0; size_t castValue = 0; for (size_t i = 0; i < pValue->size(); ++i) { castValue = (*pValue)[i]; value = value | (castValue << (8*i)); } return value; }<|endoftext|>
<commit_before>/* movementtools.cpp * Various movement tools source file */ #include "movementtools.h" // Constructor MovementTools::MovementTools(boost::shared_ptr<AL::ALBroker> broker, const std::string &name) : AL::ALModule(broker, name) { // Set description, and bind each function setModuleDescription("Smooth movement testing module"); functionName("goLimp", getName(), "Set all joints to 0 stiffness"); BIND_METHOD(MovementTools::goLimp); functionName("goStiff", getName(), "Set all joints to full stiffness"); BIND_METHOD(MovementTools::goStiff); functionName("swingForwards", getName(), "Move to forward seated position"); BIND_METHOD(MovementTools::swingForwards); functionName("swingBackwards", getName(), "Move to backward seated position"); BIND_METHOD(MovementTools::swingBackwards); functionName("setSpeed", getName(), "Set movement speed"); addParam("newSpeed", "The new speed"); BIND_METHOD(MovementTools::setSpeed); // Set broker parent IP and port pip = broker->getParentIP(); pport = broker->getParentPort(); speed = 0.6; std::string angleNamesArray[] = { "LAnklePitch" // "LAnkleRoll", // "LElbowRoll", // "LElbowYaw", // "LHipPitch", // "LHipRoll", // "LHipYawPitch", // "LKneePitch", // "LShoulderPitch", // "LShoulderRoll", // "LWristYaw", // "RAnklePitch", // "RAnkleRoll", // "RElbowRoll", // "RElbowYaw", // "RHipPitch", // "RHipRoll", // "RHipYawPitch", // "RKneePitch", // "RShoulderPitch", // "RShoulderRoll", // "RWristYaw" }; float sitForwardAnglesArray[] = { 0.921892f /* 0.04146f, -1.54462f, -0.154976f, -1.0845f, -0.0337059f, -0.0183661f, 1.54163f, 0.05825f, 0.800706f, -1.39905f, 0.921976f, -0.0168321f, // 1.53864f, // 0.22699f, -1.07231f, 0.0506639f, -0.0183661f, 1.52637f, // 0.219404f, // -0.83147f, */// 1.45419f }; float sitBackwardAnglesArray[] = { 0.820648f /* 0.023052f, -0.0475121f, 0.118076f, -0.601286f, -0.0337059f, -0.02757f, -0.090548f, 0.408002f, 0.0367742f, -1.7488f, 0.921976f, -0.0168321f, // 0.0583339f, // 0.20398f, -0.615176f, 0.0368581f, -0.02757f, -0.0923279f, // 0.420358f, // 0.0152981f, // 1.38516f */ }; angleNames = AL::ALValue(std::vector<std::string> (angleNamesArray, angleNamesArray + 17)); sitForwardAngles = AL::ALValue(std::vector<float> (sitForwardAnglesArray, sitForwardAnglesArray + 17)); sitBackwardAngles = AL::ALValue(std::vector<float> (sitBackwardAnglesArray, sitBackwardAnglesArray + 17)); } // Destructor MovementTools::~MovementTools() { } // init() - called as soon as the module is constructed void MovementTools::init() { motion = AL::ALMotionProxy(pip, pport); posture = AL::ALRobotPostureProxy(pip, pport); } void MovementTools::setSpeed(const float &newSpeed) { speed = newSpeed; } void MovementTools::goLimp() { motion.setStiffnesses("Body", 0.0f); } void MovementTools::goStiff() { motion.setStiffnesses("Body", 1.0f); } void MovementTools::swingForwards() { motion.setStiffnesses("Body", 1.0f); motion.setStiffnesses("RArm", 0.0f); motion.setAngles(angleNames, sitForwardAngles, speed); qi::os::msleep(700); motion.setStiffnesses("Body", 0.2f); motion.setStiffnesses("RArm", 0.0f); } void MovementTools::swingBackwards() { motion.setStiffnesses("Body", 1.0f); motion.setStiffnesses("RArm", 0.0f); motion.setAngles(angleNames, sitBackwardAngles, speed); qi::os::msleep(700); motion.setStiffnesses("Body", 0.2f); motion.setStiffnesses("RArm", 0.0f); } <commit_msg>Re-added movementtools code<commit_after>/* movementtools.cpp * Various movement tools source file */ #include "movementtools.h" // Constructor MovementTools::MovementTools(boost::shared_ptr<AL::ALBroker> broker, const std::string &name) : AL::ALModule(broker, name) { // Set description, and bind each function setModuleDescription("Smooth movement testing module"); functionName("goLimp", getName(), "Set all joints to 0 stiffness"); BIND_METHOD(MovementTools::goLimp); functionName("goStiff", getName(), "Set all joints to full stiffness"); BIND_METHOD(MovementTools::goStiff); functionName("swingForwards", getName(), "Move to forward seated position"); BIND_METHOD(MovementTools::swingForwards); functionName("swingBackwards", getName(), "Move to backward seated position"); BIND_METHOD(MovementTools::swingBackwards); functionName("setSpeed", getName(), "Set movement speed"); addParam("newSpeed", "The new speed"); BIND_METHOD(MovementTools::setSpeed); // Set broker parent IP and port pip = broker->getParentIP(); pport = broker->getParentPort(); speed = 0.6; std::string angleNamesArray[] = { "LAnklePitch" "LAnkleRoll", "LElbowRoll", "LElbowYaw", "LHipPitch", "LHipRoll", "LHipYawPitch", "LKneePitch", "LShoulderPitch", "LShoulderRoll", "LWristYaw", "RAnklePitch", "RAnkleRoll", // "RElbowRoll", // "RElbowYaw", "RHipPitch", "RHipRoll", "RHipYawPitch", "RKneePitch", // "RShoulderPitch", // "RShoulderRoll", // "RWristYaw" }; float sitForwardAnglesArray[] = { 0.921892f 0.04146f, -1.54462f, -0.154976f, -1.0845f, -0.0337059f, -0.0183661f, 1.54163f, 0.05825f, 0.800706f, -1.39905f, 0.921976f, -0.0168321f, // 1.53864f, // 0.22699f, -1.07231f, 0.0506639f, -0.0183661f, 1.52637f, // 0.219404f, // -0.83147f, // 1.45419f }; float sitBackwardAnglesArray[] = { 0.820648f 0.023052f, -0.0475121f, 0.118076f, -0.601286f, -0.0337059f, -0.02757f, -0.090548f, 0.408002f, 0.0367742f, -1.7488f, 0.921976f, -0.0168321f, // 0.0583339f, // 0.20398f, -0.615176f, 0.0368581f, -0.02757f, -0.0923279f, // 0.420358f, // 0.0152981f, // 1.38516f }; angleNames = AL::ALValue(std::vector<std::string> (angleNamesArray, angleNamesArray + 17)); sitForwardAngles = AL::ALValue(std::vector<float> (sitForwardAnglesArray, sitForwardAnglesArray + 17)); sitBackwardAngles = AL::ALValue(std::vector<float> (sitBackwardAnglesArray, sitBackwardAnglesArray + 17)); } // Destructor MovementTools::~MovementTools() { } // init() - called as soon as the module is constructed void MovementTools::init() { motion = AL::ALMotionProxy(pip, pport); posture = AL::ALRobotPostureProxy(pip, pport); } void MovementTools::setSpeed(const float &newSpeed) { speed = newSpeed; } void MovementTools::goLimp() { motion.setStiffnesses("Body", 0.0f); } void MovementTools::goStiff() { motion.setStiffnesses("Body", 1.0f); } void MovementTools::swingForwards() { motion.setStiffnesses("Body", 1.0f); motion.setStiffnesses("RArm", 0.0f); motion.setAngles(angleNames, sitForwardAngles, speed); qi::os::msleep(700); motion.setStiffnesses("Body", 0.2f); motion.setStiffnesses("RArm", 0.0f); } void MovementTools::swingBackwards() { motion.setStiffnesses("Body", 1.0f); motion.setStiffnesses("RArm", 0.0f); motion.setAngles(angleNames, sitBackwardAngles, speed); qi::os::msleep(700); motion.setStiffnesses("Body", 0.2f); motion.setStiffnesses("RArm", 0.0f); } <|endoftext|>
<commit_before>#include <math.h> #include "engine.h" #include "entity.h" #include "geometry.h" #include "engine_event.h" #include "misc.h" #include "wall.h" #include "player.h" #include <SFML/Window/VideoMode.hpp> #include <SFML/Window/Window.hpp> #include <SFML/Graphics/Text.hpp> #include <stdio.h> #include "commands.h" using namespace sf; static bool interacts(Engine *engine, MoveContext &ctx, Entity *a, Entity *b); void Engine::play(void) { while (step()) { Event e; while (window.pollEvent(e)) { if (e.type == Event::Closed) { quit(); } else if (e.type == Event::KeyPressed) { if (e.key.code == Keyboard::Escape) quit(); } else if (e.type == Event::JoystickConnected) { addPlayer(0, e.joystickConnect.joystickId); } else if (e.type == Event::JoystickDisconnected) { Player *pl = getPlayerByJoystickId(e.joystickConnect.joystickId); if (pl) {destroy(pl);destroy_flagged();} } else if (KeymapController::maybeConcerned(e)) { controller_activity(e); } } } } void Engine::controller_activity(Event &e) { for(EntitiesIterator it=entities.begin(); it != entities.end(); it++) { Player *pl = dynamic_cast<Player*>(*it); if (!pl) continue; KeymapController *c = dynamic_cast<KeymapController*>(pl->getController()); if (c) { int ojoyid = 0; if (c->isConcerned(e, ojoyid)) return; continue; } } /* this key event is not owned by a player, have a look at controller templates */ std::vector<KeymapController*> &cd = cdef.forplayer; for(unsigned i = 0; i < cd.size(); i++) { int ojoyid = 0; if (cd[i] && cd[i]->isConcerned(e, ojoyid)) { addPlayer(i, ojoyid); break; } } } Player *Engine::getPlayerByJoystickId(int joyid) { for(EntitiesIterator it=entities.begin(); it != entities.end(); it++) { Player *pl = dynamic_cast<Player*>(*it); if (!pl) continue; KeymapController *c = dynamic_cast<KeymapController*>(pl->getController()); if (c) { if (c->getJoystickId() == joyid) return pl; continue; } JoystickController *j = dynamic_cast<JoystickController*>(pl->getController()); if (j) { if (j->getJoystickId() == joyid) return pl; } } return NULL; } void Engine::addPlayer(unsigned cid, int joyid) { if (cid >= cdef.forplayer.size()) return; if (cid == 0 && joyid == -1) { /* search a free joystick */ for(unsigned i=0; i < Joystick::Count; i++) { if (Joystick::isConnected(i) && !getPlayerByJoystickId(i)) { joyid = i; break; } } } if (!cdef.forplayer[cid]) { fprintf(stderr, "Error: no controller %d found for new player\n", cid); return; } add(new Player(cdef.forplayer[cid]->clone(joyid), this)); } Entity *Engine::getMapBoundariesEntity() { return map_boundaries_entity; } TextureCache *Engine::getTextureCache(void) const { return &texture_cache; } Vector2d Engine::map_size(void) { Vector2u sz = window.getSize(); return Vector2d(sz.x, sz.y); } Engine::EntitiesIterator Engine::begin_entities() { return entities.begin(); } Engine::EntitiesIterator Engine::end_entities() { return entities.end(); } Engine::Engine() { first_step = true; must_quit = false; window.create(VideoMode(1920,1080), "Tank window", Style::Default); window.setVerticalSyncEnabled(true); window.clear(Color::White); score_font.loadFromFile("/usr/share/fonts/truetype/droid/DroidSans.ttf"); load_texture(background, background_texture, "sprites/dirt.jpg"); Vector2d sz = map_size(); background.setTextureRect(IntRect(0,0,sz.x,sz.y)); map_boundaries_entity = new Wall(0,0,sz.x,sz.y, NULL, this); add(map_boundaries_entity); load_keymap(cdef, "keymap.json"); } Engine::~Engine() { for(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) { delete (*it); } window.close(); } void Engine::seekCollisions(Entity *entity) { int i=100; bool retry = false; do { for(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) { Entity *centity = (*it); Segment vect; vect.pt1 = entity->position; vect.pt2 = entity->position; MoveContext ctx(IT_GHOST, vect); if (interacts(this, ctx, entity, centity)) { CollisionEvent e; e.first = entity; e.second = centity; e.interaction = IT_GHOST; broadcast(&e); if (e.retry) retry = true; } } } while(retry && --i > 0); } void Engine::add(Entity *entity) { entity->setEngine(this); entities.push_back(entity); /* signal spawn-time collisions */ seekCollisions(entity); } void Engine::destroy(Entity *entity) { /* Removes entity from engine and deletes the underlying object */ entity->setKilled(); } void Engine::broadcast(EngineEvent *event) { /* assume iterators may be invalidated during event processing, because new items may be added */ /* note that entities may be set to killed, but cannot be removed from the list (they are only flagged) */ for(size_t i=0; i < entities.size(); ++i) { Entity *entity = entities[i]; if (!entity->isKilled()) entity->event_received(event); } } void Engine::quit(void) { must_quit = true; } bool Engine::step(void) { if (must_quit) return false; if (first_step) {clock.restart();first_step=false;} draw(); compute_physics(); destroy_flagged(); return !must_quit; } void draw_score(RenderTarget &target, Font &ft, int score, Color color, Vector2d pos) { Text text; char sscore[256]; sprintf(sscore, "%d", score); text.setCharacterSize(128); text.setString(sscore); text.setColor(color); text.setPosition(Vector2f(pos.x, pos.y)); text.setFont(ft); target.draw(text); } void Engine::draw(void) { Vector2d scorepos; scorepos.x = 16; scorepos.y = 16; window.clear(); window.draw(background); for(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) { (*it)->draw(window); if (Player *pl = dynamic_cast<Player*>((*it))) { draw_score(window, score_font, pl->getScore(), pl->getColor(), scorepos); scorepos.x += 384+16; } } window.display(); } static double getEntityRadius(Entity *a) { return a->getSize().x/2; } static DoubleRect getEntityBoundingRectangle(Entity *a) { Vector2d pos = a->position; Vector2d size = a->getSize(); DoubleRect r; r.left = pos.x; r.top = pos.y; r.width = size.x; r.height = size.y; return r; } static Circle getEntityCircle(Entity *a) { Circle circle; circle.filled = true; circle.center = a->position; circle.radius = getEntityRadius(a); return circle; } /* Note: Dynamic entities must be circle-shaped */ static bool interacts(Engine *engine, MoveContext &ctx, Entity *a, Entity *b) { if (a->shape == SHAPE_CIRCLE && b->shape == SHAPE_RECTANGLE) { GeomRectangle gr; gr.filled = (b != engine->getMapBoundariesEntity()); gr.r = getEntityBoundingRectangle(b); return moveCircleToRectangle(getEntityRadius(a), ctx, gr); } else if (a->shape == SHAPE_CIRCLE && b->shape == SHAPE_CIRCLE) { return moveCircleToCircle(getEntityRadius(a), ctx, getEntityCircle(b)); } else { return false; } } bool moveCircleToRectangle(double radius, MoveContext &ctx, const DoubleRect &r); bool moveCircleToCircle(double radius, MoveContext &ctx, const Circle &colli); static bool quasi_equals(double a, double b) { return fabs(a-b) <= 1e-3*(fabs(a)+fabs(b)); } void Engine::compute_physics(void) { Int64 tm = clock.getElapsedTime().asMicroseconds(); if (tm == 0) return; clock.restart(); for(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) { Entity *entity = (*it); if (entity->isKilled()) continue; Vector2d movement = entity->movement(tm); Vector2d old_speed = movement; old_speed.x /= tm; old_speed.y /= tm; Segment vect; vect.pt1 = entity->position; vect.pt2 = vect.pt1 + movement; if ((fabs(movement.x)+fabs(movement.y)) < 1e-4) continue; MoveContext ctx(IT_GHOST, vect); for(int pass=0; pass < 2; ++pass) for (EntitiesIterator itc=entities.begin(); itc != entities.end(); ++itc) { Entity *centity = *itc; if (centity->isKilled()) continue; if (entity->isKilled()) break; if (centity == entity) continue; ctx.interaction = IT_GHOST; MoveContext ctxtemp = ctx; if (interacts(this, ctxtemp, entity, centity)) { if (entity->isKilled() || centity->isKilled()) continue; CollisionEvent e; e.type = COLLIDE_EVENT; e.first = entity; e.second = centity; e.interaction = IT_GHOST; /* default interaction type */ broadcast(&e); /* should set e.interaction */ ctx.interaction = e.interaction; if (pass == 1 && ctx.interaction != IT_GHOST) { /* On second interaction in the same frame, cancel movement */ ctx.vect.pt2 = ctx.vect.pt1 = entity->position; break; } interacts(this, ctx, entity, centity); } } if (entity->isKilled()) continue; vect = ctx.vect; CompletedMovementEvent e; e.type = COMPLETED_MOVEMENT_EVENT; e.entity = entity; e.position = vect.pt2; Vector2d new_speed = ctx.nmove; new_speed.x /= tm; new_speed.y /= tm; if (quasi_equals(old_speed.x, new_speed.x) && quasi_equals(old_speed.y, new_speed.y)) { e.new_speed = old_speed; e.has_new_speed = false; } else { e.new_speed = new_speed; e.has_new_speed = true; } broadcast(&e); } } void Engine::destroy_flagged(void) { bool some_got_deleted; do { some_got_deleted = false; for(size_t i=0; i < entities.size(); ++i) { Entity *entity = entities[i]; if (entity->isKilled()) { some_got_deleted = true; EntityDestroyedEvent e; e.type = ENTITY_DESTROYED_EVENT; e.entity = entity; broadcast(&e); entities.erase(entities.begin()+i); delete entity; --i; } } } while(some_got_deleted); #if 0 if (some_got_deleted) fprintf(stderr, "[now, I'm going to physically destroy things]\n"); for(size_t i=0; i < entities.size(); ++i) { Entity *entity = entities[i]; if (entity->isKilled()) { entities.erase(entities.begin()+i); delete entity; --i; } } if (some_got_deleted) fprintf(stderr, "[/physically destroyed things]\n"); #endif } <commit_msg>Added defensive programming logic to joyid in controllers.<commit_after>#include <math.h> #include "engine.h" #include "entity.h" #include "geometry.h" #include "engine_event.h" #include "misc.h" #include "wall.h" #include "player.h" #include <SFML/Window/VideoMode.hpp> #include <SFML/Window/Window.hpp> #include <SFML/Graphics/Text.hpp> #include <stdio.h> #include "commands.h" using namespace sf; static bool interacts(Engine *engine, MoveContext &ctx, Entity *a, Entity *b); void Engine::play(void) { while (step()) { Event e; while (window.pollEvent(e)) { if (e.type == Event::Closed) { quit(); } else if (e.type == Event::KeyPressed) { if (e.key.code == Keyboard::Escape) quit(); } else if (e.type == Event::JoystickConnected) { addPlayer(0, e.joystickConnect.joystickId); } else if (e.type == Event::JoystickDisconnected) { Player *pl = getPlayerByJoystickId(e.joystickConnect.joystickId); if (pl) {destroy(pl);destroy_flagged();} } else if (KeymapController::maybeConcerned(e)) { controller_activity(e); } } } } void Engine::controller_activity(Event &e) { for(EntitiesIterator it=entities.begin(); it != entities.end(); it++) { Player *pl = dynamic_cast<Player*>(*it); if (!pl) continue; KeymapController *c = dynamic_cast<KeymapController*>(pl->getController()); if (c) { int ojoyid = -1; if (c->isConcerned(e, ojoyid)) return; continue; } } /* this key event is not owned by a player, have a look at controller templates */ std::vector<KeymapController*> &cd = cdef.forplayer; for(unsigned i = 0; i < cd.size(); i++) { int ojoyid = -1; if (cd[i] && cd[i]->isConcerned(e, ojoyid)) { addPlayer(i, ojoyid); break; } } } Player *Engine::getPlayerByJoystickId(int joyid) { for(EntitiesIterator it=entities.begin(); it != entities.end(); it++) { Player *pl = dynamic_cast<Player*>(*it); if (!pl) continue; KeymapController *c = dynamic_cast<KeymapController*>(pl->getController()); if (c) { if (c->getJoystickId() == joyid) return pl; continue; } JoystickController *j = dynamic_cast<JoystickController*>(pl->getController()); if (j) { if (j->getJoystickId() == joyid) return pl; } } return NULL; } void Engine::addPlayer(unsigned cid, int joyid) { if (cid >= cdef.forplayer.size()) return; if (cid == 0 && joyid == -1) { /* search a free joystick */ for(unsigned i=0; i < Joystick::Count; i++) { if (Joystick::isConnected(i) && !getPlayerByJoystickId(i)) { joyid = i; break; } } } if (!cdef.forplayer[cid]) { fprintf(stderr, "Error: no controller %d found for new player\n", cid); return; } if (cid > 0) joyid = -1; add(new Player(cdef.forplayer[cid]->clone(joyid), this)); } Entity *Engine::getMapBoundariesEntity() { return map_boundaries_entity; } TextureCache *Engine::getTextureCache(void) const { return &texture_cache; } Vector2d Engine::map_size(void) { Vector2u sz = window.getSize(); return Vector2d(sz.x, sz.y); } Engine::EntitiesIterator Engine::begin_entities() { return entities.begin(); } Engine::EntitiesIterator Engine::end_entities() { return entities.end(); } Engine::Engine() { first_step = true; must_quit = false; window.create(VideoMode(1920,1080), "Tank window", Style::Default); window.setVerticalSyncEnabled(true); window.clear(Color::White); score_font.loadFromFile("/usr/share/fonts/truetype/droid/DroidSans.ttf"); load_texture(background, background_texture, "sprites/dirt.jpg"); Vector2d sz = map_size(); background.setTextureRect(IntRect(0,0,sz.x,sz.y)); map_boundaries_entity = new Wall(0,0,sz.x,sz.y, NULL, this); add(map_boundaries_entity); load_keymap(cdef, "keymap.json"); } Engine::~Engine() { for(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) { delete (*it); } window.close(); } void Engine::seekCollisions(Entity *entity) { int i=100; bool retry = false; do { for(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) { Entity *centity = (*it); Segment vect; vect.pt1 = entity->position; vect.pt2 = entity->position; MoveContext ctx(IT_GHOST, vect); if (interacts(this, ctx, entity, centity)) { CollisionEvent e; e.first = entity; e.second = centity; e.interaction = IT_GHOST; broadcast(&e); if (e.retry) retry = true; } } } while(retry && --i > 0); } void Engine::add(Entity *entity) { entity->setEngine(this); entities.push_back(entity); /* signal spawn-time collisions */ seekCollisions(entity); } void Engine::destroy(Entity *entity) { /* Removes entity from engine and deletes the underlying object */ entity->setKilled(); } void Engine::broadcast(EngineEvent *event) { /* assume iterators may be invalidated during event processing, because new items may be added */ /* note that entities may be set to killed, but cannot be removed from the list (they are only flagged) */ for(size_t i=0; i < entities.size(); ++i) { Entity *entity = entities[i]; if (!entity->isKilled()) entity->event_received(event); } } void Engine::quit(void) { must_quit = true; } bool Engine::step(void) { if (must_quit) return false; if (first_step) {clock.restart();first_step=false;} draw(); compute_physics(); destroy_flagged(); return !must_quit; } void draw_score(RenderTarget &target, Font &ft, int score, Color color, Vector2d pos) { Text text; char sscore[256]; sprintf(sscore, "%d", score); text.setCharacterSize(128); text.setString(sscore); text.setColor(color); text.setPosition(Vector2f(pos.x, pos.y)); text.setFont(ft); target.draw(text); } void Engine::draw(void) { Vector2d scorepos; scorepos.x = 16; scorepos.y = 16; window.clear(); window.draw(background); for(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) { (*it)->draw(window); if (Player *pl = dynamic_cast<Player*>((*it))) { draw_score(window, score_font, pl->getScore(), pl->getColor(), scorepos); scorepos.x += 384+16; } } window.display(); } static double getEntityRadius(Entity *a) { return a->getSize().x/2; } static DoubleRect getEntityBoundingRectangle(Entity *a) { Vector2d pos = a->position; Vector2d size = a->getSize(); DoubleRect r; r.left = pos.x; r.top = pos.y; r.width = size.x; r.height = size.y; return r; } static Circle getEntityCircle(Entity *a) { Circle circle; circle.filled = true; circle.center = a->position; circle.radius = getEntityRadius(a); return circle; } /* Note: Dynamic entities must be circle-shaped */ static bool interacts(Engine *engine, MoveContext &ctx, Entity *a, Entity *b) { if (a->shape == SHAPE_CIRCLE && b->shape == SHAPE_RECTANGLE) { GeomRectangle gr; gr.filled = (b != engine->getMapBoundariesEntity()); gr.r = getEntityBoundingRectangle(b); return moveCircleToRectangle(getEntityRadius(a), ctx, gr); } else if (a->shape == SHAPE_CIRCLE && b->shape == SHAPE_CIRCLE) { return moveCircleToCircle(getEntityRadius(a), ctx, getEntityCircle(b)); } else { return false; } } bool moveCircleToRectangle(double radius, MoveContext &ctx, const DoubleRect &r); bool moveCircleToCircle(double radius, MoveContext &ctx, const Circle &colli); static bool quasi_equals(double a, double b) { return fabs(a-b) <= 1e-3*(fabs(a)+fabs(b)); } void Engine::compute_physics(void) { Int64 tm = clock.getElapsedTime().asMicroseconds(); if (tm == 0) return; clock.restart(); for(EntitiesIterator it=entities.begin(); it != entities.end(); ++it) { Entity *entity = (*it); if (entity->isKilled()) continue; Vector2d movement = entity->movement(tm); Vector2d old_speed = movement; old_speed.x /= tm; old_speed.y /= tm; Segment vect; vect.pt1 = entity->position; vect.pt2 = vect.pt1 + movement; if ((fabs(movement.x)+fabs(movement.y)) < 1e-4) continue; MoveContext ctx(IT_GHOST, vect); for(int pass=0; pass < 2; ++pass) for (EntitiesIterator itc=entities.begin(); itc != entities.end(); ++itc) { Entity *centity = *itc; if (centity->isKilled()) continue; if (entity->isKilled()) break; if (centity == entity) continue; ctx.interaction = IT_GHOST; MoveContext ctxtemp = ctx; if (interacts(this, ctxtemp, entity, centity)) { if (entity->isKilled() || centity->isKilled()) continue; CollisionEvent e; e.type = COLLIDE_EVENT; e.first = entity; e.second = centity; e.interaction = IT_GHOST; /* default interaction type */ broadcast(&e); /* should set e.interaction */ ctx.interaction = e.interaction; if (pass == 1 && ctx.interaction != IT_GHOST) { /* On second interaction in the same frame, cancel movement */ ctx.vect.pt2 = ctx.vect.pt1 = entity->position; break; } interacts(this, ctx, entity, centity); } } if (entity->isKilled()) continue; vect = ctx.vect; CompletedMovementEvent e; e.type = COMPLETED_MOVEMENT_EVENT; e.entity = entity; e.position = vect.pt2; Vector2d new_speed = ctx.nmove; new_speed.x /= tm; new_speed.y /= tm; if (quasi_equals(old_speed.x, new_speed.x) && quasi_equals(old_speed.y, new_speed.y)) { e.new_speed = old_speed; e.has_new_speed = false; } else { e.new_speed = new_speed; e.has_new_speed = true; } broadcast(&e); } } void Engine::destroy_flagged(void) { bool some_got_deleted; do { some_got_deleted = false; for(size_t i=0; i < entities.size(); ++i) { Entity *entity = entities[i]; if (entity->isKilled()) { some_got_deleted = true; EntityDestroyedEvent e; e.type = ENTITY_DESTROYED_EVENT; e.entity = entity; broadcast(&e); entities.erase(entities.begin()+i); delete entity; --i; } } } while(some_got_deleted); #if 0 if (some_got_deleted) fprintf(stderr, "[now, I'm going to physically destroy things]\n"); for(size_t i=0; i < entities.size(); ++i) { Entity *entity = entities[i]; if (entity->isKilled()) { entities.erase(entities.begin()+i); delete entity; --i; } } if (some_got_deleted) fprintf(stderr, "[/physically destroyed things]\n"); #endif } <|endoftext|>
<commit_before> #include "sajson.h" using namespace sajson; extern "C" { struct str { const char* data; size_t length; }; parser* sj_parser(size_t length, const char* data) { mutable_string_view ms(string(data, length)); size_t* structure = new size_t[length]; return new parser(ms, structure); } void sj_parser_free(parser* parser) { delete parser; } document* sj_parser_get_document(parser* parser) { return new document(parser->get_document()); } void sj_document_free(document* document) { delete document; } bool sj_document_is_valid(document* document) { return document->is_valid(); } value* sj_document_get_root(document* document) { return new value(document->get_root()); } size_t sj_document_get_error_line(document* doc) { return doc->get_error_line(); } size_t sj_document_get_error_column(document* doc) { return doc->get_error_column(); } const char* sj_document_get_error_message(document* doc) { return doc->get_error_message().c_str(); } void sj_value_free(value* v) { delete v; } type sj_value_get_type(value* v) { return v->get_type(); } size_t sj_value_get_length(value* v) { return v->get_length(); } value* sj_value_get_array_element(value* v, size_t index) { return new value(v->get_array_element(index)); } void sj_value_get_object_key(value* v, size_t index, const char** result, size_t* resultLength) { string s = v->get_object_key(index); *result = s.data(); *resultLength = s.length(); } value* sj_value_get_object_value(value* v, size_t index) { return new value(v->get_object_value(index)); } size_t sj_value_find_object_key(value* v, string key) { return v->find_object_key(key); } int sj_value_get_integer_value(value* v) { return v->get_integer_value(); } double sj_value_get_double_value(value* v) { return v->get_double_value(); } double sj_value_get_number_value(value* v) { return v->get_number_value(); } size_t sj_value_get_string_length(value* v) { return v->get_string_length(); } void sj_value_get_string_value(value* v, const char** result, size_t* resultLength) { string s = v->as_str(); *result = s.data(); *resultLength = s.length(); } value* sj_value_get_object_with_key(value* v, const char* key, size_t keyLength) { string k(key, keyLength); size_t index = v->find_object_key(k); if (index < v->get_length()) { return new value(v->get_object_value(index)); } else { return nullptr; } } }<commit_msg>nullptr is too new for ubuntu 14!<commit_after> #include "sajson.h" using namespace sajson; extern "C" { struct str { const char* data; size_t length; }; parser* sj_parser(size_t length, const char* data) { mutable_string_view ms(string(data, length)); size_t* structure = new size_t[length]; return new parser(ms, structure); } void sj_parser_free(parser* parser) { delete parser; } document* sj_parser_get_document(parser* parser) { return new document(parser->get_document()); } void sj_document_free(document* document) { delete document; } bool sj_document_is_valid(document* document) { return document->is_valid(); } value* sj_document_get_root(document* document) { return new value(document->get_root()); } size_t sj_document_get_error_line(document* doc) { return doc->get_error_line(); } size_t sj_document_get_error_column(document* doc) { return doc->get_error_column(); } const char* sj_document_get_error_message(document* doc) { return doc->get_error_message().c_str(); } void sj_value_free(value* v) { delete v; } type sj_value_get_type(value* v) { return v->get_type(); } size_t sj_value_get_length(value* v) { return v->get_length(); } value* sj_value_get_array_element(value* v, size_t index) { return new value(v->get_array_element(index)); } void sj_value_get_object_key(value* v, size_t index, const char** result, size_t* resultLength) { string s = v->get_object_key(index); *result = s.data(); *resultLength = s.length(); } value* sj_value_get_object_value(value* v, size_t index) { return new value(v->get_object_value(index)); } size_t sj_value_find_object_key(value* v, string key) { return v->find_object_key(key); } int sj_value_get_integer_value(value* v) { return v->get_integer_value(); } double sj_value_get_double_value(value* v) { return v->get_double_value(); } double sj_value_get_number_value(value* v) { return v->get_number_value(); } size_t sj_value_get_string_length(value* v) { return v->get_string_length(); } void sj_value_get_string_value(value* v, const char** result, size_t* resultLength) { string s = v->as_str(); *result = s.data(); *resultLength = s.length(); } value* sj_value_get_object_with_key(value* v, const char* key, size_t keyLength) { string k(key, keyLength); size_t index = v->find_object_key(k); if (index < v->get_length()) { return new value(v->get_object_value(index)); } else { return 0; } } }<|endoftext|>
<commit_before>#/*########################################################################## # # The fisx library for X-Ray Fluorescence # # Copyright (c) 2014 V. Armando Sole # # This file is part of the fisx X-ray developed by V.A. Sole # # 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 "fisx_simplespecfile.h" #include <iostream> #include <fstream> #include <stdexcept> #include <stdlib.h> #include <cctype> #define isNumber(x) ( isdigit(x) || x == '-' || x == '+' || x == '.' || x == 'E' || x == 'e') namespace fisx { SimpleSpecfile::SimpleSpecfile() { this->fileName = ""; this->scanFilePositions.clear(); this->scanPosition.clear(); } SimpleSpecfile::SimpleSpecfile(std::string fileName) { this->setFileName(fileName); } void SimpleSpecfile::setFileName(std::string fileName) { std::string line; long startLine = -1; long endLine = -1; long numberOfLines = -1; std::ifstream fileInstance(fileName.c_str(), std::ios::in | std::ios::binary); std::streampos position; this->scanFilePositions.clear(); this->scanPosition.clear(); position = 0; while (std::getline(fileInstance, line)) { //std::cout << line << std::endl; ++numberOfLines; if(line.size() > 1) { if (line.substr(0, 2) == "#S") { startLine = numberOfLines; this->scanFilePositions.push_back(std::make_pair(startLine, startLine)); endLine = -1; this->scanPosition.push_back(position); } } else { if(startLine >= 0) { startLine = -1; endLine = numberOfLines; this->scanFilePositions.back().second = endLine; } } position = fileInstance.tellg(); } if ((endLine == -1) && startLine >= 0) { this->scanFilePositions.back().second = numberOfLines + 1; } fileInstance.clear(); if (fileInstance.is_open()) { fileInstance.close(); } // std::cout << "Number of scans: " << this->scanFilePositions.size(); // std::cout << std::endl; this->fileName = fileName; //std::cout << "PASSED" << std::endl; } int SimpleSpecfile::getNumberOfScans() { return (int) this->scanFilePositions.size(); } std::vector<std::string> SimpleSpecfile::getScanLabels(int scanIndex) { std::ifstream fileInstance(this->fileName.c_str(), std::ios::in | std::ios::binary); std::string line; std::string::size_type iStart, iEnd; long i; long nLines; std::vector<std::string> result; // fileInstance.seekg(0, std::ifstream::beg); if((scanIndex >= (long) this->getNumberOfScans()) || (scanIndex < 0)) { throw std::invalid_argument("Not a valid scan index"); } // This is very slow //for (i = 0; i < this->scanFilePositions[scanIndex].first; i++) //{ // std::getline(fileInstance, line); // //std::cout << line << std::endl; //} // This is faster but needs the file open in binary mode fileInstance.seekg(this->scanPosition[scanIndex], std::ios::beg); nLines = 1 + this->scanFilePositions[scanIndex].second - \ this->scanFilePositions[scanIndex].first; if (nLines < 0) { throw std::runtime_error("Negative number of lines to be read !!!"); } i = 0; while (i < nLines) { if (line.size() > 1) { if (line.substr(0, 2) != "#L") { std::getline(fileInstance, line); } else { // go out of the loop i = nLines; } } else { std::getline(fileInstance, line); } i++; } if (line.substr(0, 2) != "#L") { throw std::runtime_error("Label line not found"); } // trim leading and trailing spaces iStart = line.find_first_of(" ") + 1; iEnd = line.find_last_not_of(" "); line = line.substr(iStart, 1 + iEnd - iStart); // split on two spaces i = 0; iStart = 0; while ( i < (long) (line.size() - 2)) { if (line.substr(i, 2) == " ") { result.push_back(line.substr(iStart, i - iStart)); while ((line.substr(i, 1) == " ") && (i < (long) line.size())) { i++; } iStart = i; } else { i++; } } if (iStart < line.size()) { result.push_back(line.substr(iStart, line.size() - iStart)); } return result; } std::vector<std::vector<double> > SimpleSpecfile::getScanData(int scanIndex) { std::ifstream fileInstance(this->fileName.c_str(), std::ios::in | std::ios::binary); std::string line; std::string::size_type iString; std::string tmpString; long i; bool replaceDot; std::vector<std::vector<double> > result; std::vector<double> lineNumbers; std::vector<std::vector<double> >::size_type row = 0; if((strtod("4.5", NULL) - 4.0) < 0.4) { replaceDot = true; } else { replaceDot = false; } if((scanIndex >= (long) this->getNumberOfScans()) || (scanIndex < 0)) { throw std::invalid_argument("Not a valid scan index"); } //for (i = 0; i < this->scanFilePositions[scanIndex].first; i++) //{ // std::getline(fileInstance, line); //} // If instead of the loop I use this it does not work unless the file is opened in binary mode fileInstance.seekg(this->scanPosition[scanIndex], std::ios::beg); i = this->scanFilePositions[scanIndex].first; for ( ; i < this->scanFilePositions[scanIndex].second; i++) { std::getline(fileInstance, line); // std::cout << line << std::endl; if ((i < this->scanFilePositions[scanIndex].first) ||\ (line[0] == '#')) { // either we have not reached the scan // or it is a header or comment line ; } else { // std::cout << line.size() << "Numeric Data line: " << line << std::endl; // parse the line iString = 0; lineNumbers.clear(); while (iString < line.size()) { tmpString.clear(); while( (!isNumber(line[iString])) && (iString < line.size())) { iString++; } while( (isNumber(line[iString])) && (iString < line.size())) { if (replaceDot && (line[iString] == '.')) { tmpString += ","; } else { tmpString += line[iString]; } iString++; } if (tmpString.size() > 0) { lineNumbers.push_back(strtod(tmpString.c_str(), NULL)); } } if (lineNumbers.size() > 0) { if (result.size() > 0) { if (result[0].size() != lineNumbers.size()) { throw std::runtime_error("Badly formatted line"); } } result.push_back(lineNumbers); } row++; } } return result; } } // namespace fisx <commit_msg>Remove trailing CR to prevent problems due to modification of reference data files by the users.<commit_after>#/*########################################################################## # # The fisx library for X-Ray Fluorescence # # Copyright (c) 2014 V. Armando Sole # # This file is part of the fisx X-ray developed by V.A. Sole # # 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 "fisx_simplespecfile.h" #include <iostream> #include <fstream> #include <stdexcept> #include <stdlib.h> #include <cctype> #define isNumber(x) ( isdigit(x) || x == '-' || x == '+' || x == '.' || x == 'E' || x == 'e') namespace fisx { SimpleSpecfile::SimpleSpecfile() { this->fileName = ""; this->scanFilePositions.clear(); this->scanPosition.clear(); } SimpleSpecfile::SimpleSpecfile(std::string fileName) { this->setFileName(fileName); } void SimpleSpecfile::setFileName(std::string fileName) { std::string line; long startLine = -1; long endLine = -1; long numberOfLines = -1; std::ifstream fileInstance(fileName.c_str(), std::ios::in | std::ios::binary); std::streampos position; this->scanFilePositions.clear(); this->scanPosition.clear(); position = 0; while (std::getline(fileInstance, line)) { //std::cout << line << std::endl; ++numberOfLines; if(line.size() > 1) { if (line.substr(0, 2) == "#S") { startLine = numberOfLines; this->scanFilePositions.push_back(std::make_pair(startLine, startLine)); endLine = -1; this->scanPosition.push_back(position); } } else { if(startLine >= 0) { startLine = -1; endLine = numberOfLines; this->scanFilePositions.back().second = endLine; } } position = fileInstance.tellg(); } if ((endLine == -1) && startLine >= 0) { this->scanFilePositions.back().second = numberOfLines + 1; } fileInstance.clear(); if (fileInstance.is_open()) { fileInstance.close(); } // std::cout << "Number of scans: " << this->scanFilePositions.size(); // std::cout << std::endl; this->fileName = fileName; //std::cout << "PASSED" << std::endl; } int SimpleSpecfile::getNumberOfScans() { return (int) this->scanFilePositions.size(); } std::vector<std::string> SimpleSpecfile::getScanLabels(int scanIndex) { std::ifstream fileInstance(this->fileName.c_str(), std::ios::in | std::ios::binary); std::string line; std::string::size_type iStart, iEnd; long i; long nLines; std::vector<std::string> result; // fileInstance.seekg(0, std::ifstream::beg); if((scanIndex >= (long) this->getNumberOfScans()) || (scanIndex < 0)) { throw std::invalid_argument("Not a valid scan index"); } // This is very slow //for (i = 0; i < this->scanFilePositions[scanIndex].first; i++) //{ // std::getline(fileInstance, line); // //std::cout << line << std::endl; //} // This is faster but needs the file open in binary mode fileInstance.seekg(this->scanPosition[scanIndex], std::ios::beg); nLines = 1 + this->scanFilePositions[scanIndex].second - \ this->scanFilePositions[scanIndex].first; if (nLines < 0) { throw std::runtime_error("Negative number of lines to be read !!!"); } i = 0; while (i < nLines) { if (line.size() > 1) { if (line.substr(0, 2) != "#L") { std::getline(fileInstance, line); } else { // go out of the loop i = nLines; } } else { std::getline(fileInstance, line); } i++; } if (line.size() < 2) { throw std::runtime_error("Label line not found"); } if (line.substr(0, 2) != "#L") { throw std::runtime_error("Label line not found"); } // trim trailing CR if present if (line[line.size() - 1] == '\r') line.erase(line.size() - 1); // trim leading and trailing spaces iStart = line.find_first_of(" ") + 1; iEnd = line.find_last_not_of(" "); line = line.substr(iStart, 1 + iEnd - iStart); // split on two spaces i = 0; iStart = 0; while ( i < (long) (line.size() - 2)) { if (line.substr(i, 2) == " ") { result.push_back(line.substr(iStart, i - iStart)); while ((line.substr(i, 1) == " ") && (i < (long) line.size())) { i++; } iStart = i; } else { i++; } } if (iStart < line.size()) { result.push_back(line.substr(iStart, line.size() - iStart)); } return result; } std::vector<std::vector<double> > SimpleSpecfile::getScanData(int scanIndex) { std::ifstream fileInstance(this->fileName.c_str(), std::ios::in | std::ios::binary); std::string line; std::string::size_type iString; std::string tmpString; long i; bool replaceDot; std::vector<std::vector<double> > result; std::vector<double> lineNumbers; std::vector<std::vector<double> >::size_type row = 0; if((strtod("4.5", NULL) - 4.0) < 0.4) { replaceDot = true; } else { replaceDot = false; } if((scanIndex >= (long) this->getNumberOfScans()) || (scanIndex < 0)) { throw std::invalid_argument("Not a valid scan index"); } //for (i = 0; i < this->scanFilePositions[scanIndex].first; i++) //{ // std::getline(fileInstance, line); //} // If instead of the loop I use this it does not work unless the file is opened in binary mode fileInstance.seekg(this->scanPosition[scanIndex], std::ios::beg); i = this->scanFilePositions[scanIndex].first; for ( ; i < this->scanFilePositions[scanIndex].second; i++) { std::getline(fileInstance, line); if (!line.empty()) { if(line[line.size() - 1] == '\r') line.erase(line.size() - 1); } // std::cout << line << std::endl; if ((i < this->scanFilePositions[scanIndex].first) ||\ (line[0] == '#')) { // either we have not reached the scan // or it is a header or comment line ; } else { // std::cout << line.size() << "Numeric Data line: " << line << std::endl; // parse the line iString = 0; lineNumbers.clear(); while (iString < line.size()) { tmpString.clear(); while( (!isNumber(line[iString])) && (iString < line.size())) { iString++; } while( (isNumber(line[iString])) && (iString < line.size())) { if (replaceDot && (line[iString] == '.')) { tmpString += ","; } else { tmpString += line[iString]; } iString++; } if (tmpString.size() > 0) { lineNumbers.push_back(strtod(tmpString.c_str(), NULL)); } } if (lineNumbers.size() > 0) { if (result.size() > 0) { if (result[0].size() != lineNumbers.size()) { throw std::runtime_error("Badly formatted line"); } } result.push_back(lineNumbers); } row++; } } return result; } } // namespace fisx <|endoftext|>
<commit_before>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code (advanced), about // // - loading an Abaqus tetahedrom mesh // - apply a load to the mesh using an external tool, // say CFD or SPH (here simulated as a function in this .cpp file) // that is perform a cosimulation. #include "chrono/physics/ChSystem.h" #include "chrono/physics/ChSystemDEM.h" #include "chrono/physics/ChLoadContainer.h" #include "chrono/geometry/ChCTriangleMeshConnected.h" #include "chrono/lcp/ChLcpIterativeMINRES.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_vehicle/terrain/DeformableTerrain.h" #include "chrono_vehicle/ChVehicleModelData.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; int main(int argc, char* argv[]) { // Global parameter for tire: double tire_rad = 0.8; double tire_vel_z0 = -3; ChVector<> tire_center(0, 0.02+tire_rad, 0); ChMatrix33<> tire_alignment(Q_from_AngAxis(CH_C_PI, VECT_Y)); // create rotated 180 on y double tire_w0 = tire_vel_z0/tire_rad; // Create a Chrono::Engine physical system ChSystemDEM my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0)); application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512, video::SColorf(0.8f, 0.8f, 1.0f)); std::shared_ptr<ChBody> mtruss (new ChBody); mtruss->SetBodyFixed(true); my_system.Add(mtruss); // // CREATE A RIGID BODY WITH A MESH // // Create also a rigid body with a rigid mesh that will be used for the cosimulation, // this time the ChLoadContactSurfaceMesh cannot be used as in the FEA case, so we // will use the ChLoadBodyMesh class: std::shared_ptr<ChBody> mrigidbody (new ChBody); my_system.Add(mrigidbody); mrigidbody->SetMass(200); mrigidbody->SetInertiaXX(ChVector<>(20,20,20)); mrigidbody->SetPos(tire_center + ChVector<>(0,0.3,0)); std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape); mrigidmesh->GetMesh().LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj")); mrigidmesh->GetMesh().Transform(VNULL, Q_from_AngAxis(CH_C_PI, VECT_Y) ); mrigidbody->AddAsset(mrigidmesh); mrigidbody->GetCollisionModel()->ClearModel(); mrigidbody->GetCollisionModel()->AddTriangleMesh(mrigidmesh->GetMesh(),false, false, VNULL, ChMatrix33<>(CH_C_PI, VECT_Y),0.01); mrigidbody->GetCollisionModel()->BuildModel(); mrigidbody->SetCollide(true); std::shared_ptr<ChColorAsset> mcol(new ChColorAsset); mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f)); mrigidbody->AddAsset(mcol); std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine); myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM); myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED); if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(myengine->Get_spe_funct()) ) mfun->Set_yconst(CH_C_PI / 4.0); myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y))); my_system.Add(myengine); // // THE DEFORMABLE TERRAIN // // Create the 'deformable terrain' object std::shared_ptr<vehicle::DeformableTerrain> mterrain (new vehicle::DeformableTerrain(&my_system)); my_system.Add(mterrain); // Optionally, displace/tilt/rotate the terrain reference plane: mterrain->SetPlane(ChCoordsys<>( ChVector<>(0,0,0.5)) ); // Initialize the geometry of the soil: use either a regular grid: // mterrain->Initialize(0.2,1,1,50,50); // or use a height map: mterrain->Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 2, 2, 0, 0.3); // Set the soil terramechanical parameters: mterrain->SetSoilParametersSCM( 0.2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 20, // Mohr friction limit (degrees) 0.01 // Janosi shear coefficient (m) ); // Set some visualization parameters: either with a texture, or with falsecolor plot, etc. mterrain->SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16); //mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2); //mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets application.AssetUpdateAll(); // Use shadows in realtime view application.AddShadowAll(); // ==IMPORTANT!== Mark completion of system construction my_system.SetupInitial(); // // THE SOFT-REAL-TIME CYCLE // /* // Change solver to embedded MINRES // NOTE! it is strongly advised that you compile the optional MKL module // if you need higher precision, and switch to its MKL solver - see demos for FEA & MKL. my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_MINRES); my_system.SetIterLCPwarmStarting(true); // this helps a lot to speedup convergence in this class of problems my_system.SetIterLCPmaxItersSpeed(40); my_system.SetTolForce(1e-10); */ // Change type of integrator: //my_system.SetIntegrationType(chrono::ChSystem::INT_EULER_IMPLICIT_LINEARIZED); // fast, less precise application.SetTimestep(0.005); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.DoStep(); // ChIrrTools::drawGrid(application.GetVideoDriver(), 0.1, 0.1, 20, 20, // ChCoordsys<>(VNULL, CH_C_PI_2, VECT_X), video::SColor(50, 90, 90, 90), true); application.EndScene(); } return 0; } <commit_msg>Updated demo for deformable soil.<commit_after>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code (advanced), about // // - loading an Abaqus tetahedrom mesh // - apply a load to the mesh using an external tool, // say CFD or SPH (here simulated as a function in this .cpp file) // that is perform a cosimulation. #include "chrono/physics/ChSystem.h" #include "chrono/physics/ChSystemDEM.h" #include "chrono/physics/ChLoadContainer.h" #include "chrono/geometry/ChCTriangleMeshConnected.h" #include "chrono/lcp/ChLcpIterativeMINRES.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_vehicle/terrain/DeformableTerrain.h" #include "chrono_vehicle/ChVehicleModelData.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; int main(int argc, char* argv[]) { // Global parameter for tire: double tire_rad = 0.8; double tire_vel_z0 = -3; ChVector<> tire_center(0, 0.02+tire_rad, 0); ChMatrix33<> tire_alignment(Q_from_AngAxis(CH_C_PI, VECT_Y)); // create rotated 180 on y double tire_w0 = tire_vel_z0/tire_rad; // Create a Chrono::Engine physical system ChSystemDEM my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0)); application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512, video::SColorf(0.8f, 0.8f, 1.0f)); std::shared_ptr<ChBody> mtruss (new ChBody); mtruss->SetBodyFixed(true); my_system.Add(mtruss); // // CREATE A RIGID BODY WITH A MESH // // Create also a rigid body with a rigid mesh that will be used for the cosimulation, // this time the ChLoadContactSurfaceMesh cannot be used as in the FEA case, so we // will use the ChLoadBodyMesh class: std::shared_ptr<ChBody> mrigidbody (new ChBody); my_system.Add(mrigidbody); mrigidbody->SetMass(200); mrigidbody->SetInertiaXX(ChVector<>(20,20,20)); mrigidbody->SetPos(tire_center + ChVector<>(0,0.3,0)); std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape); mrigidmesh->GetMesh().LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj")); mrigidmesh->GetMesh().Transform(VNULL, Q_from_AngAxis(CH_C_PI, VECT_Y) ); mrigidbody->AddAsset(mrigidmesh); mrigidbody->GetCollisionModel()->ClearModel(); mrigidbody->GetCollisionModel()->AddTriangleMesh(mrigidmesh->GetMesh(),false, false, VNULL, ChMatrix33<>(CH_C_PI, VECT_Y),0.01); mrigidbody->GetCollisionModel()->BuildModel(); mrigidbody->SetCollide(true); std::shared_ptr<ChColorAsset> mcol(new ChColorAsset); mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f)); mrigidbody->AddAsset(mcol); std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine); myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM); myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED); if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(myengine->Get_spe_funct()) ) mfun->Set_yconst(CH_C_PI / 4.0); myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y))); my_system.Add(myengine); // // THE DEFORMABLE TERRAIN // // Create the 'deformable terrain' object std::shared_ptr<vehicle::DeformableTerrain> mterrain (new vehicle::DeformableTerrain(&my_system)); my_system.Add(mterrain); // Optionally, displace/tilt/rotate the terrain reference plane: mterrain->SetPlane(ChCoordsys<>( ChVector<>(0,0,0.5)) ); // Initialize the geometry of the soil: use either a regular grid: // mterrain->Initialize(0.2,1,1,50,50); // or use a height map: mterrain->Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 2, 2, 0, 0.3); // Set the soil terramechanical parameters: mterrain->SetSoilParametersSCM( 1.2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 20, // Mohr friction limit (degrees) 0.01,// Janosi shear coefficient (m) 2e7 // Elastic stiffness (Pa/m), before plastic yeld ); // Set some visualization parameters: either with a texture, or with falsecolor plot, etc. //mterrain->SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16); //mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2); mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2); //mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15); //mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15); //mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05); //mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001); //mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_ISLAND_ID, 0, 8); //mterrain->SetPlotType(vehicle::DeformableTerrain::PLOT_IS_TOUCHED, 0, 8); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets application.AssetUpdateAll(); // Use shadows in realtime view application.AddShadowAll(); // ==IMPORTANT!== Mark completion of system construction my_system.SetupInitial(); // // THE SOFT-REAL-TIME CYCLE // /* // Change solver to embedded MINRES // NOTE! it is strongly advised that you compile the optional MKL module // if you need higher precision, and switch to its MKL solver - see demos for FEA & MKL. my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_MINRES); my_system.SetIterLCPwarmStarting(true); // this helps a lot to speedup convergence in this class of problems my_system.SetIterLCPmaxItersSpeed(40); my_system.SetTolForce(1e-10); */ application.SetTimestep(0.005); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.DoStep(); ChIrrTools::drawColorbar(0,30000, "Pressure yeld [Pa]", application.GetDevice(), 1180); application.EndScene(); } return 0; } <|endoftext|>
<commit_before>#ifndef TURBO_MEMORY_TAGGED_PTR_HPP #define TURBO_MEMORY_TAGGED_PTR_HPP #include <cstdint> #include <atomic> #include <limits> #include <stdexcept> #include <string> #include <turbo/toolset/extension.hpp> namespace turbo { namespace memory { class unaligned_ptr_error : public std::invalid_argument { public: explicit unaligned_ptr_error(const std::string& what) : invalid_argument(what) { } explicit unaligned_ptr_error(const char* what) : invalid_argument(what) { } }; template <class value_t, class tag_t> class tagged_ptr final { public: typedef value_t value_type; typedef tag_t tag_type; typedef value_t* value_ptr_type; inline explicit tagged_ptr(value_type* ptr) : ptr_(ptr) { if ((reinterpret_cast<std::uintptr_t>(ptr) & tag_mask()) != 0U) { throw unaligned_ptr_error("Given pointer is not a multiple of 4"); } } inline explicit tagged_ptr(value_type* ptr, tag_type tag) : tagged_ptr(ptr) { set_tag(tag); } inline explicit tagged_ptr(tag_type tag) noexcept : tagged_ptr(nullptr, tag) { } inline tagged_ptr() noexcept : tagged_ptr(nullptr) { } tagged_ptr(const tagged_ptr<value_t, tag_t>& other) = default; tagged_ptr(tagged_ptr<value_t, tag_t>&& other) = default; tagged_ptr<value_t, tag_t>& operator=(const tagged_ptr<value_t, tag_t>& other) = default; tagged_ptr<value_t, tag_t>& operator=(tagged_ptr<value_t, tag_t>&& other) = default; ~tagged_ptr() noexcept = default; inline value_t* get_ptr() const { return reinterpret_cast<value_t*>(reinterpret_cast<std::uintptr_t>(ptr_) & ptr_mask()); } inline tag_t get_tag() const { return static_cast<tag_t>(reinterpret_cast<std::uintptr_t>(ptr_) & tag_mask()); } inline bool is_empty() const { return get_ptr() == nullptr; } inline void set_tag(tag_t tag) { ptr_ = reinterpret_cast<value_t*>(reinterpret_cast<std::uintptr_t>(get_ptr()) | (static_cast<std::uintptr_t>(tag) & tag_mask())); } inline bool operator==(const tagged_ptr<value_t, tag_t>& other) const { return ptr_ == other.ptr_; } inline bool operator!=(const tagged_ptr<value_t, tag_t>& other) const { return !(*this == other); } inline tagged_ptr<value_t, tag_t> operator|(const tag_t tag) const { tagged_ptr<value_t, tag_t> tmp; tmp.set_tag(tag); return tmp; } inline void reset() { ptr_ = nullptr; } inline void reset(value_t* ptr) { ptr_ = ptr; } inline void reset(tag_type tag) { ptr_ = nullptr; set_tag(tag); } inline void reset(value_t* ptr, tag_type tag) { ptr_ = ptr; set_tag(tag); } inline value_t& operator*() { return *get_ptr(); } inline value_t* operator->() { return get_ptr(); } private: friend class std::atomic<tagged_ptr<value_t, tag_t>>; constexpr std::uintptr_t ptr_mask() { // FIXME: should depend on pointer size rather than hard coding the tag area size return std::numeric_limits<std::uintptr_t>::max() - 3U; } constexpr std::uintptr_t tag_mask() { // FIXME: should depend on pointer size rather than hard coding the tag area size return static_cast<std::uintptr_t>(3U); } value_t* ptr_; }; } // namespace memory } // namespace turbo namespace std { /// /// Partial specialisation of std::atomic for tagged_ptr /// template <class value_t, class tag_t> struct atomic<turbo::memory::tagged_ptr<value_t, tag_t>> : private std::atomic<typename turbo::memory::tagged_ptr<value_t, tag_t>::value_ptr_type> { typedef turbo::memory::tagged_ptr<value_t, tag_t> tagged_ptr_type; typedef std::atomic<typename tagged_ptr_type::value_ptr_type> base_type; atomic() noexcept = default; constexpr atomic(tagged_ptr_type value) noexcept : base_type(value.ptr_) { } atomic(const atomic&) = delete; ~atomic() noexcept = default; using base_type::is_lock_free; inline void store(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { base_type::store(value.ptr_, sync); } inline void store(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { base_type::store(value.ptr_, sync); } inline tagged_ptr_type load(memory_order sync = memory_order_seq_cst) const volatile noexcept { tagged_ptr_type tmp; tmp.reset(base_type::load(sync)); return tmp; } inline tagged_ptr_type load(memory_order sync = memory_order_seq_cst) const noexcept { tagged_ptr_type tmp; tmp.reset(base_type::load(sync)); return tmp; } operator tagged_ptr_type() const volatile noexcept { return load(); } operator tagged_ptr_type() const noexcept { return load(); } inline tagged_ptr_type exchange(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return tagged_ptr_type(base_type::exchange(value.ptr_, sync)); } inline tagged_ptr_type exchange(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return tagged_ptr_type(base_type::exchange(value.ptr_, sync)); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) volatile noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) volatile noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, success, failure); } }; } // namespace std #endif <commit_msg>* implemented my own copy/move constructor/assignment and destructor instead of relying on the default implementation * overloaded the * and -> operators with a const version<commit_after>#ifndef TURBO_MEMORY_TAGGED_PTR_HPP #define TURBO_MEMORY_TAGGED_PTR_HPP #include <cstdint> #include <atomic> #include <limits> #include <stdexcept> #include <string> #include <turbo/toolset/extension.hpp> namespace turbo { namespace memory { class unaligned_ptr_error : public std::invalid_argument { public: explicit unaligned_ptr_error(const std::string& what) : invalid_argument(what) { } explicit unaligned_ptr_error(const char* what) : invalid_argument(what) { } }; template <class value_t, class tag_t> class tagged_ptr final { public: typedef value_t value_type; typedef tag_t tag_type; typedef value_t* value_ptr_type; inline explicit tagged_ptr(value_type* ptr) : ptr_(ptr) { if ((reinterpret_cast<std::uintptr_t>(ptr) & tag_mask()) != 0U) { throw unaligned_ptr_error("Given pointer is not a multiple of 4"); } } inline explicit tagged_ptr(value_type* ptr, tag_type tag) : tagged_ptr(ptr) { set_tag(tag); } inline explicit tagged_ptr(tag_type tag) noexcept : tagged_ptr(nullptr, tag) { } inline tagged_ptr() noexcept : tagged_ptr(nullptr) { } inline tagged_ptr(const tagged_ptr<value_t, tag_t>& other) : ptr_(other.ptr_) { } inline tagged_ptr(tagged_ptr<value_t, tag_t>&& other) : ptr_(other.ptr_) { other.reset(); } inline tagged_ptr<value_t, tag_t>& operator=(const tagged_ptr<value_t, tag_t>& other) { if (this != &other) { ptr_ = other.ptr_; } return *this; } inline tagged_ptr<value_t, tag_t>& operator=(tagged_ptr<value_t, tag_t>&& other) { if (this != &other) { ptr_ = other.ptr_; other.reset(); } return *this; } ~tagged_ptr() noexcept { reset(); } inline value_t* get_ptr() const { return reinterpret_cast<value_t*>(reinterpret_cast<std::uintptr_t>(ptr_) & ptr_mask()); } inline tag_t get_tag() const { return static_cast<tag_t>(reinterpret_cast<std::uintptr_t>(ptr_) & tag_mask()); } inline bool is_empty() const { return get_ptr() == nullptr; } inline void set_tag(tag_t tag) { ptr_ = reinterpret_cast<value_t*>(reinterpret_cast<std::uintptr_t>(get_ptr()) | (static_cast<std::uintptr_t>(tag) & tag_mask())); } inline bool operator==(const tagged_ptr<value_t, tag_t>& other) const { return ptr_ == other.ptr_; } inline bool operator!=(const tagged_ptr<value_t, tag_t>& other) const { return !(*this == other); } inline tagged_ptr<value_t, tag_t> operator|(const tag_t tag) const { tagged_ptr<value_t, tag_t> tmp; tmp.set_tag(tag); return tmp; } inline void reset() { ptr_ = nullptr; } inline void reset(value_t* ptr) { ptr_ = ptr; } inline void reset(tag_type tag) { ptr_ = nullptr; set_tag(tag); } inline void reset(value_t* ptr, tag_type tag) { ptr_ = ptr; set_tag(tag); } inline const value_t& operator*() const { return *get_ptr(); } inline value_t& operator*() { return *get_ptr(); } inline const value_t* operator->() const { return get_ptr(); } inline value_t* operator->() { return get_ptr(); } private: friend class std::atomic<tagged_ptr<value_t, tag_t>>; constexpr std::uintptr_t ptr_mask() { // FIXME: should depend on pointer size rather than hard coding the tag area size return std::numeric_limits<std::uintptr_t>::max() - 3U; } constexpr std::uintptr_t tag_mask() { // FIXME: should depend on pointer size rather than hard coding the tag area size return static_cast<std::uintptr_t>(3U); } value_t* ptr_; }; } // namespace memory } // namespace turbo namespace std { /// /// Partial specialisation of std::atomic for tagged_ptr /// template <class value_t, class tag_t> struct atomic<turbo::memory::tagged_ptr<value_t, tag_t>> : private std::atomic<typename turbo::memory::tagged_ptr<value_t, tag_t>::value_ptr_type> { typedef turbo::memory::tagged_ptr<value_t, tag_t> tagged_ptr_type; typedef std::atomic<typename tagged_ptr_type::value_ptr_type> base_type; atomic() noexcept = default; constexpr atomic(tagged_ptr_type value) noexcept : base_type(value.ptr_) { } atomic(const atomic&) = delete; ~atomic() noexcept = default; using base_type::is_lock_free; inline void store(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { base_type::store(value.ptr_, sync); } inline void store(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { base_type::store(value.ptr_, sync); } inline tagged_ptr_type load(memory_order sync = memory_order_seq_cst) const volatile noexcept { tagged_ptr_type tmp; tmp.reset(base_type::load(sync)); return tmp; } inline tagged_ptr_type load(memory_order sync = memory_order_seq_cst) const noexcept { tagged_ptr_type tmp; tmp.reset(base_type::load(sync)); return tmp; } operator tagged_ptr_type() const volatile noexcept { return load(); } operator tagged_ptr_type() const noexcept { return load(); } inline tagged_ptr_type exchange(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return tagged_ptr_type(base_type::exchange(value.ptr_, sync)); } inline tagged_ptr_type exchange(tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return tagged_ptr_type(base_type::exchange(value.ptr_, sync)); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) volatile noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_weak(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) noexcept { return base_type::compare_exchange_weak(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) volatile noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order sync = memory_order_seq_cst) noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, sync); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) volatile noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, success, failure); } inline bool compare_exchange_strong(tagged_ptr_type& expected, tagged_ptr_type value, memory_order success, memory_order failure) noexcept { return base_type::compare_exchange_strong(expected.ptr_, value.ptr_, success, failure); } }; } // namespace std #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: util.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-10-22 14:04:39 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_SCRIPTING_UTIL_UTIL_HXX_ #define _COM_SUN_STAR_SCRIPTING_UTIL_UTIL_HXX_ #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #define OUSTR(x) ::rtl::OUString( ::rtl::OUString::createFromAscii(x) ) namespace scripting_util { inline void validateXRef(::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xRef, sal_Char* Msg) throw (::com::sun::star::uno::RuntimeException) { OSL_ENSURE( xRef.is(), Msg ); if(!xRef.is()) { OSL_TRACE( Msg ); throw ::com::sun::star::uno::RuntimeException(OUSTR(Msg), ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >()); } } } #endif //_COM_SUN_STAR_SCRIPTING_UTIL_UTIL_HXX_ <commit_msg>INTEGRATION: CWS scriptingf10 (1.2.16); FILE MERGED 2005/01/12 14:03:56 toconnor 1.2.16.1: #i40429# remove OSL_TRACE calls before beta<commit_after>/************************************************************************* * * $RCSfile: util.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-01-27 15:30:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_SCRIPTING_UTIL_UTIL_HXX_ #define _COM_SUN_STAR_SCRIPTING_UTIL_UTIL_HXX_ #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #define OUSTR(x) ::rtl::OUString( ::rtl::OUString::createFromAscii(x) ) namespace scripting_util { inline void validateXRef(::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xRef, sal_Char* Msg) throw (::com::sun::star::uno::RuntimeException) { OSL_ENSURE( xRef.is(), Msg ); if(!xRef.is()) { throw ::com::sun::star::uno::RuntimeException(OUSTR(Msg), ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >()); } } } #endif //_COM_SUN_STAR_SCRIPTING_UTIL_UTIL_HXX_ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file rcd_load.H /// @brief Code to support rcd_loads /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Craig Hamilton <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_RCD_LOAD_H_ #define _MSS_RCD_LOAD_H_ #include <fapi2.H> #include "../utils/c_str.H" #include <p9_mc_scom_addresses.H> #include "../shared/mss_kind.H" namespace mss { struct rcd_data { // Which RC# this is fapi2::buffer<uint8_t> iv_rcd; // The attribute getter fapi2::ReturnCode (*iv_func)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>&, uint8_t&); // The delay needed after this RCD word is written uint64_t iv_delay; rcd_data( uint64_t i_rcd, fapi2::ReturnCode (*i_func)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>&, uint8_t&), uint64_t i_delay ): iv_rcd(i_rcd), iv_func(i_func), iv_delay(i_delay) {} }; /// /// @brief Perform the rcd_load operations /// @tparam T, the fapi2::TargetType of i_target /// @param[in] i_target, a fapi2::Target /// @return FAPI2_RC_SUCCESS if and only if ok /// template< fapi2::TargetType T > fapi2::ReturnCode rcd_load( const fapi2::Target<T>& i_target ); // // Implement the polymorphism for rcd_load // // -# Register the API. /// -# Define the template parameters for the overloaded function /// @note the first argument is the api name, and the rest are the api's template parameters. /// @note this creates __api_name##_overload template< mss::kind_t K > struct perform_rcd_load_overload { static const bool available = false; }; /// -# Register the specific overloads. The first parameter is the name /// of the api, the second is the kind of the element which is being /// overloaded - an RDIMM, an LRDIMM, etc. The remaining parameters /// indicate the specialization of the api itself. /// @note You need to define the "DEFAULT_KIND" here as an overload. This /// allows the mechanism to find the "base" implementation for things which /// have no specific overload. template<> struct perform_rcd_load_overload< DEFAULT_KIND > { static const bool available = true; }; template<> struct perform_rcd_load_overload< KIND_RDIMM_DDR4 > { static const bool available = true; }; template<> struct perform_rcd_load_overload< KIND_LRDIMM_DDR4 > { static const bool available = true; }; /// /// -# Define the default case for overloaded calls. enable_if states that /// if there is a DEFAULT_KIND overload for this TargetType, then this /// entry point will be defined. Note the general case below is enabled if /// there is no overload defined for this TargetType /// /// /// @brief Perform the rcd_load operations /// @tparam K, the kind of DIMM we're operating on (derived) /// @param[in] i_target, a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] a vector of CCS instructions we should add to /// @return FAPI2_RC_SUCCESS if and only if ok /// template< mss::kind_t K = FORCE_DISPATCH > typename std::enable_if< perform_rcd_load_overload<DEFAULT_KIND>::available, fapi2::ReturnCode>::type perform_rcd_load( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); // // We know we registered overloads for perform_rcd_load, so we need the entry point to // the dispatcher. Add a set of these for all TargetTypes which get overloads // for this API // template<> fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); template<> fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); // // Boilerplate dispatcher // template< kind_t K, bool B = perform_rcd_load_overload<K>::available > inline fapi2::ReturnCode perform_rcd_load_dispatch( const kind_t& i_kind, const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst) { // We dispatch to another kind if: // We don't have an overload defined (B == false) // Or, if we do have an overload (B == true) and this is not out kind. if ((B == false) || ((B == true) && (K != i_kind))) { return perform_rcd_load_dispatch < (kind_t)(K - 1) > (i_kind, i_target, i_inst); } // Otherwise, we call the overload. return perform_rcd_load<K>(i_target, i_inst); } // DEFAULT_KIND is 0 so this is the end of the recursion template<> inline fapi2::ReturnCode perform_rcd_load_dispatch<DEFAULT_KIND>(const kind_t&, const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst) { return perform_rcd_load<DEFAULT_KIND>(i_target, i_inst); } } #endif <commit_msg>Change include paths in memory/lib, tests<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file rcd_load.H /// @brief Code to support rcd_loads /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Craig Hamilton <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_RCD_LOAD_H_ #define _MSS_RCD_LOAD_H_ #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <lib/utils/c_str.H> #include <lib/shared/mss_kind.H> namespace mss { struct rcd_data { // Which RC# this is fapi2::buffer<uint8_t> iv_rcd; // The attribute getter fapi2::ReturnCode (*iv_func)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>&, uint8_t&); // The delay needed after this RCD word is written uint64_t iv_delay; rcd_data( uint64_t i_rcd, fapi2::ReturnCode (*i_func)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>&, uint8_t&), uint64_t i_delay ): iv_rcd(i_rcd), iv_func(i_func), iv_delay(i_delay) {} }; /// /// @brief Perform the rcd_load operations /// @tparam T, the fapi2::TargetType of i_target /// @param[in] i_target, a fapi2::Target /// @return FAPI2_RC_SUCCESS if and only if ok /// template< fapi2::TargetType T > fapi2::ReturnCode rcd_load( const fapi2::Target<T>& i_target ); // // Implement the polymorphism for rcd_load // // -# Register the API. /// -# Define the template parameters for the overloaded function /// @note the first argument is the api name, and the rest are the api's template parameters. /// @note this creates __api_name##_overload template< mss::kind_t K > struct perform_rcd_load_overload { static const bool available = false; }; /// -# Register the specific overloads. The first parameter is the name /// of the api, the second is the kind of the element which is being /// overloaded - an RDIMM, an LRDIMM, etc. The remaining parameters /// indicate the specialization of the api itself. /// @note You need to define the "DEFAULT_KIND" here as an overload. This /// allows the mechanism to find the "base" implementation for things which /// have no specific overload. template<> struct perform_rcd_load_overload< DEFAULT_KIND > { static const bool available = true; }; template<> struct perform_rcd_load_overload< KIND_RDIMM_DDR4 > { static const bool available = true; }; template<> struct perform_rcd_load_overload< KIND_LRDIMM_DDR4 > { static const bool available = true; }; /// /// -# Define the default case for overloaded calls. enable_if states that /// if there is a DEFAULT_KIND overload for this TargetType, then this /// entry point will be defined. Note the general case below is enabled if /// there is no overload defined for this TargetType /// /// /// @brief Perform the rcd_load operations /// @tparam K, the kind of DIMM we're operating on (derived) /// @param[in] i_target, a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] a vector of CCS instructions we should add to /// @return FAPI2_RC_SUCCESS if and only if ok /// template< mss::kind_t K = FORCE_DISPATCH > typename std::enable_if< perform_rcd_load_overload<DEFAULT_KIND>::available, fapi2::ReturnCode>::type perform_rcd_load( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); // // We know we registered overloads for perform_rcd_load, so we need the entry point to // the dispatcher. Add a set of these for all TargetTypes which get overloads // for this API // template<> fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); template<> fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); // // Boilerplate dispatcher // template< kind_t K, bool B = perform_rcd_load_overload<K>::available > inline fapi2::ReturnCode perform_rcd_load_dispatch( const kind_t& i_kind, const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst) { // We dispatch to another kind if: // We don't have an overload defined (B == false) // Or, if we do have an overload (B == true) and this is not out kind. if ((B == false) || ((B == true) && (K != i_kind))) { return perform_rcd_load_dispatch < (kind_t)(K - 1) > (i_kind, i_target, i_inst); } // Otherwise, we call the overload. return perform_rcd_load<K>(i_target, i_inst); } // DEFAULT_KIND is 0 so this is the end of the recursion template<> inline fapi2::ReturnCode perform_rcd_load_dispatch<DEFAULT_KIND>(const kind_t&, const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst) { return perform_rcd_load<DEFAULT_KIND>(i_target, i_inst); } } #endif <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2006 Laurent Ribon ([email protected]) Version 0.9.7, packaged on September, 2007. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_material.cpp implementation of the GLC_Material class. #include <QtDebug> #include <assert.h> #include "glc_material.h" #include "glc_collection.h" ////////////////////////////////////////////////////////////////////// // Constructor Destructor ////////////////////////////////////////////////////////////////////// GLC_Material::GLC_Material() :GLC_Object("Material") , m_fShininess(50.0) // By default shininess 50 , m_pTexture(NULL) // no texture { // Ambient Color initAmbientColor(); // Others initOtherColor(); } GLC_Material::GLC_Material(const QColor &ambientColor) :GLC_Object("Material") , m_fShininess(50.0) // default : shininess 50 , m_pTexture(NULL) // no texture { m_AmbientColor= ambientColor; // Others initOtherColor(); } GLC_Material::GLC_Material(const char *pName ,const GLfloat *pAmbientColor) :GLC_Object(pName) , m_fShininess(50.0) // default : shininess 50 , m_pTexture(NULL) // no texture { // Init Ambiant Color if (pAmbientColor != 0) { m_AmbientColor.setRgbF(static_cast<qreal>(pAmbientColor[0]), static_cast<qreal>(pAmbientColor[1]), static_cast<qreal>(pAmbientColor[2]), static_cast<qreal>(pAmbientColor[3])); } else { initAmbientColor(); } // Others initOtherColor(); } GLC_Material::GLC_Material(GLC_Texture* pTexture, const char *pName) :GLC_Object(pName) , m_fShininess(50.0) // By default shininess 50 , m_pTexture(pTexture) // Init texture { // Ambiente Color initAmbientColor(); // Others initOtherColor(); } // Copy constructor GLC_Material::GLC_Material(const GLC_Material &InitMaterial) :GLC_Object(InitMaterial.getName()) , m_fShininess(InitMaterial.m_fShininess) , m_pTexture(NULL) { if (NULL != InitMaterial.m_pTexture) { m_pTexture= new GLC_Texture(*(InitMaterial.m_pTexture)); assert(m_pTexture != NULL); } // Ambient Color m_AmbientColor= InitMaterial.m_AmbientColor; // Diffuse Color m_DiffuseColor= InitMaterial.m_DiffuseColor; // Specular Color m_SpecularColor= InitMaterial.m_SpecularColor; // Lighting emit m_LightEmission= InitMaterial.m_LightEmission; } // Destructor GLC_Material::~GLC_Material(void) { // clear whereUSED Hash table m_WhereUsed.clear(); if (NULL != m_pTexture) { delete m_pTexture; m_pTexture= NULL; } } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // Get Ambiant color QColor GLC_Material::getAmbientColor() const { return m_AmbientColor; } // Get diffuse color QColor GLC_Material::getDiffuseColor() const { return m_DiffuseColor; } // Get specular color QColor GLC_Material::getSpecularColor() const { return m_SpecularColor; } // Get the emissive color QColor GLC_Material::getLightEmission() const { return m_LightEmission; } // Get the texture File Name QString GLC_Material::getTextureFileName() const { if (m_pTexture != NULL) { return m_pTexture->getTextureFileName(); } else { return ""; } } // Get Texture Id GLuint GLC_Material::getTextureID() const { if (m_pTexture != NULL) { return m_pTexture->getTextureID(); } else { return 0; } } // return true if the texture is loaded bool GLC_Material::textureIsLoaded() const { if (m_pTexture != NULL) { return m_pTexture->isLoaded(); } else { return false; } } ////////////////////////////////////////////////////////////////////// // Set Functions ////////////////////////////////////////////////////////////////////// // Set Material properties void GLC_Material::setMaterial(const GLC_Material* pMat) { if (NULL != pMat->m_pTexture) { GLC_Texture* pTexture= new GLC_Texture(*(pMat->m_pTexture)); setTexture(pTexture); } // Ambient Color m_AmbientColor= pMat->m_AmbientColor; // Diffuse Color m_DiffuseColor= pMat->m_DiffuseColor; // Specular Color m_SpecularColor= pMat->m_SpecularColor; // Lighting emit m_LightEmission= pMat->m_LightEmission; m_fShininess= pMat->m_fShininess; updateUsed(); } // Set Ambiant Color void GLC_Material::setAmbientColor(const QColor& ambientColor) { m_AmbientColor= ambientColor; updateUsed(); } // Set Diffuse color void GLC_Material::setDiffuseColor(const QColor& diffuseColor) { m_DiffuseColor= diffuseColor; updateUsed(); } // Set Specular color void GLC_Material::setSpecularColor(const QColor& specularColor) { m_SpecularColor= specularColor; updateUsed(); } // Set Emissive void GLC_Material::setLightEmission(const QColor& lightEmission) { m_LightEmission= lightEmission; updateUsed(); } // Set Texture void GLC_Material::setTexture(GLC_Texture* pTexture) { qDebug() << "GLC_Material::SetTexture"; if (m_pTexture != NULL) { delete m_pTexture; m_pTexture= pTexture; glLoadTexture(); } else { // It is not sure that there is OpenGL context m_pTexture= pTexture; } updateUsed(); } // remove Material Texture void GLC_Material::removeTexture() { if (m_pTexture != NULL) { delete m_pTexture; m_pTexture= NULL; updateUsed(); } } // Add Geometry to where used hash table bool GLC_Material::addGLC_Geom(GLC_Geometry* pGeom) { CWhereUsed::iterator iGeom= m_WhereUsed.find(pGeom->getID()); if (iGeom == m_WhereUsed.end()) { // Ok, ID doesn't exist // Add Geometry to where used hash table m_WhereUsed.insert(pGeom->getID(), pGeom); return true; } else { // KO, ID exist qDebug("GLC_Material::AddGLC_Geom : Geometry not added"); return false; } } // Supprime une gomtrie de la collection bool GLC_Material::delGLC_Geom(GLC_uint Key) { CWhereUsed::iterator iGeom= m_WhereUsed.find(Key); if (iGeom != m_WhereUsed.end()) { // Ok, ID exist m_WhereUsed.remove(Key); // Remove container return true; } else { // KO doesn't exist qDebug("GLC_Material::DelGLC_Geom : Geometry not remove"); return false; } } ////////////////////////////////////////////////////////////////////// // OpenGL Functions ////////////////////////////////////////////////////////////////////// // Load the texture void GLC_Material::glLoadTexture(void) { if (m_pTexture != NULL) { m_pTexture->glLoadTexture(); } } // Execute OpenGL Material void GLC_Material::glExecute(GLenum Mode) { GLfloat pAmbientColor[4]= {getAmbientColor().redF(), getAmbientColor().greenF(), getAmbientColor().blueF(), getAmbientColor().alphaF()}; GLfloat pDiffuseColor[4]= {getDiffuseColor().redF(), getDiffuseColor().greenF(), getDiffuseColor().blueF(), getDiffuseColor().alphaF()}; GLfloat pSpecularColor[4]= {getSpecularColor().redF(), getSpecularColor().greenF(), getSpecularColor().blueF(), getSpecularColor().alphaF()}; GLfloat pLightEmission[4]= {getLightEmission().redF(), getLightEmission().greenF(), getLightEmission().blueF(), getLightEmission().alphaF()}; if (m_pTexture != NULL) { // for blend managing glBlendFunc(GL_SRC_ALPHA,GL_ONE); m_pTexture->glcBindTexture(); } glColor4fv(pAmbientColor); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, pAmbientColor); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, pDiffuseColor); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, pSpecularColor); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, pLightEmission); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &m_fShininess); // OpenGL Error handler GLenum errCode; if ((errCode= glGetError()) != GL_NO_ERROR) { const GLubyte* errString; errString = gluErrorString(errCode); qDebug("GLC_Material::GlExecute OpenGL Error %s", errString); } } ////////////////////////////////////////////////////////////////////// // Private servicies Functions ////////////////////////////////////////////////////////////////////// // Update geometries which used material void GLC_Material::updateUsed(void) { CWhereUsed::iterator iEntry= m_WhereUsed.begin(); while (iEntry != m_WhereUsed.constEnd()) { // Indique aux gomtrie utilisant la matire que celle ci change iEntry.value()->setMaterial(this); ++iEntry; } } // Init Ambiant Color void GLC_Material::initAmbientColor(void) { m_AmbientColor.setRgbF(0.8, 0.8, 0.8, 1.0); } // Init default color void GLC_Material::initOtherColor(void) { // Diffuse Color m_DiffuseColor.setRgbF(1.0, 1.0, 1.0, 1.0); // Specular Color m_SpecularColor.setRgbF(0.5, 0.5, 0.5, 1.0); // Lighting emit m_LightEmission.setRgbF(0.0, 0.0, 0.0, 1.0); } <commit_msg>Bug Fix in seMaterial method when assigning a material without texture to a material with texture.<commit_after>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2006 Laurent Ribon ([email protected]) Version 0.9.7, packaged on September, 2007. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_material.cpp implementation of the GLC_Material class. #include <QtDebug> #include <assert.h> #include "glc_material.h" #include "glc_collection.h" ////////////////////////////////////////////////////////////////////// // Constructor Destructor ////////////////////////////////////////////////////////////////////// GLC_Material::GLC_Material() :GLC_Object("Material") , m_fShininess(50.0) // By default shininess 50 , m_pTexture(NULL) // no texture { // Ambient Color initAmbientColor(); // Others initOtherColor(); } GLC_Material::GLC_Material(const QColor &ambientColor) :GLC_Object("Material") , m_fShininess(50.0) // default : shininess 50 , m_pTexture(NULL) // no texture { m_AmbientColor= ambientColor; // Others initOtherColor(); } GLC_Material::GLC_Material(const char *pName ,const GLfloat *pAmbientColor) :GLC_Object(pName) , m_fShininess(50.0) // default : shininess 50 , m_pTexture(NULL) // no texture { // Init Ambiant Color if (pAmbientColor != 0) { m_AmbientColor.setRgbF(static_cast<qreal>(pAmbientColor[0]), static_cast<qreal>(pAmbientColor[1]), static_cast<qreal>(pAmbientColor[2]), static_cast<qreal>(pAmbientColor[3])); } else { initAmbientColor(); } // Others initOtherColor(); } GLC_Material::GLC_Material(GLC_Texture* pTexture, const char *pName) :GLC_Object(pName) , m_fShininess(50.0) // By default shininess 50 , m_pTexture(pTexture) // Init texture { // Ambiente Color initAmbientColor(); // Others initOtherColor(); } // Copy constructor GLC_Material::GLC_Material(const GLC_Material &InitMaterial) :GLC_Object(InitMaterial.getName()) , m_fShininess(InitMaterial.m_fShininess) , m_pTexture(NULL) { if (NULL != InitMaterial.m_pTexture) { m_pTexture= new GLC_Texture(*(InitMaterial.m_pTexture)); assert(m_pTexture != NULL); } // Ambient Color m_AmbientColor= InitMaterial.m_AmbientColor; // Diffuse Color m_DiffuseColor= InitMaterial.m_DiffuseColor; // Specular Color m_SpecularColor= InitMaterial.m_SpecularColor; // Lighting emit m_LightEmission= InitMaterial.m_LightEmission; } // Destructor GLC_Material::~GLC_Material(void) { // clear whereUSED Hash table m_WhereUsed.clear(); if (NULL != m_pTexture) { delete m_pTexture; m_pTexture= NULL; } } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // Get Ambiant color QColor GLC_Material::getAmbientColor() const { return m_AmbientColor; } // Get diffuse color QColor GLC_Material::getDiffuseColor() const { return m_DiffuseColor; } // Get specular color QColor GLC_Material::getSpecularColor() const { return m_SpecularColor; } // Get the emissive color QColor GLC_Material::getLightEmission() const { return m_LightEmission; } // Get the texture File Name QString GLC_Material::getTextureFileName() const { if (m_pTexture != NULL) { return m_pTexture->getTextureFileName(); } else { return ""; } } // Get Texture Id GLuint GLC_Material::getTextureID() const { if (m_pTexture != NULL) { return m_pTexture->getTextureID(); } else { return 0; } } // return true if the texture is loaded bool GLC_Material::textureIsLoaded() const { if (m_pTexture != NULL) { return m_pTexture->isLoaded(); } else { return false; } } ////////////////////////////////////////////////////////////////////// // Set Functions ////////////////////////////////////////////////////////////////////// // Set Material properties void GLC_Material::setMaterial(const GLC_Material* pMat) { if (NULL != pMat->m_pTexture) { GLC_Texture* pTexture= new GLC_Texture(*(pMat->m_pTexture)); setTexture(pTexture); } else if (NULL != m_pTexture) { delete m_pTexture; m_pTexture= NULL; } // Ambient Color m_AmbientColor= pMat->m_AmbientColor; // Diffuse Color m_DiffuseColor= pMat->m_DiffuseColor; // Specular Color m_SpecularColor= pMat->m_SpecularColor; // Lighting emit m_LightEmission= pMat->m_LightEmission; m_fShininess= pMat->m_fShininess; updateUsed(); } // Set Ambiant Color void GLC_Material::setAmbientColor(const QColor& ambientColor) { m_AmbientColor= ambientColor; updateUsed(); } // Set Diffuse color void GLC_Material::setDiffuseColor(const QColor& diffuseColor) { m_DiffuseColor= diffuseColor; updateUsed(); } // Set Specular color void GLC_Material::setSpecularColor(const QColor& specularColor) { m_SpecularColor= specularColor; updateUsed(); } // Set Emissive void GLC_Material::setLightEmission(const QColor& lightEmission) { m_LightEmission= lightEmission; updateUsed(); } // Set Texture void GLC_Material::setTexture(GLC_Texture* pTexture) { qDebug() << "GLC_Material::SetTexture"; if (m_pTexture != NULL) { delete m_pTexture; m_pTexture= pTexture; glLoadTexture(); } else { // It is not sure that there is OpenGL context m_pTexture= pTexture; } updateUsed(); } // remove Material Texture void GLC_Material::removeTexture() { if (m_pTexture != NULL) { delete m_pTexture; m_pTexture= NULL; updateUsed(); } } // Add Geometry to where used hash table bool GLC_Material::addGLC_Geom(GLC_Geometry* pGeom) { CWhereUsed::iterator iGeom= m_WhereUsed.find(pGeom->getID()); if (iGeom == m_WhereUsed.end()) { // Ok, ID doesn't exist // Add Geometry to where used hash table m_WhereUsed.insert(pGeom->getID(), pGeom); return true; } else { // KO, ID exist qDebug("GLC_Material::AddGLC_Geom : Geometry not added"); return false; } } // Supprime une gomtrie de la collection bool GLC_Material::delGLC_Geom(GLC_uint Key) { CWhereUsed::iterator iGeom= m_WhereUsed.find(Key); if (iGeom != m_WhereUsed.end()) { // Ok, ID exist m_WhereUsed.remove(Key); // Remove container return true; } else { // KO doesn't exist qDebug("GLC_Material::DelGLC_Geom : Geometry not remove"); return false; } } ////////////////////////////////////////////////////////////////////// // OpenGL Functions ////////////////////////////////////////////////////////////////////// // Load the texture void GLC_Material::glLoadTexture(void) { if (m_pTexture != NULL) { m_pTexture->glLoadTexture(); } } // Execute OpenGL Material void GLC_Material::glExecute(GLenum Mode) { GLfloat pAmbientColor[4]= {getAmbientColor().redF(), getAmbientColor().greenF(), getAmbientColor().blueF(), getAmbientColor().alphaF()}; GLfloat pDiffuseColor[4]= {getDiffuseColor().redF(), getDiffuseColor().greenF(), getDiffuseColor().blueF(), getDiffuseColor().alphaF()}; GLfloat pSpecularColor[4]= {getSpecularColor().redF(), getSpecularColor().greenF(), getSpecularColor().blueF(), getSpecularColor().alphaF()}; GLfloat pLightEmission[4]= {getLightEmission().redF(), getLightEmission().greenF(), getLightEmission().blueF(), getLightEmission().alphaF()}; if (m_pTexture != NULL) { // for blend managing glBlendFunc(GL_SRC_ALPHA,GL_ONE); m_pTexture->glcBindTexture(); } glColor4fv(pAmbientColor); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, pAmbientColor); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, pDiffuseColor); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, pSpecularColor); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, pLightEmission); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &m_fShininess); // OpenGL Error handler GLenum errCode; if ((errCode= glGetError()) != GL_NO_ERROR) { const GLubyte* errString; errString = gluErrorString(errCode); qDebug("GLC_Material::GlExecute OpenGL Error %s", errString); } } ////////////////////////////////////////////////////////////////////// // Private servicies Functions ////////////////////////////////////////////////////////////////////// // Update geometries which used material void GLC_Material::updateUsed(void) { CWhereUsed::iterator iEntry= m_WhereUsed.begin(); while (iEntry != m_WhereUsed.constEnd()) { // Indique aux gomtrie utilisant la matire que celle ci change iEntry.value()->setMaterial(this); ++iEntry; } } // Init Ambiant Color void GLC_Material::initAmbientColor(void) { m_AmbientColor.setRgbF(0.8, 0.8, 0.8, 1.0); } // Init default color void GLC_Material::initOtherColor(void) { // Diffuse Color m_DiffuseColor.setRgbF(1.0, 1.0, 1.0, 1.0); // Specular Color m_SpecularColor.setRgbF(0.5, 0.5, 0.5, 1.0); // Lighting emit m_LightEmission.setRgbF(0.0, 0.0, 0.0, 1.0); } <|endoftext|>
<commit_before>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2021 Steven Noonan. * Licensed under the New BSD License. * */ #include <crisscross/universal_include.h> #include <crisscross/debug.h> #include <crisscross/filewriter.h> #include <crisscross/nasty_cast.h> #include <cstdio> #include <cstring> #if defined (TARGET_OS_LINUX) || defined (TARGET_OS_MACOSX) || defined (TARGET_OS_FREEBSD) || defined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD) #if !defined(TARGET_COMPILER_CLANG) #include <cxxabi.h> #else namespace __cxxabiv1 { extern "C" { char* __cxa_demangle(const char* __mangled_name, char* __output_buffer, size_t* __length, int* __status); } } namespace abi = __cxxabiv1; #endif #if defined(TARGET_OS_LINUX) && !defined(TARGET_COMPILER_CYGWIN) #include <execinfo.h> #endif #endif using namespace CrissCross::IO; #ifdef TARGET_OS_MACOSX #include <dlfcn.h> typedef int (*backtrace_t)(void * *, int); typedef char **(*backtrace_symbols_t)(void * const *, int); #endif #ifndef ENABLE_SYMBOL_ENGINE #ifdef TARGET_COMPILER_VC #pragma warning (disable: 4311) #endif #else #include <windows.h> #include <dbghelp.h> #pragma warning (disable: 4312) #pragma comment( lib, "dbghelp" ) class SymbolEngine { public: static SymbolEngine & instance(); #if TARGET_CPU_BITS == 32 std::string addressToString(DWORD address); #else std::string addressToString(DWORD64 address); #endif void StackTrace(PCONTEXT _pContext, CoreIOWriter * _outputBuffer); private: SymbolEngine(SymbolEngine const &); SymbolEngine & operator=(SymbolEngine const &); SymbolEngine(); HANDLE hProcess; public: ~SymbolEngine(); private: }; SymbolEngine & SymbolEngine::instance() { static SymbolEngine theEngine; return theEngine; } SymbolEngine::SymbolEngine() { hProcess = GetCurrentProcess(); DWORD dwOpts = SymGetOptions(); dwOpts |= SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS; SymSetOptions(dwOpts); ::SymInitialize(hProcess, 0, true); } SymbolEngine::~SymbolEngine() { ::SymCleanup(hProcess); } #if TARGET_CPU_BITS == 32 std::string SymbolEngine::addressToString(DWORD address) #elif TARGET_CPU_BITS == 64 std::string SymbolEngine::addressToString(DWORD64 address) #endif { char buffer[4096]; #if TARGET_CPU_BITS == 32 const char *format = "0x%08x"; #elif TARGET_CPU_BITS == 64 const char *format = "0x%016x"; #endif /* First the raw address */ sprintf(buffer, format, address); /* Then any name for the symbol */ struct tagSymInfo { IMAGEHLP_SYMBOL symInfo; char nameBuffer[4 * 256]; } SymInfo = { { sizeof(IMAGEHLP_SYMBOL) } }; IMAGEHLP_SYMBOL * pSym = &SymInfo.symInfo; pSym->MaxNameLength = sizeof(SymInfo) - offsetof(tagSymInfo, symInfo.Name); #if TARGET_CPU_BITS == 32 DWORD #elif TARGET_CPU_BITS == 64 DWORD64 #endif dwDisplacement; if (SymGetSymFromAddr(GetCurrentProcess(), address, &dwDisplacement, pSym)) { strcat(buffer, " "); strcat(buffer, pSym->Name); /*if ( dwDisplacement != 0 ) * oss << "+0x" << std::hex << dwDisplacement << std::dec; */ } /* Finally any file/line number */ IMAGEHLP_LINE lineInfo = { sizeof(IMAGEHLP_LINE) }; if (SymGetLineFromAddr(GetCurrentProcess(), (DWORD)address, (PDWORD)&dwDisplacement, &lineInfo)) { const char *pDelim = strrchr(lineInfo.FileName, '\\'); char temp[1024]; sprintf(temp, " at %s(%u)", (pDelim ? pDelim + 1 : lineInfo.FileName), lineInfo.LineNumber); strcat(buffer, temp); } return std::string(buffer); } void SymbolEngine::StackTrace(PCONTEXT _pContext, CoreIOWriter * _outputBuffer) { #if TARGET_CPU_BITS == 32 _outputBuffer->WriteLine(" Frame Address Code"); #else _outputBuffer->WriteLine(" Frame Address Code"); #endif STACKFRAME64 stackFrame = { 0 }; #if defined(TARGET_CPU_X86) stackFrame.AddrPC.Offset = _pContext->Eip; stackFrame.AddrStack.Offset = _pContext->Esp; stackFrame.AddrFrame.Offset = _pContext->Ebp; #elif defined(TARGET_CPU_X64) stackFrame.AddrPC.Offset = _pContext->Rip; stackFrame.AddrStack.Offset = _pContext->Rsp; stackFrame.AddrFrame.Offset = _pContext->Rbp; #elif defined(TARGET_CPU_ARM) && TARGET_CPU_BITS == 32 stackFrame.AddrPC.Offset = _pContext->Pc; stackFrame.AddrStack.Offset = _pContext->Sp; stackFrame.AddrFrame.Offset = _pContext->R11; #elif defined(TARGET_CPU_ARM) && TARGET_CPU_BITS == 64 stackFrame.AddrPC.Offset = _pContext->Pc; stackFrame.AddrStack.Offset = _pContext->Sp; stackFrame.AddrFrame.Offset = _pContext->Fp; #endif stackFrame.AddrPC.Mode = AddrModeFlat; stackFrame.AddrFrame.Mode = AddrModeFlat; stackFrame.AddrStack.Mode = AddrModeFlat; #ifdef TARGET_CPU_X86 DWORD machine = IMAGE_FILE_MACHINE_I386; #elif defined(TARGET_CPU_X64) DWORD machine = IMAGE_FILE_MACHINE_AMD64; #elif defined(TARGET_CPU_ARM) && TARGET_CPU_BITS == 32 DWORD machine = IMAGE_FILE_MACHINE_ARM; #elif defined(TARGET_CPU_ARM) && TARGET_CPU_BITS == 64 DWORD machine = IMAGE_FILE_MACHINE_ARM64; #endif #if TARGET_CPU_BITS == 32 const char *format = " 0x%08x %s"; #elif TARGET_CPU_BITS == 64 const char *format = " 0x%016x %s"; #endif while (::StackWalk(machine, hProcess, GetCurrentThread(), /* this value doesn't matter much if previous one is a real handle */ &stackFrame, _pContext, NULL, ::SymFunctionTableAccess, ::SymGetModuleBase, NULL)) { _outputBuffer->WriteLine(format, stackFrame.AddrFrame.Offset, addressToString(stackFrame.AddrPC. Offset).c_str()); } } #endif void CrissCross::Debug::PrintStackTrace(CrissCross::IO::CoreIOWriter * _outputBuffer) { #if !defined (TARGET_OS_NETBSD) && !defined (TARGET_OS_FREEBSD) && !defined (TARGET_OS_OPENBSD) \ && !defined(TARGET_COMPILER_MINGW) && !defined(TARGET_COMPILER_CYGWIN) && !defined(TARGET_OS_HAIKU) #ifdef ENABLE_SYMBOL_ENGINE CONTEXT context = { CONTEXT_ALL }; BOOL ret = ::GetThreadContext(GetCurrentThread(), &context); CoreAssert(ret != FALSE); RtlCaptureContext(&context); SymbolEngine::instance().StackTrace(&context, _outputBuffer); #elif defined (ENABLE_BACKTRACE) #if defined (TARGET_OS_MACOSX) backtrace_t backtrace; backtrace_symbols_t backtrace_symbols; backtrace = nasty_cast<backtrace_t, void*>(dlsym(RTLD_DEFAULT, "backtrace")); backtrace_symbols = nasty_cast<backtrace_symbols_t, void*>(dlsym(RTLD_DEFAULT, "backtrace_symbols")); #endif void *array[256]; int size; char * *strings; int i; memset(array, 0, sizeof(void *) * 256); /* use -rdynamic flag when compiling */ size = backtrace(array, 256); strings = backtrace_symbols(array, size); _outputBuffer->WriteLine("Obtained %d stack frames.", size); std::string bt = ""; for (i = 0; i < size; i++) { #if defined (TARGET_OS_LINUX) int status; /* extract the identifier from strings[i]. It's inside of parens. */ char *identifier = ::strchr(strings[i], '('); char *identifier_end = ::strchr(strings[i], '+'); char *address = ::strchr(strings[i], '['); bt += address; if (identifier != 0 && identifier_end != 0 && identifier < identifier_end) { bt += " "; *identifier_end = '\0'; char * realname = abi::__cxa_demangle(identifier + 1, 0, 0, &status); if (realname != NULL) { bt += realname; } else { bt += (identifier + 1); } char *off_end = ::strchr(identifier_end + 1, ')'); if (off_end) { *off_end = 0; bt += " + "; bt += (identifier_end + 1); } free(realname); } #elif defined (TARGET_OS_MACOSX) char *addr = ::strstr(strings[i], "0x"); char *mangled = ::strchr(addr, ' ') + 1; char *offset = ::strchr(addr, '+'); char *postmangle = ::strchr(mangled, ' '); if (mangled) *(mangled - 1) = 0; bt += addr; int status; bt += ": "; if (addr && mangled) { if (postmangle) *postmangle = '\0'; char *realname = abi::__cxa_demangle(mangled, 0, 0, &status); if (realname) { bt += realname; } else { bt += mangled; } bt += " "; bt += offset; free(realname); } #endif bt += "\n"; } _outputBuffer->WriteLine("%s\n", bt.c_str()); free(strings); #else /* defined(ENABLE_SYMBOL_ENGINE) || defined(ENABLE_BACKTRACE) */ _outputBuffer->WriteLine("FAIL: backtrace() function not available."); #endif #else /* !defined (TARGET_OS_NETBSD) && !defined (TARGET_OS_FREEBSD) && !defined (TARGET_OS_OPENBSD) */ _outputBuffer->WriteLine("Stack traces are not implemented for this platform."); #endif } #ifndef USE_FAST_ASSERT void Assert(bool _condition, const char *_testcase, const char *_file, int _line) { if (!_condition) { char buffer[10240]; sprintf(buffer, "Assertion failed : '%s'\nFile: %s\nLine: %d\n\n", _testcase, _file, _line); fprintf(stderr, "%s", buffer); fprintf(stderr, "=== STACK TRACE ===\n"); CoreIOWriter *stderror = new CoreIOWriter(stderr, false, CC_LN_LF); PrintStackTrace(stderror); delete stderror; #ifndef _DEBUG abort(); #else _ASSERT(_condition); #endif } } #endif <commit_msg>debug.cpp: unbreak Win32 build<commit_after>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2021 Steven Noonan. * Licensed under the New BSD License. * */ #include <crisscross/universal_include.h> #include <crisscross/debug.h> #include <crisscross/filewriter.h> #include <crisscross/nasty_cast.h> #include <cstdio> #include <cstring> #if defined (TARGET_OS_LINUX) || defined (TARGET_OS_MACOSX) || defined (TARGET_OS_FREEBSD) || defined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD) #if !defined(TARGET_COMPILER_CLANG) #include <cxxabi.h> #else namespace __cxxabiv1 { extern "C" { char* __cxa_demangle(const char* __mangled_name, char* __output_buffer, size_t* __length, int* __status); } } namespace abi = __cxxabiv1; #endif #if defined(TARGET_OS_LINUX) && !defined(TARGET_COMPILER_CYGWIN) #include <execinfo.h> #endif #endif using namespace CrissCross::IO; #ifdef TARGET_OS_MACOSX #include <dlfcn.h> typedef int (*backtrace_t)(void * *, int); typedef char **(*backtrace_symbols_t)(void * const *, int); #endif #ifndef ENABLE_SYMBOL_ENGINE #ifdef TARGET_COMPILER_VC #pragma warning (disable: 4311) #endif #else #include <windows.h> #include <dbghelp.h> #pragma warning (disable: 4312) #pragma comment( lib, "dbghelp" ) class SymbolEngine { public: static SymbolEngine & instance(); #if TARGET_CPU_BITS == 32 std::string addressToString(DWORD address); #else std::string addressToString(DWORD64 address); #endif void StackTrace(PCONTEXT _pContext, CoreIOWriter * _outputBuffer); private: SymbolEngine(SymbolEngine const &); SymbolEngine & operator=(SymbolEngine const &); SymbolEngine(); HANDLE hProcess; public: ~SymbolEngine(); private: }; SymbolEngine & SymbolEngine::instance() { static SymbolEngine theEngine; return theEngine; } SymbolEngine::SymbolEngine() { hProcess = GetCurrentProcess(); DWORD dwOpts = SymGetOptions(); dwOpts |= SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS; SymSetOptions(dwOpts); ::SymInitialize(hProcess, 0, true); } SymbolEngine::~SymbolEngine() { ::SymCleanup(hProcess); } #if TARGET_CPU_BITS == 32 std::string SymbolEngine::addressToString(DWORD address) #elif TARGET_CPU_BITS == 64 std::string SymbolEngine::addressToString(DWORD64 address) #endif { char buffer[4096]; #if TARGET_CPU_BITS == 32 const char *format = "0x%08x"; #elif TARGET_CPU_BITS == 64 const char *format = "0x%016x"; #endif /* First the raw address */ sprintf(buffer, format, address); /* Then any name for the symbol */ struct tagSymInfo { IMAGEHLP_SYMBOL symInfo; char nameBuffer[4 * 256]; } SymInfo = { { sizeof(IMAGEHLP_SYMBOL) } }; IMAGEHLP_SYMBOL * pSym = &SymInfo.symInfo; pSym->MaxNameLength = sizeof(SymInfo) - offsetof(tagSymInfo, symInfo.Name); #if TARGET_CPU_BITS == 32 DWORD #elif TARGET_CPU_BITS == 64 DWORD64 #endif dwDisplacement; if (SymGetSymFromAddr(GetCurrentProcess(), address, &dwDisplacement, pSym)) { strcat(buffer, " "); strcat(buffer, pSym->Name); /*if ( dwDisplacement != 0 ) * oss << "+0x" << std::hex << dwDisplacement << std::dec; */ } /* Finally any file/line number */ IMAGEHLP_LINE lineInfo = { sizeof(IMAGEHLP_LINE) }; if (SymGetLineFromAddr(GetCurrentProcess(), (DWORD)address, (PDWORD)&dwDisplacement, &lineInfo)) { const char *pDelim = strrchr(lineInfo.FileName, '\\'); char temp[1024]; sprintf(temp, " at %s(%u)", (pDelim ? pDelim + 1 : lineInfo.FileName), lineInfo.LineNumber); strcat(buffer, temp); } return std::string(buffer); } void SymbolEngine::StackTrace(PCONTEXT _pContext, CoreIOWriter * _outputBuffer) { #if TARGET_CPU_BITS == 32 _outputBuffer->WriteLine(" Frame Address Code"); #else _outputBuffer->WriteLine(" Frame Address Code"); #endif #if TARGET_CPU_BITS == 32 STACKFRAME stackFrame = { 0 }; #else STACKFRAME64 stackFrame = { 0 }; #endif #if defined(TARGET_CPU_X86) stackFrame.AddrPC.Offset = _pContext->Eip; stackFrame.AddrStack.Offset = _pContext->Esp; stackFrame.AddrFrame.Offset = _pContext->Ebp; #elif defined(TARGET_CPU_X64) stackFrame.AddrPC.Offset = _pContext->Rip; stackFrame.AddrStack.Offset = _pContext->Rsp; stackFrame.AddrFrame.Offset = _pContext->Rbp; #elif defined(TARGET_CPU_ARM) && TARGET_CPU_BITS == 32 stackFrame.AddrPC.Offset = _pContext->Pc; stackFrame.AddrStack.Offset = _pContext->Sp; stackFrame.AddrFrame.Offset = _pContext->R11; #elif defined(TARGET_CPU_ARM) && TARGET_CPU_BITS == 64 stackFrame.AddrPC.Offset = _pContext->Pc; stackFrame.AddrStack.Offset = _pContext->Sp; stackFrame.AddrFrame.Offset = _pContext->Fp; #endif stackFrame.AddrPC.Mode = AddrModeFlat; stackFrame.AddrFrame.Mode = AddrModeFlat; stackFrame.AddrStack.Mode = AddrModeFlat; #ifdef TARGET_CPU_X86 DWORD machine = IMAGE_FILE_MACHINE_I386; #elif defined(TARGET_CPU_X64) DWORD machine = IMAGE_FILE_MACHINE_AMD64; #elif defined(TARGET_CPU_ARM) && TARGET_CPU_BITS == 32 DWORD machine = IMAGE_FILE_MACHINE_ARM; #elif defined(TARGET_CPU_ARM) && TARGET_CPU_BITS == 64 DWORD machine = IMAGE_FILE_MACHINE_ARM64; #endif #if TARGET_CPU_BITS == 32 const char *format = " 0x%08x %s"; #elif TARGET_CPU_BITS == 64 const char *format = " 0x%016x %s"; #endif while (::StackWalk(machine, hProcess, GetCurrentThread(), /* this value doesn't matter much if previous one is a real handle */ &stackFrame, _pContext, NULL, ::SymFunctionTableAccess, ::SymGetModuleBase, NULL)) { _outputBuffer->WriteLine(format, stackFrame.AddrFrame.Offset, addressToString(stackFrame.AddrPC. Offset).c_str()); } } #endif void CrissCross::Debug::PrintStackTrace(CrissCross::IO::CoreIOWriter * _outputBuffer) { #if !defined (TARGET_OS_NETBSD) && !defined (TARGET_OS_FREEBSD) && !defined (TARGET_OS_OPENBSD) \ && !defined(TARGET_COMPILER_MINGW) && !defined(TARGET_COMPILER_CYGWIN) && !defined(TARGET_OS_HAIKU) #ifdef ENABLE_SYMBOL_ENGINE CONTEXT context = { CONTEXT_ALL }; BOOL ret = ::GetThreadContext(GetCurrentThread(), &context); CoreAssert(ret != FALSE); RtlCaptureContext(&context); SymbolEngine::instance().StackTrace(&context, _outputBuffer); #elif defined (ENABLE_BACKTRACE) #if defined (TARGET_OS_MACOSX) backtrace_t backtrace; backtrace_symbols_t backtrace_symbols; backtrace = nasty_cast<backtrace_t, void*>(dlsym(RTLD_DEFAULT, "backtrace")); backtrace_symbols = nasty_cast<backtrace_symbols_t, void*>(dlsym(RTLD_DEFAULT, "backtrace_symbols")); #endif void *array[256]; int size; char * *strings; int i; memset(array, 0, sizeof(void *) * 256); /* use -rdynamic flag when compiling */ size = backtrace(array, 256); strings = backtrace_symbols(array, size); _outputBuffer->WriteLine("Obtained %d stack frames.", size); std::string bt = ""; for (i = 0; i < size; i++) { #if defined (TARGET_OS_LINUX) int status; /* extract the identifier from strings[i]. It's inside of parens. */ char *identifier = ::strchr(strings[i], '('); char *identifier_end = ::strchr(strings[i], '+'); char *address = ::strchr(strings[i], '['); bt += address; if (identifier != 0 && identifier_end != 0 && identifier < identifier_end) { bt += " "; *identifier_end = '\0'; char * realname = abi::__cxa_demangle(identifier + 1, 0, 0, &status); if (realname != NULL) { bt += realname; } else { bt += (identifier + 1); } char *off_end = ::strchr(identifier_end + 1, ')'); if (off_end) { *off_end = 0; bt += " + "; bt += (identifier_end + 1); } free(realname); } #elif defined (TARGET_OS_MACOSX) char *addr = ::strstr(strings[i], "0x"); char *mangled = ::strchr(addr, ' ') + 1; char *offset = ::strchr(addr, '+'); char *postmangle = ::strchr(mangled, ' '); if (mangled) *(mangled - 1) = 0; bt += addr; int status; bt += ": "; if (addr && mangled) { if (postmangle) *postmangle = '\0'; char *realname = abi::__cxa_demangle(mangled, 0, 0, &status); if (realname) { bt += realname; } else { bt += mangled; } bt += " "; bt += offset; free(realname); } #endif bt += "\n"; } _outputBuffer->WriteLine("%s\n", bt.c_str()); free(strings); #else /* defined(ENABLE_SYMBOL_ENGINE) || defined(ENABLE_BACKTRACE) */ _outputBuffer->WriteLine("FAIL: backtrace() function not available."); #endif #else /* !defined (TARGET_OS_NETBSD) && !defined (TARGET_OS_FREEBSD) && !defined (TARGET_OS_OPENBSD) */ _outputBuffer->WriteLine("Stack traces are not implemented for this platform."); #endif } #ifndef USE_FAST_ASSERT void Assert(bool _condition, const char *_testcase, const char *_file, int _line) { if (!_condition) { char buffer[10240]; sprintf(buffer, "Assertion failed : '%s'\nFile: %s\nLine: %d\n\n", _testcase, _file, _line); fprintf(stderr, "%s", buffer); fprintf(stderr, "=== STACK TRACE ===\n"); CoreIOWriter *stderror = new CoreIOWriter(stderr, false, CC_LN_LF); PrintStackTrace(stderror); delete stderror; #ifndef _DEBUG abort(); #else _ASSERT(_condition); #endif } } #endif <|endoftext|>
<commit_before>#include "manip.h" #include <cmath> #include "gd.h" #include "../image/image.h" #include <iostream> namespace manip { namespace { // 大津の手法による閾値の計算 int otsu_threshold(const double average, const int histgram[256]) { double max = 0.; int max_no = 0; for(int i = 0; i < 256; ++i) { long count1 = 0, count2 = 0; long long data = 0; double breakup1 = 0., breakup2 = 0.; double average1 = 0., average2 = 0.; for(int j = 0; j < i; ++j) { count1 += histgram[j]; data += histgram[j] * j; } if(count1 > 0) { average1 = (double)data / (double)count1; for(int j = 0; j < i; ++j) { breakup1 += pow(j - average1, 2) * histgram[j]; } breakup1 /= (double)count1; } data = 0; for(int j = i; j < 256; ++j) { count2 += histgram[j]; data += histgram[j] * j; } if(count2 > 0) { average2 = (double)data / (double)count2; for(int j = i; j < 256; ++j) { breakup2 += pow(j - average2, 2) * histgram[j]; } breakup2 /= (double)count2; } const double class1 = (double)count1 * breakup1 + (double)count2 * breakup2; const double class2 = (double)count1 * pow(average1 - average, 2) + (double)count2 * pow(average2 - average, 2); const double tmp = class2 / class1; if(max < tmp) { max = tmp; max_no = i; } } return max_no; } } bool grayscale(gd &img) { img.convert_to_true_color(); img.alpha_blending(false); const int width = img.width(); const int height = img.height(); for(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) { const gd::color color = img.pixel_fast(x, y); const int r = (color & 0xff0000) >> 16; const int g = (color & 0x00ff00) >> 8; const int b = (color & 0x0000ff); const int a = (color & 0x7f000000); // そのまま使うのでビットシフトしない const int gray = (77 * r + 150 * g + 29 * b + 128) / 256; // 0.298912 * r + 0.586611 * g + 0.114478 * b + 0.5 img.pixel_fast(x, y, a | (gray * 0x010101)); } } return true; } bool colorize(gd &img, int red, int green, int blue, int alpha) { img.convert_to_true_color(); img.alpha_blending(false); const int width = img.width(); const int height = img.height(); for(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) { const gd::color color = img.pixel_fast(x, y); const int r = ((color & 0xff0000) >> 16) + red; const int g = ((color & 0x00ff00) >> 8) + green; const int b = (color & 0x0000ff) + blue; const int a = ((color & 0x7f000000) >> 24) + alpha; const int new_color = ((a < 0 ? 0 : a > 127 ? 127 : a) << 24) | ((r < 0 ? 0 : r > 255 ? 255 : r) << 16) | ((g < 0 ? 0 : g > 255 ? 255 : g) << 8) | (b < 0 ? 0 : b > 255 ? 255 : b); img.pixel_fast(x, y, new_color); } } return true; } bool binarize(gd &img, bool is_grayscaled) { img.convert_to_true_color(); img.alpha_blending(false); int hist_r[256] = {}; int hist_g[256] = {}; int hist_b[256] = {}; long total_r = 0; long total_g = 0; long total_b = 0; int pixel_count = 0; const int width = img.width(); const int height = img.height(); // ヒストグラムを取得 for(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) { const gd::color color = img.pixel_fast(x, y); const int a = (color & 0x7f000000) >> 24; if(a == 0x7f) { // 完全透明なのでスキップ continue; } ++pixel_count; const int r = (color & 0xff0000) >> 16; ++hist_r[r]; total_r += r; if(!is_grayscaled) { const int g = (color & 0x00ff00) >> 8; ++hist_g[g]; total_g += g; const int b = (color & 0x0000ff); ++hist_b[b]; total_b += b; } } } // 完全に透明な画像だったわ if(pixel_count < 1) { return true; } // 大津の手法により閾値を計算 const int otsu_threshold_r = otsu_threshold((double)total_r / (double)pixel_count, hist_r); const int otsu_threshold_g = is_grayscaled ? otsu_threshold_r : otsu_threshold((double)total_g / (double)pixel_count, hist_g); const int otsu_threshold_b = is_grayscaled ? otsu_threshold_r : otsu_threshold((double)total_b / (double)pixel_count, hist_b); for(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) { const gd::color color = img.pixel_fast(x, y); const int a = (color & 0x7f000000); const int r = ((color & 0x00ff0000) >> 16) <= otsu_threshold_r ? 0x00 : 0xff; const int g = ((color & 0x0000ff00) >> 8) <= otsu_threshold_g ? 0x00 : 0xff; const int b = ((color & 0x000000ff)) <= otsu_threshold_b ? 0x00 : 0xff; img.pixel_fast(x, y, a | (r << 16) | (g << 8) | b); } } return true; } } <commit_msg>iostream<commit_after>#include "manip.h" #include <cmath> #include "gd.h" #include "../image/image.h" namespace manip { namespace { // 大津の手法による閾値の計算 int otsu_threshold(const double average, const int histgram[256]) { double max = 0.; int max_no = 0; for(int i = 0; i < 256; ++i) { long count1 = 0, count2 = 0; long long data = 0; double breakup1 = 0., breakup2 = 0.; double average1 = 0., average2 = 0.; for(int j = 0; j < i; ++j) { count1 += histgram[j]; data += histgram[j] * j; } if(count1 > 0) { average1 = (double)data / (double)count1; for(int j = 0; j < i; ++j) { breakup1 += pow(j - average1, 2) * histgram[j]; } breakup1 /= (double)count1; } data = 0; for(int j = i; j < 256; ++j) { count2 += histgram[j]; data += histgram[j] * j; } if(count2 > 0) { average2 = (double)data / (double)count2; for(int j = i; j < 256; ++j) { breakup2 += pow(j - average2, 2) * histgram[j]; } breakup2 /= (double)count2; } const double class1 = (double)count1 * breakup1 + (double)count2 * breakup2; const double class2 = (double)count1 * pow(average1 - average, 2) + (double)count2 * pow(average2 - average, 2); const double tmp = class2 / class1; if(max < tmp) { max = tmp; max_no = i; } } return max_no; } } bool grayscale(gd &img) { img.convert_to_true_color(); img.alpha_blending(false); const int width = img.width(); const int height = img.height(); for(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) { const gd::color color = img.pixel_fast(x, y); const int r = (color & 0xff0000) >> 16; const int g = (color & 0x00ff00) >> 8; const int b = (color & 0x0000ff); const int a = (color & 0x7f000000); // そのまま使うのでビットシフトしない const int gray = (77 * r + 150 * g + 29 * b + 128) / 256; // 0.298912 * r + 0.586611 * g + 0.114478 * b + 0.5 img.pixel_fast(x, y, a | (gray * 0x010101)); } } return true; } bool colorize(gd &img, int red, int green, int blue, int alpha) { img.convert_to_true_color(); img.alpha_blending(false); const int width = img.width(); const int height = img.height(); for(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) { const gd::color color = img.pixel_fast(x, y); const int r = ((color & 0xff0000) >> 16) + red; const int g = ((color & 0x00ff00) >> 8) + green; const int b = (color & 0x0000ff) + blue; const int a = ((color & 0x7f000000) >> 24) + alpha; const int new_color = ((a < 0 ? 0 : a > 127 ? 127 : a) << 24) | ((r < 0 ? 0 : r > 255 ? 255 : r) << 16) | ((g < 0 ? 0 : g > 255 ? 255 : g) << 8) | (b < 0 ? 0 : b > 255 ? 255 : b); img.pixel_fast(x, y, new_color); } } return true; } bool binarize(gd &img, bool is_grayscaled) { img.convert_to_true_color(); img.alpha_blending(false); int hist_r[256] = {}; int hist_g[256] = {}; int hist_b[256] = {}; long total_r = 0; long total_g = 0; long total_b = 0; int pixel_count = 0; const int width = img.width(); const int height = img.height(); // ヒストグラムを取得 for(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) { const gd::color color = img.pixel_fast(x, y); const int a = (color & 0x7f000000) >> 24; if(a == 0x7f) { // 完全透明なのでスキップ continue; } ++pixel_count; const int r = (color & 0xff0000) >> 16; ++hist_r[r]; total_r += r; if(!is_grayscaled) { const int g = (color & 0x00ff00) >> 8; ++hist_g[g]; total_g += g; const int b = (color & 0x0000ff); ++hist_b[b]; total_b += b; } } } // 完全に透明な画像だったわ if(pixel_count < 1) { return true; } // 大津の手法により閾値を計算 const int otsu_threshold_r = otsu_threshold((double)total_r / (double)pixel_count, hist_r); const int otsu_threshold_g = is_grayscaled ? otsu_threshold_r : otsu_threshold((double)total_g / (double)pixel_count, hist_g); const int otsu_threshold_b = is_grayscaled ? otsu_threshold_r : otsu_threshold((double)total_b / (double)pixel_count, hist_b); for(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) { const gd::color color = img.pixel_fast(x, y); const int a = (color & 0x7f000000); const int r = ((color & 0x00ff0000) >> 16) <= otsu_threshold_r ? 0x00 : 0xff; const int g = ((color & 0x0000ff00) >> 8) <= otsu_threshold_g ? 0x00 : 0xff; const int b = ((color & 0x000000ff)) <= otsu_threshold_b ? 0x00 : 0xff; img.pixel_fast(x, y, a | (r << 16) | (g << 8) | b); } } return true; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2020-present ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "mutation_reader.hh" #include <seastar/core/gate.hh> class test_reader_lifecycle_policy : public reader_lifecycle_policy , public enable_shared_from_this<test_reader_lifecycle_policy> { using factory_function = std::function<flat_mutation_reader( schema_ptr, const dht::partition_range&, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, mutation_reader::forwarding)>; struct reader_context { std::optional<reader_concurrency_semaphore> semaphore; std::optional<const dht::partition_range> range; std::optional<const query::partition_slice> slice; reader_context() = default; reader_context(dht::partition_range range, query::partition_slice slice) : range(std::move(range)), slice(std::move(slice)) { } }; factory_function _factory_function; std::vector<foreign_ptr<std::unique_ptr<reader_context>>> _contexts; std::vector<future<>> _destroy_futures; bool _evict_paused_readers = false; public: explicit test_reader_lifecycle_policy(factory_function f, bool evict_paused_readers = false) : _factory_function(std::move(f)) , _contexts(smp::count) , _evict_paused_readers(evict_paused_readers) { } virtual flat_mutation_reader create_reader( schema_ptr schema, reader_permit, const dht::partition_range& range, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, mutation_reader::forwarding fwd_mr) override { const auto shard = this_shard_id(); if (_contexts[shard]) { _contexts[shard]->range.emplace(range); _contexts[shard]->slice.emplace(slice); } else { _contexts[shard] = make_foreign(std::make_unique<reader_context>(range, slice)); } return _factory_function(std::move(schema), *_contexts[shard]->range, *_contexts[shard]->slice, pc, std::move(trace_state), fwd_mr); } virtual future<> destroy_reader(stopped_reader reader) noexcept override { auto ctx = &*_contexts[this_shard_id()]; auto reader_opt = ctx->semaphore->unregister_inactive_read(std::move(reader.handle)); auto ret = reader_opt ? reader_opt->close() : make_ready_future<>(); return ret.finally([&ctx] { return ctx->semaphore->stop(); }); } virtual reader_concurrency_semaphore& semaphore() override { const auto shard = this_shard_id(); if (!_contexts[shard]) { _contexts[shard] = make_foreign(std::make_unique<reader_context>()); } else if (_contexts[shard]->semaphore) { return *_contexts[shard]->semaphore; } if (_evict_paused_readers) { // Create with no memory, so all inactive reads are immediately evicted. _contexts[shard]->semaphore.emplace(1, 0, format("reader_concurrency_semaphore @shard_id={}", shard)); } else { _contexts[shard]->semaphore.emplace(reader_concurrency_semaphore::no_limits{}); } return *_contexts[shard]->semaphore; } }; <commit_msg>test/lib/reader_lifecycle_policy: destroy_reader: cleanup context<commit_after>/* * Copyright (C) 2020-present ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "mutation_reader.hh" #include <seastar/core/gate.hh> class test_reader_lifecycle_policy : public reader_lifecycle_policy , public enable_shared_from_this<test_reader_lifecycle_policy> { using factory_function = std::function<flat_mutation_reader( schema_ptr, const dht::partition_range&, const query::partition_slice&, const io_priority_class&, tracing::trace_state_ptr, mutation_reader::forwarding)>; struct reader_context { std::optional<reader_concurrency_semaphore> semaphore; std::optional<const dht::partition_range> range; std::optional<const query::partition_slice> slice; reader_context() = default; reader_context(dht::partition_range range, query::partition_slice slice) : range(std::move(range)), slice(std::move(slice)) { } }; factory_function _factory_function; std::vector<foreign_ptr<std::unique_ptr<reader_context>>> _contexts; std::vector<future<>> _destroy_futures; bool _evict_paused_readers = false; public: explicit test_reader_lifecycle_policy(factory_function f, bool evict_paused_readers = false) : _factory_function(std::move(f)) , _contexts(smp::count) , _evict_paused_readers(evict_paused_readers) { } virtual flat_mutation_reader create_reader( schema_ptr schema, reader_permit, const dht::partition_range& range, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, mutation_reader::forwarding fwd_mr) override { const auto shard = this_shard_id(); if (_contexts[shard]) { _contexts[shard]->range.emplace(range); _contexts[shard]->slice.emplace(slice); } else { _contexts[shard] = make_foreign(std::make_unique<reader_context>(range, slice)); } return _factory_function(std::move(schema), *_contexts[shard]->range, *_contexts[shard]->slice, pc, std::move(trace_state), fwd_mr); } virtual future<> destroy_reader(stopped_reader reader) noexcept override { auto& ctx = _contexts[this_shard_id()]; auto reader_opt = ctx->semaphore->unregister_inactive_read(std::move(reader.handle)); auto ret = reader_opt ? reader_opt->close() : make_ready_future<>(); return ret.finally([&ctx] { return ctx->semaphore->stop().finally([&ctx] { ctx.release(); }); }); } virtual reader_concurrency_semaphore& semaphore() override { const auto shard = this_shard_id(); if (!_contexts[shard]) { _contexts[shard] = make_foreign(std::make_unique<reader_context>()); } else if (_contexts[shard]->semaphore) { return *_contexts[shard]->semaphore; } if (_evict_paused_readers) { // Create with no memory, so all inactive reads are immediately evicted. _contexts[shard]->semaphore.emplace(1, 0, format("reader_concurrency_semaphore @shard_id={}", shard)); } else { _contexts[shard]->semaphore.emplace(reader_concurrency_semaphore::no_limits{}); } return *_contexts[shard]->semaphore; } }; <|endoftext|>
<commit_before>#include "gm.h" #include "SkBitmap.h" #include "SkShader.h" #include "SkXfermode.h" namespace skiagm { static void make_bitmaps(int w, int h, SkBitmap* src, SkBitmap* dst) { src->setConfig(SkBitmap::kARGB_8888_Config, w, h); src->allocPixels(); src->eraseColor(0); SkCanvas c(*src); SkPaint p; SkRect r; SkScalar ww = SkIntToScalar(w); SkScalar hh = SkIntToScalar(h); p.setAntiAlias(true); p.setColor(0xFFFFCC44); r.set(0, 0, ww*3/4, hh*3/4); c.drawOval(r, p); dst->setConfig(SkBitmap::kARGB_8888_Config, w, h); dst->allocPixels(); dst->eraseColor(0); c.setBitmapDevice(*dst); p.setColor(0xFF66AAFF); r.set(ww/3, hh/3, ww*19/20, hh*19/20); c.drawRect(r, p); } static uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF }; class XfermodesGM : public GM { SkBitmap fBG; SkBitmap fSrcB, fDstB; void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha, SkScalar x, SkScalar y) { SkPaint p; canvas->drawBitmap(fSrcB, x, y, &p); p.setAlpha(alpha); p.setXfermode(mode); canvas->drawBitmap(fDstB, x, y, &p); } public: const static int W = 64; const static int H = 64; XfermodesGM() { fBG.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4); fBG.setPixels(gBG); fBG.setIsOpaque(true); make_bitmaps(W, H, &fSrcB, &fDstB); } protected: virtual SkString onShortName() { return SkString("xfermodes"); } virtual SkISize onISize() { return make_isize(790, 640); } void drawBG(SkCanvas* canvas) { canvas->drawColor(SK_ColorWHITE); } virtual void onDraw(SkCanvas* canvas) { canvas->translate(SkIntToScalar(10), SkIntToScalar(20)); this->drawBG(canvas); const struct { SkXfermode::Mode fMode; const char* fLabel; } gModes[] = { { SkXfermode::kClear_Mode, "Clear" }, { SkXfermode::kSrc_Mode, "Src" }, { SkXfermode::kDst_Mode, "Dst" }, { SkXfermode::kSrcOver_Mode, "SrcOver" }, { SkXfermode::kDstOver_Mode, "DstOver" }, { SkXfermode::kSrcIn_Mode, "SrcIn" }, { SkXfermode::kDstIn_Mode, "DstIn" }, { SkXfermode::kSrcOut_Mode, "SrcOut" }, { SkXfermode::kDstOut_Mode, "DstOut" }, { SkXfermode::kSrcATop_Mode, "SrcATop" }, { SkXfermode::kDstATop_Mode, "DstATop" }, { SkXfermode::kXor_Mode, "Xor" }, { SkXfermode::kPlus_Mode, "Plus" }, { SkXfermode::kMultiply_Mode, "Multiply" }, { SkXfermode::kScreen_Mode, "Screen" }, { SkXfermode::kOverlay_Mode, "Overlay" }, { SkXfermode::kDarken_Mode, "Darken" }, { SkXfermode::kLighten_Mode, "Lighten" }, { SkXfermode::kColorDodge_Mode, "ColorDodge" }, { SkXfermode::kColorBurn_Mode, "ColorBurn" }, { SkXfermode::kHardLight_Mode, "HardLight" }, { SkXfermode::kSoftLight_Mode, "SoftLight" }, { SkXfermode::kDifference_Mode, "Difference" }, { SkXfermode::kExclusion_Mode, "Exclusion" }, }; const SkScalar w = SkIntToScalar(W); const SkScalar h = SkIntToScalar(H); SkShader* s = SkShader::CreateBitmapShader(fBG, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); SkMatrix m; m.setScale(SkIntToScalar(6), SkIntToScalar(6)); s->setLocalMatrix(m); SkPaint labelP; labelP.setAntiAlias(true); labelP.setTextAlign(SkPaint::kCenter_Align); const int W = 5; SkScalar x0 = 0; for (int twice = 0; twice < 2; twice++) { SkScalar x = x0, y = 0; for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) { SkXfermode* mode = SkXfermode::Create(gModes[i].fMode); SkAutoUnref aur(mode); SkRect r; r.set(x, y, x+w, y+h); SkPaint p; p.setStyle(SkPaint::kFill_Style); p.setShader(s); canvas->drawRect(r, p); canvas->saveLayer(&r, NULL, SkCanvas::kARGB_ClipLayer_SaveFlag); // canvas->save(); draw_mode(canvas, mode, twice ? 0x88 : 0xFF, r.fLeft, r.fTop); canvas->restore(); r.inset(-SK_ScalarHalf, -SK_ScalarHalf); p.setStyle(SkPaint::kStroke_Style); p.setShader(NULL); canvas->drawRect(r, p); #if 1 canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel), x + w/2, y - labelP.getTextSize()/2, labelP); #endif x += w + SkIntToScalar(10); if ((i % W) == W - 1) { x = x0; y += h + SkIntToScalar(30); } } x0 += SkIntToScalar(400); } s->unref(); } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new XfermodesGM; } static GMRegistry reg(MyFactory); } <commit_msg>Allocate a bitmap on the stack in xfermodes.cpp to work around a limitation in SkPicture.<commit_after>#include "gm.h" #include "SkBitmap.h" #include "SkShader.h" #include "SkXfermode.h" namespace skiagm { static void make_bitmaps(int w, int h, SkBitmap* src, SkBitmap* dst) { src->setConfig(SkBitmap::kARGB_8888_Config, w, h); src->allocPixels(); src->eraseColor(0); SkCanvas c(*src); SkPaint p; SkRect r; SkScalar ww = SkIntToScalar(w); SkScalar hh = SkIntToScalar(h); p.setAntiAlias(true); p.setColor(0xFFFFCC44); r.set(0, 0, ww*3/4, hh*3/4); c.drawOval(r, p); dst->setConfig(SkBitmap::kARGB_8888_Config, w, h); dst->allocPixels(); dst->eraseColor(0); c.setBitmapDevice(*dst); p.setColor(0xFF66AAFF); r.set(ww/3, hh/3, ww*19/20, hh*19/20); c.drawRect(r, p); } static uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF }; class XfermodesGM : public GM { SkBitmap fBG; SkBitmap fSrcB, fDstB; void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha, SkScalar x, SkScalar y) { SkPaint p; canvas->drawBitmap(fSrcB, x, y, &p); p.setAlpha(alpha); p.setXfermode(mode); canvas->drawBitmap(fDstB, x, y, &p); } public: const static int W = 64; const static int H = 64; XfermodesGM() { // Do all this work in a temporary so we get a deep copy, // especially of gBG. SkBitmap scratchBitmap; scratchBitmap.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4); scratchBitmap.setPixels(gBG); scratchBitmap.setIsOpaque(true); scratchBitmap.copyTo(&fBG, SkBitmap::kARGB_4444_Config); make_bitmaps(W, H, &fSrcB, &fDstB); } protected: virtual SkString onShortName() { return SkString("xfermodes"); } virtual SkISize onISize() { return make_isize(790, 640); } void drawBG(SkCanvas* canvas) { canvas->drawColor(SK_ColorWHITE); } virtual void onDraw(SkCanvas* canvas) { canvas->translate(SkIntToScalar(10), SkIntToScalar(20)); this->drawBG(canvas); const struct { SkXfermode::Mode fMode; const char* fLabel; } gModes[] = { { SkXfermode::kClear_Mode, "Clear" }, { SkXfermode::kSrc_Mode, "Src" }, { SkXfermode::kDst_Mode, "Dst" }, { SkXfermode::kSrcOver_Mode, "SrcOver" }, { SkXfermode::kDstOver_Mode, "DstOver" }, { SkXfermode::kSrcIn_Mode, "SrcIn" }, { SkXfermode::kDstIn_Mode, "DstIn" }, { SkXfermode::kSrcOut_Mode, "SrcOut" }, { SkXfermode::kDstOut_Mode, "DstOut" }, { SkXfermode::kSrcATop_Mode, "SrcATop" }, { SkXfermode::kDstATop_Mode, "DstATop" }, { SkXfermode::kXor_Mode, "Xor" }, { SkXfermode::kPlus_Mode, "Plus" }, { SkXfermode::kMultiply_Mode, "Multiply" }, { SkXfermode::kScreen_Mode, "Screen" }, { SkXfermode::kOverlay_Mode, "Overlay" }, { SkXfermode::kDarken_Mode, "Darken" }, { SkXfermode::kLighten_Mode, "Lighten" }, { SkXfermode::kColorDodge_Mode, "ColorDodge" }, { SkXfermode::kColorBurn_Mode, "ColorBurn" }, { SkXfermode::kHardLight_Mode, "HardLight" }, { SkXfermode::kSoftLight_Mode, "SoftLight" }, { SkXfermode::kDifference_Mode, "Difference" }, { SkXfermode::kExclusion_Mode, "Exclusion" }, }; const SkScalar w = SkIntToScalar(W); const SkScalar h = SkIntToScalar(H); SkShader* s = SkShader::CreateBitmapShader(fBG, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); SkMatrix m; m.setScale(SkIntToScalar(6), SkIntToScalar(6)); s->setLocalMatrix(m); SkPaint labelP; labelP.setAntiAlias(true); labelP.setTextAlign(SkPaint::kCenter_Align); const int W = 5; SkScalar x0 = 0; for (int twice = 0; twice < 2; twice++) { SkScalar x = x0, y = 0; for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) { SkXfermode* mode = SkXfermode::Create(gModes[i].fMode); SkAutoUnref aur(mode); SkRect r; r.set(x, y, x+w, y+h); SkPaint p; p.setStyle(SkPaint::kFill_Style); p.setShader(s); canvas->drawRect(r, p); canvas->saveLayer(&r, NULL, SkCanvas::kARGB_ClipLayer_SaveFlag); draw_mode(canvas, mode, twice ? 0x88 : 0xFF, r.fLeft, r.fTop); canvas->restore(); r.inset(-SK_ScalarHalf, -SK_ScalarHalf); p.setStyle(SkPaint::kStroke_Style); p.setShader(NULL); canvas->drawRect(r, p); #if 1 canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel), x + w/2, y - labelP.getTextSize()/2, labelP); #endif x += w + SkIntToScalar(10); if ((i % W) == W - 1) { x = x0; y += h + SkIntToScalar(30); } } x0 += SkIntToScalar(400); } s->unref(); } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new XfermodesGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before><commit_msg>Estimate the renderer working set on Linux. This is less expensive and works in the Chromium SUID sandbox because it does not require access to /proc. Also cache the renderer memory usage value - in some workloads we ask for the memory usage too frequently.<commit_after><|endoftext|>
<commit_before>#include "ignsystem.h" #include <QDebug> ignsystem::ignsystem(QObject *parent) : QObject(parent), jsonParse(0), proc(0) { } QString ignsystem::cliOut(const QString& cli){ QProcess os; os.setProcessChannelMode(QProcess::MergedChannels); os.start(cli); int pid = os.pid(); qDebug() << "Executing process with PID" << pid; os.waitForFinished(-1); return os.readAllStandardOutput(); } QString ignsystem::hash(const QString &data,QString hash_func){ QByteArray hash; QByteArray byteArray = data.toLatin1(); if(hash_func == "md4"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md4); } else if(hash_func == "md5"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md5); } else if(hash_func == "sha1"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha1); } else if(hash_func == "sha224"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha224); } else if(hash_func == "sha256"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha256); } else if(hash_func == "sha384"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha384); } else if(hash_func == "sha512"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha512); } return hash.toHex(); } void ignsystem::desktopService(const QString &link){ QDesktopServices ::openUrl(QUrl(link)); } QObject *ignsystem::exec(const QString& cli){ proc = new ignprocess; proc->exec(cli); return proc; } bool ignsystem::print(const QVariant &config){ QVariantMap conf = jsonParse->jsonParser(config).toVariantMap(); QPrinter print; QTextDocument *doc = new QTextDocument(); QString type = conf["type"].toString(); QString txt = conf["content"].toString(); QString out = conf["out"].toString(); if(type == "html") { doc->setHtml(txt); } else { doc->setPlainText(txt); } if(out == "pdf"){ print.setOutputFormat(QPrinter::PdfFormat); } QPrintDialog *dialog = new QPrintDialog(&print); if (dialog->exec() != QDialog::Accepted) { return false; } else { doc->print(&print); delete doc; return true; } } <commit_msg>FIX BUGS Desktop service<commit_after>#include "ignsystem.h" #include <QDebug> ignsystem::ignsystem(QObject *parent) : QObject(parent), jsonParse(0), proc(0) { } QString ignsystem::cliOut(const QString& cli){ QProcess os; os.setProcessChannelMode(QProcess::MergedChannels); os.start(cli); int pid = os.pid(); qDebug() << "Executing process with PID" << pid; os.waitForFinished(-1); return os.readAllStandardOutput(); } QString ignsystem::hash(const QString &data,QString hash_func){ QByteArray hash; QByteArray byteArray = data.toLatin1(); if(hash_func == "md4"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md4); } else if(hash_func == "md5"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md5); } else if(hash_func == "sha1"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha1); } else if(hash_func == "sha224"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha224); } else if(hash_func == "sha256"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha256); } else if(hash_func == "sha384"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha384); } else if(hash_func == "sha512"){ hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha512); } return hash.toHex(); } void ignsystem::desktopService(const QString &link){ QDesktopServices::openUrl(QUrl(link)); } QObject *ignsystem::exec(const QString& cli){ proc = new ignprocess; proc->exec(cli); return proc; } bool ignsystem::print(const QVariant &config){ QVariantMap conf = jsonParse->jsonParser(config).toVariantMap(); QPrinter print; QTextDocument *doc = new QTextDocument(); QString type = conf["type"].toString(); QString txt = conf["content"].toString(); QString out = conf["out"].toString(); if(type == "html") { doc->setHtml(txt); } else { doc->setPlainText(txt); } if(out == "pdf"){ print.setOutputFormat(QPrinter::PdfFormat); } QPrintDialog *dialog = new QPrintDialog(&print); if (dialog->exec() != QDialog::Accepted) { return false; } else { doc->print(&print); delete doc; return true; } } <|endoftext|>
<commit_before>#ifdef _WIN32 #include "pcmaker/stdafx.h" #endif #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <fstream.h> #include <stdio.h> #include <stdlib.h> #ifdef _WIN32 #include "pcmaker/pcmaker.h" #include "pcmaker/pcmakerDlg.h" #endif #define MAX_DEPENDS 2000 struct DEPENDS_STRUCT { int indices[100]; // aloows up to 100 includes in a single files int numIndices; char name[256]; }; static DEPENDS_STRUCT *DependsStructArray[MAX_DEPENDS]; static int NumInDepends = 0; static int num; static int dependIndices[MAX_DEPENDS]; void AddToDepends(const char *file, const char *vtkHome, char *extraPtr[], int extra_num); void GetIncludes(DEPENDS_STRUCT *dependsEntry, const char *vtkHome, char *extraPtr[], int extra_num); void GetDepends(int index) { int i, j; for (i = 0; i < DependsStructArray[index]->numIndices; i++) { // see if entry is alreay in the list for (j = 0; j < num; j++) { if ( DependsStructArray[index]->indices[i] == dependIndices[j] ) break; } if (j != num ) // already been added continue; dependIndices[ num++ ] = DependsStructArray[index]->indices[i]; GetDepends(DependsStructArray[index]->indices[i]); } } extern void OutputPCDepends(char *file, FILE *fp, const char *vtkHome, char *extraPtr[], int extra_num) { int i; fprintf(fp,"DEPENDS=\\\n"); num = 0; // find this entry in DependsStructArray for (i = 0; i < NumInDepends; i++) { if ( !strcmp(file,DependsStructArray[i]->name) ) break; } if ( i == NumInDepends ) // need to add the file (and any new files it needs) AddToDepends(file, vtkHome, extraPtr, extra_num); GetDepends(i); // now output the results for (i = 0; i < num; i++) { fprintf(fp," \"%s\"\\\n",DependsStructArray[ dependIndices[i] ]->name); } fprintf(fp,"\n"); } extern void OutputUNIXDepends(char *file, FILE *fp, const char *vtkHome, char *extraPtr[], int extra_num) { int i; num = 0; // find this entry in DependsStructArray for (i = 0; i < NumInDepends; i++) { if ( !strcmp(file,DependsStructArray[i]->name) ) break; } if ( i == NumInDepends ) // need to add the file (and any new files it needs) AddToDepends(file, vtkHome, extraPtr, extra_num); GetDepends(i); // now output the results for (i = 0; i < num; i++) { fprintf(fp," \\\n %s",DependsStructArray[ dependIndices[i] ]->name); } fprintf(fp,"\n"); } void AddToDepends(const char *filename, const char *vtkHome, char *extraPtr[], int extra_num) { DEPENDS_STRUCT *dependsEntry; // allocate new entry dependsEntry = new DEPENDS_STRUCT; dependsEntry->numIndices = 0; strcpy( dependsEntry->name, filename ); if ( NumInDepends >= MAX_DEPENDS ) { #ifdef _WIN32 AfxMessageBox("ERROR: To many depends files... recompile with larger MAX_DEPENDS!!!"); #else fprintf(stderr, "ERROR: To many depends files... recompile with larger MAX_DEPENDS!!!"); #endif exit(-1); } DependsStructArray[ NumInDepends++ ] = dependsEntry; GetIncludes(DependsStructArray[NumInDepends-1],vtkHome, extraPtr, extra_num); } int GetFullPath(char *name, const char *vtkHome, char *fullPath, char *extraPtr[], int extra_num) { struct stat statBuff; int i; // does the file exist ? // search for it in the vtk src code sprintf(fullPath,"%s/common/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s/graphics/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s/imaging/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s/contrib/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s/patented/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // now do extra directories for (i = 0; i < extra_num; i++) { sprintf(fullPath,"%s/%s",extraPtr[i],name); if (!stat(fullPath,&statBuff)) return 1; } return 0; } void GetIncludes(DEPENDS_STRUCT *dependsEntry, const char *vtkHome, char *extraPtr[], int extra_num) { ifstream *IS; char line[256]; int j, k; char name[256], fullPath[512]; struct stat statBuff; // does the file exist ? // search for it in the vtk src code if (stat(dependsEntry->name,&statBuff)) { #ifdef _WIN32 sprintf(line,"ERROR: file %s not found... Continuing anyway!", dependsEntry->name); AfxMessageBox(line); #else fprintf(stderr,"ERROR: file %s not found... Continuing anyway!", dependsEntry->name); #endif return; } IS = new ifstream(dependsEntry->name); // search for includes while (!IS->eof() && !IS->fail()) { IS->getline(line,255); // do we have an include if (!strncmp(line,"#include",8)) { // is it a quoted include for (j = 8; j < (int)strlen(line); j++) { if (line[j] == '<') j = 1000; else { if (line[j] == '"') { // we found a quoted include, process it // make sure it is a vtk include file if (!strncmp(line +j +1,"vtk",3)) { // extract the class name // there should always be an end quote or this will die for (k = 0; line[j+k+1] != '"'; k++) { name[k] = line[j+k+1]; } name[k] = '\0'; // Get the full name if (!GetFullPath(name, vtkHome, fullPath, extraPtr, extra_num)) { fprintf(stderr,"ERROR: Dependency %s not found!!!", name); exit(-1); } // get the index in depends for (k = 0; k < NumInDepends; k++) { if ( !strcmp(fullPath,DependsStructArray[k]->name) ) { dependsEntry->indices[ dependsEntry->numIndices++ ] = k; break; } } // if not found, add it to the end if ( k == NumInDepends ) { AddToDepends(fullPath, vtkHome, extraPtr, extra_num); dependsEntry->indices[ dependsEntry->numIndices++ ] = k; } break; // break for (j = 8... loop } else j = 1000; } } // end if line[j] == '<' and else } // end for j = 8 ... strlen(line) } // end if (!strncmp(line,"#include")) } // end while IS->close(); delete IS; } /***************************************************************** Similar Code to above but for plitting up the Graphics library. Messy but gets the job done!!!! *****************************************************************/ #ifdef _WIN32 int GLibFlag[MAX_DEPENDS]; DEPENDS_STRUCT *GLibDependsArray[MAX_DEPENDS]; static int NumInGLibDepends = 0, NumInGLibDependsOriginal; void AddToGLibDepends(char *file) { DEPENDS_STRUCT *dependsEntry; // allocate new entry dependsEntry = new DEPENDS_STRUCT; dependsEntry->numIndices = 0; strcpy( dependsEntry->name, file ); if ( NumInGLibDepends >= MAX_DEPENDS ) { AfxMessageBox("ERROR: To many depends files... recompile with larger MAX_DEPENDS!!!"); exit(1); } GLibDependsArray[ NumInGLibDepends++ ] = dependsEntry; } int GetGLibFullPath(char *name, const char *vtkHome, char *fullPath) { struct stat statBuff; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s\\graphics\\%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s\\patented\\%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; return 0; } void GetGLibIncludes(DEPENDS_STRUCT *dependsEntry, const char *vtkHome ) { ifstream *IS; char line[256]; int j, k; char name[256], fullPath[512]; IS = new ifstream(dependsEntry->name); // search for includes while (!IS->eof()) { IS->getline(line,255); // do we have an include if (!strncmp(line,"#include",8)) { // is it a quoted include for (j = 8; j < (int)strlen(line); j++) { if (line[j] == '<') j = 1000; else { if (line[j] == '"') { // we found a quoted include, process it // make sure it is a vtk include file if (!strncmp(line +j +1,"vtk",3)) { // extract the class name // there should always be an end quote or this will die for (k = 0; line[j+k+1] != '"'; k++) { name[k] = line[j+k+1]; } name[k] = '\0'; // Get the full name if (!GetGLibFullPath(name, vtkHome, fullPath)) break; // get the index in depends for (k = 0; k < NumInGLibDepends; k++) { if ( !strcmp(fullPath,GLibDependsArray[k]->name) ) { dependsEntry->indices[ dependsEntry->numIndices++ ] = k; break; } } // if not found, add it to the end if ( k == NumInGLibDepends ) { AddToGLibDepends(fullPath); dependsEntry->indices[ dependsEntry->numIndices++ ] = k; } break; // break for (j = 8... loop } else j = 1000; } } // end if line[j] == '<' and else } // end for j = 8 ... strlen(line) } // end if (!strncmp(line,"#include")) } // end while IS->close(); delete IS; } void BuildGLibDepends(CPcmakerDlg *vals) { int i; NumInGLibDependsOriginal = NumInGLibDepends; for (i = 0; i < NumInGLibDepends; i++) { GetGLibIncludes(GLibDependsArray[i],vals->m_WhereVTK); if (i < NumInGLibDependsOriginal) vals->m_Progress.OffsetPos(5); } for (i=0;i<NumInGLibDepends;i++) GLibFlag[i] = 0; } void GetGLibDependency(int index) { int i; for (i = 0; i < GLibDependsArray[index]->numIndices; i++) { int thisIndex = GLibDependsArray[index]->indices[i]; // for each in list, check to see if flag has been set if ( !GLibFlag[ thisIndex ] ) { GLibFlag[ thisIndex ] = 1; GetGLibDependency( thisIndex ); } // if cxx file to go with h file, check it if ( thisIndex < NumInGLibDependsOriginal && !GLibFlag[ thisIndex + 1 ] ) { GLibFlag[ thisIndex + 1 ] = 1; GetGLibDependency( thisIndex + 1 ); } } } int GetGraphicsSplit(int maxSet[]) { int i, theIndex; int SetOfClasses[MAX_DEPENDS], numInSet; // FILE *fp = fopen("GraphicsDependenciesMore.txt","w"); int maxNumInSet=0, maxNumIndex; for (theIndex = 0; theIndex < NumInGLibDependsOriginal; theIndex+=2) { if ( GLibFlag[theIndex] == -1 ) continue; for (i=0;i<NumInGLibDepends;i++) { if ( GLibFlag[i] != - 1) GLibFlag[i] = 0; } GLibFlag[theIndex] = 1; // now get lib dependency for this class GetGLibDependency(theIndex); // count how many use numInSet = 0; for (i=0;i<NumInGLibDependsOriginal;i+=2) { if (GLibFlag[i] > 0) SetOfClasses[numInSet++] = i; } if ( numInSet > maxNumInSet ) { maxNumInSet = numInSet; maxNumIndex = theIndex; for (i = 0; i < numInSet; i++) maxSet[i] = SetOfClasses[i]; } if (theIndex == 0) // "force" PCForce into first library break; } // keep track of max.. set all to -1 for the max for (i=0;i<maxNumInSet;i++) { GLibFlag[ maxSet[i] ] = -1; if ( maxSet[i] > 0 ) GLibFlag[ maxSet[i]-1 ] = -1; } return maxNumInSet; } #endif <commit_msg>pc fixes<commit_after>#ifdef WIN32 #include "pcmaker/stdafx.h" #endif #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <fstream.h> #include <stdio.h> #include <stdlib.h> #ifdef WIN32 #include "pcmaker/pcmaker.h" #include "pcmaker/pcmakerDlg.h" #endif #define MAX_DEPENDS 2000 struct DEPENDS_STRUCT { int indices[100]; // aloows up to 100 includes in a single files int numIndices; char name[256]; }; static DEPENDS_STRUCT *DependsStructArray[MAX_DEPENDS]; static int NumInDepends = 0; static int num; static int dependIndices[MAX_DEPENDS]; void AddToDepends(const char *file, const char *vtkHome, char *extraPtr[], int extra_num); void GetIncludes(DEPENDS_STRUCT *dependsEntry, const char *vtkHome, char *extraPtr[], int extra_num); void GetDepends(int index) { int i, j; for (i = 0; i < DependsStructArray[index]->numIndices; i++) { // see if entry is alreay in the list for (j = 0; j < num; j++) { if ( DependsStructArray[index]->indices[i] == dependIndices[j] ) break; } if (j != num ) // already been added continue; dependIndices[ num++ ] = DependsStructArray[index]->indices[i]; GetDepends(DependsStructArray[index]->indices[i]); } } extern void OutputPCDepends(char *file, FILE *fp, const char *vtkHome, char *extraPtr[], int extra_num) { int i; fprintf(fp,"DEPENDS=\\\n"); num = 0; // find this entry in DependsStructArray for (i = 0; i < NumInDepends; i++) { if ( !strcmp(file,DependsStructArray[i]->name) ) break; } if ( i == NumInDepends ) // need to add the file (and any new files it needs) AddToDepends(file, vtkHome, extraPtr, extra_num); GetDepends(i); // now output the results for (i = 0; i < num; i++) { fprintf(fp," \"%s\"\\\n",DependsStructArray[ dependIndices[i] ]->name); } fprintf(fp,"\n"); } extern void OutputUNIXDepends(char *file, FILE *fp, const char *vtkHome, char *extraPtr[], int extra_num) { int i; num = 0; // find this entry in DependsStructArray for (i = 0; i < NumInDepends; i++) { if ( !strcmp(file,DependsStructArray[i]->name) ) break; } if ( i == NumInDepends ) // need to add the file (and any new files it needs) AddToDepends(file, vtkHome, extraPtr, extra_num); GetDepends(i); // now output the results for (i = 0; i < num; i++) { fprintf(fp," \\\n %s",DependsStructArray[ dependIndices[i] ]->name); } fprintf(fp,"\n"); } void AddToDepends(const char *filename, const char *vtkHome, char *extraPtr[], int extra_num) { DEPENDS_STRUCT *dependsEntry; // allocate new entry dependsEntry = new DEPENDS_STRUCT; dependsEntry->numIndices = 0; strcpy( dependsEntry->name, filename ); if ( NumInDepends >= MAX_DEPENDS ) { #ifdef WIN32 AfxMessageBox("ERROR: To many depends files... recompile with larger MAX_DEPENDS!!!"); #else fprintf(stderr, "ERROR: To many depends files... recompile with larger MAX_DEPENDS!!!"); #endif exit(-1); } DependsStructArray[ NumInDepends++ ] = dependsEntry; GetIncludes(DependsStructArray[NumInDepends-1],vtkHome, extraPtr, extra_num); } int GetFullPath(char *name, const char *vtkHome, char *fullPath, char *extraPtr[], int extra_num) { struct stat statBuff; int i; // does the file exist ? // search for it in the vtk src code sprintf(fullPath,"%s/common/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s/graphics/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s/imaging/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s/contrib/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s/patented/%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // now do extra directories for (i = 0; i < extra_num; i++) { sprintf(fullPath,"%s/%s",extraPtr[i],name); if (!stat(fullPath,&statBuff)) return 1; } return 0; } void GetIncludes(DEPENDS_STRUCT *dependsEntry, const char *vtkHome, char *extraPtr[], int extra_num) { ifstream *IS; char line[256]; int j, k; char name[256], fullPath[512]; struct stat statBuff; // does the file exist ? // search for it in the vtk src code if (stat(dependsEntry->name,&statBuff)) { #ifdef WIN32 sprintf(line,"ERROR: file %s not found... Continuing anyway!", dependsEntry->name); AfxMessageBox(line); #else fprintf(stderr,"ERROR: file %s not found... Continuing anyway!", dependsEntry->name); #endif return; } IS = new ifstream(dependsEntry->name); // search for includes while (!IS->eof() && !IS->fail()) { IS->getline(line,255); // do we have an include if (!strncmp(line,"#include",8)) { // is it a quoted include for (j = 8; j < (int)strlen(line); j++) { if (line[j] == '<') j = 1000; else { if (line[j] == '"') { // we found a quoted include, process it // make sure it is a vtk include file if (!strncmp(line +j +1,"vtk",3)) { // extract the class name // there should always be an end quote or this will die for (k = 0; line[j+k+1] != '"'; k++) { name[k] = line[j+k+1]; } name[k] = '\0'; // Get the full name if (!GetFullPath(name, vtkHome, fullPath, extraPtr, extra_num)) { fprintf(stderr,"ERROR: Dependency %s not found!!!", name); exit(-1); } // get the index in depends for (k = 0; k < NumInDepends; k++) { if ( !strcmp(fullPath,DependsStructArray[k]->name) ) { dependsEntry->indices[ dependsEntry->numIndices++ ] = k; break; } } // if not found, add it to the end if ( k == NumInDepends ) { AddToDepends(fullPath, vtkHome, extraPtr, extra_num); dependsEntry->indices[ dependsEntry->numIndices++ ] = k; } break; // break for (j = 8... loop } else j = 1000; } } // end if line[j] == '<' and else } // end for j = 8 ... strlen(line) } // end if (!strncmp(line,"#include")) } // end while IS->close(); delete IS; } /***************************************************************** Similar Code to above but for plitting up the Graphics library. Messy but gets the job done!!!! *****************************************************************/ #ifdef WIN32 int GLibFlag[MAX_DEPENDS]; DEPENDS_STRUCT *GLibDependsArray[MAX_DEPENDS]; static int NumInGLibDepends = 0, NumInGLibDependsOriginal; void AddToGLibDepends(char *file) { DEPENDS_STRUCT *dependsEntry; // allocate new entry dependsEntry = new DEPENDS_STRUCT; dependsEntry->numIndices = 0; strcpy( dependsEntry->name, file ); if ( NumInGLibDepends >= MAX_DEPENDS ) { AfxMessageBox("ERROR: To many depends files... recompile with larger MAX_DEPENDS!!!"); exit(1); } GLibDependsArray[ NumInGLibDepends++ ] = dependsEntry; } int GetGLibFullPath(char *name, const char *vtkHome, char *fullPath) { struct stat statBuff; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s\\graphics\\%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; // if control reaches here then it hasn't been found yet sprintf(fullPath,"%s\\patented\\%s",vtkHome,name); if (!stat(fullPath,&statBuff)) return 1; return 0; } void GetGLibIncludes(DEPENDS_STRUCT *dependsEntry, const char *vtkHome ) { ifstream *IS; char line[256]; int j, k; char name[256], fullPath[512]; IS = new ifstream(dependsEntry->name); // search for includes while (!IS->eof()) { IS->getline(line,255); // do we have an include if (!strncmp(line,"#include",8)) { // is it a quoted include for (j = 8; j < (int)strlen(line); j++) { if (line[j] == '<') j = 1000; else { if (line[j] == '"') { // we found a quoted include, process it // make sure it is a vtk include file if (!strncmp(line +j +1,"vtk",3)) { // extract the class name // there should always be an end quote or this will die for (k = 0; line[j+k+1] != '"'; k++) { name[k] = line[j+k+1]; } name[k] = '\0'; // Get the full name if (!GetGLibFullPath(name, vtkHome, fullPath)) break; // get the index in depends for (k = 0; k < NumInGLibDepends; k++) { if ( !strcmp(fullPath,GLibDependsArray[k]->name) ) { dependsEntry->indices[ dependsEntry->numIndices++ ] = k; break; } } // if not found, add it to the end if ( k == NumInGLibDepends ) { AddToGLibDepends(fullPath); dependsEntry->indices[ dependsEntry->numIndices++ ] = k; } break; // break for (j = 8... loop } else j = 1000; } } // end if line[j] == '<' and else } // end for j = 8 ... strlen(line) } // end if (!strncmp(line,"#include")) } // end while IS->close(); delete IS; } void BuildGLibDepends(CPcmakerDlg *vals) { int i; NumInGLibDependsOriginal = NumInGLibDepends; for (i = 0; i < NumInGLibDepends; i++) { GetGLibIncludes(GLibDependsArray[i],vals->m_WhereVTK); if (i < NumInGLibDependsOriginal) vals->m_Progress.OffsetPos(5); } for (i=0;i<NumInGLibDepends;i++) GLibFlag[i] = 0; } void GetGLibDependency(int index) { int i; for (i = 0; i < GLibDependsArray[index]->numIndices; i++) { int thisIndex = GLibDependsArray[index]->indices[i]; // for each in list, check to see if flag has been set if ( !GLibFlag[ thisIndex ] ) { GLibFlag[ thisIndex ] = 1; GetGLibDependency( thisIndex ); } // if cxx file to go with h file, check it if ( thisIndex < NumInGLibDependsOriginal && !GLibFlag[ thisIndex + 1 ] ) { GLibFlag[ thisIndex + 1 ] = 1; GetGLibDependency( thisIndex + 1 ); } } } int GetGraphicsSplit(int maxSet[]) { int i, theIndex; int SetOfClasses[MAX_DEPENDS], numInSet; // FILE *fp = fopen("GraphicsDependenciesMore.txt","w"); int maxNumInSet=0, maxNumIndex; for (theIndex = 0; theIndex < NumInGLibDependsOriginal; theIndex+=2) { if ( GLibFlag[theIndex] == -1 ) continue; for (i=0;i<NumInGLibDepends;i++) { if ( GLibFlag[i] != - 1) GLibFlag[i] = 0; } GLibFlag[theIndex] = 1; // now get lib dependency for this class GetGLibDependency(theIndex); // count how many use numInSet = 0; for (i=0;i<NumInGLibDependsOriginal;i+=2) { if (GLibFlag[i] > 0) SetOfClasses[numInSet++] = i; } if ( numInSet > maxNumInSet ) { maxNumInSet = numInSet; maxNumIndex = theIndex; for (i = 0; i < numInSet; i++) maxSet[i] = SetOfClasses[i]; } if (theIndex == 0) // "force" PCForce into first library break; } // keep track of max.. set all to -1 for the max for (i=0;i<maxNumInSet;i++) { GLibFlag[ maxSet[i] ] = -1; if ( maxSet[i] > 0 ) GLibFlag[ maxSet[i]-1 ] = -1; } return maxNumInSet; } #endif <|endoftext|>
<commit_before>#include "ros/ros.h" #include <boost/bind.hpp> #include <boost/ref.hpp> #include "robotiq_s_model_control/s_model_ethercat_client.h" #include <robotiq_s_model_control/SModel_robot_input.h> #include "robotiq_ethercat/ethercat_manager.h" /* Note that this code currently works only to control ONE SModel gripper attached to ONE network interface. If you want to add more grippers to the same network, you'll need to edit the source file. */ // Note that you will likely need to run the following on your binary: // sudo setcap cap_net_raw+ep <filename> void changeCallback(robotiq_s_model_control::SModelEtherCatClient& client, const robotiq_s_model_control::SModelEtherCatClient::GripperOutput::ConstPtr& msg) { client.writeOutputs(*msg); } int main(int argc, char** argv) { using robotiq_ethercat::EtherCatManager; using robotiq_s_model_control::SModelEtherCatClient; typedef SModelEtherCatClient::GripperOutput GripperOutput; typedef SModelEtherCatClient::GripperInput GripperInput; ros::init(argc, argv, "robotiq_s_model_gripper_node"); ros::NodeHandle nh ("~"); // Parameter names std::string ifname; int slave_no; bool activate; nh.param<std::string>("ifname", ifname, "enp9s0"); nh.param<int>("slave_number", slave_no, 1); nh.param<bool>("activate", activate, true); // Start ethercat manager boost::shared_ptr<EtherCatManager> manager(new EtherCatManager(ifname)); // register client SModelEtherCatClient client(manager, slave_no); client.init(nh); // conditionally activate the gripper if (activate) { // Check to see if resetting is required? Or always reset? GripperOutput out; out.rACT = 0x1; client.writeOutputs(out); } // Sorry for the indentation, trying to keep it under 100 chars ros::Subscriber sub = nh.subscribe<GripperOutput>("output", 1, boost::bind(changeCallback, boost::ref(client), _1)); ros::Publisher pub = nh.advertise<GripperInput>("input", 100); ros::Rate rate(10); // 10 Hz while (ros::ok()) { SModelEtherCatClient::GripperInput input = client.readInputs(); pub.publish(input); ros::spinOnce(); rate.sleep(); } return 0; } <commit_msg>updated ethercat node to ros control<commit_after>#include <robotiq_s_model_control/s_model_api.h> #include <robotiq_s_model_control/s_model_ethercat_client.h> #include <robotiq_ethercat/ethercat_manager.h> #include <robotiq_s_model_control/s_model_hw_interface.h> #include <controller_manager/controller_manager.h> #include <ros/ros.h> // Used to convert seconds elapsed to nanoseconds static const double BILLION = 1000000000.0; class GenericHWLoop { public: GenericHWLoop( ros::NodeHandle& nh, boost::shared_ptr<robotiq_s_model_control::SModelHWInterface> hardware_interface) : nh_(nh), name_("generic_hw_control_loop"), hardware_interface_(hardware_interface) { ROS_DEBUG("creating loop"); //! Create the controller manager controller_manager_.reset(new controller_manager::ControllerManager(hardware_interface_.get(), nh_)); ROS_DEBUG("created controller manager"); //! Load rosparams ros::NodeHandle rpsnh(nh, name_); loop_hz_ = rpsnh.param<double>("loop_hz", 30); cycle_time_error_threshold_ = rpsnh.param<double>("cycle_time_error_threshold", 0.1); //! Get current time for use with first update clock_gettime(CLOCK_MONOTONIC, &last_time_); //! Start timer ros::Duration desired_update_freq_ = ros::Duration(1 / loop_hz_); non_realtime_loop_ = nh_.createTimer(desired_update_freq_, &GenericHWLoop::update, this); ROS_DEBUG("created timer"); } /** \brief Timer event * Note: we do not use the TimerEvent time difference because it does NOT guarantee that * the time source is * strictly linearly increasing */ void update(const ros::TimerEvent& e) { //! Get change in time clock_gettime(CLOCK_MONOTONIC, &current_time_); elapsed_time_ = ros::Duration(current_time_.tv_sec - last_time_.tv_sec + (current_time_.tv_nsec - last_time_.tv_nsec) / BILLION); last_time_ = current_time_; ROS_DEBUG_STREAM_THROTTLE_NAMED(1, "GenericHWLoop","Sampled update loop with elapsed time " << elapsed_time_.toSec()); //! Error check cycle time const double cycle_time_error = (elapsed_time_ - desired_update_freq_).toSec(); if (cycle_time_error > cycle_time_error_threshold_) { ROS_WARN_STREAM_NAMED(name_, "Cycle time exceeded error threshold by: " << cycle_time_error << ", cycle time: " << elapsed_time_ << ", threshold: " << cycle_time_error_threshold_); } //! Input hardware_interface_->read(elapsed_time_); //! Control controller_manager_->update(ros::Time::now(), elapsed_time_); //! Output hardware_interface_->write(elapsed_time_); } protected: // Startup and shutdown of the internal node inside a roscpp program ros::NodeHandle nh_; // Name of this class std::string name_; // Settings ros::Duration desired_update_freq_; double cycle_time_error_threshold_; // Timing ros::Timer non_realtime_loop_; ros::Duration elapsed_time_; double loop_hz_; struct timespec last_time_; struct timespec current_time_; /** \brief ROS Controller Manager and Runner * * This class advertises a ROS interface for loading, unloading, starting, and * stopping ros_control-based controllers. It also serializes execution of all * running controllers in \ref update. */ boost::shared_ptr<controller_manager::ControllerManager> controller_manager_; /** \brief Abstract Hardware Interface for your robot */ boost::shared_ptr<robotiq_s_model_control::SModelHWInterface> hardware_interface_; }; int main(int argc, char** argv) { using robotiq_ethercat::EtherCatManager; using robotiq_s_model_control::SModelEtherCatClient; ros::init(argc, argv, "robotiq_hw_interface"); ros::NodeHandle nh; ros::NodeHandle pnh("~"); // NOTE: We run the ROS loop in a separate thread as external calls such // as service callbacks to load controllers can block the (main) control loop ros::AsyncSpinner spinner(2); spinner.start(); // Parameter names std::string ifname; int slave_no; bool activate; nh.param<std::string>("ifname", ifname, "enp9s0"); nh.param<int>("slave_number", slave_no, 1); nh.param<bool>("activate", activate, true); // Start ethercat manager boost::shared_ptr<EtherCatManager> manager(new EtherCatManager(ifname)); // Create the hw client layer boost::shared_ptr<robotiq_s_model_control::SModelEtherCatClient> ethercat_client (new robotiq_s_model_control::SModelEtherCatClient(manager, slave_no)); ethercat_client->init(pnh); // Create the hw api layer boost::shared_ptr<robotiq_s_model_control::SModelAPI> hw_api (new robotiq_s_model_control::SModelAPI(ethercat_client)); // Create the hardware interface layer boost::shared_ptr<robotiq_s_model_control::SModelHWInterface> hw_interface (new robotiq_s_model_control::SModelHWInterface(pnh, hw_api)); ROS_DEBUG("created hw interface"); // Register interfaces hardware_interface::JointStateInterface joint_state_interface; hardware_interface::PositionJointInterface position_cmd_interface; hw_interface->configure(joint_state_interface, position_cmd_interface); hw_interface->registerInterface(&joint_state_interface); hw_interface->registerInterface(&position_cmd_interface); ROS_DEBUG("registered control interfaces"); // Start the control loop GenericHWLoop control_loop(pnh, hw_interface); ROS_INFO("started"); // Wait until shutdown signal recieved ros::waitForShutdown(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2011, Paul Tagliamonte <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <malloc.h> #include <iostream> #include <pty.h> #include <stdlib.h> #include <string.h> #include "Shibuya.hh" #include "Terminal.hh" #include "conf/term.hh" void Terminal::_init_Terminal(int width, int height) { this->width = width; this->height = height; this->cX = 0; this->cY = 0; this->cMode = 0x70; /* 11100000 = 0x70 (112) FFF BBB */ this->scroll_frame_bottom = this->height; this->scroll_frame_top = 0; this->pty = -1; this->chars = (TerminalCell*) malloc(sizeof(TerminalCell) * (width * height)); for ( int i = 0; i < ( height * width ); ++i ) { this->chars[i].ch = ' '; this->chars[i].attr = this->cMode; } } Terminal::~Terminal() { free( this->chars ); } Terminal::Terminal() { this->_init_Terminal(80, 25); } Terminal::Terminal( int width, int height ) { this->_init_Terminal(width, height); } void Terminal::erase_to_from( int iX, int iY, int tX, int tY ) { int from = GET_OFFSET(iX, iY); int to = GET_OFFSET(tX, tY); std::cerr << iX << ", " << iY << " / " << tX << ", " << tY << std::endl; for ( int i = from - 1; i < to; ++i ) { this->chars[i].ch = ' '; this->chars[i].attr = 0x70; } } void Terminal::scroll_up() { for ( int iy = this->scroll_frame_top + 1; iy < this->scroll_frame_bottom; iy++ ) { for ( int ix = 0; ix < this->width; ++ix ) { int thisChar = GET_OFFSET(ix, iy); int lastChar = GET_OFFSET(ix, (iy - 1)); this->chars[lastChar].ch = this->chars[thisChar].ch; this->chars[lastChar].attr = this->chars[thisChar].attr; } } for ( int ix = 0; ix < this->width; ++ix ) { int offset = GET_OFFSET( ix, (this->scroll_frame_bottom - 1) ); this->chars[offset].ch = ' '; this->chars[offset].attr = 0x70; } } pid_t Terminal::fork( const char * command ) { struct winsize ws; ws.ws_row = this->height; ws.ws_col = this->width; ws.ws_xpixel = 0; ws.ws_ypixel = 0; pid_t childpid = forkpty(&this->pty, NULL, NULL, &ws); if (childpid < 0) return -1; if (childpid == 0) { setenv("TERM", TERMINAL_ENV_NAME, 1); execl("/bin/sh", "/bin/sh", "-c", command, NULL); // XXX: Choose shell better std::cerr << "Failed to fork." << std::endl; exit(127); } /* if we got here we are the parent process */ this->childpid = childpid; return childpid; } void Terminal::poke() { /* This is ripped off from librote */ fd_set ifs; struct timeval tvzero; char buf[512]; int bytesread; int n = 5; // XXX: Fix? if (this->pty < 0) return; while (n--) { FD_ZERO(&ifs); FD_SET(this->pty, &ifs); tvzero.tv_sec = 0; tvzero.tv_usec = 0; if (select(this->pty + 1, &ifs, NULL, NULL, &tvzero) <= 0) return; bytesread = read(this->pty, buf, 512); if (bytesread <= 0) return; for ( int i = 0; i < bytesread; ++i ) this->insert( buf[i] ); } } void Terminal::insert( unsigned char c ) { if ( c == '\n' ) { this->cX = this->width; this->advance_curs(); return; } if ( c == 7 ) { /* Bell */ } if ( c == 8 ) { --this->cX; return; } if ( c == 9 ) { /* Tab */ this->insert(' '); while ( ( this->cX % 8 ) != 0 ) { this->insert(' '); } return; } if ( c < 32 ) { return; } int ix = this->cX; int iy = this->cY; /* * XXX: Why was the math using this->cX failing? * for some reason we have to bring it into the local * scope... */ int offset = GET_OFFSET(ix, iy); this->chars[offset].ch = c; this->chars[offset].attr = this->cMode; this->advance_curs(); } void Terminal::type( char c ) { write(this->pty, &c, 1); } void Terminal::advance_curs() { this->cX++; if ( this->width <= this->cX ) { this->cX = 0; this->cY++; } if ( this->height <= this->cY ) { this->cY = (this->height - 1); this->scroll_up(); } } int Terminal::get_width() { return this->width; } int Terminal::get_height() { return this->height; } <commit_msg>Removing a cerr thing :)<commit_after>/* * Copyright (C) 2011, Paul Tagliamonte <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <malloc.h> #include <iostream> #include <pty.h> #include <stdlib.h> #include <string.h> #include "Shibuya.hh" #include "Terminal.hh" #include "conf/term.hh" void Terminal::_init_Terminal(int width, int height) { this->width = width; this->height = height; this->cX = 0; this->cY = 0; this->cMode = 0x70; /* 11100000 = 0x70 (112) FFF BBB */ this->scroll_frame_bottom = this->height; this->scroll_frame_top = 0; this->pty = -1; this->chars = (TerminalCell*) malloc(sizeof(TerminalCell) * (width * height)); for ( int i = 0; i < ( height * width ); ++i ) { this->chars[i].ch = ' '; this->chars[i].attr = this->cMode; } } Terminal::~Terminal() { free( this->chars ); } Terminal::Terminal() { this->_init_Terminal(80, 25); } Terminal::Terminal( int width, int height ) { this->_init_Terminal(width, height); } void Terminal::erase_to_from( int iX, int iY, int tX, int tY ) { int from = GET_OFFSET(iX, iY); int to = GET_OFFSET(tX, tY); for ( int i = from - 1; i < to; ++i ) { this->chars[i].ch = ' '; this->chars[i].attr = 0x70; } } void Terminal::scroll_up() { for ( int iy = this->scroll_frame_top + 1; iy < this->scroll_frame_bottom; iy++ ) { for ( int ix = 0; ix < this->width; ++ix ) { int thisChar = GET_OFFSET(ix, iy); int lastChar = GET_OFFSET(ix, (iy - 1)); this->chars[lastChar].ch = this->chars[thisChar].ch; this->chars[lastChar].attr = this->chars[thisChar].attr; } } for ( int ix = 0; ix < this->width; ++ix ) { int offset = GET_OFFSET( ix, (this->scroll_frame_bottom - 1) ); this->chars[offset].ch = ' '; this->chars[offset].attr = 0x70; } } pid_t Terminal::fork( const char * command ) { struct winsize ws; ws.ws_row = this->height; ws.ws_col = this->width; ws.ws_xpixel = 0; ws.ws_ypixel = 0; pid_t childpid = forkpty(&this->pty, NULL, NULL, &ws); if (childpid < 0) return -1; if (childpid == 0) { setenv("TERM", TERMINAL_ENV_NAME, 1); execl("/bin/sh", "/bin/sh", "-c", command, NULL); // XXX: Choose shell better std::cerr << "Failed to fork." << std::endl; exit(127); } /* if we got here we are the parent process */ this->childpid = childpid; return childpid; } void Terminal::poke() { /* This is ripped off from librote */ fd_set ifs; struct timeval tvzero; char buf[512]; int bytesread; int n = 5; // XXX: Fix? if (this->pty < 0) return; while (n--) { FD_ZERO(&ifs); FD_SET(this->pty, &ifs); tvzero.tv_sec = 0; tvzero.tv_usec = 0; if (select(this->pty + 1, &ifs, NULL, NULL, &tvzero) <= 0) return; bytesread = read(this->pty, buf, 512); if (bytesread <= 0) return; for ( int i = 0; i < bytesread; ++i ) this->insert( buf[i] ); } } void Terminal::insert( unsigned char c ) { if ( c == '\n' ) { this->cX = this->width; this->advance_curs(); return; } if ( c == 7 ) { /* Bell */ } if ( c == 8 ) { --this->cX; return; } if ( c == 9 ) { /* Tab */ this->insert(' '); while ( ( this->cX % 8 ) != 0 ) { this->insert(' '); } return; } if ( c < 32 ) { return; } int ix = this->cX; int iy = this->cY; /* * XXX: Why was the math using this->cX failing? * for some reason we have to bring it into the local * scope... */ int offset = GET_OFFSET(ix, iy); this->chars[offset].ch = c; this->chars[offset].attr = this->cMode; this->advance_curs(); } void Terminal::type( char c ) { write(this->pty, &c, 1); } void Terminal::advance_curs() { this->cX++; if ( this->width <= this->cX ) { this->cX = 0; this->cY++; } if ( this->height <= this->cY ) { this->cY = (this->height - 1); this->scroll_up(); } } int Terminal::get_width() { return this->width; } int Terminal::get_height() { return this->height; } <|endoftext|>
<commit_before>/*******************************************************************//* * Implementation of the Texture class. * * @author Brandon To * @version 1.0 * @since 2015-02-05 * @modified 2015-02-18 *********************************************************************/ #include "Texture.h" #include <cstddef> #include <cstdio> #include "SDL_util.h" #include "tinyxml.h" #include "WindowElements.h" Texture::Texture(WindowElements* windowElements) : sprite(NULL), spriteWidth(0), spriteHeight(0), angle(0), alpha(OPAQUE), alphaEnabled(false), currentAnimationFrame(0), partitioned(false) { this->windowElements = windowElements; } // Sets the sprite to the image given in imagePath void Texture::setTexture(std::string imagePath) { // Creates a new sprite from the filepath given in imagePath SDL_Texture* newSprite = SDL_util::create_texture_from_image(windowElements, imagePath); if (newSprite == NULL) { printf("[ERROR] setTexture(): Texture could not be constructed from image.\n"); } // If there was a previously set sprite, destroy the sprite and reset variables if (sprite != NULL) { SDL_DestroyTexture(sprite); sprite = NULL; alpha = OPAQUE; alphaEnabled = false; currentAnimationFrame = 0; partitioned = false; } // Sets the current sprite to the newly created sprite sprite = newSprite; newSprite = NULL; // Sets spriteWidth and spriteHeight to the width and height of the new image SDL_QueryTexture(sprite, NULL, NULL, &spriteWidth, &spriteHeight); sourceRect.x = 0; sourceRect.y = 0; sourceRect.w = spriteWidth; sourceRect.h = spriteHeight; } // Sets the sprite to be the one passed in void Texture::setTexture(SDL_Texture* texture) { // If there was a previously set sprite, destroy the sprite and reset variables if (sprite != NULL) { SDL_DestroyTexture(sprite); sprite = NULL; alpha = OPAQUE; alphaEnabled = false; currentAnimationFrame = 0; partitioned = false; } sprite = texture; texture = NULL; // Sets spriteWidth and spriteHeight to the width and height of the new image SDL_QueryTexture(sprite, NULL, NULL, &spriteWidth, &spriteHeight); sourceRect.x = 0; sourceRect.y = 0; sourceRect.w = spriteWidth; sourceRect.h = spriteHeight; } // Getter for texture SDL_Texture* Texture::getTexture() { return sprite; } // Sets the area of the sprite that will be rendered void Texture::setSourceRect(SDL_Rect* rect) { sourceRect = *rect; } // Getter for sourceRect SDL_Rect Texture::getSourceRect() { return sourceRect; } // Getter for spriteWidth int Texture::getSpriteWidth() { return spriteWidth; } // Getter for spriteHeight int Texture::getSpriteHeight() { return spriteHeight; } // Sets the angle at which the sprite will be rendered void Texture::setAngle(double angle) { this->angle = angle; } // Getter for angle double Texture::getAngle() { return angle; } // Enables alpha blending. Must be called before setAlphaBlend() void Texture::enableAlphaBlend() { if (!alphaEnabled) { SDL_SetTextureBlendMode(sprite, SDL_BLENDMODE_BLEND); alphaEnabled = true; } else { printf("[WARNING] enableAlphaBlend(): Alpha blending is already enabled.\n"); } } // Disables alpha blending. void Texture::disableAlphaBlend() { if (alphaEnabled) { SDL_SetTextureBlendMode(sprite, SDL_BLENDMODE_NONE); alphaEnabled = false; } else { printf("[WARNING] disableAlphaBlend(): Alpha blending is already disabled.\n"); } } // Sets the alpha blend value that the texture will be rendered at. // Must be called after enableAlphaBlend() void Texture::setAlphaBlend(Uint8 alpha) { if (alphaEnabled) { this->alpha = alpha; SDL_SetTextureAlphaMod(sprite, alpha); } else { printf("[ERROR] setAlphaBlend(): Alpha blending has not been enabled. Please call enableAlphaBlend() first.\n"); } } // Returns the alpha value of the texture, should be called after enableAlphaBlend() Uint8 Texture::getAlphaBlend() { if (!alphaEnabled) { printf("[WARNING] getAlphaBlend(): Called before alpha blending has been enabled.\n"); } return alpha; } // Creates an array of sub-textures for use in animation bool Texture::partitionSpritesheet(std::string xmlPath) { TiXmlDocument xmlDoc; // Return false if the XML file is not found if (!xmlDoc.LoadFile(xmlPath.c_str())) { printf("[ERROR] partitionSpritesheet(): Xml file not found.\n"); return false; } // The root element of this xml file TiXmlElement* rootElement = xmlDoc.RootElement(); // Parses through SubTexture elements to create partitioned SDL_Rects // and pushes onto vector for ( TiXmlElement* e = rootElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { SDL_Rect partitionedRect; partitionedRect.x = atoi(e->Attribute("x")); partitionedRect.y = atoi(e->Attribute("y")); partitionedRect.w = atoi(e->Attribute("width")); partitionedRect.h = atoi(e->Attribute("height")); animationRect.push_back(partitionedRect); } partitioned = true; currentAnimationFrame = 0; return true; } // Advances the animation by one frame // Returns true if successful // Returns false if texture is not partitioned or if no more animations bool Texture::advanceAnimation() { // Return immediately if texture is not partitioned if (!partitioned) { printf("[ERROR] advanceAnimation(): Texture is not partitioned.\n"); return false; } // No more animations if (++currentAnimationFrame > animationRect.size()) { return false; } sourceRect = animationRect[currentAnimationFrame]; return true; } // Sets the current animation frame // Returns true if successful // Returns false if texture is not partitioned or if animation frame is out of bounds bool Texture::setAnimationFrame(int animationFrame) { // Return immediately if texture is not partitioned if (!partitioned) { printf("[ERROR] setAnimationFrame(): Texture is not partitioned.\n"); return false; } // Returns false if animation is out of bounds if (animationFrame<0 || animationRect.size()<animationFrame) { printf("[ERROR] setAnimationFrame(): Attempted to set to an invalid animation frame.\n"); return false; } currentAnimationFrame = animationFrame; sourceRect = animationRect[animationFrame]; return true; } Texture::~Texture() { SDL_DestroyTexture(sprite); sprite = NULL; } <commit_msg>Fixed out of range error in Texture::advanceAnimation<commit_after>/*******************************************************************//* * Implementation of the Texture class. * * @author Brandon To * @version 1.0 * @since 2015-02-05 * @modified 2015-02-18 *********************************************************************/ #include "Texture.h" #include <cstddef> #include <cstdio> #include "SDL_util.h" #include "tinyxml.h" #include "WindowElements.h" Texture::Texture(WindowElements* windowElements) : sprite(NULL), spriteWidth(0), spriteHeight(0), angle(0), alpha(OPAQUE), alphaEnabled(false), currentAnimationFrame(0), partitioned(false) { this->windowElements = windowElements; } // Sets the sprite to the image given in imagePath void Texture::setTexture(std::string imagePath) { // Creates a new sprite from the filepath given in imagePath SDL_Texture* newSprite = SDL_util::create_texture_from_image(windowElements, imagePath); if (newSprite == NULL) { printf("[ERROR] setTexture(): Texture could not be constructed from image.\n"); } // If there was a previously set sprite, destroy the sprite and reset variables if (sprite != NULL) { SDL_DestroyTexture(sprite); sprite = NULL; alpha = OPAQUE; alphaEnabled = false; currentAnimationFrame = 0; partitioned = false; } // Sets the current sprite to the newly created sprite sprite = newSprite; newSprite = NULL; // Sets spriteWidth and spriteHeight to the width and height of the new image SDL_QueryTexture(sprite, NULL, NULL, &spriteWidth, &spriteHeight); sourceRect.x = 0; sourceRect.y = 0; sourceRect.w = spriteWidth; sourceRect.h = spriteHeight; } // Sets the sprite to be the one passed in void Texture::setTexture(SDL_Texture* texture) { // If there was a previously set sprite, destroy the sprite and reset variables if (sprite != NULL) { SDL_DestroyTexture(sprite); sprite = NULL; alpha = OPAQUE; alphaEnabled = false; currentAnimationFrame = 0; partitioned = false; } sprite = texture; texture = NULL; // Sets spriteWidth and spriteHeight to the width and height of the new image SDL_QueryTexture(sprite, NULL, NULL, &spriteWidth, &spriteHeight); sourceRect.x = 0; sourceRect.y = 0; sourceRect.w = spriteWidth; sourceRect.h = spriteHeight; } // Getter for texture SDL_Texture* Texture::getTexture() { return sprite; } // Sets the area of the sprite that will be rendered void Texture::setSourceRect(SDL_Rect* rect) { sourceRect = *rect; } // Getter for sourceRect SDL_Rect Texture::getSourceRect() { return sourceRect; } // Getter for spriteWidth int Texture::getSpriteWidth() { return spriteWidth; } // Getter for spriteHeight int Texture::getSpriteHeight() { return spriteHeight; } // Sets the angle at which the sprite will be rendered void Texture::setAngle(double angle) { this->angle = angle; } // Getter for angle double Texture::getAngle() { return angle; } // Enables alpha blending. Must be called before setAlphaBlend() void Texture::enableAlphaBlend() { if (!alphaEnabled) { SDL_SetTextureBlendMode(sprite, SDL_BLENDMODE_BLEND); alphaEnabled = true; } else { printf("[WARNING] enableAlphaBlend(): Alpha blending is already enabled.\n"); } } // Disables alpha blending. void Texture::disableAlphaBlend() { if (alphaEnabled) { SDL_SetTextureBlendMode(sprite, SDL_BLENDMODE_NONE); alphaEnabled = false; } else { printf("[WARNING] disableAlphaBlend(): Alpha blending is already disabled.\n"); } } // Sets the alpha blend value that the texture will be rendered at. // Must be called after enableAlphaBlend() void Texture::setAlphaBlend(Uint8 alpha) { if (alphaEnabled) { this->alpha = alpha; SDL_SetTextureAlphaMod(sprite, alpha); } else { printf("[ERROR] setAlphaBlend(): Alpha blending has not been enabled. Please call enableAlphaBlend() first.\n"); } } // Returns the alpha value of the texture, should be called after enableAlphaBlend() Uint8 Texture::getAlphaBlend() { if (!alphaEnabled) { printf("[WARNING] getAlphaBlend(): Called before alpha blending has been enabled.\n"); } return alpha; } // Creates an array of sub-textures for use in animation bool Texture::partitionSpritesheet(std::string xmlPath) { TiXmlDocument xmlDoc; // Return false if the XML file is not found if (!xmlDoc.LoadFile(xmlPath.c_str())) { printf("[ERROR] partitionSpritesheet(): Xml file not found.\n"); return false; } // The root element of this xml file TiXmlElement* rootElement = xmlDoc.RootElement(); // Parses through SubTexture elements to create partitioned SDL_Rects // and pushes onto vector for ( TiXmlElement* e = rootElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { SDL_Rect partitionedRect; partitionedRect.x = atoi(e->Attribute("x")); partitionedRect.y = atoi(e->Attribute("y")); partitionedRect.w = atoi(e->Attribute("width")); partitionedRect.h = atoi(e->Attribute("height")); animationRect.push_back(partitionedRect); } partitioned = true; currentAnimationFrame = 0; return true; } // Advances the animation by one frame // Returns true if successful // Returns false if texture is not partitioned or if no more animations bool Texture::advanceAnimation() { // Return immediately if texture is not partitioned if (!partitioned) { printf("[ERROR] advanceAnimation(): Texture is not partitioned.\n"); return false; } // No more animations if (++currentAnimationFrame >= animationRect.size()) { return false; } sourceRect = animationRect[currentAnimationFrame]; return true; } // Sets the current animation frame // Returns true if successful // Returns false if texture is not partitioned or if animation frame is out of bounds bool Texture::setAnimationFrame(int animationFrame) { // Return immediately if texture is not partitioned if (!partitioned) { printf("[ERROR] setAnimationFrame(): Texture is not partitioned.\n"); return false; } // Returns false if animation is out of bounds if (animationFrame<0 || animationRect.size()<animationFrame) { printf("[ERROR] setAnimationFrame(): Attempted to set to an invalid animation frame.\n"); return false; } currentAnimationFrame = animationFrame; sourceRect = animationRect[animationFrame]; return true; } Texture::~Texture() { SDL_DestroyTexture(sprite); sprite = NULL; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediaplayercontrol.h" #include "s60mediaplayersession.h" #include <QMediaPlaylistNavigator> #include <QtCore/qdir.h> #include <QtCore/qsocketnotifier.h> #include <QtCore/qurl.h> #include <QtCore/qdebug.h> S60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent) : QMediaPlayerControl(parent), m_mediaPlayerResolver(mediaPlayerResolver), m_session(NULL) { m_controlSettings.m_vol = -1; m_controlSettings.m_muted = false; m_controlSettings.m_playbackRate = -1; m_controlSettings.m_position = -1; } S60MediaPlayerControl::~S60MediaPlayerControl() { } qint64 S60MediaPlayerControl::position() const { if (m_session) return m_session->position(); return m_controlSettings.m_position; } qint64 S60MediaPlayerControl::duration() const { if (m_session) return m_session->duration(); return -1; } QMediaPlayer::State S60MediaPlayerControl::state() const { if (m_session) return m_session->state(); // we dont have a session -> state is stopped return QMediaPlayer::StoppedState; } QMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const { if (m_session) return m_session->mediaStatus(); return QMediaPlayer::NoMedia; } int S60MediaPlayerControl::bufferStatus() const { return -1; } int S60MediaPlayerControl::volume() const { if (m_session) return m_session->volume(); return m_controlSettings.m_vol; } bool S60MediaPlayerControl::isMuted() const { if (m_session) return m_session->isMuted(); return m_controlSettings.m_muted; } bool S60MediaPlayerControl::isSeekable() const { if (m_session) return m_session->isSeekable(); return m_controlSettings.m_position; } QPair<qint64, qint64> S60MediaPlayerControl::seekRange() const { if (m_session) { return q_check_ptr(m_session)->isSeekable() ? qMakePair<qint64, qint64>(0, m_session->duration()) : qMakePair<qint64, qint64>(0, 0); } return QPair<qint64, qint64>(); } qreal S60MediaPlayerControl::playbackRate() const { if (m_session) return m_session->playbackRate(); return -1; } void S60MediaPlayerControl::setPlaybackRate(qreal rate) { m_controlSettings.m_playbackRate = rate; if (m_session) m_session->setPlaybackRate(rate); } void S60MediaPlayerControl::setPosition(qint64 pos) { m_controlSettings.m_position = pos; if (m_session) m_session->setPosition(pos); } void S60MediaPlayerControl::play() { if (m_session) m_session->play(); else // to ensure that api know we can't play this emit mediaStatusChanged(QMediaPlayer::InvalidMedia); } void S60MediaPlayerControl::pause() { if (m_session) m_session->pause(); } void S60MediaPlayerControl::stop() { if (m_session) m_session->stop(); } void S60MediaPlayerControl::setVolume(int volume) { m_controlSettings.m_vol = volume; if (m_session) m_session->setVolume(volume); } void S60MediaPlayerControl::setMuted(bool muted) { m_controlSettings.m_muted = muted; if (m_session) m_session->setMuted(muted); } QMediaContent S60MediaPlayerControl::media() const { return m_currentResource; } const QIODevice *S60MediaPlayerControl::mediaStream() const { return m_stream; } void S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream) { Q_UNUSED(stream) // we don't want to set & load media again when it is already loaded if (m_session && (m_currentResource == source) && m_session->state() == QMediaPlayer::LoadedMedia) { return; } // store to variable as session is created based on the content type. m_currentResource = source; if (m_session) { m_session->stop(); } m_session = currentPlayerSession(); QUrl url; if (!source.isNull() && m_session) { url = source.canonicalUri(); m_session->load(url); emit mediaChanged(m_currentResource); } else { emit mediaStatusChanged(QMediaPlayer::InvalidMedia); } } void S60MediaPlayerControl::setVideoOutput(QObject *output) { if (!m_session) m_session = m_mediaPlayerResolver.VideoPlayerSession(); m_session->setVideoRenderer(output); } bool S60MediaPlayerControl::isVideoAvailable() const { if (m_session) return m_session->isVideoAvailable(); return false; } S60MediaPlayerSession* S60MediaPlayerControl::currentPlayerSession() { return m_mediaPlayerResolver.PlayerSession(); } const S60MediaControlSettings& S60MediaPlayerControl::mediaControlSettings() const { return m_controlSettings; } <commit_msg>Added initializing m_stream with NULL.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediaplayercontrol.h" #include "s60mediaplayersession.h" #include <QMediaPlaylistNavigator> #include <QtCore/qdir.h> #include <QtCore/qsocketnotifier.h> #include <QtCore/qurl.h> #include <QtCore/qdebug.h> S60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent) : QMediaPlayerControl(parent), m_mediaPlayerResolver(mediaPlayerResolver), m_session(NULL), m_stream(NULL) { m_controlSettings.m_vol = -1; m_controlSettings.m_muted = false; m_controlSettings.m_playbackRate = -1; m_controlSettings.m_position = -1; } S60MediaPlayerControl::~S60MediaPlayerControl() { } qint64 S60MediaPlayerControl::position() const { if (m_session) return m_session->position(); return m_controlSettings.m_position; } qint64 S60MediaPlayerControl::duration() const { if (m_session) return m_session->duration(); return -1; } QMediaPlayer::State S60MediaPlayerControl::state() const { if (m_session) return m_session->state(); // we dont have a session -> state is stopped return QMediaPlayer::StoppedState; } QMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const { if (m_session) return m_session->mediaStatus(); return QMediaPlayer::NoMedia; } int S60MediaPlayerControl::bufferStatus() const { return -1; } int S60MediaPlayerControl::volume() const { if (m_session) return m_session->volume(); return m_controlSettings.m_vol; } bool S60MediaPlayerControl::isMuted() const { if (m_session) return m_session->isMuted(); return m_controlSettings.m_muted; } bool S60MediaPlayerControl::isSeekable() const { if (m_session) return m_session->isSeekable(); return m_controlSettings.m_position; } QPair<qint64, qint64> S60MediaPlayerControl::seekRange() const { if (m_session) { return q_check_ptr(m_session)->isSeekable() ? qMakePair<qint64, qint64>(0, m_session->duration()) : qMakePair<qint64, qint64>(0, 0); } return QPair<qint64, qint64>(); } qreal S60MediaPlayerControl::playbackRate() const { if (m_session) return m_session->playbackRate(); return -1; } void S60MediaPlayerControl::setPlaybackRate(qreal rate) { m_controlSettings.m_playbackRate = rate; if (m_session) m_session->setPlaybackRate(rate); } void S60MediaPlayerControl::setPosition(qint64 pos) { m_controlSettings.m_position = pos; if (m_session) m_session->setPosition(pos); } void S60MediaPlayerControl::play() { if (m_session) m_session->play(); else // to ensure that api know we can't play this emit mediaStatusChanged(QMediaPlayer::InvalidMedia); } void S60MediaPlayerControl::pause() { if (m_session) m_session->pause(); } void S60MediaPlayerControl::stop() { if (m_session) m_session->stop(); } void S60MediaPlayerControl::setVolume(int volume) { m_controlSettings.m_vol = volume; if (m_session) m_session->setVolume(volume); } void S60MediaPlayerControl::setMuted(bool muted) { m_controlSettings.m_muted = muted; if (m_session) m_session->setMuted(muted); } QMediaContent S60MediaPlayerControl::media() const { return m_currentResource; } const QIODevice *S60MediaPlayerControl::mediaStream() const { return m_stream; } void S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream) { Q_UNUSED(stream) // we don't want to set & load media again when it is already loaded if (m_session && (m_currentResource == source) && m_session->state() == QMediaPlayer::LoadedMedia) { return; } // store to variable as session is created based on the content type. m_currentResource = source; if (m_session) { m_session->stop(); } m_session = currentPlayerSession(); QUrl url; if (!source.isNull() && m_session) { url = source.canonicalUri(); m_session->load(url); emit mediaChanged(m_currentResource); } else { emit mediaStatusChanged(QMediaPlayer::InvalidMedia); } } void S60MediaPlayerControl::setVideoOutput(QObject *output) { if (!m_session) m_session = m_mediaPlayerResolver.VideoPlayerSession(); m_session->setVideoRenderer(output); } bool S60MediaPlayerControl::isVideoAvailable() const { if (m_session) return m_session->isVideoAvailable(); return false; } S60MediaPlayerSession* S60MediaPlayerControl::currentPlayerSession() { return m_mediaPlayerResolver.PlayerSession(); } const S60MediaControlSettings& S60MediaPlayerControl::mediaControlSettings() const { return m_controlSettings; } <|endoftext|>
<commit_before>/* Copyright 2012, 2013 Rogier van Dalen. This file is part of Rogier van Dalen's Mathematical tools library for C++. This library 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 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** \file Test std::numeric_limits <log_float <...>>. */ #define BOOST_TEST_MODULE log_float_limits #include "../boost_unit_test.hpp" #include "math/log-float.hpp" #include <limits> #include <boost/math/special_functions/fpclassify.hpp> BOOST_AUTO_TEST_SUITE(test_suite_log_float_limits) template <class LogFloat, class Underlying> void check_limits() { typedef std::numeric_limits <LogFloat> limits; typedef std::numeric_limits <Underlying> limits_underlying; /* Static properties. */ static_assert (limits::is_specialized, ""); static_assert (!limits::is_integer, ""); static_assert (!limits::is_exact, ""); static_assert (limits::has_infinity, ""); static_assert (limits::has_quiet_NaN, ""); static_assert (limits::has_signaling_NaN, ""); static_assert (limits::has_denorm == std::denorm_absent, ""); static_assert (!limits::has_denorm_loss, ""); static_assert (limits::round_style == std::round_to_nearest, ""); static_assert (!limits::is_iec559, ""); static_assert (limits::is_bounded, ""); static_assert (!limits::is_modulo, ""); static_assert (!limits::traps, ""); static_assert (!limits::tinyness_before, ""); /* Functions. */ // min. { auto min = limits::min(); std::cout << typeid (Underlying).name() << " " << min << std::endl; BOOST_CHECK (min > 0); BOOST_CHECK_EQUAL (min.exponent(), limits_underlying::lowest()); } { auto max = limits::max(); BOOST_CHECK (max > 0); BOOST_CHECK_EQUAL (max.exponent(), limits_underlying::max()); } { // 1+epsilon must have the smallest representable underlying float as // its exponent. auto epsilon = limits::epsilon(); decltype (epsilon) one = 1; auto one_plus_epsilon = one + epsilon; BOOST_CHECK_EQUAL (one_plus_epsilon.exponent(), limits_underlying::denorm_min()); } { auto infinity = limits::infinity(); BOOST_CHECK (infinity > 0); BOOST_CHECK_EQUAL (infinity.exponent(), limits_underlying::infinity()); } { auto quiet_NaN = limits::quiet_NaN(); BOOST_CHECK (!(quiet_NaN == quiet_NaN)); using namespace boost::math; BOOST_CHECK (isnan (quiet_NaN.exponent())); } { auto signaling_NaN = limits::signaling_NaN(); BOOST_CHECK (!(signaling_NaN == signaling_NaN)); using namespace boost::math; BOOST_CHECK (isnan (signaling_NaN.exponent())); } /* Not tested because they are not meaningfully implemented: digits, digits10, max_digits10, radix min_exponent, min_exponent10, max_exponent, max_exponent10 round_error(), denorm_min() */ } template <class LogFloat, class Underlying> void check_limits_unsigned() { check_limits <LogFloat, Underlying>(); typedef std::numeric_limits <LogFloat> limits; static_assert (!limits::is_signed, ""); BOOST_CHECK_EQUAL (limits::lowest(), limits::min()); } template <class LogFloat, class Underlying> void check_limits_signed() { check_limits <LogFloat, Underlying>(); typedef std::numeric_limits <LogFloat> limits; static_assert (limits::is_signed, ""); BOOST_CHECK_EQUAL (limits::lowest(), -limits::max()); } BOOST_AUTO_TEST_CASE (test_log_float_limits) { check_limits_unsigned <math::log_float <float>, float>(); check_limits_unsigned <math::log_float <double> const, double>(); check_limits_unsigned <math::log_float <double> &, double>(); check_limits_unsigned <math::log_float <double> const &, double>(); check_limits_signed <math::signed_log_float <float>, float>(); check_limits_signed <math::signed_log_float <double> const &, double>(); check_limits_signed <math::signed_log_float <double> &&, double>(); // long double does not work under Valgrind. // check_limits_signed < // math::signed_log_float <long double>, long double>(); // check_limits_signed < // math::signed_log_float <long double> const &, long double>(); using namespace boost::math::policies; typedef policy <domain_error <errno_on_error>, overflow_error <errno_on_error>> other_policy; check_limits_unsigned <math::log_float <float, other_policy>, float>(); check_limits_unsigned <math::log_float <double, other_policy> &, double>(); check_limits_signed <math::signed_log_float <float, other_policy>, float>(); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Fix log-float test<commit_after>/* Copyright 2012, 2013 Rogier van Dalen. This file is part of Rogier van Dalen's Mathematical tools library for C++. This library 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 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** \file Test std::numeric_limits <log_float <...>>. */ #define BOOST_TEST_MODULE log_float_limits #include "../boost_unit_test.hpp" #include "math/log-float.hpp" #include <limits> #include <boost/math/special_functions/fpclassify.hpp> BOOST_AUTO_TEST_SUITE(test_suite_log_float_limits) template <class LogFloat, class Underlying> void check_limits() { typedef std::numeric_limits <LogFloat> limits; typedef std::numeric_limits <Underlying> limits_underlying; /* Static properties. */ static_assert (limits::is_specialized, ""); static_assert (!limits::is_integer, ""); static_assert (!limits::is_exact, ""); static_assert (limits::has_infinity, ""); static_assert (limits::has_quiet_NaN, ""); static_assert (limits::has_signaling_NaN, ""); static_assert (limits::has_denorm == std::denorm_absent, ""); static_assert (!limits::has_denorm_loss, ""); static_assert (limits::round_style == std::round_to_nearest, ""); static_assert (!limits::is_iec559, ""); static_assert (limits::is_bounded, ""); static_assert (!limits::is_modulo, ""); static_assert (!limits::traps, ""); static_assert (!limits::tinyness_before, ""); /* Functions. */ // min. { auto min = limits::min(); BOOST_CHECK (min > 0); BOOST_CHECK_EQUAL (min.exponent(), limits_underlying::lowest()); } { auto max = limits::max(); BOOST_CHECK (max > 0); BOOST_CHECK_EQUAL (max.exponent(), limits_underlying::max()); } { // 1+epsilon must have the smallest representable underlying float as // its exponent. auto epsilon = limits::epsilon(); decltype (epsilon) one = 1; auto one_plus_epsilon = one + epsilon; BOOST_CHECK_EQUAL (one_plus_epsilon.exponent(), limits_underlying::denorm_min()); } { auto infinity = limits::infinity(); BOOST_CHECK (infinity > 0); BOOST_CHECK_EQUAL (infinity.exponent(), limits_underlying::infinity()); } { auto quiet_NaN = limits::quiet_NaN(); BOOST_CHECK (!(quiet_NaN == quiet_NaN)); using namespace boost::math; BOOST_CHECK (isnan (quiet_NaN.exponent())); } { auto signaling_NaN = limits::signaling_NaN(); BOOST_CHECK (!(signaling_NaN == signaling_NaN)); using namespace boost::math; BOOST_CHECK (isnan (signaling_NaN.exponent())); } /* Not tested because they are not meaningfully implemented: digits, digits10, max_digits10, radix min_exponent, min_exponent10, max_exponent, max_exponent10 round_error(), denorm_min() */ } template <class LogFloat, class Underlying> void check_limits_unsigned() { check_limits <LogFloat, Underlying>(); typedef std::numeric_limits <LogFloat> limits; static_assert (!limits::is_signed, ""); BOOST_CHECK_EQUAL (limits::lowest(), limits::min()); } template <class LogFloat, class Underlying> void check_limits_signed() { check_limits <LogFloat, Underlying>(); typedef std::numeric_limits <LogFloat> limits; static_assert (limits::is_signed, ""); BOOST_CHECK_EQUAL (limits::lowest(), -limits::max()); } BOOST_AUTO_TEST_CASE (test_log_float_limits) { check_limits_unsigned <math::log_float <float>, float>(); check_limits_unsigned <math::log_float <double> const, double>(); check_limits_unsigned <math::log_float <double> &, double>(); check_limits_unsigned <math::log_float <double> const &, double>(); check_limits_signed <math::signed_log_float <float>, float>(); check_limits_signed <math::signed_log_float <double> const &, double>(); check_limits_signed <math::signed_log_float <double> &&, double>(); // long double does not work under Valgrind. // check_limits_signed < // math::signed_log_float <long double>, long double>(); // check_limits_signed < // math::signed_log_float <long double> const &, long double>(); using namespace boost::math::policies; typedef policy <domain_error <errno_on_error>, overflow_error <errno_on_error>> other_policy; check_limits_unsigned <math::log_float <float, other_policy>, float>(); check_limits_unsigned <math::log_float <double, other_policy> &, double>(); check_limits_signed <math::signed_log_float <float, other_policy>, float>(); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// // Copyright 2013 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "../far/stencilTablesFactory.h" #include "../far/patchTablesFactory.h" #include "../far/patchMap.h" #include "../far/protoStencil.h" #include "../far/topologyRefiner.h" #include <cassert> #include <algorithm> namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { namespace Far { //------------------------------------------------------------------------------ void StencilTablesFactory::generateControlVertStencils( int numControlVerts, Stencil & dst) { // Control vertices contribute a single index with a weight of 1.0 for (int i=0; i<numControlVerts; ++i) { *dst._size = 1; *dst._indices = i; *dst._weights = 1.0f; dst.Next(); } } // // StencilTables factory // StencilTables const * StencilTablesFactory::Create(TopologyRefiner const & refiner, Options options) { StencilTables * result = new StencilTables; int maxlevel = std::min(int(options.maxLevel), refiner.GetMaxLevel()); if (maxlevel==0) { return result; } // maxsize reflects the size of the default supporting basis factorized // in the stencils, with a little bit of head-room. Each subdivision scheme // has a set valence for 'regular' vertices, which drives the size of the // supporting basis of control-vertices. The goal is to reduce the number // of incidences where the pool allocator has to switch to dynamically // allocated heap memory when encountering extraordinary vertices that // require a larger supporting basis. // // The maxsize settings we use follow the assumption that the vast // majority of the vertices in a mesh are regular, and that the valence // of the extraordinary vertices is only higher by 1 edge. int maxsize = 0; bool interpolateVarying = false; switch (options.interpolationMode) { case INTERPOLATE_VERTEX: { Sdc::Type type = refiner.GetSchemeType(); switch (type) { case Sdc::TYPE_BILINEAR : maxsize = 5; break; case Sdc::TYPE_CATMARK : maxsize = 17; break; case Sdc::TYPE_LOOP : maxsize = 10; break; default: assert(0); } } break; case INTERPOLATE_VARYING: maxsize = 5; interpolateVarying=true; break; default: assert(0); } std::vector<StencilAllocator> allocators( options.generateIntermediateLevels ? maxlevel+1 : 2, StencilAllocator(maxsize, interpolateVarying)); StencilAllocator * srcAlloc = &allocators[0], * dstAlloc = &allocators[1]; /// // Interpolate stencils for each refinement level using // TopologyRefiner::InterpolateLevel<>() // for (int level=1;level<=maxlevel; ++level) { dstAlloc->Resize(refiner.GetNumVertices(level)); if (options.interpolationMode==INTERPOLATE_VERTEX) { refiner.Interpolate(level, *srcAlloc, *dstAlloc); } else { refiner.InterpolateVarying(level, *srcAlloc, *dstAlloc); } if (options.generateIntermediateLevels) { if (level<maxlevel) { if (options.factorizeIntermediateLevels) { srcAlloc = &allocators[level]; } else { // if the stencils are dependent on the previous level of // subdivision, pass an empty allocator to treat all parent // vertices as control vertices assert(allocators[0].GetNumStencils()==0); } dstAlloc = &allocators[level+1]; } } else { std::swap(srcAlloc, dstAlloc); } } // Copy stencils from the pool allocator into the tables { // Add total number of stencils, weights & indices int nelems = 0, nstencils=0; if (options.generateIntermediateLevels) { for (int level=0; level<=maxlevel; ++level) { nstencils += allocators[level].GetNumStencils(); nelems += allocators[level].GetNumVerticesTotal(); } } else { nstencils = (int)srcAlloc->GetNumStencils(); nelems = srcAlloc->GetNumVerticesTotal(); } // Allocate result->_numControlVertices = refiner.GetNumVertices(0); if (options.generateControlVerts) { nstencils += result->_numControlVertices; nelems += result->_numControlVertices; } result->resize(nstencils, nelems); // Copy stencils Stencil dst(&result->_sizes.at(0), &result->_indices.at(0), &result->_weights.at(0)); if (options.generateControlVerts) { generateControlVertStencils(result->_numControlVertices, dst); } if (options.generateIntermediateLevels) { for (int level=1; level<=maxlevel; ++level) { for (int i=0; i<allocators[level].GetNumStencils(); ++i) { *dst._size = allocators[level].CopyStencil(i, dst._indices, dst._weights); dst.Next(); } } } else { for (int i=0; i<srcAlloc->GetNumStencils(); ++i) { *dst._size = srcAlloc->CopyStencil(i, dst._indices, dst._weights); dst.Next(); } } if (options.generateOffsets) { result->generateOffsets(); } } return result; } //------------------------------------------------------------------------------ StencilTables const * StencilTablesFactory::Create(int numTables, StencilTables const ** tables) { StencilTables * result = new StencilTables; if ( (numTables<=0) or (not tables)) { return result; } int ncvs = tables[0]->GetNumControlVertices(), nstencils = 0, nelems = 0; for (int i=0; i<numTables; ++i) { StencilTables const & st = *tables[i]; if (st.GetNumControlVertices()!=ncvs) { return result; } nstencils += st.GetNumStencils(); nelems += (int)st.GetControlIndices().size(); } result->resize(nstencils, nelems); result->_numControlVertices = ncvs; Index * indices = &result->_indices[0]; float * weights = &result->_weights[0]; for (int i=0; i<numTables; ++i) { StencilTables const & st = *tables[i]; int size = (int)st._indices.size(); memcpy(indices, &st._indices[0], size*sizeof(Index)); memcpy(weights, &st._weights[0], size*sizeof(float)); indices += size; weights += size; } // have to re-generate offsets from scratch result->generateOffsets(); return result; } //------------------------------------------------------------------------------ LimitStencilTables const * LimitStencilTablesFactory::Create(TopologyRefiner const & refiner, LocationArrayVec const & locationArrays, StencilTables const * cvStencils, PatchTables const * patchTables) { // Compute the total number of stencils to generate int numStencils=0, numLimitStencils=0; for (int i=0; i<(int)locationArrays.size(); ++i) { assert(locationArrays[i].numLocations>=0); numStencils += locationArrays[i].numLocations; } if (numStencils<=0) { return 0; } bool uniform = refiner.IsUniform(); int maxlevel = refiner.GetMaxLevel(), maxsize=17; StencilTables const * cvstencils = cvStencils; if (not cvstencils) { // Generate stencils for the control vertices - this is necessary to // properly factorize patches with control vertices at level 0 (natural // regular patches, such as in a torus) // note: the control vertices of the mesh are added as single-index // stencils of weight 1.0f StencilTablesFactory::Options options; options.generateIntermediateLevels = uniform ? false :true; options.generateControlVerts = true; options.generateOffsets = true; // XXXX (manuelk) We could potentially save some mem-copies by not // instanciating the stencil tables and work directly off the pool // allocators. cvstencils = StencilTablesFactory::Create(refiner, options); } else { // Sanity checks if (cvstencils->GetNumStencils() != (uniform ? refiner.GetNumVertices(maxlevel) : refiner.GetNumVerticesTotal())) { return 0; } } // If a stencil table was given, use it, otherwise, create a new one PatchTables const * patchtables = patchTables; if (not patchTables) { // XXXX (manuelk) If no patch-tables was passed, we should be able to // infer the patches fairly easily from the refiner. Once more tags // have been added to the refiner, maybe we can remove the need for the // patch tables. OpenSubdiv::Far::PatchTablesFactory::Options options; options.adaptiveStencilTables = cvstencils; patchtables = PatchTablesFactory::Create(refiner, options); } else { // Sanity checks if (patchTables->IsFeatureAdaptive()==uniform) { if (not cvStencils) { assert(cvstencils and cvstencils!=cvStencils); delete cvstencils; } return 0; } } assert(patchtables and cvstencils); // Create a patch-map to locate sub-patches faster PatchMap patchmap( *patchtables ); // // Generate limit stencils for locations // // Create a pool allocator to accumulate ProtoLimitStencils LimitStencilAllocator alloc(maxsize); alloc.Resize(numStencils); // XXXX (manuelk) we can make uniform (bilinear) stencils faster with a // dedicated code path that does not use PatchTables or the PatchMap for (int i=0, currentStencil=0; i<(int)locationArrays.size(); ++i) { LocationArray const & array = locationArrays[i]; assert(array.ptexIdx>=0); for (int j=0; j<array.numLocations; ++j, ++currentStencil) { float s = array.s[j], t = array.t[j]; PatchMap::Handle const * handle = patchmap.FindPatch(array.ptexIdx, s, t); if (handle) { ProtoLimitStencil dst = alloc[currentStencil]; if (uniform) { patchtables->Interpolate(*handle, s, t, *cvstencils, dst); } else { patchtables->Limit(*handle, s, t, *cvstencils, dst); } ++numLimitStencils; } } } if (not cvStencils) { delete cvstencils; } // // Copy the proto-stencils into the limit stencil tables // LimitStencilTables * result = new LimitStencilTables; int nelems = alloc.GetNumVerticesTotal(); if (nelems>0) { // Allocate result->resize(numLimitStencils, nelems); // Copy stencils LimitStencil dst(&result->_sizes.at(0), &result->_indices.at(0), &result->_weights.at(0), &result->_duWeights.at(0), &result->_dvWeights.at(0)); for (int i=0; i<alloc.GetNumStencils(); ++i) { *dst._size = alloc.CopyLimitStencil(i, dst._indices, dst._weights, dst._duWeights, dst._dvWeights); dst.Next(); } // XXXX manuelk should offset creation be optional ? result->generateOffsets(); } result->_numControlVertices = refiner.GetNumVertices(0); return result; } //------------------------------------------------------------------------------ KernelBatch StencilTablesFactory::Create(StencilTables const &stencilTables) { return KernelBatch( KernelBatch::KERNEL_STENCIL_TABLE, -1, 0, stencilTables.GetNumStencils()); } } // end namespace Far } // end namespace OPENSUBDIV_VERSION } // end namespace OpenSubdiv <commit_msg>Fix Far::StencilTablesFactory tables concatenation operator<commit_after>// // Copyright 2013 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "../far/stencilTablesFactory.h" #include "../far/patchTablesFactory.h" #include "../far/patchMap.h" #include "../far/protoStencil.h" #include "../far/topologyRefiner.h" #include <cassert> #include <algorithm> namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { namespace Far { //------------------------------------------------------------------------------ void StencilTablesFactory::generateControlVertStencils( int numControlVerts, Stencil & dst) { // Control vertices contribute a single index with a weight of 1.0 for (int i=0; i<numControlVerts; ++i) { *dst._size = 1; *dst._indices = i; *dst._weights = 1.0f; dst.Next(); } } // // StencilTables factory // StencilTables const * StencilTablesFactory::Create(TopologyRefiner const & refiner, Options options) { StencilTables * result = new StencilTables; int maxlevel = std::min(int(options.maxLevel), refiner.GetMaxLevel()); if (maxlevel==0) { return result; } // maxsize reflects the size of the default supporting basis factorized // in the stencils, with a little bit of head-room. Each subdivision scheme // has a set valence for 'regular' vertices, which drives the size of the // supporting basis of control-vertices. The goal is to reduce the number // of incidences where the pool allocator has to switch to dynamically // allocated heap memory when encountering extraordinary vertices that // require a larger supporting basis. // // The maxsize settings we use follow the assumption that the vast // majority of the vertices in a mesh are regular, and that the valence // of the extraordinary vertices is only higher by 1 edge. int maxsize = 0; bool interpolateVarying = false; switch (options.interpolationMode) { case INTERPOLATE_VERTEX: { Sdc::Type type = refiner.GetSchemeType(); switch (type) { case Sdc::TYPE_BILINEAR : maxsize = 5; break; case Sdc::TYPE_CATMARK : maxsize = 17; break; case Sdc::TYPE_LOOP : maxsize = 10; break; default: assert(0); } } break; case INTERPOLATE_VARYING: maxsize = 5; interpolateVarying=true; break; default: assert(0); } std::vector<StencilAllocator> allocators( options.generateIntermediateLevels ? maxlevel+1 : 2, StencilAllocator(maxsize, interpolateVarying)); StencilAllocator * srcAlloc = &allocators[0], * dstAlloc = &allocators[1]; /// // Interpolate stencils for each refinement level using // TopologyRefiner::InterpolateLevel<>() // for (int level=1;level<=maxlevel; ++level) { dstAlloc->Resize(refiner.GetNumVertices(level)); if (options.interpolationMode==INTERPOLATE_VERTEX) { refiner.Interpolate(level, *srcAlloc, *dstAlloc); } else { refiner.InterpolateVarying(level, *srcAlloc, *dstAlloc); } if (options.generateIntermediateLevels) { if (level<maxlevel) { if (options.factorizeIntermediateLevels) { srcAlloc = &allocators[level]; } else { // if the stencils are dependent on the previous level of // subdivision, pass an empty allocator to treat all parent // vertices as control vertices assert(allocators[0].GetNumStencils()==0); } dstAlloc = &allocators[level+1]; } } else { std::swap(srcAlloc, dstAlloc); } } // Copy stencils from the pool allocator into the tables { // Add total number of stencils, weights & indices int nelems = 0, nstencils=0; if (options.generateIntermediateLevels) { for (int level=0; level<=maxlevel; ++level) { nstencils += allocators[level].GetNumStencils(); nelems += allocators[level].GetNumVerticesTotal(); } } else { nstencils = (int)srcAlloc->GetNumStencils(); nelems = srcAlloc->GetNumVerticesTotal(); } // Allocate result->_numControlVertices = refiner.GetNumVertices(0); if (options.generateControlVerts) { nstencils += result->_numControlVertices; nelems += result->_numControlVertices; } result->resize(nstencils, nelems); // Copy stencils Stencil dst(&result->_sizes.at(0), &result->_indices.at(0), &result->_weights.at(0)); if (options.generateControlVerts) { generateControlVertStencils(result->_numControlVertices, dst); } if (options.generateIntermediateLevels) { for (int level=1; level<=maxlevel; ++level) { for (int i=0; i<allocators[level].GetNumStencils(); ++i) { *dst._size = allocators[level].CopyStencil(i, dst._indices, dst._weights); dst.Next(); } } } else { for (int i=0; i<srcAlloc->GetNumStencils(); ++i) { *dst._size = srcAlloc->CopyStencil(i, dst._indices, dst._weights); dst.Next(); } } if (options.generateOffsets) { result->generateOffsets(); } } return result; } //------------------------------------------------------------------------------ StencilTables const * StencilTablesFactory::Create(int numTables, StencilTables const ** tables) { StencilTables * result = new StencilTables; if ( (numTables<=0) or (not tables)) { return result; } int ncvs = tables[0]->GetNumControlVertices(), nstencils = 0, nelems = 0; for (int i=0; i<numTables; ++i) { StencilTables const & st = *tables[i]; if (st.GetNumControlVertices()!=ncvs) { return result; } nstencils += st.GetNumStencils(); nelems += (int)st.GetControlIndices().size(); } result->resize(nstencils, nelems); unsigned char * sizes = &result->_sizes[0]; Index * indices = &result->_indices[0]; float * weights = &result->_weights[0]; for (int i=0; i<numTables; ++i) { StencilTables const & st = *tables[i]; int nstencils = st.GetNumStencils(), nelems = (int)st._indices.size(); memcpy(sizes, &st._sizes[0], nstencils*sizeof(unsigned char)); memcpy(indices, &st._indices[0], nelems*sizeof(Index)); memcpy(weights, &st._weights[0], nelems*sizeof(float)); sizes += nstencils; indices += nelems; weights += nelems; } result->_numControlVertices = ncvs; // have to re-generate offsets from scratch result->generateOffsets(); return result; } //------------------------------------------------------------------------------ LimitStencilTables const * LimitStencilTablesFactory::Create(TopologyRefiner const & refiner, LocationArrayVec const & locationArrays, StencilTables const * cvStencils, PatchTables const * patchTables) { // Compute the total number of stencils to generate int numStencils=0, numLimitStencils=0; for (int i=0; i<(int)locationArrays.size(); ++i) { assert(locationArrays[i].numLocations>=0); numStencils += locationArrays[i].numLocations; } if (numStencils<=0) { return 0; } bool uniform = refiner.IsUniform(); int maxlevel = refiner.GetMaxLevel(), maxsize=17; StencilTables const * cvstencils = cvStencils; if (not cvstencils) { // Generate stencils for the control vertices - this is necessary to // properly factorize patches with control vertices at level 0 (natural // regular patches, such as in a torus) // note: the control vertices of the mesh are added as single-index // stencils of weight 1.0f StencilTablesFactory::Options options; options.generateIntermediateLevels = uniform ? false :true; options.generateControlVerts = true; options.generateOffsets = true; // XXXX (manuelk) We could potentially save some mem-copies by not // instanciating the stencil tables and work directly off the pool // allocators. cvstencils = StencilTablesFactory::Create(refiner, options); } else { // Sanity checks if (cvstencils->GetNumStencils() != (uniform ? refiner.GetNumVertices(maxlevel) : refiner.GetNumVerticesTotal())) { return 0; } } // If a stencil table was given, use it, otherwise, create a new one PatchTables const * patchtables = patchTables; if (not patchTables) { // XXXX (manuelk) If no patch-tables was passed, we should be able to // infer the patches fairly easily from the refiner. Once more tags // have been added to the refiner, maybe we can remove the need for the // patch tables. OpenSubdiv::Far::PatchTablesFactory::Options options; options.adaptiveStencilTables = cvstencils; patchtables = PatchTablesFactory::Create(refiner, options); } else { // Sanity checks if (patchTables->IsFeatureAdaptive()==uniform) { if (not cvStencils) { assert(cvstencils and cvstencils!=cvStencils); delete cvstencils; } return 0; } } assert(patchtables and cvstencils); // Create a patch-map to locate sub-patches faster PatchMap patchmap( *patchtables ); // // Generate limit stencils for locations // // Create a pool allocator to accumulate ProtoLimitStencils LimitStencilAllocator alloc(maxsize); alloc.Resize(numStencils); // XXXX (manuelk) we can make uniform (bilinear) stencils faster with a // dedicated code path that does not use PatchTables or the PatchMap for (int i=0, currentStencil=0; i<(int)locationArrays.size(); ++i) { LocationArray const & array = locationArrays[i]; assert(array.ptexIdx>=0); for (int j=0; j<array.numLocations; ++j, ++currentStencil) { float s = array.s[j], t = array.t[j]; PatchMap::Handle const * handle = patchmap.FindPatch(array.ptexIdx, s, t); if (handle) { ProtoLimitStencil dst = alloc[currentStencil]; if (uniform) { patchtables->Interpolate(*handle, s, t, *cvstencils, dst); } else { patchtables->Limit(*handle, s, t, *cvstencils, dst); } ++numLimitStencils; } } } if (not cvStencils) { delete cvstencils; } // // Copy the proto-stencils into the limit stencil tables // LimitStencilTables * result = new LimitStencilTables; int nelems = alloc.GetNumVerticesTotal(); if (nelems>0) { // Allocate result->resize(numLimitStencils, nelems); // Copy stencils LimitStencil dst(&result->_sizes.at(0), &result->_indices.at(0), &result->_weights.at(0), &result->_duWeights.at(0), &result->_dvWeights.at(0)); for (int i=0; i<alloc.GetNumStencils(); ++i) { *dst._size = alloc.CopyLimitStencil(i, dst._indices, dst._weights, dst._duWeights, dst._dvWeights); dst.Next(); } // XXXX manuelk should offset creation be optional ? result->generateOffsets(); } result->_numControlVertices = refiner.GetNumVertices(0); return result; } //------------------------------------------------------------------------------ KernelBatch StencilTablesFactory::Create(StencilTables const &stencilTables) { return KernelBatch( KernelBatch::KERNEL_STENCIL_TABLE, -1, 0, stencilTables.GetNumStencils()); } } // end namespace Far } // end namespace OPENSUBDIV_VERSION } // end namespace OpenSubdiv <|endoftext|>
<commit_before>/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/base/fakeclock.h" #include "webrtc/base/gunit.h" #include "webrtc/base/profiler.h" #include "webrtc/base/timedelta.h" #include "webrtc/base/thread.h" namespace { const int kWaitMs = 250; const double kWaitSec = 0.250; const char* TestFunc(rtc::FakeClock* clock) { PROFILE_F(); clock->AdvanceTime(rtc::TimeDelta::FromMilliseconds(kWaitMs)); return __FUNCTION__; } } // namespace namespace rtc { TEST(ProfilerTest, TestFunction) { rtc::ScopedFakeClock fake_clock; ASSERT_TRUE(Profiler::Instance()->Clear()); // Profile a long-running function. const char* function_name = TestFunc(&fake_clock); const ProfilerEvent* event = Profiler::Instance()->GetEvent(function_name); ASSERT_TRUE(event != NULL); EXPECT_FALSE(event->is_started()); EXPECT_EQ(1, event->event_count()); EXPECT_EQ(kWaitSec, event->mean()); // Run it a second time. TestFunc(&fake_clock); EXPECT_FALSE(event->is_started()); EXPECT_EQ(2, event->event_count()); EXPECT_EQ(kWaitSec, event->mean()); EXPECT_EQ(kWaitSec * 2, event->total_time()); EXPECT_DOUBLE_EQ(event->mean(), event->total_time() / event->event_count()); } TEST(ProfilerTest, TestScopedEvents) { rtc::ScopedFakeClock fake_clock; const std::string kEvent1Name = "Event 1"; const std::string kEvent2Name = "Event 2"; const int kEvent2WaitMs = 150; const double kEvent2WaitSec = 0.150; const ProfilerEvent* event1; const ProfilerEvent* event2; ASSERT_TRUE(Profiler::Instance()->Clear()); { // Profile a scope. PROFILE(kEvent1Name); event1 = Profiler::Instance()->GetEvent(kEvent1Name); ASSERT_TRUE(event1 != NULL); EXPECT_TRUE(event1->is_started()); EXPECT_EQ(0, event1->event_count()); fake_clock.AdvanceTime(rtc::TimeDelta::FromMilliseconds(kWaitMs)); EXPECT_TRUE(event1->is_started()); } // Check the result. EXPECT_FALSE(event1->is_started()); EXPECT_EQ(1, event1->event_count()); EXPECT_EQ(kWaitSec, event1->mean()); { // Profile a second event. PROFILE(kEvent2Name); event2 = Profiler::Instance()->GetEvent(kEvent2Name); ASSERT_TRUE(event2 != NULL); EXPECT_FALSE(event1->is_started()); EXPECT_TRUE(event2->is_started()); fake_clock.AdvanceTime(rtc::TimeDelta::FromMilliseconds(kEvent2WaitMs)); } // Check the result. EXPECT_FALSE(event2->is_started()); EXPECT_EQ(1, event2->event_count()); EXPECT_EQ(kEvent2WaitSec, event2->mean()); // Make sure event1 is unchanged. EXPECT_FALSE(event1->is_started()); EXPECT_EQ(1, event1->event_count()); { // Run another event 1. PROFILE(kEvent1Name); EXPECT_TRUE(event1->is_started()); fake_clock.AdvanceTime(rtc::TimeDelta::FromMilliseconds(kWaitMs)); } // Check the result. EXPECT_FALSE(event1->is_started()); EXPECT_EQ(2, event1->event_count()); EXPECT_EQ(kWaitSec, event1->mean()); EXPECT_EQ(kWaitSec * 2, event1->total_time()); EXPECT_DOUBLE_EQ(event1->mean(), event1->total_time() / event1->event_count()); } TEST(ProfilerTest, Clear) { ASSERT_TRUE(Profiler::Instance()->Clear()); PROFILE_START("event"); EXPECT_FALSE(Profiler::Instance()->Clear()); EXPECT_TRUE(Profiler::Instance()->GetEvent("event") != NULL); PROFILE_STOP("event"); EXPECT_TRUE(Profiler::Instance()->Clear()); EXPECT_EQ(NULL, Profiler::Instance()->GetEvent("event")); } } // namespace rtc <commit_msg>Delete left-over file profiler_unittest.cc.<commit_after><|endoftext|>
<commit_before>#include "Utility.h" double EPSILON = 10e-15; // probabilities smaller than this are treated as zero /*! * @function generate Truncated poisson distribution * @abstract bla bla * @discussion Use HMBalloonRect to get information about the size of a help balloon * before the Help Manager displays it. * @param lambda * @param min sd * @param max */ // generate a truncated poisson distribution long double poisson_pmf(double lambda, int k) { long double a = expl(-lambda); long double b = powl((long double) lambda,k); long double c = factorial(k); return a * b / c; } vector<double> gen_trunc_poisson(double lambda, int min, int max) { vector<double> dist(max + 1, 0.0);//initializes distribution to all 0 double sum = 0.0; if (lambda < 500) { for (int k = lambda; k >= min; k--) { dist[k] = poisson_pmf(lambda, k); sum += dist[k]; if ( dist[k]/sum < EPSILON) break; } for (int k = lambda + 1; k <= max; k++) { dist[k] = poisson_pmf(lambda, k); sum += dist[k]; if ( dist[k]/sum < EPSILON) { dist.resize(k + 1); break; } } } else { // use a normal approximation, avoiding the factorial and pow calculations // by starting 9 SD's above lambda, we should capture all densities greater than EPSILON int prob_max = lambda + 9 * sqrt(lambda); max = MIN(max, prob_max); dist.resize(max + 1); for (int k = max; k >= min; k--) { dist[k] = normal_cdf(k + 0.5, lambda, lambda); // 0.5 is a continuity correction if ( k < max ) { dist[k+1] -= dist[k]; sum += dist[k+1]; } if ( k < lambda and dist[k+1] < EPSILON) { dist[k] = 0; break; } } } return normalize_dist(dist, sum); } // generate a truncated, discretized powerlaw distribution (= zeta dist?) vector<double> gen_trunc_powerlaw(double alpha, double kappa, int min, int max) { vector<double> dist(max + 1); double sum = 0; for (int k = min; k <= max; k++) { double pk = powl(k, (long double) -alpha) * expl(-k/(long double) kappa); dist[k] = pk; sum += pk; if (pk/sum < EPSILON) break; } // Norm the distribution return normalize_dist(dist, sum); } vector<double> gen_trunc_exponential(double lambda, int min, int max) { vector<double> dist(max + 1); double sum = 0; for (int k = min; k <= max; k++) { double pk = lambda * exp(-lambda * k); dist[k] = pk; sum += pk; if (pk/sum < EPSILON) break; } // Norm the distribution return normalize_dist(dist, sum); } vector<double> normalize_dist(vector<double> dist, double sum) { for (unsigned int i = 1; i < dist.size(); i++) dist[i] = dist[i] / sum; return dist; } vector<double> normalize_dist(vector<int> old_dist, int sum) { vector<double> dist(old_dist.size()); for (unsigned int i = 1; i < dist.size(); i++) dist[i] = ((double) old_dist[i]) / sum; return dist; } int rand_nonuniform_int(vector<double> dist, MTRand* mtrand) { //assert(sum(dist) == 1); // why doesn't this work? double last = 0; double rand = mtrand->rand(); for (unsigned int i = 0; i < dist.size(); i++ ) { double current = last + dist[i]; if ( rand <= current ) { return i; } else { last = current; } } if (last != 1) { cerr << "rand_uniform_integer() expects a normed distribution. " << "Your probabilities sum to " << setprecision(15) << last << ". Fix this using Utilities::normalize_dist()\n"; exit(1); } return -1; } double rand_exp(double lambda, MTRand* mtrand) { return -log(mtrand->rand()) / lambda; } // N is the size of the sample space--which includes 0, so the int "N" itself will never get // returned in the sample. sample is an empty vector that needs to be of size k; mtrand // is a Mersenne Twister RNG. void rand_nchoosek(int N, vector<int>& sample, MTRand* mtrand) { if (sample.size() == 0 ) return; int k = sample.size(); // k is specified by size of requested vector assert( k <= N ); int top = N-k; double Nreal = (double) N; int newidx=0; int lastidx=0; int i=0; while ( k >= 2 ) { double V = mtrand->rand(); int S=0; double quot = top/Nreal; while( quot > V ) { S++; top-=1; Nreal-=1; quot =(quot*top)/Nreal; } //skip over the next S records and select the following one for the sample newidx = lastidx + S; sample[i]=newidx; lastidx = newidx+1; i++; Nreal -= 1.0; k -= 1; } if ( k == 1 ) { // the following line had (newidx+1) instead of lastidx before, which // produced incorrect results when N == 1; this, I believe, is correct sample[i++] = lastidx + (int) mtrand->rand( (int) Nreal ); } } double normal_pdf(double x, double mu, double var) { long double PI = 3.1415926535897932384; return exp(-pow(x-mu,2) / 2.0*var) / sqrt(2*PI*var); } double normal_cdf(double x, double mu, double var) { x = (x-mu)/sqrt(var); // Abramowitz & Stegun (1964) approximation long double b0 = 0.2316419; double b1 = 0.319381530; double b2 = -0.356563782; double b3 = 1.781477937; double b4 = -1.821255978; double b5 = 1.330274429; if (x >= 0.0) { long double t = 1.0/(1.0+b0*x); return 1.0 - normal_pdf(x, 0, 1)*(b1*t + b2*pow(t,2) + b3*pow(t,3) + b4*pow(t,4) + b5*pow(t,5)); } else { long double t = 1.0/(1.0-b0*x); return normal_pdf(x, 0, 1)*(b1*t + b2*pow(t,2) + b3*pow(t,3) + b4*pow(t,4) + b5*pow(t,5)); } } /* double sum(vector<double> list) { double sum = 0; for (int i = 0; i < list.size(); i++) { sum += list[i]; } return sum; } int sum(vector<int> list) { int sum = 0; for (int i = 0; i < list.size(); i++) { sum += list[i]; } return sum; } template <typename T> T sum(vector<T> list) { T sum = 0; for (int i = 0; i < list.size(); i++) { sum += list[i]; } return sum; } template <typename T> double mean(vector<T> list) { return (double) sum(list) / list.size(); }*/ long double factorial(int num) { assert( num > -1); if (num == 0) return 1; // definition of 0! long double result = 0.0;//log(1); for (int i = 1; i <= num; i++) result = result + logl((long double) i); return expl(result); } int max_element(vector<int> list) { int element = list[0]; for (unsigned int i = 0; i < list.size(); i++) { element = max(element, list[i]); } return element; } std::string strip ( std::string const& str, char const* sepSet) { std::string::size_type const first = str.find_first_not_of(sepSet); return ( first==std::string::npos ) ? std::string() : str.substr(first, str.find_last_not_of(sepSet)-first+1); } void split(const string& s, char c, vector<string>& v) { string::size_type i = 0; string::size_type j = s.find(c); while (j != string::npos) { v.push_back(s.substr(i, j-i)); i = ++j; j = s.find(c, j); if (j == string::npos) v.push_back(s.substr(i, s.length( ))); } } /* // initialize random seed: void seed_rand() { if (called_seed) return; srand ( time(NULL) ); long seed1 = rand(); long seed2 = rand(); setall(seed1,seed2); called_seed = true; }*/ /* public static void shuffle (int[] array) { Random rng = new Random(); // i.e., java.util.Random. int n = array.length; // The number of items left to shuffle (loop invariant). while (n > 1) { int k = rng.nextInt(n); // 0 <= k < n. --n; // n is now the last pertinent index; int temp = array[n]; // swap array[n] with array[k]. array[n] = array[k]; array[k] = temp; } } */ <commit_msg>Changed split() behavior, added parameter validation<commit_after>#include "Utility.h" double EPSILON = 10e-15; // probabilities smaller than this are treated as zero /*! * @function generate Truncated poisson distribution * @abstract bla bla * @discussion Use HMBalloonRect to get information about the size of a help balloon * before the Help Manager displays it. * @param lambda * @param min sd * @param max */ // generate a truncated poisson distribution long double poisson_pmf(double lambda, int k) { long double a = expl(-lambda); long double b = powl((long double) lambda,k); long double c = factorial(k); return a * b / c; } vector<double> gen_trunc_poisson(double lambda, int min, int max) { vector<double> dist(max + 1, 0.0);//initializes distribution to all 0 double sum = 0.0; if (lambda < 500) { for (int k = lambda; k >= min; k--) { dist[k] = poisson_pmf(lambda, k); sum += dist[k]; if ( dist[k]/sum < EPSILON) break; } for (int k = lambda + 1; k <= max; k++) { dist[k] = poisson_pmf(lambda, k); sum += dist[k]; if ( dist[k]/sum < EPSILON) { dist.resize(k + 1); break; } } } else { // use a normal approximation, avoiding the factorial and pow calculations // by starting 9 SD's above lambda, we should capture all densities greater than EPSILON int prob_max = lambda + 9 * sqrt(lambda); max = MIN(max, prob_max); dist.resize(max + 1); for (int k = max; k >= min; k--) { dist[k] = normal_cdf(k + 0.5, lambda, lambda); // 0.5 is a continuity correction if ( k < max ) { dist[k+1] -= dist[k]; sum += dist[k+1]; } if ( k < lambda and dist[k+1] < EPSILON) { dist[k] = 0; break; } } } return normalize_dist(dist, sum); } // generate a truncated, discretized powerlaw distribution (= zeta dist?) vector<double> gen_trunc_powerlaw(double alpha, double kappa, int min, int max) { vector<double> dist(max + 1); double sum = 0; for (int k = min; k <= max; k++) { double pk = powl(k, (long double) -alpha) * expl(-k/(long double) kappa); dist[k] = pk; sum += pk; if (pk/sum < EPSILON) break; } // Norm the distribution return normalize_dist(dist, sum); } vector<double> gen_trunc_exponential(double lambda, int min, int max) { vector<double> dist(max + 1); if (lambda <= 0) { cerr << "Exponential distribution must have a positive parameter value\n"; return dist; } double sum = 0; for (int k = min; k <= max; k++) { double pk = lambda * exp(-lambda * k); dist[k] = pk; sum += pk; if (pk/sum < EPSILON) break; } // Norm the distribution return normalize_dist(dist, sum); } vector<double> normalize_dist(vector<double> dist, double sum) { for (unsigned int i = 1; i < dist.size(); i++) dist[i] = dist[i] / sum; return dist; } vector<double> normalize_dist(vector<int> old_dist, int sum) { vector<double> dist(old_dist.size()); for (unsigned int i = 1; i < dist.size(); i++) dist[i] = ((double) old_dist[i]) / sum; return dist; } int rand_nonuniform_int(vector<double> dist, MTRand* mtrand) { //assert(sum(dist) == 1); // why doesn't this work? double last = 0; double rand = mtrand->rand(); for (unsigned int i = 0; i < dist.size(); i++ ) { double current = last + dist[i]; if ( rand <= current ) { return i; } else { last = current; } } if (last != 1) { cerr << "rand_nonuniform_int() expects a normed distribution. " << "Your probabilities sum to " << setprecision(15) << last << ". Fix this using Utilities::normalize_dist()\n"; exit(1); } return -1; } double rand_exp(double lambda, MTRand* mtrand) { return -log(mtrand->rand()) / lambda; } // N is the size of the sample space--which includes 0, so the int "N" itself will never get // returned in the sample. sample is an empty vector that needs to be of size k; mtrand // is a Mersenne Twister RNG. void rand_nchoosek(int N, vector<int>& sample, MTRand* mtrand) { if (sample.size() == 0 ) return; int k = sample.size(); // k is specified by size of requested vector assert( k <= N ); int top = N-k; double Nreal = (double) N; int newidx=0; int lastidx=0; int i=0; while ( k >= 2 ) { double V = mtrand->rand(); int S=0; double quot = top/Nreal; while( quot > V ) { S++; top-=1; Nreal-=1; quot =(quot*top)/Nreal; } //skip over the next S records and select the following one for the sample newidx = lastidx + S; sample[i]=newidx; lastidx = newidx+1; i++; Nreal -= 1.0; k -= 1; } if ( k == 1 ) { // the following line had (newidx+1) instead of lastidx before, which // produced incorrect results when N == 1; this, I believe, is correct sample[i++] = lastidx + (int) mtrand->rand( (int) Nreal ); } } double normal_pdf(double x, double mu, double var) { long double PI = 3.1415926535897932384; return exp(-pow(x-mu,2) / 2.0*var) / sqrt(2*PI*var); } double normal_cdf(double x, double mu, double var) { x = (x-mu)/sqrt(var); // Abramowitz & Stegun (1964) approximation long double b0 = 0.2316419; double b1 = 0.319381530; double b2 = -0.356563782; double b3 = 1.781477937; double b4 = -1.821255978; double b5 = 1.330274429; if (x >= 0.0) { long double t = 1.0/(1.0+b0*x); return 1.0 - normal_pdf(x, 0, 1)*(b1*t + b2*pow(t,2) + b3*pow(t,3) + b4*pow(t,4) + b5*pow(t,5)); } else { long double t = 1.0/(1.0-b0*x); return normal_pdf(x, 0, 1)*(b1*t + b2*pow(t,2) + b3*pow(t,3) + b4*pow(t,4) + b5*pow(t,5)); } } /* double sum(vector<double> list) { double sum = 0; for (int i = 0; i < list.size(); i++) { sum += list[i]; } return sum; } int sum(vector<int> list) { int sum = 0; for (int i = 0; i < list.size(); i++) { sum += list[i]; } return sum; } template <typename T> T sum(vector<T> list) { T sum = 0; for (int i = 0; i < list.size(); i++) { sum += list[i]; } return sum; } template <typename T> double mean(vector<T> list) { return (double) sum(list) / list.size(); }*/ long double factorial(int num) { assert( num > -1); if (num == 0) return 1; // definition of 0! long double result = 0.0;//log(1); for (int i = 1; i <= num; i++) result = result + logl((long double) i); return expl(result); } int max_element(vector<int> list) { int element = list[0]; for (unsigned int i = 0; i < list.size(); i++) { element = max(element, list[i]); } return element; } std::string strip ( std::string const& str, char const* sepSet) { std::string::size_type const first = str.find_first_not_of(sepSet); return ( first==std::string::npos ) ? std::string() : str.substr(first, str.find_last_not_of(sepSet)-first+1); } void split(const string& s, char c, vector<string>& v) { string::size_type i = 0; string::size_type j = s.find(c); while (j != string::npos) { v.push_back(s.substr(i, j-i)); i = ++j; j = s.find(c, j); } if (j == string::npos) v.push_back(s.substr(i, s.length( ))); } /* // initialize random seed: void seed_rand() { if (called_seed) return; srand ( time(NULL) ); long seed1 = rand(); long seed2 = rand(); setall(seed1,seed2); called_seed = true; }*/ /* public static void shuffle (int[] array) { Random rng = new Random(); // i.e., java.util.Random. int n = array.length; // The number of items left to shuffle (loop invariant). while (n > 1) { int k = rng.nextInt(n); // 0 <= k < n. --n; // n is now the last pertinent index; int temp = array[n]; // swap array[n] with array[k]. array[n] = array[k]; array[k] = temp; } } */ <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textparagraphpropertiescontext.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "oox/drawingml/textparagraphpropertiescontext.hxx" #include <com/sun/star/text/WritingMode.hpp> #include <com/sun/star/awt/FontDescriptor.hpp> #include "oox/drawingml/colorchoicecontext.hxx" #include "oox/drawingml/textcharacterpropertiescontext.hxx" #include "oox/drawingml/drawingmltypes.hxx" #include "oox/drawingml/textfontcontext.hxx" #include "oox/helper/attributelist.hxx" #include "oox/core/namespaces.hxx" #include "textspacingcontext.hxx" #include "texttabstoplistcontext.hxx" #include "tokens.hxx" using ::rtl::OUString; using namespace ::oox::core; using ::com::sun::star::awt::FontDescriptor; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::style; using namespace ::com::sun::star::text; namespace oox { namespace drawingml { // CT_TextParagraphProperties TextParagraphPropertiesContext::TextParagraphPropertiesContext( ContextHandler& rParent, const Reference< XFastAttributeList >& xAttribs, TextParagraphProperties& rTextParagraphProperties ) : ContextHandler( rParent ) , mrTextParagraphProperties( rTextParagraphProperties ) , mrSpaceBefore( rTextParagraphProperties.getParaTopMargin() ) , mrSpaceAfter( rTextParagraphProperties.getParaBottomMargin() ) , mrBulletList( rTextParagraphProperties.getBulletList() ) { OUString sValue; AttributeList attribs( xAttribs ); PropertyMap& rPropertyMap( mrTextParagraphProperties.getTextParagraphPropertyMap() ); // ST_TextAlignType if ( xAttribs->hasAttribute( XML_algn ) ) { sal_Int32 nAlign = xAttribs->getOptionalValueToken( XML_algn, XML_l ); const OUString sParaAdjust( CREATE_OUSTRING( "ParaAdjust" ) ); rPropertyMap[ sParaAdjust ] <<= GetParaAdjust( nAlign ); } // OSL_TRACE( "OOX: para adjust %d", GetParaAdjust( nAlign )); // TODO see to do the same with RubyAdjust // ST_Coordinate32 // sValue = xAttribs->getOptionalValue( XML_defTabSz ); SJ: we need to be able to set the default tab size for each text object, // this is possible at the moment only for the whole document. // sal_Int32 nDefTabSize = ( sValue.getLength() == 0 ? 0 : GetCoordinate( sValue ) ); // TODO // bool bEaLineBrk = attribs.getBool( XML_eaLnBrk, true ); if ( xAttribs->hasAttribute( XML_latinLnBrk ) ) { bool bLatinLineBrk = attribs.getBool( XML_latinLnBrk, true ); const OUString sParaIsHyphenation( CREATE_OUSTRING( "ParaIsHyphenation" ) ); rPropertyMap[ sParaIsHyphenation ] <<= bLatinLineBrk; } // TODO see what to do with Asian hyphenation // ST_TextFontAlignType // TODO // sal_Int32 nFontAlign = xAttribs->getOptionalValueToken( XML_fontAlgn, XML_base ); if ( xAttribs->hasAttribute( XML_hangingPunct ) ) { bool bHangingPunct = attribs.getBool( XML_hangingPunct, false ); const OUString sParaIsHangingPunctuation( CREATE_OUSTRING( "ParaIsHangingPunctuation" ) ); rPropertyMap[ sParaIsHangingPunctuation ] <<= bHangingPunct; } // ST_Coordinate if ( xAttribs->hasAttribute( XML_indent ) ) { sValue = xAttribs->getOptionalValue( XML_indent ); mrTextParagraphProperties.getFirstLineIndentation() = boost::optional< sal_Int32 >( sValue.getLength() == 0 ? 0 : GetCoordinate( sValue ) ); } // ST_TextIndentLevelType // -1 is an invalid value and denote the lack of level sal_Int32 nLevel = attribs.getInteger( XML_lvl, 0 ); if( nLevel > 8 || nLevel < 0 ) { nLevel = 0; } mrTextParagraphProperties.setLevel( static_cast< sal_Int16 >( nLevel ) ); char name[] = "Outline X"; name[8] = static_cast<char>( '1' + nLevel ); const OUString sStyleNameValue( rtl::OUString::createFromAscii( name ) ); mrBulletList.setStyleName( sStyleNameValue ); // ST_TextMargin // ParaLeftMargin if ( xAttribs->hasAttribute( XML_marL ) ) { sValue = xAttribs->getOptionalValue( XML_marL ); mrTextParagraphProperties.getParaLeftMargin() = boost::optional< sal_Int32 >( sValue.getLength() == 0 ? 0 : GetCoordinate( sValue ) ); } // ParaRightMargin if ( xAttribs->hasAttribute( XML_marR ) ) { sValue = xAttribs->getOptionalValue( XML_marR ); sal_Int32 nMarR = ( sValue.getLength() == 0 ? 0 : GetCoordinate( sValue ) ); const OUString sParaRightMargin( CREATE_OUSTRING( "ParaRightMargin" ) ); rPropertyMap[ sParaRightMargin ] <<= nMarR; } if ( xAttribs->hasAttribute( XML_rtl ) ) { bool bRtl = attribs.getBool( XML_rtl, false ); const OUString sTextWritingMode( CREATE_OUSTRING( "TextWritingMode" ) ); rPropertyMap[ sTextWritingMode ] <<= ( bRtl ? WritingMode_RL_TB : WritingMode_LR_TB ); } } TextParagraphPropertiesContext::~TextParagraphPropertiesContext() { PropertyMap& rPropertyMap( mrTextParagraphProperties.getTextParagraphPropertyMap() ); if ( maLineSpacing.bHasValue ) { const OUString sParaLineSpacing( CREATE_OUSTRING( "ParaLineSpacing" ) ); //OSL_TRACE( "OOX: ParaLineSpacing unit = %d, value = %d", maLineSpacing.nUnit, maLineSpacing.nValue ); rPropertyMap[ sParaLineSpacing ] <<= maLineSpacing.toLineSpacing(); } ::std::list< TabStop >::size_type nTabCount = maTabList.size(); if( nTabCount != 0 ) { Sequence< TabStop > aSeq( nTabCount ); TabStop * aArray = aSeq.getArray(); OSL_ENSURE( aArray != NULL, "sequence array is NULL" ); ::std::copy( maTabList.begin(), maTabList.end(), aArray ); const OUString sParaTabStops( CREATE_OUSTRING( "ParaTabStops" ) ); rPropertyMap[ sParaTabStops ] <<= aSeq; } if ( mpFillPropertiesPtr ) { ::com::sun::star::uno::Reference< ::com::sun::star::graphic::XGraphic > xGraphic( mpFillPropertiesPtr->getXGraphic() ); if ( xGraphic.is() ) mrBulletList.setGraphic( xGraphic ); } if( mrBulletList.is() ) { const rtl::OUString sIsNumbering( CREATE_OUSTRING( "IsNumbering" ) ); rPropertyMap[ sIsNumbering ] <<= sal_True; } sal_Int16 nLevel = mrTextParagraphProperties.getLevel(); // OSL_TRACE("OOX: numbering level = %d", nLevel ); const OUString sNumberingLevel( CREATE_OUSTRING( "NumberingLevel" ) ); rPropertyMap[ sNumberingLevel ] <<= (sal_Int16)nLevel; sal_Bool bTmp = sal_True; const OUString sNumberingIsNumber( CREATE_OUSTRING( "NumberingIsNumber" ) ); rPropertyMap[ sNumberingIsNumber ] <<= bTmp; } // -------------------------------------------------------------------- void TextParagraphPropertiesContext::endFastElement( sal_Int32 ) throw (SAXException, RuntimeException) { } // -------------------------------------------------------------------- Reference< XFastContextHandler > TextParagraphPropertiesContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& rXAttributes ) throw (SAXException, RuntimeException) { Reference< XFastContextHandler > xRet; switch( aElementToken ) { case NMSP_DRAWINGML|XML_lnSpc: // CT_TextSpacing xRet.set( new TextSpacingContext( *this, maLineSpacing ) ); break; case NMSP_DRAWINGML|XML_spcBef: // CT_TextSpacing xRet.set( new TextSpacingContext( *this, mrSpaceBefore ) ); break; case NMSP_DRAWINGML|XML_spcAft: // CT_TextSpacing xRet.set( new TextSpacingContext( *this, mrSpaceAfter ) ); break; // EG_TextBulletColor case NMSP_DRAWINGML|XML_buClrTx: // CT_TextBulletColorFollowText ??? mrBulletList.mbBulletColorFollowText <<= sal_True; break; case NMSP_DRAWINGML|XML_buClr: // CT_Color xRet.set( new colorChoiceContext( *this, *mrBulletList.maBulletColorPtr ) ); break; // EG_TextBulletSize case NMSP_DRAWINGML|XML_buSzTx: // CT_TextBulletSizeFollowText mrBulletList.setBulletSize(100); break; case NMSP_DRAWINGML|XML_buSzPct: // CT_TextBulletSizePercent mrBulletList.setBulletSize( static_cast<sal_Int16>( GetPercent( rXAttributes->getOptionalValue( XML_val ) ) / 1000 ) ); break; case NMSP_DRAWINGML|XML_buSzPts: // CT_TextBulletSizePoint mrBulletList.setBulletSize(0); mrBulletList.setFontSize( static_cast<sal_Int16>(GetTextSize( rXAttributes->getOptionalValue( XML_val ) ) ) ); break; // EG_TextBulletTypeface case NMSP_DRAWINGML|XML_buFontTx: // CT_TextBulletTypefaceFollowText mrBulletList.mbBulletFontFollowText <<= sal_True; break; case NMSP_DRAWINGML|XML_buFont: // CT_TextFont xRet.set( new TextFontContext( *this, aElementToken, rXAttributes, mrBulletList.maBulletFont ) ); break; // EG_TextBullet case NMSP_DRAWINGML|XML_buNone: // CT_TextNoBullet mrBulletList.setNone(); break; case NMSP_DRAWINGML|XML_buAutoNum: // CT_TextAutonumberBullet { AttributeList attribs( rXAttributes ); try { sal_Int32 nType = rXAttributes->getValueToken( XML_type ); sal_Int32 nStartAt = attribs.getInteger( XML_startAt, 1 ); if( nStartAt > 32767 ) { nStartAt = 32767; } else if( nStartAt < 1 ) { nStartAt = 1; } mrBulletList.setStartAt( nStartAt ); mrBulletList.setType( nType ); } catch(SAXException& /* e */ ) { OSL_TRACE("OOX: SAXException in XML_buAutoNum"); } break; } case NMSP_DRAWINGML|XML_buChar: // CT_TextCharBullet try { mrBulletList.setBulletChar( rXAttributes->getValue( XML_char ) ); } catch(SAXException& /* e */) { OSL_TRACE("OOX: SAXException in XML_buChar"); } break; case NMSP_DRAWINGML|XML_buBlip: // CT_TextBlipBullet { mpFillPropertiesPtr = FillPropertiesPtr( new FillProperties() ); xRet.set( new BlipFillPropertiesContext( *this, rXAttributes, *mpFillPropertiesPtr.get() ) ); } break; case NMSP_DRAWINGML|XML_tabLst: // CT_TextTabStopList xRet.set( new TextTabStopListContext( *this, maTabList ) ); break; case NMSP_DRAWINGML|XML_defRPr: // CT_TextCharacterProperties xRet.set( new TextCharacterPropertiesContext( *this, rXAttributes, *mrTextParagraphProperties.getTextCharacterProperties() ) ); break; } if ( !xRet.is() ) xRet.set( this ); return xRet; } // -------------------------------------------------------------------- } } <commit_msg>INTEGRATION: CWS xmlfilter06 (1.4.6); FILE MERGED 2008/07/10 14:00:01 dr 1.4.6.8: #i10000# resync 2008/07/10 11:33:04 dr 1.4.6.7: #i10000# resync 2008/07/10 11:13:27 dr 1.4.6.6: RESYNC: (1.5-1.6); FILE MERGED 2008/06/30 16:21:11 dr 1.4.6.5: #i10000# resync additions 2008/06/30 09:57:19 dr 1.4.6.4: RESYNC: (1.4-1.5); FILE MERGED 2008/06/20 14:24:47 dr 1.4.6.3: resolve theme font names, e.g. '+mj-lt' or '+mn-ea' 2008/06/20 11:58:16 dr 1.4.6.2: line/fill/character properties rework; first steps of chart text formatting and rotation import; make line arrow import work 2008/05/27 10:40:36 dr 1.4.6.1: joined changes from CWS xmlfilter05<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textparagraphpropertiescontext.cxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "oox/drawingml/textparagraphpropertiescontext.hxx" #include <com/sun/star/text/WritingMode.hpp> #include <com/sun/star/awt/FontDescriptor.hpp> #include "oox/drawingml/colorchoicecontext.hxx" #include "oox/drawingml/textcharacterpropertiescontext.hxx" #include "oox/drawingml/fillproperties.hxx" #include "oox/helper/attributelist.hxx" #include "oox/core/namespaces.hxx" #include "textspacingcontext.hxx" #include "texttabstoplistcontext.hxx" #include "tokens.hxx" using ::rtl::OUString; using namespace ::oox::core; using ::com::sun::star::awt::FontDescriptor; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::style; using namespace ::com::sun::star::text; namespace oox { namespace drawingml { // CT_TextParagraphProperties TextParagraphPropertiesContext::TextParagraphPropertiesContext( ContextHandler& rParent, const Reference< XFastAttributeList >& xAttribs, TextParagraphProperties& rTextParagraphProperties ) : ContextHandler( rParent ) , mrTextParagraphProperties( rTextParagraphProperties ) , mrSpaceBefore( rTextParagraphProperties.getParaTopMargin() ) , mrSpaceAfter( rTextParagraphProperties.getParaBottomMargin() ) , mrBulletList( rTextParagraphProperties.getBulletList() ) { OUString sValue; AttributeList attribs( xAttribs ); PropertyMap& rPropertyMap( mrTextParagraphProperties.getTextParagraphPropertyMap() ); // ST_TextAlignType if ( xAttribs->hasAttribute( XML_algn ) ) { sal_Int32 nAlign = xAttribs->getOptionalValueToken( XML_algn, XML_l ); const OUString sParaAdjust( CREATE_OUSTRING( "ParaAdjust" ) ); rPropertyMap[ sParaAdjust ] <<= GetParaAdjust( nAlign ); } // OSL_TRACE( "OOX: para adjust %d", GetParaAdjust( nAlign )); // TODO see to do the same with RubyAdjust // ST_Coordinate32 // sValue = xAttribs->getOptionalValue( XML_defTabSz ); SJ: we need to be able to set the default tab size for each text object, // this is possible at the moment only for the whole document. // sal_Int32 nDefTabSize = ( sValue.getLength() == 0 ? 0 : GetCoordinate( sValue ) ); // TODO // bool bEaLineBrk = attribs.getBool( XML_eaLnBrk, true ); if ( xAttribs->hasAttribute( XML_latinLnBrk ) ) { bool bLatinLineBrk = attribs.getBool( XML_latinLnBrk, true ); const OUString sParaIsHyphenation( CREATE_OUSTRING( "ParaIsHyphenation" ) ); rPropertyMap[ sParaIsHyphenation ] <<= bLatinLineBrk; } // TODO see what to do with Asian hyphenation // ST_TextFontAlignType // TODO // sal_Int32 nFontAlign = xAttribs->getOptionalValueToken( XML_fontAlgn, XML_base ); if ( xAttribs->hasAttribute( XML_hangingPunct ) ) { bool bHangingPunct = attribs.getBool( XML_hangingPunct, false ); const OUString sParaIsHangingPunctuation( CREATE_OUSTRING( "ParaIsHangingPunctuation" ) ); rPropertyMap[ sParaIsHangingPunctuation ] <<= bHangingPunct; } // ST_Coordinate if ( xAttribs->hasAttribute( XML_indent ) ) { sValue = xAttribs->getOptionalValue( XML_indent ); mrTextParagraphProperties.getFirstLineIndentation() = boost::optional< sal_Int32 >( sValue.getLength() == 0 ? 0 : GetCoordinate( sValue ) ); } // ST_TextIndentLevelType // -1 is an invalid value and denote the lack of level sal_Int32 nLevel = attribs.getInteger( XML_lvl, 0 ); if( nLevel > 8 || nLevel < 0 ) { nLevel = 0; } mrTextParagraphProperties.setLevel( static_cast< sal_Int16 >( nLevel ) ); char name[] = "Outline X"; name[8] = static_cast<char>( '1' + nLevel ); const OUString sStyleNameValue( rtl::OUString::createFromAscii( name ) ); mrBulletList.setStyleName( sStyleNameValue ); // ST_TextMargin // ParaLeftMargin if ( xAttribs->hasAttribute( XML_marL ) ) { sValue = xAttribs->getOptionalValue( XML_marL ); mrTextParagraphProperties.getParaLeftMargin() = boost::optional< sal_Int32 >( sValue.getLength() == 0 ? 0 : GetCoordinate( sValue ) ); } // ParaRightMargin if ( xAttribs->hasAttribute( XML_marR ) ) { sValue = xAttribs->getOptionalValue( XML_marR ); sal_Int32 nMarR = ( sValue.getLength() == 0 ? 0 : GetCoordinate( sValue ) ); const OUString sParaRightMargin( CREATE_OUSTRING( "ParaRightMargin" ) ); rPropertyMap[ sParaRightMargin ] <<= nMarR; } if ( xAttribs->hasAttribute( XML_rtl ) ) { bool bRtl = attribs.getBool( XML_rtl, false ); const OUString sTextWritingMode( CREATE_OUSTRING( "TextWritingMode" ) ); rPropertyMap[ sTextWritingMode ] <<= ( bRtl ? WritingMode_RL_TB : WritingMode_LR_TB ); } } TextParagraphPropertiesContext::~TextParagraphPropertiesContext() { PropertyMap& rPropertyMap( mrTextParagraphProperties.getTextParagraphPropertyMap() ); if ( maLineSpacing.bHasValue ) { const OUString sParaLineSpacing( CREATE_OUSTRING( "ParaLineSpacing" ) ); //OSL_TRACE( "OOX: ParaLineSpacing unit = %d, value = %d", maLineSpacing.nUnit, maLineSpacing.nValue ); rPropertyMap[ sParaLineSpacing ] <<= maLineSpacing.toLineSpacing(); } ::std::list< TabStop >::size_type nTabCount = maTabList.size(); if( nTabCount != 0 ) { Sequence< TabStop > aSeq( nTabCount ); TabStop * aArray = aSeq.getArray(); OSL_ENSURE( aArray != NULL, "sequence array is NULL" ); ::std::copy( maTabList.begin(), maTabList.end(), aArray ); const OUString sParaTabStops( CREATE_OUSTRING( "ParaTabStops" ) ); rPropertyMap[ sParaTabStops ] <<= aSeq; } if ( mpFillPropertiesPtr && mpFillPropertiesPtr->mxGraphic.is() ) mrBulletList.setGraphic( mpFillPropertiesPtr->mxGraphic ); if( mrBulletList.is() ) { const rtl::OUString sIsNumbering( CREATE_OUSTRING( "IsNumbering" ) ); rPropertyMap[ sIsNumbering ] <<= sal_True; } sal_Int16 nLevel = mrTextParagraphProperties.getLevel(); // OSL_TRACE("OOX: numbering level = %d", nLevel ); const OUString sNumberingLevel( CREATE_OUSTRING( "NumberingLevel" ) ); rPropertyMap[ sNumberingLevel ] <<= (sal_Int16)nLevel; sal_Bool bTmp = sal_True; const OUString sNumberingIsNumber( CREATE_OUSTRING( "NumberingIsNumber" ) ); rPropertyMap[ sNumberingIsNumber ] <<= bTmp; } // -------------------------------------------------------------------- void TextParagraphPropertiesContext::endFastElement( sal_Int32 ) throw (SAXException, RuntimeException) { } // -------------------------------------------------------------------- Reference< XFastContextHandler > TextParagraphPropertiesContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& rXAttributes ) throw (SAXException, RuntimeException) { AttributeList aAttribs( rXAttributes ); Reference< XFastContextHandler > xRet; switch( aElementToken ) { case NMSP_DRAWINGML|XML_lnSpc: // CT_TextSpacing xRet.set( new TextSpacingContext( *this, maLineSpacing ) ); break; case NMSP_DRAWINGML|XML_spcBef: // CT_TextSpacing xRet.set( new TextSpacingContext( *this, mrSpaceBefore ) ); break; case NMSP_DRAWINGML|XML_spcAft: // CT_TextSpacing xRet.set( new TextSpacingContext( *this, mrSpaceAfter ) ); break; // EG_TextBulletColor case NMSP_DRAWINGML|XML_buClrTx: // CT_TextBulletColorFollowText ??? mrBulletList.mbBulletColorFollowText <<= sal_True; break; case NMSP_DRAWINGML|XML_buClr: // CT_Color xRet.set( new colorChoiceContext( *this, *mrBulletList.maBulletColorPtr ) ); break; // EG_TextBulletSize case NMSP_DRAWINGML|XML_buSzTx: // CT_TextBulletSizeFollowText mrBulletList.setBulletSize(100); break; case NMSP_DRAWINGML|XML_buSzPct: // CT_TextBulletSizePercent mrBulletList.setBulletSize( static_cast<sal_Int16>( GetPercent( rXAttributes->getOptionalValue( XML_val ) ) / 1000 ) ); break; case NMSP_DRAWINGML|XML_buSzPts: // CT_TextBulletSizePoint mrBulletList.setBulletSize(0); mrBulletList.setFontSize( static_cast<sal_Int16>(GetTextSize( rXAttributes->getOptionalValue( XML_val ) ) ) ); break; // EG_TextBulletTypeface case NMSP_DRAWINGML|XML_buFontTx: // CT_TextBulletTypefaceFollowText mrBulletList.mbBulletFontFollowText <<= sal_True; break; case NMSP_DRAWINGML|XML_buFont: // CT_TextFont mrBulletList.maBulletFont.setAttributes( aAttribs ); break; // EG_TextBullet case NMSP_DRAWINGML|XML_buNone: // CT_TextNoBullet mrBulletList.setNone(); break; case NMSP_DRAWINGML|XML_buAutoNum: // CT_TextAutonumberBullet { AttributeList attribs( rXAttributes ); try { sal_Int32 nType = rXAttributes->getValueToken( XML_type ); sal_Int32 nStartAt = attribs.getInteger( XML_startAt, 1 ); if( nStartAt > 32767 ) { nStartAt = 32767; } else if( nStartAt < 1 ) { nStartAt = 1; } mrBulletList.setStartAt( nStartAt ); mrBulletList.setType( nType ); } catch(SAXException& /* e */ ) { OSL_TRACE("OOX: SAXException in XML_buAutoNum"); } break; } case NMSP_DRAWINGML|XML_buChar: // CT_TextCharBullet try { mrBulletList.setBulletChar( rXAttributes->getValue( XML_char ) ); } catch(SAXException& /* e */) { OSL_TRACE("OOX: SAXException in XML_buChar"); } break; case NMSP_DRAWINGML|XML_buBlip: // CT_TextBlipBullet { mpFillPropertiesPtr.reset( new FillProperties ); xRet.set( new BlipFillPropertiesContext( *this, rXAttributes, *mpFillPropertiesPtr ) ); } break; case NMSP_DRAWINGML|XML_tabLst: // CT_TextTabStopList xRet.set( new TextTabStopListContext( *this, maTabList ) ); break; case NMSP_DRAWINGML|XML_defRPr: // CT_TextCharacterProperties xRet.set( new TextCharacterPropertiesContext( *this, rXAttributes, mrTextParagraphProperties.getTextCharacterProperties() ) ); break; } if ( !xRet.is() ) xRet.set( this ); return xRet; } // -------------------------------------------------------------------- } } <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2014, Alberto Corona <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include "interface.h" void printHelp() { printf("Usage: yabs [options]\n\n" "yabs, a simple build system.\n" "Options:\n" "\t-n\tCreate a new yabs build file\n" "\t-h\tPrint this dialog\n"); } <commit_msg>interface: add long options<commit_after>/* * Copyright (c) 2013-2014, Alberto Corona <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include "interface.h" void printHelp() { printf("Usage: yabs [options]\n\n" "yabs, a simple build system.\n" "Options:\n" "\t-n, --new\tCreate a new yabs build file\n" "\t-h, --help\tPrint this dialog\n" "\t-p, --parse\tVerbosely parse configuration file\n" "\t-e, --extract\tExtract dist tarball\n"); } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY OR REMOVE THIS HEADER */ /* FALCON - Fracturing And Liquid CONvection */ /* */ /* (c) pending 2012 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "Moose.h" #include "Falcon.h" #include "FalconApp.h" #include "FluidMassEnergyBalanceModule.h" FalconApp::FalconApp(int argc, char * argv[]) : MooseApp(argc, argv) { srand(libMesh::processor_id()); init(); Elk::FluidMassEnergyBalance::registerObjects(_factory); Falcon::registerObjects(_factory); } <commit_msg>Getting rid of one of MOOSE's many inits() - closes #1724<commit_after>/****************************************************************/ /* DO NOT MODIFY OR REMOVE THIS HEADER */ /* FALCON - Fracturing And Liquid CONvection */ /* */ /* (c) pending 2012 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "Moose.h" #include "Falcon.h" #include "FalconApp.h" #include "FluidMassEnergyBalanceModule.h" FalconApp::FalconApp(int argc, char * argv[]) : MooseApp(argc, argv) { srand(libMesh::processor_id()); Moose::registerObjects(_factory); Elk::FluidMassEnergyBalance::registerObjects(_factory); Falcon::registerObjects(_factory); Moose::associateSyntax(_syntax, _action_factory); } <|endoftext|>
<commit_before>#define MS_CLASS "TCPServer" #include "handles/TCPServer.h" #include "Utils.h" #include "DepLibUV.h" #include "MediaSoupError.h" #include "Logger.h" /* Static methods for UV callbacks. */ static inline void on_connection(uv_stream_t* handle, int status) { static_cast<TCPServer*>(handle->data)->onUvConnection(status); } static inline void on_close(uv_handle_t* handle) { static_cast<TCPServer*>(handle->data)->onUvClosed(); } static inline void on_error_close(uv_handle_t* handle) { delete handle; } /* Instance methods. */ TCPServer::TCPServer(const std::string &ip, MS_PORT port, int backlog) { MS_TRACE(); int err; int flags = 0; this->uvHandle = new uv_tcp_t; this->uvHandle->data = (void*)this; err = uv_tcp_init(DepLibUV::GetLoop(), this->uvHandle); if (err) { delete this->uvHandle; this->uvHandle = nullptr; MS_THROW_ERROR("uv_tcp_init() failed: %s", uv_strerror(err)); } struct sockaddr_storage bind_addr; switch (Utils::IP::GetFamily(ip)) { case AF_INET: err = uv_ip4_addr(ip.c_str(), (int)port, (struct sockaddr_in*)&bind_addr); if (err) MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err)); break; case AF_INET6: err = uv_ip6_addr(ip.c_str(), (int)port, (struct sockaddr_in6*)&bind_addr); if (err) MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err)); // Don't also bind into IPv4 when listening in IPv6. flags |= UV_TCP_IPV6ONLY; break; default: uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("invalid binding IP '%s'", ip.c_str()); break; } err = uv_tcp_bind(this->uvHandle, (const struct sockaddr*)&bind_addr, flags); if (err) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("uv_tcp_bind() failed: %s", uv_strerror(err)); } err = uv_listen((uv_stream_t*)this->uvHandle, backlog, (uv_connection_cb)on_connection); if (err) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err)); } // Set local address. if (!SetLocalAddress()) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("error setting local IP and port"); } } TCPServer::TCPServer(uv_tcp_t* uvHandle, int backlog) : uvHandle(uvHandle) { MS_TRACE(); int err; this->uvHandle->data = (void*)this; err = uv_listen((uv_stream_t*)this->uvHandle, backlog, (uv_connection_cb)on_connection); if (err) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err)); } // Set local address. if (!SetLocalAddress()) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("error setting local IP and port"); } } TCPServer::~TCPServer() { MS_TRACE(); if (this->uvHandle) delete this->uvHandle; } void TCPServer::Close() { MS_TRACE(); if (this->isClosing) return; this->isClosing = true; // If there are no connections then close now. if (this->connections.empty()) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close); } // Otherwise close all the connections (but not the TCP server). else { MS_DEBUG("closing %zu active connections", this->connections.size()); for (auto it = this->connections.begin(); it != this->connections.end(); ++it) { TCPConnection* connection = *it; connection->Close(); } } } void TCPServer::Dump() { MS_DEBUG("[TCP, local:%s :%" PRIu16 ", status:%s, connections:%zu]", this->localIP.c_str(), (uint16_t)this->localPort, (!this->isClosing) ? "open" : "closed", this->connections.size()); } const struct sockaddr* TCPServer::GetLocalAddress() { MS_TRACE(); return (const struct sockaddr*)&this->localAddr; } const std::string& TCPServer::GetLocalIP() { MS_TRACE(); return this->localIP; } MS_PORT TCPServer::GetLocalPort() { MS_TRACE(); return this->localPort; } bool TCPServer::SetLocalAddress() { MS_TRACE(); int err; int len = sizeof(this->localAddr); err = uv_tcp_getsockname(this->uvHandle, (struct sockaddr*)&this->localAddr, &len); if (err) { MS_ERROR("uv_tcp_getsockname() failed: %s", uv_strerror(err)); return false; } int family; Utils::IP::GetAddressInfo((const struct sockaddr*)&this->localAddr, &family, this->localIP, &this->localPort); return true; } inline void TCPServer::onUvConnection(int status) { MS_TRACE(); if (this->isClosing) return; int err; if (status) { MS_ERROR("error while receiving a new TCP connection: %s", uv_strerror(status)); return; } // Notify the subclass so it provides an allocated derived class of TCPConnection. TCPConnection* connection = nullptr; userOnTCPConnectionAlloc(&connection); MS_ASSERT(connection != nullptr, "TCPConnection pointer was not allocated by the user"); try { connection->Setup(this, &(this->localAddr), this->localIP, this->localPort); } catch (const MediaSoupError &error) { delete connection; return; } // Accept the connection. err = uv_accept((uv_stream_t*)this->uvHandle, (uv_stream_t*)connection->GetUvHandle()); if (err) MS_ABORT("uv_accept() failed: %s", uv_strerror(err)); // Insert the TCPConnection in the set. this->connections.insert(connection); // Start receiving data. try { connection->Start(); } catch (const MediaSoupError &error) { MS_ERROR("cannot run the TCP connection, closing the connection: %s", error.what()); connection->Close(); // NOTE: Don't return here so the user won't be notified about a "onclose" for a TCP connection // for which there was not a previous "onnew" event. } MS_DEBUG("new TCP connection:"); connection->Dump(); // Notify the subclass. userOnNewTCPConnection(connection); } inline void TCPServer::onUvClosed() { MS_TRACE(); // Motify the subclass. userOnTCPServerClosed(); // And delete this. delete this; } inline void TCPServer::onTCPConnectionClosed(TCPConnection* connection, bool is_closed_by_peer) { MS_TRACE(); MS_DEBUG("TCP connection closed:"); connection->Dump(); // Remove the TCPConnection from the set. this->connections.erase(connection); // Notify the subclass. userOnTCPConnectionClosed(connection, is_closed_by_peer); // Check if the server is closing connections and if this is the last // connection then close the server now. if (this->isClosing && this->connections.empty()) uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close); } <commit_msg>Avoid a crash due to double uv_close() in TCPServer handler.<commit_after>#define MS_CLASS "TCPServer" #include "handles/TCPServer.h" #include "Utils.h" #include "DepLibUV.h" #include "MediaSoupError.h" #include "Logger.h" /* Static methods for UV callbacks. */ static inline void on_connection(uv_stream_t* handle, int status) { static_cast<TCPServer*>(handle->data)->onUvConnection(status); } static inline void on_close(uv_handle_t* handle) { static_cast<TCPServer*>(handle->data)->onUvClosed(); } static inline void on_error_close(uv_handle_t* handle) { delete handle; } /* Instance methods. */ TCPServer::TCPServer(const std::string &ip, MS_PORT port, int backlog) { MS_TRACE(); int err; int flags = 0; this->uvHandle = new uv_tcp_t; this->uvHandle->data = (void*)this; err = uv_tcp_init(DepLibUV::GetLoop(), this->uvHandle); if (err) { delete this->uvHandle; this->uvHandle = nullptr; MS_THROW_ERROR("uv_tcp_init() failed: %s", uv_strerror(err)); } struct sockaddr_storage bind_addr; switch (Utils::IP::GetFamily(ip)) { case AF_INET: err = uv_ip4_addr(ip.c_str(), (int)port, (struct sockaddr_in*)&bind_addr); if (err) MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err)); break; case AF_INET6: err = uv_ip6_addr(ip.c_str(), (int)port, (struct sockaddr_in6*)&bind_addr); if (err) MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err)); // Don't also bind into IPv4 when listening in IPv6. flags |= UV_TCP_IPV6ONLY; break; default: uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("invalid binding IP '%s'", ip.c_str()); break; } err = uv_tcp_bind(this->uvHandle, (const struct sockaddr*)&bind_addr, flags); if (err) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("uv_tcp_bind() failed: %s", uv_strerror(err)); } err = uv_listen((uv_stream_t*)this->uvHandle, backlog, (uv_connection_cb)on_connection); if (err) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err)); } // Set local address. if (!SetLocalAddress()) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("error setting local IP and port"); } } TCPServer::TCPServer(uv_tcp_t* uvHandle, int backlog) : uvHandle(uvHandle) { MS_TRACE(); int err; this->uvHandle->data = (void*)this; err = uv_listen((uv_stream_t*)this->uvHandle, backlog, (uv_connection_cb)on_connection); if (err) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err)); } // Set local address. if (!SetLocalAddress()) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); MS_THROW_ERROR("error setting local IP and port"); } } TCPServer::~TCPServer() { MS_TRACE(); if (this->uvHandle) delete this->uvHandle; } void TCPServer::Close() { MS_TRACE(); if (this->isClosing) return; this->isClosing = true; // If there are no connections then close now. if (this->connections.empty()) { uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close); } // Otherwise close all the connections (but not the TCP server). else { MS_DEBUG("closing %zu active connections", this->connections.size()); for (auto it = this->connections.begin(); it != this->connections.end(); ++it) { TCPConnection* connection = *it; connection->Close(); } } } void TCPServer::Dump() { MS_DEBUG("[TCP, local:%s :%" PRIu16 ", status:%s, connections:%zu]", this->localIP.c_str(), (uint16_t)this->localPort, (!this->isClosing) ? "open" : "closed", this->connections.size()); } const struct sockaddr* TCPServer::GetLocalAddress() { MS_TRACE(); return (const struct sockaddr*)&this->localAddr; } const std::string& TCPServer::GetLocalIP() { MS_TRACE(); return this->localIP; } MS_PORT TCPServer::GetLocalPort() { MS_TRACE(); return this->localPort; } bool TCPServer::SetLocalAddress() { MS_TRACE(); int err; int len = sizeof(this->localAddr); err = uv_tcp_getsockname(this->uvHandle, (struct sockaddr*)&this->localAddr, &len); if (err) { MS_ERROR("uv_tcp_getsockname() failed: %s", uv_strerror(err)); return false; } int family; Utils::IP::GetAddressInfo((const struct sockaddr*)&this->localAddr, &family, this->localIP, &this->localPort); return true; } inline void TCPServer::onUvConnection(int status) { MS_TRACE(); if (this->isClosing) return; int err; if (status) { MS_ERROR("error while receiving a new TCP connection: %s", uv_strerror(status)); return; } // Notify the subclass so it provides an allocated derived class of TCPConnection. TCPConnection* connection = nullptr; userOnTCPConnectionAlloc(&connection); MS_ASSERT(connection != nullptr, "TCPConnection pointer was not allocated by the user"); try { connection->Setup(this, &(this->localAddr), this->localIP, this->localPort); } catch (const MediaSoupError &error) { delete connection; return; } // Accept the connection. err = uv_accept((uv_stream_t*)this->uvHandle, (uv_stream_t*)connection->GetUvHandle()); if (err) MS_ABORT("uv_accept() failed: %s", uv_strerror(err)); // Insert the TCPConnection in the set. this->connections.insert(connection); // Start receiving data. try { connection->Start(); } catch (const MediaSoupError &error) { MS_ERROR("cannot run the TCP connection, closing the connection: %s", error.what()); connection->Close(); // NOTE: Don't return here so the user won't be notified about a "onclose" for a TCP connection // for which there was not a previous "onnew" event. } MS_DEBUG("new TCP connection:"); connection->Dump(); // Notify the subclass. userOnNewTCPConnection(connection); } inline void TCPServer::onUvClosed() { MS_TRACE(); // Motify the subclass. userOnTCPServerClosed(); // And delete this. delete this; } inline void TCPServer::onTCPConnectionClosed(TCPConnection* connection, bool is_closed_by_peer) { MS_TRACE(); // NOTE: // Worst scenario is that in which this is the latest connection, // which is remotely closed (no TCPServer.Close() was called) and the user // call TCPServer.Close() on userOnTCPConnectionClosed() callback, so Close() // is called with zero connections and calls uv_close(), but then // onTCPConnectionClosed() continues and finds that isClosing is true and // there are zero connections, so calls uv_close() again and get a crash. // // SOLUTION: // Check isClosing value *before* onTCPConnectionClosed() callback. bool wasClosing = this->isClosing; MS_DEBUG("TCP connection closed:"); connection->Dump(); // Remove the TCPConnection from the set. this->connections.erase(connection); // Notify the subclass. userOnTCPConnectionClosed(connection, is_closed_by_peer); // TODO: CRASH: in userOnTCPConnectionClosed callback the app can call Close() // on this TCPServer so we end calling uv_close() twice and crash! // Check if the server was closing connections, and if this is the last // connection then close the server now. if (wasClosing && this->connections.empty()) uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close); } <|endoftext|>
<commit_before>// For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "osgsimpleviewerWX.h" #include <osgGA/TrackballManipulator> #include <osgDB/ReadFile> #include <wx/image.h> #include <wx/menu.h> // `Main program' equivalent, creating windows and returning main app frame bool wxOsgApp::OnInit() { // Create the main frame window MainFrame *frame = new MainFrame(NULL, wxT("wxWidgets OSG Sample"), wxDefaultPosition, wxDefaultSize); // create osg canvas // - initialize SimpleViewerWX *viewerWindow = new SimpleViewerWX(frame, wxID_ANY, wxDefaultPosition, wxSize(200, 200), wxSUNKEN_BORDER); // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile("cow.osg"); if (!loadedModel) { return false; } viewerWindow->setSceneData(loadedModel.get()); viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator); frame->SetSimpleViewer(viewerWindow); /* Show the frame */ frame->Show(true); return true; } IMPLEMENT_APP(wxOsgApp) BEGIN_EVENT_TABLE(MainFrame, wxFrame) EVT_IDLE(MainFrame::OnIdle) END_EVENT_TABLE() /* My frame constructor */ MainFrame::MainFrame(wxFrame *frame, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxFrame(frame, wxID_ANY, title, pos, size, style) { _viewerWindow = NULL; } void MainFrame::SetSimpleViewer(SimpleViewerWX *viewer) { _viewerWindow = viewer; } void MainFrame::OnIdle(wxIdleEvent &event) { _viewerWindow->render(); event.RequestMore(); } BEGIN_EVENT_TABLE(GraphicsWindowWX, wxGLCanvas) EVT_SIZE (GraphicsWindowWX::OnSize ) EVT_PAINT (GraphicsWindowWX::OnPaint ) EVT_ERASE_BACKGROUND(GraphicsWindowWX::OnEraseBackground) EVT_KEY_DOWN (GraphicsWindowWX::OnKeyDown ) EVT_KEY_UP (GraphicsWindowWX::OnKeyUp ) EVT_MOUSE_EVENTS (GraphicsWindowWX::OnMouse ) END_EVENT_TABLE() GraphicsWindowWX::GraphicsWindowWX(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxGLCanvas(parent, id, pos, size, style|wxFULL_REPAINT_ON_RESIZE, name) { // default cursor to standard _oldCursor = *wxSTANDARD_CURSOR; } GraphicsWindowWX::~GraphicsWindowWX() { } void GraphicsWindowWX::OnPaint( wxPaintEvent& WXUNUSED(event) ) { /* must always be here */ wxPaintDC dc(this); } void GraphicsWindowWX::OnSize(wxSizeEvent& event) { // this is also necessary to update the context on some platforms wxGLCanvas::OnSize(event); // set GL viewport (not called by wxGLCanvas::OnSize on all platforms...) int width, height; GetClientSize(&width, &height); // update the window dimensions, in case the window has been resized. getEventQueue()->windowResize(0, 0, width, height); } void GraphicsWindowWX::OnEraseBackground(wxEraseEvent& WXUNUSED(event)) { /* Do nothing, to avoid flashing on MSW */ } void GraphicsWindowWX::OnKeyDown(wxKeyEvent &event) { int key = event.GetKeyCode(); getEventQueue()->keyPress(key); // propagate event event.Skip(); } void GraphicsWindowWX::OnKeyUp(wxKeyEvent &event) { int key = event.GetKeyCode(); getEventQueue()->keyRelease(key); // propagate event event.Skip(); } void GraphicsWindowWX::OnMouse(wxMouseEvent& event) { if (event.ButtonDown()) { int button = event.GetButton(); getEventQueue()->mouseButtonPress(event.GetX(), event.GetY(), button); } else if (event.ButtonUp()) { int button = event.GetButton(); getEventQueue()->mouseButtonRelease(event.GetX(), event.GetY(), button); } else if (event.Dragging()) { getEventQueue()->mouseMotion(event.GetX(), event.GetY()); } } void GraphicsWindowWX::grabFocus() { // focus this window SetFocus(); } void GraphicsWindowWX::grabFocusIfPointerInWindow() { // focus this window, if the pointer is in the window wxPoint pos = wxGetMousePosition(); if (this == wxFindWindowAtPoint(pos)) { SetFocus(); } } void GraphicsWindowWX::useCursor(bool cursorOn) { if (cursorOn) { // show the old cursor SetCursor(_oldCursor); } else { // remember the old cursor _oldCursor = GetCursor(); // hide the cursor // - can't find a way to do this neatly, so create a 1x1, transparent image wxImage image(1,1); image.SetMask(true); image.SetMaskColour(0, 0, 0); wxCursor cursor(image); SetCursor(cursor); } } bool GraphicsWindowWX::makeCurrentImplementation() { SetCurrent(); return true; } void GraphicsWindowWX::swapBuffersImplementation() { SwapBuffers(); } <commit_msg>From Luigi Calori, changed hardwired "cow.osg" paramter to argv[1]<commit_after>// For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "osgsimpleviewerWX.h" #include <osgGA/TrackballManipulator> #include <osgDB/ReadFile> #include <wx/image.h> #include <wx/menu.h> // `Main program' equivalent, creating windows and returning main app frame bool wxOsgApp::OnInit() { // Create the main frame window MainFrame *frame = new MainFrame(NULL, wxT("wxWidgets OSG Sample"), wxDefaultPosition, wxDefaultSize); // create osg canvas // - initialize SimpleViewerWX *viewerWindow = new SimpleViewerWX(frame, wxID_ANY, wxDefaultPosition, wxSize(200, 200), wxSUNKEN_BORDER); // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { return false; } viewerWindow->setSceneData(loadedModel.get()); viewerWindow->setCameraManipulator(new osgGA::TrackballManipulator); frame->SetSimpleViewer(viewerWindow); /* Show the frame */ frame->Show(true); return true; } IMPLEMENT_APP(wxOsgApp) BEGIN_EVENT_TABLE(MainFrame, wxFrame) EVT_IDLE(MainFrame::OnIdle) END_EVENT_TABLE() /* My frame constructor */ MainFrame::MainFrame(wxFrame *frame, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxFrame(frame, wxID_ANY, title, pos, size, style) { _viewerWindow = NULL; } void MainFrame::SetSimpleViewer(SimpleViewerWX *viewer) { _viewerWindow = viewer; } void MainFrame::OnIdle(wxIdleEvent &event) { _viewerWindow->render(); event.RequestMore(); } BEGIN_EVENT_TABLE(GraphicsWindowWX, wxGLCanvas) EVT_SIZE (GraphicsWindowWX::OnSize ) EVT_PAINT (GraphicsWindowWX::OnPaint ) EVT_ERASE_BACKGROUND(GraphicsWindowWX::OnEraseBackground) EVT_KEY_DOWN (GraphicsWindowWX::OnKeyDown ) EVT_KEY_UP (GraphicsWindowWX::OnKeyUp ) EVT_MOUSE_EVENTS (GraphicsWindowWX::OnMouse ) END_EVENT_TABLE() GraphicsWindowWX::GraphicsWindowWX(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxGLCanvas(parent, id, pos, size, style|wxFULL_REPAINT_ON_RESIZE, name) { // default cursor to standard _oldCursor = *wxSTANDARD_CURSOR; } GraphicsWindowWX::~GraphicsWindowWX() { } void GraphicsWindowWX::OnPaint( wxPaintEvent& WXUNUSED(event) ) { /* must always be here */ wxPaintDC dc(this); } void GraphicsWindowWX::OnSize(wxSizeEvent& event) { // this is also necessary to update the context on some platforms wxGLCanvas::OnSize(event); // set GL viewport (not called by wxGLCanvas::OnSize on all platforms...) int width, height; GetClientSize(&width, &height); // update the window dimensions, in case the window has been resized. getEventQueue()->windowResize(0, 0, width, height); } void GraphicsWindowWX::OnEraseBackground(wxEraseEvent& WXUNUSED(event)) { /* Do nothing, to avoid flashing on MSW */ } void GraphicsWindowWX::OnKeyDown(wxKeyEvent &event) { int key = event.GetKeyCode(); getEventQueue()->keyPress(key); // propagate event event.Skip(); } void GraphicsWindowWX::OnKeyUp(wxKeyEvent &event) { int key = event.GetKeyCode(); getEventQueue()->keyRelease(key); // propagate event event.Skip(); } void GraphicsWindowWX::OnMouse(wxMouseEvent& event) { if (event.ButtonDown()) { int button = event.GetButton(); getEventQueue()->mouseButtonPress(event.GetX(), event.GetY(), button); } else if (event.ButtonUp()) { int button = event.GetButton(); getEventQueue()->mouseButtonRelease(event.GetX(), event.GetY(), button); } else if (event.Dragging()) { getEventQueue()->mouseMotion(event.GetX(), event.GetY()); } } void GraphicsWindowWX::grabFocus() { // focus this window SetFocus(); } void GraphicsWindowWX::grabFocusIfPointerInWindow() { // focus this window, if the pointer is in the window wxPoint pos = wxGetMousePosition(); if (this == wxFindWindowAtPoint(pos)) { SetFocus(); } } void GraphicsWindowWX::useCursor(bool cursorOn) { if (cursorOn) { // show the old cursor SetCursor(_oldCursor); } else { // remember the old cursor _oldCursor = GetCursor(); // hide the cursor // - can't find a way to do this neatly, so create a 1x1, transparent image wxImage image(1,1); image.SetMask(true); image.SetMaskColour(0, 0, 0); wxCursor cursor(image); SetCursor(cursor); } } bool GraphicsWindowWX::makeCurrentImplementation() { SetCurrent(); return true; } void GraphicsWindowWX::swapBuffersImplementation() { SwapBuffers(); } <|endoftext|>
<commit_before>#include "graphicboard.h" #include "gamesprite.h" #include "gamefont.h" #include "tetrisboard.h" #include <mw/sprite.h> #include <mw/font.h> #include <mw/text.h> #include <mw/color.h> #include <SDL_opengl.h> #include <sstream> GraphicBoard::GraphicBoard(const TetrisBoard& tetrisBoard) : tetrisBoard_(tetrisBoard) { height_ = 800; // height for the board voidHeight_ = 10; borderLineThickness_ = 7; // Should be lower than voidHeight_ previwBorderSizeInSquares_ = 5; horizontalDistanceToText_ = 40; pixlePerSquare_ = 800.0 / (tetrisBoard_.getNbrOfRows() + 2); color_ = mw::Color(237/256.0,78/256.0,8/256.0); text1_ = mw::Text("Player",fontDefault); text2_ = mw::Text("Level ",fontDefault); text3_ = mw::Text("Points",fontDefault); text4_ = mw::Text("Rows",fontDefault); gameOverMessage_ = mw::Text("",fontDefault); gameOverMessage_.setCharacterSize(70); nbrOfClearedRows_ = 0; points_ = 0; level_ = 0; name_ = "Player"; } GraphicBoard::~GraphicBoard() { } void GraphicBoard::setNbrOfClearedRows(int nbr) { nbrOfClearedRows_ = nbr; } void GraphicBoard::setPoints(int points) { points_ = points; } void GraphicBoard::setLevel(int level) { level_ = level; } void GraphicBoard::setName(std::string name) { name_ = name; } void GraphicBoard::setGameOverMessage(std::string message) { gameOverMessage_.setText(message); } void GraphicBoard::draw() { glPushMatrix(); glTranslated(voidHeight_,voidHeight_,0.0); drawBoard(); drawInfo(); glPopMatrix(); if (tetrisBoard_.isGameOver()) { glPushMatrix(); // Put it in the middle. glTranslated(getWidth()*0.5-gameOverMessage_.getWidth()*0.5,getHeight()*0.5-gameOverMessage_.getHeight()*0.5,0.0); glColor3d(1,1,1); gameOverMessage_.draw(); glPopMatrix(); } drawBorder(); } double GraphicBoard::getWidth() const { if (previwBorderSizeInSquares_*pixlePerSquare_ > text1_.getWidth()) { return tetrisBoard_.getNbrOfColumns()*pixlePerSquare_ + horizontalDistanceToText_ + previwBorderSizeInSquares_*pixlePerSquare_ + voidHeight_*2; } else { return tetrisBoard_.getNbrOfColumns()*pixlePerSquare_ + horizontalDistanceToText_ + text1_.getWidth() + voidHeight_*2; } } double GraphicBoard::getHeight() const { return height_ + voidHeight_*2; } // Private void GraphicBoard::drawBorder() const { glPushMatrix(); color_.glColor4d(); drawFrame(0,0,getWidth(),getHeight(), borderLineThickness_); glPopMatrix(); } void GraphicBoard::drawInfo() { glPushMatrix(); glTranslated(pixlePerSquare_ * tetrisBoard_.getNbrOfColumns() + horizontalDistanceToText_ + voidHeight_,0,0); glTranslated(0,getHeight() - text1_.getCharacterSize() - 30,0); text1_.setText(name_); text1_.setCharacterSize(40); glColorWhite(); text1_.draw(); glPushMatrix(); glTranslated(80, -180,0); drawPreviewBlock(); glPopMatrix(); glTranslated(0,-650,0); std::stringstream ss; ss << "Level " << level_; text2_.setText(ss.str()); glColorWhite(); text2_.draw(); glTranslated(0,-40,0); ss.str(""); ss << "Points " << points_; text3_.setText(ss.str()); text3_.draw(); glTranslated(0,-40,0); ss.str(""); ss << "Rows " << nbrOfClearedRows_; text4_.setText(ss.str()); text4_.draw(); glPopMatrix(); } void GraphicBoard::drawPreviewBlock() { glPushMatrix(); const Block& block = tetrisBoard_.nextBlock(); int nbrOfSquares = block.nbrOfSquares(); double x = 0, y = 0; for (int i = 0; i < nbrOfSquares; ++i) { Square square = block[i]; x += square.column*1.0/nbrOfSquares; y += square.row*1.0/nbrOfSquares; } glScaled(pixlePerSquare_,pixlePerSquare_,1.0); glTranslated(-x+0.5,-y+0.5,0); // Why +0.5? drawBlock(block); glPopMatrix(); glPushMatrix(); // Size is 5 squares. glScaled(previwBorderSizeInSquares_*pixlePerSquare_,previwBorderSizeInSquares_*pixlePerSquare_,1); color_.glColor4d(); // Makes the line thickness to borderLineThickness_. drawFrame(-0.5,-0.5,0.5,0.5,1.0/(previwBorderSizeInSquares_*pixlePerSquare_)*borderLineThickness_); glPopMatrix(); } void GraphicBoard::drawBoard() { glPushMatrix(); glScaled(pixlePerSquare_,pixlePerSquare_,1.0); drawGrid(); const Squares& squares = tetrisBoard_.getGameBoard(); for (Squares::const_iterator it = squares.begin(); it != squares.end(); ++it) { const Square& square = *it; drawSquare(square); } drawBlock(tetrisBoard_.currentBlock()); drawBeginArea(); glPopMatrix(); } void GraphicBoard::drawBeginArea() const { int rows = tetrisBoard_.getNbrOfRows(); int columns = tetrisBoard_.getNbrOfColumns(); double red = 0.8, green = 0.2, blue = 0.3; glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glTranslated(0,rows,0); glScaled(columns,2,0); // Draws the outer square glColor4d(red*0.8,green*0.8,blue*0.8,0.5); glBegin(GL_QUADS); glVertex2d(0.0,0.0); glVertex2d(1.0,0.0); glVertex2d(1.0,1.0); glVertex2d(0.0,1.0); glEnd(); glPopMatrix(); glDisable(GL_BLEND); } void GraphicBoard::drawBlock(const Block& block) { for (int i = 0; i < block.nbrOfSquares(); ++i) { Square square = block[i]; drawSquare(square); } } void GraphicBoard::drawSquare(const Square& square) { int column = square.column; int row = square.row; glColor4d(1,1,1,1); glPushMatrix(); glTranslated(column-1,row-1,0); glTranslated(0.5,0.5,0.0); drawSquare(square.blockType); glPopMatrix(); } void GraphicBoard::drawSquare(BlockType blockType) { mw::Sprite sprite = spriteI; switch (blockType) { case BLOCK_TYPE_J: sprite = spriteJ; break; case BLOCK_TYPE_L: sprite = spriteL; break; case BLOCK_TYPE_O: sprite = spriteO; break; case BLOCK_TYPE_S: sprite = spriteS; break; case BLOCK_TYPE_T: sprite = spriteT; break; case BLOCK_TYPE_Z: sprite = spriteZ; break; default: break; } sprite.draw(); } void GraphicBoard::drawGrid() const { glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int rows = tetrisBoard_.getNbrOfRows(); int colons = tetrisBoard_.getNbrOfColumns(); for (int row = 0; row < rows; ++row) { for (int colon = 0; colon < colons; ++colon) { glPushMatrix(); glTranslated(colon,row,0); //glScaled(0.5,0.5,0.5); drawGridSquare(); glPopMatrix(); } } glDisable(GL_BLEND); drawBeginArea(); } void GraphicBoard::drawGridSquare() const { double red = 0.8, green = 0.2, blue = 0.3; // Draws the outer square glColor4d(red*0.8,green*0.8,blue*0.8,0.6); glBegin(GL_QUADS); glVertex2d(0.0,0.0); glVertex2d(1.0,0.0); glVertex2d(1.0,1.0); glVertex2d(0.0,1.0); glEnd(); glPushMatrix(); glColor4d(red*0.1,green*0.1,blue*0.1,0.1); glTranslated(0.1,0.1,0); glScaled(0.8,0.8,1.0); // Draws the inner square glBegin(GL_QUADS); glVertex2d(0.0,0.0); glVertex2d(1.0,0.0); glVertex2d(1.0,1.0); glVertex2d(0.0,1.0); glEnd(); glPopMatrix(); } void GraphicBoard::glColorWhite() const { glColor4d(1,1,1,1); } void GraphicBoard::drawFrame(double x1, double y1, double x2, double y2, double width) const { glBegin(GL_QUADS); glVertex2d(x1, y1); glVertex2d(x2, y1); glVertex2d(x2, y1 + width); glVertex2d(x1, y1 + width); glVertex2d(x2 - width, y1); glVertex2d(x2, y1); glVertex2d(x2, y2); glVertex2d(x2 - width, y2); glVertex2d(x1, y2 - width); glVertex2d(x2, y2 - width); glVertex2d(x2, y2); glVertex2d(x1, y2); glVertex2d(x1, y1); glVertex2d(x1 + width, y1); glVertex2d(x1 + width, y2); glVertex2d(x1, y2); glEnd(); } <commit_msg>Changed illogical code. However, no changes was seen in the game by me.<commit_after>#include "graphicboard.h" #include "gamesprite.h" #include "gamefont.h" #include "tetrisboard.h" #include <mw/sprite.h> #include <mw/font.h> #include <mw/text.h> #include <mw/color.h> #include <SDL_opengl.h> #include <sstream> GraphicBoard::GraphicBoard(const TetrisBoard& tetrisBoard) : tetrisBoard_(tetrisBoard) { height_ = 800; // height for the board voidHeight_ = 10; borderLineThickness_ = 7; // Should be lower than voidHeight_ previwBorderSizeInSquares_ = 5; horizontalDistanceToText_ = 40; color_ = mw::Color(237/256.0,78/256.0,8/256.0); text1_ = mw::Text("Player",fontDefault); text2_ = mw::Text("Level ",fontDefault); text3_ = mw::Text("Points",fontDefault); text4_ = mw::Text("Rows",fontDefault); gameOverMessage_ = mw::Text("",fontDefault); gameOverMessage_.setCharacterSize(70); nbrOfClearedRows_ = 0; points_ = 0; level_ = 0; name_ = "Player"; } GraphicBoard::~GraphicBoard() { } void GraphicBoard::setNbrOfClearedRows(int nbr) { nbrOfClearedRows_ = nbr; } void GraphicBoard::setPoints(int points) { points_ = points; } void GraphicBoard::setLevel(int level) { level_ = level; } void GraphicBoard::setName(std::string name) { name_ = name; } void GraphicBoard::setGameOverMessage(std::string message) { gameOverMessage_.setText(message); } void GraphicBoard::draw() { pixlePerSquare_ = height_ / (tetrisBoard_.getNbrOfRows() + 2); glPushMatrix(); glTranslated(voidHeight_,voidHeight_,0.0); drawBoard(); drawInfo(); glPopMatrix(); if (tetrisBoard_.isGameOver()) { glPushMatrix(); // Put it in the middle. glTranslated(getWidth()*0.5-gameOverMessage_.getWidth()*0.5,getHeight()*0.5-gameOverMessage_.getHeight()*0.5,0.0); glColor3d(1,1,1); gameOverMessage_.draw(); glPopMatrix(); } drawBorder(); } double GraphicBoard::getWidth() const { if (previwBorderSizeInSquares_*pixlePerSquare_ > text1_.getWidth()) { return tetrisBoard_.getNbrOfColumns()*pixlePerSquare_ + horizontalDistanceToText_ + previwBorderSizeInSquares_*pixlePerSquare_ + voidHeight_*2; } else { return tetrisBoard_.getNbrOfColumns()*pixlePerSquare_ + horizontalDistanceToText_ + text1_.getWidth() + voidHeight_*2; } } double GraphicBoard::getHeight() const { return height_ + voidHeight_*2; } // Private void GraphicBoard::drawBorder() const { glPushMatrix(); color_.glColor4d(); drawFrame(0,0,getWidth(),getHeight(), borderLineThickness_); glPopMatrix(); } void GraphicBoard::drawInfo() { glPushMatrix(); glTranslated(pixlePerSquare_ * tetrisBoard_.getNbrOfColumns() + horizontalDistanceToText_ + voidHeight_,0,0); glTranslated(0,getHeight() - text1_.getCharacterSize() - 30,0); text1_.setText(name_); text1_.setCharacterSize(40); glColorWhite(); text1_.draw(); glPushMatrix(); glTranslated(80, -180,0); drawPreviewBlock(); glPopMatrix(); glTranslated(0,-650,0); std::stringstream ss; ss << "Level " << level_; text2_.setText(ss.str()); glColorWhite(); text2_.draw(); glTranslated(0,-40,0); ss.str(""); ss << "Points " << points_; text3_.setText(ss.str()); text3_.draw(); glTranslated(0,-40,0); ss.str(""); ss << "Rows " << nbrOfClearedRows_; text4_.setText(ss.str()); text4_.draw(); glPopMatrix(); } void GraphicBoard::drawPreviewBlock() { glPushMatrix(); const Block& block = tetrisBoard_.nextBlock(); int nbrOfSquares = block.nbrOfSquares(); double x = 0, y = 0; for (int i = 0; i < nbrOfSquares; ++i) { Square square = block[i]; x += square.column*1.0/nbrOfSquares; y += square.row*1.0/nbrOfSquares; } glScaled(pixlePerSquare_,pixlePerSquare_,1.0); glTranslated(-x+0.5,-y+0.5,0); // Why +0.5? drawBlock(block); glPopMatrix(); glPushMatrix(); // Size is 5 squares. glScaled(previwBorderSizeInSquares_*pixlePerSquare_,previwBorderSizeInSquares_*pixlePerSquare_,1); color_.glColor4d(); // Makes the line thickness to borderLineThickness_. drawFrame(-0.5,-0.5,0.5,0.5,1.0/(previwBorderSizeInSquares_*pixlePerSquare_)*borderLineThickness_); glPopMatrix(); } void GraphicBoard::drawBoard() { glPushMatrix(); glScaled(pixlePerSquare_,pixlePerSquare_,1.0); drawGrid(); const Squares& squares = tetrisBoard_.getGameBoard(); for (Squares::const_iterator it = squares.begin(); it != squares.end(); ++it) { const Square& square = *it; drawSquare(square); } drawBlock(tetrisBoard_.currentBlock()); drawBeginArea(); glPopMatrix(); } void GraphicBoard::drawBeginArea() const { int rows = tetrisBoard_.getNbrOfRows(); int columns = tetrisBoard_.getNbrOfColumns(); double red = 0.8, green = 0.2, blue = 0.3; glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glTranslated(0,rows,0); glScaled(columns,2,0); // Draws the outer square glColor4d(red*0.8,green*0.8,blue*0.8,0.5); glBegin(GL_QUADS); glVertex2d(0.0,0.0); glVertex2d(1.0,0.0); glVertex2d(1.0,1.0); glVertex2d(0.0,1.0); glEnd(); glPopMatrix(); glDisable(GL_BLEND); } void GraphicBoard::drawBlock(const Block& block) { for (int i = 0; i < block.nbrOfSquares(); ++i) { Square square = block[i]; drawSquare(square); } } void GraphicBoard::drawSquare(const Square& square) { int column = square.column; int row = square.row; glColor4d(1,1,1,1); glPushMatrix(); glTranslated(column-1,row-1,0); glTranslated(0.5,0.5,0.0); drawSquare(square.blockType); glPopMatrix(); } void GraphicBoard::drawSquare(BlockType blockType) { mw::Sprite sprite = spriteI; switch (blockType) { case BLOCK_TYPE_J: sprite = spriteJ; break; case BLOCK_TYPE_L: sprite = spriteL; break; case BLOCK_TYPE_O: sprite = spriteO; break; case BLOCK_TYPE_S: sprite = spriteS; break; case BLOCK_TYPE_T: sprite = spriteT; break; case BLOCK_TYPE_Z: sprite = spriteZ; break; default: break; } sprite.draw(); } void GraphicBoard::drawGrid() const { glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int rows = tetrisBoard_.getNbrOfRows(); int colons = tetrisBoard_.getNbrOfColumns(); for (int row = 0; row < rows; ++row) { for (int colon = 0; colon < colons; ++colon) { glPushMatrix(); glTranslated(colon,row,0); //glScaled(0.5,0.5,0.5); drawGridSquare(); glPopMatrix(); } } glDisable(GL_BLEND); drawBeginArea(); } void GraphicBoard::drawGridSquare() const { double red = 0.8, green = 0.2, blue = 0.3; // Draws the outer square glColor4d(red*0.8,green*0.8,blue*0.8,0.6); glBegin(GL_QUADS); glVertex2d(0.0,0.0); glVertex2d(1.0,0.0); glVertex2d(1.0,1.0); glVertex2d(0.0,1.0); glEnd(); glPushMatrix(); glColor4d(red*0.1,green*0.1,blue*0.1,0.1); glTranslated(0.1,0.1,0); glScaled(0.8,0.8,1.0); // Draws the inner square glBegin(GL_QUADS); glVertex2d(0.0,0.0); glVertex2d(1.0,0.0); glVertex2d(1.0,1.0); glVertex2d(0.0,1.0); glEnd(); glPopMatrix(); } void GraphicBoard::glColorWhite() const { glColor4d(1,1,1,1); } void GraphicBoard::drawFrame(double x1, double y1, double x2, double y2, double width) const { glBegin(GL_QUADS); glVertex2d(x1, y1); glVertex2d(x2, y1); glVertex2d(x2, y1 + width); glVertex2d(x1, y1 + width); glVertex2d(x2 - width, y1); glVertex2d(x2, y1); glVertex2d(x2, y2); glVertex2d(x2 - width, y2); glVertex2d(x1, y2 - width); glVertex2d(x2, y2 - width); glVertex2d(x2, y2); glVertex2d(x1, y2); glVertex2d(x1, y1); glVertex2d(x1 + width, y1); glVertex2d(x1 + width, y2); glVertex2d(x1, y2); glEnd(); } <|endoftext|>
<commit_before>#include "FffProcessor.h" namespace cura { FffProcessor FffProcessor::instance; // definition must be in cpp FffProcessor::FffProcessor() : polygon_generator(this) , gcode_writer(this) , meshgroup_number(0) { } int FffProcessor::getMeshgroupNr() { return meshgroup_number; } std::string FffProcessor::getAllSettingsString(MeshGroup& meshgroup, bool first_meshgroup) { std::stringstream sstream; if (first_meshgroup) { sstream << getAllLocalSettingsString(); // global settings sstream << " -g"; } else { sstream << " --next"; } sstream << meshgroup.getAllLocalSettingsString(); for (int extruder_nr = 0; extruder_nr < meshgroup.getExtruderCount(); extruder_nr++) { ExtruderTrain* train = meshgroup.getExtruderTrain(extruder_nr); sstream << " -e" << extruder_nr << train->getAllLocalSettingsString(); } for (unsigned int mesh_idx = 0; mesh_idx < meshgroup.meshes.size(); mesh_idx++) { Mesh& mesh = meshgroup.meshes[mesh_idx]; sstream << " -e" << mesh.getSettingAsIndex("extruder_nr") << " -l \"" << mesh_idx << "\"" << mesh.getAllLocalSettingsString(); } sstream << "\n"; return sstream.str(); } bool FffProcessor::processFiles(const std::vector< std::string >& files) { time_keeper.restart(); MeshGroup* meshgroup = new MeshGroup(this); for(std::string filename : files) { log("Loading %s from disk...\n", filename.c_str()); FMatrix3x3 matrix; if (!loadMeshIntoMeshGroup(meshgroup, filename.c_str(), matrix)) { logError("Failed to load model: %s\n", filename.c_str()); return false; } } meshgroup->finalize(); log("Loaded from disk in %5.3fs\n", time_keeper.restart()); return processMeshGroup(meshgroup); } bool FffProcessor::processMeshGroup(MeshGroup* meshgroup) { if (SHOW_ALL_SETTINGS) { logWarning(getAllSettingsString(*meshgroup, meshgroup_number == 0).c_str()); } time_keeper.restart(); if (!meshgroup) return false; TimeKeeper time_keeper_total; polygon_generator.setParent(meshgroup); gcode_writer.setParent(meshgroup); if (meshgroup->meshes.empty()) { Progress::messageProgress(Progress::Stage::FINISH, 1, 1); // 100% on this meshgroup log("Total time elapsed %5.2fs.\n", time_keeper_total.restart()); profile_string += getAllSettingsString(*meshgroup, meshgroup_number == 0); return true; } if (meshgroup->getSettingBoolean("wireframe_enabled")) { log("starting Neith Weaver...\n"); Weaver w(this); w.weave(meshgroup); log("starting Neith Gcode generation...\n"); Wireframe2gcode gcoder(w, gcode_writer.gcode, this); gcoder.writeGCode(); log("finished Neith Gcode generation...\n"); } else { SliceDataStorage storage(meshgroup); if (!polygon_generator.generateAreas(storage, meshgroup, time_keeper)) { return false; } Progress::messageProgressStage(Progress::Stage::EXPORT, &time_keeper); gcode_writer.writeGCode(storage, time_keeper); } Progress::messageProgress(Progress::Stage::FINISH, 1, 1); // 100% on this meshgroup if (CommandSocket::isInstantiated()) { CommandSocket::getInstance()->flushGcode(); CommandSocket::getInstance()->sendLayerData(); } log("Total time elapsed %5.2fs.\n", time_keeper_total.restart()); profile_string += getAllSettingsString(*meshgroup, meshgroup_number == 0); meshgroup_number++; polygon_generator.setParent(this); // otherwise consequent getSetting calls (e.g. for finalize) will refer to non-existent meshgroup gcode_writer.setParent(this); // otherwise consequent getSetting calls (e.g. for finalize) will refer to non-existent meshgroup return true; } } // namespace cura <commit_msg>fix: only process if there's any non-infill meshes (CURA-833)<commit_after>#include "FffProcessor.h" namespace cura { FffProcessor FffProcessor::instance; // definition must be in cpp FffProcessor::FffProcessor() : polygon_generator(this) , gcode_writer(this) , meshgroup_number(0) { } int FffProcessor::getMeshgroupNr() { return meshgroup_number; } std::string FffProcessor::getAllSettingsString(MeshGroup& meshgroup, bool first_meshgroup) { std::stringstream sstream; if (first_meshgroup) { sstream << getAllLocalSettingsString(); // global settings sstream << " -g"; } else { sstream << " --next"; } sstream << meshgroup.getAllLocalSettingsString(); for (int extruder_nr = 0; extruder_nr < meshgroup.getExtruderCount(); extruder_nr++) { ExtruderTrain* train = meshgroup.getExtruderTrain(extruder_nr); sstream << " -e" << extruder_nr << train->getAllLocalSettingsString(); } for (unsigned int mesh_idx = 0; mesh_idx < meshgroup.meshes.size(); mesh_idx++) { Mesh& mesh = meshgroup.meshes[mesh_idx]; sstream << " -e" << mesh.getSettingAsIndex("extruder_nr") << " -l \"" << mesh_idx << "\"" << mesh.getAllLocalSettingsString(); } sstream << "\n"; return sstream.str(); } bool FffProcessor::processFiles(const std::vector< std::string >& files) { time_keeper.restart(); MeshGroup* meshgroup = new MeshGroup(this); for(std::string filename : files) { log("Loading %s from disk...\n", filename.c_str()); FMatrix3x3 matrix; if (!loadMeshIntoMeshGroup(meshgroup, filename.c_str(), matrix)) { logError("Failed to load model: %s\n", filename.c_str()); return false; } } meshgroup->finalize(); log("Loaded from disk in %5.3fs\n", time_keeper.restart()); return processMeshGroup(meshgroup); } bool FffProcessor::processMeshGroup(MeshGroup* meshgroup) { if (SHOW_ALL_SETTINGS) { logWarning(getAllSettingsString(*meshgroup, meshgroup_number == 0).c_str()); } time_keeper.restart(); if (!meshgroup) return false; TimeKeeper time_keeper_total; polygon_generator.setParent(meshgroup); gcode_writer.setParent(meshgroup); bool empty = true; for (Mesh& mesh : meshgroup->meshes) { if (!mesh.getSettingBoolean("infill_mesh")) { empty = false; } } if (empty) { Progress::messageProgress(Progress::Stage::FINISH, 1, 1); // 100% on this meshgroup log("Total time elapsed %5.2fs.\n", time_keeper_total.restart()); profile_string += getAllSettingsString(*meshgroup, meshgroup_number == 0); return true; } if (meshgroup->getSettingBoolean("wireframe_enabled")) { log("starting Neith Weaver...\n"); Weaver w(this); w.weave(meshgroup); log("starting Neith Gcode generation...\n"); Wireframe2gcode gcoder(w, gcode_writer.gcode, this); gcoder.writeGCode(); log("finished Neith Gcode generation...\n"); } else { SliceDataStorage storage(meshgroup); if (!polygon_generator.generateAreas(storage, meshgroup, time_keeper)) { return false; } Progress::messageProgressStage(Progress::Stage::EXPORT, &time_keeper); gcode_writer.writeGCode(storage, time_keeper); } Progress::messageProgress(Progress::Stage::FINISH, 1, 1); // 100% on this meshgroup if (CommandSocket::isInstantiated()) { CommandSocket::getInstance()->flushGcode(); CommandSocket::getInstance()->sendLayerData(); } log("Total time elapsed %5.2fs.\n", time_keeper_total.restart()); profile_string += getAllSettingsString(*meshgroup, meshgroup_number == 0); meshgroup_number++; polygon_generator.setParent(this); // otherwise consequent getSetting calls (e.g. for finalize) will refer to non-existent meshgroup gcode_writer.setParent(this); // otherwise consequent getSetting calls (e.g. for finalize) will refer to non-existent meshgroup return true; } } // namespace cura <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2013 J-P Nurmi <[email protected]> * * 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 2 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. */ #include "ircsender.h" #include <QRegExp> /*! \file ircsender.h \brief #include &lt;IrcSender&gt; */ /*! \class IrcSender ircsender.h <IrcSender> \ingroup utility \brief The IrcSender class is a helper class for handling IRC message sender prefixes. An IRC message sender prefix as specified in RFC 1459: <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' &lt;user&gt; ] [ '@' &lt;host&gt; ] </pre> */ class IrcSenderPrivate : public QSharedData { public: QString prefix; QString name; QString user; QString host; }; /*! Constructs an invalid IrcSender. */ IrcSender::IrcSender() : d(new IrcSenderPrivate) { } /*! Constructs a new IrcSender initialized to \a prefix. */ IrcSender::IrcSender(const QString& prefix) : d(new IrcSenderPrivate) { setPrefix(prefix); } /*! Constructs a copy of \a other IrcSender. */ IrcSender::IrcSender(const IrcSender& other) : d(other.d) { } /*! Assigns an \a other IrcSender to this. */ IrcSender& IrcSender::operator=(const IrcSender& other) { if (this != &other) d = other.d; return *this; } /*! Destructs the IrcSender. */ IrcSender::~IrcSender() { } /*! Returns \c true if the sender is valid; otherwise \c false. A sender is considered valid if the name is not empty. */ bool IrcSender::isValid() const { return !d->name.isEmpty(); } /*! Returns the whole prefix. */ QString IrcSender::prefix() const { if (!isValid()) return QString(); QString pfx = d->name; if (!d->user.isEmpty()) pfx += "!" + d->user; if (!d->host.isEmpty()) pfx += "@" + d->host; return pfx; } /*! Sets the whole prefix. \warning Overrides any existing name, user or host. */ void IrcSender::setPrefix(const QString& prefix) { QRegExp rx("([^!@\\s]+)(![^@\\s]+)?(@\\S+)?"); bool match = rx.exactMatch(prefix.trimmed()); d->name = match ? rx.cap(1) : QString(); d->user = match ? rx.cap(2).mid(1) : QString(); d->host = match ? rx.cap(3).mid(1) : QString(); } /*! \fn QString IrcSender::name() const Returns the name. <pre> &lt;prefix&gt; ::= <b>&lt;servername&gt;</b> | <b>&lt;nick&gt;</b> [ '!' &lt;user&gt; ] [ '@' &lt;host&gt; ] </pre> */ QString IrcSender::name() const { return d->name; } /*! \fn void IrcSender::setName(const QString& name) Sets the name. <pre> &lt;prefix&gt; ::= <b>&lt;servername&gt;</b> | <b>&lt;nick&gt;</b> [ '!' &lt;user&gt; ] [ '@' &lt;host&gt; ] </pre> */ void IrcSender::setName(const QString& name) { d->name = name; } /*! \fn QString IrcSender::user() const Returns the user. <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' <b>&lt;user&gt;</b> ] [ '@' &lt;host&gt; ] </pre> */ QString IrcSender::user() const { return d->user; } /*! \fn void IrcSender::setUser(const QString& user) Sets the user. <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' <b>&lt;user&gt;</b> ] [ '@' &lt;host&gt; ] </pre> */ void IrcSender::setUser(const QString& user) { d->user = user; } /*! \fn QString IrcSender::host() const Returns the host. <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' &lt;user&gt; ] [ '@' <b>&lt;host&gt;</b> ] </pre> */ QString IrcSender::host() const { return d->host; } /*! \fn void IrcSender::setHost(const QString& host) Sets the host. <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' &lt;user&gt; ] [ '@' <b>&lt;host&gt;</b> ] </pre> */ void IrcSender::setHost(const QString& host) { d->host = host; } <commit_msg>IrcSender: lazy initialize name/user/host<commit_after>/* * Copyright (C) 2008-2013 J-P Nurmi <[email protected]> * * 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 2 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. */ #include "ircsender.h" #include <QRegExp> /*! \file ircsender.h \brief #include &lt;IrcSender&gt; */ /*! \class IrcSender ircsender.h <IrcSender> \ingroup utility \brief The IrcSender class is a helper class for handling IRC message sender prefixes. An IRC message sender prefix as specified in RFC 1459: <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' &lt;user&gt; ] [ '@' &lt;host&gt; ] </pre> */ class IrcSenderPrivate : public QSharedData { public: void init(); bool dirty; QString prefix; QString name; QString user; QString host; }; void IrcSenderPrivate::init() { QRegExp rx("([^!@\\s]+)(![^@\\s]+)?(@\\S+)?"); bool match = rx.exactMatch(prefix.trimmed()); name = match ? rx.cap(1) : QString(); user = match ? rx.cap(2).mid(1) : QString(); host = match ? rx.cap(3).mid(1) : QString(); } /*! Constructs an invalid IrcSender. */ IrcSender::IrcSender() : d(new IrcSenderPrivate) { d->dirty = false; } /*! Constructs a new IrcSender initialized to \a prefix. */ IrcSender::IrcSender(const QString& prefix) : d(new IrcSenderPrivate) { d->dirty = false; d->prefix = prefix; } /*! Constructs a copy of \a other IrcSender. */ IrcSender::IrcSender(const IrcSender& other) : d(other.d) { } /*! Assigns an \a other IrcSender to this. */ IrcSender& IrcSender::operator=(const IrcSender& other) { if (this != &other) d = other.d; return *this; } /*! Destructs the IrcSender. */ IrcSender::~IrcSender() { } /*! Returns \c true if the sender is valid; otherwise \c false. A sender is considered valid if the name is not empty. */ bool IrcSender::isValid() const { if (d->name.isEmpty()) d->init(); return !d->name.isEmpty(); } /*! Returns the whole prefix. */ QString IrcSender::prefix() const { if (d->dirty) { d->prefix = d->name; if (!d->user.isEmpty()) d->prefix += "!" + d->user; if (!d->host.isEmpty()) d->prefix += "@" + d->host; d->dirty = false; } return d->prefix; } /*! Sets the whole prefix. \warning Overrides any existing name, user or host. */ void IrcSender::setPrefix(const QString& prefix) { d->prefix = prefix; d->name.clear(); d->user.clear(); d->host.clear(); d->dirty = false; } /*! \fn QString IrcSender::name() const Returns the name. <pre> &lt;prefix&gt; ::= <b>&lt;servername&gt;</b> | <b>&lt;nick&gt;</b> [ '!' &lt;user&gt; ] [ '@' &lt;host&gt; ] </pre> */ QString IrcSender::name() const { if (d->name.isEmpty()) d->init(); return d->name; } /*! \fn void IrcSender::setName(const QString& name) Sets the name. <pre> &lt;prefix&gt; ::= <b>&lt;servername&gt;</b> | <b>&lt;nick&gt;</b> [ '!' &lt;user&gt; ] [ '@' &lt;host&gt; ] </pre> */ void IrcSender::setName(const QString& name) { d->name = name; d->dirty = true; } /*! \fn QString IrcSender::user() const Returns the user. <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' <b>&lt;user&gt;</b> ] [ '@' &lt;host&gt; ] </pre> */ QString IrcSender::user() const { if (d->user.isEmpty()) d->init(); return d->user; } /*! \fn void IrcSender::setUser(const QString& user) Sets the user. <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' <b>&lt;user&gt;</b> ] [ '@' &lt;host&gt; ] </pre> */ void IrcSender::setUser(const QString& user) { d->user = user; d->dirty = true; } /*! \fn QString IrcSender::host() const Returns the host. <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' &lt;user&gt; ] [ '@' <b>&lt;host&gt;</b> ] </pre> */ QString IrcSender::host() const { if (d->host.isEmpty()) d->init(); return d->host; } /*! \fn void IrcSender::setHost(const QString& host) Sets the host. <pre> &lt;prefix&gt; ::= &lt;servername&gt; | &lt;nick&gt; [ '!' &lt;user&gt; ] [ '@' <b>&lt;host&gt;</b> ] </pre> */ void IrcSender::setHost(const QString& host) { d->host = host; d->dirty = true; } <|endoftext|>
<commit_before>#include "matrix.h" #include "checks.h" template <std::size_t TSize1, std::size_t TSize2> std::size_t TestZeroMatrixAssign() { AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> a_matrix(TSize1, TSize2); a_matrix = AMatrix::ZeroMatrix<double>(TSize1, TSize2); for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) AMATRIX_CHECK_EQUAL(a_matrix(i, j), 0.00); return 0; // not failed } std::size_t TestMatrixAssign(std::size_t Size1, std::size_t Size2) { AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> a_matrix(Size1, Size2); AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> b_matrix(Size1, Size2); for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) a_matrix(i, j) = 2.33 * i - 4.52 * j; b_matrix = a_matrix; for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) AMATRIX_CHECK_EQUAL(b_matrix(i, j), 2.33 * i - 4.52 * j); return 0; // not failed } int main() { std::size_t number_of_failed_tests = 0; number_of_failed_tests += TestZeroMatrixAssign<1, 1>(); number_of_failed_tests += TestZeroMatrixAssign<1, 2>(); number_of_failed_tests += TestZeroMatrixAssign<2, 1>(); number_of_failed_tests += TestZeroMatrixAssign<2, 2>(); number_of_failed_tests += TestZeroMatrixAssign<3, 1>(); number_of_failed_tests += TestZeroMatrixAssign<3, 2>(); number_of_failed_tests += TestZeroMatrixAssign<3, 3>(); number_of_failed_tests += TestZeroMatrixAssign<1, 3>(); number_of_failed_tests += TestZeroMatrixAssign<2, 3>(); number_of_failed_tests += TestZeroMatrixAssign<3, 3>(); number_of_failed_tests += TestMatrixAssign(1, 1); number_of_failed_tests += TestMatrixAssign(1, 2); number_of_failed_tests += TestMatrixAssign(2, 1); number_of_failed_tests += TestMatrixAssign(2, 2); number_of_failed_tests += TestMatrixAssign(3, 1); number_of_failed_tests += TestMatrixAssign(3, 2); number_of_failed_tests += TestMatrixAssign(3, 3); number_of_failed_tests += TestMatrixAssign(1, 3); number_of_failed_tests += TestMatrixAssign(2, 3); number_of_failed_tests += TestMatrixAssign(3, 3); std::cout << number_of_failed_tests << "tests failed" << std::endl; return number_of_failed_tests; } <commit_msg>Adding size check<commit_after>#include "matrix.h" #include "checks.h" template <std::size_t TSize1, std::size_t TSize2> std::size_t TestZeroMatrixAssign() { AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> a_matrix(1,1); a_matrix = AMatrix::ZeroMatrix<double>(TSize1, TSize2); AMATRIX_CHECK_EQUAL(a_matrix.size1(), TSize1); AMATRIX_CHECK_EQUAL(a_matrix.size2(), TSize2); for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) AMATRIX_CHECK_EQUAL(a_matrix(i, j), 0.00); return 0; // not failed } std::size_t TestMatrixAssign(std::size_t Size1, std::size_t Size2) { AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> a_matrix(Size1, Size2); AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> b_matrix(Size1, Size2); for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) a_matrix(i, j) = 2.33 * i - 4.52 * j; b_matrix = a_matrix; AMATRIX_CHECK_EQUAL(b_matrix.size1(), Size1); AMATRIX_CHECK_EQUAL(b_matrix.size2(), Size2); for (std::size_t i = 0; i < a_matrix.size1(); i++) for (std::size_t j = 0; j < a_matrix.size2(); j++) AMATRIX_CHECK_EQUAL(b_matrix(i, j), 2.33 * i - 4.52 * j); return 0; // not failed } int main() { std::size_t number_of_failed_tests = 0; number_of_failed_tests += TestZeroMatrixAssign<1, 1>(); number_of_failed_tests += TestZeroMatrixAssign<1, 2>(); number_of_failed_tests += TestZeroMatrixAssign<2, 1>(); number_of_failed_tests += TestZeroMatrixAssign<2, 2>(); number_of_failed_tests += TestZeroMatrixAssign<3, 1>(); number_of_failed_tests += TestZeroMatrixAssign<3, 2>(); number_of_failed_tests += TestZeroMatrixAssign<3, 3>(); number_of_failed_tests += TestZeroMatrixAssign<1, 3>(); number_of_failed_tests += TestZeroMatrixAssign<2, 3>(); number_of_failed_tests += TestZeroMatrixAssign<3, 3>(); number_of_failed_tests += TestMatrixAssign(1, 1); number_of_failed_tests += TestMatrixAssign(1, 2); number_of_failed_tests += TestMatrixAssign(2, 1); number_of_failed_tests += TestMatrixAssign(2, 2); number_of_failed_tests += TestMatrixAssign(3, 1); number_of_failed_tests += TestMatrixAssign(3, 2); number_of_failed_tests += TestMatrixAssign(3, 3); number_of_failed_tests += TestMatrixAssign(1, 3); number_of_failed_tests += TestMatrixAssign(2, 3); number_of_failed_tests += TestMatrixAssign(3, 3); std::cout << number_of_failed_tests << "tests failed" << std::endl; return number_of_failed_tests; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: PageListWatcher.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-01-20 10:25:01 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "PageListWatcher.hxx" #include "sdpage.hxx" #include <tools/debug.hxx> #include <svx/svdmodel.hxx> ////////////////////////////////////////////////////////////////////////////// // #109538# void ImpPageListWatcher::ImpRecreateSortedPageListOnDemand() { // clear vectors maPageVectorStandard.clear(); maPageVectorNotes.clear(); mpHandoutPage = 0L; // build up vectors again const sal_uInt32 nPageCount(ImpGetPageCount()); for(sal_uInt32 a(0L); a < nPageCount; a++) { SdPage* pCandidate = ImpGetPage(a); DBG_ASSERT(pCandidate, "ImpPageListWatcher::ImpRecreateSortedPageListOnDemand: Invalid PageList in Model (!)"); switch(pCandidate->GetPageKind()) { case PK_STANDARD: { maPageVectorStandard.push_back(pCandidate); break; } case PK_NOTES: { maPageVectorNotes.push_back(pCandidate); break; } case PK_HANDOUT: { DBG_ASSERT(!mpHandoutPage, "ImpPageListWatcher::ImpRecreateSortedPageListOnDemand: Two Handout pages in PageList of Model (!)"); mpHandoutPage = pCandidate; break; } } } // set to valid mbPageListValid = sal_True; } ImpPageListWatcher::ImpPageListWatcher(const SdrModel& rModel) : mrModel(rModel), mpHandoutPage(0L), mbPageListValid(sal_False) { } ImpPageListWatcher::~ImpPageListWatcher() { } SdPage* ImpPageListWatcher::GetSdPage(PageKind ePgKind, sal_uInt32 nPgNum) { SdPage* pRetval(0L); if(!mbPageListValid) { ImpRecreateSortedPageListOnDemand(); } switch(ePgKind) { case PK_STANDARD: { DBG_ASSERT(nPgNum <= maPageVectorStandard.size(), "ImpPageListWatcher::GetSdPage: access out of range (!)"); if (nPgNum>=0 && nPgNum<maPageVectorStandard.size()) pRetval = maPageVectorStandard[nPgNum]; break; } case PK_NOTES: { DBG_ASSERT(nPgNum <= maPageVectorNotes.size(), "ImpPageListWatcher::GetSdPage: access out of range (!)"); if (nPgNum>=0 && nPgNum<maPageVectorNotes.size()) pRetval = maPageVectorNotes[nPgNum]; break; } case PK_HANDOUT: { DBG_ASSERT(mpHandoutPage, "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)"); DBG_ASSERT(nPgNum == 0L, "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)"); if (nPgNum == 0) pRetval = mpHandoutPage; break; } } return pRetval; } sal_uInt32 ImpPageListWatcher::GetSdPageCount(PageKind ePgKind) { sal_uInt32 nRetval(0L); if(!mbPageListValid) { ImpRecreateSortedPageListOnDemand(); } switch(ePgKind) { case PK_STANDARD: { nRetval = maPageVectorStandard.size(); break; } case PK_NOTES: { nRetval = maPageVectorNotes.size(); break; } case PK_HANDOUT: { if(mpHandoutPage) { nRetval = 1L; } break; } } return nRetval; } ////////////////////////////////////////////////////////////////////////////// sal_uInt32 ImpDrawPageListWatcher::ImpGetPageCount() const { return (sal_uInt32)mrModel.GetPageCount(); } SdPage* ImpDrawPageListWatcher::ImpGetPage(sal_uInt32 nIndex) const { return (SdPage*)mrModel.GetPage((sal_uInt16)nIndex); } ImpDrawPageListWatcher::ImpDrawPageListWatcher(const SdrModel& rModel) : ImpPageListWatcher(rModel) { } ImpDrawPageListWatcher::~ImpDrawPageListWatcher() { } ////////////////////////////////////////////////////////////////////////////// sal_uInt32 ImpMasterPageListWatcher::ImpGetPageCount() const { return (sal_uInt32)mrModel.GetMasterPageCount(); } SdPage* ImpMasterPageListWatcher::ImpGetPage(sal_uInt32 nIndex) const { return (SdPage*)mrModel.GetMasterPage((sal_uInt16)nIndex); } ImpMasterPageListWatcher::ImpMasterPageListWatcher(const SdrModel& rModel) : ImpPageListWatcher(rModel) { } ImpMasterPageListWatcher::~ImpMasterPageListWatcher() { } <commit_msg>INTEGRATION: CWS impress3ea1 (1.2.2); FILE MERGED 2004/02/20 12:39:05 cl 1.2.2.1: #114240# removed assertion, false alarm<commit_after>/************************************************************************* * * $RCSfile: PageListWatcher.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2004-02-26 14:32:16 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "PageListWatcher.hxx" #include "sdpage.hxx" #include <tools/debug.hxx> #include <svx/svdmodel.hxx> ////////////////////////////////////////////////////////////////////////////// // #109538# void ImpPageListWatcher::ImpRecreateSortedPageListOnDemand() { // clear vectors maPageVectorStandard.clear(); maPageVectorNotes.clear(); mpHandoutPage = 0L; // build up vectors again const sal_uInt32 nPageCount(ImpGetPageCount()); for(sal_uInt32 a(0L); a < nPageCount; a++) { SdPage* pCandidate = ImpGetPage(a); DBG_ASSERT(pCandidate, "ImpPageListWatcher::ImpRecreateSortedPageListOnDemand: Invalid PageList in Model (!)"); switch(pCandidate->GetPageKind()) { case PK_STANDARD: { maPageVectorStandard.push_back(pCandidate); break; } case PK_NOTES: { maPageVectorNotes.push_back(pCandidate); break; } case PK_HANDOUT: { DBG_ASSERT(!mpHandoutPage, "ImpPageListWatcher::ImpRecreateSortedPageListOnDemand: Two Handout pages in PageList of Model (!)"); mpHandoutPage = pCandidate; break; } } } // set to valid mbPageListValid = sal_True; } ImpPageListWatcher::ImpPageListWatcher(const SdrModel& rModel) : mrModel(rModel), mpHandoutPage(0L), mbPageListValid(sal_False) { } ImpPageListWatcher::~ImpPageListWatcher() { } SdPage* ImpPageListWatcher::GetSdPage(PageKind ePgKind, sal_uInt32 nPgNum) { SdPage* pRetval(0L); if(!mbPageListValid) { ImpRecreateSortedPageListOnDemand(); } switch(ePgKind) { case PK_STANDARD: { DBG_ASSERT(nPgNum <= maPageVectorStandard.size(), "ImpPageListWatcher::GetSdPage: access out of range (!)"); if (nPgNum>=0 && nPgNum<maPageVectorStandard.size()) pRetval = maPageVectorStandard[nPgNum]; break; } case PK_NOTES: { DBG_ASSERT(nPgNum <= maPageVectorNotes.size(), "ImpPageListWatcher::GetSdPage: access out of range (!)"); if (nPgNum>=0 && nPgNum<maPageVectorNotes.size()) pRetval = maPageVectorNotes[nPgNum]; break; } case PK_HANDOUT: { // #11420# for models used to transfer drawing shapes via clipboard its // ok to not have a handout page // DBG_ASSERT(mpHandoutPage, "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)"); DBG_ASSERT(nPgNum == 0L, "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)"); if (nPgNum == 0) pRetval = mpHandoutPage; break; } } return pRetval; } sal_uInt32 ImpPageListWatcher::GetSdPageCount(PageKind ePgKind) { sal_uInt32 nRetval(0L); if(!mbPageListValid) { ImpRecreateSortedPageListOnDemand(); } switch(ePgKind) { case PK_STANDARD: { nRetval = maPageVectorStandard.size(); break; } case PK_NOTES: { nRetval = maPageVectorNotes.size(); break; } case PK_HANDOUT: { if(mpHandoutPage) { nRetval = 1L; } break; } } return nRetval; } ////////////////////////////////////////////////////////////////////////////// sal_uInt32 ImpDrawPageListWatcher::ImpGetPageCount() const { return (sal_uInt32)mrModel.GetPageCount(); } SdPage* ImpDrawPageListWatcher::ImpGetPage(sal_uInt32 nIndex) const { return (SdPage*)mrModel.GetPage((sal_uInt16)nIndex); } ImpDrawPageListWatcher::ImpDrawPageListWatcher(const SdrModel& rModel) : ImpPageListWatcher(rModel) { } ImpDrawPageListWatcher::~ImpDrawPageListWatcher() { } ////////////////////////////////////////////////////////////////////////////// sal_uInt32 ImpMasterPageListWatcher::ImpGetPageCount() const { return (sal_uInt32)mrModel.GetMasterPageCount(); } SdPage* ImpMasterPageListWatcher::ImpGetPage(sal_uInt32 nIndex) const { return (SdPage*)mrModel.GetMasterPage((sal_uInt16)nIndex); } ImpMasterPageListWatcher::ImpMasterPageListWatcher(const SdrModel& rModel) : ImpPageListWatcher(rModel) { } ImpMasterPageListWatcher::~ImpMasterPageListWatcher() { } <|endoftext|>
<commit_before> #include "storage/Devices/BlkDeviceImpl.h" #include "storage/Devices/Filesystem.h" #include "storage/Utils/XmlFile.h" #include "storage/Utils/HumanString.h" #include "storage/Utils/StorageTmpl.h" #include "storage/SystemInfo/SystemInfo.h" #include "storage/Utils/StorageDefines.h" #include "storage/Utils/SystemCmd.h" namespace storage { BlkDevice::Impl::Impl(const xmlNode* node) : Device::Impl(node), name(), size_k(0), major_minor(0) { if (!getChildValue(node, "name", name)) throw runtime_error("no name"); getChildValue(node, "sysfs-name", sysfs_name); getChildValue(node, "sysfs-path", sysfs_path); getChildValue(node, "size-k", size_k); unsigned int major = 0, minor = 0; if (getChildValue(node, "major", major) && getChildValue(node, "minor", minor)) major_minor = makedev(major, minor); getChildValue(node, "udev-path", udev_path); getChildValue(node, "udev-id", udev_ids); } void BlkDevice::Impl::probe(SystemInfo& systeminfo) { Device::Impl::probe(systeminfo); const CmdUdevadmInfo& cmdudevadminfo = systeminfo.getCmdUdevadmInfo(name); sysfs_name = cmdudevadminfo.get_name(); sysfs_path = cmdudevadminfo.get_path(); // TODO read "sysfs_path + /size" and drop ProcParts? if (!systeminfo.getProcParts().getSize(sysfs_name, size_k)) throw; major_minor = cmdudevadminfo.get_majorminor(); if (!cmdudevadminfo.get_by_path_links().empty()) { udev_path = cmdudevadminfo.get_by_path_links().front(); process_udev_path(udev_path); } if (!cmdudevadminfo.get_by_id_links().empty()) { udev_ids = cmdudevadminfo.get_by_id_links(); process_udev_ids(udev_ids); } } void BlkDevice::Impl::save(xmlNode* node) const { Device::Impl::save(node); setChildValue(node, "name", name); setChildValue(node, "sysfs-name", sysfs_name); setChildValue(node, "sysfs-path", sysfs_path); setChildValueIf(node, "size-k", size_k, size_k > 0); setChildValueIf(node, "major", gnu_dev_major(major_minor), major_minor != 0); setChildValueIf(node, "minor", gnu_dev_minor(major_minor), major_minor != 0); setChildValueIf(node, "udev-path", udev_path, !udev_path.empty()); setChildValueIf(node, "udev-id", udev_ids, !udev_ids.empty()); } void BlkDevice::Impl::set_name(const string& name) { Impl::name = name; } void BlkDevice::Impl::set_size_k(unsigned long long size_k) { Impl::size_k = size_k; } string BlkDevice::Impl::get_size_string() const { return byte_to_humanstring(1024 * get_size_k(), false, 2, false); } bool BlkDevice::Impl::equal(const Device::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); if (!Device::Impl::equal(rhs)) return false; return name == rhs.name && sysfs_name == rhs.sysfs_name && sysfs_path == rhs.sysfs_path && size_k == rhs.size_k && major_minor == rhs.major_minor; } void BlkDevice::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); Device::Impl::log_diff(log, rhs); storage::log_diff(log, "name", name, rhs.name); storage::log_diff(log, "sysfs-name", sysfs_name, rhs.sysfs_name); storage::log_diff(log, "sysfs-path", sysfs_path, rhs.sysfs_path); storage::log_diff(log, "size_k", size_k, rhs.size_k); storage::log_diff(log, "major", get_major(), rhs.get_major()); storage::log_diff(log, "minor", get_minor(), rhs.get_minor()); } void BlkDevice::Impl::print(std::ostream& out) const { Device::Impl::print(out); out << " name:" << get_name(); if (!sysfs_name.empty()) out << " sysfs-name:" << sysfs_name; if (!sysfs_path.empty()) out << " sysfs-path:" << sysfs_path; if (get_size_k() != 0) out << " size_k:" << get_size_k(); if (get_majorminor() != 0) out << " major:" << get_major() << " minor:" << get_minor(); if (!udev_path.empty()) out << " udev-path:" << udev_path; if (!udev_ids.empty()) out << " udev-ids:" << udev_ids; } Filesystem* BlkDevice::Impl::get_filesystem() { if (get_device()->num_children() != 1) throw runtime_error("blkdevice has no children"); const Devicegraph* devicegraph = get_devicegraph(); Device* child = devicegraph->get_impl().graph[devicegraph->get_impl().child(get_vertex())].get(); return dynamic_cast<Filesystem*>(child); } const Filesystem* BlkDevice::Impl::get_filesystem() const { if (get_device()->num_children() != 1) throw runtime_error("blkdevice has no children"); const Devicegraph* devicegraph = get_devicegraph(); const Device* child = devicegraph->get_impl().graph[devicegraph->get_impl().child(get_vertex())].get(); return dynamic_cast<const Filesystem*>(child); } void BlkDevice::Impl::wait_for_device() const { string cmd_line(UDEVADMBIN " settle --timeout=20"); SystemCmd cmd(cmd_line); bool exist = access(name.c_str(), R_OK) == 0; y2mil("name:" << name << " exist:" << exist); if (!exist) { for (int count = 0; count < 500; ++count) { usleep(10000); exist = access(name.c_str(), R_OK) == 0; if (exist) break; } y2mil("name:" << name << " exist:" << exist); } if (!exist) throw runtime_error("wait_for_device failed"); } } <commit_msg>- don't save empty values<commit_after> #include "storage/Devices/BlkDeviceImpl.h" #include "storage/Devices/Filesystem.h" #include "storage/Utils/XmlFile.h" #include "storage/Utils/HumanString.h" #include "storage/Utils/StorageTmpl.h" #include "storage/SystemInfo/SystemInfo.h" #include "storage/Utils/StorageDefines.h" #include "storage/Utils/SystemCmd.h" namespace storage { BlkDevice::Impl::Impl(const xmlNode* node) : Device::Impl(node), name(), size_k(0), major_minor(0) { if (!getChildValue(node, "name", name)) throw runtime_error("no name"); getChildValue(node, "sysfs-name", sysfs_name); getChildValue(node, "sysfs-path", sysfs_path); getChildValue(node, "size-k", size_k); unsigned int major = 0, minor = 0; if (getChildValue(node, "major", major) && getChildValue(node, "minor", minor)) major_minor = makedev(major, minor); getChildValue(node, "udev-path", udev_path); getChildValue(node, "udev-id", udev_ids); } void BlkDevice::Impl::probe(SystemInfo& systeminfo) { Device::Impl::probe(systeminfo); const CmdUdevadmInfo& cmdudevadminfo = systeminfo.getCmdUdevadmInfo(name); sysfs_name = cmdudevadminfo.get_name(); sysfs_path = cmdudevadminfo.get_path(); // TODO read "sysfs_path + /size" and drop ProcParts? if (!systeminfo.getProcParts().getSize(sysfs_name, size_k)) throw; major_minor = cmdudevadminfo.get_majorminor(); if (!cmdudevadminfo.get_by_path_links().empty()) { udev_path = cmdudevadminfo.get_by_path_links().front(); process_udev_path(udev_path); } if (!cmdudevadminfo.get_by_id_links().empty()) { udev_ids = cmdudevadminfo.get_by_id_links(); process_udev_ids(udev_ids); } } void BlkDevice::Impl::save(xmlNode* node) const { Device::Impl::save(node); setChildValue(node, "name", name); setChildValueIf(node, "sysfs-name", sysfs_name, !sysfs_name.empty()); setChildValueIf(node, "sysfs-path", sysfs_path, !sysfs_path.empty()); setChildValueIf(node, "size-k", size_k, size_k > 0); setChildValueIf(node, "major", gnu_dev_major(major_minor), major_minor != 0); setChildValueIf(node, "minor", gnu_dev_minor(major_minor), major_minor != 0); setChildValueIf(node, "udev-path", udev_path, !udev_path.empty()); setChildValueIf(node, "udev-id", udev_ids, !udev_ids.empty()); } void BlkDevice::Impl::set_name(const string& name) { Impl::name = name; } void BlkDevice::Impl::set_size_k(unsigned long long size_k) { Impl::size_k = size_k; } string BlkDevice::Impl::get_size_string() const { return byte_to_humanstring(1024 * get_size_k(), false, 2, false); } bool BlkDevice::Impl::equal(const Device::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); if (!Device::Impl::equal(rhs)) return false; return name == rhs.name && sysfs_name == rhs.sysfs_name && sysfs_path == rhs.sysfs_path && size_k == rhs.size_k && major_minor == rhs.major_minor; } void BlkDevice::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); Device::Impl::log_diff(log, rhs); storage::log_diff(log, "name", name, rhs.name); storage::log_diff(log, "sysfs-name", sysfs_name, rhs.sysfs_name); storage::log_diff(log, "sysfs-path", sysfs_path, rhs.sysfs_path); storage::log_diff(log, "size_k", size_k, rhs.size_k); storage::log_diff(log, "major", get_major(), rhs.get_major()); storage::log_diff(log, "minor", get_minor(), rhs.get_minor()); } void BlkDevice::Impl::print(std::ostream& out) const { Device::Impl::print(out); out << " name:" << get_name(); if (!sysfs_name.empty()) out << " sysfs-name:" << sysfs_name; if (!sysfs_path.empty()) out << " sysfs-path:" << sysfs_path; if (get_size_k() != 0) out << " size_k:" << get_size_k(); if (get_majorminor() != 0) out << " major:" << get_major() << " minor:" << get_minor(); if (!udev_path.empty()) out << " udev-path:" << udev_path; if (!udev_ids.empty()) out << " udev-ids:" << udev_ids; } Filesystem* BlkDevice::Impl::get_filesystem() { if (get_device()->num_children() != 1) throw runtime_error("blkdevice has no children"); const Devicegraph* devicegraph = get_devicegraph(); Device* child = devicegraph->get_impl().graph[devicegraph->get_impl().child(get_vertex())].get(); return dynamic_cast<Filesystem*>(child); } const Filesystem* BlkDevice::Impl::get_filesystem() const { if (get_device()->num_children() != 1) throw runtime_error("blkdevice has no children"); const Devicegraph* devicegraph = get_devicegraph(); const Device* child = devicegraph->get_impl().graph[devicegraph->get_impl().child(get_vertex())].get(); return dynamic_cast<const Filesystem*>(child); } void BlkDevice::Impl::wait_for_device() const { string cmd_line(UDEVADMBIN " settle --timeout=20"); SystemCmd cmd(cmd_line); bool exist = access(name.c_str(), R_OK) == 0; y2mil("name:" << name << " exist:" << exist); if (!exist) { for (int count = 0; count < 500; ++count) { usleep(10000); exist = access(name.c_str(), R_OK) == 0; if (exist) break; } y2mil("name:" << name << " exist:" << exist); } if (!exist) throw runtime_error("wait_for_device failed"); } } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR 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 "system/globalenv.h" #include "functions/Accessors.h" #include "runtime/accessors/AccessorsImpl.h" #include "types/typeops.h" using namespace std; namespace zorba { PlanIter_t fn_data_func::codegen( const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann ) const { return new FnDataIterator ( loc, argv[0] ); } xqtref_t fn_data_func::return_type (const std::vector<xqtref_t> &arg_types) const { if (TypeOps::is_subtype (*arg_types [0], *GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR)) return arg_types [0]; else return sig.return_type (); } /******************************************************************************* ********************************************************************************/ PlanIter_t fn_root_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnRootIterator(loc, argv); } /******************************************************************************* ********************************************************************************/ PlanIter_t fn_nodename_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnNodeNameIterator(loc, argv); } /******************************************************************************* 2.2 fn:nilled ********************************************************************************/ PlanIter_t fn_nilled_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnNilledIterator(loc, argv); } /******************************************************************************* 2.5 fn:base-uri ********************************************************************************/ PlanIter_t fn_base_uri_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnBaseUriIterator(loc, argv); } /******************************************************************************* 2.6 fn:document-uri ********************************************************************************/ PlanIter_t fn_document_uri_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnDocumentUriIterator(loc, argv); } /******************************************************************************* ********************************************************************************/ PlanIter_t fn_name_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { PlanIter_t nnIter = new FnNodeNameIterator(loc, argv); std::vector<PlanIter_t> lVec; lVec.push_back(nnIter); return new FnStringIterator(loc, lVec, true); } } /* namespace zorba */ <commit_msg>fn:data() static typing<commit_after>/* * Copyright 2006-2008 The FLWOR 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 "system/globalenv.h" #include "functions/Accessors.h" #include "runtime/accessors/AccessorsImpl.h" #include "types/typeops.h" using namespace std; namespace zorba { PlanIter_t fn_data_func::codegen( const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann ) const { return new FnDataIterator ( loc, argv[0] ); } xqtref_t fn_data_func::return_type (const std::vector<xqtref_t> &arg_types) const { if (TypeOps::is_subtype (*arg_types [0], *GENV_TYPESYSTEM.ANY_ATOMIC_TYPE_STAR)) return arg_types [0]; // includes () case else return GENV_TYPESYSTEM.create_atomic_type (TypeConstants::XS_ANY_ATOMIC, TypeOps::quantifier (*arg_types [0])); } /******************************************************************************* ********************************************************************************/ PlanIter_t fn_root_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnRootIterator(loc, argv); } /******************************************************************************* ********************************************************************************/ PlanIter_t fn_nodename_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnNodeNameIterator(loc, argv); } /******************************************************************************* 2.2 fn:nilled ********************************************************************************/ PlanIter_t fn_nilled_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnNilledIterator(loc, argv); } /******************************************************************************* 2.5 fn:base-uri ********************************************************************************/ PlanIter_t fn_base_uri_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnBaseUriIterator(loc, argv); } /******************************************************************************* 2.6 fn:document-uri ********************************************************************************/ PlanIter_t fn_document_uri_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { return new FnDocumentUriIterator(loc, argv); } /******************************************************************************* ********************************************************************************/ PlanIter_t fn_name_func::codegen (const QueryLoc& loc, std::vector<PlanIter_t>& argv, AnnotationHolder &ann) const { PlanIter_t nnIter = new FnNodeNameIterator(loc, argv); std::vector<PlanIter_t> lVec; lVec.push_back(nnIter); return new FnStringIterator(loc, lVec, true); } } /* namespace zorba */ <|endoftext|>
<commit_before>// 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 // // 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 <cstdlib> #include <iostream> #include <stdexcept> #include "frontend/server/server.h" #include "google/cloud/spanner/client.h" #include "google/cloud/spanner/create_instance_request_builder.h" #include "google/cloud/spanner/database_admin_client.h" #include "google/cloud/spanner/instance_admin_client.h" using Server = ::google::spanner::emulator::frontend::Server; using ::google::cloud::future; using ::google::cloud::StatusOr; using ::google::cloud::spanner::DatabaseAdminClient; using ::google::cloud::spanner::v0::ConnectionOptions; const std::string server_address = "localhost:1234"; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { Server::Options options; options.server_address = server_address; std::unique_ptr<Server> server = Server::Create(options); if (!server) { return EXIT_FAILURE; } std::cout << "Server Up, Executing Test Query" << std::endl; try { // This is the connection to the emulator. ConnectionOptions emulator_connection; emulator_connection.set_endpoint(server_address) .set_credentials(grpc::InsecureChannelCredentials()); // First we create an instance to create our database on. google::cloud::spanner::Instance instance("emulator", "emulator"); google::cloud::spanner::InstanceAdminClient instance_client( google::cloud::spanner::MakeInstanceAdminConnection( emulator_connection)); future<StatusOr<google::spanner::admin::instance::v1::Instance>> instance_future = instance_client.CreateInstance( google::cloud::spanner::CreateInstanceRequestBuilder(instance, "emulator") .SetDisplayName("emulator") .SetNodeCount(1) .SetLabels({{"label-key", "label-value"}}) .Build()); StatusOr<google::spanner::admin::instance::v1::Instance> status_or_instance = instance_future.get(); if (!status_or_instance) { throw std::runtime_error(status_or_instance.status().message()); } std::cout << "Created instance [" << instance << "]\n"; // Then we create a simple database. google::cloud::spanner::Database database(instance, "test-db"); auto admin_client = DatabaseAdminClient(google::cloud::spanner::MakeDatabaseAdminConnection( emulator_connection)); future<StatusOr<google::spanner::admin::database::v1::Database>> f = admin_client.CreateDatabase(database, {R"""( CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX) ) PRIMARY KEY (SingerId))""", R"""( CREATE TABLE Albums ( SingerId INT64 NOT NULL, AlbumId INT64 NOT NULL, AlbumTitle STRING(MAX) ) PRIMARY KEY (SingerId, AlbumId), INTERLEAVE IN PARENT Singers ON DELETE CASCADE)"""}); StatusOr<google::spanner::admin::database::v1::Database> db = f.get(); if (!db) throw std::runtime_error(db.status().message()); std::cout << "Created database [" << database << "]\n"; google::cloud::spanner::Client client( google::cloud::spanner::MakeConnection(database, emulator_connection)); std::string query = std::string("INSERT INTO Singers (FirstName) VALUES (") + std::string((char*)Data, size) + std::string(")"); client.ExecuteQuery( google::cloud::spanner::SqlStatement(query); ) // auto rows = client.ExecuteQuery( // google::cloud::spanner::SqlStatement("SELECT 'Hello World'")); // for (auto const& row : // google::cloud::spanner::StreamOf<std::tuple<std::string>>(rows)) { // if (!row) throw std::runtime_error(row.status().message()); // std::cout << std::get<0>(*row) << "\n"; // } return 0; } catch (std::exception const& ex) { std::cerr << "Standard exception raised: " << ex.what() << "\n"; return 1; } server->Shutdown(); return 0; } <commit_msg>Added fixes for end-to-end testing<commit_after>// 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 // // 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 <cstdlib> #include <iostream> #include <stdexcept> #include "frontend/server/server.h" #include "google/cloud/spanner/client.h" #include "google/cloud/spanner/create_instance_request_builder.h" #include "google/cloud/spanner/database_admin_client.h" #include "google/cloud/spanner/instance_admin_client.h" using Server = ::google::spanner::emulator::frontend::Server; using ::google::cloud::future; using ::google::cloud::StatusOr; using ::google::cloud::spanner::DatabaseAdminClient; using ::google::cloud::spanner::v0::ConnectionOptions; #ifdef __OSS_FUZZ__ #define OVERWRITE 1 bool DoOssFuzzInit() { namespace fs = std::filesystem; fs::path originDir; try { originDir = fs::canonical(fs::read_symlink("/proc/self/exe")).parent_path(); } catch (const std::exception& e) { return false; } fs::path tzdataDir = originDir / "data/zoneinfo/"; if (setenv("TZDIR", tzdataDir.c_str(), OVERWRITE)) { return false; } return true; } #endif const std::string server_address = "localhost:1234"; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { #ifdef __OSS_FUZZ__ static bool Initialized = DoOssFuzzInit(); if (!Initialized) { std::abort(); } #endif Server::Options options; options.server_address = server_address; std::unique_ptr<Server> server = Server::Create(options); if (!server) { return EXIT_FAILURE; } std::cout << "Server Up, Executing Test Query" << std::endl; try { // This is the connection to the emulator. ConnectionOptions emulator_connection; emulator_connection.set_endpoint(server_address) .set_credentials(grpc::InsecureChannelCredentials()); // First we create an instance to create our database on. google::cloud::spanner::Instance instance("emulator", "emulator"); google::cloud::spanner::InstanceAdminClient instance_client( google::cloud::spanner::MakeInstanceAdminConnection( emulator_connection)); future<StatusOr<google::spanner::admin::instance::v1::Instance>> instance_future = instance_client.CreateInstance( google::cloud::spanner::CreateInstanceRequestBuilder(instance, "emulator") .SetDisplayName("emulator") .SetNodeCount(1) .SetLabels({{"label-key", "label-value"}}) .Build()); StatusOr<google::spanner::admin::instance::v1::Instance> status_or_instance = instance_future.get(); if (!status_or_instance) { throw std::runtime_error(status_or_instance.status().message()); } std::cout << "Created instance [" << instance << "]\n"; // Then we create a simple database. google::cloud::spanner::Database database(instance, "test-db"); auto admin_client = DatabaseAdminClient(google::cloud::spanner::MakeDatabaseAdminConnection( emulator_connection)); future<StatusOr<google::spanner::admin::database::v1::Database>> f = admin_client.CreateDatabase(database, {R"""( CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX) ) PRIMARY KEY (SingerId))""", R"""( CREATE TABLE Albums ( SingerId INT64 NOT NULL, AlbumId INT64 NOT NULL, AlbumTitle STRING(MAX) ) PRIMARY KEY (SingerId, AlbumId), INTERLEAVE IN PARENT Singers ON DELETE CASCADE)"""}); StatusOr<google::spanner::admin::database::v1::Database> db = f.get(); if (!db) throw std::runtime_error(db.status().message()); std::cout << "Created database [" << database << "]\n"; google::cloud::spanner::Client client( google::cloud::spanner::MakeConnection(database, emulator_connection)); std::string query = std::string("INSERT INTO Singers (FirstName) VALUES (") + std::string((char*)Data, size) + std::string(")"); client.ExecuteQuery( google::cloud::spanner::SqlStatement(query); ) // auto rows = client.ExecuteQuery( // google::cloud::spanner::SqlStatement("SELECT 'Hello World'")); // for (auto const& row : // google::cloud::spanner::StreamOf<std::tuple<std::string>>(rows)) { // if (!row) throw std::runtime_error(row.status().message()); // std::cout << std::get<0>(*row) << "\n"; // } return 0; } catch (std::exception const& ex) { std::cerr << "Standard exception raised: " << ex.what() << "\n"; return 1; } server->Shutdown(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/event_executor.h" #include <windows.h> #include "base/bind.h" #include "base/compiler_specific.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "remoting/host/clipboard.h" #include "remoting/proto/event.pb.h" // SkSize.h assumes that stdint.h-style types are already defined. #include "third_party/skia/include/core/SkTypes.h" #include "third_party/skia/include/core/SkSize.h" namespace remoting { namespace { using protocol::ClipboardEvent; using protocol::KeyEvent; using protocol::MouseEvent; // USB to XKB keycode map table. #define USB_KEYMAP(usb, xkb, win, mac) {usb, win} #include "ui/base/keycodes/usb_keycode_map.h" #undef USB_KEYMAP // A class to generate events on Windows. class EventExecutorWin : public EventExecutor { public: EventExecutorWin(scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner); virtual ~EventExecutorWin() {} // ClipboardStub interface. virtual void InjectClipboardEvent(const ClipboardEvent& event) OVERRIDE; // InputStub interface. virtual void InjectKeyEvent(const KeyEvent& event) OVERRIDE; virtual void InjectMouseEvent(const MouseEvent& event) OVERRIDE; // EventExecutor interface. virtual void Start( scoped_ptr<protocol::ClipboardStub> client_clipboard) OVERRIDE; virtual void StopAndDelete() OVERRIDE; private: void HandleKey(const KeyEvent& event); void HandleMouse(const MouseEvent& event); scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; scoped_ptr<Clipboard> clipboard_; DISALLOW_COPY_AND_ASSIGN(EventExecutorWin); }; EventExecutorWin::EventExecutorWin( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) : main_task_runner_(main_task_runner), ui_task_runner_(ui_task_runner), clipboard_(Clipboard::Create()) { } void EventExecutorWin::InjectClipboardEvent(const ClipboardEvent& event) { if (!ui_task_runner_->BelongsToCurrentThread()) { ui_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::InjectClipboardEvent, base::Unretained(this), event)); return; } clipboard_->InjectClipboardEvent(event); } void EventExecutorWin::InjectKeyEvent(const KeyEvent& event) { if (!main_task_runner_->BelongsToCurrentThread()) { main_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::InjectKeyEvent, base::Unretained(this), event)); return; } HandleKey(event); } void EventExecutorWin::InjectMouseEvent(const MouseEvent& event) { if (!main_task_runner_->BelongsToCurrentThread()) { main_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::InjectMouseEvent, base::Unretained(this), event)); return; } HandleMouse(event); } void EventExecutorWin::Start( scoped_ptr<protocol::ClipboardStub> client_clipboard) { if (!ui_task_runner_->BelongsToCurrentThread()) { ui_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::Start, base::Unretained(this), base::Passed(&client_clipboard))); return; } clipboard_->Start(client_clipboard.Pass()); } void EventExecutorWin::StopAndDelete() { if (!ui_task_runner_->BelongsToCurrentThread()) { ui_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::StopAndDelete, base::Unretained(this))); return; } clipboard_->Stop(); delete this; } void EventExecutorWin::HandleKey(const KeyEvent& event) { // HostEventDispatcher should filter events missing the pressed field. DCHECK(event.has_pressed()); DCHECK(event.has_usb_keycode()); // Reset the system idle suspend timeout. SetThreadExecutionState(ES_SYSTEM_REQUIRED); // Populate the a Windows INPUT structure for the event. INPUT input; memset(&input, 0, sizeof(input)); input.type = INPUT_KEYBOARD; input.ki.time = 0; input.ki.dwFlags = KEYEVENTF_SCANCODE; if (!event.pressed()) input.ki.dwFlags |= KEYEVENTF_KEYUP; int scancode = UsbKeycodeToNativeKeycode(event.usb_keycode()); VLOG(3) << "Converting USB keycode: " << std::hex << event.usb_keycode() << " to scancode: " << scancode << std::dec; // Ignore events which can't be mapped. if (scancode == kInvalidKeycode) return; // Windows scancodes are only 8-bit, so store the low-order byte into the // event and set the extended flag if any high-order bits are set. The only // high-order values we should see are 0xE0 or 0xE1. The extended bit usually // distinguishes keys with the same meaning, e.g. left & right shift. input.ki.wScan = scancode & 0xFF; if ((scancode & 0xFF00) != 0x0000) { input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY; } if (SendInput(1, &input, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a key event"; } } void EventExecutorWin::HandleMouse(const MouseEvent& event) { // Reset the system idle suspend timeout. SetThreadExecutionState(ES_SYSTEM_REQUIRED); // TODO(garykac) Collapse mouse (x,y) and button events into a single // input event when possible. if (event.has_x() && event.has_y()) { int x = event.x(); int y = event.y(); INPUT input; input.type = INPUT_MOUSE; input.mi.time = 0; SkISize screen_size(SkISize::Make(GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN))); if ((screen_size.width() > 1) && (screen_size.height() > 1)) { x = std::max(0, std::min(screen_size.width(), x)); y = std::max(0, std::min(screen_size.height(), y)); input.mi.dx = static_cast<int>((x * 65535) / (screen_size.width() - 1)); input.mi.dy = static_cast<int>((y * 65535) / (screen_size.height() - 1)); input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK; if (SendInput(1, &input, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a mouse move event"; } } } if (event.has_wheel_offset_x() && event.has_wheel_offset_y()) { INPUT wheel; wheel.type = INPUT_MOUSE; wheel.mi.time = 0; int dx = event.wheel_offset_x(); int dy = event.wheel_offset_y(); if (dx != 0) { wheel.mi.mouseData = dx * WHEEL_DELTA; wheel.mi.dwFlags = MOUSEEVENTF_HWHEEL; if (SendInput(1, &wheel, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a mouse wheel(x) event"; } } if (dy != 0) { wheel.mi.mouseData = dy * WHEEL_DELTA; wheel.mi.dwFlags = MOUSEEVENTF_WHEEL; if (SendInput(1, &wheel, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a mouse wheel(y) event"; } } } if (event.has_button() && event.has_button_down()) { INPUT button_event; button_event.type = INPUT_MOUSE; button_event.mi.time = 0; button_event.mi.dx = 0; button_event.mi.dy = 0; MouseEvent::MouseButton button = event.button(); bool down = event.button_down(); if (button == MouseEvent::BUTTON_LEFT) { button_event.mi.dwFlags = down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP; } else if (button == MouseEvent::BUTTON_MIDDLE) { button_event.mi.dwFlags = down ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP; } else if (button == MouseEvent::BUTTON_RIGHT) { button_event.mi.dwFlags = down ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP; } else { button_event.mi.dwFlags = down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP; } if (SendInput(1, &button_event, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a mouse button event"; } } } } // namespace scoped_ptr<EventExecutor> EventExecutor::Create( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) { return scoped_ptr<EventExecutor>( new EventExecutorWin(main_task_runner, ui_task_runner)); } } // namespace remoting <commit_msg>Update EventExecutorWin to use wheel deltas if present.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/event_executor.h" #include <windows.h> #include "base/bind.h" #include "base/compiler_specific.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "remoting/host/clipboard.h" #include "remoting/proto/event.pb.h" // SkSize.h assumes that stdint.h-style types are already defined. #include "third_party/skia/include/core/SkTypes.h" #include "third_party/skia/include/core/SkSize.h" namespace remoting { namespace { using protocol::ClipboardEvent; using protocol::KeyEvent; using protocol::MouseEvent; // USB to XKB keycode map table. #define USB_KEYMAP(usb, xkb, win, mac) {usb, win} #include "ui/base/keycodes/usb_keycode_map.h" #undef USB_KEYMAP // A class to generate events on Windows. class EventExecutorWin : public EventExecutor { public: EventExecutorWin(scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner); virtual ~EventExecutorWin() {} // ClipboardStub interface. virtual void InjectClipboardEvent(const ClipboardEvent& event) OVERRIDE; // InputStub interface. virtual void InjectKeyEvent(const KeyEvent& event) OVERRIDE; virtual void InjectMouseEvent(const MouseEvent& event) OVERRIDE; // EventExecutor interface. virtual void Start( scoped_ptr<protocol::ClipboardStub> client_clipboard) OVERRIDE; virtual void StopAndDelete() OVERRIDE; private: void HandleKey(const KeyEvent& event); void HandleMouse(const MouseEvent& event); scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; scoped_ptr<Clipboard> clipboard_; DISALLOW_COPY_AND_ASSIGN(EventExecutorWin); }; EventExecutorWin::EventExecutorWin( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) : main_task_runner_(main_task_runner), ui_task_runner_(ui_task_runner), clipboard_(Clipboard::Create()) { } void EventExecutorWin::InjectClipboardEvent(const ClipboardEvent& event) { if (!ui_task_runner_->BelongsToCurrentThread()) { ui_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::InjectClipboardEvent, base::Unretained(this), event)); return; } clipboard_->InjectClipboardEvent(event); } void EventExecutorWin::InjectKeyEvent(const KeyEvent& event) { if (!main_task_runner_->BelongsToCurrentThread()) { main_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::InjectKeyEvent, base::Unretained(this), event)); return; } HandleKey(event); } void EventExecutorWin::InjectMouseEvent(const MouseEvent& event) { if (!main_task_runner_->BelongsToCurrentThread()) { main_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::InjectMouseEvent, base::Unretained(this), event)); return; } HandleMouse(event); } void EventExecutorWin::Start( scoped_ptr<protocol::ClipboardStub> client_clipboard) { if (!ui_task_runner_->BelongsToCurrentThread()) { ui_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::Start, base::Unretained(this), base::Passed(&client_clipboard))); return; } clipboard_->Start(client_clipboard.Pass()); } void EventExecutorWin::StopAndDelete() { if (!ui_task_runner_->BelongsToCurrentThread()) { ui_task_runner_->PostTask( FROM_HERE, base::Bind(&EventExecutorWin::StopAndDelete, base::Unretained(this))); return; } clipboard_->Stop(); delete this; } void EventExecutorWin::HandleKey(const KeyEvent& event) { // HostEventDispatcher should filter events missing the pressed field. DCHECK(event.has_pressed()); DCHECK(event.has_usb_keycode()); // Reset the system idle suspend timeout. SetThreadExecutionState(ES_SYSTEM_REQUIRED); // Populate the a Windows INPUT structure for the event. INPUT input; memset(&input, 0, sizeof(input)); input.type = INPUT_KEYBOARD; input.ki.time = 0; input.ki.dwFlags = KEYEVENTF_SCANCODE; if (!event.pressed()) input.ki.dwFlags |= KEYEVENTF_KEYUP; int scancode = UsbKeycodeToNativeKeycode(event.usb_keycode()); VLOG(3) << "Converting USB keycode: " << std::hex << event.usb_keycode() << " to scancode: " << scancode << std::dec; // Ignore events which can't be mapped. if (scancode == kInvalidKeycode) return; // Windows scancodes are only 8-bit, so store the low-order byte into the // event and set the extended flag if any high-order bits are set. The only // high-order values we should see are 0xE0 or 0xE1. The extended bit usually // distinguishes keys with the same meaning, e.g. left & right shift. input.ki.wScan = scancode & 0xFF; if ((scancode & 0xFF00) != 0x0000) { input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY; } if (SendInput(1, &input, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a key event"; } } void EventExecutorWin::HandleMouse(const MouseEvent& event) { // Reset the system idle suspend timeout. SetThreadExecutionState(ES_SYSTEM_REQUIRED); // TODO(garykac) Collapse mouse (x,y) and button events into a single // input event when possible. if (event.has_x() && event.has_y()) { int x = event.x(); int y = event.y(); INPUT input; input.type = INPUT_MOUSE; input.mi.time = 0; SkISize screen_size(SkISize::Make(GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN))); if ((screen_size.width() > 1) && (screen_size.height() > 1)) { x = std::max(0, std::min(screen_size.width(), x)); y = std::max(0, std::min(screen_size.height(), y)); input.mi.dx = static_cast<int>((x * 65535) / (screen_size.width() - 1)); input.mi.dy = static_cast<int>((y * 65535) / (screen_size.height() - 1)); input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK; if (SendInput(1, &input, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a mouse move event"; } } } int wheel_delta_x = 0; int wheel_delta_y = 0; if (event.has_wheel_delta_x() && event.has_wheel_delta_y()) { wheel_delta_x = static_cast<int>(event.wheel_delta_x()); wheel_delta_y = static_cast<int>(event.wheel_delta_y()); } else if (event.has_wheel_offset_x() && event.has_wheel_offset_y()) { wheel_delta_x = event.wheel_offset_x() * WHEEL_DELTA; wheel_delta_y = event.wheel_offset_y() * WHEEL_DELTA; } if (wheel_delta_x != 0 || wheel_delta_y != 0) { INPUT wheel; wheel.type = INPUT_MOUSE; wheel.mi.time = 0; if (wheel_delta_x != 0) { wheel.mi.mouseData = wheel_delta_x; wheel.mi.dwFlags = MOUSEEVENTF_HWHEEL; if (SendInput(1, &wheel, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a mouse wheel(x) event"; } } if (wheel_delta_y != 0) { wheel.mi.mouseData = wheel_delta_y; wheel.mi.dwFlags = MOUSEEVENTF_WHEEL; if (SendInput(1, &wheel, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a mouse wheel(y) event"; } } } if (event.has_button() && event.has_button_down()) { INPUT button_event; button_event.type = INPUT_MOUSE; button_event.mi.time = 0; button_event.mi.dx = 0; button_event.mi.dy = 0; MouseEvent::MouseButton button = event.button(); bool down = event.button_down(); if (button == MouseEvent::BUTTON_LEFT) { button_event.mi.dwFlags = down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP; } else if (button == MouseEvent::BUTTON_MIDDLE) { button_event.mi.dwFlags = down ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP; } else if (button == MouseEvent::BUTTON_RIGHT) { button_event.mi.dwFlags = down ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP; } else { button_event.mi.dwFlags = down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP; } if (SendInput(1, &button_event, sizeof(INPUT)) == 0) { LOG_GETLASTERROR(ERROR) << "Failed to inject a mouse button event"; } } } } // namespace scoped_ptr<EventExecutor> EventExecutor::Create( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) { return scoped_ptr<EventExecutor>( new EventExecutorWin(main_task_runner, ui_task_runner)); } } // namespace remoting <|endoftext|>
<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: cp %s %t // RUN: %clang_cc1 -fsyntax-only -fixit -x c++ %t || true // RUN: %clang_cc1 -fsyntax-only -pedantic -Werror -x c++ %t namespace std { template<typename T> class basic_string { // expected-note 2{{'basic_string' declared here}} public: int find(const char *substr); // expected-note{{'find' declared here}} static const int npos = -1; // expected-note{{'npos' declared here}} }; typedef basic_string<char> string; // expected-note 2{{'string' declared here}} } namespace otherstd { // expected-note 2{{'otherstd' declared here}} \ // expected-note{{namespace 'otherstd' defined here}} using namespace std; } using namespace std; other_std::strng str1; // expected-error{{use of undeclared identifier 'other_std'; did you mean 'otherstd'?}} \ // expected-error{{no type named 'strng' in namespace 'otherstd'; did you mean 'string'?}} tring str2; // expected-error{{unknown type name 'tring'; did you mean 'string'?}} ::other_std::string str3; // expected-error{{no member named 'other_std' in the global namespace; did you mean 'otherstd'?}} float area(float radius, // expected-note{{'radius' declared here}} float pi) { return radious * pi; // expected-error{{did you mean 'radius'?}} } using namespace othestd; // expected-error{{no namespace named 'othestd'; did you mean 'otherstd'?}} namespace blargh = otherstd; // expected-note 3{{namespace 'blargh' defined here}} using namespace ::blarg; // expected-error{{no namespace named 'blarg' in the global namespace; did you mean 'blargh'?}} namespace wibble = blarg; // expected-error{{no namespace named 'blarg'; did you mean 'blargh'?}} namespace wobble = ::blarg; // expected-error{{no namespace named 'blarg' in the global namespace; did you mean 'blargh'?}} bool test_string(std::string s) { basc_string<char> b1; // expected-error{{no template named 'basc_string'; did you mean 'basic_string'?}} std::basic_sting<char> b2; // expected-error{{no template named 'basic_sting' in namespace 'std'; did you mean 'basic_string'?}} (void)b1; (void)b2; return s.fnd("hello") // expected-error{{no member named 'fnd' in 'std::basic_string<char>'; did you mean 'find'?}} == std::string::pos; // expected-error{{no member named 'pos' in 'std::basic_string<char>'; did you mean 'npos'?}} } struct Base { }; struct Derived : public Base { // expected-note{{base class 'Base' specified here}} int member; // expected-note 3{{'member' declared here}} Derived() : base(), // expected-error{{initializer 'base' does not name a non-static data member or base class; did you mean the base class 'Base'?}} ember() { } // expected-error{{initializer 'ember' does not name a non-static data member or base class; did you mean the member 'member'?}} int getMember() const { return ember; // expected-error{{use of undeclared identifier 'ember'; did you mean 'member'?}} } int &getMember(); }; int &Derived::getMember() { return ember; // expected-error{{use of undeclared identifier 'ember'; did you mean 'member'?}} } <commit_msg>Disable this test while I track down the platform-specific issue<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: cp %s %t // RUN: %clang_cc1 -fsyntax-only -fixit -x c++ %t || true // RUN: %clang_cc1 -fsyntax-only -pedantic -Werror -x c++ %t // // FIXME: Disabled while we investigate failure. // REQUIRES: disabled namespace std { template<typename T> class basic_string { // expected-note 2{{'basic_string' declared here}} public: int find(const char *substr); // expected-note{{'find' declared here}} static const int npos = -1; // expected-note{{'npos' declared here}} }; typedef basic_string<char> string; // expected-note 2{{'string' declared here}} } namespace otherstd { // expected-note 2{{'otherstd' declared here}} \ // expected-note{{namespace 'otherstd' defined here}} using namespace std; } using namespace std; other_std::strng str1; // expected-error{{use of undeclared identifier 'other_std'; did you mean 'otherstd'?}} \ // expected-error{{no type named 'strng' in namespace 'otherstd'; did you mean 'string'?}} tring str2; // expected-error{{unknown type name 'tring'; did you mean 'string'?}} ::other_std::string str3; // expected-error{{no member named 'other_std' in the global namespace; did you mean 'otherstd'?}} float area(float radius, // expected-note{{'radius' declared here}} float pi) { return radious * pi; // expected-error{{did you mean 'radius'?}} } using namespace othestd; // expected-error{{no namespace named 'othestd'; did you mean 'otherstd'?}} namespace blargh = otherstd; // expected-note 3{{namespace 'blargh' defined here}} using namespace ::blarg; // expected-error{{no namespace named 'blarg' in the global namespace; did you mean 'blargh'?}} namespace wibble = blarg; // expected-error{{no namespace named 'blarg'; did you mean 'blargh'?}} namespace wobble = ::blarg; // expected-error{{no namespace named 'blarg' in the global namespace; did you mean 'blargh'?}} bool test_string(std::string s) { basc_string<char> b1; // expected-error{{no template named 'basc_string'; did you mean 'basic_string'?}} std::basic_sting<char> b2; // expected-error{{no template named 'basic_sting' in namespace 'std'; did you mean 'basic_string'?}} (void)b1; (void)b2; return s.fnd("hello") // expected-error{{no member named 'fnd' in 'std::basic_string<char>'; did you mean 'find'?}} == std::string::pos; // expected-error{{no member named 'pos' in 'std::basic_string<char>'; did you mean 'npos'?}} } struct Base { }; struct Derived : public Base { // expected-note{{base class 'Base' specified here}} int member; // expected-note 3{{'member' declared here}} Derived() : base(), // expected-error{{initializer 'base' does not name a non-static data member or base class; did you mean the base class 'Base'?}} ember() { } // expected-error{{initializer 'ember' does not name a non-static data member or base class; did you mean the member 'member'?}} int getMember() const { return ember; // expected-error{{use of undeclared identifier 'ember'; did you mean 'member'?}} } int &getMember(); }; int &Derived::getMember() { return ember; // expected-error{{use of undeclared identifier 'ember'; did you mean 'member'?}} } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: %clang_cc1 -fsyntax-only -fixit -o - | %clang_cc1 -fsyntax-only -pedantic -Werror -x c++ - namespace std { template<typename T> class basic_string { int find(const char *substr); static const int npos = -1; }; typedef basic_string<char> string; } namespace otherstd { using namespace std; } using namespace std; other_std::strng str1; // expected-error{{use of undeclared identifier 'other_std'; did you mean 'otherstd'?}} \ // expected-error{{no type named 'strng' in namespace 'otherstd'; did you mean 'string'?}} tring str2; // expected-error{{unknown type name 'tring'; did you mean 'string'?}} float area(float radius, float pi) { return radious * pi; // expected-error{{use of undeclared identifier 'radious'; did you mean 'radius'?}} } bool test_string(std::string s) { basc_string<char> b1; // expected-error{{no template named 'basc_string'; did you mean 'basic_string'?}} std::basic_sting<char> b2; // expected-error{{no template named 'basic_sting' in namespace 'std'; did you mean 'basic_string'?}} (void)b1; (void)b2; return s.fnd("hello") // expected-error{{no member named 'fnd' in 'class std::basic_string<char>'; did you mean 'find'?}} == std::string::pos; // expected-error{{no member named 'pos' in 'class std::basic_string<char>'; did you mean 'npos'?}} } <commit_msg>Add another typo test for nested-name-specifiers<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: %clang_cc1 -fsyntax-only -fixit -o - | %clang_cc1 -fsyntax-only -pedantic -Werror -x c++ - namespace std { template<typename T> class basic_string { int find(const char *substr); static const int npos = -1; }; typedef basic_string<char> string; } namespace otherstd { using namespace std; } using namespace std; other_std::strng str1; // expected-error{{use of undeclared identifier 'other_std'; did you mean 'otherstd'?}} \ // expected-error{{no type named 'strng' in namespace 'otherstd'; did you mean 'string'?}} tring str2; // expected-error{{unknown type name 'tring'; did you mean 'string'?}} ::other_std::string str3; // expected-error{{no member named 'other_std' in the global namespace; did you mean 'otherstd'?}} float area(float radius, float pi) { return radious * pi; // expected-error{{use of undeclared identifier 'radious'; did you mean 'radius'?}} } bool test_string(std::string s) { basc_string<char> b1; // expected-error{{no template named 'basc_string'; did you mean 'basic_string'?}} std::basic_sting<char> b2; // expected-error{{no template named 'basic_sting' in namespace 'std'; did you mean 'basic_string'?}} (void)b1; (void)b2; return s.fnd("hello") // expected-error{{no member named 'fnd' in 'class std::basic_string<char>'; did you mean 'find'?}} == std::string::pos; // expected-error{{no member named 'pos' in 'class std::basic_string<char>'; did you mean 'npos'?}} } <|endoftext|>
<commit_before>/* * SessionConsoleProcess.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionConsoleProcess.hpp" #include <core/json/JsonRpc.hpp> #include <core/system/Process.hpp> #include <core/Exec.hpp> #include <core/SafeConvert.hpp> #include <core/Settings.hpp> #include <core/system/Environment.hpp> #include <session/SessionModuleContext.hpp> #include "config.h" #ifdef RSTUDIO_SERVER #include <core/system/Crypto.hpp> #endif using namespace core; namespace session { namespace modules { namespace console_process { namespace { const size_t OUTPUT_BUFFER_SIZE = 8192; typedef std::map<std::string, boost::shared_ptr<ConsoleProcess> > ProcTable; ProcTable s_procs; core::system::ProcessOptions procOptions() { core::system::ProcessOptions options; #ifndef _WIN32 options.detachSession = true; #endif return options; } } // anonymous namespace #ifdef _WIN32 const int kDefaultMaxOutputLines = 160; #else const int kDefaultMaxOutputLines = 500; #endif ConsoleProcess::ConsoleProcess() : dialog_(false), interactionMode_(InteractionNever), maxOutputLines_(kDefaultMaxOutputLines), started_(true), interrupt_(false), outputBuffer_(OUTPUT_BUFFER_SIZE) { // When we retrieve from outputBuffer, we only want complete lines. Add a // dummy \n so we can tell the first line is a complete line. outputBuffer_.push_back('\n'); } ConsoleProcess::ConsoleProcess(const std::string& command, const core::system::ProcessOptions& options, const std::string& caption, bool dialog, InteractionMode interactionMode, int maxOutputLines, const boost::function<void()>& onExit) : command_(command), options_(options), caption_(caption), dialog_(dialog), interactionMode_(interactionMode), maxOutputLines_(maxOutputLines), started_(false), interrupt_(false), outputBuffer_(OUTPUT_BUFFER_SIZE), onExit_(onExit) { commonInit(); } ConsoleProcess::ConsoleProcess(const std::string& program, const std::vector<std::string>& args, const core::system::ProcessOptions& options, const std::string& caption, bool dialog, InteractionMode interactionMode, int maxOutputLines, const boost::function<void()>& onExit) : program_(program), args_(args), options_(options), caption_(caption), dialog_(dialog), interactionMode_(interactionMode), maxOutputLines_(maxOutputLines), started_(false), interrupt_(false), outputBuffer_(OUTPUT_BUFFER_SIZE), onExit_(onExit) { commonInit(); } void ConsoleProcess::commonInit() { handle_ = core::system::generateUuid(false); // always redirect stderr to stdout so output is interleaved options_.redirectStdErrToStdOut = true; // request a pseudoterminal if this is an interactive console process #ifndef _WIN32 if (interactionMode() != InteractionNever) { options_.pseudoterminal = core::system::Pseudoterminal(80, 1); // define TERM to dumb (but first make sure we have an environment // block to modify) if (!options_.environment) { core::system::Options childEnv; core::system::environment(&childEnv); options_.environment = childEnv; } core::system::setenv(&(options_.environment.get()), "TERM", "dumb"); } #endif // When we retrieve from outputBuffer, we only want complete lines. Add a // dummy \n so we can tell the first line is a complete line. outputBuffer_.push_back('\n'); } std::string ConsoleProcess::bufferedOutput() const { boost::circular_buffer<char>::const_iterator pos = std::find(outputBuffer_.begin(), outputBuffer_.end(), '\n'); std::string result; if (pos != outputBuffer_.end()) pos++; std::copy(pos, outputBuffer_.end(), std::back_inserter(result)); // Will be empty if the buffer was overflowed by a single line return result; } Error ConsoleProcess::start() { if (started_) return Success(); Error error; if (!command_.empty()) { error = module_context::processSupervisor().runCommand( command_, options_, createProcessCallbacks()); } else { error = module_context::processSupervisor().runProgram( program_, args_, options_, createProcessCallbacks()); } if (!error) started_ = true; return error; } void ConsoleProcess::enqueInput(const Input& input) { inputQueue_.push(input); } void ConsoleProcess::interrupt() { interrupt_ = true; } bool ConsoleProcess::onContinue(core::system::ProcessOperations& ops) { // full stop interrupt if requested if (interrupt_) return false; // process input queue while (!inputQueue_.empty()) { // pop input Input input = inputQueue_.front(); inputQueue_.pop(); // pty interrupt if (input.interrupt) { Error error = ops.ptyInterrupt(); if (error) LOG_ERROR(error); if (input.echoInput) appendToOutputBuffer("^C"); } // text input else { Error error = ops.writeToStdin(input.text, false); if (error) LOG_ERROR(error); if (input.echoInput) appendToOutputBuffer(input.text); else appendToOutputBuffer("\n"); } } // continue return true; } void ConsoleProcess::appendToOutputBuffer(const std::string &str) { std::copy(str.begin(), str.end(), std::back_inserter(outputBuffer_)); } void ConsoleProcess::enqueOutputEvent(const std::string &output, bool error) { // copy to output buffer appendToOutputBuffer(output); // If there's more output than the client can even show, then // truncate it to the amount that the client can show. Too much // output can overwhelm the client, making it unresponsive. std::string trimmedOutput = output; string_utils::trimLeadingLines(maxOutputLines_, &trimmedOutput); json::Object data; data["handle"] = handle_; data["error"] = error; data["output"] = trimmedOutput; module_context::enqueClientEvent( ClientEvent(client_events::kConsoleProcessOutput, data)); } void ConsoleProcess::onStdout(core::system::ProcessOperations& ops, const std::string& output) { enqueOutputEvent(output, false); } void ConsoleProcess::onExit(int exitCode) { exitCode_.reset(exitCode); json::Object data; data["handle"] = handle_; data["exitCode"] = exitCode; module_context::enqueClientEvent( ClientEvent(client_events::kConsoleProcessExit, data)); if (onExit_) onExit_(); } core::json::Object ConsoleProcess::toJson() const { json::Object result; result["handle"] = handle_; result["caption"] = caption_; result["dialog"] = dialog_; result["interaction_mode"] = static_cast<int>(interactionMode_); result["max_output_lines"] = maxOutputLines_; result["buffered_output"] = bufferedOutput(); if (exitCode_) result["exit_code"] = *exitCode_; else result["exit_code"] = json::Value(); return result; } boost::shared_ptr<ConsoleProcess> ConsoleProcess::fromJson( core::json::Object &obj) { boost::shared_ptr<ConsoleProcess> pProc(new ConsoleProcess()); pProc->handle_ = obj["handle"].get_str(); pProc->caption_ = obj["caption"].get_str(); pProc->dialog_ = obj["dialog"].get_bool(); json::Value mode = obj["interaction_mode"]; if (!mode.is_null()) pProc->interactionMode_ = static_cast<InteractionMode>(mode.get_int()); else pProc->interactionMode_ = InteractionNever; json::Value maxLines = obj["max_output_lines"]; if (!maxLines.is_null()) pProc->maxOutputLines_ = maxLines.get_int(); else pProc->maxOutputLines_ = kDefaultMaxOutputLines; std::string bufferedOutput = obj["buffered_output"].get_str(); std::copy(bufferedOutput.begin(), bufferedOutput.end(), std::back_inserter(pProc->outputBuffer_)); json::Value exitCode = obj["exit_code"]; if (exitCode.is_null()) pProc->exitCode_.reset(); else pProc->exitCode_.reset(exitCode.get_int()); return pProc; } core::system::ProcessCallbacks ConsoleProcess::createProcessCallbacks() { core::system::ProcessCallbacks cb; cb.onContinue = boost::bind(&ConsoleProcess::onContinue, ConsoleProcess::shared_from_this(), _1); cb.onStdout = boost::bind(&ConsoleProcess::onStdout, ConsoleProcess::shared_from_this(), _1, _2); cb.onExit = boost::bind(&ConsoleProcess::onExit, ConsoleProcess::shared_from_this(), _1); return cb; } Error procStart(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParams(request.params, &handle); if (error) return error; ProcTable::const_iterator pos = s_procs.find(handle); if (pos != s_procs.end()) { return pos->second->start(); } else { return systemError(boost::system::errc::invalid_argument, ERROR_LOCATION); } } Error procInterrupt(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParams(request.params, &handle); if (error) return error; ProcTable::const_iterator pos = s_procs.find(handle); if (pos != s_procs.end()) { pos->second->interrupt(); return Success(); } else { return systemError(boost::system::errc::invalid_argument, ERROR_LOCATION); } } Error procReap(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParams(request.params, &handle); if (error) return error; if (!s_procs.erase(handle)) { return systemError(boost::system::errc::invalid_argument, ERROR_LOCATION); } else { return Success(); } } Error procWriteStdin(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParam(request.params, 0, &handle); if (error) return error; ConsoleProcess::Input input; error = json::readObjectParam(request.params, 1, "interrupt", &input.interrupt, "text", &input.text, "echo_input", &input.echoInput); if (error) return error; ProcTable::const_iterator pos = s_procs.find(handle); if (pos != s_procs.end()) { #ifdef RSTUDIO_SERVER if (!input.interrupt) { error = core::system::crypto::rsaPrivateDecrypt(input.text, &input.text); if (error) return error; } #endif pos->second->enqueInput(input); return Success(); } else { return systemError(boost::system::errc::invalid_argument, ERROR_LOCATION); } } boost::shared_ptr<ConsoleProcess> ConsoleProcess::create( const std::string& command, core::system::ProcessOptions options, const std::string& caption, bool dialog, InteractionMode interactionMode, int maxOutputLines, const boost::function<void()>& onExit) { options.terminateChildren = true; boost::shared_ptr<ConsoleProcess> ptrProc( new ConsoleProcess(command, options, caption, dialog, interactionMode, maxOutputLines, onExit)); s_procs[ptrProc->handle()] = ptrProc; return ptrProc; } boost::shared_ptr<ConsoleProcess> ConsoleProcess::create( const std::string& program, const std::vector<std::string>& args, core::system::ProcessOptions options, const std::string& caption, bool dialog, InteractionMode interactionMode, int maxOutputLines, const boost::function<void()>& onExit) { options.terminateChildren = true; boost::shared_ptr<ConsoleProcess> ptrProc( new ConsoleProcess(program, args, options, caption, dialog, interactionMode, maxOutputLines, onExit)); s_procs[ptrProc->handle()] = ptrProc; return ptrProc; } core::json::Array processesAsJson() { json::Array procInfos; for (ProcTable::const_iterator it = s_procs.begin(); it != s_procs.end(); it++) { procInfos.push_back(it->second->toJson()); } return procInfos; } void onSuspend(core::Settings* pSettings) { json::Array array; for (ProcTable::const_iterator it = s_procs.begin(); it != s_procs.end(); it++) { array.push_back(it->second->toJson()); } std::ostringstream ostr; json::write(array, ostr); pSettings->set("console_procs", ostr.str()); } void onResume(const core::Settings& settings) { std::string strVal = settings.get("console_procs"); if (strVal.empty()) return; json::Value value; if (!json::parse(strVal, &value)) return; json::Array procs = value.get_array(); for (json::Array::iterator it = procs.begin(); it != procs.end(); it++) { boost::shared_ptr<ConsoleProcess> proc = ConsoleProcess::fromJson(it->get_obj()); s_procs[proc->handle()] = proc; } } Error initialize() { using boost::bind; using namespace module_context; // add suspend/resume handler addSuspendHandler(SuspendHandler(onSuspend, onResume)); // install rpc methods ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "process_start", procStart)) (bind(registerRpcMethod, "process_interrupt", procInterrupt)) (bind(registerRpcMethod, "process_reap", procReap)) (bind(registerRpcMethod, "process_write_stdin", procWriteStdin)); return initBlock.execute(); } } // namespace console_process } // namespace modules } // namespace session <commit_msg>use 500 as max output lines on all platforms<commit_after>/* * SessionConsoleProcess.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionConsoleProcess.hpp" #include <core/json/JsonRpc.hpp> #include <core/system/Process.hpp> #include <core/Exec.hpp> #include <core/SafeConvert.hpp> #include <core/Settings.hpp> #include <core/system/Environment.hpp> #include <session/SessionModuleContext.hpp> #include "config.h" #ifdef RSTUDIO_SERVER #include <core/system/Crypto.hpp> #endif using namespace core; namespace session { namespace modules { namespace console_process { namespace { const size_t OUTPUT_BUFFER_SIZE = 8192; typedef std::map<std::string, boost::shared_ptr<ConsoleProcess> > ProcTable; ProcTable s_procs; core::system::ProcessOptions procOptions() { core::system::ProcessOptions options; #ifndef _WIN32 options.detachSession = true; #endif return options; } } // anonymous namespace const int kDefaultMaxOutputLines = 500; ConsoleProcess::ConsoleProcess() : dialog_(false), interactionMode_(InteractionNever), maxOutputLines_(kDefaultMaxOutputLines), started_(true), interrupt_(false), outputBuffer_(OUTPUT_BUFFER_SIZE) { // When we retrieve from outputBuffer, we only want complete lines. Add a // dummy \n so we can tell the first line is a complete line. outputBuffer_.push_back('\n'); } ConsoleProcess::ConsoleProcess(const std::string& command, const core::system::ProcessOptions& options, const std::string& caption, bool dialog, InteractionMode interactionMode, int maxOutputLines, const boost::function<void()>& onExit) : command_(command), options_(options), caption_(caption), dialog_(dialog), interactionMode_(interactionMode), maxOutputLines_(maxOutputLines), started_(false), interrupt_(false), outputBuffer_(OUTPUT_BUFFER_SIZE), onExit_(onExit) { commonInit(); } ConsoleProcess::ConsoleProcess(const std::string& program, const std::vector<std::string>& args, const core::system::ProcessOptions& options, const std::string& caption, bool dialog, InteractionMode interactionMode, int maxOutputLines, const boost::function<void()>& onExit) : program_(program), args_(args), options_(options), caption_(caption), dialog_(dialog), interactionMode_(interactionMode), maxOutputLines_(maxOutputLines), started_(false), interrupt_(false), outputBuffer_(OUTPUT_BUFFER_SIZE), onExit_(onExit) { commonInit(); } void ConsoleProcess::commonInit() { handle_ = core::system::generateUuid(false); // always redirect stderr to stdout so output is interleaved options_.redirectStdErrToStdOut = true; // request a pseudoterminal if this is an interactive console process #ifndef _WIN32 if (interactionMode() != InteractionNever) { options_.pseudoterminal = core::system::Pseudoterminal(80, 1); // define TERM to dumb (but first make sure we have an environment // block to modify) if (!options_.environment) { core::system::Options childEnv; core::system::environment(&childEnv); options_.environment = childEnv; } core::system::setenv(&(options_.environment.get()), "TERM", "dumb"); } #endif // When we retrieve from outputBuffer, we only want complete lines. Add a // dummy \n so we can tell the first line is a complete line. outputBuffer_.push_back('\n'); } std::string ConsoleProcess::bufferedOutput() const { boost::circular_buffer<char>::const_iterator pos = std::find(outputBuffer_.begin(), outputBuffer_.end(), '\n'); std::string result; if (pos != outputBuffer_.end()) pos++; std::copy(pos, outputBuffer_.end(), std::back_inserter(result)); // Will be empty if the buffer was overflowed by a single line return result; } Error ConsoleProcess::start() { if (started_) return Success(); Error error; if (!command_.empty()) { error = module_context::processSupervisor().runCommand( command_, options_, createProcessCallbacks()); } else { error = module_context::processSupervisor().runProgram( program_, args_, options_, createProcessCallbacks()); } if (!error) started_ = true; return error; } void ConsoleProcess::enqueInput(const Input& input) { inputQueue_.push(input); } void ConsoleProcess::interrupt() { interrupt_ = true; } bool ConsoleProcess::onContinue(core::system::ProcessOperations& ops) { // full stop interrupt if requested if (interrupt_) return false; // process input queue while (!inputQueue_.empty()) { // pop input Input input = inputQueue_.front(); inputQueue_.pop(); // pty interrupt if (input.interrupt) { Error error = ops.ptyInterrupt(); if (error) LOG_ERROR(error); if (input.echoInput) appendToOutputBuffer("^C"); } // text input else { Error error = ops.writeToStdin(input.text, false); if (error) LOG_ERROR(error); if (input.echoInput) appendToOutputBuffer(input.text); else appendToOutputBuffer("\n"); } } // continue return true; } void ConsoleProcess::appendToOutputBuffer(const std::string &str) { std::copy(str.begin(), str.end(), std::back_inserter(outputBuffer_)); } void ConsoleProcess::enqueOutputEvent(const std::string &output, bool error) { // copy to output buffer appendToOutputBuffer(output); // If there's more output than the client can even show, then // truncate it to the amount that the client can show. Too much // output can overwhelm the client, making it unresponsive. std::string trimmedOutput = output; string_utils::trimLeadingLines(maxOutputLines_, &trimmedOutput); json::Object data; data["handle"] = handle_; data["error"] = error; data["output"] = trimmedOutput; module_context::enqueClientEvent( ClientEvent(client_events::kConsoleProcessOutput, data)); } void ConsoleProcess::onStdout(core::system::ProcessOperations& ops, const std::string& output) { enqueOutputEvent(output, false); } void ConsoleProcess::onExit(int exitCode) { exitCode_.reset(exitCode); json::Object data; data["handle"] = handle_; data["exitCode"] = exitCode; module_context::enqueClientEvent( ClientEvent(client_events::kConsoleProcessExit, data)); if (onExit_) onExit_(); } core::json::Object ConsoleProcess::toJson() const { json::Object result; result["handle"] = handle_; result["caption"] = caption_; result["dialog"] = dialog_; result["interaction_mode"] = static_cast<int>(interactionMode_); result["max_output_lines"] = maxOutputLines_; result["buffered_output"] = bufferedOutput(); if (exitCode_) result["exit_code"] = *exitCode_; else result["exit_code"] = json::Value(); return result; } boost::shared_ptr<ConsoleProcess> ConsoleProcess::fromJson( core::json::Object &obj) { boost::shared_ptr<ConsoleProcess> pProc(new ConsoleProcess()); pProc->handle_ = obj["handle"].get_str(); pProc->caption_ = obj["caption"].get_str(); pProc->dialog_ = obj["dialog"].get_bool(); json::Value mode = obj["interaction_mode"]; if (!mode.is_null()) pProc->interactionMode_ = static_cast<InteractionMode>(mode.get_int()); else pProc->interactionMode_ = InteractionNever; json::Value maxLines = obj["max_output_lines"]; if (!maxLines.is_null()) pProc->maxOutputLines_ = maxLines.get_int(); else pProc->maxOutputLines_ = kDefaultMaxOutputLines; std::string bufferedOutput = obj["buffered_output"].get_str(); std::copy(bufferedOutput.begin(), bufferedOutput.end(), std::back_inserter(pProc->outputBuffer_)); json::Value exitCode = obj["exit_code"]; if (exitCode.is_null()) pProc->exitCode_.reset(); else pProc->exitCode_.reset(exitCode.get_int()); return pProc; } core::system::ProcessCallbacks ConsoleProcess::createProcessCallbacks() { core::system::ProcessCallbacks cb; cb.onContinue = boost::bind(&ConsoleProcess::onContinue, ConsoleProcess::shared_from_this(), _1); cb.onStdout = boost::bind(&ConsoleProcess::onStdout, ConsoleProcess::shared_from_this(), _1, _2); cb.onExit = boost::bind(&ConsoleProcess::onExit, ConsoleProcess::shared_from_this(), _1); return cb; } Error procStart(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParams(request.params, &handle); if (error) return error; ProcTable::const_iterator pos = s_procs.find(handle); if (pos != s_procs.end()) { return pos->second->start(); } else { return systemError(boost::system::errc::invalid_argument, ERROR_LOCATION); } } Error procInterrupt(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParams(request.params, &handle); if (error) return error; ProcTable::const_iterator pos = s_procs.find(handle); if (pos != s_procs.end()) { pos->second->interrupt(); return Success(); } else { return systemError(boost::system::errc::invalid_argument, ERROR_LOCATION); } } Error procReap(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParams(request.params, &handle); if (error) return error; if (!s_procs.erase(handle)) { return systemError(boost::system::errc::invalid_argument, ERROR_LOCATION); } else { return Success(); } } Error procWriteStdin(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string handle; Error error = json::readParam(request.params, 0, &handle); if (error) return error; ConsoleProcess::Input input; error = json::readObjectParam(request.params, 1, "interrupt", &input.interrupt, "text", &input.text, "echo_input", &input.echoInput); if (error) return error; ProcTable::const_iterator pos = s_procs.find(handle); if (pos != s_procs.end()) { #ifdef RSTUDIO_SERVER if (!input.interrupt) { error = core::system::crypto::rsaPrivateDecrypt(input.text, &input.text); if (error) return error; } #endif pos->second->enqueInput(input); return Success(); } else { return systemError(boost::system::errc::invalid_argument, ERROR_LOCATION); } } boost::shared_ptr<ConsoleProcess> ConsoleProcess::create( const std::string& command, core::system::ProcessOptions options, const std::string& caption, bool dialog, InteractionMode interactionMode, int maxOutputLines, const boost::function<void()>& onExit) { options.terminateChildren = true; boost::shared_ptr<ConsoleProcess> ptrProc( new ConsoleProcess(command, options, caption, dialog, interactionMode, maxOutputLines, onExit)); s_procs[ptrProc->handle()] = ptrProc; return ptrProc; } boost::shared_ptr<ConsoleProcess> ConsoleProcess::create( const std::string& program, const std::vector<std::string>& args, core::system::ProcessOptions options, const std::string& caption, bool dialog, InteractionMode interactionMode, int maxOutputLines, const boost::function<void()>& onExit) { options.terminateChildren = true; boost::shared_ptr<ConsoleProcess> ptrProc( new ConsoleProcess(program, args, options, caption, dialog, interactionMode, maxOutputLines, onExit)); s_procs[ptrProc->handle()] = ptrProc; return ptrProc; } core::json::Array processesAsJson() { json::Array procInfos; for (ProcTable::const_iterator it = s_procs.begin(); it != s_procs.end(); it++) { procInfos.push_back(it->second->toJson()); } return procInfos; } void onSuspend(core::Settings* pSettings) { json::Array array; for (ProcTable::const_iterator it = s_procs.begin(); it != s_procs.end(); it++) { array.push_back(it->second->toJson()); } std::ostringstream ostr; json::write(array, ostr); pSettings->set("console_procs", ostr.str()); } void onResume(const core::Settings& settings) { std::string strVal = settings.get("console_procs"); if (strVal.empty()) return; json::Value value; if (!json::parse(strVal, &value)) return; json::Array procs = value.get_array(); for (json::Array::iterator it = procs.begin(); it != procs.end(); it++) { boost::shared_ptr<ConsoleProcess> proc = ConsoleProcess::fromJson(it->get_obj()); s_procs[proc->handle()] = proc; } } Error initialize() { using boost::bind; using namespace module_context; // add suspend/resume handler addSuspendHandler(SuspendHandler(onSuspend, onResume)); // install rpc methods ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "process_start", procStart)) (bind(registerRpcMethod, "process_interrupt", procInterrupt)) (bind(registerRpcMethod, "process_reap", procReap)) (bind(registerRpcMethod, "process_write_stdin", procWriteStdin)); return initBlock.execute(); } } // namespace console_process } // namespace modules } // namespace session <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_SCHEDULER_COORDINATOR_HPP #define CAF_SCHEDULER_COORDINATOR_HPP #include <thread> #include <limits> #include <memory> #include <condition_variable> #include "caf/scheduler/worker.hpp" #include "caf/scheduler/abstract_coordinator.hpp" namespace caf { namespace scheduler { /** * Policy-based implementation of the abstract coordinator base class. */ template <class Policy> class coordinator : public abstract_coordinator { public: using super = abstract_coordinator; using policy_data = typename Policy::coordinator_data; coordinator(size_t nw = std::thread::hardware_concurrency(), size_t mt = std::numeric_limits<size_t>::max()) : super(nw), m_max_throughput(mt) { // nop } using worker_type = worker<Policy>; worker_type* worker_by_id(size_t id) {//override { return m_workers[id].get(); } policy_data& data() { return m_data; } protected: void initialize() override { super::initialize(); // create workers m_workers.resize(num_workers()); for (size_t i = 0; i < num_workers(); ++i) { auto& ref = m_workers[i]; ref.reset(new worker_type(i, this, m_max_throughput)); } // start all workers now that all workers have been initialized for (auto& w : m_workers) { w->start(); } } void stop() override { CAF_LOG_TRACE(""); // shutdown workers class shutdown_helper : public resumable { public: void attach_to_scheduler() override { // nop } void detach_from_scheduler() override { // nop } resumable::resume_result resume(execution_unit* ptr, size_t) override { CAF_LOG_DEBUG("shutdown_helper::resume => shutdown worker"); CAF_REQUIRE(ptr != nullptr); std::unique_lock<std::mutex> guard(mtx); last_worker = ptr; cv.notify_all(); return resumable::shutdown_execution_unit; } shutdown_helper() : last_worker(nullptr) { // nop } std::mutex mtx; std::condition_variable cv; execution_unit* last_worker; }; // use a set to keep track of remaining workers shutdown_helper sh; std::set<worker_type*> alive_workers; auto num = num_workers(); for (size_t i = 0; i < num; ++i) { alive_workers.insert(worker_by_id(i)); } CAF_LOG_DEBUG("enqueue shutdown_helper into each worker"); while (!alive_workers.empty()) { (*alive_workers.begin())->external_enqueue(&sh); // since jobs can be stolen, we cannot assume that we have // actually shut down the worker we've enqueued sh to { // lifetime scope of guard std::unique_lock<std::mutex> guard(sh.mtx); sh.cv.wait(guard, [&] { return sh.last_worker != nullptr; }); } alive_workers.erase(static_cast<worker_type*>(sh.last_worker)); sh.last_worker = nullptr; } // shutdown utility actors stop_actors(); // wait until all workers are done for (auto& w : m_workers) { w->get_thread().join(); } // run cleanup code for each resumable auto f = [](resumable* job) { job->detach_from_scheduler(); }; for (auto& w : m_workers) { m_policy.foreach_resumable(w.get(), f); } m_policy.foreach_central_resumable(this, f); } void enqueue(resumable* ptr) { m_policy.central_enqueue(this, ptr); } private: // usually of size std::thread::hardware_concurrency() std::vector<std::unique_ptr<worker_type>> m_workers; // policy-specific data policy_data m_data; // instance of our policy object Policy m_policy; // number of messages each actor is allowed to consume per resume size_t m_max_throughput; }; } // namespace scheduler } // namespace caf #endif // CAF_SCHEDULER_COORDINATOR_HPP <commit_msg>Increase minimum number of worker threads to 4.<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_SCHEDULER_COORDINATOR_HPP #define CAF_SCHEDULER_COORDINATOR_HPP #include <thread> #include <limits> #include <memory> #include <condition_variable> #include "caf/scheduler/worker.hpp" #include "caf/scheduler/abstract_coordinator.hpp" namespace caf { namespace scheduler { /** * Policy-based implementation of the abstract coordinator base class. */ template <class Policy> class coordinator : public abstract_coordinator { public: using super = abstract_coordinator; using policy_data = typename Policy::coordinator_data; coordinator(size_t nw = std::max(std::thread::hardware_concurrency(), 4u), size_t mt = std::numeric_limits<size_t>::max()) : super(nw), m_max_throughput(mt) { // nop } using worker_type = worker<Policy>; worker_type* worker_by_id(size_t id) {//override { return m_workers[id].get(); } policy_data& data() { return m_data; } protected: void initialize() override { super::initialize(); // create workers m_workers.resize(num_workers()); for (size_t i = 0; i < num_workers(); ++i) { auto& ref = m_workers[i]; ref.reset(new worker_type(i, this, m_max_throughput)); } // start all workers now that all workers have been initialized for (auto& w : m_workers) { w->start(); } } void stop() override { CAF_LOG_TRACE(""); // shutdown workers class shutdown_helper : public resumable { public: void attach_to_scheduler() override { // nop } void detach_from_scheduler() override { // nop } resumable::resume_result resume(execution_unit* ptr, size_t) override { CAF_LOG_DEBUG("shutdown_helper::resume => shutdown worker"); CAF_REQUIRE(ptr != nullptr); std::unique_lock<std::mutex> guard(mtx); last_worker = ptr; cv.notify_all(); return resumable::shutdown_execution_unit; } shutdown_helper() : last_worker(nullptr) { // nop } std::mutex mtx; std::condition_variable cv; execution_unit* last_worker; }; // use a set to keep track of remaining workers shutdown_helper sh; std::set<worker_type*> alive_workers; auto num = num_workers(); for (size_t i = 0; i < num; ++i) { alive_workers.insert(worker_by_id(i)); } CAF_LOG_DEBUG("enqueue shutdown_helper into each worker"); while (!alive_workers.empty()) { (*alive_workers.begin())->external_enqueue(&sh); // since jobs can be stolen, we cannot assume that we have // actually shut down the worker we've enqueued sh to { // lifetime scope of guard std::unique_lock<std::mutex> guard(sh.mtx); sh.cv.wait(guard, [&] { return sh.last_worker != nullptr; }); } alive_workers.erase(static_cast<worker_type*>(sh.last_worker)); sh.last_worker = nullptr; } // shutdown utility actors stop_actors(); // wait until all workers are done for (auto& w : m_workers) { w->get_thread().join(); } // run cleanup code for each resumable auto f = [](resumable* job) { job->detach_from_scheduler(); }; for (auto& w : m_workers) { m_policy.foreach_resumable(w.get(), f); } m_policy.foreach_central_resumable(this, f); } void enqueue(resumable* ptr) { m_policy.central_enqueue(this, ptr); } private: // usually of size std::thread::hardware_concurrency() std::vector<std::unique_ptr<worker_type>> m_workers; // policy-specific data policy_data m_data; // instance of our policy object Policy m_policy; // number of messages each actor is allowed to consume per resume size_t m_max_throughput; }; } // namespace scheduler } // namespace caf #endif // CAF_SCHEDULER_COORDINATOR_HPP <|endoftext|>
<commit_before>// Copyright (C) 2014 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include <math.h> #include "copasi/utilities/CUnit.h" #include "copasi/report/CKeyFactory.h" #include "copasi/report/CCopasiRootContainer.h" #include "copasi/model/CModel.h" #include <algorithm> // static C_FLOAT64 CUnit::Avogadro(6.02214129e23); // http://physics.nist.gov/cgi-bin/cuu/Value?na (Wed Jan 29 18:33:36 EST 2014) const char * CUnit::VolumeUnitNames[] = {"dimensionless", "m\xc2\xb3", "l", "ml", "\xc2\xb5l", "nl", "pl", "fl", NULL}; const char * CUnit::AreaUnitNames[] = {"dimensionless", "m\xc2\xb2", "dm\xc2\xb2", "cm\xc2\xb2", "mm\xc2\xb2", "\xc2\xb5m\xc2\xb2", "nm\xc2\xb2", "pm\xc2\xb2", "fm\xc2\xb2", NULL}; const char * CUnit::LengthUnitNames[] = {"dimensionless", "m", "dm", "cm", "mm", "\xc2\xb5m", "nm", "pm", "fm", NULL}; const char * CUnit::TimeUnitNames[] = {"dimensionless", "d", "h", "min", "s", "ms", "\xc2\xb5s", "ns", "ps", "fs", NULL}; // "mol" is the correct name, however in the COPASI XML files "Mol" is used // up to build 18 const char * CUnit::QuantityUnitOldXMLNames[] = {"dimensionless", "Mol", "mMol", "\xc2\xb5Mol", "nMol", "pMol", "fMol", "#", NULL}; const char * CUnit::QuantityUnitNames[] = {"dimensionless", "mol", "mmol", "\xc2\xb5mol", "nmol", "pmol", "fmol", "#", NULL}; // constructors CUnit::CUnit(const std::string & name, const CCopasiContainer * pParent): CCopasiContainer(name, pParent, "Unit"), mSymbol("none"), mKey(), mComponents() { setup(); } // copy constructor CUnit::CUnit(const CUnit & src, const CCopasiContainer * pParent): CCopasiContainer(src, pParent), mSymbol(src.mSymbol), mKey(), mComponents(src.mComponents) { setup(); } CUnit::~CUnit() { CCopasiRootContainer::getKeyFactory()->remove(mKey); } void CUnit::setup() { mKey = CCopasiRootContainer::getKeyFactory()->add("Unit", this); } void CUnit::fromEnum(VolumeUnit volEnum) { mComponents.clear(); mSymbol = VolumeUnitNames[volEnum]; if( volEnum == CUnit::dimensionlessVolume ) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter); tmpComponent.setExponent(3); switch (volEnum) { case CUnit::m3: //default scale = 0 break; case CUnit::l: tmpComponent.setScale(-3); break; case CUnit::ml: tmpComponent.setScale(-6); break; case CUnit::microl: tmpComponent.setScale(-9); break; case CUnit::nl: tmpComponent.setScale(-12); break; case CUnit::pl: tmpComponent.setScale(-15); break; case CUnit::fl: tmpComponent.setScale(-18); break; } addComponent(tmpComponent); } void CUnit::fromEnum(AreaUnit areaEnum) { mComponents.clear(); mSymbol = AreaUnitNames[areaEnum]; if( areaEnum == CUnit::dimensionlessArea ) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter); tmpComponent.setExponent(2); switch (areaEnum) { case CUnit::m2: //default scale = 0 break; case CUnit::dm2: tmpComponent.setScale(-2); break; case CUnit::cm2: tmpComponent.setScale(-4); break; case CUnit::mm2: tmpComponent.setScale(-6); break; case CUnit::microm2: tmpComponent.setScale(-12); break; case CUnit::nm2: tmpComponent.setScale(-18); break; case CUnit::pm2: tmpComponent.setScale(-24); break; case CUnit::fm2: tmpComponent.setScale(-30); break; } addComponent(tmpComponent); } void CUnit::fromEnum(LengthUnit lengthEnum) { mComponents.clear(); mSymbol = LengthUnitNames[lengthEnum]; if( lengthEnum == CUnit::dimensionlessLength ) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter); switch (lengthEnum) { case CUnit::m: //default scale = 0 break; case CUnit::dm: tmpComponent.setScale(-1); break; case CUnit::cm: tmpComponent.setScale(-2); break; case CUnit::mm: tmpComponent.setScale(-3); break; case CUnit::microm: tmpComponent.setScale(-6); break; case CUnit::nm: tmpComponent.setScale(-9); break; case CUnit::pm: tmpComponent.setScale(-12); break; case CUnit::fm: tmpComponent.setScale(-15); break; } addComponent(tmpComponent); } void CUnit::fromEnum(TimeUnit timeEnum) { mComponents.clear(); mSymbol = TimeUnitNames[timeEnum]; if( timeEnum == CUnit::dimensionlessTime ) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::second); switch (timeEnum) { case CUnit::d: tmpComponent.setMultiplier(60*60*24); break; case CUnit::h: tmpComponent.setMultiplier(60*60); break; case CUnit::min: case CUnit::OldMinute: tmpComponent.setMultiplier(60); break; case CUnit::s: // defaults are appropriate break; case CUnit::micros: tmpComponent.setScale(-6); break; case CUnit::ns: tmpComponent.setScale(-9); break; case CUnit::ps: tmpComponent.setScale(-12); break; case CUnit::fs: tmpComponent.setScale(-15); break; } addComponent(tmpComponent); } void CUnit::fromEnum(QuantityUnit quantityEnum) { mComponents.clear(); mSymbol = QuantityUnitNames[quantityEnum]; if( quantityEnum == CUnit::dimensionlessQuantity ) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::item); const CModel * pModel = dynamic_cast<const CModel *>(getObjectAncestor("Model")); C_FLOAT64 usedAvogadro; if(pModel != NULL) usedAvogadro = pModel->getAvogadro(); else usedAvogadro = Avogadro; tmpComponent.setMultiplier(usedAvogadro); // enum QuantityUnit {dimensionlessQuantity = 0, Mol, mMol, microMol, nMol, pMol, fMol, number, OldXML}; switch (quantityEnum) { case CUnit::Mol: break; case CUnit::mMol: tmpComponent.setScale(-3); break; case CUnit::microMol: tmpComponent.setScale(-6); break; case CUnit::nMol: tmpComponent.setScale(-9); break; case CUnit::pMol: tmpComponent.setScale(-12); break; case CUnit::fMol: tmpComponent.setScale(-15); break; case CUnit::number: case CUnit::OldXML: tmpComponent.setMultiplier(1); break; } addComponent(tmpComponent); } void CUnit::setSymbol(std::string symbol) { mSymbol = symbol; } std::string CUnit::getSymbol() const { return mSymbol; } // See if the component units cancel (divide to 1). // The CUnitComponent::Kind enumerator uses only prime numbers. // Multiplying all the components should give 1, if numerators and // denominators have the same combination of units. bool CUnit::isDimensionless() const { // If the symbol string has been set to other than "dimensionless", // assume it has dimension, regardless of the components if(mSymbol != "dimensionless" || mSymbol != "") return false; std::vector< CUnitComponent >::const_iterator it = mComponents.begin(); double reduction = 1; for (; it != mComponents.end(); it++) { reduction *= pow((double)(*it).getKind(), (*it).getExponent()); } // If the vector is empy, it will loop 0 times, and the reduction // will remain ==1 (i.e. dimensionless if no components) return reduction == 1; } void CUnit::addComponent(const CUnitComponent & component) { mComponents.push_back(component); } bool CUnit::simplifyComponents() { if (mComponents.size() < 2) return false; std::vector< CUnitComponent > replacementVector; std::vector< CUnitComponent >::const_iterator it = mComponents.begin(); CUnitComponent tempComponent; bool didSimplify = false; std::sort(mComponents.begin(), mComponents.end()); // make same Kinds adjacent for (; it != mComponents.end(); it++) { tempComponent = (*it); while (it != mComponents.end() && tempComponent.getKind() == (*(it + 1)).getKind()) { tempComponent.setExponent((tempComponent.getExponent()) + (*(it + 1)).getExponent()); tempComponent.setScale(tempComponent.getScale() + (*(it + 1)).getScale()); tempComponent.setMultiplier(tempComponent.getMultiplier() * (*(it + 1)).getMultiplier()); didSimplify = true; it++; } replacementVector.push_back(tempComponent); } if (didSimplify) { mComponents = replacementVector; } return didSimplify; } std::string CUnit::prefixFromScale(int scale) { switch (scale) { case 3: return "k"; // kilo case 2: return "h"; // hecto case 1: return "da"; // deca case -1: return "d"; // deci case -2: return "c"; // centi case -3: return "m"; // milli case -6: return "\xc2\xb5"; // micro case -9: return "n"; // nano case -12: return "p"; // pico case -15: return "f"; // femto default: return ""; // anything else, including scale = 0 } } <commit_msg>Silence more case statement compiler warnings.<commit_after>// Copyright (C) 2014 - 2015 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include <math.h> #include "copasi/utilities/CUnit.h" #include "copasi/report/CKeyFactory.h" #include "copasi/report/CCopasiRootContainer.h" #include "copasi/model/CModel.h" #include <algorithm> // static C_FLOAT64 CUnit::Avogadro(6.02214129e23); // http://physics.nist.gov/cgi-bin/cuu/Value?na (Wed Jan 29 18:33:36 EST 2014) const char * CUnit::VolumeUnitNames[] = {"dimensionless", "m\xc2\xb3", "l", "ml", "\xc2\xb5l", "nl", "pl", "fl", NULL}; const char * CUnit::AreaUnitNames[] = {"dimensionless", "m\xc2\xb2", "dm\xc2\xb2", "cm\xc2\xb2", "mm\xc2\xb2", "\xc2\xb5m\xc2\xb2", "nm\xc2\xb2", "pm\xc2\xb2", "fm\xc2\xb2", NULL}; const char * CUnit::LengthUnitNames[] = {"dimensionless", "m", "dm", "cm", "mm", "\xc2\xb5m", "nm", "pm", "fm", NULL}; const char * CUnit::TimeUnitNames[] = {"dimensionless", "d", "h", "min", "s", "ms", "\xc2\xb5s", "ns", "ps", "fs", NULL}; // "mol" is the correct name, however in the COPASI XML files "Mol" is used // up to build 18 const char * CUnit::QuantityUnitOldXMLNames[] = {"dimensionless", "Mol", "mMol", "\xc2\xb5Mol", "nMol", "pMol", "fMol", "#", NULL}; const char * CUnit::QuantityUnitNames[] = {"dimensionless", "mol", "mmol", "\xc2\xb5mol", "nmol", "pmol", "fmol", "#", NULL}; // constructors CUnit::CUnit(const std::string & name, const CCopasiContainer * pParent): CCopasiContainer(name, pParent, "Unit"), mSymbol("none"), mKey(), mComponents() { setup(); } // copy constructor CUnit::CUnit(const CUnit & src, const CCopasiContainer * pParent): CCopasiContainer(src, pParent), mSymbol(src.mSymbol), mKey(), mComponents(src.mComponents) { setup(); } CUnit::~CUnit() { CCopasiRootContainer::getKeyFactory()->remove(mKey); } void CUnit::setup() { mKey = CCopasiRootContainer::getKeyFactory()->add("Unit", this); } void CUnit::fromEnum(VolumeUnit volEnum) { mComponents.clear(); mSymbol = VolumeUnitNames[volEnum]; if (volEnum == CUnit::dimensionlessVolume) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter); tmpComponent.setExponent(3); switch (volEnum) { case CUnit::m3: //default scale = 0 break; case CUnit::l: tmpComponent.setScale(-3); break; case CUnit::ml: tmpComponent.setScale(-6); break; case CUnit::microl: tmpComponent.setScale(-9); break; case CUnit::nl: tmpComponent.setScale(-12); break; case CUnit::pl: tmpComponent.setScale(-15); break; case CUnit::fl: tmpComponent.setScale(-18); break; default: return; // just to silence compiler warning } addComponent(tmpComponent); } void CUnit::fromEnum(AreaUnit areaEnum) { mComponents.clear(); mSymbol = AreaUnitNames[areaEnum]; if (areaEnum == CUnit::dimensionlessArea) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter); tmpComponent.setExponent(2); switch (areaEnum) { case CUnit::m2: //default scale = 0 break; case CUnit::dm2: tmpComponent.setScale(-2); break; case CUnit::cm2: tmpComponent.setScale(-4); break; case CUnit::mm2: tmpComponent.setScale(-6); break; case CUnit::microm2: tmpComponent.setScale(-12); break; case CUnit::nm2: tmpComponent.setScale(-18); break; case CUnit::pm2: tmpComponent.setScale(-24); break; case CUnit::fm2: tmpComponent.setScale(-30); break; default: return; // just to silence compiler warning } addComponent(tmpComponent); } void CUnit::fromEnum(LengthUnit lengthEnum) { mComponents.clear(); mSymbol = LengthUnitNames[lengthEnum]; if (lengthEnum == CUnit::dimensionlessLength) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter); switch (lengthEnum) { case CUnit::m: //default scale = 0 break; case CUnit::dm: tmpComponent.setScale(-1); break; case CUnit::cm: tmpComponent.setScale(-2); break; case CUnit::mm: tmpComponent.setScale(-3); break; case CUnit::microm: tmpComponent.setScale(-6); break; case CUnit::nm: tmpComponent.setScale(-9); break; case CUnit::pm: tmpComponent.setScale(-12); break; case CUnit::fm: tmpComponent.setScale(-15); break; default: return; // just to silence compiler warning } addComponent(tmpComponent); } void CUnit::fromEnum(TimeUnit timeEnum) { mComponents.clear(); mSymbol = TimeUnitNames[timeEnum]; if (timeEnum == CUnit::dimensionlessTime) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::second); switch (timeEnum) { case CUnit::d: tmpComponent.setMultiplier(60 * 60 * 24); break; case CUnit::h: tmpComponent.setMultiplier(60 * 60); break; case CUnit::min: case CUnit::OldMinute: tmpComponent.setMultiplier(60); break; case CUnit::s: // defaults are appropriate break; case CUnit::micros: tmpComponent.setScale(-6); break; case CUnit::ns: tmpComponent.setScale(-9); break; case CUnit::ps: tmpComponent.setScale(-12); break; case CUnit::fs: tmpComponent.setScale(-15); break; default: return; // just to silence compiler warning } addComponent(tmpComponent); } void CUnit::fromEnum(QuantityUnit quantityEnum) { mComponents.clear(); mSymbol = QuantityUnitNames[quantityEnum]; if (quantityEnum == CUnit::dimensionlessQuantity) return; // no need to add component CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::item); const CModel * pModel = dynamic_cast<const CModel *>(getObjectAncestor("Model")); C_FLOAT64 usedAvogadro; if (pModel != NULL) usedAvogadro = pModel->getAvogadro(); else usedAvogadro = Avogadro; tmpComponent.setMultiplier(usedAvogadro); // enum QuantityUnit {dimensionlessQuantity = 0, Mol, mMol, microMol, nMol, pMol, fMol, number, OldXML}; switch (quantityEnum) { case CUnit::Mol: break; case CUnit::mMol: tmpComponent.setScale(-3); break; case CUnit::microMol: tmpComponent.setScale(-6); break; case CUnit::nMol: tmpComponent.setScale(-9); break; case CUnit::pMol: tmpComponent.setScale(-12); break; case CUnit::fMol: tmpComponent.setScale(-15); break; case CUnit::number: case CUnit::OldXML: tmpComponent.setMultiplier(1); break; default: return; // just to silence compiler warning } addComponent(tmpComponent); } void CUnit::setSymbol(std::string symbol) { mSymbol = symbol; } std::string CUnit::getSymbol() const { return mSymbol; } // See if the component units cancel (divide to 1). // The CUnitComponent::Kind enumerator uses only prime numbers. // Multiplying all the components should give 1, if numerators and // denominators have the same combination of units. bool CUnit::isDimensionless() const { // If the symbol string has been set to other than "dimensionless", // assume it has dimension, regardless of the components if (mSymbol != "dimensionless" || mSymbol != "") return false; std::vector< CUnitComponent >::const_iterator it = mComponents.begin(); double reduction = 1; for (; it != mComponents.end(); it++) { reduction *= pow((double)(*it).getKind(), (*it).getExponent()); } // If the vector is empy, it will loop 0 times, and the reduction // will remain ==1 (i.e. dimensionless if no components) return reduction == 1; } void CUnit::addComponent(const CUnitComponent & component) { mComponents.push_back(component); } bool CUnit::simplifyComponents() { if (mComponents.size() < 2) return false; std::vector< CUnitComponent > replacementVector; std::vector< CUnitComponent >::const_iterator it = mComponents.begin(); CUnitComponent tempComponent; bool didSimplify = false; std::sort(mComponents.begin(), mComponents.end()); // make same Kinds adjacent for (; it != mComponents.end(); it++) { tempComponent = (*it); while (it != mComponents.end() && tempComponent.getKind() == (*(it + 1)).getKind()) { tempComponent.setExponent((tempComponent.getExponent()) + (*(it + 1)).getExponent()); tempComponent.setScale(tempComponent.getScale() + (*(it + 1)).getScale()); tempComponent.setMultiplier(tempComponent.getMultiplier() * (*(it + 1)).getMultiplier()); didSimplify = true; it++; } replacementVector.push_back(tempComponent); } if (didSimplify) { mComponents = replacementVector; } return didSimplify; } std::string CUnit::prefixFromScale(int scale) { switch (scale) { case 3: return "k"; // kilo case 2: return "h"; // hecto case 1: return "da"; // deca case -1: return "d"; // deci case -2: return "c"; // centi case -3: return "m"; // milli case -6: return "\xc2\xb5"; // micro case -9: return "n"; // nano case -12: return "p"; // pico case -15: return "f"; // femto default: return ""; // anything else, including scale = 0 } } <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/eval/eval/simple_value.h> #include <vespa/eval/eval/fast_value.h> #include <vespa/eval/eval/value_codec.h> #include <vespa/eval/instruction/generic_join.h> #include <vespa/eval/eval/interpreted_function.h> #include <vespa/eval/eval/test/reference_operations.h> #include <vespa/eval/eval/test/tensor_model.hpp> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/gtest/gtest.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::instruction; using namespace vespalib::eval::test; using vespalib::make_string_short::fmt; std::vector<Layout> join_layouts = { {}, {}, {x(5)}, {x(5)}, {x(5)}, {y(5)}, {x(5)}, {x(5),y(5)}, {y(3)}, {x(2),z(3)}, {x(3),y(5)}, {y(5),z(7)}, float_cells({x(3),y(5)}), {y(5),z(7)}, {x(3),y(5)}, float_cells({y(5),z(7)}), float_cells({x(3),y(5)}), float_cells({y(5),z(7)}), {x({"a","b","c"})}, {x({"a","b","c"})}, {x({"a","b","c"})}, {x({"a","b"})}, {x({"a","b","c"})}, {y({"foo","bar","baz"})}, {x({"a","b","c"})}, {x({"a","b","c"}),y({"foo","bar","baz"})}, {x({"a","b"}),y({"foo","bar","baz"})}, {x({"a","b","c"}),y({"foo","bar"})}, {x({"a","b"}),y({"foo","bar","baz"})}, {y({"foo","bar"}),z({"i","j","k","l"})}, float_cells({x({"a","b"}),y({"foo","bar","baz"})}), {y({"foo","bar"}),z({"i","j","k","l"})}, {x({"a","b"}),y({"foo","bar","baz"})}, float_cells({y({"foo","bar"}),z({"i","j","k","l"})}), float_cells({x({"a","b"}),y({"foo","bar","baz"})}), float_cells({y({"foo","bar"}),z({"i","j","k","l"})}), {x(3),y({"foo", "bar"})}, {y({"foo", "bar"}),z(7)}, {x({"a","b","c"}),y(5)}, {y(5),z({"i","j","k","l"})}, float_cells({x({"a","b","c"}),y(5)}), {y(5),z({"i","j","k","l"})}, {x({"a","b","c"}),y(5)}, float_cells({y(5),z({"i","j","k","l"})}), float_cells({x({"a","b","c"}),y(5)}), float_cells({y(5),z({"i","j","k","l"})}), {x({"a","b","c"}),y(5)}, float_cells({y(5)}), {y(5)}, float_cells({x({"a","b","c"}),y(5)}), {x({}),y(5)}, float_cells({y(5)}) }; bool join_address(const TensorSpec::Address &a, const TensorSpec::Address &b, TensorSpec::Address &addr) { for (const auto &dim_a: a) { auto pos_b = b.find(dim_a.first); if ((pos_b != b.end()) && !(pos_b->second == dim_a.second)) { return false; } addr.insert_or_assign(dim_a.first, dim_a.second); } return true; } TensorSpec perform_generic_join(const TensorSpec &a, const TensorSpec &b, join_fun_t function, const ValueBuilderFactory &factory) { Stash stash; auto lhs = value_from_spec(a, factory); auto rhs = value_from_spec(b, factory); auto my_op = GenericJoin::make_instruction(lhs->type(), rhs->type(), function, factory, stash); InterpretedFunction::EvalSingle single(factory, my_op); return spec_from_value(single.eval(std::vector<Value::CREF>({*lhs,*rhs}))); } TEST(GenericJoinTest, dense_join_plan_can_be_created) { auto lhs = ValueType::from_spec("tensor(a{},b[6],c[5],e[3],f[2],g{})"); auto rhs = ValueType::from_spec("tensor(a{},b[6],c[5],d[4],h{})"); auto plan = DenseJoinPlan(lhs, rhs); std::vector<size_t> expect_loop = {30,4,6}; std::vector<size_t> expect_lhs_stride = {6,0,1}; std::vector<size_t> expect_rhs_stride = {4,1,0}; EXPECT_EQ(plan.lhs_size, 180); EXPECT_EQ(plan.rhs_size, 120); EXPECT_EQ(plan.out_size, 720); EXPECT_EQ(plan.loop_cnt, expect_loop); EXPECT_EQ(plan.lhs_stride, expect_lhs_stride); EXPECT_EQ(plan.rhs_stride, expect_rhs_stride); } TEST(GenericJoinTest, sparse_join_plan_can_be_created) { auto lhs = ValueType::from_spec("tensor(a{},b[6],c[5],e[3],f[2],g{})"); auto rhs = ValueType::from_spec("tensor(b[6],c[5],d[4],g{},h{})"); auto plan = SparseJoinPlan(lhs, rhs); using SRC = SparseJoinPlan::Source; std::vector<SRC> expect_sources = {SRC::LHS,SRC::BOTH,SRC::RHS}; std::vector<size_t> expect_lhs_overlap = {1}; std::vector<size_t> expect_rhs_overlap = {0}; EXPECT_EQ(plan.sources, expect_sources); EXPECT_EQ(plan.lhs_overlap, expect_lhs_overlap); EXPECT_EQ(plan.rhs_overlap, expect_rhs_overlap); } TEST(GenericJoinTest, dense_join_plan_can_be_executed) { auto plan = DenseJoinPlan(ValueType::from_spec("tensor(a[2])"), ValueType::from_spec("tensor(b[3])")); std::vector<int> a({1, 2}); std::vector<int> b({3, 4, 5}); std::vector<int> c(6, 0); std::vector<int> expect = {3,4,5,6,8,10}; ASSERT_EQ(plan.out_size, 6); int *dst = &c[0]; auto cell_join = [&](size_t a_idx, size_t b_idx) { *dst++ = (a[a_idx] * b[b_idx]); }; plan.execute(0, 0, cell_join); EXPECT_EQ(c, expect); } TEST(GenericJoinTest, generic_join_works_for_simple_and_fast_values) { ASSERT_TRUE((join_layouts.size() % 2) == 0); for (size_t i = 0; i < join_layouts.size(); i += 2) { TensorSpec lhs = spec(join_layouts[i], Div16(N())); TensorSpec rhs = spec(join_layouts[i + 1], Div16(N())); for (auto fun: {operation::Add::f, operation::Sub::f, operation::Mul::f, operation::Div::f}) { SCOPED_TRACE(fmt("\n===\nLHS: %s\nRHS: %s\n===\n", lhs.to_string().c_str(), rhs.to_string().c_str())); auto expect = ReferenceOperations::join(lhs, rhs, fun); auto simple = perform_generic_join(lhs, rhs, fun, SimpleValueBuilderFactory::get()); auto fast = perform_generic_join(lhs, rhs, fun, FastValueBuilderFactory::get()); EXPECT_EQ(simple, expect); EXPECT_EQ(fast, expect); } } } GTEST_MAIN_RUN_ALL_TESTS() <commit_msg>use GenSpec in generic_join_test<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/eval/eval/simple_value.h> #include <vespa/eval/eval/fast_value.h> #include <vespa/eval/eval/value_codec.h> #include <vespa/eval/instruction/generic_join.h> #include <vespa/eval/eval/interpreted_function.h> #include <vespa/eval/eval/test/reference_operations.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/gtest/gtest.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::instruction; using namespace vespalib::eval::test; using vespalib::make_string_short::fmt; GenSpec::seq_t N_16ths = [] (size_t i) { return (i + 1.0) / 16.0; }; GenSpec G() { return GenSpec().cells_float().seq(N_16ths); } std::vector<GenSpec> join_layouts = { G(), G(), G().idx("x", 5), G().idx("x", 5), G().idx("x", 5), G().idx("y", 5), G().idx("x", 5), G().idx("x", 5).idx("y", 5), G().idx("y", 3), G().idx("x", 2).idx("z", 3), G().idx("x", 3).idx("y", 5), G().idx("y", 5).idx("z", 7), G().map("x", {"a","b","c"}), G().map("x", {"a","b","c"}), G().map("x", {"a","b","c"}), G().map("x", {"a","b"}), G().map("x", {"a","b","c"}), G().map("y", {"foo","bar","baz"}), G().map("x", {"a","b","c"}), G().map("x", {"a","b","c"}).map("y", {"foo","bar","baz"}), G().map("x", {"a","b"}).map("y", {"foo","bar","baz"}), G().map("x", {"a","b","c"}).map("y", {"foo","bar"}), G().map("x", {"a","b"}).map("y", {"foo","bar","baz"}), G().map("y", {"foo","bar"}).map("z", {"i","j","k","l"}), G().idx("x", 3).map("y", {"foo", "bar"}), G().map("y", {"foo", "bar"}).idx("z", 7), G().map("x", {"a","b","c"}).idx("y", 5), G().idx("y", 5).map("z", {"i","j","k","l"}) }; bool join_address(const TensorSpec::Address &a, const TensorSpec::Address &b, TensorSpec::Address &addr) { for (const auto &dim_a: a) { auto pos_b = b.find(dim_a.first); if ((pos_b != b.end()) && !(pos_b->second == dim_a.second)) { return false; } addr.insert_or_assign(dim_a.first, dim_a.second); } return true; } TensorSpec perform_generic_join(const TensorSpec &a, const TensorSpec &b, join_fun_t function, const ValueBuilderFactory &factory) { Stash stash; auto lhs = value_from_spec(a, factory); auto rhs = value_from_spec(b, factory); auto my_op = GenericJoin::make_instruction(lhs->type(), rhs->type(), function, factory, stash); InterpretedFunction::EvalSingle single(factory, my_op); return spec_from_value(single.eval(std::vector<Value::CREF>({*lhs,*rhs}))); } TEST(GenericJoinTest, dense_join_plan_can_be_created) { auto lhs = ValueType::from_spec("tensor(a{},b[6],c[5],e[3],f[2],g{})"); auto rhs = ValueType::from_spec("tensor(a{},b[6],c[5],d[4],h{})"); auto plan = DenseJoinPlan(lhs, rhs); std::vector<size_t> expect_loop = {30,4,6}; std::vector<size_t> expect_lhs_stride = {6,0,1}; std::vector<size_t> expect_rhs_stride = {4,1,0}; EXPECT_EQ(plan.lhs_size, 180); EXPECT_EQ(plan.rhs_size, 120); EXPECT_EQ(plan.out_size, 720); EXPECT_EQ(plan.loop_cnt, expect_loop); EXPECT_EQ(plan.lhs_stride, expect_lhs_stride); EXPECT_EQ(plan.rhs_stride, expect_rhs_stride); } TEST(GenericJoinTest, sparse_join_plan_can_be_created) { auto lhs = ValueType::from_spec("tensor(a{},b[6],c[5],e[3],f[2],g{})"); auto rhs = ValueType::from_spec("tensor(b[6],c[5],d[4],g{},h{})"); auto plan = SparseJoinPlan(lhs, rhs); using SRC = SparseJoinPlan::Source; std::vector<SRC> expect_sources = {SRC::LHS,SRC::BOTH,SRC::RHS}; std::vector<size_t> expect_lhs_overlap = {1}; std::vector<size_t> expect_rhs_overlap = {0}; EXPECT_EQ(plan.sources, expect_sources); EXPECT_EQ(plan.lhs_overlap, expect_lhs_overlap); EXPECT_EQ(plan.rhs_overlap, expect_rhs_overlap); } TEST(GenericJoinTest, dense_join_plan_can_be_executed) { auto plan = DenseJoinPlan(ValueType::from_spec("tensor(a[2])"), ValueType::from_spec("tensor(b[3])")); std::vector<int> a({1, 2}); std::vector<int> b({3, 4, 5}); std::vector<int> c(6, 0); std::vector<int> expect = {3,4,5,6,8,10}; ASSERT_EQ(plan.out_size, 6); int *dst = &c[0]; auto cell_join = [&](size_t a_idx, size_t b_idx) { *dst++ = (a[a_idx] * b[b_idx]); }; plan.execute(0, 0, cell_join); EXPECT_EQ(c, expect); } TEST(GenericJoinTest, generic_join_works_for_simple_and_fast_values) { ASSERT_TRUE((join_layouts.size() % 2) == 0); for (size_t i = 0; i < join_layouts.size(); i += 2) { auto l = join_layouts[i]; auto r = join_layouts[i+1]; for (TensorSpec lhs : { l.gen(), l.cells_double().gen() }) { for (TensorSpec rhs : { r.gen(), r.cells_double().gen() }) { for (auto fun: {operation::Add::f, operation::Sub::f, operation::Mul::f, operation::Div::f}) { SCOPED_TRACE(fmt("\n===\nLHS: %s\nRHS: %s\n===\n", lhs.to_string().c_str(), rhs.to_string().c_str())); auto expect = ReferenceOperations::join(lhs, rhs, fun); auto simple = perform_generic_join(lhs, rhs, fun, SimpleValueBuilderFactory::get()); auto fast = perform_generic_join(lhs, rhs, fun, FastValueBuilderFactory::get()); EXPECT_EQ(simple, expect); EXPECT_EQ(fast, expect); } } } } } GTEST_MAIN_RUN_ALL_TESTS() <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "dense_cell_range_function.h" #include <vespa/eval/eval/value.h> namespace vespalib::eval { using namespace tensor_function; namespace { template <typename CT> void my_cell_range_op(InterpretedFunction::State &state, uint64_t param) { const auto &self = unwrap_param<DenseCellRangeFunction>(param); auto old_cells = state.peek(0).cells().typify<CT>(); ConstArrayRef<CT> new_cells(&old_cells[self.offset()], self.length()); state.pop_push(state.stash.create<DenseValueView>(self.result_type(), TypedCells(new_cells))); } struct MyCellRangeOp { template <typename CT> static auto invoke() { return my_cell_range_op<CT>; } }; } // namespace <unnamed> DenseCellRangeFunction::DenseCellRangeFunction(const ValueType &result_type, const TensorFunction &child, size_t offset, size_t length) : tensor_function::Op1(result_type, child), _offset(offset), _length(length) { } DenseCellRangeFunction::~DenseCellRangeFunction() = default; InterpretedFunction::Instruction DenseCellRangeFunction::compile_self(const ValueBuilderFactory &, Stash &) const { assert(result_type().cell_type() == child().result_type().cell_type()); using MyTypify = TypifyCellType; auto op = typify_invoke<1,MyTypify,MyCellRangeOp>(result_type().cell_type()); return InterpretedFunction::Instruction(op, wrap_param<DenseCellRangeFunction>(*this)); } } // namespace <commit_msg>assert as early as possible<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "dense_cell_range_function.h" #include <vespa/eval/eval/value.h> namespace vespalib::eval { using namespace tensor_function; namespace { template <typename CT> void my_cell_range_op(InterpretedFunction::State &state, uint64_t param) { const auto &self = unwrap_param<DenseCellRangeFunction>(param); auto old_cells = state.peek(0).cells().typify<CT>(); ConstArrayRef<CT> new_cells(&old_cells[self.offset()], self.length()); state.pop_push(state.stash.create<DenseValueView>(self.result_type(), TypedCells(new_cells))); } struct MyCellRangeOp { template <typename CT> static auto invoke() { return my_cell_range_op<CT>; } }; } // namespace <unnamed> DenseCellRangeFunction::DenseCellRangeFunction(const ValueType &result_type, const TensorFunction &child, size_t offset, size_t length) : tensor_function::Op1(result_type, child), _offset(offset), _length(length) { assert(result_type.cell_type() == child.result_type().cell_type()); } DenseCellRangeFunction::~DenseCellRangeFunction() = default; InterpretedFunction::Instruction DenseCellRangeFunction::compile_self(const ValueBuilderFactory &, Stash &) const { assert(result_type().cell_type() == child().result_type().cell_type()); using MyTypify = TypifyCellType; auto op = typify_invoke<1,MyTypify,MyCellRangeOp>(result_type().cell_type()); return InterpretedFunction::Instruction(op, wrap_param<DenseCellRangeFunction>(*this)); } } // namespace <|endoftext|>
<commit_before>/* Siconos-sample , Copyright INRIA 2005-2011. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a 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. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY [email protected] */ /*!\file BouncingBallED.cpp \brief \ref EMBouncingBall - C++ input file, Event-Driven version - V. Acary, F. Perignon. A Ball bouncing on the ground. Direct description of the model. Simulation with an Event-Driven scheme. */ #include "SiconosKernel.hpp" using namespace std; int main(int argc, char* argv[]) { boost::timer time; time.restart(); try { // ================= Creation of the model ======================= // User-defined main parameters unsigned int nDof = 3; // degrees of freedom for the ball double t0 = 0; // initial computation time double T = 8.5; // final computation time double h = 0.005; // time step double position_init = 1.0; // initial position for lowest bead. double velocity_init = 0.0; // initial velocity for lowest bead. double R = 0.1; // Ball radius double m = 1; // Ball mass double g = 9.81; // Gravity // ------------------------- // --- Dynamical systems --- // ------------------------- cout << "====> Model loading ..." << endl << endl; SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof)); (*Mass)(0, 0) = m; (*Mass)(1, 1) = m; (*Mass)(2, 2) = 3. / 5 * m * R * R; // -- Initial positions and velocities -- SP::SiconosVector q0(new SiconosVector(nDof)); SP::SiconosVector v0(new SiconosVector(nDof)); (*q0)(0) = position_init; (*v0)(0) = velocity_init; // -- The dynamical system -- SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass)); // -- Set external forces (weight) -- SP::SiconosVector weight(new SiconosVector(nDof)); (*weight)(0) = -m * g; ball->setFExtPtr(weight); // -------------------- // --- Interactions --- // -------------------- // -- nslaw -- double e = 0.9; // Interaction ball-floor // SP::SimpleMatrix H(new SimpleMatrix(1, nDof)); (*H)(0, 0) = 1.0; SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e)); SP::Relation relation0(new LagrangianLinearTIR(H)); SP::Interaction inter(new Interaction(1, nslaw0, relation0)); // -------------------------------- // --- NonSmoothDynamicalSystem --- // -------------------------------- // ------------- // --- Model --- // ------------- SP::Model bouncingBall(new Model(t0, T)); // add the dynamical system in the non smooth dynamical system bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball); // link the interaction and the dynamical system bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball); // ---------------- // --- Simulation --- // ---------------- // -- (1) OneStepIntegrators -- SP::OneStepIntegrator OSI(new LsodarOSI()); // -- (2) Time discretisation -- SP::TimeDiscretisation t(new TimeDiscretisation(t0, h)); // -- (3) Non smooth problem -- SP::OneStepNSProblem impact(new LCP()); SP::OneStepNSProblem acceleration(new LCP()); // -- (4) Simulation setup with (1) (2) (3) SP::EventDriven s(new EventDriven(t)); s->insertIntegrator(OSI); s->insertNonSmoothProblem(impact, SICONOS_OSNSP_ED_IMPACT); s->insertNonSmoothProblem(acceleration, SICONOS_OSNSP_ED_SMOOTH_ACC); // =========================== End of model definition =========================== // ================================= Computation ================================= // --- Simulation initialization --- cout << "====> Simulation initialisation ..." << endl << endl; s->setPrintStat(true); bouncingBall->initialize(s); int N = 1854; // Number of saved points: depends on the number of events ... // --- Get the values to be plotted --- // -> saved in a matrix dataPlot unsigned int outputSize = 7; SimpleMatrix dataPlot(N + 1, outputSize); SP::SiconosVector q = ball->q(); SP::SiconosVector v = ball->velocity(); SP::SiconosVector p = ball->p(1); SP::SiconosVector f = ball->p(2); // SiconosVector * y = bouncingBall->nonSmoothDynamicalSystem()->interaction(0)->y(0); SP::EventsManager eventsManager = s->eventsManager(); // For the initial time step: // time dataPlot(0, 0) = bouncingBall->t0(); dataPlot(0, 1) = (*q)(0); dataPlot(0, 2) = (*v)(0); dataPlot(0, 3) = (*p)(0); dataPlot(0, 4) = (*f)(0); // --- Time loop --- cout << "====> Start computation ... " << endl << endl; bool nonSmooth = false; unsigned int numberOfEvent = 0 ; int k = 0; int kns = 0; boost::progress_display show_progress(N); while (s->hasNextEvent() && k < N) { s->advanceToEvent(); if (eventsManager->nextEvent()->getType() == 2) nonSmooth = true; s->processEvents(); // If the treated event is non smooth, the pre-impact state has been solved in memory vectors during process. if (nonSmooth) { dataPlot(k, 0) = s->startingTime(); dataPlot(k, 1) = (*ball->qMemory()->getSiconosVector(1))(0); dataPlot(k, 2) = (*ball->velocityMemory()->getSiconosVector(1))(0); dataPlot(k, 3) = (*p)(0); dataPlot(k, 4) = (*f)(0); k++; kns++; nonSmooth = false; ++show_progress; } dataPlot(k, 0) = s->startingTime(); dataPlot(k, 1) = (*q)(0); dataPlot(k, 2) = (*v)(0); dataPlot(k, 3) = (*p)(0); dataPlot(k, 4) = (*f)(0); dataPlot(k, 5) = (*inter->lambda(1))(0); dataPlot(k, 6) = (*inter->lambda(2))(0); ++k; ++numberOfEvent; ++show_progress; } // --- Output files --- cout << endl; cout << "===== End of Event Driven simulation. " << endl; cout << numberOfEvent << " events have been processed. ==== " << endl; cout << numberOfEvent- kns << " events are of time--discretization type ==== " << endl; cout << kns << " events are of nonsmooth type ==== " << endl << endl; cout << "====> Output file writing ..." << endl << endl; dataPlot.resize(k, outputSize); ioMatrix::write("result.dat", "ascii", dataPlot, "noDim"); // Comparison with a reference file SimpleMatrix dataPlotRef(dataPlot); dataPlotRef.zero(); ioMatrix::read("BouncingBallED.ref", "ascii", dataPlotRef); if ((dataPlot - dataPlotRef).normInf() > 1e-12) { std::cout << "Warning. The results is rather different from the reference file." << std::endl; std::cout << "error = " << (dataPlot - dataPlotRef).normInf() << std::endl; return 1; } } catch (SiconosException e) { cout << e.report() << endl; } catch (...) { cout << "Exception caught." << endl; } cout << "Computation Time: " << time.elapsed() << endl; } <commit_msg>[examples] print error<commit_after>/* Siconos-sample , Copyright INRIA 2005-2011. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a 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. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY [email protected] */ /*!\file BouncingBallED.cpp \brief \ref EMBouncingBall - C++ input file, Event-Driven version - V. Acary, F. Perignon. A Ball bouncing on the ground. Direct description of the model. Simulation with an Event-Driven scheme. */ #include "SiconosKernel.hpp" using namespace std; int main(int argc, char* argv[]) { boost::timer time; time.restart(); try { // ================= Creation of the model ======================= // User-defined main parameters unsigned int nDof = 3; // degrees of freedom for the ball double t0 = 0; // initial computation time double T = 8.5; // final computation time double h = 0.005; // time step double position_init = 1.0; // initial position for lowest bead. double velocity_init = 0.0; // initial velocity for lowest bead. double R = 0.1; // Ball radius double m = 1; // Ball mass double g = 9.81; // Gravity // ------------------------- // --- Dynamical systems --- // ------------------------- cout << "====> Model loading ..." << endl << endl; SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof)); (*Mass)(0, 0) = m; (*Mass)(1, 1) = m; (*Mass)(2, 2) = 3. / 5 * m * R * R; // -- Initial positions and velocities -- SP::SiconosVector q0(new SiconosVector(nDof)); SP::SiconosVector v0(new SiconosVector(nDof)); (*q0)(0) = position_init; (*v0)(0) = velocity_init; // -- The dynamical system -- SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass)); // -- Set external forces (weight) -- SP::SiconosVector weight(new SiconosVector(nDof)); (*weight)(0) = -m * g; ball->setFExtPtr(weight); // -------------------- // --- Interactions --- // -------------------- // -- nslaw -- double e = 0.9; // Interaction ball-floor // SP::SimpleMatrix H(new SimpleMatrix(1, nDof)); (*H)(0, 0) = 1.0; SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e)); SP::Relation relation0(new LagrangianLinearTIR(H)); SP::Interaction inter(new Interaction(1, nslaw0, relation0)); // -------------------------------- // --- NonSmoothDynamicalSystem --- // -------------------------------- // ------------- // --- Model --- // ------------- SP::Model bouncingBall(new Model(t0, T)); // add the dynamical system in the non smooth dynamical system bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball); // link the interaction and the dynamical system bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball); // ---------------- // --- Simulation --- // ---------------- // -- (1) OneStepIntegrators -- SP::OneStepIntegrator OSI(new LsodarOSI()); // -- (2) Time discretisation -- SP::TimeDiscretisation t(new TimeDiscretisation(t0, h)); // -- (3) Non smooth problem -- SP::OneStepNSProblem impact(new LCP()); SP::OneStepNSProblem acceleration(new LCP()); // -- (4) Simulation setup with (1) (2) (3) SP::EventDriven s(new EventDriven(t)); s->insertIntegrator(OSI); s->insertNonSmoothProblem(impact, SICONOS_OSNSP_ED_IMPACT); s->insertNonSmoothProblem(acceleration, SICONOS_OSNSP_ED_SMOOTH_ACC); // =========================== End of model definition =========================== // ================================= Computation ================================= // --- Simulation initialization --- cout << "====> Simulation initialisation ..." << endl << endl; s->setPrintStat(true); bouncingBall->initialize(s); int N = 1854; // Number of saved points: depends on the number of events ... // --- Get the values to be plotted --- // -> saved in a matrix dataPlot unsigned int outputSize = 7; SimpleMatrix dataPlot(N + 1, outputSize); SP::SiconosVector q = ball->q(); SP::SiconosVector v = ball->velocity(); SP::SiconosVector p = ball->p(1); SP::SiconosVector f = ball->p(2); // SiconosVector * y = bouncingBall->nonSmoothDynamicalSystem()->interaction(0)->y(0); SP::EventsManager eventsManager = s->eventsManager(); // For the initial time step: // time dataPlot(0, 0) = bouncingBall->t0(); dataPlot(0, 1) = (*q)(0); dataPlot(0, 2) = (*v)(0); dataPlot(0, 3) = (*p)(0); dataPlot(0, 4) = (*f)(0); // --- Time loop --- cout << "====> Start computation ... " << endl << endl; bool nonSmooth = false; unsigned int numberOfEvent = 0 ; int k = 0; int kns = 0; boost::progress_display show_progress(N); while (s->hasNextEvent() && k < N) { s->advanceToEvent(); if (eventsManager->nextEvent()->getType() == 2) nonSmooth = true; s->processEvents(); // If the treated event is non smooth, the pre-impact state has been solved in memory vectors during process. if (nonSmooth) { dataPlot(k, 0) = s->startingTime(); dataPlot(k, 1) = (*ball->qMemory()->getSiconosVector(1))(0); dataPlot(k, 2) = (*ball->velocityMemory()->getSiconosVector(1))(0); dataPlot(k, 3) = (*p)(0); dataPlot(k, 4) = (*f)(0); k++; kns++; nonSmooth = false; ++show_progress; } dataPlot(k, 0) = s->startingTime(); dataPlot(k, 1) = (*q)(0); dataPlot(k, 2) = (*v)(0); dataPlot(k, 3) = (*p)(0); dataPlot(k, 4) = (*f)(0); dataPlot(k, 5) = (*inter->lambda(1))(0); dataPlot(k, 6) = (*inter->lambda(2))(0); ++k; ++numberOfEvent; ++show_progress; } // --- Output files --- cout << endl; cout << "===== End of Event Driven simulation. " << endl; cout << numberOfEvent << " events have been processed. ==== " << endl; cout << numberOfEvent- kns << " events are of time--discretization type ==== " << endl; cout << kns << " events are of nonsmooth type ==== " << endl << endl; cout << "====> Output file writing ..." << endl << endl; dataPlot.resize(k, outputSize); ioMatrix::write("result.dat", "ascii", dataPlot, "noDim"); // Comparison with a reference file SimpleMatrix dataPlotRef(dataPlot); dataPlotRef.zero(); ioMatrix::read("BouncingBallED.ref", "ascii", dataPlotRef); std::cout << "error = " << (dataPlot - dataPlotRef).normInf() << std::endl; if ((dataPlot - dataPlotRef).normInf() > 1e-12) { std::cout << "Warning. The results is rather different from the reference file." << std::endl; return 1; } } catch (SiconosException e) { cout << e.report() << endl; } catch (...) { cout << "Exception caught." << endl; } cout << "Computation Time: " << time.elapsed() << endl; } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "Catch.hpp"<commit_msg>another case sensitivity fix<commit_after>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp"<|endoftext|>
<commit_before>// LoginMng.cpp : t@C // #include "stdafx.h" #include "MZ3.h" #include "LoginMng.h" #include "bf.h" #include "Winsock2.h" #include "util.h" /// IvVf[^ namespace option { // Login Login::Login() { m_ownerId = _T(""); } Login::~Login() { } // Login o֐ void Login::Read() { // ---------------------------------------- // IDƃpX[h擾 // ---------------------------------------- // st@C̃pXf[^t@C쐬 CString tmp; CString fileName; fileName.Format(_T("%s\\%s"), theApp.GetAppDirPath(), _T("user.dat")); // t@C݂Ă΂̃t@Cǂݍ FILE* fp; if( util::ExistFile(fileName) ) { // ---------------------------------------- // fR[h // ---------------------------------------- fp = _wfopen(fileName, _T("rb")); if (fp == NULL) { return; } m_loginMail = Read(fp); m_loginPwd = Read(fp); m_ownerId = Read(fp); TRACE(_T("Mail = %s\n"), m_loginMail); TRACE(_T("Password = %s\n"), m_loginPwd); TRACE(_T("OwnerId = %s\n"), m_ownerId); if (m_ownerId == _T("ERROR")) { m_ownerId = _T(""); } fclose(fp); } else { m_loginMail = _T(""); m_loginPwd = _T(""); m_ownerId = _T(""); } } void Login::Write() { // st@C̃pXf[^t@C쐬 CString fileName; fileName.Format(_T("%s\\%s"), theApp.GetAppDirPath(), _T("user.dat")); FILE* fp; // ---------------------------------------- // GR[h // ---------------------------------------- if (m_loginMail.GetLength() == 0 && m_loginPwd.GetLength() == 0) { return; } if (m_ownerId.GetLength() == 0) { m_ownerId = _T("ERROR"); } fp = _wfopen(fileName, _T("wb")); if (fp == NULL) { return; } Write(fp, m_loginMail); Write(fp, m_loginPwd); Write(fp, m_ownerId); fclose(fp); } LPCTSTR Login::Read(FILE* fp) { // blowfish̏ char key[256]; memset(key, 0x00, 256); wcstombs(key, _T("Mixi_browser_for_W-ZERO3"), 255); // ÍL[ bf::bf bf; bf.init((unsigned char*)key, strlen(key)); // CString ret = _T(""); int len = (int)fgetc(fp); // ꕶڂ𔲂o char buf[256]; memset(buf, 0x00, sizeof(char) * 256); int num = (int)fread(buf, sizeof(char), ((len/8)+1)*8, fp); for (int i=0; i<(int)(len / 8) + 1; i++) { char dBuf[9]; memset(dBuf, 0x00, sizeof(char) * 9); memcpy(dBuf, buf+i*8, 8); bf.decrypt((unsigned char*)dBuf); TCHAR str[256]; memset(str, 0x00, sizeof(TCHAR) * 256); mbstowcs(str, dBuf, 8); ret += str; } return ret.Mid(0, len); } void Login::Write(FILE* fp, LPCTSTR tmp) { CString str = tmp; // blowfish̏ char key[256]; memset(key, 0x00, 256); wcstombs(key, _T("Mixi_browser_for_W-ZERO3"), 255); // ÍL[ bf::bf bf; bf.init((unsigned char*)key, strlen(key)); // int len = wcslen(tmp); fputc(len, fp); // peBO for (int i=0; i<(((len / 8) + 1) * 8) - len; i++) { str += _T("0"); } for (int i=0; i<(int)(len / 8) + 1; i++) { CString buf = str.Mid(i * 8, 8); char mchar[256]; memset(mchar, '\0', sizeof(char) * 9); wcstombs(mchar, buf, 8); bf.encrypt((unsigned char*)mchar); fwrite(mchar, sizeof(char), 8, fp); } } }// namespace option <commit_msg>OwnerID取得時の処理を修正<commit_after>// LoginMng.cpp : t@C // #include "stdafx.h" #include "MZ3.h" #include "LoginMng.h" #include "bf.h" #include "Winsock2.h" #include "util.h" /// IvVf[^ namespace option { // Login Login::Login() { m_ownerId = _T(""); } Login::~Login() { } // Login o֐ void Login::Read() { // ---------------------------------------- // IDƃpX[h擾 // ---------------------------------------- // st@C̃pXf[^t@C쐬 CString tmp; CString fileName; fileName.Format(_T("%s\\%s"), theApp.GetAppDirPath(), _T("user.dat")); // t@C݂Ă΂̃t@Cǂݍ FILE* fp; if( util::ExistFile(fileName) ) { // ---------------------------------------- // fR[h // ---------------------------------------- fp = _wfopen(fileName, _T("rb")); if (fp == NULL) { return; } m_loginMail = Read(fp); m_loginPwd = Read(fp); m_ownerId = Read(fp); TRACE(_T("Mail = %s\n"), m_loginMail); TRACE(_T("Password = %s\n"), m_loginPwd); TRACE(_T("OwnerId = %s\n"), m_ownerId); if (m_ownerId == _T("ERROR")) { m_ownerId = _T(""); } fclose(fp); } else { m_loginMail = _T(""); m_loginPwd = _T(""); m_ownerId = _T(""); } } void Login::Write() { // st@C̃pXf[^t@C쐬 CString fileName; fileName.Format(_T("%s\\%s"), theApp.GetAppDirPath(), _T("user.dat")); FILE* fp; // ---------------------------------------- // GR[h // ---------------------------------------- if (m_loginMail.GetLength() == 0 && m_loginPwd.GetLength() == 0) { return; } if (m_ownerId.GetLength() == 0) { m_ownerId = _T(""); } fp = _wfopen(fileName, _T("wb")); if (fp == NULL) { return; } Write(fp, m_loginMail); Write(fp, m_loginPwd); Write(fp, m_ownerId); fclose(fp); } LPCTSTR Login::Read(FILE* fp) { // blowfish̏ char key[256]; memset(key, 0x00, 256); wcstombs(key, _T("Mixi_browser_for_W-ZERO3"), 255); // ÍL[ bf::bf bf; bf.init((unsigned char*)key, strlen(key)); // CString ret = _T(""); int len = (int)fgetc(fp); // ꕶڂ𔲂o char buf[256]; memset(buf, 0x00, sizeof(char) * 256); int num = (int)fread(buf, sizeof(char), ((len/8)+1)*8, fp); for (int i=0; i<(int)(len / 8) + 1; i++) { char dBuf[9]; memset(dBuf, 0x00, sizeof(char) * 9); memcpy(dBuf, buf+i*8, 8); bf.decrypt((unsigned char*)dBuf); TCHAR str[256]; memset(str, 0x00, sizeof(TCHAR) * 256); mbstowcs(str, dBuf, 8); ret += str; } return ret.Mid(0, len); } void Login::Write(FILE* fp, LPCTSTR tmp) { CString str = tmp; // blowfish̏ char key[256]; memset(key, 0x00, 256); wcstombs(key, _T("Mixi_browser_for_W-ZERO3"), 255); // ÍL[ bf::bf bf; bf.init((unsigned char*)key, strlen(key)); // int len = wcslen(tmp); fputc(len, fp); // peBO for (int i=0; i<(((len / 8) + 1) * 8) - len; i++) { str += _T("0"); } for (int i=0; i<(int)(len / 8) + 1; i++) { CString buf = str.Mid(i * 8, 8); char mchar[256]; memset(mchar, '\0', sizeof(char) * 9); wcstombs(mchar, buf, 8); bf.encrypt((unsigned char*)mchar); fwrite(mchar, sizeof(char), 8, fp); } } }// namespace option <|endoftext|>
<commit_before>//Includes all the headers necessary to use the most common public pieces of the ROS system. #include <ros/ros.h> //Include some useful constants for image encoding. Refer to: http://www.ros.org/doc/api/sensor_msgs/html/namespacesensor__msgs_1_1image__encodings.html for more info. #include <geometry_msgs/Pose2D.h> #include <sensor_msgs/LaserScan.h> #include <nav_msgs/OccupancyGrid.h> #include <tf/transform_broadcaster.h> #include <nav_msgs/Odometry.h> #include <stdlib.h> #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <math.h> #include <dirent.h> #include <iomanip> #include <ctime> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <unistd.h> #include "icarus_rover_rc/Definitions.h" #include "icarus_rover_rc/ICARUS_Diagnostic.h" using namespace std; //Communication Variables //Operation Variables string Mode = ""; //Program Variables double dtime = 0.0; double Pose_X; double Pose_Y; double Pose_Theta; void ICARUS_Rover_Pose_Callback(const geometry_msgs::Pose2D::ConstPtr& msg) { tf::TransformBroadcaster odom_broadcaster; geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(msg->theta); geometry_msgs::TransformStamped odom_trans; odom_trans.header.stamp = ros::Time::now(); odom_trans.header.frame_id = "odom"; odom_trans.child_frame_id = "base_link"; odom_trans.transform.translation.x = msg->x; odom_trans.transform.translation.y = msg->y; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = odom_quat; odom_broadcaster.sendTransform(odom_trans); Pose_X = msg->x; Pose_Y = msg->y; Pose_Theta = msg->theta; printf("Got a Pose x: %f y: %f theta: %f\r\n",msg->x,msg->y,msg->theta); } void ICARUS_Sonar_Scan_Callback(const sensor_msgs::LaserScan::ConstPtr& msg) { cout << "Got a Scan" << endl; } void test_Callback(const icarus_rover_rc::ICARUS_Diagnostic::ConstPtr& msg) { cout << "Got a Diag." << endl; } int main(int argc, char **argv) { ros::init(argc, argv, "Mapping_Node"); ros::NodeHandle nh("~"); nh.getParam("Mode",Mode); ros::Publisher Pub_ICARUS_Mapping_Diagnostic = nh.advertise<icarus_rover_rc::ICARUS_Diagnostic>("ICARUS_Mapping_Diagnostic",1000); ros::Rate loop_rate(100); std::clock_t start; ros::Publisher Pub_ICARUS_OccupancyGrid; ros::Publisher Pub_ICARUS_Rover_Odom; ros::Subscriber Sub_Rover_Pose; ros::Subscriber Sub_Sonar_Scan; if(Mode.compare("Sim") == 0) { Pub_ICARUS_OccupancyGrid = nh.advertise<nav_msgs::OccupancyGrid>("ICARUS_SimOccupancyGrid",1000); Sub_Rover_Pose = nh.subscribe<geometry_msgs::Pose2D>("/Matlab_Node/ICARUS_SimRover_Pose",1000,ICARUS_Rover_Pose_Callback); cout << Sub_Rover_Pose << endl; Sub_Sonar_Scan = nh.subscribe<sensor_msgs::LaserScan>("/Matlab_Node/ICARUS_SimSonar_Scan",1000,ICARUS_Sonar_Scan_Callback); Pub_ICARUS_Rover_Odom = nh.advertise<nav_msgs::Odometry>("ICARUS_SimRover_Odom",1000); cout << "Sim Mode" << endl; } else if(Mode.compare("Live") == 0) { Pub_ICARUS_OccupancyGrid = nh.advertise<nav_msgs::OccupancyGrid>("ICARUS_OccupancyGrid",1000); Sub_Rover_Pose = nh.subscribe<geometry_msgs::Pose2D>("/Motion_Controller_Node/ICARUS_Rover_Pose",1000,ICARUS_Rover_Pose_Callback); Sub_Sonar_Scan = nh.subscribe<sensor_msgs::LaserScan>("/Sonic_Controller_Node/ICARUS_Sonar_Scan",1000,ICARUS_Sonar_Scan_Callback); Pub_ICARUS_Rover_Odom = nh.advertise<nav_msgs::Odometry>("ICARUS_Rover_Odom",1000); cout << "Live Mode" << endl; } ::icarus_rover_rc::ICARUS_Diagnostic ICARUS_Diagnostic; nav_msgs::OccupancyGrid OccupancyGrid; ICARUS_Diagnostic.header.frame_id = "ICARUS_Mapping_Diagnostic"; ICARUS_Diagnostic.System = ROVER; ICARUS_Diagnostic.SubSystem = ROBOT_CONTROLLER; ICARUS_Diagnostic.Component = MAPPING_NODE; while(ros::ok()) { start = std::clock(); ros::spinOnce(); loop_rate.sleep(); try { dtime = (std::clock() - start) / (double)(CLOCKS_PER_SEC /1); Pub_ICARUS_OccupancyGrid.publish(OccupancyGrid); //ICARUS Diagnostics Publisher ICARUS_Diagnostic.header.stamp = ros::Time::now(); Pub_ICARUS_Mapping_Diagnostic.publish(ICARUS_Diagnostic); nav_msgs::Odometry Rover_Odometry; Rover_Odometry.header.stamp = ros::Time::now(); Rover_Odometry.header.frame_id = "odom"; Rover_Odometry.pose.pose.position.x = Pose_X; Rover_Odometry.pose.pose.position.y = Pose_Y; Rover_Odometry.pose.pose.position.z = 0.0; geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(Pose_Theta); Rover_Odometry.pose.pose.orientation = odom_quat; Pub_ICARUS_Rover_Odom.publish(Rover_Odometry); } catch(const std::exception& ex) { ROS_INFO("ERROR:%s",ex.what()); //ICARUS Diagnostics Publisher ICARUS_Diagnostic.header.stamp = ros::Time::now(); ICARUS_Diagnostic.Diagnostic_Type = GENERAL_ERROR; ICARUS_Diagnostic.Level = FATAL; ICARUS_Diagnostic.Diagnostic_Message = GENERAL_ERROR; ICARUS_Diagnostic.Description = ex.what(); Pub_ICARUS_Mapping_Diagnostic.publish(ICARUS_Diagnostic); } } ICARUS_Diagnostic.header.stamp = ros::Time::now(); ICARUS_Diagnostic.Diagnostic_Type = GENERAL_ERROR; ICARUS_Diagnostic.Level = SEVERE; ICARUS_Diagnostic.Diagnostic_Message = DEVICE_NOT_AVAILABLE; ICARUS_Diagnostic.Description = "Node Closed."; Pub_ICARUS_Mapping_Diagnostic.publish(ICARUS_Diagnostic); } <commit_msg>Work on Mapping_Node tf Broadcaster.<commit_after>//Includes all the headers necessary to use the most common public pieces of the ROS system. #include <ros/ros.h> //Include some useful constants for image encoding. Refer to: http://www.ros.org/doc/api/sensor_msgs/html/namespacesensor__msgs_1_1image__encodings.html for more info. #include <geometry_msgs/Pose2D.h> #include <sensor_msgs/LaserScan.h> #include <nav_msgs/OccupancyGrid.h> #include <tf/transform_broadcaster.h> #include <nav_msgs/Odometry.h> #include <stdlib.h> #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <math.h> #include <dirent.h> #include <iomanip> #include <ctime> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <unistd.h> #include "icarus_rover_rc/Definitions.h" #include "icarus_rover_rc/ICARUS_Diagnostic.h" using namespace std; //Communication Variables //Operation Variables string Mode = ""; //Program Variables double dtime = 0.0; double Pose_X; double Pose_Y; double Pose_Theta; void ICARUS_Rover_Pose_Callback(const geometry_msgs::Pose2D::ConstPtr& msg) { tf::TransformBroadcaster odom_broadcaster; /* geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(msg->theta); geometry_msgs::TransformStamped odom_trans; odom_trans.header.stamp = ros::Time::now(); odom_trans.header.frame_id = "/base_link"; odom_trans.child_frame_id = "/odom"; odom_trans.transform.translation.x = msg->x; odom_trans.transform.translation.y = msg->y; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = odom_quat; */ geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(msg->theta); odom_broadcaster.sendTransform(tf::StampedTransform(tf::Transform(tf::Quaternion(0,0,0,1),tf::Vector3(msg->x,msg->y,0.0)),ros::Time::now(),"/base_link","odom")); //odom_broadcaster.sendTransform(odom_trans); Pose_X = msg->x; Pose_Y = msg->y; Pose_Theta = msg->theta; /* tf::TransformBroadcaster scan_broadcaster; geometry_msgs::Quaternion scan_quat = tf::createQuaternionMsgFromYaw(0.0); geometry_msgs::TransformStamped scan_trans; scan_trans.header.stamp = ros::Time::now(); scan_trans.header.frame_id = "/scan"; scan_trans.child_frame_id = "/base_link"; scan_trans.transform.translation.x = 0.0; scan_trans.transform.translation.y = 0.0; scan_trans.transform.translation.z = -.0; scan_trans.transform.rotation = scan_quat; scan_broadcaster.sendTransform(scan_trans); */ tf::TransformBroadcaster scan_broadcaster; scan_broadcaster.sendTransform(tf::StampedTransform(tf::Transform(tf::Quaternion(0,0,0,1),tf::Vector3(0.0,0.0,0.2)), ros::Time::now(),"/base_link","/scan")); printf("Got a Pose x: %f y: %f theta: %f\r\n",msg->x,msg->y,msg->theta); } void ICARUS_Sonar_Scan_Callback(const sensor_msgs::LaserScan::ConstPtr& msg) { cout << "Got a Scan" << endl; } void test_Callback(const icarus_rover_rc::ICARUS_Diagnostic::ConstPtr& msg) { cout << "Got a Diag." << endl; } int main(int argc, char **argv) { ros::init(argc, argv, "Mapping_Node"); ros::NodeHandle nh("~"); nh.getParam("Mode",Mode); ros::Publisher Pub_ICARUS_Mapping_Diagnostic = nh.advertise<icarus_rover_rc::ICARUS_Diagnostic>("ICARUS_Mapping_Diagnostic",1000); ros::Rate loop_rate(100); std::clock_t start; ros::Publisher Pub_ICARUS_OccupancyGrid; ros::Publisher Pub_ICARUS_Rover_Odom; ros::Subscriber Sub_Rover_Pose; ros::Subscriber Sub_Sonar_Scan; if(Mode.compare("Sim") == 0) { Pub_ICARUS_OccupancyGrid = nh.advertise<nav_msgs::OccupancyGrid>("ICARUS_SimOccupancyGrid",1000); Sub_Rover_Pose = nh.subscribe<geometry_msgs::Pose2D>("/Matlab_Node/ICARUS_SimRover_Pose",1000,ICARUS_Rover_Pose_Callback); cout << Sub_Rover_Pose << endl; Sub_Sonar_Scan = nh.subscribe<sensor_msgs::LaserScan>("/Matlab_Node/ICARUS_SimSonar_Scan",1000,ICARUS_Sonar_Scan_Callback); Pub_ICARUS_Rover_Odom = nh.advertise<nav_msgs::Odometry>("ICARUS_SimRover_Odom",1000); cout << "Sim Mode" << endl; } else if(Mode.compare("Live") == 0) { Pub_ICARUS_OccupancyGrid = nh.advertise<nav_msgs::OccupancyGrid>("ICARUS_OccupancyGrid",1000); Sub_Rover_Pose = nh.subscribe<geometry_msgs::Pose2D>("/Motion_Controller_Node/ICARUS_Rover_Pose",1000,ICARUS_Rover_Pose_Callback); Sub_Sonar_Scan = nh.subscribe<sensor_msgs::LaserScan>("/Sonic_Controller_Node/ICARUS_Sonar_Scan",1000,ICARUS_Sonar_Scan_Callback); Pub_ICARUS_Rover_Odom = nh.advertise<nav_msgs::Odometry>("ICARUS_Rover_Odom",1000); cout << "Live Mode" << endl; } ::icarus_rover_rc::ICARUS_Diagnostic ICARUS_Diagnostic; nav_msgs::OccupancyGrid OccupancyGrid; ICARUS_Diagnostic.header.frame_id = "ICARUS_Mapping_Diagnostic"; ICARUS_Diagnostic.System = ROVER; ICARUS_Diagnostic.SubSystem = ROBOT_CONTROLLER; ICARUS_Diagnostic.Component = MAPPING_NODE; while(ros::ok()) { start = std::clock(); ros::spinOnce(); loop_rate.sleep(); try { dtime = (std::clock() - start) / (double)(CLOCKS_PER_SEC /1); Pub_ICARUS_OccupancyGrid.publish(OccupancyGrid); //ICARUS Diagnostics Publisher ICARUS_Diagnostic.header.stamp = ros::Time::now(); Pub_ICARUS_Mapping_Diagnostic.publish(ICARUS_Diagnostic); nav_msgs::Odometry Rover_Odometry; Rover_Odometry.header.stamp = ros::Time::now(); Rover_Odometry.header.frame_id = "/odom"; Rover_Odometry.pose.pose.position.x = Pose_X; Rover_Odometry.pose.pose.position.y = Pose_Y; Rover_Odometry.pose.pose.position.z = 0.0; geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(Pose_Theta); Rover_Odometry.pose.pose.orientation = odom_quat; Pub_ICARUS_Rover_Odom.publish(Rover_Odometry); } catch(const std::exception& ex) { ROS_INFO("ERROR:%s",ex.what()); //ICARUS Diagnostics Publisher ICARUS_Diagnostic.header.stamp = ros::Time::now(); ICARUS_Diagnostic.Diagnostic_Type = GENERAL_ERROR; ICARUS_Diagnostic.Level = FATAL; ICARUS_Diagnostic.Diagnostic_Message = GENERAL_ERROR; ICARUS_Diagnostic.Description = ex.what(); Pub_ICARUS_Mapping_Diagnostic.publish(ICARUS_Diagnostic); } } ICARUS_Diagnostic.header.stamp = ros::Time::now(); ICARUS_Diagnostic.Diagnostic_Type = GENERAL_ERROR; ICARUS_Diagnostic.Level = SEVERE; ICARUS_Diagnostic.Diagnostic_Message = DEVICE_NOT_AVAILABLE; ICARUS_Diagnostic.Description = "Node Closed."; Pub_ICARUS_Mapping_Diagnostic.publish(ICARUS_Diagnostic); } <|endoftext|>
<commit_before>/*============================================================================= Copyright (c) 2012-2013 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // evaluate.cpp -- evaluate energies from a Database #include "libgibbs/include/libgibbs_pch.hpp" #include "libgibbs/include/equilibrium.hpp" #include "libtdb/include/database.hpp" #include "libtdb/include/structure.hpp" #include "libtdb/include/exceptions.hpp" #include "libgibbs/include/optimizer/optimizer.hpp" #include "libgibbs/include/optimizer/opt_Gibbs.hpp" #include "external/coin/IpIpoptApplication.hpp" #include "external/coin/IpSolveStatistics.hpp" #include <iostream> #include <fstream> #include <algorithm> #include <sstream> #include <boost/io/ios_state.hpp> using namespace Ipopt; Equilibrium::Equilibrium(const Database &DB, const evalconditions &conds) : sourcename(DB.get_info()), conditions(conds) { Phase_Collection phase_col; for (auto i = DB.get_phase_iterator(); i != DB.get_phase_iterator_end(); ++i) { if (conds.phases.find(i->first) != conds.phases.end()) { if (conds.phases.at(i->first) == true) phase_col[i->first] = i->second; } } const Phase_Collection::const_iterator phase_iter = phase_col.cbegin(); const Phase_Collection::const_iterator phase_end = phase_col.cend(); // TODO: check validity of conditions // Create an instance of your nlp... SmartPtr<TNLP> mynlp = new GibbsOpt(phase_iter, phase_end, conds); // Create an instance of the IpoptApplication // // We are using the factory, since this allows us to compile this // example with an Ipopt Windows DLL SmartPtr<IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetStringValue("derivative_test","first-order"); app->Options()->SetStringValue("hessian_approximation","limited-memory"); //app->Options()->SetIntegerValue("print_level",12); //app->Options()->SetStringValue("derivative_test_print_all","yes"); // Initialize the IpoptApplication and process the options ApplicationReturnStatus status; status = app->Initialize(); if (status != Solve_Succeeded) { std::cout << std::endl << std::endl << "*** Error during initialization!" << std::endl; BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Error initializing solver")); } status = app->OptimizeTNLP(mynlp); if (status == Solve_Succeeded || status == Solved_To_Acceptable_Level) { // Retrieve some statistics about the solve Index iter_count = app->Statistics()->IterationCount(); std::cout << std::endl << std::endl << "*** The problem solved in " << iter_count << " iterations!" << std::endl; Number final_obj = app->Statistics()->FinalObjective(); mingibbs = final_obj * conds.statevars.find('N')->second; GibbsOpt* opt_ptr = dynamic_cast<GibbsOpt*> (Ipopt::GetRawPtr(mynlp)); if (!opt_ptr) BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Internal memory error") << specific_errinfo("dynamic_cast<GibbsOpt*>")); ph_map = opt_ptr->get_phase_map(); } else { BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Solver failed to find equilibrium")); } } std::ostream& operator<< (std::ostream& stream, const Equilibrium& eq) { boost::io::ios_flags_saver ifs( stream ); // preserve original state of the stream once we leave scope stream << "Output from LIBGIBBS, equilibrium number = ??" << std::endl; stream << "Conditions:" << std::endl; // We want the individual phase information to appear AFTER // the global system data, but the most efficient ordering // requires us to iterate through all phases first. // The simple solution is to save the output to a temporary // buffer, and then flush it to the output stream later. std::stringstream temp_buf; temp_buf << std::scientific; const auto sv_end = eq.conditions.statevars.cend(); const auto xf_end = eq.conditions.xfrac.cend(); for (auto i = eq.conditions.xfrac.cbegin(); i !=xf_end; ++i) { stream << "X(" << i->first << ")=" << i->second << ", "; } for (auto i = eq.conditions.statevars.cbegin(); i != sv_end; ++i) { stream << i->first << "=" << i->second; // if this isn't the last one, add a comma if (std::distance(i,sv_end) != 1) stream << ", "; } stream << std::endl; // should be c + 2 - conditions, where c is the number of components size_t dof = eq.conditions.elements.size() + 2 - (eq.conditions.xfrac.size()+1) - eq.conditions.statevars.size(); stream << "DEGREES OF FREEDOM " << dof << std::endl; stream << std::endl; double T,P,N; T = eq.conditions.statevars.find('T')->second; P = eq.conditions.statevars.find('P')->second; N = eq.conditions.statevars.find('N')->second; stream << "Temperature " << T << " K (" << (T-273.15) << " C), " << "Pressure " << P << " Pa" << std::endl; stream << std::scientific; // switch to scientific notation for doubles stream << "Number of moles of components " << N << ", Mass ????" << std::endl; stream << "Total Gibbs energy " << eq.mingibbs << " Enthalpy ???? " << "Volume ????" << std::endl; stream << std::endl; const auto ph_end = eq.ph_map.cend(); const auto cond_spec_begin = eq.conditions.elements.cbegin(); const auto cond_spec_end = eq.conditions.elements.cend(); // double/double pair is for separate storage of numerator/denominator pieces of fraction std::map<std::string,std::pair<double,double>> global_comp; for (auto i = eq.ph_map.cbegin(); i != ph_end; ++i) { const auto subl_begin = i->second.second.cbegin(); const auto subl_end = i->second.second.cend(); const double phasefrac = i->second.first; std::map<std::string,std::pair<double,double>> phase_comp; temp_buf << i->first << "\tStatus ENTERED Driving force 0" << std::endl; // phase name temp_buf << "Number of moles " << i->second.first * N << ", Mass ???? "; temp_buf << "Mole fractions:" << std::endl; for (auto j = subl_begin; j != subl_end; ++j) { const double stoi_coef = j->first; const double den = stoi_coef; const auto spec_begin = j->second.cbegin(); const auto spec_end = j->second.cend(); const auto vacancy_iterator = (j->second).find("VA"); // this may point to spec_end /* * To make sure all mole fractions sum to 1, * we have to normalize everything using the same * sublattices. That means even species which don't * appear in a given sublattice need to have that * sublattice's coefficient appear in its denominator. * To accomplish this task, we perform two loops in each sublattice: * 1) all species (except VA), to add to the denominator * 2) only species in that sublattice, to add to the numerator * With this method, all mole fractions will sum properly. */ for (auto k = cond_spec_begin; k != cond_spec_end; ++k) { if (*k == "VA") continue; // vacancies don't contribute to mole fractions if (vacancy_iterator != spec_end) { phase_comp[*k].second += den * (1 - vacancy_iterator->second); } else { phase_comp[*k].second += den; } } for (auto k = spec_begin; k != spec_end; ++k) { if (k->first == "VA") continue; // vacancies don't contribute to mole fractions double num = k->second * stoi_coef; phase_comp[k->first].first += num; } } /* We've summed up over all sublattices in this phase. * Now add this phase's contribution to the overall composition. */ for (auto j = cond_spec_begin; j != cond_spec_end; ++j) { if (*j == "VA") continue; // vacancies don't contribute to mole fractions global_comp[*j].first += phasefrac * (phase_comp[*j].first / phase_comp[*j].second); global_comp[*j].second += phasefrac; } const auto cmp_begin = phase_comp.cbegin(); const auto cmp_end = phase_comp.cend(); for (auto g = cmp_begin; g != cmp_end; ++g) { temp_buf << g->first << " " << (g->second.first / g->second.second) << " "; } temp_buf << std::endl << "Constitution:" << std::endl; for (auto j = subl_begin; j != subl_end; ++j) { double stoi_coef = j->first; temp_buf << "Sublattice " << std::distance(subl_begin,j)+1 << ", Number of sites " << stoi_coef << std::endl; const auto spec_begin = j->second.cbegin(); const auto spec_end = j->second.cend(); for (auto k = spec_begin; k != spec_end; ++k) { temp_buf << k->first << " " << k->second << " "; } temp_buf << std::endl; } // if we're at the last phase, don't add an extra newline if (std::distance(i,ph_end) != 1) temp_buf << std::endl; } const auto glob_begin = global_comp.cbegin(); const auto glob_end = global_comp.cend(); stream << "Component\tMoles\tW-Fraction\tActivity\tPotential\tRef.state" << std::endl; for (auto h = glob_begin; h != glob_end; ++h) { stream << h->first << " " << (h->second.first / h->second.second) * N << " ???? ???? ???? ????" << std::endl; } stream << std::endl; stream << temp_buf.rdbuf(); // include the temporary buffer with all the phase data return stream; } <commit_msg>Increased derivative test perturbation size to eliminate false positives caused by floating point truncation errors.<commit_after>/*============================================================================= Copyright (c) 2012-2013 Richard Otis Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // evaluate.cpp -- evaluate energies from a Database #include "libgibbs/include/libgibbs_pch.hpp" #include "libgibbs/include/equilibrium.hpp" #include "libtdb/include/database.hpp" #include "libtdb/include/structure.hpp" #include "libtdb/include/exceptions.hpp" #include "libgibbs/include/optimizer/optimizer.hpp" #include "libgibbs/include/optimizer/opt_Gibbs.hpp" #include "external/coin/IpIpoptApplication.hpp" #include "external/coin/IpSolveStatistics.hpp" #include <iostream> #include <fstream> #include <algorithm> #include <sstream> #include <boost/io/ios_state.hpp> using namespace Ipopt; Equilibrium::Equilibrium(const Database &DB, const evalconditions &conds) : sourcename(DB.get_info()), conditions(conds) { Phase_Collection phase_col; for (auto i = DB.get_phase_iterator(); i != DB.get_phase_iterator_end(); ++i) { if (conds.phases.find(i->first) != conds.phases.end()) { if (conds.phases.at(i->first) == true) phase_col[i->first] = i->second; } } const Phase_Collection::const_iterator phase_iter = phase_col.cbegin(); const Phase_Collection::const_iterator phase_end = phase_col.cend(); // TODO: check validity of conditions // Create an instance of your nlp... SmartPtr<TNLP> mynlp = new GibbsOpt(phase_iter, phase_end, conds); // Create an instance of the IpoptApplication // // We are using the factory, since this allows us to compile this // example with an Ipopt Windows DLL SmartPtr<IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetStringValue("derivative_test","first-order"); app->Options()->SetNumericValue("derivative_test_perturbation",1e-6); app->Options()->SetStringValue("hessian_approximation","limited-memory"); //app->Options()->SetIntegerValue("print_level",12); //app->Options()->SetStringValue("derivative_test_print_all","yes"); // Initialize the IpoptApplication and process the options ApplicationReturnStatus status; status = app->Initialize(); if (status != Solve_Succeeded) { std::cout << std::endl << std::endl << "*** Error during initialization!" << std::endl; BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Error initializing solver")); } status = app->OptimizeTNLP(mynlp); if (status == Solve_Succeeded || status == Solved_To_Acceptable_Level) { // Retrieve some statistics about the solve Index iter_count = app->Statistics()->IterationCount(); std::cout << std::endl << std::endl << "*** The problem solved in " << iter_count << " iterations!" << std::endl; Number final_obj = app->Statistics()->FinalObjective(); mingibbs = final_obj * conds.statevars.find('N')->second; GibbsOpt* opt_ptr = dynamic_cast<GibbsOpt*> (Ipopt::GetRawPtr(mynlp)); if (!opt_ptr) BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Internal memory error") << specific_errinfo("dynamic_cast<GibbsOpt*>")); ph_map = opt_ptr->get_phase_map(); } else { BOOST_THROW_EXCEPTION(equilibrium_error() << str_errinfo("Solver failed to find equilibrium")); } } std::ostream& operator<< (std::ostream& stream, const Equilibrium& eq) { boost::io::ios_flags_saver ifs( stream ); // preserve original state of the stream once we leave scope stream << "Output from LIBGIBBS, equilibrium number = ??" << std::endl; stream << "Conditions:" << std::endl; // We want the individual phase information to appear AFTER // the global system data, but the most efficient ordering // requires us to iterate through all phases first. // The simple solution is to save the output to a temporary // buffer, and then flush it to the output stream later. std::stringstream temp_buf; temp_buf << std::scientific; const auto sv_end = eq.conditions.statevars.cend(); const auto xf_end = eq.conditions.xfrac.cend(); for (auto i = eq.conditions.xfrac.cbegin(); i !=xf_end; ++i) { stream << "X(" << i->first << ")=" << i->second << ", "; } for (auto i = eq.conditions.statevars.cbegin(); i != sv_end; ++i) { stream << i->first << "=" << i->second; // if this isn't the last one, add a comma if (std::distance(i,sv_end) != 1) stream << ", "; } stream << std::endl; // should be c + 2 - conditions, where c is the number of components size_t dof = eq.conditions.elements.size() + 2 - (eq.conditions.xfrac.size()+1) - eq.conditions.statevars.size(); stream << "DEGREES OF FREEDOM " << dof << std::endl; stream << std::endl; double T,P,N; T = eq.conditions.statevars.find('T')->second; P = eq.conditions.statevars.find('P')->second; N = eq.conditions.statevars.find('N')->second; stream << "Temperature " << T << " K (" << (T-273.15) << " C), " << "Pressure " << P << " Pa" << std::endl; stream << std::scientific; // switch to scientific notation for doubles stream << "Number of moles of components " << N << ", Mass ????" << std::endl; stream << "Total Gibbs energy " << eq.mingibbs << " Enthalpy ???? " << "Volume ????" << std::endl; stream << std::endl; const auto ph_end = eq.ph_map.cend(); const auto cond_spec_begin = eq.conditions.elements.cbegin(); const auto cond_spec_end = eq.conditions.elements.cend(); // double/double pair is for separate storage of numerator/denominator pieces of fraction std::map<std::string,std::pair<double,double>> global_comp; for (auto i = eq.ph_map.cbegin(); i != ph_end; ++i) { const auto subl_begin = i->second.second.cbegin(); const auto subl_end = i->second.second.cend(); const double phasefrac = i->second.first; std::map<std::string,std::pair<double,double>> phase_comp; temp_buf << i->first << "\tStatus ENTERED Driving force 0" << std::endl; // phase name temp_buf << "Number of moles " << i->second.first * N << ", Mass ???? "; temp_buf << "Mole fractions:" << std::endl; for (auto j = subl_begin; j != subl_end; ++j) { const double stoi_coef = j->first; const double den = stoi_coef; const auto spec_begin = j->second.cbegin(); const auto spec_end = j->second.cend(); const auto vacancy_iterator = (j->second).find("VA"); // this may point to spec_end /* * To make sure all mole fractions sum to 1, * we have to normalize everything using the same * sublattices. That means even species which don't * appear in a given sublattice need to have that * sublattice's coefficient appear in its denominator. * To accomplish this task, we perform two loops in each sublattice: * 1) all species (except VA), to add to the denominator * 2) only species in that sublattice, to add to the numerator * With this method, all mole fractions will sum properly. */ for (auto k = cond_spec_begin; k != cond_spec_end; ++k) { if (*k == "VA") continue; // vacancies don't contribute to mole fractions if (vacancy_iterator != spec_end) { phase_comp[*k].second += den * (1 - vacancy_iterator->second); } else { phase_comp[*k].second += den; } } for (auto k = spec_begin; k != spec_end; ++k) { if (k->first == "VA") continue; // vacancies don't contribute to mole fractions double num = k->second * stoi_coef; phase_comp[k->first].first += num; } } /* We've summed up over all sublattices in this phase. * Now add this phase's contribution to the overall composition. */ for (auto j = cond_spec_begin; j != cond_spec_end; ++j) { if (*j == "VA") continue; // vacancies don't contribute to mole fractions global_comp[*j].first += phasefrac * (phase_comp[*j].first / phase_comp[*j].second); global_comp[*j].second += phasefrac; } const auto cmp_begin = phase_comp.cbegin(); const auto cmp_end = phase_comp.cend(); for (auto g = cmp_begin; g != cmp_end; ++g) { temp_buf << g->first << " " << (g->second.first / g->second.second) << " "; } temp_buf << std::endl << "Constitution:" << std::endl; for (auto j = subl_begin; j != subl_end; ++j) { double stoi_coef = j->first; temp_buf << "Sublattice " << std::distance(subl_begin,j)+1 << ", Number of sites " << stoi_coef << std::endl; const auto spec_begin = j->second.cbegin(); const auto spec_end = j->second.cend(); for (auto k = spec_begin; k != spec_end; ++k) { temp_buf << k->first << " " << k->second << " "; } temp_buf << std::endl; } // if we're at the last phase, don't add an extra newline if (std::distance(i,ph_end) != 1) temp_buf << std::endl; } const auto glob_begin = global_comp.cbegin(); const auto glob_end = global_comp.cend(); stream << "Component\tMoles\tW-Fraction\tActivity\tPotential\tRef.state" << std::endl; for (auto h = glob_begin; h != glob_end; ++h) { stream << h->first << " " << (h->second.first / h->second.second) * N << " ???? ???? ???? ????" << std::endl; } stream << std::endl; stream << temp_buf.rdbuf(); // include the temporary buffer with all the phase data return stream; } <|endoftext|>
<commit_before>#include "task_synthetic_shapes.h" #include "libnanocv/loss.h" #include "libnanocv/util/math.hpp" #include "libnanocv/util/random.hpp" namespace ncv { synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration) : task_t(configuration), m_rows(math::clamp(text::from_params<size_t>(configuration, "rows", 32), 16, 32)), m_cols(math::clamp(text::from_params<size_t>(configuration, "cols", 32), 16, 32)), m_outputs(math::clamp(text::from_params<size_t>(configuration, "dims", 4), 2, 16)), m_folds(1), m_color(text::from_params<color_mode>(configuration, "color", color_mode::rgba)), m_size(math::clamp(text::from_params<size_t>(configuration, "size", 1024), 256, 16 * 1024)) { } namespace { rgba_t make_transparent_color() { return 0; } rgba_t make_light_color() { random_t<rgba_t> rng_red(175, 255); random_t<rgba_t> rng_green(175, 255); random_t<rgba_t> rng_blue(175, 255); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rgba_t make_dark_color() { random_t<rgba_t> rng_red(0, 125); random_t<rgba_t> rng_green(0, 125); random_t<rgba_t> rng_blue(0, 125); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rect_t make_rect(coord_t rows, coord_t cols) { random_t<coord_t> rng(3, std::min(rows / 4, cols / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(dx, dy, cols - dx - dw, rows - dy - dh); } rect_t make_interior_rect(const rect_t& rect) { random_t<coord_t> rngx(4, rect.width() / 4); random_t<coord_t> rngy(4, rect.height() / 4); const coord_t dx = rngx(); const coord_t dy = rngy(); const coord_t dw = rngx(); const coord_t dh = rngy(); return rect_t(rect.left() + dx, rect.top() + dy, rect.width() - dx - dw, rect.height() - dy - dh); } rect_t make_vertical_interior_rect(const rect_t& rect) { const coord_t dx = (rect.width() + 2) / 3; const coord_t dy = 0; const coord_t dw = (rect.width() + 2) / 3; const coord_t dh = 0; return rect_t(rect.left() + dx, rect.top() + dy, rect.width() - dx - dw, rect.height() - dy - dh); } rect_t make_horizontal_interior_rect(const rect_t& rect) { const coord_t dx = 0; const coord_t dy = (rect.height() + 2) / 3; const coord_t dw = 0; const coord_t dh = (rect.height() + 2) / 3; return rect_t(rect.left() + dx, rect.top() + dy, rect.width() - dx - dw, rect.height() - dy - dh); } image_t make_filled_rect(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, fill_color); return image; } image_t make_hollow_rect(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, fill_color); image.fill(make_interior_rect(rect), make_transparent_color()); return image; } image_t make_filled_ellipse(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill_ellipse(rect, fill_color); return image; } image_t make_hollow_ellipse(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill_ellipse(rect, fill_color); image.fill_ellipse(make_interior_rect(rect), make_transparent_color()); return image; } image_t make_cross(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(make_vertical_interior_rect(rect), fill_color); image.fill(make_horizontal_interior_rect(rect), fill_color); return image; } } bool synthetic_shapes_task_t::load(const string_t &) { random_t<size_t> rng_protocol(1, 10); random_t<size_t> rng_output(1, osize()); random_t<scalar_t> rng_gauss(scalar_t(0.5), math::cast<scalar_t>(icols() + irows()) / scalar_t(8)); const coord_t rows = static_cast<coord_t>(irows()); const coord_t cols = static_cast<coord_t>(icols()); clear_memory(0); for (size_t f = 0; f < fsize(); f ++) { for (size_t i = 0; i < m_size; i ++) { // random protocol: train vs. test const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test; // random output class: #dots const size_t o = rng_output(); const bool is_dark_background = (rng_protocol() % 2) == 0; const rgba_t back_color = is_dark_background ? make_dark_color() : make_light_color(); const rgba_t shape_color = is_dark_background ? make_light_color() : make_dark_color(); // generate random image background image_t image(irows(), icols(), color()); image.fill(back_color); image.random_noise(color_channel::rgba, -25.0, +25.0, rng_gauss()); // generate random shapes image_t shape; switch (o) { case 1: shape = make_filled_rect(rows, cols, shape_color); break; case 2: shape = make_hollow_rect(rows, cols, shape_color); break; case 3: shape = make_filled_ellipse(rows, cols, shape_color); break; case 4: shape = make_hollow_ellipse(rows, cols, shape_color); break; case 5: shape = make_cross(rows, cols, shape_color); break; default: break; } shape.random_noise(color_channel::rgba, -25.0, +25.0, rng_gauss() * 0.5); image.alpha_blend(shape.rgba()); add_image(image); // generate sample sample_t sample(n_images() - 1, sample_region(0, 0)); switch (o) { case 1: sample.m_label = "filled_rectangle"; break; case 2: sample.m_label = "hollow_rectangle"; break; case 3: sample.m_label = "filled_ellipse"; break; case 4: sample.m_label = "hollow_ellipse"; break; case 5: sample.m_label = "cross"; break; default: sample.m_label = "unkown"; break; } sample.m_target = ncv::class_target(o - 1, osize()); sample.m_fold = {f, p}; add_sample(sample); } } return true; } } <commit_msg>more noise synthetic shapes<commit_after>#include "task_synthetic_shapes.h" #include "libnanocv/loss.h" #include "libnanocv/util/math.hpp" #include "libnanocv/util/random.hpp" namespace ncv { synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration) : task_t(configuration), m_rows(math::clamp(text::from_params<size_t>(configuration, "rows", 32), 16, 32)), m_cols(math::clamp(text::from_params<size_t>(configuration, "cols", 32), 16, 32)), m_outputs(math::clamp(text::from_params<size_t>(configuration, "dims", 4), 2, 16)), m_folds(1), m_color(text::from_params<color_mode>(configuration, "color", color_mode::rgba)), m_size(math::clamp(text::from_params<size_t>(configuration, "size", 1024), 256, 16 * 1024)) { } namespace { rgba_t make_transparent_color() { return 0; } rgba_t make_light_color() { random_t<rgba_t> rng_red(175, 255); random_t<rgba_t> rng_green(175, 255); random_t<rgba_t> rng_blue(175, 255); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rgba_t make_dark_color() { random_t<rgba_t> rng_red(0, 125); random_t<rgba_t> rng_green(0, 125); random_t<rgba_t> rng_blue(0, 125); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rect_t make_rect(coord_t rows, coord_t cols) { random_t<coord_t> rng(3, std::min(rows / 4, cols / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(dx, dy, cols - dx - dw, rows - dy - dh); } rect_t make_interior_rect(const rect_t& rect) { random_t<coord_t> rngx(4, rect.width() / 4); random_t<coord_t> rngy(4, rect.height() / 4); const coord_t dx = rngx(); const coord_t dy = rngy(); const coord_t dw = rngx(); const coord_t dh = rngy(); return rect_t(rect.left() + dx, rect.top() + dy, rect.width() - dx - dw, rect.height() - dy - dh); } rect_t make_vertical_interior_rect(const rect_t& rect) { const coord_t dx = (rect.width() + 2) / 3; const coord_t dy = 0; const coord_t dw = (rect.width() + 2) / 3; const coord_t dh = 0; return rect_t(rect.left() + dx, rect.top() + dy, rect.width() - dx - dw, rect.height() - dy - dh); } rect_t make_horizontal_interior_rect(const rect_t& rect) { const coord_t dx = 0; const coord_t dy = (rect.height() + 2) / 3; const coord_t dw = 0; const coord_t dh = (rect.height() + 2) / 3; return rect_t(rect.left() + dx, rect.top() + dy, rect.width() - dx - dw, rect.height() - dy - dh); } image_t make_filled_rect(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, fill_color); return image; } image_t make_hollow_rect(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, fill_color); image.fill(make_interior_rect(rect), make_transparent_color()); return image; } image_t make_filled_ellipse(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill_ellipse(rect, fill_color); return image; } image_t make_hollow_ellipse(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill_ellipse(rect, fill_color); image.fill_ellipse(make_interior_rect(rect), make_transparent_color()); return image; } image_t make_cross(coord_t rows, coord_t cols, rgba_t fill_color) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(make_vertical_interior_rect(rect), fill_color); image.fill(make_horizontal_interior_rect(rect), fill_color); return image; } } bool synthetic_shapes_task_t::load(const string_t &) { random_t<size_t> rng_protocol(1, 10); random_t<size_t> rng_output(1, osize()); random_t<scalar_t> rng_gauss(scalar_t(0.0), scalar_t(4.0)); const coord_t rows = static_cast<coord_t>(irows()); const coord_t cols = static_cast<coord_t>(icols()); clear_memory(0); for (size_t f = 0; f < fsize(); f ++) { for (size_t i = 0; i < m_size; i ++) { // random protocol: train vs. test const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test; // random output class: #dots const size_t o = rng_output(); const bool is_dark_background = (rng_protocol() % 2) == 0; const rgba_t back_color = is_dark_background ? make_dark_color() : make_light_color(); const rgba_t shape_color = is_dark_background ? make_light_color() : make_dark_color(); // generate random image background image_t image(irows(), icols(), color()); image.fill(back_color); image.random_noise(color_channel::rgba, -50.0, +50.0, rng_gauss()); // generate random shapes image_t shape; switch (o) { case 1: shape = make_filled_rect(rows, cols, shape_color); break; case 2: shape = make_hollow_rect(rows, cols, shape_color); break; case 3: shape = make_filled_ellipse(rows, cols, shape_color); break; case 4: shape = make_hollow_ellipse(rows, cols, shape_color); break; case 5: shape = make_cross(rows, cols, shape_color); break; default: break; } shape.random_noise(color_channel::rgba, -50.0, +50.0, rng_gauss() * 0.5); image.alpha_blend(shape.rgba()); add_image(image); // generate sample sample_t sample(n_images() - 1, sample_region(0, 0)); switch (o) { case 1: sample.m_label = "filled_rectangle"; break; case 2: sample.m_label = "hollow_rectangle"; break; case 3: sample.m_label = "filled_ellipse"; break; case 4: sample.m_label = "hollow_ellipse"; break; case 5: sample.m_label = "cross"; break; default: sample.m_label = "unkown"; break; } sample.m_target = ncv::class_target(o - 1, osize()); sample.m_fold = {f, p}; add_sample(sample); } } return true; } } <|endoftext|>
<commit_before>#include <QFileInfo> #include <QRegularExpression> #include "OutputParser.h" #include "ParseState.h" #include "TestModel.h" using namespace QtcGtest::Internal; namespace { const QRegularExpression gtestStartPattern ( QLatin1String ("^(.*)\\[==========\\] Running \\d+ tests? from \\d+ test cases?\\.\\s*$")); const QRegularExpression gtestEndPattern ( QLatin1String ("^(.*)\\[==========\\] (\\d+) tests? from (\\d+) test cases? ran. \\((\\d+) ms total\\)\\s*$")); const QRegularExpression newCasePattern ( QLatin1String ("^(.*)\\[\\-{10}\\] \\d+ tests? from ([\\w/]+)(, where TypeParam = (\\w+))?\\s*$")); const QRegularExpression endCasePattern ( QLatin1String ("^(.*)\\[\\-{10}\\] \\d+ tests? from ([\\w/]+) \\((\\d+) ms total\\)\\s*$")); const QRegularExpression beginTestPattern ( QLatin1String ("^(.*)\\[ RUN \\] ([\\w/]+)\\.([\\w/]+)\\s*$")); const QRegularExpression failTestPattern ( QLatin1String ("^(.*)\\[ FAILED \\] ([\\w/]+)\\.([\\w/]+) \\((\\d+) ms\\)\\s*$")); const QRegularExpression passTestPattern ( QLatin1String ("^(.*)\\[ OK \\] ([\\w/]+)\\.([\\w/]+) \\((\\d+) ms\\)\\s*$")); const QRegularExpression failDetailPattern ( QLatin1String ("^(.+):(\\d+): Failure\\s*$")); } OutputParser::OutputParser(QObject *parent) : QObject(parent) { } bool OutputParser::isGoogleTestRun(const QString &line) const { QRegularExpressionMatch match = gtestStartPattern.match (line); return (match.hasMatch ()); } void OutputParser::parseMessage(const QString &line, TestModel &model, ParseState &state) { QRegularExpressionMatch match; match = newCasePattern.match (line); if (match.hasMatch ()) { state.currentCase = match.captured (2); if (match.lastCapturedIndex() == 4) { state.currentCase += QString (QLatin1String(" <%1>")).arg (match.captured (4)); } state.passedCount = state.failedCount = 0; model.addCase (state.currentCase); return; } match = endCasePattern.match (line); if (match.hasMatch ()) { int totalTime = match.captured (3).toInt (); model.updateCase (state.currentCase, state.passedCount, state.failedCount, totalTime); state.currentCase.clear (); state.currentTest.clear (); return; } match = beginTestPattern.match (line); if (match.hasMatch ()) { state.currentTest = match.captured (3); model.addTest (state.currentTest, state.currentCase); return; } match = passTestPattern.match (line); if (match.hasMatch ()) { QString unrelated = match.captured(1); if (!unrelated.isEmpty()) { model.addTestDetail (state.currentTest, state.currentCase, unrelated); } ++state.passedCount; ++state.passedTotalCount; int totalTime = match.captured (4).toInt (); model.updateTest (state.currentTest, state.currentCase, true, totalTime); state.currentTest.clear (); return; } match = failTestPattern.match (line); if (match.hasMatch ()) { QString unrelated = match.captured(1); if (!unrelated.isEmpty()) { model.addTestDetail (state.currentTest, state.currentCase, unrelated); } ++state.failedCount; ++state.failedTotalCount; int totalTime = match.captured (4).toInt (); model.updateTest (state.currentTest, state.currentCase, false, totalTime); state.currentTest.clear (); return; } match = failDetailPattern.match (line); if (match.hasMatch ()) { Q_ASSERT (!state.projectPath.isEmpty ()); QString file = match.captured (2); QFileInfo info (file); if (info.isRelative ()) { file = state.projectPath + QLatin1Char ('/') + match.captured (2); } int lineNumber = match.captured (3).toInt (); model.addTestError (state.currentTest, state.currentCase, line, file, lineNumber); return; } match = gtestEndPattern.match (line); if (match.hasMatch ()) { state.totalTime = match.captured (3).toInt (); return; } if (!state.currentTest.isEmpty ()) { Q_ASSERT (!state.currentCase.isEmpty ()); model.addTestDetail (state.currentTest, state.currentCase, line); } } <commit_msg>Use enums instead of hardcoded numbers.<commit_after>#include <QFileInfo> #include <QRegularExpression> #include "OutputParser.h" #include "ParseState.h" #include "TestModel.h" using namespace QtcGtest::Internal; namespace { const QRegularExpression gtestStartPattern ( QLatin1String ("^(.*)\\[==========\\] Running \\d+ tests? from \\d+ test cases?\\.\\s*$")); enum GtestStart {GtestStartUnrelated = 1}; const QRegularExpression gtestEndPattern ( QLatin1String ("^(.*)\\[==========\\] (\\d+) tests? from (\\d+) test cases? ran. \\((\\d+) ms total\\)\\s*$")); enum GtestEnd{GtestEndUnrelated = 1, GtestEndTestsRun, GtestEndCasesRun, GtestEndTimeSpent}; const QRegularExpression newCasePattern ( QLatin1String ("^(.*)\\[\\-{10}\\] \\d+ tests? from ([\\w/]+)(, where TypeParam = (\\w+))?\\s*$")); enum NewCase{NewCaseUnrelated = 1, NewCaseName, NewCaseFullParameter, NewCaseParameterType}; const QRegularExpression endCasePattern ( QLatin1String ("^(.*)\\[\\-{10}\\] \\d+ tests? from ([\\w/]+) \\((\\d+) ms total\\)\\s*$")); enum EndCase{EndCaseUnrelated = 1, EndCaseName, EndCaseTimeSpent}; const QRegularExpression beginTestPattern ( QLatin1String ("^(.*)\\[ RUN \\] ([\\w/]+)\\.([\\w/]+)\\s*$")); enum NewTest{NewTestUnrelated = 1, NewTestCaseName, NewTestName}; const QRegularExpression failTestPattern ( QLatin1String ("^(.*)\\[ FAILED \\] ([\\w/]+)\\.([\\w/]+) \\((\\d+) ms\\)\\s*$")); enum FailTest{FailTestUnrelated = 1, FailTestCaseName, FailTestName, FailTestTimeSpent}; const QRegularExpression passTestPattern ( QLatin1String ("^(.*)\\[ OK \\] ([\\w/]+)\\.([\\w/]+) \\((\\d+) ms\\)\\s*$")); enum PassTest{PassTestUnrelated = 1, PassTestCaseName, PassTestName, PassTestTimeSpent}; const QRegularExpression failDetailPattern ( QLatin1String ("^(.+):(\\d+): Failure\\s*$")); enum FailDetail{FailDetailFileName = 1, FailDetailLine}; } OutputParser::OutputParser(QObject *parent) : QObject(parent) { } bool OutputParser::isGoogleTestRun(const QString &line) const { QRegularExpressionMatch match = gtestStartPattern.match (line); return (match.hasMatch ()); } void OutputParser::parseMessage(const QString &line, TestModel &model, ParseState &state) { QRegularExpressionMatch match; match = newCasePattern.match (line); if (match.hasMatch ()) { state.currentCase = match.captured (NewCaseName); if (match.lastCapturedIndex() == NewCaseParameterType) { state.currentCase += QString (QLatin1String(" <%1>")).arg (match.captured (NewCaseParameterType)); } state.passedCount = state.failedCount = 0; model.addCase (state.currentCase); return; } match = endCasePattern.match (line); if (match.hasMatch ()) { int totalTime = match.captured (EndCaseTimeSpent).toInt (); model.updateCase (state.currentCase, state.passedCount, state.failedCount, totalTime); state.currentCase.clear (); state.currentTest.clear (); return; } match = beginTestPattern.match (line); if (match.hasMatch ()) { state.currentTest = match.captured (NewTestName); model.addTest (state.currentTest, state.currentCase); return; } match = passTestPattern.match (line); if (match.hasMatch ()) { QString unrelated = match.captured(PassTestUnrelated); if (!unrelated.isEmpty()) { model.addTestDetail (state.currentTest, state.currentCase, unrelated); } ++state.passedCount; ++state.passedTotalCount; int totalTime = match.captured (PassTestTimeSpent).toInt (); model.updateTest (state.currentTest, state.currentCase, true, totalTime); state.currentTest.clear (); return; } match = failTestPattern.match (line); if (match.hasMatch ()) { QString unrelated = match.captured(PassTestUnrelated); if (!unrelated.isEmpty()) { model.addTestDetail (state.currentTest, state.currentCase, unrelated); } ++state.failedCount; ++state.failedTotalCount; int totalTime = match.captured (FailTestTimeSpent).toInt (); model.updateTest (state.currentTest, state.currentCase, false, totalTime); state.currentTest.clear (); return; } match = failDetailPattern.match (line); if (match.hasMatch ()) { Q_ASSERT (!state.projectPath.isEmpty ()); QString file = match.captured (FailDetailFileName); QFileInfo info (file); if (info.isRelative ()) { file = state.projectPath + QLatin1Char ('/') + match.captured (FailDetailFileName); } int lineNumber = match.captured (FailDetailLine).toInt (); model.addTestError (state.currentTest, state.currentCase, line, file, lineNumber); return; } match = gtestEndPattern.match (line); if (match.hasMatch ()) { state.totalTime = match.captured (GtestEndTimeSpent).toInt (); return; } if (!state.currentTest.isEmpty ()) { Q_ASSERT (!state.currentCase.isEmpty ()); model.addTestDetail (state.currentTest, state.currentCase, line); } } <|endoftext|>
<commit_before>#include "oh/Platform.hpp" #include "oh/SpaceConnection.hpp" #include "oh/HostedObject.hpp" #include "oh/SpaceTimeOffsetManager.hpp" #include "MonoDefs.hpp" #include "MonoDomain.hpp" #include "MonoContext.hpp" #include "MonoObject.hpp" #include "MonoDelegate.hpp" #include "MonoArray.hpp" #include "MonoException.hpp" #include "util/SentMessage.hpp" using namespace Sirikata; using namespace Mono; static MonoObject* Mono_Context_CurrentUUID() { UUID uuid = MonoContext::getSingleton().getUUID(); Mono::Object obj = MonoContext::getSingleton().getDomain().UUID(uuid); return obj.object(); } /* static MonoObject* Mono_Context_CurrentObject() { Mono::Object obj = Mono::Domain::root().UUID(MonoContext::getSingleton().getVWObject()); return obj.object(); } static MonoObject* Mono_Context_CallFunction(MonoObject*callback) { Mono::Object obj = Mono::Domain::root().UUID(MonoContext::getSingleton().getVWObject()); return obj.object(); } */ static void Mono_Context_CallFunctionCallback(const std::tr1::weak_ptr<HostedObject>&weak_ho, const Mono::Domain &domain, const Mono::Delegate &callback, SentMessage*sentMessage, const RoutableMessageHeader&responseHeader, MemoryReference responseBody) { std::tr1::shared_ptr<HostedObject>ho(weak_ho); bool keepquery = false; if (ho) { MonoContext::getSingleton().push(MonoContextData()); MonoContext::getSingleton().setVWObject(&*ho,domain); String header; responseHeader.SerializeToString(&header); try { Object ret = callback.invoke(MonoContext::getSingleton().getDomain().ByteArray(header.data(), header.size()), MonoContext::getSingleton().getDomain().ByteArray(responseBody.data(), responseBody.size())); if (!ret.null()) { keepquery = ret.unboxBoolean(); } }catch (Mono::Exception&e) { SILOG(mono,debug,"Callback raised exception: "<<e); keepquery = false; } MonoContext::getSingleton().pop(); } if (!keepquery) { delete sentMessage; } } static MonoObject* InternalMono_Context_CallFunction(MonoObject *message, MonoObject*callback, const Duration&duration){ std::tr1::shared_ptr<HostedObject> ho=MonoContext::getSingleton().getVWObject(); MemoryBuffer buf; using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; using std::tr1::placeholders::_3; Mono::Array(message).unboxInPlaceByteArray(buf); if (ho&&!buf.empty()) { RoutableMessageHeader hdr; MemoryReference body=hdr.ParseFromArray(&buf[0],buf.size()); SentMessage*sm=hdr.has_id() ? new SentMessage(hdr.id(),ho->getTracker(),std::tr1::bind(&Mono_Context_CallFunctionCallback, ho->getWeakPtr(), MonoContext::getSingleton().getDomain(), Mono::Delegate(Mono::Object(callback)), _1,_2,_3)) :new SentMessage(ho->getTracker(),std::tr1::bind(&Mono_Context_CallFunctionCallback, ho->getWeakPtr(), MonoContext::getSingleton().getDomain(), Mono::Delegate(Mono::Object(callback)), _1,_2,_3)); sm->setTimeout(duration); sm->header()=hdr; sm->send(body); }else { return MonoContext::getSingleton().getDomain().Boolean(false).object(); } return MonoContext::getSingleton().getDomain().Boolean(true).object(); } static MonoObject* Mono_Context_CallFunctionWithTimeout(MonoObject *message, MonoObject*callback, MonoObject*duration){ return InternalMono_Context_CallFunction(message,callback,Mono::Object(duration).unboxTime()-Time::epoch()); } static MonoObject* Mono_Context_CallFunction(MonoObject *message, MonoObject*callback){ return InternalMono_Context_CallFunction(message,callback,Duration::seconds(4.0)); } static MonoObject* Mono_Context_SendMessage(MonoObject *message){ std::tr1::shared_ptr<HostedObject> ho=MonoContext::getSingleton().getVWObject(); MemoryBuffer buf; Mono::Array(message).unboxInPlaceByteArray(buf); if (ho&&!buf.empty()) { RoutableMessageHeader hdr; MemoryReference body=hdr.ParseFromArray(&buf[0],buf.size()); ho->send(hdr,body); }else { return MonoContext::getSingleton().getDomain().Boolean(false).object(); } return MonoContext::getSingleton().getDomain().Boolean(true).object(); } static void Mono_Context_TickDelay(MonoObject*duration) { std::tr1::shared_ptr<HostedObject> ho=MonoContext::getSingleton().getVWObject(); if (ho) { Duration period(Mono::Object(duration).unboxTime()-Time::epoch()); NOT_IMPLEMENTED(mono); //ho->tickDelay(period) } } void Mono_Context_setTime(MonoObject *timeRetval, const Time& cur) { uint64 curRaw=cur.raw(); Mono::Object retval(timeRetval); uint32 curLowerLower=curRaw%65536; uint32 curLowerUpper=(curRaw/65536)%65536; uint32 curLower=curLowerLower+curLowerUpper*65536; curRaw/=65536; curRaw/=65536; uint32 curUpper=curRaw; retval.send("setLowerUpper", MonoContext::getSingleton().getDomain().UInt32(curLower), MonoContext::getSingleton().getDomain().UInt32(curUpper)); } static void Mono_Context_GetTime(MonoObject*space_id,MonoObject *timeRetval) { SpaceID sid=SpaceID(Mono::Object(space_id).unboxUUID()); Time cur=SpaceTimeOffsetManager::getSingleton().now(sid); Mono_Context_setTime(timeRetval,cur); } static void Mono_Context_GetLocalTime(MonoObject *timeRetval) { Time cur=Time::now(Duration::zero()); //SILOG(monoscript,warning,"Time should be "<<cur.raw()); Mono_Context_setTime(timeRetval,cur); } static void Mono_Context_GetTimeByteArray(MonoObject*space_id,MonoObject *timeRetval) { MemoryBuffer buf; Mono::Array(space_id).unboxInPlaceByteArray(buf); if (buf.size()==16) { SpaceID sid=SpaceID(*Sirikata::Array<unsigned char, 16,true>().memcpy(&buf[0],buf.size())); Time cur= SpaceTimeOffsetManager::getSingleton().now(sid); //SILOG(monoscript,warning,"Time should be "<<cur.raw()); Mono_Context_setTime(timeRetval,cur); }else { Mono_Context_GetLocalTime(timeRetval); } } static void Mono_Context_GetTimeString(MonoObject*space_id, MonoObject* timeRetval) { std::string ss=Mono::Object(space_id).unboxString(); try { SpaceID sid=SpaceID(UUID(ss,UUID::HumanReadable())); Time cur = SpaceTimeOffsetManager::getSingleton().now(sid); Mono_Context_setTime(timeRetval,cur); }catch (std::invalid_argument&){ Mono_Context_GetLocalTime(timeRetval); } } namespace Sirikata { void InitHostedObjectExports () { mono_add_internal_call ("Sirikata.Runtime.HostedObject::GetUUID", (void*)Mono_Context_CurrentUUID); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iSendMessage", (void*)Mono_Context_SendMessage); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iCallFunction", (void*)Mono_Context_CallFunction); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iCallFunctionWithTimeout", (void*)Mono_Context_CallFunction); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iTickPeriod", (void*)Mono_Context_TickDelay); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iGetTime", (void*)Mono_Context_GetTime); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iGetTimeByteArray", (void*)Mono_Context_GetTimeByteArray); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iGetTimeString", (void*)Mono_Context_GetTimeString); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iGetLocalTime", (void*)Mono_Context_GetLocalTime); } } <commit_msg>apparently macs do not know what 'using' means<commit_after>#include "oh/Platform.hpp" #include "oh/SpaceConnection.hpp" #include "oh/HostedObject.hpp" #include "oh/SpaceTimeOffsetManager.hpp" #include "MonoDefs.hpp" #include "MonoDomain.hpp" #include "MonoContext.hpp" #include "MonoObject.hpp" #include "MonoDelegate.hpp" #include "MonoArray.hpp" #include "MonoException.hpp" #include "util/SentMessage.hpp" using namespace Sirikata; using namespace Mono; static MonoObject* Mono_Context_CurrentUUID() { UUID uuid = MonoContext::getSingleton().getUUID(); Mono::Object obj = MonoContext::getSingleton().getDomain().UUID(uuid); return obj.object(); } /* static MonoObject* Mono_Context_CurrentObject() { Mono::Object obj = Mono::Domain::root().UUID(MonoContext::getSingleton().getVWObject()); return obj.object(); } static MonoObject* Mono_Context_CallFunction(MonoObject*callback) { Mono::Object obj = Mono::Domain::root().UUID(MonoContext::getSingleton().getVWObject()); return obj.object(); } */ static void Mono_Context_CallFunctionCallback(const std::tr1::weak_ptr<HostedObject>&weak_ho, const Mono::Domain &domain, const Mono::Delegate &callback, SentMessage*sentMessage, const RoutableMessageHeader&responseHeader, MemoryReference responseBody) { std::tr1::shared_ptr<HostedObject>ho(weak_ho); bool keepquery = false; if (ho) { MonoContext::getSingleton().push(MonoContextData()); MonoContext::getSingleton().setVWObject(&*ho,domain); String header; responseHeader.SerializeToString(&header); try { Object ret = callback.invoke(MonoContext::getSingleton().getDomain().ByteArray(header.data(), header.size()), MonoContext::getSingleton().getDomain().ByteArray(responseBody.data(), responseBody.size())); if (!ret.null()) { keepquery = ret.unboxBoolean(); } }catch (Mono::Exception&e) { SILOG(mono,debug,"Callback raised exception: "<<e); keepquery = false; } MonoContext::getSingleton().pop(); } if (!keepquery) { delete sentMessage; } } static MonoObject* InternalMono_Context_CallFunction(MonoObject *message, MonoObject*callback, const Sirikata::Duration&duration){ std::tr1::shared_ptr<HostedObject> ho=MonoContext::getSingleton().getVWObject(); MemoryBuffer buf; using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; using std::tr1::placeholders::_3; Mono::Array(message).unboxInPlaceByteArray(buf); if (ho&&!buf.empty()) { RoutableMessageHeader hdr; MemoryReference body=hdr.ParseFromArray(&buf[0],buf.size()); SentMessage*sm=hdr.has_id() ? new SentMessage(hdr.id(),ho->getTracker(),std::tr1::bind(&Mono_Context_CallFunctionCallback, ho->getWeakPtr(), MonoContext::getSingleton().getDomain(), Mono::Delegate(Mono::Object(callback)), _1,_2,_3)) :new SentMessage(ho->getTracker(),std::tr1::bind(&Mono_Context_CallFunctionCallback, ho->getWeakPtr(), MonoContext::getSingleton().getDomain(), Mono::Delegate(Mono::Object(callback)), _1,_2,_3)); sm->setTimeout(duration); sm->header()=hdr; sm->send(body); }else { return MonoContext::getSingleton().getDomain().Boolean(false).object(); } return MonoContext::getSingleton().getDomain().Boolean(true).object(); } static MonoObject* Mono_Context_CallFunctionWithTimeout(MonoObject *message, MonoObject*callback, MonoObject*duration){ return InternalMono_Context_CallFunction(message,callback,Mono::Object(duration).unboxTime()-Time::epoch()); } static MonoObject* Mono_Context_CallFunction(MonoObject *message, MonoObject*callback){ return InternalMono_Context_CallFunction(message,callback,Sirikata::Duration::seconds(4.0)); } static MonoObject* Mono_Context_SendMessage(MonoObject *message){ std::tr1::shared_ptr<HostedObject> ho=MonoContext::getSingleton().getVWObject(); MemoryBuffer buf; Mono::Array(message).unboxInPlaceByteArray(buf); if (ho&&!buf.empty()) { RoutableMessageHeader hdr; MemoryReference body=hdr.ParseFromArray(&buf[0],buf.size()); ho->send(hdr,body); }else { return MonoContext::getSingleton().getDomain().Boolean(false).object(); } return MonoContext::getSingleton().getDomain().Boolean(true).object(); } static void Mono_Context_TickDelay(MonoObject*duration) { std::tr1::shared_ptr<HostedObject> ho=MonoContext::getSingleton().getVWObject(); if (ho) { Sirikata::Duration period(Mono::Object(duration).unboxTime()-Time::epoch()); NOT_IMPLEMENTED(mono); //ho->tickDelay(period) } } void Mono_Context_setTime(MonoObject *timeRetval, const Time& cur) { uint64 curRaw=cur.raw(); Mono::Object retval(timeRetval); uint32 curLowerLower=curRaw%65536; uint32 curLowerUpper=(curRaw/65536)%65536; uint32 curLower=curLowerLower+curLowerUpper*65536; curRaw/=65536; curRaw/=65536; uint32 curUpper=curRaw; retval.send("setLowerUpper", MonoContext::getSingleton().getDomain().UInt32(curLower), MonoContext::getSingleton().getDomain().UInt32(curUpper)); } static void Mono_Context_GetTime(MonoObject*space_id,MonoObject *timeRetval) { SpaceID sid=SpaceID(Mono::Object(space_id).unboxUUID()); Time cur=SpaceTimeOffsetManager::getSingleton().now(sid); Mono_Context_setTime(timeRetval,cur); } static void Mono_Context_GetLocalTime(MonoObject *timeRetval) { Time cur=Time::now(Sirikata::Duration::zero()); //SILOG(monoscript,warning,"Time should be "<<cur.raw()); Mono_Context_setTime(timeRetval,cur); } static void Mono_Context_GetTimeByteArray(MonoObject*space_id,MonoObject *timeRetval) { MemoryBuffer buf; Mono::Array(space_id).unboxInPlaceByteArray(buf); if (buf.size()==16) { SpaceID sid=SpaceID(*Sirikata::Array<unsigned char, 16,true>().memcpy(&buf[0],buf.size())); Time cur= SpaceTimeOffsetManager::getSingleton().now(sid); //SILOG(monoscript,warning,"Time should be "<<cur.raw()); Mono_Context_setTime(timeRetval,cur); }else { Mono_Context_GetLocalTime(timeRetval); } } static void Mono_Context_GetTimeString(MonoObject*space_id, MonoObject* timeRetval) { std::string ss=Mono::Object(space_id).unboxString(); try { SpaceID sid=SpaceID(UUID(ss,UUID::HumanReadable())); Time cur = SpaceTimeOffsetManager::getSingleton().now(sid); Mono_Context_setTime(timeRetval,cur); }catch (std::invalid_argument&){ Mono_Context_GetLocalTime(timeRetval); } } namespace Sirikata { void InitHostedObjectExports () { mono_add_internal_call ("Sirikata.Runtime.HostedObject::GetUUID", (void*)Mono_Context_CurrentUUID); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iSendMessage", (void*)Mono_Context_SendMessage); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iCallFunction", (void*)Mono_Context_CallFunction); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iCallFunctionWithTimeout", (void*)Mono_Context_CallFunction); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iTickPeriod", (void*)Mono_Context_TickDelay); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iGetTime", (void*)Mono_Context_GetTime); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iGetTimeByteArray", (void*)Mono_Context_GetTimeByteArray); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iGetTimeString", (void*)Mono_Context_GetTimeString); mono_add_internal_call ("Sirikata.Runtime.HostedObject::iGetLocalTime", (void*)Mono_Context_GetLocalTime); } } <|endoftext|>
<commit_before>#include "../../render_objects/renderables.hpp" #include "fmt/format.h" #include "vulkan_render_engine.hpp" namespace nova::renderer { void vulkan_render_engine::create_builtin_uniform_buffers() { // TODO: move this to the settings const uint32_t static_object_estimate = 5000; VkBufferCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.size = static_object_estimate * sizeof(glm::mat4); info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; const uint32_t alignment = static_cast<uint32_t>(gpu.props.limits.minUniformBufferOffsetAlignment); static_model_matrix_buffer = std::make_unique<auto_buffer>("NovaStaticModelUBO", vma_allocator, info, alignment, false); } result<renderable_id_t> vulkan_render_engine::add_renderable(const static_mesh_renderable_data& data) { return get_material_passes_for_renderable(data).map([&](const std::vector<const material_pass*>& passes) { return get_mesh_for_renderable(data).map( std::bind(&vulkan_render_engine::register_renderable, this, std::placeholders::_1, passes)); }); } result<std::vector<const material_pass*>> vulkan_render_engine::get_material_passes_for_renderable( const static_mesh_renderable_data& data) { std::vector<const material_pass*> passes; for(const auto& [pipeline_name, materials] : material_passes_by_pipeline) { static_cast<void>(pipeline_name); for(const material_pass& pass : materials) { if(pass.material_name == data.material_name) { passes.push_back(&pass); } } } if(passes.empty()) { return result<std::vector<const material_pass*>>( nova_error(fmt::format(fmt("Could not find material {:s}"), data.material_name))); } else { return result<std::vector<const material_pass*>>(std::move(passes)); } } result<const vk_mesh*> vulkan_render_engine::get_mesh_for_renderable(const static_mesh_renderable_data& data) { if(meshes.find(data.mesh) == meshes.end()) { return result<const vk_mesh*>(nova_error(fmt::format(fmt("Could not find mesh with id {:d}"), data.mesh))); } return result<const vk_mesh*>(&meshes.at(data.mesh)); } result<renderable_id_t> vulkan_render_engine::register_renderable(const vk_mesh* mesh, const std::vector<const material_pass*>& passes) { renderable_metadata meta = {}; meta.passes.reserve(meshes.size()); for(const material_pass* m : passes) { meta.passes.push_back(m->name); } meta.buffer = mesh->memory->block->get_buffer(); // Set all the renderable's data vk_static_mesh_renderable renderable = {}; renderable.draw_cmd = &mesh->draw_cmd; // Generate the renderable ID and store the renderable renderable_id_t id = RENDERABLE_ID.fetch_add(1); renderable.id = id; static_mesh_renderables[id] = renderable; metadata_for_renderables[id] = meta; // Find the materials basses that this renderable belongs to, put it in the appropriate maps for(const material_pass* pass : passes) { renderables_by_material[pass->name][mesh->memory->block->get_buffer()].push_back(id); } return result<renderable_id_t>(std::move(id)); } void vulkan_render_engine::set_renderable_visibility(const renderable_id_t id, const bool is_visible) { const renderable_metadata& meta = metadata_for_renderables.at(id); for(const std::string& pass : meta.passes) { renderables_by_material.at[pass][meta.buffer].is_visible = is_visible; } } void vulkan_render_engine::delete_renderable(renderable_id_t id) { static_cast<void>(id); } } // namespace nova::renderer<commit_msg>Implement it for real<commit_after>#include "../../render_objects/renderables.hpp" #include "fmt/format.h" #include "vulkan_render_engine.hpp" namespace nova::renderer { void vulkan_render_engine::create_builtin_uniform_buffers() { // TODO: move this to the settings const uint32_t static_object_estimate = 5000; VkBufferCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.size = static_object_estimate * sizeof(glm::mat4); info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; const uint32_t alignment = static_cast<uint32_t>(gpu.props.limits.minUniformBufferOffsetAlignment); static_model_matrix_buffer = std::make_unique<auto_buffer>("NovaStaticModelUBO", vma_allocator, info, alignment, false); } result<renderable_id_t> vulkan_render_engine::add_renderable(const static_mesh_renderable_data& data) { return get_material_passes_for_renderable(data).map([&](const std::vector<const material_pass*>& passes) { return get_mesh_for_renderable(data).map( std::bind(&vulkan_render_engine::register_renderable, this, std::placeholders::_1, passes)); }); } result<std::vector<const material_pass*>> vulkan_render_engine::get_material_passes_for_renderable( const static_mesh_renderable_data& data) { std::vector<const material_pass*> passes; for(const auto& [pipeline_name, materials] : material_passes_by_pipeline) { static_cast<void>(pipeline_name); for(const material_pass& pass : materials) { if(pass.material_name == data.material_name) { passes.push_back(&pass); } } } if(passes.empty()) { return result<std::vector<const material_pass*>>( nova_error(fmt::format(fmt("Could not find material {:s}"), data.material_name))); } else { return result<std::vector<const material_pass*>>(std::move(passes)); } } result<const vk_mesh*> vulkan_render_engine::get_mesh_for_renderable(const static_mesh_renderable_data& data) { if(meshes.find(data.mesh) == meshes.end()) { return result<const vk_mesh*>(nova_error(fmt::format(fmt("Could not find mesh with id {:d}"), data.mesh))); } return result<const vk_mesh*>(&meshes.at(data.mesh)); } result<renderable_id_t> vulkan_render_engine::register_renderable(const vk_mesh* mesh, const std::vector<const material_pass*>& passes) { renderable_metadata meta = {}; meta.passes.reserve(meshes.size()); for(const material_pass* m : passes) { meta.passes.push_back(m->name); } meta.buffer = mesh->memory->block->get_buffer(); // Set all the renderable's data vk_static_mesh_renderable renderable = {}; renderable.draw_cmd = &mesh->draw_cmd; // Generate the renderable ID and store the renderable renderable_id_t id = RENDERABLE_ID.fetch_add(1); renderable.id = id; static_mesh_renderables[id] = renderable; metadata_for_renderables[id] = meta; // Find the materials basses that this renderable belongs to, put it in the appropriate maps for(const material_pass* pass : passes) { renderables_by_material[pass->name][mesh->memory->block->get_buffer()].push_back(id); } return result<renderable_id_t>(std::move(id)); } void vulkan_render_engine::set_renderable_visibility(const renderable_id_t id, const bool is_visible) { if(static_mesh_renderables.find(id) != static_mesh_renderables.end()) { static_mesh_renderables[id].is_visible = is_visible; } // TODO: Try other types of renderables } void vulkan_render_engine::delete_renderable(renderable_id_t id) { static_cast<void>(id); } } // namespace nova::renderer<|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2006-2008 Benoit Jacob <[email protected]> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #define EIGEN_NO_STATIC_ASSERT #include "main.h" template<typename MatrixType> void basicStuff(const MatrixType& m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType; Index rows = m.rows(); Index cols = m.cols(); // this test relies a lot on Random.h, and there's not much more that we can do // to test it, hence I consider that we will have tested Random.h MatrixType m1 = MatrixType::Random(rows, cols), m2 = MatrixType::Random(rows, cols), m3(rows, cols), mzero = MatrixType::Zero(rows, cols), identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> ::Identity(rows, rows), square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows); VectorType v1 = VectorType::Random(rows), v2 = VectorType::Random(rows), vzero = VectorType::Zero(rows); SquareMatrixType sm1 = SquareMatrixType::Random(rows,rows), sm2(rows,rows); Scalar x = internal::random<Scalar>(); Index r = internal::random<Index>(0, rows-1), c = internal::random<Index>(0, cols-1); m1.coeffRef(r,c) = x; VERIFY_IS_APPROX(x, m1.coeff(r,c)); m1(r,c) = x; VERIFY_IS_APPROX(x, m1(r,c)); v1.coeffRef(r) = x; VERIFY_IS_APPROX(x, v1.coeff(r)); v1(r) = x; VERIFY_IS_APPROX(x, v1(r)); v1[r] = x; VERIFY_IS_APPROX(x, v1[r]); VERIFY_IS_APPROX( v1, v1); VERIFY_IS_NOT_APPROX( v1, 2*v1); VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1); if(!NumTraits<Scalar>::IsInteger) VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.norm()); VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1); VERIFY_IS_APPROX( vzero, v1-v1); VERIFY_IS_APPROX( m1, m1); VERIFY_IS_NOT_APPROX( m1, 2*m1); VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1); VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1); VERIFY_IS_APPROX( mzero, m1-m1); // always test operator() on each read-only expression class, // in order to check const-qualifiers. // indeed, if an expression class (here Zero) is meant to be read-only, // hence has no _write() method, the corresponding MatrixBase method (here zero()) // should return a const-qualified object so that it is the const-qualified // operator() that gets called, which in turn calls _read(). VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1)); // now test copying a row-vector into a (column-)vector and conversely. square.col(r) = square.row(r).eval(); Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows); Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows); rv = square.row(r); cv = square.col(r); VERIFY_IS_APPROX(rv, cv.transpose()); if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic) { VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1))); } if(cols!=1 && rows!=1) { VERIFY_RAISES_ASSERT(m1[0]); VERIFY_RAISES_ASSERT((m1+m1)[0]); } VERIFY_IS_APPROX(m3 = m1,m1); MatrixType m4; VERIFY_IS_APPROX(m4 = m1,m1); m3.real() = m1.real(); VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real()); VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real()); // check == / != operators VERIFY(m1==m1); VERIFY(m1!=m2); VERIFY(!(m1==m2)); VERIFY(!(m1!=m1)); m1 = m2; VERIFY(m1==m2); VERIFY(!(m1!=m2)); // check automatic transposition sm2.setZero(); for(typename MatrixType::Index i=0;i<rows;++i) sm2.col(i) = sm1.row(i); VERIFY_IS_APPROX(sm2,sm1.transpose()); sm2.setZero(); for(typename MatrixType::Index i=0;i<rows;++i) sm2.col(i).noalias() = sm1.row(i); VERIFY_IS_APPROX(sm2,sm1.transpose()); sm2.setZero(); for(typename MatrixType::Index i=0;i<rows;++i) sm2.col(i).noalias() += sm1.row(i); VERIFY_IS_APPROX(sm2,sm1.transpose()); sm2.setZero(); for(typename MatrixType::Index i=0;i<rows;++i) sm2.col(i).noalias() -= sm1.row(i); VERIFY_IS_APPROX(sm2,-sm1.transpose()); } template<typename MatrixType> void basicStuffComplex(const MatrixType& m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> RealMatrixType; Index rows = m.rows(); Index cols = m.cols(); Scalar s1 = internal::random<Scalar>(), s2 = internal::random<Scalar>(); VERIFY(internal::real(s1)==internal::real_ref(s1)); VERIFY(internal::imag(s1)==internal::imag_ref(s1)); internal::real_ref(s1) = internal::real(s2); internal::imag_ref(s1) = internal::imag(s2); VERIFY(internal::isApprox(s1, s2, NumTraits<RealScalar>::epsilon())); // extended precision in Intel FPUs means that s1 == s2 in the line above is not guaranteed. RealMatrixType rm1 = RealMatrixType::Random(rows,cols), rm2 = RealMatrixType::Random(rows,cols); MatrixType cm(rows,cols); cm.real() = rm1; cm.imag() = rm2; VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1); VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2); rm1.setZero(); rm2.setZero(); rm1 = cm.real(); rm2 = cm.imag(); VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1); VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2); cm.real().setZero(); VERIFY(static_cast<const MatrixType&>(cm).real().isZero()); VERIFY(!static_cast<const MatrixType&>(cm).imag().isZero()); } #ifdef EIGEN_TEST_PART_2 void casting() { Matrix4f m = Matrix4f::Random(), m2; Matrix4d n = m.cast<double>(); VERIFY(m.isApprox(n.cast<float>())); m2 = m.cast<float>(); // check the specialization when NewType == Type VERIFY(m.isApprox(m2)); } #endif void test_basicstuff() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( basicStuff(Matrix<float, 1, 1>()) ); CALL_SUBTEST_2( basicStuff(Matrix4d()) ); CALL_SUBTEST_3( basicStuff(MatrixXcf(internal::random<int>(1,100), internal::random<int>(1,100))) ); CALL_SUBTEST_4( basicStuff(MatrixXi(internal::random<int>(1,100), internal::random<int>(1,100))) ); CALL_SUBTEST_5( basicStuff(MatrixXcd(internal::random<int>(1,100), internal::random<int>(1,100))) ); CALL_SUBTEST_6( basicStuff(Matrix<float, 100, 100>()) ); CALL_SUBTEST_7( basicStuff(Matrix<long double,Dynamic,Dynamic>(internal::random<int>(1,100),internal::random<int>(1,100))) ); CALL_SUBTEST_3( basicStuffComplex(MatrixXcf(internal::random<int>(1,100), internal::random<int>(1,100))) ); CALL_SUBTEST_5( basicStuffComplex(MatrixXcd(internal::random<int>(1,100), internal::random<int>(1,100))) ); } CALL_SUBTEST_2(casting()); } <commit_msg>Added unit test for matrix creation from const raw data.<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2006-2008 Benoit Jacob <[email protected]> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #define EIGEN_NO_STATIC_ASSERT #include "main.h" template<typename MatrixType> void basicStuff(const MatrixType& m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType; Index rows = m.rows(); Index cols = m.cols(); // this test relies a lot on Random.h, and there's not much more that we can do // to test it, hence I consider that we will have tested Random.h MatrixType m1 = MatrixType::Random(rows, cols), m2 = MatrixType::Random(rows, cols), m3(rows, cols), mzero = MatrixType::Zero(rows, cols), identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> ::Identity(rows, rows), square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows); VectorType v1 = VectorType::Random(rows), v2 = VectorType::Random(rows), vzero = VectorType::Zero(rows); SquareMatrixType sm1 = SquareMatrixType::Random(rows,rows), sm2(rows,rows); Scalar x = internal::random<Scalar>(); Index r = internal::random<Index>(0, rows-1), c = internal::random<Index>(0, cols-1); m1.coeffRef(r,c) = x; VERIFY_IS_APPROX(x, m1.coeff(r,c)); m1(r,c) = x; VERIFY_IS_APPROX(x, m1(r,c)); v1.coeffRef(r) = x; VERIFY_IS_APPROX(x, v1.coeff(r)); v1(r) = x; VERIFY_IS_APPROX(x, v1(r)); v1[r] = x; VERIFY_IS_APPROX(x, v1[r]); VERIFY_IS_APPROX( v1, v1); VERIFY_IS_NOT_APPROX( v1, 2*v1); VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1); if(!NumTraits<Scalar>::IsInteger) VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.norm()); VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1); VERIFY_IS_APPROX( vzero, v1-v1); VERIFY_IS_APPROX( m1, m1); VERIFY_IS_NOT_APPROX( m1, 2*m1); VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1); VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1); VERIFY_IS_APPROX( mzero, m1-m1); // always test operator() on each read-only expression class, // in order to check const-qualifiers. // indeed, if an expression class (here Zero) is meant to be read-only, // hence has no _write() method, the corresponding MatrixBase method (here zero()) // should return a const-qualified object so that it is the const-qualified // operator() that gets called, which in turn calls _read(). VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1)); // now test copying a row-vector into a (column-)vector and conversely. square.col(r) = square.row(r).eval(); Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows); Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows); rv = square.row(r); cv = square.col(r); VERIFY_IS_APPROX(rv, cv.transpose()); if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic) { VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1))); } if(cols!=1 && rows!=1) { VERIFY_RAISES_ASSERT(m1[0]); VERIFY_RAISES_ASSERT((m1+m1)[0]); } VERIFY_IS_APPROX(m3 = m1,m1); MatrixType m4; VERIFY_IS_APPROX(m4 = m1,m1); m3.real() = m1.real(); VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real()); VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real()); // check == / != operators VERIFY(m1==m1); VERIFY(m1!=m2); VERIFY(!(m1==m2)); VERIFY(!(m1!=m1)); m1 = m2; VERIFY(m1==m2); VERIFY(!(m1!=m2)); // check automatic transposition sm2.setZero(); for(typename MatrixType::Index i=0;i<rows;++i) sm2.col(i) = sm1.row(i); VERIFY_IS_APPROX(sm2,sm1.transpose()); sm2.setZero(); for(typename MatrixType::Index i=0;i<rows;++i) sm2.col(i).noalias() = sm1.row(i); VERIFY_IS_APPROX(sm2,sm1.transpose()); sm2.setZero(); for(typename MatrixType::Index i=0;i<rows;++i) sm2.col(i).noalias() += sm1.row(i); VERIFY_IS_APPROX(sm2,sm1.transpose()); sm2.setZero(); for(typename MatrixType::Index i=0;i<rows;++i) sm2.col(i).noalias() -= sm1.row(i); VERIFY_IS_APPROX(sm2,-sm1.transpose()); } template<typename MatrixType> void basicStuffComplex(const MatrixType& m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> RealMatrixType; Index rows = m.rows(); Index cols = m.cols(); Scalar s1 = internal::random<Scalar>(), s2 = internal::random<Scalar>(); VERIFY(internal::real(s1)==internal::real_ref(s1)); VERIFY(internal::imag(s1)==internal::imag_ref(s1)); internal::real_ref(s1) = internal::real(s2); internal::imag_ref(s1) = internal::imag(s2); VERIFY(internal::isApprox(s1, s2, NumTraits<RealScalar>::epsilon())); // extended precision in Intel FPUs means that s1 == s2 in the line above is not guaranteed. RealMatrixType rm1 = RealMatrixType::Random(rows,cols), rm2 = RealMatrixType::Random(rows,cols); MatrixType cm(rows,cols); cm.real() = rm1; cm.imag() = rm2; VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1); VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2); rm1.setZero(); rm2.setZero(); rm1 = cm.real(); rm2 = cm.imag(); VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1); VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2); cm.real().setZero(); VERIFY(static_cast<const MatrixType&>(cm).real().isZero()); VERIFY(!static_cast<const MatrixType&>(cm).imag().isZero()); } #ifdef EIGEN_TEST_PART_2 void casting() { Matrix4f m = Matrix4f::Random(), m2; Matrix4d n = m.cast<double>(); VERIFY(m.isApprox(n.cast<float>())); m2 = m.cast<float>(); // check the specialization when NewType == Type VERIFY(m.isApprox(m2)); } #endif template <typename Scalar> void fixedSizeMatrixConstruction() { const Scalar raw[3] = {1,2,3}; Matrix<Scalar,3,1> m(raw); Array<Scalar,3,1> a(raw); VERIFY(m(0) == 1); VERIFY(m(1) == 2); VERIFY(m(2) == 3); VERIFY(a(0) == 1); VERIFY(a(1) == 2); VERIFY(a(2) == 3); } void test_basicstuff() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( basicStuff(Matrix<float, 1, 1>()) ); CALL_SUBTEST_2( basicStuff(Matrix4d()) ); CALL_SUBTEST_3( basicStuff(MatrixXcf(internal::random<int>(1,100), internal::random<int>(1,100))) ); CALL_SUBTEST_4( basicStuff(MatrixXi(internal::random<int>(1,100), internal::random<int>(1,100))) ); CALL_SUBTEST_5( basicStuff(MatrixXcd(internal::random<int>(1,100), internal::random<int>(1,100))) ); CALL_SUBTEST_6( basicStuff(Matrix<float, 100, 100>()) ); CALL_SUBTEST_7( basicStuff(Matrix<long double,Dynamic,Dynamic>(internal::random<int>(1,100),internal::random<int>(1,100))) ); CALL_SUBTEST_3( basicStuffComplex(MatrixXcf(internal::random<int>(1,100), internal::random<int>(1,100))) ); CALL_SUBTEST_5( basicStuffComplex(MatrixXcd(internal::random<int>(1,100), internal::random<int>(1,100))) ); } CALL_SUBTEST_1(fixedSizeMatrixConstruction<unsigned char>()); CALL_SUBTEST_1(fixedSizeMatrixConstruction<double>()); CALL_SUBTEST_1(fixedSizeMatrixConstruction<double>()); CALL_SUBTEST_2(casting()); } <|endoftext|>
<commit_before>/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter ([email protected]) */ #include <sys/types.h> #include <sys/stat.h> #include <cstdlib> #include <iostream> #include <iomanip> #include <sstream> #include <fstream> #include <vector> #include <trng/lcg64_shift.hpp> #include <trng/mrg2.hpp> #include <trng/mrg3.hpp> #include <trng/mrg4.hpp> #include <trng/mrg4.hpp> /** * */ template< typename Random, typename SeedType, typename SplitType, typename JumpType, typename Jump2Type, typename ResultType > class TRNG { public: TRNG( SeedType seed, SplitType splitp, SplitType splits, JumpType jump, Jump2Type jump2 ) { _random.seed(seed); _random.split(splitp, splits); _random.jump(jump); _random.jump2(jump2); std::stringstream name; name << "random[" << seed << ","; name << splitp << "," << splits << ","; name << jump << ","; name << jump2 << "].dat"; _fileName = name.str(); } ~TRNG() { } std::string next() { std::stringstream out; out << static_cast<ResultType>(_random()); return out.str(); } std::string fileName() { return _fileName; } private: Random _random; std::string _fileName; }; template< typename Random, typename SeedType, typename SplitType, typename JumpType, typename Jump2Type, typename ResultType > void write( const std::string& dir, TRNG<Random, SeedType, SplitType, JumpType, Jump2Type, ResultType>& random, std::size_t numbers ) { std::string file = dir + "/" + random.fileName(); std::fstream out(file.c_str(), std::fstream::out); for (std::size_t i = 0; i < numbers; ++i) { out << random.next() << std::endl; } out.close(); } void lcg64_shift( unsigned long seed, unsigned long splitp, unsigned long splits, unsigned long long jump, unsigned int jump2 ) { mkdir("./LCG64ShiftRandom", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); TRNG< trng::lcg64_shift, unsigned long, unsigned long, unsigned long long, unsigned int, long long > random(seed, splitp, splits, jump, jump2); write("./LCG64ShiftRandom", random, 150); } void mrg2( unsigned long seed, unsigned long splitp, unsigned long splits, unsigned long long jump, unsigned int jump2 ) { mkdir("./MRG2Random", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); TRNG< trng::mrg2, unsigned long, unsigned long, unsigned long long, unsigned int, long > random(seed, splitp, splits, jump, jump2); write("./MRG2Random", random, 150); } void mrg3( unsigned long seed, unsigned long splitp, unsigned long splits, unsigned long long jump, unsigned int jump2 ) { mkdir("./MRG3Random", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); TRNG< trng::mrg2, unsigned long, unsigned long, unsigned long long, unsigned int, int > random(seed, splitp, splits, jump, jump2); write("./MRG3Random", random, 150); } int main(void) { for (unsigned long long seed = 0; seed < 2; ++seed) { for (unsigned long splitp = 5; splitp < 10; splitp += 3) { for (unsigned long splits = 0; splits < splitp; splits += 2) { for (unsigned long long jump = 0; jump < 2; ++jump) { for (unsigned int jump2 = 0; jump2 < 64; jump2 += 23) { lcg64_shift(seed*742367882L, splitp, splits, jump*948392782L, jump2); mrg2(seed*742367882L, splitp, splits, jump*948392782L, jump2); mrg3(seed*742367882L, splitp, splits, jump*948392782L, jump2); } } } } } return 0; } <commit_msg>Improve TRNG test data configuration.<commit_after>/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter ([email protected]) */ #include <sys/types.h> #include <sys/stat.h> #include <cstdlib> #include <iostream> #include <iomanip> #include <sstream> #include <fstream> #include <vector> #include <trng/lcg64_shift.hpp> #include <trng/mrg2.hpp> #include <trng/mrg3.hpp> #include <trng/mrg4.hpp> #include <trng/mrg4.hpp> #include <trng/mt19937.hpp> /** * */ template< typename Random, typename SeedType, typename ResultType > class TRNG { public: TRNG(SeedType seed) { _random.seed(seed); std::stringstream name; name << "random[" << seed << "].dat"; _fileName = name.str(); } ~TRNG() { } std::string next() { std::stringstream out; out << static_cast<ResultType>(_random()); return out.str(); } std::string fileName() { return _fileName; } private: Random _random; std::string _fileName; }; /** * */ template< typename Random, typename SeedType, typename SplitType, typename JumpType, typename Jump2Type, typename ResultType > class TRNGParallel { public: TRNGParallel( SeedType seed, SplitType splitp, SplitType splits, JumpType jump, Jump2Type jump2 ) { _random.seed(seed); _random.split(splitp, splits); _random.jump(jump); _random.jump2(jump2); std::stringstream name; name << "random[" << seed << ","; name << splitp << "," << splits << ","; name << jump << ","; name << jump2 << "].dat"; _fileName = name.str(); } ~TRNGParallel() { } std::string next() { std::stringstream out; out << static_cast<ResultType>(_random()); return out.str(); } std::string fileName() { return _fileName; } private: Random _random; std::string _fileName; }; template< typename Random, typename SeedType, typename ResultType > void write( const std::string& dir, TRNG<Random, SeedType, ResultType>& random, std::size_t numbers ) { std::string file = dir + "/" + random.fileName(); std::fstream out(file.c_str(), std::fstream::out); for (std::size_t i = 0; i < numbers; ++i) { out << random.next() << std::endl; } out.close(); } template< typename Random, typename SeedType, typename SplitType, typename JumpType, typename Jump2Type, typename ResultType > void write( const std::string& dir, TRNGParallel<Random, SeedType, SplitType, JumpType, Jump2Type, ResultType>& random, std::size_t numbers ) { std::string file = dir + "/" + random.fileName(); std::fstream out(file.c_str(), std::fstream::out); for (std::size_t i = 0; i < numbers; ++i) { out << random.next() << std::endl; } out.close(); } void lcg64_shift( unsigned long seed, unsigned long splitp, unsigned long splits, unsigned long long jump, unsigned int jump2 ) { mkdir("./LCG64ShiftRandom", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); TRNGParallel< trng::lcg64_shift, unsigned long, unsigned long, unsigned long long, unsigned int, long long > random(seed, splitp, splits, jump, jump2); write("./LCG64ShiftRandom", random, 150); } void mrg2( unsigned long seed, unsigned long splitp, unsigned long splits, unsigned long long jump, unsigned int jump2 ) { mkdir("./MRG2Random", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); TRNGParallel< trng::mrg2, unsigned long, unsigned long, unsigned long long, unsigned int, long > random(seed, splitp, splits, jump, jump2); write("./MRG2Random", random, 150); } void mrg3( unsigned long seed, unsigned long splitp, unsigned long splits, unsigned long long jump, unsigned int jump2 ) { mkdir("./MRG3Random", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); TRNGParallel< trng::mrg2, unsigned long, unsigned long, unsigned long long, unsigned int, int > random(seed, splitp, splits, jump, jump2); write("./MRG3Random", random, 150); } void mt19937_32(unsigned long seed ) { mkdir("./MT19937_32Random", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); TRNG<trng::mt19937, unsigned long, int> random(seed); write("./MT19937_32Random", random, 150); } int main(void) { /* for (unsigned long long seed = 0; seed < 2; ++seed) { for (unsigned long splitp = 5; splitp < 10; splitp += 3) { for (unsigned long splits = 0; splits < splitp; splits += 2) { for (unsigned long long jump = 0; jump < 2; ++jump) { for (unsigned int jump2 = 0; jump2 < 64; jump2 += 23) { lcg64_shift(seed*742367882L, splitp, splits, jump*948392782L, jump2); mrg2(seed*742367882L, splitp, splits, jump*948392782L, jump2); mrg3(seed*742367882L, splitp, splits, jump*948392782L, jump2); } } } } } */ for (unsigned long long seed = 0; seed < 1000000000; seed += 12345678) { mt19937_32(seed); } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: postuhdl.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:42:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_PROPERTYHANDLER_POSTURETYPES_HXX #include <postuhdl.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_AWT_FONTSLANT_HPP_ #include <com/sun/star/awt/FontSlant.hpp> #endif #ifndef _VCL_VCLENUM_HXX #include <vcl/vclenum.hxx> #endif #ifndef _XMLOFF_XMLEMENT_HXX #include <xmloff/xmlelement.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::xmloff::token; SvXMLEnumMapEntry __READONLY_DATA aPostureGenericMapping[] = { { XML_POSTURE_NORMAL, ITALIC_NONE }, { XML_POSTURE_ITALIC, ITALIC_NORMAL }, { XML_POSTURE_OBLIQUE, ITALIC_OBLIQUE }, { XML_TOKEN_INVALID, 0 } }; /////////////////////////////////////////////////////////////////////////////// // // class XMLPosturePropHdl // XMLPosturePropHdl::~XMLPosturePropHdl() { // nothing to do } sal_Bool XMLPosturePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const { sal_uInt16 ePosture; sal_Bool bRet = SvXMLUnitConverter::convertEnum( ePosture, rStrImpValue, aPostureGenericMapping ); if( bRet ) rValue <<= (awt::FontSlant)ePosture; return bRet; } sal_Bool XMLPosturePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const { awt::FontSlant eSlant; if( !( rValue >>= eSlant ) ) { sal_Int32 nValue = 0; if( !( rValue >>= nValue ) ) return sal_False; eSlant = (awt::FontSlant)nValue; } OUStringBuffer aOut; sal_Bool bRet = SvXMLUnitConverter::convertEnum( aOut, (sal_Int32)eSlant, aPostureGenericMapping ); if( bRet ) rStrExpValue = aOut.makeStringAndClear(); return bRet; } <commit_msg>INTEGRATION: CWS impresstables2 (1.7.46); FILE MERGED 2007/08/01 14:33:18 cl 1.7.46.2: RESYNC: (1.7-1.8); FILE MERGED 2007/07/27 09:09:54 cl 1.7.46.1: fixed build issues due to pch and namespace ::rtl<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: postuhdl.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2008-03-12 10:53:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_PROPERTYHANDLER_POSTURETYPES_HXX #include <postuhdl.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_AWT_FONTSLANT_HPP_ #include <com/sun/star/awt/FontSlant.hpp> #endif #ifndef _VCL_VCLENUM_HXX #include <vcl/vclenum.hxx> #endif #ifndef _XMLOFF_XMLEMENT_HXX #include <xmloff/xmlelement.hxx> #endif using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::xmloff::token; SvXMLEnumMapEntry __READONLY_DATA aPostureGenericMapping[] = { { XML_POSTURE_NORMAL, ITALIC_NONE }, { XML_POSTURE_ITALIC, ITALIC_NORMAL }, { XML_POSTURE_OBLIQUE, ITALIC_OBLIQUE }, { XML_TOKEN_INVALID, 0 } }; /////////////////////////////////////////////////////////////////////////////// // // class XMLPosturePropHdl // XMLPosturePropHdl::~XMLPosturePropHdl() { // nothing to do } sal_Bool XMLPosturePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const { sal_uInt16 ePosture; sal_Bool bRet = SvXMLUnitConverter::convertEnum( ePosture, rStrImpValue, aPostureGenericMapping ); if( bRet ) rValue <<= (awt::FontSlant)ePosture; return bRet; } sal_Bool XMLPosturePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const { awt::FontSlant eSlant; if( !( rValue >>= eSlant ) ) { sal_Int32 nValue = 0; if( !( rValue >>= nValue ) ) return sal_False; eSlant = (awt::FontSlant)nValue; } OUStringBuffer aOut; sal_Bool bRet = SvXMLUnitConverter::convertEnum( aOut, (sal_Int32)eSlant, aPostureGenericMapping ); if( bRet ) rStrExpValue = aOut.makeStringAndClear(); return bRet; } <|endoftext|>
<commit_before>/* ** Copyright (C) 2012 Aldebaran Robotics */ #pragma once #ifndef _QIMESSAGING_EXECUTIONCONTEXT_HPP_ #define _QIMESSAGING_EXECUTIONCONTEXT_HPP_ #include <boost/shared_ptr.hpp> #include <boost/function.hpp> #include <qi/types.hpp> #include <qimessaging/api.hpp> namespace qi { class EventLoopPrivate; class AsyncCallHandlePrivate; class QIMESSAGING_API EventLoop { public: /** Create a new eventLoop. * You must then call eiter start() or run() to start event processing. */ EventLoop(); ~EventLoop(); /// Return true if current thread is the event loop thread. bool isInEventLoopThread(); /// Start in a thread (in case useThread=false was passed to constructor). void start(); /// Wait for run thread to terminate void join(); /// Ask main loop to terminate void stop(); /// Run main loop in current thread. void run(); class AsyncCallHandle { public: AsyncCallHandle(); ~AsyncCallHandle(); /// Cancel the call if it was not already processed void cancel(); boost::shared_ptr<AsyncCallHandlePrivate> _p; }; /// Call given function once after given delay in microseconds. AsyncCallHandle asyncCall(uint64_t usDelay, boost::function<void ()> callback); EventLoopPrivate *_p; }; /// Return a default event loop for network operations. QIMESSAGING_API EventLoop* getDefaultNetworkEventLoop(); /// Return a default context for other uses. QIMESSAGING_API EventLoop* getDefaultObjectEventLoop(); } #endif <commit_msg>Fix windows compilation<commit_after>/* ** Copyright (C) 2012 Aldebaran Robotics */ #pragma once #ifndef _QIMESSAGING_EXECUTIONCONTEXT_HPP_ #define _QIMESSAGING_EXECUTIONCONTEXT_HPP_ #include <boost/shared_ptr.hpp> #include <boost/function.hpp> #include <qi/types.hpp> #include <qimessaging/api.hpp> namespace qi { class EventLoopPrivate; class AsyncCallHandlePrivate; class QIMESSAGING_API EventLoop { public: /** Create a new eventLoop. * You must then call eiter start() or run() to start event processing. */ EventLoop(); ~EventLoop(); /// Return true if current thread is the event loop thread. bool isInEventLoopThread(); /// Start in a thread (in case useThread=false was passed to constructor). void start(); /// Wait for run thread to terminate void join(); /// Ask main loop to terminate void stop(); /// Run main loop in current thread. void run(); class QIMESSAGING_API AsyncCallHandle { public: AsyncCallHandle(); ~AsyncCallHandle(); /// Cancel the call if it was not already processed void cancel(); boost::shared_ptr<AsyncCallHandlePrivate> _p; }; /// Call given function once after given delay in microseconds. AsyncCallHandle asyncCall(uint64_t usDelay, boost::function<void ()> callback); EventLoopPrivate *_p; }; /// Return a default event loop for network operations. QIMESSAGING_API EventLoop* getDefaultNetworkEventLoop(); /// Return a default context for other uses. QIMESSAGING_API EventLoop* getDefaultObjectEventLoop(); } #endif <|endoftext|>
<commit_before>/* * File: PGR_renderer.cpp * Author: Martin Simon <[email protected]> * Lukas Brzobohaty <[email protected]> * * Created on 2013-10-13, 18:20 */ #include "pgr.h" #include "PGR_renderer.h" #include "model.h" //#include "sphere.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> /* Buffers */ extern GLuint roomVBO, roomEBO; /* Shaders */ extern GLuint iVS, iFS, iProg; extern GLuint positionAttrib, colorAttrib, normalAttrib, mvpUniform, laUniform, ldUniform, lightPosUniform; extern const char * vertexShaderRoom; extern const char * fragmentShaderRoom; glm::vec3 light_pos = glm::vec3(0, 2.5, 0); PGR_renderer::PGR_renderer() { } PGR_renderer::PGR_renderer(int c) { this->model = new PGR_model(C_ROOM); PGR_model * light = new PGR_model(C_LIGHT); this->model->appendModel(light); delete light; this->maxArea = -1.0; this->divided = true; this->radiosity = new PGR_radiosity(this->model, c); } PGR_renderer::PGR_renderer(const PGR_renderer& orig) { } PGR_renderer::~PGR_renderer() { delete this->radiosity; delete this->model; } void PGR_renderer::setMaxArea(float area) { this->maxArea = area; this->divided = false; } void PGR_renderer::init() { /* Create shaders */ iVS = compileShader(GL_VERTEX_SHADER, vertexShaderRoom); iFS = compileShader(GL_FRAGMENT_SHADER, fragmentShaderRoom); iProg = linkShader(2, iVS, iFS); /* Link shader input/output to gl variables */ positionAttrib = glGetAttribLocation(iProg, "position"); normalAttrib = glGetAttribLocation(iProg, "normal"); colorAttrib = glGetAttribLocation(iProg, "color"); mvpUniform = glGetUniformLocation(iProg, "mvp"); laUniform = glGetUniformLocation(iProg, "la"); ldUniform = glGetUniformLocation(iProg, "ld"); lightPosUniform = glGetUniformLocation(iProg, "lightPos"); this->divide(); /* Create buffers */ glGenBuffers(1, &roomVBO); glGenBuffers(1, &roomEBO); this->refillBuffers(); GLuint _fbo; GLuint _depth; GLuint _color; glGenFramebuffers(1, &_fbo); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glGenTextures(1, &_color); //texture for drawing // "Bind" the newly created texture : all future texture functions will modify this texture glBindTexture(GL_TEXTURE_2D, _color); // Give an empty image to OpenGL ( the last "0" ) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->fboWidth, this->fboHeight, 0, GL_RGB, GL_FLOAT, 0); // Poor filtering. Needed ! glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // The depth buffer glGenRenderbuffers(1, &_depth); glBindRenderbuffer(GL_RENDERBUFFER, _depth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, this->fboWidth, this->fboHeight); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depth); // Set "renderedTexture" as our colour attachement #0 //glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, color, 0); // glBindFramebuffer(GL_FRAMEBUFFER, 0); // this->radiosity->setFramebuffer(_fbo); this->radiosity->setTexture(_color); } bool PGR_renderer::divide() { if (!this->divided && this->maxArea > 0.0) { /* Max area set, need to divide all patches */ this->model->setMaxArea(this->maxArea); this->model->divide(); this->model->updateArrays(); this->divided = true; return true; } else return false; } void PGR_renderer::printPatches() { for (int i = 0; i <this->model->patches.size(); i++) { cout << "Patch: " << i << endl; cout << "\t[" << this->model->patches[i]->vertices[0].position[0] << "," << this->model->patches[i]->vertices[0].position[1] << "," << this->model->patches[i]->vertices[0].position[2] << "]" << endl; cout << "\t[" << this->model->patches[i]->vertices[1].position[0] << "," << this->model->patches[i]->vertices[1].position[1] << "," << this->model->patches[i]->vertices[1].position[2] << "]" << endl; cout << "\t[" << this->model->patches[i]->vertices[2].position[0] << "," << this->model->patches[i]->vertices[2].position[1] << "," << this->model->patches[i]->vertices[2].position[2] << "]" << endl; cout << "\t[" << this->model->patches[i]->vertices[3].position[0] << "," << this->model->patches[i]->vertices[3].position[1] << "," << this->model->patches[i]->vertices[3].position[2] << "]" << endl; } } void PGR_renderer::refillBuffers() { glBindBuffer(GL_ARRAY_BUFFER, roomVBO); glBufferData(GL_ARRAY_BUFFER, this->model->getVerticesCount() * sizeof (Point), this->model->getVertices(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->model->getIndicesCount() * sizeof (unsigned int), this->model->getIndices(), GL_STATIC_DRAW); } /** * Draw 3D scene using default renderer. This rendering should be real-time and * used to set view angle light sources. It doesn't need to run on GPU. */ void PGR_renderer::drawSceneDefault(glm::mat4 mvp) { glBindFramebuffer(GL_FRAMEBUFFER, 0); glUseProgram(iProg); glUniformMatrix4fv(mvpUniform, 1, GL_FALSE, glm::value_ptr(mvp)); glUniform3f(laUniform, 1, 1, 1); glUniform3f(lightPosUniform, light_pos[0], light_pos[1], light_pos[2]); glUniform3f(ldUniform, 0.5, 0.5, 0.5); /* Draw room */ glEnableVertexAttribArray(positionAttrib); glEnableVertexAttribArray(colorAttrib); glEnableVertexAttribArray(normalAttrib); glBindBuffer(GL_ARRAY_BUFFER, roomVBO); glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, position)); glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, color)); glVertexAttribPointer(normalAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, normal)); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO); glDrawElements(GL_QUADS, this->model->getIndicesCount(), GL_UNSIGNED_INT, NULL); glDisableVertexAttribArray(positionAttrib); glDisableVertexAttribArray(colorAttrib); glDisableVertexAttribArray(normalAttrib); } /** * Draw 3D scene with radiosity computed using OpenCL. This rendering doesn't * run real-time and also changing of angle/resizing window is not permitted. */ void PGR_renderer::drawSceneRadiosity(glm::mat4 mvp) { if (!this->radiosity->isComputed()) { this->radiosity->compute(); this->refillBuffers(); } glBindFramebuffer(GL_FRAMEBUFFER, 0); glUseProgram(iProg); glUniformMatrix4fv(mvpUniform, 1, GL_FALSE, glm::value_ptr(mvp)); glUniform3f(laUniform, 0.2, 0.2, 0.2); //turn off basic shadows glUniform3f(ldUniform, 0.0, 0.0, 0.0); //turn off basic shadows /* Draw room */ glEnableVertexAttribArray(positionAttrib); glEnableVertexAttribArray(colorAttrib); glBindBuffer(GL_ARRAY_BUFFER, roomVBO); glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, position)); glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, color)); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO); glDrawElements(GL_QUADS, this->model->getIndicesCount(), GL_UNSIGNED_INT, NULL); glDisableVertexAttribArray(positionAttrib); glDisableVertexAttribArray(colorAttrib); } <commit_msg>Light intensity decreased<commit_after>/* * File: PGR_renderer.cpp * Author: Martin Simon <[email protected]> * Lukas Brzobohaty <[email protected]> * * Created on 2013-10-13, 18:20 */ #include "pgr.h" #include "PGR_renderer.h" #include "model.h" //#include "sphere.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> /* Buffers */ extern GLuint roomVBO, roomEBO; /* Shaders */ extern GLuint iVS, iFS, iProg; extern GLuint positionAttrib, colorAttrib, normalAttrib, mvpUniform, laUniform, ldUniform, lightPosUniform; extern const char * vertexShaderRoom; extern const char * fragmentShaderRoom; glm::vec3 light_pos = glm::vec3(0, 2.5, 0); PGR_renderer::PGR_renderer() { } PGR_renderer::PGR_renderer(int c) { this->model = new PGR_model(C_ROOM); PGR_model * light = new PGR_model(C_LIGHT); this->model->appendModel(light); delete light; this->maxArea = -1.0; this->divided = true; this->radiosity = new PGR_radiosity(this->model, c); } PGR_renderer::PGR_renderer(const PGR_renderer& orig) { } PGR_renderer::~PGR_renderer() { delete this->radiosity; delete this->model; } void PGR_renderer::setMaxArea(float area) { this->maxArea = area; this->divided = false; } void PGR_renderer::init() { /* Create shaders */ iVS = compileShader(GL_VERTEX_SHADER, vertexShaderRoom); iFS = compileShader(GL_FRAGMENT_SHADER, fragmentShaderRoom); iProg = linkShader(2, iVS, iFS); /* Link shader input/output to gl variables */ positionAttrib = glGetAttribLocation(iProg, "position"); normalAttrib = glGetAttribLocation(iProg, "normal"); colorAttrib = glGetAttribLocation(iProg, "color"); mvpUniform = glGetUniformLocation(iProg, "mvp"); laUniform = glGetUniformLocation(iProg, "la"); ldUniform = glGetUniformLocation(iProg, "ld"); lightPosUniform = glGetUniformLocation(iProg, "lightPos"); this->divide(); /* Create buffers */ glGenBuffers(1, &roomVBO); glGenBuffers(1, &roomEBO); this->refillBuffers(); GLuint _fbo; GLuint _depth; GLuint _color; glGenFramebuffers(1, &_fbo); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glGenTextures(1, &_color); //texture for drawing // "Bind" the newly created texture : all future texture functions will modify this texture glBindTexture(GL_TEXTURE_2D, _color); // Give an empty image to OpenGL ( the last "0" ) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->fboWidth, this->fboHeight, 0, GL_RGB, GL_FLOAT, 0); // Poor filtering. Needed ! glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // The depth buffer glGenRenderbuffers(1, &_depth); glBindRenderbuffer(GL_RENDERBUFFER, _depth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, this->fboWidth, this->fboHeight); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depth); // Set "renderedTexture" as our colour attachement #0 //glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, color, 0); // glBindFramebuffer(GL_FRAMEBUFFER, 0); // this->radiosity->setFramebuffer(_fbo); this->radiosity->setTexture(_color); } bool PGR_renderer::divide() { if (!this->divided && this->maxArea > 0.0) { /* Max area set, need to divide all patches */ this->model->setMaxArea(this->maxArea); this->model->divide(); this->model->updateArrays(); this->divided = true; return true; } else return false; } void PGR_renderer::printPatches() { for (int i = 0; i <this->model->patches.size(); i++) { cout << "Patch: " << i << endl; cout << "\t[" << this->model->patches[i]->vertices[0].position[0] << "," << this->model->patches[i]->vertices[0].position[1] << "," << this->model->patches[i]->vertices[0].position[2] << "]" << endl; cout << "\t[" << this->model->patches[i]->vertices[1].position[0] << "," << this->model->patches[i]->vertices[1].position[1] << "," << this->model->patches[i]->vertices[1].position[2] << "]" << endl; cout << "\t[" << this->model->patches[i]->vertices[2].position[0] << "," << this->model->patches[i]->vertices[2].position[1] << "," << this->model->patches[i]->vertices[2].position[2] << "]" << endl; cout << "\t[" << this->model->patches[i]->vertices[3].position[0] << "," << this->model->patches[i]->vertices[3].position[1] << "," << this->model->patches[i]->vertices[3].position[2] << "]" << endl; } } void PGR_renderer::refillBuffers() { glBindBuffer(GL_ARRAY_BUFFER, roomVBO); glBufferData(GL_ARRAY_BUFFER, this->model->getVerticesCount() * sizeof (Point), this->model->getVertices(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->model->getIndicesCount() * sizeof (unsigned int), this->model->getIndices(), GL_STATIC_DRAW); } /** * Draw 3D scene using default renderer. This rendering should be real-time and * used to set view angle light sources. It doesn't need to run on GPU. */ void PGR_renderer::drawSceneDefault(glm::mat4 mvp) { glBindFramebuffer(GL_FRAMEBUFFER, 0); glUseProgram(iProg); glUniformMatrix4fv(mvpUniform, 1, GL_FALSE, glm::value_ptr(mvp)); glUniform3f(laUniform, 0.5, 0.5, 0.5); glUniform3f(lightPosUniform, light_pos[0], light_pos[1], light_pos[2]); glUniform3f(ldUniform, 0.5, 0.5, 0.5); /* Draw room */ glEnableVertexAttribArray(positionAttrib); glEnableVertexAttribArray(colorAttrib); glEnableVertexAttribArray(normalAttrib); glBindBuffer(GL_ARRAY_BUFFER, roomVBO); glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, position)); glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, color)); glVertexAttribPointer(normalAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, normal)); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO); glDrawElements(GL_QUADS, this->model->getIndicesCount(), GL_UNSIGNED_INT, NULL); glDisableVertexAttribArray(positionAttrib); glDisableVertexAttribArray(colorAttrib); glDisableVertexAttribArray(normalAttrib); } /** * Draw 3D scene with radiosity computed using OpenCL. This rendering doesn't * run real-time and also changing of angle/resizing window is not permitted. */ void PGR_renderer::drawSceneRadiosity(glm::mat4 mvp) { if (!this->radiosity->isComputed()) { this->radiosity->compute(); this->refillBuffers(); } glBindFramebuffer(GL_FRAMEBUFFER, 0); glUseProgram(iProg); glUniformMatrix4fv(mvpUniform, 1, GL_FALSE, glm::value_ptr(mvp)); glUniform3f(laUniform, 0.2, 0.2, 0.2); //turn off basic shadows glUniform3f(ldUniform, 0.0, 0.0, 0.0); //turn off basic shadows /* Draw room */ glEnableVertexAttribArray(positionAttrib); glEnableVertexAttribArray(colorAttrib); glBindBuffer(GL_ARRAY_BUFFER, roomVBO); glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, position)); glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, color)); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO); glDrawElements(GL_QUADS, this->model->getIndicesCount(), GL_UNSIGNED_INT, NULL); glDisableVertexAttribArray(positionAttrib); glDisableVertexAttribArray(colorAttrib); } <|endoftext|>
<commit_before>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Renataki SD%Complete: 100 SDComment: SDCategory: Zul'Gurub EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "zulgurub.h" enum Spells { SPELL_VANISH = 24699, SPELL_AMBUSH = 24337, SPELL_GOUGE = 24698, SPELL_THOUSAND_BLADES = 24649, SPELL_THRASH = 3417, SPELL_ENRAGE = 8269 }; enum Events { EVENT_VANISH = 1, EVENT_AMBUSH = 2, EVENT_GOUGE = 3, EVENT_THOUSAND_BLADES = 4 }; class boss_renataki : public CreatureScript { public: boss_renataki() : CreatureScript("boss_renataki") { } struct boss_renatakiAI : public BossAI { boss_renatakiAI(Creature* creature) : BossAI(creature, DATA_EDGE_OF_MADNESS) { } void Reset() override { _Reset(); me->SetReactState(REACT_AGGRESSIVE); _enraged = false; _thousandBladesCount = urand(2, 5); _thousandBladesTargets.clear(); _dynamicFlags = me->GetDynamicFlags(); } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); events.ScheduleEvent(EVENT_VANISH, 23s, 25s); events.ScheduleEvent(EVENT_GOUGE, 5s, 10s); events.ScheduleEvent(EVENT_THOUSAND_BLADES, 15s, 20s); DoCastSelf(SPELL_THRASH, true); } void DamageTaken(Unit*, uint32& /*damage*/, DamageEffectType, SpellSchoolMask) override { if (!_enraged && HealthBelowPct(30)) { me->TextEmote("%s becomes enraged", me, false); DoCast(me, SPELL_ENRAGE); _enraged = true; } } bool CanAIAttack(Unit const* target) const override { if (me->GetThreatMgr().GetThreatListSize() > 1 && me->GetThreatMgr().GetOnlineContainer().getMostHated()->getTarget() == target) return !target->HasAura(SPELL_GOUGE); return true; } bool CanBeSeen(Player const* /*player*/) override { return me->GetReactState() == REACT_AGGRESSIVE; } bool CanSeeAlways(WorldObject const* obj) override { if (me->GetReactState() == REACT_PASSIVE) { return obj->ToCreature() && obj->ToCreature()->IsPet(); } return false; } bool CanAlwaysBeDetectable(WorldObject const* seer) override { if (me->GetReactState() == REACT_PASSIVE) { return seer->ToCreature() && seer->ToCreature()->IsPet(); } return false; } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_VANISH: me->SetReactState(REACT_PASSIVE); _dynamicFlags = me->GetDynamicFlags(); me->RemoveDynamicFlag(UNIT_DYNFLAG_TRACK_UNIT); DoCastSelf(SPELL_VANISH); events.DelayEvents(5s); events.ScheduleEvent(EVENT_AMBUSH, 5s); events.ScheduleEvent(EVENT_VANISH, 38s, 45s); return; case EVENT_AMBUSH: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 1)) { me->NearTeleportTo(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), me->GetOrientation()); DoCast(target, SPELL_AMBUSH, true); } me->SetDynamicFlag(_dynamicFlags); me->RemoveAurasDueToSpell(SPELL_VANISH); me->SetReactState(REACT_AGGRESSIVE); break; case EVENT_GOUGE: DoCastAOE(SPELL_GOUGE); events.ScheduleEvent(EVENT_GOUGE, 10s, 15s); return; case EVENT_THOUSAND_BLADES: { if (_thousandBladesTargets.empty()) { std::vector<Unit*> targetList; ThreatContainer::StorageType const& threatlist = me->GetThreatMgr().GetThreatList(); for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) { if (Unit* target = (*itr)->getTarget()) { if (target->IsAlive() && target->IsWithinDist2d(me, 100.f)) { targetList.push_back(target); } } } if (!targetList.empty()) { Acore::Containers::RandomShuffle(targetList); // First get ranged targets for (Unit* target : targetList) { if (!target->IsWithinMeleeRange(me)) { _thousandBladesTargets.push_back(target); } } if (_thousandBladesTargets.size() < _thousandBladesCount) { // if still not enough, get melee targets for (Unit* target : targetList) { if (target->IsWithinMeleeRange(me)) { _thousandBladesTargets.push_back(target); } } } if (!_thousandBladesTargets.empty()) { Acore::Containers::RandomResize(_thousandBladesTargets, _thousandBladesCount); } } } if (!_thousandBladesTargets.empty()) { std::vector<Unit*>::iterator itr = _thousandBladesTargets.begin(); std::advance(itr, urand(0, _thousandBladesTargets.size() - 1)); if (Unit* target = *itr) { DoCast(target, SPELL_THOUSAND_BLADES, false); } if (_thousandBladesTargets.erase(itr) != _thousandBladesTargets.end()) { events.ScheduleEvent(EVENT_THOUSAND_BLADES, 500ms); } else { _thousandBladesCount = urand(2, 5); events.ScheduleEvent(EVENT_THOUSAND_BLADES, 15s, 22s); } } else { _thousandBladesCount = urand(2, 5); events.ScheduleEvent(EVENT_THOUSAND_BLADES, 15s, 22s); } break; } default: break; } } if (me->GetReactState() == REACT_AGGRESSIVE) DoMeleeAttackIfReady(); } private: bool _enraged; uint32 _dynamicFlags; uint8 _thousandBladesCount; std::vector<Unit*> _thousandBladesTargets; }; CreatureAI* GetAI(Creature* creature) const override { return GetZulGurubAI<boss_renatakiAI>(creature); } }; void AddSC_boss_renataki() { new boss_renataki(); } <commit_msg>fix(Core/Scripts): Renataki crash (#13811)<commit_after>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Renataki SD%Complete: 100 SDComment: SDCategory: Zul'Gurub EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "zulgurub.h" enum Spells { SPELL_VANISH = 24699, SPELL_AMBUSH = 24337, SPELL_GOUGE = 24698, SPELL_THOUSAND_BLADES = 24649, SPELL_THRASH = 3417, SPELL_ENRAGE = 8269 }; enum Events { EVENT_VANISH = 1, EVENT_AMBUSH = 2, EVENT_GOUGE = 3, EVENT_THOUSAND_BLADES = 4 }; class boss_renataki : public CreatureScript { public: boss_renataki() : CreatureScript("boss_renataki") { } struct boss_renatakiAI : public BossAI { boss_renatakiAI(Creature* creature) : BossAI(creature, DATA_EDGE_OF_MADNESS) { } void Reset() override { _Reset(); me->SetReactState(REACT_AGGRESSIVE); _enraged = false; _thousandBladesCount = urand(2, 5); _thousandBladesTargets.clear(); _dynamicFlags = me->GetDynamicFlags(); } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); events.ScheduleEvent(EVENT_VANISH, 23s, 25s); events.ScheduleEvent(EVENT_GOUGE, 5s, 10s); events.ScheduleEvent(EVENT_THOUSAND_BLADES, 15s, 20s); DoCastSelf(SPELL_THRASH, true); } void DamageTaken(Unit*, uint32& /*damage*/, DamageEffectType, SpellSchoolMask) override { if (!_enraged && HealthBelowPct(30)) { me->TextEmote("%s becomes enraged", me, false); DoCast(me, SPELL_ENRAGE); _enraged = true; } } bool CanAIAttack(Unit const* target) const override { if (me->GetThreatMgr().GetThreatListSize() > 1 && me->GetThreatMgr().GetOnlineContainer().getMostHated()->getTarget() == target) return !target->HasAura(SPELL_GOUGE); return true; } bool CanBeSeen(Player const* /*player*/) override { return me->GetReactState() == REACT_AGGRESSIVE; } bool CanSeeAlways(WorldObject const* obj) override { if (me->GetReactState() == REACT_PASSIVE) { return obj->ToCreature() && obj->ToCreature()->IsPet(); } return false; } bool CanAlwaysBeDetectable(WorldObject const* seer) override { if (me->GetReactState() == REACT_PASSIVE) { return seer->ToCreature() && seer->ToCreature()->IsPet(); } return false; } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_VANISH: me->SetReactState(REACT_PASSIVE); _dynamicFlags = me->GetDynamicFlags(); me->RemoveDynamicFlag(UNIT_DYNFLAG_TRACK_UNIT); DoCastSelf(SPELL_VANISH); events.DelayEvents(5s); events.ScheduleEvent(EVENT_AMBUSH, 5s); events.ScheduleEvent(EVENT_VANISH, 38s, 45s); return; case EVENT_AMBUSH: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 1)) { me->NearTeleportTo(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), me->GetOrientation()); DoCast(target, SPELL_AMBUSH, true); } me->SetDynamicFlag(_dynamicFlags); me->RemoveAurasDueToSpell(SPELL_VANISH); me->SetReactState(REACT_AGGRESSIVE); break; case EVENT_GOUGE: DoCastAOE(SPELL_GOUGE); events.ScheduleEvent(EVENT_GOUGE, 10s, 15s); return; case EVENT_THOUSAND_BLADES: { if (_thousandBladesTargets.empty()) { std::vector<Unit*> targetList; ThreatContainer::StorageType const& threatlist = me->GetThreatMgr().GetThreatList(); for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) { if (Unit* target = (*itr)->getTarget()) { if (target->IsAlive() && target->IsWithinDist2d(me, 100.f)) { targetList.push_back(target); } } } if (!targetList.empty()) { Acore::Containers::RandomShuffle(targetList); // First get ranged targets for (Unit* target : targetList) { if (!target->IsWithinMeleeRange(me)) { _thousandBladesTargets.push_back(target->GetGUID()); } } if (_thousandBladesTargets.size() < _thousandBladesCount) { // if still not enough, get melee targets for (Unit* target : targetList) { if (target->IsWithinMeleeRange(me)) { _thousandBladesTargets.push_back(target->GetGUID()); } } } if (!_thousandBladesTargets.empty()) { Acore::Containers::RandomResize(_thousandBladesTargets, _thousandBladesCount); } } } if (!_thousandBladesTargets.empty()) { GuidVector::iterator itr = _thousandBladesTargets.begin(); std::advance(itr, urand(0, _thousandBladesTargets.size() - 1)); if (Unit* target = ObjectAccessor::GetUnit(*me, *itr)) { DoCast(target, SPELL_THOUSAND_BLADES); } if (_thousandBladesTargets.erase(itr) != _thousandBladesTargets.end()) { events.ScheduleEvent(EVENT_THOUSAND_BLADES, 500ms); } else { _thousandBladesCount = urand(2, 5); events.ScheduleEvent(EVENT_THOUSAND_BLADES, 15s, 22s); } } else { _thousandBladesCount = urand(2, 5); events.ScheduleEvent(EVENT_THOUSAND_BLADES, 15s, 22s); } break; } default: break; } } if (me->GetReactState() == REACT_AGGRESSIVE) DoMeleeAttackIfReady(); } private: bool _enraged; uint32 _dynamicFlags; uint8 _thousandBladesCount; GuidVector _thousandBladesTargets; }; CreatureAI* GetAI(Creature* creature) const override { return GetZulGurubAI<boss_renatakiAI>(creature); } }; void AddSC_boss_renataki() { new boss_renataki(); } <|endoftext|>
<commit_before>// // board_test.cpp // game_of_life // // Created by Chris Powell on 8/28/13. // Copyright (c) 2013 Prylis Inc. All rights reserved. // #include <iostream> #include "gtest/gtest.h" #include "../include/board.h" namespace { // The fixture for testing class Foo. class BoardTest : public ::testing::Test { protected: // You can remove any or all of the following functions if its body is empty. BoardTest() { // You can do set-up work for each test here. } virtual ~BoardTest() { // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: virtual void SetUp() { // Code here will be called immediately after the constructor (right // before each test). } virtual void TearDown() { // Code here will be called immediately after each test (right // before the destructor). } // Objects declared here can be used by all tests in the test case for Foo. }; TEST(BoardTest, testEvolution) { } TEST(BoardTest, try_2) { EXPECT_EQ(2, 2); } } <commit_msg>Some nice unit tests for cell evolution.<commit_after>// // board_test.cpp // game_of_life // // Created by Chris Powell on 8/28/13. // Copyright (c) 2013 Prylis Inc. All rights reserved. // #include <iostream> #include "gtest/gtest.h" #include "../include/board.h" namespace { // The fixture for testing class Foo. class BoardTest : public ::testing::Test { protected: // You can remove any or all of the following functions if its body is empty. BoardTest() { // You can do set-up work for each test here. } virtual ~BoardTest() { // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: virtual void SetUp() { // Code here will be called immediately after the constructor (right // before each test). } virtual void TearDown() { // Code here will be called immediately after each test (right // before the destructor). } // Objects declared here can be used by all tests in the test case for Board. Board b; }; TEST_F(BoardTest, testDeadCellShouldStayDeadForNotThreeNeighbors) { int ret = b.evolveCell(0, 0); EXPECT_EQ(0, ret); ret = b.evolveCell(0, 1); EXPECT_EQ(0, ret); ret = b.evolveCell(0, 2); EXPECT_EQ(0, ret); ret = b.evolveCell(0, 4); EXPECT_EQ(0, ret); ret = b.evolveCell(0, 5); EXPECT_EQ(0, ret); ret = b.evolveCell(0, 6); EXPECT_EQ(0, ret); ret = b.evolveCell(0, 7); EXPECT_EQ(0, ret); ret = b.evolveCell(0, 8); EXPECT_EQ(0, ret); } TEST_F(BoardTest, testDeadCellComesAliveWithThreeNeighbors) { int val = b.evolveCell(0,3); EXPECT_EQ(1, val); } TEST_F(BoardTest, testLiveCellDiesWithNotThreeNeighbors) { int val = b.evolveCell(0, 0); EXPECT_EQ(0, val); val = b.evolveCell(0, 1); EXPECT_EQ(0, val); val = b.evolveCell(0, 2); EXPECT_EQ(0, val); val = b.evolveCell(0, 4); EXPECT_EQ(0, val); val = b.evolveCell(0, 5); EXPECT_EQ(0, val); val = b.evolveCell(0, 6); EXPECT_EQ(0, val); val = b.evolveCell(0, 7); EXPECT_EQ(0, val); val = b.evolveCell(0, 8); EXPECT_EQ(0, val); val = b.evolveCell(0, 9); EXPECT_EQ(0, val); } TEST_F(BoardTest, testLiveCellStaysAliveWithThreeNeighbors) { int val = b.evolveCell(1, 3); EXPECT_EQ(1, val); } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File DriverSteadyState.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Incompressible Navier Stokes solver // /////////////////////////////////////////////////////////////////////////////// #include <SolverUtils/DriverSteadyState.h> namespace Nektar { namespace SolverUtils { string DriverSteadyState::className = GetDriverFactory().RegisterCreatorFunction("SteadyState", DriverSteadyState::create); string DriverSteadyState::driverLookupId = LibUtilities::SessionReader::RegisterEnumValue("Driver","SteadyState",0); /** * */ DriverSteadyState::DriverSteadyState(const LibUtilities::SessionReaderSharedPtr pSession) : Driver(pSession) { } /** * */ DriverSteadyState:: ~DriverSteadyState() { } /** * */ void DriverSteadyState::v_InitObject(ostream &out) { Driver::v_InitObject(out); } void DriverSteadyState::v_Execute(ostream &out) { //With a loop over "DoSolve", this Driver implements the "encaplulated" Selective Frequency Damping method //to find the steady state of a flow above the critical Reynolds number. m_equ[0]->PrintSummary(out); m_equ[0]->DoInitialise(); // - SFD Routine - NumElmVelocity = m_equ[0]->GetNumElmVelocity(); Array<OneD, Array<OneD, NekDouble> > q0(NumElmVelocity); Array<OneD, Array<OneD, NekDouble> > q1(NumElmVelocity); Array<OneD, Array<OneD, NekDouble> > qBar0(NumElmVelocity); Array<OneD, Array<OneD, NekDouble> > qBar1(NumElmVelocity); NekDouble TOL(0); m_n=0; m_Check=0; m_session->LoadParameter("FilterWidth", m_Delta0, 1); m_session->LoadParameter("ControlCoeff",m_X, 1); m_session->LoadParameter("TOL", TOL, 1.0e-08); m_session->LoadParameter("IO_InfoSteps", m_infosteps, 1000); m_session->LoadParameter("IO_CheckSteps", m_checksteps, 100000); m_Delta = m_Delta0; m_dt = m_equ[0]->GetTimeStep(); m_cst1=m_X*m_dt; m_cst2=1.0/(1.0 + m_cst1); m_cst3=m_dt/m_Delta; m_cst4=m_cst2*m_cst3; m_cst5=1.0/(1.0 + m_cst3*(1.0-m_cst1*m_cst2)); //----- Convergence History Parameters ------ m_Growing=false; m_Shrinking=false; m_MinNormDiff_q_qBar = 9999; m_MaxNormDiff_q_qBar = 0; m_First_MinNormDiff_q_qBar = 0; m_Oscillation = 0; //------------------------------------------- cout << "------------------ SFD Parameters ------------------" << endl; cout << "\tDelta = " << m_Delta << endl; cout << "\tX = " << m_X << endl; cout << "----------------------------------------------------" << endl; m_equ[0]->SetStepsToOne(); //m_steps is set to 1. Then "m_equ[0]->DoSolve()" will run for only one time step ofstream m_file("ConvergenceHistory.txt", ios::out | ios::trunc); for(int i = 0; i < NumElmVelocity; ++i) { q0[i] = Array<OneD, NekDouble> (m_equ[0]->GetTotPoints(), 0.0); qBar0[i] = Array<OneD, NekDouble> (m_equ[0]->GetTotPoints(), 0.0); } MaxNormDiff_q_qBar = 1.0; Min_MaxNormDiff_q_qBar = MaxNormDiff_q_qBar; //m_LIM0 = 1.0e-04; m_LIM0 = 1.0e-03; m_LIM = m_LIM0; while (MaxNormDiff_q_qBar > TOL) { m_equ[0]->DoSolve(); for(int i = 0; i < NumElmVelocity; ++i) { m_equ[0]->CopyFromPhysField(i, q0[i]); EvaluateNextSFDVariables(i, q0, qBar0, q1, qBar1); qBar0[i] = qBar1[i]; m_equ[0]->CopyToPhysField(i, q1[i]); } if(m_infosteps && !((m_n+1)%m_infosteps)) { ConvergenceHistory(qBar1, MaxNormDiff_q_qBar); } if(m_checksteps && m_n&&(!((m_n+1)%m_checksteps))) { m_Check++; m_equ[0]->Checkpoint_Output(m_Check); } m_n++; } cout << "\nFINAL Filter Width: Delta = " << m_Delta << "; FINAL Control Coeff: X = " << m_X << "\n" << endl; m_Check++; m_equ[0]->Checkpoint_Output(m_Check); m_file.close(); // - End SFD Routine - m_equ[0]->Output(); // Evaluate and output computation time and solution accuracy. // The specific format of the error output is essential for the // regression tests to work. // Evaluate L2 Error for(int i = 0; i < m_equ[0]->GetNvariables(); ++i) { NekDouble vL2Error = m_equ[0]->L2Error(i,false); NekDouble vLinfError = m_equ[0]->LinfError(i); if (m_comm->GetRank() == 0) { out << "L 2 error (variable " << m_equ[0]->GetVariable(i) << ") : " << vL2Error << endl; out << "L inf error (variable " << m_equ[0]->GetVariable(i) << ") : " << vLinfError << endl; } } } void DriverSteadyState::EvaluateNextSFDVariables(const int i, const Array<OneD, const Array<OneD, NekDouble> > &q0, const Array<OneD, const Array<OneD, NekDouble> > &qBar0, Array<OneD, Array<OneD, NekDouble> > &q1, Array<OneD, Array<OneD, NekDouble> > &qBar1) { q1[i] = Array<OneD, NekDouble> (m_equ[0]->GetTotPoints(),0.0); qBar1[i] = Array<OneD, NekDouble> (m_equ[0]->GetTotPoints(),0.0); Vmath::Smul(qBar1[i].num_elements(), m_cst4, q0[i], 1, qBar1[i], 1); Vmath::Vadd(qBar1[i].num_elements(), qBar0[i], 1, qBar1[i], 1, qBar1[i], 1); Vmath::Smul(qBar1[i].num_elements(), m_cst5, qBar1[i], 1, qBar1[i], 1); Vmath::Smul(q1[i].num_elements(), m_cst1, qBar1[i], 1, q1[i], 1); Vmath::Vadd(q1[i].num_elements(), q0[i], 1, q1[i], 1, q1[i], 1); Vmath::Smul(q1[i].num_elements(), m_cst2, q1[i], 1, q1[i], 1); } void DriverSteadyState::ConvergenceHistory(const Array<OneD, const Array<OneD, NekDouble> > &qBar1, NekDouble &MaxNormDiff_q_qBar) { //This routine evaluates |q-qBar|L2 and save the value in "ConvergenceHistory.txt" //Moreover, a procedure to change the parameters Delta and X after 25 oscillations of |q-qBar| is implemented Array<OneD, NekDouble > NormDiff_q_qBar(NumElmVelocity, 1.0); MaxNormDiff_q_qBar=0.0; //Norm Calculation for(int i = 0; i < NumElmVelocity; ++i) { //NormDiff_q_qBar[i] = m_equ[0]->L2Error(i, qBar1[i], false); NormDiff_q_qBar[i] = m_equ[0]->LinfError(i, qBar1[i]); if (MaxNormDiff_q_qBar < NormDiff_q_qBar[i]) { MaxNormDiff_q_qBar = m_cst1*NormDiff_q_qBar[i]; } } #if NEKTAR_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD,&MPIrank); if (MPIrank==0) { //cout << "SFD - Step: " << m_n+1 << "; Time: " << m_equ[0]->GetFinalTime() << "; |q-qBar|L2 = " << MaxNormDiff_q_qBar <<endl; cout << "SFD - Step: " << m_n+1 << "; Time: " << m_equ[0]->GetFinalTime() << "; |q-qBar|inf = " << MaxNormDiff_q_qBar <<endl; std::ofstream m_file( "ConvergenceHistory.txt", std::ios_base::app); m_file << m_n+1 << "\t" << MaxNormDiff_q_qBar << endl; m_file.close(); } #else cout << "SFD - Step: " << m_n+1 << "; Time: " << m_equ[0]->GetFinalTime() << "; |q-qBar|L2 = " << MaxNormDiff_q_qBar <<endl; std::ofstream m_file( "ConvergenceHistory.txt", std::ios_base::app); m_file << m_n+1 << "\t" << MaxNormDiff_q_qBar << endl; m_file.close(); #endif /*if (m_Shrinking==false && MaxNormDiff_q_qBar > m_MaxNormDiff_q_qBar) { m_MaxNormDiff_q_qBar=MaxNormDiff_q_qBar; m_Growing=true; if (m_MaxNormDiff_q_qBar < m_First_MinNormDiff_q_qBar) { m_Oscillation = 0; m_First_MinNormDiff_q_qBar=0; } } if (MaxNormDiff_q_qBar < m_MaxNormDiff_q_qBar && m_Growing==true) { m_Growing=false; m_MaxNormDiff_q_qBar=0; } if (m_Growing==false && MaxNormDiff_q_qBar < m_MinNormDiff_q_qBar) { m_MinNormDiff_q_qBar=MaxNormDiff_q_qBar; m_Shrinking=true; if (m_Oscillation==0) { m_First_MinNormDiff_q_qBar=m_MinNormDiff_q_qBar; } } if (MaxNormDiff_q_qBar > m_MinNormDiff_q_qBar && m_Shrinking==true) { m_Shrinking=false; m_MinNormDiff_q_qBar=1000; m_Oscillation=m_Oscillation+1; } if (m_Oscillation==25) { m_Delta = m_Delta + 0.25; m_X = 0.99*(1.0/m_Delta); m_cst1=m_X*m_dt; m_cst2=1.0/(1.0 + m_cst1); m_cst3=m_dt/m_Delta; m_cst4=m_cst2*m_cst3; m_cst5=1.0/(1.0 + m_cst3*(1.0-m_cst1*m_cst2)); cout << "\nNew Filter Width: Delta = " << m_Delta << "; New Control Coeff: X = " << m_X << "\n" << endl; m_Oscillation=0; m_equ[0]->DoInitialise(); }*/ if (MaxNormDiff_q_qBar < Min_MaxNormDiff_q_qBar) { Min_MaxNormDiff_q_qBar = MaxNormDiff_q_qBar; } if (MaxNormDiff_q_qBar < m_LIM) { m_Delta = m_Delta + 0.5; m_X = 0.99*(1.0/m_Delta); m_cst1=m_X*m_dt; m_cst2=1.0/(1.0 + m_cst1); m_cst3=m_dt/m_Delta; m_cst4=m_cst2*m_cst3; m_cst5=1.0/(1.0 + m_cst3*(1.0-m_cst1*m_cst2)); cout << "\nNew Filter Width: Delta = " << m_Delta << "; New Control Coeff: X = " << m_X << "\n" << endl; //m_LIM = m_LIM/10.0; m_LIM = m_LIM/2.0; } if (MaxNormDiff_q_qBar > 5.0*Min_MaxNormDiff_q_qBar) // It means that the algo has failed to converge { Min_MaxNormDiff_q_qBar = 1.0; m_Delta0 = m_Delta0 + 0.5; m_Delta = m_Delta0; m_X = 0.99*(1.0/m_Delta); m_cst1=m_X*m_dt; m_cst2=1.0/(1.0 + m_cst1); m_cst3=m_dt/m_Delta; m_cst4=m_cst2*m_cst3; m_cst5=1.0/(1.0 + m_cst3*(1.0-m_cst1*m_cst2)); cout << "\nThe problem is reinitialized: New Filter Width: Delta = " << m_Delta << "; New Control Coeff: X = " << m_X << "\n" << endl; m_LIM = m_LIM0; m_equ[0]->DoInitialise(); } } } } <commit_msg>bug fixed (parameters SFD)<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File DriverSteadyState.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Incompressible Navier Stokes solver // /////////////////////////////////////////////////////////////////////////////// #include <SolverUtils/DriverSteadyState.h> namespace Nektar { namespace SolverUtils { string DriverSteadyState::className = GetDriverFactory().RegisterCreatorFunction("SteadyState", DriverSteadyState::create); string DriverSteadyState::driverLookupId = LibUtilities::SessionReader::RegisterEnumValue("Driver","SteadyState",0); /** * */ DriverSteadyState::DriverSteadyState(const LibUtilities::SessionReaderSharedPtr pSession) : Driver(pSession) { } /** * */ DriverSteadyState:: ~DriverSteadyState() { } /** * */ void DriverSteadyState::v_InitObject(ostream &out) { Driver::v_InitObject(out); } void DriverSteadyState::v_Execute(ostream &out) { //With a loop over "DoSolve", this Driver implements the "encaplulated" Selective Frequency Damping method //to find the steady state of a flow above the critical Reynolds number. m_equ[0]->PrintSummary(out); m_equ[0]->DoInitialise(); // - SFD Routine - NumElmVelocity = m_equ[0]->GetNumElmVelocity(); Array<OneD, Array<OneD, NekDouble> > q0(NumElmVelocity); Array<OneD, Array<OneD, NekDouble> > q1(NumElmVelocity); Array<OneD, Array<OneD, NekDouble> > qBar0(NumElmVelocity); Array<OneD, Array<OneD, NekDouble> > qBar1(NumElmVelocity); NekDouble TOL(0); m_n=0; m_Check=0; m_session->LoadParameter("FilterWidth", m_Delta0, 1); m_session->LoadParameter("ControlCoeff",m_X, 1); m_session->LoadParameter("TOL", TOL, 1.0e-08); m_session->LoadParameter("IO_InfoSteps", m_infosteps, 1000); m_session->LoadParameter("IO_CheckSteps", m_checksteps, 100000); m_Delta = m_Delta0; m_dt = m_equ[0]->GetTimeStep(); m_cst1=m_X*m_dt; m_cst2=1.0/(1.0 + m_cst1); m_cst3=m_dt/m_Delta; m_cst4=m_cst2*m_cst3; m_cst5=1.0/(1.0 + m_cst3*(1.0-m_cst1*m_cst2)); //----- Convergence History Parameters ------ m_Growing=false; m_Shrinking=false; m_MinNormDiff_q_qBar = 9999; m_MaxNormDiff_q_qBar = 0; m_First_MinNormDiff_q_qBar = 0; m_Oscillation = 0; //------------------------------------------- cout << "------------------ SFD Parameters ------------------" << endl; cout << "\tDelta = " << m_Delta << endl; cout << "\tX = " << m_X << endl; cout << "----------------------------------------------------" << endl; m_equ[0]->SetStepsToOne(); //m_steps is set to 1. Then "m_equ[0]->DoSolve()" will run for only one time step ofstream m_file("ConvergenceHistory.txt", ios::out | ios::trunc); for(int i = 0; i < NumElmVelocity; ++i) { q0[i] = Array<OneD, NekDouble> (m_equ[0]->GetTotPoints(), 0.0); qBar0[i] = Array<OneD, NekDouble> (m_equ[0]->GetTotPoints(), 0.0); } MaxNormDiff_q_qBar = 1.0; Min_MaxNormDiff_q_qBar = MaxNormDiff_q_qBar; //m_LIM0 = 1.0e-04; m_LIM0 = 1.0e-03; m_LIM = m_LIM0; while (MaxNormDiff_q_qBar > TOL) { m_equ[0]->DoSolve(); for(int i = 0; i < NumElmVelocity; ++i) { m_equ[0]->CopyFromPhysField(i, q0[i]); EvaluateNextSFDVariables(i, q0, qBar0, q1, qBar1); qBar0[i] = qBar1[i]; m_equ[0]->CopyToPhysField(i, q1[i]); } if(m_infosteps && !((m_n+1)%m_infosteps)) { ConvergenceHistory(qBar1, MaxNormDiff_q_qBar); } if(m_checksteps && m_n&&(!((m_n+1)%m_checksteps))) { m_Check++; m_equ[0]->Checkpoint_Output(m_Check); } m_n++; } cout << "\nFINAL Filter Width: Delta = " << m_Delta << "; FINAL Control Coeff: X = " << m_X << "\n" << endl; m_Check++; m_equ[0]->Checkpoint_Output(m_Check); m_file.close(); // - End SFD Routine - m_equ[0]->Output(); // Evaluate and output computation time and solution accuracy. // The specific format of the error output is essential for the // regression tests to work. // Evaluate L2 Error for(int i = 0; i < m_equ[0]->GetNvariables(); ++i) { NekDouble vL2Error = m_equ[0]->L2Error(i,false); NekDouble vLinfError = m_equ[0]->LinfError(i); if (m_comm->GetRank() == 0) { out << "L 2 error (variable " << m_equ[0]->GetVariable(i) << ") : " << vL2Error << endl; out << "L inf error (variable " << m_equ[0]->GetVariable(i) << ") : " << vLinfError << endl; } } } void DriverSteadyState::EvaluateNextSFDVariables(const int i, const Array<OneD, const Array<OneD, NekDouble> > &q0, const Array<OneD, const Array<OneD, NekDouble> > &qBar0, Array<OneD, Array<OneD, NekDouble> > &q1, Array<OneD, Array<OneD, NekDouble> > &qBar1) { q1[i] = Array<OneD, NekDouble> (m_equ[0]->GetTotPoints(),0.0); qBar1[i] = Array<OneD, NekDouble> (m_equ[0]->GetTotPoints(),0.0); Vmath::Smul(qBar1[i].num_elements(), m_cst4, q0[i], 1, qBar1[i], 1); Vmath::Vadd(qBar1[i].num_elements(), qBar0[i], 1, qBar1[i], 1, qBar1[i], 1); Vmath::Smul(qBar1[i].num_elements(), m_cst5, qBar1[i], 1, qBar1[i], 1); Vmath::Smul(q1[i].num_elements(), m_cst1, qBar1[i], 1, q1[i], 1); Vmath::Vadd(q1[i].num_elements(), q0[i], 1, q1[i], 1, q1[i], 1); Vmath::Smul(q1[i].num_elements(), m_cst2, q1[i], 1, q1[i], 1); } void DriverSteadyState::ConvergenceHistory(const Array<OneD, const Array<OneD, NekDouble> > &qBar1, NekDouble &MaxNormDiff_q_qBar) { //This routine evaluates |q-qBar|L2 and save the value in "ConvergenceHistory.txt" //Moreover, a procedure to change the parameters Delta and X after 25 oscillations of |q-qBar| is implemented Array<OneD, NekDouble > NormDiff_q_qBar(NumElmVelocity, 1.0); MaxNormDiff_q_qBar=0.0; //Norm Calculation for(int i = 0; i < NumElmVelocity; ++i) { //NormDiff_q_qBar[i] = m_equ[0]->L2Error(i, qBar1[i], false); NormDiff_q_qBar[i] = m_equ[0]->LinfError(i, qBar1[i]); if (MaxNormDiff_q_qBar < NormDiff_q_qBar[i]) { MaxNormDiff_q_qBar = m_cst1*NormDiff_q_qBar[i]; } } #if NEKTAR_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD,&MPIrank); if (MPIrank==0) { //cout << "SFD - Step: " << m_n+1 << "; Time: " << m_equ[0]->GetFinalTime() << "; |q-qBar|L2 = " << MaxNormDiff_q_qBar <<endl; cout << "SFD - Step: " << m_n+1 << "; Time: " << m_equ[0]->GetFinalTime() << "; |q-qBar|inf = " << MaxNormDiff_q_qBar <<endl; std::ofstream m_file( "ConvergenceHistory.txt", std::ios_base::app); m_file << m_n+1 << "\t" << MaxNormDiff_q_qBar << endl; m_file.close(); } #else cout << "SFD - Step: " << m_n+1 << "; Time: " << m_equ[0]->GetFinalTime() << "; |q-qBar|L2 = " << MaxNormDiff_q_qBar <<endl; std::ofstream m_file( "ConvergenceHistory.txt", std::ios_base::app); m_file << m_n+1 << "\t" << MaxNormDiff_q_qBar << endl; m_file.close(); #endif /*if (m_Shrinking==false && MaxNormDiff_q_qBar > m_MaxNormDiff_q_qBar) { m_MaxNormDiff_q_qBar=MaxNormDiff_q_qBar; m_Growing=true; if (m_MaxNormDiff_q_qBar < m_First_MinNormDiff_q_qBar) { m_Oscillation = 0; m_First_MinNormDiff_q_qBar=0; } } if (MaxNormDiff_q_qBar < m_MaxNormDiff_q_qBar && m_Growing==true) { m_Growing=false; m_MaxNormDiff_q_qBar=0; } if (m_Growing==false && MaxNormDiff_q_qBar < m_MinNormDiff_q_qBar) { m_MinNormDiff_q_qBar=MaxNormDiff_q_qBar; m_Shrinking=true; if (m_Oscillation==0) { m_First_MinNormDiff_q_qBar=m_MinNormDiff_q_qBar; } } if (MaxNormDiff_q_qBar > m_MinNormDiff_q_qBar && m_Shrinking==true) { m_Shrinking=false; m_MinNormDiff_q_qBar=1000; m_Oscillation=m_Oscillation+1; } if (m_Oscillation==25) { m_Delta = m_Delta + 0.25; m_X = 0.99*(1.0/m_Delta); m_cst1=m_X*m_dt; m_cst2=1.0/(1.0 + m_cst1); m_cst3=m_dt/m_Delta; m_cst4=m_cst2*m_cst3; m_cst5=1.0/(1.0 + m_cst3*(1.0-m_cst1*m_cst2)); cout << "\nNew Filter Width: Delta = " << m_Delta << "; New Control Coeff: X = " << m_X << "\n" << endl; m_Oscillation=0; m_equ[0]->DoInitialise(); }*/ if (MaxNormDiff_q_qBar < Min_MaxNormDiff_q_qBar) { Min_MaxNormDiff_q_qBar = MaxNormDiff_q_qBar; } if (MaxNormDiff_q_qBar < m_LIM) { m_Delta = m_Delta + 0.5; m_X = 0.99*(1.0/m_Delta); m_cst1=m_X*m_dt; m_cst2=1.0/(1.0 + m_cst1); m_cst3=m_dt/m_Delta; m_cst4=m_cst2*m_cst3; m_cst5=1.0/(1.0 + m_cst3*(1.0-m_cst1*m_cst2)); cout << "\nNew Filter Width: Delta = " << m_Delta << "; New Control Coeff: X = " << m_X << "\n" << endl; //m_LIM = m_LIM/10.0; m_LIM = m_LIM/5.0; } if (MaxNormDiff_q_qBar > 2.0*Min_MaxNormDiff_q_qBar) // It means that the algo has failed to converge { Min_MaxNormDiff_q_qBar = 1.0; m_Delta0 = m_Delta0 + 0.5; m_Delta = m_Delta0; m_X = 0.99*(1.0/m_Delta); m_cst1=m_X*m_dt; m_cst2=1.0/(1.0 + m_cst1); m_cst3=m_dt/m_Delta; m_cst4=m_cst2*m_cst3; m_cst5=1.0/(1.0 + m_cst3*(1.0-m_cst1*m_cst2)); cout << "\nThe problem is reinitialized: New Filter Width: Delta = " << m_Delta << "; New Control Coeff: X = " << m_X << "\n" << endl; m_LIM = m_LIM0; m_equ[0]->DoInitialise(); } } } } <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the QtMediaHub project on http://www.gitorious.org. Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Nokia Corporation ([email protected])** You may use this file under the terms of the BSD license as follows: "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ****************************************************************************/ #include "backend.h" #include "qmhplugin.h" #include "qmh-config.h" #include "rpc/rpcconnection.h" #include "skin.h" #ifdef QMH_AVAHI #include "qavahiservicebrowsermodel.h" #endif #include <QDir> #include <QString> #include <QPluginLoader> #include <QCoreApplication> #include <QVariant> #include <QFileSystemModel> #include <QDesktopServices> #include <QFileSystemWatcher> #ifdef GL #include <QGLFormat> #endif #include <QDebug> Backend* Backend::pSelf = 0; class BackendPrivate : public QObject { Q_OBJECT public: BackendPrivate(Backend *p) : QObject(p), #ifdef Q_OS_MAC platformOffset("/../../.."), #endif basePath(QCoreApplication::applicationDirPath() + platformOffset), // Use "large" instead of appName to fit freedesktop spec thumbnailPath(Config::value("thumbnail-path", QDir::homePath() + "/.thumbnails/" + qApp->applicationName() + "/")), inputIdleTimer(this), backendTranslator(0), logFile(qApp->applicationName().append(".log")), targetsModel(0), pSelf(p) { // TODO: check install prefix skinPaths << "/usr/share/qtmediahub/skins/"; skinPaths << QDir::homePath() + "/.qtmediahub/skins/"; skinPaths << QDir(Config::value("skins", QString(basePath % "/skins"))).absolutePath(); if (!qgetenv("QMH_SKINPATH").isEmpty()) skinPaths << QDir(qgetenv("QMH_SKINPATH")).absolutePath(); pluginPath = QDir(Config::value("plugins", QString(basePath % "/plugins"))).absolutePath(); if (!qgetenv("QMH_PLUGINPATH").isEmpty()) resourcePath = QDir(qgetenv("QMH_PLUGINPATH")).absolutePath(); else resourcePath = QDir(Config::value("resources", QString(basePath % "/resources"))).absolutePath(); inputIdleTimer.setInterval(Config::value("idle-timeout", 120)*1000); inputIdleTimer.setSingleShot(true); inputIdleTimer.start(); connect(&inputIdleTimer, SIGNAL(timeout()), pSelf, SIGNAL(inputIdle())); logFile.open(QIODevice::Text|QIODevice::ReadWrite); log.setDevice(&logFile); connect(&pathMonitor, SIGNAL(directoryChanged(const QString &)), this, SLOT(handleDirChanged(const QString &))); foreach (QString skinPath, skinPaths) { if (QDir(skinPath).exists()) pathMonitor.addPath(skinPath); } pathMonitor.addPath(pluginPath); QFileInfo thumbnailFolderInfo(thumbnailPath); if (!thumbnailFolderInfo.exists()) { QDir dir; dir.mkpath(thumbnailFolderInfo.absoluteFilePath()); } discoverSkins(); } ~BackendPrivate() { delete backendTranslator; backendTranslator = 0; qDeleteAll(pluginTranslators.begin(), pluginTranslators.end()); } public slots: void handleDirChanged(const QString &dir); public: void resetLanguage(); void discoverSkins(); void discoverEngines(); QSet<QString> advertizedEngineRoles; QList<QObject*> advertizedEngines; QList<QMHPlugin*> allEngines; const QString platformOffset; const QString basePath; QString pluginPath; QString resourcePath; const QString thumbnailPath; QStringList skinPaths; QList<QObject *> skins; QTimer inputIdleTimer; QTranslator *backendTranslator; QList<QTranslator*> pluginTranslators; QFile logFile; QTextStream log; QFileSystemWatcher pathMonitor; QAbstractItemModel *targetsModel; #if defined(Q_WS_S60) || defined(Q_WS_MAEMO) QNetworkConfigurationManager mgr; QNetworkSession *session; #endif Backend *pSelf; }; void BackendPrivate::handleDirChanged(const QString &dir) { if(dir == pluginPath) { qWarning() << "Changes in plugin path, probably about to eat your poodle"; discoverEngines(); } else if(skinPaths.contains(dir)) { qWarning() << "Changes in skin path, repopulating skins"; discoverSkins(); } } void BackendPrivate::resetLanguage() { static QString baseTranslationPath(basePath % "/translations/"); const QString language = Backend::instance()->language(); delete backendTranslator; backendTranslator = new QTranslator(this); backendTranslator->load(baseTranslationPath % language % ".qm"); qApp->installTranslator(backendTranslator); qDeleteAll(pluginTranslators.begin(), pluginTranslators.end()); //FixMe: translation should be tied to filename (not role!) /* foreach(QMHPlugin *plugin, allEngines) { QTranslator *pluginTranslator = new QTranslator(this); pluginTranslator->load(baseTranslationPath % plugin->role() % "_" % language % ".qm"); pluginTranslators << pluginTranslator; qApp->installTranslator(pluginTranslator); }*/ } void BackendPrivate::discoverSkins() { qDeleteAll(skins); skins.clear(); foreach (QString skinPath, skinPaths) { QStringList potentialSkins = QDir(skinPath).entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach(const QString &currentPath, potentialSkins) { if(QFile(skinPath % "/" % currentPath % "/" % currentPath).exists()) { Skin *skin = new Skin(currentPath, skinPath % "/" % currentPath % "/", this); skins << skin; } } } qWarning() << "Available skins:"; foreach(QObject *skin, skins) qWarning() << "\t" << qobject_cast<Skin*>(skin)->name(); } void BackendPrivate::discoverEngines() { foreach(const QString fileName, QDir(pluginPath).entryList(QDir::Files)) { QString qualifiedFileName(pluginPath % "/" % fileName); QPluginLoader pluginLoader(qualifiedFileName); if (!pluginLoader.load()) { qWarning() << tr("Cant load plugin: %1 returns %2").arg(qualifiedFileName).arg(pluginLoader.errorString()); continue; } QMHPlugin *plugin = qobject_cast<QMHPlugin*>(pluginLoader.instance()); if (!plugin) qWarning() << tr("Invalid QMH plugin present: %1").arg(qualifiedFileName); else if (!plugin->dependenciesSatisfied()) qWarning() << tr("Can't meet dependencies for %1").arg(qualifiedFileName); else if (plugin->role() < QMHPlugin::Unadvertized || plugin->role() >= QMHPlugin::RoleCount) qWarning() << tr("Plugin %1 has an undefined role").arg(qualifiedFileName); else { plugin->setParent(this); allEngines << plugin; Backend::instance()->advertizeEngine(plugin); } } resetLanguage(); } Backend::Backend(QObject *parent) : QObject(parent), d(new BackendPrivate(this)) { #if defined(Q_WS_S60) || defined(Q_WS_MAEMO) // Set Internet Access Point QList<QNetworkConfiguration> activeConfigs = d->mgr.allConfigurations(); if (activeConfigs.count() <= 0) return; QNetworkConfiguration cfg = activeConfigs.at(0); foreach(QNetworkConfiguration config, activeConfigs) { if (config.type() == QNetworkConfiguration::UserChoice) { cfg = config; break; } } session = new QNetworkSession(cfg); session->open(); if (!session->waitForOpened(-1)) return; #endif QString dejavuPath(d->resourcePath % "/3rdparty/dejavu-fonts-ttf-2.32/ttf/"); if (QDir(dejavuPath).exists()) { QFontDatabase::addApplicationFont(dejavuPath % "DejaVuSans.ttf"); QFontDatabase::addApplicationFont(dejavuPath % "DejaVuSans-Bold.ttf"); QFontDatabase::addApplicationFont(dejavuPath % "DejaVuSans-Oblique.ttf"); QFontDatabase::addApplicationFont(dejavuPath % "DejaVuSans-BoldOblique.ttf"); QApplication::setFont(QFont("DejaVu Sans")); } } Backend::~Backend() { #if defined(Q_WS_S60) || defined(Q_WS_MAEMO) session->close(); #endif delete d; d = 0; } void Backend::initialize() { d->discoverEngines(); } QString Backend::language() const { //FIXME: derive from locale //Allow override return QString(); //Bob is a testing translation placeholder //return QString("bob"); } QList<QMHPlugin *> Backend::allEngines() const { return d->allEngines; } QList<QObject *> Backend::advertizedEngines() const { return d->advertizedEngines; } QList<QObject *> Backend::skins() const { return d->skins; } Backend* Backend::instance() { if (!pSelf) { pSelf = new Backend(); } return pSelf; } void Backend::destroy() { delete pSelf; pSelf = 0; } QString Backend::basePath() const { return d->basePath; } QString Backend::pluginPath() const { return d->pluginPath; } QString Backend::resourcePath() const { return d->resourcePath; } QString Backend::thumbnailPath() const { return d->thumbnailPath; } bool Backend::transforms() const { #ifdef GL return (QGLFormat::hasOpenGL() && Config::isEnabled("transforms", true)); #else return false; #endif } void Backend::advertizeEngine(QMHPlugin *engine) { //Advertize to main menu if (engine->role() > QMHPlugin::Unadvertized) d->advertizedEngines << engine; connect(engine, SIGNAL(pluginChanged()), this, SIGNAL(advertizedEnginesChanged())); emit advertizedEnginesChanged(); } void Backend::openUrlExternally(const QUrl & url) const { QDesktopServices::openUrl(url); } void Backend::log(const QString &logMsg) { qDebug() << logMsg; d->log << logMsg << endl; } bool Backend::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease || event->type() == QEvent::MouseMove || event->type() == QEvent::MouseButtonPress) { d->inputIdleTimer.start(); } return QObject::eventFilter(obj, event); } QObject *Backend::engineByRole(QMHPlugin::PluginRole role) { foreach (QObject *currentEngine, d->advertizedEngines) if (qobject_cast<QMHPlugin*>(currentEngine)->role() == role) return currentEngine; qWarning() << tr("Seeking a non-existant plugin, prepare to die"); return 0; } QObject *Backend::engineByName(const QString &name) { foreach (QObject *currentEngine, d->allEngines) if (qobject_cast<QMHPlugin*>(currentEngine)->name() == name) return currentEngine; return 0; } QObject *Backend::targetsModel() const { if (!d->targetsModel) { #ifdef QMH_AVAHI QAvahiServiceBrowserModel *model = new QAvahiServiceBrowserModel(const_cast<Backend *>(this)); model->setAutoResolve(true); model->browse("_qmh._tcp", QAvahiServiceBrowserModel::HideIPv6 | QAvahiServiceBrowserModel::HideLocal); d->targetsModel = model; #else d->targetsModel = new QStandardItemModel(const_cast<Backend *>(this)); #endif } return d->targetsModel; } #include "backend.moc" <commit_msg>resource path should use the QMH_RESOURCEPATH env variable<commit_after>/**************************************************************************** This file is part of the QtMediaHub project on http://www.gitorious.org. Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Nokia Corporation ([email protected])** You may use this file under the terms of the BSD license as follows: "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ****************************************************************************/ #include "backend.h" #include "qmhplugin.h" #include "qmh-config.h" #include "rpc/rpcconnection.h" #include "skin.h" #ifdef QMH_AVAHI #include "qavahiservicebrowsermodel.h" #endif #include <QDir> #include <QString> #include <QPluginLoader> #include <QCoreApplication> #include <QVariant> #include <QFileSystemModel> #include <QDesktopServices> #include <QFileSystemWatcher> #ifdef GL #include <QGLFormat> #endif #include <QDebug> Backend* Backend::pSelf = 0; class BackendPrivate : public QObject { Q_OBJECT public: BackendPrivate(Backend *p) : QObject(p), #ifdef Q_OS_MAC platformOffset("/../../.."), #endif basePath(QCoreApplication::applicationDirPath() + platformOffset), // Use "large" instead of appName to fit freedesktop spec thumbnailPath(Config::value("thumbnail-path", QDir::homePath() + "/.thumbnails/" + qApp->applicationName() + "/")), inputIdleTimer(this), backendTranslator(0), logFile(qApp->applicationName().append(".log")), targetsModel(0), pSelf(p) { // TODO: check install prefix skinPaths << "/usr/share/qtmediahub/skins/"; skinPaths << QDir::homePath() + "/.qtmediahub/skins/"; skinPaths << QDir(Config::value("skins", QString(basePath % "/skins"))).absolutePath(); if (!qgetenv("QMH_SKINPATH").isEmpty()) skinPaths << QDir(qgetenv("QMH_SKINPATH")).absolutePath(); pluginPath = QDir(Config::value("plugins", QString(basePath % "/plugins"))).absolutePath(); if (!qgetenv("QMH_RESOURCEPATH").isEmpty()) resourcePath = QDir(qgetenv("QMH_RESOURCEPATH")).absolutePath(); else resourcePath = QDir(Config::value("resources", QString(basePath % "/resources"))).absolutePath(); inputIdleTimer.setInterval(Config::value("idle-timeout", 120)*1000); inputIdleTimer.setSingleShot(true); inputIdleTimer.start(); connect(&inputIdleTimer, SIGNAL(timeout()), pSelf, SIGNAL(inputIdle())); logFile.open(QIODevice::Text|QIODevice::ReadWrite); log.setDevice(&logFile); connect(&pathMonitor, SIGNAL(directoryChanged(const QString &)), this, SLOT(handleDirChanged(const QString &))); foreach (QString skinPath, skinPaths) { if (QDir(skinPath).exists()) pathMonitor.addPath(skinPath); } pathMonitor.addPath(pluginPath); QFileInfo thumbnailFolderInfo(thumbnailPath); if (!thumbnailFolderInfo.exists()) { QDir dir; dir.mkpath(thumbnailFolderInfo.absoluteFilePath()); } discoverSkins(); } ~BackendPrivate() { delete backendTranslator; backendTranslator = 0; qDeleteAll(pluginTranslators.begin(), pluginTranslators.end()); } public slots: void handleDirChanged(const QString &dir); public: void resetLanguage(); void discoverSkins(); void discoverEngines(); QSet<QString> advertizedEngineRoles; QList<QObject*> advertizedEngines; QList<QMHPlugin*> allEngines; const QString platformOffset; const QString basePath; QString pluginPath; QString resourcePath; const QString thumbnailPath; QStringList skinPaths; QList<QObject *> skins; QTimer inputIdleTimer; QTranslator *backendTranslator; QList<QTranslator*> pluginTranslators; QFile logFile; QTextStream log; QFileSystemWatcher pathMonitor; QAbstractItemModel *targetsModel; #if defined(Q_WS_S60) || defined(Q_WS_MAEMO) QNetworkConfigurationManager mgr; QNetworkSession *session; #endif Backend *pSelf; }; void BackendPrivate::handleDirChanged(const QString &dir) { if(dir == pluginPath) { qWarning() << "Changes in plugin path, probably about to eat your poodle"; discoverEngines(); } else if(skinPaths.contains(dir)) { qWarning() << "Changes in skin path, repopulating skins"; discoverSkins(); } } void BackendPrivate::resetLanguage() { static QString baseTranslationPath(basePath % "/translations/"); const QString language = Backend::instance()->language(); delete backendTranslator; backendTranslator = new QTranslator(this); backendTranslator->load(baseTranslationPath % language % ".qm"); qApp->installTranslator(backendTranslator); qDeleteAll(pluginTranslators.begin(), pluginTranslators.end()); //FixMe: translation should be tied to filename (not role!) /* foreach(QMHPlugin *plugin, allEngines) { QTranslator *pluginTranslator = new QTranslator(this); pluginTranslator->load(baseTranslationPath % plugin->role() % "_" % language % ".qm"); pluginTranslators << pluginTranslator; qApp->installTranslator(pluginTranslator); }*/ } void BackendPrivate::discoverSkins() { qDeleteAll(skins); skins.clear(); foreach (QString skinPath, skinPaths) { QStringList potentialSkins = QDir(skinPath).entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach(const QString &currentPath, potentialSkins) { if(QFile(skinPath % "/" % currentPath % "/" % currentPath).exists()) { Skin *skin = new Skin(currentPath, skinPath % "/" % currentPath % "/", this); skins << skin; } } } qWarning() << "Available skins:"; foreach(QObject *skin, skins) qWarning() << "\t" << qobject_cast<Skin*>(skin)->name(); } void BackendPrivate::discoverEngines() { foreach(const QString fileName, QDir(pluginPath).entryList(QDir::Files)) { QString qualifiedFileName(pluginPath % "/" % fileName); QPluginLoader pluginLoader(qualifiedFileName); if (!pluginLoader.load()) { qWarning() << tr("Cant load plugin: %1 returns %2").arg(qualifiedFileName).arg(pluginLoader.errorString()); continue; } QMHPlugin *plugin = qobject_cast<QMHPlugin*>(pluginLoader.instance()); if (!plugin) qWarning() << tr("Invalid QMH plugin present: %1").arg(qualifiedFileName); else if (!plugin->dependenciesSatisfied()) qWarning() << tr("Can't meet dependencies for %1").arg(qualifiedFileName); else if (plugin->role() < QMHPlugin::Unadvertized || plugin->role() >= QMHPlugin::RoleCount) qWarning() << tr("Plugin %1 has an undefined role").arg(qualifiedFileName); else { plugin->setParent(this); allEngines << plugin; Backend::instance()->advertizeEngine(plugin); } } resetLanguage(); } Backend::Backend(QObject *parent) : QObject(parent), d(new BackendPrivate(this)) { #if defined(Q_WS_S60) || defined(Q_WS_MAEMO) // Set Internet Access Point QList<QNetworkConfiguration> activeConfigs = d->mgr.allConfigurations(); if (activeConfigs.count() <= 0) return; QNetworkConfiguration cfg = activeConfigs.at(0); foreach(QNetworkConfiguration config, activeConfigs) { if (config.type() == QNetworkConfiguration::UserChoice) { cfg = config; break; } } session = new QNetworkSession(cfg); session->open(); if (!session->waitForOpened(-1)) return; #endif QString dejavuPath(d->resourcePath % "/3rdparty/dejavu-fonts-ttf-2.32/ttf/"); if (QDir(dejavuPath).exists()) { QFontDatabase::addApplicationFont(dejavuPath % "DejaVuSans.ttf"); QFontDatabase::addApplicationFont(dejavuPath % "DejaVuSans-Bold.ttf"); QFontDatabase::addApplicationFont(dejavuPath % "DejaVuSans-Oblique.ttf"); QFontDatabase::addApplicationFont(dejavuPath % "DejaVuSans-BoldOblique.ttf"); QApplication::setFont(QFont("DejaVu Sans")); } } Backend::~Backend() { #if defined(Q_WS_S60) || defined(Q_WS_MAEMO) session->close(); #endif delete d; d = 0; } void Backend::initialize() { d->discoverEngines(); } QString Backend::language() const { //FIXME: derive from locale //Allow override return QString(); //Bob is a testing translation placeholder //return QString("bob"); } QList<QMHPlugin *> Backend::allEngines() const { return d->allEngines; } QList<QObject *> Backend::advertizedEngines() const { return d->advertizedEngines; } QList<QObject *> Backend::skins() const { return d->skins; } Backend* Backend::instance() { if (!pSelf) { pSelf = new Backend(); } return pSelf; } void Backend::destroy() { delete pSelf; pSelf = 0; } QString Backend::basePath() const { return d->basePath; } QString Backend::pluginPath() const { return d->pluginPath; } QString Backend::resourcePath() const { return d->resourcePath; } QString Backend::thumbnailPath() const { return d->thumbnailPath; } bool Backend::transforms() const { #ifdef GL return (QGLFormat::hasOpenGL() && Config::isEnabled("transforms", true)); #else return false; #endif } void Backend::advertizeEngine(QMHPlugin *engine) { //Advertize to main menu if (engine->role() > QMHPlugin::Unadvertized) d->advertizedEngines << engine; connect(engine, SIGNAL(pluginChanged()), this, SIGNAL(advertizedEnginesChanged())); emit advertizedEnginesChanged(); } void Backend::openUrlExternally(const QUrl & url) const { QDesktopServices::openUrl(url); } void Backend::log(const QString &logMsg) { qDebug() << logMsg; d->log << logMsg << endl; } bool Backend::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease || event->type() == QEvent::MouseMove || event->type() == QEvent::MouseButtonPress) { d->inputIdleTimer.start(); } return QObject::eventFilter(obj, event); } QObject *Backend::engineByRole(QMHPlugin::PluginRole role) { foreach (QObject *currentEngine, d->advertizedEngines) if (qobject_cast<QMHPlugin*>(currentEngine)->role() == role) return currentEngine; qWarning() << tr("Seeking a non-existant plugin, prepare to die"); return 0; } QObject *Backend::engineByName(const QString &name) { foreach (QObject *currentEngine, d->allEngines) if (qobject_cast<QMHPlugin*>(currentEngine)->name() == name) return currentEngine; return 0; } QObject *Backend::targetsModel() const { if (!d->targetsModel) { #ifdef QMH_AVAHI QAvahiServiceBrowserModel *model = new QAvahiServiceBrowserModel(const_cast<Backend *>(this)); model->setAutoResolve(true); model->browse("_qmh._tcp", QAvahiServiceBrowserModel::HideIPv6 | QAvahiServiceBrowserModel::HideLocal); d->targetsModel = model; #else d->targetsModel = new QStandardItemModel(const_cast<Backend *>(this)); #endif } return d->targetsModel; } #include "backend.moc" <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the QtMediaHub project on http://www.gitorious.org. Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Nokia Corporation ([email protected])** You may use this file under the terms of the BSD license as follows: "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ****************************************************************************/ #include "backend.h" #include "plugins/qmhplugininterface.h" #include "plugins/qmhplugin.h" #include "dataproviders/proxymodel.h" #include "dataproviders/dirmodel.h" #include "dataproviders/modelindexiterator.h" #include "qmh-config.h" #include "qml-extensions/qmlfilewrapper.h" #include "qml-extensions/actionmapper.h" #include "dataproviders/playlist.h" #include <QDir> #include <QString> #include <QPluginLoader> #include <QCoreApplication> #include <QVariant> #include <QFileSystemModel> #include <QDesktopServices> #include <QFileSystemWatcher> #ifdef GL #include <QGLFormat> #endif #include <QDebug> Backend* Backend::pSelf = 0; class BackendPrivate : public QObject { Q_OBJECT public: BackendPrivate(Backend *p) : QObject(p), #ifdef Q_OS_MAC platformOffset("/../../.."), #endif basePath(QCoreApplication::applicationDirPath() + platformOffset), skinPath(basePath % "/skins"), pluginPath(basePath % "/plugins"), resourcePath(basePath % "/resources"), // Use "large" instead of appName to fit freedesktop spec thumbnailPath(Config::value("thumbnail-path", QDir::homePath() + "/.thumbnails/" + qApp->applicationName() + "/")), inputIdleTimer(this), qmlEngine(0), backendTranslator(0), logFile(qApp->applicationName().append(".log")), pSelf(p) { qApp->installEventFilter(this); inputIdleTimer.setInterval(Config::value("idle-timeout", 120*1000)); inputIdleTimer.setSingleShot(true); inputIdleTimer.start(); connect(&inputIdleTimer, SIGNAL(timeout()), pSelf, SIGNAL(inputIdle())); logFile.open(QIODevice::Text|QIODevice::ReadWrite); log.setDevice(&logFile); connect(&resourcePathMonitor, SIGNAL(directoryChanged(const QString &)), this, SLOT(handleDirChanged(const QString &))); resourcePathMonitor.addPath(skinPath); resourcePathMonitor.addPath(pluginPath); discoverSkins(); } ~BackendPrivate() { delete backendTranslator; backendTranslator = 0; qDeleteAll(pluginTranslators.begin(), pluginTranslators.end()); } public slots: void handleDirChanged(const QString &dir); public: void resetLanguage(); void discoverSkins(); void discoverEngines(); bool eventFilter(QObject *obj, QEvent *event); QSet<QString> advertizedEngineRoles; QList<QObject*> advertizedEngines; const QString platformOffset; const QString basePath; const QString skinPath; const QString pluginPath; const QString resourcePath; const QString thumbnailPath; QTimer inputIdleTimer; QDeclarativeEngine *qmlEngine; QTranslator *backendTranslator; QList<QTranslator*> pluginTranslators; QFile logFile; QTextStream log; QFileSystemWatcher resourcePathMonitor; QStringList skins; Backend *pSelf; }; void BackendPrivate::handleDirChanged(const QString &dir) { if(dir == pluginPath) { qWarning() << "Changes in plugin path, probably about to eat your poodle"; discoverEngines(); } else if(dir == skinPath) { qWarning() << "Changes in skin path, repopulating skins"; discoverSkins(); } } void BackendPrivate::resetLanguage() { static QString baseTranslationPath(basePath % "/translations/"); const QString language = Backend::instance()->language(); delete backendTranslator; backendTranslator = new QTranslator(this); backendTranslator->load(baseTranslationPath % language % ".qm"); qApp->installTranslator(backendTranslator); qDeleteAll(pluginTranslators.begin(), pluginTranslators.end()); foreach(QObject *pluginObject, advertizedEngines) { QMHPlugin *plugin = qobject_cast<QMHPlugin*>(pluginObject); QTranslator *pluginTranslator = new QTranslator(this); pluginTranslator->load(baseTranslationPath % plugin->role() % "_" % language % ".qm"); pluginTranslators << pluginTranslator; qApp->installTranslator(pluginTranslator); } } void BackendPrivate::discoverSkins() { skins.clear(); QStringList potentialSkins = QDir(skinPath).entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach(const QString &currentPath, potentialSkins) if(QFile(skinPath % "/" % currentPath % "/" % currentPath).exists()) skins << currentPath; qWarning() << "Available skins" << skins; } void BackendPrivate::discoverEngines() { foreach(const QString fileName, QDir(pluginPath).entryList(QDir::Files)) { QString qualifiedFileName(pluginPath % "/" % fileName); QPluginLoader pluginLoader(qualifiedFileName); if (!pluginLoader.load()) { qWarning() << tr("Cant load plugin: %1 returns %2").arg(qualifiedFileName).arg(pluginLoader.errorString()); continue; } QMHPluginInterface* pluginInterface = qobject_cast<QMHPluginInterface*>(pluginLoader.instance()); if (!pluginInterface) qWarning() << tr("Invalid QMH plugin present: %1").arg(qualifiedFileName); else if (!pluginInterface->dependenciesSatisfied()) qWarning() << tr("Can't meet dependencies for %1").arg(qualifiedFileName); else if (pluginInterface->role() == "undefined") qWarning() << tr("Plugin %1 has an undefined role").arg(qualifiedFileName); else { QMHPlugin *plugin = new QMHPlugin(qobject_cast<QMHPluginInterface*>(pluginLoader.instance()), this); plugin->setParent(this); if(qmlEngine) plugin->registerPlugin(qmlEngine->rootContext()); Backend::instance()->advertizeEngine(plugin); } } resetLanguage(); } bool BackendPrivate::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::MouseMove || event->type() == QEvent::MouseButtonPress || event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { inputIdleTimer.start(); QMetaObject::invokeMethod(pSelf, "inputActive"); } return QObject::eventFilter(obj, event); } Backend::Backend(QObject *parent) : QObject(parent), d(new BackendPrivate(this)) { QFontDatabase::addApplicationFont(d->resourcePath + "/dejavu-fonts-ttf-2.32/ttf/DejaVuSans.ttf"); QFontDatabase::addApplicationFont(d->resourcePath + "/dejavu-fonts-ttf-2.32/ttf/DejaVuSans-Bold.ttf"); QFontDatabase::addApplicationFont(d->resourcePath + "/dejavu-fonts-ttf-2.32/ttf/DejaVuSans-Oblique.ttf"); QFontDatabase::addApplicationFont(d->resourcePath + "/dejavu-fonts-ttf-2.32/ttf/DejaVuSans-BoldOblique.ttf"); QApplication::setFont(QFont("DejaVu Sans")); } Backend::~Backend() { delete d; d = 0; } void Backend::initialize(QDeclarativeEngine *qmlEngine) { // register dataproviders to QML qmlRegisterType<ActionMapper>("ActionMapper", 1, 0, "ActionMapper"); qmlRegisterType<QMHPlugin>("QMHPlugin", 1, 0, "QMHPlugin"); qmlRegisterType<ProxyModel>("ProxyModel", 1, 0, "ProxyModel"); qmlRegisterType<ProxyModelItem>("ProxyModel", 1, 0, "ProxyModelItem"); qmlRegisterType<DirModel>("DirModel", 1, 0, "DirModel"); qmlRegisterType<ModelIndexIterator>("ModelIndexIterator", 1, 0, "ModelIndexIterator"); qmlRegisterType<QMLFileWrapper>("QMLFileWrapper", 1, 0, "QMLFileWrapper"); qmlRegisterType<Playlist>("Playlist", 1, 0, "Playlist"); if (qmlEngine) { //FIXME: We are clearly failing to keep the backend Declarative free :p d->qmlEngine = qmlEngine; qmlEngine->rootContext()->setContextProperty("backend", this); qmlEngine->rootContext()->setContextProperty("playlist", new Playlist); } d->discoverEngines(); } QString Backend::language() const { //FIXME: derive from locale //Allow override return QString(); //Bob is a testing translation placeholder //return QString("bob"); } QList<QObject*> Backend::engines() const { return d->advertizedEngines; } QStringList Backend::skins() const { return d->skins; } Backend* Backend::instance() { if (!pSelf) { pSelf = new Backend(); } return pSelf; } void Backend::destroy() { delete pSelf; pSelf = 0; } QString Backend::skinPath() const { return d->skinPath; } QString Backend::pluginPath() const { return d->pluginPath; } QString Backend::resourcePath() const { return d->resourcePath; } QString Backend::thumbnailPath() const { return d->thumbnailPath; } bool Backend::transforms() const { #ifdef GL return (QGLFormat::hasOpenGL() && Config::isEnabled("transforms", true)); #else return false; #endif } void Backend::advertizeEngine(QMHPlugin *engine) { QString role = engine->property("role").toString(); if (role.isEmpty()) return; if (d->advertizedEngineRoles.contains(role)) { qWarning() << tr("Duplicate engine found for role %1").arg(role); return; } d->advertizedEngines << engine; if (d->qmlEngine) d->qmlEngine->rootContext()->setContextProperty(role % "Engine", engine); d->advertizedEngineRoles << role; emit enginesChanged(); } void Backend::openUrlExternally(const QUrl & url) const { QDesktopServices::openUrl(url); } void Backend::log(const QString &logMsg) { qDebug() << logMsg; d->log << logMsg << endl; } // again dependent on declarative, needs to be fixed void Backend::clearComponentCache() { if (d->qmlEngine) { d->qmlEngine->clearComponentCache(); } } QObject* Backend::engine(const QString &role) { foreach (QObject *currentEngine, d->advertizedEngines) if (qobject_cast<QMHPlugin*>(currentEngine)->role() == role) return currentEngine; qWarning() << tr("Seeking a non-existant plugin, prepare to die"); return 0; } #include "backend.moc" <commit_msg>Add additional Qt3D screensavers<commit_after>/**************************************************************************** This file is part of the QtMediaHub project on http://www.gitorious.org. Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Nokia Corporation ([email protected])** You may use this file under the terms of the BSD license as follows: "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ****************************************************************************/ #include "backend.h" #include "plugins/qmhplugininterface.h" #include "plugins/qmhplugin.h" #include "dataproviders/proxymodel.h" #include "dataproviders/dirmodel.h" #include "dataproviders/modelindexiterator.h" #include "qmh-config.h" #include "qml-extensions/qmlfilewrapper.h" #include "qml-extensions/actionmapper.h" #include "dataproviders/playlist.h" #include <QDir> #include <QString> #include <QPluginLoader> #include <QCoreApplication> #include <QVariant> #include <QFileSystemModel> #include <QDesktopServices> #include <QFileSystemWatcher> #ifdef GL #include <QGLFormat> #endif #include <QDebug> Backend* Backend::pSelf = 0; class BackendPrivate : public QObject { Q_OBJECT public: BackendPrivate(Backend *p) : QObject(p), #ifdef Q_OS_MAC platformOffset("/../../.."), #endif basePath(QCoreApplication::applicationDirPath() + platformOffset), skinPath(basePath % "/skins"), pluginPath(basePath % "/plugins"), resourcePath(basePath % "/resources"), // Use "large" instead of appName to fit freedesktop spec thumbnailPath(Config::value("thumbnail-path", QDir::homePath() + "/.thumbnails/" + qApp->applicationName() + "/")), inputIdleTimer(this), qmlEngine(0), backendTranslator(0), logFile(qApp->applicationName().append(".log")), pSelf(p) { qApp->installEventFilter(this); inputIdleTimer.setInterval(Config::value("idle-timeout", 2*60)*1000); inputIdleTimer.setSingleShot(true); inputIdleTimer.start(); connect(&inputIdleTimer, SIGNAL(timeout()), pSelf, SIGNAL(inputIdle())); logFile.open(QIODevice::Text|QIODevice::ReadWrite); log.setDevice(&logFile); connect(&resourcePathMonitor, SIGNAL(directoryChanged(const QString &)), this, SLOT(handleDirChanged(const QString &))); resourcePathMonitor.addPath(skinPath); resourcePathMonitor.addPath(pluginPath); discoverSkins(); } ~BackendPrivate() { delete backendTranslator; backendTranslator = 0; qDeleteAll(pluginTranslators.begin(), pluginTranslators.end()); } public slots: void handleDirChanged(const QString &dir); public: void resetLanguage(); void discoverSkins(); void discoverEngines(); bool eventFilter(QObject *obj, QEvent *event); QSet<QString> advertizedEngineRoles; QList<QObject*> advertizedEngines; const QString platformOffset; const QString basePath; const QString skinPath; const QString pluginPath; const QString resourcePath; const QString thumbnailPath; QTimer inputIdleTimer; QDeclarativeEngine *qmlEngine; QTranslator *backendTranslator; QList<QTranslator*> pluginTranslators; QFile logFile; QTextStream log; QFileSystemWatcher resourcePathMonitor; QStringList skins; Backend *pSelf; }; void BackendPrivate::handleDirChanged(const QString &dir) { if(dir == pluginPath) { qWarning() << "Changes in plugin path, probably about to eat your poodle"; discoverEngines(); } else if(dir == skinPath) { qWarning() << "Changes in skin path, repopulating skins"; discoverSkins(); } } void BackendPrivate::resetLanguage() { static QString baseTranslationPath(basePath % "/translations/"); const QString language = Backend::instance()->language(); delete backendTranslator; backendTranslator = new QTranslator(this); backendTranslator->load(baseTranslationPath % language % ".qm"); qApp->installTranslator(backendTranslator); qDeleteAll(pluginTranslators.begin(), pluginTranslators.end()); foreach(QObject *pluginObject, advertizedEngines) { QMHPlugin *plugin = qobject_cast<QMHPlugin*>(pluginObject); QTranslator *pluginTranslator = new QTranslator(this); pluginTranslator->load(baseTranslationPath % plugin->role() % "_" % language % ".qm"); pluginTranslators << pluginTranslator; qApp->installTranslator(pluginTranslator); } } void BackendPrivate::discoverSkins() { skins.clear(); QStringList potentialSkins = QDir(skinPath).entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach(const QString &currentPath, potentialSkins) if(QFile(skinPath % "/" % currentPath % "/" % currentPath).exists()) skins << currentPath; qWarning() << "Available skins" << skins; } void BackendPrivate::discoverEngines() { foreach(const QString fileName, QDir(pluginPath).entryList(QDir::Files)) { QString qualifiedFileName(pluginPath % "/" % fileName); QPluginLoader pluginLoader(qualifiedFileName); if (!pluginLoader.load()) { qWarning() << tr("Cant load plugin: %1 returns %2").arg(qualifiedFileName).arg(pluginLoader.errorString()); continue; } QMHPluginInterface* pluginInterface = qobject_cast<QMHPluginInterface*>(pluginLoader.instance()); if (!pluginInterface) qWarning() << tr("Invalid QMH plugin present: %1").arg(qualifiedFileName); else if (!pluginInterface->dependenciesSatisfied()) qWarning() << tr("Can't meet dependencies for %1").arg(qualifiedFileName); else if (pluginInterface->role() == "undefined") qWarning() << tr("Plugin %1 has an undefined role").arg(qualifiedFileName); else { QMHPlugin *plugin = new QMHPlugin(qobject_cast<QMHPluginInterface*>(pluginLoader.instance()), this); plugin->setParent(this); if(qmlEngine) plugin->registerPlugin(qmlEngine->rootContext()); Backend::instance()->advertizeEngine(plugin); } } resetLanguage(); } bool BackendPrivate::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::MouseMove || event->type() == QEvent::MouseButtonPress || event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { inputIdleTimer.start(); QMetaObject::invokeMethod(pSelf, "inputActive"); } return QObject::eventFilter(obj, event); } Backend::Backend(QObject *parent) : QObject(parent), d(new BackendPrivate(this)) { QFontDatabase::addApplicationFont(d->resourcePath + "/dejavu-fonts-ttf-2.32/ttf/DejaVuSans.ttf"); QFontDatabase::addApplicationFont(d->resourcePath + "/dejavu-fonts-ttf-2.32/ttf/DejaVuSans-Bold.ttf"); QFontDatabase::addApplicationFont(d->resourcePath + "/dejavu-fonts-ttf-2.32/ttf/DejaVuSans-Oblique.ttf"); QFontDatabase::addApplicationFont(d->resourcePath + "/dejavu-fonts-ttf-2.32/ttf/DejaVuSans-BoldOblique.ttf"); QApplication::setFont(QFont("DejaVu Sans")); } Backend::~Backend() { delete d; d = 0; } void Backend::initialize(QDeclarativeEngine *qmlEngine) { // register dataproviders to QML qmlRegisterType<ActionMapper>("ActionMapper", 1, 0, "ActionMapper"); qmlRegisterType<QMHPlugin>("QMHPlugin", 1, 0, "QMHPlugin"); qmlRegisterType<ProxyModel>("ProxyModel", 1, 0, "ProxyModel"); qmlRegisterType<ProxyModelItem>("ProxyModel", 1, 0, "ProxyModelItem"); qmlRegisterType<DirModel>("DirModel", 1, 0, "DirModel"); qmlRegisterType<ModelIndexIterator>("ModelIndexIterator", 1, 0, "ModelIndexIterator"); qmlRegisterType<QMLFileWrapper>("QMLFileWrapper", 1, 0, "QMLFileWrapper"); qmlRegisterType<Playlist>("Playlist", 1, 0, "Playlist"); if (qmlEngine) { //FIXME: We are clearly failing to keep the backend Declarative free :p d->qmlEngine = qmlEngine; qmlEngine->rootContext()->setContextProperty("backend", this); qmlEngine->rootContext()->setContextProperty("playlist", new Playlist); } d->discoverEngines(); } QString Backend::language() const { //FIXME: derive from locale //Allow override return QString(); //Bob is a testing translation placeholder //return QString("bob"); } QList<QObject*> Backend::engines() const { return d->advertizedEngines; } QStringList Backend::skins() const { return d->skins; } Backend* Backend::instance() { if (!pSelf) { pSelf = new Backend(); } return pSelf; } void Backend::destroy() { delete pSelf; pSelf = 0; } QString Backend::skinPath() const { return d->skinPath; } QString Backend::pluginPath() const { return d->pluginPath; } QString Backend::resourcePath() const { return d->resourcePath; } QString Backend::thumbnailPath() const { return d->thumbnailPath; } bool Backend::transforms() const { #ifdef GL return (QGLFormat::hasOpenGL() && Config::isEnabled("transforms", true)); #else return false; #endif } void Backend::advertizeEngine(QMHPlugin *engine) { QString role = engine->property("role").toString(); if (role.isEmpty()) return; if (d->advertizedEngineRoles.contains(role)) { qWarning() << tr("Duplicate engine found for role %1").arg(role); return; } d->advertizedEngines << engine; if (d->qmlEngine) d->qmlEngine->rootContext()->setContextProperty(role % "Engine", engine); d->advertizedEngineRoles << role; emit enginesChanged(); } void Backend::openUrlExternally(const QUrl & url) const { QDesktopServices::openUrl(url); } void Backend::log(const QString &logMsg) { qDebug() << logMsg; d->log << logMsg << endl; } // again dependent on declarative, needs to be fixed void Backend::clearComponentCache() { if (d->qmlEngine) { d->qmlEngine->clearComponentCache(); } } QObject* Backend::engine(const QString &role) { foreach (QObject *currentEngine, d->advertizedEngines) if (qobject_cast<QMHPlugin*>(currentEngine)->role() == role) return currentEngine; qWarning() << tr("Seeking a non-existant plugin, prepare to die"); return 0; } #include "backend.moc" <|endoftext|>
<commit_before>#include "stdafx.h" #include "uart.h" #include "Globals.h" #include "World.h" #include "Train.h" #include "Logs.h" uart_input::uart_input() { conf = Global::uart_conf; if (sp_get_port_by_name(conf.port.c_str(), &port) != SP_OK) throw std::runtime_error("uart: cannot find specified port"); if (sp_open(port, SP_MODE_READ_WRITE) != SP_OK) throw std::runtime_error("uart: cannot open port"); sp_port_config *config; if (sp_new_config(&config) != SP_OK || sp_set_config_baudrate(config, conf.baud) != SP_OK || sp_set_config_flowcontrol(config, SP_FLOWCONTROL_NONE) != SP_OK || sp_set_config_bits(config, 8) != SP_OK || sp_set_config_stopbits(config, 1) != SP_OK || sp_set_config_parity(config, SP_PARITY_NONE) != SP_OK || sp_set_config(port, config) != SP_OK) throw std::runtime_error("uart: cannot set config"); sp_free_config(config); if (sp_flush(port, SP_BUF_BOTH) != SP_OK) throw std::runtime_error("uart: cannot flush"); old_packet.fill(0); last_update = std::chrono::high_resolution_clock::now(); } uart_input::~uart_input() { sp_close(port); sp_free_port(port); } #define SPLIT_INT16(x) (uint8_t)x, (uint8_t)(x >> 8) void uart_input::poll() { auto now = std::chrono::high_resolution_clock::now(); if (std::chrono::duration<float>(now - last_update).count() < conf.updatetime) return; last_update = now; TTrain *t = Global::pWorld->train(); if (!t) return; sp_return ret; if ((ret = sp_input_waiting(port)) >= 16) { std::array<uint8_t, 16> buffer; ret = sp_blocking_read(port, (void*)buffer.data(), buffer.size(), 0); if (ret < 0) throw std::runtime_error("uart: failed to read from port"); if (conf.debug) { char buf[buffer.size() * 3 + 1]; size_t pos = 0; for (uint8_t b : buffer) pos += sprintf(&buf[pos], "%02X ", b); WriteLog("uart: rx: " + std::string(buf)); } data_pending = false; for (auto entry : input_bits) { input_type_t type = std::get<2>(entry); size_t byte = std::get<0>(entry) / 8; size_t bit = std::get<0>(entry) % 8; bool state = (bool)(buffer[byte] & (1 << bit)); bool repeat = (type == impulse_r || type == impulse_r_off || type == impulse_r_on); bool changed = (state != (bool)(old_packet[byte] & (1 << bit))); if (!changed && !(repeat && state)) continue; int action; command_data::desired_state_t desired_state; if (type == toggle) { action = GLFW_PRESS; desired_state = state ? command_data::ON : command_data::OFF; } else if (type == impulse_r_on) { action = state ? (changed ? GLFW_PRESS : GLFW_REPEAT) : GLFW_RELEASE; desired_state = command_data::ON; } else if (type == impulse_r_off) { action = state ? (changed ? GLFW_PRESS : GLFW_REPEAT) : GLFW_RELEASE; desired_state = command_data::OFF; } else if (type == impulse || type == impulse_r) { action = state ? (changed ? GLFW_PRESS : GLFW_REPEAT) : GLFW_RELEASE; desired_state = command_data::TOGGLE; } relay.post(std::get<1>(entry), 0, 0, action, 0, desired_state); } if (conf.mainenable) t->set_mainctrl(buffer[6]); if (conf.scndenable) t->set_scndctrl(buffer[7]); if (conf.trainenable) t->set_trainbrake((float)(((uint16_t)buffer[8] | ((uint16_t)buffer[9] << 8)) - conf.mainbrakemin) / (conf.mainbrakemax - conf.mainbrakemin)); if (conf.localenable) t->set_localbrake((float)(((uint16_t)buffer[10] | ((uint16_t)buffer[11] << 8)) - conf.mainbrakemin) / (conf.localbrakemax - conf.localbrakemin)); old_packet = buffer; } if (!data_pending && sp_output_waiting(port) == 0) { // TODO: ugly! move it into structure like input_bits uint8_t buzzer = (uint8_t)t->get_alarm(); uint8_t tacho = (uint8_t)t->get_tacho(); uint16_t tank_press = (uint16_t)std::min(conf.tankuart, t->get_tank_pressure() * 0.1f / conf.tankmax * conf.tankuart); uint16_t pipe_press = (uint16_t)std::min(conf.pipeuart, t->get_pipe_pressure() * 0.1f / conf.pipemax * conf.pipeuart); uint16_t brake_press = (uint16_t)std::min(conf.brakeuart, t->get_brake_pressure() * 0.1f / conf.brakemax * conf.brakeuart); uint16_t hv_voltage = (uint16_t)std::min(conf.hvuart, t->get_hv_voltage() / conf.hvmax * conf.hvuart); auto current = t->get_current(); uint16_t current1 = (uint16_t)std::min(conf.currentuart, current[0]) / conf.currentmax * conf.currentuart; uint16_t current2 = (uint16_t)std::min(conf.currentuart, current[1]) / conf.currentmax * conf.currentuart; uint16_t current3 = (uint16_t)std::min(conf.currentuart, current[2]) / conf.currentmax * conf.currentuart; std::array<uint8_t, 31> buffer = { tacho, //byte 0 0, //byte 1 (uint8_t)(t->btLampkaOpory.b() << 1 | t->btLampkaWysRozr.b() << 2), //byte 2 0, //byte 3 (uint8_t)(t->btLampkaOgrzewanieSkladu.b() << 0 | t->btLampkaOpory.b() << 1 | t->btLampkaPoslizg.b() << 2 | t->btLampkaCzuwaka.b() << 6 | t->btLampkaSHP.b() << 7), //byte 4 (uint8_t)(t->btLampkaStyczn.b() << 0 | t->btLampkaNadmPrzetw.b() << 2 | t->btLampkaNadmSil.b() << 4 | t->btLampkaWylSzybki.b() << 5 | t->btLampkaNadmSpr.b() << 6), //byte 5 (uint8_t)(buzzer << 7), //byte 6 SPLIT_INT16(brake_press), //byte 7-8 SPLIT_INT16(pipe_press), //byte 9-10 SPLIT_INT16(tank_press), //byte 11-12 SPLIT_INT16(hv_voltage), //byte 13-14 SPLIT_INT16(current1), //byte 15-16 SPLIT_INT16(current2), //byte 17-18 SPLIT_INT16(current3), //byte 19-20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 //byte 21-30 }; if (conf.debug) { char buf[buffer.size() * 3 + 1]; size_t pos = 0; for (uint8_t b : buffer) pos += sprintf(&buf[pos], "%02X ", b); WriteLog("uart: tx: " + std::string(buf)); } ret = sp_blocking_write(port, (void*)buffer.data(), buffer.size(), 0); if (ret != buffer.size()) throw std::runtime_error("uart: failed to write to port"); data_pending = true; } } <commit_msg>Update uart.cpp<commit_after>#include "stdafx.h" #include "uart.h" #include "Globals.h" #include "World.h" #include "Train.h" #include "Logs.h" uart_input::uart_input() { conf = Global::uart_conf; if (sp_get_port_by_name(conf.port.c_str(), &port) != SP_OK) throw std::runtime_error("uart: cannot find specified port"); if (sp_open(port, SP_MODE_READ_WRITE) != SP_OK) throw std::runtime_error("uart: cannot open port"); sp_port_config *config; if (sp_new_config(&config) != SP_OK || sp_set_config_baudrate(config, conf.baud) != SP_OK || sp_set_config_flowcontrol(config, SP_FLOWCONTROL_NONE) != SP_OK || sp_set_config_bits(config, 8) != SP_OK || sp_set_config_stopbits(config, 1) != SP_OK || sp_set_config_parity(config, SP_PARITY_NONE) != SP_OK || sp_set_config(port, config) != SP_OK) throw std::runtime_error("uart: cannot set config"); sp_free_config(config); if (sp_flush(port, SP_BUF_BOTH) != SP_OK) throw std::runtime_error("uart: cannot flush"); old_packet.fill(0); last_update = std::chrono::high_resolution_clock::now(); } uart_input::~uart_input() { sp_close(port); sp_free_port(port); } #define SPLIT_INT16(x) (uint8_t)x, (uint8_t)(x >> 8) void uart_input::poll() { auto now = std::chrono::high_resolution_clock::now(); if (std::chrono::duration<float>(now - last_update).count() < conf.updatetime) return; last_update = now; TTrain *t = Global::pWorld->train(); if (!t) return; sp_return ret; if ((ret = sp_input_waiting(port)) >= 16) { std::array<uint8_t, 16> buffer; ret = sp_blocking_read(port, (void*)buffer.data(), buffer.size(), 0); if (ret < 0) throw std::runtime_error("uart: failed to read from port"); if (conf.debug) { char buf[buffer.size() * 3 + 1]; size_t pos = 0; for (uint8_t b : buffer) pos += sprintf(&buf[pos], "%02X ", b); WriteLog("uart: rx: " + std::string(buf)); } data_pending = false; for (auto entry : input_bits) { input_type_t type = std::get<2>(entry); size_t byte = std::get<0>(entry) / 8; size_t bit = std::get<0>(entry) % 8; bool state = (bool)(buffer[byte] & (1 << bit)); bool repeat = (type == impulse_r || type == impulse_r_off || type == impulse_r_on); bool changed = (state != (bool)(old_packet[byte] & (1 << bit))); if (!changed && !(repeat && state)) continue; int action; command_data::desired_state_t desired_state; if (type == toggle) { action = GLFW_PRESS; desired_state = state ? command_data::ON : command_data::OFF; } else if (type == impulse_r_on) { action = state ? (changed ? GLFW_PRESS : GLFW_REPEAT) : GLFW_RELEASE; desired_state = command_data::ON; } else if (type == impulse_r_off) { action = state ? (changed ? GLFW_PRESS : GLFW_REPEAT) : GLFW_RELEASE; desired_state = command_data::OFF; } else if (type == impulse || type == impulse_r) { action = state ? (changed ? GLFW_PRESS : GLFW_REPEAT) : GLFW_RELEASE; desired_state = command_data::TOGGLE; } relay.post(std::get<1>(entry), 0, 0, action, 0, desired_state); } if (conf.mainenable) t->set_mainctrl(buffer[6]); if (conf.scndenable) t->set_scndctrl(buffer[7]); if (conf.trainenable) t->set_trainbrake((float)(((uint16_t)buffer[8] | ((uint16_t)buffer[9] << 8)) - conf.mainbrakemin) / (conf.mainbrakemax - conf.mainbrakemin)); if (conf.localenable) t->set_localbrake((float)(((uint16_t)buffer[10] | ((uint16_t)buffer[11] << 8)) - conf.localbrakemin) / (conf.localbrakemax - conf.localbrakemin)); old_packet = buffer; } if (!data_pending && sp_output_waiting(port) == 0) { // TODO: ugly! move it into structure like input_bits uint8_t buzzer = (uint8_t)t->get_alarm(); uint8_t tacho = (uint8_t)t->get_tacho(); uint16_t tank_press = (uint16_t)std::min(conf.tankuart, t->get_tank_pressure() * 0.1f / conf.tankmax * conf.tankuart); uint16_t pipe_press = (uint16_t)std::min(conf.pipeuart, t->get_pipe_pressure() * 0.1f / conf.pipemax * conf.pipeuart); uint16_t brake_press = (uint16_t)std::min(conf.brakeuart, t->get_brake_pressure() * 0.1f / conf.brakemax * conf.brakeuart); uint16_t hv_voltage = (uint16_t)std::min(conf.hvuart, t->get_hv_voltage() / conf.hvmax * conf.hvuart); auto current = t->get_current(); uint16_t current1 = (uint16_t)std::min(conf.currentuart, current[0]) / conf.currentmax * conf.currentuart; uint16_t current2 = (uint16_t)std::min(conf.currentuart, current[1]) / conf.currentmax * conf.currentuart; uint16_t current3 = (uint16_t)std::min(conf.currentuart, current[2]) / conf.currentmax * conf.currentuart; std::array<uint8_t, 31> buffer = { tacho, //byte 0 0, //byte 1 (uint8_t)(t->btLampkaOpory.b() << 1 | t->btLampkaWysRozr.b() << 2), //byte 2 0, //byte 3 (uint8_t)(t->btLampkaOgrzewanieSkladu.b() << 0 | t->btLampkaOpory.b() << 1 | t->btLampkaPoslizg.b() << 2 | t->btLampkaCzuwaka.b() << 6 | t->btLampkaSHP.b() << 7), //byte 4 (uint8_t)(t->btLampkaStyczn.b() << 0 | t->btLampkaNadmPrzetw.b() << 2 | t->btLampkaNadmSil.b() << 4 | t->btLampkaWylSzybki.b() << 5 | t->btLampkaNadmSpr.b() << 6), //byte 5 (uint8_t)(buzzer << 7), //byte 6 SPLIT_INT16(brake_press), //byte 7-8 SPLIT_INT16(pipe_press), //byte 9-10 SPLIT_INT16(tank_press), //byte 11-12 SPLIT_INT16(hv_voltage), //byte 13-14 SPLIT_INT16(current1), //byte 15-16 SPLIT_INT16(current2), //byte 17-18 SPLIT_INT16(current3), //byte 19-20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 //byte 21-30 }; if (conf.debug) { char buf[buffer.size() * 3 + 1]; size_t pos = 0; for (uint8_t b : buffer) pos += sprintf(&buf[pos], "%02X ", b); WriteLog("uart: tx: " + std::string(buf)); } ret = sp_blocking_write(port, (void*)buffer.data(), buffer.size(), 0); if (ret != buffer.size()) throw std::runtime_error("uart: failed to write to port"); data_pending = true; } } <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "obs-precomp.h" // Precompiled headers #include <mrpt/obs/gnss_messages_ascii_nmea.h> using namespace std; using namespace mrpt::obs::gnss; // --------------------------------------- Message_NMEA_GGA::content_t::content_t() : UTCTime(), latitude_degrees(0), longitude_degrees(0), fix_quality(0), altitude_meters(0), geoidal_distance(), orthometric_altitude(), corrected_orthometric_altitude(), satellitesUsed(0), thereis_HDOP(false), HDOP(0) { } void Message_NMEA_GGA::dumpToStream( mrpt::utils::CStream &out ) const { out.printf("[NMEA GGA datum]\n"); out.printf(" Longitude: %.09f deg Latitude: %.09f deg Height: %.03f m\n", fields.longitude_degrees, fields.latitude_degrees, fields.altitude_meters ); out.printf(" Geoidal distance: %.03f m Orthometric alt.: %.03f m Corrected ort. alt.: %.03f m\n", fields.geoidal_distance, fields.orthometric_altitude, fields.corrected_orthometric_altitude ); out.printf(" UTC time-stamp: %02u:%02u:%02.03f #sats=%2u ", fields.UTCTime.hour, fields.UTCTime.minute, fields.UTCTime.sec, fields.satellitesUsed ); out.printf("Fix mode: %u ",fields.fix_quality); switch( fields.fix_quality ) { case 0: out.printf("(Invalid)\n"); break; case 1: out.printf("(GPS fix)\n"); break; case 2: out.printf("(DGPS fix)\n"); break; case 3: out.printf("(PPS fix)\n"); break; case 4: out.printf("(Real Time Kinematic/RTK Fixed)\n"); break; case 5: out.printf("(Real Time Kinematic/RTK Float)\n"); break; case 6: out.printf("(Dead Reckoning)\n"); break; case 7: out.printf("(Manual)\n"); break; case 8: out.printf("(Simulation)\n"); break; case 9: out.printf("(mmGPS + RTK Fixed)\n"); break; case 10: out.printf("(mmGPS + RTK Float)\n"); break; default: out.printf("(UNKNOWN!)\n"); break; }; out.printf(" HDOP (Horizontal Dilution of Precision): "); if (fields.thereis_HDOP) out.printf(" %f\n", fields.HDOP); else out.printf(" N/A\n"); } // --------------------------------------- Message_NMEA_RMC::content_t::content_t() : UTCTime(), validity_char('V'), latitude_degrees(0), longitude_degrees(0), speed_knots(0), direction_degrees(0), date_day(0), date_month(0), date_year(0), magnetic_dir(), positioning_mode('N') { } void Message_NMEA_RMC::dumpToStream( mrpt::utils::CStream &out ) const { out.printf("[NMEA RMC datum]\n"); out.printf(" Longitude: %.09f deg Latitude: %.09f deg Valid?: '%c'\n", fields.longitude_degrees, fields.latitude_degrees, fields.validity_char ); out.printf(" UTC time-stamp: %02u:%02u:%02.03f ", fields.UTCTime.hour, fields.UTCTime.minute, fields.UTCTime.sec ); out.printf(" Speed: %.05f knots Direction:%.03f deg.\n ", fields.speed_knots, fields.direction_degrees ); } <commit_msg>NMEA RMC dump<commit_after>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "obs-precomp.h" // Precompiled headers #include <mrpt/obs/gnss_messages_ascii_nmea.h> using namespace std; using namespace mrpt::obs::gnss; // --------------------------------------- Message_NMEA_GGA::content_t::content_t() : UTCTime(), latitude_degrees(0), longitude_degrees(0), fix_quality(0), altitude_meters(0), geoidal_distance(), orthometric_altitude(), corrected_orthometric_altitude(), satellitesUsed(0), thereis_HDOP(false), HDOP(0) { } void Message_NMEA_GGA::dumpToStream( mrpt::utils::CStream &out ) const { out.printf("[NMEA GGA datum]\n"); out.printf(" Longitude: %.09f deg Latitude: %.09f deg Height: %.03f m\n", fields.longitude_degrees, fields.latitude_degrees, fields.altitude_meters ); out.printf(" Geoidal distance: %.03f m Orthometric alt.: %.03f m Corrected ort. alt.: %.03f m\n", fields.geoidal_distance, fields.orthometric_altitude, fields.corrected_orthometric_altitude ); out.printf(" UTC time-stamp: %02u:%02u:%02.03f #sats=%2u ", fields.UTCTime.hour, fields.UTCTime.minute, fields.UTCTime.sec, fields.satellitesUsed ); out.printf("Fix mode: %u ",fields.fix_quality); switch( fields.fix_quality ) { case 0: out.printf("(Invalid)\n"); break; case 1: out.printf("(GPS fix)\n"); break; case 2: out.printf("(DGPS fix)\n"); break; case 3: out.printf("(PPS fix)\n"); break; case 4: out.printf("(Real Time Kinematic/RTK Fixed)\n"); break; case 5: out.printf("(Real Time Kinematic/RTK Float)\n"); break; case 6: out.printf("(Dead Reckoning)\n"); break; case 7: out.printf("(Manual)\n"); break; case 8: out.printf("(Simulation)\n"); break; case 9: out.printf("(mmGPS + RTK Fixed)\n"); break; case 10: out.printf("(mmGPS + RTK Float)\n"); break; default: out.printf("(UNKNOWN!)\n"); break; }; out.printf(" HDOP (Horizontal Dilution of Precision): "); if (fields.thereis_HDOP) out.printf(" %f\n", fields.HDOP); else out.printf(" N/A\n"); } // --------------------------------------- Message_NMEA_RMC::content_t::content_t() : UTCTime(), validity_char('V'), latitude_degrees(0), longitude_degrees(0), speed_knots(0), direction_degrees(0), date_day(0), date_month(0), date_year(0), magnetic_dir(), positioning_mode('N') { } void Message_NMEA_RMC::dumpToStream( mrpt::utils::CStream &out ) const { out.printf("[NMEA RMC datum]\n"); out.printf(" Positioning mode: `%c`\n ", (char)fields.positioning_mode); out.printf(" UTC time-stamp: %02u:%02u:%02.03f\n", fields.UTCTime.hour, fields.UTCTime.minute, fields.UTCTime.sec ); out.printf(" Date (DD/MM/YY): %02u/%02u/%02u\n ", (unsigned)fields.date_day,(unsigned)fields.date_month, (unsigned)fields.date_year); out.printf(" Longitude: %.09f deg Latitude: %.09f deg Valid?: '%c'\n", fields.longitude_degrees, fields.latitude_degrees, fields.validity_char ); out.printf(" Speed: %.05f knots Direction:%.03f deg.\n ", fields.speed_knots, fields.direction_degrees ); out.printf(" Magnetic variation direction: %.04f deg\n ", fields.magnetic_dir); } <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <limits> #include <map> #include <regex> #include <string> #include <vector> #include "persistenceDiagrams/IO.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include "persistenceDiagrams/PersistenceIndicatorFunction.hh" #include "utilities/Filesystem.hh" using DataType = double; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; using PersistenceIndicatorFunction = aleph::math::StepFunction<DataType>; /* Auxiliary structure for describing a data set. I need this in order to figure out the corresponding dimension of the persistence diagram. */ struct DataSet { std::string filename; unsigned dimension; PersistenceDiagram persistenceDiagram; PersistenceIndicatorFunction persistenceIndicatorFunction; }; // Calculates the distance between two data sets. This requires enumerating all // dimensions, and finding the corresponding persistence indicator function. If // no such function exists, the function uses the norm of the function. double distance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension ) { auto getPersistenceIndicatorFunction = [] ( const std::vector<DataSet>& dataSet, unsigned dimension ) { auto it = std::find_if( dataSet.begin(), dataSet.end(), [&dimension] ( const DataSet& dataSet ) { return dataSet.dimension == dimension; } ); if( it != dataSet.end() ) return it->persistenceIndicatorFunction; else return const PersistenceIndicatorFunction(); }; double d = 0.0; for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ ) { auto f = getPersistenceIndicatorFunction( dataSet1, dimension ); auto g = getPersistenceIndicatorFunction( dataSet2, dimension ); g = g * (-1.0); d = d + (f+g).integral(); } return d; } int main( int argc, char** argv ) { if( argc <= 1 ) { // TODO: Show usage return -1; } // Maps data sets to file names. Whether a new filename constitutes // a new data set is decided by taking a look at the prefix of the // filename. std::map<std::string, std::vector<DataSet> > dataSets; // TODO: Make this regular expression more, well, 'expressive' and // support more methods of specifying a dimension. std::regex reDataSetPrefix( "(.*)_k([[:digit:]]+)\\.txt" ); std::smatch matches; // Get filenames & prefixes ------------------------------------------ unsigned minDimension = std::numeric_limits<unsigned>::max(); unsigned maxDimension = 0; { std::vector<std::string> filenames; filenames.reserve( argc - 1 ); for( int i = 1; i < argc; i++ ) filenames.push_back( argv[i] ); for( auto&& filename : filenames ) { if( std::regex_match( filename, matches, reDataSetPrefix ) ) { auto name = matches[1]; auto dimension = unsigned( std::stoul( matches[2] ) ); dataSets[name].push_back( { filename, dimension, {}, {} } ); minDimension = std::min( minDimension, dimension ); maxDimension = std::max( maxDimension, dimension ); } } } // Load persistence diagrams & calculate indicator functions --------- std::vector<PersistenceDiagram> persistenceDiagrams; for( auto&& pair : dataSets ) { for( auto&& dataSet : pair.second ) { std::cerr << "* Processing '" << dataSet.filename << "'..."; dataSet.persistenceDiagram = aleph::load<DataType>( dataSet.filename ); // FIXME: This is only required in order to ensure that the // persistence indicator function has a finite integral; it // can be solved more elegantly by using a special value to // indicate infinite intervals. dataSet.persistenceDiagram.removeUnpaired(); dataSet.persistenceIndicatorFunction = aleph::persistenceIndicatorFunction( dataSet.persistenceDiagram ); std::cerr << "finished\n"; } } // Calculate all distances ------------------------------------------- std::vector< std::vector<double> > distances; distances.resize( dataSets.size(), std::vector<double>( dataSets.size() ) ); std::size_t row = 0; for( auto it1 = dataSets.begin(); it1 != dataSets.end(); ++it1, ++row ) { std::size_t col = 0; for( auto it2 = std::next( it1 ); it2 != dataSets.end(); ++it2, ++col ) { auto d = distance( it1->second, it2->second, minDimension, maxDimension ); distances[row][col] = d; distances[col][row] = d; std::cerr << "D[" << row << "][" << col << "]: " << d << "\n"; } } } <commit_msg>More precise return type specification<commit_after>#include <algorithm> #include <iostream> #include <limits> #include <map> #include <regex> #include <string> #include <vector> #include "persistenceDiagrams/IO.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include "persistenceDiagrams/PersistenceIndicatorFunction.hh" #include "utilities/Filesystem.hh" using DataType = double; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; using PersistenceIndicatorFunction = aleph::math::StepFunction<DataType>; /* Auxiliary structure for describing a data set. I need this in order to figure out the corresponding dimension of the persistence diagram. */ struct DataSet { std::string filename; unsigned dimension; PersistenceDiagram persistenceDiagram; PersistenceIndicatorFunction persistenceIndicatorFunction; }; // Calculates the distance between two data sets. This requires enumerating all // dimensions, and finding the corresponding persistence indicator function. If // no such function exists, the function uses the norm of the function. double distance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension ) { auto getPersistenceIndicatorFunction = [] ( const std::vector<DataSet>& dataSet, unsigned dimension ) { auto it = std::find_if( dataSet.begin(), dataSet.end(), [&dimension] ( const DataSet& dataSet ) { return dataSet.dimension == dimension; } ); if( it != dataSet.end() ) return PersistenceIndicatorFunction( it->persistenceIndicatorFunction ); else return PersistenceIndicatorFunction(); }; double d = 0.0; for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ ) { auto f = getPersistenceIndicatorFunction( dataSet1, dimension ); auto g = getPersistenceIndicatorFunction( dataSet2, dimension ); g = g * (-1.0); d = d + (f+g).integral(); } return d; } int main( int argc, char** argv ) { if( argc <= 1 ) { // TODO: Show usage return -1; } // Maps data sets to file names. Whether a new filename constitutes // a new data set is decided by taking a look at the prefix of the // filename. std::map<std::string, std::vector<DataSet> > dataSets; // TODO: Make this regular expression more, well, 'expressive' and // support more methods of specifying a dimension. std::regex reDataSetPrefix( "(.*)_k([[:digit:]]+)\\.txt" ); std::smatch matches; // Get filenames & prefixes ------------------------------------------ unsigned minDimension = std::numeric_limits<unsigned>::max(); unsigned maxDimension = 0; { std::vector<std::string> filenames; filenames.reserve( argc - 1 ); for( int i = 1; i < argc; i++ ) filenames.push_back( argv[i] ); for( auto&& filename : filenames ) { if( std::regex_match( filename, matches, reDataSetPrefix ) ) { auto name = matches[1]; auto dimension = unsigned( std::stoul( matches[2] ) ); dataSets[name].push_back( { filename, dimension, {}, {} } ); minDimension = std::min( minDimension, dimension ); maxDimension = std::max( maxDimension, dimension ); } } } // Load persistence diagrams & calculate indicator functions --------- std::vector<PersistenceDiagram> persistenceDiagrams; for( auto&& pair : dataSets ) { for( auto&& dataSet : pair.second ) { std::cerr << "* Processing '" << dataSet.filename << "'..."; dataSet.persistenceDiagram = aleph::load<DataType>( dataSet.filename ); // FIXME: This is only required in order to ensure that the // persistence indicator function has a finite integral; it // can be solved more elegantly by using a special value to // indicate infinite intervals. dataSet.persistenceDiagram.removeUnpaired(); dataSet.persistenceIndicatorFunction = aleph::persistenceIndicatorFunction( dataSet.persistenceDiagram ); std::cerr << "finished\n"; } } // Calculate all distances ------------------------------------------- std::vector< std::vector<double> > distances; distances.resize( dataSets.size(), std::vector<double>( dataSets.size() ) ); std::size_t row = 0; for( auto it1 = dataSets.begin(); it1 != dataSets.end(); ++it1, ++row ) { std::size_t col = 0; for( auto it2 = std::next( it1 ); it2 != dataSets.end(); ++it2, ++col ) { auto d = distance( it1->second, it2->second, minDimension, maxDimension ); distances[row][col] = d; distances[col][row] = d; std::cerr << "D[" << row << "][" << col << "]: " << d << "\n"; } } } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // 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 2 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, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "X11Display.h" #include "../base/Exception.h" #include "../base/Logger.h" #include <SDL/SDL.h> #include <SDL/SDL_syswm.h> #ifdef AVG_ENABLE_XINERAMA #include <X11/extensions/Xinerama.h> #endif namespace avg { X11Display::X11Display() { } X11Display::~X11Display() { } float X11Display::queryPPMM() { ::Display * pDisplay = XOpenDisplay(0); float ppmm = getScreenResolution().x/float(DisplayWidthMM(pDisplay, 0)); XCloseDisplay(pDisplay); return ppmm; } IntPoint X11Display::queryScreenResolution() { IntPoint size; bool bXinerama = false; ::Display * pDisplay = XOpenDisplay(0); #ifdef AVG_ENABLE_XINERAMA int dummy1, dummy2; bXinerama = XineramaQueryExtension(pDisplay, &dummy1, &dummy2); if (bXinerama) { bXinerama = XineramaIsActive(pDisplay); } if (bXinerama) { int numHeads = 0; XineramaScreenInfo * pScreenInfo = XineramaQueryScreens(pDisplay, &numHeads); AVG_ASSERT(numHeads >= 1); /* cerr << "Num heads: " << numHeads << endl; for (int x=0; x<numHeads; ++x) { cout << "Head " << x+1 << ": " << pScreenInfo[x].width << "x" << pScreenInfo[x].height << " at " << pScreenInfo[x].x_org << "," << pScreenInfo[x].y_org << endl; } */ size = IntPoint(pScreenInfo[0].width, pScreenInfo[0].height); XFree(pScreenInfo); } #endif if (!bXinerama) { Screen* pScreen = DefaultScreenOfDisplay(pDisplay); AVG_ASSERT(pScreen); size = IntPoint(pScreen->width, pScreen->height); } XCloseDisplay(pDisplay); return size; } float X11Display::queryRefreshRate() { ::Display * pDisplay = XOpenDisplay(0); int pixelClock; XF86VidModeModeLine modeLine; bool bOK = XF86VidModeGetModeLine(pDisplay, DefaultScreen(pDisplay), &pixelClock, &modeLine); if (!bOK) { AVG_LOG_WARNING( "Could not get current refresh rate (XF86VidModeGetModeLine failed)."); AVG_LOG_WARNING("Defaulting to 60 Hz refresh rate."); } float HSyncRate = pixelClock*1000.0/modeLine.htotal; float refreshRate = HSyncRate/modeLine.vtotal; XCloseDisplay(pDisplay); return refreshRate; } ::Display* getX11Display(const SDL_SysWMinfo* pSDLWMInfo) { ::Display* pDisplay; if (pSDLWMInfo) { // SDL window exists, use it. pDisplay = pSDLWMInfo->info.x11.display; } else { pDisplay = XOpenDisplay(0); } if (!pDisplay) { throw Exception(AVG_ERR_VIDEO_GENERAL, "No X windows display available."); } return pDisplay; } Window createChildWindow(const SDL_SysWMinfo* pSDLWMInfo, XVisualInfo* pVisualInfo, const IntPoint& windowSize, Colormap& colormap) { // Create a child window with the required attributes to render into. XSetWindowAttributes swa; ::Display* pDisplay = pSDLWMInfo->info.x11.display; colormap = XCreateColormap(pDisplay, RootWindow(pDisplay, pVisualInfo->screen), pVisualInfo->visual, AllocNone); swa.colormap = colormap; swa.background_pixmap = None; swa.event_mask = StructureNotifyMask; Window win = XCreateWindow(pDisplay, pSDLWMInfo->info.x11.window, 0, 0, windowSize.x, windowSize.y, 0, pVisualInfo->depth, InputOutput, pVisualInfo->visual, CWColormap|CWEventMask, &swa); AVG_ASSERT(win); XMapWindow(pDisplay, win); return win; } } <commit_msg>Added fallback of 60Hz for XWindow::getRefreshRate<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // 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 2 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, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "X11Display.h" #include "../base/Exception.h" #include "../base/Logger.h" #include <SDL/SDL.h> #include <SDL/SDL_syswm.h> #ifdef AVG_ENABLE_XINERAMA #include <X11/extensions/Xinerama.h> #endif #include <boost/math/special_functions/fpclassify.hpp> namespace avg { X11Display::X11Display() { } X11Display::~X11Display() { } float X11Display::queryPPMM() { ::Display * pDisplay = XOpenDisplay(0); float ppmm = getScreenResolution().x/float(DisplayWidthMM(pDisplay, 0)); XCloseDisplay(pDisplay); return ppmm; } IntPoint X11Display::queryScreenResolution() { IntPoint size; bool bXinerama = false; ::Display * pDisplay = XOpenDisplay(0); #ifdef AVG_ENABLE_XINERAMA int dummy1, dummy2; bXinerama = XineramaQueryExtension(pDisplay, &dummy1, &dummy2); if (bXinerama) { bXinerama = XineramaIsActive(pDisplay); } if (bXinerama) { int numHeads = 0; XineramaScreenInfo * pScreenInfo = XineramaQueryScreens(pDisplay, &numHeads); AVG_ASSERT(numHeads >= 1); /* cerr << "Num heads: " << numHeads << endl; for (int x=0; x<numHeads; ++x) { cout << "Head " << x+1 << ": " << pScreenInfo[x].width << "x" << pScreenInfo[x].height << " at " << pScreenInfo[x].x_org << "," << pScreenInfo[x].y_org << endl; } */ size = IntPoint(pScreenInfo[0].width, pScreenInfo[0].height); XFree(pScreenInfo); } #endif if (!bXinerama) { Screen* pScreen = DefaultScreenOfDisplay(pDisplay); AVG_ASSERT(pScreen); size = IntPoint(pScreen->width, pScreen->height); } XCloseDisplay(pDisplay); return size; } float X11Display::queryRefreshRate() { ::Display * pDisplay = XOpenDisplay(0); int pixelClock; XF86VidModeModeLine modeLine; bool bOK = XF86VidModeGetModeLine(pDisplay, DefaultScreen(pDisplay), &pixelClock, &modeLine); if (!bOK) { AVG_LOG_WARNING( "Could not get current refresh rate (XF86VidModeGetModeLine failed)."); AVG_LOG_WARNING("Defaulting to 60 Hz refresh rate."); return 60; } float hSyncRate = (pixelClock * 1000.0) / modeLine.htotal; float refreshRate = hSyncRate / modeLine.vtotal; XCloseDisplay(pDisplay); if ( refreshRate < 20 || refreshRate > 200 || !(boost::math::isnormal(refreshRate))){ AVG_LOG_WARNING("Could not get valid refresh rate"); AVG_LOG_WARNING("Defaulting to 60 Hz refresh rate."); return 60; } return refreshRate; } ::Display* getX11Display(const SDL_SysWMinfo* pSDLWMInfo) { ::Display* pDisplay; if (pSDLWMInfo) { // SDL window exists, use it. pDisplay = pSDLWMInfo->info.x11.display; } else { pDisplay = XOpenDisplay(0); } if (!pDisplay) { throw Exception(AVG_ERR_VIDEO_GENERAL, "No X windows display available."); } return pDisplay; } Window createChildWindow(const SDL_SysWMinfo* pSDLWMInfo, XVisualInfo* pVisualInfo, const IntPoint& windowSize, Colormap& colormap) { // Create a child window with the required attributes to render into. XSetWindowAttributes swa; ::Display* pDisplay = pSDLWMInfo->info.x11.display; colormap = XCreateColormap(pDisplay, RootWindow(pDisplay, pVisualInfo->screen), pVisualInfo->visual, AllocNone); swa.colormap = colormap; swa.background_pixmap = None; swa.event_mask = StructureNotifyMask; Window win = XCreateWindow(pDisplay, pSDLWMInfo->info.x11.window, 0, 0, windowSize.x, windowSize.y, 0, pVisualInfo->depth, InputOutput, pVisualInfo->visual, CWColormap|CWEventMask, &swa); AVG_ASSERT(win); XMapWindow(pDisplay, win); return win; } } <|endoftext|>
<commit_before>#include "json.hpp" namespace LB { namespace json { struct value::base { virtual ~base() noexcept = default; friend bool operator==(base const &a, base const &b) noexcept { return a.equals(b); } friend bool operator<(base const &a, base const &b) noexcept { return a.less(b); } virtual bool equals(base const &) const noexcept = 0; virtual bool less(base const &) const noexcept = 0; virtual base *clone() const noexcept = 0; }; template<typename T> struct value::wrap final : base { T v; wrap() noexcept : v{} { } wrap(T const &t) noexcept : v(t) { } wrap(T &&t) noexcept : v(t) { } wrap(wrap const &w) noexcept : v(w.v) { } wrap(wrap &&) noexcept = default; wrap &operator=(wrap const &) = delete; wrap &operator=(wrap &&) = delete; virtual bool equals(base const &p) const noexcept override { if(auto w = dynamic_cast<wrap const *>(&p)) { return v == w->v; } return false; } virtual bool less(base const &p) const noexcept override { if(auto w = dynamic_cast<wrap const *>(&p)) { return v < w->v; } return false; } virtual wrap *clone() const noexcept override { return new wrap{*this}; } }; value::value(std::nullptr_t) noexcept : t{type::null} , p{nullptr} { } value::value(bool v) : t{type::boolean} , p{new wrap<bool>{v}} { } value::value(integer v) : t{type::integer} , p{new wrap<integer>{v}} { } value::value(real v) : t{type::real} , p{new wrap<real>{v}} { } value::value(string const &v) : t{type::string} , p{new wrap<string>{v}} { } value::value(string &&v) : t{type::string} , p{new wrap<string>{v}} { } value::value(char const *v) : t{type::string} , p{new wrap<string>{v}} { } value::value(array const &v) : t{type::array} , p{new wrap<array>{v}} { } value::value(array &&v) : t{type::array} , p{new wrap<array>{v}} { } value::value(object const &v) : t{type::object} , p{new wrap<object>{v}} { } value::value(object &&v) : t{type::object} , p{new wrap<object>{v}} { } value::value(value const &v) : t{v.t} , p{v.p? v.p->clone() : nullptr} { } value &value::operator=(value const &v) { t = v.t; p.reset(v.p? v.p->clone() : nullptr); return *this; } value::~value() noexcept = default; bool operator==(value const &a, value const &b) noexcept { return a.t == b.t && a.t != type::null && *a.p == *b.p; } bool operator<(value const &a, value const &b) noexcept { return json::operator</*work around VC++ bug*/(a.t, b.t) || ( a.t == b.t && a.t != type::null && *a.p < *b.p); } bool value::boolean_value() const { return dynamic_cast<wrap<bool> const &>(*p).v; } bool const &value::boolean_cref() const & { return dynamic_cast<wrap<bool> const &>(*p).v; } bool &value::boolean_ref() & { return dynamic_cast<wrap<bool> &>(*p).v; } integer value::integer_value() const { return dynamic_cast<wrap<integer> const &>(*p).v; } integer const &value::integer_cref() const & { return dynamic_cast<wrap<integer> const &>(*p).v; } integer &value::integer_ref() & { return dynamic_cast<wrap<integer> &>(*p).v; } real value::real_value() const { return dynamic_cast<wrap<real> const &>(*p).v; } real const &value::real_cref() const & { return dynamic_cast<wrap<real> const &>(*p).v; } real &value::real_ref() & { return dynamic_cast<wrap<real> &>(*p).v; } string const &value::string_cref() const & { return dynamic_cast<wrap<string> const &>(*p).v; } string &value::string_ref() & { return dynamic_cast<wrap<string> &>(*p).v; } array const &value::array_cref() const & { return dynamic_cast<wrap<array> const &>(*p).v; } array &value::array_ref() & { return dynamic_cast<wrap<array> &>(*p).v; } object const &value::object_cref() const & { return dynamic_cast<wrap<object> const &>(*p).v; } object &value::object_ref() & { return dynamic_cast<wrap<object> &>(*p).v; } string escape(string const &s) { string ret; for(auto it = std::cbegin(s); it != std::cend(s); ++it) { if(*it == '"') { ret += "\\\""; } else if(*it == '\\') { ret += "\\\\"; } else if(*it == '\b') { ret += "\\b"; } else if(*it == '\f') { ret += "\\f"; } else if(*it == '\n') { ret += "\\n"; } else if(*it == '\r') { ret += "\\r"; } else if(*it == '\t') { ret += "\\t"; } else if(*it & 0b10000000 || !std::isprint(*it)) { /*TODO std::uint16_t n = static_cast<unsigned char>(it->str()[0]); if(it->length() > 1) { n |= static_cast<std::uint16_t>(static_cast<unsigned char>(it->str()[1])) << 8; } ret += "\\u"; std::ostringstream os; os << std::hex << std::setw(4) << std::setfill('0') << n; ret += os.str(); */ } else { ret += *it; } } return ret; } string unescape(string const &s, bool exc = true) { string ret; for(auto it = std::cbegin(s); it != std::cend(s); ++it) { if(*it == '\\') { if(++it == std::cend(s)) { if(exc) { throw std::range_error{"invalid escape at end of string"}; } break; } if(*it == '\"' || *it == '\\' || *it == '/') { ret += *it; } else if(*it == 'b') { ret += '\b'; } else if(*it == 'f') { ret += '\f'; } else if(*it == 'n') { ret += '\n'; } else if(*it == 'r') { ret += '\r'; } else if(*it == 't') { ret += '\t'; } else if(*it == 'u') { /*TODO string hex; for(std::size_t i = 0; i < 4; ++i) { if(++it == std::end(map) || it->length() > 1) { if(exc) { throw std::range_error{"invalid Unicode escape at end of string"}; } return ret; } hex += *it; } std::uint16_t n; std::istringstream is {hex}; if(!(is >> std::hex >> n) && exc) { throw std::range_error{"invalid Unicode escape"}; } ret += static_cast<char>(static_cast<unsigned char>(n >> 8)); ret += static_cast<char>(static_cast<unsigned char>(n)); */ } else if(exc) { throw std::range_error{"invalid escape"}; } } else { ret += *it; } } return ret; } value deserialize(string const &s, deserialize_settings settings) { //TODO return nullptr; } void serialize(value const &v, string &s, std::size_t depth) { string const indent {depth? string(depth - std::size_t{1u}, '\t') : ""}; if(v == type::null) { s += "null"; } else if(auto w = dynamic_cast<value::wrap<bool> const *>(v.p.get())) { if(w->v) { s += indent + "true"; } else { s += indent + "false"; } } else if(auto w = dynamic_cast<value::wrap<integer> const *>(v.p.get())) { s += std::to_string(w->v); } else if(auto w = dynamic_cast<value::wrap<real> const *>(v.p.get())) { s += std::to_string(w->v); } else if(auto w = dynamic_cast<value::wrap<string> const *>(v.p.get())) { s += '"' + escape(w->v) + '"'; } else if(auto w = dynamic_cast<value::wrap<array> const *>(v.p.get())) { s += (depth? "[\n" : "["); bool first = true; for(auto const &e : w->v) { if(!first) { s += (depth? ",\n" : ","); } first = false; if(depth) { s += indent + '\t'; } serialize(e, s, (depth? depth + 1 : depth)); } s += indent + ']'; } else if(auto w = dynamic_cast<value::wrap<object> const *>(v.p.get())) { s += (depth? "{\n" : "{"); bool first = true; for(auto const &e : w->v) { if(!first) { s += (depth? ",\n" : ","); } first = false; if(depth) { s += indent + '\t'; } s += '"' + escape(e.first) + "\":"; if(depth) { if(e.second == type::array || e.second == type::object) { s += '\n' + indent; } else { s += ' '; } } serialize(e.second, s, (depth? depth + 1 : depth)); } s += indent + '}'; } } string serialize(value const &v, serialize_settings settings) { string s; serialize(v, s, (settings.formatting == serialize_formatting::pretty? 1 : 0)); return s; } } } <commit_msg>Fix pretty formatting<commit_after>#include "json.hpp" namespace LB { namespace json { struct value::base { virtual ~base() noexcept = default; friend bool operator==(base const &a, base const &b) noexcept { return a.equals(b); } friend bool operator<(base const &a, base const &b) noexcept { return a.less(b); } virtual bool equals(base const &) const noexcept = 0; virtual bool less(base const &) const noexcept = 0; virtual base *clone() const noexcept = 0; }; template<typename T> struct value::wrap final : base { T v; wrap() noexcept : v{} { } wrap(T const &t) noexcept : v(t) { } wrap(T &&t) noexcept : v(t) { } wrap(wrap const &w) noexcept : v(w.v) { } wrap(wrap &&) noexcept = default; wrap &operator=(wrap const &) = delete; wrap &operator=(wrap &&) = delete; virtual bool equals(base const &p) const noexcept override { if(auto w = dynamic_cast<wrap const *>(&p)) { return v == w->v; } return false; } virtual bool less(base const &p) const noexcept override { if(auto w = dynamic_cast<wrap const *>(&p)) { return v < w->v; } return false; } virtual wrap *clone() const noexcept override { return new wrap{*this}; } }; value::value(std::nullptr_t) noexcept : t{type::null} , p{nullptr} { } value::value(bool v) : t{type::boolean} , p{new wrap<bool>{v}} { } value::value(integer v) : t{type::integer} , p{new wrap<integer>{v}} { } value::value(real v) : t{type::real} , p{new wrap<real>{v}} { } value::value(string const &v) : t{type::string} , p{new wrap<string>{v}} { } value::value(string &&v) : t{type::string} , p{new wrap<string>{v}} { } value::value(char const *v) : t{type::string} , p{new wrap<string>{v}} { } value::value(array const &v) : t{type::array} , p{new wrap<array>{v}} { } value::value(array &&v) : t{type::array} , p{new wrap<array>{v}} { } value::value(object const &v) : t{type::object} , p{new wrap<object>{v}} { } value::value(object &&v) : t{type::object} , p{new wrap<object>{v}} { } value::value(value const &v) : t{v.t} , p{v.p? v.p->clone() : nullptr} { } value &value::operator=(value const &v) { t = v.t; p.reset(v.p? v.p->clone() : nullptr); return *this; } value::~value() noexcept = default; bool operator==(value const &a, value const &b) noexcept { return a.t == b.t && a.t != type::null && *a.p == *b.p; } bool operator<(value const &a, value const &b) noexcept { return json::operator</*work around VC++ bug*/(a.t, b.t) || ( a.t == b.t && a.t != type::null && *a.p < *b.p); } bool value::boolean_value() const { return dynamic_cast<wrap<bool> const &>(*p).v; } bool const &value::boolean_cref() const & { return dynamic_cast<wrap<bool> const &>(*p).v; } bool &value::boolean_ref() & { return dynamic_cast<wrap<bool> &>(*p).v; } integer value::integer_value() const { return dynamic_cast<wrap<integer> const &>(*p).v; } integer const &value::integer_cref() const & { return dynamic_cast<wrap<integer> const &>(*p).v; } integer &value::integer_ref() & { return dynamic_cast<wrap<integer> &>(*p).v; } real value::real_value() const { return dynamic_cast<wrap<real> const &>(*p).v; } real const &value::real_cref() const & { return dynamic_cast<wrap<real> const &>(*p).v; } real &value::real_ref() & { return dynamic_cast<wrap<real> &>(*p).v; } string const &value::string_cref() const & { return dynamic_cast<wrap<string> const &>(*p).v; } string &value::string_ref() & { return dynamic_cast<wrap<string> &>(*p).v; } array const &value::array_cref() const & { return dynamic_cast<wrap<array> const &>(*p).v; } array &value::array_ref() & { return dynamic_cast<wrap<array> &>(*p).v; } object const &value::object_cref() const & { return dynamic_cast<wrap<object> const &>(*p).v; } object &value::object_ref() & { return dynamic_cast<wrap<object> &>(*p).v; } string escape(string const &s) { string ret; for(auto it = std::cbegin(s); it != std::cend(s); ++it) { if(*it == '"') { ret += "\\\""; } else if(*it == '\\') { ret += "\\\\"; } else if(*it == '\b') { ret += "\\b"; } else if(*it == '\f') { ret += "\\f"; } else if(*it == '\n') { ret += "\\n"; } else if(*it == '\r') { ret += "\\r"; } else if(*it == '\t') { ret += "\\t"; } else if(*it & 0b10000000 || !std::isprint(*it)) { /*TODO std::uint16_t n = static_cast<unsigned char>(it->str()[0]); if(it->length() > 1) { n |= static_cast<std::uint16_t>(static_cast<unsigned char>(it->str()[1])) << 8; } ret += "\\u"; std::ostringstream os; os << std::hex << std::setw(4) << std::setfill('0') << n; ret += os.str(); */ } else { ret += *it; } } return ret; } string unescape(string const &s, bool exc = true) { string ret; for(auto it = std::cbegin(s); it != std::cend(s); ++it) { if(*it == '\\') { if(++it == std::cend(s)) { if(exc) { throw std::range_error{"invalid escape at end of string"}; } break; } if(*it == '\"' || *it == '\\' || *it == '/') { ret += *it; } else if(*it == 'b') { ret += '\b'; } else if(*it == 'f') { ret += '\f'; } else if(*it == 'n') { ret += '\n'; } else if(*it == 'r') { ret += '\r'; } else if(*it == 't') { ret += '\t'; } else if(*it == 'u') { /*TODO string hex; for(std::size_t i = 0; i < 4; ++i) { if(++it == std::end(map) || it->length() > 1) { if(exc) { throw std::range_error{"invalid Unicode escape at end of string"}; } return ret; } hex += *it; } std::uint16_t n; std::istringstream is {hex}; if(!(is >> std::hex >> n) && exc) { throw std::range_error{"invalid Unicode escape"}; } ret += static_cast<char>(static_cast<unsigned char>(n >> 8)); ret += static_cast<char>(static_cast<unsigned char>(n)); */ } else if(exc) { throw std::range_error{"invalid escape"}; } } else { ret += *it; } } return ret; } value deserialize(string const &s, deserialize_settings settings) { //TODO return nullptr; } void serialize(value const &v, string &s, std::size_t depth) { string const indent {depth? string(depth - std::size_t{1u}, '\t') : ""}; if(v == type::null) { s += "null"; } else if(auto w = dynamic_cast<value::wrap<bool> const *>(v.p.get())) { if(w->v) { s += "true"; } else { s += "false"; } } else if(auto w = dynamic_cast<value::wrap<integer> const *>(v.p.get())) { s += std::to_string(w->v); } else if(auto w = dynamic_cast<value::wrap<real> const *>(v.p.get())) { s += std::to_string(w->v); } else if(auto w = dynamic_cast<value::wrap<string> const *>(v.p.get())) { s += '"' + escape(w->v) + '"'; } else if(auto w = dynamic_cast<value::wrap<array> const *>(v.p.get())) { s += (depth? indent + "[\n" : "["); bool first = true; for(auto const &e : w->v) { if(!first) { s += (depth? ",\n" : ","); } first = false; if(depth && e != type::array && e != type::object) { s += indent + '\t'; } serialize(e, s, (depth? depth + 1 : depth)); } if(depth && !first) { s += '\n'; } s += indent + ']'; } else if(auto w = dynamic_cast<value::wrap<object> const *>(v.p.get())) { s += (depth? indent + "{\n" : "{"); bool first = true; for(auto const &e : w->v) { if(!first) { s += (depth? ",\n" : ","); } first = false; if(depth) { s += indent + '\t'; } s += '"' + escape(e.first) + "\":"; if(depth) { if(e.second == type::array || e.second == type::object) { s += '\n'; } else { s += ' '; } } serialize(e.second, s, (depth? depth + 1 : depth)); } if(depth && !first) { s += '\n'; } s += indent + "}"; } } string serialize(value const &v, serialize_settings settings) { string s; serialize(v, s, (settings.formatting == serialize_formatting::pretty? 1 : 0)); return s; } } } <|endoftext|>
<commit_before>#include "tpunit++.hpp" #include "mock4cpp.h" #include <string> struct BasicVerification: tpunit::TestFixture { BasicVerification() : tpunit::TestFixture( // TEST(BasicVerification::verify_should_not_throw_exception_if_method_was_called), // TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_called), // TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed), // TEST(BasicVerification::verify_method_was_called_at_least_once), // TEST(BasicVerification::verify_method_was_called_exactly_once), // TEST(BasicVerification::verify_method_was_never_called), // TEST(BasicVerification::verify_method_was_called_exactly_x_times), // TEST(BasicVerification::should_throw_IllegalArgumentException_on_negative_times_argument), // TEST(BasicVerification::verify_with_filter), // TEST(BasicVerification::verify_concatenated_sequence), // TEST(BasicVerification::verify_repeated_sequence), // TEST(BasicVerification::verify_multi_sequences_in_order), TEST(BasicVerification::verify_no_other_invocations_for_mock),// TEST(BasicVerification::verify_no_other_invocations_for_method_filter)// ) // { } struct SomeInterface { virtual int func(int) = 0; virtual void proc(int) = 0; }; void verify_should_throw_MethodCallVerificationException_if_method_was_not_called() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); } void verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); } void verify_should_not_throw_exception_if_method_was_called() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.proc(1); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); } void verify_method_was_called_at_least_once() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.proc(2); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); i.func(1); i.proc(2); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); } void verify_method_was_called_exactly_once() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); i.func(1); i.proc(1); Verify(mock[&SomeInterface::func]).Once(); Verify(mock[&SomeInterface::proc]).Once(); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); } void verify_method_was_never_called() { Mock<SomeInterface> mock; Verify(mock[&SomeInterface::func]).Never(); Verify(mock[&SomeInterface::proc]).Never(); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); Verify(mock[&SomeInterface::func]).Never(); Verify(mock[&SomeInterface::proc]).Never(); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Never(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Never(), mock4cpp::MethodCallVerificationException); } void verify_method_was_called_exactly_x_times() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); i.func(1); i.func(1); i.proc(1); i.proc(1); Verify(mock[&SomeInterface::func]).Times(2); Verify(mock[&SomeInterface::proc]).Times(2); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); } void should_throw_IllegalArgumentException_on_negative_times_argument() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(-1), mock4cpp::IllegalArgumentException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(-1), mock4cpp::IllegalArgumentException); } void verify_with_filter() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); Verify(mock[&SomeInterface::func].Using(1)); ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(2)), mock4cpp::MethodCallVerificationException); } void verify_concatenated_sequence() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.func(2); i.func(3); i.func(4); Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2)).Once(); Verify(mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)).AtLeastOnce(); Verify(mock[&SomeInterface::func].Using(3) + mock[&SomeInterface::func].Using(4)).Once(); Verify(mock[&SomeInterface::func] + mock[&SomeInterface::func]).Twice(); Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(3)).Never(); ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(3)), mock4cpp::MethodCallVerificationException); } void verify_repeated_sequence() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.func(2); i.func(3); i.func(1); i.func(2); i.func(3); Verify(mock[&SomeInterface::func] * 1).Times(6); Verify(mock[&SomeInterface::func] * 2).Times(3); Verify(mock[&SomeInterface::func] * 3).Times(2); Verify(mock[&SomeInterface::func] * 4).Times(1); Verify(mock[&SomeInterface::func] * 5).Times(1); Verify(mock[&SomeInterface::func] * 6).Times(1); Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)).Twice(); Verify((mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)) * 2).Once(); Verify(mock[&SomeInterface::func].Using(1) * 2).Never(); ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(1) * 2), mock4cpp::MethodCallVerificationException); } void verify_multi_sequences_in_order() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.func(2); i.func(3); i.func(1); i.func(2); i.func(3); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(1); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(1); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(1); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(2); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(3); Verify( // mock[&SomeInterface::func]) // .Times(6); Verify( // mock[&SomeInterface::func].Using(1) + // mock[&SomeInterface::func].Using(2) + // mock[&SomeInterface::func].Using(3)) // .Times(2); Verify( // mock[&SomeInterface::func].Using(1) + // mock[&SomeInterface::func].Using(2)) // .Times(2); Verify( // mock[&SomeInterface::func].Using(2) + // mock[&SomeInterface::func].Using(3)) // .Times(2); Verify( // mock[&SomeInterface::func].Using(1)) // .Times(2); Verify(mock[&SomeInterface::func].Using(2) + // mock[&SomeInterface::func].Using(1)).Never(); } void verify_no_other_invocations_for_mock() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func]); SomeInterface &i = mock.get(); VerifyNoOtherInvocations(mock); i.func(1); i.func(1); ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]).AtLeastOnce(); VerifyNoOtherInvocations(mock); i.func(1); i.func(1); ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]*3); ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]*4); VerifyNoOtherInvocations(mock); } void verify_no_other_invocations_for_method_filter() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func]); SomeInterface &i = mock.get(); VerifyNoOtherInvocations(mock[&SomeInterface::func]); i.func(1); i.func(1); ASSERT_THROW(VerifyNoOtherInvocations(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]).AtLeastOnce(); VerifyNoOtherInvocations(mock[&SomeInterface::func]); i.func(1); i.func(1); ASSERT_THROW(VerifyNoOtherInvocations(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]*3); ASSERT_THROW(VerifyNoOtherInvocations(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]*4); VerifyNoOtherInvocations(mock[&SomeInterface::func]); } } __BasicVerification; <commit_msg>add verifyNoOtherInvocations tests<commit_after>#include "tpunit++.hpp" #include "mock4cpp.h" #include <string> struct BasicVerification: tpunit::TestFixture { BasicVerification() : tpunit::TestFixture( // TEST(BasicVerification::verify_should_not_throw_exception_if_method_was_called), // TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_called), // TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed), // TEST(BasicVerification::verify_method_was_called_at_least_once), // TEST(BasicVerification::verify_method_was_called_exactly_once), // TEST(BasicVerification::verify_method_was_never_called), // TEST(BasicVerification::verify_method_was_called_exactly_x_times), // TEST(BasicVerification::should_throw_IllegalArgumentException_on_negative_times_argument), // TEST(BasicVerification::verify_with_filter), // TEST(BasicVerification::verify_concatenated_sequence), // TEST(BasicVerification::verify_repeated_sequence), // TEST(BasicVerification::verify_multi_sequences_in_order), TEST(BasicVerification::verify_no_other_invocations_for_mock),// TEST(BasicVerification::verify_no_other_invocations_for_method_filter)// ) // { } struct SomeInterface { virtual int func(int) = 0; virtual void proc(int) = 0; }; void verify_should_throw_MethodCallVerificationException_if_method_was_not_called() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); } void verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); } void verify_should_not_throw_exception_if_method_was_called() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.proc(1); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); } void verify_method_was_called_at_least_once() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.proc(2); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); i.func(1); i.proc(2); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); } void verify_method_was_called_exactly_once() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); i.func(1); i.proc(1); Verify(mock[&SomeInterface::func]).Once(); Verify(mock[&SomeInterface::proc]).Once(); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); } void verify_method_was_never_called() { Mock<SomeInterface> mock; Verify(mock[&SomeInterface::func]).Never(); Verify(mock[&SomeInterface::proc]).Never(); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); Verify(mock[&SomeInterface::func]).Never(); Verify(mock[&SomeInterface::proc]).Never(); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Never(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Never(), mock4cpp::MethodCallVerificationException); } void verify_method_was_called_exactly_x_times() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); i.func(1); i.func(1); i.proc(1); i.proc(1); Verify(mock[&SomeInterface::func]).Times(2); Verify(mock[&SomeInterface::proc]).Times(2); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); } void should_throw_IllegalArgumentException_on_negative_times_argument() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(-1), mock4cpp::IllegalArgumentException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(-1), mock4cpp::IllegalArgumentException); } void verify_with_filter() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); Verify(mock[&SomeInterface::func].Using(1)); ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(2)), mock4cpp::MethodCallVerificationException); } void verify_concatenated_sequence() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.func(2); i.func(3); i.func(4); Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2)).Once(); Verify(mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)).AtLeastOnce(); Verify(mock[&SomeInterface::func].Using(3) + mock[&SomeInterface::func].Using(4)).Once(); Verify(mock[&SomeInterface::func] + mock[&SomeInterface::func]).Twice(); Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(3)).Never(); ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(3)), mock4cpp::MethodCallVerificationException); } void verify_repeated_sequence() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.func(2); i.func(3); i.func(1); i.func(2); i.func(3); Verify(mock[&SomeInterface::func] * 1).Times(6); Verify(mock[&SomeInterface::func] * 2).Times(3); Verify(mock[&SomeInterface::func] * 3).Times(2); Verify(mock[&SomeInterface::func] * 4).Times(1); Verify(mock[&SomeInterface::func] * 5).Times(1); Verify(mock[&SomeInterface::func] * 6).Times(1); Verify(mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)).Twice(); Verify((mock[&SomeInterface::func].Using(1) + mock[&SomeInterface::func].Using(2) + mock[&SomeInterface::func].Using(3)) * 2).Once(); Verify(mock[&SomeInterface::func].Using(1) * 2).Never(); ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(1) * 2), mock4cpp::MethodCallVerificationException); } void verify_multi_sequences_in_order() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.func(2); i.func(3); i.func(1); i.func(2); i.func(3); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(1); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(1); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(1); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(2); Verify( // mock[&SomeInterface::func], // mock[&SomeInterface::func]) // .Times(3); Verify( // mock[&SomeInterface::func]) // .Times(6); Verify( // mock[&SomeInterface::func].Using(1) + // mock[&SomeInterface::func].Using(2) + // mock[&SomeInterface::func].Using(3)) // .Times(2); Verify( // mock[&SomeInterface::func].Using(1) + // mock[&SomeInterface::func].Using(2)) // .Times(2); Verify( // mock[&SomeInterface::func].Using(2) + // mock[&SomeInterface::func].Using(3)) // .Times(2); Verify( // mock[&SomeInterface::func].Using(1)) // .Times(2); Verify(mock[&SomeInterface::func].Using(2) + // mock[&SomeInterface::func].Using(1)).Never(); } void verify_no_other_invocations_for_mock() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func]); SomeInterface &i = mock.get(); VerifyNoOtherInvocations(mock); i.func(1); i.func(1); ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]).AtLeastOnce(); VerifyNoOtherInvocations(mock); i.func(1); i.func(1); ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]*3); ASSERT_THROW(VerifyNoOtherInvocations(mock), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]*4); VerifyNoOtherInvocations(mock); } void verify_no_other_invocations_for_method_filter() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func]); SomeInterface &i = mock.get(); VerifyNoOtherInvocations(mock[&SomeInterface::func]); i.func(1); i.func(1); ASSERT_THROW(VerifyNoOtherInvocations(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]).AtLeastOnce(); VerifyNoOtherInvocations(mock[&SomeInterface::func]); i.func(1); i.func(1); ASSERT_THROW(VerifyNoOtherInvocations(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]*3); ASSERT_THROW(VerifyNoOtherInvocations(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); Verify(mock[&SomeInterface::func]*4); VerifyNoOtherInvocations(mock[&SomeInterface::func].Using(1)); } } __BasicVerification; <|endoftext|>
<commit_before> #include "lexer.h" #include <regex> #include <cstring> #include <vector> #include <iostream> #include <cassert> #include <stdio.h> #include "file_mapped_io.h" internal_ bool hasFileExtension(const char* filename, const char* extension); internal_ bool isMeaninglessChar(LexingIterator& lexer); Token::Token() { } Token::Token(LexingIterator lex_itr, TokenIdentifier identifier) : index(lex_itr.token_begin - lex_itr.begin), length((lex_itr.itr - lex_itr.token_begin) + 1), id(identifier), line_count(lex_itr.token_line), column_count(lex_itr.token_column) { } // Temporary check internal_ bool hasFileExtension(const char* filename, const char* extension) { for (;;) { if (*filename == '\0') { return false; } else if (*filename == '.') { ++filename; break; } else { ++filename; } } return !strcmp(filename, extension); } inline bool isMeaninglessChar(LexingIterator& lexer) { if (*lexer.itr == '\t' || *lexer.itr == '\r' || *lexer.itr == ' ') { return true; } else if (*lexer.itr == '\n') { ++lexer.line_count; lexer.last_line_begin = lexer.itr; return true; } else { return false; } } inline static bool nextNCharsExist(LexingIterator lex_itr, int n) { return n <= lex_itr.end - lex_itr.itr; } std::vector<Token> tokenize(const char* filename) { if (!hasFileExtension(filename, "c")) { std::cout << "Loaded unsupported file format: " << filename << std::endl; } FileMapper filemap(filename); u32 file_size = static_cast<u32>(filemap.getFileSize()); const char* file_begin = static_cast<const char*>(filemap.map(0, file_size)); const char* file_end = file_begin + file_size; LexingIterator lexer = {file_begin, file_begin, file_end, file_begin - 1, 1, file_begin, 1, 1}; std::vector<Token> out_tokens; for (; lexer.itr != lexer.end; ++lexer.itr) { if (isMeaninglessChar(lexer)) continue; lexer.token_begin = lexer.itr; lexer.token_line = lexer.line_count; lexer.token_column = lexer.itr - lexer.last_line_begin; switch (*lexer.itr) { case '(': { out_tokens.push_back(Token(lexer, TokenIdentifier::OPEN_PARANTHESIS)); continue; } case ')': { out_tokens.push_back(Token(lexer, TokenIdentifier::CLOSE_PARANTHESIS)); continue; } case '[': { out_tokens.push_back(Token(lexer, TokenIdentifier::OPEN_SQUARE_BRACKET)); continue; } case ']': { out_tokens.push_back(Token(lexer, TokenIdentifier::CLOSE_SQUARE_BRACKET)); continue; } case '{': { out_tokens.push_back(Token(lexer, TokenIdentifier::OPEN_BRACKET)); continue; } case '}': { out_tokens.push_back(Token(lexer, TokenIdentifier::CLOSE_BRACKET)); continue; } } // Detect coments if (nextNCharsExist(lexer, 2) && lexer.itr[0] == '/') { if (lexer.itr[1] == '*') { ++lexer.itr; // C-style comment while (++lexer.itr != lexer.end) { if (isMeaninglessChar(lexer)) continue; if (lexer.itr[0] == '*' && nextNCharsExist(lexer, 2) && lexer.itr[1] == '/') { ++lexer.itr; out_tokens.push_back(Token(lexer, TokenIdentifier::COMMENT)); break; } } continue; } else if (lexer.itr[1] == '/') { // C++ style comment while (++lexer.itr != lexer.end) { if (*lexer.itr == '\n') { out_tokens.push_back(Token(lexer, TokenIdentifier::COMMENT)); break; } } continue; } } // Detect strings if (*lexer.itr == '"') { // Find a matching ", except for an escaped " while (++lexer.itr != lexer.end) { if (lexer.itr[0] == '"' && !(lexer.itr[-1] == '\\')) { out_tokens.push_back(Token(lexer, TokenIdentifier::LITERAL_STRING)); break; } } continue; } // Detect a char if (*lexer.itr == '\'') { while (++lexer.itr != lexer.end) { // Find a matchin ', except for an escaped ' if (lexer.itr[0] == '\'' && !(lexer.itr[-1] == '\\')) { out_tokens.push_back(Token(lexer, TokenIdentifier::LITERAL_CHAR)); break; } } continue; } // Detect number types if ((*lexer.itr >= '0' && *lexer.itr <= '9') || *lexer.itr == '.') { bool is_float = false; if (*lexer.itr == '.') is_float = true; while (++lexer.itr != lexer.end && (*lexer.itr >= '0' && *lexer.itr <= '9') || *lexer.itr == '.') { } // Number ended out_tokens.push_back( Token(lexer, is_float ? TokenIdentifier::LITERAL_FLOAT : TokenIdentifier::LITERAL_INT)); continue; } // Otherwise assume its some kind of word do { ++lexer.itr; } while (lexer.itr != lexer.end && *lexer.itr != '\n' && *lexer.itr != '\t' && *lexer.itr != '\r' && *lexer.itr != ' ' && *lexer.itr != '(' && *lexer.itr != ')' && *lexer.itr != ']' && *lexer.itr != '{' && *lexer.itr != '}'); --lexer.itr; // back off by one since spaces, newlines etc... is not a part of the word out_tokens.push_back(Token(lexer, TokenIdentifier::NAME)); } out_tokens.push_back(Token(lexer, TokenIdentifier::END_OF_FILE)); for (auto itr = out_tokens.begin(); itr != out_tokens.end(); ++itr) { printf("Token nr %d.\nIndex: %d\n Length: %d\n id: %d\n line_count: %d\n column_count: %d\n Contents: \n%.*s\n\n", (int)(itr - out_tokens.begin()), (int)itr->index, (int)itr->length, (int)itr->id, (int)itr->line_count, (int)itr->column_count, (int)itr->length, lexer.begin + itr->index); } return out_tokens; } Lexer::Lexer(const char* regex, const char* lexing_data, unsigned int input_length) : lexing_data{lexing_data, lexing_data, lexing_data + input_length, lexing_data - 1, 1, lexing_data , 1, 1} { buildDFA(regex); } Token Lexer::nextToken() { unsigned int state = dfa.begin_state; while (lexing_data.itr != lexing_data.end) { if (*lexing_data.itr == '\n') { ++lexing_data.line_count; lexing_data.last_line_begin = lexing_data.itr; } if (state == dfa.begin_state) { // start over lexing_data.token_begin = lexing_data.itr; lexing_data.token_line = lexing_data.line_count; lexing_data.token_column = lexing_data.itr - lexing_data.last_line_begin; } state = dfa.states[state * dfa.alphabet_size + (*lexing_data.itr)]; if (isFinishState(state)) { return Token(lexing_data, TokenIdentifier::NAME); } ++lexing_data.itr; } return Token(lexing_data, TokenIdentifier::END_OF_FILE); } inline bool Lexer::isFinishState(unsigned int state) { return dfa.accept_states.find(state) != dfa.accept_states.end(); } void Lexer::reset() { lexing_data.itr = lexing_data.begin; lexing_data.last_line_begin = lexing_data.begin - 1; lexing_data.token_begin = lexing_data.begin; lexing_data.line_count = 1; } // TODO: How to deal with |, e.g. (abc)* | bca | cb+ unsigned int Lexer::estimateNumStates(const char* regex) { unsigned int total_states = 1; // always have start state for (const char* itr = regex; *itr != '\0'; ++itr) { switch (*itr) { // deal with special metacharacters case '*': { // don't need a new state for * metacharacter --total_states; continue; } case '+': { continue; } case '[': { // only need one state until we find a matchin ']' // move the iterator to that position and continue do { ++itr; if (*itr == '\0') { std::cerr << "Bad regular expression: no matching ']' for '['" << std::endl; } } while (*itr != ']'); break; } case '\\': { // we escape the next metacharacter so just walk over it by one ++itr; } case '(': { // a group... continue to next character continue; } case ')': { // a closing group... continue to next character } default: { // normal character break; } } ++total_states; } return total_states; } void Lexer::buildDFA(const char* regex) { dfa.num_states = estimateNumStates(regex); const unsigned int dfa_width = dfa.alphabet_size; dfa.states = static_cast<unsigned int*>( operator new(dfa.num_states * sizeof(*dfa.states) * dfa_width)); memset(dfa.states, 0, dfa.num_states * sizeof(*dfa.states) * dfa_width); // dfa.states operates as follows // dfa.states[STATE_NUMBER * dfa_width + INPUT_CHARACTER] = NEW_STATE_NUMBER std::vector<char> next_transition; next_transition.reserve(128); unsigned int current_state = -1; for (const char* itr = regex; *itr != '\0'; ++itr) { ++current_state; assert(current_state != dfa.num_states); next_transition.clear(); switch (*itr) { // deal with special metacharacters case '[': { // only need one state until we find a matchin ']' // move the iterator to that position and continue const char* look_ahead = ++itr; const char* first_char = itr; bool flip_transition = false; if (*first_char == '^') { flip_transition = true; ++look_ahead; for (char i = 0; i < 128; ++i) { next_transition.push_back(i); } } char last_val = *look_ahead; while (*look_ahead != ']') { switch (*look_ahead) { case '\0': { std::cerr << "Bad regular expression: no matching ']' for '['" << std::endl; } case '-': { ++look_ahead; if (*look_ahead == '\\') { ++look_ahead; } char end_val = *look_ahead; if (end_val < last_val) { // swap to allow [a-z] to have same semantic meaning as [z-a] char tmp = end_val; end_val = last_val; last_val = tmp; } for (char val = last_val; val <= end_val; ++val) { if (flip_transition) { next_transition.erase(std::lower_bound(next_transition.begin(), next_transition.end(), val)); } else { next_transition.push_back(val); } } } default: { if (flip_transition) { next_transition.erase(std::lower_bound(next_transition.begin(), next_transition.end(), *look_ahead)); } else { next_transition.push_back(*look_ahead); } } } ++look_ahead; } itr = look_ahead; break; } case '\\': { // we escape the next metacharacter so just walk over it by one ++itr; // don't break, instead fall down to default } case '(': { // a group... continue to next character continue; } case ')': { // a closing group... continue to next character } default: { next_transition.push_back(*itr); // normal character break; } } // we now have collected new state transitions in next_transition // look for '*', '+' etc metacharacters to determine how to write the trasnitions const char* look_ahead = itr + 1; unsigned int next_state = current_state + 1; switch (*look_ahead) { case '*': { for (auto char_transition : next_transition) { if (dfa.states[current_state * dfa_width + char_transition] == dfa.begin_state) { dfa.states[current_state * dfa_width + char_transition] = current_state; } } itr = look_ahead; break; } case '+': { for (auto char_transition : next_transition) { if (dfa.states[current_state * dfa_width + char_transition] == dfa.begin_state) { dfa.states[current_state * dfa_width + char_transition] = next_state; dfa.states[next_state * dfa_width + char_transition] = next_state; } } itr = look_ahead; break; } default: { for (auto char_transition : next_transition) { if (dfa.states[current_state * dfa_width + char_transition] == dfa.begin_state) { dfa.states[current_state * dfa_width + char_transition] = next_state; } } break; } } } dfa.accept_states.insert(std::pair<unsigned int, unsigned int>(current_state + 1, 0)); } <commit_msg>DFA improvements<commit_after> #include "lexer.h" #include <regex> #include <cstring> #include <vector> #include <iostream> #include <cassert> #include <stdio.h> #include "file_mapped_io.h" internal_ bool hasFileExtension(const char* filename, const char* extension); internal_ bool isMeaninglessChar(LexingIterator& lexer); Token::Token() { } Token::Token(LexingIterator lex_itr, TokenIdentifier identifier) : index(lex_itr.token_begin - lex_itr.begin), length(lex_itr.itr - lex_itr.token_begin), id(identifier), line_count(lex_itr.token_line), column_count(lex_itr.token_column) { } // Temporary check internal_ bool hasFileExtension(const char* filename, const char* extension) { for (;;) { if (*filename == '\0') { return false; } else if (*filename == '.') { ++filename; break; } else { ++filename; } } return !strcmp(filename, extension); } inline bool isMeaninglessChar(LexingIterator& lexer) { if (*lexer.itr == '\t' || *lexer.itr == '\r' || *lexer.itr == ' ') { return true; } else if (*lexer.itr == '\n') { ++lexer.line_count; lexer.last_line_begin = lexer.itr; return true; } else { return false; } } inline static bool nextNCharsExist(LexingIterator lex_itr, int n) { return n <= lex_itr.end - lex_itr.itr; } std::vector<Token> tokenize(const char* filename) { if (!hasFileExtension(filename, "c")) { std::cout << "Loaded unsupported file format: " << filename << std::endl; } FileMapper filemap(filename); u32 file_size = static_cast<u32>(filemap.getFileSize()); const char* file_begin = static_cast<const char*>(filemap.map(0, file_size)); const char* file_end = file_begin + file_size; LexingIterator lexer = {file_begin, file_begin, file_end, file_begin - 1, 1, file_begin, 1, 1}; std::vector<Token> out_tokens; for (; lexer.itr != lexer.end; ++lexer.itr) { if (isMeaninglessChar(lexer)) continue; lexer.token_begin = lexer.itr; lexer.token_line = lexer.line_count; lexer.token_column = lexer.itr - lexer.last_line_begin; switch (*lexer.itr) { case '(': { out_tokens.push_back(Token(lexer, TokenIdentifier::OPEN_PARANTHESIS)); continue; } case ')': { out_tokens.push_back(Token(lexer, TokenIdentifier::CLOSE_PARANTHESIS)); continue; } case '[': { out_tokens.push_back(Token(lexer, TokenIdentifier::OPEN_SQUARE_BRACKET)); continue; } case ']': { out_tokens.push_back(Token(lexer, TokenIdentifier::CLOSE_SQUARE_BRACKET)); continue; } case '{': { out_tokens.push_back(Token(lexer, TokenIdentifier::OPEN_BRACKET)); continue; } case '}': { out_tokens.push_back(Token(lexer, TokenIdentifier::CLOSE_BRACKET)); continue; } } // Detect coments if (nextNCharsExist(lexer, 2) && lexer.itr[0] == '/') { if (lexer.itr[1] == '*') { ++lexer.itr; // C-style comment while (++lexer.itr != lexer.end) { if (isMeaninglessChar(lexer)) continue; if (lexer.itr[0] == '*' && nextNCharsExist(lexer, 2) && lexer.itr[1] == '/') { ++lexer.itr; out_tokens.push_back(Token(lexer, TokenIdentifier::COMMENT)); break; } } continue; } else if (lexer.itr[1] == '/') { // C++ style comment while (++lexer.itr != lexer.end) { if (*lexer.itr == '\n') { out_tokens.push_back(Token(lexer, TokenIdentifier::COMMENT)); break; } } continue; } } // Detect strings if (*lexer.itr == '"') { // Find a matching ", except for an escaped " while (++lexer.itr != lexer.end) { if (lexer.itr[0] == '"' && !(lexer.itr[-1] == '\\')) { out_tokens.push_back(Token(lexer, TokenIdentifier::LITERAL_STRING)); break; } } continue; } // Detect a char if (*lexer.itr == '\'') { while (++lexer.itr != lexer.end) { // Find a matchin ', except for an escaped ' if (lexer.itr[0] == '\'' && !(lexer.itr[-1] == '\\')) { out_tokens.push_back(Token(lexer, TokenIdentifier::LITERAL_CHAR)); break; } } continue; } // Detect number types if ((*lexer.itr >= '0' && *lexer.itr <= '9') || *lexer.itr == '.') { bool is_float = false; if (*lexer.itr == '.') is_float = true; while (++lexer.itr != lexer.end && (*lexer.itr >= '0' && *lexer.itr <= '9') || *lexer.itr == '.') { } // Number ended out_tokens.push_back( Token(lexer, is_float ? TokenIdentifier::LITERAL_FLOAT : TokenIdentifier::LITERAL_INT)); continue; } // Otherwise assume its some kind of word do { ++lexer.itr; } while (lexer.itr != lexer.end && *lexer.itr != '\n' && *lexer.itr != '\t' && *lexer.itr != '\r' && *lexer.itr != ' ' && *lexer.itr != '(' && *lexer.itr != ')' && *lexer.itr != ']' && *lexer.itr != '{' && *lexer.itr != '}'); --lexer.itr; // back off by one since spaces, newlines etc... is not a part of the word out_tokens.push_back(Token(lexer, TokenIdentifier::NAME)); } out_tokens.push_back(Token(lexer, TokenIdentifier::END_OF_FILE)); for (auto itr = out_tokens.begin(); itr != out_tokens.end(); ++itr) { printf("Token nr %d.\nIndex: %d\n Length: %d\n id: %d\n line_count: %d\n column_count: %d\n Contents: \n%.*s\n\n", (int)(itr - out_tokens.begin()), (int)itr->index, (int)itr->length, (int)itr->id, (int)itr->line_count, (int)itr->column_count, (int)itr->length, lexer.begin + itr->index); } return out_tokens; } Lexer::Lexer(const char* regex, const char* lexing_data, unsigned int input_length) : lexing_data{lexing_data, lexing_data, lexing_data + input_length, lexing_data - 1, 1, lexing_data , 1, 1} { buildDFA(regex); } Token Lexer::nextToken() { unsigned int state = dfa.begin_state; while (lexing_data.itr != lexing_data.end) { if (*lexing_data.itr == '\n') { ++lexing_data.line_count; lexing_data.last_line_begin = lexing_data.itr; } if (state == dfa.begin_state) { // start over lexing_data.token_begin = lexing_data.itr; lexing_data.token_line = lexing_data.line_count; lexing_data.token_column = lexing_data.itr - lexing_data.last_line_begin; } state = dfa.states[state * dfa.alphabet_size + (*lexing_data.itr)]; ++lexing_data.itr; if (state != 0) { int breakme = 5; } if (isFinishState(state)) { return Token(lexing_data, TokenIdentifier::NAME); } } return Token(lexing_data, TokenIdentifier::END_OF_FILE); } inline bool Lexer::isFinishState(unsigned int state) { return dfa.accept_states.find(state) != dfa.accept_states.end(); } void Lexer::reset() { lexing_data.itr = lexing_data.begin; lexing_data.last_line_begin = lexing_data.begin - 1; lexing_data.token_begin = lexing_data.begin; lexing_data.line_count = 1; } // TODO: How to deal with |, e.g. (abc)* | bca | cb+ unsigned int Lexer::estimateNumStates(const char* regex) { unsigned int total_states = 1; // always have start state for (const char* itr = regex; *itr != '\0'; ++itr) { switch (*itr) { // deal with special metacharacters case '*': { // don't need a new state for * metacharacter --total_states; continue; } case '+': { continue; } case '[': { // only need one state until we find a matchin ']' // move the iterator to that position and continue do { ++itr; if (*itr == '\0') { std::cerr << "Bad regular expression: no matching ']' for '['" << std::endl; } } while (*itr != ']'); break; } case '\\': { // we escape the next metacharacter so just walk over it by one ++itr; } case '(': { // a group... continue to next character continue; } case ')': { // a closing group... continue to next character } default: { // normal character break; } } ++total_states; } return total_states; } void Lexer::buildDFA(const char* regex) { dfa.num_states = estimateNumStates(regex); const unsigned int dfa_width = dfa.alphabet_size; dfa.states = static_cast<unsigned int*>( operator new(dfa.num_states * sizeof(*dfa.states) * dfa_width)); memset(dfa.states, 0, dfa.num_states * sizeof(*dfa.states) * dfa_width); // dfa.states operates as follows // dfa.states[STATE_NUMBER * dfa_width + INPUT_CHARACTER] = NEW_STATE_NUMBER std::vector<char> next_transition; next_transition.reserve(128); unsigned int current_state; unsigned int next_state = 0; for (const char* itr = regex; *itr != '\0'; ++itr) { current_state = next_state; assert(current_state != dfa.num_states); next_transition.clear(); switch (*itr) { // deal with special metacharacters case '[': { // only need one state until we find a matchin ']' // move the iterator to that position and continue const char* look_ahead = ++itr; const char* first_char = itr; bool flip_transition = false; if (*first_char == '^') { flip_transition = true; ++look_ahead; for (unsigned char i = 0; i < 128; ++i) { next_transition.push_back(i); } } // buffer the first value in case we see range based expression // e.g. [A-Z], store 'A' in first_val buffer char first_val; while (*look_ahead != ']') { switch (*look_ahead) { case '\0': { std::cerr << "Bad regular expression: no matching ']' for '['" << std::endl; } case '-': { ++look_ahead; if (*look_ahead == '\\') { ++look_ahead; } char end_val = *look_ahead; if (end_val < first_val) { // swap to allow [a-z] to have same semantic meaning as [z-a] char tmp = end_val; end_val = first_val; first_val = tmp; } for (char val = first_val; val <= end_val; ++val) { if (flip_transition) { next_transition.erase(std::lower_bound(next_transition.begin(), next_transition.end(), val)); } else { next_transition.push_back(val); } } break; } default: { first_val = *look_ahead; if (flip_transition) { next_transition.erase(std::lower_bound(next_transition.begin(), next_transition.end(), first_val)); } else { next_transition.push_back(first_val); } } } ++look_ahead; } itr = look_ahead; break; } case '\\': { // we escape the next metacharacter so just walk over it by one ++itr; // don't break, instead fall down to default } case '(': { // a group... continue to next character continue; } case ')': { // a closing group... continue to next character } default: { next_transition.push_back(*itr); // normal character break; } } // we now have collected new state transitions in next_transition // look for '*', '+' etc metacharacters to determine how to write the trasnitions const char* look_ahead = itr + 1; switch (*look_ahead) { case '*': { for (auto char_transition : next_transition) { if (dfa.states[current_state * dfa_width + char_transition] == dfa.begin_state) { dfa.states[current_state * dfa_width + char_transition] = current_state; } } itr = look_ahead; break; } case '+': { next_state = current_state + 1; for (auto char_transition : next_transition) { if (dfa.states[current_state * dfa_width + char_transition] == dfa.begin_state) { dfa.states[current_state * dfa_width + char_transition] = next_state; dfa.states[next_state * dfa_width + char_transition] = next_state; } } itr = look_ahead; break; } default: { next_state = current_state + 1; for (auto char_transition : next_transition) { if (dfa.states[current_state * dfa_width + char_transition] == dfa.begin_state) { dfa.states[current_state * dfa_width + char_transition] = next_state; } } break; } } } dfa.accept_states.insert(std::pair<unsigned int, unsigned int>(next_state, 0)); } <|endoftext|>
<commit_before>// Copyright (c) 2017, Franz Hollerer. All rights reserved. // This code is licensed under the MIT License (MIT). // See LICENSE file for full details. #include <mutex> #include <hodea/core/cstdint.hpp> #include <hodea/device/hal/device_setup.hpp> #include <hodea/rte/htsc.hpp> #include <hodea/device/hal/critical_section.hpp> #include "tfw.hpp" #include "digio_pins.hpp" using namespace hodea; static void test_lock_unlock() { Critical_section cs; #if 0 tfw_assert(__get_PRIMASK() == 0); { std::lock_guard<Critical_section> csl{cs}; tfw_assert(__get_PRIMASK() == 1); } #endif tfw_assert(__get_PRIMASK() == 0); } Tfw_status critical_section_test(Tfw_status current) { tfw_info("Testing critical section.\n"); try { test_lock_unlock(); } catch (...) { return Tfw_status::failed; } return Tfw_status::success; } <commit_msg>warning added<commit_after>// Copyright (c) 2017, Franz Hollerer. All rights reserved. // This code is licensed under the MIT License (MIT). // See LICENSE file for full details. #include <mutex> #include <hodea/core/cstdint.hpp> #include <hodea/device/hal/device_setup.hpp> #include <hodea/rte/htsc.hpp> #include <hodea/device/hal/critical_section.hpp> #include "tfw.hpp" #include "digio_pins.hpp" using namespace hodea; static void test_lock_unlock() { Critical_section cs; #warning "remove this.." #if 0 tfw_assert(__get_PRIMASK() == 0); { std::lock_guard<Critical_section> csl{cs}; tfw_assert(__get_PRIMASK() == 1); } #endif tfw_assert(__get_PRIMASK() == 0); } Tfw_status critical_section_test(Tfw_status current) { tfw_info("Testing critical section.\n"); try { test_lock_unlock(); } catch (...) { return Tfw_status::failed; } return Tfw_status::success; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: filedlgimpl.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2006-06-19 22:21:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFX_FILEDLGIMPL_HXX #define _SFX_FILEDLGIMPL_HXX #ifndef _SV_TIMER_HXX #include <vcl/timer.hxx> #endif #ifndef _SV_GRAPH_HXX #include <vcl/graph.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_STRINGPAIR_HPP_ #include <com/sun/star/beans/StringPair.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFilePicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerListener.hpp> #endif #ifndef _SFX_FCONTNR_HXX #include "fcontnr.hxx" #endif #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> #include "filedlghelper.hxx" class SfxFilterMatcher; class GraphicFilter; class FileDialogHelper; namespace sfx2 { typedef ::com::sun::star::beans::StringPair FilterPair; class FileDialogHelper_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::ui::dialogs::XFilePickerListener > { friend class FileDialogHelper; ::com::sun::star::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > mxFileDlg; ::com::sun::star::uno::Reference < ::com::sun::star::container::XNameAccess > mxFilterCFG; std::vector< FilterPair > maFilters; SfxFilterMatcher* mpMatcher; GraphicFilter* mpGraphicFilter; FileDialogHelper* mpAntiImpl; Window* mpPreferredParentWindow; ::rtl::OUString maPath; ::rtl::OUString maFileName; ::rtl::OUString maCurFilter; ::rtl::OUString maSelectFilter; ::rtl::OUString maButtonLabel; Timer maPreViewTimer; Graphic maGraphic; const short m_nDialogType; SfxFilterFlags m_nMustFlags; SfxFilterFlags m_nDontFlags; ULONG mnPostUserEventId; ErrCode mnError; FileDialogHelper::Context meContext; sal_Bool mbHasPassword : 1; sal_Bool mbIsPwdEnabled : 1; sal_Bool m_bHaveFilterOptions : 1; sal_Bool mbHasVersions : 1; sal_Bool mbHasAutoExt : 1; sal_Bool mbHasLink : 1; sal_Bool mbHasPreview : 1; sal_Bool mbShowPreview : 1; sal_Bool mbIsSaveDlg : 1; sal_Bool mbExport : 1; sal_Bool mbDeleteMatcher : 1; sal_Bool mbInsert : 1; sal_Bool mbSystemPicker : 1; sal_Bool mbPwdCheckBoxState : 1; sal_Bool mbSelection : 1; sal_Bool mbSelectionEnabled : 1; private: void addFilters( sal_Int64 nFlags, const String& rFactory, SfxFilterFlags nMust, SfxFilterFlags nDont ); void addFilter( const ::rtl::OUString& rFilterName, const ::rtl::OUString& rExtension ); void addGraphicFilter(); void enablePasswordBox( sal_Bool bInit ); void updateFilterOptionsBox(); void updateExportButton(); void updateSelectionBox(); void updateVersions(); void updatePreviewState( sal_Bool _bUpdatePreviewWindow = sal_True ); void dispose(); void loadConfig(); void saveConfig(); const SfxFilter* getCurentSfxFilter(); sal_Bool updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable ); ErrCode getGraphic( const ::rtl::OUString& rURL, Graphic& rGraphic ) const; void setDefaultValues(); void preExecute(); void postExecute( sal_Int16 _nResult ); sal_Int16 implDoExecute(); void correctVirtualDialogType(); void setControlHelpIds( const sal_Int16* _pControlId, const sal_Int32* _pHelpId ); void setDialogHelpId( const sal_Int32 _nHelpId ); sal_Bool CheckFilterOptionsCapability( const SfxFilter* _pFilter ); sal_Bool isInOpenMode() const; String getCurrentFilterUIName() const; void LoadLastUsedFilter( const ::rtl::OUString& _rContextIdentifier ); void SaveLastUsedFilter( const ::rtl::OUString& _rContextIdentifier ); void SaveLastUsedFilter( void ); void implInitializeFileName( ); DECL_LINK( TimeOutHdl_Impl, Timer* ); DECL_LINK( HandleEvent, FileDialogHelper* ); DECL_LINK( InitControls, void* ); public: // XFilePickerListener methods virtual void SAL_CALL fileSelectionChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL directoryChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL helpRequested( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL controlStateChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL dialogSizeChanged() throw( ::com::sun::star::uno::RuntimeException ); // XEventListener methods virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException ); // handle XFilePickerListener events void handleFileSelectionChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleDirectoryChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); ::rtl::OUString handleHelpRequested( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleControlStateChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleDialogSizeChanged(); // Own methods FileDialogHelper_Impl( FileDialogHelper* _pAntiImpl, const short nDialogType, sal_Int64 nFlags, Window* _pPreferredParentWindow = NULL ); virtual ~FileDialogHelper_Impl(); ErrCode execute( SvStringsDtor*& rpURLList, SfxItemSet *& rpSet, String& rFilter ); ErrCode execute(); void setFilter( const ::rtl::OUString& rFilter ); /** sets the directory which should be browsed <p>If the given path does not point to a valid (existent and accessible) folder, the request is silently dropped</p> */ void displayFolder( const ::rtl::OUString& rPath ); void setFileName( const ::rtl::OUString& _rFile ); ::rtl::OUString getPath() const; ::rtl::OUString getFilter() const; void getRealFilter( String& _rFilter ) const; ErrCode getGraphic( Graphic& rGraphic ) const; void createMatcher( const String& rFactory ); sal_Bool isShowFilterExtensionEnabled() const; void addFilterPair( const ::rtl::OUString& rFilter, const ::rtl::OUString& rFilterWithExtension ); ::rtl::OUString getFilterName( const ::rtl::OUString& rFilterWithExtension ) const; ::rtl::OUString getFilterWithExtension( const ::rtl::OUString& rFilter ) const; void SetContext( FileDialogHelper::Context _eNewContext ); }; } // end of namespace sfx2 #endif // _SFX_FILEDLGIMPL_HXX <commit_msg>INTEGRATION: CWS asyncdialogs (1.8.650); FILE MERGED 2006/07/12 20:55:54 pb 1.8.650.5: RESYNC: (1.9-1.10); FILE MERGED 2006/03/01 09:28:03 pb 1.8.650.4: fix: #i57125# IsPasswordEnabled() added 2005/12/08 08:59:46 kso 1.8.650.3: RESYNC: (1.8-1.9); FILE MERGED 2005/11/10 09:53:44 pb 1.8.650.2: fix: #i57125# isSystemFilePicker() added 2005/11/01 14:26:47 kso 1.8.650.1: #i57125# - dialog adaptions for Threading Framework.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: filedlgimpl.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2006-11-22 10:57:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFX_FILEDLGIMPL_HXX #define _SFX_FILEDLGIMPL_HXX #ifndef _SV_TIMER_HXX #include <vcl/timer.hxx> #endif #ifndef _SV_GRAPH_HXX #include <vcl/graph.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_STRINGPAIR_HPP_ #include <com/sun/star/beans/StringPair.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFilePicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerListener.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XDIALOGCLOSEDLISTENER_HPP_ #include <com/sun/star/ui/dialogs/XDialogClosedListener.hpp> #endif #ifndef _SFX_FCONTNR_HXX #include "fcontnr.hxx" #endif #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> #include "filedlghelper.hxx" class SfxFilterMatcher; class GraphicFilter; class FileDialogHelper; namespace sfx2 { typedef ::com::sun::star::beans::StringPair FilterPair; class FileDialogHelper_Impl : public ::cppu::WeakImplHelper2< ::com::sun::star::ui::dialogs::XFilePickerListener, ::com::sun::star::ui::dialogs::XDialogClosedListener > { friend class FileDialogHelper; ::com::sun::star::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > mxFileDlg; ::com::sun::star::uno::Reference < ::com::sun::star::container::XNameAccess > mxFilterCFG; std::vector< FilterPair > maFilters; SfxFilterMatcher* mpMatcher; GraphicFilter* mpGraphicFilter; FileDialogHelper* mpAntiImpl; Window* mpPreferredParentWindow; ::rtl::OUString maPath; ::rtl::OUString maFileName; ::rtl::OUString maCurFilter; ::rtl::OUString maSelectFilter; ::rtl::OUString maButtonLabel; Timer maPreViewTimer; Graphic maGraphic; const short m_nDialogType; SfxFilterFlags m_nMustFlags; SfxFilterFlags m_nDontFlags; ULONG mnPostUserEventId; ErrCode mnError; FileDialogHelper::Context meContext; sal_Bool mbHasPassword : 1; sal_Bool mbIsPwdEnabled : 1; sal_Bool m_bHaveFilterOptions : 1; sal_Bool mbHasVersions : 1; sal_Bool mbHasAutoExt : 1; sal_Bool mbHasLink : 1; sal_Bool mbHasPreview : 1; sal_Bool mbShowPreview : 1; sal_Bool mbIsSaveDlg : 1; sal_Bool mbExport : 1; sal_Bool mbDeleteMatcher : 1; sal_Bool mbInsert : 1; sal_Bool mbSystemPicker : 1; sal_Bool mbPwdCheckBoxState : 1; sal_Bool mbSelection : 1; sal_Bool mbSelectionEnabled : 1; private: void addFilters( sal_Int64 nFlags, const String& rFactory, SfxFilterFlags nMust, SfxFilterFlags nDont ); void addFilter( const ::rtl::OUString& rFilterName, const ::rtl::OUString& rExtension ); void addGraphicFilter(); void enablePasswordBox( sal_Bool bInit ); void updateFilterOptionsBox(); void updateExportButton(); void updateSelectionBox(); void updateVersions(); void updatePreviewState( sal_Bool _bUpdatePreviewWindow = sal_True ); void dispose(); void loadConfig(); void saveConfig(); const SfxFilter* getCurentSfxFilter(); sal_Bool updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable ); ErrCode getGraphic( const ::rtl::OUString& rURL, Graphic& rGraphic ) const; void setDefaultValues(); void preExecute(); void postExecute( sal_Int16 _nResult ); sal_Int16 implDoExecute(); void implStartExecute(); void correctVirtualDialogType(); void setControlHelpIds( const sal_Int16* _pControlId, const sal_Int32* _pHelpId ); void setDialogHelpId( const sal_Int32 _nHelpId ); sal_Bool CheckFilterOptionsCapability( const SfxFilter* _pFilter ); sal_Bool isInOpenMode() const; String getCurrentFilterUIName() const; void LoadLastUsedFilter( const ::rtl::OUString& _rContextIdentifier ); void SaveLastUsedFilter( const ::rtl::OUString& _rContextIdentifier ); void SaveLastUsedFilter( void ); void implInitializeFileName( ); DECL_LINK( TimeOutHdl_Impl, Timer* ); DECL_LINK( HandleEvent, FileDialogHelper* ); DECL_LINK( InitControls, void* ); public: // XFilePickerListener methods virtual void SAL_CALL fileSelectionChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL directoryChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL helpRequested( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL controlStateChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL dialogSizeChanged() throw( ::com::sun::star::uno::RuntimeException ); // XDialogClosedListener methods virtual void SAL_CALL dialogClosed( const ::com::sun::star::ui::dialogs::DialogClosedEvent& _rEvent ) throw (::com::sun::star::uno::RuntimeException); // XEventListener methods virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException ); // handle XFilePickerListener events void handleFileSelectionChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleDirectoryChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); ::rtl::OUString handleHelpRequested( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleControlStateChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleDialogSizeChanged(); // Own methods FileDialogHelper_Impl( FileDialogHelper* _pAntiImpl, const short nDialogType, sal_Int64 nFlags, Window* _pPreferredParentWindow = NULL ); virtual ~FileDialogHelper_Impl(); ErrCode execute( SvStringsDtor*& rpURLList, SfxItemSet *& rpSet, String& rFilter ); ErrCode execute(); void setFilter( const ::rtl::OUString& rFilter ); /** sets the directory which should be browsed <p>If the given path does not point to a valid (existent and accessible) folder, the request is silently dropped</p> */ void displayFolder( const ::rtl::OUString& rPath ); void setFileName( const ::rtl::OUString& _rFile ); ::rtl::OUString getPath() const; ::rtl::OUString getFilter() const; void getRealFilter( String& _rFilter ) const; ErrCode getGraphic( Graphic& rGraphic ) const; void createMatcher( const String& rFactory ); sal_Bool isShowFilterExtensionEnabled() const; void addFilterPair( const ::rtl::OUString& rFilter, const ::rtl::OUString& rFilterWithExtension ); ::rtl::OUString getFilterName( const ::rtl::OUString& rFilterWithExtension ) const; ::rtl::OUString getFilterWithExtension( const ::rtl::OUString& rFilter ) const; void SetContext( FileDialogHelper::Context _eNewContext ); inline sal_Bool isSystemFilePicker() const { return mbSystemPicker; } inline sal_Bool isPasswordEnabled() const { return mbIsPwdEnabled; } }; } // end of namespace sfx2 #endif // _SFX_FILEDLGIMPL_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textview.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-04-11 19:40:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TEXTVIEW_HXX #define _TEXTVIEW_HXX #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _TEXTDATA_HXX #include <svtools/textdata.hxx> #endif #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _VCL_DNDHELP_HXX #include <vcl/dndhelp.hxx> #endif class TextEngine; class OutputDevice; class Window; class Cursor; class KeyEvent; class MouseEvent; class CommandEvent; class TextSelFunctionSet; class SelectionEngine; class VirtualDevice; struct TextDDInfo; namespace com { namespace sun { namespace star { namespace datatransfer { namespace clipboard { class XClipboard; }}}}} struct ImpTextView; class SVT_DLLPUBLIC TextView : public vcl::unohelper::DragAndDropClient { friend class TextEngine; friend class TextUndo; friend class TextUndoManager; friend class TextSelFunctionSet; friend class ExtTextView; private: ImpTextView* mpImpl; TextView( const TextView& ) : vcl::unohelper::DragAndDropClient() {} TextView& operator=( const TextView& ) { return *this; } protected: void ShowSelection(); void HideSelection(); void ShowSelection( const TextSelection& rSel ); void ImpShowHideSelection( BOOL bShow, const TextSelection* pRange = NULL ); TextSelection ImpMoveCursor( const KeyEvent& rKeyEvent ); TextPaM ImpDelete( BOOL bForward, BYTE nMode ); void ImpSetSelection( const TextSelection& rNewSel, BOOL bUI ); BOOL IsInSelection( const TextPaM& rPaM ); void ImpPaint( OutputDevice* pOut, const Point& rStartPos, Rectangle const* pPaintArea, TextSelection const* pPaintRange = 0, TextSelection const* pSelection = 0 ); void ImpPaint( const Rectangle& rRect, BOOL bUseVirtDev ); void ImpShowCursor( BOOL bGotoCursor, BOOL bForceVisCursor, BOOL bEndKey ); void ImpHighlight( const TextSelection& rSel ); void ImpSetSelection( const TextSelection& rSelection ); Point ImpGetOutputStartPos( const Point& rStartDocPos ) const; void ImpHideDDCursor(); void ImpShowDDCursor(); BOOL ImplCheckTextLen( const String& rNewText ); VirtualDevice* GetVirtualDevice(); // DragAndDropClient virtual void dragGestureRecognized( const ::com::sun::star::datatransfer::dnd::DragGestureEvent& dge ) throw (::com::sun::star::uno::RuntimeException); virtual void dragDropEnd( const ::com::sun::star::datatransfer::dnd::DragSourceDropEvent& dsde ) throw (::com::sun::star::uno::RuntimeException); virtual void drop( const ::com::sun::star::datatransfer::dnd::DropTargetDropEvent& dtde ) throw (::com::sun::star::uno::RuntimeException); virtual void dragEnter( const ::com::sun::star::datatransfer::dnd::DropTargetDragEnterEvent& dtdee ) throw (::com::sun::star::uno::RuntimeException); virtual void dragExit( const ::com::sun::star::datatransfer::dnd::DropTargetEvent& dte ) throw (::com::sun::star::uno::RuntimeException); virtual void dragOver( const ::com::sun::star::datatransfer::dnd::DropTargetDragEvent& dtde ) throw (::com::sun::star::uno::RuntimeException); using DragAndDropClient::dragEnter; using DragAndDropClient::dragExit; using DragAndDropClient::dragOver; public: TextView( TextEngine* pEng, Window* pWindow ); virtual ~TextView(); TextEngine* GetTextEngine() const; Window* GetWindow() const; void Invalidate(); void Scroll( long nHorzScroll, long nVertScroll ); void ShowCursor( BOOL bGotoCursor = TRUE, BOOL bForceVisCursor = TRUE ); void HideCursor(); void EnableCursor( BOOL bEnable ); BOOL IsCursorEnabled() const; const TextSelection& GetSelection() const; TextSelection& GetSelection(); void SetSelection( const TextSelection& rNewSel ); void SetSelection( const TextSelection& rNewSel, BOOL bGotoCursor ); BOOL HasSelection() const; String GetSelected(); String GetSelected( LineEnd aSeparator ); void DeleteSelected(); void InsertText( const String& rNew, BOOL bSelect = FALSE ); BOOL KeyInput( const KeyEvent& rKeyEvent ); void Paint( const Rectangle& rRect ); void MouseButtonUp( const MouseEvent& rMouseEvent ); void MouseButtonDown( const MouseEvent& rMouseEvent ); void MouseMove( const MouseEvent& rMouseEvent ); void Command( const CommandEvent& rCEvt ); void Cut(); void Copy(); void Paste(); void Copy( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard ); void Paste( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard ); void Undo(); void Redo(); BOOL Read( SvStream& rInput ); BOOL Write( SvStream& rOutput ); void SetStartDocPos( const Point& rPos ); const Point& GetStartDocPos() const; Point GetDocPos( const Point& rWindowPos ) const; Point GetWindowPos( const Point& rDocPos ) const; void SetInsertMode( BOOL bInsert ); BOOL IsInsertMode() const; void SetAutoIndentMode( BOOL bAutoIndent ); BOOL IsAutoIndentMode() const; void SetReadOnly( BOOL bReadOnly ); BOOL IsReadOnly() const; void SetAutoScroll( BOOL bAutoScroll ); BOOL IsAutoScroll() const; BOOL SetCursorAtPoint( const Point& rPointPixel ); BOOL IsSelectionAtPoint( const Point& rPointPixel ); void SetPaintSelection( BOOL bPaint); BOOL IsPaintSelection() const; void SetHighlightSelection( BOOL bSelectByHighlight ); BOOL IsHighlightSelection() const; void EraseVirtualDevice(); // aus dem protected Teil hierher verschoben // F�r 'SvtXECTextCursor' (TL). Mu� ggf nochmal anders gel�st werden. TextPaM PageUp( const TextPaM& rPaM ); TextPaM PageDown( const TextPaM& rPaM ); TextPaM CursorUp( const TextPaM& rPaM ); TextPaM CursorDown( const TextPaM& rPaM ); TextPaM CursorLeft( const TextPaM& rPaM, USHORT nCharacterIteratorMode ); TextPaM CursorRight( const TextPaM& rPaM, USHORT nCharacterIteratorMode ); TextPaM CursorWordLeft( const TextPaM& rPaM ); TextPaM CursorWordRight( const TextPaM& rPaM ); TextPaM CursorStartOfLine( const TextPaM& rPaM ); TextPaM CursorEndOfLine( const TextPaM& rPaM ); TextPaM CursorStartOfParagraph( const TextPaM& rPaM ); TextPaM CursorEndOfParagraph( const TextPaM& rPaM ); TextPaM CursorStartOfDoc(); TextPaM CursorEndOfDoc(); // Old, remove! TextPaM CursorLeft( const TextPaM& rPaM, BOOL bWordMode = FALSE ); TextPaM CursorRight( const TextPaM& rPaM, BOOL bWordMode = FALSE ); /** Drag and Drop, deleting and selection regards all text that has an attribute TEXTATTR_PROTECTED set as one entitity. Drag and dropped text is automatically attibuted as protected. */ void SupportProtectAttribute(sal_Bool bSupport); }; #endif // _TEXTVIEW_HXX <commit_msg>INTEGRATION: CWS vcl82 (1.2.140); FILE MERGED 2007/08/06 14:13:07 pl 1.2.140.1: #i80073# #i73360# show warning if text is truncated due to maximum length<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: textview.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-09-26 15:02:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _TEXTVIEW_HXX #define _TEXTVIEW_HXX #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _TEXTDATA_HXX #include <svtools/textdata.hxx> #endif #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _VCL_DNDHELP_HXX #include <vcl/dndhelp.hxx> #endif class TextEngine; class OutputDevice; class Window; class Cursor; class KeyEvent; class MouseEvent; class CommandEvent; class TextSelFunctionSet; class SelectionEngine; class VirtualDevice; struct TextDDInfo; namespace com { namespace sun { namespace star { namespace datatransfer { namespace clipboard { class XClipboard; }}}}} struct ImpTextView; class SVT_DLLPUBLIC TextView : public vcl::unohelper::DragAndDropClient { friend class TextEngine; friend class TextUndo; friend class TextUndoManager; friend class TextSelFunctionSet; friend class ExtTextView; private: ImpTextView* mpImpl; TextView( const TextView& ) : vcl::unohelper::DragAndDropClient() {} TextView& operator=( const TextView& ) { return *this; } protected: void ShowSelection(); void HideSelection(); void ShowSelection( const TextSelection& rSel ); void ImpShowHideSelection( BOOL bShow, const TextSelection* pRange = NULL ); TextSelection ImpMoveCursor( const KeyEvent& rKeyEvent ); TextPaM ImpDelete( BOOL bForward, BYTE nMode ); void ImpSetSelection( const TextSelection& rNewSel, BOOL bUI ); BOOL IsInSelection( const TextPaM& rPaM ); void ImpPaint( OutputDevice* pOut, const Point& rStartPos, Rectangle const* pPaintArea, TextSelection const* pPaintRange = 0, TextSelection const* pSelection = 0 ); void ImpPaint( const Rectangle& rRect, BOOL bUseVirtDev ); void ImpShowCursor( BOOL bGotoCursor, BOOL bForceVisCursor, BOOL bEndKey ); void ImpHighlight( const TextSelection& rSel ); void ImpSetSelection( const TextSelection& rSelection ); Point ImpGetOutputStartPos( const Point& rStartDocPos ) const; void ImpHideDDCursor(); void ImpShowDDCursor(); bool ImplTruncateNewText( rtl::OUString& rNewText ) const; BOOL ImplCheckTextLen( const String& rNewText ); VirtualDevice* GetVirtualDevice(); // DragAndDropClient virtual void dragGestureRecognized( const ::com::sun::star::datatransfer::dnd::DragGestureEvent& dge ) throw (::com::sun::star::uno::RuntimeException); virtual void dragDropEnd( const ::com::sun::star::datatransfer::dnd::DragSourceDropEvent& dsde ) throw (::com::sun::star::uno::RuntimeException); virtual void drop( const ::com::sun::star::datatransfer::dnd::DropTargetDropEvent& dtde ) throw (::com::sun::star::uno::RuntimeException); virtual void dragEnter( const ::com::sun::star::datatransfer::dnd::DropTargetDragEnterEvent& dtdee ) throw (::com::sun::star::uno::RuntimeException); virtual void dragExit( const ::com::sun::star::datatransfer::dnd::DropTargetEvent& dte ) throw (::com::sun::star::uno::RuntimeException); virtual void dragOver( const ::com::sun::star::datatransfer::dnd::DropTargetDragEvent& dtde ) throw (::com::sun::star::uno::RuntimeException); using DragAndDropClient::dragEnter; using DragAndDropClient::dragExit; using DragAndDropClient::dragOver; public: TextView( TextEngine* pEng, Window* pWindow ); virtual ~TextView(); TextEngine* GetTextEngine() const; Window* GetWindow() const; void Invalidate(); void Scroll( long nHorzScroll, long nVertScroll ); void ShowCursor( BOOL bGotoCursor = TRUE, BOOL bForceVisCursor = TRUE ); void HideCursor(); void EnableCursor( BOOL bEnable ); BOOL IsCursorEnabled() const; const TextSelection& GetSelection() const; TextSelection& GetSelection(); void SetSelection( const TextSelection& rNewSel ); void SetSelection( const TextSelection& rNewSel, BOOL bGotoCursor ); BOOL HasSelection() const; String GetSelected(); String GetSelected( LineEnd aSeparator ); void DeleteSelected(); void InsertText( const String& rNew, BOOL bSelect = FALSE ); BOOL KeyInput( const KeyEvent& rKeyEvent ); void Paint( const Rectangle& rRect ); void MouseButtonUp( const MouseEvent& rMouseEvent ); void MouseButtonDown( const MouseEvent& rMouseEvent ); void MouseMove( const MouseEvent& rMouseEvent ); void Command( const CommandEvent& rCEvt ); void Cut(); void Copy(); void Paste(); void Copy( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard ); void Paste( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard ); void Undo(); void Redo(); BOOL Read( SvStream& rInput ); BOOL Write( SvStream& rOutput ); void SetStartDocPos( const Point& rPos ); const Point& GetStartDocPos() const; Point GetDocPos( const Point& rWindowPos ) const; Point GetWindowPos( const Point& rDocPos ) const; void SetInsertMode( BOOL bInsert ); BOOL IsInsertMode() const; void SetAutoIndentMode( BOOL bAutoIndent ); BOOL IsAutoIndentMode() const; void SetReadOnly( BOOL bReadOnly ); BOOL IsReadOnly() const; void SetAutoScroll( BOOL bAutoScroll ); BOOL IsAutoScroll() const; BOOL SetCursorAtPoint( const Point& rPointPixel ); BOOL IsSelectionAtPoint( const Point& rPointPixel ); void SetPaintSelection( BOOL bPaint); BOOL IsPaintSelection() const; void SetHighlightSelection( BOOL bSelectByHighlight ); BOOL IsHighlightSelection() const; void EraseVirtualDevice(); // aus dem protected Teil hierher verschoben // F�r 'SvtXECTextCursor' (TL). Mu� ggf nochmal anders gel�st werden. TextPaM PageUp( const TextPaM& rPaM ); TextPaM PageDown( const TextPaM& rPaM ); TextPaM CursorUp( const TextPaM& rPaM ); TextPaM CursorDown( const TextPaM& rPaM ); TextPaM CursorLeft( const TextPaM& rPaM, USHORT nCharacterIteratorMode ); TextPaM CursorRight( const TextPaM& rPaM, USHORT nCharacterIteratorMode ); TextPaM CursorWordLeft( const TextPaM& rPaM ); TextPaM CursorWordRight( const TextPaM& rPaM ); TextPaM CursorStartOfLine( const TextPaM& rPaM ); TextPaM CursorEndOfLine( const TextPaM& rPaM ); TextPaM CursorStartOfParagraph( const TextPaM& rPaM ); TextPaM CursorEndOfParagraph( const TextPaM& rPaM ); TextPaM CursorStartOfDoc(); TextPaM CursorEndOfDoc(); // Old, remove! TextPaM CursorLeft( const TextPaM& rPaM, BOOL bWordMode = FALSE ); TextPaM CursorRight( const TextPaM& rPaM, BOOL bWordMode = FALSE ); /** Drag and Drop, deleting and selection regards all text that has an attribute TEXTATTR_PROTECTED set as one entitity. Drag and dropped text is automatically attibuted as protected. */ void SupportProtectAttribute(sal_Bool bSupport); }; #endif // _TEXTVIEW_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cuicharmap.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2007-06-27 16:57:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #include <stdio.h> #define _CUI_CHARMAP_CXX_ #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SV_SOUND_HXX #include <vcl/sound.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> #endif #ifndef INCLUDED_SVTOOLS_COLORCFG_HXX #include <svtools/colorcfg.hxx> #endif #include <rtl/textenc.h> #include <svx/ucsubset.hxx> #include <svx/dialogs.hrc> #include "charmap.hrc" #include <svx/charmap.hxx> //add CHINA001 #include <svx/dialmgr.hxx> #include "cuicharmap.hxx" //CHINA001 #include "charmapacc.hxx" //CHINA001 #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTOBJECT_HPP_ //CHINA001 #include <com/sun/star/accessibility/AccessibleEventObject.hpp> //CHINA001 #endif //CHINA001 #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_ //CHINA001 #include <com/sun/star/accessibility/AccessibleEventId.hpp> //CHINA001 #endif //CHINA001 #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_ //CHINA001 #include <com/sun/star/accessibility/AccessibleStateType.hpp> //CHINA001 #endif //CHINA001 #ifndef _COMPHELPER_TYPES_HXX_ //CHINA001 #include <comphelper/types.hxx> //CHINA001 #endif //CHINA001 //CHINA001 using namespace ::com::sun::star::accessibility; //CHINA001 using namespace ::com::sun::star::uno; // class SvxCharacterMap ================================================= SvxCharacterMap::SvxCharacterMap( Window* pParent, BOOL bOne ) : SfxModalDialog( pParent, SVX_RES( RID_SVXDLG_CHARMAP ) ), mpCharMapData( new SvxCharMapData( this, bOne, &DIALOG_MGR() ) ) { FreeResource(); } // ----------------------------------------------------------------------- SvxCharacterMap::~SvxCharacterMap() { delete mpCharMapData; } // ----------------------------------------------------------------------- const Font& SvxCharacterMap::GetCharFont() const { return mpCharMapData->aFont; } // ----------------------------------------------------------------------- void SvxCharacterMap::SetChar( sal_UCS4 c ) { mpCharMapData->aShowSet.SelectCharacter( c ); } // ----------------------------------------------------------------------- sal_UCS4 SvxCharacterMap::GetChar() const { return mpCharMapData->aShowSet.GetSelectCharacter(); } // ----------------------------------------------------------------------- String SvxCharacterMap::GetCharacters() const { return mpCharMapData->aShowText.GetText(); } // ----------------------------------------------------------------------- void SvxCharacterMap::DisableFontSelection() { mpCharMapData->aFontText.Disable(); mpCharMapData->aFontLB.Disable(); } void SvxCharacterMap::SetCharFont( const Font& rFont ) { mpCharMapData->SetCharFont( rFont ); } <commit_msg>INTEGRATION: CWS changefileheader (1.9.368); FILE MERGED 2008/04/01 15:50:16 thb 1.9.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:21 rt 1.9.368.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cuicharmap.cxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #include <stdio.h> #define _CUI_CHARMAP_CXX_ #include <tools/shl.hxx> #include <tools/debug.hxx> #include <vcl/sound.hxx> #include <vcl/svapp.hxx> #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #include <vcl/fixed.hxx> #include <vcl/lstbox.hxx> #include <vcl/edit.hxx> #include <svtools/colorcfg.hxx> #include <rtl/textenc.h> #include <svx/ucsubset.hxx> #include <svx/dialogs.hrc> #include "charmap.hrc" #include <svx/charmap.hxx> //add CHINA001 #include <svx/dialmgr.hxx> #include "cuicharmap.hxx" //CHINA001 #include "charmapacc.hxx" //CHINA001 #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTOBJECT_HPP_ //CHINA001 #include <com/sun/star/accessibility/AccessibleEventObject.hpp> //CHINA001 #endif //CHINA001 #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_ //CHINA001 #include <com/sun/star/accessibility/AccessibleEventId.hpp> //CHINA001 #endif //CHINA001 #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_ //CHINA001 #include <com/sun/star/accessibility/AccessibleStateType.hpp> //CHINA001 #endif //CHINA001 #ifndef _COMPHELPER_TYPES_HXX_ //CHINA001 #include <comphelper/types.hxx> //CHINA001 #endif //CHINA001 //CHINA001 using namespace ::com::sun::star::accessibility; //CHINA001 using namespace ::com::sun::star::uno; // class SvxCharacterMap ================================================= SvxCharacterMap::SvxCharacterMap( Window* pParent, BOOL bOne ) : SfxModalDialog( pParent, SVX_RES( RID_SVXDLG_CHARMAP ) ), mpCharMapData( new SvxCharMapData( this, bOne, &DIALOG_MGR() ) ) { FreeResource(); } // ----------------------------------------------------------------------- SvxCharacterMap::~SvxCharacterMap() { delete mpCharMapData; } // ----------------------------------------------------------------------- const Font& SvxCharacterMap::GetCharFont() const { return mpCharMapData->aFont; } // ----------------------------------------------------------------------- void SvxCharacterMap::SetChar( sal_UCS4 c ) { mpCharMapData->aShowSet.SelectCharacter( c ); } // ----------------------------------------------------------------------- sal_UCS4 SvxCharacterMap::GetChar() const { return mpCharMapData->aShowSet.GetSelectCharacter(); } // ----------------------------------------------------------------------- String SvxCharacterMap::GetCharacters() const { return mpCharMapData->aShowText.GetText(); } // ----------------------------------------------------------------------- void SvxCharacterMap::DisableFontSelection() { mpCharMapData->aFontText.Disable(); mpCharMapData->aFontLB.Disable(); } void SvxCharacterMap::SetCharFont( const Font& rFont ) { mpCharMapData->SetCharFont( rFont ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cuiimapwnd.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2007-06-26 13:49:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif #ifndef _URLOBJ_HXX //autogen #include <tools/urlobj.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SV_HELP_HXX //autogen #include <vcl/help.hxx> #endif #ifndef _SFXSIDS_HRC #include <sfx2/sfxsids.hrc> // SID_ATTR_MACROITEM #endif #define _ANIMATION #ifndef _MACROPG_HXX //autogen #include <sfx2/macropg.hxx> #endif #ifndef _GOODIES_IMAPRECT_HXX //autogen #include <svtools/imaprect.hxx> #endif #ifndef _GOODIES_IMAPCIRC_HXX //autogen #include <svtools/imapcirc.hxx> #endif #ifndef _GOODIES_IMAPPOLY_HXX //autogen #include <svtools/imappoly.hxx> #endif #ifndef _URLBMK_HXX //autogen #include <svtools/urlbmk.hxx> #endif #include <xoutbmp.hxx> #include <dialmgr.hxx> #include <dialogs.hrc> #include <svxids.hrc> #include <imapdlg.hrc> #include <imapwnd.hxx> #include "svdpage.hxx" #include "svdorect.hxx" #include "svdocirc.hxx" #include "svdopath.hxx" #include "xfltrit.hxx" #include "svdpagv.hxx" #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #ifndef _SVX_FILLITEM_HXX //autogen #include <xfillit.hxx> #endif #ifndef _SVX_XLINIIT_HXX //autogen #include <xlineit.hxx> #endif #include <sot/formats.hxx> #include "cuiimapwnd.hxx" //CHINA001 #ifdef MAC #define TRANSCOL Color( COL_LIGHTGRAY ) #else #define TRANSCOL Color( COL_WHITE ) #endif /************************************************************************* |* |* URLDlg |* \************************************************************************/ URLDlg::URLDlg( Window* pWindow, const String& rURL, const String& rAlternativeText, const String& rDescription, const String& rTarget, const String& rName, TargetList& rTargetList ) : ModalDialog( pWindow, SVX_RES( RID_SVXDLG_IMAPURL ) ) , maFtURL( this, SVX_RES( FT_URL1 ) ) , maEdtURL( this, SVX_RES( EDT_URL ) ) , maFtTarget( this, SVX_RES( FT_TARGET ) ) , maCbbTargets( this, SVX_RES( CBB_TARGETS ) ) , maFtName( this, SVX_RES( FT_NAME ) ) , maEdtName( this, SVX_RES( EDT_NAME ) ) , maFtAlternativeText( this, SVX_RES( FT_URLDESCRIPTION ) ) , maEdtAlternativeText( this, SVX_RES( EDT_URLDESCRIPTION ) ) , maFtDescription( this, SVX_RES( FT_DESCRIPTION ) ) , maEdtDescription( this, SVX_RES( EDT_DESCRIPTION ) ) , maFlURL( this, SVX_RES( FL_URL ) ) , maBtnHelp( this, SVX_RES( BTN_HELP1 ) ) , maBtnOk( this, SVX_RES( BTN_OK1 ) ) , maBtnCancel( this, SVX_RES( BTN_CANCEL1 ) ) { FreeResource(); maEdtURL.SetText( rURL ); maEdtAlternativeText.SetText( rAlternativeText ); maEdtDescription.SetText( rDescription ); maEdtName.SetText( rName ); for( String* pStr = rTargetList.First(); pStr; pStr = rTargetList.Next() ) maCbbTargets.InsertEntry( *pStr ); if( !rTarget.Len() ) maCbbTargets.SetText( String::CreateFromAscii( "_self" ) ); else maCbbTargets.SetText( rTarget ); } <commit_msg>INTEGRATION: CWS vgbugs07 (1.8.32); FILE MERGED 2007/06/04 13:26:15 vg 1.8.32.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cuiimapwnd.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2007-06-27 16:58:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif #ifndef _URLOBJ_HXX //autogen #include <tools/urlobj.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SV_HELP_HXX //autogen #include <vcl/help.hxx> #endif #ifndef _SFXSIDS_HRC #include <sfx2/sfxsids.hrc> // SID_ATTR_MACROITEM #endif #define _ANIMATION #ifndef _MACROPG_HXX //autogen #include <sfx2/macropg.hxx> #endif #ifndef _GOODIES_IMAPRECT_HXX //autogen #include <svtools/imaprect.hxx> #endif #ifndef _GOODIES_IMAPCIRC_HXX //autogen #include <svtools/imapcirc.hxx> #endif #ifndef _GOODIES_IMAPPOLY_HXX //autogen #include <svtools/imappoly.hxx> #endif #ifndef _URLBMK_HXX //autogen #include <svtools/urlbmk.hxx> #endif #include <xoutbmp.hxx> #include <svx/dialmgr.hxx> #include <svx/dialogs.hrc> #include <svx/svxids.hrc> #include <imapdlg.hrc> #include <imapwnd.hxx> #include <svx/svdpage.hxx> #include <svx/svdorect.hxx> #include <svx/svdocirc.hxx> #include <svx/svdopath.hxx> #include <svx/xfltrit.hxx> #include <svx/svdpagv.hxx> #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #ifndef _SVX_FILLITEM_HXX //autogen #include <svx/xfillit.hxx> #endif #ifndef _SVX_XLINIIT_HXX //autogen #include <svx/xlineit.hxx> #endif #include <sot/formats.hxx> #include "cuiimapwnd.hxx" //CHINA001 #ifdef MAC #define TRANSCOL Color( COL_LIGHTGRAY ) #else #define TRANSCOL Color( COL_WHITE ) #endif /************************************************************************* |* |* URLDlg |* \************************************************************************/ URLDlg::URLDlg( Window* pWindow, const String& rURL, const String& rAlternativeText, const String& rDescription, const String& rTarget, const String& rName, TargetList& rTargetList ) : ModalDialog( pWindow, SVX_RES( RID_SVXDLG_IMAPURL ) ) , maFtURL( this, SVX_RES( FT_URL1 ) ) , maEdtURL( this, SVX_RES( EDT_URL ) ) , maFtTarget( this, SVX_RES( FT_TARGET ) ) , maCbbTargets( this, SVX_RES( CBB_TARGETS ) ) , maFtName( this, SVX_RES( FT_NAME ) ) , maEdtName( this, SVX_RES( EDT_NAME ) ) , maFtAlternativeText( this, SVX_RES( FT_URLDESCRIPTION ) ) , maEdtAlternativeText( this, SVX_RES( EDT_URLDESCRIPTION ) ) , maFtDescription( this, SVX_RES( FT_DESCRIPTION ) ) , maEdtDescription( this, SVX_RES( EDT_DESCRIPTION ) ) , maFlURL( this, SVX_RES( FL_URL ) ) , maBtnHelp( this, SVX_RES( BTN_HELP1 ) ) , maBtnOk( this, SVX_RES( BTN_OK1 ) ) , maBtnCancel( this, SVX_RES( BTN_CANCEL1 ) ) { FreeResource(); maEdtURL.SetText( rURL ); maEdtAlternativeText.SetText( rAlternativeText ); maEdtDescription.SetText( rDescription ); maEdtName.SetText( rName ); for( String* pStr = rTargetList.First(); pStr; pStr = rTargetList.Next() ) maCbbTargets.InsertEntry( *pStr ); if( !rTarget.Len() ) maCbbTargets.SetText( String::CreateFromAscii( "_self" ) ); else maCbbTargets.SetText( rTarget ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: accdoc.hxx,v $ * * $Revision: 1.18 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:46:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _ACCDOC_HXX #define _ACCDOC_HXX #ifndef _ACCCONTEXT_HXX #include "acccontext.hxx" #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_ #include <com/sun/star/accessibility/XAccessibleSelection.hpp> #endif #ifndef _ACCSELECTIONHELPER_HXX_ #include <accselectionhelper.hxx> #endif class SwRootFrm; class SwFEShell; class SwFlyFrm; class VclSimpleEvent; /** * base class for SwAccessibleDocument (in this same header file) and * SwAccessiblePreview */ class SwAccessibleDocumentBase : public SwAccessibleContext { ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> xParent; Window *pChildWin; // protected by solar mutext protected: virtual ~SwAccessibleDocumentBase(); public: SwAccessibleDocumentBase( SwAccessibleMap *pMap ); void SetVisArea(); virtual void AddChild( Window *pWin, sal_Bool bFireEvent = sal_True ); virtual void RemoveChild( Window *pWin ); //===== XAccessibleContext ============================================== /// Return the number of currently visible children. virtual long SAL_CALL getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException); /// Return the specified child or NULL if index is invalid. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild (long nIndex) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IndexOutOfBoundsException); /// Return a reference to the parent. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this objects index among the parents children. virtual sal_Int32 SAL_CALL getAccessibleIndexInParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's description. virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void) throw (com::sun::star::uno::RuntimeException); //===== XAccessibleComponent ============================================== virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocation() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Size SAL_CALL getSize() throw (::com::sun::star::uno::RuntimeException); }; /** * access to an accessible Writer document */ class SwAccessibleDocument : public SwAccessibleDocumentBase, public com::sun::star::accessibility::XAccessibleSelection { // Implementation for XAccessibleSelection interface SwAccessibleSelectionHelper aSelectionHelper; protected: // Set states for getAccessibleStateSet. // This drived class additinaly sets MULTISELECTABLE(1) virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet ); virtual ~SwAccessibleDocument(); public: SwAccessibleDocument( SwAccessibleMap *pMap ); DECL_LINK( WindowChildEventListener, VclSimpleEvent* ); //===== XServiceInfo ==================================================== /** Returns an identifier for the implementation of this object. */ virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); /** Return whether the specified service is supported by this class. */ virtual sal_Bool SAL_CALL supportsService (const ::rtl::OUString& sServiceName) throw (::com::sun::star::uno::RuntimeException); /** Returns a list of all supported services. In this case that is just the AccessibleContext service. */ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); //===== XInterface ====================================================== // XInterface is inherited through SwAcessibleContext and // XAccessibleSelection. These methods are needed to avoid // ambigiouties. virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( ) throw () { SwAccessibleContext::acquire(); }; virtual void SAL_CALL release( ) throw () { SwAccessibleContext::release(); }; //====== XTypeProvider ==================================================== virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException); //===== XAccessibleSelection ============================================ virtual void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL clearAccessibleSelection( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL selectAllAccessibleChildren( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // --> OD 2004-11-16 #111714# - index has to be treated as global child index. virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); //====== thread safe C++ interface ======================================== // The object is not visible an longer and should be destroyed virtual void Dispose( sal_Bool bRecursive = sal_False ); }; #endif <commit_msg>INTEGRATION: CWS long2int (1.18.74); FILE MERGED 2005/10/26 18:06:49 kendy 1.18.74.1: #i56715# Trivial long/ULONG -> sal_Int32/sal_uInt32 patches extracted from ooo64bit02 CWS.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: accdoc.hxx,v $ * * $Revision: 1.19 $ * * last change: $Author: vg $ $Date: 2006-03-31 09:09:45 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _ACCDOC_HXX #define _ACCDOC_HXX #ifndef _ACCCONTEXT_HXX #include "acccontext.hxx" #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_ #include <com/sun/star/accessibility/XAccessibleSelection.hpp> #endif #ifndef _ACCSELECTIONHELPER_HXX_ #include <accselectionhelper.hxx> #endif class SwRootFrm; class SwFEShell; class SwFlyFrm; class VclSimpleEvent; /** * base class for SwAccessibleDocument (in this same header file) and * SwAccessiblePreview */ class SwAccessibleDocumentBase : public SwAccessibleContext { ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> xParent; Window *pChildWin; // protected by solar mutext protected: virtual ~SwAccessibleDocumentBase(); public: SwAccessibleDocumentBase( SwAccessibleMap *pMap ); void SetVisArea(); virtual void AddChild( Window *pWin, sal_Bool bFireEvent = sal_True ); virtual void RemoveChild( Window *pWin ); //===== XAccessibleContext ============================================== /// Return the number of currently visible children. virtual sal_Int32 SAL_CALL getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException); /// Return the specified child or NULL if index is invalid. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild (sal_Int32 nIndex) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IndexOutOfBoundsException); /// Return a reference to the parent. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this objects index among the parents children. virtual sal_Int32 SAL_CALL getAccessibleIndexInParent (void) throw (::com::sun::star::uno::RuntimeException); /// Return this object's description. virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void) throw (com::sun::star::uno::RuntimeException); //===== XAccessibleComponent ============================================== virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocation() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::Size SAL_CALL getSize() throw (::com::sun::star::uno::RuntimeException); }; /** * access to an accessible Writer document */ class SwAccessibleDocument : public SwAccessibleDocumentBase, public com::sun::star::accessibility::XAccessibleSelection { // Implementation for XAccessibleSelection interface SwAccessibleSelectionHelper aSelectionHelper; protected: // Set states for getAccessibleStateSet. // This drived class additinaly sets MULTISELECTABLE(1) virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet ); virtual ~SwAccessibleDocument(); public: SwAccessibleDocument( SwAccessibleMap *pMap ); DECL_LINK( WindowChildEventListener, VclSimpleEvent* ); //===== XServiceInfo ==================================================== /** Returns an identifier for the implementation of this object. */ virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); /** Return whether the specified service is supported by this class. */ virtual sal_Bool SAL_CALL supportsService (const ::rtl::OUString& sServiceName) throw (::com::sun::star::uno::RuntimeException); /** Returns a list of all supported services. In this case that is just the AccessibleContext service. */ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); //===== XInterface ====================================================== // XInterface is inherited through SwAcessibleContext and // XAccessibleSelection. These methods are needed to avoid // ambigiouties. virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( ) throw () { SwAccessibleContext::acquire(); }; virtual void SAL_CALL release( ) throw () { SwAccessibleContext::release(); }; //====== XTypeProvider ==================================================== virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException); //===== XAccessibleSelection ============================================ virtual void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL clearAccessibleSelection( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL selectAllAccessibleChildren( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // --> OD 2004-11-16 #111714# - index has to be treated as global child index. virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nChildIndex ) throw ( ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException ); //====== thread safe C++ interface ======================================== // The object is not visible an longer and should be destroyed virtual void Dispose( sal_Bool bRecursive = sal_False ); }; #endif <|endoftext|>
<commit_before> #include "adaptive_time_solver.h" #include "diff_system.h" #include "euler_solver.h" #include "numeric_vector.h" AdaptiveTimeSolver::AdaptiveTimeSolver (sys_type& s) : UnsteadySolver(s), core_time_solver(NULL), target_tolerance(1.e-3), upper_tolerance(0.0), max_deltat(0.), min_deltat(0.), max_growth(0.), global_tolerance(true) { // We start with a reasonable time solver: implicit Eulerthe child class must populate core_time_solver // with whatever actual time solver is to be used } AdaptiveTimeSolver::~AdaptiveTimeSolver () { } void AdaptiveTimeSolver::init() { libmesh_assert(core_time_solver.get()); // We override this because our core_time_solver is the one that // needs to handle new vectors, diff_solver->init(), etc core_time_solver->init(); } void AdaptiveTimeSolver::reinit() { libmesh_assert(core_time_solver.get()); // We override this because our core_time_solver is the one that // needs to handle new vectors, diff_solver->reinit(), etc core_time_solver->reinit(); } void AdaptiveTimeSolver::advance_timestep () { NumericVector<Number> &old_nonlinear_solution = _system.get_vector("_old_nonlinear_solution"); NumericVector<Number> &nonlinear_solution = *(_system.solution); // _system.get_vector("_nonlinear_solution"); old_nonlinear_solution = nonlinear_solution; if (!first_solve) _system.time += last_deltat; } Real AdaptiveTimeSolver::error_order () const { libmesh_assert(core_time_solver.get()); return core_time_solver->error_order(); } bool AdaptiveTimeSolver::element_residual (bool request_jacobian) { libmesh_assert(core_time_solver.get()); return core_time_solver->element_residual(request_jacobian); } bool AdaptiveTimeSolver::side_residual (bool request_jacobian) { libmesh_assert(core_time_solver.get()); return core_time_solver->side_residual(request_jacobian); } AutoPtr<DiffSolver> & AdaptiveTimeSolver::diff_solver() { return core_time_solver->diff_solver(); } Real AdaptiveTimeSolver::calculate_norm(System &s, NumericVector<Number> &v) { return s.calculate_norm(v, component_norm); } <commit_msg>Fixed comment<commit_after> #include "adaptive_time_solver.h" #include "diff_system.h" #include "euler_solver.h" #include "numeric_vector.h" AdaptiveTimeSolver::AdaptiveTimeSolver (sys_type& s) : UnsteadySolver(s), core_time_solver(NULL), target_tolerance(1.e-3), upper_tolerance(0.0), max_deltat(0.), min_deltat(0.), max_growth(0.), global_tolerance(true) { // the child class must populate core_time_solver // with whatever default time solver is to be used } AdaptiveTimeSolver::~AdaptiveTimeSolver () { } void AdaptiveTimeSolver::init() { libmesh_assert(core_time_solver.get()); // We override this because our core_time_solver is the one that // needs to handle new vectors, diff_solver->init(), etc core_time_solver->init(); } void AdaptiveTimeSolver::reinit() { libmesh_assert(core_time_solver.get()); // We override this because our core_time_solver is the one that // needs to handle new vectors, diff_solver->reinit(), etc core_time_solver->reinit(); } void AdaptiveTimeSolver::advance_timestep () { NumericVector<Number> &old_nonlinear_solution = _system.get_vector("_old_nonlinear_solution"); NumericVector<Number> &nonlinear_solution = *(_system.solution); // _system.get_vector("_nonlinear_solution"); old_nonlinear_solution = nonlinear_solution; if (!first_solve) _system.time += last_deltat; } Real AdaptiveTimeSolver::error_order () const { libmesh_assert(core_time_solver.get()); return core_time_solver->error_order(); } bool AdaptiveTimeSolver::element_residual (bool request_jacobian) { libmesh_assert(core_time_solver.get()); return core_time_solver->element_residual(request_jacobian); } bool AdaptiveTimeSolver::side_residual (bool request_jacobian) { libmesh_assert(core_time_solver.get()); return core_time_solver->side_residual(request_jacobian); } AutoPtr<DiffSolver> & AdaptiveTimeSolver::diff_solver() { return core_time_solver->diff_solver(); } Real AdaptiveTimeSolver::calculate_norm(System &s, NumericVector<Number> &v) { return s.calculate_norm(v, component_norm); } <|endoftext|>
<commit_before>/** The goal of this tutorial is to implement in Tiramisu a code that is equivalent to the following for (int i = 0; i < 10; i++) for (int j = 0; j < 20; j++) output[i, j] = A[i, j] + i + 2; */ #include <tiramisu/tiramisu.h> #define NN 10 #define MM 20 using namespace tiramisu; int main(int argc, char **argv) { tiramisu::init("tut_02"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- // Declare two constants N and M. These constants will be used as loop bounds. constant N_const("N", NN); constant M_const("M", MM); // Declare iterator variables. var i("i", 0, N_const), j("j", 0, M_const); // Declare an input. The input is declared by providing iterators // (that define the size of the buffer) and the type of the buffer elements. input A({i,j}, p_uint8); // Declare the output computation. computation output({i,j}, (A(i, j) + cast(p_uint8, i) + (uint8_t)4)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of the computation. var i0("i0"), i1("i1"), j0("j0"), j1("j1"); // Tile the i, j loop around output by a 2x2 tile. The names of iterators // in the resulting loop are i0, j0, i1, j1. output.tile(i, j, 2, 2, i0, j0, i1, j1); // Parallelize the outermost loop i0 (OpenMP style parallelism). output.parallelize(i0); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- // Declare input and output buffers. buffer b_A("b_A", {expr(NN), expr(MM)}, p_uint8, a_input); buffer b_output("b_output", {expr(NN), expr(MM)}, p_uint8, a_output); // Map the computations to a buffer. // The following call indicates that each computation A[i,j] // is stored in the buffer element b_A[i,j] (one-to-one mapping). // This is the most common mapping to memory. A.store_in(&b_A); output.store_in(&b_output); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments and generate code tiramisu::codegen({&b_A, &b_output}, "build/generated_fct_developers_tutorial_02.o"); return 0; } <commit_msg>Update tutorial_02.cpp<commit_after>/** The goal of this tutorial is to implement in Tiramisu a code that is equivalent to the following for (int i = 0; i < 10; i++) for (int j = 0; j < 20; j++) output[i, j] = A[i, j] + i + 4; */ #include <tiramisu/tiramisu.h> #define NN 10 #define MM 20 using namespace tiramisu; int main(int argc, char **argv) { tiramisu::init("tut_02"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- // Declare two constants N and M. These constants will be used as loop bounds. constant N("N", NN); constant M("M", MM); // Declare iterator variables. var i("i", 0, N), j("j", 0, M); // Declare an input. The input is declared by providing iterators // (that define the size of the buffer) and the type of the buffer elements. input A({i,j}, p_uint8); // Declare the output computation. computation output({i,j}, (A(i, j) + cast(p_uint8, i) + (uint8_t)4)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of the computation. var i0("i0"), i1("i1"), j0("j0"), j1("j1"); // Tile the i, j loop around output by a 2x2 tile. The names of iterators // in the resulting loop are i0, j0, i1, j1. output.tile(i, j, 2, 2, i0, j0, i1, j1); // Parallelize the outermost loop i0 (OpenMP style parallelism). output.parallelize(i0); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- // Declare input and output buffers. buffer b_A("b_A", {expr(NN), expr(MM)}, p_uint8, a_input); buffer b_output("b_output", {expr(NN), expr(MM)}, p_uint8, a_output); // Map the computations to a buffer. // The following call indicates that each computation A[i,j] // is stored in the buffer element b_A[i,j] (one-to-one mapping). // This is the most common mapping to memory. A.store_in(&b_A); output.store_in(&b_output); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments and generate code tiramisu::codegen({&b_A, &b_output}, "build/generated_fct_developers_tutorial_02.o"); return 0; } <|endoftext|>
<commit_before>/// @file /// @author Kresimir Spes /// @author Boris Mikic /// @author Ivan Vucica /// @version 2.43 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php #include <stdio.h> #include <algorithm> #ifdef __APPLE__ #include <TargetConditionals.h> #endif #include <hltypes/harray.h> #include <hltypes/hlog.h> #include <hltypes/hltypesUtil.h> #include <hltypes/hresource.h> #include <hltypes/hstring.h> #include "april.h" #include "aprilUtil.h" #include "ImageSource.h" #include "RamTexture.h" #include "RenderSystem.h" #include "Texture.h" #include "Window.h" namespace april { PlainVertex pv[4]; TexturedVertex tv[4]; april::RenderSystem* rendersys = NULL; RenderSystem::RenderSystem() : created(false), textureFilter(Texture::FILTER_LINEAR), textureAddressMode(Texture::ADDRESS_WRAP) { this->name = "Generic"; } RenderSystem::~RenderSystem() { this->destroy(); } bool RenderSystem::create(chstr options) { if (!this->created) { hlog::writef(april::logTag, "Creating rendersystem: '%s' (options: '%s')", this->name.c_str(), options.c_str()); this->created = true; return true; } return false; } bool RenderSystem::destroy() { if (this->created) { hlog::writef(april::logTag, "Destroying rendersystem '%s'.", this->name.c_str()); while (this->textures.size() > 0) { delete this->textures[0]; } this->created = false; return true; } return false; } void RenderSystem::reset() { hlog::write(april::logTag, "Resetting rendersystem."); } void RenderSystem::setOrthoProjection(grect rect) { this->orthoProjection = rect; float t = this->getPixelOffset(); float wnd_w = (float)april::window->getWidth(); float wnd_h = (float)april::window->getHeight(); rect.x -= t * rect.w / wnd_w; rect.y -= t * rect.h / wnd_h; this->projectionMatrix.ortho(rect); this->_setProjectionMatrix(this->projectionMatrix); } void RenderSystem::setOrthoProjection(gvec2 size) { this->setOrthoProjection(grect(0.0f, 0.0f, size)); } void RenderSystem::setModelviewMatrix(gmat4 matrix) { this->modelviewMatrix = matrix; this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::setProjectionMatrix(gmat4 matrix) { this->projectionMatrix = matrix; this->_setProjectionMatrix(this->projectionMatrix); } void RenderSystem::setResolution(int w, int h) { hlog::writef(april::logTag, "Changing resolution: %d x %d", w, h); april::window->_setResolution(w, h); } Texture* RenderSystem::loadTexture(chstr filename, bool delayLoad) { hstr name = this->findTextureFilename(filename); if (name == "") { return NULL; } Texture* texture = this->_createTexture(name); if (!delayLoad) { texture->load(); } if (!delayLoad && !texture->isLoaded()) { delete texture; return NULL; } return texture; } Texture* RenderSystem::loadRamTexture(chstr filename, bool delayLoad) { hstr name = this->findTextureFilename(filename); if (name == "") { return NULL; } RamTexture* texture = new RamTexture(name); if (!delayLoad) { texture->load(); } if (!delayLoad && !texture->isLoaded()) { delete texture; return NULL; } return texture; } void RenderSystem::unloadTextures() { foreach (Texture*, it, this->textures) { (*it)->unload(); } } void RenderSystem::setIdentityTransform() { this->modelviewMatrix.setIdentity(); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::translate(float x, float y, float z) { this->modelviewMatrix.translate(x, y, z); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::rotate(float angle, float ax, float ay, float az) { this->modelviewMatrix.rotate(ax, ay, az, angle); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::scale(float s) { this->modelviewMatrix.scale(s); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::scale(float sx, float sy, float sz) { this->modelviewMatrix.scale(sx, sy, sz); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::lookAt(const gvec3 &eye, const gvec3 &direction, const gvec3 &up) { this->modelviewMatrix.lookAt(eye, direction, up); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::setPerspective(float fov, float aspect, float nearClip, float farClip) { this->projectionMatrix.perspective(fov, aspect, nearClip, farClip); this->_setProjectionMatrix(this->projectionMatrix); } void RenderSystem::drawRect(grect rect, Color color) { pv[0].x = rect.x; pv[0].y = rect.y; pv[0].z = 0.0f; pv[1].x = rect.x + rect.w; pv[1].y = rect.y; pv[1].z = 0.0f; pv[2].x = rect.x + rect.w; pv[2].y = rect.y + rect.h; pv[2].z = 0.0f; pv[3].x = rect.x; pv[3].y = rect.y + rect.h; pv[3].z = 0.0f; pv[4].x = rect.x; pv[4].y = rect.y; pv[4].z = 0.0f; this->render(LineStrip, pv, 5, color); } void RenderSystem::drawFilledRect(grect rect, Color color) { pv[0].x = rect.x; pv[0].y = rect.y; pv[0].z = 0.0f; pv[1].x = rect.x + rect.w; pv[1].y = rect.y; pv[1].z = 0.0f; pv[2].x = rect.x; pv[2].y = rect.y + rect.h; pv[2].z = 0.0f; pv[3].x = rect.x + rect.w; pv[3].y = rect.y + rect.h; pv[3].z = 0.0f; this->render(TriangleStrip, pv, 4, color); } void RenderSystem::drawTexturedRect(grect rect, grect src) { tv[0].x = rect.x; tv[0].y = rect.y; tv[0].z = 0.0f; tv[0].u = src.x; tv[0].v = src.y; tv[1].x = rect.x + rect.w; tv[1].y = rect.y; tv[1].z = 0.0f; tv[1].u = src.x + src.w; tv[1].v = src.y; tv[2].x = rect.x; tv[2].y = rect.y + rect.h; tv[2].z = 0.0f; tv[2].u = src.x; tv[2].v = src.y + src.h; tv[3].x = rect.x + rect.w; tv[3].y = rect.y + rect.h; tv[3].z = 0.0f; tv[3].u = src.x + src.w; tv[3].v = src.y + src.h; this->render(TriangleStrip, tv, 4); } void RenderSystem::drawTexturedRect(grect rect, grect src, Color color) { tv[0].x = rect.x; tv[0].y = rect.y; tv[0].z = 0.0f; tv[0].u = src.x; tv[0].v = src.y; tv[1].x = rect.x + rect.w; tv[1].y = rect.y; tv[1].z = 0.0f; tv[1].u = src.x + src.w; tv[1].v = src.y; tv[2].x = rect.x; tv[2].y = rect.y + rect.h; tv[2].z = 0.0f; tv[2].u = src.x; tv[2].v = src.y + src.h; tv[3].x = rect.x + rect.w; tv[3].y = rect.y + rect.h; tv[3].z = 0.0f; tv[3].u = src.x + src.w; tv[3].v = src.y + src.h; this->render(TriangleStrip, tv, 4, color); } void RenderSystem::presentFrame() { april::window->presentFrame(); } hstr RenderSystem::findTextureFilename(chstr filename) { if (hresource::exists(filename)) { return filename; } hstr name; harray<hstr> extensions = april::getTextureExtensions(); foreach (hstr, it, extensions) { name = filename + (*it); if (hresource::exists(name)) { return name; } } int index = filename.rfind("."); if (index >= 0) { hstr noExtensionName = filename.substr(0, index); foreach (hstr, it, extensions) { name = noExtensionName + (*it); if (hresource::exists(name)) { return name; } } } return ""; } void RenderSystem::_registerTexture(Texture* texture) { this->textures += texture; } void RenderSystem::_unregisterTexture(Texture* texture) { this->textures -= texture; } } <commit_msg>- fixed memory corruption problem<commit_after>/// @file /// @author Kresimir Spes /// @author Boris Mikic /// @author Ivan Vucica /// @version 2.43 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php #include <stdio.h> #include <algorithm> #ifdef __APPLE__ #include <TargetConditionals.h> #endif #include <hltypes/harray.h> #include <hltypes/hlog.h> #include <hltypes/hltypesUtil.h> #include <hltypes/hresource.h> #include <hltypes/hstring.h> #include "april.h" #include "aprilUtil.h" #include "ImageSource.h" #include "RamTexture.h" #include "RenderSystem.h" #include "Texture.h" #include "Window.h" namespace april { PlainVertex pv[5]; TexturedVertex tv[5]; april::RenderSystem* rendersys = NULL; RenderSystem::RenderSystem() : created(false), textureFilter(Texture::FILTER_LINEAR), textureAddressMode(Texture::ADDRESS_WRAP) { this->name = "Generic"; } RenderSystem::~RenderSystem() { this->destroy(); } bool RenderSystem::create(chstr options) { if (!this->created) { hlog::writef(april::logTag, "Creating rendersystem: '%s' (options: '%s')", this->name.c_str(), options.c_str()); this->created = true; return true; } return false; } bool RenderSystem::destroy() { if (this->created) { hlog::writef(april::logTag, "Destroying rendersystem '%s'.", this->name.c_str()); while (this->textures.size() > 0) { delete this->textures[0]; } this->created = false; return true; } return false; } void RenderSystem::reset() { hlog::write(april::logTag, "Resetting rendersystem."); } void RenderSystem::setOrthoProjection(grect rect) { this->orthoProjection = rect; float t = this->getPixelOffset(); float wnd_w = (float)april::window->getWidth(); float wnd_h = (float)april::window->getHeight(); rect.x -= t * rect.w / wnd_w; rect.y -= t * rect.h / wnd_h; this->projectionMatrix.ortho(rect); this->_setProjectionMatrix(this->projectionMatrix); } void RenderSystem::setOrthoProjection(gvec2 size) { this->setOrthoProjection(grect(0.0f, 0.0f, size)); } void RenderSystem::setModelviewMatrix(gmat4 matrix) { this->modelviewMatrix = matrix; this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::setProjectionMatrix(gmat4 matrix) { this->projectionMatrix = matrix; this->_setProjectionMatrix(this->projectionMatrix); } void RenderSystem::setResolution(int w, int h) { hlog::writef(april::logTag, "Changing resolution: %d x %d", w, h); april::window->_setResolution(w, h); } Texture* RenderSystem::loadTexture(chstr filename, bool delayLoad) { hstr name = this->findTextureFilename(filename); if (name == "") { return NULL; } Texture* texture = this->_createTexture(name); if (!delayLoad) { texture->load(); } if (!delayLoad && !texture->isLoaded()) { delete texture; return NULL; } return texture; } Texture* RenderSystem::loadRamTexture(chstr filename, bool delayLoad) { hstr name = this->findTextureFilename(filename); if (name == "") { return NULL; } RamTexture* texture = new RamTexture(name); if (!delayLoad) { texture->load(); } if (!delayLoad && !texture->isLoaded()) { delete texture; return NULL; } return texture; } void RenderSystem::unloadTextures() { foreach (Texture*, it, this->textures) { (*it)->unload(); } } void RenderSystem::setIdentityTransform() { this->modelviewMatrix.setIdentity(); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::translate(float x, float y, float z) { this->modelviewMatrix.translate(x, y, z); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::rotate(float angle, float ax, float ay, float az) { this->modelviewMatrix.rotate(ax, ay, az, angle); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::scale(float s) { this->modelviewMatrix.scale(s); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::scale(float sx, float sy, float sz) { this->modelviewMatrix.scale(sx, sy, sz); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::lookAt(const gvec3 &eye, const gvec3 &direction, const gvec3 &up) { this->modelviewMatrix.lookAt(eye, direction, up); this->_setModelviewMatrix(this->modelviewMatrix); } void RenderSystem::setPerspective(float fov, float aspect, float nearClip, float farClip) { this->projectionMatrix.perspective(fov, aspect, nearClip, farClip); this->_setProjectionMatrix(this->projectionMatrix); } void RenderSystem::drawRect(grect rect, Color color) { pv[0].x = rect.x; pv[0].y = rect.y; pv[0].z = 0.0f; pv[1].x = rect.x + rect.w; pv[1].y = rect.y; pv[1].z = 0.0f; pv[2].x = rect.x + rect.w; pv[2].y = rect.y + rect.h; pv[2].z = 0.0f; pv[3].x = rect.x; pv[3].y = rect.y + rect.h; pv[3].z = 0.0f; pv[4].x = rect.x; pv[4].y = rect.y; pv[4].z = 0.0f; this->render(LineStrip, pv, 5, color); } void RenderSystem::drawFilledRect(grect rect, Color color) { pv[0].x = rect.x; pv[0].y = rect.y; pv[0].z = 0.0f; pv[1].x = rect.x + rect.w; pv[1].y = rect.y; pv[1].z = 0.0f; pv[2].x = rect.x; pv[2].y = rect.y + rect.h; pv[2].z = 0.0f; pv[3].x = rect.x + rect.w; pv[3].y = rect.y + rect.h; pv[3].z = 0.0f; this->render(TriangleStrip, pv, 4, color); } void RenderSystem::drawTexturedRect(grect rect, grect src) { tv[0].x = rect.x; tv[0].y = rect.y; tv[0].z = 0.0f; tv[0].u = src.x; tv[0].v = src.y; tv[1].x = rect.x + rect.w; tv[1].y = rect.y; tv[1].z = 0.0f; tv[1].u = src.x + src.w; tv[1].v = src.y; tv[2].x = rect.x; tv[2].y = rect.y + rect.h; tv[2].z = 0.0f; tv[2].u = src.x; tv[2].v = src.y + src.h; tv[3].x = rect.x + rect.w; tv[3].y = rect.y + rect.h; tv[3].z = 0.0f; tv[3].u = src.x + src.w; tv[3].v = src.y + src.h; this->render(TriangleStrip, tv, 4); } void RenderSystem::drawTexturedRect(grect rect, grect src, Color color) { tv[0].x = rect.x; tv[0].y = rect.y; tv[0].z = 0.0f; tv[0].u = src.x; tv[0].v = src.y; tv[1].x = rect.x + rect.w; tv[1].y = rect.y; tv[1].z = 0.0f; tv[1].u = src.x + src.w; tv[1].v = src.y; tv[2].x = rect.x; tv[2].y = rect.y + rect.h; tv[2].z = 0.0f; tv[2].u = src.x; tv[2].v = src.y + src.h; tv[3].x = rect.x + rect.w; tv[3].y = rect.y + rect.h; tv[3].z = 0.0f; tv[3].u = src.x + src.w; tv[3].v = src.y + src.h; this->render(TriangleStrip, tv, 4, color); } void RenderSystem::presentFrame() { april::window->presentFrame(); } hstr RenderSystem::findTextureFilename(chstr filename) { if (hresource::exists(filename)) { return filename; } hstr name; harray<hstr> extensions = april::getTextureExtensions(); foreach (hstr, it, extensions) { name = filename + (*it); if (hresource::exists(name)) { return name; } } int index = filename.rfind("."); if (index >= 0) { hstr noExtensionName = filename.substr(0, index); foreach (hstr, it, extensions) { name = noExtensionName + (*it); if (hresource::exists(name)) { return name; } } } return ""; } void RenderSystem::_registerTexture(Texture* texture) { this->textures += texture; } void RenderSystem::_unregisterTexture(Texture* texture) { this->textures -= texture; } } <|endoftext|>
<commit_before>//stl list //载入头文件 #include <iostream> #include <list> using namespace std; typedef struct { char name[21]; int id; } note ; bool myFun(const int& value) { return (value < 2); } int main(int argc, char const *argv[]) { //建立 list<int> L0; // 空链表 list<int> L1(9); // 建一个含一个元素的链表 list<int> L2(5,1); // 建一个多个个元素的链表 list<int> L3(L2); // 复制L2的元素,重新建立一个链表 list<int> L4(L0.begin(), L0.end());//建一个含L0一个区域的链表 //其他元素类型的链表 list<double> Ld; list<note> Lu; //链表操作 //一个链表 list<int> l; //在链表头部插入元素 l.push_front(1); //尾部 l.push_back(2); l.push_back(3); l.pop_back();//删除链表尾的一个元素 l.pop_front();//删除链表头的一元素 l.clear();//删除所有元素 l.push_back(3); l.push_back(3); l.push_back(4); l.remove(4);//删除链表中匹配值的元素(匹配元素全部删除) //remove_if()删除条件满足的元素(遍历一次链表),参数为自定义的回调函数 // 小于2的值删除 l.push_back(1); l.remove_if(myFun); // list1(3)  //empty()判断是否链表为空 //大小 list<int>::size_type nRet = l.size(); //返回第一个元素的引用 int n= l.front() ; //返回最后一元素的引用 n = l.back() ; //返回第一个元素的迭代器(iterator) list<int>::iterator it = l.begin(); //返回最后一个元素的下一位置的指针(list为空时end()=begin()) it = l.end(); l.erase(it - 1);//删除一个元素或一个区域的元素 return 0; }<commit_msg>update list<commit_after>//stl list //载入头文件 #include <iostream> #include <list> using namespace std; typedef struct { char name[21]; int id; } note ; bool myFun(const int& value) { return (value < 2); } int main(int argc, char const *argv[]) { //建立 list<int> L0; // 空链表 list<int> L1(9); // 建一个含一个元素的链表 list<int> L2(5,1); // 建一个多个个元素的链表 list<int> L3(L2); // 复制L2的元素,重新建立一个链表 list<int> L4(L0.begin(), L0.end());//建一个含L0一个区域的链表 //其他元素类型的链表 list<double> Ld; list<note> Lu; //链表操作 //一个链表 list<int> l; //在链表头部插入元素 l.push_front(1); //尾部 l.push_back(2); l.push_back(3); l.pop_back();//删除链表尾的一个元素 l.pop_front();//删除链表头的一元素 l.clear();//删除所有元素 l.push_back(3); l.push_back(3); l.push_back(4); l.remove(4);//删除链表中匹配值的元素(匹配元素全部删除) //remove_if()删除条件满足的元素(遍历一次链表),参数为自定义的回调函数 // 小于2的值删除 l.push_back(1); l.remove_if(myFun); // list1(3)  //empty()判断是否链表为空 //大小 list<int>::size_type nRet = l.size(); //返回第一个元素的引用 int n= l.front() ; //返回最后一元素的引用 n = l.back() ; //返回第一个元素的迭代器(iterator) list<int>::iterator it = l.begin(); //返回最后一个元素的下一位置的指针(list为空时end()=begin()) it = l.end(); l.erase(it --);//删除一个元素或一个区域的元素 return 0; }<|endoftext|>
<commit_before>#include "loweventer.hpp" #include "bison/lowparser.hpp" #include "../../ast.hpp" #include "../../ast/mgd/mgdFunc.hpp" #include "../../builtin/primitive.hpp" namespace wrd { using std::string; WRD_DEF_ME(loweventer) namespace { string merge(const narr& dotname) { string ret; for(auto& e : dotname) ret += e.cast<std::string>(); return ret; } } wint me::_onScan(YYSTYPE* val, YYLTYPE* loc, yyscan_t scanner) { int tok = _mode->onScan(*this, val, loc, scanner); if (_isIgnoreWhitespace && tok == NEWLINE) return SCAN_AGAIN; _isIgnoreWhitespace = false; switch(tok) { case SCAN_MODE_NORMAL: setScan<normalScan>(); return SCAN_AGAIN; case SCAN_MODE_INDENT: setScan<indentScan>(); return SCAN_AGAIN; case SCAN_MODE_INDENT_IGNORE: _isIgnoreWhitespace = true; return SCAN_AGAIN; case SCAN_MODE_END: tok = 0; // == yyterminate(); } return tok; } wint me::onScan(loweventer& ev, YYSTYPE* val, YYLTYPE* loc, yyscan_t scanner, wbool& isBypass) { int tok; do // why do you put redundant _onScan() func?: // because of definately, clang++ bug. when I use continue at switch statement inside of // do-while loop here, it doesn't work like usual 'continue' keyword does, but it does like // 'break'. tok = _onScan(val, loc, scanner); while(tok == SCAN_AGAIN); return tok; } wint me::onEndOfFile() { WRD_DI("tokenEvent: onEndOfFile() indents.size()=%d", _indents.size()); if(_indents.size() <= 1) _dispatcher.add(SCAN_MODE_END); else _dispatcher.addFront(onDedent(_indents.front(), SCAN_MODE_END)); WRD_DI("tokenEvent: onEndOfFile: finalize by adding 'NEWLINE', then dispatch end-of-file."); return NEWLINE; } wint me::onIndent(wcnt col, wint tok) { WRD_DI("tokenEvent: onIndent(col: %d, tok: %d) indents.size()=%d", col, tok, _indents.size()); _indents.push_back(col); _dispatcher.add(tok); return INDENT; } wint me::onDedent(wcnt col, wint tok) { WRD_DI("tokenEvent: onDedent(col: %d, tok: %d) indents.size()=%d", col, tok, _indents.size()); _indents.pop_back(); wint now = _indents.back(); if(now < col) onSrcWarn(errCode::WRONG_INDENT_LV, col, now, now); while(_indents.back() > col) { WRD_DI("tokenEvent: onDedent: indentlv become %d -> %d", _indents.back(), _indents[_indents.size()-2]); _indents.pop_back(); _dispatcher.add(DEDENT); } _dispatcher.add(tok); return DEDENT; } void me::onNewLine() { WRD_DI("tokenEvent: onNewLine: _isIgnoreWhitespace=%s, _indents.size()=%d", _isIgnoreWhitespace ? "true" : "false", _indents.size()); if(!_isIgnoreWhitespace && _indents.size() >= 1) _dispatcher.add(SCAN_MODE_INDENT); } wchar me::onScanUnexpected(const wchar* token) { onSrcErr(errCode::UNEXPECTED_TOK, token); return token[0]; } wint me::onIgnoreIndent(wint tok) { WRD_DI("tokenEvent: onIgnoreIndent(%d)", tok); _dispatcher.add(SCAN_MODE_INDENT_IGNORE); return tok; } void me::onEndParse() { area& area = *_srcArea; #if WRD_IS_DBG const point& pt = area.start; WRD_DI("tokenEvent: onEndParse(%d,%d)", pt.row, pt.col); #endif area.rel(); } node* me::onPack(const narr& dotname) { WRD_DI("tokenEvent: onPack(%s)", merge(dotname).c_str()); pack* pak = &getPack().get(); // pack syntax rule #1: // if there is no specified name of pack, I create an one. std::string firstName = dotname[0].cast<std::string>(); if(nul(pak)) getPack().bind(pak = new pack(manifest(firstName), packLoadings())); const std::string& realName = pak->getManifest().name; if(realName != firstName) return onErr(errCode::PACK_NOT_MATCH, firstName.c_str(), realName.c_str()), pak; // pack syntax rule #2: // middle name automatically created if not exist. // on interpreting 'mypack' pack, user may uses 'pack' keyword with dotted-name. // for instance, // 'pack mypack.component.ui' // in this scenario, mypack instance should be created before. and component sub // pack object can be created in this parsing keyword. node* e = pak; for(int n=1; n < dotname.len(); n++) { const std::string& name = dotname[n].cast<std::string>(); node* sub = &e->sub(name); if(nul(sub)) e->subs().add(name, sub = new mgdObj()); e = sub; } _subpack.bind(e); return e; } node* me::onPack() { WRD_DI("tokenEvent: onPack()"); onWarn(errCode::NO_PACK); pack* newPack = &_pack.get(); if(!_pack) _pack.bind(newPack = new pack(manifest(), packLoadings())); const std::string& name = _pack->getManifest().name; if(name != manifest::DEFAULT_NAME) return onErr(errCode::PACK_NOT_MATCH, manifest::DEFAULT_NAME, name.c_str()), newPack; _subpack.bind(newPack); // this is a default pack containing name as '{default}'. return newPack; } blockExpr* me::onBlock() { WRD_DI("tokenEvent: onBlock()"); return new blockExpr(); } blockExpr* me::onBlock(blockExpr& blk, node& stmt) { WRD_DI("tokenEvent: onBlock()"); if(nul(blk)) return onSrcErr(errCode::IS_NULL, "blk"), onBlock(); blk.getStmts().add(stmt); WRD_DI("tokenEvent: onBlock().len=%d", blk.getStmts().len()); return &blk; } scope* me::onDefBlock() { WRD_DI("tokenEvent: onDefBlock()"); return new scope(); } scope* me::onDefBlock(scope& s, node& candidate) { WRD_DI("tokenEvent: onDefBlock(candidate=%s)", candidate.getType().getName().c_str()); if(nul(s)) return onSrcErr(errCode::IS_NULL, "s"), onDefBlock(); expr* e = &candidate.cast<expr>(); if(nul(e)) return onSrcErr(errCode::PARAM_HAS_VAL, candidate.getType().getName().c_str()), onDefBlock(); defVarExpr& defVar = e->cast<defVarExpr>(); if(!nul(defVar)) { s.add(defVar.getParam().getName(), *defVar.getParam().getOrigin()); return &s; } s.add(_onPopName(*e), e); return &s; } expr* me::onDefVar(const std::string& name, const node& origin) { WRD_DI("tokenEvent: onDefVar(%s, %s)", origin.getType().getName().c_str(), name.c_str()); return new defVarExpr(*new param(name, origin)); } void me::onSrcArea(area& area) { _srcArea = &area; } void me::_onRes(err* new1) { new1->log(); _report->add(new1); } params me::_convertParams(const narr& exprs) { params ret; for(auto& expr: exprs) { defVarExpr& cast = expr.cast<defVarExpr>(); if(nul(cast)) return onSrcErr(errCode::NOT_EXPR, expr.getType().getName().c_str()), ret; if(nul(cast.getParam())) return onSrcErr(errCode::PARAM_HAS_VAL), ret; ret.add(cast.getParam().clone()); } return ret; } mgdFunc* me::onFunc(const std::string& name, const narr& exprs, const node& evalObj, const blockExpr& blk) { const wtype& evalType = evalObj.getType(); WRD_DI("tokenEvent: onFunc: %s(...[%x]) %s: blk.len()=%d", name.c_str(), &exprs, evalType.getName().c_str(), blk.getStmts().len()); mgdFunc* ret = new mgdFunc(_convertParams(exprs), evalType, blk); _onPushName(name, *ret); return ret; } narr* me::onList() { narr* ret = new narr(); WRD_DI("tokenEvent: onList()=%x", ret); return ret; } narr* me::onList(node* newExpr) { narr* ret = new narr(*newExpr); WRD_DI("tokenEvent: onList(%s[%x])=%x", newExpr->getType().getName().c_str(), newExpr, ret); return ret; } narr* me::onList(narr& list, node* newExpr) { WRD_DI("tokenEvent: onList(list[%x], %s[%x])", &list, newExpr->getType().getName().c_str(), newExpr); list.add(newExpr); return &list; } void me::onCompilationUnit(node& subpack, scope& arr) { WRD_DI("tokenEvent: onCompilationUnit(%x, arr[%x])", &subpack, &arr); if(nul(subpack)) { onErr(errCode::NO_PACK_TRAY); return; } bicontainable& con = subpack.subs(); for(auto e=arr.begin(); e ;++e) con.add(e.getKey(), *e); } returnExpr* me::onReturn() { WRD_DI("tokenEvent: onReturn()"); return new returnExpr(); } returnExpr* me::onReturn(node& exp) { WRD_DI("tokenEvent: onReturn(%s)", exp.getType().getName().c_str()); return new returnExpr(exp); } node* me::onName(const std::string& name) { return new wStr(name); } narr* me::onDotName(const node& name) { narr* ret = new narr(); ret->add(name); return ret; } narr* me::onDotName(narr& names, const node& name) { names.add(name); return &names; } node* me::onGet(const std::string& name) { WRD_DI("tokenEvent: onGet(%s)", name.c_str()); return new getExpr(name); } node* me::onGet(const std::string& name, const narr& args) { WRD_DI("tokenEvent: onGet(%s, %d)", name.c_str(), args.len()); return new getExpr(name, args); } node* me::onGet(node& from, const std::string& name, const narr& args) { WRD_DI("tokenEvent: onGet(%s, %s, %d)", from.getType().getName().c_str(), name.c_str(), args.len()); return new getExpr(from, name, args); } void me::_onPushName(const std::string& name, node& n) { _nameMap[&n] = name; } std::string me::_onPopName(node& n) { std::string ret = _nameMap[&n]; _nameMap.erase(&n); return ret; } runExpr* me::onRunExpr(const std::string& name, const narr& args) { WRD_DI("tokenEvent: onRunExpr(%s, narr[%d])", name.c_str(), args.len()); return new runExpr(nulOf<node>(), name, args); } // @param from can be expr. so I need to evaluate it through 'as()'. runExpr* me::onFillFromOfFuncCall(const node& me, runExpr& to) { WRD_DI("tokenEvent: onFillFromOfFuncCall(%s, runExpr[%s])", me.getType(). getName().c_str(), to.getName().c_str()); to.setMe(me); return &to; } node* me::onAssign(node& lhs, node& rhs) { WRD_DI("tokenEvent: onAssign(%s, %s)", lhs.getType().getName().c_str(), rhs.getType().getName().c_str()); return new assignExpr(lhs, rhs); } expr* me::onDefAssign(const std::string& name, node& rhs) { WRD_DI("tokenEvent: onDefAssign(%s, %s)", name.c_str(), rhs.getType().getName().c_str()); return new defAssignExpr(name, rhs); } asExpr* me::onAs(const node& me, const node& as) { WRD_DI("tokenEvent: onAs(%s, %s)", me.getType().getName().c_str(), as.getType().getName().c_str()); return new asExpr(me, as); } addExpr* me::onAdd(const node& lhs, const node& rhs) { WRD_DI("tokenEvent: onAdd(%s, %s)", lhs.getType().getName().c_str(), rhs.getType().getName() .c_str()); return new addExpr(lhs, rhs); } me::loweventer() { rel(); } tstr<pack>& me::getPack() { return _pack; } str& me::getSubPack() { return _subpack; } // TODO: can I remove subpack variable? tstr<errReport>& me::getReport() { return _report; } tokenDispatcher& me::getDispatcher() { return _dispatcher; } std::vector<wcnt>& me::getIndents() { return _indents; } const area& me::getArea() const { static area dummy {{0, 0}, {0, 1}}; return _srcArea ? *_srcArea : dummy; } wbool me::isInit() const { return _mode; } void me::rel() { _report.bind(dummyErrReport::singletone); _pack.rel(); _nameMap.clear(); _states.clear(); _states.push_back(0); // 0 for default state prepareParse(); } void me::prepareParse() { _mode = nullptr; _subpack.rel(); _isIgnoreWhitespace = false; _dispatcher.rel(); _indents.clear(); _srcArea = nullptr; } } <commit_msg>wrd: fix: defAssign on defBlock should change to variable<commit_after>#include "loweventer.hpp" #include "bison/lowparser.hpp" #include "../../ast.hpp" #include "../../ast/mgd/mgdFunc.hpp" #include "../../builtin/primitive.hpp" namespace wrd { using std::string; WRD_DEF_ME(loweventer) namespace { string merge(const narr& dotname) { string ret; for(auto& e : dotname) ret += e.cast<std::string>(); return ret; } } wint me::_onScan(YYSTYPE* val, YYLTYPE* loc, yyscan_t scanner) { int tok = _mode->onScan(*this, val, loc, scanner); if (_isIgnoreWhitespace && tok == NEWLINE) return SCAN_AGAIN; _isIgnoreWhitespace = false; switch(tok) { case SCAN_MODE_NORMAL: setScan<normalScan>(); return SCAN_AGAIN; case SCAN_MODE_INDENT: setScan<indentScan>(); return SCAN_AGAIN; case SCAN_MODE_INDENT_IGNORE: _isIgnoreWhitespace = true; return SCAN_AGAIN; case SCAN_MODE_END: tok = 0; // == yyterminate(); } return tok; } wint me::onScan(loweventer& ev, YYSTYPE* val, YYLTYPE* loc, yyscan_t scanner, wbool& isBypass) { int tok; do // why do you put redundant _onScan() func?: // because of definately, clang++ bug. when I use continue at switch statement inside of // do-while loop here, it doesn't work like usual 'continue' keyword does, but it does like // 'break'. tok = _onScan(val, loc, scanner); while(tok == SCAN_AGAIN); return tok; } wint me::onEndOfFile() { WRD_DI("tokenEvent: onEndOfFile() indents.size()=%d", _indents.size()); if(_indents.size() <= 1) _dispatcher.add(SCAN_MODE_END); else _dispatcher.addFront(onDedent(_indents.front(), SCAN_MODE_END)); WRD_DI("tokenEvent: onEndOfFile: finalize by adding 'NEWLINE', then dispatch end-of-file."); return NEWLINE; } wint me::onIndent(wcnt col, wint tok) { WRD_DI("tokenEvent: onIndent(col: %d, tok: %d) indents.size()=%d", col, tok, _indents.size()); _indents.push_back(col); _dispatcher.add(tok); return INDENT; } wint me::onDedent(wcnt col, wint tok) { WRD_DI("tokenEvent: onDedent(col: %d, tok: %d) indents.size()=%d", col, tok, _indents.size()); _indents.pop_back(); wint now = _indents.back(); if(now < col) onSrcWarn(errCode::WRONG_INDENT_LV, col, now, now); while(_indents.back() > col) { WRD_DI("tokenEvent: onDedent: indentlv become %d -> %d", _indents.back(), _indents[_indents.size()-2]); _indents.pop_back(); _dispatcher.add(DEDENT); } _dispatcher.add(tok); return DEDENT; } void me::onNewLine() { WRD_DI("tokenEvent: onNewLine: _isIgnoreWhitespace=%s, _indents.size()=%d", _isIgnoreWhitespace ? "true" : "false", _indents.size()); if(!_isIgnoreWhitespace && _indents.size() >= 1) _dispatcher.add(SCAN_MODE_INDENT); } wchar me::onScanUnexpected(const wchar* token) { onSrcErr(errCode::UNEXPECTED_TOK, token); return token[0]; } wint me::onIgnoreIndent(wint tok) { WRD_DI("tokenEvent: onIgnoreIndent(%d)", tok); _dispatcher.add(SCAN_MODE_INDENT_IGNORE); return tok; } void me::onEndParse() { area& area = *_srcArea; #if WRD_IS_DBG const point& pt = area.start; WRD_DI("tokenEvent: onEndParse(%d,%d)", pt.row, pt.col); #endif area.rel(); } node* me::onPack(const narr& dotname) { WRD_DI("tokenEvent: onPack(%s)", merge(dotname).c_str()); pack* pak = &getPack().get(); // pack syntax rule #1: // if there is no specified name of pack, I create an one. std::string firstName = dotname[0].cast<std::string>(); if(nul(pak)) getPack().bind(pak = new pack(manifest(firstName), packLoadings())); const std::string& realName = pak->getManifest().name; if(realName != firstName) return onErr(errCode::PACK_NOT_MATCH, firstName.c_str(), realName.c_str()), pak; // pack syntax rule #2: // middle name automatically created if not exist. // on interpreting 'mypack' pack, user may uses 'pack' keyword with dotted-name. // for instance, // 'pack mypack.component.ui' // in this scenario, mypack instance should be created before. and component sub // pack object can be created in this parsing keyword. node* e = pak; for(int n=1; n < dotname.len(); n++) { const std::string& name = dotname[n].cast<std::string>(); node* sub = &e->sub(name); if(nul(sub)) e->subs().add(name, sub = new mgdObj()); e = sub; } _subpack.bind(e); return e; } node* me::onPack() { WRD_DI("tokenEvent: onPack()"); onWarn(errCode::NO_PACK); pack* newPack = &_pack.get(); if(!_pack) _pack.bind(newPack = new pack(manifest(), packLoadings())); const std::string& name = _pack->getManifest().name; if(name != manifest::DEFAULT_NAME) return onErr(errCode::PACK_NOT_MATCH, manifest::DEFAULT_NAME, name.c_str()), newPack; _subpack.bind(newPack); // this is a default pack containing name as '{default}'. return newPack; } blockExpr* me::onBlock() { WRD_DI("tokenEvent: onBlock()"); return new blockExpr(); } blockExpr* me::onBlock(blockExpr& blk, node& stmt) { WRD_DI("tokenEvent: onBlock()"); if(nul(blk)) return onSrcErr(errCode::IS_NULL, "blk"), onBlock(); blk.getStmts().add(stmt); WRD_DI("tokenEvent: onBlock().len=%d", blk.getStmts().len()); return &blk; } scope* me::onDefBlock() { WRD_DI("tokenEvent: onDefBlock()"); return new scope(); } scope* me::onDefBlock(scope& s, node& candidate) { WRD_DI("tokenEvent: onDefBlock(candidate=%s)", candidate.getType().getName().c_str()); if(nul(s)) return onSrcErr(errCode::IS_NULL, "s"), onDefBlock(); expr* e = &candidate.cast<expr>(); if(nul(e)) return onSrcErr(errCode::PARAM_HAS_VAL, candidate.getType().getName().c_str()), onDefBlock(); defVarExpr& defVar = e->cast<defVarExpr>(); if(!nul(defVar)) { s.add(defVar.getParam().getName(), *defVar.getParam().getOrigin()); return &s; } defAssignExpr& defAssign = e->cast<defAssignExpr>(); if(!nul(defAssign)) { s.add(defAssign.getSubName(), defAssign.getRight()); return &s; } s.add(_onPopName(*e), e); return &s; } expr* me::onDefVar(const std::string& name, const node& origin) { WRD_DI("tokenEvent: onDefVar(%s, %s)", origin.getType().getName().c_str(), name.c_str()); return new defVarExpr(*new param(name, origin)); } void me::onSrcArea(area& area) { _srcArea = &area; } void me::_onRes(err* new1) { new1->log(); _report->add(new1); } params me::_convertParams(const narr& exprs) { params ret; for(auto& expr: exprs) { defVarExpr& cast = expr.cast<defVarExpr>(); if(nul(cast)) return onSrcErr(errCode::NOT_EXPR, expr.getType().getName().c_str()), ret; if(nul(cast.getParam())) return onSrcErr(errCode::PARAM_HAS_VAL), ret; ret.add(cast.getParam().clone()); } return ret; } mgdFunc* me::onFunc(const std::string& name, const narr& exprs, const node& evalObj, const blockExpr& blk) { const wtype& evalType = evalObj.getType(); WRD_DI("tokenEvent: onFunc: %s(...[%x]) %s: blk.len()=%d", name.c_str(), &exprs, evalType.getName().c_str(), blk.getStmts().len()); mgdFunc* ret = new mgdFunc(_convertParams(exprs), evalType, blk); _onPushName(name, *ret); return ret; } narr* me::onList() { narr* ret = new narr(); WRD_DI("tokenEvent: onList()=%x", ret); return ret; } narr* me::onList(node* newExpr) { narr* ret = new narr(*newExpr); WRD_DI("tokenEvent: onList(%s[%x])=%x", newExpr->getType().getName().c_str(), newExpr, ret); return ret; } narr* me::onList(narr& list, node* newExpr) { WRD_DI("tokenEvent: onList(list[%x], %s[%x])", &list, newExpr->getType().getName().c_str(), newExpr); list.add(newExpr); return &list; } void me::onCompilationUnit(node& subpack, scope& arr) { WRD_DI("tokenEvent: onCompilationUnit(%x, arr[%x])", &subpack, &arr); if(nul(subpack)) { onErr(errCode::NO_PACK_TRAY); return; } bicontainable& con = subpack.subs(); for(auto e=arr.begin(); e ;++e) con.add(e.getKey(), *e); } returnExpr* me::onReturn() { WRD_DI("tokenEvent: onReturn()"); return new returnExpr(); } returnExpr* me::onReturn(node& exp) { WRD_DI("tokenEvent: onReturn(%s)", exp.getType().getName().c_str()); return new returnExpr(exp); } node* me::onName(const std::string& name) { return new wStr(name); } narr* me::onDotName(const node& name) { narr* ret = new narr(); ret->add(name); return ret; } narr* me::onDotName(narr& names, const node& name) { names.add(name); return &names; } node* me::onGet(const std::string& name) { WRD_DI("tokenEvent: onGet(%s)", name.c_str()); return new getExpr(name); } node* me::onGet(const std::string& name, const narr& args) { WRD_DI("tokenEvent: onGet(%s, %d)", name.c_str(), args.len()); return new getExpr(name, args); } node* me::onGet(node& from, const std::string& name, const narr& args) { WRD_DI("tokenEvent: onGet(%s, %s, %d)", from.getType().getName().c_str(), name.c_str(), args.len()); return new getExpr(from, name, args); } void me::_onPushName(const std::string& name, node& n) { _nameMap[&n] = name; } std::string me::_onPopName(node& n) { std::string ret = _nameMap[&n]; _nameMap.erase(&n); return ret; } runExpr* me::onRunExpr(const std::string& name, const narr& args) { WRD_DI("tokenEvent: onRunExpr(%s, narr[%d])", name.c_str(), args.len()); return new runExpr(nulOf<node>(), name, args); } // @param from can be expr. so I need to evaluate it through 'as()'. runExpr* me::onFillFromOfFuncCall(const node& me, runExpr& to) { WRD_DI("tokenEvent: onFillFromOfFuncCall(%s, runExpr[%s])", me.getType(). getName().c_str(), to.getName().c_str()); to.setMe(me); return &to; } node* me::onAssign(node& lhs, node& rhs) { WRD_DI("tokenEvent: onAssign(%s, %s)", lhs.getType().getName().c_str(), rhs.getType().getName().c_str()); return new assignExpr(lhs, rhs); } expr* me::onDefAssign(const std::string& name, node& rhs) { WRD_DI("tokenEvent: onDefAssign(%s, %s)", name.c_str(), rhs.getType().getName().c_str()); return new defAssignExpr(name, rhs); } asExpr* me::onAs(const node& me, const node& as) { WRD_DI("tokenEvent: onAs(%s, %s)", me.getType().getName().c_str(), as.getType().getName().c_str()); return new asExpr(me, as); } addExpr* me::onAdd(const node& lhs, const node& rhs) { WRD_DI("tokenEvent: onAdd(%s, %s)", lhs.getType().getName().c_str(), rhs.getType().getName() .c_str()); return new addExpr(lhs, rhs); } me::loweventer() { rel(); } tstr<pack>& me::getPack() { return _pack; } str& me::getSubPack() { return _subpack; } // TODO: can I remove subpack variable? tstr<errReport>& me::getReport() { return _report; } tokenDispatcher& me::getDispatcher() { return _dispatcher; } std::vector<wcnt>& me::getIndents() { return _indents; } const area& me::getArea() const { static area dummy {{0, 0}, {0, 1}}; return _srcArea ? *_srcArea : dummy; } wbool me::isInit() const { return _mode; } void me::rel() { _report.bind(dummyErrReport::singletone); _pack.rel(); _nameMap.clear(); _states.clear(); _states.push_back(0); // 0 for default state prepareParse(); } void me::prepareParse() { _mode = nullptr; _subpack.rel(); _isIgnoreWhitespace = false; _dispatcher.rel(); _indents.clear(); _srcArea = nullptr; } } <|endoftext|>
<commit_before>/*! * Copyright 2015 by Contributors * \file rank.cc * \brief Definition of rank loss. * \author Tianqi Chen, Kailong Chen */ #include <dmlc/omp.h> #include <xgboost/logging.h> #include <xgboost/objective.h> #include <vector> #include <algorithm> #include <utility> #include "../common/math.h" #include "../common/random.h" namespace xgboost { namespace obj { DMLC_REGISTRY_FILE_TAG(rank_obj); struct LambdaRankParam : public dmlc::Parameter<LambdaRankParam> { int num_pairsample; float fix_list_weight; // declare parameters DMLC_DECLARE_PARAMETER(LambdaRankParam) { DMLC_DECLARE_FIELD(num_pairsample).set_lower_bound(1).set_default(1) .describe("Number of pair generated for each instance."); DMLC_DECLARE_FIELD(fix_list_weight).set_lower_bound(0.0f).set_default(0.0f) .describe("Normalize the weight of each list by this value," " if equals 0, no effect will happen"); } }; // objective for lambda rank class LambdaRankObj : public ObjFunction { public: void Configure(const std::vector<std::pair<std::string, std::string> >& args) override { param_.InitAllowUnknown(args); } void GetGradient(const std::vector<bst_float>& preds, const MetaInfo& info, int iter, std::vector<bst_gpair>* out_gpair) override { CHECK_EQ(preds.size(), info.labels.size()) << "label size predict size not match"; std::vector<bst_gpair>& gpair = *out_gpair; gpair.resize(preds.size()); // quick consistency when group is not available std::vector<unsigned> tgptr(2, 0); tgptr[1] = static_cast<unsigned>(info.labels.size()); const std::vector<unsigned> &gptr = info.group_ptr.size() == 0 ? tgptr : info.group_ptr; CHECK(gptr.size() != 0 && gptr.back() == info.labels.size()) << "group structure not consistent with #rows"; const bst_omp_uint ngroup = static_cast<bst_omp_uint>(gptr.size() - 1); #pragma omp parallel { // parall construct, declare random number generator here, so that each // thread use its own random number generator, seed by thread id and current iteration common::RandomEngine rnd(iter * 1111 + omp_get_thread_num()); std::vector<LambdaPair> pairs; std::vector<ListEntry> lst; std::vector< std::pair<bst_float, unsigned> > rec; #pragma omp for schedule(static) for (bst_omp_uint k = 0; k < ngroup; ++k) { lst.clear(); pairs.clear(); for (unsigned j = gptr[k]; j < gptr[k+1]; ++j) { lst.push_back(ListEntry(preds[j], info.labels[j], j)); gpair[j] = bst_gpair(0.0f, 0.0f); } std::sort(lst.begin(), lst.end(), ListEntry::CmpPred); rec.resize(lst.size()); for (unsigned i = 0; i < lst.size(); ++i) { rec[i] = std::make_pair(lst[i].label, i); } std::sort(rec.begin(), rec.end(), common::CmpFirst); // enumerate buckets with same label, for each item in the lst, grab another sample randomly for (unsigned i = 0; i < rec.size(); ) { unsigned j = i + 1; while (j < rec.size() && rec[j].first == rec[i].first) ++j; // bucket in [i,j), get a sample outside bucket unsigned nleft = i, nright = static_cast<unsigned>(rec.size() - j); if (nleft + nright != 0) { int nsample = param_.num_pairsample; while (nsample --) { for (unsigned pid = i; pid < j; ++pid) { unsigned ridx = std::uniform_int_distribution<unsigned>(0, nleft + nright - 1)(rnd); if (ridx < nleft) { pairs.push_back(LambdaPair(rec[ridx].second, rec[pid].second)); } else { pairs.push_back(LambdaPair(rec[pid].second, rec[ridx+j-i].second)); } } } } i = j; } // get lambda weight for the pairs this->GetLambdaWeight(lst, &pairs); // rescale each gradient and hessian so that the lst have constant weighted float scale = 1.0f / param_.num_pairsample; if (param_.fix_list_weight != 0.0f) { scale *= param_.fix_list_weight / (gptr[k + 1] - gptr[k]); } for (size_t i = 0; i < pairs.size(); ++i) { const ListEntry &pos = lst[pairs[i].pos_index]; const ListEntry &neg = lst[pairs[i].neg_index]; const bst_float w = pairs[i].weight * scale; const float eps = 1e-16f; bst_float p = common::Sigmoid(pos.pred - neg.pred); bst_float g = p - 1.0f; bst_float h = std::max(p * (1.0f - p), eps); // accumulate gradient and hessian in both pid, and nid gpair[pos.rindex].grad += g * w; gpair[pos.rindex].hess += 2.0f * w * h; gpair[neg.rindex].grad -= g * w; gpair[neg.rindex].hess += 2.0f * w * h; } } } } const char* DefaultEvalMetric(void) const override { return "map"; } protected: /*! \brief helper information in a list */ struct ListEntry { /*! \brief the predict score we in the data */ bst_float pred; /*! \brief the actual label of the entry */ bst_float label; /*! \brief row index in the data matrix */ unsigned rindex; // constructor ListEntry(bst_float pred, bst_float label, unsigned rindex) : pred(pred), label(label), rindex(rindex) {} // comparator by prediction inline static bool CmpPred(const ListEntry &a, const ListEntry &b) { return a.pred > b.pred; } // comparator by label inline static bool CmpLabel(const ListEntry &a, const ListEntry &b) { return a.label > b.label; } }; /*! \brief a pair in the lambda rank */ struct LambdaPair { /*! \brief positive index: this is a position in the list */ unsigned pos_index; /*! \brief negative index: this is a position in the list */ unsigned neg_index; /*! \brief weight to be filled in */ bst_float weight; // constructor LambdaPair(unsigned pos_index, unsigned neg_index) : pos_index(pos_index), neg_index(neg_index), weight(1.0f) {} }; /*! * \brief get lambda weight for existing pairs * \param list a list that is sorted by pred score * \param io_pairs record of pairs, containing the pairs to fill in weights */ virtual void GetLambdaWeight(const std::vector<ListEntry> &sorted_list, std::vector<LambdaPair> *io_pairs) = 0; private: LambdaRankParam param_; }; class PairwiseRankObj: public LambdaRankObj{ protected: void GetLambdaWeight(const std::vector<ListEntry> &sorted_list, std::vector<LambdaPair> *io_pairs) override {} }; // beta version: NDCG lambda rank class LambdaRankObjNDCG : public LambdaRankObj { protected: void GetLambdaWeight(const std::vector<ListEntry> &sorted_list, std::vector<LambdaPair> *io_pairs) override { std::vector<LambdaPair> &pairs = *io_pairs; float IDCG; { std::vector<bst_float> labels(sorted_list.size()); for (size_t i = 0; i < sorted_list.size(); ++i) { labels[i] = sorted_list[i].label; } std::sort(labels.begin(), labels.end(), std::greater<bst_float>()); IDCG = CalcDCG(labels); } if (IDCG == 0.0) { for (size_t i = 0; i < pairs.size(); ++i) { pairs[i].weight = 0.0f; } } else { IDCG = 1.0f / IDCG; for (size_t i = 0; i < pairs.size(); ++i) { unsigned pos_idx = pairs[i].pos_index; unsigned neg_idx = pairs[i].neg_index; float pos_loginv = 1.0f / std::log(pos_idx + 2.0f); float neg_loginv = 1.0f / std::log(neg_idx + 2.0f); int pos_label = static_cast<int>(sorted_list[pos_idx].label); int neg_label = static_cast<int>(sorted_list[neg_idx].label); bst_float original = ((1 << pos_label) - 1) * pos_loginv + ((1 << neg_label) - 1) * neg_loginv; float changed = ((1 << neg_label) - 1) * pos_loginv + ((1 << pos_label) - 1) * neg_loginv; bst_float delta = (original - changed) * IDCG; if (delta < 0.0f) delta = - delta; pairs[i].weight = delta; } } } inline static bst_float CalcDCG(const std::vector<bst_float> &labels) { double sumdcg = 0.0; for (size_t i = 0; i < labels.size(); ++i) { const unsigned rel = static_cast<unsigned>(labels[i]); if (rel != 0) { sumdcg += ((1 << rel) - 1) / std::log2(static_cast<bst_float>(i + 2)); } } return static_cast<bst_float>(sumdcg); } }; class LambdaRankObjMAP : public LambdaRankObj { protected: struct MAPStats { /*! \brief the accumulated precision */ float ap_acc; /*! * \brief the accumulated precision, * assuming a positive instance is missing */ float ap_acc_miss; /*! * \brief the accumulated precision, * assuming that one more positive instance is inserted ahead */ float ap_acc_add; /* \brief the accumulated positive instance count */ float hits; MAPStats(void) {} MAPStats(float ap_acc, float ap_acc_miss, float ap_acc_add, float hits) : ap_acc(ap_acc), ap_acc_miss(ap_acc_miss), ap_acc_add(ap_acc_add), hits(hits) {} }; /*! * \brief Obtain the delta MAP if trying to switch the positions of instances in index1 or index2 * in sorted triples * \param sorted_list the list containing entry information * \param index1,index2 the instances switched * \param map_stats a vector containing the accumulated precisions for each position in a list */ inline bst_float GetLambdaMAP(const std::vector<ListEntry> &sorted_list, int index1, int index2, std::vector<MAPStats> *p_map_stats) { std::vector<MAPStats> &map_stats = *p_map_stats; if (index1 == index2 || map_stats[map_stats.size() - 1].hits == 0) { return 0.0f; } if (index1 > index2) std::swap(index1, index2); bst_float original = map_stats[index2].ap_acc; if (index1 != 0) original -= map_stats[index1 - 1].ap_acc; bst_float changed = 0; bst_float label1 = sorted_list[index1].label > 0.0f ? 1.0f : 0.0f; bst_float label2 = sorted_list[index2].label > 0.0f ? 1.0f : 0.0f; if (label1 == label2) { return 0.0; } else if (label1 < label2) { changed += map_stats[index2 - 1].ap_acc_add - map_stats[index1].ap_acc_add; changed += (map_stats[index1].hits + 1.0f) / (index1 + 1); } else { changed += map_stats[index2 - 1].ap_acc_miss - map_stats[index1].ap_acc_miss; changed += map_stats[index2].hits / (index2 + 1); } bst_float ans = (changed - original) / (map_stats[map_stats.size() - 1].hits); if (ans < 0) ans = -ans; return ans; } /* * \brief obtain preprocessing results for calculating delta MAP * \param sorted_list the list containing entry information * \param map_stats a vector containing the accumulated precisions for each position in a list */ inline void GetMAPStats(const std::vector<ListEntry> &sorted_list, std::vector<MAPStats> *p_map_acc) { std::vector<MAPStats> &map_acc = *p_map_acc; map_acc.resize(sorted_list.size()); bst_float hit = 0, acc1 = 0, acc2 = 0, acc3 = 0; for (size_t i = 1; i <= sorted_list.size(); ++i) { if (sorted_list[i - 1].label > 0.0f) { hit++; acc1 += hit / i; acc2 += (hit - 1) / i; acc3 += (hit + 1) / i; } map_acc[i - 1] = MAPStats(acc1, acc2, acc3, hit); } } void GetLambdaWeight(const std::vector<ListEntry> &sorted_list, std::vector<LambdaPair> *io_pairs) override { std::vector<LambdaPair> &pairs = *io_pairs; std::vector<MAPStats> map_stats; GetMAPStats(sorted_list, &map_stats); for (size_t i = 0; i < pairs.size(); ++i) { pairs[i].weight = GetLambdaMAP(sorted_list, pairs[i].pos_index, pairs[i].neg_index, &map_stats); } } }; // register the objective functions DMLC_REGISTER_PARAMETER(LambdaRankParam); XGBOOST_REGISTER_OBJECTIVE(PairwieRankObj, "rank:pairwise") .describe("Pairwise rank objective.") .set_body([]() { return new PairwiseRankObj(); }); XGBOOST_REGISTER_OBJECTIVE(LambdaRankNDCG, "rank:ndcg") .describe("LambdaRank with NDCG as objective.") .set_body([]() { return new LambdaRankObjNDCG(); }); XGBOOST_REGISTER_OBJECTIVE(LambdaRankObjMAP, "rank:map") .describe("LambdaRank with MAP as objective.") .set_body([]() { return new LambdaRankObjMAP(); }); } // namespace obj } // namespace xgboost <commit_msg>Fix issue introduced from correction to log2 (#1837)<commit_after>/*! * Copyright 2015 by Contributors * \file rank.cc * \brief Definition of rank loss. * \author Tianqi Chen, Kailong Chen */ #include <dmlc/omp.h> #include <xgboost/logging.h> #include <xgboost/objective.h> #include <vector> #include <algorithm> #include <utility> #include "../common/math.h" #include "../common/random.h" namespace xgboost { namespace obj { DMLC_REGISTRY_FILE_TAG(rank_obj); struct LambdaRankParam : public dmlc::Parameter<LambdaRankParam> { int num_pairsample; float fix_list_weight; // declare parameters DMLC_DECLARE_PARAMETER(LambdaRankParam) { DMLC_DECLARE_FIELD(num_pairsample).set_lower_bound(1).set_default(1) .describe("Number of pair generated for each instance."); DMLC_DECLARE_FIELD(fix_list_weight).set_lower_bound(0.0f).set_default(0.0f) .describe("Normalize the weight of each list by this value," " if equals 0, no effect will happen"); } }; // objective for lambda rank class LambdaRankObj : public ObjFunction { public: void Configure(const std::vector<std::pair<std::string, std::string> >& args) override { param_.InitAllowUnknown(args); } void GetGradient(const std::vector<bst_float>& preds, const MetaInfo& info, int iter, std::vector<bst_gpair>* out_gpair) override { CHECK_EQ(preds.size(), info.labels.size()) << "label size predict size not match"; std::vector<bst_gpair>& gpair = *out_gpair; gpair.resize(preds.size()); // quick consistency when group is not available std::vector<unsigned> tgptr(2, 0); tgptr[1] = static_cast<unsigned>(info.labels.size()); const std::vector<unsigned> &gptr = info.group_ptr.size() == 0 ? tgptr : info.group_ptr; CHECK(gptr.size() != 0 && gptr.back() == info.labels.size()) << "group structure not consistent with #rows"; const bst_omp_uint ngroup = static_cast<bst_omp_uint>(gptr.size() - 1); #pragma omp parallel { // parall construct, declare random number generator here, so that each // thread use its own random number generator, seed by thread id and current iteration common::RandomEngine rnd(iter * 1111 + omp_get_thread_num()); std::vector<LambdaPair> pairs; std::vector<ListEntry> lst; std::vector< std::pair<bst_float, unsigned> > rec; #pragma omp for schedule(static) for (bst_omp_uint k = 0; k < ngroup; ++k) { lst.clear(); pairs.clear(); for (unsigned j = gptr[k]; j < gptr[k+1]; ++j) { lst.push_back(ListEntry(preds[j], info.labels[j], j)); gpair[j] = bst_gpair(0.0f, 0.0f); } std::sort(lst.begin(), lst.end(), ListEntry::CmpPred); rec.resize(lst.size()); for (unsigned i = 0; i < lst.size(); ++i) { rec[i] = std::make_pair(lst[i].label, i); } std::sort(rec.begin(), rec.end(), common::CmpFirst); // enumerate buckets with same label, for each item in the lst, grab another sample randomly for (unsigned i = 0; i < rec.size(); ) { unsigned j = i + 1; while (j < rec.size() && rec[j].first == rec[i].first) ++j; // bucket in [i,j), get a sample outside bucket unsigned nleft = i, nright = static_cast<unsigned>(rec.size() - j); if (nleft + nright != 0) { int nsample = param_.num_pairsample; while (nsample --) { for (unsigned pid = i; pid < j; ++pid) { unsigned ridx = std::uniform_int_distribution<unsigned>(0, nleft + nright - 1)(rnd); if (ridx < nleft) { pairs.push_back(LambdaPair(rec[ridx].second, rec[pid].second)); } else { pairs.push_back(LambdaPair(rec[pid].second, rec[ridx+j-i].second)); } } } } i = j; } // get lambda weight for the pairs this->GetLambdaWeight(lst, &pairs); // rescale each gradient and hessian so that the lst have constant weighted float scale = 1.0f / param_.num_pairsample; if (param_.fix_list_weight != 0.0f) { scale *= param_.fix_list_weight / (gptr[k + 1] - gptr[k]); } for (size_t i = 0; i < pairs.size(); ++i) { const ListEntry &pos = lst[pairs[i].pos_index]; const ListEntry &neg = lst[pairs[i].neg_index]; const bst_float w = pairs[i].weight * scale; const float eps = 1e-16f; bst_float p = common::Sigmoid(pos.pred - neg.pred); bst_float g = p - 1.0f; bst_float h = std::max(p * (1.0f - p), eps); // accumulate gradient and hessian in both pid, and nid gpair[pos.rindex].grad += g * w; gpair[pos.rindex].hess += 2.0f * w * h; gpair[neg.rindex].grad -= g * w; gpair[neg.rindex].hess += 2.0f * w * h; } } } } const char* DefaultEvalMetric(void) const override { return "map"; } protected: /*! \brief helper information in a list */ struct ListEntry { /*! \brief the predict score we in the data */ bst_float pred; /*! \brief the actual label of the entry */ bst_float label; /*! \brief row index in the data matrix */ unsigned rindex; // constructor ListEntry(bst_float pred, bst_float label, unsigned rindex) : pred(pred), label(label), rindex(rindex) {} // comparator by prediction inline static bool CmpPred(const ListEntry &a, const ListEntry &b) { return a.pred > b.pred; } // comparator by label inline static bool CmpLabel(const ListEntry &a, const ListEntry &b) { return a.label > b.label; } }; /*! \brief a pair in the lambda rank */ struct LambdaPair { /*! \brief positive index: this is a position in the list */ unsigned pos_index; /*! \brief negative index: this is a position in the list */ unsigned neg_index; /*! \brief weight to be filled in */ bst_float weight; // constructor LambdaPair(unsigned pos_index, unsigned neg_index) : pos_index(pos_index), neg_index(neg_index), weight(1.0f) {} }; /*! * \brief get lambda weight for existing pairs * \param list a list that is sorted by pred score * \param io_pairs record of pairs, containing the pairs to fill in weights */ virtual void GetLambdaWeight(const std::vector<ListEntry> &sorted_list, std::vector<LambdaPair> *io_pairs) = 0; private: LambdaRankParam param_; }; class PairwiseRankObj: public LambdaRankObj{ protected: void GetLambdaWeight(const std::vector<ListEntry> &sorted_list, std::vector<LambdaPair> *io_pairs) override {} }; // beta version: NDCG lambda rank class LambdaRankObjNDCG : public LambdaRankObj { protected: void GetLambdaWeight(const std::vector<ListEntry> &sorted_list, std::vector<LambdaPair> *io_pairs) override { std::vector<LambdaPair> &pairs = *io_pairs; float IDCG; { std::vector<bst_float> labels(sorted_list.size()); for (size_t i = 0; i < sorted_list.size(); ++i) { labels[i] = sorted_list[i].label; } std::sort(labels.begin(), labels.end(), std::greater<bst_float>()); IDCG = CalcDCG(labels); } if (IDCG == 0.0) { for (size_t i = 0; i < pairs.size(); ++i) { pairs[i].weight = 0.0f; } } else { IDCG = 1.0f / IDCG; for (size_t i = 0; i < pairs.size(); ++i) { unsigned pos_idx = pairs[i].pos_index; unsigned neg_idx = pairs[i].neg_index; float pos_loginv = 1.0f / std::log2(pos_idx + 2.0f); float neg_loginv = 1.0f / std::log2(neg_idx + 2.0f); int pos_label = static_cast<int>(sorted_list[pos_idx].label); int neg_label = static_cast<int>(sorted_list[neg_idx].label); bst_float original = ((1 << pos_label) - 1) * pos_loginv + ((1 << neg_label) - 1) * neg_loginv; float changed = ((1 << neg_label) - 1) * pos_loginv + ((1 << pos_label) - 1) * neg_loginv; bst_float delta = (original - changed) * IDCG; if (delta < 0.0f) delta = - delta; pairs[i].weight = delta; } } } inline static bst_float CalcDCG(const std::vector<bst_float> &labels) { double sumdcg = 0.0; for (size_t i = 0; i < labels.size(); ++i) { const unsigned rel = static_cast<unsigned>(labels[i]); if (rel != 0) { sumdcg += ((1 << rel) - 1) / std::log2(static_cast<bst_float>(i + 2)); } } return static_cast<bst_float>(sumdcg); } }; class LambdaRankObjMAP : public LambdaRankObj { protected: struct MAPStats { /*! \brief the accumulated precision */ float ap_acc; /*! * \brief the accumulated precision, * assuming a positive instance is missing */ float ap_acc_miss; /*! * \brief the accumulated precision, * assuming that one more positive instance is inserted ahead */ float ap_acc_add; /* \brief the accumulated positive instance count */ float hits; MAPStats(void) {} MAPStats(float ap_acc, float ap_acc_miss, float ap_acc_add, float hits) : ap_acc(ap_acc), ap_acc_miss(ap_acc_miss), ap_acc_add(ap_acc_add), hits(hits) {} }; /*! * \brief Obtain the delta MAP if trying to switch the positions of instances in index1 or index2 * in sorted triples * \param sorted_list the list containing entry information * \param index1,index2 the instances switched * \param map_stats a vector containing the accumulated precisions for each position in a list */ inline bst_float GetLambdaMAP(const std::vector<ListEntry> &sorted_list, int index1, int index2, std::vector<MAPStats> *p_map_stats) { std::vector<MAPStats> &map_stats = *p_map_stats; if (index1 == index2 || map_stats[map_stats.size() - 1].hits == 0) { return 0.0f; } if (index1 > index2) std::swap(index1, index2); bst_float original = map_stats[index2].ap_acc; if (index1 != 0) original -= map_stats[index1 - 1].ap_acc; bst_float changed = 0; bst_float label1 = sorted_list[index1].label > 0.0f ? 1.0f : 0.0f; bst_float label2 = sorted_list[index2].label > 0.0f ? 1.0f : 0.0f; if (label1 == label2) { return 0.0; } else if (label1 < label2) { changed += map_stats[index2 - 1].ap_acc_add - map_stats[index1].ap_acc_add; changed += (map_stats[index1].hits + 1.0f) / (index1 + 1); } else { changed += map_stats[index2 - 1].ap_acc_miss - map_stats[index1].ap_acc_miss; changed += map_stats[index2].hits / (index2 + 1); } bst_float ans = (changed - original) / (map_stats[map_stats.size() - 1].hits); if (ans < 0) ans = -ans; return ans; } /* * \brief obtain preprocessing results for calculating delta MAP * \param sorted_list the list containing entry information * \param map_stats a vector containing the accumulated precisions for each position in a list */ inline void GetMAPStats(const std::vector<ListEntry> &sorted_list, std::vector<MAPStats> *p_map_acc) { std::vector<MAPStats> &map_acc = *p_map_acc; map_acc.resize(sorted_list.size()); bst_float hit = 0, acc1 = 0, acc2 = 0, acc3 = 0; for (size_t i = 1; i <= sorted_list.size(); ++i) { if (sorted_list[i - 1].label > 0.0f) { hit++; acc1 += hit / i; acc2 += (hit - 1) / i; acc3 += (hit + 1) / i; } map_acc[i - 1] = MAPStats(acc1, acc2, acc3, hit); } } void GetLambdaWeight(const std::vector<ListEntry> &sorted_list, std::vector<LambdaPair> *io_pairs) override { std::vector<LambdaPair> &pairs = *io_pairs; std::vector<MAPStats> map_stats; GetMAPStats(sorted_list, &map_stats); for (size_t i = 0; i < pairs.size(); ++i) { pairs[i].weight = GetLambdaMAP(sorted_list, pairs[i].pos_index, pairs[i].neg_index, &map_stats); } } }; // register the objective functions DMLC_REGISTER_PARAMETER(LambdaRankParam); XGBOOST_REGISTER_OBJECTIVE(PairwieRankObj, "rank:pairwise") .describe("Pairwise rank objective.") .set_body([]() { return new PairwiseRankObj(); }); XGBOOST_REGISTER_OBJECTIVE(LambdaRankNDCG, "rank:ndcg") .describe("LambdaRank with NDCG as objective.") .set_body([]() { return new LambdaRankObjNDCG(); }); XGBOOST_REGISTER_OBJECTIVE(LambdaRankObjMAP, "rank:map") .describe("LambdaRank with MAP as objective.") .set_body([]() { return new LambdaRankObjMAP(); }); } // namespace obj } // namespace xgboost <|endoftext|>
<commit_before>// Copyright (c) 2012 Plenluno All rights reserved. #include "libj/js_object.h" #include "libj/detail/js_object.h" namespace libj { JsObject::Ptr JsObject::create() { return Ptr(new detail::JsObject<JsObject>()); } } // namespace libj <commit_msg>replace "" with <><commit_after>// Copyright (c) 2012 Plenluno All rights reserved. #include <libj/js_object.h> #include <libj/detail/js_object.h> namespace libj { JsObject::Ptr JsObject::create() { return Ptr(new detail::JsObject<JsObject>()); } } // namespace libj <|endoftext|>
<commit_before>// Copyright 2009, Squish Tech, LLC. #include "libxmljs.h" #include "xml_syntax_error.h" #include "xml_document.h" #include "xml_node.h" #include "xml_parser.h" #include "html_parser.h" namespace libxmljs { v8::Persistent<v8::FunctionTemplate> memory_usage; namespace { void on_libxml_destruct(xmlNode* node) { } } // namespace LibXMLJS::LibXMLJS() { xmlInitParser(); // Not always necessary, but necessary for thread safety. // xmlRegisterNodeDefault(on_libxml_construct); xmlDeregisterNodeDefault(on_libxml_destruct); // xmlThrDefRegisterNodeDefault(on_libxml_construct); xmlThrDefDeregisterNodeDefault(on_libxml_destruct); } LibXMLJS::~LibXMLJS() { xmlCleanupParser(); // As per xmlInitParser(), or memory leak will happen. } LibXMLJS LibXMLJS::init_; static void OnFatalError(const char* location, const char* message) { #define FATAL_ERROR "\033[1;31mV8 FATAL ERROR.\033[m" if (location) fprintf(stderr, FATAL_ERROR " %s %s\n", location, message); else fprintf(stderr, FATAL_ERROR " %s\n", message); exit(1); } // Extracts a C str from a V8 Utf8Value. // TODO: Fix this error state, maybe throw exception? const char * ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<str conversion failed>"; } static void ReportException(v8::TryCatch* try_catch) { v8::Handle<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { fprintf(stderr, "Error: (no message)\n"); fflush(stderr); return; } v8::Handle<v8::Value> error = try_catch->Exception(); v8::Handle<v8::String> stack; if (error->IsObject()) { v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(error); v8::Handle<v8::Value> raw_stack = obj->Get(v8::String::New("stack")); if (raw_stack->IsString()) stack = v8::Handle<v8::String>::Cast(raw_stack); } if (stack.IsEmpty()) { v8::String::Utf8Value exception(error); // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, *exception); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); fprintf(stderr, "%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { fprintf(stderr, " "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { fprintf(stderr, "^"); } fprintf(stderr, "\n"); message->PrintCurrentStackTrace(stderr); } else { v8::String::Utf8Value trace(stack); fprintf(stderr, "%s\n", *trace); } fflush(stderr); } // Executes a str within the current v8 context. v8::Handle<v8::Value> ExecuteString(v8::Handle<v8::String> source, v8::Handle<v8::Value> filename) { v8::HandleScope scope; v8::TryCatch try_catch; v8::Handle<v8::Script> script = v8::Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(&try_catch); exit(1); } v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&try_catch); exit(1); } return scope.Close(result); } static void ExecuteNativeJS(const char* filename, const char* data) { v8::HandleScope scope; v8::TryCatch try_catch; ExecuteString(v8::String::New(data), v8::String::New(filename)); if (try_catch.HasCaught()) { puts("There is an error in Node's built-in javascript"); puts("This should be reported as a bug!"); ReportException(&try_catch); exit(1); } } void UpdateV8Memory() { v8::V8::AdjustAmountOfExternalAllocatedMemory(-current_xml_memory); current_xml_memory = xmlMemUsed(); v8::V8::AdjustAmountOfExternalAllocatedMemory(current_xml_memory); } v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) { v8::HandleScope scope; v8::Local<v8::Object> obj = v8::Object::New(); long c = xmlMemUsed(); obj->Set(v8::String::New("libxml"), v8::Integer::New(c)); obj->Set(v8::String::New("v8"), v8::Integer::New(current_xml_memory)); return scope.Close(obj); } void InitializeLibXMLJS(v8::Handle<v8::Object> target) { v8::HandleScope scope; xmlMemSetup(xmlMemFree, xmlMemMalloc, xmlMemRealloc, xmlMemoryStrdup); xmlInitMemory(); XmlSyntaxError::Initialize(target); XmlDocument::Initialize(target); XmlParser::Initialize(target); HtmlParser::Initialize(target); target->Set(v8::String::NewSymbol("version"), v8::String::New(LIBXMLJS_VERSION)); target->Set(v8::String::NewSymbol("libxml_version"), v8::String::New(LIBXML_DOTTED_VERSION)); target->Set(v8::String::NewSymbol("libxml_parser_version"), v8::String::New(xmlParserVersion)); target->Set(v8::String::NewSymbol("libxml_debug_enabled"), v8::Boolean::New(debugging)); v8::Local<v8::FunctionTemplate> func = v8::FunctionTemplate::New(MemoryUsage); memory_usage = v8::Persistent<v8::FunctionTemplate>::New(func); memory_usage->InstanceTemplate()->SetInternalFieldCount(1); target->Set(v8::String::NewSymbol("memoryUsage"), memory_usage->GetFunction()); v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); context->Global()->Set(v8::String::NewSymbol("libxml"), target); ExecuteNativeJS("xml_sax_parser.js", native_xml_sax_parser); ExecuteNativeJS("xml_document.js", native_xml_document); ExecuteNativeJS("xml_element.js", native_xml_element); } // used by node.js to initialize libraries extern "C" void init(v8::Handle<v8::Object> target) { v8::HandleScope scope; InitializeLibXMLJS(target); } int main(int argc, char* argv[]) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::V8::Initialize(); v8::V8::SetFatalErrorHandler(OnFatalError); // Create a stack-allocated handle scope. v8::HandleScope handle_scope; // Create a new context. v8::Handle<v8::Context> context = v8::Context::New(); // Enter the created context for compiling and // running the hello world script. v8::Context::Scope context_scope(context); v8::Local<v8::Object> global_obj = v8::Context::GetCurrent()->Global(); v8::Local<v8::Object> libxml_obj = v8::Object::New(); InitializeLibXMLJS(libxml_obj); global_obj->Set(v8::String::NewSymbol("libxml"), libxml_obj); // for (int i = 1; i < argc; i++) { // // Create a string containing the JavaScript source code. // Handle<String> source = ReadFile(argv[i]); // // Compile the source code. // Handle<Script> script = Script::Compile(source); // // Run the script to get the result. // Handle<Value> result = script->Run(); // } v8::V8::Dispose(); return 0; } } // namespace libxmljs <commit_msg>Call xmlMemSetup in static constructor to track memory from xmlInitParser<commit_after>// Copyright 2009, Squish Tech, LLC. #include "libxmljs.h" #include "xml_syntax_error.h" #include "xml_document.h" #include "xml_node.h" #include "xml_parser.h" #include "html_parser.h" namespace libxmljs { v8::Persistent<v8::FunctionTemplate> memory_usage; namespace { void on_libxml_destruct(xmlNode* node) { } } // namespace LibXMLJS::LibXMLJS() { xmlMemSetup(xmlMemFree, xmlMemMalloc, xmlMemRealloc, xmlMemoryStrdup); xmlInitParser(); // Not always necessary, but necessary for thread safety. // xmlRegisterNodeDefault(on_libxml_construct); xmlDeregisterNodeDefault(on_libxml_destruct); // xmlThrDefRegisterNodeDefault(on_libxml_construct); xmlThrDefDeregisterNodeDefault(on_libxml_destruct); } LibXMLJS::~LibXMLJS() { xmlCleanupParser(); // As per xmlInitParser(), or memory leak will happen. } LibXMLJS LibXMLJS::init_; static void OnFatalError(const char* location, const char* message) { #define FATAL_ERROR "\033[1;31mV8 FATAL ERROR.\033[m" if (location) fprintf(stderr, FATAL_ERROR " %s %s\n", location, message); else fprintf(stderr, FATAL_ERROR " %s\n", message); exit(1); } // Extracts a C str from a V8 Utf8Value. // TODO: Fix this error state, maybe throw exception? const char * ToCString(const v8::String::Utf8Value& value) { return *value ? *value : "<str conversion failed>"; } static void ReportException(v8::TryCatch* try_catch) { v8::Handle<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { fprintf(stderr, "Error: (no message)\n"); fflush(stderr); return; } v8::Handle<v8::Value> error = try_catch->Exception(); v8::Handle<v8::String> stack; if (error->IsObject()) { v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(error); v8::Handle<v8::Value> raw_stack = obj->Get(v8::String::New("stack")); if (raw_stack->IsString()) stack = v8::Handle<v8::String>::Cast(raw_stack); } if (stack.IsEmpty()) { v8::String::Utf8Value exception(error); // Print (filename):(line number): (message). v8::String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, *exception); // Print line of source code. v8::String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); fprintf(stderr, "%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { fprintf(stderr, " "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { fprintf(stderr, "^"); } fprintf(stderr, "\n"); message->PrintCurrentStackTrace(stderr); } else { v8::String::Utf8Value trace(stack); fprintf(stderr, "%s\n", *trace); } fflush(stderr); } // Executes a str within the current v8 context. v8::Handle<v8::Value> ExecuteString(v8::Handle<v8::String> source, v8::Handle<v8::Value> filename) { v8::HandleScope scope; v8::TryCatch try_catch; v8::Handle<v8::Script> script = v8::Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(&try_catch); exit(1); } v8::Handle<v8::Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&try_catch); exit(1); } return scope.Close(result); } static void ExecuteNativeJS(const char* filename, const char* data) { v8::HandleScope scope; v8::TryCatch try_catch; ExecuteString(v8::String::New(data), v8::String::New(filename)); if (try_catch.HasCaught()) { puts("There is an error in Node's built-in javascript"); puts("This should be reported as a bug!"); ReportException(&try_catch); exit(1); } } void UpdateV8Memory() { v8::V8::AdjustAmountOfExternalAllocatedMemory(-current_xml_memory); current_xml_memory = xmlMemUsed(); v8::V8::AdjustAmountOfExternalAllocatedMemory(current_xml_memory); } v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) { v8::HandleScope scope; v8::Local<v8::Object> obj = v8::Object::New(); long c = xmlMemUsed(); obj->Set(v8::String::New("libxml"), v8::Integer::New(c)); obj->Set(v8::String::New("v8"), v8::Integer::New(current_xml_memory)); return scope.Close(obj); } void InitializeLibXMLJS(v8::Handle<v8::Object> target) { v8::HandleScope scope; XmlSyntaxError::Initialize(target); XmlDocument::Initialize(target); XmlParser::Initialize(target); HtmlParser::Initialize(target); target->Set(v8::String::NewSymbol("version"), v8::String::New(LIBXMLJS_VERSION)); target->Set(v8::String::NewSymbol("libxml_version"), v8::String::New(LIBXML_DOTTED_VERSION)); target->Set(v8::String::NewSymbol("libxml_parser_version"), v8::String::New(xmlParserVersion)); target->Set(v8::String::NewSymbol("libxml_debug_enabled"), v8::Boolean::New(debugging)); v8::Local<v8::FunctionTemplate> func = v8::FunctionTemplate::New(MemoryUsage); memory_usage = v8::Persistent<v8::FunctionTemplate>::New(func); memory_usage->InstanceTemplate()->SetInternalFieldCount(1); target->Set(v8::String::NewSymbol("memoryUsage"), memory_usage->GetFunction()); v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); v8::Handle<v8::Context> context = v8::Context::New(NULL, global); v8::Context::Scope context_scope(context); context->Global()->Set(v8::String::NewSymbol("libxml"), target); ExecuteNativeJS("xml_sax_parser.js", native_xml_sax_parser); ExecuteNativeJS("xml_document.js", native_xml_document); ExecuteNativeJS("xml_element.js", native_xml_element); } // used by node.js to initialize libraries extern "C" void init(v8::Handle<v8::Object> target) { v8::HandleScope scope; InitializeLibXMLJS(target); } int main(int argc, char* argv[]) { v8::V8::SetFlagsFromCommandLine(&argc, argv, true); v8::V8::Initialize(); v8::V8::SetFatalErrorHandler(OnFatalError); // Create a stack-allocated handle scope. v8::HandleScope handle_scope; // Create a new context. v8::Handle<v8::Context> context = v8::Context::New(); // Enter the created context for compiling and // running the hello world script. v8::Context::Scope context_scope(context); v8::Local<v8::Object> global_obj = v8::Context::GetCurrent()->Global(); v8::Local<v8::Object> libxml_obj = v8::Object::New(); InitializeLibXMLJS(libxml_obj); global_obj->Set(v8::String::NewSymbol("libxml"), libxml_obj); // for (int i = 1; i < argc; i++) { // // Create a string containing the JavaScript source code. // Handle<String> source = ReadFile(argv[i]); // // Compile the source code. // Handle<Script> script = Script::Compile(source); // // Run the script to get the result. // Handle<Value> result = script->Run(); // } v8::V8::Dispose(); return 0; } } // namespace libxmljs <|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <climits> #include <algorithm> #include <vector> #include <mpi.h> using namespace std; #define MAXN 100 #define MAXM 10000 int p,rank; int n,m; struct edge{ int u,v,w; bool operator < (edge e) const{ return w < e.w; } }e[MAXM]; bool in_tree[MAXM]; // Union - Find int parent[MAXN + 1]; int Find(int x){ if(parent[x] == x) return x; parent[x] = Find(parent[x]); return parent[x]; } void Union(int x, int y){ x = Find(x); y = Find(y); parent[x] = y; } // dfs to find a path between two nodes in the MST vector<int> L[MAXN],edge_id[MAXN],path,path_edges; bool visited[MAXN]; bool dfs(int u, int v){ path.push_back(u); if(u == v) return true; bool ret = false; if(!visited[u]){ visited[u] = true; for(int i = 0;i < L[u].size();++i){ int to = L[u][i]; path_edges.push_back(edge_id[u][i]); if(dfs(to,v)){ ret = true; break; }else{ path_edges.pop_back(); } } } if(!ret) path.pop_back(); return ret; } // dfs to mark edges in a subtree after erasing an edge int mark[MAXN]; void dfs2(int u, int v, int cur){ if(visited[cur]) return; visited[cur] = true; mark[cur] = u; for(int i = 0;i < L[cur].size();++i){ int to = L[cur][i]; if(to != u && to != v) dfs2(u,v,to); } } // dfs to root the tree int in[MAXN],out[MAXN],cont; int parent_lca[10][MAXN],maxw[10][MAXN]; int height[MAXN]; void dfs3(int cur, int p, int e_id){ in[cur] = cont++; parent_lca[0][cur] = p; maxw[0][cur] = e[e_id].w; height[cur] = (p == 0? 0 : 1 + height[p]); for(int i = 1;i <= 9;++i){ parent_lca[i][cur] = parent_lca[i - 1][ parent_lca[i - 1][cur] ]; maxw[i][cur] = max(maxw[i - 1][cur],maxw[i - 1][ parent_lca[i - 1][cur ]]); } for(int i = (int)L[cur].size() - 1;i >= 0;--i){ int to = L[cur][i]; if(to != p) dfs3(to,cur,edge_id[cur][i]); } out[cur] = cont - 1; } // lowest common ancestor int lca(int u, int v){ if(height[u] < height[v]) swap(u,v); for(int i = 9;i >= 0;--i) if((height[u] - height[v]) >> i & 1) u = parent_lca[i][u]; if(u == v) return u; for(int i = 9;i >= 0;--i) if(parent_lca[i][u] != parent_lca[i][v]){ u = parent_lca[i][u]; v = parent_lca[i][v]; } return parent_lca[0][u]; } int max_weight(int u, int up){ int ret = 0; for(int i = 9;i >= 0;--i){ if(height[u] >> i & 1){ ret = max(ret,maxw[i][u]); u = parent_lca[i][u]; } } return ret; } // segment tree to calculate minimum in a range and update int T[4 * MAXN]; void init(int node, int l, int r){ T[node] = INT_MAX; if(l != r){ int mi = (l + r) >> 1; init(2 * node + 1,l,mi); init(2 * node + 2,mi + 1,r); } } int query(int node, int l, int r, int x, int y){ if(r < x || l > y) return INT_MAX; if(x <= l && r <= y) return T[node]; int mi = (l + r) >> 1; return min(query(2 * node + 1,l,mi,x,y),query(2 * node + 2,mi + 1,r,x,y)); } void update(int node, int l, int r, int x, int val){ if(l == r) T[node] = min(T[node],val); else{ int mi = (l + r) >> 1; if(x <= mi) update(2 * node + 1,l,mi,x,val); else update(2 * node + 2,mi + 1,r,x,val); T[node] = min(T[2 * node + 1],T[2 * node + 2]); } } // dfs for the sensitivity analysis of tree edges int k[MAXN],sensitivity[MAXM]; vector<int> L2[MAXN],W2[MAXN]; void dfs4(int cur, int p, int e_id){ if(p != 0){ sensitivity[e_id] = query(0,0,n - 1,in[cur],out[cur]) - e[e_id].w; } // decrease keys for(int i = (int)L2[cur].size() - 1;i >= 0;--i){ update(0,0,n - 1,in[ L2[cur][i] ],W2[cur][i]); } for(int i = (int)L[cur].size() - 1;i >= 0;--i){ int to = L[cur][i]; if(to != p) dfs4(to,cur,edge_id[cur][i]); } } int main(int argc, char *argv[]){ MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&p); MPI_Comm_rank(MPI_COMM_WORLD,&rank); if(rank == 0){ n = m = 0; while(scanf("%d,%d,%d",&e[m].u,&e[m].v,&e[m].w) == 3){ n = max(n,max(e[m].u,e[m].v)); ++m; } // Find minimum spanning tree using Kruskal's algorithm for(int i = 1;i <= n;++i) parent[i] = i; sort(e,e + m); int total = 0; for(int i = 0;i < m;++i){ if(Find(e[i].u) != Find(e[i].v)){ Union(e[i].u,e[i].v); total += e[i].w; in_tree[i] = true; L[ e[i].u ].push_back(e[i].v); edge_id[ e[i].u ].push_back(i); L[ e[i].v ].push_back(e[i].u); edge_id[ e[i].v ].push_back(i); //printf("%d - %d (%d)\n",e[i].u,e[i].v,e[i].w); }else in_tree[i] = false; } //printf("Total weight = %d\n\n",total); } MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD); MPI_Bcast(&m,1,MPI_INT,0,MPI_COMM_WORLD); for(int i = 1;i <= n;++i){ int list_size; if(rank == 0) list_size = L[i].size(); MPI_Bcast(&list_size,1,MPI_INT,0,MPI_COMM_WORLD); L[i].resize(list_size); MPI_Bcast(&L[i].front(),list_size,MPI_INT,0,MPI_COMM_WORLD); edge_id[i].resize(list_size); MPI_Bcast(&edge_id[i].front(),list_size,MPI_INT,0,MPI_COMM_WORLD); } MPI_Bcast(in_tree,m,MPI_C_BOOL,0,MPI_COMM_WORLD); int blocklengths[] = {1,1,1}; MPI_Aint displacements[] = {offsetof(edge,u), offsetof(edge,v), offsetof(edge,w)}; MPI_Datatype types[] = {MPI_INT, MPI_INT, MPI_INT}; MPI_Datatype MPI_EDGE; MPI_Type_create_struct(3,blocklengths,displacements,types,&MPI_EDGE); MPI_Type_commit(&MPI_EDGE); MPI_Bcast(e,m,MPI_EDGE,0,MPI_COMM_WORLD); // Find the path int T that connect two endpoint of an edge bool verified_local = true; for(int i = (m + p - 1) / p * rank;i < min(m,(m + p - 1) / p * (rank + 1));++i){ if(!in_tree[i]){ memset(visited,false,sizeof visited); path.clear(); dfs(e[i].u,e[i].v); printf("process %d, (%d, %d) : ",rank,e[i].u,e[i].v); for(int j = 0;j < path.size();++j){ if(j > 0) printf(" -> "); printf("%d",path[j]); } printf("\n"); // Verify MST for(int j = 0;j < path_edges.size();++j){ if(e[i].w < e[ path_edges[j] ].w) verified_local = false; } } } printf("\n"); bool verified_global; MPI_Reduce(&verified_local,&verified_global,1,MPI_C_BOOL,MPI_LAND,0,MPI_COMM_WORLD); if(rank == 0){ printf("Verification: "); if(verified_global) printf("It is an MST\n\n"); else printf("It is not an MST\n\n"); } // Find edges that can replace an edge in the MST int most_vital_edge_local[p]; int max_increase_local[p]; most_vital_edge_local[rank] = -1; max_increase_local[rank] = -1; for(int i = (m + p - 1) / p * rank;i < min(m,(m + p - 1) / p * (rank + 1));++i){ if(in_tree[i]){ memset(visited,false,sizeof visited); dfs2(e[i].u,e[i].v,e[i].u); dfs2(e[i].v,e[i].u,e[i].v); printf("process %d, (%d, %d) :",rank,e[i].u,e[i].v); int rep = -1; for(int j = 0;j < m;++j) if(j != i && ((mark[ e[j].u ] == e[i].u && mark[ e[j].v ] == e[i].v) || (mark[ e[j].v ] == e[i].u && mark[ e[j].u ] == e[i].v))){ printf(" (%d, %d)",e[j].u,e[j].v); if(rep == -1 || e[j].w < e[rep].w) rep = j; } printf(", replacement : (%d, %d)\n",e[rep].u,e[rep].v); if(e[rep].w - e[i].w > max_increase_local[rank]){ max_increase_local[rank] = e[rep].w - e[i].w; most_vital_edge_local[rank] = i; } } } if(rank != 0){ MPI_Send(&max_increase_local[rank],1,MPI_INT,0,0,MPI_COMM_WORLD); MPI_Send(&most_vital_edge_local[rank],1,MPI_INT,0,1,MPI_COMM_WORLD); }else{ int most_vital_edge = most_vital_edge_local[0],max_increase = max_increase_local[0]; MPI_Status status; for(int i = 1;i < p;++i){ MPI_Recv(&max_increase_local[i],1,MPI_INT,i,0,MPI_COMM_WORLD,&status); MPI_Recv(&most_vital_edge_local[i],1,MPI_INT,i,1,MPI_COMM_WORLD,&status); if(max_increase_local[i] > max_increase){ max_increase = max_increase_local[i]; most_vital_edge = most_vital_edge_local[i]; } } printf("\n"); printf("Most vital edge = (%d, %d)\n",e[most_vital_edge].u,e[most_vital_edge].v); printf("Increase = %d\n",max_increase); } MPI_Finalize(); return 0; }<commit_msg>parallel kruskal<commit_after>#include <cstdio> #include <cstring> #include <climits> #include <algorithm> #include <vector> #include <mpi.h> using namespace std; #define MAXN 100 #define MAXM 10000 int p,rank; int n,m; struct edge{ int u,v,w; int id; bool operator < (edge e) const{ return w < e.w; } }e[MAXM],e_local[MAXM]; bool in_tree[MAXM]; // Union - Find int parent[MAXN + 1],uf_rank[MAXN + 1]; int Find(int x){ if(parent[x] == x) return x; parent[x] = Find(parent[x]); return parent[x]; } void Union(int x, int y){ x = Find(x); y = Find(y); if(uf_rank[x] < uf_rank[y]){ parent[x] = y; }else{ parent[y] = x; if(uf_rank[x] == uf_rank[y]) ++uf_rank[x]; } } // dfs to find a path between two nodes in the MST vector<int> L[MAXN],edge_id[MAXN],path,path_edges; bool visited[MAXN]; bool dfs(int u, int v){ path.push_back(u); if(u == v) return true; bool ret = false; if(!visited[u]){ visited[u] = true; for(int i = 0;i < L[u].size();++i){ int to = L[u][i]; path_edges.push_back(edge_id[u][i]); if(dfs(to,v)){ ret = true; break; }else{ path_edges.pop_back(); } } } if(!ret) path.pop_back(); return ret; } // dfs to mark edges in a subtree after erasing an edge int mark[MAXN]; void dfs2(int u, int v, int cur){ if(visited[cur]) return; visited[cur] = true; mark[cur] = u; for(int i = 0;i < L[cur].size();++i){ int to = L[cur][i]; if(to != u && to != v) dfs2(u,v,to); } } int main(int argc, char *argv[]){ MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&p); MPI_Comm_rank(MPI_COMM_WORLD,&rank); if(rank == 0){ n = m = 0; while(scanf("%d,%d,%d",&e[m].u,&e[m].v,&e[m].w) == 3){ n = max(n,max(e[m].u,e[m].v)); e[m].id = m; ++m; } } MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD); MPI_Bcast(&m,1,MPI_INT,0,MPI_COMM_WORLD); int blocklengths[] = {1,1,1,1}; MPI_Aint displacements[] = {offsetof(edge,u), offsetof(edge,v), offsetof(edge,w), offsetof(edge,id)}; MPI_Datatype types[] = {MPI_INT, MPI_INT, MPI_INT, MPI_INT}; MPI_Datatype MPI_EDGE; MPI_Type_create_struct(4,blocklengths,displacements,types,&MPI_EDGE); MPI_Type_commit(&MPI_EDGE); MPI_Bcast(e,m,MPI_EDGE,0,MPI_COMM_WORLD); // Find minimum spanning tree using Kruskal's algorithm for(int i = 1;i <= n;++i){ parent[i] = i; uf_rank[i] = 0; } int start = (m + p - 1) / p * rank,end = min(m,(m + p - 1) / p * (rank + 1)); int m_local = 0; for(int i = start;i < end;++i) e_local[i - start] = e[i]; sort(e_local,e_local + (end - start)); for(int i = 0;i < end - start;++i){ if(Find(e_local[i].u) != Find(e_local[i].v)){ Union(e_local[i].u,e_local[i].v); e_local[m_local] = e_local[i]; m_local++; } } int curP = p; while(curP > 1){ if(rank < curP){ //printf("%d %d\n",rank,curP); int m1 = 0,m2 = 0; MPI_Status status; //printf("%d %d send\n",rank,curP); MPI_Send(&m_local,1,MPI_INT,rank / 2,0,MPI_COMM_WORLD); //printf("%d %d send\n",rank,curP); MPI_Send(e_local,m_local,MPI_EDGE,rank / 2,1,MPI_COMM_WORLD); //printf("%d %d send\n",rank,curP); if(2 * rank < curP){ //printf("%d %d receive\n",rank,curP); MPI_Recv(&m1,1,MPI_INT,2 * rank,0,MPI_COMM_WORLD,&status); //printf("%d %d receive\n",rank,curP); MPI_Recv(e_local,m1,MPI_EDGE,2 * rank,1,MPI_COMM_WORLD,&status); //printf("%d %d receive\n",rank,curP); if(2 * rank + 1 < curP){ //printf("%d %d receive\n",rank,curP); MPI_Recv(&m2,1,MPI_INT,2 * rank + 1,0,MPI_COMM_WORLD,&status); //printf("%d %d receive\n",rank,curP); MPI_Recv(e_local + m1,m2,MPI_EDGE,2 * rank + 1,1,MPI_COMM_WORLD,&status); //printf("%d %d receive\n",rank,curP); } int m_aux = m1 + m2; sort(e_local,e_local + m_aux); for(int i = 1;i <= n;++i){ parent[i] = i; uf_rank[i] = 0; } m_local = 0; for(int i = 0;i < m_aux;++i){ if(Find(e_local[i].u) != Find(e_local[i].v)){ Union(e_local[i].u,e_local[i].v); e_local[m_local] = e_local[i]; m_local++; } } } } curP = (curP + 1) / 2; } if(rank == 0){ int total = 0; for(int i = 0;i < m_local;++i){ L[ e_local[i].u ].push_back(e_local[i].v); edge_id[ e_local[i].u ].push_back(e_local[i].id); L[ e_local[i].v ].push_back(e_local[i].u); edge_id[ e_local[i].v ].push_back(e_local[i].id); in_tree[ e_local[i].id ] = true; printf("%d - %d (%d)\n",e_local[i].u,e_local[i].v,e_local[i].w); total += e_local[i].w; } printf("Total weight = %d\n\n",total); } for(int i = 1;i <= n;++i){ int list_size; if(rank == 0) list_size = L[i].size(); MPI_Bcast(&list_size,1,MPI_INT,0,MPI_COMM_WORLD); L[i].resize(list_size); MPI_Bcast(&L[i].front(),list_size,MPI_INT,0,MPI_COMM_WORLD); edge_id[i].resize(list_size); MPI_Bcast(&edge_id[i].front(),list_size,MPI_INT,0,MPI_COMM_WORLD); } MPI_Bcast(in_tree,m,MPI_C_BOOL,0,MPI_COMM_WORLD); // Find the path int T that connect two endpoint of an edge bool verified_local = true; for(int i = (m + p - 1) / p * rank;i < min(m,(m + p - 1) / p * (rank + 1));++i){ if(!in_tree[i]){ memset(visited,false,sizeof visited); path.clear(); dfs(e[i].u,e[i].v); printf("process %d, (%d, %d) : ",rank,e[i].u,e[i].v); for(int j = 0;j < path.size();++j){ if(j > 0) printf(" -> "); printf("%d",path[j]); } printf("\n"); // Verify MST for(int j = 0;j < path_edges.size();++j){ if(e[i].w < e[ path_edges[j] ].w) verified_local = false; } } } printf("\n"); bool verified_global; MPI_Reduce(&verified_local,&verified_global,1,MPI_C_BOOL,MPI_LAND,0,MPI_COMM_WORLD); if(rank == 0){ printf("Verification: "); if(verified_global) printf("It is an MST\n\n"); else printf("It is not an MST\n\n"); } // Find edges that can replace an edge in the MST int most_vital_edge_local[p]; int max_increase_local[p]; most_vital_edge_local[rank] = -1; max_increase_local[rank] = -1; for(int i = (m + p - 1) / p * rank;i < min(m,(m + p - 1) / p * (rank + 1));++i){ if(in_tree[i]){ memset(visited,false,sizeof visited); dfs2(e[i].u,e[i].v,e[i].u); dfs2(e[i].v,e[i].u,e[i].v); printf("process %d, (%d, %d) :",rank,e[i].u,e[i].v); int rep = -1; for(int j = 0;j < m;++j) if(j != i && ((mark[ e[j].u ] == e[i].u && mark[ e[j].v ] == e[i].v) || (mark[ e[j].v ] == e[i].u && mark[ e[j].u ] == e[i].v))){ printf(" (%d, %d)",e[j].u,e[j].v); if(rep == -1 || e[j].w < e[rep].w) rep = j; } printf(", replacement : (%d, %d)\n",e[rep].u,e[rep].v); if(e[rep].w - e[i].w > max_increase_local[rank]){ max_increase_local[rank] = e[rep].w - e[i].w; most_vital_edge_local[rank] = i; } } } if(rank != 0){ MPI_Send(&max_increase_local[rank],1,MPI_INT,0,2,MPI_COMM_WORLD); MPI_Send(&most_vital_edge_local[rank],1,MPI_INT,0,3,MPI_COMM_WORLD); }else{ int most_vital_edge = most_vital_edge_local[0],max_increase = max_increase_local[0]; MPI_Status status; for(int i = 1;i < p;++i){ MPI_Recv(&max_increase_local[i],1,MPI_INT,i,2,MPI_COMM_WORLD,&status); MPI_Recv(&most_vital_edge_local[i],1,MPI_INT,i,3,MPI_COMM_WORLD,&status); if(max_increase_local[i] > max_increase){ max_increase = max_increase_local[i]; most_vital_edge = most_vital_edge_local[i]; } } printf("\n"); printf("Most vital edge = (%d, %d)\n",e[most_vital_edge].u,e[most_vital_edge].v); printf("Increase = %d\n",max_increase); } MPI_Finalize(); return 0; }<|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * CompressMGARDPlus.cpp : * * Created on: Feb 23, 2022 * Author: Jason Wang [email protected] */ #include "CompressMGARDPlus.h" #include "CompressMGARD.h" #include "adios2/core/Engine.h" #include "adios2/helper/adiosFunctions.h" namespace adios2 { namespace core { namespace compress { CompressMGARDPlus::CompressMGARDPlus(const Params &parameters) : Operator("mgardplus", COMPRESS_MGARDPLUS, "compress", parameters) { } size_t CompressMGARDPlus::Operate(const char *dataIn, const Dims &blockStart, const Dims &blockCount, const DataType type, char *bufferOut) { // Read ADIOS2 files from here adios2::core::ADIOS adios("C++"); auto &io = adios.DeclareIO("SubIO"); auto *engine = &io.Open(m_Parameters["MeshFile"], adios2::Mode::Read); auto var = io.InquireVariable<float>(m_Parameters["MeshVariable"]); std::vector<float> data(std::accumulate(var->m_Shape.begin(), var->m_Shape.end(), sizeof(float), std::multiplies<size_t>())); engine->Get(*var, data); // Read ADIOS2 files end, use data for your algorithm size_t bufferOutOffset = 0; const uint8_t bufferVersion = 1; MakeCommonHeader(bufferOut, bufferOutOffset, bufferVersion); bufferOutOffset += 32; // TODO: reserve memory space CompressMGARD mgard(m_Parameters); size_t mgardBufferSize = mgard.Operate(dataIn, blockStart, blockCount, type, bufferOut + bufferOutOffset); if (*reinterpret_cast<OperatorType *>(bufferOut + bufferOutOffset) == COMPRESS_MGARD) { std::vector<char> tmpDecompressBuffer( helper::GetTotalSize(blockCount, helper::GetDataTypeSize(type))); mgard.InverseOperate(bufferOut + bufferOutOffset, mgardBufferSize, tmpDecompressBuffer.data()); // TODO: now the original data is in dataIn, the compressed and then // decompressed data is in tmpDecompressBuffer.data(). However, these // are char pointers, you will need to convert them into right types as // follows: if (type == DataType::Double || type == DataType::DoubleComplex) { // TODO: use reinterpret_cast<double*>(dataIn) and // reinterpret_cast<double*>(tmpDecompressBuffer.data()) // to read original data and decompressed data } else if (type == DataType::Float || type == DataType::FloatComplex) { // TODO: use reinterpret_cast<float*>(dataIn) and // reinterpret_cast<double*>(tmpDecompressBuffer.data()) // to read original data and decompressed data } // TODO: after your algorithm is done, put the result into // *reinterpret_cast<double*>(bufferOut+bufferOutOffset) for your first // double number *reinterpret_cast<double*>(bufferOut+bufferOutOffset+8) // for your second double number and so on } bufferOutOffset += mgardBufferSize; return bufferOutOffset; } size_t CompressMGARDPlus::DecompressV1(const char *bufferIn, const size_t sizeIn, char *dataOut) { // Do NOT remove even if the buffer version is updated. Data might be still // in lagacy formats. This function must be kept for backward compatibility. // If a newer buffer format is implemented, create another function, e.g. // DecompressV2 and keep this function for decompressing lagacy data. // TODO: read your results here from // *reinterpret_cast<double*>(bufferIn) for your first double number // *reinterpret_cast<double*>(bufferIn+8) for your second double number and // so on size_t bufferInOffset = 32; // this number needs to be the same as the // memory space you reserved in Operate() CompressMGARD mgard(m_Parameters); size_t sizeOut = mgard.InverseOperate(bufferIn + bufferInOffset, sizeIn - bufferInOffset, dataOut); // TODO: the regular decompressed buffer is in dataOut, with the size of // sizeOut. Here you may want to do your magic to change the decompressed // data somehow to improve its accuracy :) return sizeOut; } size_t CompressMGARDPlus::InverseOperate(const char *bufferIn, const size_t sizeIn, char *dataOut) { size_t bufferInOffset = 1; // skip operator type const uint8_t bufferVersion = GetParameter<uint8_t>(bufferIn, bufferInOffset); bufferInOffset += 2; // skip two reserved bytes if (bufferVersion == 1) { return DecompressV1(bufferIn + bufferInOffset, sizeIn - bufferInOffset, dataOut); } else if (bufferVersion == 2) { // TODO: if a Version 2 mgard buffer is being implemented, put it here // and keep the DecompressV1 routine for backward compatibility } else { helper::Throw<std::runtime_error>("Operator", "CompressMGARDPlus", "InverseOperate", "invalid mgard buffer version"); } return 0; } bool CompressMGARDPlus::IsDataTypeValid(const DataType type) const { if (type == DataType::Double || type == DataType::Float || type == DataType::DoubleComplex || type == DataType::FloatComplex) { return true; } return false; } } // end namespace compress } // end namespace core } // end namespace adios2 <commit_msg>check for empty mesh file<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * CompressMGARDPlus.cpp : * * Created on: Feb 23, 2022 * Author: Jason Wang [email protected] */ #include "CompressMGARDPlus.h" #include "CompressMGARD.h" #include "adios2/core/Engine.h" #include "adios2/helper/adiosFunctions.h" namespace adios2 { namespace core { namespace compress { CompressMGARDPlus::CompressMGARDPlus(const Params &parameters) : Operator("mgardplus", COMPRESS_MGARDPLUS, "compress", parameters) { } size_t CompressMGARDPlus::Operate(const char *dataIn, const Dims &blockStart, const Dims &blockCount, const DataType type, char *bufferOut) { // Read ADIOS2 files from here if (!m_Parameters["MeshFile"].empty()) { adios2::core::ADIOS adios("C++"); auto &io = adios.DeclareIO("SubIO"); auto *engine = &io.Open(m_Parameters["MeshFile"], adios2::Mode::Read); auto var = io.InquireVariable<float>(m_Parameters["MeshVariable"]); std::vector<float> data( std::accumulate(var->m_Shape.begin(), var->m_Shape.end(), sizeof(float), std::multiplies<size_t>())); engine->Get(*var, data); } // Read ADIOS2 files end, use data for your algorithm size_t bufferOutOffset = 0; const uint8_t bufferVersion = 1; MakeCommonHeader(bufferOut, bufferOutOffset, bufferVersion); bufferOutOffset += 32; // TODO: reserve memory space CompressMGARD mgard(m_Parameters); size_t mgardBufferSize = mgard.Operate(dataIn, blockStart, blockCount, type, bufferOut + bufferOutOffset); if (*reinterpret_cast<OperatorType *>(bufferOut + bufferOutOffset) == COMPRESS_MGARD) { std::vector<char> tmpDecompressBuffer( helper::GetTotalSize(blockCount, helper::GetDataTypeSize(type))); mgard.InverseOperate(bufferOut + bufferOutOffset, mgardBufferSize, tmpDecompressBuffer.data()); // TODO: now the original data is in dataIn, the compressed and then // decompressed data is in tmpDecompressBuffer.data(). However, these // are char pointers, you will need to convert them into right types as // follows: if (type == DataType::Double || type == DataType::DoubleComplex) { // TODO: use reinterpret_cast<double*>(dataIn) and // reinterpret_cast<double*>(tmpDecompressBuffer.data()) // to read original data and decompressed data } else if (type == DataType::Float || type == DataType::FloatComplex) { // TODO: use reinterpret_cast<float*>(dataIn) and // reinterpret_cast<double*>(tmpDecompressBuffer.data()) // to read original data and decompressed data } // TODO: after your algorithm is done, put the result into // *reinterpret_cast<double*>(bufferOut+bufferOutOffset) for your first // double number *reinterpret_cast<double*>(bufferOut+bufferOutOffset+8) // for your second double number and so on } bufferOutOffset += mgardBufferSize; return bufferOutOffset; } size_t CompressMGARDPlus::DecompressV1(const char *bufferIn, const size_t sizeIn, char *dataOut) { // Do NOT remove even if the buffer version is updated. Data might be still // in lagacy formats. This function must be kept for backward compatibility. // If a newer buffer format is implemented, create another function, e.g. // DecompressV2 and keep this function for decompressing lagacy data. // TODO: read your results here from // *reinterpret_cast<double*>(bufferIn) for your first double number // *reinterpret_cast<double*>(bufferIn+8) for your second double number and // so on size_t bufferInOffset = 32; // this number needs to be the same as the // memory space you reserved in Operate() CompressMGARD mgard(m_Parameters); size_t sizeOut = mgard.InverseOperate(bufferIn + bufferInOffset, sizeIn - bufferInOffset, dataOut); // TODO: the regular decompressed buffer is in dataOut, with the size of // sizeOut. Here you may want to do your magic to change the decompressed // data somehow to improve its accuracy :) return sizeOut; } size_t CompressMGARDPlus::InverseOperate(const char *bufferIn, const size_t sizeIn, char *dataOut) { size_t bufferInOffset = 1; // skip operator type const uint8_t bufferVersion = GetParameter<uint8_t>(bufferIn, bufferInOffset); bufferInOffset += 2; // skip two reserved bytes if (bufferVersion == 1) { return DecompressV1(bufferIn + bufferInOffset, sizeIn - bufferInOffset, dataOut); } else if (bufferVersion == 2) { // TODO: if a Version 2 mgard buffer is being implemented, put it here // and keep the DecompressV1 routine for backward compatibility } else { helper::Throw<std::runtime_error>("Operator", "CompressMGARDPlus", "InverseOperate", "invalid mgard buffer version"); } return 0; } bool CompressMGARDPlus::IsDataTypeValid(const DataType type) const { if (type == DataType::Double || type == DataType::Float || type == DataType::DoubleComplex || type == DataType::FloatComplex) { return true; } return false; } } // end namespace compress } // end namespace core } // end namespace adios2 <|endoftext|>
<commit_before>#include <ncurses.h> #include <utility> #include "board.hpp" #include "print.hpp" #include "reversi.hpp" namespace roadagain { Reversi::Reversi() : black_(DEFAULT_STONE / 2), white_(DEFAULT_STONE / 2), now_(BLACK), next_(WHITE) { } Reversi::~Reversi() { } void Reversi::start() { print(START_Y, START_X); } void Reversi::play() { std::pair<int, int> point; for (int i = 0; i < MAX_PUT; i++){ if (can_put() == false){ change(); } std::pair<int, int> point = move(); put(point); change(); } end(); } void Reversi::end() { ::move(ROW * 2 + 3, 0); if (black_ == white_){ printw("Draw"); } else { printw("Winner is %s", black_ > white_ ? "White" : "Black"); } } const int Reversi::DXY[] = { -1, 0, 1 }; bool Reversi::can_put() { for (int i = 0; i < ROW; i++){ for (int j = 0; j < COL; j++){ if (can_put(std::pair<int, int>(i, j)) == true){ return (true); } } } return (false); } bool Reversi::can_put(const std::pair<int, int>& point) { for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ if (DXY[i] == 0 && DXY[j] == 0){ continue; } if (can_put(point, DXY[i], DXY[j]) == true){ return (true); } } } return (false); } bool Reversi::can_put(const std::pair<int, int>& point, int dy, int dx) { int y = point.first + dy; int x = point.second + dx; bool can_reverse = false; while (in_board(y, x) == true && matrix_[y][x] == next_){ can_reverse = true; y += dy; x += dx; } return (in_board(y, x) == true && can_reverse == true && matrix_[y][x] == now_); } std::pair<int, int> Reversi::move() { int y = 0; int x = 0; char c; if (matrix_[y][x] == EMPTY){ print_stone(y, x, now_); } else { print_coordinate(y, x); } c = getch(); while (c != '\n' || can_put(std::pair<int, int>(y, x)) == false){ if (matrix_[y][x] == EMPTY){ clear_stone(y, x); } else { clear_coordinate(y, x); } switch (c){ case 'h': x = (x + Board::COL - 1) % Board::COL; break; case 'j': y = (y + 1) % Board::ROW; break; case 'k': y = (y + Board::ROW - 1) % Board::ROW; break; case 'l': x = (x + 1) % Board::COL; break; } if (matrix_[y][x] == EMPTY){ print_stone(y, x, now_); } else { print_coordinate(y, x); } c = getch(); } clear_stone(y, x); return (std::pair<int, int>(y, x)); } void Reversi::put(const std::pair<int, int>& point) { int y = point.first; int x = point.second; matrix_[y][x] = now_; if (now_ == BLACK){ black_++; } else { white_++; } print_stone(y, x, now_, false); reverse(point); } void Reversi::reverse(const std::pair<int, int>& point) { for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ if (DXY[i] == 0 && DXY[j] == 0){ continue; } reverse(point, DXY[i], DXY[j]); } } } void Reversi::reverse(const std::pair<int, int>& point, int dy, int dx) { int y = point.first + dy; int x = point.second + dx; int cnt = 0; while (in_board(y, x) == true && matrix_[y][x] == next_){ cnt++; y += dy; x += dx; } if (in_board(y, x) == false || matrix_[y][x] == EMPTY){ return; } while (cnt-- > 0){ y -= dy; x -= dx; matrix_[y][x] = now_; if (now_ == BLACK){ black_++; white_--; } else { white_++; black_--; } print_stone(y, x, now_, false); } } void Reversi::change() { now_ = next_; next_ = (next_ == BLACK ? WHITE : BLACK); } } <commit_msg>Added break sentence to checking available point<commit_after>#include <ncurses.h> #include <utility> #include "board.hpp" #include "print.hpp" #include "reversi.hpp" namespace roadagain { Reversi::Reversi() : black_(DEFAULT_STONE / 2), white_(DEFAULT_STONE / 2), now_(BLACK), next_(WHITE) { } Reversi::~Reversi() { } void Reversi::start() { print(START_Y, START_X); } void Reversi::play() { std::pair<int, int> point; for (int i = 0; i < MAX_PUT; i++){ if (can_put() == false){ change(); if (can_put() == false){ break; } } std::pair<int, int> point = move(); put(point); change(); } end(); } void Reversi::end() { ::move(ROW * 2 + 3, 0); if (black_ == white_){ printw("Draw"); } else { printw("Winner is %s", black_ > white_ ? "White" : "Black"); } } const int Reversi::DXY[] = { -1, 0, 1 }; bool Reversi::can_put() { for (int i = 0; i < ROW; i++){ for (int j = 0; j < COL; j++){ if (can_put(std::pair<int, int>(i, j)) == true){ return (true); } } } return (false); } bool Reversi::can_put(const std::pair<int, int>& point) { for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ if (DXY[i] == 0 && DXY[j] == 0){ continue; } if (can_put(point, DXY[i], DXY[j]) == true){ return (true); } } } return (false); } bool Reversi::can_put(const std::pair<int, int>& point, int dy, int dx) { int y = point.first + dy; int x = point.second + dx; bool can_reverse = false; while (in_board(y, x) == true && matrix_[y][x] == next_){ can_reverse = true; y += dy; x += dx; } return (in_board(y, x) == true && can_reverse == true && matrix_[y][x] == now_); } std::pair<int, int> Reversi::move() { int y = 0; int x = 0; char c; if (matrix_[y][x] == EMPTY){ print_stone(y, x, now_); } else { print_coordinate(y, x); } c = getch(); while (c != '\n' || can_put(std::pair<int, int>(y, x)) == false){ if (matrix_[y][x] == EMPTY){ clear_stone(y, x); } else { clear_coordinate(y, x); } switch (c){ case 'h': x = (x + Board::COL - 1) % Board::COL; break; case 'j': y = (y + 1) % Board::ROW; break; case 'k': y = (y + Board::ROW - 1) % Board::ROW; break; case 'l': x = (x + 1) % Board::COL; break; } if (matrix_[y][x] == EMPTY){ print_stone(y, x, now_); } else { print_coordinate(y, x); } c = getch(); } clear_stone(y, x); return (std::pair<int, int>(y, x)); } void Reversi::put(const std::pair<int, int>& point) { int y = point.first; int x = point.second; matrix_[y][x] = now_; if (now_ == BLACK){ black_++; } else { white_++; } print_stone(y, x, now_, false); reverse(point); } void Reversi::reverse(const std::pair<int, int>& point) { for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ if (DXY[i] == 0 && DXY[j] == 0){ continue; } reverse(point, DXY[i], DXY[j]); } } } void Reversi::reverse(const std::pair<int, int>& point, int dy, int dx) { int y = point.first + dy; int x = point.second + dx; int cnt = 0; while (in_board(y, x) == true && matrix_[y][x] == next_){ cnt++; y += dy; x += dx; } if (in_board(y, x) == false || matrix_[y][x] == EMPTY){ return; } while (cnt-- > 0){ y -= dy; x -= dx; matrix_[y][x] = now_; if (now_ == BLACK){ black_++; white_--; } else { white_++; black_--; } print_stone(y, x, now_, false); } } void Reversi::change() { now_ = next_; next_ = (next_ == BLACK ? WHITE : BLACK); } } <|endoftext|>
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved. #include <gtest/gtest.h> #include <folly/Conv.h> #include <folly/Format.h> #include <folly/io/async/ScopedEventBaseThread.h> #include <folly/portability/GFlags.h> #include "RSocketTests.h" #include "rsocket/test/handlers/HelloServiceHandler.h" #include "rsocket/test/test_utils/ColdResumeManager.h" DEFINE_int32(num_clients, 5, "Number of clients to parallely cold-resume"); using namespace rsocket; using namespace rsocket::tests; using namespace rsocket::tests::client_server; using namespace yarpl; using namespace yarpl::flowable; typedef std::map<std::string, std::shared_ptr<Subscriber<Payload>>> HelloSubscribers; namespace { class HelloSubscriber : public BaseSubscriber<Payload> { public: explicit HelloSubscriber(size_t latestValue) : latestValue_(latestValue) {} void requestWhenSubscribed(int n) { subscribedBaton_.wait(); this->request(n); } void awaitLatestValue(size_t value) { auto count = 50; while (value != latestValue_ && count > 0) { VLOG(1) << "Waiting " << count << " ticks for latest value..."; std::this_thread::sleep_for(std::chrono::milliseconds(100)); count--; std::this_thread::yield(); } EXPECT_EQ(value, latestValue_); } size_t valueCount() const { return count_; } size_t getLatestValue() const { return latestValue_; } protected: void onSubscribeImpl() noexcept override { subscribedBaton_.post(); } void onNextImpl(Payload p) noexcept override { auto currValue = folly::to<size_t>(p.data->moveToFbString().toStdString()); EXPECT_EQ(latestValue_, currValue - 1); latestValue_ = currValue; count_++; } void onCompleteImpl() override {} void onErrorImpl(folly::exception_wrapper) override {} private: std::atomic<size_t> latestValue_; std::atomic<size_t> count_{0}; folly::Baton<> subscribedBaton_; }; class HelloResumeHandler : public ColdResumeHandler { public: explicit HelloResumeHandler(HelloSubscribers subscribers) : subscribers_(std::move(subscribers)) {} std::string generateStreamToken(const Payload& payload, StreamId, StreamType) const override { const auto streamToken = payload.data->cloneAsValue().moveToFbString().toStdString(); VLOG(3) << "Generated token: " << streamToken; return streamToken; } std::shared_ptr<Subscriber<Payload>> handleRequesterResumeStream( std::string streamToken, size_t consumerAllowance) override { CHECK(subscribers_.find(streamToken) != subscribers_.end()); VLOG(1) << "Resuming " << streamToken << " stream with allowance " << consumerAllowance; return subscribers_[streamToken]; } private: HelloSubscribers subscribers_; }; } // namespace std::unique_ptr<rsocket::RSocketClient> createResumedClient( folly::EventBase* evb, uint32_t port, ResumeIdentificationToken token, std::shared_ptr<ResumeManager> resumeManager, std::shared_ptr<ColdResumeHandler> coldResumeHandler, folly::EventBase* stateMachineEvb = nullptr) { auto retries = 10; while (true) { try { return RSocket::createResumedClient( getConnFactory(evb, port), token, resumeManager, coldResumeHandler, nullptr, /* responder */ kDefaultKeepaliveInterval, nullptr, /* stats */ nullptr, /* connectionEvents */ ProtocolVersion::Latest, stateMachineEvb) .get(); } catch (RSocketException ex) { retries--; VLOG(1) << "Creation of resumed client failed. Exception " << ex.what() << ". Retries Left: " << retries; if (retries <= 0) { throw ex; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } } // There are three sessions and three streams. // There is cold-resumption between the three sessions. // // The first stream lasts through all three sessions. // The second stream lasts through the second and third session. // The third stream lives only in the third session. // // The first stream requests 10 frames // The second stream requests 10 frames // The third stream requests 5 frames void coldResumer(uint32_t port, uint32_t client_num) { auto firstPayload = folly::sformat("client{}_first", client_num); auto secondPayload = folly::sformat("client{}_second", client_num); auto thirdPayload = folly::sformat("client{}_third", client_num); size_t firstLatestValue, secondLatestValue; folly::ScopedEventBaseThread worker; auto token = ResumeIdentificationToken::generateNew(); auto resumeManager = std::make_shared<ColdResumeManager>(RSocketStats::noop()); { auto firstSub = std::make_shared<HelloSubscriber>(0); { auto coldResumeHandler = std::make_shared<HelloResumeHandler>( HelloSubscribers({{firstPayload, firstSub}})); std::shared_ptr<RSocketClient> firstClient; EXPECT_NO_THROW( firstClient = makeColdResumableClient( worker.getEventBase(), port, token, resumeManager, coldResumeHandler)); firstClient->getRequester() ->requestStream(Payload(firstPayload)) ->subscribe(firstSub); firstSub->requestWhenSubscribed(4); // Ensure reception of few frames before resuming. while (firstSub->valueCount() < 1) { std::this_thread::yield(); } } worker.getEventBase()->runInEventBaseThreadAndWait( [client_num, &firstLatestValue, firstSub = std::move(firstSub)]() { firstLatestValue = firstSub->getLatestValue(); VLOG(1) << folly::sformat( "client{} {}", client_num, firstLatestValue); VLOG(1) << folly::sformat("client{} First Resume", client_num); }); } { auto firstSub = std::make_shared<HelloSubscriber>(firstLatestValue); auto secondSub = std::make_shared<HelloSubscriber>(0); { auto coldResumeHandler = std::make_shared<HelloResumeHandler>( HelloSubscribers({{firstPayload, firstSub}})); std::shared_ptr<RSocketClient> secondClient; EXPECT_NO_THROW( secondClient = createResumedClient( worker.getEventBase(), port, token, resumeManager, coldResumeHandler)); // Create another stream to verify StreamIds are set properly after // resumption secondClient->getRequester() ->requestStream(Payload(secondPayload)) ->subscribe(secondSub); firstSub->requestWhenSubscribed(3); secondSub->requestWhenSubscribed(5); // Ensure reception of few frames before resuming. while (secondSub->valueCount() < 1) { std::this_thread::yield(); } } worker.getEventBase()->runInEventBaseThreadAndWait( [client_num, &firstLatestValue, firstSub = std::move(firstSub), &secondLatestValue, secondSub = std::move(secondSub)]() { firstLatestValue = firstSub->getLatestValue(); secondLatestValue = secondSub->getLatestValue(); VLOG(1) << folly::sformat( "client{} {}", client_num, firstLatestValue); VLOG(1) << folly::sformat( "client{} {}", client_num, secondLatestValue); VLOG(1) << folly::sformat("client{} Second Resume", client_num); }); } { auto firstSub = std::make_shared<HelloSubscriber>(firstLatestValue); auto secondSub = std::make_shared<HelloSubscriber>(secondLatestValue); auto thirdSub = std::make_shared<HelloSubscriber>(0); auto coldResumeHandler = std::make_shared<HelloResumeHandler>(HelloSubscribers( {{firstPayload, firstSub}, {secondPayload, secondSub}})); std::shared_ptr<RSocketClient> thirdClient; EXPECT_NO_THROW( thirdClient = createResumedClient( worker.getEventBase(), port, token, resumeManager, coldResumeHandler)); // Create another stream to verify StreamIds are set properly after // resumption thirdClient->getRequester() ->requestStream(Payload(thirdPayload)) ->subscribe(thirdSub); firstSub->requestWhenSubscribed(3); secondSub->requestWhenSubscribed(5); thirdSub->requestWhenSubscribed(5); firstSub->awaitLatestValue(10); secondSub->awaitLatestValue(10); thirdSub->awaitLatestValue(5); } } TEST(ColdResumptionTest, SuccessfulResumption) { auto server = makeResumableServer(std::make_shared<HelloServiceHandler>()); auto port = *server->listeningPort(); std::vector<std::thread> clients; for (int i = 0; i < FLAGS_num_clients; i++) { auto client = std::thread([port, i]() { coldResumer(port, i); }); clients.push_back(std::move(client)); } for (auto& client : clients) { client.join(); } } TEST(ColdResumptionTest, DifferentEvb) { auto server = makeResumableServer(std::make_shared<HelloServiceHandler>()); auto port = *server->listeningPort(); auto payload = "InitialPayload"; size_t latestValue; folly::ScopedEventBaseThread transportWorker{"transportWorker"}; folly::ScopedEventBaseThread SMWorker{"SMWorker"}; auto token = ResumeIdentificationToken::generateNew(); auto resumeManager = std::make_shared<ColdResumeManager>(RSocketStats::noop()); { auto firstSub = std::make_shared<HelloSubscriber>(0); { auto coldResumeHandler = std::make_shared<HelloResumeHandler>( HelloSubscribers({{payload, firstSub}})); std::shared_ptr<RSocketClient> firstClient; EXPECT_NO_THROW( firstClient = makeColdResumableClient( transportWorker.getEventBase(), port, token, resumeManager, coldResumeHandler, SMWorker.getEventBase())); firstClient->getRequester() ->requestStream(Payload(payload)) ->subscribe(firstSub); firstSub->requestWhenSubscribed(7); // Ensure reception of few frames before resuming. while (firstSub->valueCount() < 1) { std::this_thread::yield(); } } SMWorker.getEventBase()->runInEventBaseThreadAndWait( [&latestValue, firstSub = std::move(firstSub)]() { latestValue = firstSub->getLatestValue(); VLOG(1) << latestValue; VLOG(1) << "First Resume"; }); } { auto firstSub = std::make_shared<HelloSubscriber>(latestValue); { auto coldResumeHandler = std::make_shared<HelloResumeHandler>( HelloSubscribers({{payload, firstSub}})); std::shared_ptr<RSocketClient> secondClient; EXPECT_NO_THROW( secondClient = createResumedClient( transportWorker.getEventBase(), port, token, resumeManager, coldResumeHandler, SMWorker.getEventBase())); firstSub->requestWhenSubscribed(3); // Ensure reception of few frames before resuming. while (firstSub->valueCount() < 1) { std::this_thread::yield(); } firstSub->awaitLatestValue(10); } } server->shutdownAndWait(); } // Attempt a resumption when the previous transport/client hasn't // disconnected it. Verify resumption succeeds after the previous // transport is disconnected. TEST(ColdResumptionTest, DisconnectResumption) { auto server = makeResumableServer(std::make_shared<HelloServiceHandler>()); auto port = *server->listeningPort(); auto payload = "InitialPayload"; folly::ScopedEventBaseThread transportWorker{"transportWorker"}; auto token = ResumeIdentificationToken::generateNew(); auto resumeManager = std::make_shared<ColdResumeManager>(RSocketStats::noop()); auto sub = std::make_shared<HelloSubscriber>(0); auto crh = std::make_shared<HelloResumeHandler>(HelloSubscribers({{payload, sub}})); std::shared_ptr<RSocketClient> client; EXPECT_NO_THROW( client = makeColdResumableClient( transportWorker.getEventBase(), port, token, resumeManager, crh)); client->getRequester()->requestStream(Payload(payload))->subscribe(sub); sub->requestWhenSubscribed(7); // Ensure reception of few frames before resuming. while (sub->valueCount() < 7) { std::this_thread::yield(); } auto resumedSub = std::make_shared<HelloSubscriber>(7); auto resumedCrh = std::make_shared<HelloResumeHandler>( HelloSubscribers({{payload, resumedSub}})); std::shared_ptr<RSocketClient> resumedClient; EXPECT_NO_THROW( resumedClient = createResumedClient( transportWorker.getEventBase(), port, token, resumeManager, resumedCrh)); resumedSub->requestWhenSubscribed(3); resumedSub->awaitLatestValue(10); server->shutdownAndWait(); } <commit_msg>Disable ColdResumptionTest.SucessfulResumption<commit_after>// Copyright 2004-present Facebook. All Rights Reserved. #include <gtest/gtest.h> #include <folly/Conv.h> #include <folly/Format.h> #include <folly/io/async/ScopedEventBaseThread.h> #include <folly/portability/GFlags.h> #include "RSocketTests.h" #include "rsocket/test/handlers/HelloServiceHandler.h" #include "rsocket/test/test_utils/ColdResumeManager.h" DEFINE_int32(num_clients, 5, "Number of clients to parallely cold-resume"); using namespace rsocket; using namespace rsocket::tests; using namespace rsocket::tests::client_server; using namespace yarpl; using namespace yarpl::flowable; typedef std::map<std::string, std::shared_ptr<Subscriber<Payload>>> HelloSubscribers; namespace { class HelloSubscriber : public BaseSubscriber<Payload> { public: explicit HelloSubscriber(size_t latestValue) : latestValue_(latestValue) {} void requestWhenSubscribed(int n) { subscribedBaton_.wait(); this->request(n); } void awaitLatestValue(size_t value) { auto count = 50; while (value != latestValue_ && count > 0) { VLOG(1) << "Waiting " << count << " ticks for latest value..."; std::this_thread::sleep_for(std::chrono::milliseconds(100)); count--; std::this_thread::yield(); } EXPECT_EQ(value, latestValue_); } size_t valueCount() const { return count_; } size_t getLatestValue() const { return latestValue_; } protected: void onSubscribeImpl() noexcept override { subscribedBaton_.post(); } void onNextImpl(Payload p) noexcept override { auto currValue = folly::to<size_t>(p.data->moveToFbString().toStdString()); EXPECT_EQ(latestValue_, currValue - 1); latestValue_ = currValue; count_++; } void onCompleteImpl() override {} void onErrorImpl(folly::exception_wrapper) override {} private: std::atomic<size_t> latestValue_; std::atomic<size_t> count_{0}; folly::Baton<> subscribedBaton_; }; class HelloResumeHandler : public ColdResumeHandler { public: explicit HelloResumeHandler(HelloSubscribers subscribers) : subscribers_(std::move(subscribers)) {} std::string generateStreamToken(const Payload& payload, StreamId, StreamType) const override { const auto streamToken = payload.data->cloneAsValue().moveToFbString().toStdString(); VLOG(3) << "Generated token: " << streamToken; return streamToken; } std::shared_ptr<Subscriber<Payload>> handleRequesterResumeStream( std::string streamToken, size_t consumerAllowance) override { CHECK(subscribers_.find(streamToken) != subscribers_.end()); VLOG(1) << "Resuming " << streamToken << " stream with allowance " << consumerAllowance; return subscribers_[streamToken]; } private: HelloSubscribers subscribers_; }; } // namespace std::unique_ptr<rsocket::RSocketClient> createResumedClient( folly::EventBase* evb, uint32_t port, ResumeIdentificationToken token, std::shared_ptr<ResumeManager> resumeManager, std::shared_ptr<ColdResumeHandler> coldResumeHandler, folly::EventBase* stateMachineEvb = nullptr) { auto retries = 10; while (true) { try { return RSocket::createResumedClient( getConnFactory(evb, port), token, resumeManager, coldResumeHandler, nullptr, /* responder */ kDefaultKeepaliveInterval, nullptr, /* stats */ nullptr, /* connectionEvents */ ProtocolVersion::Latest, stateMachineEvb) .get(); } catch (RSocketException ex) { retries--; VLOG(1) << "Creation of resumed client failed. Exception " << ex.what() << ". Retries Left: " << retries; if (retries <= 0) { throw ex; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } } // There are three sessions and three streams. // There is cold-resumption between the three sessions. // // The first stream lasts through all three sessions. // The second stream lasts through the second and third session. // The third stream lives only in the third session. // // The first stream requests 10 frames // The second stream requests 10 frames // The third stream requests 5 frames void coldResumer(uint32_t port, uint32_t client_num) { auto firstPayload = folly::sformat("client{}_first", client_num); auto secondPayload = folly::sformat("client{}_second", client_num); auto thirdPayload = folly::sformat("client{}_third", client_num); size_t firstLatestValue, secondLatestValue; folly::ScopedEventBaseThread worker; auto token = ResumeIdentificationToken::generateNew(); auto resumeManager = std::make_shared<ColdResumeManager>(RSocketStats::noop()); { auto firstSub = std::make_shared<HelloSubscriber>(0); { auto coldResumeHandler = std::make_shared<HelloResumeHandler>( HelloSubscribers({{firstPayload, firstSub}})); std::shared_ptr<RSocketClient> firstClient; EXPECT_NO_THROW( firstClient = makeColdResumableClient( worker.getEventBase(), port, token, resumeManager, coldResumeHandler)); firstClient->getRequester() ->requestStream(Payload(firstPayload)) ->subscribe(firstSub); firstSub->requestWhenSubscribed(4); // Ensure reception of few frames before resuming. while (firstSub->valueCount() < 1) { std::this_thread::yield(); } } worker.getEventBase()->runInEventBaseThreadAndWait( [client_num, &firstLatestValue, firstSub = std::move(firstSub)]() { firstLatestValue = firstSub->getLatestValue(); VLOG(1) << folly::sformat( "client{} {}", client_num, firstLatestValue); VLOG(1) << folly::sformat("client{} First Resume", client_num); }); } { auto firstSub = std::make_shared<HelloSubscriber>(firstLatestValue); auto secondSub = std::make_shared<HelloSubscriber>(0); { auto coldResumeHandler = std::make_shared<HelloResumeHandler>( HelloSubscribers({{firstPayload, firstSub}})); std::shared_ptr<RSocketClient> secondClient; EXPECT_NO_THROW( secondClient = createResumedClient( worker.getEventBase(), port, token, resumeManager, coldResumeHandler)); // Create another stream to verify StreamIds are set properly after // resumption secondClient->getRequester() ->requestStream(Payload(secondPayload)) ->subscribe(secondSub); firstSub->requestWhenSubscribed(3); secondSub->requestWhenSubscribed(5); // Ensure reception of few frames before resuming. while (secondSub->valueCount() < 1) { std::this_thread::yield(); } } worker.getEventBase()->runInEventBaseThreadAndWait( [client_num, &firstLatestValue, firstSub = std::move(firstSub), &secondLatestValue, secondSub = std::move(secondSub)]() { firstLatestValue = firstSub->getLatestValue(); secondLatestValue = secondSub->getLatestValue(); VLOG(1) << folly::sformat( "client{} {}", client_num, firstLatestValue); VLOG(1) << folly::sformat( "client{} {}", client_num, secondLatestValue); VLOG(1) << folly::sformat("client{} Second Resume", client_num); }); } { auto firstSub = std::make_shared<HelloSubscriber>(firstLatestValue); auto secondSub = std::make_shared<HelloSubscriber>(secondLatestValue); auto thirdSub = std::make_shared<HelloSubscriber>(0); auto coldResumeHandler = std::make_shared<HelloResumeHandler>(HelloSubscribers( {{firstPayload, firstSub}, {secondPayload, secondSub}})); std::shared_ptr<RSocketClient> thirdClient; EXPECT_NO_THROW( thirdClient = createResumedClient( worker.getEventBase(), port, token, resumeManager, coldResumeHandler)); // Create another stream to verify StreamIds are set properly after // resumption thirdClient->getRequester() ->requestStream(Payload(thirdPayload)) ->subscribe(thirdSub); firstSub->requestWhenSubscribed(3); secondSub->requestWhenSubscribed(5); thirdSub->requestWhenSubscribed(5); firstSub->awaitLatestValue(10); secondSub->awaitLatestValue(10); thirdSub->awaitLatestValue(5); } } TEST(ColdResumptionTest, DISABLED_SuccessfulResumption) { auto server = makeResumableServer(std::make_shared<HelloServiceHandler>()); auto port = *server->listeningPort(); std::vector<std::thread> clients; for (int i = 0; i < FLAGS_num_clients; i++) { auto client = std::thread([port, i]() { coldResumer(port, i); }); clients.push_back(std::move(client)); } for (auto& client : clients) { client.join(); } } TEST(ColdResumptionTest, DifferentEvb) { auto server = makeResumableServer(std::make_shared<HelloServiceHandler>()); auto port = *server->listeningPort(); auto payload = "InitialPayload"; size_t latestValue; folly::ScopedEventBaseThread transportWorker{"transportWorker"}; folly::ScopedEventBaseThread SMWorker{"SMWorker"}; auto token = ResumeIdentificationToken::generateNew(); auto resumeManager = std::make_shared<ColdResumeManager>(RSocketStats::noop()); { auto firstSub = std::make_shared<HelloSubscriber>(0); { auto coldResumeHandler = std::make_shared<HelloResumeHandler>( HelloSubscribers({{payload, firstSub}})); std::shared_ptr<RSocketClient> firstClient; EXPECT_NO_THROW( firstClient = makeColdResumableClient( transportWorker.getEventBase(), port, token, resumeManager, coldResumeHandler, SMWorker.getEventBase())); firstClient->getRequester() ->requestStream(Payload(payload)) ->subscribe(firstSub); firstSub->requestWhenSubscribed(7); // Ensure reception of few frames before resuming. while (firstSub->valueCount() < 1) { std::this_thread::yield(); } } SMWorker.getEventBase()->runInEventBaseThreadAndWait( [&latestValue, firstSub = std::move(firstSub)]() { latestValue = firstSub->getLatestValue(); VLOG(1) << latestValue; VLOG(1) << "First Resume"; }); } { auto firstSub = std::make_shared<HelloSubscriber>(latestValue); { auto coldResumeHandler = std::make_shared<HelloResumeHandler>( HelloSubscribers({{payload, firstSub}})); std::shared_ptr<RSocketClient> secondClient; EXPECT_NO_THROW( secondClient = createResumedClient( transportWorker.getEventBase(), port, token, resumeManager, coldResumeHandler, SMWorker.getEventBase())); firstSub->requestWhenSubscribed(3); // Ensure reception of few frames before resuming. while (firstSub->valueCount() < 1) { std::this_thread::yield(); } firstSub->awaitLatestValue(10); } } server->shutdownAndWait(); } // Attempt a resumption when the previous transport/client hasn't // disconnected it. Verify resumption succeeds after the previous // transport is disconnected. TEST(ColdResumptionTest, DisconnectResumption) { auto server = makeResumableServer(std::make_shared<HelloServiceHandler>()); auto port = *server->listeningPort(); auto payload = "InitialPayload"; folly::ScopedEventBaseThread transportWorker{"transportWorker"}; auto token = ResumeIdentificationToken::generateNew(); auto resumeManager = std::make_shared<ColdResumeManager>(RSocketStats::noop()); auto sub = std::make_shared<HelloSubscriber>(0); auto crh = std::make_shared<HelloResumeHandler>(HelloSubscribers({{payload, sub}})); std::shared_ptr<RSocketClient> client; EXPECT_NO_THROW( client = makeColdResumableClient( transportWorker.getEventBase(), port, token, resumeManager, crh)); client->getRequester()->requestStream(Payload(payload))->subscribe(sub); sub->requestWhenSubscribed(7); // Ensure reception of few frames before resuming. while (sub->valueCount() < 7) { std::this_thread::yield(); } auto resumedSub = std::make_shared<HelloSubscriber>(7); auto resumedCrh = std::make_shared<HelloResumeHandler>( HelloSubscribers({{payload, resumedSub}})); std::shared_ptr<RSocketClient> resumedClient; EXPECT_NO_THROW( resumedClient = createResumedClient( transportWorker.getEventBase(), port, token, resumeManager, resumedCrh)); resumedSub->requestWhenSubscribed(3); resumedSub->awaitLatestValue(10); server->shutdownAndWait(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ww8par2.hxx,v $ * * $Revision: 1.46 $ * * last change: $Author: hr $ $Date: 2007-09-27 10:05:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */ #ifndef _WW8PAR2_HXX #define _WW8PAR2_HXX #ifndef SWTYPES_HXX #include <swtypes.hxx> // enum RndStdIds #endif #ifndef _FMTFSIZE_HXX #include <fmtfsize.hxx> #endif #ifndef _FMTORNT_HXX #include <fmtornt.hxx> #endif #ifndef _FMTSRND_HXX #include <fmtsrnd.hxx> #endif #ifndef _SVX_LRSPITEM_HXX #include <svx/lrspitem.hxx> #endif #ifndef WW8SCAN_HXX #include "ww8scan.hxx" // class WW8Style #endif #ifndef WW8PAR_HXX #include "ww8par.hxx" // WW8_BRC5 #endif class WW8RStyle; class WW8DupProperties { public: WW8DupProperties(SwDoc &rDoc, SwWW8FltControlStack *pStk); void Insert(const SwPosition &rPos); private: //No copying WW8DupProperties(const WW8DupProperties&); WW8DupProperties& operator=(const WW8DupProperties&); SwWW8FltControlStack* pCtrlStck; SfxItemSet aChrSet,aParSet; }; struct WW8FlyPara { // WinWord-Attribute // Achtung: *Nicht* umsortieren, da Teile mit // memcmp verglichen werden bool bVer67; INT16 nSp26, nSp27; // rohe Position INT16 nSp45, nSp28; // Breite / Hoehe INT16 nLeMgn, nRiMgn, nUpMgn, nLoMgn; // Raender BYTE nSp29; // rohe Bindung + Alignment BYTE nSp37; // Wrap-Mode ( 1 / 2; 0 = no Apo ? ) WW8_BRC5 brc; // Umrandung Top, Left, Bottom, Right, Between bool bBorderLines; // Umrandungslinien bool bGrafApo; // true: Dieser Rahmen dient allein dazu, die // enthaltene Grafik anders als zeichengebunden // zu positionieren bool mbVertSet; // true if vertical positioning has been set BYTE nOrigSp29; WW8FlyPara(bool bIsVer67, const WW8FlyPara* pSrc = 0); bool operator==(const WW8FlyPara& rSrc) const; void Read(const BYTE* pSprm29, WW8PLCFx_Cp_FKP* pPap); void ReadFull(const BYTE* pSprm29, SwWW8ImplReader* pIo); void Read(const BYTE* pSprm29, WW8RStyle* pStyle); void ApplyTabPos(const WW8_TablePos *pTabPos); bool IsEmpty() const; }; struct WW8SwFlyPara { SwFlyFrmFmt* pFlyFmt; // 1. Teil: daraus abgeleitete Sw-Attribute INT16 nXPos, nYPos; // Position INT16 nLeMgn, nRiMgn; // Raender INT16 nUpMgn, nLoMgn; // Raender INT16 nWidth, nHeight; // Groesse INT16 nNettoWidth; SwFrmSize eHeightFix; // Hoehe Fix oder Min RndStdIds eAnchor; // Bindung short eHRel; // Seite oder Seitenrand short eVRel; // Seite oder Seitenrand sal_Int16 eVAlign; // Oben, unten, mittig sal_Int16 eHAlign; // links, rechts, mittig SwSurround eSurround; // Wrap-Mode BYTE nXBind, nYBind; // relativ zu was gebunden // 2.Teil: sich waehrend des Einlesens ergebende AEnderungen long nNewNettoWidth; SwPosition* pMainTextPos; // um nach Apo in Haupttext zurueckzukehren USHORT nLineSpace; // LineSpace in tw fuer Graf-Apos bool bAutoWidth; bool bToggelPos; // --> OD 2007-07-03 #148498# // add parameter <nWWPgTop> - WW8's page top margin WW8SwFlyPara( SwPaM& rPaM, SwWW8ImplReader& rIo, WW8FlyPara& rWW, const sal_uInt32 nWWPgTop, const sal_uInt32 nPgLeft, const sal_uInt32 nPgWidth, const INT32 nIniFlyDx, const INT32 nIniFlyDy ); void BoxUpWidth( long nWidth ); SwWW8FltAnchorStack *pOldAnchorStck; }; class SwWW8StyInf { String sWWStyleName; USHORT nWWStyleId; public: rtl_TextEncoding eLTRFontSrcCharSet; // rtl_TextEncoding fuer den Font rtl_TextEncoding eRTLFontSrcCharSet; // rtl_TextEncoding fuer den Font rtl_TextEncoding eCJKFontSrcCharSet; // rtl_TextEncoding fuer den Font SwFmt* pFmt; WW8FlyPara* pWWFly; SwNumRule* pOutlineNumrule; long nFilePos; USHORT nBase; USHORT nFollow; USHORT nLFOIndex; BYTE nListLevel; BYTE nOutlineLevel; // falls Gliederungs-Style sal_uInt16 n81Flags; // Fuer Bold, Italic, ... sal_uInt16 n81BiDiFlags; // Fuer Bold, Italic, ... SvxLRSpaceItem maWordLR; bool bValid; // leer oder Valid bool bImported; // fuers rekursive Importieren bool bColl; // true-> pFmt ist SwTxtFmtColl bool bImportSkipped; // nur true bei !bNewDoc && vorh. Style bool bHasStyNumRule; // true-> Benannter NumRule in Style bool bHasBrokenWW6List; // true-> WW8+ style has a WW7- list bool bListReleventIndentSet; //true if this style's indent has //been explicitly set, it's set to the value //of pFmt->GetItemState(RES_LR_SPACE, false) //if it was possible to get the ItemState //for L of the LR space independantly bool bParaAutoBefore; // For Auto spacing before a paragraph bool bParaAutoAfter; // For Auto Spacing after a paragraph SwWW8StyInf() : sWWStyleName( aEmptyStr ), nWWStyleId( 0 ), eLTRFontSrcCharSet(0), eRTLFontSrcCharSet(0), eCJKFontSrcCharSet(0), pFmt( 0 ), pWWFly( 0 ), pOutlineNumrule( 0 ), nFilePos( 0 ), nBase( 0 ), nFollow( 0 ), nLFOIndex( USHRT_MAX ), nListLevel(WW8ListManager::nMaxLevel), nOutlineLevel( MAXLEVEL ), n81Flags( 0 ), n81BiDiFlags(0), maWordLR( RES_LR_SPACE ), bValid(false), bImported(false), bColl(false), bImportSkipped(false), bHasStyNumRule(false), bHasBrokenWW6List(false), bListReleventIndentSet(false), bParaAutoBefore(false), bParaAutoAfter(false) {} ~SwWW8StyInf() { delete pWWFly; } void SetOrgWWIdent( const String& rName, const USHORT nId ) { sWWStyleName = rName; nWWStyleId = nId; } const USHORT GetWWStyleId() const { return nWWStyleId; } const String& GetOrgWWName() const { return sWWStyleName; } bool IsOutline() const { return (pFmt && (MAXLEVEL > nOutlineLevel)); } bool IsOutlineNumbered() const { return pOutlineNumrule && IsOutline(); } const SwNumRule* GetOutlineNumrule() const { return pOutlineNumrule; } CharSet GetCharSet() const; }; class WW8RStyle: public WW8Style { friend class SwWW8ImplReader; wwSprmParser maSprmParser; SwWW8ImplReader* pIo; // Parser-Klasse SvStream* pStStrm; // Input-File SwNumRule* pStyRule; // Bullets und Aufzaehlungen in Styles BYTE* pParaSprms; // alle ParaSprms des UPX falls UPX.Papx USHORT nSprmsLen; // Laenge davon BYTE nWwNumLevel; // fuer Bullets und Aufzaehlungen in Styles bool bTxtColChanged; bool bFontChanged; // For Simulating Default-Font bool bCJKFontChanged; // For Simulating Default-CJK Font bool bCTLFontChanged; // For Simulating Default-CTL Font bool bFSizeChanged; // For Simulating Default-FontSize bool bFCTLSizeChanged; // For Simulating Default-CTL FontSize bool bWidowsChanged; // For Simulating Default-Widows / Orphans void ImportSprms(sal_Size nPosFc, short nLen, bool bPap); void ImportSprms(BYTE *pSprms, short nLen, bool bPap); void ImportGrupx(short nLen, bool bPara, bool bOdd); short ImportUPX(short nLen, bool bPAP, bool bOdd); void Set1StyleDefaults(); void Import1Style(USHORT nNr); void RecursiveReg(USHORT nNr); void ImportStyles(); void ImportNewFormatStyles(); void ScanStyles(); void ImportOldFormatStyles(); bool PrepareStyle(SwWW8StyInf &rSI, ww::sti eSti, sal_uInt16 nThisStyle, sal_uInt16 nNextStyle); void PostStyle(SwWW8StyInf &rSI, bool bOldNoImp); //No copying WW8RStyle(const WW8RStyle&); WW8RStyle& operator=(const WW8RStyle&); public: WW8RStyle( WW8Fib& rFib, SwWW8ImplReader* pI ); void Import(); void PostProcessStyles(); const BYTE* HasParaSprm( USHORT nId ) const; }; class WW8FlySet: public SfxItemSet { private: //No copying const WW8FlySet& operator=(const WW8FlySet&); void Init(const SwWW8ImplReader& rReader, const SwPaM* pPaM); public: WW8FlySet(SwWW8ImplReader& rReader, const WW8FlyPara* pFW, const WW8SwFlyPara* pFS, bool bGraf); WW8FlySet(SwWW8ImplReader& rReader, const SwPaM* pPaM, const WW8_PIC& rPic, long nWidth, long nHeight); WW8FlySet(const SwWW8ImplReader& rReader, const SwPaM* pPaM); }; enum WW8LvlType {WW8_None, WW8_Outline, WW8_Numbering, WW8_Sequence, WW8_Pause}; WW8LvlType GetNumType(BYTE nWwLevelNo); #endif /* vi:set tabstop=4 shiftwidth=4 expandtab: */ <commit_msg>INTEGRATION: CWS changefileheader (1.46.242); FILE MERGED 2008/04/01 15:57:59 thb 1.46.242.3: #i85898# Stripping all external header guards 2008/04/01 12:54:51 thb 1.46.242.2: #i85898# Stripping all external header guards 2008/03/31 16:55:51 rt 1.46.242.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ww8par2.hxx,v $ * $Revision: 1.47 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */ #ifndef _WW8PAR2_HXX #define _WW8PAR2_HXX #ifndef SWTYPES_HXX #include <swtypes.hxx> // enum RndStdIds #endif #include <fmtfsize.hxx> #include <fmtornt.hxx> #include <fmtsrnd.hxx> #include <svx/lrspitem.hxx> #ifndef WW8SCAN_HXX #include "ww8scan.hxx" // class WW8Style #endif #ifndef WW8PAR_HXX #include "ww8par.hxx" // WW8_BRC5 #endif class WW8RStyle; class WW8DupProperties { public: WW8DupProperties(SwDoc &rDoc, SwWW8FltControlStack *pStk); void Insert(const SwPosition &rPos); private: //No copying WW8DupProperties(const WW8DupProperties&); WW8DupProperties& operator=(const WW8DupProperties&); SwWW8FltControlStack* pCtrlStck; SfxItemSet aChrSet,aParSet; }; struct WW8FlyPara { // WinWord-Attribute // Achtung: *Nicht* umsortieren, da Teile mit // memcmp verglichen werden bool bVer67; INT16 nSp26, nSp27; // rohe Position INT16 nSp45, nSp28; // Breite / Hoehe INT16 nLeMgn, nRiMgn, nUpMgn, nLoMgn; // Raender BYTE nSp29; // rohe Bindung + Alignment BYTE nSp37; // Wrap-Mode ( 1 / 2; 0 = no Apo ? ) WW8_BRC5 brc; // Umrandung Top, Left, Bottom, Right, Between bool bBorderLines; // Umrandungslinien bool bGrafApo; // true: Dieser Rahmen dient allein dazu, die // enthaltene Grafik anders als zeichengebunden // zu positionieren bool mbVertSet; // true if vertical positioning has been set BYTE nOrigSp29; WW8FlyPara(bool bIsVer67, const WW8FlyPara* pSrc = 0); bool operator==(const WW8FlyPara& rSrc) const; void Read(const BYTE* pSprm29, WW8PLCFx_Cp_FKP* pPap); void ReadFull(const BYTE* pSprm29, SwWW8ImplReader* pIo); void Read(const BYTE* pSprm29, WW8RStyle* pStyle); void ApplyTabPos(const WW8_TablePos *pTabPos); bool IsEmpty() const; }; struct WW8SwFlyPara { SwFlyFrmFmt* pFlyFmt; // 1. Teil: daraus abgeleitete Sw-Attribute INT16 nXPos, nYPos; // Position INT16 nLeMgn, nRiMgn; // Raender INT16 nUpMgn, nLoMgn; // Raender INT16 nWidth, nHeight; // Groesse INT16 nNettoWidth; SwFrmSize eHeightFix; // Hoehe Fix oder Min RndStdIds eAnchor; // Bindung short eHRel; // Seite oder Seitenrand short eVRel; // Seite oder Seitenrand sal_Int16 eVAlign; // Oben, unten, mittig sal_Int16 eHAlign; // links, rechts, mittig SwSurround eSurround; // Wrap-Mode BYTE nXBind, nYBind; // relativ zu was gebunden // 2.Teil: sich waehrend des Einlesens ergebende AEnderungen long nNewNettoWidth; SwPosition* pMainTextPos; // um nach Apo in Haupttext zurueckzukehren USHORT nLineSpace; // LineSpace in tw fuer Graf-Apos bool bAutoWidth; bool bToggelPos; // --> OD 2007-07-03 #148498# // add parameter <nWWPgTop> - WW8's page top margin WW8SwFlyPara( SwPaM& rPaM, SwWW8ImplReader& rIo, WW8FlyPara& rWW, const sal_uInt32 nWWPgTop, const sal_uInt32 nPgLeft, const sal_uInt32 nPgWidth, const INT32 nIniFlyDx, const INT32 nIniFlyDy ); void BoxUpWidth( long nWidth ); SwWW8FltAnchorStack *pOldAnchorStck; }; class SwWW8StyInf { String sWWStyleName; USHORT nWWStyleId; public: rtl_TextEncoding eLTRFontSrcCharSet; // rtl_TextEncoding fuer den Font rtl_TextEncoding eRTLFontSrcCharSet; // rtl_TextEncoding fuer den Font rtl_TextEncoding eCJKFontSrcCharSet; // rtl_TextEncoding fuer den Font SwFmt* pFmt; WW8FlyPara* pWWFly; SwNumRule* pOutlineNumrule; long nFilePos; USHORT nBase; USHORT nFollow; USHORT nLFOIndex; BYTE nListLevel; BYTE nOutlineLevel; // falls Gliederungs-Style sal_uInt16 n81Flags; // Fuer Bold, Italic, ... sal_uInt16 n81BiDiFlags; // Fuer Bold, Italic, ... SvxLRSpaceItem maWordLR; bool bValid; // leer oder Valid bool bImported; // fuers rekursive Importieren bool bColl; // true-> pFmt ist SwTxtFmtColl bool bImportSkipped; // nur true bei !bNewDoc && vorh. Style bool bHasStyNumRule; // true-> Benannter NumRule in Style bool bHasBrokenWW6List; // true-> WW8+ style has a WW7- list bool bListReleventIndentSet; //true if this style's indent has //been explicitly set, it's set to the value //of pFmt->GetItemState(RES_LR_SPACE, false) //if it was possible to get the ItemState //for L of the LR space independantly bool bParaAutoBefore; // For Auto spacing before a paragraph bool bParaAutoAfter; // For Auto Spacing after a paragraph SwWW8StyInf() : sWWStyleName( aEmptyStr ), nWWStyleId( 0 ), eLTRFontSrcCharSet(0), eRTLFontSrcCharSet(0), eCJKFontSrcCharSet(0), pFmt( 0 ), pWWFly( 0 ), pOutlineNumrule( 0 ), nFilePos( 0 ), nBase( 0 ), nFollow( 0 ), nLFOIndex( USHRT_MAX ), nListLevel(WW8ListManager::nMaxLevel), nOutlineLevel( MAXLEVEL ), n81Flags( 0 ), n81BiDiFlags(0), maWordLR( RES_LR_SPACE ), bValid(false), bImported(false), bColl(false), bImportSkipped(false), bHasStyNumRule(false), bHasBrokenWW6List(false), bListReleventIndentSet(false), bParaAutoBefore(false), bParaAutoAfter(false) {} ~SwWW8StyInf() { delete pWWFly; } void SetOrgWWIdent( const String& rName, const USHORT nId ) { sWWStyleName = rName; nWWStyleId = nId; } const USHORT GetWWStyleId() const { return nWWStyleId; } const String& GetOrgWWName() const { return sWWStyleName; } bool IsOutline() const { return (pFmt && (MAXLEVEL > nOutlineLevel)); } bool IsOutlineNumbered() const { return pOutlineNumrule && IsOutline(); } const SwNumRule* GetOutlineNumrule() const { return pOutlineNumrule; } CharSet GetCharSet() const; }; class WW8RStyle: public WW8Style { friend class SwWW8ImplReader; wwSprmParser maSprmParser; SwWW8ImplReader* pIo; // Parser-Klasse SvStream* pStStrm; // Input-File SwNumRule* pStyRule; // Bullets und Aufzaehlungen in Styles BYTE* pParaSprms; // alle ParaSprms des UPX falls UPX.Papx USHORT nSprmsLen; // Laenge davon BYTE nWwNumLevel; // fuer Bullets und Aufzaehlungen in Styles bool bTxtColChanged; bool bFontChanged; // For Simulating Default-Font bool bCJKFontChanged; // For Simulating Default-CJK Font bool bCTLFontChanged; // For Simulating Default-CTL Font bool bFSizeChanged; // For Simulating Default-FontSize bool bFCTLSizeChanged; // For Simulating Default-CTL FontSize bool bWidowsChanged; // For Simulating Default-Widows / Orphans void ImportSprms(sal_Size nPosFc, short nLen, bool bPap); void ImportSprms(BYTE *pSprms, short nLen, bool bPap); void ImportGrupx(short nLen, bool bPara, bool bOdd); short ImportUPX(short nLen, bool bPAP, bool bOdd); void Set1StyleDefaults(); void Import1Style(USHORT nNr); void RecursiveReg(USHORT nNr); void ImportStyles(); void ImportNewFormatStyles(); void ScanStyles(); void ImportOldFormatStyles(); bool PrepareStyle(SwWW8StyInf &rSI, ww::sti eSti, sal_uInt16 nThisStyle, sal_uInt16 nNextStyle); void PostStyle(SwWW8StyInf &rSI, bool bOldNoImp); //No copying WW8RStyle(const WW8RStyle&); WW8RStyle& operator=(const WW8RStyle&); public: WW8RStyle( WW8Fib& rFib, SwWW8ImplReader* pI ); void Import(); void PostProcessStyles(); const BYTE* HasParaSprm( USHORT nId ) const; }; class WW8FlySet: public SfxItemSet { private: //No copying const WW8FlySet& operator=(const WW8FlySet&); void Init(const SwWW8ImplReader& rReader, const SwPaM* pPaM); public: WW8FlySet(SwWW8ImplReader& rReader, const WW8FlyPara* pFW, const WW8SwFlyPara* pFS, bool bGraf); WW8FlySet(SwWW8ImplReader& rReader, const SwPaM* pPaM, const WW8_PIC& rPic, long nWidth, long nHeight); WW8FlySet(const SwWW8ImplReader& rReader, const SwPaM* pPaM); }; enum WW8LvlType {WW8_None, WW8_Outline, WW8_Numbering, WW8_Sequence, WW8_Pause}; WW8LvlType GetNumType(BYTE nWwLevelNo); #endif /* vi:set tabstop=4 shiftwidth=4 expandtab: */ <|endoftext|>
<commit_before>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _T(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD\n see http://heeks.net, or for source code: http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWritten by:\n Dan Heeks\n Jon Pry\n Jonathan George\n David Nicholls")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni\n Perttu Ahola\n Dave ( the archivist )\n mpictor\n fenn\n fungunner2\n andrea ( openSUSE )\n g_code\n Luigi Barbati (Italian translation)\n André Pascual (French translation)")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <commit_msg>problems with the accent on the e. I changed it to a normal "e"<commit_after>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _T(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD\n see http://heeks.net, or for source code: http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWritten by:\n Dan Heeks\n Jon Pry\n Jonathan George\n David Nicholls")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni\n Perttu Ahola\n Dave ( the archivist )\n mpictor\n fenn\n fungunner2\n andrea ( openSUSE )\n g_code\n Luigi Barbati (Italian translation)\n Andre Pascual (French translation)")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmltext.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2004-07-13 09:09:01 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLIMP_HXX #include "xmlimp.hxx" #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::text; // --------------------------------------------------------------------- class SwXMLBodyContentContext_Impl : public SvXMLImportContext { SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); } public: SwXMLBodyContentContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName ); virtual ~SwXMLBodyContentContext_Impl(); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ); // The body element's text:global attribute can be ignored, because // we must have the correct object shell already. virtual void EndElement(); }; SwXMLBodyContentContext_Impl::SwXMLBodyContentContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName ) : SvXMLImportContext( rImport, nPrfx, rLName ) { } SwXMLBodyContentContext_Impl::~SwXMLBodyContentContext_Impl() { } SvXMLImportContext *SwXMLBodyContentContext_Impl::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; pContext = GetSwImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList, XML_TEXT_TYPE_BODY ); if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } void SwXMLBodyContentContext_Impl::EndElement() { /* #108146# Code moved to SwXMLOmport::endDocument */ GetImport().GetTextImport()->SetOutlineStyles(); } SvXMLImportContext *SwXMLImport::CreateBodyContentContext( const OUString& rLocalName ) { SvXMLImportContext *pContext = 0; if( !IsStylesOnlyMode() ) pContext = new SwXMLBodyContentContext_Impl( *this, XML_NAMESPACE_OFFICE, rLocalName ); else pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE, rLocalName ); return pContext; } <commit_msg>INTEGRATION: CWS oasisbf2 (1.10.158); FILE MERGED 2004/10/26 15:02:47 mib 1.10.158.1: #i12228#: store default outline styles<commit_after>/************************************************************************* * * $RCSfile: xmltext.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2004-11-26 13:30:42 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLIMP_HXX #include "xmlimp.hxx" #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::text; // --------------------------------------------------------------------- class SwXMLBodyContentContext_Impl : public SvXMLImportContext { SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); } public: SwXMLBodyContentContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName ); virtual ~SwXMLBodyContentContext_Impl(); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ); // The body element's text:global attribute can be ignored, because // we must have the correct object shell already. virtual void EndElement(); }; SwXMLBodyContentContext_Impl::SwXMLBodyContentContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName ) : SvXMLImportContext( rImport, nPrfx, rLName ) { } SwXMLBodyContentContext_Impl::~SwXMLBodyContentContext_Impl() { } SvXMLImportContext *SwXMLBodyContentContext_Impl::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; pContext = GetSwImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList, XML_TEXT_TYPE_BODY ); if( !pContext ) pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } void SwXMLBodyContentContext_Impl::EndElement() { /* #108146# Code moved to SwXMLOmport::endDocument */ GetImport().GetTextImport()->SetOutlineStyles( sal_False ); } SvXMLImportContext *SwXMLImport::CreateBodyContentContext( const OUString& rLocalName ) { SvXMLImportContext *pContext = 0; if( !IsStylesOnlyMode() ) pContext = new SwXMLBodyContentContext_Impl( *this, XML_NAMESPACE_OFFICE, rLocalName ); else pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE, rLocalName ); return pContext; } <|endoftext|>