Merge pull request #267 from MihailRis/update-entities-renderer

Update entities renderer
This commit is contained in:
MihailRis 2024-07-20 21:46:25 +03:00 committed by GitHub
commit 826579df2b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 198 additions and 135 deletions

View File

@ -141,6 +141,20 @@ rig:set_texture(key: str, value: str)
-- Returns the bone index by name or nil
rig:index(name: str) -> int
-- Checks the visibility status of a bone by index
-- or the skeleton if no index is specified
rig:is_visible([optional] index: int) -> bool
-- Sets the visibility status of a bone by index
-- or the skeleton if no index is specified
rig:set_visible([optional] index: int, status: bool)
-- Returns the color of the entity
rig:get_color() -> vec3
-- Sets the color of the entity
rig:set_color(color: vec3)
```
## Component events

View File

@ -150,6 +150,12 @@ rig:is_visible([optional] index: int) -> bool
-- Устанавливает статус видимости кости по индексу
-- или всего скелета, если индекс не указан
rig:set_visible([optional] index: int, status: bool)
-- Возвращает цвет сущности
rig:get_color() -> vec3
-- Устанавливает цвет сущности
rig:set_color(color: vec3)
```
## События компонента

24
res/shaders/entity.glslf Normal file
View File

@ -0,0 +1,24 @@
in vec4 a_color;
in vec2 a_texCoord;
in float a_distance;
in vec3 a_dir;
out vec4 f_color;
uniform sampler2D u_texture0;
uniform samplerCube u_cubemap;
uniform vec3 u_fogColor;
uniform float u_fogFactor;
uniform float u_fogCurve;
void main() {
vec3 fogColor = texture(u_cubemap, a_dir).rgb;
vec4 tex_color = texture(u_texture0, a_texCoord);
float depth = (a_distance/256.0);
float alpha = a_color.a * tex_color.a;
// anyway it's any alpha-test alternative required
if (alpha < 0.3f)
discard;
f_color = mix(a_color * tex_color, vec4(fogColor,1.0),
min(1.0, pow(depth*u_fogFactor, u_fogCurve)));
f_color.a = alpha;
}

41
res/shaders/entity.glslv Normal file
View File

@ -0,0 +1,41 @@
#include <commons>
layout (location = 0) in vec3 v_position;
layout (location = 1) in vec2 v_texCoord;
layout (location = 2) in vec3 v_color;
layout (location = 3) in float v_light;
out vec4 a_color;
out vec2 a_texCoord;
out float a_distance;
out vec3 a_dir;
uniform mat4 u_model;
uniform mat4 u_proj;
uniform mat4 u_view;
uniform vec3 u_cameraPos;
uniform float u_gamma;
uniform samplerCube u_cubemap;
uniform vec3 u_torchlightColor;
uniform float u_torchlightDistance;
void main() {
vec4 modelpos = u_model * vec4(v_position, 1.0);
vec3 pos3d = modelpos.xyz - u_cameraPos;
modelpos.xyz = apply_planet_curvature(modelpos.xyz, pos3d);
vec4 decomp_light = decompress_light(v_light);
vec3 light = decomp_light.rgb;
float torchlight = max(0.0, 1.0-distance(u_cameraPos, modelpos.xyz) /
u_torchlightDistance);
light += torchlight * u_torchlightColor;
a_color = vec4(pow(light, vec3(u_gamma)),1.0f);
a_texCoord = v_texCoord;
a_dir = modelpos.xyz - u_cameraPos;
vec3 skyLightColor = pick_sky_color(u_cubemap);
a_color.rgb = max(a_color.rgb, skyLightColor.rgb*decomp_light.a) * v_color;
a_distance = length(u_view * u_model * vec4(pos3d * FOG_POS_SCALE, 0.0));
gl_Position = u_proj * u_view * modelpos;
}

View File

@ -3,9 +3,6 @@
#include <constants>
#define PI 3.1415926535897932384626433832795
#define PI2 (PI*2)
vec4 decompress_light(float compressed_light) {
vec4 result;
int compressed = floatBitsToInt(compressed_light);
@ -24,4 +21,9 @@ vec3 pick_sky_color(samplerCube cubemap) {
return skyLightColor;
}
vec3 apply_planet_curvature(vec3 modelPos, vec3 pos3d) {
modelPos.y -= pow(length(pos3d.xz)*CURVATURE_FACTOR, 3.0);
return modelPos;
}
#endif // COMMONS_GLSL_

View File

@ -1,6 +1,9 @@
#ifndef CONSTANTS_GLSL_
#define CONSTANTS_GLSL_
#define PI 3.1415926535897932384626433832795
#define PI2 (PI*2)
// geometry
#define CURVATURE_FACTOR 0.002

View File

@ -10,7 +10,7 @@ uniform vec3 u_fogColor;
uniform float u_fogFactor;
uniform float u_fogCurve;
void main(){
void main() {
vec3 fogColor = texture(u_cubemap, a_dir).rgb;
vec4 tex_color = texture(u_texture0, a_texCoord);
float depth = (a_distance/256.0);

View File

@ -12,7 +12,6 @@ out vec3 a_dir;
uniform mat4 u_model;
uniform mat4 u_proj;
uniform mat4 u_view;
uniform vec3 u_skyLightColor;
uniform vec3 u_cameraPos;
uniform float u_gamma;
uniform samplerCube u_cubemap;
@ -20,15 +19,15 @@ uniform samplerCube u_cubemap;
uniform vec3 u_torchlightColor;
uniform float u_torchlightDistance;
void main(){
void main() {
vec4 modelpos = u_model * vec4(v_position, 1.0);
vec3 pos3d = modelpos.xyz-u_cameraPos.xyz;
modelpos.y -= pow(length(pos3d.xz)*CURVATURE_FACTOR, 3.0);
vec4 viewmodelpos = u_view * modelpos;
vec3 pos3d = modelpos.xyz-u_cameraPos;
modelpos.xyz = apply_planet_curvature(modelpos.xyz, pos3d);
vec4 decomp_light = decompress_light(v_light);
vec3 light = decomp_light.rgb;
float torchlight = max(0.0, 1.0-distance(u_cameraPos, modelpos.xyz)/u_torchlightDistance);
float torchlight = max(0.0, 1.0-distance(u_cameraPos, modelpos.xyz) /
u_torchlightDistance);
light += torchlight * u_torchlightColor;
a_color = vec4(pow(light, vec3(u_gamma)),1.0f);
a_texCoord = v_texCoord;
@ -37,5 +36,5 @@ void main(){
vec3 skyLightColor = pick_sky_color(u_cubemap);
a_color.rgb = max(a_color.rgb, skyLightColor.rgb*decomp_light.a);
a_distance = length(u_view * u_model * vec4(pos3d * FOG_POS_SCALE, 0.0));
gl_Position = u_proj * viewmodelpos;
gl_Position = u_proj * u_view * modelpos;
}

View File

@ -180,6 +180,7 @@ void AssetsLoader::addDefaults(AssetsLoader& loader, const Content* content) {
loader.add(AssetType::FONT, FONTS_FOLDER+"/font", "normal");
loader.add(AssetType::SHADER, SHADERS_FOLDER+"/ui", "ui");
loader.add(AssetType::SHADER, SHADERS_FOLDER+"/main", "main");
loader.add(AssetType::SHADER, SHADERS_FOLDER+"/entity", "entity");
loader.add(AssetType::SHADER, SHADERS_FOLDER+"/lines", "lines");
loader.add(AssetType::TEXTURE, TEXTURES_FOLDER+"/gui/menubg", "gui/menubg");
loader.add(AssetType::TEXTURE, TEXTURES_FOLDER+"/gui/delete_icon", "gui/delete_icon");

View File

@ -141,9 +141,5 @@ std::string GLSLExtension::process(const fs::path& file, const std::string& sour
ss << source.substr(pos, endline+1-pos);
pos = endline+1;
}
if (!header) {
std::cout << " ========================================================== " << file.u8string() << std::endl;
std::cout << ss.str() << std::endl;
}
return ss.str();
}

View File

@ -16,11 +16,11 @@
#include <algorithm>
/// xyz, uv, compressed rgba
inline constexpr uint VERTEX_SIZE = 6;
/// xyz, uv, color, compressed lights
inline constexpr uint VERTEX_SIZE = 9;
static const vattr attrs[] = {
{3}, {2}, {1}, {0}
{3}, {2}, {3}, {1}, {0}
};
inline constexpr glm::vec3 X(1, 0, 0);
@ -35,12 +35,25 @@ struct DecomposedMat4 {
glm::vec4 perspective;
};
static glm::mat4 extract_rotation(glm::mat4 matrix) {
DecomposedMat4 decomposed = {};
glm::quat rotation;
glm::decompose(
matrix,
decomposed.scale,
rotation,
decomposed.translation,
decomposed.skew,
decomposed.perspective
);
return glm::toMat3(rotation);
}
ModelBatch::ModelBatch(size_t capacity, Assets* assets, Chunks* chunks)
: buffer(std::make_unique<float[]>(capacity * VERTEX_SIZE)),
capacity(capacity),
index(0),
mesh(std::make_unique<Mesh>(buffer.get(), 0, attrs)),
combined(1.0f),
assets(assets),
chunks(chunks)
{
@ -55,9 +68,9 @@ ModelBatch::~ModelBatch() {
}
void ModelBatch::draw(const model::Mesh& mesh, const glm::mat4& matrix,
const glm::mat3& rotation,
const glm::mat3& rotation, glm::vec3 tint,
const texture_names_map* varTextures) {
glm::vec3 gpos = matrix * glm::vec4(glm::vec3(), 1.0f);
glm::vec3 gpos = matrix * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
light_t light = chunks->getLight(floor(gpos.x), floor(gpos.y), floor(gpos.z));
glm::vec4 lights (
Lightmap::extract(light, 0) / 15.0f,
@ -77,17 +90,19 @@ void ModelBatch::draw(const model::Mesh& mesh, const glm::mat4& matrix,
auto norm = rotation * vert.normal;
float d = glm::dot(norm, SUN_VECTOR);
d = 0.8f + d * 0.2f;
auto color = lights * d;
vertex(matrix * glm::vec4(vert.coord, 1.0f), vert.uv, color);
vertex(matrix * glm::vec4(vert.coord, 1.0f), vert.uv, lights*d, tint);
}
}
}
void ModelBatch::draw(const model::Model* model,
void ModelBatch::draw(glm::mat4 matrix,
glm::vec3 tint,
const model::Model* model,
const texture_names_map* varTextures) {
for (const auto& mesh : model->meshes) {
entries.push_back({combined, rotation, &mesh, varTextures});
entries.push_back({
matrix, extract_rotation(matrix), tint, &mesh, varTextures
});
}
}
@ -98,26 +113,12 @@ void ModelBatch::render() {
}
);
for (auto& entry : entries) {
draw(*entry.mesh, entry.matrix, entry.rotation, entry.varTextures);
draw(*entry.mesh, entry.matrix, entry.rotation, entry.tint, entry.varTextures);
}
flush();
entries.clear();
}
void ModelBatch::box(glm::vec3 pos, glm::vec3 size, glm::vec4 lights) {
if (index + 36 < capacity*VERTEX_SIZE) {
flush();
}
plane(pos+Z*size, X*size, Y*size, Z, lights);
plane(pos-Z*size, -X*size, Y*size, -Z, lights);
plane(pos+Y*size, X*size, -Z*size, Y, lights);
plane(pos-Y*size, X*size, Z*size, -Y, lights);
plane(pos+X*size, -Z*size, Y*size, X, lights);
plane(pos-X*size, Z*size, Y*size, -X, lights);
}
void ModelBatch::setTexture(const std::string& name,
const texture_names_map* varTextures) {
if (name.at(0) == '$') {
@ -169,41 +170,3 @@ void ModelBatch::flush() {
mesh->draw();
index = 0;
}
static glm::mat4 extract_rotation(glm::mat4 matrix) {
DecomposedMat4 decomposed = {};
glm::quat rotation;
glm::decompose(
matrix,
decomposed.scale,
rotation,
decomposed.translation,
decomposed.skew,
decomposed.perspective
);
return glm::toMat3(rotation);
}
void ModelBatch::translate(glm::vec3 vec) {
pushMatrix(glm::translate(glm::mat4(1.0f), vec));
}
void ModelBatch::rotate(glm::vec3 axis, float angle) {
pushMatrix(glm::rotate(glm::mat4(1.0f), angle, axis));
}
void ModelBatch::scale(glm::vec3 vec) {
pushMatrix(glm::scale(glm::mat4(1.0f), vec));
}
void ModelBatch::pushMatrix(glm::mat4 matrix) {
matrices.push_back(combined);
combined = combined * matrix;
rotation = extract_rotation(combined);
}
void ModelBatch::popMatrix() {
combined = matrices[matrices.size()-1];
matrices.erase(matrices.end()-1);
rotation = extract_rotation(combined);
}

View File

@ -29,10 +29,6 @@ class ModelBatch {
std::unique_ptr<Mesh> mesh;
std::unique_ptr<Texture> blank;
glm::mat4 combined;
std::vector<glm::mat4> matrices;
glm::mat3 rotation;
Assets* assets;
Chunks* chunks;
Texture* texture = nullptr;
@ -41,7 +37,7 @@ class ModelBatch {
static inline glm::vec3 SUN_VECTOR {0.411934f, 0.863868f, -0.279161f};
inline void vertex(
glm::vec3 pos, glm::vec2 uv, glm::vec4 light
glm::vec3 pos, glm::vec2 uv, glm::vec4 light, glm::vec3 tint
) {
float* buffer = this->buffer.get();
buffer[index++] = pos.x;
@ -49,6 +45,9 @@ class ModelBatch {
buffer[index++] = pos.z;
buffer[index++] = uv.x * region.getWidth() + region.u1;
buffer[index++] = uv.y * region.getHeight() + region.v1;
buffer[index++] = tint.x;
buffer[index++] = tint.y;
buffer[index++] = tint.z;
union {
float floating;
@ -63,25 +62,11 @@ class ModelBatch {
buffer[index++] = compressed.floating;
}
inline void plane(glm::vec3 pos, glm::vec3 right, glm::vec3 up, glm::vec3 norm, glm::vec4 lights) {
norm = rotation * norm;
float d = glm::dot(norm, SUN_VECTOR);
d = 0.8f + d * 0.2f;
auto color = lights * d;
vertex(pos-right-up, {0,0}, color);
vertex(pos+right-up, {1,0}, color);
vertex(pos+right+up, {1,1}, color);
vertex(pos-right-up, {0,0}, color);
vertex(pos+right+up, {1,1}, color);
vertex(pos-right+up, {0,1}, color);
}
void draw(const model::Mesh& mesh, const glm::mat4& matrix,
const glm::mat3& rotation, const texture_names_map* varTextures);
void box(glm::vec3 pos, glm::vec3 size, glm::vec4 lights);
void draw(const model::Mesh& mesh,
const glm::mat4& matrix,
const glm::mat3& rotation,
glm::vec3 tint,
const texture_names_map* varTextures);
void setTexture(const std::string& name,
const texture_names_map* varTextures);
void setTexture(Texture* texture);
@ -90,6 +75,7 @@ class ModelBatch {
struct DrawEntry {
glm::mat4 matrix;
glm::mat3 rotation;
glm::vec3 tint;
const model::Mesh* mesh;
const texture_names_map* varTextures;
};
@ -98,15 +84,10 @@ public:
ModelBatch(size_t capacity, Assets* assets, Chunks* chunks);
~ModelBatch();
void translate(glm::vec3 vec);
void rotate(glm::vec3 axis, float angle);
void scale(glm::vec3 vec);
void pushMatrix(glm::mat4 matrix);
void popMatrix();
void draw(const model::Model* model,
void draw(glm::mat4 matrix,
glm::vec3 tint,
const model::Model* model,
const texture_names_map* varTextures);
void render();
};

View File

@ -152,22 +152,12 @@ void WorldRenderer::drawChunks(Chunks* chunks, Camera* camera, Shader* shader) {
}
}
void WorldRenderer::renderLevel(
const DrawContext&,
Camera* camera,
const EngineSettings& settings,
bool pause
void WorldRenderer::setupWorldShader(
Shader* shader, Camera* camera, const EngineSettings& settings,
float fogFactor
) {
auto assets = engine->getAssets();
auto atlas = assets->get<Atlas>("blocks");
auto shader = assets->get<Shader>("main");
auto indices = level->content->getIndices();
float fogFactor = 15.0f / ((float)settings.chunks.loadDistance.get()-2);
// Setting up main shader
shader->use();
shader->uniformMatrix("u_model", glm::mat4(1.0f));
shader->uniformMatrix("u_proj", camera->getProjection());
shader->uniformMatrix("u_view", camera->getView());
shader->uniform1f("u_timer", timer);
@ -178,6 +168,7 @@ void WorldRenderer::renderLevel(
shader->uniform3f("u_cameraPos", camera->position);
shader->uniform1i("u_cubemap", 1);
auto indices = level->content->getIndices();
// Light emission when an emissive item is chosen
{
auto inventory = player->getInventory();
@ -191,15 +182,32 @@ void WorldRenderer::renderLevel(
);
shader->uniform1f("u_torchlightDistance", 6.0f);
}
}
void WorldRenderer::renderLevel(
const DrawContext&,
Camera* camera,
const EngineSettings& settings,
bool pause
) {
auto assets = engine->getAssets();
auto atlas = assets->get<Atlas>("blocks");
float fogFactor = 15.0f / ((float)settings.chunks.loadDistance.get()-2);
auto shader = assets->get<Shader>("main");
setupWorldShader(shader, camera, settings, fogFactor);
// Binding main shader textures
skybox->bind();
atlas->getTexture()->bind();
drawChunks(level->chunks.get(), camera, shader);
shader->uniformMatrix("u_model", glm::mat4(1.0f));
auto entityShader = assets->get<Shader>("entity");
setupWorldShader(entityShader, camera, settings, fogFactor);
level->entities->render(assets, *modelBatch, *frustumCulling, pause);
if (!pause) {
scripting::on_frontend_render();
}
@ -263,8 +271,8 @@ void WorldRenderer::renderDebugLines(
glm::vec3 coord = player->camera->position;
if (coord.x < 0) coord.x--;
if (coord.z < 0) coord.z--;
int cx = floordiv((int)coord.x, CHUNK_W);
int cz = floordiv((int)coord.z, CHUNK_D);
int cx = floordiv(static_cast<int>(coord.x), CHUNK_W);
int cz = floordiv(static_cast<int>(coord.z), CHUNK_D);
drawBorders(
cx * CHUNK_W, 0, cz * CHUNK_D,
@ -276,8 +284,8 @@ void WorldRenderer::renderDebugLines(
glm::vec3 tsl(displayWidth/2, displayHeight/2, 0.f);
glm::mat4 model(glm::translate(glm::mat4(1.f), tsl));
linesShader->uniformMatrix("u_projview", glm::ortho(
0.f, (float)displayWidth,
0.f, (float)displayHeight,
0.f, static_cast<float>(displayWidth),
0.f, static_cast<float>(displayHeight),
-length, length) * model * glm::inverse(camera->rotation)
);

View File

@ -62,6 +62,13 @@ class WorldRenderer {
Camera* camera,
Shader* linesShader
);
void setupWorldShader(
Shader* shader,
Camera* camera,
const EngineSettings& settings,
float fogFactor
);
public:
static bool showChunkBorders;
static bool showEntitiesDebug;

View File

@ -112,6 +112,22 @@ static int l_set_visible(lua::State* L) {
return 0;
}
static int l_get_color(lua::State* L) {
if (auto entity = get_entity(L, 1)) {
auto& skeleton = entity->getSkeleton();
return lua::pushvec(L, skeleton.tint);
}
return 0;
}
static int l_set_color(lua::State* L) {
if (auto entity = get_entity(L, 1)) {
auto& skeleton = entity->getSkeleton();
skeleton.tint = lua::tovec3(L, 2);
}
return 0;
}
const luaL_Reg skeletonlib [] = {
{"get_model", lua::wrap<l_get_model>},
{"set_model", lua::wrap<l_set_model>},
@ -122,5 +138,7 @@ const luaL_Reg skeletonlib [] = {
{"index", lua::wrap<l_index>},
{"is_visible", lua::wrap<l_is_visible>},
{"set_visible", lua::wrap<l_set_visible>},
{"get_color", lua::wrap<l_get_color>},
{"set_color", lua::wrap<l_set_color>},
{NULL, NULL}
};

View File

@ -99,9 +99,8 @@ void SkeletonConfig::render(
}
model = modelOverride.model ? modelOverride.model : model;
if (model) {
batch.pushMatrix(skeleton.calculated.matrices[i]);
batch.draw(model, &skeleton.textures);
batch.popMatrix();
batch.draw(skeleton.calculated.matrices[i], skeleton.tint, model,
&skeleton.textures);
}
}
}

View File

@ -75,6 +75,7 @@ namespace rigging {
std::unordered_map<std::string, std::string> textures;
std::vector<ModelReference> modelOverrides;
bool visible;
glm::vec3 tint {1.0f, 1.0f, 1.0f};
Skeleton(const SkeletonConfig* config);
};