Elite on the BBC Micro

# Drawing lines: LOIN (Part 3 of 7) (Disc version)

```       Name: LOIN (Part 3 of 7)                                [View in context]
Type: Subroutine                                       [Compare versions]
Category: Drawing lines
Summary: Draw a shallow line going right and up or left and down
Deep dive: Bresenham's line algorithm

This routine draws a line from (X1, Y1) to (X2, Y2). It has multiple stages.
If we get here, then:

* The line is going right and up (no swap) or left and down (swap)

* X1 < X2 and Y1-1 > Y2

* Draw from (X1, Y1) at bottom left to (X2, Y2) at top right

LDA SWAP               \ If SWAP > 0 then we swapped the coordinates above, so
BNE LI6                \ jump down to LI6 to skip plotting the first pixel

DEX                    \ Decrement the counter in X because we're about to plot
\ the first pixel

.LIL2

\ We now loop along the line from left to right, using X
\ as a decreasing counter, and at each count we plot a
\ single pixel using the pixel mask in R

LDA R                  \ Fetch the pixel byte from R

EOR (SC),Y             \ Store R into screen memory at SC(1 0), using EOR
STA (SC),Y             \ logic so it merges with whatever is already on-screen

.LI6

LSR R                  \ Shift the single pixel in R to the right to step along
\ the x-axis, so the next pixel we plot will be at the
\ next x-coordinate along

BCC LI7                \ If the pixel didn't fall out of the right end of R

ROR R                  \ Otherwise we need to move over to the next character
\ block, so first rotate R right so the set C flag goes
\ back into the left end, giving %10000000

LDA SC                 \ Add 8 to SC, so SC(1 0) now points to the next
ADC #8                 \ character along to the right
STA SC

.LI7

LDA S                  \ Set S = S + Q to update the slope error
STA S

DEY                    \ Otherwise we just overflowed, so decrement Y to move
\ to the pixel line above

BPL LIC2               \ If Y is positive we are still within the same

DEC SCH                \ Otherwise we need to move up into the character block
LDY #7                 \ above, so decrement the high byte of the screen
\ address and set the pixel line to the last line in
\ that character block

.LIC2

DEX                    \ Decrement the counter in X

BNE LIL2               \ If we haven't yet reached the right end of the line,
\ loop back to LIL2 to plot the next pixel along

LDY YSAV               \ Restore Y from YSAV, so that it's preserved

RTS                    \ Return from the subroutine
```