Clean up and improve group behaviors' code

The first pass was somewhat obtuse and lacked a common class that
differentiated them from behaviors that didn't use Proximities.
This commit is contained in:
Francois Belair 2020-01-10 12:15:50 -05:00
parent 780e6038b8
commit a01f5d5b2e
13 changed files with 110 additions and 85 deletions

View File

@ -19,7 +19,7 @@ _global_script_classes=[ {
"language": "GDScript", "language": "GDScript",
"path": "res://src/behaviors/GSTArrive.gd" "path": "res://src/behaviors/GSTArrive.gd"
}, { }, {
"base": "GSTSteeringBehavior", "base": "GSTGroupBehavior",
"class": "GSTAvoidCollisions", "class": "GSTAvoidCollisions",
"language": "GDScript", "language": "GDScript",
"path": "res://src/behaviors/GSTAvoidCollisions.gd" "path": "res://src/behaviors/GSTAvoidCollisions.gd"
@ -29,7 +29,7 @@ _global_script_classes=[ {
"language": "GDScript", "language": "GDScript",
"path": "res://src/behaviors/GSTBlend.gd" "path": "res://src/behaviors/GSTBlend.gd"
}, { }, {
"base": "GSTSteeringBehavior", "base": "GSTGroupBehavior",
"class": "GSTCohesion", "class": "GSTCohesion",
"language": "GDScript", "language": "GDScript",
"path": "res://src/behaviors/GSTCohesion.gd" "path": "res://src/behaviors/GSTCohesion.gd"
@ -54,6 +54,11 @@ _global_script_classes=[ {
"language": "GDScript", "language": "GDScript",
"path": "res://src/behaviors/GSTFollowPath.gd" "path": "res://src/behaviors/GSTFollowPath.gd"
}, { }, {
"base": "GSTSteeringBehavior",
"class": "GSTGroupBehavior",
"language": "GDScript",
"path": "res://src/GSTGroupBehavior.gd"
}, {
"base": "GSTProximity", "base": "GSTProximity",
"class": "GSTInfiniteProximity", "class": "GSTInfiniteProximity",
"language": "GDScript", "language": "GDScript",
@ -99,7 +104,7 @@ _global_script_classes=[ {
"language": "GDScript", "language": "GDScript",
"path": "res://src/behaviors/GSTSeek.gd" "path": "res://src/behaviors/GSTSeek.gd"
}, { }, {
"base": "GSTSteeringBehavior", "base": "GSTGroupBehavior",
"class": "GSTSeparation", "class": "GSTSeparation",
"language": "GDScript", "language": "GDScript",
"path": "res://src/behaviors/GSTSeparation.gd" "path": "res://src/behaviors/GSTSeparation.gd"
@ -120,9 +125,9 @@ _global_script_classes=[ {
"path": "res://src/GSTTargetAcceleration.gd" "path": "res://src/GSTTargetAcceleration.gd"
}, { }, {
"base": "Reference", "base": "Reference",
"class": "Utils", "class": "GSTUtils",
"language": "GDScript", "language": "GDScript",
"path": "res://src/Utils.gd" "path": "res://src/GSTUtils.gd"
} ] } ]
_global_script_class_icons={ _global_script_class_icons={
"GSTAgentLocation": "", "GSTAgentLocation": "",
@ -134,6 +139,7 @@ _global_script_class_icons={
"GSTFace": "", "GSTFace": "",
"GSTFlee": "", "GSTFlee": "",
"GSTFollowPath": "", "GSTFollowPath": "",
"GSTGroupBehavior": "",
"GSTInfiniteProximity": "", "GSTInfiniteProximity": "",
"GSTLookWhereYouGo": "", "GSTLookWhereYouGo": "",
"GSTMatchOrientation": "", "GSTMatchOrientation": "",
@ -147,7 +153,7 @@ _global_script_class_icons={
"GSTSteeringAgent": "", "GSTSteeringAgent": "",
"GSTSteeringBehavior": "", "GSTSteeringBehavior": "",
"GSTTargetAcceleration": "", "GSTTargetAcceleration": "",
"Utils": "" "GSTUtils": ""
} }
[application] [application]

View File

@ -0,0 +1,16 @@
extends GSTSteeringBehavior
class_name GSTGroupBehavior
# Extended behavior that features a Proximity group for group-based behaviors.
var proximity: GSTProximity
var _callback: = funcref(self, "report_neighbor")
func _init(agent: GSTSteeringAgent, proximity: GSTProximity).(agent) -> void:
self.proximity = proximity
func report_neighbor(neighbor: GSTSteeringAgent) -> bool:
return false

View File

@ -1,60 +1,69 @@
extends Reference extends Reference
class_name GSTPath class_name GSTPath
# Represents a path made up of Vector3 waypoints, split into path segments for use by path
# following algorithms.
# # Keeping it updated requires calling `create_path` to update the path.
var segments: Array var open: bool
var is_open: bool
var path_length: float var path_length: float
var nearest_point_on_segment: Vector3 var _segments: Array
var nearest_point_on_path: Vector3
var _nearest_point_on_segment: Vector3
var _nearest_point_on_path: Vector3
func _init(waypoints: Array, is_open: = false) -> void: func _init(waypoints: Array, is_open: = false) -> void:
self.is_open = is_open self.is_open = is_open
_create_path(waypoints) create_path(waypoints)
nearest_point_on_segment = waypoints[0] _nearest_point_on_segment = waypoints[0]
nearest_point_on_path = waypoints[0] _nearest_point_on_path = waypoints[0]
func get_start_point() -> Vector3: func create_path(waypoints: Array) -> void:
return segments.front().begin if not waypoints or waypoints.size() < 2:
printerr("Waypoints cannot be null and must contain at least two (2) waypoints.")
_segments = []
path_length = 0
var current: Vector3 = _segments[0]
var previous: Vector3
func get_end_point() -> Vector3: for i in range(1, waypoints.size(), 1):
return segments.back().end previous = current
if i < waypoints.size():
current = waypoints[i]
func calculate_point_segment_distance_squared(a: Vector3, b: Vector3, c: Vector3) -> float: elif open:
nearest_point_on_segment = a break
var ab: = b - a else:
var ab_length_squared: = ab.length_squared() current = waypoints[0]
if ab_length_squared != 0: var segment: = GSTSegment.new(previous, current)
var t = (c - a).dot(ab) / ab_length_squared path_length += segment.length
nearest_point_on_segment += ab * clamp(t, 0, 1) segment.cumulative_length = path_length
_segments.append(segment)
return nearest_point_on_segment.distance_squared_to(c)
func calculate_distance(agent_current_position: Vector3, path_parameter: Dictionary) -> float: func calculate_distance(agent_current_position: Vector3, path_parameter: Dictionary) -> float:
var smallest_distance_squared: float = INF var smallest_distance_squared: float = INF
var nearest_segment: GSTSegment var nearest_segment: GSTSegment
for i in range(segments.size()): for i in range(_segments.size()):
var segment: GSTSegment = segments[i] var segment: GSTSegment = _segments[i]
var distance_squared: = calculate_point_segment_distance_squared( var distance_squared: = _calculate_point_segment_distance_squared(
segment.begin, segment.begin,
segment.end, segment.end,
agent_current_position) agent_current_position)
if distance_squared < smallest_distance_squared: if distance_squared < smallest_distance_squared:
nearest_point_on_path = nearest_point_on_segment _nearest_point_on_path = _nearest_point_on_segment
smallest_distance_squared = distance_squared smallest_distance_squared = distance_squared
nearest_segment = segment nearest_segment = segment
path_parameter.segment_index = i path_parameter.segment_index = i
var length_on_path: = ( var length_on_path: = (
nearest_segment.cumulative_length - nearest_segment.cumulative_length -
nearest_point_on_path.distance_to(nearest_segment.end)) _nearest_point_on_path.distance_to(nearest_segment.end))
path_parameter.distance = length_on_path path_parameter.distance = length_on_path
@ -62,7 +71,7 @@ func calculate_distance(agent_current_position: Vector3, path_parameter: Diction
func calculate_target_position(param: Dictionary, target_distance: float) -> Vector3: func calculate_target_position(param: Dictionary, target_distance: float) -> Vector3:
if is_open: if open:
target_distance = clamp(target_distance, 0, path_length) target_distance = clamp(target_distance, 0, path_length)
else: else:
if target_distance < 0: if target_distance < 0:
@ -71,8 +80,8 @@ func calculate_target_position(param: Dictionary, target_distance: float) -> Vec
target_distance = fmod(target_distance, path_length) target_distance = fmod(target_distance, path_length)
var desired_segment: GSTSegment var desired_segment: GSTSegment
for i in range(segments.size()): for i in range(_segments.size()):
var segment: GSTSegment = segments[i] var segment: GSTSegment = _segments[i]
if segment.cumulative_length >= target_distance: if segment.cumulative_length >= target_distance:
desired_segment = segment desired_segment = segment
break break
@ -84,27 +93,23 @@ func calculate_target_position(param: Dictionary, target_distance: float) -> Vec
(distance / desired_segment.length) + desired_segment.end) (distance / desired_segment.length) + desired_segment.end)
func _create_path(waypoints: Array) -> void: func get_start_point() -> Vector3:
if not waypoints or waypoints.size() < 2: return _segments.front().begin
printerr("Waypoints cannot be null and must contain at least two (2) waypoints.")
segments = []
path_length = 0
var current: Vector3 = segments[0]
var previous: Vector3
for i in range(1, waypoints.size(), 1): func get_end_point() -> Vector3:
previous = current return _segments.back().end
if i < waypoints.size():
current = waypoints[i]
elif is_open: func _calculate_point_segment_distance_squared(start: Vector3, end: Vector3, position: Vector3) -> float:
break _nearest_point_on_segment = start
else: var start_end: = end - start
current = waypoints[0] var start_end_length_squared: = start_end.length_squared()
var segment: = GSTSegment.new(previous, current) if start_end_length_squared != 0:
path_length += segment.length var t = (position - start).dot(start_end) / start_end_length_squared
segment.cumulative_length = path_length _nearest_point_on_segment += start_end * clamp(t, 0, 1)
segments.append(segment)
return _nearest_point_on_segment.distance_squared_to(position)
class GSTSegment: class GSTSegment:

View File

@ -1,6 +1,6 @@
extends GSTAgentLocation extends GSTAgentLocation
class_name GSTSteeringAgent class_name GSTSteeringAgent
# Extended agent data type that adds velocity and speed data. # Extended agent data type that adds velocity, speed, and size data
var zero_linear_speed_threshold: = 0.01 var zero_linear_speed_threshold: = 0.01

View File

@ -1,4 +1,4 @@
class_name Utils class_name GSTUtils
# Useful math and utility functions to complement Godot's own. # Useful math and utility functions to complement Godot's own.

View File

@ -30,7 +30,7 @@ func _arrive(acceleration: GSTTargetAcceleration, target_position: Vector3) -> G
desired_velocity = (desired_velocity - agent.linear_velocity) * 1.0 / time_to_reach desired_velocity = (desired_velocity - agent.linear_velocity) * 1.0 / time_to_reach
acceleration.linear = Utils.clampedv3(desired_velocity, agent.max_linear_acceleration) acceleration.linear = GSTUtils.clampedv3(desired_velocity, agent.max_linear_acceleration)
acceleration.angular = 0 acceleration.angular = 0
return acceleration return acceleration

View File

@ -1,9 +1,8 @@
extends GSTSteeringBehavior extends GSTGroupBehavior
class_name GSTAvoidCollisions class_name GSTAvoidCollisions
# Behavior that steers the agent to avoid obstacles lying in its path, approximated by a sphere. # Behavior that steers the agent to avoid obstacles lying in its path, approximated by a sphere.
var proximity: GSTProximity
var first_neighbor: GSTSteeringAgent var first_neighbor: GSTSteeringAgent
var shortest_time: float var shortest_time: float
var first_minimum_separation: float var first_minimum_separation: float
@ -12,8 +11,8 @@ var first_relative_position: Vector3
var first_relative_velocity: Vector3 var first_relative_velocity: Vector3
func _init(agent: GSTSteeringAgent, proximity: GSTProximity).(agent) -> void: func _init(agent: GSTSteeringAgent, proximity: GSTProximity).(agent, proximity) -> void:
self.proximity = proximity pass
func _calculate_steering(acceleration: GSTTargetAcceleration) -> GSTTargetAcceleration: func _calculate_steering(acceleration: GSTTargetAcceleration) -> GSTTargetAcceleration:
@ -22,7 +21,7 @@ func _calculate_steering(acceleration: GSTTargetAcceleration) -> GSTTargetAccele
first_minimum_separation = 0 first_minimum_separation = 0
first_distance = 0 first_distance = 0
var neighbor_count: = proximity.find_neighbors(funcref(self, "_report_neighbor")) var neighbor_count: = proximity.find_neighbors(_callback)
if neighbor_count == 0 or not first_neighbor: if neighbor_count == 0 or not first_neighbor:
acceleration.set_zero() acceleration.set_zero()
@ -39,7 +38,7 @@ func _calculate_steering(acceleration: GSTTargetAcceleration) -> GSTTargetAccele
return acceleration return acceleration
func _report_neighbor(neighbor: GSTSteeringAgent) -> bool: func report_neighbor(neighbor: GSTSteeringAgent) -> bool:
var relative_position: = neighbor.position - agent.position var relative_position: = neighbor.position - agent.position
var relative_velocity: = neighbor.linear_velocity - agent.linear_velocity var relative_velocity: = neighbor.linear_velocity - agent.linear_velocity
var relative_speed_squared: = relative_velocity.length_squared() var relative_speed_squared: = relative_velocity.length_squared()

View File

@ -38,7 +38,7 @@ func _calculate_steering(blended_accel: GSTTargetAcceleration) -> GSTTargetAccel
blended_accel.add_scaled_accel(_accel, bw.weight) blended_accel.add_scaled_accel(_accel, bw.weight)
blended_accel.linear = Utils.clampedv3(blended_accel.linear, agent.max_linear_acceleration) blended_accel.linear = GSTUtils.clampedv3(blended_accel.linear, agent.max_linear_acceleration)
blended_accel.angular = min(blended_accel.angular, agent.max_angular_acceleration) blended_accel.angular = min(blended_accel.angular, agent.max_angular_acceleration)
return blended_accel return blended_accel

View File

@ -1,27 +1,26 @@
extends GSTSteeringBehavior extends GSTGroupBehavior
class_name GSTCohesion class_name GSTCohesion
# Group behavior that produces linear acceleration that attempts to move the agent towards the # Group behavior that produces linear acceleration that attempts to move the agent towards the
# center of mass of the agents in the area defined by the defined Proximity. # center of mass of the agents in the area defined by the defined Proximity.
var center_of_mass: Vector3 var center_of_mass: Vector3
var proximity: GSTProximity
func _init(agent: GSTSteeringAgent, proximity: GSTProximity).(agent) -> void: func _init(agent: GSTSteeringAgent, proximity: GSTProximity).(agent, proximity) -> void:
self.proximity = proximity pass
func _calculate_steering(acceleration: GSTTargetAcceleration) -> GSTTargetAcceleration: func _calculate_steering(acceleration: GSTTargetAcceleration) -> GSTTargetAcceleration:
acceleration.set_zero() acceleration.set_zero()
center_of_mass = Vector3.ZERO center_of_mass = Vector3.ZERO
var neighbor_count = proximity.find_neighbors(funcref(self, "_report_neighbor")) var neighbor_count = proximity.find_neighbors(_callback)
if neighbor_count > 0: if neighbor_count > 0:
center_of_mass *= 1.0 / neighbor_count center_of_mass *= 1.0 / neighbor_count
acceleration.linear = (center_of_mass - agent.position).normalized() * agent.max_linear_acceleration acceleration.linear = (center_of_mass - agent.position).normalized() * agent.max_linear_acceleration
return acceleration return acceleration
func _report_neighbor(neighbor: GSTSteeringAgent) -> bool: func report_neighbor(neighbor: GSTSteeringAgent) -> bool:
center_of_mass += neighbor.position center_of_mass += neighbor.position
return true return true

View File

@ -1,4 +1,4 @@
extends GSTSteeringBehavior extends GSTGroupBehavior
class_name GSTSeparation class_name GSTSeparation
# Group behavior that produces acceleration repelling from the other neighbors that are in the # Group behavior that produces acceleration repelling from the other neighbors that are in the
# immediate area defined by the given `GSTProximity`. # immediate area defined by the given `GSTProximity`.
@ -11,21 +11,20 @@ class_name GSTSeparation
var decay_coefficient: = 1.0 var decay_coefficient: = 1.0
var acceleration: GSTTargetAcceleration var acceleration: GSTTargetAcceleration
var proximity: GSTProximity
func _init(agent: GSTSteeringAgent, proximity: GSTProximity).(agent) -> void: func _init(agent: GSTSteeringAgent, proximity: GSTProximity).(agent, proximity) -> void:
self.proximity = proximity pass
func _calculate_steering(acceleration: GSTTargetAcceleration) -> GSTTargetAcceleration: func _calculate_steering(acceleration: GSTTargetAcceleration) -> GSTTargetAcceleration:
acceleration.set_zero() acceleration.set_zero()
self.acceleration = acceleration self.acceleration = acceleration
proximity.find_neighbors(funcref(self, "_report_neighbor")) proximity.find_neighbors(_callback)
return acceleration return acceleration
func _report_neighbor(neighbor: GSTSteeringAgent) -> bool: func report_neighbor(neighbor: GSTSteeringAgent) -> bool:
var to_agent: = agent.position - neighbor.position var to_agent: = agent.position - neighbor.position
var distance_squared: = to_agent.length_squared() var distance_squared: = to_agent.length_squared()

View File

@ -1,6 +1,6 @@
extends GSTProximity extends GSTProximity
class_name GSTInfiniteProximity class_name GSTInfiniteProximity
# Specifies any agent that is in the specified list as being neighbors with the owner agent. # Determines any agent that is in the specified list as being neighbors with the owner agent.
func _init(agent: GSTSteeringAgent, agents: Array).(agent, agents) -> void: func _init(agent: GSTSteeringAgent, agents: Array).(agent, agents) -> void:

View File

@ -1,6 +1,7 @@
extends Reference extends Reference
class_name GSTProximity class_name GSTProximity
# Defines an area that is used by group behaviors to find and process the owner's neighbors. # Defines a way to determine any agent that is in the specified list as being neighbors with the
# owner agent.
var agent: GSTSteeringAgent var agent: GSTSteeringAgent

View File

@ -1,7 +1,7 @@
extends GSTProximity extends GSTProximity
class_name GSTRadiusProximity class_name GSTRadiusProximity
# Specifies any agent that is in the specified list as being neighbors with the owner agent if they # Determines any agent that is in the specified list as being neighbors with the owner agent if
# lie within the specified radius. # they lie within the specified radius.
var radius: = 0.0 var radius: = 0.0
@ -34,7 +34,7 @@ func find_neighbors(callback: FuncRef) -> int:
var range_to: = radius + current_agent.bounding_radius var range_to: = radius + current_agent.bounding_radius
if distance_squared < range_to * range_to: if distance_squared < range_to * range_to:
if callback.call_func(current_agent) == true: if callback.call_func(current_agent):
current_agent.tagged = true current_agent.tagged = true
neighbor_count += 1 neighbor_count += 1
continue continue
@ -45,7 +45,7 @@ func find_neighbors(callback: FuncRef) -> int:
var current_agent = agents[i] as GSTSteeringAgent var current_agent = agents[i] as GSTSteeringAgent
if current_agent != agent and current_agent.tagged: if current_agent != agent and current_agent.tagged:
if callback.call_func(current_agent) == true: if callback.call_func(current_agent):
neighbor_count += 1 neighbor_count += 1
return neighbor_count return neighbor_count