less trivial C++ interop

This commit is contained in:
2024-08-04 21:50:08 +10:00
parent 60e9c3f4ea
commit f5faf18e54
7 changed files with 126 additions and 17 deletions

View File

@ -1,4 +1,4 @@
add_library(CppBackend STATIC backend.h backend.cpp)
add_library(CppBackend STATIC ball.hpp ball.cpp)
set_property(TARGET CppBackend PROPERTY Swift_MODULE_NAME "CppBackend")
set_property(TARGET CppBackend PROPERTY CXX_STANDARD 20)

View File

@ -1,7 +0,0 @@
#include "backend.h"
#include <iostream>
void backend_init() {
std::cout << "Hello World" << std::endl;
}

View File

@ -1,3 +0,0 @@
#pragma once
void backend_init();

View File

@ -0,0 +1,41 @@
#include "ball.hpp"
#include <cmath>
Ball::Ball(vec2f pos, float angle, float ballSize) noexcept :
_position(pos),
_velocity(simd::make<vec2f>(
std::cos(angle * M_PI * 2.0f),
-std::sin(angle * M_PI * 2.0f)
)),
_size(ballSize) {
}
void Ball::update(float deltaTime) noexcept {
_position += _velocity * speed * deltaTime;
if (_position.x < _size) {
_velocity.x = -_velocity.x;
_position.x = _size;
} else if (_position.x > worldSize - _size) {
_velocity.x = -_velocity.x;
_position.x = worldSize - _size;
}
if (_position.y < _size) {
_velocity.y = -_velocity.y;
_position.y = _size;
} else if (_position.y > worldSize - _size) {
_velocity.y = -_velocity.y;
_position.y = worldSize - _size;
}
}
void BallWorld::add(Ball::vec2f pos, float angle, float ballSize) noexcept {
balls.emplace_back(Ball{ pos, angle, ballSize });
}
void BallWorld::update(float deltaTime) noexcept {
for (auto& ball : balls) {
ball.update(deltaTime);
}
}

View File

@ -0,0 +1,39 @@
#pragma once
#include <simd/simd.h>
#include <vector>
struct Ball {
using vec2f = simd::float2;
private:
constexpr static float speed = 80.0f;
constexpr static float worldSize = 512.0f;
vec2f _position, _velocity;
float _size;
public:
Ball(vec2f pos, float angle, float ballSize) noexcept;
virtual ~Ball() noexcept = default;
void update(float deltaTime) noexcept;
[[nodiscard]] constexpr const vec2f& position() const noexcept {
return _position;
}
[[nodiscard]] constexpr const vec2f& velocity() const noexcept {
return _velocity;
}
[[nodiscard]] constexpr const float size() const noexcept {
return _size;
}
};
struct BallWorld {
std::vector<Ball> balls;
void add(Ball::vec2f pos, float angle, float ballSize) noexcept;
void update(float deltaTime) noexcept;
};

View File

@ -1,3 +1,3 @@
module CppBackend {
header "backend.h"
header "ball.hpp"
}