vkmEngine 1.0.15
A C++ game engine · vkmengine.com
Loading...
Searching...
No Matches
behavior.h
1#pragma once
2
3#include <exception>
4#include <functional>
5#include <memory>
6#include <string>
7#include <string_view>
8#include <type_traits>
9#include <utility>
10#include <vector>
11
12#include "logger.h"
13
14#include "core/reflect.h"
15#include "debug/engine_error_log.h"
16
17#include "ecs/entity.h"
18#include "ecs/scene.h"
19#include "ecs/component/core/name.h"
20#include "ecs/hierarchy_operations.h"
21#include "platform/window/window_manager.h"
22#include "system/render/render_settings.h"
23#include "core/event/event_bus.h"
24#include "net/net_session.h"
25#include "system/physics/physics_events.h"
26#include "platform/input/input_map.h"
27#include "system/ui/screen_view.h"
28
29namespace Vkm::Engine {
30
31class Behavior;
32class HostChrome;
33class Clock;
34class ResourceManager;
35class BehaviorSystem;
37struct OceanData;
38
47 Scene* scene = nullptr;
48 ResourceManager* resources = nullptr;
49
52
53 EventBus* events = nullptr;
54 InputMap* input = nullptr;
55 NetSession* net = nullptr;
56 Clock* clock = nullptr;
57 RenderSettings* render = nullptr;
58 const RenderSettings* projectRender = nullptr;
59 const HostChrome* chrome = nullptr;
60 std::vector<EntityId>* pendingDestroy = nullptr;
61 std::string* pendingSceneLoad = nullptr;
62 bool* pendingRestart = nullptr;
63 const OceanData* ocean = nullptr;
64};
65
66namespace detail {
67
73template<typename Fn>
74struct ListenerEvent : ListenerEvent<decltype(&Fn::operator())> {};
75
76template<typename C, typename R, typename A>
77struct ListenerEvent<R (C::*)(A) const> {
78 using type = std::decay_t<A>;
79};
80
81template<typename C, typename R, typename A>
82struct ListenerEvent<R (C::*)(A)> {
83 using type = std::decay_t<A>;
84};
85
86template<typename R, typename A>
87struct ListenerEvent<R (*)(A)> {
88 using type = std::decay_t<A>;
89};
90
99template<typename EventT, typename Fn>
100struct SubscribedEvent {
101 using type = EventT;
102};
103
104template<typename Fn>
105struct SubscribedEvent<void, Fn> {
106 using type = typename ListenerEvent<Fn>::type;
107};
108
109} // namespace detail
110
119Behavior* findBehaviorNamed(Scene& scene, EntityId entity, std::string_view typeName);
120
122const Behavior* findBehaviorNamed(const Scene& scene, EntityId entity, std::string_view typeName);
123
131EntityId findEntityWithBehaviorNamed(Scene& scene, std::string_view typeName);
132
143template<typename T>
144T* findBehavior(Scene& scene, EntityId entity) {
145 return static_cast<T*>(findBehaviorNamed(scene, entity, Reflect::Traits<T>::NAME));
146}
147
149template<typename T>
150const T* findBehavior(const Scene& scene, EntityId entity) {
151 return static_cast<const T*>(findBehaviorNamed(scene, entity, Reflect::Traits<T>::NAME));
152}
153
163template<typename T>
164EntityId findEntityWithBehavior(Scene& scene) {
165 return findEntityWithBehaviorNamed(scene, Reflect::Traits<T>::NAME);
166}
167
180template<typename T>
181T* findBehavior(Scene& scene) {
182 return findBehavior<T>(scene, findEntityWithBehavior<T>(scene));
183}
184
192class Behavior {
193 public:
194 Behavior() = default;
195 virtual ~Behavior() { clearSubscriptions(); }
196
197 Behavior(const Behavior& other) = delete;
198 Behavior& operator=(const Behavior& other) = delete;
199
200 Behavior(Behavior && other) = delete;
201 Behavior& operator=(Behavior && other) = delete;
202
203 public:
209 virtual void onStart() {}
210
219 virtual void onUpdate(float dt) {}
220
229 virtual void onRealtimeUpdate(float dt) {}
230
236 virtual void onFixedUpdate(float dt) {}
237
249 virtual void onCollisionEnter(const Collision& hit) {}
250
258 virtual void onCollisionStay(const Collision& hit) {}
259
268 virtual void onCollisionExit(const Collision& hit) {}
269
275 virtual void onTriggerEnter(EntityId other) {}
276
282 virtual void onTriggerStay(EntityId other) {}
283
289 virtual void onTriggerExit(EntityId other) {}
290
294 virtual void onDestroy() {}
295
301 virtual const char* typeName() const = 0;
302
308 virtual void visitFields(BehaviorFieldVisitor& visitor) {}
309
315 virtual std::unique_ptr<Behavior> clone() const = 0;
316
324 EntityId entity() const { return m_entity; }
325
326 protected:
327
338 template<typename T>
339 T* tryGet() { return m_ctx->scene->tryGet<T>(m_entity); }
340
342 template<typename T>
343 const T* tryGet() const { return m_ctx->scene->tryGet<T>(m_entity); }
344
351 template<typename T>
352 T& get() { return m_ctx->scene->get<T>(m_entity); }
353
355 template<typename T>
356 const T& get() const { return m_ctx->scene->get<T>(m_entity); }
357
364 template<typename T>
365 bool has() const { return m_ctx->scene->has<T>(m_entity); }
366
374 template<typename T>
375 auto& add(T && component) {
376 return m_ctx->scene->add(m_entity, std::forward<T>(component));
377 }
378
385 template<typename T>
386 T* findBehavior() { return findBehavior<T>(m_entity); }
387
394 template<typename T>
395 T* findInScene() { return ::Vkm::Engine::findBehavior<T>(*m_ctx->scene); }
396
410 template<typename T>
411 T* findBehavior(EntityId other) { return Vkm::Engine::findBehavior<T>(*m_ctx->scene, other); }
412
421 template<typename T>
422 static T* findBehavior(Scene& world, EntityId entity) {
423 return Vkm::Engine::findBehavior<T>(world, entity);
424 }
425
427 template<typename T>
428 static const T* findBehavior(const Scene& world, EntityId entity) {
429 return Vkm::Engine::findBehavior<T>(world, entity);
430 }
431
437 Scene& scene() { return *m_ctx->scene; }
438
444 ResourceManager& resources() { return *m_ctx->resources; }
445
453 EventSender events() { return EventSender(*m_ctx->events); }
454
460 RenderSettings& render() { return *m_ctx->render; }
461
470 const RenderSettings& projectRender() const { return *m_ctx->projectRender; }
471
479 InputMap& input() { return *m_ctx->input; }
480
486 NetSession& net() { return *m_ctx->net; }
487
496 Clock& clock() { return *m_ctx->clock; }
497 const Clock& clock() const { return *m_ctx->clock; }
498
504 WindowManager* window() { return m_ctx->window; }
505
516
526 const OceanData* ocean() const;
527
533 std::optional<Math::Ray> pointerRay() const;
534
544 bool isSimulated() const {
545 return m_ctx->net->simulates(*m_ctx->scene, m_entity);
546 }
547
556 bool isMine() const {
557 return m_ctx->net->isMine(m_entity);
558 }
559
568 bool isReplaying() const { return m_ctx->net->replaying(); }
569
579 const InputCommand& command() const {
580 return m_ctx->net->commandFor(m_entity);
581 }
582
592 return m_ctx->scene->createEntity();
593 }
594
601 EntityId spawn(const char* name) {
602 const EntityId entity = spawn();
603 m_ctx->scene->add(entity, makeName(name));
604 return entity;
605 }
606
616 EntityId spawn(const char* name, EntityId parent) {
617 const EntityId entity = spawn(name);
618 HierarchyOperations::setParent(*m_ctx->scene, entity, parent);
619 return entity;
620 }
621
630 void destroy(EntityId target) { m_ctx->pendingDestroy->push_back(target); }
631
635 void destroy() { destroy(m_entity); }
636
646 void loadScene(const std::string& scenePath) { *m_ctx->pendingSceneLoad = scenePath; }
647
655 void restartScene() { *m_ctx->pendingRestart = true; }
656
670 template<typename EventT = void, typename Fn>
671 void subscribe(Fn&& callback) {
672 using Event = typename detail::SubscribedEvent<EventT, std::decay_t<Fn>>::type;
673 std::function<void(const Event&)> listener = std::forward<Fn>(callback);
674 // Null only before binding, so this is a subscribe from a constructor.
675 if (!m_ctx) {
676 LOG_ERROR(
677 "A behavior subscribed before it started; "
678 "subscribe() belongs in onStart(), not the constructor"
679 );
680 return;
681 }
682 // Guarded, or a throw would unwind through the bus and out of the frame.
683 EventBus* events = m_ctx->events;
684 const ListenerId id = events->subscribe<Event>(
685 [this, listener = std::move(listener)](const Event& event) {
686 runGuarded("event listener", [&] { listener(event); });
687 }
688 );
689 m_subscriptions.push_back([events, id]() { events->unsubscribe<Event>(id); });
690 }
691
692 private:
693 friend class BehaviorSystem;
694
702 template<typename Fn>
703 bool runGuarded(const char* hookName, Fn&& fn) {
704 try {
705 fn();
706 return false;
707 } catch (const std::exception& e) {
708 reportError("Behavior", hookLabel(hookName), e.what());
709 } catch (...) {
710 reportError("Behavior", hookLabel(hookName), "non-std exception");
711 }
712 return true;
713 }
714
721 std::string hookLabel(const char* hookName) const {
722 return std::string(typeName()) + " / " + hookName;
723 }
724
731 void bindContext(EntityId entity, BehaviorContext& context) {
732 m_entity = entity;
733 m_ctx = &context;
734 }
735
742 void clearSubscriptions() {
743 for (auto& unsubscribe : m_subscriptions) unsubscribe();
744 m_subscriptions.clear();
745 }
746
747 private:
748 EntityId m_entity{};
749 BehaviorContext* m_ctx = nullptr;
750
751 std::vector<std::function<void()>> m_subscriptions;
752 bool m_started = false;
753 bool m_disabled = false;
754};
755
756} // namespace Vkm::Engine
Type-erased visitor over a behavior's reflected authoring fields.
Definition behavior_field_visitor.h:23
Drives the lifecycle of every entity's ScriptComponent behaviors.
Definition behavior_system.h:30
Base class for native C++ gameplay behaviors.
Definition behavior.h:192
const T & get() const
This entity's T, which it must have.
Definition behavior.h:356
InputMap & input()
Named input actions, for the frame queries and to define bindings.
Definition behavior.h:479
void restartScene()
Start the scene being played over: the file loadScene last loaded, else the scene the host began play...
Definition behavior.h:655
WindowManager * window()
The window, or null on a host that draws nothing, such as a dedicated server.
Definition behavior.h:504
virtual void onTriggerStay(EntityId other)
Called on each later tick other is still inside, on onCollisionStay's terms.
Definition behavior.h:282
const InputCommand & command() const
The input driving this entity on the tick now running.
Definition behavior.h:579
T * findInScene()
The scene's behavior of type T, as findBehavior(Scene&) finds it.
Definition behavior.h:395
std::optional< Math::Ray > pointerRay() const
The ray from the camera through the cursor.
T * findBehavior(EntityId other)
other's behavior of type T, or null when it has none.
Definition behavior.h:411
T * findBehavior()
This entity's behavior of type T, or null when it has none.
Definition behavior.h:386
virtual void onUpdate(float dt)
Called every variable-step frame on which simulation time advanced.
Definition behavior.h:219
const T * tryGet() const
This entity's T, or null when it has none.
Definition behavior.h:343
NetSession & net()
The wire, or an offline session that answers as though local.
Definition behavior.h:486
virtual const char * typeName() const =0
Stable type name, identical to this type's BehaviorRegistry key; serialization uses it.
void destroy()
Destroy this behavior's own entity and its subtree, deferred likewise.
Definition behavior.h:635
virtual std::unique_ptr< Behavior > clone() const =0
Deep copy for entity duplication; authored fields only, the context is rebound.
Clock & clock()
Real and simulation time, and the play state behind them.
Definition behavior.h:496
bool isMine() const
Whether this entity belongs to the player at this end.
Definition behavior.h:556
static T * findBehavior(Scene &world, EntityId entity)
The free findBehavior, which the member overloads would otherwise hide.
Definition behavior.h:422
static const T * findBehavior(const Scene &world, EntityId entity)
The free findBehavior, which the member overloads would otherwise hide.
Definition behavior.h:428
virtual void onCollisionEnter(const Collision &hit)
Called on the first tick this entity touches another, in a resolved (non-trigger) contact.
Definition behavior.h:249
virtual void onDestroy()
Called on entity removal, and when the session ends (see BehaviorSystem::endSession).
Definition behavior.h:294
virtual void onFixedUpdate(float dt)
Called on each fixed-step tick; fed from simulation time, so pause and time-scale apply.
Definition behavior.h:236
bool isReplaying() const
Whether this tick already happened and is being run again.
Definition behavior.h:568
EntityId spawn(const char *name, EntityId parent)
Create an entity carrying name, parented under parent.
Definition behavior.h:616
virtual void onRealtimeUpdate(float dt)
Called every frame on real time, paused or not.
Definition behavior.h:229
virtual void onTriggerExit(EntityId other)
Called on the first tick other no longer overlaps, on onCollisionExit's terms.
Definition behavior.h:289
void loadScene(const std::string &scenePath)
Load scenePath, replacing everything currently in the scene.
Definition behavior.h:646
bool isSimulated() const
Whether this end decides what happens to this entity.
Definition behavior.h:544
virtual void onCollisionStay(const Collision &hit)
Called on each later tick the contact lasts.
Definition behavior.h:258
ResourceManager & resources()
The assets this session holds, to look one up or add one.
Definition behavior.h:444
virtual void onCollisionExit(const Collision &hit)
Called on the first tick the contact is over.
Definition behavior.h:268
void subscribe(Fn &&callback)
Listen for an event until the behavior is destroyed or the session ends.
Definition behavior.h:671
const OceanData * ocean() const
The scene's sea at this moment: the tick's in onFixedUpdate, the frame's in onUpdate (OceanSystem).
bool has() const
Whether this entity carries a T.
Definition behavior.h:365
virtual void onStart()
Called on the first simulation tick this instance runs in play mode.
Definition behavior.h:209
EventSender events()
The event bus's sending half, to emit or enqueue on.
Definition behavior.h:453
T & get()
This entity's T, which it must have.
Definition behavior.h:352
const RenderSettings & projectRender() const
The project's render settings, which render() started from.
Definition behavior.h:470
virtual void onTriggerEnter(EntityId other)
Called on the first tick other overlaps this entity's trigger.
Definition behavior.h:275
EntityId entity() const
The entity this behavior is attached to.
Definition behavior.h:324
T * tryGet()
This entity's T, or null when it has none.
Definition behavior.h:339
ScreenView screen() const
The 3D view through the scene's active camera: the pointer's ray into the world, a point of the world...
auto & add(T &&component)
Give this entity a T.
Definition behavior.h:375
EntityId spawn(const char *name)
Create an entity carrying name.
Definition behavior.h:601
RenderSettings & render()
The quality settings the frame is drawn at; a write lands on the next frame.
Definition behavior.h:460
void destroy(EntityId target)
Destroy entity and its subtree, firing onDestroy.
Definition behavior.h:630
Scene & scene()
The scene this behavior's entity lives in.
Definition behavior.h:437
virtual void visitFields(BehaviorFieldVisitor &visitor)
Visit the behavior's reflected authoring fields; ReflectedBehavior generates it.
Definition behavior.h:308
EntityId spawn()
Create a new, empty entity; add components to it through scene().
Definition behavior.h:591
The engine's frame clock: real + simulation time and the fixed-step accumulator.
Definition clock.h:18
Typed pub/sub event dispatcher.
Definition event_bus.h:22
The sending half of an EventBus: emit and enqueue, and no subscribe.
Definition event_bus.h:148
What an authoring host tells the engine about the frame it draws over.
Definition host_chrome.h:18
Named actions resolved from physical bindings, sampled once per frame.
Definition input_map.h:79
One end of a game, whether it is the authority or a guest.
Definition net_session.h:118
Type-erased resource registry with typed handles and generational lifetimes.
Definition resource_manager.h:46
Central registry managing entities and an open set of component types.
Definition scene.h:29
The 3D view a game draws through: where it sits in the window, and the scene's active camera filling ...
Definition screen_view.h:26
Owns the application's window, its WindowSurface, input, and frame limiting.
Definition window_manager.h:69
Everything gameplay code may reach, bundled behind one pointer.
Definition behavior.h:46
const HostChrome * chrome
Where in the window the scene is drawn.
Definition behavior.h:59
const OceanData * ocean
OceanSystem's, this tick's or frame's.
Definition behavior.h:63
WindowManager * window
The only nullable field: a host that draws nothing has none.
Definition behavior.h:51
One entity's view of a CollisionEvent, as its behaviors' collision hooks receive it.
Definition physics_events.h:47
Names one entity of one Scene, for as long as that slot holds it.
Definition entity.h:23
Everything one simulation tick was told to do, as a value.
Definition input_command.h:28
The scene's sea at the moment being computed (OceanSystem): its waves, its ripples and its look - wha...
Definition ocean_data.h:13
The reflection trait, specialised per type by VKM_REFLECT_BEGIN / VKM_F / VKM_REFLECT_END.
Definition reflect.h:41
Editable render tuning: pass toggles + per-effect parameters.
Definition render_settings.h:101