/** Rainbow.irx                 **/
/** usage: RAINBOW order        **/
/** example: RAINBOW 1          **/
/**                             **/
/** Draw a diagram illustrating **/
/** how light refracted and     **/
/** reflected by a water drop   **/
/** produces a rainbow.         **/
/** 'order' is the number of    **/
/** internal reflections in the **/
/** water drop considered.      **/


OPTIONS FAILAT 20
SIGNAL ON FAILURE

ARG order .
ADDRESS "ICAD"
IF order = "?" THEN
    DO
    '*message usage: RAINBOW order'
    RETURN
    END

NUMERIC DIGITS 6
IF order = "" THEN order = 1
IF order < 1 THEN order = 1
length = 3*order+20

'/option/slide'
'0 0!'
'[340 200]!'

'/color/13'
'/draw/circle'
'0 0!'
'0 1!'

'/draw/line'
'/color/13'
xinit = -30
xinit '0!'
'0 0!!'

PI = 3.1415926
NO = 1      /* index of refraction of air */
NI = 1.3    /* index of refraction of scatterer */
NI_inc = .01 /* change in index of refraction of scatterer with color */
color.1 = 7; color.2 = 10; color.3 = 5
color.4 = 9; color.5 = 11; color.6 = 6

orderp1 = order+1
DO cnum = 1 to 6
    N_ratio = NO / NI
    DO b=.01 TO .99 BY .01
        thetaOUT = ASIN(b); thetaIN = ASIN(N_ratio*b)
        alpha = PI - 2 * thetaIN; phi = -PI + thetaOUT
        x.0 = COS(phi); y.0 = -SIN(phi);
        DO ord = 1 TO orderp1
            phi = phi + alpha
            x.ord = COS(phi); y.ord = -SIN(phi);
        END
        tmp = phi + thetaOUT
        xend = x.orderp1 + length*COS(tmp)
        yend = y.orderp1 - length*SIN(tmp)

        '/draw/line'
        '/color/13'

        xinit b'!'
        x.0 y.0'!!'

        tmp = -b;   xinit tmp'!'
        tmp = -y.0; x.0 tmp'!!'

        '/Color/'color.cnum
        DO ord = 1 TO orderp1
            x.ord y.ord'!'
        END
        xend yend'!!'

        DO ord = 1 TO orderp1
            tmp = -y.ord; x.ord tmp'!'
        END
        tmp = -yend; xend tmp'!!'

    END
    NI = NI + NI_inc
END

'/color/13'
'/draw/circle'
'0 0!'
'0 1!'
RETURN

failure:
	EXIT 20
