main.cpp 12.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <util/files.h>
#include <util/console.h>

#include <core/state.h>
#include <core/audio/sound_source.h>
#include <core/objects/skybox.h>
#include <core/rendering/gbuffer.h>
#include <core/res/resources.h>

#include <raytrace/tracer/pathtracer.h>

#include <components/FramerateCounter.h>
#include <components/PlayerController.h>

using namespace glare;

enum class RenderMode
{
	eLines = 0,
	eRaw = 1,
	eGBuffer = 2,
	ePathtrace = 3
};


// Default paths for easy change access
27
const fs::path engine_settings_path = files::asset("/preferences/default.xml");
28
const fs::path pathtracer_settings_path = files::asset("/preferences/pathtracer_default.xml");
29
30
const fs::path skybox_files_path = files::asset("/textures/ryfjallet/");
const fs::path env_audio_path = files::asset("/audio/env.wav");
31
const fs::path startup_scene_path = files::asset("/meshes/scenery/material_testscene.dae");
32
33
34
35
36

// My little all-enclosing pathtracer pointer
std::unique_ptr<raytrace::Pathtracer> pathtracer = nullptr;

// Some Application states
37
38
fs::path current_scene_root = startup_scene_path.parent_path();
RenderMode render_mode = RenderMode::eGBuffer;
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

// All functions used in here
void keyPress(controls::Key key, controls::KeyMods mods);
void loadScene(const fs::path& path, float scale = 1.f);
void drawDebugGui();


// Implementation
int main(int argc, char* argv[])
{
	core::state::initialize(engine_settings_path);
	core::Callbacks::addKeyDownCallback("main_application", keyPress);

	// Create a skybox from cube map.
	core::state::skybox->reset(core::Skybox::collectFilesFrom(skybox_files_path));

	// Load the pre-determined startup scene
	loadScene(startup_scene_path, 1.f);

	// Make some ambient sound source
	al::listenerf(al::ListenerParam::eGain, 0.02f);
	auto audio_buffer = core::Resources::getInstance().getAudioBuffer(env_audio_path);
	auto environment_source = core::state::graph_root->makeComponent<core::SoundSource>(audio_buffer->id());
	environment_source->setLooping(true);
	environment_source->play();

	// Initialize an empty pathtracer
	pathtracer = std::make_unique<raytrace::Pathtracer>();
	pathtracer->loadSettings(pathtracer_settings_path);

	// For debug purposes, add a frame rate counter to the root node, which will never be deleted/removed on runtime if not explicitly told so.
	core::state::graph_root->makeComponent<component::FramerateCounter>();

	core::state::mainLoop([&](double delta)
	{
		switch (render_mode)
		{
		case RenderMode::eLines:
		{
			gl::polygonMode(gl::Face::eFrontAndBack, gl::PolygonMode::eLine);
			bool cull = gl::isEnabled(gl::EnableParameter::eCullFace);
			gl::setEnabled(gl::EnableParameter::eCullFace, false);
81
			core::state::graph_root->draw();
82
83
84
85
86
			gl::setEnabled(gl::EnableParameter::eCullFace, cull);
			gl::polygonMode(gl::Face::eFrontAndBack, gl::PolygonMode::eFill);
		}
		break;
		case RenderMode::eRaw:
87
88
			core::state::graph_root->draw();
			break;
89
90
		case RenderMode::eGBuffer:
			core::state::gbuffer->activate();
91
			core::state::graph_root->draw();
92
			core::state::gbuffer->draw();
93
			break;
94
95
96
		case RenderMode::ePathtrace:
		{
			// If it's not manually initialized via the GUI button, initialize the Pathtracer here.
97
			if (!pathtracer->collector())
98
				pathtracer->reload(core::state::graph_root);
99
			pathtracer->renderToScreen(core::state::window->getWidth(), core::state::window->getHeight());
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
		}
		break;
		}

		drawDebugGui();
	});
}

void keyPress(controls::Key key, controls::KeyMods mods)
{
	switch (key) {
	case controls::Key::e1: render_mode = RenderMode::eLines; break;
	case controls::Key::e2: render_mode = RenderMode::eRaw; break;
	case controls::Key::e3: render_mode = RenderMode::eGBuffer; break;
	case controls::Key::e4: render_mode = RenderMode::ePathtrace; break;
	default: break;
	}
}

void loadScene(const fs::path& path, float scale)
{
	// Ain't no need for the last scene anymore.
	core::state::graph_root->clearChildren();

	//Initialize some scene graph from an obj file
	if (auto scene = core::Resources::getInstance().getColladaFile(path, scale))
	{
		core::state::graph_root->attach(scene);
	}
	else
	{
		core::state::quit();
		console::prompt("Scene could not be loaded: " + path.string() + ". Press [ENTER] to exit.", 1);
	}

	std::shared_ptr<core::GraphNode> cam_node = core::state::graph_root->findFirstWithComponent<core::Camera>();
	if (cam_node)
	{
		//If there are any cameras in the collada file, take the first one.
		core::state::camera = cam_node->getComponent<core::Camera>();
	}
	else
	{
		//Add a camera to render from
		cam_node = std::make_shared<core::GraphNode>("custom_camera");
		cam_node->addComponent(core::state::camera);
		core::state::graph_root->attach(cam_node);
	}

	//Attach a PlayerController to the current main camera, so we can fly around in the scene.
	cam_node->makeComponent<component::PlayerController>();

	// Reload Pathtracer if used.
	if (pathtracer && pathtracer->collector())
		pathtracer->reload(core::state::graph_root);
}

void drawDebugGui()
{
	// Debug Window
	ImGui::Begin("Debug", nullptr, ImGuiWindowFlags_AlwaysAutoResize);

	// Render Mode
	ImGui::BeginNamedGroup("Render Mode");
	{
		ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth());
		int render_state = int(render_mode);
		if (ImGui::Combo("", &render_state, { "OpenGL Wireframe", "OpenGL Raw Color", "OpenGL GBuffer", "Pathtracing" }))
			render_mode = RenderMode(render_state);
		ImGui::PopItemWidth();
	}
	ImGui::EndNamedGroup();


	if (pathtracer->collector()) {

		ImGui::Spacing();

		ImGui::Title("Scene Settings");
		ImGui::TextWrapped("By default, a transformation or mesh update will trigger a pathtracer sample count reset. If you want to limit this to explicit settings changes and camera movements, uncheck the following option.");
		bool collector_active = pathtracer->collector()->isActive();
		if (ImGui::Checkbox("Reset on scene update", &collector_active))
			pathtracer->collector()->setActive(collector_active);

		ImGui::Spacing();

		if (ImGui::CollapsingHeader("Sampling and Performance"))
		{
			ImGui::BeginNamedGroup("Ray Generator");
189
190
191
192
193
194
195
			{
				int raygenstate = int(pathtracer->getGenerator());
				ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth());
				if (ImGui::Combo("", &raygenstate, { "Trace [default]", "OpenGL GBuffer" })) {
					pathtracer->setGenerator(raytrace::RayGeneratorType(raygenstate));
				}
				ImGui::PopItemWidth();
196
197
198
199
200
201
			}
			ImGui::EndNamedGroup();

			ImGui::Spacing();

			ImGui::BeginNamedGroup("Samples");
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
			{
				ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth());
				ImGui::ProgressBar(pathtracer->currentSample() / float(pathtracer->getMaxSamples()), ImVec2(-1, 0),
					("Current: " + std::to_string(pathtracer->currentSample()) + " of " + std::to_string(pathtracer->getMaxSamples())).c_str());
				ImGui::PopItemWidth();

				ImGui::Spacing();
				int max_samples = pathtracer->getMaxSamples();
				if (ImGui::DragInt("Maximum", &max_samples, 10, 1, 50000))
					pathtracer->setMaxSamples(max_samples);

				int spfr = pathtracer->getSamplesPerFrame();
				if (ImGui::DragInt("per frame", &spfr, 0.1f, 1, 10))
					pathtracer->setSamplesPerFrame(spfr);
			}
217
218
219
			ImGui::EndNamedGroup();

			ImGui::Spacing();
220

221
222
			ImGui::BeginNamedGroup("Bounces");
			ImGui::TextWrapped("The global bounce limit clamps down all effect-dependant bounce limits to a unified maximum value.");
223
224
225
226
			{
				int bounces = pathtracer->getBounces();
				if (ImGui::DragInt("Global Limit", &bounces, 0.1f, 0, 15))
					pathtracer->setBounces(bounces);
227

228
				ImGui::Spacing();
229

230
				if (ImGui::TreeNode("Bounce Thresholds"))
231
				{
232
233
234
235
					// Let's keep this function locally near to the only place it's being used.
					static auto effectBounces = [](const std::string &label, raytrace::EffectType effect)
					{
						int val = pathtracer->getEffectBounces(effect);
236
						if (ImGui::DragInt(label.c_str(), &val, 0.1f, 0, 255))
237
238
239
							pathtracer->setEffectBounces(effect, uint8_t(val));
					};

240
241
242
243
					effectBounces("Diffusion", raytrace::EffectType::eDiffusion);
					effectBounces("Reflection", raytrace::EffectType::eReflection);
					effectBounces("Transmission", raytrace::EffectType::eTransmission);
					effectBounces("Emission", raytrace::EffectType::eEmission);
244
245
					ImGui::TreePop();
				}
246
247
248
249
			}
			ImGui::EndNamedGroup();

			ImGui::TextWrapped("The direct clamp setting will lead to the primary ray result color being clamped down to a set maximum. That means each color component will be clamped. The same applies to the \"clamp indirect\" setting for non-primary bounces.");
250
251
252
253
			{
				float clamp_direct = pathtracer->getClampDirect();
				if (ImGui::DragFloat("Clamp Direct", &clamp_direct, 0.1f, 0.0f, 100.f))
					pathtracer->setClampDirect(clamp_direct);
254

255
256
257
258
				float clamp_indirect = pathtracer->getClampIndirect();
				if (ImGui::DragFloat("Clamp Indirect", &clamp_indirect, 0.1f, 0.0f, 100.f))
					pathtracer->setClampIndirect(clamp_indirect);
			}
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
		}

		if (ImGui::CollapsingHeader("Linespace Thresholds"))
		{
			ImGui::Title("PDF Thresholds");
			ImGui::TextWrapped("The following threshold values will determine as of which accumulated PDF value the Line Space should be used instead of the BVH.");
			{
				float acc = pathtracer->getAccuracyThreshold();
				if (ImGui::DragFloat("Direct", &acc, 0.001f, 0.0f, 1.f))
					pathtracer->setAccuracyThreshold(acc);

				float shd = pathtracer->getShadowThreshold();
				if (ImGui::DragFloat("Shadow", &shd, 0.001f, 0.0f, 1.f))
					pathtracer->setShadowThreshold(shd);
			}

			ImGui::Title("Distance Threshold");
			ImGui::TextWrapped("Works like a level of detail slider. This is the maximum path length with which the BVH should be used.");
			{
				float dt = pathtracer->getDistanceThreshold();
				if (ImGui::DragFloat("Distance", &dt, 0.1f, 0.0f, 10000.f))
					pathtracer->setDistanceThreshold(dt);
			}

			ImGui::Title("Bounce Thresholds");
			ImGui::TextWrapped("The following threshold values will determine as of which bounce the Line Space should be used instead of the BVH. This can vary for every kind of effect.");
			{
				// Let's keep this function locally near to the only place it's being used.
				static auto bounceControl = [](const std::string &label, raytrace::EffectType effect)
				{
					int val = pathtracer->getLinespaceBounceThreshold(effect);
					if (ImGui::DragInt(label.c_str(), &val, 0.1f, 0, pathtracer->getEffectBounces(effect)))
						pathtracer->setLinespaceBounceThresholds(effect, uint8_t(val));
				};

294
295
296
297
				bounceControl("Diffusion", raytrace::EffectType::eDiffusion);
				bounceControl("Reflection", raytrace::EffectType::eReflection);
				bounceControl("Transmission", raytrace::EffectType::eTransmission);
				bounceControl("Emission", raytrace::EffectType::eEmission);
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
			}
		}

		ImGui::Spacing();
		ImGui::Title("Save Render as...");
		if (ImGui::FeatureButton("32bit HDR", ImVec2(ImGui::GetContentRegionAvailWidth() / 2, 0)))
			pathtracer->saveRender(files::asset("/screenshots/render.hdr"));

		ImGui::SameLine();

		if (ImGui::FeatureButton("8bit PNG", ImVec2(ImGui::GetContentRegionAvailWidth(), 0)))
			pathtracer->saveRender(files::asset("/screenshots/render.png"));
	}
	else if (ImGui::FeatureButton("Initialize Pathtracer", ImVec2(ImGui::GetContentRegionAvailWidth(), 0)))
	{
313
		pathtracer->reload(core::state::graph_root);
314
315
316
317
318
	}

	ImGui::Separator();
	ImGui::Title("General Settings");

319
	int vsync = int(core::state::window->getVSync());
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
	if (ImGui::Combo("VSync", &vsync, { "None", "60 FPS", "30 FPS", "20 FPS" }))
		core::state::window->setVSync(VSync(vsync));

	ImGui::Separator();
	ImGui::Title("Controls");
	ImGui::TitledDescription("Right Click", "Grab cursor, enables looking around. Right click again to release it.");
	ImGui::TitledDescription("W/S", "Fly along the looking direction.");
	ImGui::TitledDescription("A/D", "Fly along the horizontal perpendiculat to the looking direction.");
	ImGui::TitledDescription("E", "Fly towards the relative up-direction.");
	ImGui::TitledDescription("Q", "Fly towards the relative down-direction.");
	ImGui::TitledDescription("1, 2, 3", "Toggle rendering mode.");

	ImGui::End();


	//Scene selection Window
	ImGui::Begin("Scenes", nullptr, ImVec2(200, 300));

	ImGui::Title(current_scene_root.string().c_str());
	static float import_scale = 1.f;
	ImGui::DragFloat("Scale", &import_scale, 0.01f, 0.01f, 100.0f);
	ImGui::BeginGroup();

	// Go to parent directory
	if (ImGui::Button("..", ImVec2(ImGui::GetContentRegionAvailWidth(), 32)))
		current_scene_root = current_scene_root.parent_path();

	for (auto& p : fs::directory_iterator(current_scene_root)) {
		fs::path path = p;
349

350
351
352
353
354
355
356
357
358
359
360
		// Either draw directory button or...
		if (is_directory(path) && ImGui::Button(path.filename().string().c_str(), ImVec2(ImGui::GetContentRegionAvailWidth(), 40)))
			current_scene_root = path;
		// ... draw a button which loads a dae file.
		else if (path.extension() == ".dae" && ImGui::FeatureButton(path.filename().string().c_str(), ImVec2(ImGui::GetContentRegionAvailWidth(), 32)))
			loadScene(path, import_scale);
	}
	ImGui::EndGroup();

	ImGui::End();
}