Repository navigation
New extension to Batch objects and improvements of terrain 3D #2373
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ClementPasteau
wants to merge
1
commit into
main
Choose a base branch
from
terrain-improvement
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,218 @@ | ||
| { | ||
| "author": "", | ||
| "category": "Advanced", | ||
| "dimension": "3D", | ||
| "extensionNamespace": "", | ||
| "fullName": "Static 3D scenery batching", | ||
| "gdevelopVersion": ">=5.5.222", | ||
| "helpPath": "", | ||
| "iconUrl": "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0ibWRpLWdyb3VwIiB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZD0iTTEsMVY1SDJWMTlIMVYyM0g1VjIySDE5VjIzSDIzVjE5SDIyVjVIMjNWMUgxOVYySDVWMU01LDRIMTlWNUgyMFYxOUgxOVYyMEg1VjE5SDRWNUg1TTYsNlYxNEg5VjE4SDE4VjlIMTRWNk04LDhIMTJWMTJIOE0xNCwxMUgxNlYxNkgxMVYxNEgxNCIgLz48L3N2Zz4=", | ||
| "name": "StaticBatch3D", | ||
| "previewIconUrl": "https://resources.gdevelop-app.com/assets/Icons/group.svg", | ||
| "shortDescription": "Draw many 3D models that never move as a few meshes, to make scenery faster to draw.", | ||
| "version": "0.1.0", | ||
| "description": [ | ||
| "Scenery made of hundreds of 3D model instances (stands, boards, houses, rocks) costs one or more draw calls per instance, which is what slows down phones and older computers the most.", | ||
| "", | ||
| "The action \"Draw 3D models together\" merges the instances of the chosen objects into one mesh per material and hides them: the scenery looks the same and is drawn in a few draw calls.", | ||
| "", | ||
| "- Use it once, at the beginning of the scene, on objects that never move.", | ||
| "- Merged instances must not be moved, resized, hidden or shown after: the merged scenery would not follow.", | ||
| "- Optionally, the instances are deleted after being merged: they are still drawn but take no time at each frame. Use it for scenery that the events never use again (no collision, no picking).", | ||
| "- Models with an animation, morph targets or transparent materials are left as they are.", | ||
| "- The merged scenery is removed when the scene is unloaded." | ||
| ], | ||
| "origin": { | ||
| "identifier": "StaticBatch3D", | ||
| "name": "gdevelop-extension-store" | ||
| }, | ||
| "tags": [ | ||
| "3d", | ||
| "performance", | ||
| "batching", | ||
| "optimization", | ||
| "scenery", | ||
| "draw calls" | ||
| ], | ||
| "authorIds": [], | ||
| "dependencies": [], | ||
| "globalVariables": [], | ||
| "sceneVariables": [], | ||
| "eventsFunctions": [ | ||
| { | ||
| "fullName": "", | ||
| "functionType": "Action", | ||
| "name": "onSceneUnloading", | ||
| "sentence": "", | ||
| "events": [ | ||
| { | ||
| "type": "BuiltinCommonInstructions::JsCode", | ||
| "inlineCode": [ | ||
| "const batchesByScene = gdjs.__staticBatch3DExtension || (gdjs.__staticBatch3DExtension = new WeakMap());", | ||
| "for (const mesh of batchesByScene.get(runtimeScene) || []) {", | ||
| " mesh.removeFromParent();", | ||
| " mesh.geometry.dispose();", | ||
| " mesh.material.dispose();", | ||
| "}", | ||
| "batchesByScene.delete(runtimeScene);" | ||
| ], | ||
| "parameterObjects": "", | ||
| "useStrict": true, | ||
| "eventsSheetExpanded": false | ||
| } | ||
| ], | ||
| "parameters": [], | ||
| "objectGroups": [] | ||
| }, | ||
| { | ||
| "description": "Merge the 3D models of the instances into one mesh per material, and hide (or delete) the instances. To use once, on objects that never move. Models with animations or transparent materials are left as they are.", | ||
| "fullName": "Draw 3D models together", | ||
| "functionType": "Action", | ||
| "name": "MergeModels", | ||
| "sentence": "Draw the instances of _PARAM1_ together, as static scenery (delete the instances: _PARAM2_)", | ||
| "events": [ | ||
| { | ||
| "type": "BuiltinCommonInstructions::JsCode", | ||
| "inlineCode": [ | ||
| "const objects = eventsFunctionContext.getObjects(\"Objects\");", | ||
| "/** The merged meshes of each scene, to remove them when it is unloaded. */", | ||
| "const batchesByScene = gdjs.__staticBatch3DExtension || (gdjs.__staticBatch3DExtension = new WeakMap());", | ||
| "if (!batchesByScene.has(runtimeScene)) batchesByScene.set(runtimeScene, []);", | ||
| "const batches = batchesByScene.get(runtimeScene);", | ||
| "const textureKey = texture => (texture ? texture.uuid : \"\");", | ||
| "const materialKey = material => [", | ||
| " material.type, textureKey(material.map), textureKey(material.normalMap), textureKey(material.emissiveMap),", | ||
| " textureKey(material.roughnessMap), textureKey(material.metalnessMap), textureKey(material.aoMap), textureKey(material.envMap),", | ||
| " material.color ? material.color.getHex() : \"\", material.emissive ? material.emissive.getHex() : \"\", material.emissiveIntensity,", | ||
| " material.roughness, material.metalness, material.envMapIntensity, material.alphaTest, material.side, material.vertexColors, material.flatShading,", | ||
| "].join(\"|\");", | ||
| "const canBeMerged = mesh =>", | ||
| " !mesh.isSkinnedMesh && !mesh.isInstancedMesh && !Array.isArray(mesh.material) && !mesh.material.transparent &&", | ||
| " mesh.geometry.attributes.position && mesh.geometry.attributes.normal && Object.keys(mesh.geometry.morphAttributes).length === 0;", | ||
| "", | ||
| "const merged = [];", | ||
| "/** Meshes with the same material, layer and shadows, by key. */", | ||
| "const groups = new Map();", | ||
| "for (const object of objects) {", | ||
| " const model = object.get3DRendererObject();", | ||
| " if (!model || object.isHidden() || object.__isInStaticBatch) continue;", | ||
| " const meshes = [];", | ||
| " model.traverse(node => { if (node.isMesh && node.visible) meshes.push(node); });", | ||
| " // An object is merged whole or not at all: it is hidden after.", | ||
| " if (meshes.length === 0 || !meshes.every(canBeMerged)) continue;", | ||
| " const renderer = object.getRenderer();", | ||
| " renderer.updatePosition();", | ||
| " renderer.updateRotation();", | ||
| " renderer.updateSize();", | ||
| " model.updateWorldMatrix(true, true);", | ||
| " for (const mesh of meshes) {", | ||
| " const attributes = mesh.geometry.attributes;", | ||
| " const key = [", | ||
| " object.getLayer(), materialKey(mesh.material), mesh.castShadow, mesh.receiveShadow,", | ||
| " attributes.uv ? \"uv\" : \"\", attributes.color ? \"color\" + attributes.color.itemSize : \"\",", | ||
| " ].join(\"|\");", | ||
| " let group = groups.get(key);", | ||
| " if (!group) groups.set(key, (group = { layerName: object.getLayer(), meshes: [], vertexCount: 0, indexCount: 0 }));", | ||
| " group.meshes.push(mesh);", | ||
| " group.vertexCount += attributes.position.count;", | ||
| " group.indexCount += mesh.geometry.index ? mesh.geometry.index.count : attributes.position.count;", | ||
| " }", | ||
| " object.__isInStaticBatch = true;", | ||
| " merged.push(object);", | ||
| "}", | ||
| "", | ||
| "const vertex = new THREE.Vector3();", | ||
| "const matrix = new THREE.Matrix4();", | ||
| "const sceneInverse = new THREE.Matrix4();", | ||
| "const normalMatrix = new THREE.Matrix3();", | ||
| "for (const group of groups.values()) {", | ||
| " const first = group.meshes[0];", | ||
| " // The merged mesh is put in the 3D scene of the layer: vertices are in its coordinates.", | ||
| " const threeScene = runtimeScene.getLayer(group.layerName).getRenderer().getThreeScene();", | ||
| " threeScene.updateWorldMatrix(true, false);", | ||
| " sceneInverse.copy(threeScene.matrixWorld).invert();", | ||
| " const hasUv = !!first.geometry.attributes.uv;", | ||
| " const colorSize = first.geometry.attributes.color ? first.geometry.attributes.color.itemSize : 0;", | ||
| " const positions = new Float32Array(group.vertexCount * 3);", | ||
| " const normals = new Float32Array(group.vertexCount * 3);", | ||
| " const uvs = hasUv ? new Float32Array(group.vertexCount * 2) : null;", | ||
| " const colors = colorSize ? new Float32Array(group.vertexCount * colorSize) : null;", | ||
| " const indices = new Uint32Array(group.indexCount);", | ||
| " let vertexOffset = 0;", | ||
| " let indexOffset = 0;", | ||
| " for (const mesh of group.meshes) {", | ||
| " const { position, normal, uv, color } = mesh.geometry.attributes;", | ||
| " matrix.multiplyMatrices(sceneInverse, mesh.matrixWorld);", | ||
| " normalMatrix.getNormalMatrix(matrix);", | ||
| " for (let index = 0; index < position.count; index++) {", | ||
| " const target = vertexOffset + index;", | ||
| " vertex.fromBufferAttribute(position, index).applyMatrix4(matrix).toArray(positions, target * 3);", | ||
| " vertex.fromBufferAttribute(normal, index).applyMatrix3(normalMatrix).normalize().toArray(normals, target * 3);", | ||
| " if (uvs) { uvs[target * 2] = uv.getX(index); uvs[target * 2 + 1] = uv.getY(index); }", | ||
| " if (colors) for (let channel = 0; channel < colorSize; channel++) colors[target * colorSize + channel] = color.getComponent(index, channel);", | ||
| " }", | ||
| " // A mirrored object (the Y axis of the scene goes down) has its faces turned inside out.", | ||
| " const isMirrored = matrix.determinant() < 0;", | ||
| " const meshIndex = mesh.geometry.index;", | ||
| " const count = meshIndex ? meshIndex.count : position.count;", | ||
| " for (let corner = 0; corner + 2 < count; corner += 3) {", | ||
| " const a = meshIndex ? meshIndex.getX(corner) : corner;", | ||
| " const b = meshIndex ? meshIndex.getX(corner + 1) : corner + 1;", | ||
| " const c = meshIndex ? meshIndex.getX(corner + 2) : corner + 2;", | ||
| " indices[indexOffset + corner] = vertexOffset + a;", | ||
| " indices[indexOffset + corner + 1] = vertexOffset + (isMirrored ? c : b);", | ||
| " indices[indexOffset + corner + 2] = vertexOffset + (isMirrored ? b : c);", | ||
| " }", | ||
| " vertexOffset += position.count;", | ||
| " indexOffset += count;", | ||
| " }", | ||
| " const geometry = new THREE.BufferGeometry();", | ||
| " geometry.setAttribute(\"position\", new THREE.BufferAttribute(positions, 3));", | ||
| " geometry.setAttribute(\"normal\", new THREE.BufferAttribute(normals, 3));", | ||
| " if (uvs) geometry.setAttribute(\"uv\", new THREE.BufferAttribute(uvs, 2));", | ||
| " if (colors) geometry.setAttribute(\"color\", new THREE.BufferAttribute(colors, colorSize));", | ||
| " geometry.setIndex(new THREE.BufferAttribute(indices, 1));", | ||
| " geometry.computeBoundingSphere();", | ||
| " geometry.computeBoundingBox();", | ||
| " const merged = new THREE.Mesh(geometry, first.material.clone());", | ||
| " merged.name = \"StaticBatch\";", | ||
| " merged.castShadow = first.castShadow;", | ||
| " merged.receiveShadow = first.receiveShadow;", | ||
| " merged.matrixAutoUpdate = false;", | ||
| " threeScene.add(merged);", | ||
| " batches.push(merged);", | ||
| "}", | ||
| "// The objects are not drawn anymore: deleted, they also stop being processed at every frame.", | ||
| "const shouldDelete = eventsFunctionContext.getArgument(\"DeleteInstances\");", | ||
| "for (const object of merged) {", | ||
| " if (shouldDelete) object.deleteFromScene();", | ||
| " else object.hide(true);", | ||
| "}" | ||
| ], | ||
| "parameterObjects": "", | ||
| "useStrict": true, | ||
| "eventsSheetExpanded": false | ||
| } | ||
| ], | ||
| "parameters": [ | ||
| { | ||
| "description": "3D models", | ||
| "name": "Objects", | ||
| "supplementaryInformation": "Scene3D::Model3DObject", | ||
| "type": "objectList" | ||
| }, | ||
| { | ||
| "description": "Delete the instances after merging them", | ||
| "longDescription": "Deleted instances are still drawn, merged, but do not exist for the events anymore and take no time at each frame.", | ||
| "name": "DeleteInstances", | ||
| "type": "yesorno", | ||
| "defaultValue": "no", | ||
| "optional": true | ||
| } | ||
| ], | ||
| "objectGroups": [] | ||
| } | ||
| ], | ||
| "eventsBasedBehaviors": [], | ||
| "eventsBasedObjects": [] | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should that be true by default?