#Making a script to load materials based on distance to save memory?

11 messages · Page 1 of 1 (latest)

karmic gorge
#

Here's the script I have so far

extends MeshInstance3D
class_name wc_DBML

@export_group("Setup")
@export var camera: Camera3D

@export_group("Parameters")
enum detailLevel{l1=1, l2=2, l4=4, l8=8, l16=16, l32=32, l64=64, l128=128, l256=256, l512=512, l1024=1024, l2048=2048, l4096=4096, l8192=8192}
@export var maxDetail: detailLevel = detailLevel.l1024

@export_group("Mips")
@export var mat1: Material
@export var mat2: Material
@export var mat4: Material
@export var mat8: Material
@export var mat16: Material
@export var mat32: Material
@export var mat64: Material
@export var mat128: Material
@export var mat256: Material
@export var mat512: Material
@export var mat1024: Material
@export var mat2048: Material
@export var mat4096: Material
@export var mat8192: Material

var distanceFromCamera := 0.0
var log_dfc := 0.0
var floor_dfc := 0

func setVariables() -> void:
    distanceFromCamera = getDistanceFromCamera()
    log_dfc = pow(distanceFromCamera, 0.5)
    floor_dfc = floor(log_dfc)

func _physics_process( _delta: float ) -> void:
    setVariables()
    print(maxDetail)
    updateMaterial()

func getDistanceFromCamera() -> float:
    return (global_position - camera.global_position).length()

func getMaterialToLoad() -> Material:
    match(floor_dfc):
        1:
            return mat8192
        _:
            return mat1

func updateMaterial() -> void:
    set_surface_override_material(0, getMaterialToLoad())
#

Simplified explanation:

#

This script has a bunch of @export parameters containing the materials I will use, as well as parameters such as the camera location. Then it calculates the distance between the camera and the object, and tracks that in a var called distanceFromCamera. Then it gets turned into a logarithmic curve, and then that is sent into floor() to convert it to an int. This int is then used to switch between the surface material override on surface 0.

#

It doesn't seem to load and unload these assets as I want them to; instead it keeps all of them loaded at all times. I want them to be unloaded and unloaded based on whenever they are needed. Is that even possible? How can I do this?

#

I am new to loading resources at runtime so I’m sorry if this is a dumb question.

past ridge
#

you have them in the exported variables, so that keeps them loaded

#

you want them gone, you have to not keep them in a variable at all, but instead keep a path and load the path manually into memory when you want to use the material.

#

be warned, loading is not free (fairly obvious) and if the materials are using different shaders, switching materials can cause a hitch while the shader compiles.

karmic gorge
#

Can I keep the path in a string or something?

#

*An exported one

past ridge
#

yeah, you can keep the path in an exported string.