SCRMaps
/
Sign in

Angles, distances and binary search

The functions for working with coordinates, and the search you do not have to write yourself.

9 min read

As soon as you can read a unit's coordinates you need angles and distances - which way to send something, how far apart two units are. All of it already exists as functions.

The coordinate toolkit
atan2(y, x)Angle from coordinates, 0 to 360 - the mathematical convention, so zero is three o'clock.
atan2_256(y, x)The same in 256 directions, matching the unit's own facing byte: 0 is twelve o'clock, 64 three, 128 six, 192 nine.
lengthdir(length, angle)x and y from an angle and a length - the inverse of atan2. There is a _256 pair too.
sqrt(n)Square root, truncated. A distance is sqrt(x*x + y*y).
pow(x, y)A power. Folds to a constant at compile time when both arguments are constants.
div(a, b)Returns the quotient and the remainder together - and it is unsigned division, so it cannot take a negative. See below.

Division needs care. div is unsigned and the documentation says so - "supports only positive integers". Give it something that can go negative, such as a difference of coordinates, and you get a wrong number rather than an error. Three signed divisions were added in 0.9.9.8, and on negatives they disagree with each other.

What each of the three makes of div(17, -3)
div_towards_zero-5 and 2. Rounds towards zero, like C or JavaScript.
div_floor-6 and -1. Rounds towards negative infinity - the mathematical modulo.
div_euclid-5 and 2. The remainder is always between 0 and |b|.

If the remainder becomes an array index or a slot number, use div_euclid: it is the only one that cannot hand you a negative. For "every N pixels" where coordinates fall on both sides of a reference point, div_floor. And when both values really are unsigned - memory, counters, ids - plain div is correct and cheapest.

atan2_256 changed behaviour in euddraft 0.9.9.8. The official example checks atan2_256(10, 10) >= 90 once to work out which side of that it is on and swaps the argument order accordingly. If you lift someone's code and your angles are ninety degrees out, this is why.

Binary search is the more interesting one. When a condition only answers true or false but you need a number - how many units are in a location - people write code that narrows it a bit at a time. There is already a function for that.

function helperFunc(x) {
    const location = getcurpl() + ($L("P1 Area") + 1);
    return l2v(Bring(P8, AtLeast, x, "Men", location));
}
// 조건을 만족하는 가장 큰 x = 그 로케이션의 유닛 수
const count = EUDBinaryMax(helperFunc, 0, 200);
EUDBinaryMax finds the largest x for which cond(x) holds; EUDBinaryMin the smallest.

Narrowing the range is not free of consequence. The default is 0 to 0xFFFFFFFF, so for something with a known ceiling like a unit count, pass that ceiling - it takes the search from 32 steps down to about 8.