1 /*
   2  * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.scenario.effect.compiler.backend.sw.sse;
  27 
  28 import java.io.InputStreamReader;
  29 import java.io.Reader;
  30 import java.util.Collection;
  31 import java.util.Comparator;
  32 import java.util.HashMap;
  33 import java.util.HashSet;
  34 import java.util.Map;
  35 import java.util.Set;
  36 import java.util.SortedSet;
  37 import java.util.TreeSet;
  38 import com.sun.scenario.effect.compiler.JSLParser;
  39 import com.sun.scenario.effect.compiler.model.BaseType;
  40 import com.sun.scenario.effect.compiler.model.Qualifier;
  41 import com.sun.scenario.effect.compiler.model.Type;
  42 import com.sun.scenario.effect.compiler.model.Variable;
  43 import com.sun.scenario.effect.compiler.tree.FuncDef;
  44 import com.sun.scenario.effect.compiler.tree.ProgramUnit;
  45 import com.sun.scenario.effect.compiler.tree.TreeScanner;
  46 import org.antlr.stringtemplate.StringTemplate;
  47 import org.antlr.stringtemplate.StringTemplateGroup;
  48 import org.antlr.stringtemplate.language.DefaultTemplateLexer;
  49 
  50 /**
  51  */
  52 public class SSEBackend extends TreeScanner {
  53 
  54     private final JSLParser parser;
  55     private final String body;
  56 
  57     public SSEBackend(JSLParser parser, ProgramUnit program) {
  58         // TODO: will be removed once we clean up static usage
  59         resetStatics();
  60 
  61         this.parser = parser;
  62         
  63         SSETreeScanner scanner = new SSETreeScanner();
  64         scanner.scan(program);
  65         this.body = scanner.getResult();
  66     }
  67     
  68     public static class GenCode {
  69         public String javaCode;
  70         public String nativeCode;
  71     }
  72 
  73     private static void appendGetRelease(StringBuilder get,
  74                                          StringBuilder rel,
  75                                          String ctype,
  76                                          String cbufName, String jarrayName)
  77     {
  78         get.append("j" + ctype + " *" + cbufName + " = (j" + ctype + " *)");
  79         get.append("env->GetPrimitiveArrayCritical(" + jarrayName + ", 0);\n");
  80         get.append("if (" + cbufName + " == NULL) return;\n");
  81         rel.append("env->ReleasePrimitiveArrayCritical(" + jarrayName + ", " + cbufName + ", JNI_ABORT);\n");
  82     }
  83 
  84     private static SortedSet<Variable> getSortedVars(Collection<Variable> unsortedVars) {
  85         Comparator<Variable> c = new Comparator<Variable>() {
  86             public int compare(Variable v0, Variable v1) {
  87                 return v0.getName().compareTo(v1.getName());
  88             }
  89         };
  90         SortedSet<Variable> sortedVars = new TreeSet<Variable>(c);
  91         sortedVars.addAll(unsortedVars);
  92         return sortedVars;
  93     }
  94 
  95     public final GenCode getGenCode(String effectName,
  96                                     String peerName,
  97                                     String interfaceName)
  98     {
  99         Map<String, Variable> vars = parser.getSymbolTable().getGlobalVariables();
 100         StringBuilder interfaceDecl = new StringBuilder();
 101         StringBuilder constants = new StringBuilder();
 102         StringBuilder samplers = new StringBuilder();
 103         StringBuilder cleanup = new StringBuilder();
 104         StringBuilder srcRects = new StringBuilder();
 105         StringBuilder posDecls = new StringBuilder();
 106         StringBuilder pixInitY = new StringBuilder();
 107         StringBuilder pixInitX = new StringBuilder();
 108         StringBuilder posIncrY = new StringBuilder();
 109         StringBuilder posInitY = new StringBuilder();
 110         StringBuilder posIncrX = new StringBuilder();
 111         StringBuilder posInitX = new StringBuilder();
 112         StringBuilder jparams = new StringBuilder();
 113         StringBuilder jparamDecls = new StringBuilder();
 114         StringBuilder cparamDecls = new StringBuilder();
 115         StringBuilder arrayGet = new StringBuilder();
 116         StringBuilder arrayRelease = new StringBuilder();
 117 
 118         appendGetRelease(arrayGet, arrayRelease, "int", "dst", "dst_arr");
 119         
 120         // TODO: only need to declare these if pixcoord is referenced
 121         // somewhere in the program...
 122         pixInitY.append("float pixcoord_y = (float)dy;\n");
 123         pixInitX.append("float pixcoord_x = (float)dx;\n");
 124 
 125         // this step isn't strictly necessary but helps give some predictability
 126         // to the generated jar/nativelib so that the method signatures have
 127         // a consistent parameter ordering on all platforms for each build,
 128         // which may help debugging (see RT-4475)
 129         SortedSet<Variable> sortedVars = getSortedVars(vars.values());
 130         for (Variable v : sortedVars) {
 131             if (v.getQualifier() == Qualifier.CONST && v.getConstValue() == null) {
 132                 // this must be a special built-in variable (e.g. pos0);
 133                 // these are handled elsewhere, so just continue...
 134                 continue;
 135             }
 136             
 137             Type t = v.getType();
 138             BaseType bt = t.getBaseType();
 139             String vtype = bt.toString();
 140             String vname = v.getName();
 141             if (v.getQualifier() != null && bt != BaseType.SAMPLER) {
 142                 String accName = v.getAccessorName();
 143                 if (v.isArray()) {
 144                     // TODO: we currently assume that param arrays will be
 145                     // stored in NIO Int/FloatBuffers, but the inner loop
 146                     // expects to access them as Java arrays, so we convert
 147                     // here; this is obviously bad for performance, so we need
 148                     // to come up with a better system soon...
 149                     String bufType = (bt == BaseType.FLOAT) ?
 150                         "FloatBuffer" : "IntBuffer";
 151                     String bufName = vname + "_buf";
 152                     String arrayName = vname + "_arr";
 153                     constants.append(bufType + " " + bufName + " = " + accName + "();\n");
 154                     constants.append(vtype + "[] " + arrayName);
 155                     constants.append(" = new " + vtype + "[");
 156                     constants.append(bufName + ".capacity()];\n");
 157                     constants.append(bufName + ".get(" + arrayName + ");\n");
 158                     jparams.append(",\n");
 159                     jparams.append(arrayName);
 160                     jparamDecls.append(",\n");
 161                     jparamDecls.append(vtype + "[] " + vname);
 162                     cparamDecls.append(",\n");
 163                     cparamDecls.append("j" + vtype + "Array " + vname);
 164                     appendGetRelease(arrayGet, arrayRelease, vtype, arrayName, vname);
 165                 } else {
 166                     if (t.isVector()) {
 167                         String arrayName = vname + "_arr";
 168                         constants.append(vtype + "[] " + arrayName + " = " + accName + "();\n");
 169                         jparams.append(",\n");
 170                         jparamDecls.append(",\n");
 171                         cparamDecls.append(",\n");
 172                         for (int i = 0; i < t.getNumFields(); i++) {
 173                             if (i > 0) {
 174                                 jparams.append(", ");
 175                                 jparamDecls.append(", ");
 176                                 cparamDecls.append(", ");
 177                             }
 178                             String vn = vname + getSuffix(i);
 179                             jparams.append(arrayName + "[" + i + "]");
 180                             jparamDecls.append(vtype + " " + vn);
 181                             cparamDecls.append("j" + vtype + " " + vn);
 182                         }
 183                     } else {
 184                         constants.append(vtype + " " + vname);
 185                         if (v.getQualifier() == Qualifier.CONST) {
 186                             constants.append(" = " + v.getConstValue());
 187                         } else {
 188                             constants.append(" = " + accName + "()");
 189                         }
 190                         constants.append(";\n");
 191                         jparams.append(",\n");
 192                         jparams.append(vname);
 193                         jparamDecls.append(",\n");
 194                         jparamDecls.append(vtype + " " + vname);
 195                         cparamDecls.append(",\n");
 196                         cparamDecls.append("j" + vtype + " " + vname);
 197                     }
 198                 }
 199             } else if (v.getQualifier() == Qualifier.PARAM && bt == BaseType.SAMPLER) {
 200                 int i = v.getReg();
 201                 if (t == Type.FSAMPLER) {
 202                     samplers.append("FloatMap src" + i + " = (FloatMap)getSamplerData(" + i + ");\n");
 203                     samplers.append("int src" + i + "x = 0;\n");
 204                     samplers.append("int src" + i + "y = 0;\n");
 205                     samplers.append("int src" + i + "w = src" + i + ".getWidth();\n");
 206                     samplers.append("int src" + i + "h = src" + i + ".getHeight();\n");
 207                     samplers.append("int src" + i + "scan = src" + i + ".getWidth();\n");
 208                     samplers.append("float[] " + vname + " = src" + i + ".getData();\n");
 209 
 210                     arrayGet.append("float " + vname + "_vals[4];\n");
 211 
 212                     // TODO: for now, assume [0,0,1,1]
 213                     srcRects.append("float[] src" + i + "Rect = new float[] {0,0,1,1};\n");
 214                     
 215                     jparams.append(",\n");
 216                     jparams.append(vname);
 217                     
 218                     jparamDecls.append(",\n");
 219                     jparamDecls.append("float[] " + vname + "_arr");
 220                     
 221                     cparamDecls.append(",\n");
 222                     cparamDecls.append("jfloatArray " + vname + "_arr");
 223                     
 224                     appendGetRelease(arrayGet, arrayRelease, "float", vname, vname + "_arr");
 225                 } else {
 226                     if (t == Type.LSAMPLER) {
 227                         samplers.append("HeapImage src" + i + " = (HeapImage)inputs[" + i + "].getUntransformedImage();\n");
 228                     } else {
 229                         samplers.append("HeapImage src" + i + " = (HeapImage)inputs[" + i + "].getTransformedImage(dstBounds);\n");
 230                         cleanup.append("inputs[" + i + "].releaseTransformedImage(src" + i + ");\n");
 231                     }
 232                     samplers.append("int src" + i + "x = 0;\n");
 233                     samplers.append("int src" + i + "y = 0;\n");
 234                     samplers.append("int src" + i + "w = src" + i + ".getPhysicalWidth();\n");
 235                     samplers.append("int src" + i + "h = src" + i + ".getPhysicalHeight();\n");
 236                     samplers.append("int src" + i + "scan = src" + i + ".getScanlineStride();\n");
 237                     samplers.append("int[] " + vname + " =\n");
 238                     samplers.append("    src" + i + ".getPixelArray();\n");
 239 
 240                     samplers.append("Rectangle src" + i + "Bounds = new Rectangle(");
 241                     samplers.append("src" + i + "x, ");
 242                     samplers.append("src" + i + "y, ");
 243                     samplers.append("src" + i + "w, ");
 244                     samplers.append("src" + i + "h);\n");
 245                     if (t == Type.LSAMPLER) {
 246                         samplers.append("Rectangle src" + i + "InputBounds = inputs[" + i + "].getUntransformedBounds();\n");
 247                         samplers.append("BaseTransform src" + i + "Transform = inputs[" + i + "].getTransform();\n");
 248                     } else {
 249                         samplers.append("Rectangle src" + i + "InputBounds = inputs[" + i + "].getTransformedBounds(dstBounds);\n");
 250                         samplers.append("BaseTransform src" + i + "Transform = BaseTransform.IDENTITY_TRANSFORM;\n");
 251                     }
 252                     samplers.append("setInputBounds(" + i + ", src" + i + "InputBounds);\n");
 253                     samplers.append("setInputNativeBounds(" + i + ", src" + i + "Bounds);\n");
 254 
 255                     if (t == Type.LSAMPLER) {
 256                         arrayGet.append("float " + vname + "_vals[4];\n");
 257                     }
 258 
 259                     // the source rect decls need to come after all calls to
 260                     // setInput[Native]Bounds() for all inputs (since the
 261                     // getSourceRegion() impl may need to query the bounds of
 262                     // other inputs, as is the case in PhongLighting)...
 263                     srcRects.append("float[] src" + i + "Rect = new float[4];\n");
 264                     // Note that we only allocate 4 floats here because none
 265                     // of the loops can deal with fully mapped inputs.  Only
 266                     // shaders that declare LSAMPLERs would require mapped
 267                     // inputs and so far that is only Perspective and
 268                     // Displacement, both of which override getTC() and return
 269                     // only 4 values.
 270                     srcRects.append("getTextureCoordinates(" + i + ", src" + i + "Rect,\n");
 271                     srcRects.append("                      src" + i + "InputBounds.x, src" + i + "InputBounds.y,\n");
 272                     srcRects.append("                      src" + i + "w, src" + i + "h,\n");
 273                     srcRects.append("                      dstBounds, src" + i + "Transform);\n");
 274 
 275                     jparams.append(",\n");
 276                     jparams.append(vname);
 277                     
 278                     jparamDecls.append(",\n");
 279                     jparamDecls.append("int[] " + vname + "_arr");
 280                     
 281                     cparamDecls.append(",\n");
 282                     cparamDecls.append("jintArray " + vname + "_arr");
 283                     
 284                     appendGetRelease(arrayGet, arrayRelease, "int", vname, vname + "_arr");
 285                 }
 286 
 287                 posDecls.append("float inc" + i + "_x = (src" + i + "Rect_x2 - src" + i + "Rect_x1) / dstw;\n");
 288                 posDecls.append("float inc" + i + "_y = (src" + i + "Rect_y2 - src" + i + "Rect_y1) / dsth;\n");
 289 
 290                 posInitY.append("float pos" + i + "_y = src" + i + "Rect_y1 + inc" + i + "_y*0.5f;\n");
 291                 posInitX.append("float pos" + i + "_x = src" + i + "Rect_x1 + inc" + i + "_x*0.5f;\n");
 292                 posIncrX.append("pos" + i + "_x += inc" + i + "_x;\n");
 293                 posIncrY.append("pos" + i + "_y += inc" + i + "_y;\n");
 294 
 295                 jparams.append(",\n");
 296                 jparams.append("src" + i + "Rect[0], src" + i + "Rect[1],\n");
 297                 jparams.append("src" + i + "Rect[2], src" + i + "Rect[3],\n");
 298                 jparams.append("src" + i + "w, src" + i + "h, src" + i + "scan");
 299                 
 300                 jparamDecls.append(",\n");
 301                 jparamDecls.append("float src" + i + "Rect_x1, float src" + i + "Rect_y1,\n");
 302                 jparamDecls.append("float src" + i + "Rect_x2, float src" + i + "Rect_y2,\n");
 303                 jparamDecls.append("int src" + i + "w, int src" + i + "h, int src" + i + "scan");
 304 
 305                 cparamDecls.append(",\n");
 306                 cparamDecls.append("jfloat src" + i + "Rect_x1, jfloat src" + i + "Rect_y1,\n");
 307                 cparamDecls.append("jfloat src" + i + "Rect_x2, jfloat src" + i + "Rect_y2,\n");
 308                 cparamDecls.append("jint src" + i + "w, jint src" + i + "h, jint src" + i + "scan");
 309             }
 310         }
 311 
 312         if (interfaceName != null) {
 313             interfaceDecl.append("implements "+interfaceName);
 314         }
 315 
 316         Reader template = new InputStreamReader(getClass().getResourceAsStream("SSEJavaGlue.stg"));
 317         StringTemplateGroup group = new StringTemplateGroup(template, DefaultTemplateLexer.class);
 318         StringTemplate jglue = group.getInstanceOf("glue");
 319         jglue.setAttribute("effectName", effectName);
 320         jglue.setAttribute("peerName", peerName);
 321         jglue.setAttribute("interfaceDecl", interfaceDecl.toString());
 322         jglue.setAttribute("usercode", usercode.toString());
 323         jglue.setAttribute("samplers", samplers.toString());
 324         jglue.setAttribute("cleanup", cleanup.toString());
 325         jglue.setAttribute("srcRects", srcRects.toString());
 326         jglue.setAttribute("constants", constants.toString());
 327         jglue.setAttribute("params", jparams.toString());
 328         jglue.setAttribute("paramDecls", jparamDecls.toString());
 329 
 330         template = new InputStreamReader(getClass().getResourceAsStream("SSENativeGlue.stg"));
 331         group = new StringTemplateGroup(template, DefaultTemplateLexer.class);
 332         StringTemplate cglue = group.getInstanceOf("glue");
 333         cglue.setAttribute("peerName", peerName);
 334         cglue.setAttribute("jniName", peerName.replace("_", "_1"));
 335         cglue.setAttribute("paramDecls", cparamDecls.toString());
 336         cglue.setAttribute("arrayGet", arrayGet.toString());
 337         cglue.setAttribute("arrayRelease", arrayRelease.toString());
 338         cglue.setAttribute("posDecls", posDecls.toString());
 339         cglue.setAttribute("pixInitY", pixInitY.toString());
 340         cglue.setAttribute("pixInitX", pixInitX.toString());
 341         cglue.setAttribute("posIncrY", posIncrY.toString());
 342         cglue.setAttribute("posInitY", posInitY.toString());
 343         cglue.setAttribute("posIncrX", posIncrX.toString());
 344         cglue.setAttribute("posInitX", posInitX.toString());
 345         cglue.setAttribute("body", body);
 346         
 347         GenCode gen = new GenCode();
 348         gen.javaCode = jglue.toString();
 349         gen.nativeCode = cglue.toString();
 350         return gen;
 351     }
 352     
 353     // TODO: need better mechanism for querying fields
 354     private static char[] fields = {'x', 'y', 'z', 'w'};
 355     public static String getSuffix(int i) {
 356         return "_" + fields[i];
 357     }
 358 
 359     static int getFieldIndex(char field) {
 360         switch (field) {
 361         case 'r':
 362         case 'x':
 363             return 0;
 364         case 'g':
 365         case 'y':
 366             return 1;
 367         case 'b':
 368         case 'z':
 369             return 2;
 370         case 'a':
 371         case 'w':
 372             return 3;
 373         default:
 374             throw new InternalError();
 375         }
 376     }
 377     
 378     // TODO: these shouldn't be implemented as a static method
 379     private static Map<String, FuncDef> funcDefs = new HashMap<String, FuncDef>();
 380     static void putFuncDef(FuncDef def) {
 381         funcDefs.put(def.getFunction().getName(), def);
 382     }
 383     static FuncDef getFuncDef(String name) {
 384         return funcDefs.get(name);
 385     }
 386     
 387     private static Set<String> resultVars = new HashSet<String>();
 388     static boolean isResultVarDeclared(String vname) {
 389         return resultVars.contains(vname);
 390     }
 391     static void declareResultVar(String vname) {
 392         resultVars.add(vname);
 393     }
 394     
 395     private static StringBuilder usercode = new StringBuilder();
 396     static void addGlueBlock(String block) {
 397         usercode.append(block);
 398     }
 399     
 400     private static void resetStatics() {
 401         funcDefs.clear();
 402         resultVars.clear();
 403         usercode = new StringBuilder();
 404     }
 405 }