summaryrefslogtreecommitdiff
path: root/app/xlockmore/modes/swirl.c
blob: fca7c516f2f3f95eed3402060655f7b0304e057a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
/* -*- Mode: C; tab-width: 4 -*- */
/* swirl --- swirly patterns */

#if !defined( lint ) && !defined( SABER )
static const char sccsid[] = "@(#)swirl.c	5.09 2003/06/30 xlockmore";

#endif

/*-
 * Copyright (c) 1994 M.Dobie <mrd@ecs.soton.ac.uk>
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and that
 * both that copyright notice and this permission notice appear in
 * supporting documentation.
 *
 * This file is provided AS IS with no warranties of any kind.  The author
 * shall have no liability with respect to the infringement of copyrights,
 * trade secrets or any patents by this file or any part thereof.  In no
 * event will the author be liable for any lost revenue or profits or
 * other special, indirect and consequential damages.
 *
 * Revision History:
 * 30-Jun-2003: Changed writeable mode to be more consistent with
 *              xscreensaver's starfish, looks like I am not going to
 *              port the variable speed colormapping when done drawing.
 * 01-Nov-2000: Allocation checks
 * 13-May-1997: jwz@jwz.org: turned into a standalone program.
 * 21-Apr-1995: improved startup time for TrueColour displays
 *              (limited to 16bpp to save memory) S.Early <sde1000@cam.ac.uk>
 * 09-Jan-1995: fixed colour maps (more colourful) and the image now spirals
 *              outwards from the centre with a fixed number of points drawn
 *              every iteration. Thanks to M.Dobie <mrd@ecs.soton.ac.uk>.
 * 1994: written.   Copyright (c) 1994 M.Dobie <mrd@ecs.soton.ac.uk>
 *       based on original code by R.Taylor
 */

#ifdef STANDALONE
#define MODE_swirl
#define PROGCLASS "Swirl"
#define HACK_INIT init_swirl
#define HACK_DRAW draw_swirl
#define swirl_opts xlockmore_opts
#define DEFAULTS "*delay: 5000 \n" \
 "*count: 5 \n" \
 "*ncolors: 200 \n"
#define SMOOTH_COLORS
#define WRITABLE_COLORS
#include "xlockmore.h"		/* from the xscreensaver distribution */
#else /* !STANDALONE */
#include "xlock.h"		/* from the xlockmore distribution */
#include "color.h"
#endif /* !STANDALONE */

#ifdef MODE_swirl

#define DEF_CYCLE "True"

static Bool cycle_p;

static XrmOptionDescRec opts[] =
{
  {(char *) "-cycle", (char *) ".swirl.cycle", XrmoptionNoArg, (caddr_t) "on"},
  {(char *) "+cycle", (char *) ".swirl.cycle", XrmoptionNoArg, (caddr_t) "off"}
};

static argtype vars[] =
{
  {(void *) & cycle_p, (char *) "cycle", (char *) "Cycle", (char *) DEF_CYCLE, t_Bool}
};

static OptionStruct desc[] =
{
  {(char *) "-/+cycle", (char *) "turn on/off colour cycling"}
};

ModeSpecOpt swirl_opts =
{sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, desc};

#ifdef USE_MODULES
ModStruct   swirl_description =
{"swirl", "init_swirl", "draw_swirl", "release_swirl",
 "refresh_swirl", "init_swirl", (char *) NULL, &swirl_opts,
 5000, 5, 1, 1, 64, 1.0, "",
 "Shows animated swirling patterns", 0, NULL};

#endif

#include <time.h>

#define MASS            4	/* maximum mass of a knot */
#define MIN_RES         5	/* minimim resolution (>= MIN_RES) */
#define MAX_RES         1	/* maximum resolution (>0) */
#define TWO_PLANE_PCNT  30	/* probability for two plane mode (0-100) */
#define RESTART         2500	/* number of cycles before restart */
#define BATCH_DRAW      100	/* points to draw per iteration */

/* knot types */
typedef enum {
	NONE = 0,
	ORBIT = (1 << 0),
	WHEEL = (1 << 1),
	PICASSO = (1 << 2),
	RAY = (1 << 3),
	HOOK = (1 << 4),
	ALL = (1 << 5)
} KNOT_T;

/* a knot */
typedef struct Knot {
	int         x, y;	/* position */
	int         m;		/* mass */
	KNOT_T      t;		/* type in the first (or only) plane */
	KNOT_T      T;		/* type in second plane if there is one */
	int         M;		/* mass in second plane if there is one */
} KNOT     , *KNOT_P;

/* drawing direction */
typedef enum {
	DRAW_RIGHT, DRAW_DOWN, DRAW_LEFT, DRAW_UP
} DIR_T;

/****************************************************************/

/* data associated with a swirl window */
typedef struct swirl_data {
	/* window paramaters */
	int         width, height;	/* window size */
	int         depth;	/* depth */
	int         rdepth;	/* real depth (for XImage) */
	Visual     *visual;	/* visual */

	/* swirl drawing parameters */
	int         n_knots;	/* number of knots */
	KNOT_P      knots;	/* knot details */
	KNOT_T      knot_type;	/* general type of knots */
	int         resolution;	/* drawing resolution, 1..5 */
	int         max_resolution;	/* maximum resolution, MAX_RES */
	int         r;		/* pixel step */
	Bool        two_plane;	/* two plane mode? */
	Bool        first_plane;	/* doing first plane? */
	int         start_again;	/* when to restart */

	/* spiral drawing parameters */
	int         x, y;	/* current point */
	DIR_T       dir;	/* current direction */
	int         dir_todo, dir_done;		/* how many points in current direction? */
	int         batch_todo, batch_done;	/* how many points in this batch */
	Bool        started, drawing;	/* are we drawing? */
	Bool        off_screen;

	/* image stuff */
	XImage     *ximage;

	/* colours stuff */
	int         shift;	/* colourmap shift */
	int         dshift;	/* colourmap shift while drawing */
	unsigned int cur_color;
	GC          gc;
	Colormap    cmap;
	unsigned long blackpixel, whitepixel, fg, bg;
	int direction;
	XColor     *colors;
	int         ncolors;
	Bool        cycle_p, mono_p, no_colors, reverse;
	ModeInfo   *mi;
} swirlstruct;

/* an array of swirls for each screen */
static swirlstruct *swirls = (swirlstruct *) NULL;

/*-
   random_no

   Return a random integer between 0 and n inclusive

   -      n is the maximum number

   Returns a random integer */

static int
random_no(unsigned int n)
{
	return ((int) ((n + 1) * (double) LRAND() / MAXRAND));
}

/****************************************************************/

static void
free_swirl(Display *display, swirlstruct *sp)
{
  ModeInfo *mi = sp->mi;

	if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
		MI_WHITE_PIXEL(mi) = sp->whitepixel;
		MI_BLACK_PIXEL(mi) = sp->blackpixel;
#ifndef STANDALONE
		MI_FG_PIXEL(mi) = sp->fg;
		MI_BG_PIXEL(mi) = sp->bg;
#endif
		if (sp->colors != NULL) {
			if (sp->ncolors && !sp->no_colors)
				free_colors(display, sp->cmap, sp->colors,
					sp->ncolors);
			free(sp->colors);
			sp->colors = (XColor *) NULL;
		}
		if (sp->cmap != None) {
			XFreeColormap(display, sp->cmap);
			sp->cmap = None;
		}
	}
	if (sp->gc != None) {
		XFreeGC(display, sp->gc);
		sp->gc = None;
	}
	if (sp->ximage != None) {
		(void) XDestroyImage(sp->ximage);
		sp->ximage = None;
	}
	if (sp->knots != NULL) {
		free(sp->knots);
		sp->knots = (KNOT_P) NULL;
	}
}

#ifndef STANDALONE
extern char *background;
extern char *foreground;
#endif

/*-
   initialise_swirl

   Initialise all the swirl data

   -      swirl is the swirl data */

static void
initialise_swirl(swirlstruct *sp)
{
	sp->width = 0;	/* width and height of window */
	sp->height = 0;
	sp->depth = 1;
	sp->rdepth = 1;
	sp->visual = (Visual *) NULL;
	sp->resolution = MIN_RES + 1;	/* current resolution */
	sp->max_resolution = MAX_RES;	/* maximum resolution */
	sp->n_knots = 0;	/* number of knots */
	sp->knot_type = ALL;	/* general type of knots */
	sp->two_plane = False;	/* two plane mode? */
	sp->first_plane = False;	/* doing first plane? */
	sp->start_again = -1;	/* restart counter */

	/* drawing parameters */
	sp->x = 0;
	sp->y = 0;
	sp->started = False;
	sp->drawing = False;

	/* image stuff */
	sp->ximage = None;
}

/****************************************************************/

/*-
 * initialise_image
 *
 * Initialise the image for drawing to
 *
 * -      swirl is the swirl data
 */
static Bool
initialise_image(Display * dpy, swirlstruct *sp)
{
	unsigned int pad;
	int         bytes_per_line;
	int         image_depth = sp->rdepth;
	int         data_depth = image_depth;
	unsigned char *image;	/* image data */

	/* On SGIs at least, using an XImage of depth 24 on a Visual of depth 24
	 *  requires the XImage data to use 32 bits per pixel.  I don't understand
	 *  how one is supposed to determine this -- maybe XListPixmapFormats?
	 *  But on systems that don't work this way, allocating 32 bpp instead of
	 *  24 will be wasteful but non-fatal.  -- jwz, 16-May-97.
	 */
	if (data_depth >= 24 && data_depth < 32)
		data_depth = 32;

	/* get the bitmap pad */
	pad = BitmapPad(dpy);
	/* destroy the old image (destroy XImage and data) */
	if (sp->ximage != NULL)
		(void) XDestroyImage(sp->ximage);

	/* how many bytes per line? (bits rounded up to pad) */
	bytes_per_line = ((sp->width * data_depth + pad - 1) / pad) * (pad / 8);

	/* allocate space for the image */
	if ((image = (unsigned char *) calloc(bytes_per_line *
			sp->height, 1)) == NULL) {
		return False;
	}

	/* create an ximage with this */
	if ((sp->ximage = XCreateImage(dpy, sp->visual, image_depth, ZPixmap,
				     0, (char *) image, sp->width,
				     sp->height, pad, bytes_per_line)) == None) {
		free(image);
		return False;
	}
	return True;
}

/*-
 * create_knots
 *
 * Initialise the array of knot
 *
 * swirl is the swirl data
 */
static Bool
create_knots(swirlstruct *sp)
{
	int         k;
	Bool        orbit, wheel, picasso, ray, hook;
	KNOT_P      knot;

	/* create array for knots */
	if (sp->knots)
		free(sp->knots);
	if ((sp->knots = (KNOT_P) calloc(sp->n_knots,
			sizeof (KNOT))) == NULL) {
		return False;
	}

	/* no knots yet */
	orbit = wheel = picasso = ray = hook = False;

	/* what types do we have? */
	if ((int) sp->knot_type & (int) ALL) {
		orbit = wheel = ray = hook = True;
	} else {
		if ((int) sp->knot_type & (int) ORBIT)
			orbit = True;
		if ((int) sp->knot_type & (int) WHEEL)
			wheel = True;
		if ((int) sp->knot_type & (int) PICASSO)
			picasso = True;
		if ((int) sp->knot_type & (int) RAY)
			ray = True;
		if ((int) sp->knot_type & (int) HOOK)
			hook = True;
	}

	/* initialise each knot */
	knot = sp->knots;
	for (k = 0; k < sp->n_knots; k++) {
		/* position */
		knot->x = random_no((unsigned int) sp->width);
		knot->y = random_no((unsigned int) sp->height);

		/* mass */
		knot->m = random_no(MASS) + 1;

		/* can be negative */
		if (random_no(100) > 50)
			knot->m *= -1;

		/* type */
		knot->t = NONE;
		while (knot->t == NONE) {
			/* choose a random one from the types available */
			switch (random_no(4)) {
				case 0:
					if (orbit)
						knot->t = ORBIT;
					break;
				case 1:
					if (wheel)
						knot->t = WHEEL;
					break;
				case 2:
					if (picasso)
						knot->t = PICASSO;
					break;
				case 3:
					if (ray)
						knot->t = RAY;
					break;
				case 4:
					if (hook)
						knot->t = HOOK;
					break;
			}
		}

		/* if two planes, do same for second plane */
		if (sp->two_plane) {
			knot->T = NONE;
			while (knot->T == NONE || knot->T == knot->t) {
				/* choose a different type */
				switch (random_no(4)) {
					case 0:
						if (orbit)
							knot->T = ORBIT;
						break;
					case 1:
						if (wheel)
							knot->T = WHEEL;
						break;
					case 2:
						if (picasso)
							knot->T = PICASSO;
						break;
					case 3:
						if (ray)
							knot->T = RAY;
						break;
					case 4:
						if (hook)
							knot->T = HOOK;
						break;
				}
			}
		}
		/* next knot */
		knot++;
	}
	return True;
}

/****************************************************************/

/*-
 * do_point
 *
 * Work out the pixel value at i, j. Ensure it does not clash with BlackPixel
 * or WhitePixel.
 *
 * -      swirl is the swirl data
 * -      i, j is the point to calculate
 *
 * Returns the value of the point
 */
static unsigned long
do_point(swirlstruct *sp, int i, int j)
{
	int         tT, k, add, value;
	unsigned long colour_value;
	double      dx, dy, theta, dist;
	int         ncolours, qcolours;
	double      rads;
	KNOT_P      knot;
	ModeInfo   *mi = sp->mi;

	/* how many colours? */
	ncolours = sp->ncolors;
	qcolours = ncolours / 4;

	/* colour step round a circle */
	rads = (double) ncolours / (2.0 * M_PI);

	/* start at zero */
	value = 0;

	/* go through all the knots */
	knot = sp->knots;
	for (k = 0; k < sp->n_knots; k++) {
		dx = i - knot->x;
		dy = j - knot->y;

		/* in two_plane mode get the appropriate knot type */
		if (sp->two_plane)
			tT = (int) ((sp->first_plane) ? knot->t : knot->T);
		else
			tT = (int) knot->t;

		/* distance from knot */
		dist = sqrt(dx * dx + dy * dy);

		/* nothing to add at first */
		add = 0;

		/* work out the contribution (if close enough) */
		if (dist > 0.1)
			switch (tT) {
				case ORBIT:
					add = (int) (ncolours / (1.0 + 0.01 * abs(knot->m) * dist));
					break;
				case WHEEL:
					/* Avoid atan2: DOMAIN error message */
					if (dy == 0.0 && dx == 0.0)
						theta = 1.0;
					else
						theta = (atan2(dy, dx) + M_PI) / M_PI;
					if (theta < 1.0)
						add = (int) (ncolours * theta +
						  sin(0.1 * knot->m * dist) *
						qcolours * exp(-0.01 * dist));
					else
						add = (int) (ncolours * (theta - 1.0) +
						  sin(0.1 * knot->m * dist) *
						qcolours * exp(-0.01 * dist));
					break;
				case PICASSO:
					add = (int) (ncolours *
					  fabs(cos(0.002 * knot->m * dist)));
					break;
				case RAY:
					/* Avoid atan2: DOMAIN error message */
					if (dy == 0.0 && dx == 0.0)
						add = 0;
					else
						add = (int) (ncolours * fabs(sin(2.0 * atan2(dy, dx))));

					break;
				case HOOK:
					/* Avoid atan2: DOMAIN error message */
					if (dy == 0.0 && dx == 0.0)
						add = (int) (0.05 * (abs(knot->m) - 1) * dist);
					else
						add = (int) (rads * atan2(dy, dx) +
							     0.05 * (abs(knot->m) - 1) * dist);
					break;
			}
		/* for a positive mass add on the contribution else take it off */
		if (knot->m > 0)
			value += add;
		else
			value -= add;

		/* next knot */
		knot++;
	}

	/* toggle plane */
	sp->first_plane = (!sp->first_plane);

	if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
		if (ncolours < 2) {
			ncolours = 2;
		}
		/* make sure we handle negative values properly */
		if (value >= 0)
			colour_value = (value % ncolours) + 2;
		else
			colour_value = ncolours - (abs((int) value) % (ncolours - 1));

		/* definitely make sure it is in range */
		colour_value = colour_value % ncolours;

                if (sp->mono_p) {
                        return colour_value;
                } else {
                        return sp->colors[colour_value].pixel;
                }
        } else {
		if (value >= 0)
			colour_value = (value % MI_NPIXELS(mi)) + 2;
		else
			colour_value = MI_NPIXELS(mi) - (abs((int) value) % (MI_NPIXELS(mi) - 1));
		/* definitely make sure it is in range */
		colour_value = colour_value % MI_NPIXELS(mi);
                if (MI_NPIXELS(mi) > 2) {
                        return MI_PIXEL(mi, colour_value);
		} else if (colour_value % 2)
                        return MI_BLACK_PIXEL(mi);
                else
                        return MI_WHITE_PIXEL(mi);
        }
}

/****************************************************************/

/*-
 * draw_block
 *
 * Draw a square block of points with the same value.
 *
 * -      ximage is the XImage to draw on.
 * -      x, y is the top left corner
 * -      s is the length of each side
 * -      v is the value
 */
static void
draw_block(XImage * ximage, int x, int y, int s, unsigned long v)
{
	int         a, b;

	for (a = 0; a < s; a++)
		for (b = 0; b < s; b++) {
			XPutPixel(ximage, x + b, y + a, v);
		}
}

/****************************************************************/

/*-
 * draw_point  Draw the current point in a swirl pattern onto the XImage
 *
 * -    swirl is the swirl
 * -    win is the window to update
 */
static void
draw_point(ModeInfo * mi, swirlstruct *sp)
{
	int         r;
	int         x, y;

	/* get current point coordinates and resolution */
	x = sp->x;
	y = sp->y;
	r = sp->r;

	/* check we are within the window */
	if ((x < 0) || (x > sp->width - r) || (y < 0) || (y > sp->height - r))
		return;

	/* what style are we drawing? */
	if (sp->two_plane) {
		int         r2;

		/* halve the block size */
		r2 = r / 2;

		/* interleave blocks at half r */
		draw_block(sp->ximage, x, y, r2, do_point(sp, x, y));
		draw_block(sp->ximage, x + r2, y, r2, do_point(sp, x + r2, y));
		draw_block(sp->ximage, x + r2, y + r2, r2, do_point(sp,
							    x + r2, y + r2));
		draw_block(sp->ximage, x, y + r2, r2, do_point(sp, x, y + r2));
	} else
		draw_block(sp->ximage, x, y, r, do_point(sp, x, y));

	/* update the screen */
/*-
 * PURIFY 4.0.1 on SunOS4 and on Solaris 2 reports a 256 byte memory leak on
 * the next line. */
	(void) XPutImage(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi), sp->ximage,
			 x, y, x, y, r, r);
}

/****************************************************************/

/*-
 * next_point  Move to the next point in the spiral pattern
 *  -    swirl is the swirl
 *  -    win is the window to update
 */
static void
next_point(swirlstruct *sp)
{
	/* more to do in this direction? */
	if (sp->dir_done < sp->dir_todo) {
		/* move in the current direction */
		switch (sp->dir) {
			case DRAW_RIGHT:
				sp->x += sp->r;
				break;
			case DRAW_DOWN:
				sp->y += sp->r;
				break;
			case DRAW_LEFT:
				sp->x -= sp->r;
				break;
			case DRAW_UP:
				sp->y -= sp->r;
				break;
		}

		/* done another point */
		sp->dir_done++;
	} else {
		/* none drawn yet */
		sp->dir_done = 0;

		/* change direction - check and record if off screen */
		switch (sp->dir) {
			case DRAW_RIGHT:
				sp->dir = DRAW_DOWN;
				if (sp->x > sp->width - sp->r) {
					/* skip these points */
					sp->dir_done = sp->dir_todo;
					sp->y += (sp->dir_todo * sp->r);

					/* check for finish */
					if (sp->off_screen)
						sp->drawing = False;
					sp->off_screen = True;
				} else
					sp->off_screen = False;
				break;
			case DRAW_DOWN:
				sp->dir = DRAW_LEFT;
				sp->dir_todo++;
				if (sp->y > sp->height - sp->r) {
					/* skip these points */
					sp->dir_done = sp->dir_todo;
					sp->x -= (sp->dir_todo * sp->r);

					/* check for finish */
					if (sp->off_screen)
						sp->drawing = False;
					sp->off_screen = True;
				} else
					sp->off_screen = False;
				break;
			case DRAW_LEFT:
				sp->dir = DRAW_UP;
				if (sp->x < 0) {
					/* skip these points */
					sp->dir_done = sp->dir_todo;
					sp->y -= (sp->dir_todo * sp->r);

					/* check for finish */
					if (sp->off_screen)
						sp->drawing = False;
					sp->off_screen = True;
				} else
					sp->off_screen = False;
				break;
			case DRAW_UP:
				sp->dir = DRAW_RIGHT;
				sp->dir_todo++;
				if (sp->y < 0) {
					/* skip these points */
					sp->dir_done = sp->dir_todo;
					sp->x += (sp->dir_todo * sp->r);

					/* check for finish */
					if (sp->off_screen)
						sp->drawing = False;
					sp->off_screen = True;
				} else
					sp->off_screen = False;
				break;
		}
	}
}

/****************************************************************/

/*-
 * init_swirl
 *
 * Initialise things for swirling
 *
 * -      win is the window to draw in
 */
void
init_swirl(ModeInfo * mi)
{
	Display    *display = MI_DISPLAY(mi);
	Window      window = MI_WINDOW(mi);
	swirlstruct *sp;

	/* does the swirls array exist? */
	if (swirls == NULL) {
		int         i;

		/* allocate an array, one entry for each screen */
		if ((swirls = (swirlstruct *) calloc(MI_NUM_SCREENS(mi),
				sizeof (swirlstruct))) == NULL)
			return;

		/* initialise them all */
		for (i = 0; i < MI_NUM_SCREENS(mi); i++)
			initialise_swirl(&swirls[i]);
	}
	/* get a pointer to this swirl */
	sp = &(swirls[MI_SCREEN(mi)]);
	sp->mi = mi;

	/* get window parameters */
	sp->width = MI_WIDTH(mi);
	sp->height = MI_HEIGHT(mi);
	sp->depth = MI_DEPTH(mi);
	sp->rdepth = sp->depth;
	sp->visual = MI_VISUAL(mi);

	if (sp->depth > 16)
		sp->depth = 16;

	/* initialise image for speeding up drawing */
	if (!initialise_image(display, sp)) {
		free_swirl(display, sp);
		return;
	}
	MI_CLEARWINDOW(mi);

	if (!sp->gc) {
		if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
			XColor      color;

#ifndef STANDALONE
			sp->fg = MI_FG_PIXEL(mi);
			sp->bg = MI_BG_PIXEL(mi);
#endif
			sp->blackpixel = MI_BLACK_PIXEL(mi);
			sp->whitepixel = MI_WHITE_PIXEL(mi);
			if ((sp->cmap = XCreateColormap(display, window,
					MI_VISUAL(mi), AllocNone)) == None) {
				free_swirl(display, sp);
				return;
			}
			XSetWindowColormap(display, window, sp->cmap);
			(void) XParseColor(display, sp->cmap, "black", &color);
			(void) XAllocColor(display, sp->cmap, &color);
			MI_BLACK_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, sp->cmap, "white", &color);
			(void) XAllocColor(display, sp->cmap, &color);
			MI_WHITE_PIXEL(mi) = color.pixel;
#ifndef STANDALONE
			(void) XParseColor(display, sp->cmap, background, &color);
			(void) XAllocColor(display, sp->cmap, &color);
			MI_BG_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, sp->cmap, foreground, &color);
			(void) XAllocColor(display, sp->cmap, &color);
			MI_FG_PIXEL(mi) = color.pixel;
#endif
			sp->colors = (XColor *) NULL;
			sp->ncolors = 0;
		}
		if ((sp->gc = XCreateGC(display, MI_WINDOW(mi),
			     (unsigned long) 0, (XGCValues *) NULL)) == None) {
			free_swirl(display, sp);
			return;
		}
	}
	MI_CLEARWINDOW(mi);

  /* Set up colour map */
  sp->direction = (LRAND() & 1) ? 1 : -1;
  if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
    if (sp->colors != NULL) {
      if (sp->ncolors && !sp->no_colors)
        free_colors(display, sp->cmap, sp->colors, sp->ncolors);
      free(sp->colors);
      sp->colors = (XColor *) NULL;
    }
    sp->ncolors = MI_NCOLORS(mi);
    if (sp->ncolors < 2)
      sp->ncolors = 2;
    if (sp->ncolors <= 2)
      sp->mono_p = True;
    else
      sp->mono_p = False;

    if (sp->mono_p)
      sp->colors = (XColor *) NULL;
    else
      if ((sp->colors = (XColor *) malloc(sizeof (*sp->colors) *
          (sp->ncolors + 1))) == NULL) {
        free_swirl(display, sp);
        return;
      }
    sp->cycle_p = has_writable_cells(mi);
    if (sp->cycle_p) {
      if (MI_IS_FULLRANDOM(mi)) {
        if (!NRAND(8))
          sp->cycle_p = False;
        else
          sp->cycle_p = True;
      } else {
        sp->cycle_p = cycle_p;
      }
    }
    if (!sp->mono_p) {
      if (!(LRAND() % 10))
        make_random_colormap(
#if STANDALONE
            display, MI_WINDOW(mi),
#else
            mi,
#endif
              sp->cmap, sp->colors, &sp->ncolors,
              True, True, &sp->cycle_p);
      else if (!(LRAND() % 2))
        make_uniform_colormap(
#if STANDALONE
            display, MI_WINDOW(mi),
#else
            mi,
#endif
                  sp->cmap, sp->colors, &sp->ncolors,
                  True, &sp->cycle_p);
      else
        make_smooth_colormap(
#if STANDALONE
            display, MI_WINDOW(mi),
#else
            mi,
#endif
                 sp->cmap, sp->colors, &sp->ncolors,
                 True, &sp->cycle_p);
    }
    XInstallColormap(display, sp->cmap);
    if (sp->ncolors < 2) {
      sp->ncolors = 2;
      sp->no_colors = True;
    } else
      sp->no_colors = False;
    if (sp->ncolors <= 2)
      sp->mono_p = True;

    if (sp->mono_p)
      sp->cycle_p = False;

  }
  if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
                if (sp->mono_p) {
			sp->cur_color = MI_BLACK_PIXEL(mi);
		}
  }

	/* resolution starts off chunky */
	sp->resolution = MIN_RES + 1;

	/* calculate the pixel step for this resulution */
	sp->r = (1 << (sp->resolution - 1));

	/* how many knots? */
	sp->n_knots = random_no((unsigned int) MI_COUNT(mi) / 2) +
		MI_COUNT(mi) + 1;

	/* what type of knots? */
	sp->knot_type = ALL;	/* for now */

	/* use two_plane mode occaisionally */
	if (random_no(100) <= TWO_PLANE_PCNT) {
		sp->two_plane = sp->first_plane = True;
		sp->max_resolution = 2;
	} else
		sp->two_plane = False;

	/* fix the knot values */
	if (!create_knots(sp)) {
		free_swirl(display, sp);
		return;
	}

	/* we are off */
	sp->started = True;
	sp->drawing = False;
}

/****************************************************************/

/*-
 * draw_swirl
 *
 * Draw one iteration of swirling
 *
 * -      win is the window to draw in
 */
void
draw_swirl(ModeInfo * mi)
{
	swirlstruct *sp;

	if (swirls == NULL)
		return;
	sp = &(swirls[MI_SCREEN(mi)]);
	if (sp->knots == NULL)
		return;

	MI_IS_DRAWN(mi) = True;

	/* are we going? */
	if (sp->started) {
		/* in the middle of drawing? */
		if (sp->drawing) {
		  if(sp->cycle_p) {
		 rotate_colors(MI_DISPLAY(mi), sp->cmap, sp->colors, sp->ncolors, sp->direction);
		    if (!(LRAND() % 1000))
      sp->direction = -sp->direction;
                 }
			/* draw a batch of points */
			sp->batch_todo = BATCH_DRAW;
			while ((sp->batch_todo > 0) && sp->drawing) {
				/* draw a point */
				draw_point(mi, sp);

				/* move to the next point */
				next_point(sp);

				/* done a point */
				sp->batch_todo--;
			}
		} else {
		  if(sp->cycle_p) {
		 rotate_colors(MI_DISPLAY(mi), sp->cmap, sp->colors, sp->ncolors, sp->direction);
		    if (!(LRAND() % 1000))
      sp->direction = -sp->direction;
                 }

			/* time for a higher resolution? */
			if (sp->resolution > sp->max_resolution) {
				/* move to higher resolution */
				sp->resolution--;

				/* calculate the pixel step for this resulution */
				sp->r = (1 << (sp->resolution - 1));

				/* start drawing again */
				sp->drawing = True;

				/* start in the middle of the screen */
				sp->x = (sp->width - sp->r) / 2;
				sp->y = (sp->height - sp->r) / 2;

				/* initialise spiral drawing parameters */
				sp->dir = DRAW_RIGHT;
				sp->dir_todo = 1;
				sp->dir_done = 0;
			} else {
				/* all done, decide when to restart */
				if (sp->start_again == -1) {
					/* start the counter */
					sp->start_again = RESTART;
				} else if (sp->start_again == 0) {
					/* reset the counter */
					sp->start_again = -1;

					/* start again */
					init_swirl(mi);
				} else
					/* decrement the counter */
					sp->start_again--;
			}
		}
	}
}

/****************************************************************/

void
release_swirl(ModeInfo * mi)
{
	/* does the swirls array exist? */
	if (swirls != NULL) {
		int         screen;

		/* free them all */
		for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++)
			free_swirl(MI_DISPLAY(mi), &swirls[screen]);
		/* deallocate an array, one entry for each screen */
		free(swirls);
		swirls = (swirlstruct *) NULL;
	}
}

/****************************************************************/

void
refresh_swirl(ModeInfo * mi)
{
	swirlstruct *sp;

	if (swirls == NULL)
		return;
	sp = &swirls[MI_SCREEN(mi)];

	if (sp->started) {
		MI_CLEARWINDOW(mi);
		if (sp->drawing)
			sp->resolution = sp->resolution + 1;
		sp->drawing = False;
	}
}

#endif /* MODE_swirl */