SpiecsEngine
 
Loading...
Searching...
No Matches
ThreadPoolBasic.h
Go to the documentation of this file.
1/**
2* @file ThreadPoolBasic.h
3* @brief The ThreadPool_Basic Class Definitions.
4* @author Spices.
5*/
6
7#pragma once
8#include "Core/Core.h"
9#include "Core/Library/ThreadLibrary.h"
10
11#include <future>
12#include <queue>
13
14namespace Spices {
15
16 const uint32_t THREAD_MAX_THRESHHOLD = std::thread::hardware_concurrency();
17 constexpr uint32_t THREAD_MAX_IDLE_TIME = 60;
18
19 /**
20 * @brief Thread Function Object.
21 */
22 template<typename ...Params>
23 class Thread
24 {
25 public:
26
27 /**
28 * @brief Thread Task.
29 */
30 using ThreadTask = std::function<void(Params...)>;
31
32 public:
33
34 /**
35 * @brief Thread Function.
36 */
37 using ThreadFunc = std::function<void(Thread*)>;
38
39 /**
40 * @brief Constructor Function.
41 * @param[in] func Thread Function lambda.
42 * @param[in] threadId Thread ID.
43 */
44 Thread(ThreadFunc func, uint32_t threadId)
45 : m_Func(func)
46 , m_ThreadId(threadId)
47 , m_ThreadTasks(0)
48 , m_IsInTask(false)
49 {}
50
51 /**
52 * @brief Destructor Function.
53 */
54 virtual ~Thread() = default;
55
56 /**
57 * @brief Copy Constructor Function.
58 * @note This Class not allowed copy behaves.
59 */
60 Thread(const Thread&) = delete;
61
62 /**
63 * @brief Copy Assignment Operation.
64 * @note This Class not allowed copy behaves.
65 */
66 Thread& operator=(const Thread&) = delete;
67
68 /**
69 * @brief Start a thread to execute Thread Function.
70 */
71 void Start();
72
73 /**
74 * @brief Get Thread Id.
75 */
76 uint32_t GetId() const { return m_ThreadId; }
77
78 /**
79 * @brief Receive a task must execute by this thread.
80 * @param[in] func Function Pointer.
81 */
82 void ReceiveThreadTask(std::function<void(Params...)> func);
83
84 /**
85 * @brief Get this mutex.
86 */
87 auto RequireTask() -> ThreadTask;
88
89 /**
90 * @brief Wait for all thread tasks finished.
91 */
92 void Wait() const;
93
94 /**
95 * @brief Set this Thread is in task or not.
96 */
97 void SetThreadInTask(bool isInTask);
98
99 /**
100 * @brief Get this Thread is in task or not.
101 * @return Returns true if in task.
102 */
103 bool GetThreadInTask() const { return m_IsInTask.load(); }
104
105 public:
106
107 /**
108 * @brief Get Thread Tasks Count.
109 * @reutrn Returns the Thread Tasks Count.
110 */
111 int GetThreadTasksCount() const { return m_ThreadTasks.load(); }
112
113 private:
114
115 /**
116 * @brief A Mutex for Thread.
117 */
118 std::mutex m_Mutex;
119
120 /**
121 * @brief Thread Function.
122 */
123 ThreadFunc m_Func;
124
125 /**
126 * @brief Thread Id.
127 */
128 uint32_t m_ThreadId;
129
130 /**
131 * @brief Thread Tasks Queue.
132 */
134
135 /**
136 * @brief Thread Tasks Count.
137 */
138 std::atomic_int m_ThreadTasks;
139
140 /**
141 * @brief True if this thread is executing a task.
142 */
143 std::atomic_bool m_IsInTask;
144 };
145
146 /**
147 * @brief ThreadPool Run Mode
148 */
149 enum class PoolMode
150 {
151 MODE_FIXED, /* @brief Fixed Thread Number. */
152 MODE_CACHED, /* @brief Dynamic Thread Number. */
153 };
154
155 /**
156 * @brief Thread Pool Basic Class.
157 * Instance inherited from it and use multithreading feature.
158 */
159 template<typename... Params>
161 {
162 public:
163
164 /**
165 * @brief Thread Function lambda Object.
166 */
167 using Task = std::function<void(Params...)>;
168
169 public:
170
171 /**
172 * @brief Constructor Function.
173 * @param[in] name ThreadPool Name.
174 */
175 ThreadPool_Basic(const std::string& name = "NonNameT");
176
177 /**
178 * @brief Destructor Function.
179 */
181
182 /**
183 * @brief Copy Constructor Function.
184 * @note This Class not allowed copy behaves.
185 */
187
188 /**
189 * @brief Copy Assignment Operation.
190 * @note This Class not allowed copy behaves.
191 */
193
194 /**
195 * @brief Set Pool Run Mode.
196 * @param[in] mode Pool Run Mode.
197 */
198 void SetMode(PoolMode mode);
199
200 /**
201 * @brief Set Pool Threads idle time out.
202 * @param[in] idleTime .
203 */
204 void SetThreadIdleTimeOut(int idleTime);
205
206 /**
207 * @brief Wait for all tasks executed finish in taskqueue.
208 */
209 void Wait();
210
211 /**
212 * @brief Continue ThreadPool.
213 */
214 void Continue();
215
216 /**
217 * @brief Suspend ThreadPool.
218 */
219 void Suspend();
220
221 /**
222 * @brief Submit a task to specific thread.
223 */
224 void SubmitThreadTask_LightWeight(uint32_t threadId, std::function<void(Params...)> func);
225
226 /**
227 * @brief Submit a task to all thread.
228 */
229 void SubmitThreadTask_LightWeight_ForEach(std::function<void(Params...)> func);
230
231 /***************************Must Implementation if Agent with Multiple Parameters*****************************/
232
233 /**
234 * @brief Thread Function.
235 * @param[in] thread Thread Entity.
236 */
237 void ThreadFunc(Thread<>* thread);
238
239 /**
240 * @brief Submit a task to task queue, and wait for a idle thread to execute it.
241 * @tparam Func Task Function.
242 * @tparam Args Task Function Parameter.
243 * @return Returns task function return value as a future.
244 */
245 template<typename Func, typename... Args>
246 auto SubmitPoolTask(Func&& func, Args&&... args) -> std::future<decltype(func(std::forward<Args>(args)...))>;
247
248 /**
249 * @brief Start Run this thread pool.
250 * @param[in] initThreadSize Thread Size.
251 */
252 void Start(int initThreadSize = 0.5 * std::thread::hardware_concurrency());
253
254 /*************************************************************************************************************/
255
256 public:
257
258 /**
259 * @brief Get Threads Count.
260 * This function is just used for unit test, should not be used in engine.
261 * @return Return Threads Count.
262 */
263 const int GetThreadsCount() const { return m_NThreads.load(); }
264
265 /**
266 * @brief Get Threads.
267 * This function is just used for unit test, should not be used in engine.
268 * @return Return Threads.
269 */
270 const std::unordered_map<uint32_t, std::unique_ptr<Thread<Params...>>>& GetThreads() const { return m_Threads; }
271
272 /**
273 * @brief GetInitThreadSize.
274 * This function is just used for unit test, should not be used in engine.
275 * @return Returns InitThreadSize.
276 */
277 const int GetInitThreadSize() const { return m_InitThreadSize; }
278
279 /**
280 * @brief GetIdleThreadSize.
281 * This function is just used for unit test, should not be used in engine.
282 * @return Returns IdleThreadSize.
283 */
284 const int GetIdleThreadSize() const { return m_IdleThreadSize.load(); }
285
286 /**
287 * @brief Get TaskQueue Count.
288 * This function is just used for unit test, should not be used in engine.
289 * @return Returns Task Queue Count.
290 */
291 const int GetTasks() const { return m_Tasks.load(); }
292
293 /**
294 * @brief GetPoolMode.
295 * This function is just used for unit test, should not be used in engine.
296 * @return Returns PoolMode.
297 */
298 const PoolMode& GetPoolMode() const { return m_PoolMode; }
299
300 /**
301 * @brief ThreadIdleTimeOut.
302 * This function is just used for unit test, should not be used in engine.
303 * @return Returns ThreadIdleTimeOut.
304 */
305 const int GetThreadIdleTimeOut() const { return m_ThreadIdleTimeOut; }
306
307 /**
308 * @brief GetIsPoolRunning.
309 * This function is just used for unit test, should not be used in engine.
310 * @return Returns true if pool is in use.
311 */
312 const bool IsPoolRunning() const { return m_IsPoolRunning.load(); }
313
314 protected:
315
316 /**
317 * @brief Check whether this pool is still in running.
318 */
319 bool CheckRunningState() const { return m_IsPoolRunning; }
320
321 protected:
322
323 /**
324 * @brief This ThreadPool Name.
325 */
326 std::string m_PoolName;
327
328 /**
329 * @brief Threads Container.
330 */
332
333 /**
334 * @brief Threads Count.
335 */
336 std::atomic_int m_NThreads;
337
338 /**
339 * @brief Initialized thread size.
340 */
342
343 /**
344 * @brief thread idle time out.
345 */
347
348 /**
349 * @brief Idled thread size.
350 */
351 std::atomic_int m_IdleThreadSize;
352
353 /**
354 * @brief Task Queue.
355 */
357
358 /**
359 * @brief Number of tasks;
360 */
361 std::atomic_int m_Tasks;
362
363 /**
364 * @brief Mutex for thread safe.
365 */
366 std::mutex m_Mutex;
367
368 /**
369 * @brief Task Queue not empty.
370 */
371 std::condition_variable m_NotEmpty;
372
373 /**
374 * @brief Thread pool Exit Condition.
375 */
376 std::condition_variable m_ExitCond;
377
378 /**
379 * @brief Thread pool thread idle Condition.
380 */
381 std::condition_variable m_IdleCond;
382
383 /**
384 * @brief Thread Pool Run Mode.
385 */
387
388 /**
389 * @brief True if this thread pool is in use.
390 */
391 std::atomic_bool m_IsPoolRunning;
392
393 /**
394 * @brief True if needs suspend on executing the task.
395 */
397 };
398
399 template<typename ...Params>
400 inline void Thread<Params...>::Start()
401 {
403
404 std::thread t(m_Func, this);
405 t.detach();
406 }
407
408 template<typename ...Params>
409 inline void Thread<Params...>::ReceiveThreadTask(std::function<void(Params...)> func)
410 {
412
413 std::unique_lock<std::mutex> lock(m_Mutex);
414
415 m_ThreadTasksQueue.push(func);
416 ++m_ThreadTasks;
417 }
418
419 template<typename ...Params>
420 inline auto Thread<Params...>::RequireTask() -> Thread<Params...>::ThreadTask
421 {
423
424 std::unique_lock<std::mutex> lock(m_Mutex);
425
426 if (m_ThreadTasksQueue.empty())
427 {
428 m_IsInTask = false;
429 return nullptr;
430 }
431
432 auto ptr = m_ThreadTasksQueue.front();
433 m_ThreadTasksQueue.pop();
434 m_IsInTask = true;
435 --m_ThreadTasks;
436 return ptr;
437 }
438
439 template<typename ...Params>
440 inline void Thread<Params...>::Wait() const
441 {
443
444 while (m_ThreadTasks.load() != 0 || m_IsInTask.load()) {};
445 }
446
447 template<typename ...Params>
448 inline void Thread<Params...>::SetThreadInTask(bool isInTask)
449 {
451
452 m_IsInTask = isInTask;
453 }
454
455 template<typename ...Params>
456 inline void ThreadPool_Basic<Params...>::SetMode(PoolMode mode)
457 {
459
460 if (CheckRunningState()) return;
461 m_PoolMode = mode;
462 }
463
464 template<typename ...Params>
465 inline ThreadPool_Basic<Params...>::ThreadPool_Basic(const std::string& name)
466 : m_PoolName(name)
471 , m_IsPoolRunning(false)
472 , m_IsSuspend(false)
473 {}
474
475 template<typename ...Params>
476 inline ThreadPool_Basic<Params...>::~ThreadPool_Basic()
477 {
479
480 m_IsPoolRunning = false;
481
482 /**
483 * @brief Wait for all threads return.
484 */
485 std::unique_lock<std::mutex> lock(m_Mutex);
486 m_NotEmpty.notify_all();
487 m_ExitCond.wait(lock, [&]()->bool { return m_Threads.empty(); });
488 }
489
490 template<typename ...Params>
491 inline void ThreadPool_Basic<Params...>::SetThreadIdleTimeOut(int idleTime)
492 {
494
495 if (CheckRunningState()) return;
496 m_ThreadIdleTimeOut = idleTime;
497 }
498
499 template<typename ...Params>
500 inline void ThreadPool_Basic<Params...>::Wait()
501 {
503
504 auto idleCond = [&]() {
505 return m_IdleThreadSize.load() == m_NThreads.load() && m_Tasks.load() == 0;
506 };
507
508 if (!idleCond())
509 {
510 std::unique_lock<std::mutex> lock(m_Mutex);
511 m_IdleCond.wait(lock, idleCond);
512 }
513
514 for (auto& pair : m_Threads)
515 {
516 pair.second->Wait();
517 }
518 }
519
520 template<typename ...Params>
521 inline void ThreadPool_Basic<Params...>::Continue()
522 {
524
525 m_IsSuspend = false;
526
527 if (m_Tasks.load() > 0)
528 {
529 m_NotEmpty.notify_all();
530 }
531 }
532
533 template<typename ...Params>
534 inline void ThreadPool_Basic<Params...>::Suspend()
535 {
537
538 m_IsSuspend = true;
539
540 std::unique_lock<std::mutex> lock(m_Mutex);
541
542 m_IdleCond.wait(lock, [&]() { return m_IdleThreadSize.load() == m_NThreads.load(); });
543 }
544
545 template<typename ...Params>
546 inline void ThreadPool_Basic<Params...>::SubmitThreadTask_LightWeight(uint32_t threadId, std::function<void(Params...)> func)
547 {
549
550 {
551 std::unique_lock<std::mutex> lock(m_Mutex);
552
553 m_Threads[threadId]->ReceiveThreadTask(func);
554 }
555
556 m_NotEmpty.notify_all();
557 }
558
559 template<typename ...Params>
560 inline void ThreadPool_Basic<Params...>::SubmitThreadTask_LightWeight_ForEach(std::function<void(Params...)> func)
561 {
563
564 {
565 std::unique_lock<std::mutex> lock(m_Mutex);
566
567 for (auto& pair : m_Threads)
568 {
569 pair.second->ReceiveThreadTask(func);
570 }
571 }
572
573 m_NotEmpty.notify_all();
574 }
575
576 template<typename ...Params>
577 inline void ThreadPool_Basic<Params...>::ThreadFunc(Thread<>* thread)
578 {
580
581 /**
582 * @brief Name thread.
583 */
584 std::stringstream ss;
585 ss << m_PoolName << thread->GetId();
586
588
589 auto lastTime = std::chrono::high_resolution_clock::now();
590
591 for (;;)
592 {
593 Task task;
594 {
595 std::unique_lock<std::mutex> lock(m_Mutex);
596
597 while ((m_Tasks.load() == 0 && thread->GetThreadTasksCount() == 0) || m_IsSuspend)
598 {
599 /**
600 * @brief Exit.
601 */
602 if (!m_IsPoolRunning)
603 {
604 m_Threads.erase(thread->GetId());
605 --m_IdleThreadSize;
606 m_ExitCond.notify_all();
607 return;
608 }
609
610 if (m_PoolMode == PoolMode::MODE_CACHED)
611 {
612 if (m_NotEmpty.wait_for(lock, std::chrono::seconds(1)) == std::cv_status::timeout)
613 {
614 auto now = std::chrono::high_resolution_clock::now();
615 auto dur = std::chrono::duration_cast<std::chrono::seconds>(now - lastTime);
616
617 /**
618 * @brief Try recovery unused threads.
619 */
620 if (dur.count() >= m_ThreadIdleTimeOut && m_Threads.size() > m_InitThreadSize)
621 {
622 m_Threads.erase(thread->GetId());
623 --m_IdleThreadSize;
624 --m_NThreads;
625
626 return;
627 }
628 }
629 }
630 else
631 {
632 m_NotEmpty.wait(lock);
633 }
634 }
635
636 /**
637 * @brief Rink First, Thread Tasks.
638 */
639 task = thread->RequireTask();
640
641 /**
642 * @brief Rink Second, Pool Tasks.
643 */
644 if (!task)
645 {
646 task = m_TaskQueue.front();
647 m_TaskQueue.pop();
648 thread->SetThreadInTask(true);
649 --m_Tasks;
650 }
651
652 --m_IdleThreadSize;
653 }
654
655 if (m_Tasks > 0)
656 {
657 m_NotEmpty.notify_all();
658 }
659
660 /**
661 * @brief execute task.
662 */
663 if (task != nullptr)
664 {
665 task();
666 thread->SetThreadInTask(false);
667 ++m_IdleThreadSize;
668 m_IdleCond.notify_all();
669 }
670 else
671 {
672 thread->SetThreadInTask(false);
673 ++m_IdleThreadSize;
674 m_IdleCond.notify_all();
675 }
676
677 lastTime = std::chrono::high_resolution_clock::now();
678 }
679 }
680
681 template<typename ...Params>
682 inline void ThreadPool_Basic<Params...>::Start(int initThreadSize)
683 {
685
686 m_IsPoolRunning = true;
687 m_InitThreadSize = initThreadSize;
688 m_IdleThreadSize = initThreadSize;
689 m_NThreads = initThreadSize;
690
691 for (uint32_t i = 0; i < m_InitThreadSize; i++)
692 {
693 auto ptr = std::make_unique<Thread<>>(std::bind(&ThreadPool_Basic<>::ThreadFunc, this, std::placeholders::_1), i);
694 int threadId = ptr->GetId();
695
696 m_Threads.emplace(threadId, std::move(ptr));
697 m_Threads[threadId]->Start();
698 }
699 }
700
701 template<typename ...Params>
702 template<typename Func, typename ...Args>
703 inline auto ThreadPool_Basic<Params...>::SubmitPoolTask(Func&& func, Args && ...args) -> std::future<decltype(func(std::forward<Args>(args)...))>
704 {
706
707 using RType = decltype(func(args...));
708
709 /**
710 * @brief pack function pointer with packaged_task and get future.
711 */
712 auto task = std::make_shared<std::packaged_task<RType()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
713 std::future<RType> result = task->get_future();
714
715 {
716 std::unique_lock<std::mutex> lock(m_Mutex);
717
718 /**
719 * @brief pack task as a lambda and submit it to queue.
720 */
721 m_TaskQueue.emplace([task]() {(*task)(); });
722 ++m_Tasks;
723
724 /**
725 * @brief Expand threads container if in MODE_CACHED.
726 */
727 if (m_PoolMode == PoolMode::MODE_CACHED && m_TaskQueue.size() > m_IdleThreadSize && m_Threads.size() < THREAD_MAX_THRESHHOLD)
728 {
729 for (uint32_t i = 0; i < THREAD_MAX_THRESHHOLD; i++)
730 {
731 if (m_Threads.find(i) == m_Threads.end())
732 {
733 auto ptr = std::make_unique<Thread<>>(std::bind(&ThreadPool_Basic::ThreadFunc, this, std::placeholders::_1), i);
734 uint32_t threadId = ptr->GetId();
735
736 ptr->Start();
737 m_Threads.emplace(threadId, std::move(ptr));
738
739 ++m_IdleThreadSize;
740 ++m_NThreads;
741
742 break;
743 }
744 }
745 }
746 }
747
748 m_NotEmpty.notify_all();
749
750 return result;
751 }
752
753 /**
754 * @brief Using ThreadPool as a simple format of ThreadPool_Basic<>
755 */
756 using ThreadPool = ThreadPool_Basic<>;
757}
#define ASSERT(expr)
Assert macro.
Definition Core.h:29
int main()
Main Function.
Definition EntryPoint.h:15
#define PROCESS_INSTANCE_ENTRY
Macros of modify Process instance state.
#define PROCESS_INSTANCE_EXIT
#define Update_F(item)
Definition MeshPack.h:92
std::string AftermathErrorMessage(GFSDK_Aftermath_Result result)
Helper for checking Nsight Aftermath failures.
bool operator<(const GFSDK_Aftermath_ShaderDebugInfoIdentifier &lhs, const GFSDK_Aftermath_ShaderDebugInfoIdentifier &rhs)
Helper for comparing GFSDK_Aftermath_ShaderDebugInfoIdentifier.
#define SPICES_PROFILE_ZONE
#define VK_FUNCTION_POINTER(function)
Macro for declare function pointer variable in VulkanFunctions.
#define VMA_ALLOCATOR
Use VMA for memory allocate.
Definition VulkanUtils.h:27
Application(const Application &)=delete
Copy Constructor Function.
virtual ~Application()
Destructor Function.
Application & operator=(const Application &)=delete
Copy Assignment Operation.
Application()
Constructor Function.
static void Run()
Run Our World.
Application Class. Our Engine Start here.
Definition Application.h:20
virtual bool OnCreatePack(bool isCreateBuffer=true) override
This interface is used for build specific mesh pack data.
Definition MeshPack.cpp:359
uint32_t m_Columns
How much cols number we use.
Definition MeshPack.h:486
uint32_t m_Rows
How much rows number we use.
Definition MeshPack.h:481
CubePack(uint32_t rows=2, uint32_t columns=2, bool instanced=true)
Constructor Function. Init member variables.
Definition MeshPack.h:456
virtual ~CubePack() override=default
Destructor Function.
CubePack Class. This class defines box type mesh pack.
Definition MeshPack.h:446
Entity Class. This class defines the specific behaves of Entity.
Definition Entity.h:20
virtual bool OnCreatePack(bool isCreateBuffer=true) override
This interface is used for build specific mesh pack data.
Definition MeshPack.cpp:551
virtual ~FilePack() override=default
Destructor Function.
FilePack(const std::string &filePath, bool instanced=true)
Constructor Function. Init member variables.
Definition MeshPack.h:551
std::string m_Path
The mesh file path in disk.
Definition MeshPack.h:575
FilePack Class. This class defines file type mesh pack.
Definition MeshPack.h:542
static void CrashDumpDescriptionCallback(PFN_GFSDK_Aftermath_AddGpuCrashDumpDescription addDescription, void *pUserData)
GPU crash dump description callback.
static void Init()
Create single instance of this class.
static constexpr unsigned int c_MarkerFrameHistory
keep four frames worth of marker history.
void WriteShaderDebugInformationToFile(GFSDK_Aftermath_ShaderDebugInfoIdentifier identifier, const void *pShaderDebugInfo, const uint32_t shaderDebugInfoSize) const
Helper for writing shader debug information to a file.
void SetMarker(uint64_t &markerId, const std::string &info)
Set Marker.
MarkerMap m_MarkerMap
App-managed marker tracking.
void OnShaderLookup(const GFSDK_Aftermath_ShaderBinaryHash &shaderHash, PFN_GFSDK_Aftermath_SetData setShaderBinary) const
Handler for shader lookup callbacks. This is used by the JSON decoder for mapping shader instruction ...
void SetFrameCut(uint64_t frameCut)
Set FrameCut.
static void OnDescription(PFN_GFSDK_Aftermath_AddGpuCrashDumpDescription addDescription)
Handler for GPU crash dump description callbacks.
virtual ~GpuCrashTracker()
Destructor Function.
static void ShaderSourceDebugInfoLookupCallback(const GFSDK_Aftermath_ShaderDebugName *pShaderDebugName, PFN_GFSDK_Aftermath_SetData setShaderBinary, void *pUserData)
Shader source debug info lookup callback.
static void AftermathDeviceLostCheck()
Aftermath handle device lost function.
void OnResolveMarker(const void *pMarkerData, const uint32_t markerDataSize, void **ppResolvedMarkerData, uint32_t *pResolvedMarkerDataSize)
Handler for app-managed marker resolve callback.
std::mutex m_Mutex
For thread-safe access of GPU crash tracker state.
static std::unique_ptr< GpuCrashTracker > m_GpuCrashTracker
GpuCrashTracker single instance.
static void ShaderDebugInfoCallback(const void *pShaderDebugInfo, const uint32_t shaderDebugInfoSize, void *pUserData)
Shader debug information callback.
bool m_Initialized
Is the GPU crash dump tracker initialized?
std::array< std::map< uint64_t, std::string >, c_MarkerFrameHistory > MarkerMap
static void ShaderDebugInfoLookupCallback(const GFSDK_Aftermath_ShaderDebugInfoIdentifier *pIdentifier, PFN_GFSDK_Aftermath_SetData setShaderDebugInfo, void *pUserData)
Shader debug information lookup callback.
void OnCrashDump(const void *pGpuCrashDump, const uint32_t gpuCrashDumpSize)
Handler for GPU crash dump callbacks from Nsight Aftermath.
void OnShaderDebugInfo(const void *pShaderDebugInfo, const uint32_t shaderDebugInfoSize)
Handler for shader debug information callbacks.
void Initialize()
Initialize the GPU crash dump tracker.
static void GpuCrashDumpCallback(const void *pGpuCrashDump, const uint32_t gpuCrashDumpSize, void *pUserData)
GPU crash dump callback.
static GpuCrashTracker & Get()
Get single instance of this class.
ShaderDataBase m_ShaderDataBase
The mock shader database.
ShaderDataBase & GetShaderDataBase()
Get ShaderDataBase.
void OnShaderSourceDebugInfoLookup(const GFSDK_Aftermath_ShaderDebugName &shaderDebugName, PFN_GFSDK_Aftermath_SetData setShaderBinary) const
Handler for shader source debug info lookup callbacks. This is used by the JSON decoder for mapping s...
void WriteGpuCrashDumpToFile(const void *pGpuCrashDump, const uint32_t gpuCrashDumpSize)
Helper for writing a GPU crash dump to a file.
static void ResolveMarkerCallback(const void *pMarkerData, const uint32_t markerDataSize, void *pUserData, void **ppResolvedMarkerData, uint32_t *pResolvedMarkerDataSize)
App-managed marker resolve callback.
void OnShaderDebugInfoLookup(const GFSDK_Aftermath_ShaderDebugInfoIdentifier &identifier, PFN_GFSDK_Aftermath_SetData setShaderDebugInfo) const
Handler for shader debug information lookup callbacks. This is used by the JSON decoder for mapping s...
static void ShaderLookupCallback(const GFSDK_Aftermath_ShaderBinaryHash *pShaderHash, PFN_GFSDK_Aftermath_SetData setShaderBinary, void *pUserData)
Shader lookup callback.
Implements GPU crash dump tracking using the Nsight Aftermath API.
static std::vector< VkVertexInputAttributeDescription > GetAttributeDescriptions()
Get VkVertexInputAttributeDescription for IA.
Definition Vertex.cpp:25
static std::vector< VkVertexInputBindingDescription > GetBindingDescriptions()
Get VkVertexInputBindingDescription for IA.
Definition Vertex.cpp:12
static std::vector< VkVertexInputAttributeDescription > GetSlateAttributeDescriptions()
Get Slate VkVertexInputAttributeDescription for IA.
Definition Vertex.cpp:60
static std::vector< VkVertexInputBindingDescription > GetSlateBindingDescriptions()
Get Slate VkVertexInputBindingDescription for IA.
Definition Vertex.cpp:39
static std::shared_ptr< spdlog::logger > s_ClientLogger
Game Stage Logger.
Definition Log.h:80
static bool m_IsInitialized
Definition Log.h:28
static std::shared_ptr< spdlog::logger > s_CoreLogger
Engine Stage Logger.
Definition Log.h:75
static void Init()
Init Log.
Definition Log.cpp:24
static std::shared_ptr< spdlog::logger > & GetCoreLogger()
Get Engine Stage Logger.
Definition Log.h:46
static std::shared_ptr< spdlog::logger > & GetClientLogger()
Get Game Stage Logger.
Definition Log.h:52
static void PostHandle(format_string_t< Args... > fmt, Args &&...args)
Post handle with log message.
Definition Log.h:84
static void ShutDown()
Shutdown Log.
Definition Log.cpp:82
static bool SaveDefaultMaterial()
Test function.
static bool Load(const std::string &fileName, Material *outMaterial)
Public called API, it is entrance.
static bool LoadFromSASSET(const std::string &fileName, Material *outMaterial)
Load data from a .sasset file.
static bool LoadFromMaterial(const std::string &fileName, Material *outMaterial)
Load data from a .material file.
This enum defines tree types of material file.
virtual ~MaterialProperties()=default
Destructor Function.
MaterialProperties()
Constructor Function.
Wrapper of material render options.
void BuildMaterial(bool isAutoRegistry=true)
This interface need to be overwritten by specific material. It defines how we build texture and descr...
Definition Material.cpp:136
void PushToTextureParams(const std::string &name, const TextureParam &texture)
Push item to ShaderPath.
Definition Material.cpp:101
const std::vector< std::string > & GetShaderPath(const std::string &stage)
Get material shader path.
Definition Material.cpp:76
scl::linked_unordered_map< std::string, ConstantParams > m_ConstantParams
Constant parameters. Key: parameter name, Value: parameter value.
Definition Material.h:226
T GetDefaultConstantParams(const std::string &name)
Get default material constant parameter.
Definition Material.h:261
bool m_AlreadyBuild
True if this material already build a buffer.
Definition Material.h:252
const std::unordered_map< std::string, std::vector< std::string > > & GetShaderPath() const
Get material shader path.
Definition Material.h:111
void UpdateMaterial()
Update material data to buffer.
Definition Material.cpp:369
std::unordered_map< std::string, std::vector< std::string > > m_Shaders
Shader path Key: shader usage, Value: shader file name.
Definition Material.h:212
void Deserialize()
Deserialize the data from a disk file(.material) to this class.
Definition Material.cpp:63
void PushToShaderPath(const std::string &name, const std::string &shader)
Push item to ShaderPath.
Definition Material.cpp:91
std::unordered_map< std::string, std::vector< std::string > > m_DefaultShaders
Definition Material.h:213
void PushToConstParams(const std::string &name, const ConstantParam &param)
Push item to ConstParams.
Definition Material.cpp:111
uint64_t GetMaterialParamsAddress() const
Get material parameter address on GPU.
Definition Material.cpp:120
const std::string & GetName() const
Get Material Path.
Definition Material.h:98
scl::runtime_memory_block m_Buffermemoryblocks
m_Buffers's c++ data container. Key: set, Value: scl::runtime_memory_block.
Definition Material.h:232
Material()=default
Constructor Function.
scl::linked_unordered_map< std::string, TextureParam > m_DefaultTextureParams
Definition Material.h:220
bool GetIsDrawWindow() const
Get boolean of whether draw a material window.
Definition Material.h:170
void SetIsDrawWindow(bool isDrawWindow)
Set boolean of whether draw a material window.
Definition Material.h:176
scl::linked_unordered_map< std::string, TextureParam > & GetTextureParams()
Get material texture parameters.
Definition Material.h:117
void SetName(const std::string &path)
Set material path.
Definition Material.h:129
bool m_IsDrawWindow
True if this material needs to draw a window.
Definition Material.h:247
scl::linked_unordered_map< std::string, ConstantParams > & GetConstantParams()
Get material constant parameters.
Definition Material.h:123
Material(const std::string &materialPath)
Constructor Function. Deserialize immediately. Usually call it.
Definition Material.cpp:20
scl::linked_unordered_map< std::string, TextureParam > m_TextureParams
Texture parameters. Key: parameter name, Value: parameter value.
Definition Material.h:219
std::mutex m_Mutex
Mutex of this material.
Definition Material.h:257
virtual ~Material()
Destructor Function.
Definition Material.cpp:33
std::unique_ptr< VulkanBuffer > m_MaterialParameterBuffer
Definition Material.h:237
MaterialProperties m_Properties
Properties of render options.
Definition Material.h:242
std::string m_MaterialPath
Definition Material.h:206
void Serialize()
Serialize this class data to a disk file(.material).
Definition Material.cpp:53
Material Class. This class contains a branch of parameter and shader, also descriptor.
Definition Material.h:62
MeshLoader Class. This class only defines static function for load data from mesh file.
Definition MeshLoader.h:48
AccelKHR m_Accel
This meshPack blas accel.
Definition MeshPack.h:368
UUID GetUUID() const
Get mesh pack UUID.
Definition MeshPack.h:235
std::optional< std::atomic_uint32_t > m_ShaderGroupHandle
specific shader group handle. Used in IndirectDGCPipeline.
Definition MeshPack.h:353
void SetHitShaderHandle(uint32_t handle)
Set hit shader Handle.
Definition MeshPack.h:212
std::string m_MeshPackName
MeshPack Name.
Definition MeshPack.h:321
uint32_t GetNTasks() const
Get NTasks.
Definition MeshPack.h:265
void OnDraw(const VkCommandBuffer &commandBuffer) const
Draw indexed.
Definition MeshPack.cpp:96
virtual bool OnCreatePack(bool isCreateBuffer=true)
This interface is used for build specific mesh pack data.
Definition MeshPack.cpp:119
MeshResource m_MeshResource
Mesh Resources.
Definition MeshPack.h:331
uint32_t GetShaderGroupHandle() const
Get ShaderGroup Handle, which accessed by gdc buffer.
Definition MeshPack.cpp:180
std::optional< std::atomic_uint32_t > m_HitShaderHandle
specific hit shader handle. Used in RayTracing Pipeline.
Definition MeshPack.h:347
void OnDrawMeshTasks(const VkCommandBuffer &commandBuffer) const
Draw Mesh Tasks.
Definition MeshPack.cpp:112
VkDrawMeshTasksIndirectCommandNV m_MeshTaskIndirectDrawCommand
Draw Command.
Definition MeshPack.h:383
MeshDesc & GetMeshDesc()
Get Mesh Description.
Definition MeshPack.h:271
const std::string & GetPackType() const
Get Pack Type.
Definition MeshPack.h:283
uint32_t GetHitShaderHandle() const
Get Hit Shader Handle, which accessed by ray gen shader.
Definition MeshPack.cpp:165
MeshPack(const std::string &name, bool instanced)
Constructor Function.
Definition MeshPack.cpp:78
bool HasBlasAccel()
Is this meshPack has a valid blas.
Definition MeshPack.cpp:251
std::string m_PackType
specific mesh pack type.
Definition MeshPack.h:363
void CreateBuffer()
Create Vertices buffer anf Indices buffer.
Definition MeshPack.cpp:278
VulkanRayTracing::BlasInput MeshPackToVkGeometryKHR()
Convert MeshPack into the ray tracing geometry used to build the BLAS.
Definition MeshPack.cpp:195
std::atomic_bool m_IsRequiredAccel
True if required accel by BLAS Build.
Definition MeshPack.h:373
void OnBind(const VkCommandBuffer &commandBuffer) const
Bind VBO and EBO.
Definition MeshPack.cpp:86
MeshDesc m_Desc
Mesh Description.
Definition MeshPack.h:358
std::shared_ptr< Material > GetMaterial()
Get material in this class.
Definition MeshPack.h:206
const VkDrawMeshTasksIndirectCommandNV & GetDrawCommand() const
Get Draw Command.
Definition MeshPack.h:277
void SetMaterial(std::shared_ptr< Material > material)
Set specific material for this class.
Definition MeshPack.cpp:155
MeshPack & operator=(const MeshPack &)=delete
Copy Constructor Function.
void SetShaderGroupHandle(uint32_t handle)
Set hit shader Handle.
Definition MeshPack.h:218
const MeshResource & GetResource() const
Get Resource.
Definition MeshPack.h:307
std::shared_ptr< Material > m_Material
specific material pointer.
Definition MeshPack.h:341
void SetMaterial(const std::string &materialPath)
Set specific material for this class.
Definition MeshPack.cpp:145
uint32_t m_NTasks
Task Shader Work Group Size.
Definition MeshPack.h:336
virtual ~MeshPack()=default
Destructor Function.
UUID m_UUID
UUID for mesh pack.
Definition MeshPack.h:378
const std::vector< Meshlet > & GetMeshlets() const
Get Meshlets array.
Definition MeshPack.h:259
MeshPack(const MeshPack &)=delete
Copy Constructor Function.
bool m_Instanced
If this mesh pack needs instanced.
Definition MeshPack.h:326
AccelKHR & GetAccel()
Get this accel.
Definition MeshPack.cpp:261
MeshPack Class. This class defines some basic behaves and variables. This class need to be inherited ...
Definition MeshPack.h:156
static bool PackPrimVerticesFromSparseInputs(MeshPack *meshPack, const std::vector< glm::uvec3 > primVertices, std::vector< glm::vec3 > &packPoints, std::vector< glm::uvec3 > &packPrimPoints, std::unordered_map< uint32_t, uint32_t > &primVerticesMapReverse)
Pack PrimVertices from Sparse PrimVertices Inputs.
static SpicesShader::Sphere CalculateBoundSphere(const std::vector< glm::vec3 > &points)
Calculate BoundSphere from Points.
static bool FindBoundaryPoints(MeshPack *meshPack, const std::vector< glm::uvec3 > &primVertices, std::unordered_map< uint32_t, bool > &boundaryPoints, std::unordered_map< uint32_t, bool > &stableBoundaryPoints, std::unordered_map< uint32_t, EdgePoint > &boundaryEdgePoints, std::unordered_map< uint32_t, std::unordered_map< uint32_t, bool > > &pointConnect)
Find Points located in Boundaries.
static bool MergeByDistance(MeshPack *meshPack, std::vector< glm::uvec3 > &primVertices, scl::kd_tree< 6 > &kdTree, float maxDistance, float maxUVDistance)
Merge Vertex by Distance.
static void GenerateMeshLodClusterHierarchy(MeshPack *meshPack)
Generate Mesh Lod Resources.
static bool PackVertexToPoints(MeshPack *meshPack, const std::vector< glm::uvec3 > &primVertices, std::vector< glm::vec3 > &points)
Pack Vertices to Points.
static bool UnPackPrimVerticesToSparseInputs(std::vector< glm::uvec3 > &primVertices, std::unordered_map< uint32_t, uint32_t > &primVerticesMapReverse, const std::vector< glm::uvec3 > &packPrimPoints)
Unpack PrimVertices to Sparse PrimVertices Inputs.
static void AppendMeshlets(MeshPack *meshPack, uint32_t lod, const SpicesShader::Sphere &clusterBoundSphere, const std::vector< glm::uvec3 > &primVertices)
Create and Append Meshlets to MeshPack use given indices.
static std::vector< MeshletGroup > GroupMeshlets(MeshPack *meshPack, std::vector< Meshlet > &meshlets)
Split Meshlets to Groups.
static bool BuildKDTree(MeshPack *meshPack, const std::vector< glm::uvec3 > &primVertices, scl::kd_tree< 6 > &kdTree)
Build KDTree use specific meshlets.
Class for provide functions of process Meshpack.
uint32_t m_Columns
How much cols number we use.
Definition MeshPack.h:437
uint32_t m_Rows
How much rows number we use.
Definition MeshPack.h:432
virtual bool OnCreatePack(bool isCreateBuffer=true) override
This interface is used for build specific mesh pack data.
Definition MeshPack.cpp:315
PlanePack(uint32_t rows=2, uint32_t columns=2, bool instanced=true)
Constructor Function. Init member variables.
Definition MeshPack.h:407
virtual ~PlanePack() override=default
Destructor Function.
PlanePack Class. This class defines plane type mesh pack.
Definition MeshPack.h:397
ResourcePool()=default
Constructor Function.
ResourcePool & operator=(const ResourcePool &)=delete
Copy Constructor Function.
static bool Has(const std::string &name)
Determine if specific resource is exist.
static std::shared_ptr< T > Load(const std::string &path, Args... args)
Load a resource by path. When we need a resource, we call this API. Load if resource is not found.
static void Registry(const std::string &name, std::shared_ptr< T > resource)
Registry a resource to this Pool.
static void Destroy()
Destroy this resource pool. Release all Resource Pointer, which means resource can be destructed afte...
ResourcePool(const ResourcePool &)=delete
Copy Constructor Function.
virtual ~ResourcePool()=default
Destructor Function.
static void UnLoad(const std::string &path)
UnLoad a resource by path.
static std::shared_ptr< T > Access(const std::string &path)
Access a resource by path directly. Do nothing if resource is not found.
static std::unordered_map< std::string, std::unique_ptr< Resource > > m_Resources
Static variable stores all specific resources in a basic type Pool.
static std::shared_mutex m_Mutex
Mutex for this pool.
Template ResourcePool Class. This class will assign Every Type of Resource per Pool....
virtual ~Resource()
Unload resource.
Definition Resource.h:57
Resource(std::function< std::any()> fn)
Constructor Function.
Definition Resource.h:38
std::any m_Resource
Resource instance wrapper.
Definition Resource.h:94
void UnLoad()
UnLoad this resource.
Definition Resource.h:112
std::function< std::any()> m_CreateFunction
Resource create function.
Definition Resource.h:104
ResourceStateEnum
Enum of ResourceState.
Definition Resource.h:25
std::shared_ptr< T > GetResource()
Get resource instance.
Definition Resource.h:137
ResourceStateEnum m_State
Resource state.
Definition Resource.h:99
std::mutex m_Mutex
Mutex of this resource.
Definition Resource.h:109
ResourceStateEnum GetState() const
Get resource state.
Definition Resource.h:68
void CreateResource()
Create resource instance.
Definition Resource.h:123
Resource Wrapper of ResourceInstance.
Definition Resource.h:18
static VkShaderStageFlagBits ToFlagBits(ShaderStage stage)
Convert ShaderStage to VkShaderStageFlagBits.
static std::string ToString(ShaderStage stage)
Convert ShaderStage to String.
static shaderc_shader_kind ToShaderCKind(ShaderStage stage)
Convert ShaderStage to shaderc_shader_kind.
static ShaderStage ToStage(std::string stage)
Convert String to ShaderStage.
ShaderHelper Class.
SpherePack(uint32_t rows=15, uint32_t columns=24, bool instanced=true)
Constructor Function. Init member variables.
Definition MeshPack.h:504
uint32_t m_Rows
How much rows number we use.
Definition MeshPack.h:529
virtual ~SpherePack() override=default
Destructor Function.
virtual bool OnCreatePack(bool isCreateBuffer=true) override
This interface is used for build specific mesh pack data.
Definition MeshPack.cpp:563
uint32_t m_Columns
How much cols number we use.
Definition MeshPack.h:534
SpherePack Class. This class defines sphere type mesh pack.
Definition MeshPack.h:494
Texture2DCube Class. This class defines the basic behaves of Texture2DCube.
Texture2D(const RendererResourceCreateInfo &info)
Constructor Function. Used for create render resource.
Definition Texture2D.cpp:15
Texture2D(const std::string &path)
Constructor Function. Init class variable, load date immediately. Usually call it.
Definition Texture2D.cpp:93
virtual ~Texture2D() override=default
Destructor Function.
Texture2D()=default
Constructor Function.
Texture2D Class. This class defines the basic behaves of texture2D.
Definition Texture2D.h:20
static void Load(const std::string &fileName, Texture2DCube *outTexture)
Load image to a Texture2DCube object.
static void Load(const std::string &fileName, Texture2D *outTexture)
Load image to a Texture2D object.
static bool LoadSrc(const std::string &fileName, const std::string &it, Texture2D *outTexture, bool isCreateCompressTexture=true)
Function of load a src file.
static bool SearchFile(const std::string &fileName, std::function< void(const std::string &)> binF, std::function< void(const std::string &)> srcF)
Search texture file and load.
static bool LoadBin(const std::string &fileName, const std::string &it, Texture2D *outTexture)
Function of load a ktx file.
TextureLoader Class. This class only defines static function for load data from image file.
virtual ~Texture()=default
Destructor Function.
std::string m_ResourcePath
Texture's path in disk.
Definition Texture.h:74
Texture(const std::string &path)
Constructor Function. Init class variable. Usually call it.
Definition Texture.h:47
Texture()=default
Constructor Function.
std::shared_ptr< T > GetResource()
Get Specific resource, usually is a wrapper of VulkanImage.
Definition Texture.h:78
std::any m_Resource
Texture's resource, coule be any kind of type.
Definition Texture.h:68
Texture Class. This class defines the basic behaves of texture. When we add an new Texture,...
Definition Texture.h:33
static bool SetThreadName(const std::string &name)
Set Thread name.
Thread Static Function Library.
void Continue()
Continue ThreadPool.
bool m_IsSuspend
True if needs suspend on executing the task.
const int GetIdleThreadSize() const
GetIdleThreadSize. This function is just used for unit test, should not be used in engine.
std::atomic_int m_IdleThreadSize
Idled thread size.
std::queue< Task > m_TaskQueue
Task Queue.
void SetThreadIdleTimeOut(int idleTime)
Set Pool Threads idle time out.
std::atomic_int m_Tasks
Number of tasks;.
std::condition_variable m_ExitCond
Thread pool Exit Condition.
PoolMode m_PoolMode
Thread Pool Run Mode.
bool CheckRunningState() const
Check whether this pool is still in running.
const bool IsPoolRunning() const
GetIsPoolRunning. This function is just used for unit test, should not be used in engine.
void SetMode(PoolMode mode)
Set Pool Run Mode.
std::mutex m_Mutex
Mutex for thread safe.
const int GetThreadsCount() const
Get Threads Count. This function is just used for unit test, should not be used in engine.
virtual ~ThreadPool_Basic()
Destructor Function.
const PoolMode & GetPoolMode() const
GetPoolMode. This function is just used for unit test, should not be used in engine.
std::unordered_map< uint32_t, std::unique_ptr< Thread< Params... > > > m_Threads
Threads Container.
ThreadPool_Basic(const std::string &name="NonNameT")
Constructor Function.
void Suspend()
Suspend ThreadPool.
void Start(int initThreadSize=0.5 *std::thread::hardware_concurrency())
Start Run this thread pool.
const int GetTasks() const
Get TaskQueue Count. This function is just used for unit test, should not be used in engine.
std::string m_PoolName
This ThreadPool Name.
ThreadPool_Basic & operator=(const ThreadPool_Basic &)=delete
Copy Assignment Operation.
std::condition_variable m_NotEmpty
Task Queue not empty.
uint32_t m_InitThreadSize
Initialized thread size.
auto SubmitPoolTask(Func &&func, Args &&... args) -> std::future< decltype(func(std::forward< Args >(args)...))>
Submit a task to task queue, and wait for a idle thread to execute it.
void ThreadFunc(Thread<> *thread)
Thread Function.
uint32_t m_ThreadIdleTimeOut
thread idle time out.
const std::unordered_map< uint32_t, std::unique_ptr< Thread< Params... > > > & GetThreads() const
Get Threads. This function is just used for unit test, should not be used in engine.
std::atomic_int m_NThreads
Threads Count.
ThreadPool_Basic(const ThreadPool_Basic &)=delete
Copy Constructor Function.
std::condition_variable m_IdleCond
Thread pool thread idle Condition.
void SubmitThreadTask_LightWeight(uint32_t threadId, std::function< void(Params...)> func)
Submit a task to specific thread.
void SubmitThreadTask_LightWeight_ForEach(std::function< void(Params...)> func)
Submit a task to all thread.
const int GetThreadIdleTimeOut() const
ThreadIdleTimeOut. This function is just used for unit test, should not be used in engine.
void Wait()
Wait for all tasks executed finish in taskqueue.
std::atomic_bool m_IsPoolRunning
True if this thread pool is in use.
const int GetInitThreadSize() const
GetInitThreadSize. This function is just used for unit test, should not be used in engine.
Thread Pool Basic Class. Instance inherited from it and use multithreading feature.
Thread & operator=(const Thread &)=delete
Copy Assignment Operation.
std::queue< ThreadTask > m_ThreadTasksQueue
Thread Tasks Queue.
void Start()
Start a thread to execute Thread Function.
virtual ~Thread()=default
Destructor Function.
std::atomic_int m_ThreadTasks
Thread Tasks Count.
Thread(const Thread &)=delete
Copy Constructor Function.
Thread(ThreadFunc func, uint32_t threadId)
Constructor Function.
void Wait() const
Wait for all thread tasks finished.
void SetThreadInTask(bool isInTask)
Set this Thread is in task or not.
void ReceiveThreadTask(std::function< void(Params...)> func)
Receive a task must execute by this thread.
uint32_t m_ThreadId
Thread Id.
uint32_t GetId() const
Get Thread Id.
bool GetThreadInTask() const
Get this Thread is in task or not.
int GetThreadTasksCount() const
Get Thread Tasks Count. @reutrn Returns the Thread Tasks Count.
ThreadFunc m_Func
Thread Function.
std::mutex m_Mutex
A Mutex for Thread.
std::atomic_bool m_IsInTask
True if this thread is executing a task.
auto RequireTask() -> ThreadTask
Get this mutex.
Thread Function Object.
float m_FrameTime
time step(s) during frames.
Definition TimeStep.h:85
std::chrono::steady_clock::time_point m_StartTime
Engine Start time.
Definition TimeStep.h:75
void Flush()
Refresh time in each engine loop.
Definition TimeStep.cpp:26
const float & ft() const
Get time step during frames.
Definition TimeStep.h:51
TimeStep(const TimeStep &)=delete
Copy Constructor Function.
const uint64_t & fs() const
Get frames count.
Definition TimeStep.h:63
TimeStep()
Constructor Function.
Definition TimeStep.cpp:12
virtual ~TimeStep()=default
Destructor Function.
std::chrono::steady_clock::time_point m_LastTime
Last frame time.
Definition TimeStep.h:80
float m_GameTime
time step(s) since Engine Start.
Definition TimeStep.h:90
uint64_t m_Frames
Frames since Engine Start.
Definition TimeStep.h:95
TimeStep & operator=(const TimeStep &)=delete
Copy Assignment Operation.
const float & gt() const
Get time step since Engine Start.
Definition TimeStep.h:57
This Class handles our engine time step during frames. Global Unique.
Definition TimeStep.h:22
static TracyGPUContext & Get()
Get this Single Instance.
static std::shared_ptr< TracyGPUContext > m_TracyGPUContext
This Single Instance.
virtual ~TracyGPUContext()=default
Destructor Function.
tracy::VkCtx * m_Context
Tracy Vulkan Context.
TracyGPUContext(VulkanState &state)
Constructor Function.
VulkanState & m_VulkanState
VulkanState.
tracy::VkCtx *& GetContext()
Get Context.
static void CreateInstance(VulkanState &state)
Create this Single Instance.
Wapper of Tracy GPU collect features.
UUID()
Constructor Function.
Definition UUID.cpp:18
uint64_t m_UUID
UUID.
Definition UUID.h:52
UUID(uint64_t uuid)
Constructor Function.
Definition UUID.cpp:22
UUID(const UUID &)=default
Destructor Function.
std::string ToString()
Transform UUID to String.
Definition UUID.cpp:26
operator uint64_t() const
Operator Function.
Definition UUID.h:39
This class helps to generate a uuid for one resource.
Definition UUID.h:16
VkBufferUsageFlags m_Usage
The buffer usage.
VkMemoryPropertyFlags m_Flags
The buffer memory requirement flags.
VkBuffer m_Buffer
The buffer this class handled.
void CreateBuffer(VulkanState &vulkanState, const std::string &name, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties)
Create a buffer.
VulkanBuffer(VulkanState &vulkanState, const std::string &name, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties)
Constructor Function. Create VkBuffer.
VmaAllocation m_Alloc
VMA allocation.
uint64_t GetSize() const
Get Buffer Size.
void CopyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
Copy data from a buffer to another.
void WriteToBuffer(const void *data, VkDeviceSize size=VK_WHOLE_SIZE, VkDeviceSize offset=0)
Write data to buffer.
VkDeviceSize m_DeviceSize
The buffer size.
VkDeviceAddress & GetAddress()
Get VkBuffer Address.
void Map(VkDeviceSize size=VK_WHOLE_SIZE, VkDeviceSize offset=0)
Map buffer video memory to a local memory.
void WriteFromBuffer(void *data, VkDeviceSize size=VK_WHOLE_SIZE, VkDeviceSize offset=0)
Write data from buffer.
VkDescriptorBufferInfo * GetBufferInfo(VkDeviceSize size=VK_WHOLE_SIZE, VkDeviceSize offset=0)
Get VkDescriptorBufferInfo.
virtual ~VulkanBuffer() override
Destructor Function.
VkDescriptorBufferInfo m_BufferInfo
VkDescriptorBufferInfo.
std::string m_Name
Buffer Name.
VkDeviceAddress m_BufferAddress
The buffer gpu address.
VulkanBuffer(VulkanState &vulkanState)
Constructor Function. Create VkBuffer.
VkBuffer & Get()
Get VkBuffer.
void Flush(VkDeviceSize size=VK_WHOLE_SIZE, VkDeviceSize offset=0) const
Flush the buffer's video memory data.
This Class is a Wrapper of VulkanBuffer.
static void EndLabel(VkCommandBuffer cmdBuffer)
End Record Commands with a Label.
static void BeginLabel(VkCommandBuffer cmdBuffer, const std::string &caption, glm::vec4 color=glm::vec4(1.0f))
Start Record Commands with a Label.
static void BeginQueueLabel(VkQueue queue, const std::string &caption, glm::vec4 color=glm::vec4(1.0f))
Start Record Queue with a Label.
static void SetObjectName(VkObjectType type, uint64_t handle, VkDevice &device, const std::string &caption)
Set Vulkan Object with a name, which can be captured.
static void InsertQueueLabel(VkQueue queue, const std::string &caption, glm::vec4 color=glm::vec4(1.0f))
Insert Record Queue with a Label.
static void SetObjectTag(VkObjectType type, uint64_t handle, VkDevice &device, const std::vector< char * > &captions)
Set Vulkan Object with tags, which can be captured.
static void InsertLabel(VkCommandBuffer cmdBuffer, const std::string &caption, glm::vec4 color=glm::vec4(1.0f))
Insert Record Commands with a Label.
static void EndQueueLabel(VkQueue queue)
End Record Queue with a Label.
This Class Defines static function for helping vulkan debug.
VulkanObject(const VulkanObject &)=delete
Copy Constructor Function.
virtual ~VulkanObject()=default
Destructor Function. We destroy pipeline layout here.
VulkanObject & operator=(const VulkanObject &)=delete
Copy Assignment Operation.
VulkanState & m_VulkanState
The global VulkanState Referenced from VulkanRenderBackend.
VulkanObject(VulkanState &vulkanState)
Constructor Function. Init member variables.
VulkanObject Class. This class defines the basic behaves of VulkanObject. When we create an new Vulka...
VkPipelineShaderStageCreateInfo GetShaderStageCreateInfo() const
virtual ~VulkanShaderModule() override
Destructor Function.
std::string GetShaderPath(const std::string &name, const std::string &shaderType)
Get shader path string.
VkShaderModule m_ShaderModule
The VkShaderModule this class handled.
VkShaderModule & Get()
Get VkShaderModule this class handled.
VulkanShaderModule(VulkanState &vulkanState, const std::string &shaderName, const std::string &shaderStage)
Constructor Function. Create VkShaderModule.
VulkanShaderModule(VulkanState &vulkanState, const std::string &shaderName, const ShaderStage &shaderStage, const std::vector< uint8_t > &spirv, const std::string &fullPath)
Constructor Function. Create VkShaderModule.
This Class is a Wrapper of VkShaderModule.
static void CreateMeshEntity(World *world, const std::string &name, const std::shared_ptr< Mesh > &mesh, std::function< void(Entity &)> onAdded=nullptr)
Create Entity with MeshComponent. Lightweight for game thread.
static void CreateMeshEntity(World *world, const std::string &name, std::function< std::shared_ptr< Mesh >()> onMeshCreated, std::function< void(Entity &)> onAdded=nullptr)
Create Entity with a Basic MeshComponent Async.
World Functions Class.
WorldMarkFlags GetMarker() const
Get WorldMarkFlags this frame.
Definition World.h:119
void ViewComponent(const std::vector< uint32_t > &ranges, uint32_t floor, uint32_t ceil, F &&fn)
View all component in this world in ranges.
Definition World.h:309
uint32_t WorldMarkFlags
Definition World.h:53
void Mark(WorldMarkFlags flags)
Mark WorldMarkFlags with flags.
Definition World.h:125
Entity CreateEntity(const std::string &name="None")
Create a new empty entity in this world.
Definition World.cpp:13
void OnComponentAdded(Entity *entity, T &component)
Called On any Component Added to this world.
Definition World.h:386
void ReserMark()
Reset WorldMarkFlags to Clean.
Definition World.h:130
void ViewRoot(F &&fn)
View all root in this world.
Definition World.h:329
Entity CreateEmptyEntity(UUID uuid)
Definition World.cpp:85
Entity CreateEntityWithUUID(UUID uuid, const std::string &name="None")
Create a new empty entity with a uuid in this world.
Definition World.cpp:20
void ViewComponent(F &&fn)
View all component in this world.
Definition World.h:276
void ViewComponent(const std::vector< uint32_t > &ranges, F &&fn)
View all component in this world in ranges.
Definition World.h:293
virtual void OnDeactivate()=0
This interface defines the specific world behaves after on activated.
virtual ~World()=default
Destructor Function.
Entity QueryEntitybyID(uint32_t id)
Get World Entity by id(entt::entity).
Definition World.cpp:41
virtual void OnPreActivate()=0
This interface define the specific world behaves before on activated.
entt::registry m_Registry
This variable handles all entity.
Definition World.h:250
std::shared_mutex m_Mutex
Mutex for world.
Definition World.h:245
void DestroyEntity(Entity &entity)
Destroy a entity from this world.
Definition World.cpp:31
T & GetComponent(entt::entity e)
Get Component owned by this entity.
Definition World.h:353
@ FrushStableFrame
Definition World.h:48
@ MeshAddedToWorld
Definition World.h:47
@ NeedUpdateTLAS
Definition World.h:49
void RemoveComponent(entt::entity e)
Remove Component owned from this entity.
Definition World.h:366
WorldMarkFlags m_Marker
World State this frame.
Definition World.h:272
entt::registry & GetRegistry()
Get Registry variable.
Definition World.h:106
void RemoveFromRoot(Entity &entity)
Remove a entity from this world root.
Definition World.cpp:58
virtual void OnActivate(TimeStep &ts)=0
This interface define the specific world behaves on activated.
void AddToRoot(Entity &entity)
Add a entity to this world root.
Definition World.cpp:67
World()=default
Constructor Function.
std::unordered_map< UUID, entt::entity > m_RootEntityMap
This variable is a cache. @noto Not in use now.
Definition World.h:257
bool IsRootEntity(Entity &entity)
Determine if a entity is in root.
Definition World.cpp:76
void ClearMarkerWithBits(WorldMarkFlags flags)
Clear WorldMarkFlags with flags.
Definition World.cpp:48
bool HasComponent(entt::entity e)
If Component is owned by this entity or not.
Definition World.h:376
T & AddComponent(entt::entity e, Args &&... args)
Template Function. Used for add specific component to entity.
Definition World.h:343
World Class. This class defines the basic behaves of World. When we create an new world,...
Definition World.h:41
virtual ~kd_tree()
Destructor Function.
Definition KDTree.h:596
void insert_recursive_async(Node *&node, std::shared_ptr< std::vector< item > > points, Spices::ThreadPool *threadPool, int depth)
Recursive function to insert a point into the kd_tree async.
Definition KDTree.h:320
size_t size() const
Get KD Tree size.
Definition KDTree.h:237
kd_tree()
Constructor to initialize the kd_tree with a null root.
Definition KDTree.h:158
void insert_async(const std::vector< item > &points, Spices::ThreadPool *threadPool)
Insert a point into the kd_tree async. Start at the root, comparing the new point’s first dimension w...
Definition KDTree.h:608
void insert_recursive(Node *&node, std::shared_ptr< std::vector< item > > points, int depth)
Recursive function to insert a point into the kd_tree.
Definition KDTree.h:241
void print() const
Public function to print the kd_tree.
Definition KDTree.h:672
std::atomic_size_t m_Size
Sizes of this kd tree.
Definition KDTree.h:81
Node * m_Root
Pointer to the root node of the tree.
Definition KDTree.h:76
void insert(const std::vector< item > &points)
Insert a point into the kd_tree. Start at the root, comparing the new point’s first dimension with th...
Definition KDTree.h:602
void range_search_recursive(Node *node, const item &point, const item &condition, std::vector< item > &rangePoints, int depth) const
Recursive function to search for all nearest points in the kd_tree.
Definition KDTree.h:463
void deletenode_recursive(Node *node)
Delete all node created by this ke_tree.
Definition KDTree.h:563
bool search_recursive(Node *node, const item &point, int depth) const
Recursive function to search for a point in the kd_tree.
Definition KDTree.h:421
auto nearest_neighbour_search(const item &point, const item &condition) const -> item
Search for a nearest point in the kd_tree. Traverse the tree as in a normal search to find the leaf n...
Definition KDTree.h:629
auto range_search(const item &point, const item &condition) const -> std::vector< item >
Search for all points within given range. Start at the root. If the current node is within the range,...
Definition KDTree.h:660
bool search(const item &point) const
Search for a point in the kd_tree. Start at the root, comparing the search point’s first dimension wi...
Definition KDTree.h:623
void print_recursive(Node *node, int depth) const
Recursive function to print the kd_tree.
Definition KDTree.h:529
The kd_tree with K dimensions container Class. K the number of dimensions. Every node in the tree is ...
Definition KDTree.h:27
void erase(const K &key)
Remove a element inside the container if founded by key.
V * find_value(const K &key)
Find the value by key.
void clear()
Clear this container's data.
V * prev_value(const K &key)
Get the previous element by the key.
std::shared_mutex m_Mutex
Mutex for this container.
void for_each(F &&fn)
Iter the container in order.
linked_unordered_map()
Constructor Function.
std::unordered_map< K, V > m_Map
void push_back(const K &key, const V &value)
Add a element to this container.
V * end()
Get the end element of this container.
bool has_key(const K &key)
Determine whether the key is in the container.
size_t size()
The container's element size.
void for_each(F &fn)
Iter the container in order.
std::list< K > m_Keys
The container keeps iter in order.
virtual ~linked_unordered_map()=default
Destructor Function.
std::atomic_int m_Size
This container size.
bool has_equal_size()
Determine whether the container's element size is same.
V * next_value(const K &key)
Get the next element by the key.
V * first()
Get the first element of this container.
The container combines hashmap and list together. Used in the case that we want iter a hashmap in ord...
size_t bytes_
The bytes of the continue memory block handled.
bool has_value(const std::string &name)
Determine is item inside this container.
void for_each(const std::function< bool(const std::string &name, void *pt)> &fn) const
Iter the object_ and call explain_element() to filling data.
std::unordered_map< std::string, size_t > object_
The data information of the continue memory block handled. Data: parameter name - parameter position ...
void build()
Malloc a memory to begin_.
void add_element(const std::string &name, const std::string &type)
Add a element to object_, means a memory block will be occupied with given param type.
size_t item_location(const std::string &name)
Get item location in blocks.
size_t get_bytes() const
Get the bytes_.
virtual ~runtime_memory_block()
Destructor Function.
size_t size() const
Get the size of object_.
void * begin_
The begin pointer of the continue memory block handled.
void explain_element(const std::string &name, const T &value)
Fill in a memory with given data.
runtime_memory_block()=default
Constructor Function.
void * get_addr() const
Get the begin_.
T & get_value(const std::string &name)
Get value that explained by name.
The container is wrapper of a continue memory block. Used in Material::BuildMaterial(),...
ShaderStage
enum of shader stage.
static const char * memoryPoolNames[3]
MemoryPool's name.
Definition Core.h:43
glm::mat4 OtrhographicMatrix(float left, float right, float top, float bottom, float nearPlane, float farPlane)
Calculate Otrhographic Matrix.
Definition Math.cpp:114
glm::mat4 PerspectiveMatrixInverseZ(float fov, float nearPlane, float aspectRatio)
Calculate Perspective Matrix(reverse z version).
Definition Math.cpp:127
PoolMode
ThreadPool Run Mode.
glm::mat4 PerspectiveMatrix(float fov, float nearPlane, float farPlane, float aspectRatio)
Calculate Perspective Matrix.
Definition Math.cpp:100
bool DecomposeTransform(const glm::mat4 &transform, glm::vec3 &outTranslation, glm::vec3 &outRotation, glm::vec3 &outScale)
Decompose matrix to split SRT transform.
Definition Math.cpp:15
TextureType
The enum of all Texture Type.
Definition Texture.h:20
std::shared_ptr< World > CreateWorld()
extern WorldCreation definition in Game.
Definition EntryPoint.cpp:6
static void HandleVkResult(VkResult result)
Handle VkResult Function.
Definition VulkanUtils.h:39
constexpr uint32_t THREAD_MAX_IDLE_TIME
constexpr uint32_t MaxFrameInFlight
Max In Flight Frame. 2 buffers are enough in this program.
Definition VulkanUtils.h:22
const uint32_t THREAD_MAX_THRESHHOLD
std::string to_string(const GFSDK_Aftermath_ShaderDebugInfoIdentifier &identifier)
Convert GFSDK_Aftermath_ShaderDebugInfoIdentifier to string.
std::string to_string(GFSDK_Aftermath_Result result)
Convert GFSDK_Aftermath_Result to string.
std::string to_hex_string(T n)
Convert T to hex string.
AccelStructure Wrapper.
Definition Attribute.h:17
MeshResource's item template.
Definition Attribute.h:28
std::string paramType
Definition Material.h:38
This struct's data is defined from .material file.
Definition Material.h:37
ConstantParam value
Definition Material.h:47
ConstantParam max
Definition Material.h:54
ConstantParam defaultValue
Definition Material.h:48
ConstantParam min
Definition Material.h:51
This struct's data is defined from .material file.
Definition Material.h:46
uint32_t prev
datas.
Definition Vertex.h:223
EdgePoint(uint32_t prev, uint32_t self, uint32_t next)
Constructor Function.
Definition Vertex.h:205
uint32_t next
Definition Vertex.h:225
bool valid()
Determine whether this edge point is valid.
Definition Vertex.h:215
EdgePoint()
Constructor Function.
Definition Vertex.h:193
uint32_t self
Definition Vertex.h:224
EdgePoint Class. This class defines what EdgePoint data.
Definition Vertex.h:187
Edge()=default
Constructor Function.
bool operator==(const Edge &other) const
Destructor Function. @attemtion Why Destructor causes bug here.
Definition Vertex.h:117
Edge(uint32_t f, uint32_t s)
Constructor Function.
Definition Vertex.h:99
bool operator<(const Edge &other) const
Less Operation.
Definition Vertex.h:127
Edge Class. This class defines what Edge data.
Definition Vertex.h:86
bool operator<(const HalfEdge &other) const
Less Operation.
Definition Vertex.h:177
HalfEdge()=default
Constructor Function.
bool operator==(const HalfEdge &other) const
Destructor Function. @attemtion Why Destructor causes bug here.
Definition Vertex.h:168
HalfEdge(uint32_t f, uint32_t s)
Constructor Function.
Definition Vertex.h:150
HalfEdge Class. This class defines what HalfEdge data.
Definition Vertex.h:137
uint32_t meshletOffset
Definition MeshPack.h:31
uint32_t nMeshlets
Definition MeshPack.h:32
uint32_t nPrimitives
Definition MeshPack.h:30
uint32_t primVertexOffset
Definition MeshPack.h:29
Lod Data.
Definition MeshPack.h:28
MeshDesc()
Constructor Function.
Definition MeshPack.cpp:29
MeshDesc Copy() const
Copy a MeshDesc from this.
Definition MeshPack.cpp:61
uint64_t GetBufferAddress() const
Get m_Buffer's Address.
Definition MeshPack.cpp:71
Add Construction Functions to SpicesShader::MeshDesc.
Definition MeshPack.h:90
MeshResource()=default
Constructor Function.
TexCoords texCoords
Definition MeshPack.h:71
Positions positions
Declare value.
Definition MeshPack.h:68
PrimitiveVertices primitiveVertices
Definition MeshPack.h:74
PrimitiveLocations primitiveLocations
Definition MeshPack.h:75
PrimitivePoints primitivePoints
Definition MeshPack.h:73
virtual ~MeshResource()=default
Destructor Function.
void CreateBuffer(const std::string &name)
Create MeshResource Buffers.
Definition MeshPack.cpp:14
Mesh Resources Data.
Definition MeshPack.h:39
std::vector< size_t > meshlets
MeshletGroup for simplify.
void FromMeshopt(const meshopt_Meshlet &m, const meshopt_Bounds &bounds)
Destructor Function. @attemtion Why Destructor causes bug here.
Definition Vertex.cpp:85
Meshlet()=default
Constructor Function.
Meshlet Class. This class defines what Meshlet data.
Definition Vertex.h:58
This struct defines the data used to create a texture2d. From render pass.
static constexpr char const * name
Define a named category tag type.
static constexpr char const * name
Define a custom domain tag type.
static constexpr char const * message
Define a registered string tag type.
String2()=default
Constructor Function.
std::string x
x component.
Definition Math.h:97
std::string y
y component.
Definition Math.h:102
virtual ~String2()=default
Destructor Function.
String2(const std::string &str0, const std::string &str1)
Constructor Function.
Definition Math.h:76
bool operator==(const String2 &other) const
equal operation.
Definition Math.h:88
double string
Definition Math.h:63
std::string texturePath
Definition Material.h:29
std::string textureType
Definition Material.h:28
This struct's data is defined from .material file.
Definition Material.h:27
uint32_t y
y component.
Definition Math.h:56
uint32_t x
x component.
Definition Math.h:51
UInt2()=default
Constructor Function.
bool operator==(const UInt2 &other) const
equal operation.
Definition Math.h:42
virtual ~UInt2()=default
Destructor Function.
UInt2(const uint32_t &x, const uint32_t &y)
Constructor Function.
Definition Math.h:30
double unsigned int
Definition Math.h:17
void Init(VkInstance instance)
Init All Vulkan Function Pointer.
Vulkan Function Pointers Collection. It holds all function pointer which need get manually.
VulkanState(const VulkanState &)=delete
Copy Constructor Function.
VkSwapchainKHR m_SwapChain
VkCommandPool m_GraphicCommandPool
std::array< VkSemaphore, MaxFrameInFlight > m_ComputeQueueSemaphore
VmaAllocator m_VmaAllocator
Definition VulkanUtils.h:97
std::array< VkImage, MaxFrameInFlight > m_SwapChainImages
std::array< VkImageView, MaxFrameInFlight > m_SwapChainImageViews
std::array< VkSemaphore, MaxFrameInFlight > m_GraphicQueueSemaphore
std::array< VkFence, MaxFrameInFlight > m_ComputeFence
std::array< VkSampler, MaxFrameInFlight > m_SwapChainImageSamplers
uint32_t m_ComputeQueueFamily
std::array< VkCommandBuffer, MaxFrameInFlight > m_GraphicCommandBuffer
VulkanFunctions m_VkFunc
Definition VulkanUtils.h:98
GLFWwindow * m_Windows
Definition VulkanUtils.h:92
VkInstance m_Instance
Definition VulkanUtils.h:93
uint32_t m_GraphicQueueFamily
VulkanState()=default
Constructor Function.
std::array< VkSemaphore, MaxFrameInFlight > m_GraphicImageSemaphore
VkSurfaceKHR m_Surface
Definition VulkanUtils.h:94
std::array< VkCommandBuffer, MaxFrameInFlight > m_ComputeCommandBuffer
VkPhysicalDevice m_PhysicalDevice
Definition VulkanUtils.h:95
VkCommandPool m_ComputeCommandPool
std::array< VkFence, MaxFrameInFlight > m_GraphicFence
VulkanState & operator=(const VulkanState &)=delete
Copy Assignment Operation.
This struct contains all Vulkan object in used global.
Definition VulkanUtils.h:74
virtual ~Node()
Destructor Function.
Definition KDTree.h:580
Node * m_Right
Pointer to right child.
Definition KDTree.h:68
Node * m_Left
Pointer to left child.
Definition KDTree.h:63
Node(const item &pt)
Constructor Function.
Definition KDTree.h:44
item m_Point
Array to store the coordinates.
Definition KDTree.h:58
size_t operator()(Spices::EdgePoint const &edgeP) const
Definition Vertex.h:255
size_t operator()(Spices::Edge const &edge) const
Definition Vertex.h:236
size_t operator()(Spices::HalfEdge const &edge) const
Definition Vertex.h:246
size_t operator()(Spices::String2 const &info) const noexcept
Definition Math.h:187
size_t operator()(Spices::UInt2 const &info) const noexcept
Definition Math.h:179
std::size_t operator()(const Spices::UUID &uuid) const noexcept
Definition UUID.h:62