|
| 1 | +# SPDX-FileCopyrightText: The Threadbare Authors |
| 2 | +# SPDX-License-Identifier: MPL-2.0 |
| 3 | +@tool |
| 4 | +class_name Flower |
| 5 | +extends Decoration |
| 6 | +## A decoration which deterministically picks its texture from a hardcoded list of directories. |
| 7 | +## |
| 8 | +## The goal here is to be able to add new flowers to a flowerbed in Fray's End by adding a file to |
| 9 | +## the repository, without touching any scene in a conflict-prone way. |
| 10 | + |
| 11 | +const TEXTURE_DIRECTORIES := [ |
| 12 | + "res://scenes/game_elements/props/decoration/crochenthemum/", |
| 13 | + "res://scenes/game_elements/props/decoration/mushroom/", |
| 14 | + "res://scenes/game_elements/props/decoration/flower/assets/", |
| 15 | +] |
| 16 | +static var _textures: Array[Texture2D] |
| 17 | + |
| 18 | + |
| 19 | +static func _load_textures_from(directory_path: String) -> void: |
| 20 | + var files := ResourceLoader.list_directory(directory_path) |
| 21 | + files.sort() |
| 22 | + for file: String in files: |
| 23 | + var path := directory_path.path_join(file) |
| 24 | + var resource := ResourceLoader.load(path) |
| 25 | + if resource is Texture2D: |
| 26 | + _textures.append(resource) |
| 27 | + else: |
| 28 | + push_warning("%s is not a Texture2D" % path) |
| 29 | + |
| 30 | + |
| 31 | +# Initialises the static _textures list, if not already done |
| 32 | +static func _initialise_textures() -> void: |
| 33 | + if _textures: |
| 34 | + return |
| 35 | + |
| 36 | + for directory_path: String in TEXTURE_DIRECTORIES: |
| 37 | + _load_textures_from(directory_path) |
| 38 | + |
| 39 | + |
| 40 | +func _validate_property(property: Dictionary) -> void: |
| 41 | + if property.name == "texture": |
| 42 | + # Prevent modifying texture property in inspector: it would be re-set next time the scene |
| 43 | + # loads. |
| 44 | + property.usage |= PROPERTY_USAGE_READ_ONLY |
| 45 | + property.usage |= PROPERTY_USAGE_NO_INSTANCE_STATE |
| 46 | + |
| 47 | + # Don't store the texture in the scene file: it would be overwritten when new flower images |
| 48 | + # are added. |
| 49 | + property.usage &= ~PROPERTY_USAGE_STORAGE |
| 50 | + |
| 51 | + |
| 52 | +func _init() -> void: |
| 53 | + _initialise_textures() |
| 54 | + |
| 55 | + |
| 56 | +func _enter_tree() -> void: |
| 57 | + # Assign a texture to this instance of the flower, in a fashion that is deterministic so long |
| 58 | + # as the set of flowers does not change. |
| 59 | + var tree := get_tree() |
| 60 | + var current_scene := tree.edited_scene_root if Engine.is_editor_hint() else tree.current_scene |
| 61 | + |
| 62 | + # Don't save a texture in flower.tscn's Sprite2D |
| 63 | + if Engine.is_editor_hint() and self == current_scene: |
| 64 | + return |
| 65 | + |
| 66 | + var path := current_scene.get_path_to(self) |
| 67 | + texture = _textures[path.hash() % _textures.size()] |
0 commit comments