diff --git a/examples/3d-island-terrain/3d-island-terrain.json b/examples/3d-island-terrain/3d-island-terrain.json index 81e11559c..d7132d46f 100644 --- a/examples/3d-island-terrain/3d-island-terrain.json +++ b/examples/3d-island-terrain/3d-island-terrain.json @@ -28881,7 +28881,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -31513,8 +31513,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -31625,8 +31624,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -31662,6 +31660,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -31959,6 +31974,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -32005,6 +32021,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -32093,6 +32111,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -32105,8 +32125,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -32164,104 +32190,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -32302,7 +32392,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -32314,9 +32406,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -32352,6 +32442,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -33444,8 +33535,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -35962,8 +36052,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -36446,8 +36535,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-3D-platformer/starting-3D-platformer.json b/examples/starting-3D-platformer/starting-3D-platformer.json index c95601789..de8e8f5d9 100644 --- a/examples/starting-3D-platformer/starting-3D-platformer.json +++ b/examples/starting-3D-platformer/starting-3D-platformer.json @@ -27616,7 +27616,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -30248,8 +30248,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -30360,8 +30359,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -30397,6 +30395,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -30694,6 +30709,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -30740,6 +30756,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -30828,6 +30846,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -30840,8 +30860,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -30899,104 +30925,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -31037,7 +31127,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -31049,9 +31141,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -31087,6 +31177,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -32179,8 +32270,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -34697,8 +34787,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -35181,8 +35270,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-3d-car-racing/starting-3d-car-racing.json b/examples/starting-3d-car-racing/starting-3d-car-racing.json index 6aa96b1fa..803478133 100644 --- a/examples/starting-3d-car-racing/starting-3d-car-racing.json +++ b/examples/starting-3d-car-racing/starting-3d-car-racing.json @@ -13159,7 +13159,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -15791,8 +15791,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -15903,8 +15902,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -15940,6 +15938,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -16237,6 +16252,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -16283,6 +16299,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -16371,6 +16389,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -16383,8 +16403,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -16442,104 +16468,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -16580,7 +16670,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -16592,9 +16684,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -16630,6 +16720,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -17722,8 +17813,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -20240,8 +20330,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -20724,8 +20813,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-3d-driving/starting-3d-driving.json b/examples/starting-3d-driving/starting-3d-driving.json index c4ed8dd7a..bb07357fa 100644 --- a/examples/starting-3d-driving/starting-3d-driving.json +++ b/examples/starting-3d-driving/starting-3d-driving.json @@ -12652,7 +12652,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -15284,8 +15284,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -15396,8 +15395,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -15433,6 +15431,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -15730,6 +15745,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -15776,6 +15792,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -15864,6 +15882,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -15876,8 +15896,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -15935,104 +15961,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -16073,7 +16163,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -16085,9 +16177,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -16123,6 +16213,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -17215,8 +17306,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -19733,8 +19823,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -20217,8 +20306,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-3d-grand-theft-auto/starting-3d-grand-theft-auto.json b/examples/starting-3d-grand-theft-auto/starting-3d-grand-theft-auto.json index 6e6887b49..648a58b2c 100644 --- a/examples/starting-3d-grand-theft-auto/starting-3d-grand-theft-auto.json +++ b/examples/starting-3d-grand-theft-auto/starting-3d-grand-theft-auto.json @@ -28608,7 +28608,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -31240,8 +31240,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -31352,8 +31351,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -31389,6 +31387,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -31686,6 +31701,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -31732,6 +31748,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -31820,6 +31838,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -31832,8 +31852,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -31891,104 +31917,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -32029,7 +32119,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -32041,9 +32133,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -32079,6 +32169,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -33171,8 +33262,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -35689,8 +35779,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -36173,8 +36262,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-3d-tank/starting-3d-tank.json b/examples/starting-3d-tank/starting-3d-tank.json index e4e27d4bc..399816742 100644 --- a/examples/starting-3d-tank/starting-3d-tank.json +++ b/examples/starting-3d-tank/starting-3d-tank.json @@ -36634,7 +36634,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -39266,8 +39266,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -39378,8 +39377,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -39415,6 +39413,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -39712,6 +39727,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -39758,6 +39774,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -39846,6 +39864,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -39858,8 +39878,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -39917,105 +39943,169 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", + " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", " }", " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", + " }", " }", "", " _updateBendingObjects() {", @@ -40055,7 +40145,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -40067,9 +40159,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -40105,6 +40195,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -41197,8 +41288,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -43715,8 +43805,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -44199,8 +44288,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-3D-platformer/starting-expanded-3D-platformer.json b/examples/starting-expanded-3D-platformer/starting-expanded-3D-platformer.json index 33c0f11cb..aa8b7eaa5 100644 --- a/examples/starting-expanded-3D-platformer/starting-expanded-3D-platformer.json +++ b/examples/starting-expanded-3D-platformer/starting-expanded-3D-platformer.json @@ -29668,7 +29668,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -32300,8 +32300,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -32412,8 +32411,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -32449,6 +32447,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -32746,6 +32761,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -32792,6 +32808,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -32880,6 +32898,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -32892,8 +32912,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -32951,104 +32977,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -33089,7 +33179,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -33101,9 +33193,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -33139,6 +33229,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -34231,8 +34322,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -36749,8 +36839,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -37233,8 +37322,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-3d-car-racing/starting-expanded-3d-car-racing.json b/examples/starting-expanded-3d-car-racing/starting-expanded-3d-car-racing.json index 629d735dd..6efa21a4e 100644 --- a/examples/starting-expanded-3d-car-racing/starting-expanded-3d-car-racing.json +++ b/examples/starting-expanded-3d-car-racing/starting-expanded-3d-car-racing.json @@ -15056,7 +15056,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -17688,8 +17688,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -17800,8 +17799,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -17837,6 +17835,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -18134,6 +18149,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -18180,6 +18196,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -18268,6 +18286,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -18280,8 +18300,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -18339,104 +18365,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -18477,7 +18567,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -18489,9 +18581,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -18527,6 +18617,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -19619,8 +19710,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -22137,8 +22227,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -22621,8 +22710,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-3d-driving/starting-expanded-3d-driving.json b/examples/starting-expanded-3d-driving/starting-expanded-3d-driving.json index a26151e5c..017fb3606 100644 --- a/examples/starting-expanded-3d-driving/starting-expanded-3d-driving.json +++ b/examples/starting-expanded-3d-driving/starting-expanded-3d-driving.json @@ -14356,7 +14356,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -16988,8 +16988,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -17100,8 +17099,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -17137,6 +17135,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -17434,6 +17449,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -17480,6 +17496,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -17568,6 +17586,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -17580,8 +17600,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -17639,104 +17665,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -17777,7 +17867,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -17789,9 +17881,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -17827,6 +17917,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -18919,8 +19010,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -21437,8 +21527,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -21921,8 +22010,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-3d-flight-sim/starting-expanded-3d-flight-sim.json b/examples/starting-expanded-3d-flight-sim/starting-expanded-3d-flight-sim.json index 778ab0052..5f400ab2b 100644 --- a/examples/starting-expanded-3d-flight-sim/starting-expanded-3d-flight-sim.json +++ b/examples/starting-expanded-3d-flight-sim/starting-expanded-3d-flight-sim.json @@ -12748,7 +12748,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -15380,8 +15380,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -15492,8 +15491,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -15529,6 +15527,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -15826,6 +15841,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -15872,6 +15888,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -15960,6 +15978,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -15972,8 +15992,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -16031,104 +16057,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -16169,7 +16259,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -16181,9 +16273,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -16219,6 +16309,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -17311,8 +17402,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -19829,8 +19919,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -20313,8 +20402,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-3d-grand-theft-auto/starting-expanded-3d-grand-theft-auto.json b/examples/starting-expanded-3d-grand-theft-auto/starting-expanded-3d-grand-theft-auto.json index 10f58c56f..6341846bf 100644 --- a/examples/starting-expanded-3d-grand-theft-auto/starting-expanded-3d-grand-theft-auto.json +++ b/examples/starting-expanded-3d-grand-theft-auto/starting-expanded-3d-grand-theft-auto.json @@ -31888,7 +31888,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -34520,8 +34520,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -34632,8 +34631,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -34669,6 +34667,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -34966,6 +34981,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -35012,6 +35028,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -35100,6 +35118,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -35112,8 +35132,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -35171,104 +35197,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -35309,7 +35399,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -35321,9 +35413,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -35359,6 +35449,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -36451,8 +36542,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -38969,8 +39059,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -39453,8 +39542,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-3d-rts-unit-selection/starting-expanded-3d-rts-unit-selection.json b/examples/starting-expanded-3d-rts-unit-selection/starting-expanded-3d-rts-unit-selection.json index 354b32a9a..b1e6bba04 100644 --- a/examples/starting-expanded-3d-rts-unit-selection/starting-expanded-3d-rts-unit-selection.json +++ b/examples/starting-expanded-3d-rts-unit-selection/starting-expanded-3d-rts-unit-selection.json @@ -15376,7 +15376,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -18008,8 +18008,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -18120,8 +18119,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -18157,6 +18155,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -18454,6 +18469,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -18500,6 +18516,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -18588,6 +18606,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -18600,8 +18620,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -18659,104 +18685,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -18797,7 +18887,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -18809,9 +18901,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -18847,6 +18937,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -19939,8 +20030,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -22457,8 +22547,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -22941,8 +23030,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-3d-tank/starting-expanded-3d-tank.json b/examples/starting-expanded-3d-tank/starting-expanded-3d-tank.json index a89d0bc4a..5d7f2985f 100644 --- a/examples/starting-expanded-3d-tank/starting-expanded-3d-tank.json +++ b/examples/starting-expanded-3d-tank/starting-expanded-3d-tank.json @@ -38548,7 +38548,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -41180,8 +41180,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -41292,8 +41291,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -41329,6 +41327,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -41626,6 +41641,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -41672,6 +41688,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -41760,6 +41778,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -41772,8 +41792,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -41831,105 +41857,169 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", + " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", " }", " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", + " }", " }", "", " _updateBendingObjects() {", @@ -41969,7 +42059,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -41981,9 +42073,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -42019,6 +42109,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -43111,8 +43202,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -45629,8 +45719,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -46113,8 +46202,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-3d-top-down-rpg/starting-expanded-3d-top-down-rpg.json b/examples/starting-expanded-3d-top-down-rpg/starting-expanded-3d-top-down-rpg.json index 8673a14aa..941bedd78 100644 --- a/examples/starting-expanded-3d-top-down-rpg/starting-expanded-3d-top-down-rpg.json +++ b/examples/starting-expanded-3d-top-down-rpg/starting-expanded-3d-top-down-rpg.json @@ -47145,7 +47145,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -49777,8 +49777,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -49889,8 +49888,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -49926,6 +49924,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -50223,6 +50238,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -50269,6 +50285,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -50357,6 +50375,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -50369,8 +50389,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -50428,105 +50454,169 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", + " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", " }", " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", + " }", " }", "", " _updateBendingObjects() {", @@ -50566,7 +50656,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -50578,9 +50670,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -50616,6 +50706,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -51708,8 +51799,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -54226,8 +54316,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -54710,8 +54799,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-first-person-farming/starting-expanded-first-person-farming.json b/examples/starting-expanded-first-person-farming/starting-expanded-first-person-farming.json index 2c362a21a..faf1fcc19 100644 --- a/examples/starting-expanded-first-person-farming/starting-expanded-first-person-farming.json +++ b/examples/starting-expanded-first-person-farming/starting-expanded-first-person-farming.json @@ -50136,7 +50136,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -52768,8 +52768,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -52880,8 +52879,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -52917,6 +52915,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -53214,6 +53229,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -53260,6 +53276,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -53348,6 +53366,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -53360,8 +53380,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -53419,104 +53445,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -53557,7 +53647,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -53569,9 +53661,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -53607,6 +53697,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -54699,8 +54790,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -57217,8 +57307,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -57701,8 +57790,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-first-person-horror/starting-expanded-first-person-horror.json b/examples/starting-expanded-first-person-horror/starting-expanded-first-person-horror.json index 0a036d738..8f463a565 100644 --- a/examples/starting-expanded-first-person-horror/starting-expanded-first-person-horror.json +++ b/examples/starting-expanded-first-person-horror/starting-expanded-first-person-horror.json @@ -31041,7 +31041,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -33673,8 +33673,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -33785,8 +33784,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -33822,6 +33820,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -34119,6 +34134,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -34165,6 +34181,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -34253,6 +34271,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -34265,8 +34285,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -34324,104 +34350,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -34462,7 +34552,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -34474,9 +34566,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -34512,6 +34602,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -35604,8 +35695,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -38122,8 +38212,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -38606,8 +38695,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-first-person-shooter-enemies/starting-expanded-first-person-shooter-enemies.json b/examples/starting-expanded-first-person-shooter-enemies/starting-expanded-first-person-shooter-enemies.json index ba65b346c..73343a68a 100644 --- a/examples/starting-expanded-first-person-shooter-enemies/starting-expanded-first-person-shooter-enemies.json +++ b/examples/starting-expanded-first-person-shooter-enemies/starting-expanded-first-person-shooter-enemies.json @@ -42458,7 +42458,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -45090,8 +45090,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -45202,8 +45201,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -45239,6 +45237,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -45536,6 +45551,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -45582,6 +45598,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -45670,6 +45688,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -45682,8 +45702,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -45741,104 +45767,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -45879,7 +45969,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -45891,9 +45983,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -45929,6 +46019,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -47021,8 +47112,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -49539,8 +49629,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -50023,8 +50112,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-first-person-shooter-horror/starting-expanded-first-person-shooter-horror.json b/examples/starting-expanded-first-person-shooter-horror/starting-expanded-first-person-shooter-horror.json index 685821385..a51a07efc 100644 --- a/examples/starting-expanded-first-person-shooter-horror/starting-expanded-first-person-shooter-horror.json +++ b/examples/starting-expanded-first-person-shooter-horror/starting-expanded-first-person-shooter-horror.json @@ -48295,7 +48295,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -50927,8 +50927,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -51039,8 +51038,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -51076,6 +51074,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -51373,6 +51388,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -51419,6 +51435,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -51507,6 +51525,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -51519,8 +51539,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -51578,104 +51604,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -51716,7 +51806,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -51728,9 +51820,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -51766,6 +51856,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -52858,8 +52949,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -55376,8 +55466,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -55860,8 +55949,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-expanded-first-person-survival-crafting/starting-expanded-first-person-survival-crafting.json b/examples/starting-expanded-first-person-survival-crafting/starting-expanded-first-person-survival-crafting.json index 66b3af0b3..cb6cdfa6f 100644 --- a/examples/starting-expanded-first-person-survival-crafting/starting-expanded-first-person-survival-crafting.json +++ b/examples/starting-expanded-first-person-survival-crafting/starting-expanded-first-person-survival-crafting.json @@ -37722,7 +37722,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -40354,8 +40354,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -40466,8 +40465,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -40503,6 +40501,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -40800,6 +40815,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -40846,6 +40862,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -40934,6 +40952,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -40946,8 +40966,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -41005,104 +41031,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -41143,7 +41233,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -41155,9 +41247,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -41193,6 +41283,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -42285,8 +42376,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -44803,8 +44893,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -45287,8 +45376,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-first-person-farming/starting-first-person-farming.json b/examples/starting-first-person-farming/starting-first-person-farming.json index c01ef9edc..17fa1fe03 100644 --- a/examples/starting-first-person-farming/starting-first-person-farming.json +++ b/examples/starting-first-person-farming/starting-first-person-farming.json @@ -48373,7 +48373,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -51005,8 +51005,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -51117,8 +51116,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -51154,6 +51152,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -51451,6 +51466,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -51497,6 +51513,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -51585,6 +51603,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -51597,8 +51617,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -51656,104 +51682,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -51794,7 +51884,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -51806,9 +51898,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -51844,6 +51934,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -52936,8 +53027,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -55454,8 +55544,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -55938,8 +56027,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-first-person-horror/starting-first-person-horror.json b/examples/starting-first-person-horror/starting-first-person-horror.json index 699cbb184..32a5ea851 100644 --- a/examples/starting-first-person-horror/starting-first-person-horror.json +++ b/examples/starting-first-person-horror/starting-first-person-horror.json @@ -30305,7 +30305,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -32937,8 +32937,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -33049,8 +33048,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -33086,6 +33084,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -33383,6 +33398,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -33429,6 +33445,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -33517,6 +33535,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -33529,8 +33549,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -33588,104 +33614,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", + "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -33726,7 +33816,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -33738,9 +33830,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -33776,6 +33866,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -34868,8 +34959,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -37386,8 +37476,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -37870,8 +37959,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-first-person-shooter-enemies/starting-first-person-shooter-enemies.json b/examples/starting-first-person-shooter-enemies/starting-first-person-shooter-enemies.json index f07eefd29..f16c95c84 100644 --- a/examples/starting-first-person-shooter-enemies/starting-first-person-shooter-enemies.json +++ b/examples/starting-first-person-shooter-enemies/starting-first-person-shooter-enemies.json @@ -41269,7 +41269,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -43901,8 +43901,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -44013,8 +44012,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -44050,6 +44048,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -44347,6 +44362,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -44393,6 +44409,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -44481,6 +44499,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -44493,8 +44513,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -44552,104 +44578,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -44690,7 +44780,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -44702,9 +44794,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -44740,6 +44830,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -45832,8 +45923,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -48350,8 +48440,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -48834,8 +48923,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-first-person-shooter-horror/starting-first-person-shooter-horror.json b/examples/starting-first-person-shooter-horror/starting-first-person-shooter-horror.json index 416c95936..095d588f7 100644 --- a/examples/starting-first-person-shooter-horror/starting-first-person-shooter-horror.json +++ b/examples/starting-first-person-shooter-horror/starting-first-person-shooter-horror.json @@ -46322,7 +46322,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -48954,8 +48954,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -49066,8 +49065,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -49103,6 +49101,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -49400,6 +49415,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -49446,6 +49462,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -49534,6 +49552,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -49546,8 +49566,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -49605,104 +49631,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -49743,7 +49833,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -49755,9 +49847,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -49793,6 +49883,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -50885,8 +50976,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -53403,8 +53493,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -53887,8 +53976,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-first-person-shooter/starting-first-person-shooter.json b/examples/starting-first-person-shooter/starting-first-person-shooter.json index c465d44d9..d165b16df 100644 --- a/examples/starting-first-person-shooter/starting-first-person-shooter.json +++ b/examples/starting-first-person-shooter/starting-first-person-shooter.json @@ -40055,7 +40055,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -42687,8 +42687,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -42799,8 +42798,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -42836,6 +42834,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -43133,6 +43148,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -43179,6 +43195,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -43267,6 +43285,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -43279,8 +43299,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -43338,104 +43364,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -43476,7 +43566,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -43488,9 +43580,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -43526,6 +43616,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -44618,8 +44709,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -47136,8 +47226,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -47620,8 +47709,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-first-person-survival-crafting/starting-first-person-survival-crafting.json b/examples/starting-first-person-survival-crafting/starting-first-person-survival-crafting.json index 10a8708c8..5bb029768 100644 --- a/examples/starting-first-person-survival-crafting/starting-first-person-survival-crafting.json +++ b/examples/starting-first-person-survival-crafting/starting-first-person-survival-crafting.json @@ -35575,7 +35575,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -38207,8 +38207,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -38319,8 +38318,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -38356,6 +38354,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -38653,6 +38668,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -38699,6 +38715,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -38787,6 +38805,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -38799,8 +38819,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -38858,104 +38884,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -38996,7 +39086,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -39008,9 +39100,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -39046,6 +39136,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -40138,8 +40229,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -42656,8 +42746,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -43140,8 +43229,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/examples/starting-first-person/starting-first-person.json b/examples/starting-first-person/starting-first-person.json index 533154b92..4238bd3b3 100644 --- a/examples/starting-first-person/starting-first-person.json +++ b/examples/starting-first-person/starting-first-person.json @@ -23188,7 +23188,7 @@ "name": "Terrain3D", "previewIconUrl": "https://asset-resources.gdevelop.io/public-resources/Icons/10e0a26c0d500830dfe23b94138beb0ef61607ba62bca05a5aa5c849777f1b06_terrain.svg", "shortDescription": "A ground with hills and valleys that can be sculpted and painted in the editor, with collisions.", - "version": "0.3.1", + "version": "0.3.2", "description": [ "A 3D terrain object for open worlds, adventure or racing games: hills, mountains, islands or valleys, with painted layers of grass, dirt, rock or sand.", "", @@ -25820,8 +25820,7 @@ " * in the terrain group coordinates. Holes are hit too, so that brushes can fill them.", " */", " raycastFromCursor(game, raycaster, ndc) {", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(this.object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " ndc.set(", @@ -25932,8 +25931,7 @@ " this.applyChanges();", " this.renderer.uniforms.terrainWorldScale.value = getWorldScale(this.object);", " this._updateWetShore();", - " const layer = this.object.getInstanceContainer().getLayer(this.object.getLayer());", - " this.renderer.updateLevelsOfDetail(layer.getRenderer().getThreeCamera());", + " this.renderer.updateLevelsOfDetail(getCamera(this.object));", " }", "", " _updateWetShore() {", @@ -25969,6 +25967,23 @@ " return typeof scene.getRenderer3DWorldScale === 'function' ? scene.getRenderer3DWorldScale() : 1;", "};", "", + "/**", + " * @param {gdjs.RuntimeObject} object", + " * @returns {THREE.Camera | null} The camera of the scene layer showing the object. Layers of custom objects", + " * have no camera: the one of the scene layer of the custom object containing the object is used.", + " */", + "const getCamera = (object) => {", + " let container = object.getInstanceContainer();", + " while (container instanceof gdjs.CustomRuntimeObjectInstanceContainer) {", + " object = container.getOwner();", + " container = object.getInstanceContainer();", + " }", + " const camera = container.getLayer(object.getLayer()).getRenderer().getThreeCamera();", + " // The matrix of the camera is otherwise only updated when the scene is drawn: it would be the one of the previous frame.", + " if (camera) camera.updateMatrixWorld();", + " return camera;", + "};", + "", "/** @type {WeakMap} */", "const averageColors = new WeakMap();", "let white = null;", @@ -26266,6 +26281,7 @@ " Terrain,", " // Used by the terrain grass and the scattered models.", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -26312,6 +26328,8 @@ "const AREA_SIZE = 1000;", "const AREA_DEPTH = 40;", "const CHUNK_SIZE = 500;", + "// Blades are placed around the camera as it moves: at most this number by frame, to avoid slowing down the game.", + "const MAX_BLADES_PLACED_BY_FRAME = 36000;", "const MAX_BENDING_OBJECTS = 8;", "", "/**", @@ -26400,6 +26418,8 @@ "", "const { getWorldScale, patchShaderCode, createRandom, findHighestGround, GroundPlacement } = gdjs.__terrain3DExtension;", "", + "/** @typedef {{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}} GrassChunk */", + "", "/**", " * The grass of a terrain grass object: blades drawn with GPU instancing, in chunks", " * that are hidden when off-screen and thinned out with the distance. They grow", @@ -26412,8 +26432,14 @@ " this.group = new THREE.Group();", " object.get3DRendererObject().add(this.group);", " this.bladeGeometry = createBladeGeometry();", - " /** @type {Array<{mesh: THREE.Mesh, blades: number, center: THREE.Vector3}>} */", - " this.chunks = [];", + " /**", + " * The chunks with blades placed, by index in the grid of chunks (null when no blade grows in a chunk).", + " * @type {Map}", + " */", + " this.chunks = new Map();", + " /** @type {Array<{chunkX: number, chunkY: number, distance: number}>} */", + " this._missingChunks = [];", + " this._placeWithoutLimit = true;", " this.placement = new GroundPlacement(object.getRuntimeScene());", " this._groundAtBlade = { ground: null, z: 0 };", " this.uniforms = {", @@ -26471,104 +26497,168 @@ " ].join('|');", " }", "", - " /** Place the blades again, for example after the ground or the object changed. */", - " rebuild() {", - " const grounds = Array.from(this.placement.grounds);", - " for (const chunk of this.chunks) {", + " _getBladesPerChunk() {", + " return Math.round((Math.max(this.object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", + " }", + "", + " _removeChunks() {", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " chunk.mesh.removeFromParent();", " chunk.mesh.geometry.dispose();", " }", - " this.chunks.length = 0;", + " this.chunks.clear();", + " }", "", + " /** Place the blades again, for example after the ground or the object changed. */", + " rebuild() {", + " this._removeChunks();", + " this._placeWithoutLimit = true;", + " }", + "", + " /**", + " * Place the blades of a chunk. Each chunk has its own random numbers: its blades are the same every time.", + " * @returns {GrassChunk | null} null when no blade grows in the chunk.", + " */", + " _placeChunk(chunkX, chunkY) {", + " const grounds = Array.from(this.placement.grounds);", " const { object } = this;", " const width = object.getWidth();", " const height = object.getHeight();", " const scaleX = width / AREA_SIZE;", " const scaleY = height / AREA_SIZE;", " const scaleZ = Math.max(object.getDepth() / AREA_DEPTH, 0.0001);", - " const bladesPerChunk = Math.round((Math.max(object._getDensity(), 0) * CHUNK_SIZE * CHUNK_SIZE) / 10000);", " const groundLayer = parseInt(object._getGroundLayer(), 10) || 0;", " const maxSlope = object._getMaxSlope();", - " const chunksX = Math.max(Math.ceil(width / CHUNK_SIZE), 1);", - " const chunksY = Math.max(Math.ceil(height / CHUNK_SIZE), 1);", - " const nextRandom = createRandom(object._getSeed() * 7919 + 1);", " const bladeHeight = Math.max(object._getBladeHeight(), 0);", + " const bladesPerChunk = this._getBladesPerChunk();", + " const nextRandom = createRandom(", + " ((object._getSeed() * 7919 + 1) ^ Math.imul(chunkX + 1, 73856093) ^ Math.imul(chunkY + 1, 19349663)) >>> 0", + " );", "", - " for (let chunkY = 0; chunkY < chunksY; chunkY++) {", - " for (let chunkX = 0; chunkX < chunksX; chunkX++) {", - " const roots = new Float32Array(bladesPerChunk * 4);", - " const shapes = new Float32Array(bladesPerChunk * 2);", - " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", - " let blades = 0;", - " let minZ = Infinity;", - " let maxZ = -Infinity;", - " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", - " // In scene units, relative to the object.", - " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", - " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", - " const angle = nextRandom() * Math.PI * 2;", - " const heightFactor = 0.6 + 0.8 * nextRandom();", - " const tint = nextRandom();", - " const growth = nextRandom();", - " if (x > width || y > height) continue;", - " const sceneX = object.getX() + x;", - " const sceneY = object.getY() + y;", - " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", - " const groundZ = ground ? z : object.getZ();", - " if (ground) {", - " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", - " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", - " if (typeof ground.getTintAt === 'function') {", - " const tint = ground.getTintAt(sceneX, sceneY);", - " for (let channel = 0; channel < 3; channel++) {", - " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", - " }", - " }", + " const roots = new Float32Array(bladesPerChunk * 4);", + " const shapes = new Float32Array(bladesPerChunk * 2);", + " const groundTints = new Uint8Array(bladesPerChunk * 3).fill(255);", + " let blades = 0;", + " let minZ = Infinity;", + " let maxZ = -Infinity;", + " for (let attempt = 0; attempt < bladesPerChunk; attempt++) {", + " // In scene units, relative to the object.", + " const x = (chunkX + nextRandom()) * CHUNK_SIZE;", + " const y = (chunkY + nextRandom()) * CHUNK_SIZE;", + " const angle = nextRandom() * Math.PI * 2;", + " const heightFactor = 0.6 + 0.8 * nextRandom();", + " const tint = nextRandom();", + " const growth = nextRandom();", + " if (x > width || y > height) continue;", + " const sceneX = object.getX() + x;", + " const sceneY = object.getY() + y;", + " const { ground, z } = findHighestGround(grounds, sceneX, sceneY, this._groundAtBlade);", + " const groundZ = ground ? z : object.getZ();", + " if (ground) {", + " if (groundLayer > 0 && growth > ground.getLayerWeightAt(sceneX, sceneY, groundLayer)) continue;", + " if (ground.getSlopeAt(sceneX, sceneY) > maxSlope) continue;", + " if (typeof ground.getTintAt === 'function') {", + " const tint = ground.getTintAt(sceneX, sceneY);", + " for (let channel = 0; channel < 3; channel++) {", + " groundTints[blades * 3 + channel] = Math.round(255 * Math.pow(tint[channel] / 255, 2.2));", " }", - " const localZ = (groundZ - object.getZ()) / scaleZ;", - " roots[blades * 4] = x / scaleX;", - " roots[blades * 4 + 1] = y / scaleY;", - " roots[blades * 4 + 2] = localZ;", - " roots[blades * 4 + 3] = angle;", - " shapes[blades * 2] = heightFactor * bladeHeight;", - " shapes[blades * 2 + 1] = tint;", - " minZ = Math.min(minZ, localZ);", - " maxZ = Math.max(maxZ, localZ);", - " blades++;", " }", - " if (blades === 0) continue;", - "", - " const geometry = new THREE.InstancedBufferGeometry();", - " geometry.index = this.bladeGeometry.index;", - " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", - " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", - " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", - " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", - " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", - " geometry.instanceCount = blades;", - " // The furthest tips can go with the wind and the bending objects (see the shader).", - " const maxBladeHeight = bladeHeight * 1.4;", - " const lean =", - " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", - " Math.max(object._getBladeWidth(), 0) / 2;", - " const leanX = lean / scaleX;", - " const leanY = lean / scaleY;", - " geometry.boundingBox = new THREE.Box3(", - " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", - " new THREE.Vector3(", - " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", - " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", - " maxZ + (bladeHeight * 1.4) / scaleZ", - " )", - " );", - " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", - " const mesh = new THREE.Mesh(geometry, this.material);", - " mesh.receiveShadow = true;", - " // Raycasts would only test one blade: the selection plane is used instead.", - " mesh.raycast = () => {};", - " this.group.add(mesh);", - " this.chunks.push({ mesh, blades, center: geometry.boundingSphere.center.clone() });", " }", + " const localZ = (groundZ - object.getZ()) / scaleZ;", + " roots[blades * 4] = x / scaleX;", + " roots[blades * 4 + 1] = y / scaleY;", + " roots[blades * 4 + 2] = localZ;", + " roots[blades * 4 + 3] = angle;", + " shapes[blades * 2] = heightFactor * bladeHeight;", + " shapes[blades * 2 + 1] = tint;", + " minZ = Math.min(minZ, localZ);", + " maxZ = Math.max(maxZ, localZ);", + " blades++;", + " }", + " if (blades === 0) return null;", + "", + " const geometry = new THREE.InstancedBufferGeometry();", + " geometry.index = this.bladeGeometry.index;", + " geometry.setAttribute('position', this.bladeGeometry.attributes.position);", + " geometry.setAttribute('normal', this.bladeGeometry.attributes.normal);", + " geometry.setAttribute('grassRoot', new THREE.InstancedBufferAttribute(roots.subarray(0, blades * 4), 4));", + " geometry.setAttribute('grassShape', new THREE.InstancedBufferAttribute(shapes.subarray(0, blades * 2), 2));", + " geometry.setAttribute('grassGroundTint', new THREE.InstancedBufferAttribute(groundTints.subarray(0, blades * 3), 3, true));", + " geometry.instanceCount = blades;", + " // The furthest tips can go with the wind and the bending objects (see the shader).", + " const maxBladeHeight = bladeHeight * 1.4;", + " const lean =", + " (0.35 * 1.9 * 0.943 * Math.max(object._getWindStrength(), 0) + 0.9) * maxBladeHeight +", + " Math.max(object._getBladeWidth(), 0) / 2;", + " const leanX = lean / scaleX;", + " const leanY = lean / scaleY;", + " geometry.boundingBox = new THREE.Box3(", + " new THREE.Vector3((chunkX * CHUNK_SIZE) / scaleX - leanX, (chunkY * CHUNK_SIZE) / scaleY - leanY, minZ),", + " new THREE.Vector3(", + " Math.min((chunkX + 1) * CHUNK_SIZE, width) / scaleX + leanX,", + " Math.min((chunkY + 1) * CHUNK_SIZE, height) / scaleY + leanY,", + " maxZ + (bladeHeight * 1.4) / scaleZ", + " )", + " );", + " geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());", + " const mesh = new THREE.Mesh(geometry, this.material);", + " mesh.receiveShadow = true;", + " // Raycasts would only test one blade: the selection plane is used instead.", + " mesh.raycast = () => {};", + " this.group.add(mesh);", + " return { mesh, blades, center: geometry.boundingSphere.center.clone() };", + " }", + "", + " /**", + " * Place the blades of the chunks near the camera (the nearest first) and remove the ones of the chunks", + " * far from it: a large field would otherwise be slow to place and use a lot of memory for blades never drawn.", + " */", + " _updateChunksAroundCamera() {", + " const { object } = this;", + " // The camera in scene units, relative to the object (`_matrix` is the inverse of the group one).", + " const camera = this._chunkPosition.copy(this._cameraPosition).applyMatrix4(this._matrix);", + " const cameraX = (camera.x * object.getWidth()) / AREA_SIZE;", + " const cameraY = (camera.y * object.getHeight()) / AREA_SIZE;", + " const chunksX = Math.max(Math.ceil(object.getWidth() / CHUNK_SIZE), 1);", + " const chunksY = Math.max(Math.ceil(object.getHeight() / CHUNK_SIZE), 1);", + " const getDistance = (chunkX, chunkY) =>", + " Math.hypot((chunkX + 0.5) * CHUNK_SIZE - cameraX, (chunkY + 0.5) * CHUNK_SIZE - cameraY);", + "", + " // Chunks are placed a bit before blades are shown.", + " const placementDistance = Math.max(object._getFadeDistance(), 1) + CHUNK_SIZE;", + " const missingChunks = this._missingChunks;", + " missingChunks.length = 0;", + " const firstChunkX = Math.max(Math.floor((cameraX - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkX = Math.min(Math.floor((cameraX + placementDistance) / CHUNK_SIZE), chunksX - 1);", + " const firstChunkY = Math.max(Math.floor((cameraY - placementDistance) / CHUNK_SIZE), 0);", + " const lastChunkY = Math.min(Math.floor((cameraY + placementDistance) / CHUNK_SIZE), chunksY - 1);", + " for (let chunkY = firstChunkY; chunkY <= lastChunkY; chunkY++) {", + " for (let chunkX = firstChunkX; chunkX <= lastChunkX; chunkX++) {", + " if (this.chunks.has(chunkY * chunksX + chunkX)) continue;", + " const distance = getDistance(chunkX, chunkY);", + " if (distance <= placementDistance) missingChunks.push({ chunkX, chunkY, distance });", + " }", + " }", + " // Everything is placed at once after a change, so that blades don't disappear for a few frames.", + " const maxPlacedChunks = this._placeWithoutLimit", + " ? Infinity", + " : Math.max(Math.floor(MAX_BLADES_PLACED_BY_FRAME / Math.max(this._getBladesPerChunk(), 1)), 1);", + " this._placeWithoutLimit = false;", + " if (missingChunks.length > maxPlacedChunks) {", + " missingChunks.sort((chunk, otherChunk) => chunk.distance - otherChunk.distance);", + " missingChunks.length = maxPlacedChunks;", + " }", + " for (const { chunkX, chunkY } of missingChunks) {", + " this.chunks.set(chunkY * chunksX + chunkX, this._placeChunk(chunkX, chunkY));", + " }", + "", + " for (const [key, chunk] of this.chunks) {", + " if (getDistance(key % chunksX, Math.floor(key / chunksX)) < 2 * placementDistance) continue;", + " this.chunks.delete(key);", + " if (!chunk) continue;", + " chunk.mesh.removeFromParent();", + " chunk.mesh.geometry.dispose();", " }", " }", "", @@ -26609,7 +26699,9 @@ " // Far chunks are hidden, and thinned out before (in 3D world units).", " const fadeDistance = Math.max(this.object._getFadeDistance(), 1) / getWorldScale(this.object);", " this._cameraPosition.setFromMatrixPosition(camera.matrixWorld);", - " for (const chunk of this.chunks) {", + " this._updateChunksAroundCamera();", + " for (const chunk of this.chunks.values()) {", + " if (!chunk) continue;", " const distance = this._chunkPosition", " .copy(chunk.center)", " .applyMatrix4(this.group.matrixWorld)", @@ -26621,9 +26713,7 @@ " }", "", " dispose() {", - " for (const chunk of this.chunks) {", - " chunk.mesh.geometry.dispose();", - " }", + " this._removeChunks();", " this.bladeGeometry.dispose();", " this.material.dispose();", " this.group.removeFromParent();", @@ -26659,6 +26749,7 @@ "", "const {", " getWorldScale,", + " getCamera,", " getGrounds,", " patchShaderCode,", " createRandom,", @@ -27751,8 +27842,7 @@ " if (hit) return hit;", "", " const { object } = scatter;", - " const layer = object.getInstanceContainer().getLayer(object.getLayer());", - " const camera = layer.getRenderer().getThreeCamera();", + " const camera = getCamera(object);", " if (!camera) return null;", " const inputManager = game.getInputManager();", " this.ndc.set(", @@ -30269,8 +30359,7 @@ "const time = isInGameEdition", " ? performance.now() / 1000", " : object.getRuntimeScene().getTimeManager().getTimeFromStart() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainGrass.update(elapsedTime, time, layer.getRenderer().getThreeCamera());" + "object.__terrainGrass.update(elapsedTime, time, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, @@ -30753,8 +30842,7 @@ "const game = runtimeScene.getGame();", "const isInGameEdition = game.isInGameEdition && game.isInGameEdition();", "const elapsedTime = isInGameEdition ? 1 / 60 : object.getElapsedTime() / 1000;", - "const layer = object.getInstanceContainer().getLayer(object.getLayer());", - "object.__terrainScatter.update(elapsedTime, layer.getRenderer().getThreeCamera());" + "object.__terrainScatter.update(elapsedTime, gdjs.__terrain3DExtension.getCamera(object));" ], "parameterObjects": "Object", "useStrict": true, diff --git a/rendering-screenshots/3d-island-terrain/the-island-from-above.png b/rendering-screenshots/3d-island-terrain/the-island-from-above.png index 58187d95a..2ef6bd69c 100644 Binary files a/rendering-screenshots/3d-island-terrain/the-island-from-above.png and b/rendering-screenshots/3d-island-terrain/the-island-from-above.png differ diff --git a/rendering-screenshots/3d-island-terrain/the-view-of-the-player.png b/rendering-screenshots/3d-island-terrain/the-view-of-the-player.png index ecbc8b2e7..547654c15 100644 Binary files a/rendering-screenshots/3d-island-terrain/the-view-of-the-player.png and b/rendering-screenshots/3d-island-terrain/the-view-of-the-player.png differ