Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

Fix error handling for negative values in RandomPCG::rand_weighted

Cyklon_3000f80a9820afa4
diff --git a/core/math/random_pcg.cpp b/core/math/random_pcg.cpp
index 3f40c0084e0..51ce7b3a267 100644
--- a/core/math/random_pcg.cpp
+++ b/core/math/random_pcg.cpp
@@ -49,6 +49,7 @@ int64_t RandomPCG::rand_weighted(const Vector<float> &p_weights) {
const float *weights = p_weights.ptr();
float weights_sum = 0.0;
for (int64_t i = 0; i < weights_size; ++i) {
+ ERR_FAIL_COND_V_MSG(weights[i] < 0.0, -1, vformat("Weight array contains the negative value %f at index %d.", weights[i], i));
weights_sum += weights[i];
}
diff --git a/doc/classes/RandomNumberGenerator.xml b/doc/classes/RandomNumberGenerator.xml
index 7fd3cd4bb10..8a48cc1920b 100644
--- a/doc/classes/RandomNumberGenerator.xml
+++ b/doc/classes/RandomNumberGenerator.xml
@@ -21,9 +21,9 @@
<return type="int" />
<param index="0" name="weights" type="PackedFloat32Array" />
<description>
- Returns a random integer between [code]0[/code] and the size of the array that is passed as a parameter. Each value in the array should be a floating-point number that represents the relative likelihood that it will be returned as an index. A higher value means the value is more likely to be returned as an index, while a value of [code]0[/code] means it will never be returned as an index.
+ Returns a random integer between [code]0[/code] and the size of the array that is passed as a parameter. Each value in the array should be a non-negative floating-point number that represents the relative likelihood that it will be returned as an index. A higher value means the value is more likely to be returned as an index, while a value of [code]0[/code] means it will never be returned as an index.
For example, if [code skip-lint][0.5, 1, 1, 2][/code] is passed as a parameter, then the method is twice as likely to return [code]3[/code] (the index of the value [code]2[/code]) and twice as unlikely to return [code]0[/code] (the index of the value [code]0.5[/code]) compared to the indices [code]1[/code] and [code]2[/code].
- Prints an error and returns [code]-1[/code] if the array is empty.
+ Prints an error and returns [code]-1[/code] if the array is empty or contains any negative values.
[codeblocks]
[gdscript]
var rng = RandomNumberGenerator.new()