From d95e17b980bd8ee113cfe9ab8604bf0443b75e91 Mon Sep 17 00:00:00 2001 From: Richard Tingle <6330028+richardTingle@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:59:30 +0000 Subject: [PATCH 1/5] Support rotating light probes after they are baked --- .../main/java/com/jme3/light/LightProbe.java | 61 ++++++ .../SinglePassAndImageBasedLightingLogic.java | 16 +- .../com/jme3/scene/control/LightControl.java | 30 ++- .../resources/Common/ShaderLib/PBR.glsllib | 16 +- .../pbrlighting/PBRLightingUtils.glsllib | 7 +- .../jme3/light/LightProbeRotationTest.java | 198 ++++++++++++++++++ 6 files changed, 317 insertions(+), 11 deletions(-) create mode 100644 jme3-core/src/test/java/com/jme3/light/LightProbeRotationTest.java diff --git a/jme3-core/src/main/java/com/jme3/light/LightProbe.java b/jme3-core/src/main/java/com/jme3/light/LightProbe.java index 7ab654f352..3045eca972 100644 --- a/jme3-core/src/main/java/com/jme3/light/LightProbe.java +++ b/jme3-core/src/main/java/com/jme3/light/LightProbe.java @@ -60,6 +60,11 @@ *
* The light probe has an area of effect centered on its position. It can have a Spherical area or an Oriented Box area *
+ * A light probe also has a rotation in world space: the orientation of its captured environment. Rotating a probe + * turns the lighting and reflections it gives, which is useful when the environment the probe was captured from is + * itself rotated (for example a probe captured from a sky that is later turned). Like the position, it can be kept in + * step with a spatial using a {@link com.jme3.scene.control.LightControl}. + *
* A LightProbe will only be taken into account when it's marked as ready and enabled. * A light probe is ready when it has valid environment map data set. * Note that you should never call setReady yourself. @@ -79,6 +84,8 @@ public class LightProbe extends Light implements Savable { private ProbeArea area = new SphereProbeArea(Vector3f.ZERO, 1.0f); private boolean ready = false; private Vector3f position = new Vector3f(); + private Quaternion rotation = new Quaternion(); + private Matrix3f rotationMatrix = new Matrix3f(); private int nbMipMaps; public enum AreaType{ @@ -163,6 +170,7 @@ public void write(JmeExporter ex) throws IOException { oc.write(shCoefficients, "shCoeffs", null); oc.write(prefilteredEnvMap, "prefilteredEnvMap", null); oc.write(position, "position", null); + oc.write(rotation, "rotation", Quaternion.IDENTITY); oc.write(area, "area", new SphereProbeArea(Vector3f.ZERO, 1.0f)); oc.write(ready, "ready", false); oc.write(nbMipMaps, "nbMipMaps", 0); @@ -182,6 +190,8 @@ public void read(JmeImporter im) throws IOException { area = new SphereProbeArea(bounds.getCenter(), bounds.getRadius()); } area.setCenter(position); + rotation = (Quaternion) ic.readSavable("rotation", new Quaternion()); + rotation.toRotationMatrix(rotationMatrix); nbMipMaps = ic.readInt("nbMipMaps", 0); ready = ic.readBoolean("ready", false); @@ -218,6 +228,7 @@ public void setAreaType(AreaType type){ break; case OrientedBox: area = new OrientedBoxProbeArea(new Transform()); + ((OrientedBoxProbeArea) area).setRotation(rotation); break; } area.setCenter(position); @@ -274,6 +285,47 @@ public void setPosition(Vector3f position) { area.setCenter(position); } + /** + * Returns the rotation of the LightProbe in world space: the orientation of its captured environment. + * + * @return the world-space rotation (not a copy, do not modify) + */ + public Quaternion getRotation() { + return rotation; + } + + /** + * Sets the rotation of the LightProbe in world space. This turns the environment the probe lights with (both its + * irradiance and its prefiltered reflections). The probe is treated as a rigid whole, so an oriented box area is + * turned by the same change in rotation, just as {@link #setPosition(Vector3f)} moves the area. The box keeps any + * rotation it already had (for example a box aligned with the walls of a room that was not built on the world + * axes); the box's own rotation remains world space. + *
+ * Probes are captured in world axes, so a newly captured probe has the identity rotation. + * + * @param rotation the world-space rotation (not null, unaffected) + */ + public void setRotation(Quaternion rotation) { + if (area instanceof OrientedBoxProbeArea) { + OrientedBoxProbeArea box = (OrientedBoxProbeArea) area; + // carry the box through the same rigid turn (new * inverse(old)), keeping any rotation it already had + Quaternion boxRotation = rotation.mult(this.rotation.inverse()).multLocal(box.getRotation()).normalizeLocal(); + box.setRotation(boxRotation); + } + this.rotation.set(rotation); + this.rotation.toRotationMatrix(rotationMatrix); + } + + /** + * Returns the rotation to send to the shader, as a matrix taking directions from the probe's captured + * environment into world space. + * + * @return the pre-existing matrix + */ + public Matrix3f getUniformRotationMatrix() { + return rotationMatrix; + } + public int getNbMipMaps() { return nbMipMaps; } @@ -312,11 +364,20 @@ public Type getType() { return Type.Probe; } + @Override + public LightProbe clone() { + LightProbe probe = (LightProbe) super.clone(); + probe.rotation = rotation.clone(); + probe.rotationMatrix = rotationMatrix.clone(); + return probe; + } + @Override public String toString() { return getClass().getSimpleName() + "[name=" + name + ", position=" + position + + ", rotation=" + rotation + ", area=" + area + ", enabled=" + enabled + "]"; diff --git a/jme3-core/src/main/java/com/jme3/material/logic/SinglePassAndImageBasedLightingLogic.java b/jme3-core/src/main/java/com/jme3/material/logic/SinglePassAndImageBasedLightingLogic.java index df7243e611..61044bcc95 100644 --- a/jme3-core/src/main/java/com/jme3/material/logic/SinglePassAndImageBasedLightingLogic.java +++ b/jme3-core/src/main/java/com/jme3/material/logic/SinglePassAndImageBasedLightingLogic.java @@ -133,6 +133,11 @@ protected int updateLightListUniforms(Shader shader, Geometry g, LightList light Uniform lightProbeData2 = shader.getUniform("g_LightProbeData2"); Uniform lightProbeData3 = shader.getUniform("g_LightProbeData3"); + // Matrix3f + Uniform lightProbeRotation = shader.getUniform("g_LightProbeRotation"); + Uniform lightProbeRotation2 = shader.getUniform("g_LightProbeRotation2"); + Uniform lightProbeRotation3 = shader.getUniform("g_LightProbeRotation3"); + Uniform shCoeffs = shader.getUniform("g_ShCoeffs"); Uniform lightProbePemMap = shader.getUniform("g_PrefEnvMap"); Uniform shCoeffs2 = shader.getUniform("g_ShCoeffs2"); @@ -153,14 +158,14 @@ protected int updateLightListUniforms(Shader shader, Geometry g, LightList light //If there is a lightProbe in the list we force its render on the first pass if (!lightProbes.isEmpty()) { LightProbe lightProbe = lightProbes.get(0); - lastTexUnit = setProbeData(rm, lastTexUnit, lightProbeData, shCoeffs, lightProbePemMap, lightProbe); + lastTexUnit = setProbeData(rm, lastTexUnit, lightProbeData, lightProbeRotation, shCoeffs, lightProbePemMap, lightProbe); if (lightProbes.size() > 1) { lightProbe = lightProbes.get(1); - lastTexUnit = setProbeData(rm, lastTexUnit, lightProbeData2, shCoeffs2, lightProbePemMap2, lightProbe); + lastTexUnit = setProbeData(rm, lastTexUnit, lightProbeData2, lightProbeRotation2, shCoeffs2, lightProbePemMap2, lightProbe); } if (lightProbes.size() > 2) { lightProbe = lightProbes.get(2); - setProbeData(rm, lastTexUnit, lightProbeData3, shCoeffs3, lightProbePemMap3, lightProbe); + setProbeData(rm, lastTexUnit, lightProbeData3, lightProbeRotation3, shCoeffs3, lightProbePemMap3, lightProbe); } } else { //Disable IBL for this pass @@ -244,9 +249,10 @@ protected int updateLightListUniforms(Shader shader, Geometry g, LightList light return curIndex; } - private int setProbeData(RenderManager rm, int lastTexUnit, Uniform lightProbeData, Uniform shCoeffs, - Uniform lightProbePemMap, LightProbe lightProbe) { + private int setProbeData(RenderManager rm, int lastTexUnit, Uniform lightProbeData, Uniform lightProbeRotation, + Uniform shCoeffs, Uniform lightProbePemMap, LightProbe lightProbe) { lightProbeData.setValue(VarType.Matrix4, lightProbe.getUniformMatrix()); + lightProbeRotation.setValue(VarType.Matrix3, lightProbe.getUniformRotationMatrix()); //setVector4InArray(lightProbe.getPosition().x, lightProbe.getPosition().y, lightProbe.getPosition().z, 1f / area.getRadius() + lightProbe.getNbMipMaps(), 0); shCoeffs.setValue(VarType.Vector3Array, lightProbe.getShCoeffs()); /* diff --git a/jme3-core/src/main/java/com/jme3/scene/control/LightControl.java b/jme3-core/src/main/java/com/jme3/scene/control/LightControl.java index 3c0619b912..d424c3c1e3 100644 --- a/jme3-core/src/main/java/com/jme3/scene/control/LightControl.java +++ b/jme3-core/src/main/java/com/jme3/scene/control/LightControl.java @@ -37,6 +37,7 @@ import com.jme3.export.OutputCapsule; import com.jme3.light.DirectionalLight; import com.jme3.light.Light; +import com.jme3.light.LightProbe; import com.jme3.light.PointLight; import com.jme3.light.SpotLight; import com.jme3.math.Quaternion; @@ -57,6 +58,10 @@ * This is particularly useful for attaching lights to animated characters, * moving vehicles, or dynamically controlled objects. *
+ *+ * A {@link LightProbe} is synchronized with the spatial's full rotation, not a + * single direction, so the axis settings do not apply to it. + *
* * @author Tim * @author Markil 3 @@ -103,7 +108,7 @@ public LightControl() { * * @param light The light to be synced. * @throws IllegalArgumentException if the light type is not supported - * (only Point, Directional, and Spot lights are supported). + * (only Point, Directional, Spot and Probe lights are supported). */ public LightControl(Light light) { validateSupportedLightType(light); @@ -116,7 +121,7 @@ public LightControl(Light light) { * @param light The light to be synced. * @param controlDir The direction of synchronization (SpatialToLight or LightToSpatial). * @throws IllegalArgumentException if the light type is not supported - * (only Point, Directional, and Spot lights are supported). + * (only Point, Directional, Spot and Probe lights are supported). */ public LightControl(Light light, ControlDirection controlDir) { validateSupportedLightType(light); @@ -166,6 +171,7 @@ private void validateSupportedLightType(Light light) { case Point: case Directional: case Spot: + case Probe: // These types are supported, validation passes. break; default: @@ -218,6 +224,11 @@ private void spatialToLight(Light light) { SpotLight sl = (SpotLight) light; sl.setPosition(worldPosition); sl.setDirection(lightDirection); + + } else if (light instanceof LightProbe) { + LightProbe probe = (LightProbe) light; + probe.setPosition(worldPosition); + probe.setRotation(spatial.getWorldRotation()); } vars.release(); } @@ -234,6 +245,7 @@ private void lightToSpatial(Light light) { Vector3f lightDirection = vars.vect2; Quaternion rotation = vars.quat1; boolean rotateSpatial = false; + boolean orientSpatial = false; boolean translateSpatial = false; if (light instanceof PointLight) { @@ -258,6 +270,13 @@ private void lightToSpatial(Light light) { } translateSpatial = true; rotateSpatial = true; + + } else if (light instanceof LightProbe) { + LightProbe probe = (LightProbe) light; + lightPosition.set(probe.getPosition()); + rotation.set(probe.getRotation()); + translateSpatial = true; + orientSpatial = true; } // Transform light's world properties to spatial's parent's local space @@ -267,6 +286,10 @@ private void lightToSpatial(Light light) { vars.tempMat4.rotateVect(lightPosition); vars.tempMat4.translateVect(lightPosition); vars.tempMat4.rotateVect(lightDirection); + if (orientSpatial) { + Quaternion parentRotation = vars.quat2.set(spatial.getParent().getWorldRotation()); + rotation.set(parentRotation.inverseLocal().multLocal(rotation)); + } } // Apply transformed properties to spatial's local transformation @@ -274,6 +297,9 @@ private void lightToSpatial(Light light) { rotation.lookAt(lightDirection, Vector3f.UNIT_Y).normalizeLocal(); spatial.setLocalRotation(rotation); } + if (orientSpatial) { + spatial.setLocalRotation(rotation); + } if (translateSpatial) { spatial.setLocalTranslation(lightPosition); } diff --git a/jme3-core/src/main/resources/Common/ShaderLib/PBR.glsllib b/jme3-core/src/main/resources/Common/ShaderLib/PBR.glsllib index 34e516c7f7..af2bd58230 100644 --- a/jme3-core/src/main/resources/Common/ShaderLib/PBR.glsllib +++ b/jme3-core/src/main/resources/Common/ShaderLib/PBR.glsllib @@ -197,7 +197,8 @@ vec3 ApproximateSpecularIBLPolynomial(samplerCube envMap, vec3 SpecularColor , f } -float renderProbe(vec3 viewDir, vec3 worldPos, vec3 normal, vec3 norm, float Roughness, vec4 diffuseColor, vec4 specularColor, float ndotv, vec3 ao, mat4 lightProbeData,vec3 shCoeffs[9],samplerCube prefEnvMap, inout vec3 color ){ +// lightProbeRotation takes directions from the probe's captured environment into world space (see LightProbe.setRotation) +float renderProbe(vec3 viewDir, vec3 worldPos, vec3 normal, vec3 norm, float Roughness, vec4 diffuseColor, vec4 specularColor, float ndotv, vec3 ao, mat4 lightProbeData, mat3 lightProbeRotation, vec3 shCoeffs[9],samplerCube prefEnvMap, inout vec3 color ){ // lightProbeData is a mat4 with this layout // 3x3 rot mat| @@ -263,10 +264,14 @@ float renderProbe(vec3 viewDir, vec3 worldPos, vec3 normal, vec3 norm, float Rou #endif } + // into the probe's environment space; for a rotation the transpose is the inverse, and v * M multiplies by it + vec3 probeNormal = normal * lightProbeRotation; + vec3 probeRv = rv * lightProbeRotation; + vec3 indirectDiffuse = vec3(0.0); vec3 indirectSpecular = vec3(0.0); - indirectDiffuse = sphericalHarmonics(normal.xyz, shCoeffs) * diffuseColor.rgb; - vec3 dominantR = getSpecularDominantDir( normal, rv.xyz, Roughness * Roughness ); + indirectDiffuse = sphericalHarmonics(probeNormal, shCoeffs) * diffuseColor.rgb; + vec3 dominantR = getSpecularDominantDir( probeNormal, probeRv, Roughness * Roughness ); indirectSpecular = ApproximateSpecularIBLPolynomial(prefEnvMap, specularColor.rgb, Roughness, ndotv, dominantR, nbMipMaps); #ifdef HORIZON_FADE @@ -285,3 +290,8 @@ float renderProbe(vec3 viewDir, vec3 worldPos, vec3 normal, vec3 norm, float Rou color = indirectLighting * step( 0.0, probePos.w); return ndf; } + +// for shaders written before probes could be rotated +float renderProbe(vec3 viewDir, vec3 worldPos, vec3 normal, vec3 norm, float Roughness, vec4 diffuseColor, vec4 specularColor, float ndotv, vec3 ao, mat4 lightProbeData,vec3 shCoeffs[9],samplerCube prefEnvMap, inout vec3 color ){ + return renderProbe(viewDir, worldPos, normal, norm, Roughness, diffuseColor, specularColor, ndotv, ao, lightProbeData, mat3(1.0), shCoeffs, prefEnvMap, color); +} diff --git a/jme3-core/src/main/resources/Common/ShaderLib/module/pbrlighting/PBRLightingUtils.glsllib b/jme3-core/src/main/resources/Common/ShaderLib/module/pbrlighting/PBRLightingUtils.glsllib index 8962c9a9e5..e6d00e4a88 100644 --- a/jme3-core/src/main/resources/Common/ShaderLib/module/pbrlighting/PBRLightingUtils.glsllib +++ b/jme3-core/src/main/resources/Common/ShaderLib/module/pbrlighting/PBRLightingUtils.glsllib @@ -173,16 +173,19 @@ uniform samplerCube g_PrefEnvMap; uniform vec3 g_ShCoeffs[9]; uniform mat4 g_LightProbeData; + uniform mat3 g_LightProbeRotation; #endif #if NB_PROBES >= 2 uniform samplerCube g_PrefEnvMap2; uniform vec3 g_ShCoeffs2[9]; uniform mat4 g_LightProbeData2; + uniform mat3 g_LightProbeRotation2; #endif #if NB_PROBES == 3 uniform samplerCube g_PrefEnvMap3; uniform vec3 g_ShCoeffs3[9]; uniform mat4 g_LightProbeData3; + uniform mat3 g_LightProbeRotation3; #endif #endif @@ -660,7 +663,7 @@ vec4(surface.specularColor, 1.0), surface.NdotV, surface.ao, - g_LightProbeData, g_ShCoeffs, g_PrefEnvMap, color1); + g_LightProbeData, g_LightProbeRotation, g_ShCoeffs, g_PrefEnvMap, color1); #if NB_PROBES >= 2 float ndf2 = renderProbe( surface.viewDir, @@ -673,6 +676,7 @@ surface.NdotV, surface.ao, g_LightProbeData2, + g_LightProbeRotation2, g_ShCoeffs2, g_PrefEnvMap2, color2); @@ -689,6 +693,7 @@ surface.NdotV, surface.ao, g_LightProbeData3, + g_LightProbeRotation3, g_ShCoeffs3, g_PrefEnvMap3, color3); diff --git a/jme3-core/src/test/java/com/jme3/light/LightProbeRotationTest.java b/jme3-core/src/test/java/com/jme3/light/LightProbeRotationTest.java new file mode 100644 index 0000000000..6f6947cb22 --- /dev/null +++ b/jme3-core/src/test/java/com/jme3/light/LightProbeRotationTest.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2009-2026 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.jme3.light; + +import com.jme3.asset.AssetManager; +import com.jme3.asset.DesktopAssetManager; +import com.jme3.export.binary.BinaryExporter; +import com.jme3.math.FastMath; +import com.jme3.math.Matrix3f; +import com.jme3.math.Quaternion; +import com.jme3.math.Vector3f; +import com.jme3.scene.Node; +import com.jme3.scene.control.LightControl; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * Tests the world-space rotation of a {@link LightProbe} and its synchronization through {@link LightControl}. + */ +public class LightProbeRotationTest { + + private static final float DELTA = 1e-5f; + + @Test + public void newProbeIsUnrotated() { + LightProbe probe = new LightProbe(); + + assertRotationsEqual(Quaternion.IDENTITY, probe.getRotation()); + Assertions.assertEquals(Matrix3f.IDENTITY, probe.getUniformRotationMatrix()); + } + + @Test + public void setRotationUpdatesUniformMatrix() { + LightProbe probe = new LightProbe(); + Quaternion rotation = new Quaternion().fromAngleAxis(FastMath.HALF_PI, Vector3f.UNIT_Y); + + probe.setRotation(rotation); + + Vector3f probeX = probe.getUniformRotationMatrix().mult(Vector3f.UNIT_X); + assertVectorsEqual(rotation.mult(Vector3f.UNIT_X), probeX); + } + + @Test + public void setRotationDoesNotAffectSphericalArea() { + LightProbe probe = new LightProbe(); + Matrix3f areaRotation = new Matrix3f(); + + probe.setRotation(new Quaternion().fromAngleAxis(1f, Vector3f.UNIT_Y)); + + probe.getUniformMatrix().toRotationMatrix(areaRotation); + Assertions.assertEquals(Matrix3f.IDENTITY, areaRotation); + } + + @Test + public void setRotationTurnsOrientedBoxArea() { + Quaternion rotation = new Quaternion().fromAngleAxis(1f, Vector3f.UNIT_Y); + + LightProbe rotatedThenBoxed = new LightProbe(); + rotatedThenBoxed.setRotation(rotation); + rotatedThenBoxed.setAreaType(LightProbe.AreaType.OrientedBox); + + LightProbe boxedThenRotated = new LightProbe(); + boxedThenRotated.setAreaType(LightProbe.AreaType.OrientedBox); + boxedThenRotated.setRotation(rotation); + + assertRotationsEqual(rotation, ((OrientedBoxProbeArea) rotatedThenBoxed.getArea()).getRotation()); + assertRotationsEqual(rotation, ((OrientedBoxProbeArea) boxedThenRotated.getArea()).getRotation()); + } + + @Test + public void setRotationKeepsBoxRotationFromSetup() { + LightProbe probe = new LightProbe(); + probe.setAreaType(LightProbe.AreaType.OrientedBox); + OrientedBoxProbeArea box = (OrientedBoxProbeArea) probe.getArea(); + box.setRotation(yRotation(30)); + + probe.setRotation(yRotation(10)); + assertRotationsEqual(yRotation(40), box.getRotation()); + + probe.setRotation(yRotation(25)); + assertRotationsEqual(yRotation(55), box.getRotation()); + + probe.setRotation(Quaternion.IDENTITY); + assertRotationsEqual(yRotation(30), box.getRotation()); + } + + @Test + public void cloneHasIndependentRotation() { + LightProbe probe = new LightProbe(); + probe.setRotation(new Quaternion().fromAngleAxis(1f, Vector3f.UNIT_Y)); + + LightProbe clone = probe.clone(); + clone.setRotation(new Quaternion().fromAngleAxis(2f, Vector3f.UNIT_Y)); + + assertRotationsEqual(new Quaternion().fromAngleAxis(1f, Vector3f.UNIT_Y), probe.getRotation()); + assertVectorsEqual(probe.getRotation().mult(Vector3f.UNIT_X), probe.getUniformRotationMatrix().mult(Vector3f.UNIT_X)); + } + + @Test + public void rotationSurvivesSaveAndLoad() { + AssetManager assetManager = new DesktopAssetManager(true); + LightProbe probe = new LightProbe(); + Quaternion rotation = new Quaternion().fromAngleAxis(0.7f, Vector3f.UNIT_Y); + probe.setRotation(rotation); + + LightProbe loaded = BinaryExporter.saveAndLoad(assetManager, probe); + + assertRotationsEqual(rotation, loaded.getRotation()); + assertVectorsEqual(rotation.mult(Vector3f.UNIT_X), loaded.getUniformRotationMatrix().mult(Vector3f.UNIT_X)); + } + + @Test + public void lightControlCopiesSpatialTransformToProbe() { + Node parent = new Node("parent"); + parent.setLocalTranslation(5, 0, 0); + parent.setLocalRotation(new Quaternion().fromAngleAxis(FastMath.HALF_PI, Vector3f.UNIT_Y)); + Node child = new Node("child"); + child.setLocalTranslation(0, 0, 2); + child.setLocalRotation(new Quaternion().fromAngleAxis(0.3f, Vector3f.UNIT_X)); + parent.attachChild(child); + parent.updateGeometricState(); + + LightProbe probe = new LightProbe(); + child.addControl(new LightControl(probe)); + child.getControl(LightControl.class).update(0); + + assertVectorsEqual(child.getWorldTranslation(), probe.getPosition()); + assertRotationsEqual(child.getWorldRotation(), probe.getRotation()); + } + + @Test + public void lightControlCopiesProbeTransformToSpatial() { + Node parent = new Node("parent"); + parent.setLocalTranslation(5, 0, 0); + parent.setLocalRotation(new Quaternion().fromAngleAxis(FastMath.HALF_PI, Vector3f.UNIT_Y)); + Node child = new Node("child"); + parent.attachChild(child); + parent.updateGeometricState(); + + LightProbe probe = new LightProbe(); + probe.setPosition(new Vector3f(1, 2, 3)); + Quaternion probeRotation = new Quaternion().fromAngleAxis(0.4f, Vector3f.UNIT_Z); + probe.setRotation(probeRotation); + child.addControl(new LightControl(probe, LightControl.ControlDirection.LightToSpatial)); + child.getControl(LightControl.class).update(0); + parent.updateGeometricState(); + + assertVectorsEqual(probe.getPosition(), child.getWorldTranslation()); + assertRotationsEqual(probeRotation, child.getWorldRotation()); + } + + private static Quaternion yRotation(float degrees) { + return new Quaternion().fromAngleAxis(degrees * FastMath.DEG_TO_RAD, Vector3f.UNIT_Y); + } + + private static void assertVectorsEqual(Vector3f expected, Vector3f actual) { + Assertions.assertEquals(expected.x, actual.x, DELTA); + Assertions.assertEquals(expected.y, actual.y, DELTA); + Assertions.assertEquals(expected.z, actual.z, DELTA); + } + + /** + * Compares orientations by what they do to the axes, so a quaternion and its negation count as equal. + */ + private static void assertRotationsEqual(Quaternion expected, Quaternion actual) { + assertVectorsEqual(expected.mult(Vector3f.UNIT_X), actual.mult(Vector3f.UNIT_X)); + assertVectorsEqual(expected.mult(Vector3f.UNIT_Y), actual.mult(Vector3f.UNIT_Y)); + } +} From c97d0660b31f5e541c7ab3f0dd927f2d1f9c5f7b Mon Sep 17 00:00:00 2001 From: Richard Tingle <6330028+richardTingle@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:01:41 +0000 Subject: [PATCH 2/5] Fix bug where rebaking a rotated light probe broke it --- .../jme3/environment/EnvironmentCamera.java | 35 ++- .../environment/EnvironmentProbeControl.java | 2 +- .../jme3/environment/LightProbeFactory.java | 4 +- .../com/jme3/environment/baker/EnvBaker.java | 15 ++ .../environment/baker/GenericEnvBaker.java | 17 +- .../main/java/com/jme3/light/LightProbe.java | 3 +- .../light/pbr/TestLightProbeRotation.java | 58 +++++ .../light/pbr/ScenarioLightProbeRotation.java | 221 ++++++++++++++++++ 8 files changed, 349 insertions(+), 6 deletions(-) create mode 100644 jme3-screenshot-tests/jme3-screenshot-tests-desktop/src/test/java/org/jmonkeyengine/screenshottests/light/pbr/TestLightProbeRotation.java create mode 100644 jme3-screenshot-tests/jme3-screenshot-tests-shared/src/main/java/org/jmonkeyengine/screenshottests/scenarios/light/pbr/ScenarioLightProbeRotation.java diff --git a/jme3-core/src/main/java/com/jme3/environment/EnvironmentCamera.java b/jme3-core/src/main/java/com/jme3/environment/EnvironmentCamera.java index 10c42df8da..c07c0489fb 100644 --- a/jme3-core/src/main/java/com/jme3/environment/EnvironmentCamera.java +++ b/jme3-core/src/main/java/com/jme3/environment/EnvironmentCamera.java @@ -37,6 +37,7 @@ import com.jme3.environment.util.EnvMapUtils; import com.jme3.light.LightProbe; import com.jme3.math.ColorRGBA; +import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.renderer.*; import com.jme3.scene.Spatial; @@ -104,6 +105,7 @@ public class EnvironmentCamera extends BaseAppState { protected ByteBuffer[] buffers; protected Vector3f position = new Vector3f(); + protected Quaternion rotation = new Quaternion(); protected ColorRGBA backGroundColor; /** @@ -270,6 +272,37 @@ public void setPosition(final Vector3f position) { } } + /** + * Returns the orientation of the captured cubemap in world space. + * + * @return the rotation (not a copy, do not modify) + */ + public Quaternion getRotation() { + return rotation; + } + + /** + * Sets the orientation of the captured cubemap in world space, so the snapshot suits a {@link LightProbe} with + * that rotation. + * + * @param rotation the world-space rotation (not null, unaffected) + */ + public void setRotation(final Quaternion rotation) { + this.rotation.set(rotation); + + if (viewports == null) { + return; + } + + for (int i = 0; i < viewports.length; i++) { + viewports[i].getCamera().setRotation(faceRotation(axisX[i], axisY[i], axisZ[i])); + } + } + + private Quaternion faceRotation(Vector3f axisX, Vector3f axisY, Vector3f axisZ) { + return rotation.mult(new Quaternion().fromAxes(axisX, axisY, axisZ)); + } + /** * Returns an array of the 6 ViewPorts used to capture the snapshot. * Note that this will be null until after initialize() is called. @@ -373,7 +406,7 @@ protected Camera createOffCamera(final int mapSize, final Vector3f worldPos, final Vector3f axisX, final Vector3f axisY, final Vector3f axisZ) { final Camera offCamera = new Camera(mapSize, mapSize); offCamera.setLocation(worldPos); - offCamera.setAxes(axisX, axisY, axisZ); + offCamera.setRotation(faceRotation(axisX, axisY, axisZ)); offCamera.setFrustumPerspective(90f, 1f, 0.1f, 1000); offCamera.setLocation(position); return offCamera; diff --git a/jme3-core/src/main/java/com/jme3/environment/EnvironmentProbeControl.java b/jme3-core/src/main/java/com/jme3/environment/EnvironmentProbeControl.java index 655456b16e..4e35e57eb1 100644 --- a/jme3-core/src/main/java/com/jme3/environment/EnvironmentProbeControl.java +++ b/jme3-core/src/main/java/com/jme3/environment/EnvironmentProbeControl.java @@ -345,7 +345,7 @@ void rebakeNow(RenderManager renderManager) { baker.setSphericalHarmonicsMode(sphericalHarmonicsMode); baker.setTexturePulling(isRequiredSavableResults()); - baker.bakeEnvironment(spatial, getPosition(), frustumNear, frustumFar, filter); + baker.bakeEnvironment(spatial, getPosition(), getRotation(), frustumNear, frustumFar, filter); baker.bakeSpecularIBL(); baker.bakeSphericalHarmonicsCoefficients(); diff --git a/jme3-core/src/main/java/com/jme3/environment/LightProbeFactory.java b/jme3-core/src/main/java/com/jme3/environment/LightProbeFactory.java index f035f95267..233f08e67e 100644 --- a/jme3-core/src/main/java/com/jme3/environment/LightProbeFactory.java +++ b/jme3-core/src/main/java/com/jme3/environment/LightProbeFactory.java @@ -124,6 +124,7 @@ public static LightProbe makeProbe(final EnvironmentCamera envCam, Spatial scene public static LightProbe makeProbe(final EnvironmentCamera envCam, Spatial scene, final EnvMapUtils.GenerationType genType, final JobProgressListener- * Probes are captured in world axes, so a newly captured probe has the identity rotation. + * The bakers capture the environment in the probe's current rotation, so re-baking a rotated probe gives the same + * lighting as baking it unrotated and then rotating it. * * @param rotation the world-space rotation (not null, unaffected) */ diff --git a/jme3-screenshot-tests/jme3-screenshot-tests-desktop/src/test/java/org/jmonkeyengine/screenshottests/light/pbr/TestLightProbeRotation.java b/jme3-screenshot-tests/jme3-screenshot-tests-desktop/src/test/java/org/jmonkeyengine/screenshottests/light/pbr/TestLightProbeRotation.java new file mode 100644 index 0000000000..0cfe1f73d6 --- /dev/null +++ b/jme3-screenshot-tests/jme3-screenshot-tests-desktop/src/test/java/org/jmonkeyengine/screenshottests/light/pbr/TestLightProbeRotation.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2026 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.jmonkeyengine.screenshottests.light.pbr; + +import org.jmonkeyengine.screenshottests.scenarios.light.pbr.ScenarioLightProbeRotation; +import org.jmonkeyengine.screenshottests.testframework.desktop.DesktopRunner; +import org.jmonkeyengine.screenshottests.testframework.desktop.ScreenshotTestDesktopBase; +import org.junit.jupiter.api.Test; + +/** + * Light probes rotated after baking. See {@link ScenarioLightProbeRotation}. + */ +public class TestLightProbeRotation extends ScreenshotTestDesktopBase { + + @Test + public void testSphericalProbeRotation() { + ScenarioLightProbeRotation.testSphericalProbeRotation().run(new DesktopRunner()); + } + + @Test + public void testOrientedBoxProbeRotation() { + ScenarioLightProbeRotation.testOrientedBoxProbeRotation().run(new DesktopRunner()); + } + + @Test + public void testProbeRotatedAgainstSky() { + ScenarioLightProbeRotation.testProbeRotatedAgainstSky().run(new DesktopRunner()); + } +} diff --git a/jme3-screenshot-tests/jme3-screenshot-tests-shared/src/main/java/org/jmonkeyengine/screenshottests/scenarios/light/pbr/ScenarioLightProbeRotation.java b/jme3-screenshot-tests/jme3-screenshot-tests-shared/src/main/java/org/jmonkeyengine/screenshottests/scenarios/light/pbr/ScenarioLightProbeRotation.java new file mode 100644 index 0000000000..a0d09170d0 --- /dev/null +++ b/jme3-screenshot-tests/jme3-screenshot-tests-shared/src/main/java/org/jmonkeyengine/screenshottests/scenarios/light/pbr/ScenarioLightProbeRotation.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2026 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.jmonkeyengine.screenshottests.scenarios.light.pbr; + +import com.jme3.app.Application; +import com.jme3.app.SimpleApplication; +import com.jme3.app.state.BaseAppState; +import com.jme3.asset.AssetManager; +import com.jme3.environment.EnvironmentProbeControl; +import com.jme3.light.LightProbe; +import com.jme3.light.OrientedBoxProbeArea; +import com.jme3.material.Material; +import com.jme3.math.ColorRGBA; +import com.jme3.math.FastMath; +import com.jme3.math.Quaternion; +import com.jme3.math.Vector3f; +import com.jme3.renderer.Camera; +import com.jme3.scene.Geometry; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import com.jme3.scene.control.LightControl; +import com.jme3.scene.shape.Sphere; +import com.jme3.util.SkyFactory; +import org.jmonkeyengine.screenshottests.testframework.Scenario; +import org.jmonkeyengine.screenshottests.testframework.ScreenshotTest; + +/** + * Light probes that are baked and then rotated (see {@link LightProbe#setRotation(Quaternion)}). + *
+ * A row of spheres, from mirror-like to fully rough, is lit only by a probe baked from the sky. The equivalence tests + * bake the probe, then turn the whole world (sky, spheres and probe) and the camera together by the same rotation. + * That must look exactly like never having turned anything, so each is a multi-scenario test whose scenarios must + * render identically. If the probe's rotation were ignored the reflections would stay put while everything else + * turned, and the scenarios would differ. The re-bake scenario captures the probe again after it has been turned, + * which must give the same result (the capture is taken in the probe's rotated space, not the world's). + */ +public class ScenarioLightProbeRotation { + + private static final int BAKE_SIZE = 256; + + /** + * The world is turned on this frame, after the probe has been baked (it bakes on the first frame rendered). + */ + private static final int ROTATE_ON_FRAME = 3; + + private static final int REBAKE_ON_FRAME = 4; + + private static final int SCREENSHOT_FRAME = 6; + + private static final Quaternion WORLD_ROTATION = new Quaternion().fromAngleAxis(50 * FastMath.DEG_TO_RAD, Vector3f.UNIT_Y); + + private static final Quaternion BOX_ROTATION_AT_SETUP = new Quaternion().fromAngleAxis(30 * FastMath.DEG_TO_RAD, Vector3f.UNIT_Y); + + private enum RotationMethod { + NONE, + SET_ROTATION, + LIGHT_CONTROL, + LIGHT_CONTROL_THEN_REBAKE + } + + /** + * A spherical probe (as baked by default) turned after baking. + */ + public static ScreenshotTest testSphericalProbeRotation() { + return new ScreenshotTest( + new Scenario("Unrotated", probeScene(false, RotationMethod.NONE)), + new Scenario("BakedThenRotatedWithSetRotation", probeScene(false, RotationMethod.SET_ROTATION)), + new Scenario("BakedThenRotatedWithLightControl", probeScene(false, RotationMethod.LIGHT_CONTROL)), + new Scenario("RotatedThenRebaked", probeScene(false, RotationMethod.LIGHT_CONTROL_THEN_REBAKE)) + ).setFramesToTakeScreenshotsOn(SCREENSHOT_FRAME); + } + + /** + * An oriented box probe whose box was already rotated at setup (like a room not built on the world axes), turned + * after baking. The box must keep its setup rotation and be turned on top of it, or the parallax correction would + * no longer line up and the scenarios would differ. + */ + public static ScreenshotTest testOrientedBoxProbeRotation() { + return new ScreenshotTest( + new Scenario("Unrotated", probeScene(true, RotationMethod.NONE)), + new Scenario("BakedThenRotatedWithSetRotation", probeScene(true, RotationMethod.SET_ROTATION)), + new Scenario("BakedThenRotatedWithLightControl", probeScene(true, RotationMethod.LIGHT_CONTROL)), + new Scenario("RotatedThenRebaked", probeScene(true, RotationMethod.LIGHT_CONTROL_THEN_REBAKE)) + ).setFramesToTakeScreenshotsOn(SCREENSHOT_FRAME); + } + + /** + * Only the probe is turned, so its lighting and reflections no longer match the visible sky. This shows what the + * rotation does on its own. + */ + public static ScreenshotTest testProbeRotatedAgainstSky() { + return new ScreenshotTest(new BaseAppState() { + private int frame = 0; + private EnvironmentProbeControl probe; + + @Override + protected void initialize(Application app) { + probe = buildScene((SimpleApplication) app, new Node("world"), false); + } + + @Override + public void update(float tpf) { + frame++; + if (frame == ROTATE_ON_FRAME) { + probe.setRotation(new Quaternion().fromAngleAxis(FastMath.HALF_PI, Vector3f.UNIT_Y)); + } + } + + @Override protected void cleanup(Application app) {} + @Override protected void onEnable() {} + @Override protected void onDisable() {} + }).setFramesToTakeScreenshotsOn(SCREENSHOT_FRAME); + } + + private static BaseAppState probeScene(boolean orientedBox, RotationMethod rotationMethod) { + return new BaseAppState() { + private int frame = 0; + private final Node world = new Node("world"); + private EnvironmentProbeControl probe; + + @Override + protected void initialize(Application app) { + probe = buildScene((SimpleApplication) app, world, orientedBox); + if (rotationMethod == RotationMethod.LIGHT_CONTROL || rotationMethod == RotationMethod.LIGHT_CONTROL_THEN_REBAKE) { + Node probeNode = new Node("probeNode"); + probeNode.addControl(new LightControl(probe)); + world.attachChild(probeNode); + } + } + + @Override + public void update(float tpf) { + frame++; + if (frame == ROTATE_ON_FRAME && rotationMethod != RotationMethod.NONE) { + world.setLocalRotation(WORLD_ROTATION); + if (rotationMethod == RotationMethod.SET_ROTATION) { + probe.setRotation(WORLD_ROTATION); + } + Camera cam = getApplication().getCamera(); + cam.setLocation(WORLD_ROTATION.mult(cam.getLocation())); + cam.setRotation(WORLD_ROTATION.mult(cam.getRotation())); + } + if (frame == REBAKE_ON_FRAME && rotationMethod == RotationMethod.LIGHT_CONTROL_THEN_REBAKE) { + probe.rebake(); + } + } + + @Override protected void cleanup(Application app) {} + @Override protected void onEnable() {} + @Override protected void onDisable() {} + }; + } + + /** + * Builds the sky and spheres under the world node and a probe, at the origin, baked from the sky. + */ + private static EnvironmentProbeControl buildScene(SimpleApplication app, Node world, boolean orientedBox) { + AssetManager assetManager = app.getAssetManager(); + Node rootNode = app.getRootNode(); + + Camera cam = app.getCamera(); + cam.setLocation(new Vector3f(0, 2.5f, 9)); + cam.lookAt(new Vector3f(0, 0, 0), Vector3f.UNIT_Y); + + Spatial sky = SkyFactory.createSky(assetManager, "Textures/Sky/Path.hdr", SkyFactory.EnvMapType.EquirectMap); + world.attachChild(sky); + + float[] roughnesses = {0.05f, 0.35f, 1f}; + for (int i = 0; i < roughnesses.length; i++) { + Geometry sphere = new Geometry("sphere" + i, new Sphere(48, 48, 1.2f)); + Material material = new Material(assetManager, "Common/MatDefs/Light/PBRLighting.j3md"); + material.setColor("BaseColor", ColorRGBA.White); + material.setFloat("Metallic", roughnesses[i] < 1f ? 1f : 0f); + material.setFloat("Roughness", roughnesses[i]); + sphere.setMaterial(material); + sphere.setLocalTranslation((i - 1) * 3f, 0, 0); + world.attachChild(sphere); + } + rootNode.attachChild(world); + + EnvironmentProbeControl probe = new EnvironmentProbeControl(assetManager, BAKE_SIZE); + if (orientedBox) { + probe.setAreaType(LightProbe.AreaType.OrientedBox); + OrientedBoxProbeArea box = (OrientedBoxProbeArea) probe.getArea(); + box.setExtent(new Vector3f(7, 4, 5)); + box.setRotation(BOX_ROTATION_AT_SETUP); + } + rootNode.addControl(probe); + probe.tag(sky); + return probe; + } +} From 3b5b9f5800da98549c4c0ca70c2895158cbee8e9 Mon Sep 17 00:00:00 2001 From: Richard Tingle <6330028+richardTingle@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:34:37 +0000 Subject: [PATCH 3/5] Include a manual example test --- .../light/pbr/TestLightProbeRotation.java | 276 ++++++++++++++++++ 1 file changed, 276 insertions(+) create mode 100644 jme3-examples/src/main/java/jme3test/light/pbr/TestLightProbeRotation.java diff --git a/jme3-examples/src/main/java/jme3test/light/pbr/TestLightProbeRotation.java b/jme3-examples/src/main/java/jme3test/light/pbr/TestLightProbeRotation.java new file mode 100644 index 0000000000..27623adaad --- /dev/null +++ b/jme3-examples/src/main/java/jme3test/light/pbr/TestLightProbeRotation.java @@ -0,0 +1,276 @@ +/* + * Copyright (c) 2026 jMonkeyEngine + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of 'jMonkeyEngine' nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package jme3test.light.pbr; + +import com.jme3.app.SimpleApplication; +import com.jme3.environment.EnvironmentProbeControl; +import com.jme3.font.BitmapText; +import com.jme3.input.KeyInput; +import com.jme3.input.controls.ActionListener; +import com.jme3.input.controls.AnalogListener; +import com.jme3.input.controls.KeyTrigger; +import com.jme3.light.LightProbe; +import com.jme3.light.OrientedBoxProbeArea; +import com.jme3.material.Material; +import com.jme3.math.ColorRGBA; +import com.jme3.math.FastMath; +import com.jme3.math.Quaternion; +import com.jme3.math.Vector3f; +import com.jme3.scene.Geometry; +import com.jme3.scene.Node; +import com.jme3.scene.Spatial; +import com.jme3.scene.control.LightControl; +import com.jme3.scene.debug.WireBox; +import com.jme3.scene.shape.Box; +import com.jme3.scene.shape.Sphere; +import com.jme3.util.SkyFactory; + +/** + * Manual partner of the TestLightProbeRotation screenshot test, showing why a light probe needs to rotate after it is + * baked. + *
+ * The viewer stands on a platform that never moves (as a player might stand on a ship's bridge, or a VR user in their + * room). In front of it, the world (the sky, a big red cube and three spheres from mirror to fully rough) is turned + * about a point, as if the platform were turning within it. The probe is baked once from the sky and the cube, and + * follows the world through a {@link LightControl}. The platform is not baked into the probe but is lit by it, so it + * should pick up the turning world's lighting while it stays still. + *
+ * Switch "probe follows world" off to see the problem this solves: the reflections and lighting, on the spheres and the + * platform alike, stay where they were while the sky and the cube turn away from them. + */ +public class TestLightProbeRotation extends SimpleApplication { + + private static final float TURN_SPEED = 0.4f; + + private static final Vector3f ROTATION_CENTRE = new Vector3f(0, 0, -10); + + private static final Quaternion BOX_ROTATION_AT_SETUP = new Quaternion().fromAngleAxis(30 * FastMath.DEG_TO_RAD, Vector3f.UNIT_Y); + + /** + * Large enough to take in the platform whichever way the world is turned. + */ + private static final Vector3f BOX_EXTENT = new Vector3f(16, 6, 16); + + private static final String TURN_LEFT = "TurnLeft"; + private static final String TURN_RIGHT = "TurnRight"; + private static final String TOGGLE_AUTO_TURN = "ToggleAutoTurn"; + private static final String TOGGLE_FOLLOW = "ToggleFollow"; + private static final String REBAKE = "Rebake"; + private static final String TOGGLE_BOX = "ToggleBox"; + + private final Node world = new Node("world"); + private float worldAngle = 0; + private boolean autoTurn = false; + private EnvironmentProbeControl probe; + private LightControl probeFollowsWorld; + private Geometry boxOutline; + private BitmapText hud; + + public static void main(String[] args) { + new TestLightProbeRotation().start(); + } + + @Override + public void simpleInitApp() { + cam.setLocation(new Vector3f(0, 1.7f, 1.5f)); + cam.lookAt(ROTATION_CENTRE, Vector3f.UNIT_Y); + flyCam.setDragToRotate(true); + flyCam.setMoveSpeed(0); + + buildPlatform(); + buildWorld(); + + boxOutline = new Geometry("probeBox", new WireBox(BOX_EXTENT.x, BOX_EXTENT.y, BOX_EXTENT.z)); + boxOutline.setMaterial(unshaded(ColorRGBA.Yellow)); + + hud = new BitmapText(guiFont); + guiNode.attachChild(hud); + + inputManager.addMapping(TURN_LEFT, new KeyTrigger(KeyInput.KEY_J)); + inputManager.addMapping(TURN_RIGHT, new KeyTrigger(KeyInput.KEY_L)); + inputManager.addMapping(TOGGLE_AUTO_TURN, new KeyTrigger(KeyInput.KEY_T)); + inputManager.addMapping(TOGGLE_FOLLOW, new KeyTrigger(KeyInput.KEY_F)); + inputManager.addMapping(REBAKE, new KeyTrigger(KeyInput.KEY_R)); + inputManager.addMapping(TOGGLE_BOX, new KeyTrigger(KeyInput.KEY_B)); + inputManager.addListener(turnListener, TURN_LEFT, TURN_RIGHT); + inputManager.addListener(toggleListener, TOGGLE_AUTO_TURN, TOGGLE_FOLLOW, REBAKE, TOGGLE_BOX); + + updateHud(); + } + + private void buildPlatform() { + Material platformMaterial = pbr(new ColorRGBA(0.8f, 0.8f, 0.85f, 1), 1f, 0.25f); + + Geometry deck = new Geometry("deck", new Box(3, 0.1f, 3)); + deck.setMaterial(platformMaterial); + deck.setLocalTranslation(0, -0.1f, 0); + rootNode.attachChild(deck); + + Geometry rail = new Geometry("rail", new Box(3, 0.05f, 0.05f)); + rail.setMaterial(platformMaterial); + rail.setLocalTranslation(0, 1, -3); + rootNode.attachChild(rail); + + for (int i = -1; i <= 1; i++) { + Geometry post = new Geometry("post" + i, new Box(0.05f, 0.5f, 0.05f)); + post.setMaterial(platformMaterial); + post.setLocalTranslation(i * 2.95f, 0.5f, -3); + rootNode.attachChild(post); + } + } + + private void buildWorld() { + world.setLocalTranslation(ROTATION_CENTRE); + + Spatial sky = SkyFactory.createSky(assetManager, "Textures/Sky/Path.hdr", SkyFactory.EnvMapType.EquirectMap); + world.attachChild(sky); + + Geometry redCube = new Geometry("redCube", new Box(2.5f, 2.5f, 2.5f)); + redCube.setMaterial(unshaded(ColorRGBA.Red)); + redCube.setLocalTranslation(-9, 1.5f, 3); + world.attachChild(redCube); + + float[] roughnesses = {0.05f, 0.35f, 1f}; + for (int i = 0; i < roughnesses.length; i++) { + Geometry sphere = new Geometry("sphere" + i, new Sphere(48, 48, 1.2f)); + sphere.setMaterial(pbr(ColorRGBA.White, roughnesses[i] < 1f ? 1f : 0f, roughnesses[i])); + sphere.setLocalTranslation((i - 1) * 3f, 1, 0); + world.attachChild(sphere); + } + rootNode.attachChild(world); + + probe = new EnvironmentProbeControl(assetManager, 256); + rootNode.addControl(probe); + probe.tag(sky); + probe.tag(redCube); + + Node probeNode = new Node("probeNode"); + probeNode.setLocalTranslation(0, 1, 0); + probeFollowsWorld = new LightControl(probe); + probeNode.addControl(probeFollowsWorld); + world.attachChild(probeNode); + } + + @Override + public void simpleUpdate(float tpf) { + if (autoTurn) { + turnWorld(TURN_SPEED * tpf); + } + if (!probeFollowsWorld.isEnabled()) { + probe.setPosition(world.getWorldTranslation().add(0, 1, 0)); + probe.setRotation(Quaternion.IDENTITY); + } + if (probe.getArea() instanceof OrientedBoxProbeArea) { + OrientedBoxProbeArea box = (OrientedBoxProbeArea) probe.getArea(); + boxOutline.setLocalTranslation(box.getCenter()); + boxOutline.setLocalRotation(box.getRotation()); + } + } + + private void turnWorld(float angle) { + worldAngle += angle; + world.setLocalRotation(new Quaternion().fromAngleAxis(worldAngle, Vector3f.UNIT_Y)); + updateHud(); + } + + private final AnalogListener turnListener = (name, value, tpf) -> + turnWorld(TURN_SPEED * tpf * (TURN_LEFT.equals(name) ? 1 : -1)); + + private final ActionListener toggleListener = (name, isPressed, tpf) -> { + if (!isPressed) { + return; + } + switch (name) { + case TOGGLE_AUTO_TURN: + autoTurn = !autoTurn; + break; + case TOGGLE_FOLLOW: + probeFollowsWorld.setEnabled(!probeFollowsWorld.isEnabled()); + break; + case REBAKE: + probe.rebake(); + break; + case TOGGLE_BOX: + toggleBox(); + break; + } + updateHud(); + }; + + /** + * Switches between a spherical area and a box that, like a room not built on the world axes, is already rotated + * relative to the world. + */ + private void toggleBox() { + if (probe.getAreaType() == LightProbe.AreaType.OrientedBox) { + probe.setAreaType(LightProbe.AreaType.Spherical); + probe.getArea().setRadius(Float.MAX_VALUE); + boxOutline.removeFromParent(); + } else { + probe.setAreaType(LightProbe.AreaType.OrientedBox); + OrientedBoxProbeArea box = (OrientedBoxProbeArea) probe.getArea(); + box.setExtent(BOX_EXTENT); + box.setRotation(probe.getRotation().mult(BOX_ROTATION_AT_SETUP)); + rootNode.attachChild(boxOutline); + } + } + + private Material pbr(ColorRGBA colour, float metallic, float roughness) { + Material material = new Material(assetManager, "Common/MatDefs/Light/PBRLighting.j3md"); + material.setColor("BaseColor", colour); + material.setFloat("Metallic", metallic); + material.setFloat("Roughness", roughness); + return material; + } + + private Material unshaded(ColorRGBA colour) { + Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); + material.setColor("Color", colour); + return material; + } + + private void updateHud() { + hud.setText(String.format( + "World turned: %.0f degrees (the platform never moves)%n" + + "J / L: turn the world about the point in front of the platform%n" + + "T: keep turning: %s%n" + + "F: probe follows world: %s%n" + + "R: re-bake the probe (should make no visible difference)%n" + + "B: probe area: %s%n" + + "Drag the mouse to look around", + worldAngle * FastMath.RAD_TO_DEG, + autoTurn ? "on" : "off", + probeFollowsWorld.isEnabled() ? "on" : "off (lighting ignores the turn)", + probe.getAreaType() == LightProbe.AreaType.OrientedBox ? "box (yellow, rotated 30 degrees at setup)" : "spherical")); + hud.setLocalTranslation(10, cam.getHeight() - 10, 0); + } +} From f32d21da85d5e37ab23d252bcf8a6e63fd84cfe7 Mon Sep 17 00:00:00 2001 From: Richard Tingle <6330028+richardTingle@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:01:39 +0000 Subject: [PATCH 4/5] Fix bug where cloned probes weren't complete clones --- .../main/java/com/jme3/light/LightProbe.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/jme3-core/src/main/java/com/jme3/light/LightProbe.java b/jme3-core/src/main/java/com/jme3/light/LightProbe.java index dc6b919298..30c1a9b14c 100644 --- a/jme3-core/src/main/java/com/jme3/light/LightProbe.java +++ b/jme3-core/src/main/java/com/jme3/light/LightProbe.java @@ -368,11 +368,31 @@ public Type getType() { @Override public LightProbe clone() { LightProbe probe = (LightProbe) super.clone(); + probe.position = position.clone(); probe.rotation = rotation.clone(); probe.rotationMatrix = rotationMatrix.clone(); + probe.area = cloneArea(area); return probe; } + /** + * Copies the built-in area types; a custom {@link ProbeArea} cannot be copied through the interface, so it stays + * shared with the original. + */ + private static ProbeArea cloneArea(ProbeArea area) { + try { + if (area instanceof SphereProbeArea) { + return ((SphereProbeArea) area).clone(); + } + if (area instanceof OrientedBoxProbeArea) { + return ((OrientedBoxProbeArea) area).clone(); + } + } catch (CloneNotSupportedException ex) { + throw new AssertionError(ex); + } + return area; + } + @Override public String toString() { return getClass().getSimpleName() From 7b301404229ed761c8d4ae00c2ee0c7a326728bd Mon Sep 17 00:00:00 2001 From: Richard Tingle <6330028+richardTingle@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:08:27 +0000 Subject: [PATCH 5/5] Eliminate duplicate methods (that could break overriders) --- .../jme3/environment/baker/GenericEnvBaker.java | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/jme3-core/src/main/java/com/jme3/environment/baker/GenericEnvBaker.java b/jme3-core/src/main/java/com/jme3/environment/baker/GenericEnvBaker.java index b10ca5c9ca..75631a9f5e 100644 --- a/jme3-core/src/main/java/com/jme3/environment/baker/GenericEnvBaker.java +++ b/jme3-core/src/main/java/com/jme3/environment/baker/GenericEnvBaker.java @@ -170,18 +170,10 @@ public TextureCubeMap getEnvMap() { * @return The updated camera */ protected Camera updateAndGetInternalCamera(int faceId, int w, int h, Vector3f position, float frustumNear, float frustumFar) { - return updateAndGetInternalCamera(faceId, w, h, position, Quaternion.IDENTITY, frustumNear, frustumFar); - } - - /** - * Updates the internal camera to face the given cubemap face of a cubemap with the given world-space orientation, - * and returns it. - */ - protected Camera updateAndGetInternalCamera(int faceId, int w, int h, Vector3f position, Quaternion rotation, float frustumNear, float frustumFar) { cam.resize(w, h, false); cam.setLocation(position); cam.setFrustumPerspective(90.0F, 1F, frustumNear, frustumFar); - cam.setRotation(rotation.mult(new Quaternion().fromAxes(axisX[faceId], axisY[faceId], axisZ[faceId]))); + cam.setRotation(new Quaternion().fromAxes(axisX[faceId], axisY[faceId], axisZ[faceId])); return cam; } @@ -229,7 +221,9 @@ public void bakeEnvironment(Spatial scene, Vector3f position, Quaternion rotatio for (int i = 0; i < 6; i++) { FrameBuffer envbaker = envbakers[i]; - ViewPort viewPort = new ViewPort("EnvBaker", updateAndGetInternalCamera(i, envbaker.getWidth(), envbaker.getHeight(), position, rotation, frustumNear, frustumFar)); + Camera faceCam = updateAndGetInternalCamera(i, envbaker.getWidth(), envbaker.getHeight(), position, frustumNear, frustumFar); + faceCam.setRotation(rotation.mult(faceCam.getRotation())); + ViewPort viewPort = new ViewPort("EnvBaker", faceCam); viewPort.setClearFlags(true, true, true); viewPort.setBackgroundColor(ColorRGBA.Pink);