Skip to content

Commit

Permalink
implement nifty counter for Controller
Browse files Browse the repository at this point in the history
  • Loading branch information
ion098 committed May 28, 2024
1 parent 75eb85e commit af8e66d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
13 changes: 11 additions & 2 deletions include/gamepad/controller.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ class Button {
};

class Controller {
friend struct ControllerInit;
public:
explicit Controller(pros::controller_id_e_t id): controller(id) {}
/**
* Updates the state of the gamepad (all joysticks and buttons), and also runs
* any registered handlers.
Expand All @@ -70,8 +70,17 @@ class Controller {
X{}, B{}, Y{}, A{};
float LeftX = 0, LeftY = 0, RightX = 0, RightY = 0;
private:
explicit Controller(pros::controller_id_e_t id): controller(id) {}
static Button Controller::* button_to_ptr(pros::controller_digital_e_t button);
void updateButton(pros::controller_digital_e_t button_id);
pros::Controller controller;
}; // namespace Gamepad
};

static struct ControllerInit {
ControllerInit();
~ControllerInit();
} _controllerInit;

extern Controller& master;
extern Controller& partner;
}
27 changes: 27 additions & 0 deletions src/gamepad/controller.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,35 @@
#include "gamepad/controller.hpp"
#include "gamepad/todo.hpp"
#include "pros/misc.h"

#include <new>
#include <array>
#include <cstddef>

namespace Gamepad {

static int nifty_counter; // zero initialized at load time
static std::array<std::byte, sizeof(Controller)> master_buf alignas(Controller);
Controller& master = *reinterpret_cast<Controller*> (&*master_buf.begin());
static std::array<std::byte, sizeof(Controller)> partner_buf alignas(Controller);
Controller& partner = *reinterpret_cast<Controller*> (&*partner_buf.begin());

ControllerInit::ControllerInit() {
if(nifty_counter == 0) {
new (&*master_buf.begin()) Controller(pros::E_CONTROLLER_MASTER);
new (&*partner_buf.begin()) Controller(pros::E_CONTROLLER_PARTNER);
}
++nifty_counter;
}

ControllerInit::~ControllerInit() {
--nifty_counter;
if(nifty_counter == 0) {
master.~Controller();
partner.~Controller();
}
}

uint32_t Button::onPress(std::function<void(void)> func) {
return this->onPressEvent.add_listener(std::move(func));
}
Expand Down

0 comments on commit af8e66d

Please sign in to comment.