v09i057: xwater - a simple but fun simulation of water, Part01/01
Michael Frank
mpf at portia.stanford.edu
Fri Sep 28 12:19:27 AEST 1990
Submitted-by: Michael Frank <mpf at portia.stanford.edu>
Posting-number: Volume 9, Issue 57
Archive-name: xwater/part01
This program simulates a bunch of water drops or "molecules" flowing
around through a display of pixels that the user can turn on and off.
The algorithm is very simple but has some interesting emergent
properties. I first implemented this algorithm in assembler years ago
on a TRS-80 Color Computer.
The xwindows code is based on the "xskel" program by Mark Moraes.
Thanks, Mark, for an excellent beginners' framework.
This is my first real distribution of a program on the net, so please
politely inform me if I did anything wrong!
, , __ mpf at portia.stanford.edu...this...
/|/| . _ |_ _ _ | |_ _ _ ,_ |, mpf at sunset.ai.sri.com.....space..
/ | | | (_ | | (_| (-' | | | (_| | | |\ mpf at csli.stanford.edu.....for....
"Be excellent to each other." -Bill&Ted (415) 497-4182............rent...
---------------------------- CUT HERE -----------------------------------------
#! /bin/sh
# This is a shell archive. Remove anything before this line, then unpack
# it by saving it into a file and typing "sh file". To overwrite existing
# files, type "sh file -c". You can also feed this as standard input via
# unshar, or by typing "sh <file", e.g.. If this archive is complete, you
# will see the following message at the end:
# "End of shell archive."
# Contents: COPYING.GNU COPYRIGHT COPYRIGHT.xskel Imakefile README
# README.xskel runimake xwater.c
# Wrapped by mpf at elaine1.stanford.edu on Mon Sep 24 22:14:20 1990
PATH=/bin:/usr/bin:/usr/ucb ; export PATH
if test -f 'COPYING.GNU' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'COPYING.GNU'\"
else
echo shar: Extracting \"'COPYING.GNU'\" \(12488 characters\)
sed "s/^X//" >'COPYING.GNU' <<'END_OF_FILE'
X
X GNU GENERAL PUBLIC LICENSE
X Version 1, February 1989
X
X Copyright (C) 1989 Free Software Foundation, Inc.
X 675 Mass Ave, Cambridge, MA 02139, USA
X Everyone is permitted to copy and distribute verbatim copies
X of this license document, but changing it is not allowed.
X
X Preamble
X
X The license agreements of most software companies try to keep users
Xat the mercy of those companies. By contrast, our General Public
XLicense is intended to guarantee your freedom to share and change free
Xsoftware--to make sure the software is free for all its users. The
XGeneral Public License applies to the Free Software Foundation's
Xsoftware and to any other program whose authors commit to using it.
XYou can use it for your programs, too.
X
X When we speak of free software, we are referring to freedom, not
Xprice. Specifically, the General Public License is designed to make
Xsure that you have the freedom to give away or sell copies of free
Xsoftware, that you receive source code or can get it if you want it,
Xthat you can change the software or use pieces of it in new free
Xprograms; and that you know you can do these things.
X
X To protect your rights, we need to make restrictions that forbid
Xanyone to deny you these rights or to ask you to surrender the rights.
XThese restrictions translate to certain responsibilities for you if you
Xdistribute copies of the software, or if you modify it.
X
X For example, if you distribute copies of a such a program, whether
Xgratis or for a fee, you must give the recipients all the rights that
Xyou have. You must make sure that they, too, receive or can get the
Xsource code. And you must tell them their rights.
X
X We protect your rights with two steps: (1) copyright the software, and
X(2) offer you this license which gives you legal permission to copy,
Xdistribute and/or modify the software.
X
X Also, for each author's protection and ours, we want to make certain
Xthat everyone understands that there is no warranty for this free
Xsoftware. If the software is modified by someone else and passed on, we
Xwant its recipients to know that what they have is not the original, so
Xthat any problems introduced by others will not reflect on the original
Xauthors' reputations.
X
X The precise terms and conditions for copying, distribution and
Xmodification follow.
X
X GNU GENERAL PUBLIC LICENSE
X TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
X
X 0. This License Agreement applies to any program or other work which
Xcontains a notice placed by the copyright holder saying it may be
Xdistributed under the terms of this General Public License. The
X"Program", below, refers to any such program or work, and a "work based
Xon the Program" means either the Program or any work containing the
XProgram or a portion of it, either verbatim or with modifications. Each
Xlicensee is addressed as "you".
X
X 1. You may copy and distribute verbatim copies of the Program's source
Xcode as you receive it, in any medium, provided that you conspicuously and
Xappropriately publish on each copy an appropriate copyright notice and
Xdisclaimer of warranty; keep intact all the notices that refer to this
XGeneral Public License and to the absence of any warranty; and give any
Xother recipients of the Program a copy of this General Public License
Xalong with the Program. You may charge a fee for the physical act of
Xtransferring a copy.
X
X 2. You may modify your copy or copies of the Program or any portion of
Xit, and copy and distribute such modifications under the terms of Paragraph
X1 above, provided that you also do the following:
X
X a) cause the modified files to carry prominent notices stating that
X you changed the files and the date of any change; and
X
X b) cause the whole of any work that you distribute or publish, that
X in whole or in part contains the Program or any part thereof, either
X with or without modifications, to be licensed at no charge to all
X third parties under the terms of this General Public License (except
X that you may choose to grant warranty protection to some or all
X third parties, at your option).
X
X c) If the modified program normally reads commands interactively when
X run, you must cause it, when started running for such interactive use
X in the simplest and most usual way, to print or display an
X announcement including an appropriate copyright notice and a notice
X that there is no warranty (or else, saying that you provide a
X warranty) and that users may redistribute the program under these
X conditions, and telling the user how to view a copy of this General
X Public License.
X
X d) You may charge a fee for the physical act of transferring a
X copy, and you may at your option offer warranty protection in
X exchange for a fee.
X
XMere aggregation of another independent work with the Program (or its
Xderivative) on a volume of a storage or distribution medium does not bring
Xthe other work under the scope of these terms.
X
X 3. You may copy and distribute the Program (or a portion or derivative of
Xit, under Paragraph 2) in object code or executable form under the terms of
XParagraphs 1 and 2 above provided that you also do one of the following:
X
X a) accompany it with the complete corresponding machine-readable
X source code, which must be distributed under the terms of
X Paragraphs 1 and 2 above; or,
X
X b) accompany it with a written offer, valid for at least three
X years, to give any third party free (except for a nominal charge
X for the cost of distribution) a complete machine-readable copy of the
X corresponding source code, to be distributed under the terms of
X Paragraphs 1 and 2 above; or,
X
X c) accompany it with the information you received as to where the
X corresponding source code may be obtained. (This alternative is
X allowed only for noncommercial distribution and only if you
X received the program in object code or executable form alone.)
X
XSource code for a work means the preferred form of the work for making
Xmodifications to it. For an executable file, complete source code means
Xall the source code for all modules it contains; but, as a special
Xexception, it need not include source code for modules which are standard
Xlibraries that accompany the operating system on which the executable
Xfile runs, or for standard header files or definitions files that
Xaccompany that operating system.
X
X 4. You may not copy, modify, sublicense, distribute or transfer the
XProgram except as expressly provided under this General Public License.
XAny attempt otherwise to copy, modify, sublicense, distribute or transfer
Xthe Program is void, and will automatically terminate your rights to use
Xthe Program under this License. However, parties who have received
Xcopies, or rights to use copies, from you under this General Public
XLicense will not have their licenses terminated so long as such parties
Xremain in full compliance.
X
X 5. By copying, distributing or modifying the Program (or any work based
Xon the Program) you indicate your acceptance of this license to do so,
Xand all its terms and conditions.
X
X 6. Each time you redistribute the Program (or any work based on the
XProgram), the recipient automatically receives a license from the original
Xlicensor to copy, distribute or modify the Program subject to these
Xterms and conditions. You may not impose any further restrictions on the
Xrecipients' exercise of the rights granted herein.
X
X 7. The Free Software Foundation may publish revised and/or new versions
Xof the General Public License from time to time. Such new versions will
Xbe similar in spirit to the present version, but may differ in detail to
Xaddress new problems or concerns.
X
XEach version is given a distinguishing version number. If the Program
Xspecifies a version number of the license which applies to it and "any
Xlater version", you have the option of following the terms and conditions
Xeither of that version or of any later version published by the Free
XSoftware Foundation. If the Program does not specify a version number of
Xthe license, you may choose any version ever published by the Free Software
XFoundation.
X
X 8. If you wish to incorporate parts of the Program into other free
Xprograms whose distribution conditions are different, write to the author
Xto ask for permission. For software which is copyrighted by the Free
XSoftware Foundation, write to the Free Software Foundation; we sometimes
Xmake exceptions for this. Our decision will be guided by the two goals
Xof preserving the free status of all derivatives of our free software and
Xof promoting the sharing and reuse of software generally.
X
X NO WARRANTY
X
X 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
XFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
XOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
XPROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
XOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
XMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
XTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
XPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
XREPAIR OR CORRECTION.
X
X 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
XWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
XREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
XINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
XOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
XTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
XYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
XPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
XPOSSIBILITY OF SUCH DAMAGES.
X
X END OF TERMS AND CONDITIONS
X
X Appendix: How to Apply These Terms to Your New Programs
X
X If you develop a new program, and you want it to be of the greatest
Xpossible use to humanity, the best way to achieve this is to make it
Xfree software which everyone can redistribute and change under these
Xterms.
X
X To do so, attach the following notices to the program. It is safest to
Xattach them to the start of each source file to most effectively convey
Xthe exclusion of warranty; and each file should have at least the
X"copyright" line and a pointer to where the full notice is found.
X
X <one line to give the program's name and a brief idea of what it does.>
X Copyright (C) 19yy <name of author>
X
X This program is free software; you can redistribute it and/or modify
X it under the terms of the GNU General Public License as published by
X the Free Software Foundation; either version 1, or (at your option)
X any later version.
X
X This program is distributed in the hope that it will be useful,
X but WITHOUT ANY WARRANTY; without even the implied warranty of
X MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
X GNU General Public License for more details.
X
X You should have received a copy of the GNU General Public License
X along with this program; if not, write to the Free Software
X Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
X
XAlso add information on how to contact you by electronic and paper mail.
X
XIf the program is interactive, make it output a short notice like this
Xwhen it starts in an interactive mode:
X
X Gnomovision version 69, Copyright (C) 19xx name of author
X Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
X This is free software, and you are welcome to redistribute it
X under certain conditions; type `show c' for details.
X
XThe hypothetical commands `show w' and `show c' should show the
Xappropriate parts of the General Public License. Of course, the
Xcommands you use may be called something other than `show w' and `show
Xc'; they could even be mouse-clicks or menu items--whatever suits your
Xprogram.
X
XYou should also get your employer (if you work as a programmer) or your
Xschool, if any, to sign a "copyright disclaimer" for the program, if
Xnecessary. Here a sample; alter the names:
X
X Yoyodyne, Inc., hereby disclaims all copyright interest in the
X program `Gnomovision' (a program to direct compilers to make passes
X at assemblers) written by James Hacker.
X
X <signature of Ty Coon>, 1 April 1989
X Ty Coon, President of Vice
X
XThat's all there is to it!
END_OF_FILE
if test 12488 -ne `wc -c <'COPYING.GNU'`; then
echo shar: \"'COPYING.GNU'\" unpacked with wrong size!
fi
# end of 'COPYING.GNU'
fi
if test -f 'COPYRIGHT' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'COPYRIGHT'\"
else
echo shar: Extracting \"'COPYRIGHT'\" \(1123 characters\)
sed "s/^X//" >'COPYRIGHT' <<'END_OF_FILE'
X
X xwater: A Simple-Minded But Fun Simulation of Water Molecules
X Copyright (C) 1990 Michael Frank
X
X This program is free software; you can redistribute it and/or modify
X it under the terms of the GNU General Public License as published by
X the Free Software Foundation; either version 1, or (at your option)
X any later version.
X
X This program is distributed in the hope that it will be useful,
X but WITHOUT ANY WARRANTY; without even the implied warranty of
X MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
X GNU General Public License for more details.
X
X You should have received a copy of the GNU General Public License
X along with this program; if not, write to the Free Software
X Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
X
X Michael Frank, the author, may be contacted by email at
X mpf at portia.stanford.edu, or write to Michael Frank, 7005 Sleigh Ln.,
X Harrison, TN, 37341.
X
X Credits: The origin of this software lies in the xskel program
X written by Mark Moraes. See README.xskel and COPYRIGHT.xskel.
X I (Mike Frank) basically just added the water algorithm.
END_OF_FILE
if test 1123 -ne `wc -c <'COPYRIGHT'`; then
echo shar: \"'COPYRIGHT'\" unpacked with wrong size!
fi
# end of 'COPYRIGHT'
fi
if test -f 'COPYRIGHT.xskel' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'COPYRIGHT.xskel'\"
else
echo shar: Extracting \"'COPYRIGHT.xskel'\" \(915 characters\)
sed "s/^X//" >'COPYRIGHT.xskel' <<'END_OF_FILE'
X/*
X * Copyright University of Toronto 1988, 1989.
X * Written by Mark Moraes
X *
X * Permission is granted to anyone to use this software for any purpose on
X * any computer system, and to alter it and redistribute it freely, subject
X * to the following restrictions:
X *
X * 1. The author and the University of Toronto are not responsible
X * for the consequences of use of this software, no matter how awful,
X * even if they arise from flaws in it.
X *
X * 2. The origin of this software must not be misrepresented, either by
X * explicit claim or by omission. Since few users ever read sources,
X * credits must appear in the documentation.
X *
X * 3. Altered versions must be plainly marked as such, and must not be
X * misrepresented as being the original software. Since few users
X * ever read sources, credits must appear in the documentation.
X *
X * 4. This notice may not be removed or altered.
X */
END_OF_FILE
if test 915 -ne `wc -c <'COPYRIGHT.xskel'`; then
echo shar: \"'COPYRIGHT.xskel'\" unpacked with wrong size!
fi
# end of 'COPYRIGHT.xskel'
fi
if test -f 'Imakefile' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'Imakefile'\"
else
echo shar: Extracting \"'Imakefile'\" \(176 characters\)
sed "s/^X//" >'Imakefile' <<'END_OF_FILE'
XLOCAL_LIBRARIES = $(XTOOLLIB) $(XLIB)
XDEFINES = # -DWINDOWDEBUG # -DOUTPUT_ONLY
XCDEBUGFLAGS = # -g
X
XSimpleProgramTarget(xwater)
X
Xlint:
X $(LINT) $(LINTFLAGS) $(SRCS) -lXt -lX11
END_OF_FILE
if test 176 -ne `wc -c <'Imakefile'`; then
echo shar: \"'Imakefile'\" unpacked with wrong size!
fi
# end of 'Imakefile'
fi
if test -f 'README' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'README'\"
else
echo shar: Extracting \"'README'\" \(2431 characters\)
sed "s/^X//" >'README' <<'END_OF_FILE'
X
X xwater: A Simple-Minded But Fun Simulation of Water Molecules
X Copyright (C) 1990 Michael Frank
X
X This program is free software; you can redistribute it and/or modify
X it under the terms of the GNU General Public License as published by
X the Free Software Foundation; either version 1, or (at your option)
X any later version.
X
X This program is distributed in the hope that it will be useful,
X but WITHOUT ANY WARRANTY; without even the implied warranty of
X MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
X GNU General Public License for more details.
X
X You should have received a copy of the GNU General Public License
X along with this program; if not, write to the Free Software
X Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
X
X Michael Frank, the author, may be contacted by email at
X mpf at portia.stanford.edu, or write to Michael Frank, 7005 Sleigh Ln.,
X Harrison, TN, 37341.
X
X Credits: The origin of this software lies in the xskel program
X written by Mark Moraes. See README.xskel and COPYRIGHT.xskel.
X I (Mike Frank) basically just added the water algorithm.
X
X----------------------------------------------------------------------
X
X This simulation is based on a very simple algorithm, but it has some
X interesting emergent properties. The program moves water "drops" or
X "molecules" around a grid of "off" and "on" pixels representing
X empty space and obstacles. The rules governing water-drop motion
X are set forth by a very simple algorithm:
X
X Loop through an array listing positions of all water molecules.
X If the molecule can move down (i.e., the pixel below it is empty),
X move it down.
X Else, if it can move either left or right, move it that direction.
X (If it can move in both directions, pick one randomly.)
X Else, if it can move up, move it up.
X Else, don't move it.
X End loop.
X
X To faciliatate experimentation, there is a simple interactive facility:
X The user can draw obstacle-pixels into the grid with the left mouse
X button, erase them with the right mouse button, and stop and start the
X simulation with the middle mouse button.
X
X Some things to try include:
X - ramps
X - bowls
X - single-pixel-wide tubes going up
X - wide U-shaped tubes
X - plumbing
X - waterfalls
X
X And more. Use your imagination!
X
X If anyone does more work on this program, I'd like to hear about it.
END_OF_FILE
if test 2431 -ne `wc -c <'README'`; then
echo shar: \"'README'\" unpacked with wrong size!
fi
# end of 'README'
fi
if test -f 'README.xskel' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'README.xskel'\"
else
echo shar: Extracting \"'README.xskel'\" \(278 characters\)
sed "s/^X//" >'README.xskel' <<'END_OF_FILE'
XA simple program that puts up a window and allows sketching in it.
X(If compiled with -DOUTPUT_ONLY, then it doesn't accept input,
Xand acts as a simple window, suitable for graphic output)
X
XUses the X Toolkit which makes it easy to expand and change.
X
X - moraes at csri.toronto.edu
END_OF_FILE
if test 278 -ne `wc -c <'README.xskel'`; then
echo shar: \"'README.xskel'\" unpacked with wrong size!
fi
# end of 'README.xskel'
fi
if test -f 'runimake' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'runimake'\"
else
echo shar: Extracting \"'runimake'\" \(337 characters\)
sed "s/^X//" >'runimake' <<'END_OF_FILE'
X#! /bin/csh -f
X
X# This is the invocation of imake that worked for this program on this system.
X# by Michael Frank.
X# Change it for your own filesystem.
X
Xcp Makefile Makefile.bak
Xset X=/usr/local/X11R4
Xset MIT=${X}/mit
Xset INC=${X}/include
Xset TMPL=${MIT}/config
Xset TOP=${INC}
Ximake -I${TMPL} -TImake.tmpl -DTOPDIR=${TOP} -s Makefile $*
END_OF_FILE
if test 337 -ne `wc -c <'runimake'`; then
echo shar: \"'runimake'\" unpacked with wrong size!
fi
chmod +x 'runimake'
# end of 'runimake'
fi
if test -f 'xwater.c' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'xwater.c'\"
else
echo shar: Extracting \"'xwater.c'\" \(17150 characters\)
sed "s/^X//" >'xwater.c' <<'END_OF_FILE'
X/*
X xwater: A Simple-Minded But Fun Simulation of Water Molecules
X Copyright (C) 1990 Michael Frank
X
X This program is free software; you can redistribute it and/or modify
X it under the terms of the GNU General Public License as published by
X the Free Software Foundation; either version 1, or (at your option)
X any later version.
X
X This program is distributed in the hope that it will be useful,
X but WITHOUT ANY WARRANTY; without even the implied warranty of
X MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
X GNU General Public License for more details.
X
X You should have received a copy of the GNU General Public License
X along with this program; if not, write to the Free Software
X Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
X
X Michael Frank, the author, may be contacted by email at
X mpf at portia.stanford.edu, or write to Michael Frank, 7005 Sleigh Ln.,
X Harrison, TN, 37341.
X
X Credits: The origin of this software lies in the xskel program
X written by Mark Moraes. See README.xskel and COPYRIGHT.xskel.
X I (Mike Frank) basically just added the water algorithm.
X*/
X
X
X/*
X
X This simulation is based on a very simple algorithm, but it has some
X interesting emergent properties. The program moves water "drops" or
X "molecules" around a grid of "off" and "on" pixels representing
X empty space and obstacles. The rules governing water-drop motion
X are set forth by a very simple algorithm:
X
X Loop through an array listing positions of all water molecules.
X If the molecule can move down (i.e., the pixel below it is empty),
X move it down.
X Else, if it can move either left or right, move it that direction.
X (If it can move in both directions, pick one randomly.)
X Else, if it can move up, move it up.
X Else, don't move it.
X End loop.
X
X To faciliatate experimentation, there is a simple interactive facility:
X The user can draw obstacle-pixels into the grid with the left mouse
X button, erase them with the right mouse button, and stop and start the
X simulation with the middle mouse button.
X
X Some things to try include:
X - ramps
X - bowls
X - single-pixel-wide tubes going up
X - wide U-shaped tubes
X - plumbing
X - waterfalls
X
X And more. Use your imagination!
X
X If anyone does more work on this program, I'd like to hear about it.
X*/
X
X/*
X This program was modified by Michael Frank from xskel.c by Mark
X Moraes. Changes by me are set off by a comment with my
X initials, MPF, so search for that to find my changes. Actually, I
X got lazy, and I've done a number of changes without marking them
X with MPF. Just do a diff with Moraes' original.
X */
X
X/*
X * A simple window, with trivial mouse interaction - Mark Moraes.
X */
X#include <stdio.h>
X#include <X11/Intrinsic.h>
X#include <X11/StringDefs.h>
X#include <X11/Xos.h>
X#include <X11/cursorfont.h>
X#include <X11/Xutil.h>
X
X#define APP_NAME "xwater"
X#define APP_CLASS "Xwater"
X
X#ifndef OUTPUT_ONLY
X# define RightButton Button3
X# define MiddleButton Button2
X# define LeftButton Button1
X# define RightButtonMask Button3Mask
X# define MiddleButtonMask Button2Mask
X# define LeftButtonMask Button1Mask
X#endif /* OUTPUT_ONLY */
X
X/* #define CELLWIDTH 4
X #define CELLHEIGHT 4
X */
X
Xstatic int CELLWIDTH = 4;
Xstatic int CELLHEIGHT = 4;
X
X#define XCELLS 150
X#define YCELLS 150
X
X#define xcell(i) ((i)*CELLWIDTH)
X#define ycell(i) ((i)*CELLHEIGHT)
X
X/*
X * If MAXARGS isn't enough to hold all the arguments you pass any Xt
X * procedure, the program aborts
X */
X#define MAXARGS 32
Xstatic int nargs;
Xstatic Arg wargs[MAXARGS];
X#define startargs() nargs = 0
X#define setarg(name, value) \
X if (nargs < MAXARGS) \
X XtSetArg(wargs[nargs], name, value), nargs++; \
X else \
X abort()
X
Xstatic Cursor WorkingCursor;
Xstatic Display *dpy;
Xstatic Window win;
Xstatic GC gc;
Xstatic GC cleargc;
X
Xstatic int running = 0;
X
X/* Defaults */
Xstatic int defaultWidth;
Xstatic int defaultHeight;
X
Xstatic int Width, Height;
Xstatic Pixel fg, bg;
Xstatic char *progname;
X
X/* Application Resources - no particular widget */
Xstatic XtResource application_resources[] = {
X {"name", "Name", XtRString, sizeof(char *),
X (Cardinal)&progname, XtRString, APP_NAME},
X {"width", "Width", XtRInt, sizeof(int),
X (Cardinal)&Width, XtRInt, (caddr_t) &defaultWidth},
X {"height", "Height", XtRInt, sizeof(int),
X (Cardinal)&Height, XtRInt, (caddr_t) &defaultHeight},
X {"foreground", "Foreground", XtRPixel, sizeof(Pixel),
X (Cardinal)&fg, XtRString, (caddr_t) "Black"},
X {"background", "Background", XtRPixel, sizeof(Pixel),
X (Cardinal)&bg, XtRString, (caddr_t) "White"},
X};
X
X/* MPF - I added these so that I can use the XtApp functions, especially
X XtAppAddWorkProc, because I want my program to have a work procedure
X instead of just waiting for events.
X */
Xstatic XtAppContext app_context;
Xstatic XtWorkProcId slosh_id; /* Slosh is the name of my work-proc. */
Xstatic XtWorkProc Slosh(); /* A forward declaration. */
X/* MPF's function declarations*/
Xstatic void waterInit(), allocateGrid(), createMolecules();
Xstatic void setGridCell(), clearGridCell(), resizeGrid();
Xstatic int gridPeek();
Xstatic void gridSet(), gridClear();
Xextern long random();
X
X/*
X * Command line options table. The command line is parsed for these,
X * and it sets/overrides the appropriate values in the resource
X * database
X */
Xstatic XrmOptionDescRec optionDescList[] = {
X {"-width", "*width", XrmoptionSepArg, (caddr_t) NULL},
X {"-height", "*height", XrmoptionSepArg, (caddr_t) NULL},
X {"-fg", "*foreground", XrmoptionSepArg, (caddr_t) NULL},
X {"-bg", "*background", XrmoptionSepArg, (caddr_t) NULL},
X};
X
X
X
Xmain(argc, argv)
X int argc;
X char **argv;
X{
X Widget toplevel;
X Widget w;
X XGCValues gcv;
X#ifndef OUTPUT_ONLY
X void RepaintCanvas();
X void RecordMapStatus();
X void MouseInput();
X#else
X XEvent ev;
X#endif
X
X if ((argc>1) && (atoi(argv[1]) > 0)) {
X CELLHEIGHT = CELLWIDTH = atoi(argv[1]);
X argc--;
X argv++;
X }
X defaultWidth = CELLWIDTH * XCELLS;
X defaultHeight = CELLHEIGHT * YCELLS;
X /*
X * Create the top level Widget that represents encloses the
X * application.
X */
X /* toplevel = XtInitialize(argv[0], APP_CLASS,
X optionDescList, XtNumber(optionDescList), (Cardinal *) &argc,
X argv);
X */
X /* MPF - I replaced the XtInitialize with XtAppInitialize so
X that I can use XtAppAddWorkProc. */
X toplevel = XtAppInitialize(&app_context, APP_CLASS,
X optionDescList, XtNumber(optionDescList),
X &argc, argv, NULL, /* fallback_resources*/
X NULL, 0);
X
X XtGetApplicationResources(toplevel, (caddr_t) 0, application_resources,
X XtNumber(application_resources), (ArgList) NULL, (Cardinal)0);
X
X
X if (argc != 1) {
X (void) fprintf(stderr, "Usage: %s [Xt options]\n", argv[0]);
X exit(-1);
X }
X
X /*
X * Create a simple Core class widget which we'll use for the actual
X * game. A Core class widget is basically just a window, with a
X * simple Xt "wrapper" around it.
X */
X startargs();
X setarg(XtNwidth, Width);
X setarg(XtNheight, Height);
X w = XtCreateManagedWidget(argv[0], widgetClass, toplevel,
X wargs, XtNumber(wargs));
X
X#ifndef OUTPUT_ONLY
X /*
X * Set the procedures for various X Windows actions - exposure events
X * which arrive when a window needs to be redrawn. The map event lets
X * you know that the window is now on the screen so you can actually
X * do stuff. The ButtonPress event lets you know that a mouse button
X * was pressed.
X */
X XtAddEventHandler(w, (EventMask) ExposureMask, False,
X RepaintCanvas, "redraw_data");
X XtAddEventHandler(w, (EventMask) StructureNotifyMask, False,
X RecordMapStatus, "map_data");
X /* One day, we'll use the translation manager here */
X XtAddEventHandler(w,
X (EventMask) ButtonPressMask | ButtonMotionMask, False,
X MouseInput, "input_data");
X#endif
X
X /*
X * Create the windows, and set their attributes according to the Widget
X * data.
X */
X XtRealizeWidget(toplevel);
X
X /* We need these for the raw Xlib calls */
X win = XtWindow(w);
X dpy = XtDisplay(w);
X
X WorkingCursor = XCreateFontCursor(dpy, XC_top_left_arrow);
X XDefineCursor(dpy, win, WorkingCursor);
X
X /*
X * make the GC stuff here - one for copy, one for invert. Remember
X * to change the both appropriately
X */
X gcv.foreground = fg;
X gcv.background = bg;
X gcv.function = GXcopy;
X gc = XCreateGC(dpy, win, GCForeground | GCBackground
X | GCFunction, &gcv);
X gcv.foreground = bg;
X cleargc = XCreateGC(dpy, win, GCForeground | GCBackground
X | GCFunction, &gcv);
X
X /* MPF */
X waterInit();
X
X /*
X * Now process the events.
X */
X#ifndef OUTPUT_ONLY
X /* XtMainLoop(); */
X /* MPF - Changed XtMainLoop to XtAppMainLoop so I can have it
X do my WorkProc, Slosh, when nothing else is going on. */
X XtAppMainLoop(app_context);
X#else
X /* Wait for first exposure event so we know window has been mapped */
X XWindowEvent(dpy, win, (long) ExposureMask, &ev);
X /* pause is just for the demo. Usually we'd return or draw something */
X pause();
X#endif
X}
X
X#ifndef OUTPUT_ONLY
X
Xstatic int isMapped = 0;
X
Xvoid
X setcell(x, y, gc)
Xint x, y;
XGC gc;
X{
X int xreal = x * CELLWIDTH;
X int yreal = y * CELLHEIGHT;
X
X XFillRectangle(dpy, win, gc, xreal, yreal,
X CELLWIDTH, CELLHEIGHT);
X}
X
X/*ARGSUSED*/
Xvoid RepaintCanvas(w, data, ev)
X Widget w;
X caddr_t data;
X XEvent *ev;
X{
X if (!isMapped)
X return;
X /*
X * Redraw the array
X */
X
X /* MPF-commented this out.
X if (ev && ev->xexpose.count == 0) {
X XEvent event;
X while (XCheckTypedEvent(dpy, Expose, &event));
X }
X XClearWindow(dpy, ev->xany.window);
X */
X /* MPF - and added this. */
X {
X unsigned int realx,realy,realwidth,realheight;
X unsigned int x,y,x2,y2;
X unsigned int i,j;
X realx=ev->xexpose.x; realy=ev->xexpose.y;
X realwidth=ev->xexpose.width; realheight=ev->xexpose.height;
X x=realx/CELLWIDTH; y=realy/CELLHEIGHT;
X x2=(realx+realwidth)/CELLWIDTH;
X y2=(realy+realheight)/CELLHEIGHT;
X for(j=y;j<y2;j++)
X for(i=x;i<x2;i++)
X if (gridPeek(i,j))
X setcell(i,j,gc);
X }
X
X#ifdef WINDOWDEBUG
X (void) printf("repaint\n");
X#endif
X XFlush(dpy);
X}
X
X/*ARGSUSED*/
Xvoid RecordMapStatus(w, data, ev)
X Widget w;
X caddr_t data;
X XEvent *ev;
X{
X if (ev->type == MapNotify) {
X#ifdef WINDOWDEBUG
X (void) printf("window mapped\n");
X#endif
X isMapped = TRUE;
X } else if (ev->type = ConfigureNotify) {
X#ifdef WINDOWDEBUG
X (void) printf("window resized to %d, %d\n",
X ev->xconfigure.width,
X ev->xconfigure.height
X );
X#endif
X /* MPF - Changed what the above line prints, for fun. */
X /* and added this: */
X resizeGrid((int)(ev->xconfigure.width/CELLWIDTH),
X (int)(ev->xconfigure.height/CELLHEIGHT));
X }
X}
X
X
X/*ARGSUSED*/
Xvoid MouseInput(w, data, ev)
X Widget w;
X caddr_t data;
X XEvent *ev;
X{
X#ifdef WINDOWDEBUG
X (void) printf("Input to canvas - %d (0x%x)\n", ev->xany.type, ev->xany.type);
X#endif
X switch (ev->xany.type) {
X case ButtonPress:
X if (ev->xbutton.button == LeftButton) {
X /* Turn on cell MPF - changed this too*/
X setGridCell((int)(ev->xbutton.x / CELLWIDTH),
X (int)(ev->xbutton.y / CELLHEIGHT));
X /* setcell((int) (ev->xbutton.x / CELLWIDTH),
X (int) (ev->xbutton.y / CELLHEIGHT), gc); */
X } else if (ev->xbutton.button == MiddleButton) {
X /* Toggle simulation on/off */
X running = !running;
X if (running)
X slosh_id = XtAppAddWorkProc(app_context,Slosh,"slosh_dummy_data");
X else
X XtRemoveWorkProc(slosh_id);
X } else if (ev->xbutton.button == RightButton) { /* else added by MPF */
X clearGridCell((int)(ev->xbutton.x / CELLWIDTH),
X (int)(ev->xbutton.y / CELLHEIGHT));
X }
X break;
X case MotionNotify:
X if (ev->xmotion.state & LeftButtonMask) {
X /* Turn on cell */
X setGridCell((int)(ev->xmotion.x / CELLWIDTH),
X (int)(ev->xmotion.y / CELLHEIGHT));
X /*
X setcell((int) (ev->xmotion.x / CELLWIDTH),
X (int) (ev->xmotion.y / CELLHEIGHT), gc);
X */
X } else if (ev->xmotion.state & RightButtonMask) {
X /* Turn on cell */
X clearGridCell((int)(ev->xmotion.x / CELLWIDTH),
X (int)(ev->xmotion.y / CELLHEIGHT));
X /*
X setcell((int) (ev->xmotion.x / CELLWIDTH),
X (int) (ev->xmotion.y / CELLHEIGHT), gc);
X */
X }
X break;
X default:
X (void) printf("Got an event of type %d (%x).\n",
X ev->xany.type, ev->xany.type);
X break;
X }
X}
X#endif
X
X/* MPF - My new functions here! */
X/*===========================================================================*/
X
Xtypedef unsigned int Coord;
Xtypedef unsigned long BitVector32;
X
Xtypedef struct Droplet {
X Coord x,y;
X} Droplet;
X
Xtypedef struct WaterGrid {
X Coord width,height;
X BitVector32 *bits;
X} WaterGrid;
X
X#define NDROPLETS 1000
X
Xstatic Droplet drops[NDROPLETS]; /* Array of all water droplets. */
Xstatic WaterGrid waterGrid; /* Representation of the grid in window */
X
X
X/*
X * Slosh
X * My water workproc. Very simple algorithm. Just iterates
X * thru all water molecules, moving them down if it can, otherwise left
X * or right if it can, otherwise up if it can.
X */
X
X
Xstatic XtWorkProc Slosh(closure)
X XtPointer closure;
X{
X register int i,height,width,x,y,ny,nx1,nx2;
X height=waterGrid.height;
X width=waterGrid.width;
X for(i=0;i<NDROPLETS;i++){
X x=drops[i].x; y=drops[i].y;
X ny=(y+1)%height;
X if (!gridPeek(x,ny)) {
X clearGridCell(x,y);
X setGridCell(x,ny);
X drops[i].y=ny;
X } else {
X nx1=(x+width-1)%width;
X nx2=(x+1)%width;
X if ((!gridPeek(nx1,y)) || (!gridPeek(nx2,y))) {
X if (random()%2) {
X if (!gridPeek(nx1,y)) {
X clearGridCell(x,y);
X setGridCell(nx1,y);
X drops[i].x=nx1;
X } else {
X clearGridCell(x,y);
X setGridCell(nx2,y);
X drops[i].x=nx2;
X }
X } else {
X if (!gridPeek(nx2,y)) {
X clearGridCell(x,y);
X setGridCell(nx2,y);
X drops[i].x=nx2;
X } else {
X clearGridCell(x,y);
X setGridCell(nx1,y);
X drops[i].x=nx1;
X }
X }
X } else {
X ny = (y+height-1)%height;
X if (!gridPeek(x,ny)) {
X clearGridCell(x,y);
X setGridCell(x,ny);
X drops[i].y=ny;
X }
X }
X }
X }
X if (isMapped) XFlush(dpy);
X}
X
X/*
X * waterInit
X * Set up arrays based on the initial size of the window.
X * scatter some water molecules around at random.
X *
X */
X
Xstatic void waterInit()
X{
X XWindowAttributes win_att;
X
X if (!XGetWindowAttributes(dpy,win,&win_att))
X {
X perror("XGetWindowAttributes");
X exit(1);
X }
X
X waterGrid.width = win_att.width / CELLWIDTH;
X waterGrid.height = win_att.height / CELLHEIGHT;
X
X allocateGrid(win_att.width/CELLWIDTH,
X win_att.height/CELLHEIGHT);
X createMolecules();
X}
X
X/*
X * allocateGrid
X * Allocate enough memory for the grid so that we have
X * one bit for every cell in the grid.
X *
X */
X
Xstatic void allocateGrid()
X{
X unsigned long nvectors = (waterGrid.width * waterGrid.height + 1) / 32;
X waterGrid.bits = (BitVector32 *)calloc(nvectors,sizeof(BitVector32));
X}
X
Xstatic void clearGridCell(x,y)
X Coord x,y;
X{
X gridClear(x,y);
X if (isMapped) setcell((int)x,(int)y,cleargc);
X}
X
Xstatic void createMolecules()
X{
X int i;
X Coord x,y;
X
X for( i = 0 ; i < NDROPLETS ; i++ ){
X x = random()%waterGrid.width;
X y = random()%waterGrid.height;
X setGridCell(x,y);
X drops[i].x = x;
X drops[i].y = y;
X }
X if (isMapped) XFlush(dpy);
X}
X
X/*
X * resizeGrid
X * allocate a new grid array, copy the data, wrapping if neccessary,
X * and then free the old grid bits.
X */
X
Xstatic void resizeGrid(newWidth,newHeight)
X Coord newWidth;
X Coord newHeight;
X{
X unsigned long nvectors = (newWidth*newHeight + 1)/32;
X BitVector32 * newbits = (BitVector32 *)calloc(nvectors,sizeof(BitVector32));
X Coord i,j;
X
X for(i=0;i<NDROPLETS;i++){
X gridClear(drops[i].x,drops[i].y);
X drops[i].x = drops[i].x%newWidth;
X drops[i].y = drops[i].y%newHeight;
X }
X
X for(j=0;j<waterGrid.height;j++)
X for(i=0;i<waterGrid.width;i++)
X if (gridPeek(i,j))
X gridSet(newbits,newWidth,i%newWidth,j%newHeight);
X
X free(waterGrid.bits);
X waterGrid.width = newWidth;
X waterGrid.height = newHeight;
X waterGrid.bits = newbits;
X
X for(i=0;i<NDROPLETS;i++){
X gridSet(waterGrid.bits,newWidth,drops[i].x,drops[i].y);
X }
X
X if (isMapped) {
X int i,j;
X XClearWindow(dpy,win);
X for(j=0;j<newHeight;j++)
X for(i=0;i<newWidth;i++)
X if (gridPeek(i,j))
X setcell(i,j,gc);
X }
X XFlush(dpy);
X}
X
Xstatic int gridPeek(x,y)
X Coord x,y;
X{
X unsigned long bitaddress = x+(y*waterGrid.width);
X return waterGrid.bits[bitaddress/32]&(1<<(bitaddress%32));
X}
X
Xstatic void gridSet(bitarray,width,x,y)
X BitVector32 *bitarray;
X Coord width;
X Coord x,y;
X{
X unsigned long bitaddress = x+(y*width);
X bitarray[bitaddress/32]|=1<<(bitaddress%32);
X}
X
X
Xstatic void gridClear(x,y)
X Coord x,y;
X{
X unsigned long bitaddress = x+(y*waterGrid.width);
X int vecindex = bitaddress/32;
X int bitnum = bitaddress%32;
X waterGrid.bits[vecindex]&=(~(1<<bitnum));
X}
X
Xstatic void setGridCell(x,y)
X Coord x,y;
X{
X gridSet(waterGrid.bits,waterGrid.width,x,y);
X if (isMapped) setcell(x,y,gc);
X}
X
END_OF_FILE
if test 17150 -ne `wc -c <'xwater.c'`; then
echo shar: \"'xwater.c'\" unpacked with wrong size!
fi
# end of 'xwater.c'
fi
echo shar: End of shell archive.
exit 0
--
, , __ mpf at portia.stanford.edu...this...
/|/| . _ |_ _ _ | |_ _ _ ,_ |, mpf at sunset.ai.sri.com.....space..
/ | | | (_ | | (_| (-' | | | (_| | | |\ mpf at csli.stanford.edu.....for....
"Be excellent to each other." -Bill&Ted (415) 497-4182............rent...
dan
----------------------------------------------------
O'Reilly && Associates argv at sun.com / argv at ora.com
Opinions expressed reflect those of the author only.
More information about the Comp.sources.x
mailing list