You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX 3D模型渲染异常求助:受光面始终显示错误,模型面无法正常渲染

JavaFX 3D模型渲染异常求助:受光面始终显示错误,模型面无法正常渲染

各位好,我正在开发一个简易的3D模型查看/编辑器应用,但现在渲染器出了个离谱的bug——不管怎么旋转模型,受光面总是固定显示在顶部区域,背光面则一直在背面,完全不符合光源的实际位置。

我已经仔细检查过模型的法线,确认没有翻转,但还是找不到问题出在哪。我不确定bug是不是出在渲染方法里,所以如果需要排查的话可以用完整的项目代码。现在实在摸不准问题根源,希望能得到大家的帮助,让模型能正常根据光源计算面的明暗。

具体bug表现

  • 旋转模型时,各个面的受光/背光状态完全固定,不会跟着光源位置或者视角变化
  • 实际应该被光源照亮的面没正确变亮,反而原本该背光的面一直显示为受光状态
  • 操作模型的全程,面的明暗都没有正确更新,呈现出完全错误的固定受光效果

我用到的光照渲染代码

下面是负责计算光照并渲染的核心方法:

private static void renderLighting(GraphicsContext graphicsContext, List<Point2f> resultPoints, List<Vector3f> worldVertices, Model mesh) {
    // Improved diffuse lighting with soft shadow calculation
    Vector3f lightPosition = new Vector3f(10, 10, 10); // Example light position
    Color lightColor = Color.WHITE;
    Color objectColor = Color.LIGHTGRAY;

    Vector3f polygonNormal = calculatePolygonNormal(worldVertices);

    Vector3f lightDirection = new Vector3f(
            lightPosition.x - worldVertices.get(0).x,
            lightPosition.y - worldVertices.get(0).y,
            lightPosition.z - worldVertices.get(0).z
    );
    lightDirection.normalize();

    float diffuseIntensity = Math.max(0, polygonNormal.dotProduct(lightDirection));

    // Adding soft shadow effect
    float shadowFactor = calculateSoftShadowFactor(worldVertices, lightPosition);
    diffuseIntensity *= shadowFactor;

    double red = objectColor.getRed() * (lightColor.getRed() * diffuseIntensity);
    double green = objectColor.getGreen() * (lightColor.getGreen() * diffuseIntensity);
    double blue = objectColor.getBlue() * (lightColor.getBlue() * diffuseIntensity);

    graphicsContext.setFill(Color.color(clamp(red), clamp(green), clamp(blue)));

    double[] xPoints = resultPoints.stream().mapToDouble(p -> p.x).toArray();
    double[] yPoints = resultPoints.stream().mapToDouble(p -> p.y).toArray();

    graphicsContext.fillPolygon(xPoints, yPoints, resultPoints.size());
}

备注:内容来源于stack exchange,提问作者Levon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:24:29