-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiffuseShader.hpp
89 lines (74 loc) · 1.87 KB
/
DiffuseShader.hpp
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
#pragma once
#include "Vertex.h"
#include "SceneContext.h"
#include "VertexShaderMatHelper.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <memory>
class DiffuseShader
{
public:
using UseDerivative = std::true_type;
struct VSOut {
glm::vec4 proj_pos;
glm::vec2 texcoord;
VSOut& operator+=(const VSOut& rhs)
{
proj_pos += rhs.proj_pos;
texcoord += rhs.texcoord;
return *this;
}
VSOut operator+(const VSOut& rhs) const
{
return VSOut(*this) += rhs;
}
VSOut& operator*=(float v) {
proj_pos *= v;
texcoord *= v;
return *this;
}
VSOut operator*(float rhs) const
{
return VSOut(*this) *= rhs;
}
void Lerp(const VSOut& v0, const VSOut& v1, const VSOut& v2, float a, float b, float c) noexcept {
texcoord = v0.texcoord * a + v1.texcoord * b + v2.texcoord * c;
}
};
class VertexShader : public VertexShaderMatHelper {
public:
VSOut operator()(const Vertex& v) const
{
return {
proj_view * model * glm::vec4(v.position, 1.0f),
v.texcoord
};
}
};
class PixelShader {
public:
std::shared_ptr<SceneContext> pContext;
glm::vec4 operator()(const VSOut& v, const VSOut& ddx, const VSOut& ddy, int modelId, int meshId) const
{
auto material_id = pContext->models[modelId]->meshes[meshId].material_idx;
auto& material = pContext->models[modelId]->materials[material_id];
glm::vec4 color;
if (material->diffuse != nullptr) {
float w = material->diffuse->GetWidth();
float h = material->diffuse->GetHeight();
float mx2 = std::max(
glm::dot(ddx.texcoord, ddx.texcoord) * w * w,
glm::dot(ddy.texcoord, ddy.texcoord) * h * h
);
float level = 0.5f * glm::log2(mx2);
color = material->diffuse->Sample(v.texcoord.x, v.texcoord.y, level);
}
else
color = glm::vec4(material->Kd, 1.0f);
return color;
}
};
public:
VertexShader vs;
PixelShader ps;
};