application.cpp 13.1 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
27
28
29
30
31
32
33
34
35
36
37
38
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
#include "application.h"

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

#include <core/audio/sound_buffer.h>
#include <core/audio/sound_source.h>
#include <core/res/resources.h>

#include <util/openal.h>
#include <util/console.h>

namespace glare
{
	PathtracerApp::PathtracerApp()
		: app::Application()
	{

	}

	void PathtracerApp::onStart(const Arguments& arguments)
	{
		m_current_scene_root = files::asset("/meshes/scenery/");

		//Create a skybox from cube map.
		skybox().reset(core::Skybox::collectFilesFrom(files::asset("/textures/ryfjallet/")));

		//initializeScene(m_current_scene_root / "TY_Plane.dae", 1.f);
		//initializeScene(m_current_scene_root / "dragn.dae", 1.f);
		//initializeScene(m_current_scene_root / "benchmark_stfd_bunny_diff.dae", 1.f);
		initializeScene(m_current_scene_root / "cbox.dae", 1.f);

		al::listenerf(al::ListenerParam::eGain, 0.02f);
		auto audio_buffer = core::Resources::getInstance().getAudioBuffer(files::asset("/audio/env.wav"));
		auto environment_source = core::state::graph_root->makeComponent<core::SoundSource>(audio_buffer->id());
		environment_source->setLooping(true);
		environment_source->play();
	}

	void PathtracerApp::onGui()
	{
		drawDebugWindow();
		drawSceneSelector();
		//drawLinespaceControls();
	}

	void PathtracerApp::onQuit()
	{

	}

	void PathtracerApp::onResize(unsigned width, unsigned height)
	{

	}

	void PathtracerApp::onKeyPress(controls::Key key, controls::KeyMods mods)
	{
		switch (key) {
		case controls::Key::e1:
		{
			setRenderMode(app::RenderMode::eLines);
		} break;
		case controls::Key::e2:
		{
			setRenderMode(app::RenderMode::eRaw);
		} break;
		case controls::Key::e3:
		{
			setRenderMode(app::RenderMode::eGBuffer);
		} break;
		case controls::Key::e4:
		{
			setRenderMode(app::RenderMode::ePathtrace);
		} break;
		default: break;
		}
	}

	void PathtracerApp::initializeScene(fs::path path, float scale)
	{
		//Initialize some scene graph from an obj file
		core::state::graph_root = core::Resources::getInstance().getColladaFile(path, scale);
		if (!core::state::graph_root)
		{
			core::state::quit();
			glfwTerminate();
			Log_Error << "Scene could not be loaded: " << path;
			console::prompt(1);
		}

		std::shared_ptr<core::GraphNode> cam_node = core::state::graph_root->findFirst([](const core::GraphNode &node) {
			return bool(node.getComponent<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);
		}
		cam_node->makeComponent<component::PlayerController>();
		core::state::graph_root->makeComponent<component::FramerateCounter>();

#define DEBUG__ADD_ROTATOR
#ifdef DEBUG__ADD_ROTATOR
		auto node = core::state::graph_root->findFirstWithName("#Suzanne-mesh");
		if (node) {
			node->addComponent(std::make_shared<component::Rotator>());
		}
#endif
	}

	void PathtracerApp::drawControlItem(std::string title, std::string description)
	{
		ImGui::Title(title.c_str());
		ImGui::SameLine();
		ImGui::TextWrapped(description.c_str());
	}

	void PathtracerApp::drawDebugWindow()
	{
		ImGui::Begin("Debug", nullptr, ImGuiWindowFlags_AlwaysAutoResize);

		ImGui::BeginGroup();
		static int render_state = 0;
		render_state = int(renderMode());
		ImGui::Title("Render Mode");
		ImGui::PushID("id_render_mode");
		ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth());
		ImGui::Combo("", &render_state, { "OpenGL Wireframe", "OpenGL Raw Color", "OpenGL GBuffer", "Pathtracing" });
		ImGui::PopItemWidth();
		ImGui::PopID();
		if (renderMode() != app::RenderMode(render_state)) {
			glFinish();
			setRenderMode(app::RenderMode(render_state));
		}
		ImGui::EndGroup();

		if (renderMode() == app::RenderMode::ePathtrace) {

			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();
			ImGui::Checkbox("Reset on scene update", &collector_active);
			if (collector_active != pathtracer().collector()->isActive())
				pathtracer().collector()->setActive(collector_active);

			ImGui::Spacing();

			ImGui::BeginGroup();
			static int raygenstate = 0;
			raygenstate = int(m_ray_gen_state);
			ImGui::Title("Ray Generator");
			ImGui::PushID("id_ray_generator");
			ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth());
			ImGui::Combo("", &raygenstate, { "GBuffer", "Default (BVH)" });
			ImGui::PopItemWidth();
			ImGui::PopID();

			if (raygenstate != int(m_ray_gen_state)) {
				m_ray_gen_state = AppRayGenState(raygenstate);
				switch (m_ray_gen_state)
				{
				case AppRayGenState::eDefault:
					pathtracer().setGenerator(std::make_shared<raytrace::RayGeneratorDefault>());
					break;
				case AppRayGenState::eGBuffer:
					pathtracer().setGenerator(std::make_shared<raytrace::RayGeneratorGBuffer>());
					break;
				default:
					break;
				}
			}
			ImGui::EndGroup();

			ImGui::Spacing();

			ImGui::PushID("id_samples");
			ImGui::Title("Samples");
			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::Spacing();

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

			int spfr = pathtracer().getSamplesPerFrame();
			ImGui::DragInt("per frame", &spfr, 0.1f, 1, 10);
			if (spfr != pathtracer().getSamplesPerFrame())
				pathtracer().setSamplesPerFrame(spfr);
			ImGui::PopID();

			ImGui::Spacing();
			ImGui::Title("Bounces");
			ImGui::PushID("id_bounces");

			ImGui::TextWrapped("The global bounce limit clamps down all effect-dependant bounce limits to a unified maximum value.");
			int bounces = pathtracer().getBounces();
			ImGui::DragInt("Global Limit", &bounces, 0.1f, 0, 15);
			if (bounces != pathtracer().getBounces())
				pathtracer().setBounces(bounces);

			if (ImGui::CollapsingHeader("Bounce Thresholds"))
			{
				drawEffectBounceControl("Diffuse", raytrace::EffectType::eDiffuse);
				drawEffectBounceControl("Translucent", raytrace::EffectType::eTranslucent);
				drawEffectBounceControl("Reflective", raytrace::EffectType::eReflection);
				drawEffectBounceControl("Refractive", raytrace::EffectType::eRefraction);
				drawEffectBounceControl("Transparence", raytrace::EffectType::eTransparent);
				drawEffectBounceControl("Emissive", raytrace::EffectType::eEmissive);
			}

			ImGui::Spacing();

			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.");
			float clamp_direct = pathtracer().getClampDirect();
			ImGui::DragFloat("Clamp Direct", &clamp_direct, 0.1f, 0.0f, 100.f);
			if (clamp_direct != pathtracer().getClampDirect())
				pathtracer().setClampDirect(clamp_direct);

			float clamp_indirect = pathtracer().getClampIndirect();
			ImGui::DragFloat("Clamp Indirect", &clamp_indirect, 0.1f, 0.0f, 100.f);
			if (clamp_indirect != pathtracer().getClampIndirect())
				pathtracer().setClampIndirect(clamp_indirect);

			ImGui::PopID();

			auto &&style = ImGui::GetStyle();
			auto col_bt = style.Colors[ImGuiCol_Button];
			auto col_bt_h = style.Colors[ImGuiCol_ButtonHovered];
			auto col_bt_a = style.Colors[ImGuiCol_ButtonActive];

			auto color_bt = color::hex<color::rgba32f>("#4CAF50");
			auto color_bt_h = color::hex<color::rgba32f>("#81C784");
			auto color_bt_a = color::hex<color::rgba32f>("#2E7D32");

			style.Colors[ImGuiCol_Button] = ImVec4(color_bt.r, color_bt.g, color_bt.b, color_bt.a);
			style.Colors[ImGuiCol_ButtonHovered] = ImVec4(color_bt_h.r, color_bt_h.g, color_bt_h.b, color_bt_h.a);
			style.Colors[ImGuiCol_ButtonActive] = ImVec4(color_bt_a.r, color_bt_a.g, color_bt_a.b, color_bt_a.a);

			ImGui::Spacing();
			ImGui::Title("Save Render as...");
			ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() / 2);
			if (ImGui::Button("32bit HDR"))
			{
				pathtracer().saveRender(files::asset("/screenshots/render.hdr"));
			}

			ImGui::SameLine();

			if (ImGui::Button("8bit PNG"))
			{
				pathtracer().saveRender(files::asset("/screenshots/render.png"));
			}
			ImGui::PopItemWidth();
			style.Colors[ImGuiCol_Button] = col_bt;
			style.Colors[ImGuiCol_ButtonHovered] = col_bt_h;
			style.Colors[ImGuiCol_ButtonActive] = col_bt_a;
		}
		
		ImGui::Separator();
		ImGui::Title("General Settings");

		static int vsync = 0;
		vsync = int(core::state::window->getVSync());
		ImGui::Combo("VSync", &vsync, { "None", "60 FPS", "30 FPS", "20 FPS" });
		if(vsync != int(core::state::window->getVSync()))
			core::state::window->setVSync(VSync(vsync));

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

		ImGui::End();
	}

	void PathtracerApp::drawSceneSelector()
	{
		ImGui::Begin("Scenes", nullptr, ImVec2(200, 300));

		ImGui::Title(m_current_scene_root.string().c_str());
		ImGui::DragFloat("Scale", &m_import_scale, 0.01f, 0.01f, 100.0f);
		ImGui::BeginGroup();
		if (ImGui::Button("..", ImVec2(ImGui::GetContentRegionAvailWidth(), 32)))
		{
			m_current_scene_root = m_current_scene_root.parent_path();
		}

		for (auto& p : fs::directory_iterator(m_current_scene_root)) {
			fs::path path = p;
			if (is_directory(path)) {
				if (ImGui::Button(path.filename().string().c_str(), ImVec2(ImGui::GetContentRegionAvailWidth(), 40)))
				{
					m_current_scene_root = path;
				}
			}
			else if (path.extension() == ".dae")
			{
				if (ImGui::Button(path.filename().string().c_str(), ImVec2(ImGui::GetContentRegionAvailWidth(), 32)))
				{
					initializeScene(path, m_import_scale);
					pathtracer().reload(core::state::graph_root);
				}
			}
		}
		ImGui::EndGroup();

		ImGui::End();
	}

	void PathtracerApp::drawLSBounceControl(const std::string &label, raytrace::EffectType effect)
	{
		int val = pathtracer().getLinespaceBounceThreshold(effect);
		ImGui::DragInt(label.c_str(), &val, 0.1f, 0, pathtracer().getEffectBounces(effect));
		if (val != pathtracer().getLinespaceBounceThreshold(effect))
		{
			pathtracer().setLinespaceBounceThresholds(effect, uint8_t(val));
		}
	}

	void PathtracerApp::drawEffectBounceControl(const std::string &label, raytrace::EffectType effect)
	{
		int val = pathtracer().getEffectBounces(effect);
		ImGui::DragInt(label.c_str(), &val, 0.1f, 0, 15);
		if (val != pathtracer().getEffectBounces(effect))
		{
			pathtracer().setEffectBounces(effect, uint8_t(val));
		}
	}

	void PathtracerApp::drawLinespaceControls()
	{
		ImGui::Begin("Linespace Settings", nullptr, ImVec2(200, 300));

		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();
			ImGui::DragFloat("Direct", &acc, 0.001f, 0.0f, 1.f);
			if (acc != pathtracer().getAccuracyThreshold())
				pathtracer().setAccuracyThreshold(acc);

			float shd = pathtracer().getShadowThreshold();
			ImGui::DragFloat("Shadow", &shd, 0.001f, 0.0f, 1.f);
			if (shd != pathtracer().getShadowThreshold())
				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();
			ImGui::DragFloat("Distance", &dt, 0.1f, 0.0f, 10000.f);
			if (dt != pathtracer().getDistanceThreshold())
				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.");
		{
			drawLSBounceControl("Diffuse", raytrace::EffectType::eDiffuse);
			drawLSBounceControl("Translucent", raytrace::EffectType::eTranslucent);
			drawLSBounceControl("Reflective", raytrace::EffectType::eReflection);
			drawLSBounceControl("Refractive", raytrace::EffectType::eRefraction);
			drawLSBounceControl("Transparency", raytrace::EffectType::eTransparent);
			drawLSBounceControl("Emissive", raytrace::EffectType::eEmissive);
		}

		ImGui::End();
	}
}