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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
// Copyright Epic Games, Inc. All Rights Reserved.

#include "ShooterTestAsyncMessageTestActor.h"

#include "AudioThread.h"
#include "Async/Async.h"
#include "AsyncMessageBindingOptions.h"
#include "AsyncGameplayMessageSystem.h"
#include "AsyncMessageWorldSubsystem.h"
#include "AsyncMessageSystemLogs.h"
#include "Components/StaticMeshComponent.h"
#include "NativeGameplayTags.h"
#include "TimerManager.h"

UE_DEFINE_GAMEPLAY_TAG(Message_Tag_Red, "Change.Color.Red")
UE_DEFINE_GAMEPLAY_TAG(Message_Tag_Green, "Change.Color.Green")
UE_DEFINE_GAMEPLAY_TAG(Message_Tag_Blue, "Change.Color.Blue")
UE_DEFINE_GAMEPLAY_TAG(Message_Tag_Async_Test, "Async.Message.Test")
UE_DEFINE_GAMEPLAY_TAG(Message_Tag_Test_Heavy, "Tests.HeavyMessage")
UE_DEFINE_GAMEPLAY_TAG(Message_Tag_Test_HeavySubmessage, "Tests.HeavyMessage.SubMessage")

static FAsyncMessageId Message_ChangeColor_Red = { Message_Tag_Red };
static FAsyncMessageId Message_ChangeColor_Green = { Message_Tag_Green};
static FAsyncMessageId Message_ChangeColor_Blue = { Message_Tag_Blue };

static FAsyncMessageId Message_Async_Test = { Message_Tag_Async_Test };

///////////////////////////////////////////////////////////////
// AAsyncColorChangeBroadcastActor

AAsyncColorChangeBroadcastActor::AAsyncColorChangeBroadcastActor(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	ColorMessageToBroadcast = Message_ChangeColor_Red;
}

void AAsyncColorChangeBroadcastActor::BeginPlay()

{
	Super::BeginPlay();
	
	SpawnBackgroundTask();

	SpawnGameplayTagBroadcaster();
}

void AAsyncColorChangeBroadcastActor::SpawnBackgroundTask()

{	
	TWeakObjectPtr<AAsyncColorChangeBroadcastActor> WeakThis(this);

	// Queue a message from a non-game thread, a normal thread from the task pool in this case
	AsyncTask(ENamedThreads::AnyNormalThreadNormalTask, [WeakThis]()
	{
		if (!WeakThis.IsValid())
		{ 
			return;
		}

		if (TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(WeakThis->GetWorld()))
		{
			// Queue a color change message
			Sys.Get()->QueueMessageForBroadcast(WeakThis->ColorMessageToBroadcast, TStructView<FColorChangingMessage>(WeakThis->ColorChangeData));
		}

		WeakThis->NumBroadcasts++;
	});

	// Set up a timer to spawn a new background task every second
	GetWorld()->GetTimerManager().SetTimer(StartBackgroundTaskTimerHandle,
		FTimerDelegate::CreateWeakLambda(this, [this]()
			{
				SpawnBackgroundTask();
			}), 1.0f, false, ColorMessageBroadcastFrequency);
}

void AAsyncColorChangeBroadcastActor::SpawnGameplayTagBroadcaster()

{
	if (!GameplayTagToBroadcastA.IsValid() && !GameplayTagToBroadcastB.IsValid())
	{
		return;
	}
	
	TWeakObjectPtr<UWorld> WeakWorld = GetWorld();
	TWeakObjectPtr<AAsyncColorChangeBroadcastActor> WeakThis = this;
	
	// Set up a timer to spawn a new background task. This will queue the message on the game thread
	GetWorld()->GetTimerManager().SetTimer(GameplayTagSpawner,
		FTimerDelegate::CreateWeakLambda(this, [WeakWorld, WeakThis]()
		{
			if (!WeakThis.IsValid())
			{
				return;
			}
			
			// Queue the gameplay tag message a for broadcast
			if (TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(WeakWorld.Get()))
			{
				if (WeakThis->GameplayTagToBroadcastA.IsValid())
				{
					Sys->QueueMessageForBroadcast(WeakThis->GameplayTagToBroadcastA);	
				}

				if (WeakThis->GameplayTagToBroadcastB.IsValid())
				{
					Sys->QueueMessageForBroadcast(WeakThis->GameplayTagToBroadcastB);
				}
			}
		}), 1.0f, true, GameplayTagBroadcastFrequency);
}

///////////////////////////////////////////////////////////////
// AColorChangingTestListener

AColorChangingTestListener::AColorChangingTestListener(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ColorChangingMesh"));
	SetRootComponent(MeshComp);
	
	// We will be overriding the materials on this mesh to change their color, so make some dynamic instances of the material
	for (int32 MatIdx = 0; MatIdx < MeshComp->GetNumMaterials(); ++MatIdx)
	{
		MeshComp->CreateDynamicMaterialInstance(MatIdx);
	}
}

void AColorChangingTestListener::BeginPlay()

{
	Super::BeginPlay();
	
	if (TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(GetWorld()))
	{
		// Listen to ALL color messages
		BoundHandle_ColorParent = Sys->BindListener(
			Message_ChangeColor_Red.GetParentMessageId(),
			TWeakObjectPtr<AColorChangingTestListener>(this),
			&ThisClass::HandleAnyColorChange);
	}

	if (bShouldSpawnTaskOnOtherThread)
	{
		SetupNamedThreadListener();
	}
	
	PreviousColorBoundTo = FMath::RandRange(0, 2);
	
	SetupColorListener();
}

void AColorChangingTestListener::EndPlay(const EEndPlayReason::Type EndPlayReason)

{
	Super::EndPlay(EndPlayReason);

	ResetListenerToColor();

	if (TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(GetWorld()))
	{
		Sys->UnbindListener(BoundHandle_ColorParent);
	}
}

void AColorChangingTestListener::SetupColorListener()

{
	if (TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(GetWorld()))
	{
		const FAsyncMessageId MessageToListenFor = GetColorChangeToListenTo();

		FAsyncMessageBindingOptions Opts = {};

		// Listen to the color messages
		BoundHandle_Color = Sys->BindListener(
			MessageToListenFor,
			TWeakObjectPtr<AColorChangingTestListener>(this),
			&ThisClass::HandleColorChange,
			Opts);
	}
}

void AColorChangingTestListener::ResetListenerToColor()

{
	if (TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(GetWorld()))
	{
		Sys->UnbindListener(BoundHandle_Color);
		BoundHandle_Color = FAsyncMessageHandle::Invalid;
	}
}

void AColorChangingTestListener::SetupNamedThreadListener()

{
	check(bShouldSpawnTaskOnOtherThread);

	// We want to receive our event on the RHI thread
	FAsyncMessageBindingOptions Opts = {};
	Opts.SetNamedThreads(ENamedThreads::RHIThread);

	if (TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(GetWorld()))
	{
		Sys->BindListener(Message_Async_Test, [](const FAsyncMessage& Message)
		{
			// Ensure that we are actually geting our message on the thread we have requested to
			const uint32 CurrentThread = FPlatformTLS::GetCurrentThreadId();
			ensure(CurrentThread == Message.GetThreadQueuedFromThreadId());
			
			UE_LOG(LogAsyncMessageSystem, Verbose, TEXT("Successfully received message on RHI thread"));
		}, Opts);
	}

	// Wait 5 seconds, and then spawn an async task on the background thread to queue the message
	const float NextDelay = 5.0f;

	TWeakObjectPtr<UWorld> WeakWorld = GetWorld();

	// Set up a timer to spawn a new background task every second
	GetWorld()->GetTimerManager().SetTimer(BackgroundQueueMessageHandle,
		FTimerDelegate::CreateWeakLambda(this, [WeakWorld]()
			{
				// Spawn an async task to queue an message, on a background thread
				AsyncTask(ENamedThreads::RHIThread, [WeakWorld]()
				{
					if (TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(WeakWorld.Get()))
					{
						Sys->QueueMessageForBroadcast(Message_Async_Test);
					}
				});
			
				// loop every 1 second
			}), 1.0f, true, NextDelay);
}

void AColorChangingTestListener::HandleColorChange(const FAsyncMessage& Message)

{
	TRACE_CPUPROFILER_EVENT_SCOPE(AColorChangingTestListener::HandleColorChange);

	ensure(IsInGameThread() || IsInParallelGameThread());
	
	// Some specific color change here
	const FColorChangingMessage* Data = Message.GetPayloadData<const FColorChangingMessage>();
	if (!Data)
	{
		ensure(false);
		return;
	}

	// Change the dynamic material param colors
	FLinearColor Col = Data->DesiredColorToChange;
	MeshComp->SetColorParameterValueOnMaterials(MaterialColorParamName, Col);	
	
	// If we are listening for a specific message already, don't attempt to rebind
	if (OverrideMessageBinding.IsValid())
	{
		return;
	}
	
	// Stop listening for the color that we just got
	ResetListenerToColor();

	// And start listening to a new fancy color message
	SetupColorListener();
}

void AColorChangingTestListener::HandleAnyColorChange(const FAsyncMessage& Message)

{
	TRACE_CPUPROFILER_EVENT_SCOPE(AColorChangingTestListener::HandleAnyColorChange);
	
	ensure(IsInGameThread() || IsInParallelGameThread());

	const FColorChangingMessage* Data = Message.GetPayloadData<const FColorChangingMessage>();
	if (!Data)
	{
		ensure(false);
		return;
	}

	const uint32 MyThread = FPlatformTLS::GetCurrentThreadId();

	// Any time there is a color change, rotate the actor a bit	
	AddActorLocalRotation(FRotator(0.0, 0.0, 10.0));
}

const FAsyncMessageId AColorChangingTestListener::GetColorChangeToListenTo()

{
	// If you have specified a specific color to listen for let you do so here
	if (OverrideMessageBinding.IsValid())
	{
		return OverrideMessageBinding;
	}
	
	// Increment to the next color
	PreviousColorBoundTo = FMath::WrapExclusive(++PreviousColorBoundTo, 0, 3);

	int32 IndexToBindTo = PreviousColorBoundTo;
	
	if (IndexToBindTo == 0)
	{
		return Message_ChangeColor_Red;
	}
	else if (IndexToBindTo == 1)
	{
		return Message_ChangeColor_Green;
	}
	else if (IndexToBindTo == 2)
	{
		return Message_ChangeColor_Blue;
	}
	
	return Message_ChangeColor_Blue;
}

AHeavyPerformanceBroadcastor::AHeavyPerformanceBroadcastor(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("RootMeshComp"));
	SetRootComponent(MeshComp);
	
	MessagePayloadToQueue = FInstancedStruct::Make(FTestHeavyMessage{});

	// The tick function is TG_PrePhysics by default
	// Tick this actor every time pre-physics
	PrimaryActorTick.bCanEverTick = true;
	PrimaryActorTick.TickGroup = CustomTickGroup;
}

void AHeavyPerformanceBroadcastor::Tick(float DeltaSeconds)

{
	Super::Tick(DeltaSeconds);

	QueueMessage();	
}

void AHeavyPerformanceBroadcastor::QueueMessage()

{
	TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(GetWorld());
	if (!Sys)
	{
		return;
	}

	for (int32 i = 0; i < NumberOfTimesToQueue; ++i)
	{
		// Queue a color change message
		Sys->QueueMessageForBroadcast(MessageToQueue, MessagePayloadToQueue);	
	}
}

AHeavyPerformanceListener::AHeavyPerformanceListener(const FObjectInitializer& ObjectInitializer)
{
	MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ListenerRootMeshComp"));
	SetRootComponent(MeshComp);
	MeshComp->SetMobility(EComponentMobility::Movable);
}

void AHeavyPerformanceListener::BeginPlay()

{
	Super::BeginPlay();

	SetupListener();
}

void AHeavyPerformanceListener::EndPlay(const EEndPlayReason::Type EndPlayReason)

{
	Super::EndPlay(EndPlayReason);
	
	RemoveListener();
}

void AHeavyPerformanceListener::HandleMessage(const FAsyncMessage& Message)

{
	const FTestHeavyMessage* Data = Message.GetPayloadData<const FTestHeavyMessage>();
	
	if (!Data)
	{
		ensure(false);
		return;
	}

	// Rotate the actor a little itsy bitsy, just to replicate doing some kind of simple gameplay work.
	AddActorLocalRotation(Data->AmountToRotate);
}

void AHeavyPerformanceListener::SetupListener()

{
	check(!ListenerHandle.IsValid());
	TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(GetWorld());
	if (!Sys)
	{
		return;
	}

	FAsyncMessageBindingOptions BindingOpts = {};
	BindingOpts.SetTickGroup(GroupToListenFor);
	
	ListenerHandle = Sys->BindListener(
		MessageToListenFor,
		TWeakObjectPtr<AHeavyPerformanceListener>(this),
		&AHeavyPerformanceListener::HandleMessage,
		BindingOpts);

	ensure(ListenerHandle.IsValid());
}

void AHeavyPerformanceListener::RemoveListener()

{
	if (!ListenerHandle.IsValid())
	{
		return;
	}
	
	TSharedPtr<FAsyncGameplayMessageSystem> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem<FAsyncGameplayMessageSystem>(GetWorld());
	if (!Sys)
	{
		return;
	}

	Sys->UnbindListener(ListenerHandle);
}