Skip to content
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

weighted random selector/sequence #206

Merged
merged 7 commits into from
Aug 21, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions addons/beehave/nodes/composites/randomized_composite.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
@tool
class_name RandomizedComposite extends Composite

const WEIGHTS_PREFIX = "Weights/"

## Sets a predicable seed
@export var random_seed: int = 0:
set(rs):
random_seed = rs
if random_seed != 0:
seed(random_seed)
else:
randomize()

## Wether to use weights for every child or not.
@export var use_weights: bool:
set(value):
use_weights = value
if use_weights and Engine.is_editor_hint():
_update_weights(get_children())
_connect_children_changing_signals()
notify_property_list_changed()

var _weights: Dictionary


func _ready():
_connect_children_changing_signals()


func _connect_children_changing_signals():
if not child_entered_tree.is_connected(_on_child_entered_tree):
child_entered_tree.connect(_on_child_entered_tree)

if not child_exiting_tree.is_connected(_on_child_exiting_tree):
child_exiting_tree.connect(_on_child_exiting_tree)


func get_shuffled_children() -> Array[Node]:
var children_bag: Array[Node] = get_children().duplicate()
if use_weights:
var weights: Array[int]
weights.assign(children_bag.map(func (child): return _weights[child.name]))
children_bag.assign(_weighted_shuffle(children_bag, weights))
else:
children_bag.shuffle()
return children_bag


## Returns a shuffled version of a given array using the supplied array of weights.
## Think of weights as the chance of a given item being the first in the array.
func _weighted_shuffle(items: Array, weights: Array[int]) -> Array:
if len(items) != len(weights):
push_error("items and weights size mismatch: expected %d weights, got %d instead." % [len(items), len(weights)])
return items

# This method is based on the weighted random sampling algorithm
# by Efraimidis, Spirakis; 2005. This runs in O(n log(n)).

# For each index, it will calculate random_value^(1/weight).
var chance_calc = func(i): return [i, randf() ** (1.0 / weights[i])]
var random_distribuition = range(len(items)).map(chance_calc)

# Now we just have to order by the calculated value, descending.
random_distribuition.sort_custom(func(a, b): return a[1] > b[1])

return random_distribuition.map(func(dist): return items[dist[0]])


func _get_property_list():
var properties = []

if use_weights:
for key in _weights.keys():
properties.append({
"name": WEIGHTS_PREFIX + key,
"type": TYPE_INT,
"usage": PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_EDITOR,
"hint": PROPERTY_HINT_RANGE,
"hint_string": "1,100"
})

return properties


func _set(property: StringName, value: Variant) -> bool:
if property.begins_with(WEIGHTS_PREFIX):
var weight_name = property.trim_prefix(WEIGHTS_PREFIX)
_weights[weight_name] = value
return true

return false


func _get(property: StringName):
if property.begins_with(WEIGHTS_PREFIX):
var weight_name = property.trim_prefix(WEIGHTS_PREFIX)
return _weights[weight_name]

return null


func _update_weights(children: Array[Node]) -> void:
var new_weights = {}
for c in children:
if _weights.has(c.name):
new_weights[c.name] = _weights[c.name]
else:
new_weights[c.name] = 1
_weights = new_weights
notify_property_list_changed()


func _on_child_entered_tree(node: Node):
_update_weights(get_children())

if not node.renamed.is_connected(_on_child_renamed):
node.renamed.connect(_on_child_renamed)


func _on_child_exiting_tree(node: Node):
var children = get_children()
children.erase(node)
_update_weights(children)


func _on_child_renamed():
_update_weights(get_children())


func get_class_name() -> Array[StringName]:
var classes := super()
classes.push_back(&"RandomizedComposite")
return classes
18 changes: 4 additions & 14 deletions addons/beehave/nodes/composites/selector_random.gd
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,18 @@
## will be executed in a random order.
@tool
@icon("../../icons/selector_random.svg")
class_name SelectorRandomComposite extends Composite

## Sets a predicable seed
@export var random_seed:int = 0:
set(rs):
random_seed = rs
if random_seed != 0:
seed(random_seed)
else:
randomize()

class_name SelectorRandomComposite extends RandomizedComposite

## A shuffled list of the children that will be executed in reverse order.
var _children_bag: Array[Node] = []
var c: Node

func _ready() -> void:
super()
if random_seed == 0:
randomize()


func tick(actor: Node, blackboard: Blackboard) -> int:
if _children_bag.is_empty():
_reset()
Expand Down Expand Up @@ -76,10 +68,8 @@ func _get_reversed_indexes() -> Array[int]:
return reversed


## Generates a new shuffled list of the children.
func _reset() -> void:
_children_bag = get_children().duplicate()
_children_bag.shuffle()
_children_bag = get_shuffled_children()


func get_class_name() -> Array[StringName]:
Expand Down
19 changes: 7 additions & 12 deletions addons/beehave/nodes/composites/sequence_random.gd
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,23 @@
## will be executed in a random order.
@tool
@icon("../../icons/sequence_random.svg")
class_name SequenceRandomComposite extends Composite
class_name SequenceRandomComposite extends RandomizedComposite


signal reseted(new_order)
lostptr marked this conversation as resolved.
Show resolved Hide resolved

## Whether the sequence should start where it left off after a previous failure.
@export var resume_on_failure: bool = false
## Whether the sequence should start where it left off after a previous interruption.
@export var resume_on_interrupt: bool = false
## Sets a predicable seed
@export var random_seed: int = 0:
set(rs):
random_seed = rs
if random_seed != 0:
seed(random_seed)
else:
randomize()

## A shuffled list of the children that will be executed in reverse order.
var _children_bag: Array[Node] = []
var c: Node


func _ready() -> void:
super()
if random_seed == 0:
randomize()

Expand Down Expand Up @@ -84,13 +79,13 @@ func _get_reversed_indexes() -> Array[int]:
return reversed


## Generates a new shuffled list of the children.
func _reset() -> void:
_children_bag = get_children().duplicate()
_children_bag.shuffle()
_children_bag = get_shuffled_children()
reseted.emit(_children_bag)


func get_class_name() -> Array[StringName]:
var classes := super()
classes.push_back(&"SequenceRandomComposite")
return classes

22 changes: 22 additions & 0 deletions node_2d.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
extends Node2D

var results: Dictionary

var times_reseted: int = 0

@onready var label: Label = $Label

func _on_sequence_random_composite_reseted(new_order):
times_reseted += 1
var first = new_order[0]
if not results.has(first.name):
results[first.name] = 0
results[first.name] += 1
_update_label()

func _update_label():
var text = "resets: %d\n" % times_reseted
for node in results.keys():
var perc = float(results[node]) / float(times_reseted) * 100.0
text += "%s: %.2f%%\n" % [node, perc]
label.text = text
38 changes: 38 additions & 0 deletions node_2d.tscn
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
[gd_scene load_steps=5 format=3 uid="uid://qjpfc7lbb2a1"]

[ext_resource type="Script" path="res://node_2d.gd" id="1_bh4q4"]
[ext_resource type="Script" path="res://addons/beehave/nodes/beehave_tree.gd" id="1_ktxiv"]
[ext_resource type="Script" path="res://addons/beehave/nodes/composites/sequence_random.gd" id="2_gocxx"]
[ext_resource type="Script" path="res://test/actions/mock_action.gd" id="3_qrq84"]

[node name="Node2D" type="Node2D"]
script = ExtResource("1_bh4q4")

[node name="Label" type="Label" parent="."]
offset_right = 40.0
offset_bottom = 23.0

[node name="BeehaveTree" type="Node" parent="."]
script = ExtResource("1_ktxiv")

[node name="SequenceRandomComposite" type="Node" parent="BeehaveTree"]
script = ExtResource("2_gocxx")
use_weights = true
Weights/First = 40
Weights/Second = 30
Weights/Third = 15
Weights/Forth = 15

[node name="First" type="Node" parent="BeehaveTree/SequenceRandomComposite"]
script = ExtResource("3_qrq84")

[node name="Second" type="Node" parent="BeehaveTree/SequenceRandomComposite"]
script = ExtResource("3_qrq84")

[node name="Third" type="Node" parent="BeehaveTree/SequenceRandomComposite"]
script = ExtResource("3_qrq84")

[node name="Forth" type="Node" parent="BeehaveTree/SequenceRandomComposite"]
script = ExtResource("3_qrq84")

[connection signal="reseted" from="BeehaveTree/SequenceRandomComposite" to="." method="_on_sequence_random_composite_reseted"]
Loading