Skip to content

Commit

Permalink
Fixed edge cases of nearest_po2 function
Browse files Browse the repository at this point in the history
  • Loading branch information
MewPurPur committed Jan 26, 2023
1 parent 10d22a4 commit 3ac5603
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
12 changes: 11 additions & 1 deletion core/variant/variant_utility.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,17 @@ struct VariantUtilityFunctions {
}

static inline int64_t nearest_po2(int64_t x) {
return nearest_power_of_2_templated(uint64_t(x));
if (x <= 1) {
return 1;
}
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
return ++x;
}

// Random
Expand Down
7 changes: 2 additions & 5 deletions doc/classes/@GlobalScope.xml
Original file line number Diff line number Diff line change
Expand Up @@ -692,17 +692,14 @@
<return type="int" />
<param index="0" name="value" type="int" />
<description>
Returns the nearest equal or larger power of 2 for the integer [param value].
Returns the smallest power of 2 that is equal to or larger than [param value].
In other words, returns the smallest value [code]a[/code] where [code]a = pow(2, n)[/code] such that [code]value &lt;= a[/code] for some non-negative integer [code]n[/code].
[codeblock]
nearest_po2(3) # Returns 4
nearest_po2(4) # Returns 4
nearest_po2(5) # Returns 8

nearest_po2(0) # Returns 0 (this may not be expected)
nearest_po2(-1) # Returns 0 (this may not be expected)
nearest_po2(0) # Returns 1
[/codeblock]
[b]Warning:[/b] Due to the way it is implemented, this function returns [code]0[/code] rather than [code]1[/code] for negative values of [param value] (in reality, 1 is the smallest integer power of 2).
</description>
</method>
<method name="pingpong">
Expand Down
3 changes: 3 additions & 0 deletions modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,9 @@ public static real_t MoveToward(real_t from, real_t to, real_t delta)
/// <returns>The nearest larger power of 2.</returns>
public static int NearestPo2(int value)
{
if (value <= 1)
return 1;

value--;
value |= value >> 1;
value |= value >> 2;
Expand Down

0 comments on commit 3ac5603

Please sign in to comment.