repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
LiqCode/PriLib
LIQLib/LIQLib/UINavgition/UINavigationController+lqcNav.h
// // UINavigationController+lqcNav.h // LIQLib // // Created by LQ_MAC on 16/4/22. // Copyright © 2016年 LQ_MAC. All rights reserved. // #import <UIKit/UIKit.h> @interface UINavigationController (lqcNav) + (void)lqc_navRegister; - (void)pushViewControllerAndRemoveTopWithContoller:(UIViewController *)viewController animated:(BOOL)animated; /* * 先pop到classname对应的controller,然后再把controller压进去,使用self来遍历 */ - (void)pushToTopClassName:(NSString *)className withController:(UIViewController *)controller; @end @interface UIViewController (Login) @property (nonatomic, assign ) BOOL needRemoveWhenPushOtherViewController; @end
LiqCode/PriLib
LIQLib/LIQLib/AppDelegate.h
// // AppDelegate.h // LIQLib // // Created by LQ_MAC on 16/4/22. // Copyright © 2016年 LQ_MAC. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
LiqCode/PriLib
LIQLib/LIQLib/LIQRuntime/LQCRuntime.h
// // LQCRuntime.h // LIQLib // // Created by LQ_MAC on 16/4/22. // Copyright © 2016年 LQ_MAC. All rights reserved. // #import <Foundation/Foundation.h> #import <objc/runtime.h> @interface LQCRuntime : NSObject static inline void lqc_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector); static inline BOOL lqc_addMethod(Class theClass, SEL selector, Method method); @end
JHenriksson86/ndt_2d
ndt_eval/include/ndt_eval/transform_handler.h
#ifndef TRANSFORM_HANDLER_H #define TRANSFORM_HANDLER_H // STL #include <iostream> #include <string> #include <sstream> #include <fstream> #include <limits> // ROS #include <ros/ros.h> #include <geometry_msgs/Transform.h> #include <geometry_msgs/TransformStamped.h> #include <tf2_ros/transform_broadcaster.h> #include <tf2_ros/static_transform_broadcaster.h> #include <tf2/LinearMath/Quaternion.h> #include <tf2/convert.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> // Eigen #include "eigen3/Eigen/Geometry" #include "eigen3/Eigen/Dense" namespace ndt2d { class TransformHandler { private: Eigen::Affine3d registration_transform_; Eigen::Affine3d robot_pose_; Eigen::Affine3d odometry_; Eigen::Affine3d old_odometry_; Eigen::Affine3d robot_to_laser_; std::string stamp_; tf2_ros::TransformBroadcaster broadcaster_; tf2_ros::StaticTransformBroadcaster static_broadcaster_; Eigen::Affine3d global_sensor_pose_; public: TransformHandler(); TransformHandler(const Eigen::Affine3d& robot_to_laser); TransformHandler(const TransformHandler& transform); ~TransformHandler(); void setStamp(const std::string& stamp); const std::string& getStamp() const; void setRobotToLaserTransform(const Eigen::Affine3d& robot_to_laser); const Eigen::Affine3d& getRobotToLaserTransform() const; void setRobotPose(const Eigen::Affine3d& pose); const Eigen::Affine3d& getRobotPose() const; void addRegistrationResult(const geometry_msgs::Transform& transform); static geometry_msgs::Transform getInitialGuessMsg( double x, double y, double z, double roll, double pitch, double yaw); geometry_msgs::Transform getInitialGuessMsg() const; geometry_msgs::Transform getTransformMsg() const; geometry_msgs::Transform getGlobalSensorPoseTransformMsg() const; std::string robotPoseToString() const; std::string to_string() const; void loadStamp(const std::string& file_path, int row); void loadOdometry(const std::string& file_path, int row); void broadcastTransform(); void broadcastStaticTransform(); static void transformMessageToEigenTransform( const geometry_msgs::Transform& msg, Eigen::Affine3d& transform_out); static void eigenTransformToTransformMessage( const Eigen::Affine3d& transform, geometry_msgs::Transform& msg_out); EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: std::ifstream& gotoLine(std::ifstream& file, int num); geometry_msgs::TransformStamped getStampedTransform( const Eigen::Affine3d& transform, const std::string& parent_frame, const std::string& child_frame) const; void init(); }; }; #endif
JHenriksson86/ndt_2d
ndt_2d/include/ndt_2d_util.h
<gh_stars>1-10 #ifndef NDT_2D_UTIL_H #define NDT_2D_UTIL_H // STL #include <cmath> #include <sstream> #include <string> // ROS #include "geometry_msgs/Transform.h" // Eigen #include "eigen3/Eigen/Dense" namespace ndt2d { typedef Eigen::Matrix<double, 2, 1, Eigen::DontAlign> UVector2d; typedef Eigen::Matrix<double, 2, 2, Eigen::DontAlign> UMatrix2d; class TransformationVector { private: Eigen::Vector3d vector_; public: TransformationVector() { vector_ = Eigen::Vector3d::Zero(); } TransformationVector(double x, double y, double angle) { vector_ = Eigen::Vector3d(x, y, angle); } TransformationVector(Eigen::Vector3d vector) { this->vector_ = vector; } TransformationVector(geometry_msgs::Transform transform_message) { setTransformation(transform_message); } TransformationVector(const TransformationVector &trans_vector) { this->vector_ = trans_vector.vector_; } double &operator[](unsigned int row) { return vector_[row]; } const double &operator[](unsigned int row) const { return vector_[row]; } TransformationVector operator+(const TransformationVector &obj) const { TransformationVector result; result.vector_ = this->vector_ + obj.vector_; return result; } TransformationVector operator-(const TransformationVector &obj) const { TransformationVector result; result.vector_ = this->vector_ - obj.vector_; return result; } TransformationVector calculateAbsoluteDifference( const TransformationVector &reference) const { Eigen::Vector3d result = this->vector_ + reference.getParameterVector(); result = result.cwiseAbs(); return TransformationVector(result); } void setTransformation(const geometry_msgs::Transform msgs) { vector_[0] = msgs.translation.x; vector_[1] = msgs.translation.y; vector_[2] = std::asin(msgs.rotation.z) * 2.0; } void setTransformationParameters(const double *array) { for (int i = 0; i < vector_.size(); i++) { vector_[i] = *(array + i); } } geometry_msgs::Transform getTransformMessage() const { geometry_msgs::Transform msg; msg.translation.x = vector_[0]; msg.translation.y = vector_[1]; msg.translation.z = 0.0; msg.rotation.x = 0.0; msg.rotation.y = 0.0; msg.rotation.z = std::sin(vector_[2] / 2.0); msg.rotation.w = std::cos(vector_[2] / 2.0); return msg; } UMatrix2d getRotationMatrix() const { double angle = vector_[2]; UMatrix2d rot_matrix; rot_matrix << std::cos(angle), -std::sin(angle), std::sin(angle), std::cos(angle); return rot_matrix; } UVector2d getTranslationVector() const { return UVector2d(vector_[0], vector_[1]); } const Eigen::Vector3d &getParameterVector() const { return vector_; } void getParameterArray(double *out_array) { for (int i = 0; i < vector_.size(); i++) { *(out_array + i) = vector_[i]; } } double getX() const { return vector_[0]; } double getY() const { return vector_[1]; } double getRotation() const { return vector_[2]; } std::string to_string() const { std::stringstream ss; ss << vector_[0] << "," << vector_[1] << "," << vector_[2]; return ss.str(); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; class Gaussian { private: UVector2d mean_; UMatrix2d covariance_; public: Gaussian() { this->mean_ = UVector2d::Zero(); this->covariance_ = UMatrix2d::Zero(); } Gaussian(UVector2d mean, UMatrix2d covariance) { this->mean_ = mean; this->covariance_ = covariance; } Gaussian(const Gaussian &gaussian) { this->mean_ = gaussian.mean_; this->covariance_ = gaussian.covariance_; } const UVector2d &getMean() const { return mean_; } const UMatrix2d &getCovariance() const { return covariance_; } void setMean(const UVector2d &mean) { this->mean_ = mean; } void setCovariance(const UMatrix2d &covariance) { this->covariance_ = covariance; } void transform(const TransformationVector &transformation) { Gaussian temp = getTransformed(transformation); this->mean_ = temp.getMean(); this->covariance_ = temp.getCovariance(); } Gaussian getTransformed(const TransformationVector &transformation) const { UVector2d mean = transformation.getRotationMatrix() * this->mean_ + transformation.getTranslationVector(); UMatrix2d rot_matrix = transformation.getRotationMatrix(); UMatrix2d covariance = rot_matrix.transpose() * this->covariance_ * rot_matrix; return Gaussian(mean, covariance); } static void matchClosestGaussians(std::vector<Gaussian> *in_out_m1, std::vector<Gaussian> *in_out_m2) { int number_of_gaussians; std::vector<Gaussian> *m1; std::vector<Gaussian> *m2; bool m1_smallest; if (in_out_m1->size() <= in_out_m2->size()) { number_of_gaussians = in_out_m1->size(); m1 = in_out_m1; m2 = in_out_m2; m1_smallest = true; } else { number_of_gaussians = in_out_m2->size(); m1 = in_out_m2; m2 = in_out_m1; m1_smallest = false; } std::vector<Gaussian> sorted_gaussians; for (int i = 0; i < number_of_gaussians; i++) { sorted_gaussians.push_back( takeClosestGaussian(m1->at(i), m2)); } if (m1_smallest) *in_out_m2 = sorted_gaussians; else *in_out_m1 = sorted_gaussians; } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: static Gaussian takeClosestGaussian(const Gaussian &gaussian, std::vector<Gaussian> *gaussians) { double best_score = DBL_MAX; int best_index = 0; UVector2d fixed_mean = gaussian.getMean(); //UMatrix2d fixed_cov = gaussian.getCovariance(); for (unsigned int i = 0; i < gaussians->size(); i++) { UVector2d movable_mean = gaussians->at(i).getMean(); //UMatrix2d movable_cov = gaussians->at(i).getCovariance(); double score = std::sqrt( std::pow(fixed_mean[0] - movable_mean[0], 2) + std::pow(fixed_mean[1] - movable_mean[1], 2)); if (score < best_score) { best_score = score; best_index = i; } } Gaussian result = gaussians->at(best_index); ROS_DEBUG_STREAM("Closest gaussian result:\n" << "best_score: " << best_score << "\n" << "mean:\n" << result.getMean() << "\n" << gaussian.getMean() << "\n" << "covariance:\n" << result.getCovariance() << "\n" << gaussian.getCovariance()); gaussians->erase(gaussians->begin() + best_index); return result; } }; }; // namespace ndt2d #endif
JHenriksson86/ndt_2d
ndt_2d/include/ndt_2d_math.h
#ifndef NDT_2D_MATH_H #define NDT_2D_MATH_H #include <ros/ros.h> #include "ndt_2d_util.h" #include "eigen3/Eigen/Dense" #include <cmath> #include <cfloat> #include <iostream> namespace ndt2d { struct StepMath { static Eigen::Vector2d calcMeanVector(const Gaussian& movable_point, const Gaussian& fixed_point) { return movable_point.getMean() - fixed_point.getMean(); } static Eigen::Matrix<double,2,3> gradMeanVector(const Gaussian& movable_point) { Eigen::Vector2d mean = movable_point.getMean(); Eigen::Matrix<double,2,3> result; result << 1.0, 0.0, -mean[1], 0.0, 1.0, mean[0]; return result; } static Eigen::Matrix<double,6,3> hessianMeanVector(const Gaussian& movable_point) { Eigen::Vector2d mean = movable_point.getMean(); Eigen::Matrix<double,6,3> result = Eigen::Matrix<double,6,3>::Zero(); result(4,2) = -mean[0]; result(5,2) = -mean[1]; return result; } static Eigen::Matrix2d calcB(const Gaussian& movable_point, const Gaussian& fixed_point) { Eigen::Matrix2d cov_sum = movable_point.getCovariance() + fixed_point.getCovariance(); Eigen::Matrix2d result; bool invertible; cov_sum.computeInverseWithCheck(result, invertible); if(!invertible) ROS_ERROR("B matrix not invertible!"); return result; } static Eigen::Matrix<double,2,6> gradB(const Gaussian& movable_point) { Eigen::Matrix2d cov = movable_point.getCovariance(); double xx = cov(0,0); double xy = cov(0,1); double yy = cov(1,1); Eigen::Matrix<double,2,6> result = Eigen::Matrix<double,2,6>::Zero(); result(0,4) = 2.0*xy; result(0,5) = yy-xx; result(1,4) = result(0,5); result(1,5) = -2.0*xy; return result; } static Eigen::Matrix<double,6,6> hessianB(const Gaussian& movable_point) { Eigen::Matrix2d cov = movable_point.getCovariance(); double xx = cov(0,0); double xy = cov(0,1); double yy = cov(1,1); Eigen::Matrix<double,6,6> result = Eigen::Matrix<double,6,6>::Zero(); result(4,4) = 2.0*(yy-xx); result(4,5) = -4.0*xy; result(5,4) = result(4,5); result(5,5) = 2.0*(xx-yy); return result; } static Eigen::Vector3d q(const Gaussian& movable_point, const Eigen::Vector2d& mean_vector, const Eigen::Matrix2d& B) { Eigen::Matrix<double,2,3> J = gradMeanVector(movable_point); Eigen::Matrix<double,2,6> Z = gradB(movable_point); ROS_DEBUG_STREAM("q input:\n" << "mean_vector:\n" << mean_vector << std::endl << "B:\n" << B << std::endl << "J:\n" << J << std::endl << "Z:\n" << Z ); Eigen::Vector3d result(0.0, 0.0, 0.0); for(int i = 0; i < result.size(); i++) { Eigen::Vector2d J_temp = J.block<2,1>(0,i); Eigen::Matrix2d Z_temp = Z.block<2,2>(0,i*2); double exp1 = mean_vector.transpose()*B*J_temp; double exp2 = mean_vector.transpose()*B*Z_temp*B*mean_vector; result[i] = 2.0*exp1 - exp2; } ROS_DEBUG_STREAM("q result: \n" << result); return result; } static double calculateMeanCost(std::vector<Gaussian>& fixed_gaussians, std::vector<Gaussian>& movable_gaussians, Eigen::Vector3d* out_mean_gradient, Eigen::Matrix3d* out_mean_hessian) { if(fixed_gaussians.size() != movable_gaussians.size()) { ROS_ERROR("Fixed (%d) and movable (%d) gaussians are not equal", (int)fixed_gaussians.size(), (int)movable_gaussians.size()); return 0.0; } double total_cost = 0.0; Eigen::Vector3d cost_gradient = Eigen::Vector3d::Zero(); Eigen::Matrix3d cost_hessian = Eigen::Matrix3d::Zero(); for(unsigned int i = 0; i < fixed_gaussians.size(); i++) { Gaussian fixed = fixed_gaussians[i]; Gaussian movable = movable_gaussians[i]; Eigen::Vector2d mean_vector = calcMeanVector(movable, fixed); Eigen::Matrix2d B = calcB(movable, fixed); total_cost += calcObjectiveFunction(mean_vector, B); Eigen::Vector3d q_ = q(movable, mean_vector, B); cost_gradient += gradObjectiveFunction(mean_vector, B, q_); cost_hessian += hessianObjectiveFunction(movable, fixed, mean_vector, B, q_); } double N = (double)fixed_gaussians.size(); *out_mean_gradient = cost_gradient * (1.0/N); *out_mean_hessian = cost_hessian * (1.0/N); return total_cost * (1.0/N); } static double calcObjectiveFunction(const Eigen::Vector2d& mean_vector, const Eigen::Matrix2d& B, double d1 = 1.0, double d2 = 0.05) { return -d1*std::exp( (-d2/2.0)*mean_vector.transpose()*B*mean_vector ); } static Eigen::Vector3d gradObjectiveFunction(const Eigen::Vector2d& mean_vector, const Eigen::Matrix2d& B, const Eigen::Vector3d& q, double d1 = 1.0, double d2 = 0.05) { double exponent = std::exp( (-d2/2.0)*mean_vector.transpose()*B*mean_vector ); double scaling = d1*d2/2.0; Eigen::Vector3d result = scaling * q * exponent; ROS_DEBUG_STREAM("gradObjectiveFunction result\n" << result); return result; } static Eigen::Matrix3d hessianObjectiveFunction(const Gaussian& movable_point, const Gaussian& fixed_point, const Eigen::Vector2d& mean_vector, const Eigen::Matrix2d& B, const Eigen::Vector3d& q, double d1 = 1.0, double d2 = 0.05) { Eigen::Matrix<double,6,3> Hab = hessianMeanVector(movable_point); Eigen::Matrix<double,6,6> Zab = hessianB(movable_point); Eigen::Matrix<double,2,3> Ja = gradMeanVector(movable_point); Eigen::Matrix<double,2,6> Za = gradB(movable_point); Eigen::Matrix<double,2,6> Zb = gradB(fixed_point); Eigen::Matrix<double,1,2> mean_transpose = mean_vector.transpose(); const double exponent = std::exp( (-d2/2.0)*mean_transpose*B*mean_vector ); ROS_DEBUG_STREAM("hessianObjectiveFunction\n" << "exponent: " << exponent << "\n" << "mean:\n" << mean_vector << "\n" << "B:\n" << B << "\n" << "Ja:\n" << Ja << "\n" << "Za:\n" << Za << "\n" << "Zb:\n" << Zb << "\n" << "Hab:\n" << Hab << "\n" << "Zab:\n" << Zab ); Eigen::Matrix3d result = Eigen::Matrix3d::Zero(); for(int row = 0; row < result.rows(); row++) { Eigen::Vector2d temp_Ja = Ja.block<2,1>(0,row); Eigen::Matrix2d temp_Za = Za.block<2,2>(0,row*2); double exp1 = temp_Ja.transpose() * B * temp_Ja; exp1 -= 2.0 * mean_transpose * B * temp_Za * temp_Ja; for(int col = 0; col < result.cols(); col++) { double exp2 = exp1; Eigen::Vector2d temp_Hab = Hab.block<2,1>(row*2, col); exp2 += mean_transpose * B * temp_Hab; Eigen::Matrix2d temp_Zb = Zb.block<2,2>(0, col*2); exp2 -= mean_transpose * B * temp_Za * B * temp_Zb * B * mean_vector; Eigen::Matrix2d temp_Zab = Zab.block<2,2>(row*2, col*2); exp2 -= 0.5 * mean_transpose * B * temp_Zab * B * mean_vector; exp2 -= (d2/4.0) * q.transpose() * q; result(row,col) = d1*d2* exp2 * exponent; } } ROS_DEBUG_STREAM("hessianObjectiveFunction result\n" << result); return result; } }; struct StandardMath { static Eigen::Vector2d calcMeanVector(const Gaussian& movable_point, const Gaussian& fixed_point, const TransformationVector& trans) { Gaussian temp_move = movable_point.getTransformed(trans); return temp_move.getMean() - fixed_point.getMean(); } static Eigen::Matrix2d calcB(const Gaussian& movable_point, const Gaussian& fixed_point, const TransformationVector& trans) { Gaussian temp_move = movable_point.getTransformed(trans); Eigen::Matrix2d cov_sum = temp_move.getCovariance() + fixed_point.getCovariance(); Eigen::Matrix2d result; bool invertible; cov_sum.computeInverseWithCheck(result, invertible); if(!invertible) ROS_ERROR("B matrix not invertible!"); ROS_DEBUG_STREAM("calcB:\n" << "result*cov_sum:\n" << result*cov_sum ); return result; } static Eigen::Matrix<double,2,3> gradMeanVector(const Gaussian& movable_point, const TransformationVector& trans) { double s_rz = std::sin(trans.getRotation()); double c_rz = std::cos(trans.getRotation()); Eigen::Vector2d mean = movable_point.getMean(); Eigen::Matrix<double,2,3> result; result << 1.0, 0.0, -mean[0]*s_rz -mean[1]*c_rz, 0.0, 1.0, mean[0]*c_rz-mean[1]*s_rz; ROS_DEBUG_STREAM("gradMeanVector:\n" << "mean:\n" << mean << "\n" << "rz:" << trans.getRotation() << "\n" << "result:\n" << result ); return result; } static Eigen::Matrix<double,2,6> gradB(const Gaussian& movable_point, const TransformationVector& trans) { double s_rz = std::sin(trans.getRotation()); double c_rz = std::cos(trans.getRotation()); Eigen::Matrix2d rot_matrix = trans.getRotationMatrix(); Eigen::Matrix2d d_rot_matrix; d_rot_matrix << -s_rz, -c_rz, c_rz, -s_rz; Eigen::Matrix2d cov = movable_point.getCovariance(); Eigen::Matrix<double,2,6> result = Eigen::Matrix<double,2,6>::Zero(); result.block<2,2>(0,4) = d_rot_matrix.transpose()*cov*rot_matrix + rot_matrix.transpose()*cov*d_rot_matrix; ROS_DEBUG_STREAM("gradB:\n" << result); return result; } static Eigen::Vector3d q(const Gaussian& movable_point, const TransformationVector& trans, const Eigen::Vector2d& mean_vector, const Eigen::Matrix2d& B) { Eigen::Matrix<double,2,3> J = gradMeanVector(movable_point, trans); Eigen::Matrix<double,2,6> Z = gradB(movable_point, trans); ROS_DEBUG_STREAM("q input:\n" << "mean_vector:\n" << mean_vector << std::endl << "B:\n" << B << std::endl << "J:\n" << J << std::endl << "Z:\n" << Z ); Eigen::Vector3d result(0.0, 0.0, 0.0); for(int i = 0; i < result.size(); i++) { Eigen::Vector2d J_temp = J.block<2,1>(0,i); Eigen::Matrix2d Z_temp = Z.block<2,2>(0,i*2); double exp1 = mean_vector.transpose()*B*J_temp; double exp2 = mean_vector.transpose()*B*Z_temp*B*mean_vector; ROS_DEBUG_STREAM("q loop" << i << ":\n" "J_temp:\n" << J_temp << std::endl << "Z_temp:\n" << Z_temp << std::endl << "exp1:" << exp1 << std::endl << "exp2:" << exp2 ); result[i] = 2.0*exp1 - exp2; } ROS_DEBUG_STREAM("q result: \n" << result); return result; } static double calcLikelyhood(const Eigen::Vector2d& mean_vector, const Eigen::Matrix2d& B, double d1 = 1.0, double d2 = 0.05) { //Eigen::Matrix<double,1,2> mean_t = mean_vector.transpose(); return std::exp((-d2/2.0)*mean_vector.dot(B*mean_vector)); } static double calcCost(const Eigen::Vector2d& mean_vector, const Eigen::Matrix2d& B, double d1 = 1.0) { return -d1*calcLikelyhood(mean_vector, B); } static Eigen::Vector3d calcGradient(const Eigen::Vector2d& mean_vector, const Eigen::Matrix2d& B, const Eigen::Vector3d& q, double d1 = 1.0, double d2 = 0.05) { double scaling = d1*d2/2.0; Eigen::Vector3d result = scaling * q * calcLikelyhood(mean_vector, B); ROS_DEBUG_STREAM("gradObjectiveFunction result\n" << result); return result; } }; }; #endif
JHenriksson86/ndt_2d
ndt_2d/include/ndt_2d_scan.h
<filename>ndt_2d/include/ndt_2d_scan.h #ifndef NDT_2D_SCAN_H #define NDT_2D_SCAN_H // STL #include <iostream> #include <vector> #include <cmath> #include <fstream> #include <string> // PCL //#include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/PCLPointCloud2.h> //#include <pcl/common/transforms.h> // ROS #include <ros/ros.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/PointCloud2.h> #include <visualization_msgs/Marker.h> // Eigen #include "eigen3/Eigen/Dense" #include "eigen3/Eigen/Geometry" // NDT #include "ndt_2d_util.h" namespace ndt2d { class LaserScanPoint { private: UVector2d polar_coordinates_; UVector2d cart_coordinates_; public: LaserScanPoint() { polar_coordinates_ = UVector2d::Zero(); cart_coordinates_ = UVector2d::Zero(); } LaserScanPoint(double distance, double angle) { this->setPolarCoordinates(distance, angle); } LaserScanPoint(const LaserScanPoint &point) { this->polar_coordinates_ = point.polar_coordinates_; this->cart_coordinates_ = point.cart_coordinates_; } void setPolarCoordinates(double distance, double angle) { polar_coordinates_ << distance, angle; cart_coordinates_ << distance * std::cos(angle), distance * std::sin(angle); } void setCartesianCoordinates(double x, double y) { cart_coordinates_ << x, y; polar_coordinates_ << std::sqrt(std::pow(x, 2) + std::pow(y, 2)), std::atan2(y, x); } UVector2d getCartesianCoordinates() const { return cart_coordinates_; } void transform(const TransformationVector &trans) { UVector2d coordinates = trans.getRotationMatrix() * cart_coordinates_ + trans.getTranslationVector(); this->setCartesianCoordinates(coordinates[0], coordinates[1]); } LaserScanPoint getTransformed(const TransformationVector &trans) const { UVector2d coordinates = trans.getRotationMatrix() * cart_coordinates_ + trans.getTranslationVector(); LaserScanPoint result; result.setCartesianCoordinates(coordinates[0], coordinates[1]); return result; } double getDistance() const { return polar_coordinates_[0]; } double getAngle() const { return polar_coordinates_[1]; } double getX() const { return cart_coordinates_[0]; } double getY() const { return cart_coordinates_[1]; } ~LaserScanPoint() {} EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; class LaserScan { private: std::vector<LaserScanPoint> points_; public: LaserScan() { points_.reserve(720); } LaserScan(const LaserScan &scan) { for (unsigned int i = 0; i < scan.size(); i++) { points_.push_back(scan.points_[i]); } } void clear() { points_.clear(); } void push_back(const LaserScanPoint &point) { points_.push_back(point); } void transform(const TransformationVector &trans) { for (unsigned int i = 0; i < points_.size(); i++) { points_[i].transform(trans); } } LaserScan getTransformed(const TransformationVector &trans) const { LaserScan result; for (unsigned int i = 0; i < points_.size(); i++) { result.push_back(points_[i].getTransformed(trans)); } return result; } void addScanMessage(const sensor_msgs::LaserScan::ConstPtr &msg) { for (unsigned int i = 0; i < msg->ranges.size(); i++) { if (msg->ranges[i] > 0.0) { double angle = msg->angle_min + msg->angle_increment * (double)i; double distance = msg->ranges[i]; LaserScanPoint point(distance, angle); points_.push_back(point); } } } unsigned int size() const { return points_.size(); } const LaserScanPoint &operator[](unsigned int index) const { return points_[index]; } LaserScanPoint &operator[](unsigned int index) { return points_[index]; } bool saveLaserScan(const std::string &filename, const std::string &path = "") { std::string output_filename = path + "/" + filename + ".scan"; ROS_INFO("Saving data to %s", output_filename.c_str()); std::ofstream output; output.open(output_filename.c_str(), std::ofstream::out | std::ofstream::trunc); for (unsigned int i = 0; i < points_.size(); i++) { output << points_[i].getX() << "," << points_[i].getY() << std::endl; } output.close(); return true; } bool loadLaserScan(const std::string &filename, const std::string &path = "") { std::string input_filename = path + "/" + filename + ".scan"; ROS_INFO("Loading data from %s", input_filename.c_str()); std::ifstream input; input.open(input_filename.c_str(), std::ifstream::in); bool load_ok = true; while (load_ok) { std::string x, y; std::getline(input, x, ','); std::getline(input, y); load_ok = input.good(); if (load_ok) { double x_cord = std::stod(x); double y_cord = std::stod(y); LaserScanPoint point; point.setCartesianCoordinates(x_cord, y_cord); points_.push_back(point); } else if (input.eof()) { ROS_INFO("End of file reached."); } else { ROS_ERROR("Something went wrong with load."); } } input.close(); return true; } visualization_msgs::Marker createMarker(double red, double green, double blue) { visualization_msgs::Marker marker; marker.header.frame_id = "world"; marker.header.stamp = ros::Time::now(); marker.ns = "my_namespace"; marker.id = 0; marker.type = visualization_msgs::Marker::POINTS; marker.action = visualization_msgs::Marker::ADD; marker.pose.position.x = 0.0; marker.pose.position.y = 0.0; marker.pose.position.z = 0.0; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; marker.scale.x = 0.1; marker.scale.y = 0.1; marker.scale.z = 0.1; marker.color.a = 1.0; // Don't forget to set the alpha! marker.color.r = red; marker.color.g = green; marker.color.b = blue; for (unsigned int i = 0; i < points_.size(); i++) { if (points_[i].getDistance() > 0.0) { geometry_msgs::Point point; point.x = points_[i].getX(); point.y = points_[i].getY(); point.z = 0.0; marker.points.push_back(point); } } return marker; } EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; class PointCloud2d { private: typedef pcl::PointCloud<pcl::PointXYZ> PointCloud; PointCloud cloud_; std::string frame_; public: PointCloud2d(std::string frame = "world") { this->frame_ = frame; } PointCloud2d(const sensor_msgs::PointCloud2& pc2_message, std::string frame = "world") { this->frame_ = frame; setPointCloud(pc2_message); } ~PointCloud2d(){} int numberOfPoints() const { return int(cloud_.size()); } UVector2d at(std::size_t n) const { pcl::PointXYZ point = cloud_.at(n); return UVector2d(point.x, point.y); } void setPointCloud(const sensor_msgs::PointCloud2& pc2_message) { pcl::fromROSMsg(pc2_message, cloud_); } private: }; } // namespace ndt2d #endif
JHenriksson86/ndt_2d
ndt_2d/include/ndt_2d_registration_old.h
<filename>ndt_2d/include/ndt_2d_registration_old.h #ifndef NDT_2D_REG_NODE_H #define NDT_2D_REG_NODE_H #include <ros/ros.h> #include "eigen3/Eigen/Dense" #include "ceres/ceres.h" #include "glog/logging.h" #include "ndt_2d_map.h" #include "ndt_2d_scan.h" #include "ndt_2d_math.h" #include <cmath> #include <cfloat> #include <iostream> namespace ndt2d { class NDTRegistration { private: NDTMap* fixed_scan_; NDTMap* movable_scan_; TransformationVector trans_vector_; Math math_; double d1_; double d2_; unsigned int max_iterations_; double step_size_; public: NDTRegistration(double max_iterations, double step_size = 0.1, double d1 = 1.0, double d2 = 0.05) { this->d1_ = d1; this->d2_ = d2; this->math_ = Math(d1, d2); this->max_iterations_ = max_iterations; this->step_size_ = step_size; } void setMaps(NDTMap* fixed_scan, NDTMap* movable_scan) { this->fixed_scan_ = fixed_scan; this->movable_scan_ = movable_scan; } void setTransformation(TransformationVector vector) { this->trans_vector_ = vector; } TransformationVector getTransformation() { return trans_vector_; } void optimize() { std::vector<Gaussian> fixed_gaussians = fixed_scan_->getGaussianVector(); std::vector<Gaussian> movable_gaussians = movable_scan_->getGaussianVector(); //Match closest gaussians ROS_DEBUG("Before matching: Fixed gaussians size %d, Movable gaussians size %d", (int)fixed_gaussians.size(), (int)movable_gaussians.size()); matchClosestGaussians(&fixed_gaussians, &movable_gaussians); ROS_DEBUG("After matching: Fixed gaussians size %d, Movable gaussians size %d", (int)fixed_gaussians.size(), (int)movable_gaussians.size()); int iterations = 1; TransformationVector best_transformation = trans_vector_; double best_cost = DBL_MAX; while(true) { //Calculate cost, gradient and hessian Eigen::Vector3d gradient; Eigen::Matrix3d hessian; double cost = math_.calculateMeanCost(fixed_gaussians, movable_gaussians, &gradient, &hessian); if(cost < best_cost && cost != 0.0) { best_transformation = trans_vector_; best_cost = cost; } Eigen::Matrix3d hessian_inverse = Eigen::Matrix3d::Zero(); bool invertible = false; //hessian.computeInverseWithCheck(hessian_inverse, invertible); if(!invertible) { ROS_WARN("Hessian not invertible, testing pseudoinverse."); Eigen::MatrixXd dynamic_hessian = hessian; Eigen::JacobiSVD<Eigen::MatrixXd> svd( dynamic_hessian, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::Vector3d singular = svd.singularValues(); Eigen::Matrix3d u = svd.matrixU(); Eigen::Matrix3d u_inv = u.inverse(); Eigen::Matrix3d v = svd.matrixV(); ROS_INFO_STREAM("Singular value decomposition result:\n" << "S:\n" << singular << "\n" << "V:\n" << v << "\n" << "U:\n" << u << "\n" << "U*:\n" << u_inv); Eigen::Matrix3d singular_matrix = Eigen::Matrix3d::Zero(); for(int i = 0; i < singular.size(); i++) { if(singular(i) > 0.01) singular_matrix(i,i) = 1.0 / singular(i); else singular_matrix(i,i) = singular(i); } hessian_inverse = v*singular_matrix*u_inv; Eigen::Matrix3d error = hessian * hessian_inverse; ROS_INFO_STREAM("Pseudoinverse result:\n" << hessian_inverse << "\n" << "Error:\n" << error); if(!invertible) { ROS_ERROR("Pseudo inverse failed also quitting!"); break; } hessian_inverse = hessian_inverse * hessian.transpose(); } ROS_INFO("Cost: %.2f", cost); ROS_INFO_STREAM("Gradient: \n" << gradient); ROS_INFO_STREAM("Hessian: \n" << hessian); //ROS_INFO_STREAM("Hessian inverse: \n" << hessian_inverse); Eigen::Vector3d newton_result = hessian_inverse * gradient; //Eigen::Vector3d newton_result = hessian.fullPivHouseholderQr().solve(gradient); double relative_error = (hessian * newton_result - gradient).norm() / gradient.norm(); ROS_INFO_STREAM("Newton result:\n" << newton_result << "\n" << "Relative error: " << relative_error); Eigen::Vector3d scaled_transform = newton_result * (-1.0) * step_size_; TransformationVector transformation(scaled_transform); //Apply newton result for(int i = 0; i < movable_gaussians.size(); i++) { movable_gaussians[i].transform(transformation); } trans_vector_ = trans_vector_ + transformation; ROS_INFO_STREAM("Optimization iteration nr: " << iterations << " result: \n" << newton_result); iterations++; if(iterations > max_iterations_) break; if(newton_result[0] > 100.0 || newton_result[0] < -100.0) break; if(newton_result[1] > 100.0 || newton_result[1] < -100.0) break; if(newton_result[2] > 100.0 || newton_result[2] < -100.0) break; } trans_vector_ = best_transformation; } void matchClosestGaussians(std::vector<Gaussian>* in_out_m1, std::vector<Gaussian>* in_out_m2) { int number_of_gaussians; std::vector<Gaussian>* m1; std::vector<Gaussian>* m2; bool m1_smallest; if(in_out_m1->size() <= in_out_m2->size()) { number_of_gaussians = in_out_m1->size(); m1 = in_out_m1; m2 = in_out_m2; m1_smallest = true; } else { number_of_gaussians = in_out_m2->size(); m1 = in_out_m2; m2 = in_out_m1; m1_smallest = false; } std::vector<Gaussian> sorted_gaussians; for(int i = 0; i < number_of_gaussians; i++) { sorted_gaussians.push_back( takeClosestGaussian(m1->at(i), m2) ); } if(m1_smallest) *in_out_m2 = sorted_gaussians; else *in_out_m1 = sorted_gaussians; } private: Gaussian takeClosestGaussian(const Gaussian& gaussian, std::vector<Gaussian>* gaussians) { double best_score = DBL_MAX; int best_index = 0; Eigen::Vector2d fixed_mean = gaussian.getMean(); Eigen::Matrix2d fixed_cov = gaussian.getCovariance(); for(int i = 0; i < gaussians->size(); i++) { Eigen::Vector2d movable_mean = gaussians->at(i).getMean(); Eigen::Matrix2d movable_cov = gaussians->at(i).getCovariance(); double score = std::sqrt( std::pow(fixed_mean[0]-movable_mean[0],2) + std::pow(fixed_mean[1]-movable_mean[1],2) ); if(score < best_score) { best_score = score; best_index = i; } } Gaussian result = gaussians->at(best_index); ROS_DEBUG_STREAM("Closest gaussian result:\n" << "best_score: " << best_score << "\n" << "mean:\n" << result.getMean() << "\n" << gaussian.getMean() << "\n" << "covariance:\n" << result.getCovariance() << "\n" << gaussian.getCovariance() ); gaussians->erase(gaussians->begin() + best_index); return result; } }; }; #endif
JHenriksson86/ndt_2d
ndt_2d/include/ndt_2d_registration.h
#ifndef NDT_2D_REG_CERES_H #define NDT_2D_REG_CERES_H #include <ros/ros.h> #include "eigen3/Eigen/Dense" #include "ceres/ceres.h" #include "glog/logging.h" #include "ndt_2d_math.h" #include "ndt_2d_map.h" #include "ndt_2d_scan.h" #include <cmath> #include <cfloat> #include <iostream> #include <sstream> #include <string> namespace ndt2d { class NDT2DStandardCost : public ceres::FirstOrderFunction { private: NDTMap *fixed_scan_; NDTMap *movable_scan_; std::vector<Gaussian> fixed_gaussians_; std::vector<Gaussian> movable_gaussians_; const double d1_; const double d2_; public: NDT2DStandardCost( NDTMap *fixed_scan, NDTMap *movable_scan, double d1 = 1.0, double d2 = 0.05, double rematch_limit = 0.5) : d1_(d1), d2_(d2) { this->fixed_scan_ = fixed_scan; this->movable_scan_ = movable_scan; matchGaussians(); } virtual ~NDT2DStandardCost() {} virtual bool Evaluate(const double *parameters, double *cost, double *gradient) const { double tx = parameters[0]; double ty = parameters[1]; double rz = parameters[2]; TransformationVector trans(tx, ty, rz); //Check for jacobians bool grad = false; if (gradient != NULL) { grad = true; } double cost_sum = 0.0; Eigen::Vector3d grad_sum = Eigen::Vector3d::Zero(); for (unsigned int i = 0; i < fixed_gaussians_.size(); i++) { Eigen::Vector2d mean_vector = StandardMath::calcMeanVector( movable_gaussians_[i], fixed_gaussians_[i], trans); Eigen::Matrix2d B = StandardMath::calcB( movable_gaussians_[i], fixed_gaussians_[i], trans); double cost = StandardMath::calcCost(mean_vector, B, d1_); cost_sum += cost; //std::cout << "cost: " << cost_sum << "\n"; if (grad) { Eigen::Vector3d q_vec = StandardMath::q( movable_gaussians_[i], trans, mean_vector, B); Eigen::Vector3d gradient = StandardMath::calcGradient( mean_vector, B, q_vec, d1_, d2_); grad_sum += gradient; } } cost[0] = cost_sum; if (grad) { gradient[0] = grad_sum(0); gradient[1] = grad_sum(1); gradient[2] = grad_sum(2); } return true; } virtual int NumParameters() const { return 3; } private: void matchGaussians() { this->fixed_gaussians_ = fixed_scan_->getGaussianVector(); this->movable_gaussians_ = movable_scan_->getGaussianVector(); ROS_INFO("Before matching: Fixed gaussians size %d, Movable gaussians size %d", (int)fixed_gaussians_.size(), (int)movable_gaussians_.size()); Gaussian::matchClosestGaussians(&fixed_gaussians_, &movable_gaussians_); ROS_INFO("After matching: Fixed gaussians size %d, Movable gaussians size %d", (int)fixed_gaussians_.size(), (int)movable_gaussians_.size()); } }; class NDT2DStepCost : public ceres::FirstOrderFunction { private: NDTMap *fixed_scan_; NDTMap *movable_scan_; std::vector<Gaussian> fixed_gaussians_; std::vector<Gaussian> movable_gaussians_; const double d1_; const double d2_; public: NDT2DStepCost( NDTMap *fixed_scan, NDTMap *movable_scan, double d1 = 1.0, double d2 = 0.05, double rematch_limit = 0.5) : d1_(d1), d2_(d2) { this->fixed_scan_ = fixed_scan; this->movable_scan_ = movable_scan; matchGaussians(); } virtual ~NDT2DStepCost() {} virtual bool Evaluate(const double *parameters, double *cost, double *gradient) const { double tx = parameters[0]; double ty = parameters[1]; double rz = parameters[2]; TransformationVector trans_parameters(tx, ty, rz); std::vector<Gaussian> transformed_movable_gaussians = this->movable_gaussians_; //Transform gaussians according to new parameters //ROS_INFO_STREAM("Movable transformation " << trans_parameters.to_string()); for (unsigned int i = 0; i < movable_gaussians_.size(); i++) { transformed_movable_gaussians[i].transform(trans_parameters); } //Check for jacobians bool grad = false; if (gradient != NULL) { grad = true; } double cost_sum = 0.0; Eigen::Vector3d grad_sum = Eigen::Vector3d::Zero(); for (unsigned int i = 0; i < fixed_gaussians_.size(); i++) { Eigen::Vector2d mean_vector = StepMath::calcMeanVector( transformed_movable_gaussians[i], fixed_gaussians_[i]); Eigen::Matrix2d B = StepMath::calcB( transformed_movable_gaussians[i], fixed_gaussians_[i]); double cost = StepMath::calcObjectiveFunction(mean_vector, B, d1_, d2_); cost_sum += cost; //std::cout << "cost: " << cost_sum << "\n"; if (grad) { Eigen::Vector3d q_vec = StepMath::q( transformed_movable_gaussians[i], mean_vector, B); Eigen::Vector3d gradient = StepMath::gradObjectiveFunction( mean_vector, B, q_vec, d1_, d2_); grad_sum += gradient; } } cost[0] = cost_sum; if (grad) { gradient[0] = grad_sum(0); gradient[1] = grad_sum(1); gradient[2] = grad_sum(2); } return true; } virtual int NumParameters() const { return 3; } private: void matchGaussians() { this->fixed_gaussians_ = fixed_scan_->getGaussianVector(); this->movable_gaussians_ = movable_scan_->getGaussianVector(); ROS_INFO("Before matching: Fixed gaussians size %d, Movable gaussians size %d", (int)fixed_gaussians_.size(), (int)movable_gaussians_.size()); Gaussian::matchClosestGaussians(&fixed_gaussians_, &movable_gaussians_); ROS_INFO("After matching: Fixed gaussians size %d, Movable gaussians size %d", (int)fixed_gaussians_.size(), (int)movable_gaussians_.size()); } }; enum class CostFunction { Standard = 0, Step = 1 }; class NDTRegistrationCeres { private: NDTMap *fixed_scan_; NDTMap *movable_scan_; CostFunction cost_function_; TransformationVector parameters_; double d1_; double d2_; //Ceres stuff ceres::GradientProblemSolver::Summary summary_; ceres::GradientProblemSolver::Options options_; public: NDTRegistrationCeres(const CostFunction &cost_function, double d1 = 1.0, double d2 = 0.05) { this->d1_ = d1; this->d2_ = d2; this->cost_function_ = cost_function; this->parameters_ = TransformationVector(); this->options_.minimizer_progress_to_stdout = false; } NDTRegistrationCeres(const CostFunction &cost_function, const TransformationVector &initial_guess, double d1 = 1.0, double d2 = 0.05) : NDTRegistrationCeres(cost_function, d1, d2) { this->parameters_ = initial_guess; } void setMaps(NDTMap *fixed_scan, NDTMap *movable_scan) { this->parameters_ = TransformationVector(); this->fixed_scan_ = fixed_scan; this->movable_scan_ = movable_scan; } void setTransformation(TransformationVector vector) { this->parameters_ = vector; } TransformationVector getTransformation() const { return parameters_; } void setCostFunction(CostFunction cost_function) { this->cost_function_ = cost_function; } const CostFunction &getCostFunction() const { return cost_function_; } void optimize() { ROS_DEBUG_STREAM("Initial parameters set to: " << parameters_.to_string()); double parameters[3]; parameters_.getParameterArray(parameters); ceres::FirstOrderFunction *cost; if (this->cost_function_ == CostFunction::Step) cost = new NDT2DStepCost(fixed_scan_, movable_scan_); else cost = new NDT2DStandardCost(fixed_scan_, movable_scan_); ceres::GradientProblem problem(cost); ceres::Solve(options_, problem, parameters, &summary_); parameters_.setTransformationParameters(parameters); ; } //Summary functions void printFullReport() const { std::cout << summary_.FullReport() << "\n"; } double getTimeTaken() const { return summary_.total_time_in_seconds; } int getNumberOfIterations() const { return summary_.iterations.size(); } // Options std::string options_to_string() const { std::stringstream ss; std::string error; if (!options_.IsValid(&error)) { ss << "Options not valid: " << error << "\n"; } ss << "line_search_type: " << options_.line_search_type << "\n" << "line_search_direction_type: " << options_.line_search_direction_type << "\n" << "minimizer_progress_to_stdout: " << options_.minimizer_progress_to_stdout << "\n" << "max_line_search_step_contraction: " << options_.max_line_search_step_contraction << "\n" << "min_line_search_step_contraction: " << options_.min_line_search_step_contraction << "\n"; return ss.str(); } }; }; // namespace ndt2d #endif
JHenriksson86/ndt_2d
ndt_2d/include/ndt_2d_mapcell.h
#ifndef NDT_2D_MAP_CELL_H #define NDT_2D_MAP_CELL_H #include "eigen3/Eigen/Dense" #include <vector> #include <iostream> #include <numeric> #include <cmath> #include "ndt_2d_util.h" namespace ndt2d{ class NDTCell { protected: std::vector<UVector2d> scan_points_; Gaussian gaussian_; unsigned int total_number_of_scps_; const unsigned int min_scan_points_; bool has_gaussian_; public: NDTCell(unsigned int min_scan_points = 3) : min_scan_points_(min_scan_points) { init(); } NDTCell(const NDTCell& cell) : min_scan_points_(cell.min_scan_points_) { scan_points_ = cell.scan_points_; gaussian_ = cell.gaussian_; total_number_of_scps_ = cell.total_number_of_scps_; has_gaussian_ = cell.has_gaussian_; } void clear() { init(); } unsigned int getUnregisteredSCPS() const { return scan_points_.size(); } unsigned int getRegisteredSCPS() const { return total_number_of_scps_; } bool hasGaussian() const { return has_gaussian_; } UVector2d getMean() const { return gaussian_.getMean(); } UMatrix2d getCovariance() const { return gaussian_.getCovariance(); } Gaussian getGaussian() const { return gaussian_; } void addScanPoint(const UVector2d& scan_point) { UVector2d point(scan_point[0], scan_point[1]); scan_points_.push_back(point); } virtual bool calculateGaussian() { if(scan_points_.size() < min_scan_points_) { init(); return false; } double n = (double)scan_points_.size(); UVector2d mean = UVector2d::Zero(); for(unsigned int i = 0; i < scan_points_.size(); i++) { mean += scan_points_[i]; } mean = (1.0/n)*mean; UMatrix2d covariance_sum = UMatrix2d::Zero(); for(unsigned int i = 0; i < scan_points_.size(); i++) { UVector2d scan_mean_diff = scan_points_[i] - mean; covariance_sum += scan_mean_diff*scan_mean_diff.transpose(); } gaussian_.setMean(mean); gaussian_.setCovariance((1.0/(n-1.0))*covariance_sum); has_gaussian_ = true; total_number_of_scps_ = scan_points_.size(); scan_points_.clear(); return true; } ~NDTCell() { scan_points_.clear(); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: virtual void init() { scan_points_.clear(); has_gaussian_ = false; total_number_of_scps_ = 0; } std::vector<double> makeCovMatrixMessage() const { UMatrix2d cov = gaussian_.getCovariance(); double cov_array[] = { cov(0,0), cov(0,1), 0.0, cov(1,0), cov(1,1), 0.0, 0.0, 0.0, 0.0 }; std::vector<double> msg(cov_array, cov_array + 9); return msg; } }; class NDTOMCell : public NDTCell { private: UVector2d T_; //Unnormalized mean UMatrix2d S_; //Unnormalized covariance public: NDTOMCell(unsigned int min_scan_points = 3) : NDTCell(min_scan_points) { init(); } ~NDTOMCell() { scan_points_.clear(); } virtual bool calculateGaussian() { if(scan_points_.size() < min_scan_points_) return false; double n = (double)scan_points_.size(); double m = (double)total_number_of_scps_; UVector2d T = calculateT(); UMatrix2d S = calculateS(T, n); if(has_gaussian_) { double S_norm = m/(n*(m+n)); UVector2d T_diff = ((n/m)*T_-T); S_ += S + S_norm*(T_diff*T_diff.transpose()); T_ += T; } else { S_ = S; T_ = T; has_gaussian_ = true; } total_number_of_scps_ += scan_points_.size(); scan_points_.clear(); gaussian_.setMean(T_ * (1.0/(n+m))); gaussian_.setCovariance(S_ * (1.0/(n+m-1))); return true; } private: virtual void init() { scan_points_.clear(); total_number_of_scps_ = 0; has_gaussian_ = false; T_ = UVector2d::Zero(); S_ = UMatrix2d::Zero(); } UVector2d calculateT() { UVector2d sum = UVector2d::Zero(); for(unsigned int i = 0; i < scan_points_.size(); i++) sum += scan_points_[i]; return sum; } UMatrix2d calculateS(const UVector2d& T, double number_of_scan_points) { UMatrix2d S = UMatrix2d::Zero(); UVector2d norm_T = (1.0/number_of_scan_points) * T; for(unsigned int i = 0; i < scan_points_.size(); i++) { UVector2d temp_vector = scan_points_[i]-norm_T; S += temp_vector*temp_vector.transpose(); } return S; } }; }; #endif
JHenriksson86/ndt_2d
ndt_eval/include/ndt_eval/pointcloud_handler.h
#ifndef PCD_HANDLER_H #define PCD_HANDLER_H // STL #include <iostream> #include <string> // PCL #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/PCLPointCloud2.h> #include <pcl/common/transforms.h> #include <pcl/filters/voxel_grid.h> // ROS #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/Transform.h> // Eigen #include "eigen3/Eigen/Dense" #include "eigen3/Eigen/Geometry" // NDT #include "ndt_eval/transform_handler.h" namespace ndt2d { class PointCloudHandler { private: typedef pcl::PointCloud<pcl::PointXYZ> PointCloud; PointCloud::Ptr cloud_; std::string frame_; std::string stamp_; public: PointCloudHandler(std::string frame = "/base_laser"); PointCloudHandler( const sensor_msgs::PointCloud2& pc_message, std::string frame = "/base_laser"); ~PointCloudHandler(); int getNumberOfPoints() const; void loadPCD(std::string pcd_path); void setStamp(const std::string& stamp); const std::string& getStamp() const; sensor_msgs::PointCloud2 getPointCloud2Message( bool reduced = false, double grid_size = 1.0) const; sensor_msgs::PointCloud2 getPointCloud2Message( const geometry_msgs::Transform& transform, bool reduced = false, double grid_size = 1.0) const; Eigen::MatrixXd getPointMatrix( bool reduced = false, double grid_size = 1.0) const; private: sensor_msgs::PointCloud2 pclToPC2(const PointCloud& pcl_cloud) const; void downsampleCloud(double grid_size, PointCloud::Ptr input_cloud, PointCloud& output_cloud) const; }; }; #endif
JHenriksson86/ndt_2d
ndt_2d/include/ndt_2d_map.h
#ifndef NDT_2D_MAP_H #define NDT_2D_MAP_H // STL #include <vector> #include <list> #include <iostream> #include <cmath> // ROS #include <ros/ros.h> // Eigen #include "eigen3/Eigen/Dense" #include "eigen3/Eigen/StdVector" // NDT #include "ndt_2d_mapcell.h" #include "ndt_2d_scan.h" #include "ndt_2d_util.h" namespace ndt2d { class NDTMap { private: std::vector<std::vector<NDTCell>> map_; UMatrix2d rotation_; UVector2d translation_; const int rows_; const int columns_; const double cell_size_; public: NDTMap(int rows = 20, int columns = 20, double cell_size = 1.0) : rows_(rows), columns_(columns), cell_size_(cell_size) { initMap(rows, columns); } NDTMap(const LaserScan &scan, int rows = 20, int columns = 20, double cell_size = 1.0) : rows_(rows), columns_(columns), cell_size_(cell_size) { initMap(rows, columns); this->addScans(scan); } NDTMap(const PointCloud2d &pointcloud, int rows = 20, int columns = 20, double cell_size = 1.0) : rows_(rows), columns_(columns), cell_size_(cell_size) { initMap(rows, columns); this->addPointCloud(pointcloud); } unsigned int getRows() const { return rows_; } unsigned int getColumns() const { return columns_; } double getMapXSize() const { return ((double)columns_) * cell_size_; } double getMapYSize() const { return ((double)rows_) * cell_size_; } double getCellSize() const { return cell_size_; } void clear() { for (int row = 0; row < rows_; row++) { for (int col = 0; col < columns_; col++) { this->operator()(row, col).clear(); } } } const NDTCell &operator()(unsigned int row, unsigned int column) const { return map_[row][column]; } NDTCell &operator()(unsigned int row, unsigned int column) { return map_[row][column]; } bool addScan(double x, double y) { return addScan(UVector2d(x, y)); } bool addScan(UVector2d point) { double rows = (double)rows_; double cols = (double)columns_; double xlimit = cell_size_ * (rows / 2.0); double ylimit = cell_size_ * (cols / 2.0); if (point[0] > xlimit || point[0] < -xlimit || point[1] > ylimit || point[1] < -ylimit) { ROS_WARN("Failed to add scan, outside of limits scan coordinates (%.2f, %.2f)", point[0], point[1]); return false; } UVector2d transformed_point = rotation_ * point + translation_; transformed_point = transformed_point * (1.0 / cell_size_); UVector2d array_coords = Eigen::floor(transformed_point.array()); ROS_DEBUG("Inserting point (%.2f,%.2f) at position (%d,%d) in array", point[0], point[1], (int)array_coords[0], (int)array_coords[1]); this->operator()(array_coords[0], array_coords[1]).addScanPoint(point); return true; } bool addScans(const LaserScan &scan) { ROS_DEBUG("Adding %d scans to ndt", (int)scan.size()); for (unsigned int i = 0; i < scan.size(); i++) { this->addScan(scan[i].getCartesianCoordinates()); } return true; } bool addPointCloud(const PointCloud2d &cloud) { ROS_DEBUG("Adding %d pointcloud to ndt", (int)cloud.numberOfPoints()); for(int i = 0; i < cloud.numberOfPoints(); i++) { this->addScan(cloud.at(i)); } return true; } void calculateGaussians() { for (int row = 0; row < rows_; row++) { for (int col = 0; col < columns_; col++) { this->operator()(row, col).calculateGaussian(); } } } std::vector<Gaussian> getGaussianVector() { std::vector<Gaussian> gaussians; for (int row = 0; row < rows_; row++) { for (int col = 0; col < columns_; col++) { NDTCell cell = this->operator()(row, col); if (cell.hasGaussian()) { gaussians.push_back(cell.getGaussian()); } } } return gaussians; } ~NDTMap() {} EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: void initMap(int rows, int columns) { this->rotation_ << 0.0, -1.0, 1.0, 0.0; this->translation_ = UVector2d(rows, columns) * cell_size_ * 0.5; std::vector<NDTCell> column; for (int i = 0; i < rows; i++) { column.push_back(NDTCell()); } map_ = std::vector<std::vector<NDTCell>>(); for (int i = 0; i < columns; i++) { map_.push_back(column); } ROS_DEBUG("NDT map initiated with rows = %d and columns = %d", int(map_.size()), int(map_[0].size())); } Eigen::Vector3d getCellCenter(int row, int col) { Eigen::Vector3d return_vec; return_vec[0] = (double)(col - columns_ / 2) * cell_size_ + cell_size_ / 2.0; return_vec[1] = (double)(rows_ / 2 - row) * cell_size_ - cell_size_ / 2.0; return_vec[2] = 0.0; return return_vec; } }; } // namespace ndt2d #endif
JHenriksson86/ndt_2d
ndt_2d/include/ndt_2d_service.h
#ifndef NDT_2D_H #define NDT_2D_H // ROS #include <ros/ros.h> #include "sensor_msgs/PointCloud2.h" #include "geometry_msgs/Transform.h" // NDT #include "ndt_2d_map.h" #include "ndt_2d_scan.h" #include "ndt_2d_registration.h" #include "ndt_msgs/Registration.h" #include "ndt_msgs/NDT2dParameters.h" namespace ndt2d { class NDT2dService { private: ros::NodeHandle *nh_; ros::ServiceServer service_; PointCloud2d fixed_cloud_; PointCloud2d movable_cloud_; TransformationVector initial_guess_; TransformationVector result_transform_; int map_cell_count_; double map_cell_size_; public: NDT2dService(){} void subscribeAndAdvertise(ros::NodeHandle *node_handle) { this->nh_ = node_handle; this->service_ = nh_->advertiseService("registration", &NDT2dService::serviceCallback, this); } void runRegistration() { NDTRegistrationCeres registration(CostFunction::Step); // Fixed NDT NDTMap fixed_ndt(fixed_cloud_, map_cell_count_, map_cell_count_, map_cell_size_); fixed_ndt.calculateGaussians(); // Movable NDT NDTMap movable_ndt(movable_cloud_, map_cell_count_, map_cell_count_, map_cell_size_); movable_ndt.calculateGaussians(); // Registration registration.setMaps(&fixed_ndt, &movable_ndt); registration.setTransformation(initial_guess_); registration.optimize(); ROS_INFO("Time taken = %.4f, iterations = %d", registration.getTimeTaken(), registration.getNumberOfIterations()); result_transform_ = registration.getTransformation(); } ~NDT2dService() {} private: bool serviceCallback( ndt_msgs::Registration::Request &request, ndt_msgs::Registration::Response &response) { this->fixed_cloud_.setPointCloud(request.fixed_cloud); this->movable_cloud_.setPointCloud(request.movable_cloud); this->initial_guess_.setTransformation(request.initial_guess); this->map_cell_size_ = request.parameters.map_cell_size; this->map_cell_count_ = request.parameters.map_cell_count; ROS_INFO("Map cell size = %.2f, count = %d", map_cell_size_, map_cell_count_); runRegistration(); geometry_msgs::Transform result_msg = result_transform_.getTransformMessage(); ROS_INFO_STREAM("Registration result:\n" << result_msg); response.result = result_msg; return true; } }; }; // namespace ndt2d #endif
JHenriksson86/ndt_2d
ndt_eval/include/ndt_eval/registration_evaluation.h
<reponame>JHenriksson86/ndt_2d #ifndef REGISTRATION_EVALUATION_H #define REGISTRATION_EVALUATION_H #define _USE_MATH_DEFINES // STL #include <string> #include <iostream> #include <cmath> #include <fstream> // ROS #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/Transform.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> // Eigen #include "eigen3/Eigen/Geometry" // NDT #include "ndt_msgs/Registration.h" #include "ndt_msgs/NDT2dParameters.h" #include "ndt_eval/pointcloud_handler.h" #include "ndt_eval/transform_handler.h" namespace ndt2d { class RegistrationEvaluation { private: ros::NodeHandle* nh_; ros::ServiceClient registration_client_; ros::Publisher fixed_cloud_pub_; ros::Publisher movable_cloud_pub_; ros::Publisher result_cloud_pub_; PointCloudHandler* fixed_cloud_; PointCloudHandler* movable_cloud_; TransformHandler robot_pose_; ndt_msgs::NDT2dParameters registration_parameters_; std::string pcd_path_, pcd_name_, output_file_, odometry_file_; int pcd_start_, pcd_stop_, pcd_step_size_; bool initial_guess_; public: RegistrationEvaluation(ros::NodeHandle* nh); ~RegistrationEvaluation(); void run(); private: geometry_msgs::Transform callRegistrationService( ndt_msgs::Registration& srv, PointCloudHandler* fixed_cloud, PointCloudHandler* movable_cloud, const geometry_msgs::Transform& initial_guess); void saveEstimate() const; void getPCDParameters(); void getRegistrationParameters(); Eigen::Affine3d getScannerTransform() const; }; } #endif
ChargeIn/QLightTerm
qlightterminal.h
<filename>qlightterminal.h /* * Copyright© <NAME> <<EMAIL>> */ #ifndef QLIGHTTERMINAL_H #define QLIGHTTERMINAL_H #include <QWidget> #include <QStringList> #include <QScrollBar> #include <QHBoxLayout> #include <QKeyCombination> #include <QTimer> #include <QPointF> #include <QTime> #include <QColor> #include "st.h" typedef struct { Qt::Key key; Qt::KeyboardModifier mods; char cmd[7]; size_t cmd_size; int nextKey; } SpecialKey; typedef struct { int width; int height; int viewPortHeight; // number of lines visible int viewPortWidth; // number of characters per line int scrollMultiplier; // allows for smooth scrolling int fontSize; double lineheight; double lineHeightScale; double charHeight; double charWith; int vPadding; int hPadding; } Window; class QLightTerminal : public QWidget { Q_OBJECT public: QLightTerminal(QWidget *parent = nullptr); public slots: void updateTerminal(Term * term); /* * Scrolls the terminal vertically to the given offset * Max scroll height is the max line count multiplied by win.scrollMultiplier */ void scrollX(int x); void setFontSize(int size, int weight = 500); void setBackground(QColor color); void setLineHeightScale(double lineHeight); void setPadding(double vertical, double horizontal); void close(); signals: void s_closed(); // emitted when the terminal is closed void s_error(QString); protected: void keyPressEvent(QKeyEvent *event) override; void resizeEvent(QResizeEvent *event) override; void wheelEvent(QWheelEvent *event) override; void focusOutEvent(QFocusEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void mouseDoubleClickEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; bool focusNextPrevChild(bool next) override; void paintEvent(QPaintEvent *event) override; private: SimpleTerminal *st; QScrollBar scrollbar; QHBoxLayout boxLayout; QTimer cursorTimer; QTimer selectionTimer; QTimer resizeTimer; Window win; double cursorVisible = true; void setupScrollbar(); void updateStyleSheet(); void updateSelection(); void resize(); bool closed = false; qint64 lastClick = 0; bool mouseDown = false; bool selectionStarted = false; QPointF lastMousePos; // last tracked mouse pos if mouse down /* * Special Keyboard Character * TODO: Add more */ const int defaultBackground = 259; constexpr static const SpecialKey keys[25] = { { Qt::Key_Left, Qt::KeyboardModifier::NoModifier, "\033[D", 3, 4 }, { Qt::Key_Left, Qt::ShiftModifier, "\033[1;2D", 7, 3 }, { Qt::Key_Left, Qt::AltModifier, "\033[1;3D", 7, 2 }, { Qt::Key_Left, Qt::ControlModifier, "\033[1;5D", 7, 1 }, { Qt::Key_Up, Qt::NoModifier, "\033[A", 3, 4 }, { Qt::Key_Up, Qt::ShiftModifier, "\033[1;2A", 7, 3 }, { Qt::Key_Up, Qt::AltModifier, "\033[1;3A", 7, 2 }, { Qt::Key_Up, Qt::ControlModifier, "\033[1;5A", 7, 1 }, { Qt::Key_Right, Qt::NoModifier, "\033[C", 3, 4 }, { Qt::Key_Right, Qt::ShiftModifier, "\033[1;2C", 7, 3 }, { Qt::Key_Right, Qt::AltModifier, "\033[1;3C", 7, 2 }, { Qt::Key_Right, Qt::ControlModifier, "\033[1;5C", 7, 1 }, { Qt::Key_Down, Qt::NoModifier, "\033[B", 3, 4 }, { Qt::Key_Down, Qt::ShiftModifier, "\033[1;2B", 7, 3 }, { Qt::Key_Down, Qt::AltModifier, "\033[1;3B", 7, 2 }, { Qt::Key_Down, Qt::ControlModifier, "\033[1;5B", 7, 1 }, { Qt::Key_F1, Qt::NoModifier, "\033OP", 3, 1 }, { Qt::Key_F2, Qt::NoModifier, "\033OQ", 3, 1 }, { Qt::Key_F3, Qt::NoModifier, "\033OR", 3, 1 }, { Qt::Key_F4, Qt::NoModifier, "\033OS", 3, 1 }, { Qt::Key_F5, Qt::NoModifier, "\033[15~", 6, 1 }, { Qt::Key_F6, Qt::NoModifier, "\033[17~", 6, 1 }, { Qt::Key_F7, Qt::NoModifier, "\033[18~", 6, 1 }, { Qt::Key_F8, Qt::NoModifier, "\033[19~", 6, 1 }, { Qt::Key_F9, Qt::NoModifier, "\033[20~", 6, 1 }, }; /* * Terminal colors (same as xterm) */ QColor colors[260] = { // 8 normal Colors QColor(0, 0, 0), // Black QColor(240, 82, 79), // Red QColor(98, 177, 32), // Green QColor(166, 138, 13), // Yellow QColor(57, 147, 212), // Blue QColor(167, 113, 191), // Magenta QColor(0, 163, 163), // Cyan QColor(128, 128, 128), // Gray // 8 bright colors QColor(89, 89, 89), // Dark Gray QColor(255, 64, 80), // Bright Red QColor(79, 196, 20), // Bright Green QColor(229, 191, 0), // Bright Yellow QColor(31, 176, 225), // Bright Blue QColor(237, 126, 237), // Bright Magenta QColor(0, 229, 229), // Bright Cyan QColor(255, 255, 255), // White QColor(0, 0, 0), QColor(0, 0, 95), QColor(0, 0, 135), QColor(0, 0, 175), QColor(0, 0, 215), QColor(0, 0, 255), QColor(0, 95, 0), QColor(0, 95, 95), QColor(0, 95, 135), QColor(0, 95, 175), QColor(0, 95, 215), QColor(0, 95, 255), QColor(0, 135, 0), QColor(0, 135, 95), QColor(0, 135, 135), QColor(0, 135, 175), QColor(0, 135, 215), QColor(0, 135, 255), QColor(0, 175, 0), QColor(0, 175, 95), QColor(0, 175, 135), QColor(0, 175, 175), QColor(0, 175, 215), QColor(0, 175, 255), QColor(0, 215, 0), QColor(0, 215, 95), QColor(0, 215, 135), QColor(0, 215, 175), QColor(0, 215, 215), QColor(0, 215, 255), QColor(0, 255, 0), QColor(0, 255, 95), QColor(0, 255, 135), QColor(0, 255, 175), QColor(0, 255, 215), QColor(0, 255, 255), QColor(95, 0, 0), QColor(95, 0, 95), QColor(95, 0, 135), QColor(95, 0, 175), QColor(95, 0, 215), QColor(95, 0, 255), QColor(95, 95, 0), QColor(95, 95, 95), QColor(95, 95, 135), QColor(95, 95, 175), QColor(95, 95, 215), QColor(95, 95, 255), QColor(95, 135, 0), QColor(95, 135, 95), QColor(95, 135, 135), QColor(95, 135, 175), QColor(95, 135, 215), QColor(95, 135, 255), QColor(95, 175, 0), QColor(95, 175, 95), QColor(95, 175, 135), QColor(95, 175, 175), QColor(95, 175, 215), QColor(95, 175, 255), QColor(95, 215, 0), QColor(95, 215, 95), QColor(95, 215, 135), QColor(95, 215, 175), QColor(95, 215, 215), QColor(95, 215, 255), QColor(95, 255, 0), QColor(95, 255, 95), QColor(95, 255, 135), QColor(95, 255, 175), QColor(95, 255, 215), QColor(95, 255, 255), QColor(135, 0, 0), QColor(135, 0, 95), QColor(135, 0, 135), QColor(135, 0, 175), QColor(135, 0, 215), QColor(135, 0, 255), QColor(135, 95, 0), QColor(135, 95, 95), QColor(135, 95, 135), QColor(135, 95, 175), QColor(135, 95, 215), QColor(135, 95, 255), QColor(135, 135, 0), QColor(135, 135, 95), QColor(135, 135, 135), QColor(135, 135, 175), QColor(135, 135, 215), QColor(135, 135, 255), QColor(135, 175, 0), QColor(135, 175, 95), QColor(135, 175, 135), QColor(135, 175, 175), QColor(135, 175, 215), QColor(135, 175, 255), QColor(135, 215, 0), QColor(135, 215, 95), QColor(135, 215, 135), QColor(135, 215, 175), QColor(135, 215, 215), QColor(135, 215, 255), QColor(135, 255, 0), QColor(135, 255, 95), QColor(135, 255, 135), QColor(135, 255, 175), QColor(135, 255, 215), QColor(135, 255, 255), QColor(175, 0, 0), QColor(175, 0, 95), QColor(175, 0, 135), QColor(175, 0, 175), QColor(175, 0, 215), QColor(175, 0, 255), QColor(175, 95, 0), QColor(175, 95, 95), QColor(175, 95, 135), QColor(175, 95, 175), QColor(175, 95, 215), QColor(175, 95, 255), QColor(175, 135, 0), QColor(175, 135, 95), QColor(175, 135, 135), QColor(175, 135, 175), QColor(175, 135, 215), QColor(175, 135, 255), QColor(175, 175, 0), QColor(175, 175, 95), QColor(175, 175, 135), QColor(175, 175, 175), QColor(175, 175, 215), QColor(175, 175, 255), QColor(175, 215, 0), QColor(175, 215, 95), QColor(175, 215, 135), QColor(175, 215, 175), QColor(175, 215, 215), QColor(175, 215, 255), QColor(175, 255, 0), QColor(175, 255, 95), QColor(175, 255, 135), QColor(175, 255, 175), QColor(175, 255, 215), QColor(175, 255, 255), QColor(215, 0, 0), QColor(215, 0, 95), QColor(215, 0, 135), QColor(215, 0, 175), QColor(215, 0, 215), QColor(215, 0, 255), QColor(215, 95, 0), QColor(215, 95, 95), QColor(215, 95, 135), QColor(215, 95, 175), QColor(215, 95, 215), QColor(215, 95, 255), QColor(215, 135, 0), QColor(215, 135, 95), QColor(215, 135, 135), QColor(215, 135, 175), QColor(215, 135, 215), QColor(215, 135, 255), QColor(215, 175, 0), QColor(215, 175, 95), QColor(215, 175, 135), QColor(215, 175, 175), QColor(215, 175, 215), QColor(215, 175, 255), QColor(215, 215, 0), QColor(215, 215, 95), QColor(215, 215, 135), QColor(215, 215, 175), QColor(215, 215, 215), QColor(215, 215, 255), QColor(215, 255, 0), QColor(215, 255, 95), QColor(215, 255, 135), QColor(215, 255, 175), QColor(215, 255, 215), QColor(215, 255, 255), QColor(255, 0, 0), QColor(255, 0, 95), QColor(255, 0, 135), QColor(255, 0, 175), QColor(255, 0, 215), QColor(255, 0, 255), QColor(255, 95, 0), QColor(255, 95, 95), QColor(255, 95, 135), QColor(255, 95, 175), QColor(255, 95, 215), QColor(255, 95, 255), QColor(255, 135, 0), QColor(255, 135, 95), QColor(255, 135, 135), QColor(255, 135, 175), QColor(255, 135, 215), QColor(255, 135, 255), QColor(255, 175, 0), QColor(255, 175, 95), QColor(255, 175, 135), QColor(255, 175, 175), QColor(255, 175, 215), QColor(255, 175, 255), QColor(255, 215, 0), QColor(255, 215, 95), QColor(255, 215, 135), QColor(255, 215, 175), QColor(255, 215, 215), QColor(255, 215, 255), QColor(255, 255, 0), QColor(255, 255, 95), QColor(255, 255, 135), QColor(255, 255, 175), QColor(255, 255, 215), QColor(255, 255, 255), QColor(8, 8, 8), QColor(18, 18, 18), QColor(28, 28, 28), QColor(38, 38, 38), QColor(48, 48, 48), QColor(58, 58, 58), QColor(68, 68, 68), QColor(78, 78, 78), QColor(88, 88, 88), QColor(98, 98, 98), QColor(108, 108, 108), QColor(118, 118, 118), QColor(128, 128, 128), QColor(138, 138, 138), QColor(148, 148, 148), QColor(158, 158, 158), QColor(168, 168, 168), QColor(178, 178, 178), QColor(188, 188, 188), QColor(198, 198, 198), QColor(208, 208, 208), QColor(218, 218, 218), QColor(228, 228, 228), QColor(238, 238, 238), // Default colors QColor(255, 255, 255), QColor(85, 85, 85), QColor(200, 200, 200), // Default font color QColor(24, 24, 24) // Default background color }; }; #endif // QLIGHTTERMINAL_H
ChargeIn/QLightTerm
st.h
#ifndef ST_H #define ST_H #include <QObject> #include <QString> #include <QSocketNotifier> #include <sys/ioctl.h> #include "st-utils.h" class SimpleTerminal : public QObject { Q_OBJECT public: Term term; Selection sel; SimpleTerminal(QObject *parent = nullptr); ~SimpleTerminal(); void tnew(int col, int row); void ttynew(); void execsh(); void closePty(); void tresize(int col, int row); void ttyresize(int tw, int th); int twrite(const char *buf, int size, int show_ctrl); void ttywrite(const char *s, size_t n, int may_echo); void ttywriteraw(const char *s, size_t n); void kscrollup(int n); void kscrolldown(int n); void tdumpsel(void); char *getsel(void); void selstart(int col, int row, int snap); void selextend(int col, int row, int type, int done); void selsnap(int *x, int *y, int direction); int selected(int x, int y); void selclear(void); void selscroll(int orig, int n); public slots: size_t ttyread(); signals: void s_error(QString); void s_closed(); void s_updateView(Term *state); private: TermWindow win; winsize wsize; int master, slave; pid_t processId; char readBuf[BUFSIZ]; int readBufPos = 0; int readBufSize = 0; QSocketNotifier *readNotifier; CSIEscape csiescseq; STREscape strescseq; /* * Default colors (colorname index) * foreground, background, cursor, reverse cursor */ unsigned int defaultcs = 256; unsigned int defaultrcs = 257; unsigned int defaultfg = 258; unsigned int defaultbg = 259; unsigned int defaultCursor = 160; // no longer used const int tabspaces = 8; /* allow certain non-interactive (insecure) window operations such as: setting the clipboard text */ int allowwindowops = 0; const char *vtiden = "\033[?6c"; const uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0}; const uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8}; const Rune utfmin[UTF_SIZ + 1] = {0, 0, 0x80, 0x800, 0x10000}; const Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF}; size_t utf8decode(const char *c, Rune *u, size_t clen); Rune utf8decodebyte(char c, size_t *i); size_t utf8validate(Rune *u, size_t i); size_t utf8encode(Rune u, char *c); char utf8encodebyte(Rune u, size_t i); void tputc(Rune u); void tcontrolcode(uchar ascii); void tputtab(int n); void tmoveto(int x, int y); void tstrsequence(uchar c); void strreset(void); void tclearregion(int x1, int y1, int x2, int y2); void selnormalize(void); void strhandle(void); void strparse(void); void strdump(void); void tsetchar(Rune u, const Glyph *attr, int x, int y); void csireset(void); void csiparse(void); void csihandle(void); void csidump(void); void tsetdirt(int top, int bot); void tdump(void); void tdumpline(int n); int tlinelen(int y); void tnewline(int first_col); void tinsertblank(int n); void tinsertblankline(int n); void tscrollup(int orig, int n, int copyhist); void tscrolldown(int orig, int n, int copyhist); void tsetscroll(int t, int b); void tcursor(int mode); void tmoveato(int x, int y); void tdeletechar(int n); void tdeftran(char ascii); void tdectest(char c); void tdefutf8(char ascii); void tdeleteline(int n); int eschandle(uchar ascii); void treset(void); void tfulldirt(void); void osc_color_response(int index, int num); void redraw(void); void draw(void); char *base64dec(const char *src); char base64dec_getc(const char **src); void osc4_color_response(int num); void tsetattr(const int *attr, int l); int32_t tdefcolor(const int *attr, int *npar, int l); void xsetmode(int set, unsigned int flags); void tsetmode(int priv, int set, const int *args, int narg); void tswapscreen(void); void bell(void); // TODO void xsetsel(char *str); void xclipcopy(void); int xsetcolorname(int x, const char *name); int xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b); void xloadcols(void); int xsetcursor(int cursor); void tprinter(char *s, size_t len); // TODO }; #endif // ST_H
ChargeIn/QLightTerm
st-utils.h
#ifndef STUTILS_H #define STUTILS_H #include <stdint.h> #include <QObject> /* macros */ #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) < (b) ? (b) : (a)) #define LEN(a) (sizeof(a) / sizeof(a)[0]) #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b)) #define DIVCEIL(n, d) (((n) + ((d) - 1)) / (d)) #define DEFAULT(a, b) (a) = (a) ? (a) : (b) #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x) #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || \ (a).bg != (b).bg) #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + \ (t1.tv_nsec-t2.tv_nsec)/1E6) #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit))) #define TRUECOLOR(r, g, b) (1 << 24 | (r) << 16 | (g) << 8 | (b)) #define IS_TRUECOL(x) (1 << 24 & (x)) #define TRUERED(x) (((x) & 0xff0000) >> 8) #define TRUEGREEN(x) (((x) & 0xff00)) #define TRUEBLUE(x) (((x) & 0xff) << 8) #define RED_FROM_TRUE(x) (0xFF & (x >> 16)) #define GREEN_FROM_TRUE(x) (0xFF & (x >> 8)) #define BLUE_FROM_TRUE(x) (0xFF & x) enum glyph_attribute { ATTR_NULL = 0, ATTR_BOLD = 1 << 0, ATTR_FAINT = 1 << 1, ATTR_ITALIC = 1 << 2, ATTR_UNDERLINE = 1 << 3, ATTR_BLINK = 1 << 4, ATTR_REVERSE = 1 << 5, ATTR_INVISIBLE = 1 << 6, ATTR_STRUCK = 1 << 7, ATTR_WRAP = 1 << 8, ATTR_WIDE = 1 << 9, ATTR_WDUMMY = 1 << 10, ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT, }; enum selection_mode { SEL_IDLE = 0, SEL_EMPTY = 1, SEL_READY = 2 }; enum selection_type { SEL_REGULAR = 1, SEL_RECTANGULAR = 2 }; enum selection_snap { SNAP_WORD = 1, SNAP_LINE = 2 }; /* Arbitrary sizes */ #define UTF_INVALID 0xFFFD #define UTF_SIZ 4 #define ESC_BUF_SIZ (128*UTF_SIZ) #define ESC_ARG_SIZ 16 #define STR_BUF_SIZ ESC_BUF_SIZ #define STR_ARG_SIZ ESC_ARG_SIZ #define HISTSIZE 1000 /* macros */ #define IS_SET(mode, flag) ((mode & (flag)) != 0) #define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == 0x7f) #define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f)) #define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c)) #define ISDELIM(u) (u && wcschr(L" ", u)) #define TLINE(term, y) ((y) < term.scr ? term.hist[((y) + term.histi - \ term.scr + HISTSIZE + 1) % HISTSIZE] : \ term.line[(y) - term.scr]) typedef uint_least32_t Rune; #define Glyph Glyph_ typedef struct { Rune u; /* character code */ ushort mode; /* attribute flags */ uint32_t fg; /* foreground */ uint32_t bg; /* background */ } Glyph; typedef Glyph *Line; typedef struct { Glyph attr; /* current char attributes */ int x; int y; char state; } TCursor; enum term_mode { MODE_WRAP = 1 << 0, MODE_INSERT = 1 << 1, MODE_ALTSCREEN = 1 << 2, MODE_CRLF = 1 << 3, MODE_ECHO = 1 << 4, MODE_PRINT = 1 << 5, MODE_UTF8 = 1 << 6, }; enum cursor_movement { CURSOR_SAVE, CURSOR_LOAD }; enum cursor_state { CURSOR_DEFAULT = 0, CURSOR_WRAPNEXT = 1, CURSOR_ORIGIN = 2 }; enum charset { CS_GRAPHIC0, CS_GRAPHIC1, CS_UK, CS_USA, CS_MULTI, CS_GER, CS_FIN }; enum escape_state { ESC_START = 1, ESC_CSI = 2, ESC_STR = 4, /* DCS, OSC, PM, APC */ ESC_ALTCHARSET = 8, ESC_STR_END = 16, /* a final string was encountered */ ESC_TEST = 32, /* Enter in test mode */ ESC_UTF8 = 64, }; typedef struct { int mode; int type; int snap; /* * Selection variables: * nb – normalized coordinates of the beginning of the selection * ne – normalized coordinates of the end of the selection * ob – original coordinates of the beginning of the selection * oe – original coordinates of the end of the selection */ struct { int x, y; } nb, ne, ob, oe; int alt; } Selection; /* Internal representation of the screen */ typedef struct { int row; /* nb row */ int col; /* nb col */ Line *line; /* screen */ Line *alt; /* alternate screen */ Line hist[HISTSIZE]; /* history buffer */ int histi; /* history index */ int scr; /* scroll back */ int altHisti; /* alt screen history index */ int altScr; /* alt screen scrollback */ int *dirty; /* dirtyness of lines */ TCursor c; /* cursor */ int ocx; /* old cursor col */ int ocy; /* old cursor row */ int top; /* top scroll limit */ int bot; /* bottom scroll limit */ int mode; /* terminal mode flags */ int esc; /* escape state flags */ char trantbl[4]; /* charset table translation */ int charset; /* current charset */ int icharset; /* selected charset for sequence */ int *tabs; Rune lastc; /* last printed char outside of sequence, 0 if control */ } Term; /* CSI Escape sequence structs */ /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */ typedef struct { char buf[ESC_BUF_SIZ]; /* raw string */ size_t len; /* raw string length */ char priv; int arg[ESC_ARG_SIZ]; int narg; /* nb of args */ char mode[2]; } CSIEscape; /* STR Escape sequence structs */ /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */ typedef struct { char type; /* ESC type ... */ char *buf; /* allocated raw string */ size_t siz; /* allocation size */ size_t len; /* raw string length */ char *args[STR_ARG_SIZ]; int narg; /* nb of args */ } STREscape; static const char base64_digits[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, -1, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; enum win_mode { MODE_VISIBLE = 1 << 0, MODE_FOCUSED = 1 << 1, MODE_APPKEYPAD = 1 << 2, MODE_MOUSEBTN = 1 << 3, MODE_MOUSEMOTION = 1 << 4, MODE_REVERSE = 1 << 5, MODE_KBDLOCK = 1 << 6, MODE_HIDE = 1 << 7, MODE_APPCURSOR = 1 << 8, MODE_MOUSESGR = 1 << 9, MODE_8BIT = 1 << 10, MODE_BLINK = 1 << 11, MODE_FBLINK = 1 << 12, MODE_FOCUS = 1 << 13, MODE_MOUSEX10 = 1 << 14, MODE_MOUSEMANY = 1 << 15, MODE_BRCKTPASTE = 1 << 16, MODE_NUMLOCK = 1 << 17, MODE_MOUSE = MODE_MOUSEBTN | MODE_MOUSEMOTION | MODE_MOUSEX10\ | MODE_MOUSEMANY, }; /* Purely graphic info */ typedef struct { int tw, th; /* tty width and height */ int w, h; /* window width and height */ int ch; /* char height */ int cw; /* char width */ int mode; /* window state/mode flags */ int cursor; /* cursor style */ } TermWindow; #endif // STUTILS_H
PavanKamra96/BTP305
Lab5/Notifications.h
/** Name: <NAME> Course: BTP305 **/ #ifndef _Notifications_h_ #define _Notifications_h_ #include <iostream> #include <cstring> #include <vector> #include "Message.h" #define msgDEFINE 10 namespace w5 { class Notifications { private: std::vector<Message> M; public: Notifications(); Notifications(const Notifications&); Notifications& operator=(const Notifications&); Notifications(Notifications&&); Notifications&& operator=(Notifications&&); void operator+=(const Message& msg); void display(std::ostream& os) const; }; } #endif
PavanKamra96/BTP305
lab4/KVList.h
<reponame>PavanKamra96/BTP305<gh_stars>0 /** Name: <NAME> Course: BTP305 **/ #include <iostream> #include <string> template < typename K, typename V, int n > class KVList { private: K a[n]; V b[n]; size_t count; public: KVList(): count(0) {}; size_t size() const { return count; } const K & key(int i) const { return a[i]; } const V & value(int i) const { return b[i]; } KVList & add(const K & key, const V & value) { if (n > count) { a[count] = key; b[count] = value; count++; } return *this; } int find(const K & k) const { if (count > 0) { for (int i = 0; i < count; i++) { if (a[i] == k) { return i; } } } return 0; } KVList & replace(int i, const K & k, const V & v) { if (count >= i) { a[i] = k; b[i] = v; } return *this; } };
PavanKamra96/BTP305
lab1/process.h
/* Name: <NAME> Date: 9/18/2015 Course: BTP305 Purpose: method called process is declared.*/ void process (const char*);
PavanKamra96/BTP305
Lab7/taxableProduct.h
<filename>Lab7/taxableProduct.h /** Name: <NAME> Course:BTP305 **/ #ifndef _TAXABLE_PRODUCT_H #define _TAXABLE_PRODUCT_H #include "Product.h" #include <iostream> namespace w7{ class taxableProduct: public Product { private: char taxType; static const double TAX[2]; // do not do in constructor. public: taxableProduct(); taxableProduct(long P, double c, char a); double getCharge() const; void display (std::ostream& os) const; }; } #endif
PavanKamra96/BTP305
lab1/Cstring.h
<filename>lab1/Cstring.h /** Name: <NAME> Course: BTP305 **/ #ifndef _CSTRING_H_ #define _CSTRING_H_ #include <iostream> #include < cstring > // Creates a CString class inside the namespace w1. namespace w1 { const int charNum = 4; class CString { public: CString(); CString(const char * ); void display(std::ostream & ) const; private: char str[charNum + 1]; }; std::ostream & operator << (std::ostream & , const CString & ); } #endif
PavanKamra96/BTP305
Lab7/iProduct.h
/** Name: <NAME> Course: BTP305 **/ #ifndef _I_PRODUCT_H_ #define _I_PRODUCT_H_ #include <iostream> #include <fstream> namespace w7 { class iProduct { public: virtual double getCharge() const = 0; virtual void display(std::ostream&) const = 0; virtual ~iProduct(){}; }; std::ostream& operator<<(std::ostream&, const iProduct&); iProduct* readProduct(std::ifstream&); } #endif
PavanKamra96/BTP305
Lab2/Stations.h
<reponame>PavanKamra96/BTP305 /** Name: <NAME> Course: BTP305 **/ #ifndef _STATIONS_H_ #define _STATIONS_H_ #include <iostream> #include <cstring> #include "Station.h" namespace w2 { class Stations { private: Station *stat; char delimiter; int amount_Of_Stations; public: Stations(const char*); ~Stations(); void update() const; void restock() const; void report() const; }; } #endif
PavanKamra96/BTP305
Lab9/Element.h
<gh_stars>0 /** Name: <NAME> Course: BTP305 **/ #include <iostream> #include <iomanip> #include <string> #include <fstream> extern const int FWC; extern const int FWD; extern const int FWP; namespace w9 { struct Description { unsigned code; std::string desc; bool load(std::ifstream & f) { // this inputs from the file. f >> code >> desc; return f.good(); } void display(std::ostream & os) const { os << std::setw(FWC) << code << std::setw(FWD) << desc << std::endl; // displays info from the os stream. } }; struct Price { unsigned code; double price; bool load(std::ifstream & f) { // inputs from the file. f >> code >> price; return f.good(); } void display(std::ostream & os) const { os << std::setw(FWC) << code << std::setw(FWP) << price << std::endl; } }; struct Product { std::string desc; double price; Product() {} Product(const std::string & str, double p): desc(str), price(p) {} void display(std::ostream & os) const { os << std::setw(FWD) << desc << std::setw(FWP) << price << std::endl; } void validate() { // this validates program to see if the prices are over 0. if (price < 0.0) { throw "***Negative prices are invalid***"; } } }; }
PavanKamra96/BTP305
Lab7/Sale.h
/** Name: <NAME> Course: BTP305 **/ #ifndef _SALE_H_ #define _SALE_H_ #include "iProduct.h" #include <vector> #include <fstream> #include <iomanip> namespace w7 { class Sale { std::vector<iProduct*> products; public: Sale(const char* filename); void display(std::ostream& os) const; }; } #endif
PavanKamra96/BTP305
Lab2/Station.h
<reponame>PavanKamra96/BTP305 /** Name: <NAME> Course: BTP305 **/ #ifndef _STATION_H_ #define _STATION_H_ #include <iostream> #include <cstring> #include <string> enum PassType {Student, Adult}; class Station { private: std::string station_Name; unsigned int studen_Pass; unsigned int adult_Pass; public: Station(); void set(const std::string&, unsigned, unsigned); void update(PassType, int); unsigned inStock(PassType) const; const std::string& getName() const; }; #endif
PavanKamra96/BTP305
Lab5/Message.h
<reponame>PavanKamra96/BTP305<filename>Lab5/Message.h /** Name: <NAME> Course: BTP305 **/ #ifndef _Message_h_ #define _Message_h_ #include <iostream> #include <vector> #include <cstring> #include <string> #include <fstream> namespace w5 { class Message { private: std::string user_name; std::string reply_name; std::string tweet; std::string whole_Msg; public: Message(); Message(std::ifstream& in, char c); bool empty() const; void display(std::ostream&) const; }; } #endif
PavanKamra96/BTP305
Lab9/List.h
/** Name: <NAME> Course: BTP305 **/ #include <iostream> #include <iomanip> #include <vector> #include <string> #include <fstream> namespace w9 { template < typename T > class List { std::vector < T > list; public: List() {} List(const char * fn) { std::ifstream file(fn); if (!file) throw std::string("*** Failed to open file ") + std::string(fn) + std::string(" ***"); while (file) { T e; if (e.load(file)) list.push_back( * new T(e)); } } size_t size() const { return list.size(); } const T & operator[](size_t i) const { return list[i]; } void operator += (std::unique_ptr < T > & p) { list.push_back( * p); } void display(std::ostream & os) const { os << std::fixed << std::setprecision(2); for (auto & e: list) e.display(os); } }; template < typename T > std::ostream & operator << (std::ostream & os, const List < T > & l) { l.display(os); return os; } }
PavanKamra96/BTP305
Lab3/Text.h
<reponame>PavanKamra96/BTP305 /** Name: <NAME> Date: 9/29/2015 Course: BTP305 Purpose: The Header file for Text.cpp. **/ #ifndef _TEXT_H_ #define _TEXT_H_ #include <iostream> #include <cstring> #include <string> namespace w3 { class Text { private: std::string* T; size_t records; public: Text(); Text(std::string const&); Text(const Text&); // copy constructor Text& operator=(const Text&); // copy assignment operator Text(Text&&); // move constructor Text&& operator=(Text&&); // move assignment operator ~Text(); // destructor size_t size() const; // member function that returns the number of records of text data. }; } #endif
PavanKamra96/BTP305
Lab8/DataTable.h
/** Name: <NAME> Course: BTP305 **/ #ifndef _DATATABLE_H_ #define _DATATABLE_H_ #include <iostream> #include <fstream> #include <math.h> #include <vector> #include <iomanip> #include <algorithm> #include <functional> namespace w8 { template < typename T > class DataTable { private: std::vector < T > xcord; //vector for the x-coordinate std::vector < T > ycord; //vector for the y-coordinate int field_width; //field_width for the display int precision_Value; //precision value for the display. public: // Default Constructor DataTable(): field_width(0), precision_Value(0) {} // Overload Constructor - inputs filename, Field Width, & Precision. DataTable(std::ifstream & file, int FW, int PV) { field_width = FW; precision_Value = PV; while (!file.eof()) { if (file.good()) { T x, y; file >> x >> y; if (file.good()) { xcord.push_back(x); ycord.push_back(y); } } } } // Calculate & returns the Mean. T mean() const { T mean, Total; Total = std::accumulate(ycord.begin(), ycord.end(), (T) 0); mean = Total / ycord.size(); return mean; } // Calculates & returns the standard deviation T sigma() const { T deviation, Total; T avg = mean(); Total = std::accumulate(ycord.begin(), ycord.end(), (T) 0, [ = ](T Total, T current) { Total += std::pow(current - avg, 2); return Total; }); deviation = Total / (ycord.size() - 1); deviation = std::sqrt(deviation); return deviation; } //Calculates & returns the mean of the dependent coordinates. T median() const { std::vector < T > y = ycord; std::sort(y.begin(), y.end()); return y[std::round(y.size() / 2.0)]; } //This calculates the slope & y_intercept by reference void regression(T & slope, T & y_intercept) const { T part1, part2, part3; part1 = (std::inner_product(xcord.begin(), xcord.end(), ycord.begin(), (T) 0)) * xcord.size(); part1 = part1 - (std::accumulate(xcord.begin(), xcord.end(), (T) 0) * std::accumulate(ycord.begin(), ycord.end(), (T) 0)); part2 = xcord.size() * (std::accumulate(xcord.begin(), xcord.end(), (T) 0, [](T part2, T current) { part2 += std::pow(current, 2); return part2; })); part2 = part2 - (std::pow(std::accumulate(xcord.begin(), xcord.end(), (T) 0), 2)); slope = part1 / part2; y_intercept = (std::accumulate(ycord.begin(), ycord.end(), (T) 0)) - (slope * std::accumulate(xcord.begin(), xcord.end(), (T) 0)); y_intercept = y_intercept / xcord.size(); } //displays the x and y Data Values void display(std::ostream & os) const { //os << "Data Values" << std::endl; //os << "============" << std::endl; os << std::setw(field_width) << "x" << std::setw(field_width) << "y" << std::endl; for (int i = 0; i < xcord.size(); i++) { os << std::setw(field_width) << std::fixed << std::setprecision(precision_Value) << xcord[i]; os << std::setw(field_width) << std::fixed << std::setprecision(precision_Value) << ycord[i] << std::endl; } } ~DataTable() { xcord.clear(); ycord.clear(); } }; template < typename T > // the << operator uploaded. std::ostream & operator << (std::ostream & os, const DataTable < T > & st) { st.display(os); return os; } } #endif
PavanKamra96/BTP305
Lab6/Grades.h
<reponame>PavanKamra96/BTP305 /** Name: <NAME> Course: BTP305 **/ #ifndef _Grades_h_ #define _Grades_h_ #include <iostream> #include <string> #include <fstream> #include <functional> class Grades { private: long* studentID; float* Grade; int recordsNum; public: Grades(); ~Grades(); Grades(const char*); void displayGrades(std::ostream&, std::function<std::string(float)>) const; }; #endif
PavanKamra96/BTP305
Lab7/Product.h
/** Name: <NAME> Course: BTP305 **/ #ifndef _PRODUCT_H_ #define _PRODUCT_H_ #include "iProduct.h" #include <iostream> #include <iomanip> namespace w7 { class Product: public iProduct { private: long ProductId; double cost; public: Product(); Product(long, double); double getCharge() const; void display(std::ostream& os) const; }; } #endif
CristianManosalva/SOXV6
stdio.h
#ifndef ULIBC_STDIO_H #define ULIBC_STDIO_H #include <stdarg.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef ULIBC_SIZE_T #define ULIBC_SIZE_T typedef unsigned int size_t; #endif /* ULIBC_SIZE_T */ #ifdef __cplusplus #define NULL 0L #else /* __cplusplus */ #define NULL ((void*)0) #endif /* __cplusplus */ typedef unsigned int fpos_t; #define _IOFBF 0 #define _IOLBF 1 #define _IONBF 2 #define BUFSIZ 1024 #define EOF (-1) #define FOPEN_MAX 1000 #define FILENAME_MAX 4096 #define L_tmpnam 20 #define SEEK_SET 0 #define SEEK_CUR 1 #define SEEK_END 2 #define TMP_MAX 10000 typedef struct __FILE { int fd; char* buffer; char* rd_pos; char* wr_pos; fpos_t read_off_beg; fpos_t read_off_pos; fpos_t read_off_end; fpos_t write_off_beg; fpos_t write_off_pos; fpos_t write_off_end; int error; int eof; int mode; int flags; } FILE; extern FILE* const stdin; extern FILE* const stdout; extern FILE* const stderr; int remove(const char* filename); int rename(const char* src, const char* dst); FILE* tmpfile(void); char* tmpnam(char* s); int fclose(FILE* stream); int fflush(FILE* stream); FILE* fopen(const char* filename, const char* mode); FILE* freopen(const char* filename, const char* mode, FILE* stream); void setbuf(FILE* stream, char* buf); int setvbuf(FILE* stream, char* buf, int mode, size_t size); int fprintf(FILE* stream, const char* format, ...); int fscanf(FILE* stream, const char* format, ...); int printf(const char* format, ...); int scanf(const char* format, ...); int sprintf(char* s, const char* format, ...); int sscanf(const char* s, const char* format, ...); int vfprintf(FILE* stream, const char* format, va_list arg); int vprintf(const char* format, va_list arg); int vsprintf(char* s, const char* format, va_list arg); int fgetc(FILE* stream); char* fgets(char* s, int n, FILE* stream); int fputc(int c, FILE* stream); int fputs(const char* s, FILE* stream); int getc(FILE* stream); int getchar(void); char* gets(char* s); int putc(int c, FILE* stream); int putchar(int c); int puts(const char* s); int ungetc(int c, FILE* stream); size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream); size_t fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream); int fgetpos(FILE* stream,fpos_t* pos); int fseek(FILE* stream, long int offset, int whence); int fsetpos(FILE* stream, const fpos_t* pos); long int ftell(FILE* stream); void rewind(FILE* stream); void clearerr(FILE* stream); int feof(FILE* stream); int ferror(FILE* stream); void perror(const char* s); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* ULIBC_STDIO_H */
CristianManosalva/SOXV6
foo.c
<reponame>CristianManosalva/SOXV6 #include "types.h" #include "stat.h" #include "user.h" #include "fcntl.h" int main(int argc, char *argv[]){ int k, n, id; double x=0, z, d; if(argc < 2) n = 1; else n = atoi (argv[1]); if(n < 0 || n > 20) n = 2; if(argc < 3) d = 0.1; else d = atoi (argv[2]); x=0; id=0; for(k = 0; k < n; k++){ id = fork(); if(id < 0){ printf(1, "%d failed in fork!\n ", getpid()); } else if(id > 0){ printf(1, "parent %d, creating child %d\n", getpid(), id); wait(); } else { printf(1, "child %d created\n", getpid()); for(z = 0; z < 8000000.0; z += d) x = x +3.14*89.64; break; } } exit(); }
ameya134/Real_time_FIR_filtering
src/inc/hal/timer0.h
<reponame>ameya134/Real_time_FIR_filtering /* ***************************************************************** * * This file provides the declarations for configuration and * use of Timer0 peripheral on tm4c129encpdt * * Author: <NAME> * Date Created: 1st March 2021 * Date Modified: 13th May 2021 * * *****************************************************************/ #ifndef _TIMER0_H #define _TIMER0_H #include "tm4c129encpdt.h" /* macros to configure the interrupt, adc and dma triggers */ #define TIMER0A_GENERATE_INTERRUPT 0 #define TIMER0A_GENERATE_ADC_TRIG 1 #define TIMER0A_GENERATE_DMA_TRIG 1 /* channel no and encoding no for timer0 dma transfer request */ #define TIMER0_DMA_CHANNEL_NO 18 #define TIMER0_DMA_CHANNEL_ENCODE 0 /* macros for interrupt no and priority of the interrupt */ #if( TIMER0A_GENERATE_INTERRUPT == 1) #define TIMER0A_INT_NUM (19U) /* the priority of interrupt needs to be lower than max_sycall_prio * of FreeRTOS in order to use FreeRTOS API inside the ISR */ #define TIMER0A_INT_NVIC_PRIO (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1) void timer0_handler(void); #endif /* ************************************************************************** * This function Initialized the Timer0 with a load value * * param: loadval Initial load value of the timer * * return: void * * brief: Function initializes the timer0 module in periodic count down * mode with the given load value. * * If the TIMER0A_GENERATE_INTERRUPT flag is defined as 1 then the timer * generated. * * TIMER0A_GENERATE_ADC_TRIG flag, if turned on, generates an ADC trigger * every time the timer0 reaches a value of 0 while counting down. * * TIMER0A_GENERATE_DMA_TRIG flag, if turned on, generates a DMA trigger * every time the timer0 reaches a value of 0 while counting down. * * **************************************************************************/ void init_timer0(uint32_t loadVal); /* *************************************************************************** * * This function enables the timer0 * * param: void * * return: void * * brief: This function enables the timer0 which starts the timer0 counting * * **************************************************************************/ void timer0_enable(void); #endif
ameya134/Real_time_FIR_filtering
src/inc/timestamp.h
<gh_stars>0 /* ******************************************************** * * header file for timestamp API * * Author: <NAME> * Date Created: 6th May 2021 * Date Modified: 6th May 2021 * * *******************************************************/ #ifndef _TIMESTAMP_H #define _TIMESTAMP_H #include "main.h" #include "tm4c129encpdt.h" /* *************************************************************************** * * This function initializes the timer7 in 32-bit, one shot, count up mode. * * param: void * * return: void * * brief: This function starts the timer7 in 32-bit, one shot, count up mode * to be used for timekeeping. This function needs to be called initially * before calling other timestamp functions. * * **************************************************************************/ void init_timestamp_timer(void); /* *************************************************************************** * * This function returns the count value of the timer7 * * param: void * * return: uint32_t timer7 count value * * brief: This function returns count value of timer7 which can be used to * calculate time period between 2 calls to this function. * * **************************************************************************/ uint32_t getTimeStampVal(void); /* *************************************************************************** * * This function starts the timer7 to count up. * * param: void * * return: void * * brief: This function starts the timer7. Timer7 starts counting up in * one shot mode. * * **************************************************************************/ void TimeStampStart(void); /* *************************************************************************** * * This function halts the timer7. * * param: void * * return: void * * brief: This function halts the counting of timer7. timer7 retains its * current counting value in TIMER7_TAV_R register. * * **************************************************************************/ void TimeStampHalt(void); /* *************************************************************************** * * This function restarts the timer7 to count up. * * param: void * * return: void * * brief: This function restarts the timer7. the current value of timer7 is * set to 0 and then Timer7 starts counting up in one shot mode. * * **************************************************************************/ void TimeStampRestart(void); #endif
ameya134/Real_time_FIR_filtering
src/hal/clock.c
/* *********************************************************** * This file implements the API used to configure and * use the various clocks present on tm4c129encpdt * This file uses TI's provided tm4c129encpdt.h header file * * Author: <NAME> * Date created: 28th April 2021 * Last modified: 13th May 2021 * * ***********************************************************/ #include "main.h" #include "clock.h" /* ******************************************************************************* * This function configures the PLL to produce the desired * clock frequency for the system clock. * * param: clock_src The clock source input to the PLL(MOSC,PIOSC etc) * param: Q Q is a divisor value for PLL * param: N N is a divisor value for PLL * param: MINT Integer part of PLL multiplier value * param: MFRAC Fractional part of PLL multiplier value * param: PSYDIV clock divisor for PLL VCO frequency. * param: MEMTIM_PARAM memory timing parameter * * return: void * * brief: This function takes arguments for PLL multiplier and divisor and sets the * Pll output frequency accordingly. * * PLL can be set to use either PIOSC_CLOCK_SRC (16MHz) or * MOSC_CLOCK_SRC (externally connected crystal). * * The output frequency of the PLL can be calculated with the help of following * formulae. * * PLL output freq Fvco = Fin * MDIV * * where, * * Fin = Fxtal/((Q+1)*(N+1)) * * and * * MDIV = MINT + MFRAC/1024 * * The system clock frequency SysClock is obtained by following equation. * * SysClk = Fvco / (PSYDIV + 1) * * As the system clock frequency is changed we need to change the memory timing parameters. * The appropriate Memory timing parameters for a bracket of frequency range are given * in the datasheet and should be appropriately passed by the caller. * * *******************************************************************************/ void configure_pll_clock(int clock_src,int Q, int N,int MINT, int MFRAC,int PSYSDIV,int MEMTIM_PARAM) { /* Initialize the main oscilator if it is selected */ if(clock_src == MOSC_CLOCK_SRC){ SYSCTL_MOSCCTL_R |= ( SYSCTL_MOSCCTL_OSCRNG ); SYSCTL_MOSCCTL_R &= ~( SYSCTL_MOSCCTL_NOXTAL | SYSCTL_MOSCCTL_PWRDN ); SYSCTL_RSCLKCFG_R |= (SYSCTL_RSCLKCFG_PLLSRC_MOSC); } /* disable pll and configure the parameters in pll registers */ SYSCTL_PLLFREQ0_R &= ~(SYSCTL_PLLFREQ0_PLLPWR); SYSCTL_PLLFREQ0_R |= (MINT << SYSCTL_PLLFREQ0_MINT_S); SYSCTL_PLLFREQ0_R |= (MFRAC << SYSCTL_PLLFREQ0_MFRAC_S); SYSCTL_PLLFREQ1_R |= (N << SYSCTL_PLLFREQ1_N_S); SYSCTL_PLLFREQ1_R |= (Q << SYSCTL_PLLFREQ1_Q_S); /* enable pll */ SYSCTL_PLLFREQ0_R |= (SYSCTL_PLLFREQ0_PLLPWR); /* notify system of the new frequency and wait for pll to stabilize */ SYSCTL_RSCLKCFG_R |= (SYSCTL_RSCLKCFG_NEWFREQ); while(!(SYSCTL_PLLSTAT_R & SYSCTL_PLLSTAT_LOCK)); /* Configure memory timing parameters */ SYSCTL_MEMTIM0_R |= ((MEMTIM_PARAM << SYSCTL_MEMTIM0_FWS_S) | (MEMTIM_PARAM << SYSCTL_MEMTIM0_EWS_S) ); /* Memory timing parameters are calculated and updated according to the target frequency. * These timing parameters can be found in the datasheet. */ if(MEMTIM_PARAM == 0){ SYSCTL_MEMTIM0_R |= ((SYSCTL_MEMTIM0_FBCHT_M & (MEMTIM_PARAM<< 6)) | (SYSCTL_MEMTIM0_EBCHT_M & (MEMTIM_PARAM<< 22)) ); } SYSCTL_MEMTIM0_R |= ((SYSCTL_MEMTIM0_FBCHT_M & ((MEMTIM_PARAM+1)<< 6)) | (SYSCTL_MEMTIM0_EBCHT_M & ((MEMTIM_PARAM+1) << 22)) ); SYSCTL_MEMTIM0_R &= ~(SYSCTL_MEMTIM0_FBCE | SYSCTL_MEMTIM0_EBCE); SYSCTL_RSCLKCFG_R |= (SYSCTL_RSCLKCFG_USEPLL | SYSCTL_RSCLKCFG_MEMTIMU | (PSYSDIV << SYSCTL_RSCLKCFG_PSYSDIV_S)); return; }
ameya134/Real_time_FIR_filtering
src/inc/app.h
/* ***************************************************************** * * Header file for app.c * * Author: <NAME> * Date Created: 4th April 2021 * Date Modified: 16th May 2021 * * *****************************************************************/ #ifndef _APP_H #define _APP_H #include "tm4c129encpdt.h" #include "FreeRTOSConfig.h" /* Macros needed by the application */ /* macros related to led blink task */ #define LED_BLINK_ENABLE 1 #define LED_BLINK_DELAY_MS 1000 #define LED_BLINK_PRIO tskIDLE_PRIORITY+1 /* ADC sampling frequency used by the application in Hertz */ #define TIMER0_FREQUENCY_HZ 48000 /* 48KHz sampling rate */ #define configADC_INT_PRIO (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1) #define FIR_FILTER_PRIO LED_BLINK_PRIO+1 /* PWM period for output is 10 times smaller than sampling rate */ #define OUPUT_PWM_PERIOD_CYCLES ((SYSCLOCK_FREQ_Hz/TIMER0_FREQUENCY_HZ)/10) /* Macros for required data processing */ #define DATA_BUF_LEN 16 /* 16 samples processed at a time */ #define FILTER_LEN 16 /* length of impulse response */ #define CONVOLUTION_LEN (DATA_BUF_LEN + FILTER_LEN -1) /* length of convolution output of input and filter */ /* ******************************************************************************** * * This is the setup function that creates the FreeRTOS tasks * * param: void * * return: void * * brief: This function creates the FreeRTOS tasks and needs to be called * before starting the FreeRTOS scheduler. It creates the FIR_filter_task. * It also creates the LED_blink_task if the LED_BLINK_ENABLE macros is * defined as 1. * * ********************************************************************************/ void app_tasks_setup(void); #endif
ameya134/Real_time_FIR_filtering
test/test.h
<filename>test/test.h /* * Header file for test functions */ #ifndef _TEST_H #define _TEST_H /* This function is called from main when * the PERFORM_TEST flag is set to 1 */ int test_main(void); #endif
ameya134/Real_time_FIR_filtering
src/timestamp.c
/* ***************************************************************** * * This file implements the timestamp functions using timer7 * * Author: <NAME> * Date Created: 6th May 2021 * Date Modified: 6th May 2021 * * ****************************************************************/ #include "timestamp.h" /* *************************************************************************** * * This function initializes the timer7 in 32-bit, one shot, count up mode. * * param: void * * return: void * * brief: This function starts the timer7 in 32-bit, one shot, count up mode * to be used for timekeeping. This function needs to be called initially * before calling other timestamp functions. * * **************************************************************************/ void init_timestamp_timer(void) { /* enable clocking to timer module */ SYSCTL_RCGCTIMER_R |= SYSCTL_RCGCTIMER_R7; /* wait till the peripheral is ready */ while(!(SYSCTL_PRTIMER_R & SYSCTL_PRTIMER_R7)); /* Disable the timer and clear previous configuration * before doing the configuration. * Timer is in 32bit mode by default */ TIMER7_CTL_R &= ~(TIMER_CTL_TAEN); TIMER7_CFG_R = 0x0; /* Configure timer mode * set oneshot mode and disable interrupt * set count direction to count up */ TIMER7_TAMR_R |= (TIMER_TAMR_TACINTD | TIMER_TAMR_TACDIR | TIMER_TAMR_TAMR_1_SHOT); /* load the timer value */ TIMER7_TAILR_R = 0xFFFF; return; } /* *************************************************************************** * * This function returns the count value of the timer7 * * param: void * * return: uint32_t timer7 count value * * brief: This function returns count value of timer7 which can be used to * calculate time period between 2 calls to this function. * * **************************************************************************/ uint32_t getTimeStampVal(void) { return TIMER7_TAV_R; } /* *************************************************************************** * * This function starts the timer7 to count up. * * param: void * * return: void * * brief: This function starts the timer7. Timer7 starts counting up in * one shot mode. * * **************************************************************************/ void TimeStampStart(void) { /* enable timer 0 */ TIMER7_CTL_R |= TIMER_CTL_TAEN; } /* *************************************************************************** * * This function halts the timer7. * * param: void * * return: void * * brief: This function halts the counting of timer7. timer7 retains its * current counting value in TIMER7_TAV_R register. * * **************************************************************************/ void TimeStampHalt(void) { /* disable timer 0 */ TIMER7_CTL_R &= ~(TIMER_CTL_TAEN); } /* *************************************************************************** * * This function restarts the timer7 to count up. * * param: void * * return: void * * brief: This function restarts the timer7. the current value of timer7 is * set to 0 and then Timer7 starts counting up in one shot mode. * * **************************************************************************/ void TimeStampRestart(void) { /* reset the timer value to 0 */ TIMER7_CTL_R &= ~(TIMER_CTL_TAEN); TIMER7_TAV_R = 0; TIMER7_CTL_R |= TIMER_CTL_TAEN; }
ameya134/Real_time_FIR_filtering
src/main.c
/* *********************************************************************** * This is the main file which initializes the FreeRTOS * * main calls the initialization functions and then starts the scheduler * * Author: <NAME> * Date Created: 3rd April 2021 * Last modified: 15th May 2021 * * **********************************************************************/ #include "main.h" #include "system_tm4c.h" #include "../test/test.h" #include "FreeRTOS.h" #include "task.h" #include "app.h" /* ********************************************************************** * The main function calls the system initialize function, rtos task * setup function and then starts the FreeRTOS scheduler. * * if PERFORM_TEST flag has been set to 1 then it directly calls the * test function. * * **********************************************************************/ int main(void){ #if( PERFORM_TEST == 1 ) test_main(); #endif /* system init */ SystemInit(); /* Call the init task for application */ app_tasks_setup(); /* Start FreeRTOS */ vTaskStartScheduler(); /* control should never reach to this point */ while(1){ // wait for interrupt in low power sleep mode __asm("wfi"); } return 0; } /* Idle tasks calls this hook */ void vApplicationIdleHook(void) { /*do any background work here*/ return; } /* A stackoverflow results in a call to this function * and the task hangs in the while loop */ void vApplicationStackOverflowHook( TaskHandle_t xTask, char * pcTaskName ) { while(1); return; } /* A failed call to malloc results in a call to this function * and the task hangs in the while loop */ void vApplicationMallocFailedHook(void) { while(1); return; }
ameya134/Real_time_FIR_filtering
src/system_tm4c.c
<gh_stars>0 /* ******************************************************** * * This file implements the system initilization function * * Author: <NAME> * Date Created: 6th May 2021 * Date Modified: 6th May 2021 * * *******************************************************/ #include <main.h> #include <system_tm4c.h> #include "app.h" #include "clock.h" #include "bsp.h" #include "uart.h" #include "dma.h" #include "adc.h" #include "pwm.h" #include "timer0.h" /* system related functions and declarations */ uint32_t SystemCoreClock = SYSCLOCK_FREQ_Hz; /* System Clock Frequency in Hz */ /* *************************************************************************** * * This function calls the initialization functions for different required * peripherals. * * param: void * * return: void * * brief: This function calls the initialization functions for different * peripherals. PLL is configured to change the system clock frequency. * * **************************************************************************/ void SystemInit(void){ /* Do system initializations */ /* Init system clock and set the PLL */ configure_pll_clock(MOSC_CLOCK_SRC,0U,4U,96U,0U,(4U-1U),5); /* Init UART */ UARTInit((uint32_t)115200); #if( LED_BLINK_ENABLE == 1) /* INIT LED 1 */ INIT_LED_1(); #endif /* Init DMA for ADC */ DMA_init(); /* Initialize the ADC */ ADC_init(); /* Initialize PWM */ PWMLedInit(OUPUT_PWM_PERIOD_CYCLES,1); /* Initialize timer0 */ init_timer0((uint32_t) SystemCoreClock/TIMER0_FREQUENCY_HZ); UARTSendString("system initialization done...\n\r"); return; }
ameya134/Real_time_FIR_filtering
src/hal/adc.c
<reponame>ameya134/Real_time_FIR_filtering /* *************************************************************************** * * This file implements the functions for configuration and use of ADC module * on tm4c129encpdt * * Author: <NAME> * Date Created: 22nd March 2021 * Date Modified: 14th May 2021 * * ***************************************************************************/ #include "adc.h" #include "FreeRTOS.h" #include "task.h" #include "semphr.h" #include "app.h" #include "bsp.h" #include "uart.h" #include "timer0.h" #if( ADC_USE_DMA == 1) /* Variables required by application in the ADC interrupt handler * These are input and output buffers for ADC data and output * buffers. ADC_buf_var contains the information about the * A and B buffer that hardware is using. */ extern volatile int ADC_buf_var; extern int32_t INPUT_BUFFER_A[DATA_BUF_LEN]; extern int32_t INPUT_BUFFER_B[DATA_BUF_LEN]; extern int32_t OUTPUT_BUFFER_A[DATA_BUF_LEN]; extern int32_t OUTPUT_BUFFER_B[DATA_BUF_LEN]; extern struct DMA_control_word TIMER0_channel_control_word; /* This control word is used by the application which needs the * ADC SS0 to generate DMA transfer requests. This control word is * configured according to the needs of the application. */ struct DMA_control_word ADC_channel_control_word = { .XFERMODE = 0x1, /* Basic mode */ .NXTUSEBURST = 0x0, /* no next use burst for last transfers */ .XFERSIZE = (DATA_BUF_LEN -1), /* Transfer size */ .ARBSIZE = 0x2, /* arbitrate after 4 transfers (fifo half full for ss0) */ .SRCPROT0 = 0x0, /* non privilaged access */ /* .reserved1 */ .DESTPROT0 = 0x0, /* non privilaged access */ /* .reserved0 */ .SRCSIZE = 0x1, /* 16 bit data size */ .SRCINC = 0x3, /* No increment */ .DESTSIZE = 0x1, /* 16 bit data size */ .DESTINC = 0x2, /* 32 bit increment */ }; /* ADC_data_ready is a semaphore that is polled by the application */ extern SemaphoreHandle_t ADC_data_ready; BaseType_t xHigherPriorityTaskWoken; /* *********************************************************************************** * * This is the interrupt handler for ADC dma done interrupt. * * param: void * * return: void * * brief: This interrupt handler responds to DMA done signal generated by the DMA * after the completion of transfer of fixed number of samples to input data buffers * as specified by the control word. The application makes use of a dual buffer logic. * When ADC and PWM modules are using buffer A the software processes the data in * input buffer B and stores the output in output buffer B and vice versa. * When a DMA done interrupt is generated the handler checks the adc_buf_var flag and * sets the DMA hardware to use the appropriate buffers for the next samples. After * starting the DMA transfers the application release the ADC_data_ready semaphore on * which the application task is pending. * * ***********************************************************************************/ void ADC0_sequencer0_handler(void) { /* clear the interrupt by writing 1 to ADC0_ISC_R register*/ ADC0_ISC_R |= (ADC_ISC_DMAIN0); /* Use buffers A and B alternately */ if(ADC_buf_var == 0){ ADC_buf_var = 1; DMA_reconfigure_channel( ADC_DMA_CHANNEL_NO, /* channel no 14 for adc0 ss0 */ (uint32_t *) &ADC0_SSFIFO0_R, /* source end pointer */ (uint32_t *) &INPUT_BUFFER_B[DATA_BUF_LEN -1], /* desetination end pointer */ &ADC_channel_control_word /* channel control_word */ ); /* check if all the buffer data has been transmitted to pwm output */ while (!(TIMER0_RIS_R & TIMER_RIS_DMAARIS)); TIMER0_RIS_R |= (TIMER_RIS_DMAARIS); DMA_reconfigure_channel( TIMER0_DMA_CHANNEL_NO, /* channel no 14 for adc0 ss0 */ (uint32_t *)&OUTPUT_BUFFER_B[DATA_BUF_LEN -1], /* source end pointer */ (uint32_t *)&PWM0_0_CMPA_R, /* destination end pointer */ &TIMER0_channel_control_word /* channel control word */ ); } else{ ADC_buf_var = 0; DMA_reconfigure_channel( ADC_DMA_CHANNEL_NO, /* channel no 14 for adc0 ss0 */ (uint32_t *) &ADC0_SSFIFO0_R, /* source end pointer */ (uint32_t *) &INPUT_BUFFER_A[DATA_BUF_LEN -1], /* desetination end pointer */ &ADC_channel_control_word /* channel control_word */ ); /* check if all the buffer data has been transmitted to pwm output */ while (!(TIMER0_RIS_R & TIMER_RIS_DMAARIS)); TIMER0_RIS_R |= (TIMER_RIS_DMAARIS); DMA_reconfigure_channel( TIMER0_DMA_CHANNEL_NO, /* channel no 14 for adc0 ss0 */ (uint32_t *)&OUTPUT_BUFFER_A[DATA_BUF_LEN -1], /* source end pointer */ (uint32_t *)&PWM0_0_CMPA_R, /* destination end pointer */ &TIMER0_channel_control_word /* channel control word */ ); } /* enable/start the dma transfer for input and output * on ADC and timer0 channels of dma */ DMA_start_transfer(ADC_DMA_CHANNEL_NO); DMA_start_transfer(TIMER0_DMA_CHANNEL_NO); /* Release the ADC_data_ready semaphore to start * ADC data processing by FIR_filter_task */ xHigherPriorityTaskWoken = pdFALSE; xSemaphoreGiveFromISR(ADC_data_ready,&xHigherPriorityTaskWoken); if(xHigherPriorityTaskWoken == pdTRUE){ portYIELD_FROM_ISR(xHigherPriorityTaskWoken); } return; } #endif /* ****************************************************************************** * * This function initializes the ADC module. * * param: void * * return: void * * breif: This function enables the ADC module. It sets up the sample sequencer 0 * (SS0) to sample the pin PE3 which is Analog Input pin 0 (AIN0). The ADC SS0 is * triggered when timer0 generates timeout event. Hence the sampling frequency is * equal to the timer0 frequency. * * uDMA for ADC SS0 is set. This generates an dma transfer request when the SS0 * FIFO is half full. Also DMAdone interrupt is enabled by the ADC_USE_DMA macro. * This generates an interrupt when DMA is done transfering predetermined number * of samples to ADC buffer in memory. DMA initialization needs to be done * separately. * * ADC analog clock is set to use the PLL hence PLL needs to configured * before calling this function. * * ******************************************************************************/ void ADC_init(void) { /* enable clock to adc 0 module */ SYSCTL_RCGCADC_R |= SYSCTL_RCGCADC_R0; while(!(SYSCTL_PRADC_R & SYSCTL_PRADC_R0)); /* Set ADC clock to use PLL */ ADC0_CC_R |= ((ADC_CC_CS_M & ADC_CC_CS_SYSPLL) | (ADC_CC_CLKDIV_M & ((30U-1U) << ADC_CC_CLKDIV_S )) ); /* enable clock to port E*/ SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R4; while(!(SYSCTL_PRGPIO_R & SYSCTL_PRGPIO_R4)); /* configure gpio PE3 for AIN0 * *enable alternate port function * *disable digital function on the pin * *select analog mode by disabling analog isolation */ GPIO_PORTE_AHB_AFSEL_R |= (1U<<3); GPIO_PORTE_AHB_DEN_R &= ~(1U<<3); GPIO_PORTE_AHB_AMSEL_R |= (1U<<3); /* Configure the sample sequencer 0 * *Disable SS0 * *set trigger event in ADCEMUX to timer trigger * *Set end bit after last sample and enable raw interrupt status * without enabling interrupt mask so that software can poll * raw interrupt status. * */ ADC0_ACTSS_R &= ~(ADC_ACTSS_ASEN0); ADC0_EMUX_R |= (ADC_EMUX_EM0_M & ADC_EMUX_EM0_TIMER); /*timer trigger*/ ADC0_SSMUX0_R |= (0x0 << ADC_SSMUX0_MUX0_S); ADC0_SSCTL0_R |= (ADC_SSCTL0_IE0 | ADC_SSCTL0_END0); #if( ADC_USE_DMA == 1) /* Enable the dma for ss0 * Enable the bit mask and nvic register for ss0 * Set the interrupt prio lower (higher number) * than FreeRTOS maxprio for syscall in order to call the FreeRTOS * API from interrupt handler * * 3 prio bits have been implemented on tm4c129encpdt. bits are located * at MSB portion of corresponding 8 bit field in NVIC prio registers * */ ADC0_ACTSS_R |= (ADC_ACTSS_ADEN0); ADC0_IM_R |= (ADC_IM_DMAMASK0); NVIC_EN0_R |= (1U << ADC0_SS0_INT_NUM); NVIC_PRI3_R |= ( ( ADC0_SS0_INT_NVIC_PRIO << (8 - configPRIO_BITS) ) << 2*8); #endif /* enable SS0 */ ADC0_ACTSS_R |= ADC_ACTSS_ASEN0; } /* ******************************************************************************* * * This function returns the sampled value from SS0 FIFO register * * param: void * * return uint16 12 bit sample value from SSO FIFO * * brief: ADC SS0 stores its sampled values in SS0 FIFO. this * function reads the FIFO register and returns a 16 bit value * containing th 12 bit sample data. * * *******************************************************************************/ uint16_t ADC_get_val(void) { return (ADC_SSFIFO0_DATA_M & ADC0_SSFIFO0_R); }
ameya134/Real_time_FIR_filtering
src/hal/pwm.c
<filename>src/hal/pwm.c /* *********************************************************** * This file implements the functions used to configure and * use the pwm module present on tm4c129encpdt * This file uses TI's provided tm4c129encpdt.h header file * * Author: <NAME> * Date created: 13th Dec 2020 * Last modified: 8th Jan 2021 * * ***********************************************************/ #include "tm4c129encpdt.h" #include "main.h" #include "pwm.h" #include "uart.h" /* ******************************************************************** * This function initializes the pwm unit and led * * param: period time period of the pwm in clock cycle. * * param: duty duty cycle in percentage for the pwm. * * return: void * * brief: This function configures and enables the pwm module and the * gpio module required to send the pwm output to led on port F pin 4. * port F pin 4 is configured as a tertiary function pin which is driven * by the pwm module. * * ********************************************************************/ void PWMLedInit(uint32_t period, uint8_t duty){ /* Enable power to the pwm module */ SYSCTL_RCGCPWM_R |= SYSCTL_RCGCPWM_R0; while(!(SYSCTL_PRPWM_R & SYSCTL_PRPWM_R0)); /* Enable power to the gpio module */ SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R5; while(!(SYSCTL_PRGPIO_R & SYSCTL_PRGPIO_R5)); /* init gpio */ GPIO_PORTF_AHB_DEN_R |= (1U<<0); GPIO_PORTF_AHB_AFSEL_R |= (1U<<0); GPIO_PORTF_AHB_PCTL_R |= (0x06<<0); /* Init PWM */ /* disable the pwm before setup*/ PWM0_0_CTL_R |= (0x0<<0); PWM0_0_GENA_R |= ((0x3<<6) | (0x2<<2)); uint32_t loadVal = period; uint32_t dutyVal = (duty * period)/100; PWM0_0_LOAD_R = loadVal; PWM0_0_CMPA_R = dutyVal; PWM0_0_CTL_R |= (1U<<0); PWM0_ENABLE_R |= (1U<<0); return; } /* ******************************************************************** * This function updates the duty cycle of pwm * * param: duty duty cycle in percentage for the pwm. * * return: void * * brief: Updates the compare register to update the duty cycle of the * pwm signal. * * ********************************************************************/ void PWMLedDutyUpdate(uint8_t duty){ uint32_t temp; /* If duty is greater than 100 set it as 100. * load_val -1 is done so as pwm would stop if * compare and load values are same */ if(duty >= 100){ temp = PWM0_0_LOAD_R - 1; } else{ temp = (duty * PWM0_0_LOAD_R)/100; } PWM0_0_CMPA_R = temp; return; } /* ******************************************************************** * This function initializes the pwm unit and led * * param: void * * return: duty returns the duty cycle of the pwm signal * * brief: Calculates and returns the current duty cycle value from * compare and load registers. * * ********************************************************************/ uint8_t PWMGetDuty(void){ uint8_t duty = (100*PWM0_0_CMPA_R)/PWM0_0_LOAD_R; return (duty); }
ameya134/Real_time_FIR_filtering
src/inc/hal/adc.h
/* ******************************************************** * Header file for ADC module * * Author: <NAME> * Date Created: 22nd March 2021 * Date Modified: 14th May 2021 * * ********************************************************/ #ifndef _ADC_H #define _ADC_H #include "tm4c129encpdt.h" #include "main.h" #include "app.h" /* macro for configuring dma for adc in ADC_init */ #define ADC_USE_DMA 1 #if( ADC_USE_DMA == 1) #include "dma.h" /* Channel no and peripheral encoding number * for ADC SS0 channel of uDMA */ #define ADC_DMA_CHANNEL_NO 14 #define ADC_DMA_CHANNEL_ENCODE 0 /* ADC SS0 interrupt number and interrupt priority */ #define ADC0_SS0_INT_NUM 14 #define ADC0_SS0_INT_NVIC_PRIO configADC_INT_PRIO /* *********************************************************************************** * * This is the interrupt handler for ADC dma done interrupt. * * param: void * * return: void * * brief: This interrupt handler responds to DMA done signal generated by the DMA * after the completion of transfer of fixed number of samples to input data buffers * as specified by the control word. The application makes use of a dual buffer logic. * When ADC and PWM modules are using buffer A the software processes the data in * input buffer B and stores the output in output buffer B and vice versa. * When a DMA done interrupt is generated the handler checks the adc_buf_var flag and * sets the DMA hardware to use the appropriate buffers for the next samples. After * starting the DMA transfers the application release the ADC_data_ready semaphore on * which the application task is pending. * * ***********************************************************************************/ void ADC0_sequencer0_handler(void); #endif /* ****************************************************************************** * * This function initializes the ADC module. * * param: void * * return: void * * breif: This function enables the ADC module. It sets up the sample sequencer 0 * (SS0) to sample the pin PE3 which is Analog Input pin 0 (AIN0). The ADC SS0 is * triggered when timer0 generates timeout event. Hence the sampling frequency is * equal to the timer0 frequency. * * uDMA for ADC SS0 is set. This generates an dma transfer request when the SS0 * FIFO is half full. Also DMAdone interrupt is enabled by the ADC_USE_DMA macro. * This generates an interrupt when DMA is done transfering predetermined number * of samples to ADC buffer in memory. DMA initialization needs to be done * separately. * * ADC analog clock is set to use the PLL hence PLL needs to configured * before calling this function. * * ******************************************************************************/ void ADC_init(void); /* ******************************************************************************* * * This function returns the sampled value from SS0 FIFO register * * param: void * * return uint16 12 bit sample value from SSO FIFO * * brief: ADC SS0 stores its sampled values in SS0 FIFO. this * function reads the FIFO register and returns a 16 bit value * containing th 12 bit sample data. * * *******************************************************************************/ uint16_t ADC_get_val(void); #endif
ameya134/Real_time_FIR_filtering
src/inc/convolution.h
/* ***************************************************************** * * Header file for convolution.c * * Author: <NAME> * Date Created: 5th May 2021 * Date Modified: 5th May 2021 * * *****************************************************************/ #ifndef _CONVOLUTION_H #define _CONVOLUTION_H #include "main.h" /* ********************************************************************** * This function computes the linear convolution of two signals * of length 16 * * param: x pointer to signal 1 array (generally input) * param: h pointer to signal 2 array (generally transfer function) * param: y pointer to output array to store answer of convolution * * return: void * * brief: This function computes the Linear Convolution of two descrete * time signals of length 16. The length of output is (2*16 -1) = 31. * * ***********************************************************************/ void convolve_16x16(int32_t *x,int32_t *h, int32_t *y); #endif
ameya134/Real_time_FIR_filtering
test/test_1.c
/* ******************************************************************** * * This file can be used to run any test funtions * * *******************************************************************/ #include "main.h" #include "clock.h" #include "uart.h" #include "convolution.h" #include "timestamp.h" /* Mock input output array for testing convolution function */ int32_t arr_x[16] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int32_t arr_h[16] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int32_t arr_y[16] = {0}; /* run any functions that need to be tested for time here */ void test1(void) { convolve_16x16(arr_x,arr_h,arr_y); return; } /* system inits required for running test */ void System_Init(void) { /* Init system clock and set the PLL */ configure_pll_clock(MOSC_CLOCK_SRC,0U,4U,96U,0U,(4U-1U),5); /* Init UART */ UARTInit((uint32_t)115200); init_timestamp_timer(); return; } int test_main(void) { uint32_t time1,time2; System_Init(); /* timer initialize */ TimeStampStart(); /* record timer values before and after running * the test to find out runtime */ time1 = getTimeStampVal(); test1(); time2 = getTimeStampVal(); /* print the timer values */ UARTPrintNumToString(time1); UARTSendString("\n\r"); UARTPrintNumToString(time2); UARTSendString("\n\r"); /* Hang at the loop at the end of test * for system state examination */ while(1); return 0; }
ameya134/Real_time_FIR_filtering
src/inc/hal/bsp.h
#ifndef BSP_H #define BSP_H #include <stdint.h> #include "tm4c129encpdt.h" #define GPIO_PORT_N 12 #define GPIO_PORT_F 5 /*connected to port N*/ #define LED1_PIN 1 #define LED1_PORT GPIO_PORT_N #define LED2_PIN 0 #define LED2_PORT GPIO_PORT_N /*connected to port F*/ #define LED3_PIN 4 #define LED3_PORT GPIO_PORT_F #define LED4_PIN 0 #define LED4_PORT GPIO_PORT_F /* Initialises the led connected to * port N pin 1 as gpio output */ void INIT_LED_1(void); /* Initialises the led connected to * port N pin 0 as gpio output */ void INIT_LED_2(void); /* Initialises the led connected to * port F pin 4 as gpio output */ void INIT_LED_3(void); /* Initialises the led connected to * port F pin 0 as gpio output */ void INIT_LED_4(void); /* ************************************************************ * This function turns the led on * * param: portBase the port letter of the led * param: pinNo the pin no of led pin * * return: void * * brief: Function turns on led connected to port portBase and * pin pinNo * * ************************************************************/ void LED_TURN_ON(uint8_t portBase, uint8_t pinNO); /* ************************************************************ * This function turns the led off * * param: portBase the port letter of the led * param: pinNo the pin no of led pin * * return: void * * brief: Function turns off led connected to port portBase and * pin pinNo * * ************************************************************/ void LED_TURN_OFF(uint8_t portBase, uint8_t pinNO); /* ************************************************************ * This function toggles the led * * param: portBase the port letter of the led * param: pinNo the pin no of led pin * * return: void * * brief: Function toggles the led connected to port portBase and * pin pinNo * * ************************************************************/ void LED_TOGGLE_STATE(uint8_t portBase, uint8_t pinNO); #endif
ameya134/Real_time_FIR_filtering
src/inc/hal/pwm.h
/* ******************************************************** * This file provides the funciton prototypes for * configuration and use of pwm module which is present on * tm4c129encpdt * * Author: <NAME> * Date created: 13th Dec 2020 * Last modified: 8th Jan 2021 * * ********************************************************/ #ifndef _PWM_H #define _PWM_H /* ******************************************************************** * This function initializes the pwm unit and led * * param: period time period of the pwm in clock cycle. * * param: duty duty cycle in percentage for the pwm. * * return: void * * brief: This function configures and enables the pwm module and the * gpio module required to send the pwm output to led on port F pin 4. * port F pin 4 is configured as a tertiary function pin which is driven * by the pwm module. * * ********************************************************************/ void PWMLedInit(uint32_t period, uint8_t duty); /* ******************************************************************** * This function updates the duty cycle of pwm * * param: duty duty cycle in percentage for the pwm. * * return: void * * brief: Updates the compare register t update the duty cycle of the * pwm signal. * * ********************************************************************/ void PWMLedDutyUpdate(uint8_t duty); /* ******************************************************************** * This function initializes the pwm unit and led * * param: void * * return: duty returns the duty cycle of the pwm signal * * brief: Calculates and returns the current duty cycle value from * compare and load registers. * * ********************************************************************/ uint8_t PWMGetDuty(void); #endif
ameya134/Real_time_FIR_filtering
src/string.c
#include "stdint.h" #include "string.h" /* ******************************************************************************* * This function converts an integer into its base 10 string representation * * param: num number that is to be converted into string format * * param: restStr pointer to string where results are written to. * * param: numZeros number of leading zeros * * return: void * * brief: The function converts the integer value into its base 10 character * represenation. The result is written to the memory where retStr pointer points * * *******************************************************************************/ void convertIntToString(uint32_t num, char *retStr,int numZeros){ int i=0; if(num == 0){ retStr[0] = '0'; retStr[1] = '\0'; return; } while(num !=0){ retStr[i] = '0' + num%10; num /= 10; i++; } if(i < numZeros){ while(i<numZeros){ retStr[i] = '0'; i++; } } reverseString(retStr, i); /* '\0' is appended at the end */ retStr[i] = '\0'; return; } /* *************************************************************************** * This function converts a base 10 representation of string to an integer * * param: str pointer to the string to be converted * * return: uint32_t returns the integer value represented by the string * * brief: The function converts the string values into integer equivalent and * returns the integer value. * * **************************************************************************/ uint32_t convertStringToInt(char *str){ int i=0; uint32_t num=0; if((str[i] < '0') | (str[i] > '9')){ return 0; } while(str[i] != '\0'){ num *= 10; num += str[i] - '0'; i++; } return num; } /* *************************************************************************** * This function reverses the index order of the characters in the string * * param: str pointer to the string to be reversed * * param: len length of the string to be reversed * * return: void * * brief: The function reverses the order of characters in a string for a given * length. It is possible to reverse only a part of the string. * * **************************************************************************/ void reverseString(char *str, uint8_t len){ char temp; uint8_t i; for(i=0;i<len/2;i++){ temp = str[i]; str[i] = str[len-1-i]; str[len-1-i] = temp; } return; } /* *************************************************************************** * This function compares two strings * * param: str1 pointer to the first string to be compared * param: str2 pointer to the second string to be compared * * return: uint32_t returns the result of comparison * * brief: The function compares two strings by subtracting their values. both * strings need to be null terminated. if both strings are identical then 0x00 * is returned. If the strings don't match then -1 is returned. * * **************************************************************************/ int32_t strCmp(char *str1, char *str2,int len){ int i=0; while((str1[i] - str2[i]) == 0){ /* return either if end of string is reached or * strings match upto specified length * len is passed as -ve value for ignoring the len val*/ if( ((str1[i] == '\0') && (str2[i] == '\0')) || (i == len)){ return 0; } i++; } return -1; } /* *************************************************************************** * This sets the value of the memory location * * param: __ptr pointer to the start of memory location * param: value value to be set at memory location * param: len length of memory location * * return: pointer to memory location * * brief: This function sets the value from mem location __ptr to __ptr + len * to value arg given by caller * **************************************************************************/ void *memset(void * __ptr, uint8_t value, uint32_t len){ uint32_t i; uint8_t *ptr = (uint8_t *) __ptr; if(ptr == 0) return 0; for(i=0;i<len;i++) *ptr++ = value; return ((void *)__ptr); } /* *************************************************************************** * This function copies data from __src to __dst * * param: __dst pointer to the copy destination * param: str2 pointer to the source * param: length of memory to be copied * * return: pointer to destination * * brief: The function compares two strings by subtracting their values. both * strings need to be null terminated. if both strings are identical then 0x00 * is returned. If the strings don't match then -1 is returned. * * **************************************************************************/ void *memcpy(void *__dst, const void *__src, uint32_t len) { uint8_t *src = (uint8_t *) __src; uint8_t *dst = (uint8_t *) __dst; uint32_t i; if ((src == 0) | (dst == 0)) return 0; for(i=0;i<len;i++) *dst++ = *src++; return ((void*)__dst); }
ameya134/Real_time_FIR_filtering
src/inc/system_tm4c.h
/* ******************************************************** * * Header file for system related functions * * Author: <NAME> * Date Created: 6th May 2021 * Date Modified: 6th May 2021 * * *******************************************************/ #ifndef _SYSTEM_TM4C #define _SYSTEM_TM4C /* variable for system clock frequency */ extern uint32_t SystemCoreClock; /* *************************************************************************** * * This function calls the initialization functions for different required * peripherals. * * param: void * * return: void * * brief: This function calls the initialization functions for different * peripherals. PLL is configured to change the system clock frequency. * * **************************************************************************/ void SystemInit(void); #endif
ameya134/Real_time_FIR_filtering
src/inc/string.h
#ifndef _STRING_H #define _STRING_H #include "stdint.h" /* ******************************************************************************* * This function converts an integer into its base 10 string representation * * param: num number that is to be converted into string format * * param: restStr pointer to string where results are written to. * * param: numZeros number of leading zeros * * return: void * * brief: The function converts the integer value into its base 10 character * represenation. The result is written to the memory where retStr pointer points * * *******************************************************************************/ void convertIntToString(uint32_t num, char *retStr, int numZeros); /* *************************************************************************** * This function converts a base 10 representation of string to an integer * * param: str pointer to the string to be converted * * return: uint32_t returns the integer value represented by the string * * brief: The function converts the string values into integer equivalent and * returns the integer value. * * **************************************************************************/ uint32_t convertStringToInt(char *str); /* *************************************************************************** * This function reverses the index order of the characters in the string * * param: str pointer to the string to be reversed * * param: len length of the string to be reversed * * return: void * * brief: The function reverses the order of characters in a string for a given * length. It is possible to reverse only a part of the string. * * **************************************************************************/ void reverseString(char * str, uint8_t len); /* *************************************************************************** * This function compares two strings * * param: str1 pointer to the first string to be compared * param: str2 pointer to the second string to be compared * * return: uint32_t returns the result of comparison * * brief: The function compares two strings by subtracting their values. both * strings need to be null terminated. if both strings are identical then 0x00 * is returned. If the strings don't match then -1 is returned. * * **************************************************************************/ int32_t strCmp(char *str1, char *str2,int len); /* *************************************************************************** * This sets the value of the memory location * * param: __ptr pointer to the start of memory location * param: value value to be set at memory location * param: len length of memory location * * return: pointer to memory location * * brief: This function sets the value from mem location __ptr to __ptr + len * to value arg given by caller * **************************************************************************/ void *memset(void *__ptr, uint8_t value, uint32_t len); /* *************************************************************************** * This function copies data from __src to __dst * * param: __dst pointer to the copy destination * param: str2 pointer to the source * param: length of memory to be copied * * return: pointer to destination * * brief: The function compares two strings by subtracting their values. both * strings need to be null terminated. if both strings are identical then 0x00 * is returned. If the strings don't match then -1 is returned. * * **************************************************************************/ void *memcpy(void *__dst, const void *__src, uint32_t len); #endif
ameya134/Real_time_FIR_filtering
src/hal/bsp.c
/* This is the led driver for ek-tm4c129exl launchpad * this driver works with tm4c129encpdt.h provided by TI * in tivaware. */ #include "bsp.h" /* variable to monitor state of leds. * can be used from other files by extern */ static uint8_t ledBits=0x00; /* Initialises the led connected to * port N pin 1 as gpio output */ void INIT_LED_1(void) { /* start clock to port N(12th port)*/ SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R12; while(!(SYSCTL_PRGPIO_R & SYSCTL_PRGPIO_R12)); GPIO_PORTN_DIR_R |= (1U<<LED1_PIN); GPIO_PORTN_DEN_R |= (1U<<LED1_PIN); GPIO_PORTN_DATA_R &= ~(1U<<LED1_PIN); ledBits &= ~(1U<<LED1_PIN); } /* Initialises the led connected to * port N pin 0 as gpio output */ void INIT_LED_2(void) { /* start clock to port N(12th port)*/ SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R12; while(!(SYSCTL_PRGPIO_R & SYSCTL_PRGPIO_R12)); GPIO_PORTN_DIR_R |= (1U<<LED2_PIN); GPIO_PORTN_DEN_R |= (1U<<LED2_PIN); GPIO_PORTN_DATA_R &= ~(1U<<LED2_PIN); ledBits &= ~(1U<<LED2_PIN); } /* Initialises the led connected to * port F pin 4 as gpio output */ void INIT_LED_3(void) { /* start clock to port F(5th port)*/ SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R5; while(!(SYSCTL_PRGPIO_R & SYSCTL_PRGPIO_R5)); GPIO_PORTF_AHB_DIR_R |= (1U<<LED3_PIN); GPIO_PORTF_AHB_DEN_R |= (1U<<LED3_PIN); GPIO_PORTF_AHB_DATA_R &= ~(1U<<LED3_PIN); ledBits &= ~(1U<<LED3_PIN); } /* Initialises the led connected to * port F pin 0 as gpio output */ void INIT_LED_4(void) { /* start clock to port F(5th port)*/ SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R5; while(!(SYSCTL_PRGPIO_R & SYSCTL_PRGPIO_R5)); GPIO_PORTF_AHB_DIR_R |= (1U<<LED4_PIN); GPIO_PORTF_AHB_DEN_R |= (1U<<LED4_PIN); GPIO_PORTF_AHB_DATA_R &= ~(1U<<LED4_PIN); ledBits &= ~(1U<<LED4_PIN); } /* ************************************************************ * This function turns the led on * * param: portBase the port letter of the led * param: pinNo the pin no of led pin * * return: void * * brief: Function turns on led connected to port portBase and * pin pinNo * * ************************************************************/ void LED_TURN_ON(uint8_t portBase, uint8_t pinNO) { if(portBase == GPIO_PORT_N) GPIO_PORTN_DATA_R |= (1U<<pinNO); if(portBase == GPIO_PORT_F) GPIO_PORTF_AHB_DATA_R |= (1U<<pinNO); ledBits |= (1U<<LED1_PIN); } /* ************************************************************ * This function turns the led off * * param: portBase the port letter of the led * param: pinNo the pin no of led pin * * return: void * * brief: Function turns off led connected to port portBase and * pin pinNo * * ************************************************************/ void LED_TURN_OFF(uint8_t portBase, uint8_t pinNO) { if(portBase == GPIO_PORT_N) GPIO_PORTN_DATA_R &= ~(1U<<pinNO); if(portBase == GPIO_PORT_F) GPIO_PORTF_AHB_DATA_R &= ~(1U<<pinNO); ledBits &= ~(1U<<LED1_PIN); } /* ************************************************************ * This function toggles the led * * param: portBase the port letter of the led * param: pinNo the pin no of led pin * * return: void * * brief: Function toggles the led connected to port portBase and * pin pinNo * * ************************************************************/ void LED_TOGGLE_STATE(uint8_t portBase, uint8_t pinNO) { if(portBase == GPIO_PORT_N) GPIO_PORTN_DATA_R ^= (1U<<pinNO); if(portBase == GPIO_PORT_F) GPIO_PORTF_AHB_DATA_R ^= (1U<<pinNO); ledBits ^= (1U<<LED1_PIN); }
ameya134/Real_time_FIR_filtering
src/inc/main.h
/* PROJECT HEADER FILE FOR IMPORTAT CONSTANTS */ #ifndef _MAIN_H #define _MAIN_H #include "stdint.h" #include "clock.h" /* SYSTEM RELATED MACROS ARE DECLARED HERE */ /* clock source selection macro */ #define SYS_CLOCK_SRC MOSC_CLOCK_SRC /* Use main external oscilator of 25MHz */ /* system clock frequency */ #define SYSCLOCK_FREQ_Hz 120000000 /* Sysclock frequency is 120 MHz */ /* Set this macro to 1 to call the test function */ #define PERFORM_TEST 0 #endif
ameya134/Real_time_FIR_filtering
src/hal/dma.c
<gh_stars>0 /* ************************************************************** * * This file defines the functions needed to configure and use * the DMA peripheral on tm4c129encpdt microcontroller. * * Author: <NAME> * Date Created: 15th April 2021 * Date Modified: 13th May 2021 * * *************************************************************/ #include "main.h" #include "dma.h" #include "hw_types.h" /* ******************************************************************** * This function Initializes the DMA module. * * param: void * * return: void * * brief: This function inititalizes the DMA module and sets the pointer * to the control table located in the SRAM. * * ********************************************************************/ void DMA_init(void) { /* Enable the clock to the dma perpheral */ SYSCTL_RCGCDMA_R |= SYSCTL_RCGCDMA_R0; while(!(SYSCTL_PRDMA_R & SYSCTL_PRDMA_R0)); /* Set dma master enable bit and set the * channel control base pointer*/ UDMA_CFG_R |= UDMA_CFG_MASTEN; UDMA_CTLBASE_R = (uint32_t) &DMA_control_table; return; } /* ******************************************************************************************** * This function configures a channel to transfer data from source * to destination. * * param: channel_no DMA channel to be configured for transfer * param: channel_encoding encoding value for the peripheral connected to channel * param: burstModeOnly Channel responds to only burst requests when this is 1. * param: src_end_ptr pointer to the last memory location of the * source buffer or memory location * param: dest_end_ptr pointer to the last memory location of the * destination buffer or memory location * param: control_word control word for the configuration of channel * * return: void * * brief: This function configures the DMA channel to transfer data from source location * to the destination. the source and/or destination can be single memory locations or * arrays of memory locations. The size of elements, transfer size, transfer type is programmed * in the control word. * * ********************************************************************************************/ void DMA_configure_channel(uint8_t channel_no,uint8_t channel_encoding,uint8_t burstModeOnly, uint32_t *src_end_ptr,uint32_t *dst_end_ptr, struct DMA_control_word *control_word) //uint8_t data_size, uint8_t arbsize, uint16_t xfersize) { /* channel priority is default */ /* UDMA_PRIOSET_R |= (1U << channel_no) */ /* select primary channel control structure */ UDMA_ALTCLR_R |= (1U << channel_no); /* set dma to respond to burst request */ if(burstModeOnly){ UDMA_USEBURSTSET_R |= (1U << channel_no); } else{ UDMA_USEBURSTCLR_R |= (1U << channel_no); } /* clear the mask for the channel to recognize the requests */ UDMA_REQMASKCLR_R |= (1U << channel_no); /* configure channel assignments */ HWREG(((uint32_t)&UDMA_CHMAP0_R) + ((channel_no >> 3)*4)) |= ( (0xF & channel_encoding) << (4*(0x07 & channel_no))); /* configure the channel control structure */ DMA_control_table.channel_ctl_struct[channel_no].src_end_ptr = src_end_ptr; DMA_control_table.channel_ctl_struct[channel_no].dst_end_ptr = dst_end_ptr; DMA_control_table.channel_ctl_struct[channel_no].control_word = *control_word; return; } /* ******************************************************************************************** * This function reconfigures the dma channel after the previous transfer has been completed. * * param: channel_no DMA channel to be configured for transfer * param: src_end_ptr pointer to the last memory location of the * source buffer or memory location * param: dest_end_ptr pointer to the last memory location of the * destination buffer or memory location * param: control_word control word for the configuration of channel * * return: void * * brief: This function reconfigures the dma channel after the previous transfer has been * completed. * * ********************************************************************************************/ void DMA_reconfigure_channel(uint8_t channel_no, uint32_t *src_end_ptr, uint32_t *dst_end_ptr, struct DMA_control_word *control_word) { DMA_control_table.channel_ctl_struct[channel_no].src_end_ptr = src_end_ptr; DMA_control_table.channel_ctl_struct[channel_no].dst_end_ptr = dst_end_ptr; DMA_control_table.channel_ctl_struct[channel_no].control_word = *control_word; return; } /* ******************************************************************** * This function starts/enables the DMA transfers on a channel. * * param: channel_no Dma channel no to be enabled/ started. * * return: void * * brief: This function starts/ enables the dma channel to responds to * transfer requests from peripherals and/or software triggers. * ********************************************************************/ void DMA_start_transfer(uint8_t channel_no) { UDMA_ENASET_R |= (1U << channel_no); }
ameya134/Real_time_FIR_filtering
src/hal/uart.c
<reponame>ameya134/Real_time_FIR_filtering /* *************************************************************************** * This file contains the implementation of functions to send * data using the UART 0. compatible with TI's tivaware microcontroller * header file * * Author: <NAME> * Date created: 4th Dec 2020 * Last modified: 8th Jan 2021 * * ***************************************************************************/ #include "main.h" #include "tm4c129encpdt.h" #include "uart.h" #include "string.h" /* ******************************************************************************* * This function initializes the UART module * * param: baudrate data transfer rate in bits/sec for UART module * * return: void * * brief: The following function initializes all the necessary gpio and * UART module settings to use UART * * baud rate is calculated using following formula * * BRD = BRDI + BRDF = UARTsysclk / (clkdiv * baudrate) * * where BRDI is the 16 bit integer part and BRDF is the * 6 bit fractional part * * *******************************************************************************/ void UARTInit(uint32_t baudrate){ /* Enable the power to UART Module and appropriate GPIO port*/ SYSCTL_RCGCUART_R |= SYSCTL_RCGCUART_R0; while(!(SYSCTL_PRUART_R & SYSCTL_PRUART_R0)); SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R0; while(!(SYSCTL_PRGPIO_R & SYSCTL_PRGPIO_R0)); /* enable DEN and AFSEL for PA0 and PA1 */ GPIO_PORTA_AHB_DEN_R |= ((1U<<1) | (1U<<0)); GPIO_PORTA_AHB_AFSEL_R |= ((1U<<1) | (1U<<0)); /* Set 4bit field in GPIOPCTL reg for tx, rx pins */ GPIO_PORTA_AHB_PCTL_R |= ((0x01<<4) | (0x01<<0)); /* set the UART control register and baudrate * first we disable the UART then set the parameters * then reenable the UART * * set bit 9 for Rx enable * set bit 8 for Tx enable * set bit 0 for UART enable*/ /* disable UART temporarily*/ UART0_CTL_R &= ~(1U<<0); UART0_CTL_R |= ((1U<<9) | (1U<<8)); UART0_IBRD_R = (uint32_t) SYSCLOCK_FREQ_Hz / (16 * baudrate); //float temp = 0.425347; //UART0_FBRD_R = (uint32_t) 44;//((temp *64) + 0.5); //float temp = 0.104; UART0_FBRD_R = (uint32_t) 7;//((temp *64) + 0.5); UART0_LCRH_R |= (0x03<<5); UART0_CC_R |= (0x00<<0); /* enable UART */ UART0_CTL_R |= (1U<<0); return; } /* *************************************************************************** * This function receives a byte of data through UART module * * param: void * * return: uint8_t return a byte of data received from uart module * * brief: The function return a byte of data received by the UART module on * the Rx pin of the microcontroller. A value of 0x00 is returned if no new * data is available. * * **************************************************************************/ uint8_t UARTRecvChar(void){ /* check if new data is available, * otherwise return 0 */ if((UART0_FR_R & (1U<<6))){ return ((uint8_t) UART0_DR_R); } return 0; } /* ****************************************************************************** * This function sends a byte of data through UART module * * param: c byte of data that is to be sent * * return: void * * brief: The functions sends a byte of data through uart module when an ongoing * transmission if any is completed. * * *****************************************************************************/ void UARTSendChar(char c){ /* check the busy flag */ while(UART0_FR_R & (1U<<5)); UART0_DR_R = c; return; } /* ********************************************************************************* * This function sends a string of data through UART module * * param: s pointer to the string/ char array of the data that is to be sent. * * return: void * * brief: The function send the string, pointed by the pointer argument through the * UART module. The function keeps sending the next byte until null terminating char * is reached. It is expected that the string to be sent is terminated * with '\0' by the caller. * * ********************************************************************************/ void UARTSendString(char *s){ while(*s != '\0'){ UARTSendChar(*s); s++; } return; } /* ********************************************************************************** * This function sends a BASE 10 character representation of an integer through UART. * * param: num The number that is to be sent through UART. * * return: void * * brief: This function sends the BASE 10 character representation of an integer. * This function relies on a function which is used to convert integer into string. * * *********************************************************************************/ #ifdef _STRING_H char tempStr[12]; void UARTPrintNumToString(uint32_t num){ convertIntToString(num, tempStr,4); UARTSendString(tempStr); return; } #endif
ameya134/Real_time_FIR_filtering
src/inc/hal/clock.h
/* ******************************************************** * This file provides the API declaration for * configuration and use of various clock sources which are * present on tm4c129encpdt * * Author: <NAME> * Date created: 28th April 2021 * Last modified: 13th May 2021 * * ********************************************************/ #ifndef _CLOCK_H #define _CLOCK_H #include "tm4c129encpdt.h" /* DEFINES for clock sources */ #define PIOSC_CLOCK_SRC 0 #define MOSC_CLOCK_SRC 1 /* Frequency in Hertz for various clock sources */ #define PIOSC_FREQ_Hz 16000000 /* Precision internal oscilator at 16MHz */ #define MOSC_FREQ_Hz 25000000 /* Main external crystal oscilator at 25MHz */ /* ******************************************************************************* * This function configures the PLL to produce the desired * clock frequency for the system clock. * * param: clock_src The clock source input to the PLL(MOSC,PIOSC etc) * param: Q Q is a divisor value for PLL * param: N N is a divisor value for PLL * param: MINT Integer part of PLL multiplier value * param: MFRAC Fractional part of PLL multiplier value * param: PSYDIV clock divisor for PLL VCO frequency. * param: MEMTIM_PARAM memory timing parameter * * return: void * * brief: This function takes arguments for PLL multiplier and divisor and sets the * Pll output frequency accordingly. * * PLL can be set to use either PIOSC_CLOCK_SRC (16MHz) or * MOSC_CLOCK_SRC (externally connected crystal). * * The output frequency of the PLL can be calculated with the help of following * formulae. * * PLL output freq Fvco = Fin * MDIV * * where, * * Fin = Fxtal/((Q+1)*(N+1)) * * and * * MDIV = MINT + MFRAC/1024 * * The system clock frequency SysClock is obtained by following equation. * * SysClk = Fvco / (PSYDIV + 1) * * As the system clock frequency is changed we need to change the memory timing parameters. * The appropriate Memory timing parameters for a bracket of frequency range are given * in the datasheet and should be appropriately passed by the caller. * * *******************************************************************************/ void configure_pll_clock(int clock_src,int Q, int N,int MINT, int MFRAC,int PSYSDIV,int MEMTIM_PARAM); #endif
ameya134/Real_time_FIR_filtering
src/inc/hal/uart.h
/* ******************************************************** * This is the header file for UART functions declarations * * Author: <NAME> * Date created: 4th Dec 2020 * Last modified: 8th Jan 2021 * * ********************************************************/ #ifndef _UART_H #define _UART_H /* *************************************************************************** * This function initializes the UART module * * param: baudrate data transfer rate in bits/sec for UART module * * return: void * * brief: The following function initializes the all the necessary gpio and * UART module settings to use UART * * baud rate is calculated using following formula * * BRD = BRDI + BRDF = UARTsysclk / (clkdiv * baudrate) * * where BRDI is the 16 bit integer part and BRDF is the * 6 bit fractional part * * **************************************************************************/ void UARTInit(uint32_t baudrate); /* *************************************************************************** * This function receives a byte of data through UART module * * param: void * * return: uint8_t return a byte of data received from uart module * * brief: The function return a byte of data received by the UART module on * the Rx pin of the microcontroller. A value of 0x00 is returned if no new * data is available. * * **************************************************************************/ uint8_t UARTRecvChar(void); /* ****************************************************************************** * This function sends a byte of data through UART module * * param: c byte of data that is to be sent * * return: void * * brief: The functions sends a byte of data through uart module when an ongoing * transmission if any is completed. * * *****************************************************************************/ void UARTSendChar(char c); /* ********************************************************************************* * This function sends a string of data through UART module * * param: s pointer to the string/ char array of the data that is to be sent. * * return: void * * brief: The function send the string, pointed by the pointer argument through the * UART module. The function keeps sending the next byte until null terminating char * is reached. It is expected that the string to be sent is terminated * with '\0' by the caller. * * ********************************************************************************/ void UARTSendString(char *s); /* ********************************************************************************** * This function sends a BASE 10 character representation of an integer through UART. * * param: num The number that is to be sent through UART. * * return: void * * brief: This function sends the BASE 10 character representation of an integer. * This function relies on a function which is used to convert integer into string. * * *********************************************************************************/ void UARTPrintNumToString(uint32_t num); #endif
ameya134/Real_time_FIR_filtering
src/hal/timer0.c
<gh_stars>0 /* *********************************************************************** * * This file provides implementation of functions for configuration and * use of Timer0 peripheral on tm4c129encpdt * * Author: <NAME> * Date Created: 1st March 2021 * Date Modified: 13th May 2021 * * ***********************************************************************/ #include "main.h" #include "timer0.h" #include "bsp.h" #include "dma.h" #include "FreeRTOS.h" #include "task.h" #include "semphr.h" #include "app.h" /* This control word is used by the application which needs the * Timer0 to generate DMA transfer requests. This control word is configured * according to the needs of the application. */ #if( TIMER0A_GENERATE_DMA_TRIG == 1) struct DMA_control_word TIMER0_channel_control_word = { .XFERMODE = 0x1, /* Basic mode */ .NXTUSEBURST = 0x0, /* no next use burst for last transfers */ .XFERSIZE = (DATA_BUF_LEN -1), /* Transfer size */ .ARBSIZE = 0x0, /* arbitrate after 1 transfer */ .SRCPROT0 = 0x0, /* non privilaged access */ /* .reserved1 */ .DESTPROT0 = 0x0, /* non privilaged access */ /* .reserved0 */ .SRCSIZE = 0x1, /* 16 bit data size */ .SRCINC = 0x2, /* 32 bit increment */ .DESTSIZE = 0x1, /* 16 bit data size */ .DESTINC = 0x3, /* No increment */ }; #endif /* ************************************************************************** * This function Initializes the Timer0 with a load value * * param: loadval Initial load value of the timer * * return: void * * brief: Function initializes the timer0 module in periodic count down * mode with the given load value. * * If the TIMER0A_GENERATE_INTERRUPT flag is defined as 1 then the timer * generated. * * TIMER0A_GENERATE_ADC_TRIG flag, if turned on, generates an ADC trigger * every time the timer0 reaches a value of 0 while counting down. * * TIMER0A_GENERATE_DMA_TRIG flag, if turned on, generates a DMA trigger * every time the timer0 reaches a value of 0 while counting down. * * **************************************************************************/ void init_timer0(uint32_t loadVal) { /* enable clocking to timer module */ SYSCTL_RCGCTIMER_R |= SYSCTL_RCGCTIMER_R0; /* wait till the peripheral is ready */ while(!(SYSCTL_PRTIMER_R & SYSCTL_PRTIMER_R0)); /* Disable the timer and clear previous configuration * before doing the configuration */ TIMER0_CTL_R &= ~(TIMER_CTL_TAEN); TIMER0_CFG_R = 0x0; /* Configure timer mode * set periodic mode and enable interrupt if flag is set */ TIMER0_TAMR_R |= (0x2 << 0); /* configure to generate adc trigger */ #if( TIMER0A_GENERATE_ADC_TRIG == 1) TIMER0_CTL_R |= TIMER_CTL_TAOTE; TIMER0_ADCEV_R |= TIMER_ADCEV_TATOADCEN; #endif /* configure to generate dma transfer trigger */ #if( TIMER0A_GENERATE_DMA_TRIG == 1) TIMER0_DMAEV_R |= (TIMER_DMAEV_TATODMAEN); #endif /* configure to generate timeout interrupt */ #if( TIMER0A_GENERATE_INTERRUPT == 1 ) /* set interrupt mask to generate periodic interrupt */ TIMER0_IMR_R |= (1U <<0); NVIC_EN0_R |= (1U <<TIMER0A_INT_NUM); /* Priority of interrupt needs to be lower than max_syscall_prio * in order to use the FreeRTOS API. This is done by modifying the * NVIC register corresponding to this timer interrupt number. * * The higher 3 bits of a byte specify the interrupt prio. the corresponding * bits to be changed for this interrupt are on the most significant byte * (ie. 4th byte) of the PRI4 register. * * Higher numerical value corresponds to lower logical priotiy level.*/ NVIC_PRI4_R = ( ( TIMER0A_INT_NVIC_PRIO << (8 - configPRIO_BITS) ) << 3*8 ); #else TIMER0_TAMR_R |= (0x1 << 12); #endif /* load the timer value */ TIMER0_TAILR_R = loadVal; return; } /* *************************************************************************** * * This function enables the timer0 * * param: void * * return: void * * brief: This function enables the timer0 which starts the timer0 counting * * **************************************************************************/ void timer0_enable(void) { /* enable timer 0 */ TIMER0_CTL_R |= (1U << 0); return; } /* Interrupt handler for timer0 if interrupts are generated. */ #if(TIMER0A_GENERATE_INTERRUPT == 1) void timer0_handler(void) { /* clear the interrrupt bit */ TIMER0_ICR_R |= (1U<<0); return; } #endif
ameya134/Real_time_FIR_filtering
src/inc/hal/dma.h
/* ************************************************************************ * This file provides the declarations to configure and use the DMA module * on tm4c129encpdt * * Author: <NAME> * Date Created: 15th April 2021 * DAte Modified: 13th May 2021 * * ************************************************************************/ #ifndef _DMA_H #define _DMA_H #include "tm4c129encpdt.h" /* Structures for DMA channel control table */ /* Control word is used to configure the basic properties * of DMA transfer for a given channel. */ struct DMA_control_word{ /* First member of the structure goes as LSB * Last member of the structure goes as MSB */ uint16_t XFERMODE : 3; /* bit 02:00 uDMA transfer mode */ uint16_t NXTUSEBURST : 1; /* bit 03 next use burst */ uint16_t XFERSIZE : 10; /* bit 13:04 transfer size */ uint16_t ARBSIZE : 4; /* bit 17:14 arbitration size */ uint16_t SRCPROT0 : 1; /* bit 18 source privilage access */ uint16_t reserved1 : 2; /* bit 20:19 reserved */ uint16_t DESTPROT0 : 1; /* bit 21 destination privilage access */ uint16_t reserved0 : 2; /* bit 23:22 reserved */ uint16_t SRCSIZE : 2; /* bit 25:24 source data size */ uint16_t SRCINC : 2; /* bit 27:26 source address increment */ uint16_t DESTSIZE : 2; /* bit 29:28 destination data size */ uint16_t DESTINC : 2; /* bit 31:30 destination address increment */ } __attribute__((packed)); /* Control structure for a channel consists of source and destination * pointers and the control word. */ struct DMA_control_structure{ uint32_t *src_end_ptr; /* pointer to the end of source buffer or source addr */ uint32_t *dst_end_ptr; /* pointer to the end of destination buffer or destination addr */ struct DMA_control_word control_word; /* conrol word for the channel */ uint32_t reserved; }; /* Control table consists of primary and secondary control structures * for all the channels. control table needs to be aligned at 1024 * byte boundary */ struct DMA_control_table{ struct DMA_control_structure channel_ctl_struct[32]; /* primary control structs */ struct DMA_control_structure secondary_channel_ctl_struct[32]; /* secondary control structs */ } __attribute((aligned(1024))) DMA_control_table; /* ******************************************************************** * This function Initializes the DMA module. * * param: void * * return: void * * brief: This function inititalizes the DMA module and sets the pointer * to the control table located in the SRAM. * * ********************************************************************/ void DMA_init(void); /* ******************************************************************************************** * This function configures a channel to transfer data from source * to destination. * * param: channel_no DMA channel to be configured for transfer * param: channel_encoding encoding value for the peripheral connected to channel * param: burstModeOnly Channel responds to only burst requests when this is 1. * param: src_end_ptr pointer to the last memory location of the * source buffer or memory location * param: dest_end_ptr pointer to the last memory location of the * destination buffer or memory location * param: control_word control word for the configuration of channel * * return: void * * brief: This function configures the DMA channel to transfer data from source location * to the destination. the source and/or destination can be single memory locations or * arrays of memory locations. The size of elements, transfer size, transfer type is programmed * in the control word. * * ********************************************************************************************/ void DMA_configure_channel(uint8_t channel_no,uint8_t channel_encoding,uint8_t burstModeOnly, uint32_t *src_end_ptr, uint32_t *dst_end_ptr, struct DMA_control_word *control_word); /* ******************************************************************************************** * This function reconfigures the dma channel after the previous transfer has been completed. * * param: channel_no DMA channel to be configured for transfer * param: src_end_ptr pointer to the last memory location of the * source buffer or memory location * param: dest_end_ptr pointer to the last memory location of the * destination buffer or memory location * param: control_word control word for the configuration of channel * * return: void * * brief: This function reconfigures the dma channel after the previous transfer has been * completed. * * ********************************************************************************************/ void DMA_reconfigure_channel(uint8_t channel_no, uint32_t *src_end_ptr, uint32_t *dst_end_ptr, struct DMA_control_word *control_word); /* ******************************************************************** * This function starts/enables the DMA transfers on a channel. * * param: channel_no Dma channel no to be enabled/ started. * * return: void * * brief: This function starts/ enables the dma channel to responds to * transfer requests from peripherals and/or software triggers. * ********************************************************************/ void DMA_start_transfer(uint8_t channel_no); #endif
ameya134/Real_time_FIR_filtering
src/app.c
<gh_stars>0 /* ************************************************************** * * Application logic is implemented here * * All the FreeRTOS tasks are initialised from app_task_setup() * Fucntion call. Each task is scheduled by the scheduler when * main starts the scheduler. * * Author: <NAME> * Date Created: 4th April 2021 * Date Modified: 4th April 2021 * * ***************************************************************/ #include "main.h" #include "app.h" #include "string.h" #include "convolution.h" #include "FreeRTOS.h" #include "task.h" #include "semphr.h" #include "bsp.h" #include "adc.h" #include "timer0.h" #include "pwm.h" #include "uart.h" /* This variable keeps track of buffers being used by hardware * Value of 0 represents hardware using buffer A * Value of 1 represents hardware using buffer B * The software uses the other buffer for calculations */ volatile int ADC_buf_var = 0; /* Input buffers A and B */ int32_t INPUT_BUFFER_A[DATA_BUF_LEN]; int32_t INPUT_BUFFER_B[DATA_BUF_LEN]; /* Impulse response of FIR filter */ int32_t FIR_h_n[FILTER_LEN] = {-219,324,-24,1165,3469,6579,9625,11522,11522,9625,6579,3469,1165,-24,-324,-219}; /* Output buffers A and B */ int32_t OUTPUT_BUFFER_A[CONVOLUTION_LEN]; int32_t OUTPUT_BUFFER_B[CONVOLUTION_LEN]; /* Pointers to the input and output buffers to be used * by software for calculations */ int32_t *INPUT_BUFFER_ptr; int32_t *OUTPUT_BUFFER_ptr; /* This semaphore is released by ADC ISR when DATA_BUF_LEN * number of ADC samples have been transfered to inpt buffers */ SemaphoreHandle_t ADC_data_ready; /* DMA control words for ADC and TIMER0 channel of DMA */ extern struct DMA_control_word ADC_channel_control_word; extern struct DMA_control_word TIMER0_channel_control_word; /* ******************************************************************************* * * This function does the setup required by the FIR_filter_task * * param: void * * return: void * * brief: This function initializes the ADC_data_ready semaphore. It then * configures the ADC dma channels to transfer the ADC samples to input buffers. * DMA transfers are started and then timer0 is enabled which triggers ADC SS0 * to sample AIN0 pin. * * ******************************************************************************/ static void FIR_task_setup(void) { UARTSendString("FIR filtering started...\n\r"); ADC_data_ready = xSemaphoreCreateBinary(); DMA_configure_channel( ADC_DMA_CHANNEL_NO, /* channel no 14 for adc0 ss0 */ ADC_DMA_CHANNEL_ENCODE, /* channel coding 0 for adc0 ss0 */ 1, /* Use burst only */ (uint32_t *)&ADC0_SSFIFO0_R, /* source end pointer */ (uint32_t *)&INPUT_BUFFER_A[DATA_BUF_LEN -1], /* destination end pointer */ &ADC_channel_control_word /* channel control word */ ); DMA_configure_channel( TIMER0_DMA_CHANNEL_NO, /* channel no 14 for adc0 ss0 */ TIMER0_DMA_CHANNEL_ENCODE, /* channel coding 0 for adc0 ss0 */ 1, /* Use burst only */ (uint32_t *)&OUTPUT_BUFFER_A[DATA_BUF_LEN -1], /* source end pointer */ (uint32_t *)&PWM0_0_CMPA_R, /* destination end pointer */ &TIMER0_channel_control_word /* channel control word */ ); /* start the dma transfer */ DMA_start_transfer(ADC_DMA_CHANNEL_NO); DMA_start_transfer(TIMER0_DMA_CHANNEL_NO); timer0_enable(); return; } /* ***************************************************************************** * * This function pre-processes the output buffer before the main processing * * param: void * * return: void * * brief: This function prepares the output buffers before the convolution * with impulse response is computed. This function implements the OAM method. * OVERLAP ADD METHOD(OAM) is used to make sure the effect of preious samples * is propagated to the full length in time of the impulse response. * * ******************************************************************************/ static void FIR_buffer_prepare(void) { /* use buffer A and B alternately * copy last FILTER_LEN-1 samples from * previous computations which are carried * forward in overlap ad method */ if(ADC_buf_var == 1){ memcpy(OUTPUT_BUFFER_A, (&OUTPUT_BUFFER_B[DATA_BUF_LEN]), (FILTER_LEN-1)*sizeof(*OUTPUT_BUFFER_A)); INPUT_BUFFER_ptr = INPUT_BUFFER_A; OUTPUT_BUFFER_ptr = OUTPUT_BUFFER_A; } else{ memcpy(OUTPUT_BUFFER_B, (&OUTPUT_BUFFER_A[DATA_BUF_LEN]), (FILTER_LEN-1)*sizeof(*OUTPUT_BUFFER_B)); INPUT_BUFFER_ptr = INPUT_BUFFER_B; OUTPUT_BUFFER_ptr = OUTPUT_BUFFER_B; } /* clear the remaining array elements */ memset(&OUTPUT_BUFFER_ptr[FILTER_LEN - 1], 0, (CONVOLUTION_LEN - (FILTER_LEN -1))*sizeof(*OUTPUT_BUFFER_ptr)); return; } /* ******************************************************************************* * * This is a FreeRTOS task. * * param: *param pointer to the parameters that are passed to the task * * return: void * * brief: This task initializes the dma channels and starts the timer0 during * the setup. The tasks keeps pending on the ADC_data_ready semaphore which * is released by the ADC isr when sampling of DATA_BUF_LEN number of AIN0 is * done. the FIR_buffer_prepare pre-processes the output buffer to implement * overlap add method. After this convolution of input signal and the impulse * response is performed. After this the output data is scaled and then the * task again keeps pending on the semaphore * * ******************************************************************************/ void FIR_filter_task(void *param) { /* setup for fir filter task */ FIR_task_setup(); for(;;){ /* wait for semaphore to be released when * DMA completes ADC data transfer */ if(pdTRUE == xSemaphoreTake(ADC_data_ready,0xffff)){ /* process the data from ADC */ /* use buffer that has been updated by uDMA */ FIR_buffer_prepare(); convolve_16x16(INPUT_BUFFER_ptr,FIR_h_n,OUTPUT_BUFFER_ptr); /* scale the output */ int i; for(i=0;i<16;i++){ OUTPUT_BUFFER_ptr[i] >>= 8; } }else{ /* error aquiring the semaphore */ UARTSendString("ERROR: Unable to aquire ADC data semaphore\n\r"); while(1); } } return; } /* ******************************************************************************* * * This task blinks the led * * param: *param pointer to the parameters that are passed to the task * * return: void * * brief: This function keeps toggles the state of led at fixed intervals * * ******************************************************************************/ #if( LED_BLINK_ENABLE == 1) void LED_blink_task(void *param) { const TickType_t xDelay = LED_BLINK_DELAY_MS/portTICK_PERIOD_MS; for(;;){ /* Toggle the led and wait for xDelay period */ LED_TOGGLE_STATE(LED1_PORT,LED1_PIN); vTaskDelay(xDelay); } return; } #endif /* ******************************************************************************** * * This is the setup function that creates the FreeRTOS tasks * * param: void * * return: void * * brief: This function creates the FreeRTOS tasks and needs to be called * before starting the FreeRTOS scheduler. It creates the FIR_filter_task. * It also creates the LED_blink_task if the LED_BLINK_ENABLE macros is * defined as 1. * * ********************************************************************************/ void app_tasks_setup(void) { BaseType_t xRetVal; #if( LED_BLINK_ENABLE == 1) static TaskHandle_t xHandleLedTask = NULL; xRetVal = xTaskCreate( &LED_blink_task, /* task handler pointer */ "LED_BLINK", /* task name */ 256, /* stack size in words */ (void *)0, /* param for task */ LED_BLINK_PRIO, /* priority of task */ &xHandleLedTask /* task handle variable */ ); if(xRetVal == 0) { while(1); } #endif static TaskHandle_t xHandleFIRFilterTask = NULL; xRetVal = xTaskCreate( &FIR_filter_task, /* task handler pointer */ "LED_BLINK", /* task name */ 256, /* stack size in words */ (void *)0, /* param for task */ FIR_FILTER_PRIO, /* priority of task */ &xHandleFIRFilterTask /* task handle variable */ ); if(xRetVal == 0) { while(1); } UARTSendString("Tasks Initialized...\n\r"); UARTSendString("Starting Scheduler...\n\r"); return; }
ameya134/Real_time_FIR_filtering
src/convolution.c
/* ********************************************************************* * * This file implements functions to calculate Linear convolution * of two signals * * Author: <NAME> * Date created: 6th May 2021 * Last modified: 13th May 2021 * * *********************************************************************/ #include "convolution.h" /* ********************************************************************** * This function computes the linear convolution of two signals * of length 16 * * param: x pointer to signal 1 array (generally input) * param: h pointer to signal 2 array (generally transfer function) * param: y pointer to output array to store answer of convolution * * return: void * * brief: This function computes the Linear Convolution of two descrete * time signals of length 16. The length of output is (2*16 -1) = 31. * * ***********************************************************************/ void convolve_16x16(int32_t *x,int32_t *h, int32_t *y) { uint8_t i,j; for(i=0;i<16;i++){ for(j=0;j<16;j++){ y[i+j] += x[i]*h[j]; } } return; }
matobaa/hjkl_keymap_for_meishi_keyboard
firmware/keyboards/meishi/keymaps/hjkl/game.c
<gh_stars>0 // gameboard #define MAX_X (4) #define MAX_Y (4) char matrix[MAX_X][MAX_Y]; char matrix_backup[MAX_X][MAX_Y]; int score = 0; void backup(void) { for (int x = 0; x < MAX_Y; x++) { for (int y = 0; y < MAX_X; y++) { matrix_backup[x][y] = matrix[x][y]; } } } void recovery(void) { for (int x = 0; x < MAX_Y; x++) { for (int y = 0; y < MAX_X; y++) { matrix[x][y] = matrix_backup[x][y]; } } } bool canmove(void) { for (int x = 0; x < MAX_Y; x++) { for (int y = 0; y < MAX_X; y++) { if(matrix[x][y]==0) return true; } } int last = 0; for (int x = 0; x < MAX_Y; x++) { last = matrix[x][0]; for (int y = 1; y < MAX_X; y++) { if(last == matrix[x][y]) return true; last = matrix[x][y]; } } for (int y = 0; y < MAX_X; y++) { last = matrix[0][y]; for (int x = 1; x < MAX_Y; x++) { if(last == matrix[x][y]) return true; last = matrix[x][y]; } } return false; } bool newtile(void) { int qtyempty = 0; // count for (int x = 0; x < MAX_Y; x++) { for (int y = 0; y < MAX_X; y++) { if(matrix[x][y] == 0) { qtyempty++; } } } if(qtyempty==0) return false; int newindex = rand() % qtyempty; // place a new tile for (int x = 0; x < MAX_Y; x++) { for (int y = 0; y < MAX_X; y++) { if(matrix[x][y] == 0) { if(newindex == 0) { int newvalue = (rand() % 5) == 0 ? 2 : 1; matrix[x][y] = newvalue; return true; } newindex--; } } } return false; } void reset_board(void) { for (int x = 0; x < MAX_Y; x++) { for (int y = 0; y < MAX_X; y++) { matrix[x][y] = 0; } } newtile(); newtile(); score = 0; } void dump_board(void) { for (int x = 0; x < MAX_Y; x++) { for (int y = 0; y < MAX_X; y++) { send_char(matrix[x][y] < 10 ? ('0'+ matrix[x][y]) : ('A' + matrix[x][y] - 10)); } send_char('\n'); } send_char('\n'); } // { LEFT, DOWN, UP, RIGHT }; bool move(int direction) { bool result = false; if(direction == 0) { // left for(int x=0; x<MAX_X; x++) { for(int y=0; y<MAX_Y-1; y++) { if(matrix[x][y] == 0) { for(int dy=y+1; dy<MAX_Y; dy++) { if(matrix[x][dy] != 0) { matrix[x][y] = matrix[x][dy]; matrix[x][dy] = 0; result = true; break; } } } if(matrix[x][y] != 0) { for(int dy=y+1; dy<MAX_Y; dy++) { if(matrix[x][dy] == matrix[x][y]) { matrix[x][y] += 1; matrix[x][dy] = 0; result = true; break; } if(matrix[x][dy] != 0) break; } } } } } if(direction == 2) { // down for(int y=0; y<MAX_Y; y++) { for(int x=0; x<MAX_X-1; x++) { if(matrix[x][y] == 0) { for(int dx=x+1; dx<MAX_X; dx++) { if(matrix[dx][y] != 0) { matrix[x][y] = matrix[dx][y]; matrix[dx][y] = 0; result = true; break; } } } if(matrix[x][y] != 0) { for(int dx=x+1; dx<MAX_X; dx++) { if(matrix[dx][y] == matrix[x][y]) { matrix[x][y] += 1; matrix[dx][y] = 0; result = true; break; } if(matrix[dx][y] != 0) break; } } } } } if(direction == 3) { // right for(int x=0; x<MAX_X; x++) { for(int y=MAX_Y-1; 0<y; y--) { if(matrix[x][y] == 0) { for(int dy=y-1; 0<=dy; dy--) { if(matrix[x][dy] != 0) { matrix[x][y] = matrix[x][dy]; matrix[x][dy] = 0; result = true; break; } } } if(matrix[x][y] != 0) { for(int dy=y-1; 0<=dy; dy--) { if(matrix[x][dy] == matrix[x][y]) { matrix[x][y] += 1; matrix[x][dy] = 0; result = true; break; } if(matrix[x][dy] != 0) break; } } } } } if(direction == 1) { // up for(int y=0; y<MAX_Y; y++) { for(int x=MAX_X-1; 0<x; x--) { if(matrix[x][y] == 0) { for(int dx=x-1; 0<=dx; dx--) { if(matrix[dx][y] != 0) { matrix[x][y] = matrix[dx][y]; matrix[dx][y] = 0; result = true; break; } } } if(matrix[x][y] != 0) { for(int dx=x-1; 0<=dx; dx--) { if(matrix[dx][y] == matrix[x][y]) { matrix[x][y] += 1; matrix[dx][y] = 0; result = true; break; } if(matrix[dx][y] != 0) break; } } } } } return result; }
matobaa/hjkl_keymap_for_meishi_keyboard
firmware/keyboards/meishi/keymaps/hjkl/keymap.c
<reponame>matobaa/hjkl_keymap_for_meishi_keyboard<gh_stars>0 /* Copyright 2019 matobaa * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include QMK_KEYBOARD_H #include "game.c" void rewind(void) { register_code(KC_LSFT); tap_code(KC_UP); tap_code(KC_UP); tap_code(KC_UP); tap_code(KC_UP); tap_code(KC_UP); unregister_code(KC_LSFT); } unsigned int pressed = 0x00; // bitmap represents key status bool sent = false; enum custom_keycode { LEFT = SAFE_RANGE, DOWN, UP, RIGHT }; const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { [0] = LAYOUT( LEFT, DOWN, UP, RIGHT ), /* Default layer */ }; const uint16_t PROGMEM fn_actions[] = { }; void matrix_init_user(void) { reset_board(); } void matrix_scan_user(void) { } bool process_record_user(uint16_t keycode, keyrecord_t *record) { int key = 1 << (keycode - SAFE_RANGE); if (IS_PRESSED(record->event)) { pressed |= key; switch(pressed) { case 0x09: srand(timer_read()); reset_board(); sent = true; break; case 0x05: case 0x0a: SEND_STRING("UNDO"); sent = true; break; case 0x03: case 0x06: case 0x0c: rewind(); dump_board(); sent = true; break; } } if (IS_RELEASED(record->event)) { pressed &= ~key; if(pressed == 0) { if(!sent) { move(keycode - SAFE_RANGE) && newtile(); rewind(); dump_board(); if(!canmove()) { SEND_STRING("GAME OVER"); return false; } } sent = false; } } return true; } void led_set_user(uint8_t usb_led) { }
masterKing/MyCode
JWAutoScrollView.h
<reponame>masterKing/MyCode // // JWAutoScrollView.h // 07-图片轮播器 // // Created by Franky on 2017/2/14. // Copyright © 2017年 cngold. All rights reserved. // #import <UIKit/UIKit.h> @interface JWAutoScrollView : UIView /** 自定义构造方法*/ - (instancetype)initWithFrame:(CGRect)frame images:(NSArray *)images; @end
braxtons12/Hyperion-Math
include/HyperionMath/Interpolator.h
<gh_stars>0 #pragma once #include <gsl/gsl> #include <type_traits> #include "Exponentials.h" #include "HyperionUtils/Concepts.h" #include "HyperionUtils/Macros.h" #include "HyperionUtils/OptionAndResult.h" namespace hyperion::math { using utils::None; using utils::Option; using utils::Some; using utils::concepts::FloatingPoint; /// @brief The possible kinds of value interpolation possible by `Interpolator` enum class InterpolationType { Linear = 0, Logarithmic, Exponential }; IGNORE_PADDING_START /// @brief Interpolates from a starting value to a final value in the way prescribed by `Type` /// @note `T` must be a floating point type /// @note The start value must be in [0, target value] and the target value must be > 0 /// /// @tparam T - The floating point type to perform operations in /// @tparam Type - The type of interpolation template<FloatingPoint T, InterpolationType Type = InterpolationType::Linear> class Interpolator { public: static constexpr T DEFAULT_TARGET_VALUE = gsl::narrow_cast<T>(1.0); static constexpr T DEFAULT_INITIAL_VALUE = gsl::narrow_cast<T>(0.0); static constexpr T DEFAULT_TRANSITION_LENGTH = gsl::narrow_cast<T>(0.1); static constexpr size_t DEFAULT_SAMPLE_RATE = 44100ULL; /// @brief Creates a default `Interpolator` constexpr Interpolator() noexcept = default; /// @brief Creates an `Interpolator` with the given target value /// /// @param targetValue - The target final value to interpolate to constexpr explicit Interpolator(T targetValue) noexcept : m_target_value(targetValue), mLinearTransitionStep( (m_target_value - m_initial_value) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds)), m_samples_to_transition(get_samples_to_transition()) { } /// @brief Creates an `Interpolator` with the given target value and sample rate /// /// @param targetValue - The target final value to interpolate to /// @param sampleRate - The sample rate to process at constexpr explicit Interpolator(T targetValue, size_t sampleRate) noexcept : m_sample_rate(sampleRate), m_target_value(targetValue), mLinearTransitionStep( (m_target_value - m_initial_value) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds)), m_samples_to_transition(get_samples_to_transition()) { } /// @brief Creates an `Interpolator` with the given target and initial values, and sample /// rate /// /// @param targetValue - The target final value to interpolate to /// @param initial_value - The initial value to start interpolation from /// @param sampleRate - The sample rate to process at constexpr Interpolator(T targetValue, T initial_value, size_t sampleRate) noexcept : m_sample_rate(sampleRate), m_target_value(targetValue), m_current_value(initial_value), m_initial_value(m_current_value), mLinearTransitionStep( (m_target_value - m_initial_value) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds)), m_samples_to_transition(get_samples_to_transition()) { } /// @brief Creates an `Interpolator` with the given target and initial values, time to /// interpolate over, and sample rate /// /// @param targetValue - The target final value to interpolate to /// @param initial_value - The initial value to start interpolation from /// @param transitionLengthSeconds - The transition time to interpolate over /// @param sampleRate - The sample rate to process at constexpr Interpolator(T targetValue, T initial_value, T transitionLengthSeconds, size_t sampleRate) noexcept : m_sample_rate(sampleRate), m_target_value(targetValue), m_current_value(initial_value), m_initial_value(m_current_value), m_transition_lengthSeconds(transitionLengthSeconds), mLinearTransitionStep( (m_target_value - m_initial_value) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds)), m_samples_to_transition(get_samples_to_transition()) { } constexpr Interpolator(const Interpolator& interpolator) noexcept = default; constexpr Interpolator(Interpolator&& interpolator) noexcept = default; ~Interpolator() noexcept = default; /// @brief Gets the next value in the interpolation sequence /// If `currentSample` is given, gets the value in the sequence for the given sample index /// @note This is only available for `Interpolator`s of type /// `InterpolationType::Logarithmic` or `InterpolationType::Exponential` /// @param currentSample - The (optional) sample in the sequence to get the value for /// /// @return - The interpolation value inline auto get_next_value(Option<size_t> currentSample = None()) noexcept -> T { if(currentSample.is_some()) { m_current_transition_sample = currentSample.unwrap(); } if(m_current_transition_sample <= m_samples_to_transition) { m_current_value = interpolate(m_current_transition_sample); m_current_transition_sample++; } return m_current_value; } /// @brief Resets the `Interpolator`. /// - If `initial_value` is given, the `Interpolator` will start at the given one instead of /// `DEFAULT_INITIAL_VALUE` /// - If `transitionLengthSeconds` is also given, the `Interpolator` will interpolate over /// that length of time instead of the current one /// /// @param initial_value - The initial value to start interpolation from /// @param transitionLengthSeconds - The transition time to interpolate over inline auto reset(Option<T> initial_value, Option<T> transitionLengthSeconds) noexcept -> void { if(initial_value.is_some()) { m_current_value = initial_value.unwrap(); m_initial_value = m_current_value; } else { m_current_value = DEFAULT_INITIAL_VALUE; m_initial_value = m_current_value; } if(transitionLengthSeconds.is_some()) { m_transition_lengthSeconds = transitionLengthSeconds.unwrap(); } mLinearTransitionStep = (m_target_value - m_current_value) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds); m_samples_to_transition = get_samples_to_transition(); m_current_transition_sample = 0ULL; } /// @brief Sets the target value to interpolate to, to the given one /// /// @param targetValue - The value to interpolate to constexpr inline auto set_target(T targetValue) noexcept -> void { m_target_value = targetValue; m_initial_value = m_current_value; mLinearTransitionStep = (m_target_value - m_initial_value) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds); m_samples_to_transition = get_samples_to_transition(); } /// @brief Sets the sample rate to use for interpolation /// /// @param sampleRate - The sample rate to use for interpolation inline auto set_sample_rate(size_t sampleRate) noexcept -> void { m_sample_rate = sampleRate; mLinearTransitionStep = (m_target_value - m_initial_value) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds); m_samples_to_transition = get_samples_to_transition(); m_current_transition_sample = 0ULL; } constexpr auto operator=(const Interpolator& interpolator) noexcept -> Interpolator& = default; constexpr auto operator=(Interpolator&& interpolator) noexcept -> Interpolator& = default; private: static constexpr T LOG_TIME_FACTOR = gsl::narrow_cast<T>(5.0); static constexpr T EXP_TIME_FACTOR = gsl::narrow_cast<T>(0.693); size_t m_sample_rate = DEFAULT_SAMPLE_RATE; T m_target_value = DEFAULT_TARGET_VALUE; T m_current_value = DEFAULT_INITIAL_VALUE; T m_initial_value = DEFAULT_INITIAL_VALUE; T m_transition_lengthSeconds = DEFAULT_TRANSITION_LENGTH; T mLinearTransitionStep = (m_target_value - m_initial_value) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds); size_t m_samples_to_transition = get_samples_to_transition(); size_t m_current_transition_sample = 0; /// @brief Gets the interpolated value for the given sample /// /// @param sample - The sample to get the interpolated value for /// /// @return The interpolated value inline auto interpolate(size_t sample) noexcept -> T { if constexpr(Type == InterpolationType::Linear) { return linear_interpolation(sample); } else if constexpr(Type == InterpolationType::Logarithmic) { return log_interpolation(sample); } else { return exp_interpolation(sample); } } inline auto linear_interpolation(size_t sample) noexcept -> T { return m_initial_value + (mLinearTransitionStep * gsl::narrow_cast<T>(sample)); } /// @brief Performs "logarithmic" interpolation. /// In reality, this is a pseudo logarithmic shape: /// /// y = transition_factor * /// [1 + (peak_factor - 1) * (-e^{1 - t / (transtionLength / time_factor) } ) ] /// /// where t = sample / sampleRate /// /// which has a horizontal asymptote at ~ the target value and more pronouced slope /// /// @param sample - The sample to get the interpolation value for /// /// @return - The interpolated value inline auto log_interpolation(size_t sample) noexcept -> T { return (m_initial_value - m_target_value) * math::Exponentials::exp(-gsl::narrow_cast<T>(sample) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds / LOG_TIME_FACTOR)) + m_target_value; } /// @brief Performs exponential interpolation: /// /// y = e^{t / (transitionLength / time_factor) } - 1 /// /// where t = sample / sampleRate /// /// @param sample The sample to get the interpolation value for /// /// @return - The interpolated value inline auto exp_interpolation(size_t sample) noexcept -> T { return (m_target_value - m_initial_value) * (math::Exponentials::exp( gsl::narrow_cast<T>(sample) / (gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds / EXP_TIME_FACTOR)) - gsl::narrow_cast<T>(1.0)) + m_initial_value; } /// @brief Gets the number of samples necessary to fully complete the interpolation sequence /// /// @return The number of samples in the interpolation sequence inline auto get_samples_to_transition() noexcept -> size_t { return gsl::narrow_cast<size_t>(gsl::narrow_cast<T>(m_sample_rate) * m_transition_lengthSeconds); } }; IGNORE_PADDING_STOP } // namespace hyperion::math
braxtons12/Hyperion-Math
include/HyperionMath/Vec3.h
<gh_stars>0 #pragma once #include <gsl/gsl> #include <iostream> #include "General.h" #include "HyperionUtils/Concepts.h" #include "Random.h" namespace hyperion::math { using gsl::narrow_cast; using utils::concepts::SignedNumeric, utils::concepts::Integral, utils::concepts::SignedIntegral, utils::concepts::FloatingPoint; enum class Vec3Idx : size_t { X = 0ULL, Y, Z }; template<SignedNumeric T = float> class Vec3 { public: /// @brief Creates a default `Vec3` constexpr Vec3() noexcept = default; /// @brief Creates a new `Vec3` with the given x, y, and z components /// /// @param x - The x component /// @param y - The y component /// @param z - The z component constexpr Vec3(T x, T y, T z) noexcept : elements{x, y, z} { } constexpr Vec3(const Vec3& vec) noexcept = default; constexpr Vec3(Vec3&& vec) noexcept = default; constexpr ~Vec3() noexcept = default; /// @brief Returns the x component /// /// @return a const ref to the x component [[nodiscard]] inline constexpr auto x() const noexcept -> const T& { return elements[X]; } /// @brief Returns the x component /// /// @return a mutable (ie: non-const) ref to the x component [[nodiscard]] inline constexpr auto x() noexcept -> T& { return elements[X]; } /// @brief Returns the y component /// /// @return a const ref to the y component [[nodiscard]] inline constexpr auto y() const noexcept -> const T& { return elements[Y]; } /// @brief Returns the y component /// /// @return a mutable (ie: non-const) ref to the y component [[nodiscard]] inline constexpr auto y() noexcept -> T& { return elements[Y]; } /// @brief Returns the z component /// /// @return a const ref to the z component [[nodiscard]] inline constexpr auto z() const noexcept -> const T& { return elements[Z]; } /// @brief Returns the z component /// /// @return a mutable (ie: non-const) ref to the z component [[nodiscard]] inline constexpr auto z() noexcept -> T& { return elements[Z]; } /// @brief Returns the magnitude (length) of the vector /// /// @return The magnitude template<FloatingPoint TT = float> [[nodiscard]] inline constexpr auto magnitude() const noexcept -> TT { return General::sqrt(narrow_cast<TT>(magnitude_squared())); } /// @brief Returns the dot product of this and `vec` /// /// @param vec - The vector to perform the dot product with /// /// @return The dot product template<FloatingPoint TT = float> [[nodiscard]] inline constexpr auto dot_prod(const Vec3<TT>& vec) const noexcept -> TT { return narrow_cast<TT>(x()) * vec.x() + narrow_cast<TT>(y()) * vec.y() + narrow_cast<TT>(z()) * vec.z(); } /// @brief Returns the dot product of this and `vec` /// /// @param vec - The vector to perform the dot product with /// /// @return The dot product template<SignedIntegral TT = int> [[nodiscard]] inline constexpr auto dot_prod(const Vec3<TT>& vec) const noexcept -> T { return x() * narrow_cast<T>(vec.x()) + y() * narrow_cast<T>(vec.y()) + z() * narrow_cast<T>(vec.z()); } /// @brief Performs the cross product /// /// @param vec The vector to perform the cross product with /// /// @return The cross product template<FloatingPoint TT = float> [[nodiscard]] inline constexpr auto cross_prod(const Vec3<TT>& vec) const noexcept -> Vec3<TT> { const auto _x = narrow_cast<TT>(y()) * vec.z() - narrow_cast<TT>(z()) * vec.y(); const auto _y = narrow_cast<TT>(z()) * vec.x() - narrow_cast<TT>(x()) * vec.z(); const auto _z = narrow_cast<TT>(x()) * vec.y() - narrow_cast<TT>(y()) * vec.x(); return {_x, _y, _z}; } /// @brief Performs the cross product /// /// @param vec The vector to perform the cross product with /// /// @return The cross product template<SignedIntegral TT = int> [[nodiscard]] inline constexpr auto cross_prod(const Vec3<TT>& vec) const noexcept -> Vec3 { const auto _x = y() * narrow_cast<T>(vec.z()) - z() * narrow_cast<T>(vec.y()); const auto _y = z() * narrow_cast<T>(vec.x()) - x() * narrow_cast<T>(vec.z()); const auto _z = x() * narrow_cast<T>(vec.y()) - y() * narrow_cast<T>(vec.x()); return {_x, _y, _z}; } /// @brief Returns **a** vector normal to this one /// @note this is not necessarily the **only** vector normal to this one /// /// @return a vector normal to this [[nodiscard]] inline constexpr auto normal() const noexcept -> Vec3 { return cross_prod( Vec3<T>(narrow_cast<T>(1.0), narrow_cast<T>(0.0), narrow_cast<T>(0.0))); } /// @brief Returns this vector with normalized magnitude /// /// @return this vector, normalized template<FloatingPoint TT = float> [[nodiscard]] inline constexpr auto normalized() const noexcept -> Vec3<TT> { return std::move(*this / magnitude<TT>()); } template<SignedNumeric TT = float> [[nodiscard]] inline static constexpr auto random() noexcept -> Vec3<TT> { return {random_value<TT>(), random_value<TT>(), random_value<TT>()}; } template<SignedNumeric TT = float> [[nodiscard]] inline static constexpr auto random(TT min, TT max) noexcept -> Vec3<TT> { return {random_value<TT>(min, max), random_value<TT>(min, max), random_value<TT>(min, max)}; } template<FloatingPoint TT = float> [[nodiscard]] inline static constexpr auto random_in_unit_sphere() noexcept -> Vec3<TT> { do { auto val = random<TT>(narrow_cast<TT>(-1), narrow_cast<TT>(1)); if(narrow_cast<TT>(val.magnitude_squared()) < narrow_cast<TT>(1)) { return val; } } while(true); } template<FloatingPoint TT = float> [[nodiscard]] inline static constexpr auto random_in_unit_disk() noexcept -> Vec3<TT> { do { auto val = random(narrow_cast<TT>(-1), narrow_cast<TT>(1)); val.z() = narrow_cast<TT>(0); if(narrow_cast<TT>(val.magnitude_squared()) < narrow_cast<TT>(1)) { return val; } } while(true); } [[nodiscard]] inline constexpr auto is_approx_zero() noexcept -> bool { constexpr auto zero_tolerance = narrow_cast<T>(0.0001); return (General::abs(x()) < zero_tolerance) && (General::abs(y()) < zero_tolerance) && (General::abs(z()) < zero_tolerance); } [[nodiscard]] inline constexpr auto reflected(const Vec3& surface_normal) const noexcept -> Vec3 { return std::move( *this - narrow_cast<T>(2) * (this->dot_prod(surface_normal) * surface_normal)); } [[nodiscard]] inline constexpr auto refracted(const Vec3& surface_normal, T eta_external_over_eta_internal) noexcept -> Vec3 { const auto uv = *this; const auto cos_theta = General::min((-uv).dot_prod(surface_normal), narrow_cast<T>(1)); auto out_perpendicular = eta_external_over_eta_internal * (uv + cos_theta * surface_normal); auto out_parallel = -General::sqrt(General::abs( narrow_cast<T>(1) - out_perpendicular.magnitude_squared())) * surface_normal; return out_perpendicular + out_parallel; } constexpr auto operator=(const Vec3& vec) noexcept -> Vec3& = default; constexpr auto operator=(Vec3&& vec) noexcept -> Vec3& = default; template<FloatingPoint TT = float> inline constexpr auto operator==(const Vec3<TT>& vec) const noexcept -> bool { const auto xEqual = General::abs<TT>(narrow_cast<TT>(x()) - vec.x()) < narrow_cast<TT>(0.01); const auto yEqual = General::abs<TT>(narrow_cast<TT>(y()) - vec.y()) < narrow_cast<TT>(0.01); const auto zEqual = General::abs<TT>(narrow_cast<TT>(z()) - vec.z()) < narrow_cast<TT>(0.01); return xEqual && yEqual && zEqual; } template<SignedIntegral TT = int> inline constexpr auto operator==(const Vec3<TT>& vec) const noexcept -> bool { if constexpr(FloatingPoint<T>) { const auto xEqual = General::abs<T>(x() - narrow_cast<T>(vec.x())) < narrow_cast<TT>(0.01); const auto yEqual = General::abs<T>(y() - narrow_cast<T>(vec.y())) < narrow_cast<TT>(0.01); const auto zEqual = General::abs<T>(z() - narrow_cast<T>(vec.z())) < narrow_cast<TT>(0.01); return xEqual && yEqual && zEqual; } else { return x() == narrow_cast<T>(vec.x()) && y() == narrow_cast<T>(vec.y()) && z() == narrow_cast<T>(vec.z()); } } template<SignedNumeric TT = T> inline constexpr auto operator!=(const Vec3<TT>& vec) const noexcept -> bool { return !(*this == vec); } inline constexpr auto operator-() const noexcept -> Vec3 { return {-x(), -y(), -z()}; } inline constexpr auto operator[](Vec3Idx i) const noexcept -> T { const auto index = static_cast<size_t>(i); return elements[index]; // NOLINT } inline constexpr auto operator[](Vec3Idx i) noexcept -> T& { const auto index = static_cast<size_t>(i); return elements[index]; // NOLINT } template<FloatingPoint TT = float> inline constexpr auto operator+(const Vec3<TT>& vec) const noexcept -> Vec3<TT> { return {narrow_cast<TT>(x()) + vec.x(), narrow_cast<TT>(y()) + vec.y(), narrow_cast<TT>(z()) + vec.z()}; } template<SignedIntegral TT = int> inline constexpr auto operator+(const Vec3<TT>& vec) const noexcept -> Vec3 { return {x() + narrow_cast<T>(vec.x()), y() + narrow_cast<T>(vec.y()), z() + narrow_cast<T>(vec.z())}; } template<SignedNumeric TT = T> inline constexpr auto operator+=(const Vec3<TT>& vec) noexcept -> Vec3 { x() += narrow_cast<T>(vec.x()); y() += narrow_cast<T>(vec.y()); z() += narrow_cast<T>(vec.z()); return *this; } template<FloatingPoint TT = float> inline constexpr auto operator-(const Vec3<TT>& vec) const noexcept -> Vec3<TT> { return {narrow_cast<TT>(x()) - vec.x(), narrow_cast<TT>(y()) - vec.y(), narrow_cast<TT>(z()) - vec.z()}; } template<SignedIntegral TT = int> inline constexpr auto operator-(const Vec3<TT>& vec) const noexcept -> Vec3 { return {x() - narrow_cast<T>(vec.x()), y() - narrow_cast<T>(vec.y()), z() - narrow_cast<T>(vec.z())}; } template<SignedNumeric TT = T> inline constexpr auto operator-=(const Vec3<TT>& vec) noexcept -> Vec3& { x() -= narrow_cast<T>(vec.x()); y() -= narrow_cast<T>(vec.y()); z() -= narrow_cast<T>(vec.z()); return *this; } inline constexpr auto operator*(FloatingPoint auto s) const noexcept -> Vec3<decltype(s)> { using TT = decltype(s); return {narrow_cast<TT>(x()) * s, narrow_cast<TT>(y()) * s, narrow_cast<TT>(z()) * s}; } inline constexpr auto operator*(SignedIntegral auto s) const noexcept -> Vec3 { auto scalar = narrow_cast<T>(s); return {x() * scalar, y() * scalar, z() * scalar}; } friend inline constexpr auto operator*(FloatingPoint auto lhs, const Vec3& rhs) noexcept -> Vec3<decltype(lhs)> { return rhs * lhs; } friend inline constexpr auto operator*(SignedIntegral auto lhs, const Vec3& rhs) noexcept -> Vec3 { return rhs * lhs; } inline constexpr auto operator*=(FloatingPoint auto s) noexcept -> Vec3& { using TT = decltype(s); x() = narrow_cast<T>(narrow_cast<TT>(x()) * s); y() = narrow_cast<T>(narrow_cast<TT>(y()) * s); z() = narrow_cast<T>(narrow_cast<TT>(z()) * s); return *this; } inline constexpr auto operator*=(SignedIntegral auto s) noexcept -> Vec3& { auto scalar = narrow_cast<T>(s); x() *= scalar; y() *= scalar; z() *= scalar; return *this; } inline constexpr auto operator/(FloatingPoint auto s) const noexcept -> Vec3<decltype(s)> { using TT = decltype(s); return {narrow_cast<TT>(x()) / s, narrow_cast<TT>(y()) / s, narrow_cast<TT>(z()) / s}; } inline constexpr auto operator/(SignedIntegral auto s) const noexcept -> Vec3 { auto scalar = narrow_cast<T>(s); return {x() / scalar, y() / scalar, z() / scalar}; } friend inline constexpr auto operator/(FloatingPoint auto lhs, const Vec3& rhs) noexcept -> Vec3<decltype(lhs)> { return rhs / lhs; } friend inline constexpr auto operator/(SignedIntegral auto lhs, const Vec3& rhs) noexcept -> Vec3 { return rhs / lhs; } inline constexpr auto operator/=(FloatingPoint auto s) noexcept -> Vec3& { using TT = decltype(s); x() = narrow_cast<T>(narrow_cast<TT>(x()) / s); y() = narrow_cast<T>(narrow_cast<TT>(y()) / s); z() = narrow_cast<T>(narrow_cast<TT>(z()) / s); return *this; } inline constexpr auto operator/=(SignedIntegral auto s) noexcept -> Vec3& { auto scalar = narrow_cast<T>(s); x() /= scalar; y() /= scalar; z() /= scalar; return *this; } friend inline constexpr auto operator<<(std::ostream& out, const Vec3& vec) noexcept -> std::ostream& { return out << vec.x() << ' ' << vec.y() << ' ' << vec.z(); } private: static constexpr size_t NUM_ELEMENTS = static_cast<size_t>(Vec3Idx::Z) + 1; T elements[NUM_ELEMENTS] // NOLINT = {narrow_cast<T>(0), narrow_cast<T>(0), narrow_cast<T>(0)}; /// @brief Calculates the magnitude squared of this vector /// /// @return The magnitude squared [[nodiscard]] inline constexpr auto magnitude_squared() const noexcept -> T { return x() * x() + y() * y() + z() * z(); } /// Index for x component static constexpr size_t X = static_cast<size_t>(Vec3Idx::X); /// Index for y component static constexpr size_t Y = static_cast<size_t>(Vec3Idx::Y); /// Index for z component static constexpr size_t Z = static_cast<size_t>(Vec3Idx::Z); }; // Deduction Guides template<FloatingPoint T> explicit Vec3(T, T, T) -> Vec3<T>; template<SignedIntegral T> explicit Vec3(T, T, T) -> Vec3<T>; } // namespace hyperion::math
braxtons12/Hyperion-Math
include/HyperionMath/HyperionMath.h
<reponame>braxtons12/Hyperion-Math #pragma once #include "Constants.h" #include "Exponentials.h" #include "General.h" #include "Interpolator.h" #include "Point2.h" #include "Point3.h" #include "Random.h" #include "Trig.h" #include "Vec2.h" #include "Vec3.h"
braxtons12/Hyperion-Math
test/src/GeneralTestDouble.h
<reponame>braxtons12/Hyperion-Math #pragma once #ifndef __MSC_VER #include <cmath> #endif #include <limits> #include "HyperionMath/General.h" #include "TestConstants.h" #include "gtest/gtest.h" namespace hyperion::math::test { using test::DOUBLE_ACCEPTED_ERROR; TEST(GeneralTestDouble, sqrtCase1) { double input = 1.0; ASSERT_NEAR(General::sqrt(input), std::sqrt(input), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, sqrtCase2) { double input = 2.0; ASSERT_NEAR(General::sqrt(input), std::sqrt(input), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, sqrtCase3) { double input = 3.12345; ASSERT_NEAR(General::sqrt(input), std::sqrt(input), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, sqrtCase4) { double input = 6.12345; ASSERT_NEAR(General::sqrt(input), std::sqrt(input), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, fabsCase1) { double input = 1.0; ASSERT_NEAR(General::abs(input), std::fabs(input), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, fabsCase2) { double input = 2.0; ASSERT_NEAR(General::abs(input), std::fabs(input), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, fabsCase3) { double input = 3.12345; ASSERT_NEAR(General::abs(input), std::fabs(input), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, fabsCase4) { double input = -3.12345; ASSERT_NEAR(General::abs(input), std::fabs(input), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, truncCase1) { double input = 1.0; ASSERT_EQ(General::trunc(input), std::trunc(input)); } TEST(GeneralTestDouble, truncCase2) { double input = 2.0; ASSERT_EQ(General::trunc(input), std::trunc(input)); } TEST(GeneralTestDouble, truncCase3) { double input = 3.12345; ASSERT_EQ(General::trunc(input), std::trunc(input)); } TEST(GeneralTestDouble, truncCase4) { double input = -3.12345; ASSERT_EQ(General::trunc(input), std::trunc(input)); } TEST(GeneralTestDouble, fmodCase1) { double input = 1.0; double mod = 0.3; ASSERT_NEAR(General::fmod(input, mod), std::fmod(input, mod), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, fmodCase2) { double input = 2.0; double mod = 0.3; ASSERT_NEAR(General::fmod(input, mod), std::fmod(input, mod), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, fmodCase3) { double input = 3.12345; double mod = 0.3; ASSERT_NEAR(General::fmod(input, mod), std::fmod(input, mod), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, fmodCase4) { double input = -3.12345; double mod = 0.3; ASSERT_NEAR(General::fmod(input, mod), std::fmod(input, mod), DOUBLE_ACCEPTED_ERROR); } TEST(GeneralTestDouble, maxCase1) { double less = 1.0; double more = 3.12345; ASSERT_EQ(General::max(less, more), std::max(less, more)); } TEST(GeneralTestDouble, maxCase2) { double less = -3.0; double more = 12.12345; ASSERT_EQ(General::max(less, more), std::max(less, more)); } TEST(GeneralTestDouble, maxCase3) { double less = 7.0; double more = -123.12345; ASSERT_EQ(General::max(less, more), std::max(less, more)); } TEST(GeneralTestDouble, maxCase4) { double less = 10.0; double more = 123.12345; ASSERT_EQ(General::max(less, more), std::max(less, more)); } TEST(GeneralTestDouble, roundCase1) { double input = 1.5; ASSERT_EQ(General::round(input), 2); } TEST(GeneralTestDouble, roundCase2) { double input = -1.5; ASSERT_EQ(General::round(input), -1); } TEST(GeneralTestDouble, roundCase3) { double input = 4.2; ASSERT_EQ(General::round(input), 4); } TEST(GeneralTestDouble, roundUCase1) { double input = 1.5; ASSERT_EQ(General::roundU(input), 2); } TEST(GeneralTestDouble, roundUCase2) { double input = 3.2; ASSERT_EQ(General::roundU(input), 3); } TEST(GeneralTestDouble, roundUCase3) { double input = -1.5; ASSERT_EQ(General::roundU(input), std::numeric_limits<size_t>::max()); } } // namespace hyperion::math::test
braxtons12/Hyperion-Math
include/HyperionMath/Point3.h
#pragma once #include <iostream> #include "HyperionUtils/Concepts.h" #include "Vec3.h" namespace hyperion::math { using math::Vec3; using math::Vec3Idx; using ::utils::concepts::FloatingPoint; using ::utils::concepts::SignedIntegral; using ::utils::concepts::SignedNumeric; using Point3Idx = Vec3Idx; template<SignedNumeric T = float> class Point3 { public: constexpr Point3() noexcept = default; constexpr Point3(T x, T y, T z) noexcept : m_vec(x, y, z) { } template<SignedNumeric TT = T> explicit constexpr Point3(const Vec3<TT>& vec) noexcept : m_vec(static_cast<T>(vec.x()), static_cast<T>(vec.y()), static_cast<T>(vec.z())) { } template<SignedNumeric TT = T> explicit constexpr Point3(Vec3<TT>&& vec) noexcept : m_vec(static_cast<T>(vec.x()), static_cast<T>(vec.y()), static_cast<T>(vec.z())) { } constexpr Point3(const Point3& point) noexcept = default; constexpr Point3(Point3&& point) noexcept = default; constexpr ~Point3() noexcept = default; inline constexpr auto x() const noexcept -> const T& { return m_vec.x(); } inline constexpr auto x() noexcept -> T& { return m_vec.x(); } inline constexpr auto y() const noexcept -> const T& { return m_vec.y(); } inline constexpr auto y() noexcept -> T& { return m_vec.y(); } inline constexpr auto z() const noexcept -> const T& { return m_vec.z(); } inline constexpr auto z() noexcept -> T& { return m_vec.z(); } inline constexpr auto as_vec() const noexcept -> Vec3<T> { return m_vec; } constexpr auto operator=(const Point3& point) noexcept -> Point3& = default; constexpr auto operator=(Point3&& point) noexcept -> Point3& = default; inline constexpr auto operator[](Point3Idx i) const noexcept -> T { return m_vec[i]; } inline constexpr auto operator[](Point3Idx i) noexcept -> T& { return m_vec[i]; } template<SignedNumeric TT = T> inline constexpr auto operator+(const Point3<TT>& point) const noexcept -> Point3 { return Point3(m_vec + point.m_vec); } template<SignedNumeric TT = T> inline constexpr auto operator+=(const Point3<TT>& point) noexcept -> Point3& { m_vec += point.m_vec; return *this; } template<SignedNumeric TT = T> inline constexpr auto operator-(const Point3<TT>& point) const noexcept -> Point3 { return Point3(m_vec - point.m_vec); } template<SignedNumeric TT = T> inline constexpr auto operator-=(const Point3<TT>& point) noexcept -> Point3& { m_vec -= point.m_vec; return *this; } template<SignedNumeric TT = T> inline constexpr auto operator+(const Vec3<TT>& vec) const noexcept -> Point3 { return Point3(m_vec + vec); } template<SignedNumeric TT = T> inline constexpr auto operator+=(const Vec3<TT>& vec) noexcept -> Point3& { m_vec += vec; return *this; } template<SignedNumeric TT = T> inline constexpr auto operator-(const Vec3<TT>& vec) const noexcept -> Point3 { return Point3(m_vec - vec); } template<SignedNumeric TT = T> inline constexpr auto operator-=(const Vec3<TT>& vec) noexcept -> Point3& { m_vec -= vec; return *this; } inline constexpr auto operator*(SignedNumeric auto s) const noexcept -> Point3 { return Point3(m_vec * s); } friend inline constexpr auto operator*(SignedNumeric auto lhs, const Point3& rhs) noexcept -> Point3 { return rhs * lhs; } inline constexpr auto operator*=(SignedNumeric auto s) noexcept -> Point3& { m_vec *= s; return *this; } inline constexpr auto operator/(SignedNumeric auto s) const noexcept -> Point3 { return Point3(m_vec / s); } friend inline constexpr auto operator/(SignedNumeric auto lhs, const Point3& rhs) noexcept -> Point3 { return rhs / lhs; } inline constexpr auto operator/=(SignedNumeric auto s) noexcept -> Point3& { m_vec /= s; return *this; } friend inline constexpr auto operator<<(std::ostream& out, const Point3& point) noexcept -> std::ostream& { return out << point.x() << ' ' << point.y() << ' ' << point.z(); } private: Vec3<T> m_vec = Vec3<T>(); }; template<FloatingPoint T> explicit Point3(T, T, T) -> Point3<T>; template<SignedIntegral T> explicit Point3(T, T, T) -> Point3<T>; } // namespace hyperion::math
braxtons12/Hyperion-Math
test/src/ExponentialsTestFloat.h
<gh_stars>0 #pragma once #ifndef __MSC_VER #include <cmath> #endif #include "HyperionMath/Exponentials.h" #include "TestConstants.h" #include "gtest/gtest.h" namespace hyperion::math::test { using test::FLOAT_ACCEPTED_ERROR; TEST(ExponentialsTestFloat, frexpfCase1) { float input = 1.0F; float resultTest = 0.0F; float resultStd = 0.0F; int exponentTest = 0; int exponentStd = 0; resultTest = Exponentials::frexp(input, &exponentTest); resultStd = std::frexp(input, &exponentStd); ASSERT_FLOAT_EQ(resultTest, resultStd); ASSERT_EQ(exponentTest, exponentStd); } TEST(ExponentialsTestFloat, frexpfCase2) { float input = 2.093284109F; float resultTest = 0.0F; float resultStd = 0.0F; int exponentTest = 0; int exponentStd = 0; resultTest = Exponentials::frexp(input, &exponentTest); resultStd = std::frexp(input, &exponentStd); ASSERT_FLOAT_EQ(resultTest, resultStd); ASSERT_EQ(exponentTest, exponentStd); } TEST(ExponentialsTestFloat, expfCase1) { float input = 1.0F; ASSERT_FLOAT_EQ(Exponentials::exp(input), std::exp(input)); } TEST(ExponentialsTestFloat, expfCase2) { float input = -1.0F / (44100.0F * 0.3F); ASSERT_FLOAT_EQ(Exponentials::exp(input), std::exp(input)); } TEST(ExponentialsTestFloat, expfCase3) { float input = 3.0F; ASSERT_FLOAT_EQ(Exponentials::exp(input), std::exp(input)); } TEST(ExponentialsTestFloat, expfCase4) { float input = 9.0F; ASSERT_FLOAT_EQ(Exponentials::exp(input), std::exp(input)); } TEST(ExponentialsTestFloat, lnfCase1) { float input = 1.0F; ASSERT_FLOAT_EQ(Exponentials::ln(input), std::log(input)); } TEST(ExponentialsTestFloat, lnfCase2) { float input = 3.0F; ASSERT_NEAR(Exponentials::ln(input), std::log(input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, log2fCase1) { float input = 1.0F; ASSERT_NEAR(Exponentials::log2(input), std::log2(input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, log2fCase2) { float input = 3.0F; ASSERT_NEAR(Exponentials::log2(input), std::log2(input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, log10fCase1) { float input = 1.0F; ASSERT_NEAR(Exponentials::log10(input), std::log10(input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, log10fCase2) { float input = 3.0F; ASSERT_NEAR(Exponentials::log10(input), std::log10(input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, pow2fCase1) { float input = 1.0F; ASSERT_NEAR(Exponentials::pow2(input), std::pow(2.0F, input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, pow2fCase2) { float input = 3.0F; ASSERT_NEAR(Exponentials::pow2(input), std::pow(2.0F, input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, pow2fCase3) { float input = 3.123456F; ASSERT_NEAR(Exponentials::pow2(input), std::pow(2.0F, input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, pow2fCase4) { float input = -2.123456F; ASSERT_NEAR(Exponentials::pow2(input), std::pow(2.0F, input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, pow10fCase1) { float input = 1.0F; ASSERT_NEAR(Exponentials::pow10(input), std::pow(10.0F, input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, pow10fCase2) { float input = 3.0F; ASSERT_NEAR(Exponentials::pow10(input), std::pow(10.0F, input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, pow10fCase3) { float input = 3.123456F; ASSERT_NEAR(Exponentials::pow10(input), std::pow(10.0F, input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, pow10fCase4) { float input = -2.123456F; ASSERT_NEAR(Exponentials::pow10(input), std::pow(10.0F, input), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, powfCase1) { float base = 3.5F; float exponent = 1.0F; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, powfCase2) { float base = 3.5F; float exponent = 2.0F; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, powfCase3) { float base = 3.5F; float exponent = 2.123456F; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, powfCase4) { float base = 3.5F; float exponent = -2.123456F; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, powfCase5) { float base = 3.5F; float exponent = 1.0F / 2.0F; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, powfCase6) { float base = 0.7F; float exponent = 1.0F / 2.0F; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, powfCase7) { float base = 0.2F; float exponent = 1.0F / 2.0F; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, powfCase8) { float base = 2.0F; float exponent = 7.5F; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), FLOAT_ACCEPTED_ERROR); } TEST(ExponentialsTestFloat, powfCase9) { float base = 8.0F; float exponent = 0.5F; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), FLOAT_ACCEPTED_ERROR + 0.0001); // close enough } } // namespace hyperion::math::test
braxtons12/Hyperion-Math
include/HyperionMath/Random.h
<gh_stars>0 /// based on https://mklimenko.github.io/english/2018/06/04/constexpr-random/ #pragma once #include <atomic> #include <cstdint> #include <gsl/gsl> #include <limits> #include <random> #include "HyperionUtils/Concepts.h" namespace hyperion::math { using gsl::narrow_cast; #ifndef _MSC_VER using std::size_t; #endif //_MSC_VER // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_DATETIME_START \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wdate-time\"") #else // NOLINTNEXTLINE #define IGNORE_DATETIME_START #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_DATETIME_STOP \ _Pragma("GCC diagnostic pop") #else // NOLINTNEXTLINE #define IGNORE_DATETIME_STOP #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_WEAK_VTABLES_START \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wweak-vtables\"") #else // NOLINTNEXTLINE #define IGNORE_WEAK_VTABLES_START #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_WEAK_VTABLES_STOP \ _Pragma("GCC diagnostic pop") #else // NOLINTNEXTLINE #define IGNORE_WEAK_VTABLES_STOP #endif // clang-format on IGNORE_WEAK_VTABLES_START class Engine { public: constexpr Engine() noexcept = default; constexpr Engine(const Engine& engine) noexcept = default; constexpr Engine(Engine&& engine) noexcept = default; virtual constexpr ~Engine() noexcept = default; [[nodiscard]] virtual constexpr auto get_seed() const noexcept -> size_t = 0; virtual constexpr auto seed(size_t seed) noexcept -> void = 0; virtual constexpr auto generate() noexcept -> size_t = 0; template<size_t size> inline constexpr auto generate_array() noexcept -> std::array<size_t, size> { auto array = std::array<size_t, size>(); for(auto& element : array) { element = generate(); } } [[nodiscard]] virtual constexpr auto max_value() const noexcept -> size_t = 0; constexpr auto operator=(const Engine& engine) noexcept -> Engine& = default; constexpr auto operator=(Engine&& engine) noexcept -> Engine& = default; virtual constexpr auto operator()() noexcept -> size_t = 0; }; IGNORE_WEAK_VTABLES_STOP template<size_t max = 714025> class LinearCongruentialEngine final : public Engine { public: constexpr LinearCongruentialEngine() noexcept = default; constexpr LinearCongruentialEngine( const LinearCongruentialEngine& engine) noexcept = default; constexpr LinearCongruentialEngine(LinearCongruentialEngine&& engine) noexcept = default; constexpr ~LinearCongruentialEngine() noexcept final = default; IGNORE_DATETIME_START [[nodiscard]] inline constexpr auto get_seed() const noexcept -> size_t final { const auto* t = __TIME__; return time_from_string(t, 0) * 60 * 60 + time_from_string(t, 3) * 60 + time_from_string(t, 6); } IGNORE_DATETIME_STOP inline constexpr auto seed(size_t seed) noexcept -> void final { m_previous = seed; } [[nodiscard]] inline constexpr auto generate() noexcept -> size_t final { m_previous = (m_a * m_previous + m_c) % max; return m_previous; } [[nodiscard]] inline constexpr auto max_value() const noexcept -> size_t final { return max; } constexpr auto operator=(const LinearCongruentialEngine& engine) noexcept -> LinearCongruentialEngine& = default; constexpr auto operator=(LinearCongruentialEngine&& engine) noexcept -> LinearCongruentialEngine& = default; inline constexpr auto operator()() noexcept -> size_t final { return generate(); } private: size_t m_a = 4096; size_t m_c = 150889; size_t m_previous = get_seed(); [[nodiscard]] static inline constexpr auto time_from_string(const char* string, int offset) noexcept -> size_t { return narrow_cast<size_t>(string[offset] - '0') * 10 // NOLINT + narrow_cast<size_t>(string[offset + 1] - '0'); // NOLINT } }; IGNORE_WEAK_VTABLES_START template<typename EngineType, utils::concepts::Numeric T = int> requires utils::concepts::Derived<EngineType, Engine> class Distribution { public: constexpr Distribution() noexcept = default; constexpr Distribution(const Distribution& distribution) noexcept = default; constexpr Distribution(Distribution&& distribution) noexcept = default; virtual constexpr ~Distribution() noexcept = default; virtual constexpr auto normalized_random_value() noexcept -> double = 0; virtual constexpr auto random_value() noexcept -> T = 0; template<size_t size> inline constexpr auto normalized_random_values() noexcept -> std::array<double, size> { auto array = std::array<double, size>(); for(auto& element : array) { element = normalized_random_value(); } return array; } template<size_t size> inline constexpr auto random_values() noexcept -> std::array<T, size> { auto array = std::array<T, size>(); for(auto& element : array) { element = random_value(); } return array; } virtual constexpr auto seed(size_t seed) noexcept -> void = 0; [[nodiscard]] virtual constexpr auto get_seed() noexcept -> size_t = 0; [[nodiscard]] virtual constexpr auto get_min() const noexcept -> T = 0; virtual constexpr auto set_min(T min) noexcept -> void = 0; [[nodiscard]] virtual constexpr auto get_max() const noexcept -> T = 0; virtual constexpr auto set_max(T max) noexcept -> void = 0; constexpr auto operator=(const Distribution& distribution) noexcept -> Distribution& = default; constexpr auto operator=(Distribution&& distribution) noexcept -> Distribution& = default; virtual constexpr auto operator()() noexcept -> T = 0; }; IGNORE_WEAK_VTABLES_STOP template<typename EngineType, utils::concepts::Numeric T = int> requires utils::concepts::Derived<EngineType, Engine> class UniformDistribution final : public Distribution<EngineType, T> { public: constexpr UniformDistribution() noexcept requires utils::concepts::DefaultConstructible<EngineType> : m_engine(std::make_unique<EngineType>()) { m_engine->seed(m_engine->get_seed()); } constexpr UniformDistribution(T min, T max) noexcept requires utils::concepts::DefaultConstructible<EngineType> : m_min(min), m_max(max), m_engine(std::make_unique<EngineType>()) { m_engine->seed(m_engine->get_seed()); } constexpr UniformDistribution(T min, T max, std::unique_ptr<EngineType>&& engine) noexcept : m_min(min), m_max(max), m_engine(engine) { m_engine->seed(m_engine->get_seed()); } explicit constexpr UniformDistribution(std::unique_ptr<EngineType>&& engine) noexcept : m_engine(std::move(engine)) { m_engine->seed(m_engine->get_seed()); } template<typename... Args> requires utils::concepts::Derived<EngineType, Engine> && utils::concepts:: ConstructibleFrom<EngineType, Args...> explicit constexpr UniformDistribution(Args&&... args) noexcept : m_engine(std::make_unique<EngineType>(args...)) { m_engine->seed(m_engine->get_seed()); } template<typename... Args> requires utils::concepts::Derived<EngineType, Engine> && utils::concepts:: ConstructibleFrom<EngineType, Args...> explicit constexpr UniformDistribution(T min, T max, Args&&... args) noexcept : m_min(min), m_max(max), m_engine(std::make_unique<EngineType>(args...)) { m_engine->seed(m_engine->get_seed()); } constexpr UniformDistribution(const UniformDistribution& distribution) noexcept = default; constexpr UniformDistribution(UniformDistribution&& distribution) noexcept = default; constexpr ~UniformDistribution() noexcept final = default; inline constexpr auto normalized_random_value() noexcept -> double final { return narrow_cast<double>(m_engine->generate()) / narrow_cast<double>(m_engine->max_value()); } inline constexpr auto random_value() noexcept -> T final { return narrow_cast<T>(this->normalized_random_value()) * (m_max - m_min) + m_min; } inline constexpr auto seed(size_t seed) noexcept -> void final { m_engine->seed(seed); } [[nodiscard]] inline constexpr auto get_seed() noexcept -> size_t final { return m_engine->get_seed(); } inline constexpr auto set_min(T min) noexcept -> void final { m_min = min; } [[nodiscard]] inline constexpr auto get_min() const noexcept -> T final { return m_min; } inline constexpr auto set_max(T max) noexcept -> void final { m_max = max; } [[nodiscard]] inline constexpr auto get_max() const noexcept -> T final { return m_max; } constexpr auto operator=(const UniformDistribution& distribution) noexcept -> UniformDistribution& = default; constexpr auto operator=(UniformDistribution&& distribution) noexcept -> UniformDistribution& = default; inline constexpr auto operator()() noexcept -> T final { return random_value(); } private: T m_min = narrow_cast<T>(0); T m_max = narrow_cast<T>(1); std::unique_ptr<EngineType> m_engine; }; template<utils::concepts::Numeric T = float> [[clang::no_destroy]] static math::UniformDistribution<math::LinearCongruentialEngine<>, T> GLOBAL_UNIFORM_DISTRIBUTION; template<utils::concepts::Numeric T = float> static std::atomic_bool GLOBAL_UNIFORM_DISTRIBUTION_INITIALIZED; template<utils::concepts::Numeric T = float> inline static constexpr auto initialize_global_uniform_distribution() noexcept -> void { bool initialized = false; if(GLOBAL_UNIFORM_DISTRIBUTION_INITIALIZED<T>.compare_exchange_strong( initialized, true, std::memory_order_seq_cst)) { GLOBAL_UNIFORM_DISTRIBUTION< T> = math::UniformDistribution<math::LinearCongruentialEngine<>, T>(); } } template<utils::concepts::FloatingPoint T = float> inline auto random_value() noexcept -> T { initialize_global_uniform_distribution<T>(); GLOBAL_UNIFORM_DISTRIBUTION<T>.set_min(narrow_cast<T>(0)); GLOBAL_UNIFORM_DISTRIBUTION<T>.set_max(narrow_cast<T>(1)); return GLOBAL_UNIFORM_DISTRIBUTION<T>(); } template<utils::concepts::Numeric T = float> inline auto random_value(T min, T max) noexcept -> T { initialize_global_uniform_distribution<T>(); GLOBAL_UNIFORM_DISTRIBUTION<T>.set_min(min); GLOBAL_UNIFORM_DISTRIBUTION<T>.set_max(max); return GLOBAL_UNIFORM_DISTRIBUTION<T>(); } } // namespace hyperion::math
braxtons12/Hyperion-Math
test/src/TrigTestDouble.h
#pragma once #ifndef __MSC_VER #include <cmath> #endif #include "HyperionMath/Trig.h" #include "TestConstants.h" #include "gtest/gtest.h" namespace hyperion::math::test { using test::DOUBLE_ACCEPTED_ERROR; TEST(TrigFuncsTestDouble, cosCase1) { double input = Constants<double>::pi; ASSERT_NEAR(Trig::cos(input), std::cos(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, cosCase2) { double input = Constants<double>::piOver2; ASSERT_NEAR(Trig::cos(input), std::cos(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, cosCase3) { double input = Constants<double>::piOver4; ASSERT_NEAR(Trig::cos(input), std::cos(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, cosCase4) { double input = -Constants<double>::piOver4; ASSERT_NEAR(Trig::cos(input), std::cos(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, sinCase1) { double input = Constants<double>::pi; ASSERT_NEAR(Trig::sin(input), std::sin(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, sinCase2) { double input = Constants<double>::piOver2; ASSERT_NEAR(Trig::sin(input), std::sin(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, sinCase3) { double input = Constants<double>::piOver4; ASSERT_NEAR(Trig::sin(input), std::sin(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, sinCase4) { double input = -Constants<double>::piOver4; ASSERT_NEAR(Trig::sin(input), std::sin(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, tanCase1) { double input = Constants<double>::pi; ASSERT_NEAR(Trig::tan(input), std::tan(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, tanCase2) { double input = Constants<double>::piOver12; ASSERT_NEAR(Trig::tan(input), std::tan(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, tanCase3) { double input = Constants<double>::piOver4; ASSERT_NEAR(Trig::tan(input), std::tan(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, tanCase4) { double input = -Constants<double>::piOver4; ASSERT_NEAR(Trig::tan(input), std::tan(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, atanCase1) { double input = Constants<double>::pi; ASSERT_NEAR(Trig::atan(input), std::atan(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, atanCase2) { double input = Constants<double>::piOver12; ASSERT_NEAR(Trig::atan(input), std::atan(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, atanCase3) { double input = Constants<double>::piOver4; ASSERT_NEAR(Trig::atan(input), std::atan(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, atanCase4) { double input = -Constants<double>::piOver4; ASSERT_NEAR(Trig::atan(input), std::atan(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, tanhCase1) { double input = Constants<double>::pi; ASSERT_NEAR(Trig::tanh(input), std::tanh(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, tanhCase2) { double input = Constants<double>::piOver12; ASSERT_NEAR(Trig::tanh(input), std::tanh(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, tanhCase3) { double input = Constants<double>::piOver4; ASSERT_NEAR(Trig::tanh(input), std::tanh(input), DOUBLE_ACCEPTED_ERROR); } TEST(TrigFuncsTestDouble, tanhCase4) { double input = -Constants<double>::piOver4; ASSERT_NEAR(Trig::tanh(input), std::tanh(input), DOUBLE_ACCEPTED_ERROR); } } // namespace hyperion::math::test
braxtons12/Hyperion-Math
test/src/InterpolatorTest.h
<reponame>braxtons12/Hyperion-Math<gh_stars>0 #pragma once #include <gtest/gtest.h> #include "HyperionMath/General.h" #include "HyperionMath/Interpolator.h" namespace hyperion::math::test { TEST(InterpolatorTest, linearInterpolator) { auto interp = Interpolator<float, InterpolationType::Linear>(1.0F, 0.0F, 1.0F, 10ULL); ASSERT_FLOAT_EQ(0.0F, interp.get_next_value(utils::Some(size_t(0)))); ASSERT_FLOAT_EQ(1.0F, interp.get_next_value(utils::Some(size_t(10)))); } TEST(InterpolatorTest, logInterpolator) { auto interp = Interpolator<float, InterpolationType::Logarithmic>(1.0F, 0.0F, 1.0F, 10ULL); auto percent99 = 1.0F * 0.99F; ASSERT_FLOAT_EQ(0.0F, interp.get_next_value(utils::Some(size_t(0)))); // we want to be within 1% of the target value ASSERT_TRUE(math::General::abs(interp.get_next_value(utils::Some(size_t(10))) - percent99) <= (1.0F - percent99)); } TEST(InterpolatorTest, expInterpolator) { auto interp = Interpolator<float, InterpolationType::Exponential>(1.0F, 0.0F, 1.0F, 10ULL); auto percent99 = 1.0F * 0.99F; ASSERT_FLOAT_EQ(0.0F, interp.get_next_value(utils::Some(size_t(0)))); // we want to be within 1% of the target value ASSERT_TRUE(math::General::abs(interp.get_next_value(utils::Some(size_t(10))) - percent99) <= (1.0F - percent99)); } } // namespace hyperion::math::test
braxtons12/Hyperion-Math
test/src/ExponentialsTestDouble.h
<reponame>braxtons12/Hyperion-Math<gh_stars>0 #pragma once #ifndef __MSC_VER #include <cmath> #endif #include "HyperionMath/Exponentials.h" #include "TestConstants.h" #include "gtest/gtest.h" namespace hyperion::math::test { using test::DOUBLE_ACCEPTED_ERROR; TEST(ExponentialsTestDouble, rexpCase1) { double input = 1.0; double resultTest = 0.0; double resultStd = 0.0; int exponentTest = 0; int exponentStd = 0; resultTest = Exponentials::frexp(input, &exponentTest); resultStd = std::frexp(input, &exponentStd); ASSERT_NEAR(resultTest, resultStd, DOUBLE_ACCEPTED_ERROR); ASSERT_EQ(exponentTest, exponentStd); } TEST(ExponentialsTestDouble, rexpCase2) { double input = 2.093284109; double resultTest = 0.0; double resultStd = 0.0; int exponentTest = 0; int exponentStd = 0; resultTest = Exponentials::frexp(input, &exponentTest); resultStd = std::frexp(input, &exponentStd); ASSERT_NEAR(resultTest, resultStd, DOUBLE_ACCEPTED_ERROR); ASSERT_EQ(exponentTest, exponentStd); } TEST(ExponentialsTestDouble, expCase1) { double input = 1.0; ASSERT_NEAR(Exponentials::exp(input), std::exp(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, expCase2) { double input = -1.0 / (44100.0 * 0.3); ASSERT_NEAR(Exponentials::exp(input), std::exp(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, expCase3) { double input = 3.0; ASSERT_NEAR(Exponentials::exp(input), std::exp(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, expCase4) { double input = 9.0; ASSERT_NEAR(Exponentials::exp(input), std::exp(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, lnCase1) { double input = 1.0; ASSERT_NEAR(Exponentials::ln(input), std::log(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, lnCase2) { double input = 3.0; ASSERT_NEAR(Exponentials::ln(input), std::log(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, log2Case1) { double input = 1.0; ASSERT_NEAR(Exponentials::log2(input), std::log2(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, log2Case2) { double input = 3.0; ASSERT_NEAR(Exponentials::log2(input), std::log2(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, log10Case1) { double input = 1.0; ASSERT_NEAR(Exponentials::log10(input), std::log10(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, log10Case2) { double input = 3.0; ASSERT_NEAR(Exponentials::log10(input), std::log10(input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, pow2Case1) { double input = 1.0; ASSERT_NEAR(Exponentials::pow2(input), std::pow(2.0, input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, pow2Case2) { double input = 3.0; ASSERT_NEAR(Exponentials::pow2(input), std::pow(2.0, input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, pow2Case3) { double input = 3.123456; ASSERT_NEAR(Exponentials::pow2(input), std::pow(2.0, input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, pow2Case4) { double input = -2.123456; ASSERT_NEAR(Exponentials::pow2(input), std::pow(2.0, input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, pow10Case1) { double input = 1.0; ASSERT_NEAR(Exponentials::pow10(input), std::pow(10.0, input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, pow10Case2) { double input = 3.0; ASSERT_NEAR(Exponentials::pow10(input), std::pow(10.0, input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, pow10Case3) { double input = 3.123456; ASSERT_NEAR(Exponentials::pow10(input), std::pow(10.0, input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, pow10Case4) { double input = -2.123456; ASSERT_NEAR(Exponentials::pow10(input), std::pow(10.0, input), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, powCase1) { double base = 3.5; double exponent = 1.0; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, powCase2) { double base = 3.5; double exponent = 2.0; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, powCase3) { double base = 3.5; double exponent = 2.123456; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestDouble, powCase4) { double base = 3.5; double exponent = -2.123456; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestdouble, powCase5) { double base = 3.5; double exponent = 1.0 / 2.0; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestdouble, powCase6) { double base = 0.7; double exponent = 1.0 / 2.0; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestdouble, powCase7) { double base = 0.2; double exponent = 1.0 / 2.0; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), DOUBLE_ACCEPTED_ERROR); } TEST(ExponentialsTestdouble, powCase8) { double base = 2.0; double exponent = 7.5; ASSERT_NEAR(Exponentials::pow(base, exponent), std::pow(base, exponent), DOUBLE_ACCEPTED_ERROR); // close enough } } // namespace hyperion::math::test
braxtons12/Hyperion-Math
test/src/Vec2Test.h
#pragma once #include <gtest/gtest.h> #include "HyperionMath/Vec2.h" #include "TestConstants.h" namespace hyperion::math::test { using test::DOUBLE_ACCEPTED_ERROR; using test::FLOAT_ACCEPTED_ERROR; TEST(Vec2Test, magnitude) { auto vec = Vec2(3.0F, 5.0F); ASSERT_NEAR(vec.magnitude(), 5.830951895F, FLOAT_ACCEPTED_ERROR); } TEST(Vec2Test, dotProdFloat) { auto vec1 = Vec2(3.5F, 5.5F); auto vec2 = Vec2(5.5F, 3.5F); ASSERT_FLOAT_EQ(vec1.dot_prod(vec2), 38.5F); } TEST(Vec2Test, dotProdDouble) { auto vec1 = Vec2(3.5, 5.5); auto vec2 = Vec2(5.5, 3.5); ASSERT_DOUBLE_EQ(vec1.dot_prod(vec2), 38.5); } TEST(Vec2Test, dotProdFloatInt) { auto vec1 = Vec2(3.5F, 5.5F); auto vec2 = Vec2(6, 4); ASSERT_FLOAT_EQ(vec1.dot_prod(vec2), 43.0F); } TEST(Vec2Test, dotProdIntFloat) { auto vec1 = Vec2(6, 4); auto vec2 = Vec2(3.5F, 5.5F); ASSERT_FLOAT_EQ(vec1.dot_prod(vec2), 43.0F); } TEST(Vec2Test, crossProdFloat) { auto vec1 = Vec2(3.5F, 8.4F); auto vec2 = Vec2(4.3F, 9.2F); ASSERT_NEAR(vec1.cross_prod(vec2), -3.92F, FLOAT_ACCEPTED_ERROR); } TEST(Vec2Test, crossProdDouble) { auto vec1 = Vec2(3.5, 8.4); auto vec2 = Vec2(4.3, 9.2); ASSERT_NEAR(vec1.cross_prod(vec2), -3.92, DOUBLE_ACCEPTED_ERROR); } TEST(Vec2Test, crossProdFloatInt) { auto vec1 = Vec2(3.5F, 8.4F); auto vec2 = Vec2(4, 9); ASSERT_NEAR(vec1.cross_prod(vec2), -2.1F, FLOAT_ACCEPTED_ERROR); } TEST(Vec2Test, crossProdIntFloat) { auto vec1 = Vec2(4, 9); auto vec2 = Vec2(3.5F, 8.4F); ASSERT_NEAR(vec1.cross_prod(vec2), 2.1F, FLOAT_ACCEPTED_ERROR); } TEST(Vec2Test, normalFloatFloat) { auto vec = Vec2(3.5F, 5.5F); auto normal = vec.normal(); ASSERT_FLOAT_EQ(normal.dot_prod(vec), 0.0F); } TEST(Vec2Test, normalDoubleFloat) { auto vec = Vec2(3.5, 5.5); auto normal = vec.normal(); ASSERT_NEAR(normal.dot_prod(vec), 0.0F, FLOAT_ACCEPTED_ERROR); } TEST(Vec2Test, normalIntFloat) { auto vec = Vec2(3, 5); auto normal = vec.normal(); ASSERT_FLOAT_EQ(normal.dot_prod(vec), 0.0F); } TEST(Vec2Test, normalizedFloat) { auto vec = Vec2(3.5F, 5.5F); ASSERT_FLOAT_EQ(vec.normalized().magnitude(), 1.0F); } TEST(Vec2Test, normalizedDouble) { auto vec = Vec2(3.5, 5.5); ASSERT_FLOAT_EQ(vec.normalized().magnitude(), 1.0F); } TEST(Vec2Test, normalizedInt) { auto vec = Vec2(3, 5); ASSERT_NEAR(vec.normalized().magnitude(), 1.0F, FLOAT_ACCEPTED_ERROR); } TEST(Vec2Test, opNegative) { auto vec = Vec2(3, 5); ASSERT_EQ(-vec, Vec2(-3, -5)); } TEST(Vec2Test, opPlus) { auto vec = Vec2(3, 5); auto vec2 = Vec2(3.5F, 5.5F); ASSERT_EQ(vec + vec2, Vec2(6.5F, 10.5F)); } TEST(Vec2Test, opPlusEquals) { auto vec = Vec2(3, 5); auto vec2 = Vec2(3.5F, 5.5F); vec += vec2; ASSERT_EQ(vec, Vec2(6, 10)); } TEST(Vec2Test, opMinus) { auto vec = Vec2(3, 5); auto vec2 = Vec2(3.5F, 5.5F); ASSERT_EQ(vec - vec2, Vec2(-0.5F, -0.5F)); } TEST(Vec2Test, opMinusEquals) { auto vec = Vec2(3, 5); auto vec2 = Vec2(3.5F, 5.5F); vec -= vec2; ASSERT_EQ(vec, Vec2(0, 0)); } TEST(Vec2Test, opMul) { auto vec = Vec2(3, 5); ASSERT_EQ(vec * 2.5, Vec2(7.5, 12.5)); } TEST(Vec2Test, opMulEquals) { auto vec = Vec2(3, 5); vec *= 2.5; ASSERT_EQ(vec, Vec2(7, 12)); } TEST(Vec2Test, opDivide) { auto vec = Vec2(3, 5); ASSERT_EQ(vec / 2.5, Vec2(1.2, 2.0)); } TEST(Vec2Test, opDivideEquals) { auto vec = Vec2(3, 5); vec /= 2.5; ASSERT_EQ(vec, Vec2(1, 2)); } } // namespace hyperion::math::test
liuyihau/HZCustomToolBar
Example/HZCustomToolBar/HZAppDelegate.h
// // HZAppDelegate.h // HZCustomToolBar // // Created by <EMAIL> on 05/09/2017. // Copyright (c) 2017 <EMAIL>. All rights reserved. // @import UIKit; @interface HZAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
liuyihau/HZCustomToolBar
HZCustomToolBar/Classes/UITextView+Extension.h
// // UITextView+Extension.h // 华仔微博2期 // // Created by tarena on 15/8/19. // Copyright (c) 2015年 tarena. All rights reserved. // #import <UIKit/UIKit.h> @interface UITextView (Extension) -(void)insertAttributedText:(NSAttributedString *)text settingBlock:(void(^)(NSMutableAttributedString *attributedText))settingBlock; @end
liuyihau/HZCustomToolBar
Example/Pods/Target Support Files/HZCustomToolBar/HZCustomToolBar-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "MyWorkCircleCommentToolBar.h" #import "UITextView+Extension.h" #import "XHMessageTextView.h" FOUNDATION_EXPORT double HZCustomToolBarVersionNumber; FOUNDATION_EXPORT const unsigned char HZCustomToolBarVersionString[];
liuyihau/HZCustomToolBar
Example/HZCustomToolBar/HZViewController.h
<gh_stars>0 // // HZViewController.h // HZCustomToolBar // // Created by <EMAIL> on 05/09/2017. // Copyright (c) 2017 <EMAIL>. All rights reserved. // @import UIKit; @interface HZViewController : UIViewController @end
liuyihau/HZCustomToolBar
HZCustomToolBar/Classes/MyWorkCircleCommentToolBar.h
// // MyWorkCircleCommentToolBar.h // czjxw // // Created by zhangy on 15/11/17. // Copyright © 2015年 mariocmy. All rights reserved. // #import <UIKit/UIKit.h> #import "XHMessageTextView.h" #define kInputTextViewMinHeight 36 #define kInputTextViewMaxHeight 200 #define kHorizontalPadding 8 #define kVerticalPadding 5 @protocol MyWorkCircleCommentToolBarDelegate <NSObject> @optional /** * 文字输入框开始编辑 * * @param messageInputTextView 输入框对象 */ - (void)inputTextViewDidBeginEditing:(XHMessageTextView *)messageInputTextView; /** * 文字输入框将要开始编辑 * * @param messageInputTextView 输入框对象 */ - (void)inputTextViewWillBeginEditing:(XHMessageTextView *)messageInputTextView; /** * 发送文字消息,可能包含系统自带表情 * * @param text 文字消息 */ - (void)didSendText:(NSString *)text; @required /** * 高度变到toHeight */ - (void)didChangeFrameToHeight:(CGFloat)toHeight; @end @interface MyWorkCircleCommentToolBar : UIView @property (nonatomic, weak) id <MyWorkCircleCommentToolBarDelegate> delegate; /** * 操作栏背景图片 */ @property (strong, nonatomic) UIImage *toolbarBackgroundImage; /** * 背景图片 */ @property (strong, nonatomic) UIImage *backgroundImage; /** * 表情的附加页面 */ @property (strong, nonatomic) UIView *faceView; /** * 用于输入文本消息的输入框 */ @property (strong, nonatomic) XHMessageTextView *inputTextView; /** * 文字输入区域最大高度,必须 > KInputTextViewMinHeight(最小高度)并且 < KInputTextViewMaxHeight,否则设置无效 */ @property (nonatomic) CGFloat maxTextInputViewHeight; /** * 初始化方法 * * @param frame 位置及大小 * * @return DXMessageToolBar */ - (instancetype)initWithFrame:(CGRect)frame; /** * 默认高度 * * @return 默认高度 */ + (CGFloat)defaultHeight; - (void)finishSendMessage; -(void)becomeFirstResponderForTextField; @end
stgaudron/C-Firtree
firtree.c
#include <unistd.h> #include <stdlib.h> #include <stdio.h> static int get_columns(int size) { int index_size; int index_lines; int max_lines; int columns; columns = 1; index_size = 1; while (index_size < size) { max_lines = index_size + 3; index_lines = 1; while (index_lines < max_lines) { columns = columns + 2; index_lines = index_lines + 1; } index_size = index_size + 1; columns = columns - (index_size / 2) * 2; } return (columns); } static void put_bottom(int size, int total_max_columns, int max_lines, int index_lines) { int columns; int index_columns; if (size % 2 == 1) columns = size; else columns = size + 1; while (index_lines <= max_lines) { index_columns = 1; while (index_columns < (total_max_columns - columns + 2) / 2) { write(1, " ", 1); index_columns = index_columns + 1; } index_columns = 1; while (index_columns <= columns) { write(1, "|", 1); index_columns = index_columns + 1; } write(1, "\n", 1); index_lines = index_lines + 1; } } static int put_tree(int total_max_columns, int columns, int max_columns) { int index_columns; index_columns = 1; while (index_columns < (total_max_columns - columns + 2) / 2) { write(1, " ", 1); index_columns = index_columns + 1; } index_columns = 1; while (index_columns <= columns && columns <= max_columns) { write(1, "*", 1); index_columns = index_columns + 1; } write(1, "\n", 1); return (columns + 2); } static void check_errors(int size) { if (size == 0) { return ; } if (size < 0) { write(2, "The argument must be positive.\n", 31); return ; } } void tree(int size) { int max_lines; int total_max_lines; int columns; int index_lines; int index_size; if (size <= 0) return (check_errors(size)); total_max_lines = size + 3; index_size = 1; while (index_size <= size) { columns = get_columns(index_size); max_lines = index_size + 3; index_lines = 1; while (index_lines <= max_lines) { columns = put_tree(get_columns(size) + total_max_lines * 2 - 2, columns, columns * max_lines * 2); index_lines = index_lines + 1; } index_size = index_size + 1; } put_bottom(size, get_columns(size) + total_max_lines * 2 - 2, size, 1); } int main(int argc, char **argv) { if (!argv[1]) { write(2, "Requires an argument to size tree.\n", 36); return 0 ; } tree(atoi(argv[1])); }
heshanera/xv6
guestVM.c
<gh_stars>1-10 // A simple VM Manager - it will run a mock user program under its control #include "types.h" #include "stat.h" #include "user.h" #include "guestSysCalls.h" char *appargv[] = { "application", 0 }; int main() { printf(1, "---This is the VM server---\n"); printf(1, "starting user program() \n"); int pid = fork(); if(pid < 0) { return 0; } else if(pid == 0) { exec("application", appargv); } else if(pid > 0) { wait(); } printf(1, "---Exiting from VM server---. \n"); exit(); }
heshanera/xv6
prog.c
<reponame>heshanera/xv6<gh_stars>0 #include "types.h" #include "stat.h" #include "user.h" int main() { printf(1,"Background service started... \n"); setpriority(1); while(1){ //printf(1,"."); sleep(5); } }
heshanera/xv6
application.c
<reponame>heshanera/xv6<gh_stars>1-10 // A simple user program which will be running under the VM control #include "types.h" #include "stat.h" #include "user.h" int gdate() { return vmtrap(1); } int gmonth() { return vmtrap(2); } int gyear() { return vmtrap(3); } int main() { printf(1, "this is the application program...\n"); printf(1, "date = %d\n", gdate()); printf(1, "month = %d\n", gmonth()); printf(1, "year = %d\n", gyear()); exit(); }
heshanera/xv6
sysproc.c
#include "types.h" #include "x86.h" #include "defs.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" #include "guestSysCalls.h" int sys_fork(void) { return fork(); } int sys_exit(void) { exit(); return 0; // not reached } int sys_wait(void) { return wait(); } int sys_kill(void) { int pid; if(argint(0, &pid) < 0) return -1; return kill(pid); } int sys_getpid(void) { return proc->pid; } int sys_sbrk(void) { int addr; int n; if(argint(0, &n) < 0) return -1; addr = proc->sz; if(growproc(n) < 0) return -1; return addr; } int sys_sleep(void) { int n; uint ticks0; if(argint(0, &n) < 0) return -1; acquire(&tickslock); ticks0 = ticks; while(ticks - ticks0 < n){ if(proc->killed){ release(&tickslock); return -1; } sleep(&ticks, &tickslock); } release(&tickslock); return 0; } // return how many clock tick interrupts have occurred // since start. int sys_uptime(void) { uint xticks; acquire(&tickslock); xticks = ticks; release(&tickslock); return xticks; } // change the priority of the current process int sys_setpriority(void) { int n; if(argint(0, &n) < 0) return -1; proc->priority = (int)n; return n; } int sys_getprocessinfo(void) { int size; char * buf; char * s; int i = 0; struct proc * process; if (argint(0, &size) < 0) { return -1; } if (argptr(1, &buf,size) < 0) { return -1; } s = buf; process = getptable(); while(buf + size > s) { *(int *)s = process->pid; s += 4; *(int *)s = process->sz; s += 4; i = 0; while( i < 16){ *s = *(process->name+i); s++; i++; } *(int *)s = process->priority; s += 4; *(int *)s = process->state; s += 4; process++; } return 1; } int sys_vmtrap(void) { int n, i, vm; char vmname[] = "guestVM"; if(argint(0, &n) < 0) return -1; i = 0; while(1) { if (*(proc->parent->name + i) != *(vmname+i)) { vm = 0; break; } i++; if (i == 7) { vm = 1; break;} } if (vm == 1) return gtrap(n); else { kill(proc->pid); return 0; } }
heshanera/xv6
ps.c
#include "types.h" #include "stat.h" #include "user.h" #define NUM_STRUCTS 10 enum procstate { UNUSED, EMBRYO, SLEEPING, RUNNABLE, RUNNING, ZOMBIE }; char * pstate[] = { "U", "E", "S", "RNBL", "R", "Z" }; struct procdetails { int pid; // Process ID int psize; // Size of process memory (bytes) char pname[16]; // Process name int priority; // Priority of the process enum procstate pstate; // Process state }; int main(void) { struct procdetails proc_det_arr[NUM_STRUCTS]; struct procdetails *p; int return_val = getprocessinfo( NUM_STRUCTS*sizeof(struct procdetails), &proc_det_arr ); p = &proc_det_arr[0]; printf( 1,"%s %s %s %s %s\n", "PID","MEM","STAT","PRIO","PROC" ); while( p != &proc_det_arr[NUM_STRUCTS-1]) { if ((p->pid == 0 ) && (p->psize == 0)) break; printf( 1," %d %dB %s %d %s\n", p->pid, p->psize, pstate[p->pstate], p->priority, p->pname ); p++; } printf(1,"\nProgram %d \n\n",return_val); exit(); }
heshanera/xv6
guestSysCalls.h
// The system calls provided by the VM Managerl int gsys_date(); int gsys_month(); int gsys_year(); int gtrap(int sys_call_num);
kranzky/sooth
ext/sooth_native/sooth_statistic.h
<reponame>kranzky/sooth<filename>ext/sooth_native/sooth_statistic.h #ifndef SOOTH_STATISTIC_H #define SOOTH_STATISTIC_H //============================================================================== #include <stdint.h> typedef struct { uint32_t event; uint32_t count; } SoothStatistic; //============================================================================== #endif
kranzky/sooth
ext/sooth_native/sooth_context.h
<reponame>kranzky/sooth #ifndef SOOTH_CONTEXT_H #define SOOTH_CONTEXT_H //============================================================================== #include <stdint.h> #include "sooth_statistic.h" typedef struct { uint32_t id; uint32_t count; uint32_t statistics_size; SoothStatistic * statistics; } SoothContext; //============================================================================== #endif
lnarolski/PLCino
typy_wyliczeniowe.h
<reponame>lnarolski/PLCino<filename>typy_wyliczeniowe.h #ifndef TYPY_WYLICZENIOWE_H #define TYPY_WYLICZENIOWE_H enum elementy { cewka, styk, operator_porownania, operator_matematyczny, //do wyrzucenia blok_funkcyjny, lacznik, pusty }; //RODZAJE CEWEK: #define ZWYKLA 1 #define ZANEGOWANA 2 //RODZAJE STYKÓW: #define ZWYKLY 1 #define ZANEGOWANY 2 //RODZAJE BLOKÓW FUNKCYJNYCH: #define TIMER 1 #define LICZNIK 2 #define MOVE 3 //RODZAJE OPERATORÓW PORÓWNANIA: #define WIEKSZY_BADZ_ROWNY 1 #define WIEKSZY 2 #define MNIEJSZY_BADZ_ROWNY 3 #define MNIEJSZY 4 #define ROWNY 5 #define ROZNY 6 //RODZJE OPERATORÓW MATEMATYCZNYCH: #define DODAWANIE 1 #define ODEJMOWANIE 2 //RODZAJE ŁĄCZNIKÓW: #define LEWO_PRAWO 1 #define GORA_DOL 2 #define DOL_PRAWO 3 #define DOL_LEWO 4 #define GORA_PRAWO 5 #define GORA_LEWO 6 //RODZAJE ROZDZIELACZY: #define GORA_PRAWO_DOL 7 #define GORA_LEWO_DOL 8 #define LEWO_DOL_PRAWO 9 #define LEWO_GORA_PRAWO 10 #define GORA_DOL_LEWO_PRAWO 11 //PARAMETRY #define WEJSCIA 1 #define WYJSCIA 2 #define PV 3 #define ZMIENNA_RESETUJACA 4 #define ELEMENT1 5 #define ELEMENT2 6 #define ELEMENT_DO_PRZENIESIENIA 7 #define ZMIENNA_DOCELOWA 8 //TYP ZMIENNEJ #define NIE_DOTYCZY 1 #define DYSKRETNA 2 //#define ANALOGOWA 3 //<NAME> //#define NIE_DOTYCZY 1 #define WEJSCIE 2 #define WYJSCIE 3 #endif // TYPY_WYLICZENIOWE_H
lnarolski/PLCino
ui_zmienne.h
<gh_stars>0 /******************************************************************************** ** Form generated from reading UI file 'zmienne.ui' ** ** Created by: Qt User Interface Compiler version 5.9.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_ZMIENNE_H #define UI_ZMIENNE_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QPushButton> #include <QtWidgets/QTableWidget> #include <QtWidgets/QVBoxLayout> QT_BEGIN_NAMESPACE class Ui_Dialog { public: QGridLayout *gridLayout; QHBoxLayout *horizontalLayout; QVBoxLayout *verticalLayout; QPushButton *pushButton_3; QPushButton *pushButton; QPushButton *pushButton_2; QTableWidget *tableWidget; void setupUi(QDialog *Dialog) { if (Dialog->objectName().isEmpty()) Dialog->setObjectName(QStringLiteral("Dialog")); Dialog->resize(400, 300); gridLayout = new QGridLayout(Dialog); gridLayout->setObjectName(QStringLiteral("gridLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); pushButton_3 = new QPushButton(Dialog); pushButton_3->setObjectName(QStringLiteral("pushButton_3")); verticalLayout->addWidget(pushButton_3); pushButton = new QPushButton(Dialog); pushButton->setObjectName(QStringLiteral("pushButton")); verticalLayout->addWidget(pushButton); pushButton_2 = new QPushButton(Dialog); pushButton_2->setObjectName(QStringLiteral("pushButton_2")); verticalLayout->addWidget(pushButton_2); horizontalLayout->addLayout(verticalLayout); gridLayout->addLayout(horizontalLayout, 0, 1, 1, 1); tableWidget = new QTableWidget(Dialog); if (tableWidget->columnCount() < 2) tableWidget->setColumnCount(2); tableWidget->setObjectName(QStringLiteral("tableWidget")); tableWidget->setColumnCount(2); gridLayout->addWidget(tableWidget, 0, 0, 1, 1); retranslateUi(Dialog); QMetaObject::connectSlotsByName(Dialog); } // setupUi void retranslateUi(QDialog *Dialog) { Dialog->setWindowTitle(QApplication::translate("Dialog", "Dialog", Q_NULLPTR)); pushButton_3->setText(QApplication::translate("Dialog", "Nowa", Q_NULLPTR)); pushButton->setText(QApplication::translate("Dialog", "Usu\305\204", Q_NULLPTR)); pushButton_2->setText(QApplication::translate("Dialog", "Zmie\305\204 nazw\304\231", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class Dialog: public Ui_Dialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_ZMIENNE_H
lnarolski/PLCino
model_uzywane_zmienne.h
<filename>model_uzywane_zmienne.h #ifndef MODEL_UZYWANE_ZMIENNE_H #define MODEL_UZYWANE_ZMIENNE_H #include <QAbstractTableModel> #include <QMap> #include <zmienna_w_arduino.h> #include <typy_wyliczeniowe.h> class model_uzywane_zmienne : public QAbstractTableModel { Q_OBJECT public: enum MapRoles { KeyRole = Qt::UserRole + 1, ValueRole }; explicit model_uzywane_zmienne(QObject *parent = 0); int rowCount(const QModelIndex& parent = QModelIndex()) const; int columnCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; inline void setMap(QMap<QString, zmienna_w_arduino>* map) { _map = map; } void dodaj_zmienna(QString nazwa, zmienna_w_arduino zmienna); void usun_zmienna(QString nazwa); QVariant headerData(int section, Qt::Orientation orientation, int role) const; //metoda odpowiedzialna za nadawanie nazw nagłówków private: QMap<QString, zmienna_w_arduino>* _map; //adres do listy używanych zmiennych z głównej klasy PLCino QString typ_zmiennej_QString(quint32 zmienna) const; QString rodzaj_pinu_QString(quint32 zmienna) const; }; #endif // MODEL_UZYWANE_ZMIENNE_H
lnarolski/PLCino
edycja_specjalna.h
<reponame>lnarolski/PLCino<gh_stars>0 #ifndef EDYCJA_SPECJALNA_H #define EDYCJA_SPECJALNA_H #include <QWizard> #include <QWizardPage> #include <QLabel> #include <QLineEdit> #include <QVBoxLayout> #include <elementy_drabinki.h> class edycja_specjalna : public QWizard { public: edycja_specjalna(elementy_drabinki *temp); void accept() override; private: elementy_drabinki *adres_temp; QWizardPage *edycja_licznika(); QWizardPage *edycja_timera(); QWizardPage *edycja_MOVE(); QWizardPage *edycja_operatora_matematycznego(); QWizardPage *edycja_operatora_porownania(); }; class licznik_strona : public QWizardPage { public: licznik_strona(elementy_drabinki *temp) { adres_temp = temp; QLabel *podanie_zmiennej = new QLabel("Podaj zmienną licznika:"); QLineEdit *podanie_zmiennej_QLineEdit = new QLineEdit(); podanie_zmiennej_QLineEdit->setText(adres_temp->zmienna); QLabel *podanie_wartosci = new QLabel("Podaj PV:"); QLineEdit *podanie_wartosci_QLineEdit = new QLineEdit(); podanie_wartosci_QLineEdit->setInputMask("99999"); podanie_wartosci_QLineEdit->setText(adres_temp->parametry.value(PV)); QLabel *podanie_zmiennej_resetujacej = new QLabel("Podaj zmienną resetujacą:"); QLineEdit *podanie_zmiennej_resetujacej_QLineEdit = new QLineEdit(); podanie_zmiennej_resetujacej_QLineEdit->setText(adres_temp->parametry.value(ZMIENNA_RESETUJACA)); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(podanie_zmiennej); layout->addWidget(podanie_zmiennej_QLineEdit); layout->addWidget(podanie_wartosci); layout->addWidget(podanie_wartosci_QLineEdit); layout->addWidget(podanie_zmiennej_resetujacej); layout->addWidget(podanie_zmiennej_resetujacej_QLineEdit); this->setLayout(layout); this->registerField("podanie_zmiennej_QLineEdit", podanie_zmiennej_QLineEdit); this->registerField("podanie_wartosci_QLineEdit", podanie_wartosci_QLineEdit); this->registerField("podanie_zmiennej_resetujacej_QLineEdit", podanie_zmiennej_resetujacej_QLineEdit); } elementy_drabinki *adres_temp; }; class timer_strona : public QWizardPage { public: timer_strona(elementy_drabinki *temp) { adres_temp = temp; QLabel *podanie_zmiennej = new QLabel("Podaj zmienną timera:"); QLineEdit *podanie_zmiennej_QLineEdit = new QLineEdit(); podanie_zmiennej_QLineEdit->setText(adres_temp->zmienna); QLabel *podanie_wartosci = new QLabel("Podaj PV(ms):"); QLineEdit *podanie_wartosci_QLineEdit = new QLineEdit(); podanie_wartosci_QLineEdit->setInputMask("99999"); podanie_wartosci_QLineEdit->setText(adres_temp->parametry.value(PV)); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(podanie_zmiennej); layout->addWidget(podanie_zmiennej_QLineEdit); layout->addWidget(podanie_wartosci); layout->addWidget(podanie_wartosci_QLineEdit); this->setLayout(layout); this->registerField("podanie_zmiennej_QLineEdit", podanie_zmiennej_QLineEdit); this->registerField("podanie_wartosci_QLineEdit", podanie_wartosci_QLineEdit); } elementy_drabinki *adres_temp; }; class move_strona : public QWizardPage { public: move_strona(elementy_drabinki *temp) { adres_temp = temp; QLabel *podanie_wartosci = new QLabel("Podaj element do przeniesienia:"); QLineEdit *podanie_wartosci_QLineEdit = new QLineEdit(); podanie_wartosci_QLineEdit->setText(adres_temp->parametry.value(ELEMENT_DO_PRZENIESIENIA)); QLabel *podanie_zmiennej_docelowej = new QLabel("Podaj zmienną docelową:"); QLineEdit *podanie_zmiennej_docelowej_QLineEdit = new QLineEdit(); podanie_zmiennej_docelowej_QLineEdit->setText(adres_temp->parametry.value(ZMIENNA_DOCELOWA)); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(podanie_wartosci); layout->addWidget(podanie_wartosci_QLineEdit); layout->addWidget(podanie_zmiennej_docelowej); layout->addWidget(podanie_zmiennej_docelowej_QLineEdit); this->setLayout(layout); this->registerField("podanie_wartosci_QLineEdit", podanie_wartosci_QLineEdit); this->registerField("podanie_zmiennej_docelowej_QLineEdit", podanie_zmiennej_docelowej_QLineEdit); } elementy_drabinki *adres_temp; }; class operator_porownania_strona : public QWizardPage { public: operator_porownania_strona(elementy_drabinki *temp) { adres_temp = temp; QLabel *napis_informacyjny = new QLabel("Blok porównuje pierwszy element z drugim."); QLabel *podanie_element1 = new QLabel("Podaj pierwszy element:"); QLineEdit *podanie_element1_QLineEdit = new QLineEdit(); podanie_element1_QLineEdit->setText(adres_temp->parametry.value(ELEMENT1)); QLabel *podanie_element2 = new QLabel("Podaj drugi element:"); QLineEdit *podanie_element2_QLineEdit = new QLineEdit(); podanie_element2_QLineEdit->setText(adres_temp->parametry.value(ELEMENT2)); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(napis_informacyjny); layout->addWidget(podanie_element1); layout->addWidget(podanie_element1_QLineEdit); layout->addWidget(podanie_element2); layout->addWidget(podanie_element2_QLineEdit); this->setLayout(layout); this->registerField("podanie_element1_QLineEdit", podanie_element1_QLineEdit); this->registerField("podanie_element2_QLineEdit", podanie_element2_QLineEdit); } elementy_drabinki *adres_temp; }; class operator_matematyczny_strona : public QWizardPage { public: operator_matematyczny_strona(elementy_drabinki *temp) { adres_temp = temp; QLabel *napis_informacyjny = new QLabel("Blok przeprowadza działanie matematyczne i zapisuje jego wynik w miejscu pierwszego elementu."); QLabel *podanie_element1 = new QLabel("Podaj pierwszy element:"); QLineEdit *podanie_element1_QLineEdit = new QLineEdit(); podanie_element1_QLineEdit->setText(adres_temp->parametry.value(ELEMENT1)); QLabel *podanie_element2 = new QLabel("Podaj drugi element:"); QLineEdit *podanie_element2_QLineEdit = new QLineEdit(); podanie_element2_QLineEdit->setText(adres_temp->parametry.value(ELEMENT2)); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(napis_informacyjny); layout->addWidget(podanie_element1); layout->addWidget(podanie_element1_QLineEdit); layout->addWidget(podanie_element2); layout->addWidget(podanie_element2_QLineEdit); this->setLayout(layout); this->registerField("podanie_element1_QLineEdit", podanie_element1_QLineEdit); this->registerField("podanie_element2_QLineEdit", podanie_element2_QLineEdit); } elementy_drabinki *adres_temp; }; #endif // EDYCJA_SPECJALNA_H
lnarolski/PLCino
ui_dodawanie_zmiennej.h
/******************************************************************************** ** Form generated from reading UI file 'dodawanie_zmiennej.ui' ** ** Created by: Qt User Interface Compiler version 5.9.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_DODAWANIE_ZMIENNEJ_H #define UI_DODAWANIE_ZMIENNEJ_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QComboBox> #include <QtWidgets/QDialog> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QVBoxLayout> QT_BEGIN_NAMESPACE class Ui_dodawanie_zmiennej { public: QGridLayout *gridLayout; QDialogButtonBox *buttonBox; QGridLayout *gridLayout_2; QLabel *label; QSpacerItem *verticalSpacer; QHBoxLayout *horizontalLayout; QVBoxLayout *verticalLayout_2; QLabel *label_3; QComboBox *rodzaj_zmiennej_comboBox; QVBoxLayout *verticalLayout; QLabel *label_4; QComboBox *typ_pinu_comboBox; QLineEdit *numer_pinu; QLabel *label_2; QLineEdit *nazwa_zmiennej; void setupUi(QDialog *dodawanie_zmiennej) { if (dodawanie_zmiennej->objectName().isEmpty()) dodawanie_zmiennej->setObjectName(QStringLiteral("dodawanie_zmiennej")); dodawanie_zmiennej->setWindowModality(Qt::WindowModal); dodawanie_zmiennej->resize(400, 188); dodawanie_zmiennej->setModal(false); gridLayout = new QGridLayout(dodawanie_zmiennej); gridLayout->setObjectName(QStringLiteral("gridLayout")); buttonBox = new QDialogButtonBox(dodawanie_zmiennej); buttonBox->setObjectName(QStringLiteral("buttonBox")); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); gridLayout->addWidget(buttonBox, 1, 0, 1, 1); gridLayout_2 = new QGridLayout(); gridLayout_2->setObjectName(QStringLiteral("gridLayout_2")); gridLayout_2->setSizeConstraint(QLayout::SetDefaultConstraint); label = new QLabel(dodawanie_zmiennej); label->setObjectName(QStringLiteral("label")); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(label->sizePolicy().hasHeightForWidth()); label->setSizePolicy(sizePolicy); gridLayout_2->addWidget(label, 0, 0, 1, 1); verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout_2->addItem(verticalSpacer, 5, 0, 1, 1); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); verticalLayout_2 = new QVBoxLayout(); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); label_3 = new QLabel(dodawanie_zmiennej); label_3->setObjectName(QStringLiteral("label_3")); label_3->setAlignment(Qt::AlignCenter); verticalLayout_2->addWidget(label_3); rodzaj_zmiennej_comboBox = new QComboBox(dodawanie_zmiennej); rodzaj_zmiennej_comboBox->setObjectName(QStringLiteral("rodzaj_zmiennej_comboBox")); verticalLayout_2->addWidget(rodzaj_zmiennej_comboBox); horizontalLayout->addLayout(verticalLayout_2); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); label_4 = new QLabel(dodawanie_zmiennej); label_4->setObjectName(QStringLiteral("label_4")); label_4->setAlignment(Qt::AlignCenter); verticalLayout->addWidget(label_4); typ_pinu_comboBox = new QComboBox(dodawanie_zmiennej); typ_pinu_comboBox->setObjectName(QStringLiteral("typ_pinu_comboBox")); verticalLayout->addWidget(typ_pinu_comboBox); horizontalLayout->addLayout(verticalLayout); gridLayout_2->addLayout(horizontalLayout, 4, 0, 1, 1); numer_pinu = new QLineEdit(dodawanie_zmiennej); numer_pinu->setObjectName(QStringLiteral("numer_pinu")); gridLayout_2->addWidget(numer_pinu, 3, 0, 1, 1); label_2 = new QLabel(dodawanie_zmiennej); label_2->setObjectName(QStringLiteral("label_2")); sizePolicy.setHeightForWidth(label_2->sizePolicy().hasHeightForWidth()); label_2->setSizePolicy(sizePolicy); gridLayout_2->addWidget(label_2, 2, 0, 1, 1); nazwa_zmiennej = new QLineEdit(dodawanie_zmiennej); nazwa_zmiennej->setObjectName(QStringLiteral("nazwa_zmiennej")); nazwa_zmiennej->setReadOnly(false); gridLayout_2->addWidget(nazwa_zmiennej, 1, 0, 1, 1); gridLayout->addLayout(gridLayout_2, 0, 0, 1, 1); QWidget::setTabOrder(nazwa_zmiennej, numer_pinu); QWidget::setTabOrder(numer_pinu, rodzaj_zmiennej_comboBox); QWidget::setTabOrder(rodzaj_zmiennej_comboBox, typ_pinu_comboBox); retranslateUi(dodawanie_zmiennej); QObject::connect(buttonBox, SIGNAL(accepted()), dodawanie_zmiennej, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), dodawanie_zmiennej, SLOT(reject())); QMetaObject::connectSlotsByName(dodawanie_zmiennej); } // setupUi void retranslateUi(QDialog *dodawanie_zmiennej) { dodawanie_zmiennej->setWindowTitle(QApplication::translate("dodawanie_zmiennej", "Dodaj now\304\205 zmienn\304\205", Q_NULLPTR)); label->setText(QApplication::translate("dodawanie_zmiennej", "Podaj nazw\304\231 zmiennej:", Q_NULLPTR)); label_3->setText(QApplication::translate("dodawanie_zmiennej", "Rodzaj zmiennej:", Q_NULLPTR)); rodzaj_zmiennej_comboBox->clear(); rodzaj_zmiennej_comboBox->insertItems(0, QStringList() << QApplication::translate("dodawanie_zmiennej", "Nie dotyczy", Q_NULLPTR) << QApplication::translate("dodawanie_zmiennej", "Dyskretna", Q_NULLPTR) << QApplication::translate("dodawanie_zmiennej", "Analogowa", Q_NULLPTR) ); label_4->setText(QApplication::translate("dodawanie_zmiennej", "Typ pinu:", Q_NULLPTR)); typ_pinu_comboBox->clear(); typ_pinu_comboBox->insertItems(0, QStringList() << QApplication::translate("dodawanie_zmiennej", "Nie dotyczy", Q_NULLPTR) << QApplication::translate("dodawanie_zmiennej", "Wej\305\233cie", Q_NULLPTR) << QApplication::translate("dodawanie_zmiennej", "Wyj\305\233cie", Q_NULLPTR) ); label_2->setText(QApplication::translate("dodawanie_zmiennej", "Podaj numer pinu:", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class dodawanie_zmiennej: public Ui_dodawanie_zmiennej {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_DODAWANIE_ZMIENNEJ_H
lnarolski/PLCino
wybor_portu.h
#ifndef WYBOR_PORTU_H #define WYBOR_PORTU_H #include <QDialog> #include <QtSerialPort/QSerialPortInfo> #include <QAbstractButton> namespace Ui { class Wybor_portu; } class Wybor_portu : public QDialog { Q_OBJECT public: explicit Wybor_portu(QWidget *parent = 0, QString *adres_do_konfiguracji = NULL); ~Wybor_portu(); private slots: void on_buttonBox_accepted(); void on_buttonBox_rejected(); void on_buttonBox_clicked(QAbstractButton *button); private: Ui::Wybor_portu *ui; QWidget* rodzic; QString* wybrany_port; }; #endif // WYBOR_PORTU_H
lnarolski/PLCino
dodawanie_zmiennej.h
<filename>dodawanie_zmiennej.h #ifndef DODAWANIE_ZMIENNEJ_H #define DODAWANIE_ZMIENNEJ_H #include <QDialog> #include <QMap> #include <QString> #include "model_uzywane_zmienne.h" #include <zmienna_w_arduino.h> namespace Ui { class dodawanie_zmiennej; } class dodawanie_zmiennej : public QDialog { Q_OBJECT public: explicit dodawanie_zmiennej(QMap<QString, zmienna_w_arduino> *lista, model_uzywane_zmienne *model, QString nazwa_zmiennej = "", QString *adres_nazwy_zmiennej_z_modelu_drabinki = NULL, QString numer_pinu = "", quint32 rodzaj_zmiennej = 0, quint32 typ_pinu = 0, QWidget *parent = 0); ~dodawanie_zmiennej(); private slots: void on_buttonBox_accepted(); void on_buttonBox_rejected(); public: Ui::dodawanie_zmiennej *ui; private: QMap<QString, zmienna_w_arduino> *lista_uzywanych_zmiennych; //adres do listy używanych zmiennych w głównej klasie model_uzywane_zmienne *model_temp; //adres do modelu danych używanego przez listę używanych zmiennych QString* nazwa_wybranej_zmiennej; }; #endif // DODAWANIE_ZMIENNEJ_H
lnarolski/PLCino
ui_okno_edycji_wlasciwosci.h
<reponame>lnarolski/PLCino /******************************************************************************** ** Form generated from reading UI file 'okno_edycji_wlasciwosci.ui' ** ** Created by: Qt User Interface Compiler version 5.9.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_OKNO_EDYCJI_WLASCIWOSCI_H #define UI_OKNO_EDYCJI_WLASCIWOSCI_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QVBoxLayout> QT_BEGIN_NAMESPACE class Ui_okno_edycji_wlasciwosci { public: QGridLayout *gridLayout; QVBoxLayout *verticalLayout; QDialogButtonBox *buttonBox; void setupUi(QDialog *okno_edycji_wlasciwosci) { if (okno_edycji_wlasciwosci->objectName().isEmpty()) okno_edycji_wlasciwosci->setObjectName(QStringLiteral("okno_edycji_wlasciwosci")); okno_edycji_wlasciwosci->resize(400, 300); gridLayout = new QGridLayout(okno_edycji_wlasciwosci); gridLayout->setObjectName(QStringLiteral("gridLayout")); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); gridLayout->addLayout(verticalLayout, 0, 0, 1, 1); buttonBox = new QDialogButtonBox(okno_edycji_wlasciwosci); buttonBox->setObjectName(QStringLiteral("buttonBox")); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); gridLayout->addWidget(buttonBox, 1, 0, 1, 1); retranslateUi(okno_edycji_wlasciwosci); QObject::connect(buttonBox, SIGNAL(accepted()), okno_edycji_wlasciwosci, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), okno_edycji_wlasciwosci, SLOT(reject())); QMetaObject::connectSlotsByName(okno_edycji_wlasciwosci); } // setupUi void retranslateUi(QDialog *okno_edycji_wlasciwosci) { okno_edycji_wlasciwosci->setWindowTitle(QApplication::translate("okno_edycji_wlasciwosci", "Dialog", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class okno_edycji_wlasciwosci: public Ui_okno_edycji_wlasciwosci {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_OKNO_EDYCJI_WLASCIWOSCI_H
lnarolski/PLCino
elementy_schematu.h
<gh_stars>0 #ifndef KOMPILATOR_H #define KOMPILATOR_H class elementy_schematu { public: elementy_schematu(elementy_drabinki* a, int linia, int kolumna, int wiersz) { element = a; numer_linii = linia; numer_kolumny = kolumna; numer_wiersza = wiersz; } elementy_drabinki* element; QList<elementy_schematu*> wejscia_elementu; QList<elementy_schematu*> wyjscia_elementu; int numer_linii; int numer_kolumny; int numer_wiersza; }; #endif // KOMPILATOR_H