106 lines
2.1 KiB
C++
106 lines
2.1 KiB
C++
#ifndef DLANG_LIBS_MATH_HPP
|
|
#define DLANG_LIBS_MATH_HPP
|
|
|
|
#include <chrono>
|
|
#include <thread>
|
|
#include <random>
|
|
|
|
#include "../vm.hpp"
|
|
#include "../helpers.hpp"
|
|
|
|
static void NativeMathAbs(DlangVM* vm)
|
|
{
|
|
auto val = dlang_tonumber(vm);
|
|
dlang_pushnumber(vm, std::fabs(val));
|
|
}
|
|
|
|
static void NativeMathFloor(DlangVM* vm)
|
|
{
|
|
double val = dlang_tonumber(vm);
|
|
dlang_pushnumber(vm, std::floor(val));
|
|
}
|
|
|
|
static void NativeMathCeil(DlangVM* vm)
|
|
{
|
|
double val = dlang_tonumber(vm);
|
|
dlang_pushnumber(vm, std::ceil(val));
|
|
}
|
|
|
|
static void NativeMathSqrt(DlangVM* vm)
|
|
{
|
|
double val = dlang_tonumber(vm);
|
|
dlang_pushnumber(vm, std::sqrt(val));
|
|
}
|
|
|
|
static void NativeMathPow(DlangVM* vm)
|
|
{
|
|
double exp = dlang_tonumber(vm);
|
|
double base = dlang_tonumber(vm);
|
|
dlang_pushnumber(vm, std::pow(base, exp));
|
|
}
|
|
|
|
static void NativeMathSin(DlangVM* vm)
|
|
{
|
|
double val = dlang_tonumber(vm);
|
|
dlang_pushnumber(vm, std::sin(val));
|
|
}
|
|
|
|
static void NativeMathCos(DlangVM* vm)
|
|
{
|
|
double val = dlang_tonumber(vm);
|
|
dlang_pushnumber(vm, std::cos(val));
|
|
}
|
|
|
|
thread_local static std::random_device rd;
|
|
thread_local static std::mt19937 gen(rd());
|
|
|
|
static void NativeMathSeed(DlangVM* vm)
|
|
{
|
|
double seedVal = dlang_tonumber(vm);
|
|
gen.seed(static_cast<unsigned int>(seedVal));
|
|
}
|
|
|
|
static void NativeMathRandom(DlangVM* vm)
|
|
{
|
|
double max = dlang_tonumber(vm);
|
|
double min = dlang_tonumber(vm);
|
|
|
|
std::uniform_real_distribution<double> dis(min, max);
|
|
dlang_pushnumber(vm, dis(gen));
|
|
}
|
|
|
|
inline void openlib_math(DlangVM* vm)
|
|
{
|
|
dlang_newtable(vm);
|
|
|
|
dlang_pushcfunction(vm, NativeMathAbs);
|
|
dlang_setfield(vm, "abs");
|
|
|
|
dlang_pushcfunction(vm, NativeMathFloor);
|
|
dlang_setfield(vm, "floor");
|
|
|
|
dlang_pushcfunction(vm, NativeMathCeil);
|
|
dlang_setfield(vm, "ceil");
|
|
|
|
dlang_pushcfunction(vm, NativeMathSqrt);
|
|
dlang_setfield(vm, "sqrt");
|
|
|
|
dlang_pushcfunction(vm, NativeMathPow);
|
|
dlang_setfield(vm, "pow");
|
|
|
|
dlang_pushcfunction(vm, NativeMathSin);
|
|
dlang_setfield(vm, "sin");
|
|
|
|
dlang_pushcfunction(vm, NativeMathCos);
|
|
dlang_setfield(vm, "cos");
|
|
|
|
dlang_pushcfunction(vm, NativeMathSeed);
|
|
dlang_setfield(vm, "seed");
|
|
|
|
dlang_pushcfunction(vm, NativeMathRandom);
|
|
dlang_setfield(vm, "random");
|
|
|
|
dlang_setglobal(vm, "math");
|
|
}
|
|
|
|
#endif |