Cogs.Core
TwinVisualsTexAtlasRenderTask.cpp
1#include "Foundation/Logging/Logger.h"
2
3#include "Rendering/IGraphicsDevice.h"
4#include "Rendering/IContext.h"
5#include "Rendering/IEffects.h"
6#include "Rendering/IBuffers.h"
7#include "Rendering/IRenderTargets.h"
8#include "Rendering/ICapabilities.h"
9
10#include "Context.h"
11#include "ExtensionRegistry.h"
12
13#include "Systems/Core/LightSystem.h"
14
15#include "Renderer/Renderer.h"
16#include "Renderer/RenderStates.h"
17#include "Renderer/RenderTarget.h"
18#include "Renderer/RenderTexture.h"
19#include "Renderer/RenderPipelineDefinition.h"
20#include "Renderer/EngineBuffers.h"
21
22#include "Systems/Core/EnvironmentSystem.h"
23#include "Systems/Core/TransformSystem.h"
24
25#include "Utilities/Parsing.h"
26#include "Utilities/Preprocessor.h"
27#include "Resources/ResourceStore.h"
28
29#include "../../TexAtlas/Source/TexAtlasComponent.h"
30#include "../../TexAtlas/Source/TexAtlasSystem.h"
31
32#include "TwinVisualsSystem.h"
33#include "TwinVisualsComponent.h"
34#include "TwinVisualsTexAtlasRenderTask.h"
35
36#include <glm/gtc/color_space.hpp>
37#include <sstream>
38#include <regex>
39#include <map>
40
41namespace {
42 using namespace Cogs::Core;
43
44 Cogs::Logging::Log logger = Cogs::Logging::getLogger("TwinVisuals");
45
46 // Convert remaining #define directives to WGSL const expressions.
47 [[nodiscard]]
48 std::string convertDefinesToConst(const std::string& s) {
49 std::string result;
50 result.reserve(s.size());
51 std::istringstream iss(s);
52 std::regex e1("^\\s*#define\\s+([^\\s]+)\\s+([^\\s]+)");
53 std::regex e2("^\\s*#define\\s+([^\\s]+)\\s*$");
54 std::map<std::string, std::string> added;
55 for (std::string line; std::getline(iss, line); ) {
56 std::smatch match;
57 std::string id, val;
58 if (std::regex_search(line, match, e1)) {
59 id = match.str(1); val = match.str(2);
60 } else if (std::regex_search(line, match, e2)) {
61 id = match.str(1); val = "1";
62 }
63 if (id.empty()) {
64 result += line + "\n";
65 continue;
66 }
67 if (added.count(id)) continue;
68 result += "const " + id + " = " + val + ";\n";
69 added[id] = val;
70 }
71 return result;
72 }
73
74 // Preprocess a WGSL shader with the partial preprocessor.
75 [[nodiscard]]
76 std::string preprocessWgslShader(RenderTaskContext* rtc, const std::string& shaderPath,
77 const EffectDescription& desc, const std::string& suffix)
78 {
79 std::string src;
80 for (const auto& d : desc.definitions) {
81 src += "#define " + d.first + " " + d.second + "\n";
82 }
83 src += "#include \"" + shaderPath + "\"\n";
84
86 if (!pp.process(rtc->context, src)) {
87 LOG_ERROR(logger, "TwinVisualsTexAtlasRenderTask: Failed to preprocess %s", shaderPath.c_str());
88 return {};
89 }
90 src.swap(pp.processed);
91 src = convertDefinesToConst(src);
92
93 size_t code = Cogs::hash(src);
94 std::string resourcePath = "TwinVisuals/Shaders/TexAtlasTask" + suffix + "_" + std::to_string(code) + ".wgsl";
95 rtc->context->resourceStore->addResource(resourcePath, src);
96 return resourcePath;
97 }
98
99 void setupGlobalBindings(RenderTaskContext* renderTaskContext, GlobalBinding& globalBinding, Cogs::EffectHandle effect)
100 {
101 Cogs::IEffects* effects = renderTaskContext->device->getEffects();
102
103 globalBinding.sceneBufferBinding = effects->getConstantBufferBinding(effect, "SceneBuffer");
104
105 globalBinding.shadowArrayBinding = effects->getTextureBinding(effect, "cascadedShadowMap", 1);
106 globalBinding.shadowArrayBinding_1 = effects->getTextureBinding(effect, "cascadedShadowMap_1", 1);
107 globalBinding.shadowCubeArrayBinding = effects->getTextureBinding(effect, "cubeShadowMap", 2);
108 globalBinding.shadowCubeArrayBinding_1 = effects->getTextureBinding(effect, "cubeShadowMap_1", 2);
109 globalBinding.shadowSamplerBinding = effects->getSamplerStateBinding(effect, "cascadedShadowSampler", 2);
110
111 globalBinding.linearSampler = effects->getSamplerStateBinding(effect, "linearSampler", 0);
112 globalBinding.radianceSamplerBinding = effects->getSamplerStateBinding(effect, "environmentRadianceSampler", 0);
113 globalBinding.irradianceSamplerBinding = effects->getSamplerStateBinding(effect, "environmentIrradianceSampler", 0);
114 globalBinding.ambientIrradianceSamplerBinding = effects->getSamplerStateBinding(effect, "ambientIrradianceSampler", 0);
115
116 globalBinding.skyBinding = effects->getTextureBinding(effect, "environmentSky", 0);
117 globalBinding.skySamplerBinding = effects->getSamplerStateBinding(effect, "environmentSkySampler", 0);
118 }
119
120 void applyGlobalBindings(RenderTaskContext* renderTaskContext, GlobalBinding& globalBinding)
121 {
122 Cogs::IContext* deviceContext = renderTaskContext->device->getImmediateContext();
123 EngineBuffers* engineBuffers = renderTaskContext->engineBuffers;
124 RenderResources* resources = renderTaskContext->resources;
125 RenderStates* states = renderTaskContext->states;
126
127 if (HandleIsValid(globalBinding.sceneBufferBinding)) {
128 deviceContext->setConstantBuffer(globalBinding.sceneBufferBinding, engineBuffers->sceneBufferHandle);
129 }
130
131 if (bool shadowsEnabled = renderTaskContext->context->variables->get("renderer.shadowsEnabled", false); shadowsEnabled) {
132 LightSystem* lightSystem = renderTaskContext->context->lightSystem;
133
134 if (HandleIsValid(globalBinding.shadowArrayBinding)) {
135 if (RenderTexture* shadowTexture = resources->getRenderTexture(lightSystem->cascadeArray); shadowTexture) {
136 deviceContext->setTexture(globalBinding.shadowArrayBinding, shadowTexture->textureHandle);
137 }
138 }
139
140 if (HandleIsValid(globalBinding.shadowArrayBinding_1)) {
141 if (RenderTexture* shadowTexture = resources->getRenderTexture(lightSystem->cascadeArray); shadowTexture) {
142 deviceContext->setTexture(globalBinding.shadowArrayBinding_1, shadowTexture->textureHandle);
143 }
144 }
145
146 if (HandleIsValid(globalBinding.shadowCubeArrayBinding)) {
147 if (RenderTexture* shadowTexture = resources->getRenderTexture(lightSystem->cubeArray); shadowTexture) {
148 deviceContext->setTexture(globalBinding.shadowCubeArrayBinding, shadowTexture->textureHandle);
149 }
150 }
151
152 if (HandleIsValid(globalBinding.shadowCubeArrayBinding_1)) {
153 if (RenderTexture* shadowTexture = resources->getRenderTexture(lightSystem->cubeArray); shadowTexture) {
154 deviceContext->setTexture(globalBinding.shadowCubeArrayBinding_1, shadowTexture->textureHandle);
155 }
156 }
157
158 if (HandleIsValid(globalBinding.shadowSamplerBinding)) {
159 deviceContext->setSamplerState(globalBinding.shadowSamplerBinding, states->shadowSampler);
160 }
161 }
162
163 if (HandleIsValid(globalBinding.radianceSamplerBinding)) {
164 deviceContext->setSamplerState(globalBinding.radianceSamplerBinding, states->defaultSampler);
165 }
166 if (HandleIsValid(globalBinding.irradianceSamplerBinding)) {
167 deviceContext->setSamplerState(globalBinding.irradianceSamplerBinding, states->defaultSampler);
168 }
169 if (HandleIsValid(globalBinding.ambientIrradianceSamplerBinding)) {
170 deviceContext->setSamplerState(globalBinding.ambientIrradianceSamplerBinding, states->defaultSampler);
171 }
172 if (HandleIsValid(globalBinding.brdfLUTSamplerBinding)) {
173 deviceContext->setSamplerState(globalBinding.brdfLUTSamplerBinding, states->defaultSampler);
174 }
175 if (HandleIsValid(globalBinding.linearSampler)) {
176 deviceContext->setSamplerState(globalBinding.linearSampler, states->defaultSampler);
177 }
178
179 if (HandleIsValid(globalBinding.skyBinding)) {
180 EnvironmentSystem* environmentSystem = renderTaskContext->context->environmentSystem;
181 EnvironmentComponent* env = environmentSystem ? environmentSystem->getGlobalEnvironment() : nullptr;
182 if (env && env->skyDome) {
183 if (RenderTexture* skyTexture = renderTaskContext->renderer->getRenderResources().getRenderTexture(env->skyDome); skyTexture) {
184 deviceContext->setTexture(globalBinding.skyBinding, skyTexture->textureHandle);
185 }
186 }
187 }
188 if (HandleIsValid(globalBinding.skySamplerBinding)) {
189 deviceContext->setSamplerState(globalBinding.skySamplerBinding, states->defaultSampler);
190 }
191 }
192
193 Cogs::ResourceStatus setupEffect(RenderTaskContext* renderTaskContext, TwinVisualsTexAtlasRenderTask& task, TexAtlasState& state)
194 {
195 const RenderSettings& renderSettings = renderTaskContext->renderer->getSettings();
196 const bool reverseDepth = renderTaskContext->context->variables->get("renderer.reverseDepth", false);
197
199 switch (renderTaskContext->renderer->getDevice()->getType()) {
201 desc.vs = "TwinVisuals/Shaders/TexAtlasTaskVS.es30.glsl";
202 desc.ps = "TwinVisuals/Shaders/TexAtlasTaskPS.es30.glsl";
203 break;
205 desc.vs = "TwinVisuals/Shaders/TexAtlasTaskVS.wgsl";
206 desc.ps = "TwinVisuals/Shaders/TexAtlasTaskPS.wgsl";
207 break;
208 default:
209 LOG_ERROR(logger, "TwinVisualsTexAtlasRenderTask: entity does not have a TexAtlasComponent");
210 task.effectStatus = Cogs::ResourceStatus::Error;
212 }
213
214 EnginePermutation* permutation = renderTaskContext->renderer->getEnginePermutations().get("Forward");
215 for (auto& d : permutation->getDefinition()->definitions) {
216 desc.definitions.emplace_back(d.first, d.second);
217 }
218
219 if (reverseDepth) {
220 desc.definitions.push_back({ "COGS_REVERSE_DEPTH", "1" });
221 }
222
223 // See Default.permutations for defines.
224 switch (renderSettings.sRGBConversion) {
225 case RenderSettings::SRGBConversion::Fast:
226 desc.definitions.push_back({ "COGS_SRGB_CONVERSION_FAST", "1" });
227 break;
228 case RenderSettings::SRGBConversion::Approx:
229 desc.definitions.push_back({ "COGS_SRGB_CONVERSION_APPROX", "1" });
230 break;
231 case RenderSettings::SRGBConversion::Exact:
232 desc.definitions.push_back({ "COGS_SRGB_CONVERSION_EXACT", "1" });
233 break;
234 default:
235 assert(false && "Invalid enum");
236 break;
237 }
238
239 // See Default.permutations for defines.
240 switch (renderSettings.tonemapper) {
241 case RenderSettings::Tonemapper::Reinhard:
242 desc.definitions.push_back({ "COGS_TONEMAP_REINHARD", "1" });
243 break;
244 case RenderSettings::Tonemapper::Filmic:
245 desc.definitions.push_back({ "COGS_TONEMAP_FILMIC", "1" });
246 break;
247 case RenderSettings::Tonemapper::ACESLuminance:
248 desc.definitions.push_back({ "COGS_TONEMAP_ACES_LUMINANCE", "1" });
249 break;
250 case RenderSettings::Tonemapper::PBRNeutral:
251 desc.definitions.push_back({ "COGS_TONEMAP_PBR_NEUTRAL", "1" });
252 break;
253 default:
254 assert(false && "Invalid enum");
255 break;
256 }
257
258 if (renderTaskContext->context->variables->get("renderer.backBuffer.sRGB", true)) {
259 desc.definitions.emplace_back("OUTPUT_SRGB", "1");
260 }
261 if (task.inputSrgb) {
262 desc.definitions.emplace_back("INPUT_SRGB", "1");
263 }
264 if (task.lumaInAlpha) {
265 desc.definitions.emplace_back("LUMA_IN_ALPHA", "1");
266 }
267
268 static const std::string keys[4] = {
269 "TEX_ATLAS_LEVELS_0",
270 "TEX_ATLAS_LEVELS_1",
271 "TEX_ATLAS_LEVELS_2",
272 "TEX_ATLAS_LEVELS_3"
273 };
274 for (size_t i = 0; i < 4; i++) {
275 if (0 < state.levels[i]) {
276 desc.definitions.emplace_back(keys[i], std::to_string(state.levels[i]));
277 }
278 }
279
280 switch (state.style) {
281 case TwinVisualsTexAtlasStyle::Grayscale:
282 desc.definitions.emplace_back("TEX_ATLAS_COLORING_GRAYSCALE", "1");
283 break;
284 case TwinVisualsTexAtlasStyle::None:
285 desc.definitions.emplace_back("TEX_ATLAS_COLORING_NONE", "1");
286 break;
287 case TwinVisualsTexAtlasStyle::Color:
288 break;
289 default:
290 assert(false && "Invalid enum");
291 break;
292 }
293
294 EnvironmentSystem* environmentSystem = renderTaskContext->context->environmentSystem;
295 EnvironmentComponent* env = environmentSystem ? environmentSystem->getGlobalEnvironment() : nullptr;
296 if (env && env->skyDome) {
297 desc.definitions.emplace_back("SKY_CUBEMAP", "1");
298 }
299
300 // For WebGPU, run the partial preprocessor to handle #ifdef/#include in WGSL
301 if (renderTaskContext->renderer->getDevice()->getType() == Cogs::GraphicsDeviceType::WebGPU) {
302 std::string vsPath = preprocessWgslShader(renderTaskContext, desc.vs, desc, "VS");
303 std::string psPath = preprocessWgslShader(renderTaskContext, desc.ps, desc, "PS");
304 if (vsPath.empty() || psPath.empty()) {
305 LOG_ERROR(logger, "TwinVisualsTexAtlasRenderTask: Failed to preprocess WGSL shaders");
306 task.effectStatus = Cogs::ResourceStatus::Error;
308 }
309 desc.vs = vsPath;
310 desc.ps = psPath;
311 desc.definitions.clear();
312 }
313
314 CachedEffect* effect = renderTaskContext->renderer->getEffectCache().loadEffect(renderTaskContext, desc);
315
316 Cogs::IEffects* effects = renderTaskContext->device->getEffects();
317 Cogs::ResourceStatus status = HandleIsValid(effect->handle) ? effects->checkEffect(effect->handle) : Cogs::ResourceStatus::Error;
318
319 if (status == Cogs::ResourceStatus::Ready && (task.effect != effect || task.effectStatus != Cogs::ResourceStatus::Ready)) {
320 setupGlobalBindings(renderTaskContext, task.globalBinding, effect->handle);
321 }
322
323 if (status == Cogs::ResourceStatus::Error && task.effectStatus != Cogs::ResourceStatus::Error) {
324 LOG_ERROR(logger, "TwinVisualsTexAtlasRenderTask: Invalid tex atlas effect handle.");
325 }
326
327 task.effect = effect;
328 task.effectStatus = status;
329 return status;
330 }
331}
332
333Cogs::Core::TwinVisualsTexAtlasRenderTask::TwinVisualsTexAtlasRenderTask(
334 RenderTaskContext* renderTaskContext,
335 TexAtlasSystem* texAtlasSystem,
336 TwinVisualsSystem* twinVisualsSystem,
337 const RenderTaskDefinition& renderTaskDefinition,
338 const PipelineOptions& /*pipelineOptions*/)
339: texAtlasSystem(texAtlasSystem)
340, twinVisualsSystem(twinVisualsSystem)
341{
342 assert(texAtlasSystem);
343 assert(twinVisualsSystem);
344 const bool reverseDepth = renderTaskContext->context->variables->get("renderer.reverseDepth", false);
345
346 bool depthTest = true;
347 bool depthWrite = true;
348 for (const auto& p : renderTaskDefinition.parameters) {
349 if (p.key == "clear") {
350 p.asBool(clearColor);
351 } else if (p.key == "blendMode") {
352 blendMode = parseEnum<BlendMode>(p.value, blendMode);
353 } else if (p.key == "depthTest") {
354 p.asBool(depthTest);
355 }
356 else if (p.key == "writeDepth") {
357 p.asBool(depthWrite);
358 } else if (p.key == "inputSrgb") {
359 p.asBool(inputSrgb);
360 }
361 else if (p.key == "outputSrgb") {
362 p.asBool(outputSrgb);
363 } else if (p.key == "lumaInAlpha") {
364 p.asBool(lumaInAlpha);
365 } else if (p.key == "viewportFromTarget") {
366 p.asBool(viewportFromTarget);
367 }
368 }
369
370 Cogs::IGraphicsDevice* device = renderTaskContext->renderer->getDevice();
371 Cogs::IBuffers* buffers = device->getBuffers();
372 Cogs::IRenderTargets* renderTargets = device->getRenderTargets();
373
374 DepthStencilState depthState{};
375 if (depthTest) {
376 depthState = {
377 .depthEnabled = true,
378 .writeEnabled = depthWrite,
379 // Do depth test, but we use OrEqual so ground-plane that goes beyond farplane can use far-plane depth and win the tie.
380 .depthFunction = reverseDepth ? DepthStencilState::GreaterOrEqual : DepthStencilState::LessOrEqual
381 };
382 }
383 else if (depthWrite) {
384 depthState = {
385 .depthEnabled = true,
386 .writeEnabled = true,
387 .depthFunction = DepthStencilState::Always
388 };
389 }
390 else {
391 depthState = {
392 .depthEnabled = false,
393 .writeEnabled = false,
394 .depthFunction = DepthStencilState::Always
395 };
396 }
397 depthStencilStateHandle = renderTargets->loadDepthStencilState(depthState);
398
399 constants = buffers->loadBuffer(nullptr, sizeof(TexAtlasState::constants), Usage::Dynamic, AccessMode::Write, BindFlags::ConstantBuffer);
400}
401
403{
404 state = TexAtlasState{};
405 RenderResources& renderResources = renderTaskContext->renderer->getRenderResources();
406
407 const glm::dvec3 origin = renderTaskContext->context->transformSystem->getOrigin();
408
409 size_t ix = 0;
410 if (TwinVisualsComponent* tvComp = twinVisualsSystem->globalTwinVisualsComponent; tvComp) {
411 state.style = tvComp->texAtlasStyle;
412
413 // Calculate shift to use in shader
414 const float c = std::cos(tvComp->gridRotation);
415 const float s = std::sin(tvComp->gridRotation);
416 glm::dvec2 o = glm::dvec2(origin) - tvComp->gridOrigin;
417 glm::dmat2 R(c, s,
418 -s, c);
419 glm::vec2 shift = glm::vec2(fract((1.0 / double(tvComp->gridSpacingMaj)) * (R * o)));
420
421 state.constants.backgroundColor = glm::convertSRGBToLinear(renderTaskContext->renderer->getBackgroundColor());
422 state.constants.groundColor = tvComp->groundColor;
423 state.constants.hazeColor = glm::vec4(tvComp->hazeColor,
424 tvComp->hazeIntensity);
425 state.constants.opaqueness = tvComp->groundOpaqueness;
426 state.constants.groundElevation = float(tvComp->groundElevation - origin.z);
427 state.constants.gridRotationCos = c;
428 state.constants.gridRotationSin = s;
429 state.constants.gridOffsetX = shift.x;
430 state.constants.gridOffsetY = shift.y;
431 state.constants.gridLineColorMaj = tvComp->gridLineColorMaj;
432 state.constants.gridLineColorMin = tvComp->gridLineColorMin;
433 state.constants.gridScaleMaj = tvComp->gridEnable ? (1.f / tvComp->gridSpacingMaj) : 0.f;
434 state.constants.lineWidthMaj = tvComp->gridLineWidthMaj;
435 state.constants.lineWidthMin = tvComp->gridLineWidthMin;
436 state.constants.fadeTweakMaj = tvComp->gridFadeTweakMaj;
437 state.constants.fadeTweakMin = tvComp->gridFadeTweakMin;
438
439 for (const WeakEntityPtr& weakEntity : tvComp->texAtlases) {
440 if (ix >= 4) break;
441
442 EntityPtr entity = weakEntity.lock();
443 if (!entity) continue;
444
445 TexAtlasComponent* texAtlasComp = entity->getComponent<TexAtlasComponent>();
446 if (!texAtlasComp) {
447 if (firstRun) {
448 LOG_ERROR(logger, "TwinVisualsTexAtlasRenderTask: entity does not have a TexAtlasComponent");
449 }
450 continue;
451 }
452
453 TexAtlasData& texAtlasData = texAtlasSystem->getData(texAtlasComp);
454 texAtlasData.inUse = true;
455
456 RenderTexture* treeTex = renderResources.getRenderTexture(texAtlasData.treeTex);
457 RenderTexture* tilesTex = renderResources.getRenderTexture(texAtlasData.tilesTex);
458 if (!treeTex || !tilesTex) continue;
459
460 state.constants.floatCoeffs[ix] = texAtlasData.floatCoefficients;
461 state.constants.intCoeffs[ix] = texAtlasData.intCoefficients;
462 state.tilesTex[ix] = tilesTex->textureHandle;
463 state.treeTex[ix] = treeTex->textureHandle;
464 state.levels[ix] = texAtlasData.levels;
465 ix++;
466 }
467 }
468
469 firstRun = false;
470
471 return setupEffect(renderTaskContext, *this, state);
472}
473
474void Cogs::Core::TwinVisualsTexAtlasRenderTask::apply(RenderTaskContext* renderTaskContext)
475{
476 assert(effectStatus == Cogs::ResourceStatus::Ready);
477
478 RenderStates& renderStates = renderTaskContext->renderer->getRenderStates();
479
480 RenderList* renderList = input.get(RenderResourceType::RenderList)->renderList;
481 RenderTarget* renderTarget = output.get(RenderResourceType::RenderTarget)->renderTarget;
482
483 updateEngineBuffers(renderTaskContext, renderTarget, renderList->viewportData, nullptr);
484
485 IGraphicsDevice* device = renderTaskContext->renderer->getDevice();
486 IContext* deviceContext = device->getImmediateContext();
487 deviceContext->setEffect(effect->handle);
488
489 if(renderTaskContext->device->getCapabilities()->getDeviceCapabilities().RenderPass){
490 RenderPassInfo info;
491 info.renderTargetHandle = renderTarget->renderTargetHandle;
492 info.depthStencilHandle = DepthStencilHandle::NoHandle;
493 info.loadOp[0] = clearColor ? LoadOp::Clear : LoadOp::Load;
494 info.storeOp[0] = StoreOp::Store;
495 glm::vec4 color = renderTarget->getClearColor();
496 info.clearValue[0][0] = color[0];
497 info.clearValue[0][1] = color[1];
498 info.clearValue[0][2] = color[2];
499 info.clearValue[0][3] = color[3];
500 info.depthLoadOp = LoadOp::Load;
501 info.depthStoreOp = StoreOp::Discard;
502 deviceContext->beginRenderPass(info);
503 }
504 else{
505 deviceContext->setRenderTarget(renderTarget->renderTargetHandle, DepthStencilHandle::NoHandle);
506
507 if (clearColor) {
508 deviceContext->clearRenderTarget(glm::value_ptr(renderTarget->getClearColor()));
509 }
510 }
511
512 if (viewportFromTarget) {
513 deviceContext->setViewport(0.0f, 0.0f, static_cast<float>(renderTarget->width), static_cast<float>(renderTarget->height));
514 } else {
515 deviceContext->setViewport(0, 0, renderTaskContext->renderer->getSize().x, renderTaskContext->renderer->getSize().y);
516 }
517 deviceContext->setDepthStencilState(depthStencilStateHandle);
518 deviceContext->setRasterizerState(renderTaskContext->states->defaultRasterizerStateHandle);
519 deviceContext->setBlendState(renderTaskContext->states->blendStates[size_t(blendMode)].handle);
520 deviceContext->setVertexBuffers(nullptr, 0, nullptr, nullptr);
523
524 applyGlobalBindings(renderTaskContext, globalBinding);
525
526 deviceContext->updateBuffer(constants, &state.constants, sizeof(TexAtlasState::constants));
527 deviceContext->setConstantBuffer("TexAtlasCoefficients", constants);
528
529 static const std::string texAtlasTilesTextureName[4] = {
530 "texAtlasTiles0",
531 "texAtlasTiles1",
532 "texAtlasTiles2",
533 "texAtlasTiles3"
534 };
535 static const std::string texAtlasTilesSamplerName[4] = {
536 "texAtlasTiles0Sampler",
537 "texAtlasTiles1Sampler",
538 "texAtlasTiles2Sampler",
539 "texAtlasTiles3Sampler"
540 };
541 static const std::string texAtlasTreeTextureName[4] = {
542 "texAtlasTree0",
543 "texAtlasTree1",
544 "texAtlasTree2",
545 "texAtlasTree3"
546 };
547 static const std::string texAtlasTreeSamplerName[4] = {
548 "texAtlasTree0Sampler",
549 "texAtlasTree1Sampler",
550 "texAtlasTree2Sampler",
551 "texAtlasTree3Sampler"
552 };
553
554 for (size_t i = 0; i < 4; i++) {
555 deviceContext->setTexture(texAtlasTilesTextureName[i], uint32_t(i), state.tilesTex[i]);
556 deviceContext->setSamplerState(texAtlasTilesSamplerName[i], uint32_t(i), renderStates.commonSamplerStates[1]); // Clamp + MinMagMipLinear
557 deviceContext->setTexture(texAtlasTreeTextureName[i], uint32_t(i), state.treeTex[i]);
558 deviceContext->setSamplerState(texAtlasTreeSamplerName[i], uint32_t(i), renderStates.commonSamplerStates[3]); // Clamp + MinMagMipPoint
559 }
560
561 if (RenderTaskResource* color = input.get(RenderResourceType::RenderTexture, "ColorTexture"); color && color->renderTexure) {
562 deviceContext->setTexture("colorTexture", 5, color->renderTexure->textureHandle);
563 deviceContext->setSamplerState("colorTextureSampler", 5, renderStates.commonSamplerStates[1]); // Clamp + MinMagMipLinear
564 }
565 if (RenderTaskResource* depth = input.get(RenderResourceType::RenderTexture, "DepthTexture"); depth && depth->renderTexure) {
566 deviceContext->setTexture("depthTexture", 6, depth->renderTexure->textureHandle);
567 deviceContext->setSamplerState("depthTextureSampler", 6, renderStates.commonSamplerStates[3]); // Clamp + MinMagMipPoint
568 }
569 deviceContext->draw(PrimitiveType::TriangleList, 0, 3);
570 if (renderTaskContext->device->getCapabilities()->getDeviceCapabilities().RenderPass) {
571 deviceContext->endRenderPass();
572 }
573}
574
575void Cogs::Core::TwinVisualsTexAtlasRenderTask::cleanup(RenderTaskContext* renderTaskContext)
576{
577 Cogs::IGraphicsDevice* device = renderTaskContext->renderer->getDevice();
578 Cogs::IBuffers* buffers = device->getBuffers();
579 Cogs::IRenderTargets* renderTargets = device->getRenderTargets();
580 if (HandleIsValid(constants)) {
581 buffers->releaseBuffer(constants);
583 }
584 if (HandleIsValid(depthStencilStateHandle)) {
585 renderTargets->releaseDepthStencilState(depthStencilStateHandle);
586 depthStencilStateHandle = Cogs::DepthStencilStateHandle::NoHandle;
587 }
588}
ComponentType * getComponent() const
Definition: Component.h:159
std::unique_ptr< class Variables > variables
Variables service instance.
Definition: Context.h:180
EnvironmentComponent * getGlobalEnvironment() const
Get the global environment component.
Holds all LightComponent instances in the system.
Definition: LightSystem.h:78
Contains render resources used by the renderer.
RenderStates & getRenderStates() override
Get the reference to the RenderStates structure.
Definition: Renderer.h:70
IGraphicsDevice * getDevice() override
Get the graphics device used by the renderer.
Definition: Renderer.h:46
const RenderSettings & getSettings() const override
Get the settings of the renderer.
Definition: Renderer.h:47
glm::vec4 getBackgroundColor() const override
Get the reference to the background color.
Definition: Renderer.h:43
EnginePermutations & getEnginePermutations() override
Get the reference to the EnginePermutations structure.
Definition: Renderer.h:78
EffectCache & getEffectCache() override
Get the reference to the EffectCache structure.
Definition: Renderer.h:72
glm::vec2 getSize() const override
Get the output surface size of the renderer.
Definition: Renderer.h:45
glm::dvec3 getOrigin() const
Gets the Origin offset of the scene.
Represents a graphics device used to manage graphics resources and issue drawing commands.
virtual IEffects * getEffects()=0
Get a pointer to the effect management interface.
virtual ICapabilities * getCapabilities()=0
Get a pointer to the capability management interface used to query the graphics device capability fla...
virtual IContext * getImmediateContext()=0
Get a pointer to the immediate context used to issue commands to the graphics device.
virtual IBuffers * getBuffers()=0
Get a pointer to the buffer management interface.
virtual GraphicsDeviceType getType() const
Get the type of the graphics device.
virtual IRenderTargets * getRenderTargets()=0
Get a pointer to the render target management interface.
Log implementation class.
Definition: LogManager.h:140
Contains the Engine, Renderer, resource managers and other systems needed to run Cogs....
std::shared_ptr< ComponentModel::Entity > EntityPtr
Smart pointer for Entity access.
Definition: EntityPtr.h:12
bool HandleIsValid(const ResourceHandle_t< T > &handle)
Check if the given resource is valid, that is not equal to NoHandle or InvalidHandle.
std::weak_ptr< ComponentModel::Entity > WeakEntityPtr
Weak Smart pointer for Entity access.
Definition: EntityPtr.h:18
constexpr Log getLogger(const char(&name)[LEN]) noexcept
Definition: LogManager.h:181
@ OpenGLES30
Graphics device using the OpenGLES 3.0 API.
@ WebGPU
Graphics device using the WebGPU API Backend.
ResourceStatus
Status of an asynchronously loaded resource, such as an effect or a pipeline.
Definition: Common.h:198
@ Error
The resource failed to load.
@ Ready
The resource has loaded successfully and is ready for use.
constexpr size_t hash() noexcept
Simple getter function that returns the initial value for fnv1a hashing.
Definition: HashFunctions.h:62
@ TriangleList
List of triangles.
Partial C preprocessor.
Definition: Preprocessor.h:42
bool process(Context *context, const StringView input)
Run a text block through the preprocessor.
std::string processed
Resulting processed text.
Definition: Preprocessor.h:48
Render settings variables.
Cogs::ResourceStatus checkReady(RenderTaskContext *renderTaskContext) override
Check if the task is ready to be applied, e.g.
Encapsulates state for depth buffer usage and stencil buffer usage in a state object.
bool depthEnabled
If depth testing is enabled/disabled. Default is true.
static const Handle_t NoHandle
Represents a handle to nothing.
Definition: Common.h:78
Provides buffer management functionality.
Definition: IBuffers.h:13
virtual BufferHandle loadBuffer(const void *data, const size_t size, Usage::EUsage usage, uint32_t accessMode, uint32_t bindFlags, uint32_t stride=0)=0
Loads a new buffer using the given data to populate the buffer.
virtual void releaseBuffer(BufferHandle bufferHandle)=0
Releases the buffer with the given bufferHandle.
virtual const GraphicsDeviceCapabilities & getDeviceCapabilities() const
Gets the device capabilities in a structure.
Represents a graphics device context which can receive rendering commands.
Definition: IContext.h:43
virtual void setTexture(const StringView &name, unsigned int unit, TextureHandle textureHandle)=0
Sets the texture slot given by unit with the given name to contain the given texture.
virtual void setRasterizerState(const RasterizerStateHandle handle)=0
Set the current rasterizer state.
virtual void setBlendState(const BlendStateHandle handle, const float *constant=nullptr)=0
Set the current blend state.
virtual void setInputLayout(const InputLayoutHandle inputLayoutHandle)=0
Sets the current input layout.
virtual void clearRenderTarget(const float *value)=0
Clear the currently set render target to the given value (4 component floating point RGBA).
virtual void endRenderPass()=0
End a render pass.
virtual void setIndexBuffer(IndexBufferHandle bufferHandle, uint32_t stride=4, uint32_t offset=0)=0
Sets the current index buffer.
virtual void setDepthStencilState(const DepthStencilStateHandle handle)=0
Set the current depth stencil state.
virtual void setConstantBuffer(const StringView &name, const BufferHandle bufferHandle, const uint32_t offset=0, const uint32_t size=~0u)=0
Sets a constant buffer to be bound to the given name and slot.
virtual void updateBuffer(BufferHandle bufferHandle, const void *data, size_t size)=0
Replace contents of buffer with new data.
virtual void setViewport(const float x, const float y, const float width, const float height)=0
Sets the current viewport to the given location and dimensions.
virtual void draw(PrimitiveType primitiveType, const size_t startVertex, const size_t numVertexes)=0
Draws non-indexed, non-instanced primitives.
virtual void beginRenderPass(const RenderPassInfo &info)=0
Begin a render pass.
virtual void setSamplerState(const StringView &name, unsigned int unit, SamplerStateHandle samplerStateHandle)=0
Sets the sampler slot given by unit with the given name to contain the given sampler state.
virtual void setVertexBuffers(const VertexBufferHandle *vertexBufferHandles, const size_t count, const uint32_t *strides, const uint32_t *offsets)=0
Sets the current vertex buffers.
virtual void setEffect(EffectHandle handle)=0
Set the current effect.
virtual void setRenderTarget(const RenderTargetHandle handle, const DepthStencilHandle depthStencilHandle)=0
Sets the current render target and an associated depth stencil target.
Provides effects and shader management functionality.
Definition: IEffects.h:158
virtual SamplerStateBindingHandle getSamplerStateBinding(EffectHandle effectHandle, const StringView &name, const unsigned int slot)=0
Get a handle to a sampler state object binding, mapping how to bind the sampler state to the given ef...
virtual ConstantBufferBindingHandle getConstantBufferBinding(EffectHandle effectHandle, const StringView &name)=0
Get a handle to a constant buffer binding, mapping how to bind a constant buffer to the given effect.
virtual TextureBindingHandle getTextureBinding(EffectHandle effectHandle, const StringView &name, const unsigned int slot)=0
Get a handle to a texture object binding, mapping how to bind textures to the given effect.
virtual ResourceStatus checkEffect(EffectHandle effectHandle)=0
Check the load status of the effect with the given effectHandle.
Provides render target management functionality.
virtual void releaseDepthStencilState(DepthStencilStateHandle handle)=0
Release the depth stencil state with the given handle.
virtual DepthStencilStateHandle loadDepthStencilState(const DepthStencilState &depthStencilState)=0
Load a depth stencil state object.