我正在尝试让网格法线和灯光在 LibGDX 项目中工作。
我已经有了从高度图纹理像素生成的纹理网格。
问题 是我无法正确点亮法线。我也不是 100% 确定我在 TerrainChunk 类中正确设置了普通顶点。
这里是主类代码:
package com.me.terrain;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
public class Terra extends Game {
private PerspectiveCamera camera;
private CameraInputController camController;
private TerrainChunk chunk;
private Mesh mesh;
private ShaderProgram shader;
private Texture terrainTexture;
private final Matrix3 normalMatrix = new Matrix3();
private static final float[] lightPosition = { 5, 35, 5 };
private static final float[] ambientColor = { 0.2f, 0.2f, 0.2f, 1.0f };
private static final float[] diffuseColor = { 0.5f, 0.5f, 0.5f, 1.0f };
private static final float[] specularColor = { 0.7f, 0.7f, 0.7f, 1.0f };
private static final float[] fogColor = { 0.2f, 0.1f, 0.6f, 1.0f };
private Matrix4 model = new Matrix4();
private Matrix4 modelView = new Matrix4();
private final String vertexShader =
"attribute vec4 a_position; \n" +
"attribute vec3 a_normal; \n" +
"attribute vec2 a_texCoord; \n" +
"attribute vec4 a_color; \n" +
"uniform mat4 u_MVPMatrix; \n" +
"uniform mat3 u_normalMatrix; \n" +
"uniform vec3 u_lightPosition; \n" +
"varying float intensity; \n" +
"varying vec2 texCoords; \n" +
"varying vec4 v_color; \n" +
"void main() { \n" +
" vec3 normal = normalize(u_normalMatrix * a_normal); \n" +
" vec3 light = normalize(u_lightPosition); \n" +
" intensity = max( dot(normal, light) , 0.0); \n" +
" v_color = a_color; \n" +
" texCoords = a_texCoord; \n" +
" gl_Position = u_MVPMatrix * a_position; \n" +
"}";
private final String fragmentShader =
"#ifdef GL_ES \n" +
"precision mediump float; \n" +
"#endif \n" +
"uniform vec4 u_ambientColor; \n" +
"uniform vec4 u_diffuseColor; \n" +
"uniform vec4 u_specularColor; \n" +
"uniform sampler2D u_texture; \n" +
"varying vec2 texCoords; \n" +
"varying vec4 v_color; \n" +
"varying float intensity; \n" +
"void main() { \n" +
" gl_FragColor = v_color * intensity * texture2D(u_texture, texCoords); \n" +
"}";
@Override
public void create() {
// Terrain texture size is 128x128
terrainTexture = new Texture(Gdx.files.internal("data/concrete2.png"));
// Height map (black/white) texture size is 32x32
String heightMapFile = "data/heightmap.png";
// position, normal, color, texture
int vertexSize = 3 + 3 + 1 + 2;
chunk = new TerrainChunk(32, 32, vertexSize, heightMapFile);
mesh = new Mesh(true, chunk.vertices.length / 3, chunk.indices.length,
new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE),
new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE),
new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE),
new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE));
mesh.setVertices(chunk.vertices);
mesh.setIndices(chunk.indices);
camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.set(5, 50, 5);
camera.direction.set(3, 0, 0).sub(camera.position).nor();
camera.near = 0.005f;
camera.far = 300;
camera.update();
camController = new CameraInputController(camera);
Gdx.input.setInputProcessor(camController);
ShaderProgram.pedantic = false;
shader = new ShaderProgram(vertexShader, fragmentShader);
}
@Override
public void render() {
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
camController.update();
camera.update();
// This is wrong?
model.setToRotation(new Vector3(0, 1, 0), 45f);
modelView.set(camera.view).mul(model);
terrainTexture.bind();
shader.begin();
shader.setUniformMatrix("u_MVPMatrix", camera.combined);
shader.setUniformMatrix("u_normalMatrix", normalMatrix.set(modelView).inv().transpose());
shader.setUniform3fv("u_lightPosition", lightPosition, 0, 3);
shader.setUniform4fv("u_ambientColor", ambientColor, 0, 4);
shader.setUniform4fv("u_diffuseColor", diffuseColor, 0, 4);
shader.setUniform4fv("u_specularColor", specularColor, 0, 4);
shader.setUniformi("u_texture", 0);
mesh.render(shader, GL20.GL_TRIANGLES);
shader.end();
}
}
TerrainChunk 类代码:
final static class TerrainChunk {
public final float[] heightMap;
public final short width;
public final short height;
public final float[] vertices;
public final short[] indices;
public final int vertexSize;
private final int positionSize = 3;
public TerrainChunk(int width, int height, int vertexSize, String heightMapTexture) {
if ((width + 1) * (height + 1) > Short.MAX_VALUE) {
throw new IllegalArgumentException(
"Chunk size too big, (width + 1)*(height+1) must be <= 32767");
}
this.heightMap = new float[(width + 1) * (height + 1)];
this.width = (short) width;
this.height = (short) height;
this.vertices = new float[heightMap.length * vertexSize];
this.indices = new short[width * height * 6];
this.vertexSize = vertexSize;
buildHeightmap(heightMapTexture);
buildIndices();
buildVertices();
calcNormals(indices, vertices);
}
public void buildHeightmap(String pathToHeightMap) {
FileHandle handle = Gdx.files.internal(pathToHeightMap);
Pixmap heightmapImage = new Pixmap(handle);
Color color = new Color();
int idh = 0;
for (int x = 0; x < this.width + 1; x++) {
for (int y = 0; y < this.height + 1; y++) {
Color.rgba8888ToColor(color, heightmapImage.getPixel(x, y));
this.heightMap[idh++] = color.r;
}
}
}
public void buildVertices() {
int heightPitch = height + 1;
int widthPitch = width + 1;
int idx = 0;
int hIdx = 0;
int strength = 10; // multiplier for height map
float scale = 4f;
for (int z = 0; z < heightPitch; z++) {
for (int x = 0; x < widthPitch; x++) {
// POSITION
vertices[idx++] = scale * x;
vertices[idx++] = heightMap[hIdx++] * strength;
vertices[idx++] = scale * z;
// NORMAL, skip these for now
idx += 3;
// COLOR
vertices[idx++] = Color.WHITE.toFloatBits();
// TEXTURE
vertices[idx++] = (x / (float) width);
vertices[idx++] = (z / (float) height);
}
}
}
private void buildIndices() {
int idx = 0;
short pitch = (short) (width + 1);
short i1 = 0;
short i2 = 1;
short i3 = (short) (1 + pitch);
short i4 = pitch;
short row = 0;
for (int z = 0; z < height; z++) {
for (int x = 0; x < width; x++) {
indices[idx++] = i1;
indices[idx++] = i2;
indices[idx++] = i3;
indices[idx++] = i3;
indices[idx++] = i4;
indices[idx++] = i1;
i1++;
i2++;
i3++;
i4++;
}
row += pitch;
i1 = row;
i2 = (short) (row + 1);
i3 = (short) (i2 + pitch);
i4 = (short) (row + pitch);
}
}
// Gets the index of the first float of a normal for a specific vertex
private int getNormalStart(int vertIndex) {
return vertIndex * vertexSize + positionSize;
}
// Gets the index of the first float of a specific vertex
private int getPositionStart(int vertIndex) {
return vertIndex * vertexSize;
}
// Adds the provided value to the normal
private void addNormal(int vertIndex, float[] verts, float x, float y, float z) {
int i = getNormalStart(vertIndex);
verts[i] += x;
verts[i + 1] += y;
verts[i + 2] += z;
}
/*
* Normalizes normals
*/
private void normalizeNormal(int vertIndex, float[] verts) {
int i = getNormalStart(vertIndex);
float x = verts[i];
float y = verts[i + 1];
float z = verts[i + 2];
float num2 = ((x * x) + (y * y)) + (z * z);
float num = 1f / (float) Math.sqrt(num2);
x *= num;
y *= num;
z *= num;
verts[i] = x;
verts[i + 1] = y;
verts[i + 2] = z;
}
/*
* Calculates the normals
*/
private void calcNormals(short[] indices, float[] verts) {
for (int i = 0; i < indices.length; i += 3) {
int i1 = getPositionStart(indices[i]);
int i2 = getPositionStart(indices[i + 1]);
int i3 = getPositionStart(indices[i + 2]);
// p1
float x1 = verts[i1];
float y1 = verts[i1 + 1];
float z1 = verts[i1 + 2];
// p2
float x2 = verts[i2];
float y2 = verts[i2 + 1];
float z2 = verts[i2 + 2];
// p3
float x3 = verts[i3];
float y3 = verts[i3 + 1];
float z3 = verts[i3 + 2];
// u = p3 - p1
float ux = x3 - x1;
float uy = y3 - y1;
float uz = z3 - z1;
// v = p2 - p1
float vx = x2 - x1;
float vy = y2 - y1;
float vz = z2 - z1;
// n = cross(v, u)
float nx = (vy * uz) - (vz * uy);
float ny = (vz * ux) - (vx * uz);
float nz = (vx * uy) - (vy * ux);
// normalize(n)
float num2 = ((nx * nx) + (ny * ny)) + (nz * nz);
float num = 1f / (float) Math.sqrt(num2);
nx *= num;
ny *= num;
nz *= num;
addNormal(indices[i], verts, nx, ny, nz);
addNormal(indices[i + 1], verts, nx, ny, nz);
addNormal(indices[i + 2], verts, nx, ny, nz);
}
for (int i = 0; i < (verts.length / vertexSize); i++) {
normalizeNormal(i, verts);
}
}
}
我看到的是,当我移动相机时,当我在地形上方时,灯光无法正确显示。 当我在地形下时,它们会显示更多,但我认为即使那样也不正确。
图片:
最佳答案
通过使用 MeshPartBuilder/GL_LINES 调试和绘制所有正常位置解决了该问题。
我发现法线指向地形内部。改变法线方向是解决方案。
关于java - LibGDX 网格高度图法线和灯光,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337797/
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/
HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候
遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg
我基本上来自Java背景并且努力理解Ruby中的模运算。(5%3)(-5%3)(5%-3)(-5%-3)Java中的上述操作产生,2个-22个-2但在Ruby中,相同的表达式会产生21个-1-2.Ruby在逻辑上有多擅长这个?模块操作在Ruby中是如何实现的?如果将同一个操作定义为一个web服务,两个服务如何匹配逻辑。 最佳答案 在Java中,模运算的结果与被除数的符号相同。在Ruby中,它与除数的符号相同。remainder()在Ruby中与被除数的符号相同。您可能还想引用modulooperation.
Java的Collections.unmodifiableList和Collections.unmodifiableMap在Ruby标准API中是否有等价物? 最佳答案 使用freeze应用程序接口(interface):Preventsfurthermodificationstoobj.ARuntimeErrorwillberaisedifmodificationisattempted.Thereisnowaytounfreezeafrozenobject.SeealsoObject#frozen?.Thismethodretur
在Java中,可以像这样从一个字符串创建一个IO流:Readerr=newStringReader("mytext");我希望能够在Ruby中做同样的事情,这样我就可以获取一个字符串并将其视为一个IO流。 最佳答案 r=StringIO.new("mytext")和here'sthedocumentation. 关于java-Java的StringReader的Ruby等价物是什么?,我们在StackOverflow上找到一个类似的问题: https://st