aboutsummaryrefslogtreecommitdiff
path: root/src/Engine/Scene.h
blob: 4b41203814290b009583281fe5ab9112b99af4a1 (plain)
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
#pragma once

#include <vector>
#include <limits>

#include "object.h"

namespace Donut
{
    class Scene
    {
    public:
        Scene()
            : m_light_pos(5.0f, 5.0f, 5.0f) { }

        auto trace(Ray& ray) -> glm::vec3
        {
            float closest = std::numeric_limits<float>::infinity();
            const Object* hit_obj = nullptr;

            for (auto& obj : objs)
            {
                float t;

                if (obj.intersect(ray, t))
                    if (t < closest)
                    {
                        closest = t;
                        hit_obj = &obj;
                    }
            }

            if (hit_obj)
            {
                glm::vec3 hit_point = ray.m_origin + ray.m_direction * closest;
                glm::vec3 normal = hit_obj->get_normal(hit_point);
                glm::vec3 light_dir = glm::normalize(m_light_pos - hit_point);

                float diff = std::max(glm::dot(normal, light_dir), 0.0f);

                Ray shadow_ray(hit_point + normal * 0.001f, light_dir);
                bool in_shadow = false;

                for (auto& obj : objs)
                {
                    float t;

                    if (obj.intersect(shadow_ray, t))
                    {
                        in_shadow = true;
                        break;
                    }
                }

                glm::vec3 color = hit_obj->m_material.m_color;
                float ambient = 0.1f;

                if (in_shadow)
                    return color * ambient;
                return color * (ambient + diff * 0.9f);
            }

            return glm::vec3(0.0f, 0.0f, 0.1f);
        }

    public:
        std::vector<Object> objs;
        glm::vec3 m_light_pos;
    };
};