text:
// Copyright (C) 2014 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//
//     * Neither the name of The Regents or University of California nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
//         Torsten Sattler (sattlert@inf.ethz.ch)

#include <Eigen/Dense>

#include <math.h>
#include "gtest/gtest.h"

#include "theia/alignment/alignment.h"
#include "theia/test/test_utils.h"
#include "theia/vision/sfm/camera/camera_pose.h"

namespace theia {

namespace {

using Eigen::Vector3d;
using Eigen::Vector2d;
using Eigen::Matrix3d;
using Eigen::Matrix;

class CameraPoseTest : public ::testing::Test {
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW protected : virtual void SetUp() {
    // Initializes R with a random rotation matrix.
    //    R_ << -0.5633,  0.7560,  0.3334,
    //         -0.6822, -0.1978, -0.7039,
    //         -0.4662, -0.6239, 0.6272;
    rotation_matrix_.block<1, 3>(0, 0) =
        Vector3d(-0.5633, 0.7560, 0.3334).normalized().transpose();
    rotation_matrix_.block<1, 3>(1, 0) =
        Vector3d(-0.6822, -0.1978, -0.7039).normalized().transpose();
    rotation_matrix_.block<1, 3>(2, 0) =
        Vector3d(-0.4662, -0.6239, 0.6272).normalized().transpose();

    translation_ = Vector3d(0.0, 1.0, -20.0);

    position_ = -rotation_matrix_.transpose() * translation_;

    f_ = -1.0;
    calibration_matrix_ << f_, 0.0, 0.0, 0.0, f_, 0.0, 0.0, 0.0, 1.0;

    k1_ = -2.0;
    k2_ = 3.0;
    k3_ = 5.0;
    k4_ = -3.5;

    transformation_matrix_.linear() = rotation_matrix_;
    transformation_matrix_.translation() = translation_;

    projection_matrix_ = calibration_matrix_ * transformation_matrix_.matrix();

    pose_.InitializePose(rotation_matrix_, translation_, calibration_matrix_,
                         k1_, k2_, k3_, k4_);
  }

  // Checks that a pose was correctly initialized with the parameters given
  // above.
  void TestPose(const CameraPose &pose) {
    const Matrix3d calibration_matrix = pose.calibration_matrix();

    // calibration_matrix_ has the form diag(f,f,1), while calibration_matrix
    // might have the form diag(1,1,1/f).
    // In order to be comparable, we thus introduce a temporary internal
    // camera calibration that we compare against.
    const Matrix3d calibration_matrix_tmp =
        calibration_matrix_ * calibration_matrix(2, 2);
    test::ExpectMatricesNear(calibration_matrix, calibration_matrix_tmp, 1e-6);

    double k1 = 0.0;
    double k2 = 1.0;
    double k3 = 2.0;
    double k4 = 3.0;
    pose.radial_distortion(&k1, &k2, &k3, &k4);
    ASSERT_DOUBLE_EQ(k1_, k1);
    ASSERT_DOUBLE_EQ(k2_, k2);
    ASSERT_DOUBLE_EQ(k3_, k3);
    ASSERT_DOUBLE_EQ(k4_, k4);

    Matrix<double, 3, 4> projection_matrix = pose.projection_matrix();
    // Depending on the form of the internal calibration which was used to
    // initialize the pose, the projection matrix might differ by a scaling
    // factor from projection_matrix_. Again, we use a temporary projection
    // matrix to allow a meaningful comparison.
    Matrix<double, 3, 4> projection_matrix_tmp =
        calibration_matrix_tmp * transformation_matrix_.matrix();
    test::ExpectMatricesNear(projection_matrix, projection_matrix_tmp, 1e-6);

    Matrix<double, 3, 4> T = pose.transformation_matrix();
    test::ExpectMatricesNear(T, transformation_matrix_.matrix(), 1e-6);
  }

  // The rotation matrix of the pose.
  Matrix3d rotation_matrix_;
  // The translation of the pose.
  Vector3d translation_;

  // The position of the pose.
  Vector3d position_;

  // The focal length of the pose.
  double f_;
  // Internal camera calibration matrix.
  Matrix3d calibration_matrix_;
  // The radial distortion parameters of the pose.
  double k1_;
  double k2_;
  double k3_;
  double k4_;
  // The projection matrix of the pose.
  Matrix<double, 3, 4> projection_matrix_;
  // The transformation matrix of the pose.
  Eigen::AffineCompact3d transformation_matrix_;
  // A camera pose for testing.
  CameraPose pose_;
};

TEST_F(CameraPoseTest, InializationFromParameters) {
  CameraPose pose;
  pose.InitializePose(rotation_matrix_, translation_, calibration_matrix_, k1_,
                      k2_, k3_, k4_);
  TestPose(pose);
}

TEST_F(CameraPoseTest, InializationFromOtherPose) {
  CameraPose pose;
  pose.InitializePose(pose_);
  TestPose(pose);
}

TEST_F(CameraPoseTest, InializationFromProjectionMatrix) {
  Matrix3d K;
  K << 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, -1.0;

  Matrix<double, 3, 4> projection_matrix = K * transformation_matrix_.matrix();
  CameraPose pose;
  pose.InitializePose(projection_matrix, k1_, k2_, k3_, k4_);
  TestPose(pose);
}

TEST_F(CameraPoseTest, WorldToCameraWorks) {
  Vector3d p_w = -rotation_matrix_.inverse() * translation_;
  Vector3d p_c(Vector3d::Zero());
  pose_.WorldToCamera(p_w, &p_c);
  ASSERT_NEAR(0.0, p_c[0], 1e-6);
  ASSERT_NEAR(0.0, p_c[1], 1e-6);
  ASSERT_NEAR(0.0, p_c[2], 1e-6);
}

TEST_F(CameraPoseTest, WorldToCameraManyPointsWorks) {
  std::vector<Vector3d> world_points = { Vector3d(1.0, 1.0, 5.0),
                                         Vector3d(-2.3, 1.7, 3.8),
                                         Vector3d(1.9, -0.9, 4.1),
                                         Vector3d(-1.4, -1.9, 3.0) };
  std::vector<Vector3d> gt_camera_points;
  for (int i = 0; i < world_points.size(); i++) {
    gt_camera_points.push_back(transformation_matrix_ * world_points[i]);
  }

  std::vector<Vector3d> camera_points;
  pose_.WorldToCamera(world_points, &camera_points);
  ASSERT_EQ(camera_points.size(), world_points.size());
  for (int i = 0; i < world_points.size(); i++) {
    ASSERT_DOUBLE_EQ(camera_points[i].x(), gt_camera_points[i].x());
    ASSERT_DOUBLE_EQ(camera_points[i].y(), gt_camera_points[i].y());
    ASSERT_DOUBLE_EQ(camera_points[i].z(), gt_camera_points[i].z());
  }
}

TEST_F(CameraPoseTest, CameraToWorldWorks) {
  Vector3d p_w = transformation_matrix_.inverse().translation();
  Vector3d p_c(Vector3d::Zero());
  Vector3d p_w_comp(Vector3d::Zero());
  pose_.CameraToWorld(p_c, &p_w_comp);
  ASSERT_NEAR(p_w[0], p_w_comp[0], 1e-6);
  ASSERT_NEAR(p_w[1], p_w_comp[1], 1e-6);
  ASSERT_NEAR(p_w[2], p_w_comp[2], 1e-6);
}

TEST_F(CameraPoseTest, CameraToWorldManyPointsWorks) {
  std::vector<Vector3d> camera_points = { Vector3d(1.0, 1.0, 5.0),
                                          Vector3d(-2.3, 1.7, 3.8),
                                          Vector3d(1.9, -0.9, 4.1),
                                          Vector3d(-1.4, -1.9, 3.0) };
  std::vector<Vector3d> gt_world_points;
  for (int i = 0; i < camera_points.size(); i++) {
    gt_world_points.push_back(transformation_matrix_.inverse() *
                              camera_points[i]);
  }

  std::vector<Vector3d> world_points;
  pose_.CameraToWorld(camera_points, &world_points);
  ASSERT_EQ(world_points.size(), camera_points.size());
  for (int i = 0; i < world_points.size(); i++) {
    ASSERT_DOUBLE_EQ(world_points[i].x(), gt_world_points[i].x());
    ASSERT_DOUBLE_EQ(world_points[i].y(), gt_world_points[i].y());
    ASSERT_DOUBLE_EQ(world_points[i].z(), gt_world_points[i].z());
  }
}

TEST_F(CameraPoseTest, CameraToImageWorks) {
  Matrix3d R(Matrix3d::Identity());
  Vector3d t(Vector3d::Zero());
  CameraPose pose;
  pose.InitializePose(R, t, calibration_matrix_, 0.0, 0.0, 0.0, 0.0);

  Vector2d p_i;
  pose.CameraToImage(Vector3d(10.0, -20.0, -1.0), &p_i);
  ASSERT_DOUBLE_EQ(10.0, p_i[0]);
  ASSERT_DOUBLE_EQ(-20.0, p_i[1]);

  // Tests that the decision whether the point is in front or behind the
  // camera also works in the case that the intrinsic matrix is given in the
  // form diag(1,1,1/f).
  CameraPose pose2;
  Matrix3d K(Matrix3d::Identity());
  K(2, 2) = -0.5;
  pose2.InitializePose(R, t, K, 0.0, 0.0, 0.0, 0.0);
  pose2.CameraToImage(Vector3d(10.0, -20.0, -1.0), &p_i);
  ASSERT_DOUBLE_EQ(p_i.x(), 20.0);
  ASSERT_DOUBLE_EQ(p_i.y(), -40.0);

  K(2, 2) = 0.5;
  pose2.InitializePose(R, t, K, 0.0, 0.0, 0.0, 0.0);
  pose2.CameraToImage(Vector3d(10.0, 10.0, 1.0), &p_i);
  ASSERT_DOUBLE_EQ(p_i.x(), 20.0);
  ASSERT_DOUBLE_EQ(p_i.y(), 20.0);
}

TEST_F(CameraPoseTest, CameraToImageManyPointsWorks) {
  Matrix3d R(Matrix3d::Identity());
  Vector3d t(Vector3d::Zero());
  CameraPose pose;
  pose.InitializePose(R, t, calibration_matrix_, 0.0, 0.0, 0.0, 0.0);

  std::vector<Vector3d> p_world = {
    Vector3d(1.0, 1.0, 2.0), Vector3d(-5.0, 0.2, 1.0), Vector3d(1.6, -0.9, 1.2)
  };

  std::vector<Vector2d> gt_p_image = { Vector2d(-1.0 / 2.0, -1.0 / 2.0),
                                       Vector2d(5.0 / 1.0, -0.2 / 1.0),
                                       Vector2d(-1.6 / 1.2, 0.9 / 1.2) };

  std::vector<Vector2d> p_image;
  pose.CameraToImage(p_world, &p_image);
  ASSERT_EQ(p_image.size(), p_world.size());
  for (int i = 0; i < p_image.size(); i++) {
    ASSERT_DOUBLE_EQ(p_image[i].x(), gt_p_image[i].x());
    ASSERT_DOUBLE_EQ(p_image[i].y(), gt_p_image[i].y());
  }
}

TEST_F(CameraPoseTest, WorldToImageWorks) {
  Matrix3d R(Matrix3d::Identity());
  Vector3d t(Vector3d::Zero());
  CameraPose pose;
  pose.InitializePose(R, t, calibration_matrix_, 0.0, 0.0, 0.0, 0.0);

  Vector2d p_i(0.0, 0.0);
  ASSERT_FALSE(pose.WorldToImage(Vector3d(10.0, 10.0, 0.0), &p_i));
  ASSERT_FALSE(pose.WorldToImage(Vector3d(10.0, 10.0, 1.0), &p_i));
  ASSERT_TRUE(pose.WorldToImage(Vector3d(10.0, -20.0, -1.0), &p_i));
  ASSERT_NEAR(10.0, p_i[0], 1e-6);
  ASSERT_NEAR(-20.0, p_i[1], 1e-6);

  // Tests that the decision whether the point is in front or behind the
  // camera also works in the case that the intrinsic matrix is given in the
  // form diag(1,1,1/f).
  CameraPose pose2;
  Matrix3d K(Matrix3d::Identity());
  K(2, 2) = -0.5;
  pose2.InitializePose(R, t, K, 0.0, 0.0, 0.0, 0.0);
  ASSERT_FALSE(pose2.WorldToImage(Vector3d(10.0, 10.0, 0.0), &p_i));
  ASSERT_FALSE(pose2.WorldToImage(Vector3d(10.0, 10.0, 1.0), &p_i));
  ASSERT_TRUE(pose2.WorldToImage(Vector3d(10.0, -20.0, -1.0), &p_i));

  K(2, 2) = 0.5;
  pose2.InitializePose(R, t, K, 0.0, 0.0, 0.0, 0.0);
  ASSERT_FALSE(pose2.WorldToImage(Vector3d(10.0, 10.0, 0.0), &p_i));
  ASSERT_TRUE(pose2.WorldToImage(Vector3d(10.0, 10.0, 1.0), &p_i));
  ASSERT_FALSE(pose2.WorldToImage(Vector3d(10.0, -20.0, -1.0), &p_i));
}

TEST_F(CameraPoseTest, WorldToImageManyPointsWorks) {
  Matrix3d R(Matrix3d::Identity());
  Vector3d t(Vector3d::Zero());
  CameraPose pose;
  pose.InitializePose(R, t, calibration_matrix_, 0.0, 0.0, 0.0, 0.0);

  std::vector<Vector3d> p_world = {
    Vector3d(1.0, 1.0, 2.0), Vector3d(-5.0, 0.2, 1.0), Vector3d(1.6, -0.9, 1.2)
  };

  std::vector<Vector2d> gt_p_image = { Vector2d(-1.0 / 2.0, -1.0 / 2.0),
                                       Vector2d(5.0 / 1.0, -0.2 / 1.0),
                                       Vector2d(-1.6 / 1.2, 0.9 / 1.2) };

  std::vector<Vector2d> p_image;
  pose.WorldToImage(p_world, &p_image);
  ASSERT_EQ(p_image.size(), p_world.size());
  for (int i = 0; i < p_image.size(); i++) {
    ASSERT_DOUBLE_EQ(p_image[i].x(), gt_p_image[i].x());
    ASSERT_DOUBLE_EQ(p_image[i].y(), gt_p_image[i].y());
  }
}

TEST_F(CameraPoseTest, OneParameterUndistortImagePoint) {
  Matrix3d R(Matrix3d::Identity());
  Vector3d t(Vector3d::Zero());
  CameraPose pose;
  pose.InitializePose(R, t, calibration_matrix_, 1.0, 0.0, 0.0, 0.0);

  Vector2d p_u;
  pose.UndistortImagePoint(Vector2d(0.0, 0.0), &p_u);
  ASSERT_NEAR(0.0, p_u[0], 1e-6);
  ASSERT_NEAR(0.0, p_u[1], 1e-6);

  pose.UndistortImagePoint(Vector2d(1.0, 2.0), &p_u);
  ASSERT_NEAR(1.0 / 6.0, p_u[0], 1e-6);
  ASSERT_NEAR(2.0 / 6.0, p_u[1], 1e-6);

  pose.InitializePose(R, t, calibration_matrix_, -10.0, 0.0, 0.0, 0.0);
  pose.UndistortImagePoint(Vector2d(0.0, 0.0), &p_u);
  ASSERT_NEAR(0.0, p_u[0], 1e-6);
  ASSERT_NEAR(0.0, p_u[1], 1e-6);

  pose.UndistortImagePoint(Vector2d(5.0, 3.0), &p_u);
  ASSERT_NEAR(5.0 / (-339.0), p_u[0], 1e-6);
  ASSERT_NEAR(3.0 / (-339.0), p_u[1], 1e-6);
}

TEST_F(CameraPoseTest, OneParameterUndistortImagePointManyPoints) {
  Matrix3d R(Matrix3d::Identity());
  Vector3d t(Vector3d::Zero());
  CameraPose pose;
  pose.InitializePose(R, t, calibration_matrix_, 1.0, 0.0, 0.0, 0.0);

  std::vector<Vector2d> distorted_points = { Vector2d(0.0, 0.0),
                                             Vector2d(1.0, 2.0),
                                             Vector2d(-5.0, 3.0) };
  std::vector<Vector2d> gt_undistorted_points = {
    Vector2d(0.0, 0.0), Vector2d(1.0 / 6.0, 2.0 / 6.0),
    Vector2d(-5.0 / 35.0, 3.0 / 35.0)
  };

  std::vector<Vector2d> undistorted_points;
  pose.UndistortImagePoint(distorted_points, &undistorted_points);
  ASSERT_EQ(undistorted_points.size(), distorted_points.size());
  for (int i = 0; i < distorted_points.size(); i++) {
    ASSERT_DOUBLE_EQ(undistorted_points[i].x(), gt_undistorted_points[i].x());
    ASSERT_DOUBLE_EQ(undistorted_points[i].y(), gt_undistorted_points[i].y());
  }

  pose.InitializePose(R, t, calibration_matrix_, -2.0, 0.0, 0.0, 0.0);
  gt_undistorted_points = { Vector2d(0.0, 0.0),
                            Vector2d(1.0 / -9.0, 2.0 / -9.0),
                            Vector2d(-5.0 / -67.0, 3.0 / -67.0) };
  pose.UndistortImagePoint(distorted_points, &undistorted_points);
  ASSERT_EQ(undistorted_points.size(), distorted_points.size());
  for (int i = 0; i < distorted_points.size(); i++) {
    ASSERT_DOUBLE_EQ(undistorted_points[i].x(), gt_undistorted_points[i].x());
    ASSERT_DOUBLE_EQ(undistorted_points[i].y(), gt_undistorted_points[i].y());
  }
}

TEST_F(CameraPoseTest, FourParameterUndistortImagePoint) {
  Matrix3d R(Matrix3d::Identity());
  Vector3d t(Vector3d::Zero());
  CameraPose pose;
  pose.InitializePose(R, t, calibration_matrix_, 1.0, 0.0, 0.0, 1.0);

  Vector2d p_u;
  pose.UndistortImagePoint(Vector2d(0.0, 0.0), &p_u);
  ASSERT_NEAR(0.0, p_u[0], 1e-6);
  ASSERT_NEAR(0.0, p_u[1], 1e-6);

  pose.UndistortImagePoint(Vector2d(1.0, 2.0), &p_u);
  ASSERT_NEAR(1.0 / 631.0, p_u[0], 1e-6);
  ASSERT_NEAR(2.0 / 631.0, p_u[1], 1e-6);

  pose.InitializePose(R, t, calibration_matrix_, -10.0, 0.2, 0.03, -0.001);
  pose.UndistortImagePoint(Vector2d(0.0, 0.0), &p_u);
  ASSERT_NEAR(0.0, p_u[0], 1e-6);
  ASSERT_NEAR(0.0, p_u[1], 1e-6);

  pose.UndistortImagePoint(Vector2d(5.0, 3.0), &p_u);
  ASSERT_NEAR(5.0 / (-265.016), p_u[0], 1e-6);
  ASSERT_NEAR(3.0 / (-265.016), p_u[1], 1e-6);
}

TEST_F(CameraPoseTest, FourParameterUndistortImagePointManyPoints) {
  Matrix3d R(Matrix3d::Identity());
  Vector3d t(Vector3d::Zero());
  CameraPose pose;
  pose.InitializePose(R, t, calibration_matrix_, 1.0, 0.0, 0.0, 0.1);

  std::vector<Vector2d> distorted_points = { Vector2d(0.0, 0.0),
                                             Vector2d(1.0, 2.0),
                                             Vector2d(-5.0, 3.0) };
  std::vector<Vector2d> gt_undistorted_points(distorted_points.size());
  for (int i = 0; i < distorted_points.size(); i++) {
    pose.UndistortImagePoint(distorted_points[i], &(gt_undistorted_points[i]));
  }

  std::vector<Vector2d> undistorted_points;
  pose.UndistortImagePoint(distorted_points, &undistorted_points);
  ASSERT_EQ(undistorted_points.size(), distorted_points.size());
  for (int i = 0; i < distorted_points.size(); i++) {
    ASSERT_DOUBLE_EQ(undistorted_points[i].x(), gt_undistorted_points[i].x());
    ASSERT_DOUBLE_EQ(undistorted_points[i].y(), gt_undistorted_points[i].y());
  }

  pose.InitializePose(R, t, calibration_matrix_, -2.0, 1.07, 0.03, 0.004);
  for (int i = 0; i < distorted_points.size(); i++) {
    pose.UndistortImagePoint(distorted_points[i], &(gt_undistorted_points[i]));
  }

  pose.UndistortImagePoint(distorted_points, &undistorted_points);
  ASSERT_EQ(undistorted_points.size(), distorted_points.size());
  for (int i = 0; i < distorted_points.size(); i++) {
    ASSERT_DOUBLE_EQ(undistorted_points[i].x(), gt_undistorted_points[i].x());
    ASSERT_DOUBLE_EQ(undistorted_points[i].y(), gt_undistorted_points[i].y());
  }
}

}  // namespace

}  // namespace theia

max_stars_repo_name: nuernber/Theia

max_issues_repo_name: nuernber/Theia

max_forks_repo_name: nuernber/Theia


text:
//
// ts/internet.hpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2022 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_TS_INTERNET_HPP
#define BOOST_ASIO_TS_INTERNET_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/address_v4.hpp>
#include <boost/asio/ip/address_v4_iterator.hpp>
#include <boost/asio/ip/address_v4_range.hpp>
#include <boost/asio/ip/address_v6.hpp>
#include <boost/asio/ip/address_v6_iterator.hpp>
#include <boost/asio/ip/address_v6_range.hpp>
#include <boost/asio/ip/bad_address_cast.hpp>
#include <boost/asio/ip/basic_endpoint.hpp>
#include <boost/asio/ip/basic_resolver_query.hpp>
#include <boost/asio/ip/basic_resolver_entry.hpp>
#include <boost/asio/ip/basic_resolver_iterator.hpp>
#include <boost/asio/ip/basic_resolver.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/ip/network_v4.hpp>
#include <boost/asio/ip/network_v6.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ip/udp.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/asio/ip/unicast.hpp>
#include <boost/asio/ip/multicast.hpp>

#endif // BOOST_ASIO_TS_INTERNET_HPP

ext: hpp


text:
#include <boost/test/unit_test.hpp>

#include "LRWBSubwordGraph.hh"

using namespace std;

string lrwb_amname = string("data/speecon_ml_gain3500_occ300_21.7.2011_22");
set<string> lrwb_prefix_subwords;
set<string> lrwb_stem_subwords;
set<string> lrwb_suffix_subwords;
set<string> lrwb_word_subwords;

namespace LRWBGraphTestUtils {
void read_fixtures(LRWBSubwordGraph &swg, string lexfname) {
    swg.read_phone_model(lrwb_amname + ".ph");
    swg.read_lexicon(lexfname,
                     lrwb_prefix_subwords,
                     lrwb_stem_subwords,
                     lrwb_suffix_subwords,
                     lrwb_word_subwords);
}

void word_subwords(const set<string> &word_subwords,
                   map<string, vector<string> > &word_segs) {
    for (auto wswit = word_subwords.begin(); wswit != word_subwords.end(); ++wswit)
        word_segs[*wswit] = { *wswit };
}

void pre_suf_words(
    const set<string> &prefix_subwords,
    const set<string> &suffix_subwords,
    map<string, vector<string> > &word_segs,
    int maxWords = 10000)
{
    int wc = 0;
    for (auto prefit = prefix_subwords.begin(); prefit != prefix_subwords.end(); ++prefit) {
        for (auto sufit = suffix_subwords.begin(); sufit != suffix_subwords.end(); ++sufit) {
            vector<string> word_seg;
            word_seg.push_back(*prefit);
            word_seg.push_back(*sufit);
            string wrd = *prefit + *sufit;
            word_segs[wrd] = word_seg;
            if (++wc > maxWords) return;
        }
    }
}

void pre_stem_suf_words(
    const set<string> &prefix_subwords,
    const set<string> &stem_subwords,
    const set<string> &suffix_subwords,
    map<string, vector<string> > &word_segs,
    int maxWords = 10000)
{
    int wc = 0;
    for (auto prefit = prefix_subwords.begin(); prefit != prefix_subwords.end(); ++prefit) {
        for (auto stemit = stem_subwords.begin(); stemit != stem_subwords.end(); ++stemit) {
            for (auto sufit = suffix_subwords.begin(); sufit != suffix_subwords.end(); ++sufit) {
                vector<string> word_seg;
                word_seg.push_back(*prefit);
                word_seg.push_back(*stemit);
                word_seg.push_back(*sufit);
                string wrd = *prefit + *stemit + *sufit;
                word_segs[wrd] = word_seg;
                if (++wc > maxWords) return;
            }
        }
    }
}

void pre_stem_stem_suf_words(
    const set<string> &prefix_subwords,
    const set<string> &stem_subwords,
    const set<string> &suffix_subwords,
    map<string, vector<string> > &word_segs,
    int maxWords = 10000)
{
    int wc = 0;
    for (auto prefit = prefix_subwords.begin(); prefit != prefix_subwords.end(); ++prefit) {
        for (auto stemit = stem_subwords.begin(); stemit != stem_subwords.end(); ++stemit) {
            for (auto stemit2 = stem_subwords.begin(); stemit2 != stem_subwords.end(); ++stemit2) {
                for (auto sufit = suffix_subwords.begin(); sufit != suffix_subwords.end(); ++sufit) {
                    vector<string> word_seg;
                    word_seg.push_back(*prefit);
                    word_seg.push_back(*stemit);
                    word_seg.push_back(*stemit2);
                    word_seg.push_back(*sufit);
                    string wrd = *prefit + *stemit + *stemit2 + *sufit;
                    word_segs[wrd] = word_seg;
                    if (++wc > maxWords) return;
                }
            }
        }
    }
}
};

// Only complete word subwords
BOOST_AUTO_TEST_CASE(LRWBSubwordGraphTest1)
{
    LRWBSubwordGraph swg;
    LRWBGraphTestUtils::read_fixtures(swg, "data/lrwb_1.lex");

    swg.create_graph(lrwb_prefix_subwords,
                     lrwb_stem_subwords,
                     lrwb_suffix_subwords,
                     lrwb_word_subwords);

    BOOST_CHECK( swg.assert_words(lrwb_word_subwords) );
    BOOST_CHECK( swg.assert_only_words(lrwb_word_subwords) );
    BOOST_CHECK( swg.assert_word_pairs(lrwb_word_subwords, true, false) ); //short sil, wb symbol
}

// Prefix, suffix and complete word subwords
// No stems or one phone subwords
BOOST_AUTO_TEST_CASE(LRWBSubwordGraphTest2)
{
    cerr << endl;
    LRWBSubwordGraph swg;
    LRWBGraphTestUtils::read_fixtures(swg, "data/lrwb_2.lex");

    swg.create_graph(lrwb_prefix_subwords,
                     lrwb_stem_subwords,
                     lrwb_suffix_subwords,
                     lrwb_word_subwords);

    map<string, vector<string> > testWords;
    LRWBGraphTestUtils::word_subwords(lrwb_word_subwords, testWords);
    LRWBGraphTestUtils::pre_suf_words(lrwb_prefix_subwords,
                                      lrwb_suffix_subwords,
                                      testWords);
    cerr << "Number of words to verify: " << testWords.size() << endl;
    BOOST_CHECK( swg.assert_words(testWords) );
    BOOST_CHECK( swg.assert_word_pairs(testWords, true, false) ); //short sil, wb symbol
}

// All subword types
// No one phone subwords
BOOST_AUTO_TEST_CASE(LRWBSubwordGraphTest3)
{
    cerr << endl;
    LRWBSubwordGraph swg;
    LRWBGraphTestUtils::read_fixtures(swg, "data/lrwb_3.lex");

    swg.create_graph(lrwb_prefix_subwords,
                     lrwb_stem_subwords,
                     lrwb_suffix_subwords,
                     lrwb_word_subwords);

    map<string, vector<string> > testWords;
    LRWBGraphTestUtils::word_subwords(lrwb_word_subwords, testWords);
    LRWBGraphTestUtils::pre_suf_words(lrwb_prefix_subwords,
                                      lrwb_suffix_subwords,
                                      testWords);
    LRWBGraphTestUtils::pre_stem_suf_words(lrwb_prefix_subwords,
                                           lrwb_stem_subwords,
                                           lrwb_suffix_subwords,
                                           testWords);
    cerr << "Number of words to verify: " << testWords.size() << endl;
    BOOST_CHECK( swg.assert_words(testWords) );
    BOOST_CHECK( swg.assert_word_pairs(testWords, true, false) ); //short sil, wb symbol
}

// All subword types
// One phone stem subword
BOOST_AUTO_TEST_CASE(LRWBSubwordGraphTest4)
{
    cerr << endl;
    LRWBSubwordGraph swg;
    LRWBGraphTestUtils::read_fixtures(swg, "data/lrwb_4.lex");

    swg.create_graph(lrwb_prefix_subwords,
                     lrwb_stem_subwords,
                     lrwb_suffix_subwords,
                     lrwb_word_subwords);

    map<string, vector<string> > testWords;
    LRWBGraphTestUtils::word_subwords(lrwb_word_subwords, testWords);
    LRWBGraphTestUtils::pre_suf_words(lrwb_prefix_subwords,
                                      lrwb_suffix_subwords,
                                      testWords);
    LRWBGraphTestUtils::pre_stem_suf_words(lrwb_prefix_subwords,
                                           lrwb_stem_subwords,
                                           lrwb_suffix_subwords,
                                           testWords);
    cerr << "Number of words to verify: " << testWords.size() << endl;
    BOOST_CHECK( swg.assert_words(testWords) );
    BOOST_CHECK( swg.assert_word_pairs(testWords, true, false) ); //short sil, wb symbol
}

// All subword types
// One phone prefix, stem and suffix subwords
BOOST_AUTO_TEST_CASE(LRWBSubwordGraphTest5)
{
    cerr << endl;
    LRWBSubwordGraph swg;
    LRWBGraphTestUtils::read_fixtures(swg, "data/lrwb_5.lex");

    swg.create_graph(lrwb_prefix_subwords,
                     lrwb_stem_subwords,
                     lrwb_suffix_subwords,
                     lrwb_word_subwords);

    map<string, vector<string> > testWords;
    LRWBGraphTestUtils::word_subwords(lrwb_word_subwords, testWords);
    LRWBGraphTestUtils::pre_suf_words(lrwb_prefix_subwords,
                                      lrwb_suffix_subwords,
                                      testWords);
    LRWBGraphTestUtils::pre_stem_suf_words(lrwb_prefix_subwords,
                                           lrwb_stem_subwords,
                                           lrwb_suffix_subwords,
                                           testWords);
    cerr << "Number of words to verify: " << testWords.size() << endl;
    BOOST_CHECK( swg.assert_words(testWords) );
    BOOST_CHECK( swg.assert_word_pairs(testWords, true, false) ); //short sil, wb symbol
}

// All subword types
// One phone prefix, stem and suffix subwords
// Test multiple stems for the test words
BOOST_AUTO_TEST_CASE(LRWBSubwordGraphTest5b)
{
    cerr << endl;
    LRWBSubwordGraph swg;
    LRWBGraphTestUtils::read_fixtures(swg, "data/lrwb_5.lex");

    swg.create_graph(lrwb_prefix_subwords,
                     lrwb_stem_subwords,
                     lrwb_suffix_subwords,
                     lrwb_word_subwords);

    map<string, vector<string> > testWords;
    LRWBGraphTestUtils::word_subwords(lrwb_word_subwords, testWords);
    LRWBGraphTestUtils::pre_suf_words(
        lrwb_prefix_subwords,
        lrwb_suffix_subwords,
        testWords);
    LRWBGraphTestUtils::pre_stem_suf_words(
        lrwb_prefix_subwords,
        lrwb_stem_subwords,
        lrwb_suffix_subwords,
        testWords);
    LRWBGraphTestUtils::pre_stem_stem_suf_words(
        lrwb_prefix_subwords,
        lrwb_stem_subwords,
        lrwb_suffix_subwords,
        testWords);
    cerr << "Number of words to verify: " << testWords.size() << endl;
    BOOST_CHECK( swg.assert_words(testWords) );
    BOOST_CHECK( swg.assert_word_pairs(testWords, 10000, true, false) ); //short sil, wb symbol
}

// Larger normal subword lexicon
BOOST_AUTO_TEST_CASE(LRWBSubwordGraphTest6)
{
    cerr << endl;
    LRWBSubwordGraph swg;
    LRWBGraphTestUtils::read_fixtures(swg, "data/lrwb_1k.lex");

    cerr << "creating graph" << endl;
    swg.create_graph(lrwb_prefix_subwords,
                     lrwb_stem_subwords,
                     lrwb_suffix_subwords,
                     lrwb_word_subwords,
                     true);

    map<string, vector<string> > testWords;
    LRWBGraphTestUtils::word_subwords(lrwb_word_subwords, testWords);
    LRWBGraphTestUtils::pre_suf_words(
        lrwb_prefix_subwords,
        lrwb_suffix_subwords,
        testWords,
        1000);
    LRWBGraphTestUtils::pre_stem_suf_words(
        lrwb_prefix_subwords,
        lrwb_stem_subwords,
        lrwb_suffix_subwords,
        testWords,
        2000);
    LRWBGraphTestUtils::pre_stem_stem_suf_words(
        lrwb_prefix_subwords,
        lrwb_stem_subwords,
        lrwb_suffix_subwords,
        testWords,
        2000);
    cerr << "Number of words to verify: " << testWords.size() << endl;
    BOOST_CHECK( swg.assert_words(testWords) );
    BOOST_CHECK( swg.assert_word_pairs(testWords, 5000, true, false) ); //short sil, wb symbol
}

// Problem case if the other cross-word network not constructed
/*
BOOST_AUTO_TEST_CASE(LRWBSubwordGraphTest6)
{
    cerr << endl;
    LRWBSubwordGraph swg;
    LRWBGraphTestUtils::read_fixtures(swg, "data/lrwb_6.lex");

    swg.create_graph(lrwb_prefix_subwords,
                     lrwb_stem_subwords,
                     lrwb_suffix_subwords,
                     lrwb_word_subwords);

    map<string, vector<string> > testWords;
    LRWBGraphTestUtils::word_subwords(lrwb_word_subwords, testWords);
    LRWBGraphTestUtils::pre_suf_words(lrwb_prefix_subwords,
                                      lrwb_suffix_subwords,
                                      testWords);
    LRWBGraphTestUtils::pre_stem_suf_words(lrwb_prefix_subwords,
                                           lrwb_stem_subwords,
                                           lrwb_suffix_subwords,
                                           testWords);
    cerr << "Number of words to verify: " << testWords.size() << endl;
    BOOST_CHECK( swg.assert_words(testWords) );
    BOOST_CHECK( swg.assert_word_pairs(testWords, true, false) ); //short sil, wb symbol
}
*/

//ofstream origoutf("acw.dot");
//swg.print_dot_digraph(swg.m_nodes, origoutf, true);
//origoutf.close();

ext: cc

max_stars_repo_name: aalto-speech/wdecoder

max_issues_repo_name: aalto-speech/wdecoder

max_forks_repo_name: aalto-speech/wdecoder


text:
#pragma once

#include <string>
#include <set>
#include <map>
#include <memory>
#include <ostream>

#include <boost/property_tree/ptree_fwd.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

#include <orwell/game/RGBColour.hpp>
#include <orwell/game/Coordinates.hpp>

namespace orwell
{
namespace game
{
class Team;
class Ruleset;

class Landmark
{
public:
	Landmark(
		Coordinates const & iPosition,
		RGBColour const & iColour);

	virtual ~Landmark();

	Coordinates const & getPosition() const;

	RGBColour const & getColour() const;

	bool operator==(orwell::game::Landmark const & iOther) const;

	static Landmark ParseConfig(
			std::string const & iMapLimitName,
			boost::property_tree::ptree const & iPtree);

private:
	Coordinates m_position;
	RGBColour m_colour;
};

} // game
} // orwell

std::ostream & operator<<(
		std::ostream & ioOstream,
		orwell::game::Landmark const & iLandmark);

max_stars_repo_name: orwell-int/server-game

max_issues_repo_name: orwell-int/server-game

max_forks_repo_name: orwell-int/server-game


text:
#include <Eigen/Dense>
#include <VirtualRobot/MathTools.h>
#include <VirtualRobot/Nodes/ForceTorqueSensor.h>
#include <SimDynamics/SimDynamics.h>

#include <boost/assert.hpp>
#include <boost/make_shared.hpp>

#include "uxabiped/stabilizer/CartesianStabilizer.h"
#include "uxabiped/utils/Kinematics.h"

#include "uxabiped/controller/PostureController.h"

namespace Bipedal
{

/**
 * These controller needs a trajectory with the following control features:
 *
 * Poses:
 *  - chest pose
 *  - pelvis pose
 *  - left foot pose
 *  - right foot pose
 *
 * Values:
 *  - support phase
 *
 */
CartesianStabilizer::CartesianStabilizer(const VirtualRobot::RobotPtr& robot,
                                         const VirtualRobot::RobotNodePtr& chest,
                                         const VirtualRobot::RobotNodePtr& leftFoot,
                                         const VirtualRobot::RobotNodePtr& rightFoot,
                                         const VirtualRobot::RobotNodePtr& pelvis)
: chest(chest)
, leftFoot(leftFoot)
, rightFoot(rightFoot)
, pelvis(pelvis)
, chestPostureController(new ThreeDOFPostureController(8, 12, 8, 12, 8, 12))
, leftFootPostureController(new ThreeDOFPostureController(10, 17, 15, 30, 20, 20))
, rightFootPostureController(new ThreeDOFPostureController(10, 17, 15, 30, 20, 20))
, pelvisPostureController(new ThreeDOFPostureController(8, 12, 8, 12, 8, 12))
, chestPose(Eigen::Matrix4f::Identity())
, pelvisPose(Eigen::Matrix4f::Identity())
, leftFootPose(Eigen::Matrix4f::Identity())
, rightFootPose(Eigen::Matrix4f::Identity())
, chestPoseRef(Eigen::Matrix4f::Identity())
, pelvisPoseRef(Eigen::Matrix4f::Identity())
, leftFootPoseRef(Eigen::Matrix4f::Identity())
, rightFootPoseRef(Eigen::Matrix4f::Identity())
, rootPose(Eigen::Matrix4f::Identity())
, comPosition(Eigen::Vector3f::Zero())
, zmpPosition(Eigen::Vector3f::Zero())
, comPositionRef(Eigen::Vector3f::Zero())
, zmpPositionRef(Eigen::Vector3f::Zero())
{
}

void CartesianStabilizer::update(float dt,
                                 const Eigen::Vector3f& comActualWorld,
                                 const Eigen::Vector3f& comVelocityActualWorld,
                                 const Eigen::Vector3f& zmpActualWorld,
                                 Bipedal::SupportPhase phase,
                                 const Eigen::Matrix4f& chestPoseRefWorld,
                                 const Eigen::Matrix4f& pelvisPoseRefWorld,
                                 const Eigen::Matrix4f& leftFootPoseRefWorld,
                                 const Eigen::Matrix4f& rightFootPoseRefWorld,
                                 const Eigen::Vector3f& comRefGroundFrame,
                                 const Eigen::Vector3f& comVelocityRefGroundFrame,
                                 const Eigen::Vector3f& zmpRefGroundFrame)
{
    chestPoseRef     = chestPoseRefWorld;
    pelvisPoseRef    = pelvisPoseRefWorld;
    leftFootPoseRef  = leftFootPoseRefWorld;
    rightFootPoseRef = rightFootPoseRefWorld;

    // Reference coordinate system for orientations is the ground frame
    // not the global frame
    // Note: We don't care about positions here, only the orientation part is used
    Eigen::Matrix4f worldToRefGF = computeGroundFrame(leftFootPoseRef, rightFootPoseRef, phase).inverse();
    Eigen::Matrix4f worldToGF = computeGroundFrame(leftFoot->getGlobalPose(), rightFoot->getGlobalPose(), phase).inverse();

    pelvisPose = pelvisPoseRef * pelvisPostureController->correctPosture(
        worldToRefGF * pelvisPoseRef,
        worldToGF * pelvis->getGlobalPose()
    );

    chestPose = chestPoseRef * chestPostureController->correctPosture(
        worldToRefGF * chestPoseRef,
        worldToGF * chest->getGlobalPose()
    );

    Eigen::Matrix4f leftCorrection = leftFootPostureController->correctPosture(
        worldToRefGF * leftFootPoseRef,
        worldToGF * leftFoot->getGlobalPose()
    );
    Eigen::Matrix4f rightCorrection = rightFootPostureController->correctPosture(
        worldToRefGF * rightFootPoseRef,
        worldToGF * rightFoot->getGlobalPose()
    );

    leftFootPose = leftFootPoseRef * leftCorrection;
    rightFootPose = rightFootPoseRef * rightCorrection;

    comPositionRef = comRefGroundFrame;
    zmpPositionRef = zmpRefGroundFrame;
    comPosition   = comPositionRef;
    zmpPosition   = zmpPositionRef;
}

std::unordered_map<std::string, DampeningController*> CartesianStabilizer::getControllers()
{
    std::unordered_map<std::string, DampeningController*> controllers;

    controllers["Chest_Roll"]     = &chestPostureController->phiDC;
    controllers["Chest_Pitch"]    = &chestPostureController->thetaDC;
    controllers["Chest_Yaw"]    = &chestPostureController->gammaDC;
    controllers["LeftFoot_Roll"]  = &leftFootPostureController->phiDC;
    controllers["LeftFoot_Pitch"] = &leftFootPostureController->thetaDC;
    controllers["LeftFoot_Yaw"] = &leftFootPostureController->gammaDC;
    controllers["RightFoot_Roll"]  = &rightFootPostureController->phiDC;
    controllers["RightFoot_Pitch"] = &rightFootPostureController->thetaDC;
    controllers["RightFoot_Yaw"] = &rightFootPostureController->gammaDC;
    controllers["Pelvis_Roll"]  = &pelvisPostureController->phiDC;
    controllers["Pelvis_Pitch"] = &pelvisPostureController->thetaDC;
    controllers["Pelvis_Yaw"] = &pelvisPostureController->gammaDC;

    return controllers;
}

}

ext: cpp

max_stars_repo_name: nvtienanh/UXAProject

max_issues_repo_name: nvtienanh/UXAProject

max_forks_repo_name: nvtienanh/UXAProject


text:
#include "StdInc.h"

#include <ResourceManager.h>
#include <ResourceEventComponent.h>
#include <ResourceMetaDataComponent.h>
#include <ResourceManagerConstraintsComponent.h>

#include <fxScripting.h>

#include <ServerInstanceBase.h>
#include <ServerInstanceBaseRef.h>

#include <GameServer.h>
#include <ServerEventComponent.h>

#include <GameBuilds.h>

#include <RelativeDevice.h>

#include <VFSManager.h>

#include <skyr/url.hpp>
#include <skyr/percent_encode.hpp>

#include <PrintListener.h>

#include <ResourceStreamComponent.h>
#include <EventReassemblyComponent.h>

#include <KeyedRateLimiter.h>

#include <StructuredTrace.h>

#include <filesystem>

#include <ScriptEngine.h>

#include <ManifestVersion.h>
#include <cfx_version.h>

#include <boost/algorithm/string.hpp>

// a set of resources that are system-managed and should not be stopped from script
static std::set<std::string> g_managedResources = {
	"spawnmanager",
	"mapmanager",
	"baseevents",
	"chat",
	"sessionmanager",
	"webadmin",
	"monitor"
};

class LocalResourceMounter : public fx::ResourceMounter
{
public:
	LocalResourceMounter(fx::ResourceManager* manager)
		: m_manager(manager)
	{

	}

	virtual bool HandlesScheme(const std::string& scheme) override
	{
		return (scheme == "file");
	}

	virtual pplx::task<fwRefContainer<fx::Resource>> LoadResource(const std::string& uri) override
	{
		auto uriParsed = skyr::make_url(uri);

		fwRefContainer<fx::Resource> resource;

		if (uriParsed)
		{
			auto pathRef = uriParsed->pathname();
			auto fragRef = uriParsed->hash().substr(1);

			if (!pathRef.empty() && !fragRef.empty())
			{
#ifdef _WIN32
				std::string pr = pathRef.substr(1);
#else
				std::string pr = pathRef;
#endif

				resource = m_manager->CreateResource(fragRef, this);
				if (!resource->LoadFrom(*skyr::percent_decode(pr)))
				{
					m_manager->RemoveResource(resource);
					resource = nullptr;
				}
			}
		}

		return pplx::task_from_result<fwRefContainer<fx::Resource>>(resource);
	}

private:
	fx::ResourceManager* m_manager;
};

static void HandleServerEvent(fx::ServerInstanceBase* instance, const fx::ClientSharedPtr& client, net::Buffer& buffer)
{
	uint16_t eventNameLength = buffer.Read<uint16_t>();

	// validate input
	if (eventNameLength <= 0 || eventNameLength > std::numeric_limits<uint16_t>::max())
	{
		return;
	}

	static fx::RateLimiterStore<uint32_t, false> netEventRateLimiterStore{ instance->GetComponent<console::Context>().GetRef() };
	static auto netEventRateLimiter = netEventRateLimiterStore.GetRateLimiter("netEvent", fx::RateLimiterDefaults{ 50.f, 200.f });
	static auto netFloodRateLimiter = netEventRateLimiterStore.GetRateLimiter("netEventFlood", fx::RateLimiterDefaults{ 75.f, 300.f });
	static auto netEventSizeRateLimiter = netEventRateLimiterStore.GetRateLimiter("netEventSize", fx::RateLimiterDefaults{ 128 * 1024.0, 384 * 1024.0 });

	uint32_t netId = client->GetNetId();

	if (!netEventRateLimiter->Consume(netId))
	{
		if (!netFloodRateLimiter->Consume(netId))
		{
			gscomms_execute_callback_on_main_thread([client, instance]()
			{
				instance->GetComponent<fx::GameServer>()->DropClient(client, "Reliable network event overflow.");
			});
		}

		return;
	}

	std::vector<char> eventNameBuffer(eventNameLength - 1);
	buffer.Read(eventNameBuffer.data(), eventNameBuffer.size());
	buffer.Read<uint8_t>();

	uint32_t dataLength = buffer.GetRemainingBytes();

	if (!netEventSizeRateLimiter->Consume(netId, double(dataLength)))
	{
		std::string eventName(eventNameBuffer.begin(), eventNameBuffer.end());
		gscomms_execute_callback_on_main_thread([client, instance, eventName]()
		{
			// if this happens, try increasing rateLimiter_netEventSize_rate and rateLimiter_netEventSize_burst
			// preferably, fix client scripts to not have this large a set of events with high frequency
			instance->GetComponent<fx::GameServer>()->DropClient(client, "Reliable network event size overflow: %s", eventName);
		});

		return;
	}

	std::vector<uint8_t> data(dataLength);
	buffer.Read(data.data(), data.size());

	fwRefContainer<fx::ResourceManager> resourceManager = instance->GetComponent<fx::ResourceManager>();
	fwRefContainer<fx::ResourceEventManagerComponent> eventManager = resourceManager->GetComponent<fx::ResourceEventManagerComponent>();

	eventManager->QueueEvent(
		std::string(eventNameBuffer.begin(), eventNameBuffer.end()),
		std::string(data.begin(), data.end()),
		fmt::sprintf("net:%d", netId)
	);
}

static std::shared_ptr<ConVar<std::string>> g_citizenDir;
static std::map<std::string, std::set<std::string>> g_resourcesByComponent;

static void ScanResources(fx::ServerInstanceBase* instance)
{
	// mapping of names to paths
	static std::map<std::string, std::string> scanData;

	auto resMan = instance->GetComponent<fx::ResourceManager>();

	std::string resourceRoot(instance->GetRootPath() + "/resources/");
	std::string systemResourceRoot(g_citizenDir->GetValue() + "/system_resources/");

	auto resourceRootPath = std::filesystem::u8path(resourceRoot).lexically_normal();
	auto systemResourceRootPath = std::filesystem::u8path(systemResourceRoot).lexically_normal();

	std::queue<std::string> pathsToIterate;
	pathsToIterate.push(systemResourceRoot);
	pathsToIterate.push(resourceRoot);

	std::vector<pplx::task<fwRefContainer<fx::Resource>>> tasks;

	// save scanned resource names so we don't scan them twice
	std::set<std::string> scannedNow;
	std::set<std::string> updatedNow;
	size_t newResources = 0;
	size_t updatedResources = 0;
	size_t reloadedResources = 0;

	trace("^2Scanning resources.^7\n", newResources);

	while (!pathsToIterate.empty())
	{
		std::string thisPath = pathsToIterate.front();
		pathsToIterate.pop();

		auto vfsDevice = vfs::GetDevice(thisPath);

		vfs::FindData findData;
		auto handle = vfsDevice->FindFirst(thisPath, &findData);

		if (handle != INVALID_DEVICE_HANDLE)
		{
			do
			{
				if (findData.name == "." || findData.name == "..")
				{
					continue;
				}

				// TODO(fxserver): non-win32
				if (findData.attributes & FILE_ATTRIBUTE_DIRECTORY)
				{
					std::string resPath(thisPath + "/" + findData.name);

					// is this a category?
					if (findData.name[0] == '[' && findData.name[findData.name.size() - 1] == ']')
					{
						pathsToIterate.push(resPath);
					}
					// it's a resource
					else if (scannedNow.find(findData.name) == scannedNow.end())
					{
						const auto& resourceName = findData.name;
						scannedNow.insert(resourceName);

						auto oldRes = resMan->GetResource(resourceName, false);
						auto oldScanData = scanData.find(resourceName);

						// did the path change? if so, unload the old resource
						if (oldRes.GetRef() && oldScanData != scanData.end() && oldScanData->second != resPath)
						{
							// remove from by-component lists
							for (auto& list : g_resourcesByComponent)
							{
								list.second.erase(resourceName);
							}

							// unmount relative device
							vfs::Unmount(fmt::sprintf("@%s/", resourceName));

							// stop and remove resource
							oldRes->Stop();
							resMan->RemoveResource(oldRes);

							// undo ptr
							oldRes = {};
						}

						if (oldRes.GetRef())
						{
							auto metaDataComponent = oldRes->GetComponent<fx::ResourceMetaDataComponent>();

							// filter function to remove _extra entries (Lua table ordering determinism)
							auto filterMetadata = [](auto&& metadataIn)
							{
								for (auto it = metadataIn.begin(); it != metadataIn.end(); )
								{
									if (boost::algorithm::ends_with(it->first, "_extra"))
									{
										it = metadataIn.erase(it);
									}
									else
									{
										++it;
									}
								}

								return std::move(metadataIn);
							};

							// save the old metadata for comparison
							auto oldMetaData = filterMetadata(metaDataComponent->GetAllEntries());

							// load new metadata
							metaDataComponent->LoadMetaData(resPath);

							// compare differences
							auto newMetaData = filterMetadata(metaDataComponent->GetAllEntries());
							bool different = (newMetaData.size() != oldMetaData.size()) || (newMetaData != oldMetaData);

							// if different, track as updated
							if (different)
							{
								updatedNow.insert(resourceName);
								updatedResources++;
							}

							// track resource as reloaded
							reloadedResources++;
						}
						else
						{
							console::DPrintf("resources", "Found new resource %s in %s\n", resourceName, resPath);
							newResources++;
							updatedNow.insert(resourceName);

							auto path = std::filesystem::u8path(resPath);

							// determine which root we're relative to
							std::error_code ec;
							auto refPath = path.lexically_normal();

							std::filesystem::path* rootRef = nullptr;

							auto [relEnd, _] = std::mismatch(resourceRootPath.begin(), resourceRootPath.end(), refPath.begin());
							auto rpEnd = --resourceRootPath.end();

							if (relEnd != rpEnd)
							{
								auto [relEnd, _] = std::mismatch(systemResourceRootPath.begin(), systemResourceRootPath.end(), refPath.begin());
								auto rpEnd = --systemResourceRootPath.end();

								if (relEnd == rpEnd)
								{
									rootRef = &systemResourceRootPath;
								}
							}
							else
							{
								rootRef = &resourceRootPath;
							}

							// get the relative path to the root
							std::vector<std::string> components;

							if (rootRef)
							{
								auto relPath = std::filesystem::relative(path, *rootRef, ec);

								if (!ec)
								{
									for (const auto& component : relPath)
									{
										auto name = component.filename().u8string();

										if (name[0] == '[' && name[name.size() - 1] == ']')
										{
											components.push_back(name);
										}
									}
								}
							}

							// mount the resource for later use in VFS (e.g. from `exec`)
							fwRefContainer<vfs::RelativeDevice> relativeDevice = new vfs::RelativeDevice(resPath + "/");
							vfs::Mount(relativeDevice, fmt::sprintf("@%s/", resourceName));
							scanData[resourceName] = resPath;

							skyr::url_record record;
							record.scheme = "file";

							skyr::url url{ std::move(record) };
							url.set_pathname(*skyr::percent_encode(resPath, skyr::encode_set::path));
							url.set_hash(*skyr::percent_encode(resourceName, skyr::encode_set::fragment));

							auto task = resMan->AddResource(url.href())
										.then([components = std::move(components)](fwRefContainer<fx::Resource> resource)
										{
											if (resource.GetRef())
											{
												for (const auto& component : components)
												{
													g_resourcesByComponent[component].insert(resource->GetName());
												}
											}

											return resource;
										});

							tasks.push_back(task);
						}
					}
				}
			} while (vfsDevice->FindNext(handle, &findData));

			vfsDevice->FindClose(handle);
		}
	}

	pplx::when_all(tasks.begin(), tasks.end()).wait();

	if (reloadedResources > 0)
	{
		trace("^2Found %d new resources, and refreshed %d/%d resources.^7\n", newResources, updatedResources, reloadedResources);
	}
	else
	{
		trace("^2Found %d resources.^7\n", newResources);
	}

	auto trl = instance->GetComponent<fx::TokenRateLimiter>();
	trl->Update(1.0, std::max(double(newResources + reloadedResources), 3.0));

	// check for outdated
	std::set<std::string> nonManifestResources;

	resMan->ForAllResources([&updatedNow, &nonManifestResources](const fwRefContainer<fx::Resource>& resource)
	{
		auto md = resource->GetComponent<fx::ResourceMetaDataComponent>();

		auto fxV2 = md->IsManifestVersionBetween("adamant", "");
		auto fxV1 = md->IsManifestVersionBetween(ManifestVersion{ "44febabe-d386-4d18-afbe-5e627f4af937" }.guid, guid_t{ 0 });

		if (!fxV2 || !*fxV2)
		{
			if (!fxV1 || !*fxV1)
			{
				if (!md->GlobEntriesVector("client_script").empty())
				{
					auto resourceName = resource->GetName();

					// only alert if a resource updated this iteration
					if (updatedNow.find(resourceName) != updatedNow.end())
					{
						nonManifestResources.insert(resourceName);
					}
				}
			}
		}
	});

	if (!nonManifestResources.empty())
	{
		trace("^1Some resources have an outdated resource manifest:^7\n");

		for (auto& name : nonManifestResources)
		{
			trace("    - %s\n", name);
		}

		trace("\nPlease update these resources.\n");
	}

	/*NETEV onResourceListRefresh SERVER
	/#*
	 * A server-side event triggered when the `refresh` command completes.
	 #/
	declare function onResourceListRefresh(): void;
	*/
	instance
		->GetComponent<fx::ResourceManager>()
		->GetComponent<fx::ResourceEventManagerComponent>()
		->TriggerEvent2("onResourceListRefresh", {});
}

static class : public fx::EventReassemblySink
{
public:
	virtual void SendPacket(int target, std::string_view packet) override
	{
		auto client = instance->GetComponent<fx::ClientRegistry>()->GetClientByNetID(target);

		if (client)
		{
			net::Buffer outPacket;
			outPacket.Write(HashRageString("msgReassembledEvent"));
			outPacket.Write(packet.data(), packet.size());

			client->SendPacket(1, outPacket);
		}
	}

	virtual bool LimitEvent(int source) override
	{
		static fx::RateLimiterStore<uint32_t, false> netEventRateLimiterStore{ instance->GetComponent<console::Context>().GetRef() };
		static auto netEventRateLimiter = netEventRateLimiterStore.GetRateLimiter("netEvent", fx::RateLimiterDefaults{ 50.f, 200.f });
		static auto netFloodRateLimiter = netEventRateLimiterStore.GetRateLimiter("netEventFlood", fx::RateLimiterDefaults{ 75.f, 300.f });

		if (!netEventRateLimiter->Consume(source))
		{
			if (!netFloodRateLimiter->Consume(source))
			{
				gscomms_execute_callback_on_main_thread([this, source]()
				{
					auto client = instance->GetComponent<fx::ClientRegistry>()->GetClientByNetID(source);

					if (client)
					{
						instance->GetComponent<fx::GameServer>()->DropClient(client, "Unreliable network event overflow.");
					}
				}, true);
			}

			return true;
		}

		return false;
	}

public:
	fx::ServerInstanceBase* instance;
} g_reassemblySink;

inline std::string ToNarrow(const std::string& str)
{
	return str;
}

std::shared_mutex g_resourceStartOrderLock;
std::list<std::string> g_resourceStartOrder;

static InitFunction initFunction([]()
{
	fx::ServerInstanceBase::OnServerCreate.Connect([](fx::ServerInstanceBase* instance)
	{
		{
			g_citizenDir = instance->AddVariable<std::string>("citizen_dir", ConVar_None, ToNarrow(MakeRelativeCitPath(L"citizen")));

			// create cache directory if needed
			auto device = vfs::GetDevice(instance->GetRootPath());
			auto cacheDir = instance->GetRootPath() + "/cache/";

			if (device.GetRef())
			{
				device->CreateDirectory(cacheDir);

				// precreate cache/files/ so that later components won't have to
				device->CreateDirectory(cacheDir + "files/");
			}

			vfs::Mount(new vfs::RelativeDevice(g_citizenDir->GetValue() + "/"), "citizen:/");
			vfs::Mount(new vfs::RelativeDevice(cacheDir), "cache:/");
		}

		instance->SetComponent(fx::CreateResourceManager());
		instance->SetComponent(new fx::ServerEventComponent());
		instance->SetComponent(new fx::TokenRateLimiter(1.0f, 3.0f));

		fwRefContainer<fx::ResourceManager> resman = instance->GetComponent<fx::ResourceManager>();
		resman->SetComponent(new fx::ServerInstanceBaseRef(instance));
		resman->SetComponent(instance->GetComponent<console::Context>());
		resman->SetComponent(fx::EventReassemblyComponent::Create());

		{
			auto concom = resman->GetComponent<fx::ResourceManagerConstraintsComponent>();
			concom->SetEnforcingConstraints(true);

			std::string serverVersion = GIT_TAG;
			constexpr const auto prefixLen = std::string_view{ "v1.0.0." }.length();

			concom->RegisterConstraint("server", atoi((serverVersion.length() > prefixLen) ? (serverVersion.c_str() + prefixLen) : "99999"));
			concom->RegisterConstraint("onesync", [instance](std::string_view onesyncCheck, std::string* error) -> bool
			{
				if (fx::IsOneSync())
				{
					return true;
				}

				if (error)
				{
					*error = "OneSync needs to be enabled";
				}

				return false;
			});

			concom->RegisterConstraint("gameBuild", [instance](std::string_view gameBuildCheck, std::string* error) -> bool
			{
				auto enforcedBuild = fx::GetEnforcedGameBuildNumber();

				if (enforcedBuild)
				{
					fx::GameBuild minBuild;

					if (ConsoleArgumentType<fx::GameBuild>::Parse(std::string(gameBuildCheck), &minBuild))
					{
						int minBuildNum = atoi(minBuild.c_str());

						if (enforcedBuild >= minBuildNum)
						{
							return true;
						}
						else
						{
							if (error)
							{
								*error = fmt::sprintf("sv_enforceGameBuild needs to be at least %d (current is %d)", minBuildNum, enforcedBuild);
							}
						}
					}
				}

				return false;
			});

			concom->RegisterConstraint("native", [](std::string_view nativeHash, std::string* error)
			{
				if (nativeHash.length() > 2 && nativeHash.substr(0, 2) == "0x")
				{
					uint64_t nativeNum = strtoull(std::string(nativeHash.substr(2)).c_str(), nullptr, 16);

					if (fx::ScriptEngine::GetNativeHandler(nativeNum))
					{
						return true;
					}

					if (error)
					{
						*error = fmt::sprintf("native 0x%X isn't supported", nativeNum);
					}
				}

				return false;
			});
		}

		// TODO: not instanceable
		auto rac = resman->GetComponent<fx::EventReassemblyComponent>();

		instance
			->GetComponent<fx::GameServer>()
			->GetComponent<fx::HandlerMapComponent>()
			->Add(HashRageString("msgReassembledEvent"), [rac](const fx::ClientSharedPtr& client, net::Buffer& buffer)
			{
				rac->HandlePacket(client->GetNetId(), std::string_view{ (char*)(buffer.GetBuffer() + buffer.GetCurOffset()), buffer.GetRemainingBytes() });
			});

		g_reassemblySink.instance = instance;
		rac->SetSink(&g_reassemblySink);

		instance->GetComponent<fx::ClientRegistry>()->OnClientCreated.Connect([rac](const fx::ClientSharedPtr& client)
		{
			fx::Client* unsafeClient = client.get();
			unsafeClient->OnAssignNetId.Connect([rac, unsafeClient]()
			{
				if (unsafeClient->GetNetId() < 0xFFFF)
				{
					rac->RegisterTarget(unsafeClient->GetNetId());

					unsafeClient->OnDrop.Connect([rac, unsafeClient]()
					{
						rac->UnregisterTarget(unsafeClient->GetNetId());
					});
				}
			});
		});

		instance->GetComponent<fx::GameServer>()->OnNetworkTick.Connect([rac]()
		{
			rac->NetworkTick();
		});

		resman->AddMounter(new LocalResourceMounter(resman.GetRef()));

		fx::Resource::OnInitializeInstance.Connect([](fx::Resource* resource)
		{
			fx::ServerInstanceBase* instance = resource->GetManager()->GetComponent<fx::ServerInstanceBaseRef>()->Get();

			// resource game filtering
			resource->OnStart.Connect([instance, resource]()
			{
				auto gameServer = instance->GetComponent<fx::GameServer>();
				auto md = resource->GetComponent<fx::ResourceMetaDataComponent>();
				auto games = md->GetEntries("game");

				bool allowed = true;

				// store the game name
				std::string gameNameString;
				switch (gameServer->GetGameName())
				{
				case fx::GameName::GTA4:
					gameNameString = "gta4";
					break;
				case fx::GameName::GTA5:
					gameNameString = "gta5";
					break;
				case fx::GameName::RDR3:
					gameNameString = "rdr3";
					break;
				default:
					gameNameString = "unknown";
				}

				// if is FXv2
				auto isCfxV2 = md->GetEntries("is_cfxv2");

				if (isCfxV2.begin() != isCfxV2.end())
				{
					// validate game name
					std::set<std::string> gameSet;

					for (const auto& game : games)
					{
						gameSet.insert(game.second);
					}

					bool isCommon = (gameSet.find("common") != gameSet.end());
					bool isGame = (gameSet.find(gameNameString) != gameSet.end());

					if (isCommon && isGame)
					{
						console::PrintWarning("resources", "Resource %s specifies both `common` and a specific game. This is considered ill-formed.\n", resource->GetName());
						allowed = false;
					}
					else if (!isCommon && !isGame)
					{
						console::PrintWarning("resources", "Resource %s does not support the current game (%s).\n", resource->GetName(), gameNameString);
						allowed = false;
					}

					if (!*md->IsManifestVersionBetween("adamant", ""))
					{
						console::PrintWarning("resources", "Resource %s does not specify an `fx_version` in fxmanifest.lua.\n", resource->GetName());
						allowed = false;
					}

					if (isGame && gameNameString == "rdr3")
					{
						auto warningEntries = md->GetEntries("rdr3_warning");

						static const std::string warningString = "I acknowledge that this is a prerelease build of RedM, and I am aware my resources *will* become incompatible once RedM ships.";

						if (warningEntries.begin() == warningEntries.end() || warningEntries.begin()->second != warningString)
						{
							console::PrintWarning("resources", "Resource %s does not contain the RedM pre-release warning in fxmanifest.lua.\nPlease add ^2rdr3_warning '%s'^3 to fxmanifest.lua in this resource.\n", resource->GetName(), warningString);
							allowed = false;
						}
					}
				}
				else
				{
					// allow non-FXv2 for GTA5 only
					if (gameNameString != "gta5")
					{
						console::PrintWarning("resources", "Resource %s is not using CitizenFXv2 manifest. This is not allowed for the current game (%s).\n", resource->GetName(), gameNameString);
						allowed = false;
					}
				}

				return allowed;
			}, INT32_MIN);

			resource->OnStart.Connect([=]()
			{
				trace("Started resource %s\n", resource->GetName());

				auto metaData = resource->GetComponent<fx::ResourceMetaDataComponent>();
				auto iv = metaData->GetEntries("server_only");

				if (iv.begin() != iv.end())
				{
					return;
				}

				{
					std::unique_lock<std::shared_mutex> _(g_resourceStartOrderLock);
					g_resourceStartOrder.push_back(resource->GetName());
				}

				auto clientRegistry = instance->GetComponent<fx::ClientRegistry>();
				auto trl = instance->GetComponent<fx::TokenRateLimiter>();

				net::Buffer outBuffer;
				outBuffer.Write(HashRageString("msgResStart"));
				outBuffer.Write(resource->GetName().c_str(), resource->GetName().length());

				clientRegistry->ForAllClients([&](const fx::ClientSharedPtr& client)
				{
					client->SendPacket(0, outBuffer, NetPacketType_Reliable);

					trl->ReturnToken(client->GetConnectionToken());
				});
			}, 99999999);

			resource->OnStop.Connect([=]()
			{
				trace("Stopping resource %s\n", resource->GetName());

				auto metaData = resource->GetComponent<fx::ResourceMetaDataComponent>();
				auto iv = metaData->GetEntries("server_only");

				if (iv.begin() != iv.end())
				{
					return;
				}

				{
					std::unique_lock<std::shared_mutex> _(g_resourceStartOrderLock);
					g_resourceStartOrder.erase(std::remove_if(g_resourceStartOrder.begin(), g_resourceStartOrder.end(), [&resource](const std::string& name)
											   {
												   return name == resource->GetName();
											   }),
					g_resourceStartOrder.end());
				}

				auto clientRegistry = instance->GetComponent<fx::ClientRegistry>();

				net::Buffer outBuffer;
				outBuffer.Write(HashRageString("msgResStop"));
				outBuffer.Write(resource->GetName().c_str(), resource->GetName().length());

				clientRegistry->ForAllClients([&](const fx::ClientSharedPtr& client)
				{
					client->SendPacket(0, outBuffer, NetPacketType_Reliable);
				});
			}, -1000);
		});

		ScanResources(instance);

		static auto commandRef = instance->AddCommand("start", [=](const std::string& resourceName)
		{
			if (resourceName.empty())
			{
				return;
			}

			if (resourceName[0] == '[' && resourceName[resourceName.size() - 1] == ']')
			{
				for (const auto& resource : g_resourcesByComponent[resourceName])
				{
					auto conCtx = instance->GetComponent<console::Context>();
					conCtx->ExecuteSingleCommandDirect(ProgramArguments{ "start", resource });
				}

				return;
			}

			auto resource = resman->GetResource(resourceName);

			if (!resource.GetRef())
			{
				trace("^3Couldn't find resource %s.^7\n", resourceName);
				return;
			}

			if (!resource->Start())
			{
				if (resource->GetState() == fx::ResourceState::Stopped)
				{
					trace("^3Couldn't start resource %s.^7\n", resourceName);
					return;
				}
			}
		});

		static auto stopCommandRef = instance->AddCommand("stop", [=](const std::string& resourceName)
		{
			if (resourceName.empty())
			{
				return;
			}

			if (resourceName[0] == '[' && resourceName[resourceName.size() - 1] == ']')
			{
				for (const auto& resource : g_resourcesByComponent[resourceName])
				{
					auto conCtx = instance->GetComponent<console::Context>();
					conCtx->ExecuteSingleCommandDirect(ProgramArguments{ "stop", resource });
				}

				return;
			}

			auto resource = resman->GetResource(resourceName);

			if (!resource.GetRef())
			{
				trace("^3Couldn't find resource %s.^7\n", resourceName);
				return;
			}

			if (!resource->Stop())
			{
				if (resource->GetState() != fx::ResourceState::Stopped)
				{
					trace("^3Couldn't stop resource %s.^7\n", resourceName);
					return;
				}
			}
		});

		static auto restartCommandRef = instance->AddCommand("restart", [=](const std::string& resourceName)
		{
			auto resource = resman->GetResource(resourceName);

			if (!resource.GetRef())
			{
				trace("^3Couldn't find resource %s.^7\n", resourceName);
				return;
			}

			if (resource->GetState() != fx::ResourceState::Started)
			{
				trace("Can't restart a stopped resource.\n");
				return;
			}

			auto conCtx = instance->GetComponent<console::Context>();
			conCtx->ExecuteSingleCommandDirect(ProgramArguments{ "stop", resourceName });
			conCtx->ExecuteSingleCommandDirect(ProgramArguments{ "start", resourceName });
		});

		static bool configured = false;

		static auto ensureCommandRef = instance->AddCommand("ensure", [=](const std::string& resourceName)
		{
			if (resourceName[0] == '[' && resourceName[resourceName.size() - 1] == ']')
			{
				for (const auto& resource : g_resourcesByComponent[resourceName])
				{
					auto conCtx = instance->GetComponent<console::Context>();
					conCtx->ExecuteSingleCommandDirect(ProgramArguments{ "ensure", resource });
				}

				return;
			}

			auto resource = resman->GetResource(resourceName);

			if (!resource.GetRef())
			{
				trace("^3Couldn't find resource %s.^7\n", resourceName);
				return;
			}

			auto conCtx = instance->GetComponent<console::Context>();

			// don't allow `ensure` to restart a resource if we're still configuring (e.g. executing a startup script)
			// this'll lead to issues when, say, the following script runs:
			//     ensure res2
			//     ensure res1
			//
			// if res2 depends on res1, res1 restarting will lead to res2 stopping but not being started again
			// #TODO: restarting behavior of stopped dependencies at runtime
			if (configured && resource->GetState() == fx::ResourceState::Started)
			{
				conCtx->ExecuteSingleCommandDirect(ProgramArguments{ "stop", resourceName });
			}

			conCtx->ExecuteSingleCommandDirect(ProgramArguments{ "start", resourceName });
		});

		instance->OnInitialConfiguration.Connect([]()
		{
			configured = true;
		});

		static auto refreshCommandRef = instance->AddCommand("refresh", [=]()
		{
			ScanResources(instance);
		});

		instance->GetComponent<console::Context>()->GetCommandManager()->FallbackEvent.Connect([=](const std::string& commandName, const ProgramArguments& arguments, const std::string& context)
		{
			auto eventComponent = resman->GetComponent<fx::ResourceEventManagerComponent>();

			// assert privilege
			if (!seCheckPrivilege(fmt::sprintf("command.%s", commandName)))
			{
				return true;
			}

			// if canceled, the command was handled, so cancel the fwEvent
			return (eventComponent->TriggerEvent2("rconCommand", {}, commandName, arguments.GetArguments()));
		}, -100);

		static std::string rawCommand;

		instance->GetComponent<console::Context>()->GetCommandManager()->FallbackEvent.Connect([=](const std::string& commandName, const ProgramArguments& arguments, const std::string& context)
		{
			if (!context.empty())
			{
				auto eventComponent = resman->GetComponent<fx::ResourceEventManagerComponent>();

				try
				{
					return eventComponent->TriggerEvent2("__cfx_internal:commandFallback", { "internal-net:" + context }, rawCommand);
				}
				catch (std::bad_any_cast& e)
				{
					trace("caught bad_any_cast in FallbackEvent handler for %s\n", commandName);
				}
			}

			return true;
		}, 99999);

		auto gameServer = instance->GetComponent<fx::GameServer>();
		gameServer->GetComponent<fx::HandlerMapComponent>()->Add(HashRageString("msgServerEvent"), std::bind(&HandleServerEvent, instance, std::placeholders::_1, std::placeholders::_2));

		gameServer->GetComponent<fx::HandlerMapComponent>()->Add(HashRageString("msgServerCommand"), [=](const fx::ClientSharedPtr& client, net::Buffer& buffer)
		{
			static fx::RateLimiterStore<uint32_t, false> netEventRateLimiterStore{ instance->GetComponent<console::Context>().GetRef() };
			static auto netEventRateLimiter = netEventRateLimiterStore.GetRateLimiter("netCommand", fx::RateLimiterDefaults{ 7.f, 14.f });
			static auto netFloodRateLimiter = netEventRateLimiterStore.GetRateLimiter("netCommandFlood", fx::RateLimiterDefaults{ 25.f, 45.f });

			uint32_t netId = client->GetNetId();

			if (!netEventRateLimiter->Consume(netId))
			{
				if (!netFloodRateLimiter->Consume(netId))
				{
					gscomms_execute_callback_on_main_thread([client, instance]()
					{
						instance->GetComponent<fx::GameServer>()->DropClient(client, "Reliable server command overflow.");
					});
				}

				return;
			}

			auto cmdLen = buffer.Read<uint16_t>();

			std::vector<char> cmd(cmdLen);
			buffer.Read(cmd.data(), cmdLen);

			std::string printString;

			fx::PrintListenerContext context([&](const std::string_view& print)
			{
				printString += print;
			});

			fx::ScopeDestructor destructor([&]()
			{
				msgpack::sbuffer sb;

				msgpack::packer<msgpack::sbuffer> packer(sb);
				packer.pack_array(1).pack(printString);

				instance->GetComponent<fx::ServerEventComponent>()->TriggerClientEvent("__cfx_internal:serverPrint", sb.data(), sb.size(), { std::to_string(client->GetNetId()) });
			});

			// save the raw command for fallback usage
			rawCommand = std::string(cmd.begin(), cmd.end());

			// invoke
			auto consoleCxt = instance->GetComponent<console::Context>();
			consoleCxt->GetCommandManager()->Invoke(rawCommand, std::to_string(client->GetNetId()));

			// unset raw command
			rawCommand = "";
		});

		gameServer->OnTick.Connect([=]()
		{
			resman->Tick();
		});
	}, 50);
});

#include <ScriptEngine.h>
#include <optional>

void fx::ServerEventComponent::TriggerClientEvent(const std::string_view& eventName, const void* data, size_t dataLen, const std::optional<std::string_view>& targetSrc)
{
	// build the target event
	net::Buffer outBuffer;
	outBuffer.Write(0x7337FD7A);

	// source netId
	outBuffer.Write<uint16_t>(-1);

	// event name
	outBuffer.Write<uint16_t>(eventName.size() + 1);
	outBuffer.Write(eventName.data(), eventName.size());
	outBuffer.Write<uint8_t>(0);

	// payload
	outBuffer.Write(data, dataLen);

	// get the game server and client registry
	auto gameServer = m_instance->GetComponent<fx::GameServer>();
	auto clientRegistry = m_instance->GetComponent<fx::ClientRegistry>();

	// do we have a specific client to send to?
	if (targetSrc)
	{
		int targetNetId = atoi(targetSrc->data());
		auto client = clientRegistry->GetClientByNetID(targetNetId);

		if (client)
		{
			// TODO(fxserver): >MTU size?
			client->SendPacket(0, outBuffer, NetPacketType_Reliable);
		}
	}
	else
	{
		clientRegistry->ForAllClients([&](const fx::ClientSharedPtr& client)
		{
			client->SendPacket(0, outBuffer, NetPacketType_Reliable);
		});
	}
}

static InitFunction initFunction2([]()
{
	fx::ScriptEngine::RegisterNativeHandler("PRINT_STRUCTURED_TRACE", [](fx::ScriptContext& context)
	{
		std::string_view jsonData = context.CheckArgument<const char*>(0);

		try
		{
			auto j = nlohmann::json::parse(jsonData);

			StructuredTrace({ "type", "script_structured_trace" }, { "payload", j });
		}
		catch (std::exception& e)
		{

		}
	});

	fx::ScriptEngine::RegisterNativeHandler("TRIGGER_CLIENT_EVENT_INTERNAL", [](fx::ScriptContext& context)
	{
		std::string_view eventName = context.CheckArgument<const char*>(0);
		std::optional<std::string_view> targetSrc;

		{
			auto targetSrcIdx = context.CheckArgument<const char*>(1);

			if (strcmp(targetSrcIdx, "-1") != 0)
			{
				targetSrc = targetSrcIdx;
			}
		}

		const void* data = context.GetArgument<const void*>(2);
		uint32_t dataLen = context.GetArgument<uint32_t>(3);

		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto instance = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get();

		instance->GetComponent<fx::ServerEventComponent>()->TriggerClientEvent(eventName, data, dataLen, targetSrc);
	});

	fx::ScriptEngine::RegisterNativeHandler("TRIGGER_LATENT_CLIENT_EVENT_INTERNAL", [](fx::ScriptContext& context)
	{
		std::string eventName = context.CheckArgument<const char*>(0);
		auto targetSrcIdx = context.CheckArgument<const char*>(1);

		const void* data = context.GetArgument<const void*>(2);
		uint32_t dataLen = context.GetArgument<uint32_t>(3);

		int bps = context.GetArgument<int>(4);

		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto rac = resourceManager->GetComponent<fx::EventReassemblyComponent>();

		rac->TriggerEvent(std::stoi(targetSrcIdx), std::string_view{ eventName.c_str(), eventName.size() + 1 }, std::string_view{ reinterpret_cast<const char*>(data), dataLen }, bps);
	});

	fx::ScriptEngine::RegisterNativeHandler("START_RESOURCE", [](fx::ScriptContext& context)
	{
		auto resourceManager = fx::ResourceManager::GetCurrent();
		fwRefContainer<fx::Resource> resource = resourceManager->GetResource(context.CheckArgument<const char*>(0));

		bool success = false;

		if (resource.GetRef())
		{
			success = resource->Start();
		}

		context.SetResult(success);
	});

	fx::ScriptEngine::RegisterNativeHandler("STOP_RESOURCE", [](fx::ScriptContext& context)
	{
		auto resourceManager = fx::ResourceManager::GetCurrent();
		fwRefContainer<fx::Resource> resource = resourceManager->GetResource(context.CheckArgument<const char*>(0));

		bool success = false;

		if (resource.GetRef())
		{
			fx::OMPtr<IScriptRuntime> runtime;
			std::string currentResourceName;

			if (FX_SUCCEEDED(fx::GetCurrentScriptRuntime(&runtime)))
			{
				currentResourceName = reinterpret_cast<fx::Resource*>(runtime->GetParentObject())->GetName();
			}

			if (g_managedResources.find(resource->GetName()) != g_managedResources.end() || resource->GetName() == currentResourceName)
			{
				success = false;
			}
			else
			{
				success = resource->Stop();
			}
		}

		context.SetResult(success);
	});

	fx::ScriptEngine::RegisterNativeHandler("SCHEDULE_RESOURCE_TICK", [](fx::ScriptContext& context)
	{
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// #TODOMONITOR: make helper
		auto monitorVar = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get()->GetComponent<console::Context>()->GetVariableManager()->FindEntryRaw("monitorMode");

		if (monitorVar && monitorVar->GetValue() != "0")
		{
			return;
		}

		fwRefContainer<fx::Resource> resource = resourceManager->GetResource(context.CheckArgument<const char*>(0));

		gscomms_execute_callback_on_main_thread([resource]()
		{
			if (resource.GetRef())
			{
				resource->GetManager()->MakeCurrent();
				resource->Tick();
			}
		}, true);
	});

	fx::ScriptEngine::RegisterNativeHandler("REGISTER_RESOURCE_ASSET", [](fx::ScriptContext& context)
	{
		auto resourceManager = fx::ResourceManager::GetCurrent();
		fwRefContainer<fx::Resource> resource = resourceManager->GetResource(context.CheckArgument<const char*>(0));

		if (!resource.GetRef())
		{
			throw std::runtime_error("Invalid resource name passed to REGISTER_RESOURCE_ASSET.");
		}

		auto diskName = context.CheckArgument<const char*>(1);

		auto streamComponent = resource->GetComponent<fx::ResourceStreamComponent>();
		auto sf = streamComponent->AddStreamingFile(resource->GetPath() + "/" + diskName);

		if (!sf)
		{
			throw std::runtime_error("Failed to register streaming file in REGISTER_RESOURCE_ASSET.");
		}

		static std::string tempStr;
		tempStr = sf->GetCacheString();

		context.SetResult<const char*>(tempStr.c_str());
	});

	fx::ScriptEngine::RegisterNativeHandler("SET_GAME_TYPE", [](fx::ScriptContext& context)
	{
		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto instance = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get();

		// get the server's console context
		auto consoleContext = instance->GetComponent<console::Context>();

		se::ScopedPrincipal principalScope(se::Principal{ "system.console" });

		// set gametype variable
		consoleContext->ExecuteSingleCommandDirect(ProgramArguments{ "set", "gametype", context.CheckArgument<const char*>(0) });
	});

	fx::ScriptEngine::RegisterNativeHandler("SET_MAP_NAME", [](fx::ScriptContext& context)
	{
		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto instance = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get();

		// get the server's console context
		auto consoleContext = instance->GetComponent<console::Context>();

		se::ScopedPrincipal principalScope(se::Principal{ "system.console" });

		// set mapname variable
		consoleContext->ExecuteSingleCommandDirect(ProgramArguments{ "set", "mapname", context.CheckArgument<const char*>(0) });
	});

	fx::ScriptEngine::RegisterNativeHandler("ENABLE_ENHANCED_HOST_SUPPORT", [](fx::ScriptContext& context)
	{
		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto instance = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get();

		// get the server's console context
		auto consoleContext = instance->GetComponent<console::Context>();

		se::ScopedPrincipal principalScope(se::Principal{ "system.console" });

		// set mapname variable
		consoleContext->ExecuteSingleCommandDirect(ProgramArguments{ "set", "sv_enhancedHostSupport", context.GetArgument<bool>(0) ? "1" : "0" });
	});

	fx::ScriptEngine::RegisterNativeHandler("GET_CONVAR", [](fx::ScriptContext& context)
	{
		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto instance = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get();

		// get the server's console context
		auto consoleContext = instance->GetComponent<console::Context>();

		// get the variable manager
		auto varMan = consoleContext->GetVariableManager();

		// get the variable
		auto var = varMan->FindEntryRaw(context.CheckArgument<const char*>(0));

		if (!var)
		{
			context.SetResult(context.CheckArgument<const char*>(1));
		}
		else
		{
			static std::string varVal;
			varVal = var->GetValue();

			context.SetResult(varVal.c_str());
		}
	});

	fx::ScriptEngine::RegisterNativeHandler("GET_CONVAR_INT", [](fx::ScriptContext& context)
	{
		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto instance = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get();

		// get the server's console context
		auto consoleContext = instance->GetComponent<console::Context>();

		// get the variable manager
		auto varMan = consoleContext->GetVariableManager();

		// get the variable
		auto var = varMan->FindEntryRaw(context.CheckArgument<const char*>(0));

		if (!var)
		{
			context.SetResult(context.GetArgument<int>(1));
		}
		else
		{
			context.SetResult(atoi(var->GetValue().c_str()));
		}
	});

	fx::ScriptEngine::RegisterNativeHandler("SET_CONVAR", [](fx::ScriptContext& context)
	{
		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto instance = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get();

		// get the server's console context
		auto consoleContext = instance->GetComponent<console::Context>();

		se::ScopedPrincipal principalScope(se::Principal{ "system.console" });

		// set variable
		consoleContext->ExecuteSingleCommandDirect(ProgramArguments{ "set", context.CheckArgument<const char*>(0), context.CheckArgument<const char*>(1) });
	});

	fx::ScriptEngine::RegisterNativeHandler("SET_CONVAR_SERVER_INFO", [](fx::ScriptContext& context)
	{
		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto instance = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get();

		// get the server's console context
		auto consoleContext = instance->GetComponent<console::Context>();

		se::ScopedPrincipal principalScope(se::Principal{ "system.console" });

		// set variable
		consoleContext->ExecuteSingleCommandDirect(ProgramArguments{ "sets", context.CheckArgument<const char*>(0), context.CheckArgument<const char*>(1) });
	});

	fx::ScriptEngine::RegisterNativeHandler("SET_CONVAR_REPLICATED", [](fx::ScriptContext& context)
	{
		// get the current resource manager
		auto resourceManager = fx::ResourceManager::GetCurrent();

		// get the owning server instance
		auto instance = resourceManager->GetComponent<fx::ServerInstanceBaseRef>()->Get();

		// get the server's console context
		auto consoleContext = instance->GetComponent<console::Context>();

		se::ScopedPrincipal principalScope(se::Principal{ "system.console" });

		// set variable
		consoleContext->ExecuteSingleCommandDirect(ProgramArguments{ "setr", context.CheckArgument<const char*>(0), context.CheckArgument<const char*>(1) });
	});
});

max_stars_repo_name: slashkeyvalue/fivem

max_issues_repo_name: gottfriedleibniz/fivem

max_forks_repo_name: gottfriedleibniz/fivem


text:
#include <math_lib/bissectrix.h>
#include <math_lib/vec_base.h>

#include <boost/qvm/vec.hpp>
#include <boost/qvm/vec_operations.hpp>

#include <gtest/gtest.h>

using namespace pagoda;

TEST(Bissectrix, when_finding_the_bissectrix_between_two_vectors_should_return_a_vector)
{
	boost::qvm::vec<float, 3> v1{1, 1, 0};
	boost::qvm::vec<float, 3> v2{-1, 1, 0};

	auto r = bissectrix(v1, v2);
	EXPECT_TRUE(r == (Vec3F{0, 1, 0}));
}

TEST(Bissectrix, when_finding_the_bissectrix_between_two_colinear_vectors_should_return_an_orthogonal_vector)
{
	boost::qvm::vec<float, 3> v1{1, 0, 0};
	boost::qvm::vec<float, 3> v2{-1, 0, 0};

	auto r = bissectrix(v1, v2);

	EXPECT_EQ(boost::qvm::dot(r, v1), 0.0f);
}

max_stars_repo_name: diegoarjz/selector

max_issues_repo_name: diegoarjz/selector

max_forks_repo_name: diegoarjz/selector


text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

/**
\file

\brief dimension.cpp

\detailed
Test dimension list manipulation.

Output:
@verbatim

//[dimension_output
length_dimension  = list<dim<length_base_dimension, static_rational<1l, 1l> >, dimensionless_type>
mass_dimension    = list<dim<mass_base_dimension, static_rational<1l, 1l> >, dimensionless_type>
time_dimension    = list<dim<time_base_dimension, static_rational<1l, 1l> >, dimensionless_type>
energy_dimension  = list<dim<length_base_dimension, static_rational<2l, 1l> >, list<dim<mass_base_dimension, static_rational<1l, 1l> >, list<dim<time_base_dimension, static_rational<-2l, 1l> >, dimensionless_type> > >
LM_type      = list<dim<length_base_dimension, static_rational<1l, 1l> >, list<dim<mass_base_dimension, static_rational<1l, 1l> >, dimensionless_type> >
L_T_type     = list<dim<length_base_dimension, static_rational<1l, 1l> >, list<dim<time_base_dimension, static_rational<-1l, 1l> >, dimensionless_type> >
V_type       = list<dim<length_base_dimension, static_rational<1l, 1l> >, list<dim<time_base_dimension, static_rational<-1l, 1l> >, dimensionless_type> >
//]

@endverbatim
**/

#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/assert.hpp>

#include <iostream>

#include <boost/units/detail/utility.hpp>

#include "test_system.hpp"

namespace mpl = boost::mpl;

int main(void)
{
    using namespace boost::units;

    BOOST_MPL_ASSERT((boost::is_same<
        length_dimension,
        mpl::push_front<
            dimensionless_type,
            dim<length_base_dimension, static_rational<1L, 1L> >
        >::type
    >));
    BOOST_MPL_ASSERT((boost::is_same<
        mass_dimension,
        mpl::push_front<
            dimensionless_type,
            dim<mass_base_dimension, static_rational<1L, 1L> >
        >::type
    >));
    BOOST_MPL_ASSERT((boost::is_same<energy_dimension,
        mpl::push_front<
        mpl::push_front<
        mpl::push_front<
        dimensionless_type,
        dim<time_base_dimension, static_rational<-2L, 1L> > >::type,
        dim<mass_base_dimension, static_rational<1L, 1L> > >::type,
        dim<length_base_dimension, static_rational<2L, 1L> > >::type>));

    std::cout << "length_dimension  = "
              << simplify_typename(length_dimension()) << std::endl
              << "mass_dimension    = "
              << simplify_typename(mass_dimension()) << std::endl
              << "time_dimension    = "
              << simplify_typename(time_dimension()) << std::endl
              << "energy_dimension  = "
              << simplify_typename(energy_dimension()) << std::endl;

    //[dimension_snippet_1
    typedef mpl::times<length_dimension,mass_dimension>::type   LM_type;
    typedef mpl::divides<length_dimension,time_dimension>::type L_T_type;
    typedef static_root<
        mpl::divides<energy_dimension,mass_dimension>::type,
        static_rational<2>
    >::type    V_type;
    //]

    BOOST_MPL_ASSERT((boost::is_same<LM_type,
        mpl::push_front<
        mpl::push_front<
        dimensionless_type,
        dim<mass_base_dimension, static_rational<1L, 1L> > >::type,
        dim<length_base_dimension, static_rational<1L, 1L> > >::type>));

    BOOST_MPL_ASSERT((boost::is_same<L_T_type,
        mpl::push_front<
        mpl::push_front<
        dimensionless_type,
        dim<time_base_dimension, static_rational<-1L, 1L> > >::type,
        dim<length_base_dimension, static_rational<1L, 1L> > >::type>));

    BOOST_MPL_ASSERT((boost::is_same<V_type,
        mpl::push_front<
        mpl::push_front<
        dimensionless_type,
        dim<time_base_dimension, static_rational<-1L, 1L> > >::type,
        dim<length_base_dimension, static_rational<1L, 1L> > >::type>));

    std::cout << "LM_type      = " << simplify_typename(LM_type()) << std::endl
              << "L_T_type     = " << simplify_typename(L_T_type()) << std::endl
              << "V_type       = " << simplify_typename(V_type()) << std::endl;

    return 0;
}

max_issues_repo_name: boost-cmake/vintage

max_forks_repo_name: boost-cmake/vintage


text:
//==================================================================================================
/*!
  @file

  @copyright 2015 NumScale SAS
  @copyright 2015 J.T.Lapreste

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_EXPM1_KERNEL_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_EXPM1_KERNEL_HPP_INCLUDED

#include <boost/simd/function/fast.hpp>
#include <boost/simd/constant/ratio.hpp>
#include <boost/simd/constant/half.hpp>
#include <boost/simd/constant/invlog_2.hpp>
#include <boost/simd/constant/log_2hi.hpp>
#include <boost/simd/constant/log_2lo.hpp>
#include <boost/simd/constant/maxexponent.hpp>
#include <boost/simd/constant/nbmantissabits.hpp>
#include <boost/simd/constant/six.hpp>
#include <boost/simd/constant/three.hpp>
#include <boost/simd/function/bitwise_cast.hpp>
#include <boost/simd/function/divides.hpp>
#include <boost/simd/function/expm1.hpp>
#include <boost/simd/function/ldexp.hpp>
#include <boost/simd/function/fms.hpp>
#include <boost/simd/function/fnms.hpp>
#include <boost/simd/function/if_else.hpp>
#include <boost/simd/function/is_less.hpp>
#include <boost/simd/function/minus.hpp>
#include <boost/simd/function/multiplies.hpp>
#include <boost/simd/function/oneminus.hpp>
#include <boost/simd/function/oneplus.hpp>
#include <boost/simd/function/plus.hpp>
#include <boost/simd/function/round2even.hpp>
#include <boost/simd/function/shift_left.hpp>
#include <boost/simd/function/sqr.hpp>
#include <boost/simd/function/toint.hpp>
#include <boost/simd/function/unary_minus.hpp>
#include <boost/simd/function/horn.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <boost/dispatch/meta/scalar_of.hpp>

namespace boost { namespace simd
{
  namespace detail
  {
    namespace bd =  boost::dispatch;
    namespace bs =  boost::simd;

    template < typename A0, typename sA0 = bd::scalar_of_t<A0> >
    struct expm1_kernel;

    template < typename A0 >
    struct expm1_kernel < A0, float >
    {
      // computes expm1 for float or float vectors
      static BOOST_FORCEINLINE A0 expm1(const A0& a0) BOOST_NOEXCEPT
      {
        using i_t = bd::as_integer_t<A0>;
        using s_t = bd::scalar_of_t<A0>;
        A0 k  = round2even(Invlog_2<A0>()*a0);
        A0 x = fnms(k, Log_2hi<A0>(), a0);
        x =  fnms(k, Log_2lo<A0>(), x);
        A0 hx  = x*Half<A0>();
        A0 hxs = x*hx;
        A0 r1 = horn<s_t,
                     0X3F800000UL,// 1
                     0XBD08887FUL, // -3.3333298E-02
                     0X3ACF6DB4UL  // 1.5825541E-03
                     > (hxs);
        A0 t  = fnms(r1, hx, Three<A0>());
        A0 e  = hxs*((r1-t)/(Six<A0>() - x*t));
        e  = fms(x, e, hxs);
        i_t ik =  toint(k);
        A0 two2mk = bitwise_cast<A0>(shift_left(Maxexponent<A0>()-ik,Nbmantissabits<s_t>()));
        A0 y = oneminus(two2mk)-(e-x);
        return fast_(ldexp)(y, ik);
      }
    };

    template < typename A0 >
    struct expm1_kernel < A0, double >
    {
      // computes expm1 for  double or double vectors
      static  BOOST_FORCEINLINE A0 expm1(const A0& a0) BOOST_NOEXCEPT
      {
        using i_t = bd::as_integer_t<A0>;
        using s_t = bd::scalar_of_t<A0>;
        A0 k  = round2even(Invlog_2<A0>()*a0);
        A0 hi = fnms(k, Log_2hi<A0>(), a0);
        A0 lo = k*Log_2lo<A0>();
        A0 x  = hi-lo;
        A0 hxs = sqr(x)*Half<A0>();
        A0 r1 = horn<s_t,
                     0X3FF0000000000000ULL,
                     0XBFA11111111110F4ULL,
                     0X3F5A01A019FE5585ULL,
                     0XBF14CE199EAADBB7ULL,
                     0X3ED0CFCA86E65239ULL,
                     0XBE8AFDB76E09C32DULL
                     > (hxs);
        A0 t  = Three<A0>()-r1*Half<A0>()*x;
        A0 e  = hxs*((r1-t)/(Six<A0>() - x*t));
        A0 c = (hi-x)-lo;
        e  = (x*(e-c)-c)-hxs;
        i_t ik =  toint(k);
        A0 two2mk = bitwise_cast<A0>(shift_left(Maxexponent<A0>()-ik,Nbmantissabits<s_t>()));
        A0 ct1= oneminus(two2mk)-(e-x);
        A0 ct2= oneplus((x-(e+two2mk)));
        A0 y = if_else((k < Ratio<A0, 20>()),ct1,ct2);
        return fast_(ldexp)(y, ik);
      }
    };
  }
} }
#endif


text:
//
// Created by student on 16.01.2020.
//

#ifndef SERWIS_SPRZETU_KOMPUTEROWEGO_CLIENT_HPP
#define SERWIS_SPRZETU_KOMPUTEROWEGO_CLIENT_HPP

#include <string>
#include <memory>
#include <vector>
#include "Address.hpp"
#include <boost/uuid/uuid.hpp>

class Order;

typedef std::shared_ptr<Order> OrderSPtr;

class ClientType;

typedef std::shared_ptr<ClientType> ClientTypeSPtr;

class Client {
    std::string firstName;
    std::string lastName;
    boost::uuids::uuid ID;
    Address address;
    Address registeredAddress;
    std::vector<OrderSPtr> orders;
    ClientTypeSPtr clientType;

public:
    Client(const std::string &firstName, const std::string &lastName,
           const std::string &addressStreet, const std::string &addressNumber,
           const std::string &registeredAddressStreet, const std::string &registeredAddressNumber);

    virtual ~Client();

    const std::string &getFirstName() const;

    const std::string &getLastName() const;

    const boost::uuids::uuid &getId() const;

    void setFirstName(const std::string &newFirstName);

    void setLastName(const std::string &newLastName);

    void setAddress(const std::string &street, const std::string &number);

    void setRegisteredAddress(const std::string &street, const std::string &number);

    std::string clientInfo(bool isClient = true);

    const Address &getAddress() const;

    const Address &getRegisteredAddress() const;

    void addOrder(const OrderSPtr &order);

    void removeOrder(const OrderSPtr &orderToRemove);

    void setClientType(int numOfOrders);

    double calculateDiscount(double price, int numberOfOrders);

    int numberOfOrders();

    std::vector<OrderSPtr> &getOrders();

    Client &operator=(const Client &rhs);

};

bool operator==(const Client &lhs, const Client &rhs);

#endif //SERWIS_SPRZETU_KOMPUTEROWEGO_CLIENT_HPP

max_stars_repo_name: aantczakpiotr/OOP-final-project

max_issues_repo_name: aantczakpiotr/OOP-final-project

max_forks_repo_name: aantczakpiotr/OOP-final-project