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)),
125 scene(
std::make_unique<
Scene>(this)),
128 LOG_TRACE(logger,
"Created context.");
133 variables->set(
"renderer.graphicsDevice",
"Null");
136 LOG_INFO(logger,
"renderer.graphicsDevice is already set. Ignoring nowindow.");
146 dynamicComponentSystem = Memory::create<DynamicComponentSystem>(
memory->baseAllocator);
153 textureGenerator->cleanup();
155 if (
auto meshGenerator = services->getService<
MeshGenerator>()) {
156 meshGenerator->cleanup();
163 defaultView =
nullptr;
165 scriptingManager->cleanup();
169 taskManager->waitAll();
186 LOG_DEBUG(logger,
"Destroyed context.");
192 static bool initialized =
false;
195 LOG_WARNING(logger,
"Context already statically initialized.");
200 LOG_INFO(logger,
"COGS_VERSION_STRING %s", COGS_VERSION_STRING);
201 LOG_INFO(logger,
"COGS_GIT_REVISION %s", COGS_XQUOTE(COGS_GIT_REVISION));
211 LOG_DEBUG(logger,
"Initialized types for reflection.");
217 static bool cleaned =
false;
220 LOG_WARNING(logger,
"Context already statically cleaned.");
225 Cogs::Core::cleanupTypes();
226 Cogs::Core::Strings::cleanup();
229bool Cogs::Core::Context::createDevice()
232 auto deviceType = parseEnum<GraphicsDeviceType>(variables->get(
"renderer.graphicsDevice",
"Default"),
GraphicsDeviceType::Default);
237 LOG_WARNING(logger,
"Device could not be created using the given type id: %d",
static_cast<int>(deviceType));
238 LOG_INFO(logger,
"Trying to create default device.");
244 LOG_INFO(logger,
"Successfully created fallback device of type %s", device->getIdentifier().c_str());
248 LOG_INFO(logger,
"Initialized device of type %s", device->getIdentifier().c_str());
252 LOG_ERROR(logger,
"Could not create graphics device. Destroying context.");
256 GraphicsDeviceSettings settings = {};
257 settings.windowData = getDefaultView()->refWindowData();
262 settings.featureLevelMajor = 4;
263 settings.featureLevelMinor = 6;
266 settings.numSamples = variables->get(
"renderer.samples", 2);
268 if (variables->get(
"cache.enableShaderCache",
false)) {
272 if (variables->get(
"effects.dumpShaders",
false)) {
276 if (variables->get(
"renderer.forceSoftwareRendering",
false)) {
280 if (variables->get(
"renderer.sharedSurface",
false)) {
284 if (variables->get(
"renderer.debugDevice",
false)) {
288 if (variables->get(
"renderer.useSwapEffectDiscard",
false)) {
292 if (!variables->get(
"renderer.disableClipControl",
false)) {
296 settings.colorFormat = parseTextureFormat(variables->get(
"renderer.colorFormat",
"R8G8B8A8_UNORM_SRGB"), TextureFormat::R8G8B8A8_UNORM_SRGB);
297 settings.depthFormat = parseTextureFormat(variables->get(
"renderer.depthFormat",
"D32_FLOAT"), TextureFormat::D32_FLOAT);
298 settings.ioHandler = resourceStore->getIOHandler();
299 settings.sharedSurface = &sharedSurface;
301 return device->setSettings(settings);
305 scriptingManager->initialize();
315 LOG_TRACE(logger,
"Initialized static systems.");
336 initializeDynamicComponents();
338 materialManager->initializeDefaultMaterial();
339 materialInstanceManager->initializeDefaultMaterialInstance();
341 LOG_TRACE(logger,
"Initializing extensions...");
345 LOG_TRACE(logger,
"Extensions initialized.");
349 defaultView->initialize(
nullptr);
358 transformSystem->setOrigin({ 0, 0, 0 });
364 registerDynamicComponentType(
"CurvedEarthPositionComponent");
365 registerDynamicComponentType(
"FollowComponent");
366 registerDynamicComponentType(
"FontSelectorComponent");
367 registerDynamicComponentType(
"TrajectoryAlignedComponent");
368 registerDynamicComponentType(
"ReflectionComponent");
369 registerDynamicComponentType(
"BasicTerrainComponent");
370 registerDynamicComponentType(
"NearLimitComponent");
371 registerDynamicComponentType(
"ExpressionComponent");
372 registerDynamicComponentType(
"FPSNavigationComponent");
373 registerDynamicComponentType(
"TeleportNavigationComponent");
374 registerDynamicComponentType(
"PickingBeamComponent");
375 registerDynamicComponentType(
"MotionComponent");
376 registerDynamicComponentType(
"SwitchComponent");
377 registerDynamicComponentType(
"OrbitingCameraController");
384 if (!type.isValid()) {
385 LOG_ERROR(logger,
"Cannot register %.*s as dynamic component. Did you forget to register the type?", StringViewFormat(typeName));
390 auto base = type.getBase();
391 while (base && base != &Reflection::TypeDatabase::getType<DynamicComponent>()) {
392 base = base->getBase();
396 LOG_ERROR(logger,
"Cannot register %.*s as dynamic component without inheriting from DynamicComponent base class.", StringViewFormat(typeName));
398 assert(
false &&
"Invalid dynamic component base class.");
401 dynamicComponentSystem->registerType(
this, type);
406 extensionSystems->systems[id] = system;
410 if (engine && engine->isReady()) {
417 return extensionSystems->systems[id];
420void Cogs::Core::Context::update() {
423 taskManager->updateState(
this);
426 services->dispatchFrameCallbacks();
433void Cogs::Core::Context::preRender() {
434 for (
auto & c : cameraSystem->pool) {
436 cullingManager->dispatchCulling(&cameraSystem->getData(&c));
439 lightSystem->preRender(
this);
441 if (callbacks.preRenderCallback) {
442 callbacks.preRenderCallback(
this);
444 for (ViewContext* view : views) {
450 ViewContext* viewContext =
new ViewContext(
this, windowData);
452 views.push_back(viewContext);
456void Cogs::Core::Context::deleteView(ViewContext* view) {
457 auto e = views.end();
458 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.
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.