3#include "MemoryContext.h"
4#include "ViewContext.h"
8#include "ExtensionRegistry.h"
10#include "EntityStore.h"
14#include "Renderer/CullingManager.h"
15#include "Renderer/RenderResources.h"
16#include "Renderer/RenderTexture.h"
17#include "Renderer/Renderer.h"
19#include "Scene/RayPick.h"
20#include "Scene/GetBounds.h"
22#include "Services/PipelineService.h"
23#include "Services/QualityService.h"
24#include "Services/Services.h"
25#include "Services/DPIService.h"
26#include "Services/Features.h"
27#include "Services/Variables.h"
28#include "Services/TaskManager.h"
29#include "Services/Time.h"
30#include "Services/Random.h"
31#include "Services/DeferredNameResolution.h"
32#include "Services/ResourceUsageLogger.h"
34#include "Scripting/ScriptingManager.h"
36#include "Components/Data/TrajectoryComponent.h"
37#include "Components/Data/DataSetComponent.h"
38#include "Components/Geometry/MarkerPointSetComponent.h"
40#include "Generators/MeshGenerator.h"
41#include "Generators/TextureGenerator.h"
43#include "Input/InputManager.h"
45#include "Systems/Core/DynamicComponentSystem.h"
46#include "Systems/Core/InstancedModelSystem.h"
47#include "Systems/Core/LightSystem.h"
48#include "Systems/Core/ModelSystem.h"
50#include "Systems/Data/TrajectorySystem.h"
52#include "Systems/Geometry/ExtrusionSystem.h"
53#include "Systems/Geometry/ShapeSystem.h"
54#include "Systems/Geometry/VariableExtrusionSystem.h"
55#include "Systems/Geometry/MarkerPointSetSystem.h"
56#include "Systems/Geometry/MeshGeneratorSystem.h"
57#include "Systems/Geometry/AdaptivePlanarGridSystem.h"
59#include "Systems/Appearance/MaterialSystem.h"
60#include "Systems/Appearance/TextureGeneratorSystem.h"
61#include "Systems/Appearance/BasicOceanSystem.h"
62#include "Systems/Appearance/ScreenSizeSystem.h"
64#include "Systems/Layout/TrajectoryLayoutSystem.h"
66#include "Resources/MaterialManager.h"
67#include "Resources/ModelManager.h"
68#include "Resources/ResourceStore.h"
69#include "Resources/Texture.h"
70#include "Resources/TextureManager.h"
72#include "ResourceManifest.h"
74#include "Serialization/AssetReader.h"
76#include "../Extensions/Components/FollowComponent.h"
78#include "Rendering/Factory.h"
79#include "Rendering/ISwapChain.h"
81#include "Foundation/Logging/Logger.h"
82#include "Foundation/Platform/FileSystemWatcher.h"
83#include "Foundation/Platform/WindowData.h"
98 std::unordered_map<Reflection::TypeId, ComponentSystemBase *> systems;
103Cogs::Core::Context::Context() : Context(nullptr, 0) {
110 variables(
std::make_unique<
Variables>(variableValues, count)),
116 time(
std::make_unique<
Time>(this)),
124 scene(
std::make_unique<
Scene>(this)),
127 LOG_TRACE(logger,
"Created context.");
129 if (
variables->exist(
"filesystemwatcher")) {
130 LOG_INFO(logger,
"Enabling filesystemwatcher for auto-reload");
131 watcher = std::make_unique<FileSystemWatcher>();
137 variables->set(
"renderer.graphicsDevice",
"Null");
140 LOG_INFO(logger,
"renderer.graphicsDevice is already set. Ignoring nowindow.");
150 dynamicComponentSystem = Memory::create<DynamicComponentSystem>(
memory->baseAllocator);
157 textureGenerator->cleanup();
159 if (
auto meshGenerator = services->getService<
MeshGenerator>()) {
160 meshGenerator->cleanup();
167 defaultView =
nullptr;
169 scriptingManager->cleanup();
173 taskManager->waitAll();
190 LOG_DEBUG(logger,
"Destroyed context.");
196 static bool initialized =
false;
199 LOG_WARNING(logger,
"Context already statically initialized.");
204 LOG_INFO(logger,
"COGS_VERSION_STRING %s", COGS_VERSION_STRING);
205 LOG_INFO(logger,
"COGS_GIT_REVISION %s", COGS_XQUOTE(COGS_GIT_REVISION));
215 LOG_DEBUG(logger,
"Initialized types for reflection.");
221 static bool cleaned =
false;
224 LOG_WARNING(logger,
"Context already statically cleaned.");
229 Cogs::Core::cleanupTypes();
230 Cogs::Core::Strings::cleanup();
233bool Cogs::Core::Context::createDevice()
236 auto deviceType = parseEnum<GraphicsDeviceType>(variables->get(
"renderer.graphicsDevice",
"Default"),
GraphicsDeviceType::Default);
241 LOG_WARNING(logger,
"Device could not be created using the given type id: %d",
static_cast<int>(deviceType));
242 LOG_INFO(logger,
"Trying to create default device.");
248 LOG_INFO(logger,
"Successfully created fallback device of type %s", device->getIdentifier().c_str());
252 LOG_INFO(logger,
"Initialized device of type %s", device->getIdentifier().c_str());
256 LOG_ERROR(logger,
"Could not create graphics device. Destroying context.");
260 GraphicsDeviceSettings settings = {};
261 settings.windowData = getDefaultView()->refWindowData();
266 settings.featureLevelMajor = 4;
267 settings.featureLevelMinor = 6;
270 settings.numSamples = variables->get(
"renderer.samples", 2);
272 if (variables->get(
"cache.enableShaderCache",
false)) {
276 if (variables->get(
"effects.dumpShaders",
false)) {
280 if (variables->get(
"renderer.forceSoftwareRendering",
false)) {
284 if (variables->get(
"renderer.sharedSurface",
false)) {
288 if (variables->get(
"renderer.debugDevice",
false)) {
292 if (variables->get(
"renderer.useSwapEffectDiscard",
false)) {
296 if (!variables->get(
"renderer.disableClipControl",
false)) {
300 settings.colorFormat = parseTextureFormat(variables->get(
"renderer.colorFormat",
"R8G8B8A8_UNORM_SRGB"), TextureFormat::R8G8B8A8_UNORM_SRGB);
301 settings.depthFormat = parseTextureFormat(variables->get(
"renderer.depthFormat",
"D32_FLOAT"), TextureFormat::D32_FLOAT);
302 settings.ioHandler = resourceStore->getIOHandler();
303 settings.sharedSurface = &sharedSurface;
305 return device->setSettings(settings);
309 scriptingManager->initialize();
319 LOG_TRACE(logger,
"Initialized static systems.");
340 initializeDynamicComponents();
342 materialManager->initializeDefaultMaterial();
343 materialInstanceManager->initializeDefaultMaterialInstance();
345 LOG_TRACE(logger,
"Initializing extensions...");
349 LOG_TRACE(logger,
"Extensions initialized.");
353 defaultView->initialize(
nullptr);
362 transformSystem->setOrigin({ 0, 0, 0 });
368 registerDynamicComponentType(
"CurvedEarthPositionComponent");
369 registerDynamicComponentType(
"FollowComponent");
370 registerDynamicComponentType(
"FontSelectorComponent");
371 registerDynamicComponentType(
"TrajectoryAlignedComponent");
372 registerDynamicComponentType(
"ReflectionComponent");
373 registerDynamicComponentType(
"BasicTerrainComponent");
374 registerDynamicComponentType(
"NearLimitComponent");
375 registerDynamicComponentType(
"ExpressionComponent");
376 registerDynamicComponentType(
"FPSNavigationComponent");
377 registerDynamicComponentType(
"TeleportNavigationComponent");
378 registerDynamicComponentType(
"PickingBeamComponent");
379 registerDynamicComponentType(
"MotionComponent");
380 registerDynamicComponentType(
"SwitchComponent");
381 registerDynamicComponentType(
"OrbitingCameraController");
388 if (!type.isValid()) {
389 LOG_ERROR(logger,
"Cannot register %.*s as dynamic component. Did you forget to register the type?", StringViewFormat(typeName));
394 auto base = type.getBase();
395 while (base && base != &Reflection::TypeDatabase::getType<DynamicComponent>()) {
396 base = base->getBase();
400 LOG_ERROR(logger,
"Cannot register %.*s as dynamic component without inheriting from DynamicComponent base class.", StringViewFormat(typeName));
402 assert(
false &&
"Invalid dynamic component base class.");
405 dynamicComponentSystem->registerType(
this, type);
410 extensionSystems->systems[id] = system;
414 if (engine && engine->isReady()) {
421 return extensionSystems->systems[id];
424void Cogs::Core::Context::update() {
427 taskManager->updateState(
this);
430 services->dispatchFrameCallbacks();
437void Cogs::Core::Context::preRender() {
438 for (
auto & c : cameraSystem->pool) {
440 cullingManager->dispatchCulling(&cameraSystem->getData(&c));
443 lightSystem->preRender(
this);
445 if (callbacks.preRenderCallback) {
446 callbacks.preRenderCallback(
this);
448 for (ViewContext* view : views) {
454 ViewContext* viewContext =
new ViewContext(
this, windowData);
456 views.push_back(viewContext);
460void Cogs::Core::Context::deleteView(ViewContext* view) {
461 auto e = views.end();
462 auto i = std::find(views.begin(), e, view);
Utility class for bounds calculation of Scene / Entity.
Base class for component systems.
virtual void initialize(Context *context)
Initialize the system.
Typed component system managing a pool of components with the given ComponentType.
static void cleanupStatic()
Perform static cleanup of the Context.
class ComponentSystemBase * getExtensionSystem(const uint16_t id)
Retrieve the system with the given id.
void initializeDynamicComponents()
Initialize and register dynamic component types.
void initialize()
Initialize all services and component systems.
static void initializeStatic()
Perform static initialization of the Context.
void clear()
Does clearing of context.
void registerDynamicComponentType(const StringView &typeName)
Register a dynamic component type with the given typeName.
class EntityStore * store
Entity store.
std::unique_ptr< struct MemoryContext > memory
Memory and allocation info.
std::unique_ptr< class Variables > variables
Variables service instance.
Context(const char **variables, int count)
Constructs a new context instance, initializing all services, an engine instance, and extension syste...
std::unique_ptr< class ResourceStore > resourceStore
ResourceStore service instance.
void registerExtensionSystem(const uint16_t id, class ComponentSystemBase *system)
Register an extension component system using the given id.
~Context() override
Destructs a context instance.
std::unique_ptr< FileSystemWatcher > watcher
File system watcher.
The engine owns all the systems and resource managers, and is responsible for executing different sta...
Stores top level entities for the engine.
static void initialize(Context *context)
Performs initialization of all extensions registered with add().
static void initializeStatic()
Performs static initialization of all extensions registered with add().
Contains extension systems accessible by key.
Updates material components.
Provides handling of reading and caching of external resources.
Manages Task queuing and execution.
Provides time services for components depending on elapsed or system time for animation or other trac...
Manages runtime variables for the engine.
Log implementation class.
static const Type & getType()
Get the Type of the given template argument.
Provides a weakly referenced view over the contents of a string.
@ EnableRender
Renderable.
@ NoDefault
Don't load the default scene. Highly recommended as not setting this flag cause extra scene parse.
constexpr Log getLogger(const char(&name)[LEN]) noexcept
Contains all Cogs related functionality.
@ Default
Default type of graphics device, same as unknown.
@ OpenGL20
Graphics device using OpenGL, supporting at least OpenGL 2.0.
@ ForceSoftwareRendering
Force software rendering.
@ DumpShaderContents
Dump shader contents for debugging.
@ EnableShaderCache
Enables using a shader cache to avoid recompiling previously seen shaders.
@ UseOpenGLClipControl
For OpenGL / OpenGLES backends.
@ Debug
If available, the device will operate in debug mode, performing additional validation of input data,...
@ UseSwapEffectDiscard
Under DX11 the default swap effect is FLIP_DISCARD, however there are some systems where this does no...
@ UseSharedSurface
Use shared surface for D3D9 interop.
@ PreTransform
Run before transformations are updated.
@ PreRendering
Run before rendering is performed.
@ PostView
Run after view data has been updated. Anything after this is appropriate for geometry depending on e....
@ Geometry
Run at the time geometry data is updated.
@ PreLightView
Run after view, but before the time light views are updated.
@ PostTransform
Run immediately after transformations are updated.
static void releaseDevice(class IGraphicsDevice *device)
Release the given graphics device, freeing all associated resources.
static class IGraphicsDevice * createDevice(RenderingAllocatorInfo *allocatorInfo=nullptr)
Creates a graphics device.
Memory::Allocator * baseAllocator
Base allocator. Used for misc. internal memory allocations.