//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/Shape/TruncatedEllipsoidNet.cpp
//! @brief     Implements class TruncatedEllipsoidNet.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Sample/Shape/TruncatedEllipsoidNet.h"
#include "Base/Util/Assert.h"
#include <algorithm>
#include <cmath>

TruncatedEllipsoidNet::TruncatedEllipsoidNet(double r_x, double r_y, double r_z, double height,
                                             double dh)
{
    ASSERT(std::isfinite(r_z));
    static const int n_heights =
        std::max(2, static_cast<int>(std::round(
                        static_cast<double>(Shape3D::N_Circle) * height / 2.0 / r_z + 0.5)));
    double h_step = (height - dh) / (n_heights - 1);
    ASSERT(std::isfinite(h_step));
    m_vertices.resize(n_heights * Shape3D::N_Circle);
    auto it = m_vertices.begin();
    for (int i = 0; i < n_heights; ++i) {
        double z = i * h_step;
        // for r_z=height, dh=0, i=n_heights-1, the argument of the following sqrt should be 0,
        // but can be slightly smaller because of floating-point errors, therefore needs
        // to be overwritten by 0.
        double radius_factor = std::sqrt(std::max(0., 1.0 - std::pow((z + r_z - height) / r_z, 2)));
        ASSERT(std::isfinite(z));
        ASSERT(std::isfinite(radius_factor));
        auto ellipse = EllipseVerticesZ(radius_factor * r_x, radius_factor * r_y, i * h_step);
        std::move(ellipse.begin(), ellipse.end(), it);
        it = it + ellipse.size();
    }
}

TruncatedEllipsoidNet::~TruncatedEllipsoidNet() = default;
