mirror of
git://git.tartarus.org/simon/puzzles.git
synced 2025-04-21 08:01:30 -07:00
Galaxies: avoid division by zero in draw_arrow().
During an interactive drag of an arrow, it's possible to put the mouse pointer precisely on the pixel the arrow is pointing at. When that happens, draw_arrow computes the zero-length vector from the pointer to the target pixel, and tries to normalise it to unit length by dividing by its length. Of course, this leads to computing 0/0 = NaN. Depending on the platform, this can cause different effects. Conversion of a floating-point NaN to an integer is not specified by IEEE 754; on some platforms (e.g. Arm) it comes out as 0, and on others (e.g. x86), INT_MIN. If the conversion delivers INT_MIN, one possible effect is that the arrow is drawn as an immensely long diagonal line, pointing upwards and leftwards from the target point. To add to the confusion, that line would not immediately appear on the display in full, because of the draw_update system. But further dragging-around of arrows will gradually reveal it as draw_update rectangles intersect the corrupted display area. However, that diagonal line need not show up at all, because once draw_arrow has accidentally computed a lot of values in the region of INT_MIN, it then adds them together, causing signed integer overflow (i.e. undefined behaviour) to confuse matters further! In fact, this diagonal-line drawing artefact has only been observed on the WebAssembly front end. The x86 desktop platforms might very plausibly have done it too, but in fact they didn't (I'm guessing because of this UB issue, or else some kind of clipping inside the graphics library), which is how we haven't found this bug until now. Having found it, however, the fix is simple. If asked to draw an arrow from a point to itself, take an early return from draw_arrow before dividing by zero, and don't draw anything at all.
This commit is contained in:
@ -3159,7 +3159,10 @@ static void game_free_drawstate(drawing *dr, game_drawstate *ds)
|
|||||||
static void draw_arrow(drawing *dr, game_drawstate *ds,
|
static void draw_arrow(drawing *dr, game_drawstate *ds,
|
||||||
int cx, int cy, int ddx, int ddy, int col)
|
int cx, int cy, int ddx, int ddy, int col)
|
||||||
{
|
{
|
||||||
float vlen = (float)sqrt(ddx*ddx+ddy*ddy);
|
int sqdist = ddx*ddx+ddy*ddy;
|
||||||
|
if (sqdist == 0)
|
||||||
|
return; /* avoid division by zero */
|
||||||
|
float vlen = (float)sqrt(sqdist);
|
||||||
float xdx = ddx/vlen, xdy = ddy/vlen;
|
float xdx = ddx/vlen, xdy = ddy/vlen;
|
||||||
float ydx = -xdy, ydy = xdx;
|
float ydx = -xdy, ydy = xdx;
|
||||||
int e1x = cx + (int)(xdx*TILE_SIZE/3), e1y = cy + (int)(xdy*TILE_SIZE/3);
|
int e1x = cx + (int)(xdx*TILE_SIZE/3), e1y = cy + (int)(xdy*TILE_SIZE/3);
|
||||||
|
Reference in New Issue
Block a user