Home My Page Projects Code Snippets Project Openings 3D graphics for Standard ML
Summary Activity SCM

SCM Repository

[sml3d] Diff of /trunk/sml3d/src/particles/compiler/translate.sml
ViewVC logotype

Diff of /trunk/sml3d/src/particles/compiler/translate.sml

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1008, Sun Jan 16 17:04:08 2011 UTC revision 1143, Wed May 4 03:50:40 2011 UTC
# Line 1  Line 1 
1  (* translate.sml  (* translate.sml
2   *  
3   * COPYRIGHT (c) 2009 John Reppy (http://cs.uchicago.edu/~jhr)   * COPYRIGHT (c) 2009 John Reppy (http://cs.uchicago.edu/~jhr)
4   * All rights reserved.   * All rights reserved.
5   *   *
# Line 8  Line 8 
8    
9  structure Translate : sig  structure Translate : sig
10    
11      val compile : Particles.particle_group -> PSysIR.program      val compile : Particles.program -> PSysIR.program
12    
13    end = struct    end = struct
14    
# Line 20  Line 20 
20    
21      fun printErr s = TextIO.output(TextIO.stdErr, s ^ "\n")      fun printErr s = TextIO.output(TextIO.stdErr, s ^ "\n")
22    
23    (*
24      datatype particle_state = PS of {      datatype particle_state = PS of {
25          pos : IR.var,           (* vec3 *)          pos : IR.var,           (* vec3 *)
26          vel : IR.var,           (* vec3 *)          vel : IR.var,           (* vec3 *)
27          size : IR.var,          (* float *)          size : IR.var,          (* float *)
28          ttl : IR.var,           (* float *)          ttl : IR.var,           (* float *)
29          color : IR.var,         (* vec3 (NOTE: should be vector4) *)          color : IR.var,         (* vec3 (NOTE: should be vector4) *)
30          pos2 : IR.var,          (* vec3 *)        user : IR.var list
         dummy : IR.var  
31        }        }
32    *)
33        type particle_state = IR.var list
34    
35    (* special PSV global variables *)    (* special PSV global variables *)
36      val epsilon = PSV.constf(0.00001)      val epsilon = PSV.constf(0.00001)
# Line 36  Line 38 
38    (* constants *)    (* constants *)
39      val pi = 3.14159265358979      val pi = 3.14159265358979
40    
41    (* dummy placeholder *)      fun retState s = IR.mkRETURN s
     fun dummy (state, k) =  
           IR.mkPRIM(  
             IR.newLocal(  
               "temp",  
               IR.T_BOOL,  
               (IR.COPY, [IR.newConst("c", IR.C_BOOL false)])  
             ),  
             IR.COPY,  
             [IR.newConst("c", IR.C_BOOL false)],  
             k state  
           )  
   
   
     fun retState s = let  
       val PS{pos, vel, size, ttl, color, pos2, dummy} = s  
      in  
       IR.mkRETURN (  
         [pos, vel, size, ttl, color, pos2, dummy],  
         [IR.POS, IR.VEL, IR.SZ, IR.TTL, IR.COLOR, IR.POS2, IR.DUMMY]  
       )  
      end  
42    
43    (* translation environment *)    (* translation environment *)
44      datatype env = TE of (IR.block list ref * IR.var PSV.Map.map)      datatype env = TE of (IR.block list ref * IR.var PSV.Map.map)
45        fun insert (TE(blks, env), x, x') = TE(blks, PSV.Map.insert (env, x, x'))
46    
47      (* Interaction with environment and state variables *)
48      fun psvToIRVar (TE(_, env), x as PSV.V{name, id, ...}) = (case PSV.Map.find(env, x)      fun psvToIRVar (TE(_, env), x as PSV.V{name, id, ...}) = (case PSV.Map.find(env, x)
49             of SOME x' => x'             of SOME x' => x'
50              | NONE => raise Fail (String.concat["unknown variable ", name, " with ID ", Int.toString id])              | NONE => raise Fail (String.concat["unknown variable ", name, " with ID ", Int.toString id])
51            (* end case *))            (* end case *))
52    
53      fun insert (TE(blks, env), x, x') = TE(blks, PSV.Map.insert (env, x, x'))          fun findIRVarByName (state, name) = let
54              fun eq (var as IR.V{name=st_name, ...}) = st_name = ("ps_" ^ name)
   (* create a block that implements the given continuation *)  
     fun newBlock (TE(blks, _), k : particle_state -> IR.stmt) = let  
           val pos = IR.newParam ("ps_pos", IR.T_VEC)  
           val vel = IR.newParam ("ps_vel", IR.T_VEC)  
           val size = IR.newParam ("ps_size", IR.T_FLOAT)  
           val ttl = IR.newParam ("ps_ttl", IR.T_FLOAT)  
           val color = IR.newParam ("ps_color", IR.T_VEC)  
           val dummy = IR.newParam ("ps_dummy", IR.T_FLOAT)  
           val pos2 = IR.newParam ("ps_pos2", IR.T_VEC)  
           val state = PS{pos=pos, vel=vel, size=size, ttl=ttl, color=color, pos2=pos2, dummy=dummy}  
           val blk = IR.newBlock ([pos, vel, size, ttl, color, pos2, dummy], k state)  
55            in            in
56              blks := blk :: !blks;            (case (List.find eq state)
57              blk              of SOME sv => sv
58                 | NONE => raise Fail ("Could not find var mapping.")
59              (* end case *))
60            end            end
61    
62          fun newBlockWithArgs (TE(blks, _), args, k : particle_state -> IR.stmt) = let          fun getIRVarForSV (v as PSV.SV{name, ...}, state) = findIRVarByName(state, name)
63            val pos = IR.newParam ("ps_pos", IR.T_VEC)  
64            val vel = IR.newParam ("ps_vel", IR.T_VEC)     (* create a block that implements the given continuation *)
65            val size = IR.newParam ("ps_size", IR.T_FLOAT)      fun newBlockWithArgs (TE(blks, _), state , args, k : particle_state -> IR.stmt) = let
66            val ttl = IR.newParam ("ps_ttl", IR.T_FLOAT)         fun copyVar(v as IR.V{name, varType, ...}) = IR.newParam(name, varType)
67            val color = IR.newParam ("ps_color", IR.T_VEC)         val newState = List.map copyVar state
68            val dummy = IR.newParam ("ps_dummy", IR.T_FLOAT)             val blk = IR.newBlock (newState @ args, k newState)
           val pos2 = IR.newParam ("ps_pos2", IR.T_VEC)  
           val state = PS{pos=pos, vel=vel, size=size, ttl=ttl, color=color, pos2=pos2, dummy = dummy}  
           val blk = IR.newBlock ([pos, vel, size, ttl, color, pos2, dummy] @ args, k state)  
69            in            in
70              blks := blk :: !blks;              blks := blk :: !blks;
71              blk              blk
72            end            end
73    
74      fun goto (PS{pos, vel, size, ttl, color, pos2, dummy}, blk) =          fun newBlock (env, state, k) = newBlockWithArgs(env, state, [], k)
           IR.mkGOTO(blk, [pos, vel, size, ttl, color, pos2, dummy])  
75    
76          fun gotoWithArgs(PS{pos, vel, size, ttl, color, pos2, dummy}, args, blk) =      fun gotoWithArgs(state, args, blk) = IR.mkGOTO(blk, state @ args)
77            IR.mkGOTO(blk, [pos, vel, size, ttl, color, pos2, dummy] @ args)      fun goto (state, blk) = gotoWithArgs(state, [], blk)
78    
79      fun letPRIM (x, ty, p, args, body) = let      fun letPRIM (x, ty, p, args, body) = let
80            val x' = IR.newLocal(x, ty, (p, args))            val x' = IR.newLocal(x, ty, (p, args))
# Line 112  Line 82 
82              IR.mkPRIM(x', p, args, body x')              IR.mkPRIM(x', p, args, body x')
83            end            end
84    
   (* prim bound to state variable (S_LOCAL for now) *)  
     fun letSPRIM(x, ty, p, args, body) = let  
           val x' = IR.new(x, IR.S_LOCAL(ref (p, args)), ty)  
           in  
             IR.mkPRIM(x', p, args, body x')  
           end  
   
85    (* Not sure if this should be made into a primitive or not, but    (* Not sure if this should be made into a primitive or not, but
86     * basically this creates the XOR'd value of var1 and var2 and     * basically this creates the XOR'd value of var1 and var2 and
87     * stores it in result.     * stores it in result.
# Line 129  Line 92 
92            letPRIM("testNAND", IR.T_BOOL, IR.NOT, [testAND], fn testNAND =>            letPRIM("testNAND", IR.T_BOOL, IR.NOT, [testAND], fn testNAND =>
93            letPRIM(result, IR.T_BOOL, IR.AND, [testOR, testNAND], stmt))))            letPRIM(result, IR.T_BOOL, IR.AND, [testOR, testNAND], stmt))))
94    
95        fun genFloatVar (fltVar, env, domain : Float.float P.domain, dist, stmt : IR.var -> IR.stmt) = let
96          fun genRandVal(var, stmt : IR.var -> IR.stmt) = (case dist
97            of P.DIST_UNIFORM =>
98              letPRIM(var, IR.T_FLOAT, IR.RAND, [], stmt)
99    
100             (* The PDF here is f(x) = 2x when 0 < x <= 1, so the CDF is going
101              * to be the integral of f from 0 -> y => y^2. Hence, whenever we
102              * generate a random number, in order to get the random value according
103              * to this probability distribution, we just square it.
104              *)
105             | P.DIST_INC_LIN =>
106              letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
107              letPRIM(var, IR.T_FLOAT, IR.MULT, [randVal, randVal], stmt))
108    
109             (* The PDF here is f(x) = -2x + 2 when 0 <= x < 1, so the CDF is going
110              * to be the integral of f from 0 -> y => -(y^2) + 2y. Hence, whenever we
111              * generate a random number, in order to get the random value according
112              * to this probability distribution, we just square it.
113              *)
114             | P.DIST_DEC_LIN =>
115              letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
116              letPRIM("randSq", IR.T_FLOAT, IR.MULT, [randVal, randVal], fn randSq =>
117              letPRIM("termOne", IR.T_FLOAT, IR.MULT, [randSq, IR.newConst("negOne", IR.C_FLOAT ~1.0)], fn termOne =>
118              letPRIM("termTwo", IR.T_FLOAT, IR.MULT, [randVal, IR.newConst("negOne", IR.C_FLOAT 2.0)], fn termTwo =>
119              letPRIM(var, IR.T_FLOAT, IR.ADD, [termOne, termTwo], stmt)
120              ))))
121    
122             | _ => raise Fail "Unable to create random float for specified distribution"
123           (* end case *))
124         in
125         (case domain
126          of P.D_POINT(pt) =>
127             (* Our options here are pretty limited... *)
128             letPRIM (fltVar, IR.T_FLOAT, IR.COPY, [psvToIRVar(env, pt)], stmt)
129    
130           | P.D_BOX{max, min} =>
131             genRandVal("randf", fn rand =>
132             letPRIM("boxDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, max), psvToIRVar(env, max)], fn diff =>
133             letPRIM("scale", IR.T_FLOAT, IR.MULT, [diff, rand], fn scale =>
134             letPRIM( fltVar, IR.T_FLOAT, IR.ADD, [psvToIRVar(env, max), scale], stmt )
135             )))
136           | _ => raise Fail ("Cannot generate float in specified domain: " ^ (P.dToStr domain))
137         (* end case *))
138        end
139    
140    (* Generates a random vector within the given domain and puts it in vecVar *)    (* Generates a random vector within the given domain and puts it in vecVar *)
141      fun genVecVar (vecVar, env, domain, stmt : IR.var -> IR.stmt) = (case domain      fun genVecVar (
142          vecVar,
143          env,
144          domain : Vec3f.vec3 P.domain,
145          dist : Vec3f.vec3 P.distribution,
146          stmt : IR.var -> IR.stmt
147        ) = (case domain
148             of P.D_POINT(pt) =>             of P.D_POINT(pt) =>
149               (* Our options here are pretty limited... *)               (* Our options here are pretty limited... *)
150                  letPRIM (vecVar, IR.T_VEC, IR.COPY, [psvToIRVar(env, pt)], stmt)                  letPRIM (vecVar, IR.T_VEC, IR.COPY, [psvToIRVar(env, pt)], stmt)
151    
152              | P.D_LINE({pt1, pt2}) =>              | P.D_LINE({pt1, pt2}) =>
153    
154                (* Lerp between the points. *)                (* Lerp between the points. *)
155                  letPRIM ("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>                  letPRIM ("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
156                  letPRIM ("randInv", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), randVal], fn randInv =>                  letPRIM ("randInv", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), randVal], fn randInv =>
# Line 181  Line 196 
196    
197    
198              | P.D_TRIANGLE{pt1, pt2, pt3} =>              | P.D_TRIANGLE{pt1, pt2, pt3} =>
199    
200                  letPRIM ("pt1ToPt2", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn pt1ToPt2 =>                  letPRIM ("pt1ToPt2", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn pt1ToPt2 =>
201                  letPRIM ("pt1ToPt3", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt3), psvToIRVar(env, pt1)], fn pt1ToPt3 =>                  letPRIM ("pt1ToPt3", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt3), psvToIRVar(env, pt1)], fn pt1ToPt3 =>
202                  letPRIM ("randOne", IR.T_FLOAT, IR.RAND, [], fn rand1 =>                  letPRIM ("randOne", IR.T_FLOAT, IR.RAND, [], fn rand1 =>
# Line 201  Line 217 
217                    letPRIM("htInv", IR.T_FLOAT, IR.DIV, [IR.newConst("one", IR.C_FLOAT 1.0), height], fn htInv =>                    letPRIM("htInv", IR.T_FLOAT, IR.DIV, [IR.newConst("one", IR.C_FLOAT 1.0), height], fn htInv =>
218                    letPRIM("n", IR.T_VEC, IR.SCALE, [htInv, normVec], fn norm =>                    letPRIM("n", IR.T_VEC, IR.SCALE, [htInv, normVec], fn norm =>
219                    (* Generate a point in the lower disc. *)                    (* Generate a point in the lower disc. *)
220                      genVecVar("ptInDisc", insert(env, normVar, norm), P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad}, fn ptInDisc =>                      genVecVar("ptInDisc",
221                          insert(env, normVar, norm),
222                          P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},
223                          dist,
224                          fn ptInDisc =>
225                    (* Now add this point to a random scaling of the normVec. *)                    (* Now add this point to a random scaling of the normVec. *)
226                      letPRIM("s", IR.T_FLOAT, IR.MULT, [height, ourRand], fn scale =>                      letPRIM("s", IR.T_FLOAT, IR.MULT, [height, ourRand], fn scale =>
227                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, normVec], fn scaledNormVec =>                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, normVec], fn scaledNormVec =>
# Line 209  Line 229 
229                   end                   end
230    
231              | P.D_DISC {pt, normal, irad, orad} =>              | P.D_DISC {pt, normal, irad, orad} =>
232    
233                (* Get a random angle... *)                (* Get a random angle... *)
234                  letPRIM ("r", IR.T_FLOAT, IR.RAND, [], fn randForAng =>                  letPRIM ("r", IR.T_FLOAT, IR.RAND, [], fn randForAng =>
235                  letPRIM ("t", IR.T_FLOAT, IR.MULT, [randForAng, IR.newConst("fullCir", IR.C_FLOAT (2.0 * pi))], fn randAng =>                  letPRIM ("t", IR.T_FLOAT, IR.MULT, [randForAng, IR.newConst("fullCir", IR.C_FLOAT (2.0 * pi))], fn randAng =>
236    
237                (* Get a random radius *)                (* Get a random radius *)
238                  letPRIM ("e0", IR.T_FLOAT, IR.RAND, [], fn newRand =>                  letPRIM ("e0", IR.T_FLOAT, IR.RAND, [], fn newRand =>
239                  letPRIM ("e0sq", IR.T_FLOAT, IR.MULT, [newRand, newRand], fn randRadSq =>                  letPRIM ("e0sq", IR.T_FLOAT, IR.MULT, [newRand, newRand], fn randRadSq =>
240                  letPRIM ("radDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, orad), psvToIRVar(env, irad)], fn radDiff =>                  letPRIM ("radDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, orad), psvToIRVar(env, irad)], fn radDiff =>
241                  letPRIM ("newRadDist", IR.T_FLOAT, IR.MULT, [randRadSq, radDiff], fn newRadDist =>                  letPRIM ("newRadDist", IR.T_FLOAT, IR.MULT, [randRadSq, radDiff], fn newRadDist =>
242                  letPRIM ("newRad", IR.T_FLOAT, IR.ADD, [psvToIRVar(env, irad), newRadDist], fn newRad =>                  letPRIM ("newRad", IR.T_FLOAT, IR.ADD, [psvToIRVar(env, irad), newRadDist], fn newRad =>
243    
244                (* Find a vector in the plane of the disc, and then                (* Find a vector in the plane of the disc, and then
245                 * translate it to the center.               * translate it to the center. *)
                *)  
246                  letPRIM ("ntoc", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn normToCen =>                  letPRIM ("ntoc", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn normToCen =>
247                  letPRIM ("v", IR.T_VEC, IR.CROSS, [psvToIRVar(env, pt), normToCen], fn vecInDisc =>                  letPRIM ("v", IR.T_VEC, IR.CROSS, [psvToIRVar(env, pt), normToCen], fn vecInDisc =>
248                  letPRIM ("vidn", IR.T_VEC, IR.NORM, [vecInDisc], fn vecInDiscNorm =>                  letPRIM ("vidn", IR.T_VEC, IR.NORM, [vecInDisc], fn vecInDiscNorm =>
249                  letPRIM ("p", IR.T_VEC, IR.CROSS, [vecInDiscNorm, psvToIRVar(env, normal)], fn ptInDisc =>                  letPRIM ("p", IR.T_VEC, IR.CROSS, [vecInDiscNorm, psvToIRVar(env, normal)], fn ptInDisc =>
250                  letPRIM ("pidn", IR.T_VEC, IR.NORM, [ptInDisc], fn ptInDiscNorm =>                  letPRIM ("pidn", IR.T_VEC, IR.NORM, [ptInDisc], fn ptInDiscNorm =>
251    
252                (* Figure out x and y values for our new radius and angle *)                (* Figure out x and y values for our new radius and angle *)
253                  letPRIM ("rx", IR.T_FLOAT, IR.COS, [randAng], fn radX =>                  letPRIM ("rx", IR.T_FLOAT, IR.COS, [randAng], fn radX =>
254                  letPRIM ("ar1", IR.T_FLOAT, IR.MULT, [newRad, radX], fn amtVecOne =>                  letPRIM ("ar1", IR.T_FLOAT, IR.MULT, [newRad, radX], fn amtVecOne =>
# Line 234  Line 257 
257                  letPRIM ("ar2", IR.T_FLOAT, IR.MULT, [newRad, radY], fn amtVecTwo =>                  letPRIM ("ar2", IR.T_FLOAT, IR.MULT, [newRad, radY], fn amtVecTwo =>
258                  letPRIM ("rv2", IR.T_VEC, IR.SCALE, [amtVecTwo, ptInDiscNorm], fn resVecTwo =>                  letPRIM ("rv2", IR.T_VEC, IR.SCALE, [amtVecTwo, ptInDiscNorm], fn resVecTwo =>
259                  letPRIM ("res", IR.T_VEC, IR.ADD_VEC, [resVecOne, resVecTwo], fn result =>                  letPRIM ("res", IR.T_VEC, IR.ADD_VEC, [resVecOne, resVecTwo], fn result =>
260                  letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [result, psvToIRVar(env, pt)], stmt))))))))))))))))))))  
261                letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [result, psvToIRVar(env, pt)], stmt)
262                )))))))))))))))))))
263    
264              | P.D_CONE{pt1, pt2, irad, orad} => let              | P.D_CONE{pt1, pt2, irad, orad} => let
265                  val normVar = PSV.new("local_ht", PSV.T_VEC3F)                  val normVar = PSV.new("local_ht", PSV.T_VEC3F)
# Line 242  Line 267 
267                    letPRIM("eh",  IR.T_FLOAT, IR.RAND, [], fn ourRand =>                    letPRIM("eh",  IR.T_FLOAT, IR.RAND, [], fn ourRand =>
268                    letPRIM("nv", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn normVec =>                    letPRIM("nv", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn normVec =>
269                    letPRIM("n", IR.T_VEC, IR.NORM, [normVec], fn norm =>                    letPRIM("n", IR.T_VEC, IR.NORM, [normVec], fn norm =>
270                      genVecVar("ptInDisc", insert(env, normVar, norm), P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad}, fn ptInDisc =>               genVecVar("ptInDisc",
271                  insert(env, normVar, norm),
272                  P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},
273                  dist,
274                  fn ptInDisc =>
275                      letPRIM("gptt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), ptInDisc], fn genPtToTip =>                      letPRIM("gptt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), ptInDisc], fn genPtToTip =>
276                      letPRIM("gpttlen", IR.T_FLOAT, IR.LEN, [genPtToTip], fn genPtToTipLen =>                      letPRIM("gpttlen", IR.T_FLOAT, IR.LEN, [genPtToTip], fn genPtToTipLen =>
277                      letPRIM("s", IR.T_FLOAT, IR.MULT, [genPtToTipLen, ourRand], fn scale =>                      letPRIM("s", IR.T_FLOAT, IR.MULT, [genPtToTipLen, ourRand], fn scale =>
278                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, genPtToTip], fn scaledNormVec =>                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, genPtToTip], fn scaledNormVec =>
279                      letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [ptInDisc, scaledNormVec], stmt)))))))))               letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [ptInDisc, scaledNormVec], stmt)
280                 ))))))))
281                  end                  end
282    
283              | _ => raise Fail "Cannot generate point in specified domain."                  | P.D_SPHERE{center, irad, orad} =>
284            (* end case *))  
285            (*                    (* Source: http://mathworld.wolfram.com/SpherePointPicking.html *)
286            | generate (Dplane{pt, n}) = Vec3f.unpack pt  
287        | generate (Drectangle{pt, u, v}) = Vec3f.unpack pt            (* generate two random values... one will be called u and will
288        | generate (Dsphere{c, orad, irad}) = Vec3f.unpack c             * represent cos(theta), and the other will be called v and will
289        | generate (Dblob{c, stddev}) = Vec3f.unpack c             * represent a random value in [0, 2 * pi] *)
290            *)            letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn rv =>
291              letPRIM("dblRandVal", IR.T_FLOAT, IR.MULT, [rv, IR.newConst("Two", IR.C_FLOAT 2.0)], fn drv =>
292              letPRIM("rand", IR.T_FLOAT, IR.SUB, [drv, IR.newConst("One", IR.C_FLOAT 1.0)], fn u =>
293    
294              letPRIM("rv2", IR.T_FLOAT, IR.RAND, [], fn rv2 =>
295              letPRIM("rand2", IR.T_FLOAT, IR.MULT, [rv2, IR.newConst("TwoPi", IR.C_FLOAT (2.0 * Float.M_PI))], fn theta =>
296    
297              letPRIM("cosTheta", IR.T_FLOAT, IR.COS, [theta], fn cosT =>
298              letPRIM("sinTheta", IR.T_FLOAT, IR.SIN, [theta], fn sinT =>
299    
300              letPRIM("usq", IR.T_FLOAT, IR.MULT, [u, u], fn usq =>
301              letPRIM("usqInv", IR.T_FLOAT, IR.SUB, [IR.newConst("One", IR.C_FLOAT 1.0), usq], fn usqInv =>
302              letPRIM("sinPhi", IR.T_FLOAT, IR.SQRT, [usqInv], fn sinP =>
303    
304              letPRIM("xVal", IR.T_FLOAT, IR.MULT, [sinP, cosT], fn xVal =>
305              letPRIM("yVal", IR.T_FLOAT, IR.MULT, [sinP, sinT], fn yVal =>
306              (* zval is just u *)
307    
308              letPRIM("vec", IR.T_VEC, IR.GEN_VEC, [xVal, yVal, u], fn vec =>
309    
310              (* Generate a random radius... *)
311                      letPRIM("ratio", IR.T_FLOAT, IR.DIV, [psvToIRVar(env, irad), psvToIRVar(env, orad)], fn ratio =>
312                      letPRIM("invRatio", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), ratio], fn invRatio =>
313                      letPRIM("randVar", IR.T_FLOAT, IR.RAND, [], fn rand =>
314                      letPRIM("randScale", IR.T_FLOAT, IR.MULT, [rand, invRatio], fn randScale =>
315                      letPRIM("randVal", IR.T_FLOAT, IR.ADD, [randScale, ratio], fn randVal =>
316                      letPRIM("randValSq", IR.T_FLOAT, IR.MULT, [randVal, randVal], fn randValSq =>
317                      letPRIM("radDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, orad), psvToIRVar(env, irad)], fn radDiff =>
318                      letPRIM("randRadVal", IR.T_FLOAT, IR.MULT, [radDiff, randValSq], fn randRadVal =>
319                      letPRIM("rad", IR.T_FLOAT, IR.ADD, [psvToIRVar(env, irad), randRadVal], fn rad =>
320    
321                      (* Normalize the vector and scale it by the radius. *)
322                      letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [rad, vec], fn sVec =>
323                      letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [sVec, psvToIRVar(env, center)], stmt)
324                      ))))))))))
325                      )))))))))))))
326    
327                | _ => raise Fail ("Cannot generate point in specified domain: "  ^ (P.dToStr domain))
328              (* end case *))
329    
330    (* This function takes an IR boolean, its environment, a particle state, domain,    (* This function takes an IR boolean, its environment, a particle state, domain,
331     * and continuation.     * and continuation.
# Line 266  Line 333 
333     * We set the boolean to whether or not the current particle given by the particle     * We set the boolean to whether or not the current particle given by the particle
334     * state is within the domain, and then pass the continuation on.     * state is within the domain, and then pass the continuation on.
335     *)     *)
336      fun mkWithinVar (boolVar, env, var, d, stmt : IR.var -> IR.stmt) = let      fun mkVecWithinVar (boolVar, env, var, d : Vec3f.vec3 P.domain, stmt : IR.var -> IR.stmt) = let
337            val pos = var            val pos = var
338            in            in
339              case d              case d
# Line 335  Line 402 
402                    letPRIM("inOrad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), posToCLen], fn inOrad =>                    letPRIM("inOrad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), posToCLen], fn inOrad =>
403                    letPRIM("inIrad", IR.T_BOOL, IR.GT, [posToCLen, psvToIRVar(env, irad)], fn inIrad =>                    letPRIM("inIrad", IR.T_BOOL, IR.GT, [posToCLen, psvToIRVar(env, irad)], fn inIrad =>
404                    letPRIM(boolVar, IR.T_BOOL, IR.AND, [inIrad, inOrad], stmt)))))                    letPRIM(boolVar, IR.T_BOOL, IR.AND, [inIrad, inOrad], stmt)))))
405    
406                      | P.D_CYLINDER {pt1, pt2, irad, orad} =>
407    
408                      (* !FIXME! Right now, we see whether or not the point is within the two planes defined
409                       * by the endpoints of the cylinder, and then testing to see whether or not the smallest
410                       * distance to the line segment falls within the radii. It might be faster to find the
411                       * closest point to the line defined by the endpoints and then see whether or not the point
412                       * is within the segment.
413                       *)
414    
415                      (* Is it in one plane *)
416                      letPRIM("plane1Norm", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn plane1Norm =>
417                      letPRIM("posToPt1", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, pt1)], fn posToPt1 =>
418                      letPRIM("dot1", IR.T_FLOAT, IR.DOT, [posToPt1, plane1Norm], fn dot1Prod =>
419                      letPRIM("inPlane1", IR.T_BOOL, IR.GT, [dot1Prod, IR.newConst("zero", IR.C_FLOAT 0.0)], fn inPlane1=>
420    
421                      (* Is it in another plane *)
422                      letPRIM("plane2Norm", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt1), psvToIRVar(env, pt2)], fn plane2Norm =>
423                      letPRIM("posToPt2", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, pt2)], fn posToPt2 =>
424                      letPRIM("dot2", IR.T_FLOAT, IR.DOT, [posToPt2, plane2Norm], fn dot2Prod =>
425                      letPRIM("inPlane2", IR.T_BOOL, IR.GT, [dot2Prod, IR.newConst("zero", IR.C_FLOAT 0.0)], fn inPlane2=>
426    
427                      (* Is it in both planes? *)
428                      letPRIM("inPlanes", IR.T_BOOL, IR.AND, [inPlane1, inPlane2], fn inPlanes =>
429    
430                      (* Find distance from segment *)
431                      letPRIM("a", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn a =>
432                      letPRIM("b", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt1), pos], fn b =>
433                      letPRIM("alen", IR.T_FLOAT, IR.LEN, [a], fn alen =>
434                      letPRIM("axb", IR.T_VEC, IR.CROSS, [a, b], fn axb =>
435                      letPRIM("axblen", IR.T_FLOAT, IR.LEN, [axb], fn axblen =>
436                      letPRIM("dist", IR.T_FLOAT, IR.DIV, [axblen, alen], fn dist =>
437    
438                      (* Is distance in both radii? *)
439                      letPRIM("inOradGt", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), dist], fn inOradGt =>
440                      letPRIM("inOradEq", IR.T_BOOL, IR.EQUALS, [psvToIRVar(env, orad), dist], fn inOradEq =>
441                      letPRIM("inOrad", IR.T_BOOL, IR.OR, [inOradGt, inOradEq], fn inOrad =>
442    
443                      letPRIM("inIradGt", IR.T_BOOL, IR.GT, [dist, psvToIRVar(env, irad)], fn inIradGt =>
444                      letPRIM("inIradEq", IR.T_BOOL, IR.EQUALS, [dist, psvToIRVar(env, irad)], fn inIradEq =>
445                      letPRIM("inIrad", IR.T_BOOL, IR.OR, [inIradGt, inIradEq], fn inIrad =>
446    
447                      letPRIM("inBothRad", IR.T_BOOL, IR.AND, [inIrad, inOrad], fn inBothRad =>
448    
449                      (* It's in the cylinder (tube) if it's within both radii and in both planes... *)
450                      letPRIM(boolVar, IR.T_BOOL, IR.AND, [inPlanes, inBothRad], stmt)
451                      ))))))))))))))))))))))
452  (*  (*
453                | P.D_TRIANGLE {pt1: vec3f var, pt2: vec3f var, pt3: vec3f var}                | P.D_TRIANGLE {pt1: vec3f var, pt2: vec3f var, pt3: vec3f var}
454                | P.D_PLANE {pt: vec3f var, normal: vec3f var}                | P.D_PLANE {pt: vec3f var, normal: vec3f var}
455                | P.D_RECT {pt: vec3f var, htvec: vec3f var, wdvec: vec3f var}                | P.D_RECT {pt: vec3f var, htvec: vec3f var, wdvec: vec3f var}
456                | P.D_BOX {min: vec3f var, max: vec3f var}                | P.D_BOX {min: vec3f var, max: vec3f var}
457                | P.D_SPHERE {center: vec3f var, irad: vec3f var, orad: vec3f var}                | P.D_SPHERE {center: vec3f var, irad: vec3f var, orad: vec3f var}
               | P.D_CYLINDER {pt1: vec3f var, pt2: vec3f var, irad: float var, orad: float var}  
458                | P.D_CONE {pt1: vec3f var, pt2: vec3f var, irad: float var, orad: float var}                | P.D_CONE {pt1: vec3f var, pt2: vec3f var, irad: float var, orad: float var}
459                | P.D_BLOB {center: vec3f var, stddev: float var}                | P.D_BLOB {center: vec3f var, stddev: float var}
460                | P.D_DISC {pt: vec3f var, normal: vec3f var, irad: float var, orad: float var}                | P.D_DISC {pt: vec3f var, normal: vec3f var, irad: float var, orad: float var}
461  *)  *)
462                | _ => raise Fail "Cannot determine within-ness for specified domain."                | _ => raise Fail ("Cannot determine within-ness for specified vec3 domain: " ^ (P.dToStr d))
463              (* end case *)              (* end case *)
464            end (*end let *)            end (*end let *)
465    
466            fun mkFloatWithinVar (boolVar, env, var, d : Float.float P.domain, stmt : IR.var -> IR.stmt) = (case d
467              of P.D_POINT(pt) => letPRIM(boolVar, IR.T_BOOL, IR.EQUALS, [psvToIRVar(env, pt), var], stmt)
468               | P.D_BOX {min, max} =>
469                 letPRIM("bigMin", IR.T_BOOL, IR.GT, [var, psvToIRVar(env, min)], fn bigMin =>
470                 letPRIM("smallMax", IR.T_BOOL, IR.GT, [psvToIRVar(env, max), var], fn smallMax =>
471                 letPRIM(boolVar, IR.T_BOOL, IR.AND, [bigMin, smallMax], stmt)))
472               | _ => raise Fail ("Cannot determine within-ness for specified float domain: " ^ (P.dToStr d))
473             (* end case *))
474    
475    (* generate code to produce a random particle state from a domain *)          fun mkIntBool(env, p1var, p2var, d : Vec3f.vec3 P.domain, state, k : IR.var -> particle_state -> IR.stmt) = let
476      fun newParticle (posDomain, velDomain, colDomain, env, k : particle_state -> IR.stmt) =            val _ = ()
477              (* genVecVar (vecVar, env, domain, stmt) *)           in
478              genVecVar("ps_pos", env, posDomain, fn newPos =>            (case d
479              genVecVar("ps_vel", env, velDomain, fn newVel =>              of P.D_POINT(pt) =>
480              genVecVar("ps_col", env, colDomain, fn newCol =>  
481              letPRIM ("randSize", IR.T_FLOAT, IR.RAND, [], fn randSize =>               (* Get vectors *)
482              letPRIM ("halvedSize", IR.T_FLOAT, IR.MULT, [randSize, IR.newConst("halver", IR.C_FLOAT 0.5)], fn halfSize =>               letPRIM("p1ToPt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar (env, pt), p1var], fn p1ToPt =>
483              letSPRIM("ps_size", IR.T_FLOAT, IR.ADD, [halfSize, IR.newConst("scalar", IR.C_FLOAT 0.5)], fn newSize =>               letPRIM("p2ToPt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar (env, pt), p2var], fn p2ToPt =>
484              letSPRIM ("ps_ttl", IR.T_FLOAT, IR.COPY, [IR.newConst("fbool", IR.C_FLOAT 10000.0)], fn newIsDead =>               letPRIM("p1ToP2", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn p1ToP2 =>
485                k(PS{pos = newPos,  
486                     vel = newVel,               (* Get distances *)
487                     size = newSize,               letPRIM("p1ToPtLen", IR.T_FLOAT, IR.LEN, [p1ToPt], fn p1ToPtLen =>
488                     ttl = newIsDead,               letPRIM("p2ToPtLen", IR.T_FLOAT, IR.LEN, [p2ToPt], fn p2ToPtLen =>
489                     color = newCol,               letPRIM("p1ToP2Len", IR.T_FLOAT, IR.LEN, [p1ToP2], fn p1ToP2Len =>
490                     pos2 = IR.newConst("ps_pos2", IR.C_VEC {x=0.0, y=0.0, z=0.0}),  
491                     dummy = IR.newConst("ps_dummy", IR.C_FLOAT 0.01)})               (* Add & subtract ... *)
492                 letPRIM("distSum", IR.T_FLOAT, IR.ADD, [p1ToPtLen, p2ToPtLen], fn distSum =>
493                 letPRIM("distDiff", IR.T_FLOAT, IR.SUB, [distSum, p1ToP2Len], fn distDiff =>
494                 letPRIM("distDiffAbs", IR.T_FLOAT, IR.ABS, [distDiff], fn distDiffAbs =>
495    
496                 (* Do the boolean stuff... *)
497                 letPRIM("intersect", IR.T_BOOL, IR.GT, [psvToIRVar(env, epsilon), distDiffAbs], fn intVar => k intVar state)
498    
499                 )))
500                 )))
501                 )))
502    
503                | P.D_PLANE {pt, normal} =>
504                  letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
505                  letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
506                  letPRIM("p2d", IR.T_FLOAT, IR.DOT, [p2var, psvToIRVar(env, normal)], fn p2d =>
507                  letPRIM("p1dist", IR.T_FLOAT, IR.SUB, [d, p1d], fn p1dist =>
508                  letPRIM("p2dist", IR.T_FLOAT, IR.SUB, [d, p2d], fn p2dist =>
509                  letPRIM("distProd", IR.T_FLOAT, IR.MULT, [p1dist, p2dist], fn distProd =>
510                  letPRIM("intersect", IR.T_BOOL, IR.GT, [IR.newConst("zero", IR.C_FLOAT 0.0), distProd], fn intVar => k intVar state)
511                  ))))))
512    
513                | P.D_DISC {pt, normal, orad, irad} => let
514                  val boolVar = IR.newParam("intersect", IR.T_BOOL)
515                  val newBlk = newBlockWithArgs(env, state, [boolVar], k boolVar)
516                 in
517                  letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
518                  letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
519    
520                  (* Early out... does it intersect the plane?
521                   *
522                   * !SPEED! Due to the perceived slowness of branching on
523                   * GPUs, this might not actually be faster on all runtime environments *)
524    
525                  letPRIM("p2d", IR.T_FLOAT, IR.DOT, [p2var, psvToIRVar(env, normal)], fn p2d =>
526                  letPRIM("p1dist", IR.T_FLOAT, IR.SUB, [d, p1d], fn p1dist =>
527                  letPRIM("p2dist", IR.T_FLOAT, IR.SUB, [d, p2d], fn p2dist =>
528                  letPRIM("distProd", IR.T_FLOAT, IR.MULT, [p1dist, p2dist], fn distProd =>
529                  letPRIM("earlyOut", IR.T_BOOL, IR.GT, [distProd, IR.newConst("zero", IR.C_FLOAT 0.0)], fn earlyOut =>
530                  IR.mkIF(earlyOut,
531                    (* then *)
532                    letPRIM("intersect", IR.T_BOOL, IR.NOT, [earlyOut], fn var => gotoWithArgs(state, [var], newBlk)),
533                    (* else *)
534                    letPRIM("v", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn v =>
535                    letPRIM("vDotn", IR.T_FLOAT, IR.DOT, [v, psvToIRVar(env, normal)], fn vdn =>
536                    letPRIM("t", IR.T_FLOAT, IR.DIV, [p1dist, vdn], fn t =>
537    
538                    (* !TODO! Add some sort of assert mechanism to make sure that t is
539                     * in the interval [0, 1]... *)
540                    letPRIM("vscale", IR.T_VEC, IR.SCALE, [t, v], fn vscale =>
541                    letPRIM("ppt", IR.T_VEC, IR.ADD_VEC, [p1var, vscale], fn ppt =>
542                    letPRIM("lenVec", IR.T_VEC, IR.SUB_VEC, [ppt, psvToIRVar(env, pt)], fn cv =>
543                    letPRIM("len", IR.T_FLOAT, IR.LEN, [cv], fn len =>
544    
545                    (* Check to see whether or not it's within the radius... *)
546                    letPRIM("gtirad", IR.T_BOOL, IR.GT, [len, psvToIRVar(env, irad)], fn gtirad =>
547                    letPRIM("ltorad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), len], fn ltorad =>
548                    letPRIM("intersect", IR.T_BOOL, IR.AND, [gtirad, ltorad], fn var => gotoWithArgs(state, [var], newBlk))
549                   ))))))))))
550              )))))))              )))))))
551                end (* P.D_DISC *)
552    
553                | _ => raise Fail ("Cannot calculate intersection bool for specified domain: " ^ (P.dToStr d))
554              (* end case *))
555    
556             end (* mkIntBool *)
557    
558            (* We assume that the segment already intersects with the domain. *)
559            fun mkIntPt(env, p1var, p2var, d : Vec3f.vec3 P.domain, k : IR.var -> IR.stmt) = let
560              val _ = ()
561             in
562              (case d
563                of P.D_POINT(pt) => k (psvToIRVar (env, pt))
564    
565                 | P.D_PLANE {pt, normal} =>
566                   letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
567                   letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
568                   letPRIM("num", IR.T_FLOAT, IR.SUB, [d, p1d], fn num =>
569                   letPRIM("v", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn v =>
570                   letPRIM("den", IR.T_FLOAT, IR.DOT, [v, psvToIRVar(env, normal)], fn den =>
571                   letPRIM("t", IR.T_FLOAT, IR.DIV, [num, den], fn t =>
572                   letPRIM("vsc", IR.T_VEC, IR.SCALE, [t, v], fn vs =>
573                   letPRIM("intPt", IR.T_VEC, IR.ADD_VEC, [p1var, vs], k)
574                   )))))))
575    
576                 (* Since we already know they intersect, the intersection point must be
577                  * just the point that's on the plane... *)
578                 | P.D_DISC {pt, normal, orad, irad} => mkIntPt(env, p1var, p2var, P.D_PLANE{pt = pt, normal = normal}, k)
579                 | _ => raise Fail ("Cannot calculate intersection point for specified domain: "  ^ (P.dToStr d))
580              (* end case *))
581             end (* mkIntPt *)
582    
583      (* Find the normal at the given position of the particle for the specified      (* Find the normal at the given position of the particle for the specified
584       * domain. Note, that the particle doesn't necessarily need to be on the       * domain. Note, that the particle doesn't necessarily need to be on the
585       * domain, but if it's not then the behavior is undefined.       * domain, but if it's not then the behavior is undefined. *)
586       *)      fun normAtPoint(retNorm, d, env, pos, state, k : IR.var -> particle_state -> IR.stmt) = let
     fun normAtPoint(retNorm, d, env, state, k : IR.var -> particle_state -> IR.stmt) = let  
587        val newNorm = IR.newParam("n", IR.T_VEC)        val newNorm = IR.newParam("n", IR.T_VEC)
588        val nextBlk = newBlockWithArgs(env, [newNorm], k(newNorm))        val nextBlk = newBlockWithArgs(env, state, [newNorm], k(newNorm))
       val PS{pos, ...} = state  
589       in       in
590        (case d        (case d
591            of P.D_PLANE{pt, normal} => letPRIM(retNorm, IR.T_VEC, IR.COPY, [psvToIRVar(env, normal)],            of P.D_PLANE{pt, normal} => letPRIM(retNorm, IR.T_VEC, IR.COPY, [psvToIRVar(env, normal)],
592                fn newNormVar => gotoWithArgs(state, [newNormVar], nextBlk))                fn newNormVar => gotoWithArgs(state, [newNormVar], nextBlk))
593             | P.D_DISC{pt, normal, irad, orad} =>             | P.D_DISC{pt, normal, irad, orad} =>
594                mkWithinVar("inP", env, pos, d, fn inPlane =>                mkVecWithinVar("inP", env, pos, d, fn inPlane =>
595                    IR.mkIF(inPlane,                    IR.mkIF(inPlane,
596                      (* then *)                      (* then *)
597                      letPRIM(retNorm, IR.T_VEC, IR.COPY, [psvToIRVar(env, normal)],                      letPRIM(retNorm, IR.T_VEC, IR.COPY, [psvToIRVar(env, normal)],
# Line 397  Line 605 
605                     )                     )
606                   )                   )
607    
608             | P.D_SPHERE{center, irad, orad} => let             | P.D_SPHERE{center, irad, orad} =>
               val PS{pos, ...} = state  
               in  
609                      letPRIM("sv", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, center)], fn subVec =>                      letPRIM("sv", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, center)], fn subVec =>
610                  letPRIM(retNorm, IR.T_VEC, IR.NORM, [subVec], fn newNormVar => k newNormVar state                  letPRIM(retNorm, IR.T_VEC, IR.NORM, [subVec], fn newNormVar => k newNormVar state
611                      ))                      ))
612    
613               | _ => raise Fail("Cannot find normal to point of specified domain." ^ (P.dToStr d))
614             (* end case *))
615                end                end
616    
617             | _ => raise Fail("Cannot find normal to point of specified domain.")          fun trExpr(expr, env, state, k : IR.var -> particle_state -> IR.stmt) = (case expr
618              of P.CONSTF f => k (IR.newConst ("c", IR.C_FLOAT f)) state
619    
620           | P.CONST3F v => k (IR.newConst ("c", IR.C_VEC v)) state
621    
622           | P.VAR v => k (psvToIRVar (env, v)) state
623    
624           | P.STATE_VAR sv => k (getIRVarForSV (sv, state)) state
625    
626           | P.GENERATE3F (dom, dist) => genVecVar("genVec", env, dom, dist, fn var => k var state)
627    
628           | P.GENERATEF (dom, dist) => genFloatVar("genFlt", env, dom, dist, fn var => k var state)
629    
630           | P.ADD(e1, e2) =>
631             trExpr(e1, env, state, fn e1var => fn state' =>
632             trExpr(e2, env, state', fn e2var => fn state'' =>
633             let
634              val IR.V{varType=vt1, ...} = e1var
635              val IR.V{varType=vt2, ...} = e2var
636             in
637              (case (vt1, vt2)
638                of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("addVar", IR.T_FLOAT, IR.ADD, [e1var, e2var], fn var => k var state'')
639                 | (IR.T_VEC, IR.T_VEC) => letPRIM("addVar", IR.T_VEC, IR.ADD_VEC, [e1var, e2var], fn var => k var state'')
640                 | _ => raise Fail ("Type mismatch to ADD expression")
641              (* end case *))
642             end))
643    
644           | P.SCALE (e1, e2) =>
645             trExpr(e1, env, state, fn e1var => fn state' =>
646             trExpr(e2, env, state', fn e2var => fn state'' =>
647             let
648              val IR.V{varType=vt1, ...} = e1var
649              val IR.V{varType=vt2, ...} = e2var
650             in
651              (case (vt1, vt2)
652                of (IR.T_FLOAT, IR.T_VEC) => letPRIM("scaleVar", IR.T_VEC, IR.SCALE, [e1var, e2var], fn var => k var state'')
653                 | (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("scaleVar", IR.T_FLOAT, IR.MULT, [e1var, e2var], fn var => k var state'')
654                 | _ => raise Fail (String.concat["Type mismatch to SCALE expression: ", IR.ty2Str vt1, ", ", IR.ty2Str vt2])
655              (* end case *))
656             end))
657    
658           | P.DIV (e1, e2) =>
659             trExpr(e1, env, state, fn e1var => fn state' =>
660             trExpr(e2, env, state', fn e2var => fn state'' =>
661             let
662              val IR.V{varType=vt1, ...} = e1var
663              val IR.V{varType=vt2, ...} = e2var
664             in
665              (case (vt1, vt2)
666                of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("divVar", IR.T_FLOAT, IR.DIV, [e1var, e2var], fn var => k var state'')
667                 | _ => raise Fail (String.concat["Type mismatch to DIV expression: ", IR.ty2Str vt1, ", ", IR.ty2Str vt2])
668              (* end case *))
669             end))
670    
671           | P.NEG e =>
672             trExpr(e, env, state, fn evar => fn state' =>
673             let
674              val IR.V{varType, ...} = evar
675             in
676              (case varType
677                of IR.T_FLOAT => letPRIM("negVar", IR.T_FLOAT, IR.MULT, [evar, IR.newConst("negOne", IR.C_FLOAT ~1.0)], fn var => k var state')
678                 | IR.T_VEC => letPRIM("negVar", IR.T_VEC, IR.NEG_VEC, [evar], fn var => k var state')
679                 | _ => raise Fail ("Type mismatch to NEG expression")
680              (* end case *))
681             end)
682    
683           | P.DOT (e1, e2) =>
684             trExpr(e1, env, state, fn e1var => fn state' =>
685             trExpr(e2, env, state', fn e2var => fn state'' =>
686             let
687              val IR.V{varType=vt1, ...} = e1var
688              val IR.V{varType=vt2, ...} = e2var
689             in
690              (case (vt1, vt2)
691                of (IR.T_VEC, IR.T_VEC) => letPRIM("dotVar", IR.T_FLOAT, IR.DOT, [e1var, e2var], fn var => k var state'')
692                 | _ => raise Fail ("Type mismatch to DOT expression")
693              (* end case *))
694             end))
695    
696           | P.CROSS (e1, e2) =>
697             trExpr(e1, env, state, fn e1var => fn state' =>
698             trExpr(e2, env, state', fn e2var => fn state'' =>
699             let
700              val IR.V{varType=vt1, ...} = e1var
701              val IR.V{varType=vt2, ...} = e2var
702             in
703              (case (vt1, vt2)
704                of (IR.T_VEC, IR.T_VEC) => letPRIM("crossVar", IR.T_VEC, IR.CROSS, [e1var, e2var], fn var => k var state'')
705                 | _ => raise Fail ("Type mismatch to CROSS expression")
706              (* end case *))
707             end))
708    
709           | P.NORMALIZE e =>
710             trExpr(e, env, state, fn evar => fn state' =>
711             let
712              val IR.V{varType, ...} = evar
713             in
714              (case varType
715                of IR.T_VEC => letPRIM("normVar", IR.T_VEC, IR.NORM, [evar], fn var => k var state')
716                 | _ => raise Fail ("Type mismatch to NORMALIZE expression")
717              (* end case *))
718             end)
719    
720           | P.LENGTH e =>
721             trExpr(e, env, state, fn evar => fn state' =>
722             let
723              val IR.V{varType, ...} = evar
724             in
725              (case varType
726                of IR.T_VEC => letPRIM("lenVar", IR.T_FLOAT, IR.LEN, [evar], fn var => k var state')
727                 | _ => raise Fail ("Type mismatch to LENGTH expression")
728              (* end case *))
729             end)
730    
731           (* !SPEED! We're assuming that there is an intersection here... *)
732           | P.INTERSECT {p1, p2, d} =>
733             trExpr(p1, env, state, fn p1var => fn state' =>
734             trExpr(p2, env, state', fn p2var => fn state'' =>
735             let
736              val IR.V{varType=vt1, ...} = p1var
737              val IR.V{varType=vt2, ...} = p2var
738             in
739              (case (vt1, vt2)
740                of (IR.T_VEC, IR.T_VEC) => mkIntPt(env, p1var, p2var, d, fn var => k var state'')
741                 | _ => raise Fail("Type mismatch to INTERSECT expression")
742              (* end case *))
743             end))
744    
745           | P.NORMALTO (e, d) =>
746             trExpr(e, env, state, fn evar => fn state' =>
747             let
748              val IR.V{varType, ...} = evar
749              fun cont s = k s
750             in
751              (case varType
752                of IR.T_VEC => normAtPoint("normVar", d, env, evar, state', k)
753                 | _ => raise Fail("Type mismatch to NORMALTO expression")
754              (* end case *))
755             end)
756    
757           | P.LOOKUP (varName) => let
758             fun findVar (IR.V{name, ...}) = name = varName
759            in
760             (case (List.find findVar state)
761               of SOME v => k v state
762                | NONE => raise Fail("Compiler Error: Undefined variable: " ^ varName)
763           (* end case *))           (* end case *))
764          end          end
765    
766          fun trEmitter(emit, env, state, k : particle_state -> IR.stmt) = let            (* end case expr *))
767    
768              (* generate code to produce a random particle state from a domain *)
769        fun newParticle (sv_gens, env, state, k : particle_state -> IR.stmt) = let
770    
771          fun createVar(P.GEN{var, ...}) = let
772            val P.PSV.SV{name, ty, ...} = var
773           in
774            IR.newLocal("ps_" ^ name, IR.psvTyToIRTy ty, (IR.RAND, []))
775           end
776    
777            val PS{ttl, ...} = state        val newState = List.map createVar sv_gens
778            val P.EMIT{maxNum, posDomain, velDomain, colDomain, ...} = emit  
779            val blk = newBlock (env, k)        fun genVar((sv_gen, var), cont) = let
780            val P.GEN{exp, ...} = sv_gen
781            val IR.V{varType, ...} = var
782           in
783            (* This is kind of a hack, but it'll get optimized out.
784             * Also, I think it's OK to leave the state' unused since we're
785             * creating variables here and its assumed that they're independent. *)
786            trExpr(exp, env, state, fn newVal => fn state' => IR.mkPRIM(var, IR.COPY, [newVal], cont))
787           end (* genVar *)
788    
789         in
790          List.foldr (fn (x, y) => genVar(x, y)) (k newState) (ListPair.zipEq (sv_gens, newState))
791         end (* new particle *)
792    
793        fun trEmitter(emit, env, state, k : particle_state -> IR.stmt) = let
794          val P.EMIT{freq, sv_gens} = emit
795          val blk = newBlock (env, state, k)
796          val ttl = findIRVarByName(state, "ttl")
797           in           in
798            letPRIM("isDead", IR.T_BOOL, IR.GT, [IR.newConst("small", IR.C_FLOAT 0.1), ttl], fn isDead =>            letPRIM("isDead", IR.T_BOOL, IR.GT, [IR.newConst("small", IR.C_FLOAT 0.1), ttl], fn isDead =>
799        IR.mkIF(isDead,        IR.mkIF(isDead,
800         (* then *)         (* then *)
801         letPRIM("t1", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env, maxNum)], fn t1 =>         trExpr(freq, env, state, fn t1 => fn state' =>
802         letPRIM("t2", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env, PSV.numDead)], fn t2 =>         letPRIM("t2", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env, PSV.numDead)], fn t2 =>
803         letPRIM("prob", IR.T_FLOAT, IR.DIV, [t1, t2], fn prob =>         letPRIM("prob", IR.T_FLOAT, IR.DIV, [t1, t2], fn prob =>
804         letPRIM("r", IR.T_FLOAT, IR.RAND, [], fn r =>         letPRIM("r", IR.T_FLOAT, IR.RAND, [], fn r =>
805         letPRIM("t3", IR.T_BOOL, IR.GT, [prob, r], fn t3 =>         letPRIM("t3", IR.T_BOOL, IR.GT, [prob, r], fn t3 =>
806         IR.mkIF(t3,         IR.mkIF(t3,
807          (* then *)          (* then *)
808          newParticle (posDomain, velDomain, colDomain, env,          newParticle (sv_gens, env, state', fn state'' => retState state''),
          fn state' => retState state'),  
809          (* else *)          (* else *)
810          IR.DISCARD)))))),          IR.DISCARD)))))),
811         (* else *)         (* else *)
812         retState state))         retState state))
813       end       end
814    
815          fun trPred(pred, env, state, thenk : particle_state -> IR.stmt, elsek : particle_state -> IR.stmt) = let      (* trExpr(expr, env, state, k : IR.var -> IR.stmt) *)
816            val PS{pos, vel, ...} = state      (* mkFloatWithinVar (boolVar, env, var, d : Float.float P.domain, stmt : IR.var -> IR.stmt) *)
817            val P.PR{ifstmt, ...} = pred      fun trPred(cond, env, state, thenk : particle_state -> IR.stmt, elsek : particle_state -> IR.stmt) = let
818           in        fun grabVar(cond, env, state, k : IR.var -> particle_state -> IR.stmt) = (case cond
819            case ifstmt          of P.WITHINF(d, expr) =>
820             of P.WITHIN(d) => mkWithinVar("wv", env, pos, d, fn withinVar =>              trExpr(expr, env, state, fn checkMe => fn state' =>
821              IR.mkIF(withinVar, thenk(state), elsek(state)))              mkFloatWithinVar("wv", env, checkMe, d, fn var => k var state'))
822              | P.WITHINVEL(d) => mkWithinVar("wv", env, vel, d, fn withinVar =>  
823              IR.mkIF(withinVar, thenk(state), elsek(state)))           | P.WITHIN3F(d, expr) =>
824           end              trExpr(expr, env, state, fn checkMe => fn state' =>
825                mkVecWithinVar("wv", env, checkMe, d, fn var => k var state'))
826      fun trAct (action, env, state, k : particle_state -> IR.stmt) = let  
827            val PS{pos, vel, size, ttl, color, pos2, dummy} = state           | P.DO_INTERSECT {p1, p2, d} =>
828            in             trExpr(p1, env, state, fn p1var => fn state' =>
829              case action             trExpr(p2, env, state', fn p2var => fn state'' =>
830               of P.BOUNCE{friction, resilience, cutoff, d} => let             mkIntBool(env, p1var, p2var, d, state'', k)))
831                    val blk = newBlock (env, k)  
832                    val negOne = IR.newConst("negOne", IR.C_FLOAT ~1.0)           | P.GTHAN (e1, e2) =>
833                    in             trExpr(e1, env, state, fn e1var => fn state' =>
834                      letPRIM("vs", IR.T_VEC, IR.SCALE, [psvToIRVar(env, PSV.timeStep), vel], fn velScale =>             trExpr(e2, env, state', fn e2var => fn state'' =>
835                      letPRIM("np", IR.T_VEC, IR.ADD_VEC, [pos, velScale], fn nextPos =>             letPRIM("gtVar", IR.T_BOOL, IR.GT, [e1var, e2var], fn var => k var state'')))
836                      mkWithinVar("wcp", env, pos, d, fn withinCurPos =>  
837                      mkWithinVar("wnp", env, nextPos, d, fn withinNextPos =>           | P.AND(c1, c2) =>
838                      letPRIM("nwcp", IR.T_BOOL, IR.NOT, [withinCurPos], fn notWithinCurPos =>             grabVar(c1, env, state, fn c1Var => fn state' =>
839                      letPRIM("sb", IR.T_BOOL, IR.AND, [notWithinCurPos, withinNextPos], fn shouldBounce =>             grabVar(c2, env, state', fn c2Var => fn state'' =>
840                      IR.mkIF(shouldBounce,             letPRIM("andVar", IR.T_BOOL, IR.AND, [c1Var, c2Var], fn var => k var state'')))
841                        (*then*)  
842                          normAtPoint("n", d, env, state, fn normAtD => fn state' => let           | P.OR(c1, c2) =>
843                 val PS{pos=nextPos, vel=nextVel, size=nextSize, ttl=nextIsDead, color=nextColor, pos2=nextPos2, dummy=nextDummy} = state'             grabVar(c1, env, state, fn c1Var => fn state' =>
844                            in             grabVar(c2, env, state', fn c2Var => fn state'' =>
845                             letPRIM("negVel", IR.T_VEC, IR.SCALE, [negOne, nextVel], fn negVel =>             letPRIM("andVar", IR.T_BOOL, IR.OR, [c1Var, c2Var], fn var => k var state'')))
846                             letPRIM("dnv", IR.T_FLOAT, IR.DOT, [negVel, normAtD], fn dotNegVel =>  
847                             letPRIM("sn", IR.T_VEC, IR.SCALE, [dotNegVel, normAtD], fn scaledN =>           | P.XOR(c1, c2) =>
848                             letPRIM("t", IR.T_VEC, IR.SUB_VEC, [negVel, scaledN], fn tang =>             grabVar(c1, env, state, fn c1Var => fn state' =>
849               grabVar(c2, env, state', fn c2Var => fn state'' =>
850                             letPRIM("tlsq", IR.T_FLOAT, IR.LEN_SQ, [tang], fn tangLenSq =>             mkXOR ("xorVar", c1Var, c2Var, fn var => k var state'')))
851                             letPRIM("cosq", IR.T_FLOAT, IR.MULT, [psvToIRVar(env, cutoff), psvToIRVar(env, cutoff)], fn cutoffSq =>  
852                             letPRIM("inco", IR.T_BOOL, IR.GT, [tangLenSq, cutoffSq], fn inCutoff =>           | P.NOT(c) =>
853               grabVar(c, env, state, fn cvar => fn state' =>
854               letPRIM("notVar", IR.T_BOOL, IR.NOT, [cvar], fn var => k var state'))
855    
856                             letPRIM("resNorm", IR.T_VEC, IR.SCALE, [psvToIRVar(env, resilience), scaledN], fn resNorm =>          (* end case *))
   
                            IR.mkIF(inCutoff,  
                              (*then*)  
                              letPRIM("fInv", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), psvToIRVar(env, friction)], fn frictInv =>  
                              letPRIM("f", IR.T_FLOAT, IR.MULT, [negOne, frictInv], fn modFrict =>  
                              letPRIM("fTang", IR.T_VEC, IR.SCALE, [modFrict, tang], fn frictTang =>  
                              letPRIM("newVel", IR.T_VEC, IR.ADD_VEC, [frictTang, resNorm], fn newVel =>  
                               goto(PS{pos=nextPos, vel=newVel, size=nextSize, ttl=nextIsDead, color=nextColor, pos2=nextPos2, dummy=nextDummy}, blk)  
                             )))),  
                              (*else*)  
                              letPRIM("fTang", IR.T_VEC, IR.SCALE, [negOne, tang], fn frictTang =>  
                              letPRIM("ps_vel", IR.T_VEC, IR.ADD_VEC, [frictTang, resNorm], fn newVel =>  
                               goto(PS{pos=nextPos, vel=newVel, size=nextSize, ttl=nextIsDead, color=nextColor, pos2=nextPos2, dummy=nextDummy}, blk)  
                              ))  
                          )))))))))  
                          end  
                       ),  
                       (*else*)  
                       goto(state, blk))))))))  
                   end  
   
               | P.ACCEL dir =>  
                     letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [psvToIRVar(env, PSV.timeStep), psvToIRVar(env, dir)], fn theScale =>  
                     letPRIM("ps_vel", IR.T_VEC, IR.ADD_VEC, [theScale, vel], fn newVel =>  
                       k(PS{pos = pos, vel = newVel, size = size, ttl = ttl, color = color, pos2=pos2, dummy=dummy})))  
   
               | P.MOVE =>  
                 letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [psvToIRVar(env, PSV.timeStep), vel], fn theScale =>  
                     letPRIM("ps_pos", IR.T_VEC, IR.ADD_VEC, [theScale, pos], fn newPos =>  
                       k(PS{pos = newPos, vel = vel, size = size, ttl = ttl, color = color, pos2=pos2, dummy=dummy})))  
               (*  
               | P.SINK({d, kill_inside}) =>  
                     mkWithinVar("isWithin", env, state, d, fn withinVal =>  
                     mkXOR ("shouldNotKill", withinVal, psvToIRVar(env, kill_inside),  
                       fn shouldNotKill =>  
                     letPRIM("shouldKill", IR.T_BOOL, IR.NOT, [shouldNotKill], fn shouldKill =>  
                     letPRIM("isReallyDead", IR.T_BOOL, IR.OR, [shouldKill, ttl], fn isReallyDead =>  
                     k(PS{pos = pos, vel = vel, size = size, ttl = isReallyDead, color = color})  
                         ))))  
               *)  
   
               | P.ORBITLINESEG {endp1, endp2, maxRad, mag} => let  
                   val blk = newBlock (env, k)  
857                  in                  in
858                  letPRIM("subVec", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, endp2), psvToIRVar(env, endp1)], fn subVec =>        grabVar(cond, env, state, fn result => fn state' =>
859                  letPRIM("vecToEndP", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, endp1)], fn vecToEndP =>        IR.mkIF(result, thenk(state'), elsek(state')))
                 letPRIM("basis", IR.T_VEC, IR.NORM, [subVec], fn basis =>  
                 letPRIM("parDot", IR.T_FLOAT, IR.DOT, [basis, vecToEndP], fn parDot =>  
                 letPRIM("parVec", IR.T_VEC, IR.SCALE, [parDot, basis], fn parVec =>  
                 letPRIM("closestP", IR.T_VEC, IR.ADD_VEC, [psvToIRVar(env, endp1), parVec], fn closestP =>  
                 letPRIM("vecToP", IR.T_VEC, IR.SUB_VEC, [closestP, pos], fn vecToP =>  
                 letPRIM("distToP", IR.T_FLOAT, IR.LEN, [vecToP], fn distToP =>  
                 letPRIM("effRad", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, maxRad), distToP], fn effRad =>  
                 letPRIM("radInDist", IR.T_BOOL, IR.GT, [psvToIRVar(env, epsilon), effRad], fn radInDist =>  
                 IR.mkIF(radInDist,  
                   (*then*)  
                   goto(state, blk),  
                   (*else*)  
                   letPRIM("magRatio", IR.T_FLOAT, IR.DIV, [distToP, psvToIRVar(env, maxRad)], fn magRatio =>  
                   letPRIM("oneMinMR", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), magRatio], fn oneMinMR =>  
                   letPRIM("gravityMag", IR.T_FLOAT, IR.MULT, [oneMinMR, psvToIRVar(env, mag)], fn gravityMag =>  
                   letPRIM("totalMag", IR.T_FLOAT, IR.MULT, [gravityMag, psvToIRVar(env, PSV.timeStep)], fn totMag =>  
                   letPRIM("accVec", IR.T_VEC, IR.SUB_VEC, [closestP, pos], fn accVec =>  
                   letPRIM("acc", IR.T_VEC, IR.SCALE, [totMag, accVec], fn acc =>  
                   letPRIM("ps_vel", IR.T_VEC, IR.ADD_VEC, [vel, acc], fn newVel =>  
                   goto(PS{pos = pos, vel = newVel, size = size, ttl = ttl, color = color, pos2=pos2, dummy=dummy}, blk)  
                   )))))))  
                 )))))))))))  
                 end  
   
               (* just kill it. *)  
               (* | P.DIE => k(PS{pos = pos, vel = vel, size = size, ttl = IR.newConst("falseVar", IR.C_BOOL true), color = color, dummy=dummy}) *)  
               | P.DIE => IR.DISCARD  
               | _ => raise Fail("Action not implemented...")  
             (* end case *)  
860            end            end
861    
862      fun compile (P.PG{      fun compile (P.PG{
863         emit as P.EMIT{maxNum, vars=emitVars, ...},         emit as P.EMIT{freq, sv_gens}, act, render,
864         act as P.PSAE{action=root_act, vars=actionVars},         vars, state_vars, render_vars
        render  
865      }) = let      }) = let
866            val blks = ref[]            val blks = ref[]
867    
868          fun printVar (PSV.V{name, id, ...}) =
869            printErr (String.concat[name, ": ", Int.toString id])
870    
871          val demand = IR.getDemand(render)
872          fun getIRNameForSV (v as PSV.SV{name, ...}) =
873           (case (PSV.SVMap.find (render_vars, v))
874             of SOME na => let
875               fun inDemand n = List.exists (fn x => #1 x = "ps_" ^ n) demand
876              in
877               (* Sanity check *)
878               if not (inDemand na) then
879                 raise Fail (String.concat["Variable with name ", name," marked for rendering but not in demand."])
880               else
881                 "ps_" ^ na
882              end
883              | NONE => "ps_" ^ name
884           (* end case *))
885    
886          fun convertToIR (v as PSV.SV{ty, ...}) = IR.newParam(getIRNameForSV v, IR.psvTyToIRTy ty)
887            val env = let            val env = let
888                (* add special globals to free vars *)                (* add special globals to free vars *)
889                  val vars = PSV.Set.union(emitVars, PSV.Set.addList(actionVars, [maxNum, PSV.numDead, PSV.timeStep, epsilon]))          val pgm_vars = PSV.Set.union(PSV.Set.singleton epsilon, vars)
890                  fun ins (x as PSV.V{name, ty, binding, id, ...}, map) = let          fun insv (x as PSV.V{name, ty, binding, id, ...}, map) = let
891                        val x' = (case (ty, !binding)                        val x' = (case (ty, !binding)
892                               of (PSV.T_BOOL,  PSV.UNDEF) => IR.newGlobal(x, IR.T_BOOL)                               of (PSV.T_BOOL,  PSV.UNDEF) => IR.newGlobal(x, IR.T_BOOL)
893                                | (PSV.T_BOOL,  PSV.BOOL boolVal) => IR.newConst(name, IR.C_BOOL(boolVal))                                | (PSV.T_BOOL,  PSV.BOOL boolVal) => IR.newConst(name, IR.C_BOOL(boolVal))
# Line 573  Line 901 
901                              (* end case *))                              (* end case *))
902                        in                        in
903                          PSV.Map.insert (map, x, x')                          PSV.Map.insert (map, x, x')
904                        end                     end (* ins *)
905                  in                  in
906                    TE(blks, PSV.Set.foldl ins PSV.Map.empty vars)                   TE( blks, PSV.Set.foldl insv PSV.Map.empty pgm_vars )
907                  end                  end (* env *)
908    
909        fun evalActs f [] state = f [] state        fun evalActs theAct state f = (case theAct
             | evalActs f (psa :: psal) state = (case psa  
910                of P.SEQ(acts) => (case acts                of P.SEQ(acts) => (case acts
911                   of [] => raise Fail "Should never reach here."                  of [] => f state
912                    | [act] => trAct(act, env, state, evalActs f psal)                   | oneAct :: rest => evalActs oneAct state (fn state' => (evalActs (P.SEQ(rest)) state' f))
                   | act :: rest => trAct(act, env, state, evalActs f (P.SEQ(rest) :: psal))  
913                  (* end case *))                  (* end case *))
914                 | P.PRED(pred as P.PR{thenstmt=t, elsestmt=e, ...}) => let  
915                     val cblk = newBlock(env, evalActs f psal)                 | P.PRED(cond, thenAct, elseAct) => let
916                     fun trPredActs [] state' = goto(state', cblk)                     val joinBlk = newBlock (env, state, fn state' => f state')
917                       | trPredActs _ _ = raise Fail "Should never reach here."                     fun joinActs state = IR.mkGOTO(joinBlk, state)
918                      in
919                       trPred(cond, env, state,
920                         fn state' => evalActs thenAct state' joinActs,
921                         fn state' => evalActs elseAct state' joinActs
922                       )
923                      end
924    
925                   | P.DIE => IR.DISCARD
926    
927                   | P.ASSIGN(sv, expr) => let
928                     val PSV.SV{ty, ...} = sv
929                     fun replaceStateVar (var, []) = [var]
930                       | replaceStateVar (var, nv :: svars) = let
931                         val IR.V{name=nvname, ...} = nv
932                         val IR.V{name=varname, ...} = var
933                    in                    in
934                     trPred(pred, env, state, evalActs trPredActs t, evalActs trPredActs e)                       if nvname = varname then
935                           var :: svars
936                         else
937                           nv :: replaceStateVar(var, svars)
938                    end                    end
939                (* end case *))                  in
940                     trExpr(expr, env, state, fn newVar => fn state' =>
941                     letPRIM(getIRNameForSV sv, IR.psvTyToIRTy ty, IR.COPY, [newVar],
942                       fn thisVar => f (replaceStateVar(thisVar, state'))))
943                    end
944    
945                   | P.LET(P.V(varName), exp, act) =>
946                     trExpr(exp, env, state, fn newVar => fn state' => let
947    
948            (* At the highest level, we want to return when we reach the end of the action list *)                     val joinBlk = newBlock(env, state', f)
949            fun trActs [] state = let  
950                  val PS{pos, vel, size, ttl, color, pos2, dummy} = state                     fun inOriginalState (IR.V{name=vn, ...}) = let
951                         fun nameCompare (IR.V{name=vn1, ...}) = vn = vn1
952                        in
953                         List.exists nameCompare state'
954                        end
955    
956                       fun gotoJoinBlk state'' = goto(List.filter inOriginalState state'', joinBlk)
957    
958                       val IR.V{varType, ...} = newVar
959                       val newParam = IR.newParam(varName, varType)
960                       val newState = newParam :: state'
961    
962                       val blk = newBlock(env, newState, fn state'' => evalActs act state'' gotoJoinBlk)
963                  in                  in
964                    IR.mkRETURN (                     goto(newVar :: state', blk)
965                      [ pos, vel, size, ttl, color, pos2, dummy ],                    end
                     [IR.POS, IR.VEL, IR.SZ, IR.TTL, IR.COLOR, IR.POS2, IR.DUMMY]  
966                    )                    )
967                  end (* trActs *)  
968              | trActs _ _ = raise Fail "Should never reach here"                (* end case *))
969    
970            (* The entry block is the first block of the program, or in other words, the emitter. *)            (* The entry block is the first block of the program, or in other words, the emitter. *)
971            val entryBlock = newBlock (            val entryBlock = newBlock (
972              env,              env,
973                List.map convertToIR (PSV.SVSet.listItems state_vars),
974              fn pstate => trEmitter(              fn pstate => trEmitter(
975                emit,                emit,
976                env,                env,
977                pstate,                pstate,
978                fn state => evalActs trActs root_act state                fn state => evalActs act state retState
979              )              )
980            )            )
981    
# Line 627  Line 990 
990    
991            val outPgm = PSysIR.PGM {            val outPgm = PSysIR.PGM {
992              globals = PSV.Map.filter isGlobal (extractVarMap env),              globals = PSV.Map.filter isGlobal (extractVarMap env),
993                persistents = demand,
994                uveOptimized = false,
995          emitter = entryBlock,          emitter = entryBlock,
996              physics = List.nth(!blks, 1),              physics = List.nth(!blks, 1),
997              render = render              render = render
998            }            }
999    
1000            val optimized = if (Checker.checkIR(outPgm)) then (printErr "Pre-optimization complete."; Optimize.optimizeIR(outPgm)) else outPgm            val _ = IR.outputPgm(TextIO.stdErr, outPgm)
1001              val optimized = if (Checker.checkIR(outPgm)) then (printErr "\nPre-optimization complete."; Optimize.optimizeIR(outPgm)) else outPgm
1002            in            in
1003              (* IR.outputPgm(TextIO.stdErr, outPgm); *)              (* Note: it only succeeds if we can optimize, too *)
1004              if Checker.checkIR(optimized) then          if Checker.checkIR(optimized) then printErr "Compilation succeeded." else ();
1005               printErr "Compilation succeeded." (* Note: it only succeeds if we can optimize, too *)  
             else  
              ();  
1006              optimized              optimized
1007            end (* compile *)            end (* compile *)
1008    

Legend:
Removed from v.1008  
changed lines
  Added in v.1143

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0