Fix basic material and add demo

This commit is contained in:
SirLynix 2022-06-28 08:54:35 +02:00 committed by Jérôme Leclercq
parent ccd7885213
commit b2fad27618
4 changed files with 303 additions and 82 deletions

View File

@ -0,0 +1,240 @@
#include <Nazara/Core.hpp>
#include <Nazara/Platform.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Renderer.hpp>
#include <NZSL/SpirvConstantCache.hpp>
#include <NZSL/SpirvPrinter.hpp>
#include <Nazara/Utility.hpp>
#include <array>
#include <chrono>
#include <iostream>
#include <thread>
int main()
{
std::filesystem::path resourceDir = "assets/examples";
if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory("../.." / resourceDir))
resourceDir = "../.." / resourceDir;
Nz::Renderer::Config rendererConfig;
std::cout << "Run using Vulkan? (y/n)" << std::endl;
if (std::getchar() == 'y')
rendererConfig.preferredAPI = Nz::RenderAPI::Vulkan;
else
rendererConfig.preferredAPI = Nz::RenderAPI::OpenGL;
Nz::Modules<Nz::Graphics> nazara(rendererConfig);
Nz::RenderWindow window;
Nz::MeshParams meshParams;
meshParams.center = true;
meshParams.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, -90.f, 0.f)) * Nz::Matrix4f::Scale(Nz::Vector3f(0.002f));
meshParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ_Normal_UV_Tangent);
std::shared_ptr<Nz::RenderDevice> device = Nz::Graphics::Instance()->GetRenderDevice();
std::string windowTitle = "Physically Based Rendering Test";
if (!window.Create(device, Nz::VideoMode(1920, 1080, 32), windowTitle))
{
std::cout << "Failed to create Window" << std::endl;
return __LINE__;
}
std::shared_ptr<Nz::Mesh> sphereMesh = std::make_shared<Nz::Mesh>();
sphereMesh->CreateStatic();
sphereMesh->BuildSubMesh(Nz::Primitive::UVSphere(1.f, 50, 50));
sphereMesh->SetMaterialCount(1);
sphereMesh->GenerateNormalsAndTangents();
std::shared_ptr<Nz::GraphicalMesh> gfxMesh = Nz::GraphicalMesh::BuildFromMesh(*sphereMesh);
// Textures
Nz::TextureParams texParams;
texParams.renderDevice = device;
Nz::TextureParams srgbTexParams = texParams;
srgbTexParams.loadFormat = Nz::PixelFormat::RGBA8_SRGB;
std::shared_ptr<Nz::Material> material = std::make_shared<Nz::Material>();
std::shared_ptr<Nz::MaterialPass> forwardPass = std::make_shared<Nz::MaterialPass>(Nz::PhysicallyBasedMaterial::GetSettings());
forwardPass->EnableDepthBuffer(true);
forwardPass->EnableFaceCulling(true);
material->AddPass("ForwardPass", forwardPass);
std::shared_ptr<Nz::Texture> normalMap = Nz::Texture::LoadFromFile(resourceDir / "Rusty/rustediron2_normal.png", texParams);
Nz::PhysicallyBasedMaterial pbrMat(*forwardPass);
pbrMat.EnableAlphaTest(false);
pbrMat.SetAlphaMap(Nz::Texture::LoadFromFile(resourceDir / "alphatile.png", texParams));
pbrMat.SetDiffuseMap(Nz::Texture::LoadFromFile(resourceDir / "Rusty/rustediron2_basecolor.png", srgbTexParams));
pbrMat.SetMetallicMap(Nz::Texture::LoadFromFile(resourceDir / "Rusty/rustediron2_metallic.png", texParams));
pbrMat.SetRoughnessMap(Nz::Texture::LoadFromFile(resourceDir / "Rusty/rustediron2_roughness.png", texParams));
pbrMat.SetNormalMap(normalMap);
Nz::Model model(std::move(gfxMesh), sphereMesh->GetAABB());
for (std::size_t i = 0; i < model.GetSubMeshCount(); ++i)
model.SetMaterial(i, material);
Nz::Vector2ui windowSize = window.GetSize();
Nz::Camera camera(window.GetRenderTarget());
//camera.UpdateClearColor(Nz::Color::Gray);
Nz::ViewerInstance& viewerInstance = camera.GetViewerInstance();
viewerInstance.UpdateTargetSize(Nz::Vector2f(window.GetSize()));
viewerInstance.UpdateProjViewMatrices(Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(windowSize.x) / windowSize.y, 0.1f, 1000.f), Nz::Matrix4f::Translate(Nz::Vector3f::Backward() * 1));
Nz::WorldInstancePtr modelInstance = std::make_shared<Nz::WorldInstance>();
modelInstance->UpdateWorldMatrix(Nz::Matrix4f::Translate(Nz::Vector3f::Forward() * 2 + Nz::Vector3f::Left()));
Nz::Recti scissorBox(Nz::Vector2i(window.GetSize()));
Nz::ForwardFramePipeline framePipeline;
std::size_t cameraIndex = framePipeline.RegisterViewer(&camera, 0);
std::size_t worldInstanceIndex1 = framePipeline.RegisterWorldInstance(modelInstance);
framePipeline.RegisterRenderable(worldInstanceIndex1, &model, 0xFFFFFFFF, scissorBox);
std::shared_ptr<Nz::DirectionalLight> light = std::make_shared<Nz::DirectionalLight>();
light->UpdateRotation(Nz::EulerAnglesf(-45.f, 0.f, 0.f));
framePipeline.RegisterLight(light, 0xFFFFFFFF);
Nz::Vector3f viewerPos = Nz::Vector3f::Zero();
Nz::EulerAnglesf camAngles(0.f, 0.f, 0.f);
Nz::Quaternionf camQuat(camAngles);
window.EnableEventPolling(true);
Nz::Clock updateClock;
Nz::Clock secondClock;
unsigned int fps = 0;
Nz::Mouse::SetRelativeMouseMode(true);
while (window.IsOpen())
{
Nz::WindowEvent event;
while (window.PollEvent(&event))
{
switch (event.type)
{
case Nz::WindowEventType::Quit:
window.Close();
break;
case Nz::WindowEventType::KeyPressed:
if (event.key.virtualKey == Nz::Keyboard::VKey::N)
{
if (pbrMat.GetNormalMap())
pbrMat.SetNormalMap({});
else
pbrMat.SetNormalMap(normalMap);
}
break;
case Nz::WindowEventType::MouseMoved: // La souris a bougé
{
// Gestion de la caméra free-fly (Rotation)
float sensitivity = 0.3f; // Sensibilité de la souris
// On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris
camAngles.yaw = camAngles.yaw - event.mouseMove.deltaX * sensitivity;
camAngles.yaw.Normalize();
// Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles
camAngles.pitch = Nz::Clamp(camAngles.pitch - event.mouseMove.deltaY*sensitivity, -89.f, 89.f);
camQuat = camAngles;
//light->UpdateRotation(camQuat);
break;
}
case Nz::WindowEventType::Resized:
{
Nz::Vector2ui newWindowSize = window.GetSize();
viewerInstance.UpdateProjectionMatrix(Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(newWindowSize.x) / newWindowSize.y, 0.1f, 1000.f));
viewerInstance.UpdateTargetSize(Nz::Vector2f(newWindowSize));
break;
}
default:
break;
}
}
if (updateClock.GetMilliseconds() > 1000 / 60)
{
float cameraSpeed = 2.f * updateClock.GetSeconds();
updateClock.Restart();
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Z))
viewerPos += camQuat * Nz::Vector3f::Forward() * cameraSpeed;
// Si la flèche du bas ou la touche S est pressée, on recule
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::S))
viewerPos += camQuat * Nz::Vector3f::Backward() * cameraSpeed;
// Etc...
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Q))
viewerPos += camQuat * Nz::Vector3f::Left() * cameraSpeed;
// Etc...
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::D))
viewerPos += camQuat * Nz::Vector3f::Right() * cameraSpeed;
// Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation)
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift))
viewerPos += Nz::Vector3f::Up() * cameraSpeed;
// Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc...
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl))
viewerPos += Nz::Vector3f::Down() * cameraSpeed;
//light->UpdatePosition(viewerPos);
}
Nz::RenderFrame frame = window.AcquireFrame();
if (!frame)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
viewerInstance.UpdateViewMatrix(Nz::Matrix4f::TransformInverse(viewerPos, camAngles));
viewerInstance.UpdateEyePosition(viewerPos);
framePipeline.InvalidateViewer(cameraIndex);
framePipeline.Render(frame);
frame.Present();
// On incrémente le compteur de FPS improvisé
fps++;
if (secondClock.GetMilliseconds() >= 1000) // Toutes les secondes
{
// Et on insère ces données dans le titre de la fenêtre
window.SetTitle(windowTitle + " - " + Nz::NumberToString(fps) + " FPS");
/*
Note: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier,
via quelque chose de similaire à u8"Cha\u00CEne de caract\u00E8res".
Cependant, si le code source est encodé en UTF-8 (Comme c'est le cas dans ce fichier),
cela fonctionnera aussi comme ceci : "Chaîne de caractères".
*/
// Et on réinitialise le compteur de FPS
fps = 0;
// Et on relance l'horloge pour refaire ça dans une seconde
secondClock.Restart();
}
}
return EXIT_SUCCESS;
}

View File

@ -0,0 +1,5 @@
target("PBR")
set_group("Examples")
set_kind("binary")
add_deps("NazaraGraphics")
add_files("main.cpp")

View File

@ -0,0 +1,5 @@
[nzsl_version("1.0")]
module Engine.Constants;
[export]
const Pi: f32 = 3.1415926535897932384626433832795;

View File

@ -79,12 +79,12 @@ struct VertToFrag
[location(1), cond(HasUV)] uv: vec2[f32],
[location(2), cond(HasColor)] color: vec4[f32],
[location(3), cond(HasNormal)] normal: vec3[f32],
[location(4), cond(HasNormalMapping)] tbnMatrix: mat3[f32],
[location(4), cond(HasNormalMapping)] tangent: vec3[f32],
[builtin(position)] position: vec4[f32],
}
// Fragment stage
const PI: f32 = 3.1415926535897932384626433832795;
import Pi from Engine.Constants;
fn DistributionGGX(N: vec3[f32], H: vec3[f32], roughness: f32) -> f32
{
@ -96,7 +96,7 @@ fn DistributionGGX(N: vec3[f32], H: vec3[f32], roughness: f32) -> f32
let num = a2;
let denom = (NdotH2 * (a2 - 1.0) + 1.0);
denom = PI * denom * denom;
denom = Pi * denom * denom;
return num / denom;
}
@ -158,15 +158,20 @@ fn main(input: VertToFrag) -> FragOut
const if (HasNormal)
{
let lightAmbient = vec3[f32](0.0, 0.0, 0.0);
let lightDiffuse = vec3[f32](0.0, 0.0, 0.0);
let lightSpecular = vec3[f32](0.0, 0.0, 0.0);
let lightRadiance = vec3[f32](0.0, 0.0, 0.0);
let eyeVec = normalize(viewerData.eyePosition - input.worldPos);
let normal: vec3[f32];
const if (HasNormalMapping && false)
normal = normalize(input.tbnMatrix * (MaterialNormalMap.Sample(input.uv).xyz * 2.0 - vec3[f32](1.0, 1.0, 1.0)));
const if (HasNormalMapping)
{
let N = normalize(input.normal);
let T = normalize(input.tangent);
let B = cross(N, T);
let tbnMatrix = mat3[f32](T, B, N);
normal = normalize(tbnMatrix * (MaterialNormalMap.Sample(input.uv).xyz * 2.0 - vec3[f32](1.0, 1.0, 1.0)));
}
else
normal = normalize(input.normal);
@ -187,101 +192,72 @@ fn main(input: VertToFrag) -> FragOut
let F0 = vec3[f32](0.04, 0.04, 0.04);
F0 = albedo * metallic + F0 * (1.0 - metallic);
let albedoFactor = albedo / Pi;
for i in u32(0) -> lightData.lightCount
{
let light = lightData.lights[i];
let lightAmbientFactor = light.factor.x;
let lightDiffuseFactor = light.factor.y;
let attenuation = 1.0;
// TODO: Add switch instruction
let lightToPosNorm: vec3[f32];
if (light.type == DirectionalLight)
lightToPosNorm = -light.parameter1.xyz;
else
{
let lightDir = -light.parameter1.xyz;
let H = normalize(lightDir + eyeVec);
// cook-torrance brdf
let NDF = DistributionGGX(normal, H, roughness);
let G = GeometrySmith(normal, eyeVec, lightDir, roughness);
let F = FresnelSchlick(max(dot(H, eyeVec), 0.0), F0);
let kS = F;
let kD = vec3[f32](1.0, 1.0, 1.0) - kS;
kD *= 1.0 - metallic;
let numerator = NDF * G * F;
let denominator = 4.0 * max(dot(normal, eyeVec), 0.0) * max(dot(normal, lightDir), 0.0);
let specular = numerator / max(denominator, 0.0001);
let NdotL = max(dot(normal, -lightDir), 0.0);
lightDiffuse += (kD * albedo / PI + specular) * light.color.rgb * NdotL;
//lightDiffuse = specular;
}
else if (light.type == PointLight)
{
// PointLight | SpotLight
let lightPos = light.parameter1.xyz;
let lightInvRadius = light.parameter1.w;
let lightToPos = input.worldPos - lightPos;
let dist = length(lightToPos);
let lightToPosNorm = lightToPos / max(dist, 0.0001);
let attenuationFactor = max(1.0 - dist * lightInvRadius, 0.0);
attenuation = max(1.0 - dist * lightInvRadius, 0.0);
lightToPosNorm = lightToPos / max(dist, 0.0001);
lightAmbient += attenuationFactor * light.color.rgb * lightAmbientFactor * settings.AmbientColor;
if (light.type == SpotLight)
{
let lightDir = light.parameter2.xyz;
let lightInnerAngle = light.parameter3.x;
let lightOuterAngle = light.parameter3.y;
let lambert = max(dot(normal, -lightToPosNorm), 0.0);
lightDiffuse += attenuationFactor * lambert * light.color.rgb * lightDiffuseFactor;
let reflection = reflect(lightToPosNorm, normal);
let specFactor = max(dot(reflection, eyeVec), 0.0);
specFactor = pow(specFactor, settings.Shininess);
lightSpecular += attenuationFactor * specFactor * light.color.rgb;
let curAngle = dot(lightDir, lightToPosNorm);
let innerMinusOuterAngle = lightInnerAngle - lightOuterAngle;
attenuation *= max((curAngle - lightOuterAngle) / innerMinusOuterAngle, 0.0);
}
}
else if (light.type == SpotLight)
{
let lightPos = light.parameter1.xyz;
let lightDir = light.parameter2.xyz;
let lightInvRadius = light.parameter1.w;
let lightInnerAngle = light.parameter3.x;
let lightOuterAngle = light.parameter3.y;
let lightToPos = input.worldPos - lightPos;
let dist = length(lightToPos);
let lightToPosNorm = lightToPos / max(dist, 0.0001);
let radiance = light.color.rgb * attenuation;
let curAngle = dot(lightDir, lightToPosNorm);
let innerMinusOuterAngle = lightInnerAngle - lightOuterAngle;
let halfDir = normalize(lightToPosNorm + eyeVec);
let attenuationFactor = max(1.0 - dist * lightInvRadius, 0.0);
attenuationFactor *= max((curAngle - lightOuterAngle) / innerMinusOuterAngle, 0.0);
// cook-torrance brdf
let NDF = DistributionGGX(normal, halfDir, roughness);
let G = GeometrySmith(normal, eyeVec, lightToPosNorm, roughness);
let F = FresnelSchlick(max(dot(halfDir, eyeVec), 0.0), F0);
lightAmbient += attenuationFactor * light.color.rgb * lightAmbientFactor * settings.AmbientColor;
let kS = F;
let diffuse = vec3[f32](1.0, 1.0, 1.0) - kS;
diffuse *= 1.0 - metallic;
let lambert = max(dot(normal, -lightToPosNorm), 0.0);
let numerator = NDF * G * F;
let denominator = 4.0 * max(dot(normal, eyeVec), 0.0) * max(dot(normal, lightToPosNorm), 0.0);
let specular = numerator / max(denominator, 0.0001);
lightDiffuse += attenuationFactor * lambert * light.color.rgb * lightDiffuseFactor;
let reflection = reflect(lightToPosNorm, normal);
let specFactor = max(dot(reflection, eyeVec), 0.0);
specFactor = pow(specFactor, settings.Shininess);
lightSpecular += attenuationFactor * specFactor * light.color.rgb;
}
let NdotL = max(dot(normal, lightToPosNorm), 0.0);
lightRadiance += (diffuse * albedoFactor + specular) * radiance * NdotL;
}
lightSpecular *= settings.SpecularColor;
let ambient = (0.03).rrr * albedo;
const if (HasSpecularTexture)
lightSpecular *= MaterialSpecularMap.Sample(input.uv).rgb;
let lightColor = lightAmbient + lightDiffuse + lightSpecular;
let color = ambient + lightRadiance * diffuseColor.rgb;
color = color / (color + vec3[f32](1.0, 1.0, 1.0));
color = pow(color, (1.0 / 2.2).xxx);
let output: FragOut;
output.RenderTarget0 = vec4[f32](lightColor, 1.0) * diffuseColor;
output.RenderTarget0 = vec4[f32](color, 1.0);
return output;
}
else
@ -360,7 +336,7 @@ fn main(input: VertIn) -> VertToFrag
output.worldPos = worldPosition.xyz;
output.position = viewerData.viewProjMatrix * worldPosition;
let rotationMatrix = mat3[f32](instanceData.worldMatrix);
let rotationMatrix = transpose(inverse(mat3[f32](instanceData.worldMatrix)));
const if (HasColor)
output.color = input.color;
@ -372,12 +348,7 @@ fn main(input: VertIn) -> VertToFrag
output.uv = input.uv;
const if (HasNormalMapping)
{
let binormal = cross(input.normal, input.tangent);
output.tbnMatrix[0] = normalize(rotationMatrix * input.tangent);
output.tbnMatrix[1] = normalize(rotationMatrix * binormal);
output.tbnMatrix[2] = normalize(rotationMatrix * input.normal);
}
output.tangent = rotationMatrix * input.tangent;
return output;
}