Line and Circle

postscript languageの基本アイテムである、直線と円をまずは描いてみる。

x0 y0 moveto : 始点(x0, y0)のセット
x1 y1 lineto: 終点(x1,y1)への直線描画
x0 y0 r0 phi0 phi1 arc : 原点(x0,y0)、半径r0、角度phi1からphi2までの (半時計回り)の円弧

script 1: line.ps
    %!PS-adobe-3.0
    newpath

    300 700 moveto
    500 500 lineto
    300 300 lineto
    100 500 lineto
    closepath
    stroke

    showpage
  

4本の直線によって、正方形を描くスクリプト。

まずは%! PS-adobe-3.0によって、 OSにこのスクリプトはPSであることを伝える。
file line.psとすると、ちゃんとpostscript textと認識してくれる。

postscriptのscriptで必ず必要なのが、newpathshowpage。 すべてのコマンドは、この2つのコマンドに挟まれることになる。

正方形の頂点はA(300,700), B(500,500), C(300,300),D(100,500)。
A-B-C-D-Aの順番で直線を引いている。 これは、四角形の最上頂点から時計回りでの描画に相当。
movetoでAに移動。linetoでB,C,Dと直線を引く(準備をする)。
ただし、strokeコマンドが実行されるまで、実際の描画はされない。変数の保持は strokeが実行されるまで。

ポストスクリプトの基本は「一筆書き」。 最後はD-Aの直線はclosepathで実行する。閉曲線を描く時はこのコマンドが便利。

script 1: Result

次は、この四角形に内接する円を描いてみる。

四角形の中心は(300,500)。したがって内接円の半径は100√2となる。

script 1.1: line_and_circle.ps
    %!PS-Adobe-3.0
    newpath

% square drawing
    300 700 moveto
    500 500 lineto
    300 300 lineto
    100 500 lineto
    closepath

% circle drawing
    300 2 sqrt 100 mul add 500 moveto
    300 500 100 2 sqrt mul 0 360 arc fill
    stroke
    showpage
  

四角形を描いた後、円描画のための始点を、円周上にmovetoする必要がある。 中心と点Bを結ぶ直線と円の交点(300, 100√2)にその点を定めた。
100√2 = 100 2 sqrt mul = 2 sqrt 100 mulという代数表現に注意。

arc fillとしたら、正方形と円の間の囲まれた領域が塗りつぶされた。円の内部を塗りつぶすにはどうすればよいのだろうか?

Progarmme 1.1: Result

上のスクリプトの応用問題として、 eofill (even-odd fill)を用いて「弓道の的」のようなものを描いてみたが、 まだオブジェクトの偶奇の関係がよくわからず、場当たり的なスクリプトとなってしまった。

script 1.2: 弓道の的
%!PS-Adobe-3.0
newpath
%100 500 moveto

300 700 moveto
500 500 lineto
300 300 lineto
100 500 lineto
closepath

1 setgray
300 2 sqrt 100 mul add 500 moveto
300 500 100 2 sqrt mul 0 360 arc fill

0 setgray
300 2 sqrt 20 mul add 500 moveto
300 500 20 2 sqrt mul 0 360 arc fill

300 2 sqrt 40 mul add 500 moveto
300 500 40 2 sqrt mul 0 360 arc 

300 2 sqrt 60 mul add 500 moveto
300 500 60 2 sqrt mul 0 360 arc eofill

300 2 sqrt 80 mul add 500 moveto
300 500 80 2 sqrt mul 0 360 arc 

300 2 sqrt 100 mul add 500 moveto
300 500 100 2 sqrt mul 0 360 arc eofill 

stroke

3 setlinewidth

300 701 moveto
501 500 lineto
300 301 lineto
101 500 lineto
closepath 
stroke

showpage
  

Progarmme 1.2: Result