File: ActorBase.h

package info (click to toggle)
jazz2-native 3.5.0-1
  • links: PTS, VCS
  • area: contrib
  • in suites:
  • size: 16,836 kB
  • sloc: cpp: 172,557; xml: 113; python: 36; makefile: 5; sh: 2
file content (481 lines) | stat: -rw-r--r-- 15,872 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#pragma once

#include "../EventType.h"
#include "../LightEmitter.h"
#include "../Resources.h"
#include "../Tiles/TileCollisionParams.h"

#include "../../nCine/Base/Task.h"
#include "../../nCine/Primitives/AABB.h"
#include "../../nCine/Audio/AudioBufferPlayer.h"
#include "../../nCine/Graphics/BaseSprite.h"
#include "../../nCine/Graphics/SceneNode.h"

#include <Base/TypeInfo.h>
#include <Containers/Function.h>
#include <Containers/StringView.h>
#include <IO/MemoryStream.h>

#ifndef DOXYGEN_GENERATING_OUTPUT
// If coroutines are not supported, load resources synchronously
#if defined(WITH_COROUTINES)
#	define async_return co_return
#	define async_await co_await
#else
#	define async_return return
#	define async_await
#endif
#endif

using namespace Death::Containers::Literals;
using namespace Jazz2::Resources;

namespace Jazz2
{
	class ILevelHandler;
	class LevelHandler;
}

namespace Jazz2::Rendering
{
	class LightingRenderer;
}

#if defined(WITH_MULTIPLAYER)
namespace Jazz2::Multiplayer
{
	class MpLevelHandler;
}
namespace Jazz2::UI::Multiplayer
{
	class MpInGameCanvasLayer;
}
#endif

namespace Jazz2::Actors
{
	class Player;

	/** @brief Flags that modify behaviour of @ref ActorBase, supports a bitwise combination of its member values */
	enum class ActorState {
		None = 0x00,

		/** @brief Actor is created from event map, this flag is used automatically by event system */
		IsCreatedFromEventMap = 0x01,
		/** @brief Actor is created by generator, this flag is used automatically by event system */
		IsFromGenerator = 0x02,

		/** @brief Actor should be illuminated */
		Illuminated = 0x04,

		/** @brief Actor should be created asynchronously, not to block main thread */
		Async = 0x08,

		/** @brief Mask of all instantiation flags that can be used in @ref ActorActivationDetails */
		InstantiationFlags = IsCreatedFromEventMap | IsFromGenerator | Illuminated | Async,

		/** @brief This flag is set automatically after call to @ref ActorBase::OnActivatedAsync() */
		Initialized = 0x0100,

		// Actor instance flags
		/** @brief Actor is invulnerable */
		IsInvulnerable = 0x0200,
		/** @brief Actor is standing on the ground and can jump */
		CanJump = 0x0400,
		/** @brief Actor can be frozen */
		CanBeFrozen = 0x0800,
		/** @brief Actor is facing left */
		IsFacingLeft = 0x1000,

		//Reserved = 0x2000,

		/** @brief Actor should be preserved when state is rolled back to checkpoint */
		PreserveOnRollback = 0x4000,

		// Collision flags
		/** @brief Collide with tiles */
		CollideWithTileset = 0x10000,
		/** @brief Collide with other non-solid actors, @ref ActorBase::OnHandleCollision() will be called for each collision */
		CollideWithOtherActors = 0x20000,
		/** @brief Collide with solid objects */
		CollideWithSolidObjects = 0x40000,
		/** @brief Don't add object to collision tree at all (cannot be changed during object lifetime) */
		ForceDisableCollisions = 0x80000,

		/** @brief Check collisions at the end of current frame, should be used if position or size changed */
		IsDirty = 0x100000,
		/** @brief Remove object at the end of current frame */
		IsDestroyed = 0x200000,

		/** @brief Apply gravitation */
		ApplyGravitation = 0x400000,
		/** @brief Marks object as solid, so other objects with @ref CollideWithSolidObjects will collide with it */
		IsSolidObject = 0x800000,
		/** @brief Check collisions only with hitbox */
		SkipPerPixelCollisions = 0x1000000,

		/** @brief Don't use full hitbox for collisions with tiles, also exclude upper part of hitbox when falling down */
		CollideWithTilesetReduced = 0x2000000,
		/** @brief Collide with other solid object only if it's above center of the other hitbox */
		CollideWithSolidObjectsBelow = 0x4000000,
		/** @brief Ignore solid collisions agains similar objects that have this flag */
		ExcludeSimilar = 0x8000000,
	};

	DEATH_ENUM_FLAGS(ActorState);

	/** @brief Description how to initialize an actor */
	struct ActorActivationDetails {
		/** @brief Current level handler */
		ILevelHandler* LevelHandler;
		/** @brief Position */
		Vector3i Pos;
		/** @brief Actor state */
		ActorState State;
		/** @brief Event type */
		EventType Type;
		/** @brief Event activation parameters */
		const std::uint8_t* Params;

		ActorActivationDetails(ILevelHandler* levelHandler, const Vector3i& pos, const std::uint8_t* params = nullptr)
			: LevelHandler(levelHandler), Pos(pos), State(ActorState::None), Type(EventType::Empty), Params(params)
		{
		}
	};

	/** @brief Move type, supports a bitwise combination of its member values */
	enum class MoveType {
		Absolute = 0x00,		/**< Move to absolute position */
		Relative = 0x01,		/**< Move to relative position */
		Force = 0x02			/**< Ignore all collision checks */
	};

	DEATH_ENUM_FLAGS(MoveType);

	/** @brief Actor renderer type */
	enum class ActorRendererType {
		Default,				/**< Default rendering */
		Outline,				/**< Draw outline around the sprite */
		WhiteMask,				/**< Draw all non-transparent pixels as white */
		PartialWhiteMask,		/**< Draw all non-transparent pixels as boosted shades of gray */
		FrozenMask				/**< Apply frozen effect to the sprite */
	};

	/** @brief Effect type of @ref ActorBase::CreateParticleDebrisOnPerish() */
	enum class ParticleDebrisEffect {
		Unknown,				/**< Unspecified */
		Standard,				/**< Standard */
		StandardInWater,		/**< Standard (in water) */
		Dissolve,				/**< Dissolve (for ghosts) */
		Frozen,					/**< Frozen (for breaking the ice) */
		Fire,					/**< Fire (for toasting) */
		Lightning				/**< Lightning (for electrocuting) */
	};

	/** @brief Base class of an object */
	class ActorBase : public std::enable_shared_from_this<ActorBase>
	{
		DEATH_RUNTIME_OBJECT();

		friend class Player;
		friend class Jazz2::LevelHandler;
		friend class Jazz2::Rendering::LightingRenderer;
#if defined(WITH_MULTIPLAYER)
		friend class Jazz2::Multiplayer::MpLevelHandler;
		friend class Jazz2::UI::Multiplayer::MpInGameCanvasLayer;
#endif

	public:
		ActorBase();
		virtual ~ActorBase();

		/** @brief Outer AABB hitbox */
		AABBf AABB;
		/** @brief Inner AABB hitbox */
		AABBf AABBInner;

		/** @brief Returns `true` if the object is currently facing left */
		bool IsFacingLeft() const;

		/** @brief Called after the object is created */
		Task<bool> OnActivated(const ActorActivationDetails& details);
		/** @brief Called when the object collides with another object */
		virtual bool OnHandleCollision(std::shared_ptr<ActorBase> other);
		/** @brief Called to check whether @p collider can cause damage to the object */
		virtual bool CanCauseDamage(ActorBase* collider);

		/** @brief Returns `true` if the object is invulnerable */
		bool IsInvulnerable();
		/** @brief Returns current health */
		std::int32_t GetHealth();
		/** @brief Sets current health */
		void SetHealth(std::int32_t value);
		/** @brief Returns maximum health */
		std::int32_t GetMaxHealth();
		/** @brief Decreases health by specified amount */
		void DecreaseHealth(std::int32_t amount = 1, ActorBase* collider = nullptr);

		/** @brief Moves the object */
		bool MoveInstantly(Vector2f pos, MoveType type, Tiles::TileCollisionParams& params);
		/** @overload */
		bool MoveInstantly(Vector2f pos, MoveType type)
		{
			Tiles::TileCollisionParams params = { Tiles::TileDestructType::None, _speed.Y >= 0.0f };
			return MoveInstantly(pos, type, params);
		}

		/** @brief Adds external force */
		void AddExternalForce(float x, float y);

		/** @brief Returns `true` if this object is colliding with a given object */
		bool IsCollidingWith(ActorBase* other);
		/** @brief Returns `true` if this object is colliding with a given AABB */
		bool IsCollidingWith(const AABBf& aabb);
		/** @brief Updates AABB for current position, rotation and animation frame */
		void UpdateAABB();

		/** @brief Returns current position */
		Vector2f GetPos() {
			return _pos;
		}

		/** @brief Returns current speed */
		Vector2f GetSpeed() {
			return _speed;
		}

		/** @brief Returns actor state */
		constexpr ActorState GetState() const noexcept {
			return _state;
		}

		/** @overload */
		constexpr bool GetState(ActorState flag) const noexcept {
			return (_state & flag) == flag;
		}

	protected:
		/** @brief Actor renderer */
		class ActorRenderer : public BaseSprite
		{
			friend class ActorBase;

		public:
			ActorRenderer(ActorBase* owner);

			/** @brief Whether the animation is paused */
			bool AnimPaused;
			/** @brief Frame configuration */
			Vector2i FrameConfiguration;
			/** @brief Frame dimensions */
			Vector2i FrameDimensions;
			/** @brief Animation loop mode */
			AnimationLoopMode LoopMode;
			/** @brief Frame offset */
			std::int32_t FirstFrame;
			/** @brief Frame count */
			std::int32_t FrameCount;
			/** @brief Animation duration (in normalized frames) */
			float AnimDuration;
			/** @brief Current animation progress */
			float AnimTime;
			/** @brief Current animation frame */
			std::int32_t CurrentFrame;
			/** @brief Hotspot */
			Vector2f Hotspot;

			/** @brief Initializes the renderer to the specified renderer type */
			void Initialize(ActorRendererType type);

			void OnUpdate(float timeMult) override;
			bool OnDraw(RenderQueue& renderQueue) override;

			/** @brief Returns `true` if animation is running */
			bool IsAnimationRunning();
			/** @brief Returns active renderer type */
			ActorRendererType GetRendererType() const;

		protected:
			void textureHasChanged(Texture* newTexture) override;

		private:
			ActorBase* _owner;
			ActorRendererType _rendererType;
			float _rendererTransition;

			void UpdateVisibleFrames();
			static std::int32_t NormalizeFrame(std::int32_t frame, std::int32_t min, std::int32_t max);
		};

		/** @{ @name Constants */

		/** @brief Alpha transparency threshold */
		static constexpr std::uint8_t AlphaThreshold = 40;
		/** @brief Step for collision checking */
		static constexpr float CollisionCheckStep = 0.5f;
		/** @brief Step for per-pixel collisions */
		static constexpr std::int32_t PerPixelCollisionStep = 3;
		/** @brief Maximum number of animation candidates */
		static constexpr std::int32_t AnimationCandidatesCount = 5;

		/** @} */

#ifndef DOXYGEN_GENERATING_OUTPUT
		// Hide these members from documentation before refactoring
		ILevelHandler* _levelHandler;

		Vector2f _pos;
		Vector2f _speed;
		Vector2f _externalForce;
		float _internalForceY;
		float _elasticity;
		float _friction;
		float _unstuckCooldown;
		float _frozenTimeLeft;
		std::int32_t _maxHealth;
		std::int32_t _health;

		Vector2i _originTile;
		float _spawnFrames;
		Metadata* _metadata;
		ActorRenderer _renderer;
		GraphicResource* _currentAnimation;
		GraphicResource* _currentTransition;
		bool _currentTransitionCancellable;
#endif

		/** @brief Sets internal parent node */
		void SetParent(SceneNode* parent);

		/** @brief Sets whether the object is facing left */
		void SetFacingLeft(bool value);

		/** @brief Called when the object is created and activated */
		virtual Task<bool> OnActivatedAsync(const ActorActivationDetails& details);
		/** @brief Called when corresponding tile should be deactivated */
		virtual bool OnTileDeactivated();

		/** @brief Called when the object is attached to an another object */
		virtual void OnAttach(ActorBase* parent);
		/** @brief Called when the object is detached from the previously attached object */
		virtual void OnDetach(ActorBase* parent);

		/** @brief Called when health of the object changed */
		virtual void OnHealthChanged(ActorBase* collider);
		/** @brief Called when the object has no health left and should perish */
		virtual bool OnPerish(ActorBase* collider);

		/** @brief Called every frame to update the object state */
		virtual void OnUpdate(float timeMult);
		/** @brief Called when the hitbox needs to be updated */
		virtual void OnUpdateHitbox();
		/** @brief Called when the object needs to be drawn */
		virtual bool OnDraw(RenderQueue& renderQueue);
		/** @brief Called when emitting lights */
		virtual void OnEmitLights(SmallVectorImpl<LightEmitter>& lights) { }
		/** @brief Called when the object hits a floor */
		virtual void OnHitFloor(float timeMult);
		/** @brief Called when the object hits a ceiling */
		virtual void OnHitCeiling(float timeMult);
		/** @brief Called when the object hits a wall */
		virtual void OnHitWall(float timeMult);

		/** @brief Called when an event is triggered */
		virtual void OnTriggeredEvent(EventType eventType, std::uint8_t* eventParams);

		/** @brief Performs standard movement behavior */
		void TryStandardMovement(float timeMult, Tiles::TileCollisionParams& params);
		/** @brief Updates hitbox to a given size */
		void UpdateHitbox(std::int32_t w, std::int32_t h);
		/** @brief Updates frozen state of the object */
		void UpdateFrozenState(float timeMult);
		/** @brief Handles change of frozen state after collision with other object */
		void HandleFrozenStateChange(ActorBase* shot);

		/** @brief Creates a particle debris from a sprite when the object is going to perish */
		void CreateParticleDebrisOnPerish(ActorBase* collider);
		/** @overload */
		void CreateParticleDebrisOnPerish(ParticleDebrisEffect effect, Vector2f speed);
		/** @brief Creates a sprite debris */
		void CreateSpriteDebris(AnimState state, std::int32_t count);
		/** @brief Returns scale of ice shrapnels */
		virtual float GetIceShrapnelScale() const;

		/** @brief Plays a sound effect for the object */
		std::shared_ptr<AudioBufferPlayer> PlaySfx(StringView identifier, float gain = 1.0f, float pitch = 1.0f);
		/** @brief Sets an animation of the object */
		bool SetAnimation(AnimState state, bool skipAnimation = false);
		/** @brief Sets a transition animation of the object */
		bool SetTransition(AnimState state, bool cancellable, Function<void()>&& callback = {});
		/** @brief Cancels a cancellable transition */
		void CancelTransition();
		/** @brief Cancels any transition */
		void ForceCancelTransition();
		/** @brief Called when an animation started */
		virtual void OnAnimationStarted();
		/** @brief Called when an animation finished */
		virtual void OnAnimationFinished();

		/** @brief Called when the object receives a network packet */
		virtual void OnPacketReceived(MemoryStream& packet);
		/** @brief Sends a packet to the other side of a non-local session */
		void SendPacket(ArrayView<const std::uint8_t> data);

		/** @brief Preloads specified metadata and its linked assets to cache */
		static void PreloadMetadataAsync(StringView path);
		/** @brief Loads specified metadata and its linked assets */
		void RequestMetadata(StringView path);

		/** @brief Loads specified metadata and its linked assets asynchronously if supported */
#if defined(WITH_COROUTINES)
		auto RequestMetadataAsync(StringView path)
		{
			struct awaitable {
				ActorBase* actor;
				const StringView& path;

				bool await_ready() {
					return false;
				}
				void await_suspend(std::coroutine_handle<> handle) {
					// TODO: implement async
					auto metadata = ContentResolver::Get().RequestMetadata(path);
					actor->_metadata = metadata;
					handle();
				}
				void await_resume() { }
			};
			return awaitable{this, path};
		}
#else
		void RequestMetadataAsync(StringView path);
#endif

		/** @brief Sets actor state */
		constexpr void SetState(ActorState flags) noexcept {
			_state = flags;
		}

		/** @overload */
		constexpr void SetState(ActorState flag, bool value) noexcept {
			if (value) {
				_state = _state | flag;
			} else {
				_state = _state & (~flag);
			}
		}

	private:
		ActorBase(const ActorBase&) = delete;
		ActorBase& operator=(const ActorBase&) = delete;

		std::int32_t _collisionProxyID;
		ActorState _state;
		Function<void()> _currentTransitionCallback;

		bool IsCollidingWithAngled(ActorBase* other);
		bool IsCollidingWithAngled(const AABBf& aabb);

		void RefreshAnimation(bool skipAnimation = false);
	};
}