Thursday, 3 April 2014

Shao Jianhua invites you to Freelancer.com

freelancer
freelancer elite
Shao Jianhua
wants you to join Freelancer.com - the world's largest outsourcing marketplace!
Shao I've been using Freelancer.com to hire talented professionals for a fraction of the cost, and to make money by completing work.
Accept Invitation

Unsubscribe from this mailing list.

Thursday, 2 December 2010

Jianhua Shao invited you to Dropbox

Jianhua Shao wants you to use Dropbox to sync and share files online and across computers.

Get started here.

- The Dropbox Team

Wednesday, 4 November 2009

Monday, 13 July 2009

Jianhua Shao wants to keep up with you on Twitter

Jianhua Shao wants to keep up with you on Twitter

To find out more about Twitter visit http://twitter.com/i/3126e78b1ce18d3ddf5645889d738f8d64bcbfb0

Thanks,
— The Twitter Team

About Twitter

Twitter is a unique approach to communication and networking based on the simple concept of status. What are you doing? What are your friends doing—right now? With Twitter, you may answer this question over SMS or the Web and the responses are shared between contacts.

This message was sent by a Twitter user who entered your email address. If you'd prefer not to receive emails when other people invite you to Twitter you can opt-out

Please do not reply to this message; it was sent from an unmonitored email address. This message is a service email related to your use of Twitter. For general inquiries or to request support with your Twitter account, please visit us at Twitter Support.

Tuesday, 16 October 2007

浅谈游戏设计思路 - “棋盘”游戏

原帖及讨论:http://www.bc-cn.net/bbs/dispbbs.asp?boardid=225&id=81786

作者:孙靖(Jig) 时间:2006 - 07 - 31
若要转贴或使用本文章介绍的技术,请在你发布的文章或作品中注明出处。

先前在论坛中看了一位朋友让大家给他查看一下他写的推箱子游戏为什么出错,我第一想法就是这很难做到,别人写的程序,特别是实现流程和逻辑只有作者本人比较清楚,外人是要花费一定时间才能把握程序的中主体设计思想再进一步研究。我想除了学习或项目要求是很少人愿意花这样的精力去读别人的代码的,而粗看他的代码,我觉得是他本人在程序设计的思想上出了差错,而细想现在对引擎或硬件知识介绍的多却很少有讲解怎么实现对现实的抽象,即怎么合理的去设计游戏,实用软件......所以想写这样一篇文章来和大家探讨一下“棋盘”游戏的设计思路。
“棋盘”游戏的种类丰富,俄罗斯方块,推箱子,象棋,五子棋......等等这些都可以归类到“棋盘”游戏中来。面对这类游戏设计的时候,我本人的见解是首先对“棋盘”做研究,实在不行再去研究“棋子”。换句话说,就是以游戏中的活动区域为研究对象,像象棋就是他的棋盘,俄罗斯方块就是他整个的方块的活动区域。我们这里姑且就把他叫做“棋盘法”。

一. “棋盘法”基本实现方法
“棋盘法”实现起来其实很简单,一般来说就是把棋盘看作一个网格,那么我们就把他看作与之对应的二维数组。然后适当组织数据结构去抽象旗子,制定规
则,这样就很容易实现游戏。

二. “棋盘法”的优缺点
任何一个算法或思想都是有优缺点的,而我们的“棋盘法”的最大优点就是可以方便我们组织数据结构,简化了游戏规则的编写,使我们编程时思路比较清晰直观,通常就是直接根据游戏实际规则编写就可以了,这个我们会以实例加以说明。然而他最大的缺点就是可能耗费大量内存,试想,如果我们的棋盘规格很大,那我们就得开辟一个比较大的二维数组,并且如果你要将代码移植到单片机,ARM等硬件平台上。那你就不得不考虑自己的方法问题,在这些硬件平台上内存资源是极其宝贵的。也许有朋友会说那在PC机上总可以的。的确现在PC机资源丰富,功能强大,可有时候还是不能如你所愿。一个很经典的例子就是五子棋的人工智能,为了让五子棋在人机对战中具备攻防兼备的智能,我们只有开辟一个于棋盘规格相呼应的二维的树组来记录棋盘上各点的胜算几率,(有兴趣的朋友可以到网上去找找资料)这样的话,在DOS下你就只能开辟一个约 10X10 的棋盘,即使在WINDOS下也只能大约 16 X 16 的棋盘。(当然,这里是说直接开辟数组,采用特别技术的不算)。所以说,这个“棋盘法”也是有他自己的限制的。

三. “棋盘法”的适用条件
根据上面的介绍,我们应该很容易总结出“棋盘法”的适用条件。即棋盘规格适中,棋子会频繁的在棋盘中移动。游戏规则若复杂更应首先推选“棋盘法”。很好的一个例子就是象棋。象棋的走法规则复杂,而采用棋盘法就可以很直观的把规则做出来。当然其中要注意的是,程序员要考虑好使用内存的大小,考虑好游戏编写方法和内存数据管理技巧的相匹配。比如,一个很经典的游戏 -- 贪食蛇。他就不适合用“棋盘法”或是说用这个方法不合算。贪食蛇的棋盘很大,可蛇身并不会很大,若采用“棋盘法”那内存无疑是浪费,而且在规则实现上也是直接以蛇身作为研究对象好解决问题。所以在编写这类游戏时得在宏观上对他有个较全面的考虑。

四. “棋盘法”的例子
前面说过,可以用“棋盘法”编写的游戏很多,我们以前玩的小游戏我基本都写过,基于方便说明问题和论坛朋友提出的帮忙看看他的推箱子游戏。那下面我们就拿推箱子游戏来说明“棋盘法”的编写过程。

1. 前期准备
在编写这个游戏之前,我们先个游戏找个主题,我的是“植树”。即“箱子其实就是树,由一个小人搬运到树坑中。首先我们开辟一个 12X12 大小的二维数组作为棋盘。然后我们思考一下推箱子的棋子有哪些?一个是小人,可移动的数,还有树坑。我们的游戏过程也很简单,在棋盘上有一圈篱笆,这个是小人的活动方法,其中有几个固定的树坑,还有分散在不同地方的树,小人要推动这些树全部进入树坑就算游戏通关。有了以上思考,我们就着手来实现。

2. 定义数据
我们开辟一个 12X12 的二维数组表示棋盘,然后我们来定义个数值代表的含义。数值为 0 表示此格子为背景,1 表示为篱笆,2 表示为树,3 表示为树坑,4表示人小人,5 表示为树已移植到树坑。
有了此定义,我们就写出显示各棋子的模块:

void Dot_pawn(char x, char y, char mode); /* 在棋盘相应位置画出棋子,其中mode为 0 表示背景,1 表示篱笆,
2 表示未移植树,3 表示树坑,4 表示人, 5 表示树种坑中*/
void Dot_pawn(char x, char y, char mode)
{
char *name_bmp;

switch(mode) /* 根据Mode决定显示的图片 */
{
case 0:
name_bmp = "kong.bmp";
break;

case 1:
name_bmp = "liba.bmp";
break;

case 2:
name_bmp = "shuh.bmp";
break;

case 3:
name_bmp = "huang.bmp";
break;

case 4:
name_bmp = "ren.bmp";
break;

case 5:
name_bmp = "shul.bmp";
break;
}

if (x > -1 && x < 13 && y > -1 && y , 13) /* 在棋盘内 */
{
Chessboard[y][x] = mode;
show_bmp(name_bmp, 40 * x, 40 * y);
}
}

3. 实现规则
我们以小人的运动为基础,很自然就可以写出具体的规则。首先我们要明确这么一点,当按动方向键后,要记录下小人将要走到的格子,然后进行规则判断:

如果小人将到达的格子为篱笆(即阻挡小人的路线)
{
退出规则判断,棋面布局不做任何改变;
}

如果小人将到达的格子不为树(即小人只是自己移动,不用搬动树)
{
恢复小人原有格子背景;
在小人将到达的格子绘制小人;
}
如果小人将到达的格子为树(即小人要搬动树)
{
如果将被小人搬动的树允许被搬动(即被搬动树的前方无其他树并且不是篱笆)
{
如果将被小人搬动的树的前方为背景
{
恢复将被小人搬动的树的原来背景;
在树新位置绘制树;
恢复小人原有格子背景;
在小人将到达的格子绘制小人;
}
如果将被小人搬动的树的前方为树坑
{
恢复将被小人搬动的树的原来背景;
在树新位置绘制已种植好的树;
恢复小人原有格子背景;
在小人将到达的格子绘制小人;
}
}
}

如果已种植好的树达到社顶数量
{
游戏通关,重新开始游戏;
}


看,以上就是对规则的一个文字实现,我们只要按照以上规则写出代码就实现了游戏规则的程序化。我想到这也充分体现了“棋盘法”的最大优势。游戏规则被简化,显的很直观易懂,容易编程实现。我们来看代码:

void Rule(); /* 游戏规则 */

void Rule()
{
char x, y, count = 0;

/* 如果人将要到的位置为篱笆,退出 */
if (Chessboard[Man_will_y][Man_will_x] == 1)
{
return;
}

/* 如果人将要到的位置不为树,即不用推箱子 */
if (Chessboard[Man_will_y][Man_will_x] != 2 && Chessboard[Man_will_y][Man_will_x] != 5)
{
Dot_pawn(Man_x, Man_y, Mode_old); /* 恢复原有面貌 */
Mode_old = Chessboard[Man_will_y][Man_will_x]; /* 记录新,以便以后恢复背景 */
Dot_pawn(Man_will_x, Man_will_y, 4); /* 画出人 */

Man_x = Man_will_x; /* 记录下人的新位置 */
Man_y = Man_will_y;
}
else /* 推箱子 */
{
/* 判断被推箱子的前方是否有阻挡 */
if (Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] != 1
&&Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] != 2
&& Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] != 5)
{
/* 如果被推的箱子为2,即未移植树 */
if (Chessboard[Man_will_y][Man_will_x] == 2)
{
/* 前方为树坑 */
if (Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] == 3)
{
Dot_pawn(2 * Man_will_x - Man_x, 2 * Man_will_y - Man_y, 5); /* 植好树 */
Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] = 5;
}
else /* 前方为空地 */
{
Dot_pawn(2 * Man_will_x - Man_x, 2 * Man_will_y - Man_y, 2); /* 推动树 */
Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] = 2;
}

Dot_pawn(Man_will_x, Man_will_y, 0); /* 恢复原树背景 */
Chessboard[Man_will_y][Man_will_x] = 0;
}
else /* 被推的箱子为5 表示树种坑中 */
{
/* 前方为树坑 */
if (Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] == 3)
{
Dot_pawn(2 * Man_will_x - Man_x, 2 * Man_will_y - Man_y, 5); /* 植好树 */
Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] = 5;
}
else /* 前方为空地 */
{
Dot_pawn(2 * Man_will_x - Man_x, 2 * Man_will_y - Man_y, 2); /* 推动树 */
Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] = 2;
}

Dot_pawn(Man_will_x, Man_will_y, 3); /* 恢复原树背景 */
Chessboard[Man_will_y][Man_will_x] = 3;
}

Dot_pawn(Man_x, Man_y, Mode_old); /* 恢复人位置原有面貌 */
Mode_old = Chessboard[Man_will_y][Man_will_x]; /* 记录新,以便以后恢复背景 */
Dot_pawn(Man_will_x, Man_will_y, 4); /* 画出人 */

Man_x = Man_will_x; /* 记录下人的新位置 */
Man_y = Man_will_y;
}
}

for (y = 0; y < 12; y++)
{
for (x = 0; x < 12; x++)
{
if (Chessboard[y][x] == 5)
{
count++;
if (count == 6)
{
neo_printf(500, 400, "OK");
init_pawn();
}
}
}
}
}

看以上代码就是对前面规则文字叙述的实现。好了,其实介绍到这里,我这个所谓的“棋盘法”也就完了。而对此种方法,我个人总结就是 —— 只要他能简化规则,让规则实现起来方便,即使多耗费点内存,美工多点工序我都是愿意采用此种方法。
写这篇文章纯粹就是发表自己的一点观点,希望给想接触游戏编程的朋友一点启发,和游戏编程高手讨论方法。若是朋友你有其他的想法可以提出我们一同探讨

下面给出这个例子的全部代码:

#include


/* 定义按键 */
#define ESC 15131
#define REST 4722
#define UP 21504
#define DOWN 21760
#define LEFT 20992
#define RIGHT 21248



char Chessboard[12][12]; /* 定义“棋盘”,12 X 12 大小 */
char Man_x, Man_y; /* 定义人的位置 */
char Man_will_x, Man_will_y; /* 记录人下步要到的位置 */
char Mode_old; /* 记录下人的位置原来的mode值 */

void Dot_pawn(char x, char y, char mode); /* 在棋盘相应位置画出棋子,其中mode为 0 表示空白,1 表示篱笆,
2 表示未移植树,3 表示树坑,4 表示人, 5 表示树种坑中*/
void init_pawn(); /* 初始化棋盘 */
void paly_game(); /* 开始游戏 */
void Rule(); /* 游戏规则 */


void Dot_pawn(char x, char y, char mode)
{
char *name_bmp;

switch(mode) /* 根据Mode决定显示的图片 */
{
case 0:
name_bmp = "kong.bmp";
break;

case 1:
name_bmp = "liba.bmp";
break;

case 2:
name_bmp = "shuh.bmp";
break;

case 3:
name_bmp = "huang.bmp";
break;

case 4:
name_bmp = "ren.bmp";
break;

case 5:
name_bmp = "shul.bmp";
break;
}

if (x > -1 && x < 13 && y > -1 && y , 13) /* 在棋盘内 */
{
Chessboard[y][x] = mode;
show_bmp(name_bmp, 40 * x, 40 * y);
}
}

void init_pawn()
{
FILE *fp;
char x, y;
int mode;


/* 直接读取外部文件设置画面,很方便 */
fp = fopen("set.txt", "r+");
for (y = 0; y < 12; y++)
{
for (x = 0; x < 12; x++)
{
fscanf(fp, "%d", &mode);
Dot_pawn(x, y, mode);

if (mode == 4)
{
Mode_old = 0;
Man_x = x;
Man_y = y;
}
}
}
fclose(fp);
}


void paly_game()
{

while(1)
{
switch(readkey())
{
case ESC: /* 退出 */
return;
break;

case REST: /* 重复初始化 */
init_pawn();
break;

case UP: /* 上键 */
Man_will_x = Man_x; /* 记录人将要到的位置 */
Man_will_y = Man_y - 1;
Rule();
break;

case DOWN: /* 下键 */
Man_will_x = Man_x;
Man_will_y = Man_y + 1;
Rule();
break;

case LEFT: /* 左键 */
Man_will_x = Man_x - 1;
Man_will_y = Man_y;
Rule();
break;

case RIGHT: /* 右键 */
Man_will_x = Man_x + 1;
Man_will_y = Man_y;
Rule();
break;

}
}
}

void Rule()
{
char x, y, count = 0;

/* 如果人将要到的位置为篱笆,退出 */
if (Chessboard[Man_will_y][Man_will_x] == 1)
{
return;
}

/* 如果人将要到的位置不为树,即不用推箱子 */
if (Chessboard[Man_will_y][Man_will_x] != 2 && Chessboard[Man_will_y][Man_will_x] != 5)
{
Dot_pawn(Man_x, Man_y, Mode_old); /* 恢复原有面貌 */
Mode_old = Chessboard[Man_will_y][Man_will_x]; /* 记录新,以便以后恢复背景 */
Dot_pawn(Man_will_x, Man_will_y, 4); /* 画出人 */

Man_x = Man_will_x; /* 记录下人的新位置 */
Man_y = Man_will_y;
}
else /* 推箱子 */
{
/* 判断被推箱子的前方是否有阻挡 */
if (Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] != 1
&&Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] != 2
&& Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] != 5)
{
/* 如果被推的箱子为2,即未移植树 */
if (Chessboard[Man_will_y][Man_will_x] == 2)
{
/* 前方为树坑 */
if (Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] == 3)
{
Dot_pawn(2 * Man_will_x - Man_x, 2 * Man_will_y - Man_y, 5); /* 植好树 */
Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] = 5;
}
else /* 前方为空地 */
{
Dot_pawn(2 * Man_will_x - Man_x, 2 * Man_will_y - Man_y, 2); /* 推动树 */
Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] = 2;
}

Dot_pawn(Man_will_x, Man_will_y, 0); /* 恢复原树背景 */
Chessboard[Man_will_y][Man_will_x] = 0;
}
else /* 被推的箱子为5 表示树种坑中 */
{
/* 前方为树坑 */
if (Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] == 3)
{
Dot_pawn(2 * Man_will_x - Man_x, 2 * Man_will_y - Man_y, 5); /* 植好树 */
Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] = 5;
}
else /* 前方为空地 */
{
Dot_pawn(2 * Man_will_x - Man_x, 2 * Man_will_y - Man_y, 2); /* 推动树 */
Chessboard[2 * Man_will_y - Man_y][2 * Man_will_x - Man_x] = 2;
}

Dot_pawn(Man_will_x, Man_will_y, 3); /* 恢复原树背景 */
Chessboard[Man_will_y][Man_will_x] = 3;
}

Dot_pawn(Man_x, Man_y, Mode_old); /* 恢复人位置原有面貌 */
Mode_old = Chessboard[Man_will_y][Man_will_x]; /* 记录新,以便以后恢复背景 */
Dot_pawn(Man_will_x, Man_will_y, 4); /* 画出人 */

Man_x = Man_will_x; /* 记录下人的新位置 */
Man_y = Man_will_y;
}
}

for (y = 0; y < 12; y++)
{
for (x = 0; x < 12; x++)
{
if (Chessboard[y][x] == 5)
{
count++;
if (count == 6)
{
neo_printf(500, 400, "OK");
init_pawn();
}
}
}
}
}

void main(void)
{
/* -------------------- NEO下的一系列初始化 ---------------------- */
SAMPLE *sample = NULL;

neo_init();
set_window_mode(0);
set_vbe_mode(VBE640X480X64K);
install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL);
install_keyboard();

sample = load_wav("bei.wav");
play_sample(sample, 255, 128, 0, 1);
/* --------------------------------------------------------------- */

init_pawn(); /* 初始化棋盘 */
paly_game(); /* 开始游戏 */


destroy_sample(sample);
}
END_OF_MAIN();

Thursday, 11 October 2007

TUTORIAL and cookbook

Current Page:
Current Path:
Clipping Path:
Positions on the POSTSCRIPT current page are described in terms
of a user coordinate system or user space.
The POSTSCRIPT user space can be altered in three ways. The
coordinate system’s origin may be translated, moved to any
point in user space. The axes may be rotated to any orientation.
The axes may be scaled to any degree desired;
Note that spaces, tabs, and newline characters act as delimiters of
POSTSCRIPT objects. Other characters, such as parentheses and
brackets, can be delimiters under some circumstances;
top two numbers from the stack, add them, and leave the sum on
the stack.
-27 neg Þ 27
25 3 idiv Þ 8
Thus, if the top item on the stack was
a dictionary (we shall be talking about this at greater length
later), the == operator would print
––dictionary––
on the terminal.
Another useful interactive stack operator is pstack. This operator
prints the contents of the entire stack. Unlike the == operator,
pstack does not remove any of the stack’s contents.
We start out by calling the newpath operator. This operator
empties the current path and declares we are starting a new path.
Note that the lineto operator does not actually draw on the current
page. It simply adds a line segment to the current path. You
may later draw in this line, but it does not happen automatically.
The
closepath operator adds a line segment to the current path connecting
the current point to the last point addressed by a moveto
operator. It closes the path with a mitered join, eliminating the
notch we noticed in our first box. It is possible to change the
method by which POSTSCRIPT joins line segments;
Note that each box had to start with a moveto. This is because the fill operator clears the current path; after a fill, there is no
current point and a lineto or rlineto would have no starting
point. The stroke operator also clears the current path.
To change the value of a variable, you redefine it with a new
value.
findfont looks up the name in a dictionary called FontDirectory
and places the appropriate font dictionary on the stack.
stringwidth takes a string from the top of the stack and replaces
it with the horizontal and vertical distances the current point
would be moved if the string were shown in the current font. The
y offset is left on top of the stack, with x below it. Thus, the line
above duplicates the string on the stack, replaces the top copy of
the string with the x and y offsets, and then drops the y offset
from the stack. The stack is left with the string’s width on top of
the stack and the string itself below.

I've added you as a friend on Facebook...

facebook
Shao Jianhua
Shao Jianhua

I've added you as a friend on Facebook...

I've requested to add you as a friend on Facebook. You can use Facebook to see the profiles of the people around you, share photos, and connect with friends.

Thanks,
Shao

Here's the link:
http://www.facebook.com/p.php?i=533036236&k=Y6L663RYU3ZMZJFDUBX2P&r&v=2
This e-mail contains promotional materials. If you do not wish to receive future commercial mailings from Facebook, click here. Facebook's offices are located at 156 University Ave., Palo Alto, CA 94301

Tuesday, 9 October 2007

A First Guide to PostScript

What is PostScript?
PostScript is a programming language optimized for printing graphics and text (whether on paper, film, or CRT is immaterial). In the jargon of the day, it is a page description language. It was introduced by Adobe in 1985 and first (to my knowledge) appeared in the Apple LaserWriter. The main purpose of PostScript was to provide a convenient language in which to describe images in a device independent manner. This device independence means that the image is described without reference to any specific device features (e.g. printer resolution) so that the same description could be used on any PostScript printer (say, a LaserWriter or a Linotron) without modification. In practice, some PostScript files do make assumptions about the target device (such as its resolution or the number of paper trays it has), but this is bad practice and limits portability.

The language itself, which is typically interpreted, is stack-based in the same manner as an RPN calculator. A program pushes arguments for an operator onto a stack and then invokes the operator. Typically, the operator will have some result which is left at the top of the stack. As an example, let us say we want to multiply 12 and 134. We would use the following PostScript code:

12 134 mul

The first two words “12” and “134” push the numbers 12 and 134 onto the stack. “mul” invokes the multiply operator which pops two values off the stack, multiplies them, and then pushes the result back onto the stack. The resulting value can be left there to be used by another operator later in the program.

To follow the conventions used by Adobe in their manuals, I will synopsize operators using the following scheme: arg-1 arg-2 ... operator result. This scheme means that, to use operator, you must push arguments arg-1, arg-2, and so on before invoking the operator. operator will return the result: result. Many operators return no result (they have some side-effect); these will be shown as returning “-”.

Graphics Concepts
There are a few concepts that you need to know about before we dive into the language itself. These concepts are the concepts PostScript uses to describe and manipulate images on a page. There are really only a few.

Device Space
This is the coordinate space understood by the printer hardware. This coordinate system is typically measured in terms of the device’s resolution. There is really nothing else that can be said about this space, as PostScript programs are typically not expressed using it.
User Space
This is the coordinate system used by PostScript programs to describe the location of points and lines. User space is essentially the same as the first quadrant of the standard coordinate system used in high school math classes. Point (0, 0) is in the lower left corner. Coordinates are real numbers, so there is no set resolution in user space. The interpreter automatically converts user space coordinates to device space.
Current Transformation Matrix
The transformation of user space coordinates to device space coordinates is done through the current transformation matrix. This matrix is a three by three matrix that allows the user to rotate, scale, and translate the entire user space within the device space. This is the source of a lot of PostScript’s power, as will be demonstrated later.
Path
A path is a collection of (possibly disjoint) line segments and curves arranged on the page. The path does not describe actual ink on the paper; it merely describes an imaginary tracing over the page. There are operators which allow the user to draw ink along the path (stroke), fill an enclosed path with ink (fill), or clip out all future images that are outside the path (clip).
Current Path
This is the path that the PostScript program is creating at the moment. The current path is assembled piece by piece.
Clipping Path
The PostScript rendering system will ignore any part of a line segment, curve, or bitmap that extends outside a certain region; it will only draw the parts of those elements which are within the region. The region is described by a path called the clipping path. The clipping path is usually a rectangle about a quarter of an inch in from the edge of the page, but it can easily be set by the user to an arbitrary path.
Graphics State
This is a collection of various settings that describe the current state of the graphics system. Things like the current path, the current font, and the current transformation matrix make up the graphics state. Often, a program will need to temporarily save a graphics state to be used later. There are a couple of ways of doing this, but the easiest is to push the state onto a special graphics state stack and pop it back later. This can be accomplished with the gsave, and grestore operators.

Language Concepts
As a programming language, PostScript is particularly simple. There are really only a few concepts that need to be sketched out.

Comment
A comment in PostScript is any text preceded by a “%”. The special comment “%!” as the first two characters of a PostScript program is seen as a tag marking the file as PostScript code by many systems (including Unix’s lpr command). It is a good idea to start every PostScript document with a “%!”... doing so will ensure that every spooler and printer the document may encounter will recognize it as PostScript code.
Stack
There are several stacks in a PostScript system, but only two are important for this guide: the operand stack, and the dictionary stack. The operand stack is where arguments to procedures (or operators, in PostScript jargon) are pushed prior to use. The dictionary stack is for dictionaries, and it provides storage for variables.
Dictionary
A dictionary is a collection of name-value pairs. All named variables are stored in dictionaries. Also, all available operators are stored in dictionaries along with their code. The dictionary stack is a stack of all currently open dictionaries. When a program refers to some key, the interpreter wanders down the stack looking for the first instance of that key in a dictionary. In this manner, names may be associated with variables and a simple form of scoping is implemented. Conveniently, dictionaries may be given names and be stored in other dictionaries.
Name
A name is any sequence of characters that can not be interpreted as a number. With the exception of spaces and certain reserved characters (the characters “(”, “)”, “[”, “]”, “<”, “>”, “{”, “}”, “/”, and “%”) any character may be part of a name. The name may even start with digits (1Z is a name, for example), but you can get into problems with them (1E10 is a real number). A name is seen as being a reference to some value in a dictionary on the dictionary stack.

It should be noted that there are a couple of names that are legal in PostScript which do not follow the above definition. These are the “[” and the “]” operators. Yes, they are operators and are stored in the dictionary. Some other names that might surprise you are: “=”, “==”, “<<”, and “>>”.

If a name is preceded by a slash, PostScript will place the name on the stack as an operand. If the name has no slash, the interpreter will look up its value in the dictionary stack. If the value is a procedure object, the procedure will be evaluated. If the value is not a procedure, the value will be pushed onto the operand stack.

Number
PostScript supports integers and reals. You can express numbers in two forms: radix form, and scientific notation. Radix form is a number of the form radix#value where radix specifies the base for value. Scientific notation is the standard mantissaEexponent form used in most languages.
String
Strings are, of course, just strings of characters. There are two ways of expressing strings in Level 1 PostScript. The most common way is to wrap your text in parentheses. For example the string “This is a string” would be written as (This is a string). You can also express a string as hexadecimal codes in angle brackets. For example, the string “ABC” would be expressed as <414243>. There are several escape codes that may be used in the parenthesis format of strings.
Array
Arrays in PostScript are like arrays in any other language. Arrays may contain objects of different type, and they are written as a list of objects surrounded by brackets. For instance, [12 /Foo 5] is a three element array containing the number 12, the name Foo, and the number 5.
Procedure
A procedure is your way of defining new operators. A procedure is an array that is executable and is written with braces rather than brackets. For example, a procedure to square the top element on the stack might be written as: {dup mul}. We can define this procedure to be the square operator with: /square {dup mul} def.

Programming in PostScript
Programming in PostScript is really pretty easy. The fundamentals are that you push operands onto the operand stack by naming them, and then you invoke the operator to use them. That’s really all there is to it. The real art is knowing which operator to use. Operators to draw and put text on the screen will be covered later, and these make up the bulk of PostScript code, but there are a couple that are used mainly for maintaining the program itself.

The first of these operators is def. “def” is responsible for entering a definition into the top-most dictionary on the dictionary stack. The top operand on the operand stack is the value, and the operand below the value is the key (and should be a name). Let’s say that we wanted to define the name “x” to have a value of 5. The PostScript to do this is: /x 5 def. Notice the use of the slash on the “x”. The slash ensures that the name “x” will be pushed onto the stack and not any value it may already have in the dictionary stack.

“def” is also used to define new operators. The value in this case is just a procedure. The following code defines an operator “foo” which adds its top-most two operands and multiplies the result with the next operand on the stack: /foo {add mul} def. Remember, operators that return results push them onto the stack, where they may be used later.

An important point to know when defining procedures is that the elements in the procedure are not evaluated until the procedure is invoked. That means that in the procedure {1 2 add 3 mul}, the actual names “add” and “mul” are stored in the array that is the procedure. This is different from an actual array in which the components are evaluated when the array is created. For contrast, the array [1 2 add 3 mul] contains one object: the number 9.

This delayed evaluation of procedure components has two important effects. First, the definition of an operator used in a procedure is the one that is in effect when the procedure is run, not when it is defined. Second, because each operator has to be looked up each time the procedure is invoked, things can be a little slow. Fortunately, PostScript provides a handy operator to replace each name in a procedure object with its current definition. This operator is called bind, and it can speed up your program considerably. Bind is typically used as:

/foo {add mul} bind def

This defines foo to be a procedure array with two components: the procedures for add and mul. Note that, if add or mul is re-defined after defining foo, foo will have the same behavior as before. Without the use of bind, foo’s behavior would change.

Drawing and Filling Shapes
Principles

The main purpose of PostScript is to draw graphics on the page. One of the elegant aspects of PostScript is that even text is a kind of graphic. The main task that must be mastered, then, is constructing paths which may be used to create the image.

To draw and fill shapes, the basic sequence is:

* Start the path with the newpath operator.
* Construct the path out of line segments and curves (the path need not be contiguous).
* Draw the path with the stroke operator or fill it in with the fill operator.

This basic sequence can be modified to do more complicated things as we will see later.
Drawing a Box

In this first example, we will draw a square inch box toward the lower left corner of the page. We start off by defining a function to convert inches into PostScript's main unit, the point (a point is defined in PostScript as 1/72th of an inch, which is slightly shorter than a true printer’s point of 1/72.27 inch). The conversion is simple, we just multiply the number of inches by 72. This gives us the function

/inch {72 mul} def

To actually draw the square, we start a new path and move the current point to a point an inch in from both margins. This is accomplished with the code:

newpath
1 inch 1 inch moveto

At this point, the path contains only the point (72, 72). We add in line segments leading away from this point with the lineto operator. This operator adds a line segment from the current point to the point specified to lineto and makes that point the new current point. We can build three sides of the box as follows:

2 inch 1 inch lineto
2 inch 2 inch lineto
1 inch 2 inch lineto

We can add the last line by telling PostScript to close up the path with the smallest possible line segment. The closepath operator does this. This operator is especially useful if you need a closed figure for filling. Once we have closed the path, we can draw it with the stroke operator. We finish off the example by ejecting the page (if you are using a printer). PostScript ejects a page with the showpage operator:

closepath
stroke
showpage

You can view and try the complete example, if you like.
Refinements

The lineto operator works in absolute coordinates within user space. That is, 72 72 lineto adds a line segment from the current point to the point (72, 72) in user space. In drawing the box, however, it is more convenient to ignore the absolute coordinates of the box's vertexes and think instead of the lengths and directions of its sides. Fortunately, PostScript provides a version of lineto which takes relative coordinates instead. This is the rlineto operator. rlineto adds the coordinates given as operands to the coordinates of the current point in the path to find the destination point. That is, 10 20 rlineto will draw a line from the current point to a point 10 points to the right and 20 points toward the top of the page. This is in contrast to 10 20 lineto which adds a line segment which always ends at (10, 20).

To see how we can use rlineto, let's replace the lineto lines in the last example with the following code:

1 inch 0 inch rlineto
0 inch 1 inch rlineto
-1 inch 0 inch rlineto

This new example will draw the same figure, but it draws the lines using relative coordinates instead of absolute. This makes it a little easier to visualize and has the added benefit that the same code can draw the three lines at a different location. Note that a negative relative x coordinate moves the point in the left direction while a negative relative y coordinate moves the point down the page.
Filling Shapes

Filling a shape is just as easy as drawing it. You create the path using the standard path creation operators, but instead of calling stroke at the end, you invoke the fill operator. The fill operator will fill the path with the current ink settings. If you want to fill a shape with a pattern, you will need to do some special tricks which we will cover later. We will use the box from above as an example, but we replace the original invocation of stroke with fill.

Fill uses a simple winding rule (which is described in the Programming Language Reference Manual) to determine what parts of the page are inside or outside the path. The regions that are inside are painted. Note that arbitrarily complex shapes can be filled with this operator so long as you have enough memory on your PostScript interpreter. You can easily fill in different shades and even some patterns, but to fill an area with a complex image takes some special effects which we will cover later.
Shading and Width

In PostScript, you can view lines as being drawn by pens that have a given width and ink as having particular shades. You are not restricted to completely black ink and one-point wide lines. PostScript provides two handy operators to change these characteristics.

The setgray operator sets the intensity of the ink used in drawing lines and filling shapes (actually, setgray affects all subsequent markings made on the page). setgray takes a single numerical argument between 0 and 1. “0” signifies black, and “1” signifies white. Numbers between these two values signify various shades of gray.

The setlinewidth operator does just what its name suggests: it sets the width of lines to be drawn. It takes a single numerical argument which is the width of the line in points. setlinewidth affects all lines stroked after the operator is invoked.

Both of these operators affect the markings placed on the page after they are called... they do not effect the path until it is stroked or filled. In particular, you can not set the width or gray level for one part of the path and then change it for another... they are the same for all parts of the path, since it is stroked or filled only once. Also, both of these operators affect part of the graphics state and can be saved with gsave and restored with grestore.

I have worked up an example using both these operators. I also demonstrate how you can use gsave and grestore to control the graphics state.

Putting Text on the Page
Printing text on a page is, understandably, a simple process. It consists basically of these main steps:

* Set up a font to use
* Set the current point to where the lower left corner of the text will be
* Give the string to print to the show operator

The show operator is the basic operator for printing strings of text. It takes a string and prints it out in the current font and with the lower left corner at the current point. After the text has been printed, the current point is at the lower right of the string.
Fonts

Fonts in PostScript are actually dictionaries. A font dictionary contains several operators. Most of these operators simply set up the path for a single character in the font. When PostScript needs to typeset an “A” in the current font, it finds the operator specified in the font for “A” and invokes it. This operator goes about the business of drawing the letter. This means that there is no fundamental difference between letters and any other kind of ink on the page: text is graphics. Furthermore, since a font is essentially just a program to draw things, the current graphics state applies to text just as much as it applies to lines and curves which your program draws. This is one of the most powerful features of PostScript, as we will see later.

The fonts themselves are stored in a special dictionary of fonts, and they are named. If you want to retrieve a font by name, you need to use the findfont operator. findfont retrieves the font from the dictionary (if it is there) and leaves the font on the stack. You can then specify how big the font should be and make it the current font. The basic process for setting the font is:

* Retrieve the font from the dictionary with findfont,
* Set the size of the font with scalefont,
* Make this new font the current font with setfont

scalefont takes two arguments, the lower argument on the stack is a font dictionary while the second is the size of the new font in points. scalefont returns a new font dictionary which is the same as the old one but scaled to the given size. setfont, on the other hand, takes a font dictionary and makes it the current font.

For example, let us say that we want to start typesetting in Times Roman, and we want it to be set to 20 points. The following code would set up the correct font:

/Times-Roman findfont % Get the basic font
20 scalefont % Scale the font to 20 points
setfont % Make it the current font

Since the font “Times-Roman” is stored in a dictionary, we search for it using its PostScript name. Your printer will usually come with a set of built in fonts and will almost always allow you to add more. The names of the fonts available will vary from printer to printer, but Times is almost always present. Fonts typically come in families. “Times” is the name of the family we used here, and it has four member fonts: Times-Roman, Times-Italic, Time-Bold, and Times-BoldItalic.
Showing Text

The show operator is used to typeset text on the page. It takes a single argument: a string containing the text to be typeset. Text can be considered to be part of the path, so you must also have set the current point with call to moveto or an equivalent operator. A typical call to show might look like this:

newpath % Start a new path
72 72 moveto % Lower left corner of text at (72, 72)
(Hello, world!) show % Typeset "Hello, world!"

If we ran this code right after the font selection code above, we would get the string “Hello, world!” printed an inch in from the lower left corner, and it would be printed in 20 point Times-Roman. You can actually try this example.

Adding Color
In recent years, color printers have become more common... to the point where it is almost impossible to buy a black-and-white printer. Fortunately, PostScript handles color documents quite easily, and you do not have to learn much to add color to your documents.

There are many, many ways to specify color. The science of color reproduction and perception is very complex and encompasses physics, chemistry, physiology, and psychology. PostScript provides a great deal of flexibility on this front, providing several different methods for specifying color to let you get as close as possible to the color you want specifying it in the way that is most natural in your application. I will discuss only two methods here, however, because—frankly—I know as much about color as a bee knows about ancient Phoenician.
RGB

The first method I will mention is the so-called RGB colorspace. In this model, you specify the red, green, and blue components of the color you want to reproduce. This is model specifies color using the additive primaries and will be very familiar to those who work with monitors and computer graphics.

To specify a color using the RGB color space, you can use the setrgbcolor operator. This operator takes three operands: the red, green, and blue components of the color you want (0 means none, 1 means maximum). For example, to specify red, you can write 1 0 0 setrgbcolor; and to get a dark yellow, you can write 0.5 0 0.5 setrgbcolor. Black is 0 0 0 setrgbcolor, and white is 1 1 1 setrgbcolor.
CMYK

Another way to specify color is through the CMYK colorspace. In this model, you specify color using the subtractive primaries more common in the printing world: cyan, magenta, and yellow. To the primaries, a black component is added, to allow you to control the tone of the color (this is not necessary in the RGB model, since you are controlling the intensity of the light inherently).

To specify a color using the CYMK color space, you can use the setcymkcolor operator. This operator takes four operands: the cyan, yellow, magenta, and black components of the color you want (0 means none, 1 means maximum). For example, to specify red, you can write 0 1 1 0 setcymkcolor; and to get a dark yellow, you can write 0 1 0 0.5 setcymkcolor.

One convenient property of PostScript is that color is handled as a property of the ink in the graphics state just like the gray level. In fact, the gray level set by setgray is really just color. What this means is that you can set the color of a line, or the color of a fill in exactly the same way as you set the gray level. You just call the operator before you stroke the line or fill the path. You can even use it to set the color of text by calling the appropriate operator before you call show.

Since color works in such a similar way to the setgray operator, I am providing you with a complete example, but I will not break it down here.
A Warning

I have really simplified things considerably in this discussion. There are more than just two color spaces in PostScript, and there are several features in PostScript to allow for accurate color rendition. One thing that I’ve glossed over is that different devices reproduce color with different degrees of accuracy (and different pigments not only have different color-accuracy but will vary over time). Another thing that I have glossed over is the fact that these two models are focused around color reproduction: it is also possible to specify color based on how it is perceived.

If you do not care about color reproduction to that level of precision, then you do not need to worry about it. The color operators I have described are sufficient. If you do, you know far more about the matter than I do and will likely find the features you need described in the PLRM.

Transformations
The PostScript interpreter keeps track of a matrix called the current transformation matrix. When constructing an image, the interpreter uses this matrix to convert the world coordinates used by the program into device coordinates used by the printer itself. Generally, the actual contents of the matrix are of little interest to a well-written PostScript program; the reason for this is that the specific contents are device-dependent. A program that uses them might not work properly. PostScript does provide a number of operators, however, that transform the matrix in a device-independent way. These operators allow you to transform the way user space maps onto device space, and they modify the current transformation matrix with a simple matrix transformation. The basic transformation operators are:

* rotate
* translate
* scale

It is useful to realize that the current transformation matrix (and, hence the effect of all these operators) is part of the current graphics state and can be saved and restored using the gsave, and grestore operators. In addition, the transformations on the matrix affect path components constructed after the transformation. Even if a path is only partially constructed when a transformation is invoked, the parts of the path that were in place before the transformation will be unaffected.
Rotate

The rotate operator takes a single, numerical operand. This operand specifies how many degrees to rotate the user space around its origin (positive values specify counter clockwise rotations). This transform allows you to do some pretty neat tricks. For example, let’s say you have written a routine to draw some complex shape; and you have found that you need to draw it several times at different angles. In a more primitive graphics system, you might need to re-write to routine to take an angle as an argument, but in PostScript you only need to rotate the coordinates with the rotate operator.

As a concrete example, let’s say you want to draw lines in a circular pattern so that each line is ten degrees from its neighbors. Rather than figure out the coordinates for each of the 36 lines, we can just draw a horizontal line and rotate it repeatedly to different angles. To do the repeated looping, we can use the for operator. The for operator takes four arguments: an initial index value, a step size, a final index value, and a procedure. The operator increments an index from the initial value to the final value, incrementing it by the step size. For each index value, for will push the index on the stack and execute the procedure. This gives you a simple means of looping.

We start by setting up the for loop. At the beginning of the loop’s procedure, we start a new path and save the graphics state.

0 10 360 { % Go from 0 to 360 degrees in 10 degree steps
newpath % Start a new path
gsave % Keep rotations temporary

We next set the start of the line to (144, 144) and rotate the coordinates, we do not rotate before moving because (144, 144) would then be in a different location.

144 144 moveto
rotate % Rotate by degrees on stack from 'for'

We next draw just a horizontal line:

72 0 rlineto
stroke

Finally, we restore the old graphics state and end the loop.

grestore % Get back the unrotated state
} for % Iterate over angles

Translate

The translate operator takes two operands: an x-coordinate, and a y-coordinate. The translate operator sets the origin of user space to the point that was at the given coordinates in user space. The main use of the translate is to draw copies of a shape in different locations. Typically, a shape will be constructed at the origin, and the shape will be translated to the correct location before it is to be drawn. A simple example translates a box constructed at the origin to the point (72, 72) in the original user space.
Scale

The scale operator takes two arguments: an x scale factor, and a y scale factor. The operator scales each coordinate by its associated scale factor. That is, if you have an x scale factor of 0.5 and a y scale factor of 3, the x coordinate will be reduced by a factor of two while the y coordinate will be magnified by a factor of 3. This operator allows you to change the size and dimensions of objects quite easily.

A simple example can just scale text in a couple of ways: We can make things narrow:

gsave
72 72 moveto
0.5 1 scale % Make the text narrow
(Narrow Text) show % Draw it
grestore

We can make things tall:

gsave
72 144 moveto
1 2 scale % Make the text tall
(Tall Text) show % Draw it
grestore

We can distort the text completely:

gsave
72 216 moveto
2 0.5 scale % Make the text wide and short
(Squeezed Text) show % Draw it
grestore

Combining Transformations

Each of these transformations merely modifies the current transformation matrix. This means that these operators can be combined for some interesting effects. For example, you can take a normal document and print two of its pages on a single page (reduced and placed side-by-side) simply by translating the first page to one side, rotating the page by ninety degrees and then reducing the page so that it fits. The second page is handled in the same manner, but is translated to the other side of the page. This can be easily done by PostScript post-processors so long as they know where one page ends and the next begins (this is often accomplished using special comments). A somewhat simpler example is to draw a simple box and some text translated, rotated, and scaled in various ways. An important thing to remember when viewing this example is that translations are always relative to the current user space. This means that

0.5 0.5 scale
72 72 translate

will have a different effect on the image than does

72 72 translate
0.5 0.5 scale

In the first case, the origin will be half an inch in from the bottom and left margins. In the second case, the origin will be an inch in from the two margins.

Clipping for Effect
Within the graphics state of a PostScript system is a special path called the clipping path. Every bit of ink to be placed on the page is checked against this path. If PostScript determines that the ink would go outside the current clipping path, that portion of ink is ignored. If the ink would be within the clipping path, it is actually placed on the page. For the mathematically inclined, the clipping process is intersection: the set of pixels to be painted is intersected with the set of pixels within the current clipping path to get the set of pixels to paint. For objects that are partly inside and partly outside the clipping path, the natural implication is that only the part that is within the clipping path is drawn.

By default, the clipping path is defined to be a rectangle just within the boundary of the page (usually it is set to about a quarter of an inch). You can set your own clip path by constructing the path with the normal path construction operators and invoking the clip operator. There is only one difficulty: once you reduce the size of the current clipping path, there is no way to expand the size of the clipping path with clip. The only way to go back to a larger clipping path is to save the one you would like to restore with gsave and restore it later with grestore. In fact, it is always good policy to only set a clipping path withing a bracketing gsave/grestore pair. You will always be safe if you do this.
Clipping a Simple Path

As a simple example of clipping, let us say that we want to draw a box and fill it with text in such a way that some text is cut off. The effect we are wanting is that of a hole in a piece of paper over some newsprint, say. This can be done quite simply.

First, we set up the box to act as our window. We can set up the path, stroke it if we want to see it, and then clip to it:

gsave % Save the old clip path
72 72 box % Set up our box
gsave % Don't allow box to be lost after stroke
stroke
grestore % Restore the box path
clip % Clip to the box

The clip path is now established, and we can now go on to draw the text that should be clipped (note that there is a leading gsave... this is to keep us from loosing our old clip path which covered the whole page).

60 60 moveto
(This is Times-Roman clipped to a box) show
70 90 moveto
(This is Times-Roman clipped to a box) show
50 120 moveto
(This is Times-Roman clipped to a box) show

Once we have finished, we can just do a grestore to clean up after ourselves.

While there are some implementation limitations on the complexity of the clip path, in general you can have very complex paths... not just squares. Arcs, lines, even text can be used to create the clip path.
Clipping to Text

There may come a time when you will want to do some special effects with text. For example, you might want to print out “July 4” using letters that look like the flag. This is fairly easy to do using clipping. A somewhat simpler problem would be to draw text that looks like a sunburst (that is, the text is filled with a sunburst pattern). This is also fairly easy to do once you know how to clip to text. The secret is an operator called charpath. This operator takes a string and a Boolean and builds the path at the current point that would trace out the text of the string. The path, once created, can be stroked, filled, clipped, or any other combination of things; it is, after all, just a path. The Boolean which charpath requires is for handling special kinds of fonts, and it is generally left true.

As before, the steps to this example are to build the path, clip to it, and draw the image needing to be clipped.

Here we build the path by setting up our current point and string, and then invoking charpath:

gsave % Save old clip path
/Times-Roman findfont 60 scalefont setfont
72 72 moveto (Clipping) true charpath % Set up the text's path

Once we have the path, we can invoke clip to establish the complex path of the text as the current clip path. With the clip path established, we can draw our sunburst, which will be confined to the area inside the text:

clip
174 72 translate % Set our origin to middle
0 2 360 { % For every second degree of circle
newpath
gsave
rotate % Rotate to angle
0 0 moveto % From new origin
300 0 rlineto % Setup a 300 point long line
stroke % ... and draw it
grestore
} for

Again, because of our judicious use of gsave and grestore, a simple grestore cleans up the graphics state when we're done.

grestore

As you might imagine, this sort of effect is very powerful and can make it very easy for you to create some stunning images.

Raster Graphics
One of the common questions I have gotten over the years is how to handle other graphics file formats in PostScript. People often ask about including GIFs, JPEGs, and the like in a PostScript file. While this sort of thing is really beyond the scope of this guide, the basics of handling so-called raster graphics is not.
Raster Graphics Basics

Raster graphics is that style of graphics in which the image is broken up into a matrix of picture elements (pixels). The matrix will have a certain number of rows, each containing a certain number of pixels. Each pixel can be assigned any of a number of colors. The number of colors depending upon the “depth” of the image, often expressed as the number of bits needed to encode all the colors. Typical bit depths used today are: 1 (two colors, usually black and white), 2 (four colors, usually shades of gray), 4 (16 colors), 8 (256 colors), 16 (65,536 colors), 24 (so-called true color), and 32 (more colors than you can shake a stick at).

The numbers of rows and columns gives you the resolution. If there are c columns and r rows, the image is referred to as a r x c image. If the image is to have a certain physical size, this size combined with the number of pixels give you the number of dots-per-inch (DPI) of the image, which is a measure of its resolution. The higher the DPI, the smaller the dots, and the harder it is to see them as individuals.

Raster graphics are convenient in that they can represent photo-realistic images quite easily, but they have limitations. Because the pixels are arranged in a regular pattern, weird moire patterns can appear if they are displayed on a monitor incorrectly, or if they represent an image with a regular pattern that interacts badly with the pattern of the pixels. Likewise, if the resolution is too low and the contrast is too high, certain pixels can stand out and leave the image with the “jaggies.”
Raster Graphics in PostScript

Most graphics work in PostScript is done in vector graphics style. This style of graphics is where the image is composed of lines and curves that are described mathematically. It is the style of graphics we have used throughout the guide. The advantage of vector graphics is that you can do all sorts of mathematical operations on the image (rotate, scale, etc.) and still get a decent image. An implication of this is that vector graphics are device independent, since they do not care about the display resolution of the display device. Still, PostScript recognizes the need for support of raster graphics, and so it provides a set of operators just to display raster graphics.

The main operator is image, and it is fairly complex. Go grab yourself a cup of coffee, stretch your legs, and prepare to tuck in.

image takes five arguments that describe the image to be displayed and paints that image in a square with one corner at (0, 0) and the other at (1, 1) in the current coordinate frame. All the operands describe the image data and how it should be used to fill up that square. Of course, you probably do not want to draw images in the unit square at (0, 0) all the time, so you must use scale, rotate, and translate to move the unit square to the desired location (and size).

The image operator is used in the following way: width height depth matrix data image -. The operands width and height define the size and shape of image matrix in terms of pixels (in the image data, not the display results). The operand depth describes the number of bits per pixels and, hence, the number of shades of gray. Legal values here are 1 (black and white), 2 (four shades), 4 (16 shades), 8 (256 shades), and 12 (4,096 shades). The operand matrix is a PostScript transform matrix that maps from the unit square to the image’s pixel coordinates. The image’s coordinates go from (0, 0) in the lower left to (width, height) in the upper right. The last operand, data is the source of the actual image data. In Level 1 PostScript, this is a procedure, but it can be any number of things in Level 2 and Level 3. Just sticking with Level 1 for now, this procedure is called to fetch all the data for the image, as needed. The procedure returns a string, and the bits within the string are taken and dismantled to create the image. If the procedure does not return enough data to cover the whole image, it is called repeatedly until all the pixels are accounted for. The order at which the pixels are handled is left to right, bottom to top.

Clear? I didn’t think so. Let’s take a look at a simple example that will show you the basics. Let’s draw a simple smiley face. First, let’s take a look at how the smiley face will be laid out in the matrix:
. . X X X X . . C3
. X . . . . X . BD
X . X . . X . X 5A
X . . . . . . X 7E
X . X . . X . X 5A
X . . X X . . X 66
. X . . . . X . BD
. . X X X X . . C3

The left eight columns are the eight columns of the image. The “X” represents a black pixel, and the “.” represents a white pixel. Since black is represented by a 0 in PostScript, and white by a 1, we can convert this 8x8 matrix into an eight byte sequence. The ninth column is the hexadecimal encoding of the row... taking the others columns as a binary number with the dots representing 1’s and the X’s representing 0’s.

Now, let’s take this image data and try to build up an actual image. First, we need to map the unit square to the location we want to show the image in. Let’s make the image a 1 inch square image with the lower left corner at (72, 72).

gsave % We're mucking about with graphics state... save the original
72 72 translate % position the lower left at (72, 72)
72 72 scale % make the image 1 inch square

Now, we set up the actual image data.

8 % 8 columns in the image
8 % 8 rows in the image
1 % 1-bit per pixel: black and white
[8 0 0 8 0 0] % map the unit square to (0, 0) - (8, 8)
{} % the image data as a hex-encoded string
image % actually draw the image
grestore

Note that the pixel data maps left to right the same way the bits do when you write them in binary. That is, the left-most pixel for a given byte in the data maps to the left-most bit in the byte. Also, note the funny way the string is specified. It is written in hexadecimal using the < and > notation instead of the more usual parenthesis notation. This notation indicates that what is contained between the < and > is a string of 8-bit data bytes encoded in hex. You will see this notation fairly often in working PostScript, since it is a convenient way to store binary data in an ASCII format.
A Gradient

This example is all well and good, but it is just black and white. How do you deal with gray scale images? The procedure is similar, you just specify a different bit depth and lay out your data in a slightly different manner (instead of a single bit per pixel, you will now need to map multiple bits per pixel. As an example, let’s try to make a horizontal gradient fill that goes through sixteen different shades:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Sixteen different shades implies 4 bits per pixel, which means that this data can be represented in 8 bytes again (2 pixels per byte). Encoded in hexadecimal again, the data for the above gradient is: 0123456789ABCDEF. Now, we just need to do with this data what we did before, with one exception. The image data no longer represents an 8x8 image, instead it represents a 16x1 image that is 4 bits deep... we need to modify the settings accordingly. Also, instead of scaling this image to a 1 inch square, let’s make it 2 inches high by 1 wide and set it next to the smiley face:

gsave
216 72 translate % lower-left of images at (216, 72)
72 144 scale % size of rendered image is 72 points by 72 points
16 % 16 pixels wide
1 % 1 pixel high
4 % 4 bits per pixel
[16 0 0 1 0 0] % transform array... maps unit square to pixels
{<0123456789ABCDEF>} % the image data itself
image % let's draw!
grestore

Note that, even though the image data is for a one line image, we can scale that single line to fill just about any area. By the way, drawing with the image operator is very much like drawing with any other operator. In particular, clipping can be used to control what parts of the page can be filled by image, so you can use it to do interesting effects like shapes (or text) with gradient fills or with a photographic image as a fill pattern.
The Basics of Color

So, these examples are nice and all, but they are in dull monochrome. What if you want to do color? PostScript does include a handy operator for color images called, creatively enough colorimage. The colorimage operator adds a number of operands to handle the addition of color and to provide for a number of ways of supplying the color data.

The first thing to consider is how you want to specify the colors. Is your image grayscale? RGB? CMYK? This information will indicate the number of color channels you need. Grayscale takes one. RGB takes three (one for red, one for green, and one for blue). Finally, CMYK takes four: cyan, magenta, yellow, and black. Next, you need to think about how these channels are going to be provided to the colorimage operator; will they be interleaved into a single data source string, or will they be broken out into separate data sources. These two decisions will determine the number of additional operands to colorimage: one specifies the number of channels, one specifies whether the channels are separate or interleaved, and then there is one for each channel data source.

To make this a bit more concrete, let’s take a look at a color gradient, which will be a variant of the previous gradient:
Gradient: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Red: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Green: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Blue: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

So, we will now lay this information out in a very similar manner to the original gradient. The example, however, will use three color channels, and they will be provided by separate data sources:

gsave
360 72 translate % set lower left of image at (360, 72)
72 144 scale % size of rendered image is 72 points by 72 points
16 % number of columns per row
1 % number of rows
4 % bits per color channel (1, 2, 4, or 8)
[16 0 0 1 0 0] % transform array... maps unit square to pixels
{<0000000000000000>} % the red image data
{} % the green image data
{<0123456789ABCDEF>} % the blue image data
true % pull channels from separate sources
3 % 3 color channels (RGB)
colorimage
grestore

Note that the bits-per-pixel operand is really a bits-per-pixel-per-channel operand. This is really no different than for image, it is just that image always works with a single channel. In fact the call:

w h bpp matrix data image

is exactly equivalent to:

w h bpp matrix data true 1 colorimage

Wrap-up

You have now seen a basic example of three different types of raster graphics in PostScript (you can view a complete example of all three). This is only a start, however.

Encapsulated PostScript
What is Encapsulated PostScript?

At some point, you may want to include some nice PostScript image into a document. There are a number of problems associated with this, but the main one is that your page layout program needs to know how big the image is, and how to move it to the correct place on the page. Encapsulated PostScript (EPS) is that part of Adobe’s Document Structuring Convention that provides this information.
What Is the Document Structuring Convention?

The DSC is a special file format for PostScript documents. The full details for the DSC can (and should) be gotten from Adobe. If you are writing a PostScript printer driver or other utility which will be used by a large number of people to create or manipulate PostScript documents, do not even think about writing it without making it DSC-compliant. You will save yourself and your users a lot of headaches.

Although the full DSC is beyond the scope of this guide, the most basic rules can be explained. A DSC-compliant document is an ordinary PostScript document with a number of comments added. These comments provide information to any post-processors which work with the files. Some comments strictly provide information, others are used to structure the document into sections, which may be shuffled or processed in other ways by the post-processor.

Every DSC-compliant document is indicated by having the comment %!PS-Adobe-3.0 as the first line. This comment is a flag to indicate that the document is compliant. You should never use this comment unless your document really is DSC compliant. There are many other parts to proper DSC. A document which follows the DSC can be manipulated in many ways. In particular, post-processors can shuffle the pages, print two or more pages on a side, and so on. The printer drivers from some notable companies do not follow the DSC, and their PostScript documents are, therefore, impossible to work with once they’ve been generated.
Now, What About EPS?

An EPS file is a PostScript file which follows the DSC and which follows a couple of other rules. These rules can be summarized as follows:

* The first line must be %!PS-Adobe-3.0 EPSF-3.0
* The file must make use of the BoundingBox comment
* The file should be a single page image (in DSC terms, the %%Pages comment must have a value of 0 or 1).
* The file should not use any operators which affect the global state.
* Finally, the EPS file should not use showpage. Actually, Adobe says that it is fine to use showpage in your EPS files. Officially, it is the responsibility of the importing application to redefine showpage so that the EPS file does not actually eject the page. Still, in creating EPS files, it would be wise not to use this operator.

BoundingBox

The BoundingBox comment is used in DSC to indicate where the actual image will be on a page. The comment describes a rectangle which completely encloses the image. The form of the comment is: %%BoundingBox: llx lly urx ury. For instance, suppose I have an image which extends from x=72 to x=144 and from y=150 to y=170. The BoundingBox comment in the document should then be: %%BoundingBox: 72 150 144 170.