示例#1
1
 public MapBuilder(String name, File toLoad, File toSave, String tileDir) {
   super(name);
   currTileImg = null;
   currTileLoc = "";
   try {
     System.out.println(tileDir);
     currTileImg = new ImageIcon(getTile(tileDir, 0, 0, DISPLAY_SCALE));
     currTileLoc = "0_0";
   } catch (IOException e) {
     System.out.println("Generating current tile failed.");
     System.out.println(e);
     System.exit(0);
   }
   currTileDisplay = new JLabel(new ImageIcon(scaleImage(currTileImg.getImage(), 2)));
   this.input = toLoad;
   output = toSave;
   this.tileDir = tileDir;
   if (toLoad != null) {
     try {
       backEnd = loadMap(toLoad);
     } catch (FileNotFoundException e) {
       System.err.println("Could not find input file.");
       System.exit(0);
     }
   } else {
     backEnd = emptyMap(DEFAULT_WIDTH, DEFAULT_HEIGHT);
   }
   mapWidth = backEnd.getWidth();
   mapHeight = backEnd.getHeight();
 }
 /** push bytes back, to be read again later. */
 private void pushback(byte[] bytes, int len) {
   if (pushbackBufferLen == 0) {
     pushbackBuffer = bytes; // TODO: copy?
     pushbackBufferLen = len;
     pushbackBufferOffset = 0;
   } else {
     final byte[] newPushbackBuffer = new byte[pushbackBufferLen + len];
     System.arraycopy(pushbackBuffer, 0, newPushbackBuffer, 0, pushbackBufferLen);
     System.arraycopy(bytes, 0, newPushbackBuffer, pushbackBufferLen, len);
     pushbackBuffer = newPushbackBuffer;
     pushbackBufferLen = pushbackBufferLen + len;
     pushbackBufferOffset = 0;
   }
 }
 /** constructor */
 public DanceQueuePanel() {
   //	flow layout
   setLayout(new FlowLayout());
   //	uses buffer	to	draw arrows	based	on	queues in an array
   myImage = new BufferedImage(600, 600, BufferedImage.TYPE_INT_RGB);
   myBuffer = myImage.getGraphics();
   // uses timer to queue buffer changes
   time = 0;
   timer = new Timer(5, new Listener());
   timer.start();
   setFocusable(true);
   // picks instructions	based	on	song & level
   if (Danceoff.getSong() == -1 && Danceoff.getDifficulty() == 0) {
     arrows = new Arrow[] {new UpArrow(1000), new DownArrow(2000), new LeftArrow(3000)};
   }
   // setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 3),
   //	"DanceQueuePanel"));
   // load images for arrows
   rightArrowImg = null;
   leftArrowImg = null;
   upArrowImg = null;
   downArrowImg = null;
   try {
     rightArrowImg = ImageIO.read(new File("arrowB right.png"));
     leftArrowImg = ImageIO.read(new File("arrowB left.png"));
     upArrowImg = ImageIO.read(new File("arrowB up copy.png"));
     downArrowImg = ImageIO.read(new File("arrowB down.png"));
   } catch (IOException e) {
     warn("YOU FAIL", e);
     System.exit(2);
   }
 }
示例#4
0
 public void loadTree() {
   System.out.println("Loading tree");
   StreamTokenizer stream = null;
   try {
     FileInputStream f = new FileInputStream(tree);
     Reader input = new BufferedReader(new InputStreamReader(f));
     stream = new StreamTokenizer(input);
     stream.resetSyntax();
     stream.wordChars(32, 127);
   } catch (Exception e) {
     System.out.println("Error opening " + tree);
     System.exit(1);
   }
   list = new ArrayList();
   try {
     // read the file to the end
     while (stream.nextToken() != StreamTokenizer.TT_EOF) {
       // is a word being read
       if (stream.ttype == StreamTokenizer.TT_WORD) {
         list.add(new String(stream.sval));
       }
       // is a number being read
       if (stream.ttype == StreamTokenizer.TT_NUMBER) {
         list.add(new Double(stream.nval));
       }
     }
   } catch (Exception e) {
     System.out.println("\nError reading " + tree + ". Exiting...");
     System.exit(1);
   }
 }
示例#5
0
  public static void main(String[] args) {
    // read arguments and respond correctly
    File in;
    File out;
    String tileDirectory;
    if (args.length == 0 || args.length > 2) {
      in = null;
      out = null;
      tileDirectory = "";
      System.err.println("Incorrect number of arguments. Required: Filename (tileset path)");
      System.exit(0);
    } else if (args.length == 1) { // load old file
      in = new File(args[0]);
      out = in;
      Scanner s = null;
      try {
        s = new Scanner(in);
      } catch (FileNotFoundException e) {
        System.out.println("Could not find input file.");
        System.exit(0);
      }
      tileDirectory = s.nextLine();
    } else {
      in = null;
      out = new File(args[0]);
      tileDirectory = args[1];
      try {
        File f = new File(tileDirectory);
        if (!f.isDirectory()) {
          throw new IOException("Tileset does not exist");
        }
      } catch (IOException e) {
        System.err.println(e);
        System.out.println("This error is likely thanks to an invalid tileset path");
        System.exit(0);
      }
    }

    MapBuilder test = new MapBuilder("Map Editor", in, out, tileDirectory);

    // Build GUI
    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            test.CreateAndDisplayGUI();
          }
        });
  }
  public static BufferedImage encodeImage(String filename, int[] primes) {
    /* encodes a and b in the image using a sequence.
     * We are assuming that the image would be big enough
     * to hold the 16 bits
     */

    BufferedImage img, newimg = null;
    int[] a = convertToBinary(primes[0], 8);
    int[] b = convertToBinary(primes[1], 8);
    int[] a_b = copyBits(a, b); // copy all bits into one array

    try {
      img = ImageIO.read(new File(imagePath + filename));
      for (int i = 0; i < a_b.length; i++) {
        int p = img.getRGB(i, i);
        int[] bin = convertToBinary(p, 32);
        bin[0] = a_b[i];
        int d = convertToDigit(bin, 32);
        img.setRGB(i, i, d);
      }
      ImageIO.write(img, "png", new File(imagePath + "new_" + filename));
      newimg = ImageIO.read(new File(imagePath + "new_" + filename));
    } catch (IOException e) {
      System.out.println("ERROR WRITING IMAGE...\n" + e.toString());
      System.exit(1);
    }

    return newimg;
  }
示例#7
0
 public static void main(String[] args) {
   try {
     // The image is loaded either from this
     //   default filename or the first command-
     //   line argument.
     // The second command-line argument specifies
     //   what string will be displayed. The third
     //   specifies at what point in the string the
     //   background color will change.
     String filename = "Raphael.jpg";
     String message = "Java2D";
     int split = 4;
     if (args.length > 0) filename = args[0];
     if (args.length > 1) message = args[1];
     if (args.length > 2) split = Integer.parseInt(args[2]);
     ApplicationFrame f = new ApplicationFrame("ShowOff v1.0");
     f.setLayout(new BorderLayout());
     ShowOff showOff = new ShowOff(filename, message, split);
     f.add(showOff, BorderLayout.CENTER);
     f.setSize(f.getPreferredSize());
     f.center();
     f.setResizable(false);
     f.setVisible(true);
   } catch (Exception e) {
     System.out.println(e);
     System.exit(0);
   }
 }
示例#8
0
  public APCircleWindow() {
    super("AP Circles");
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    String startDirectoryName = System.getProperty("user.dir");
    startDirectory = new File(startDirectoryName);
    // this for convenience, as the program normally starts in graph/display
    //		startDirectory = startDirectory.getParentFile();

    gw = this;

    generalXML = new GeneralXML(graph);

    gp = new APCirclePanel(this);
    getContentPane().add(gp);

    graph = gp.getGraph();

    initView();
    initExperiment();
    initUtility();
    initLayout();
    initMenu();

    setSize(width, height);

    Dimension frameDim = Toolkit.getDefaultToolkit().getScreenSize();
    int posX = (frameDim.width - getSize().width) / 2;
    int posY = (frameDim.height - getSize().height) / 2;
    setLocation(posX, posY);

    setVisible(true);

    gp.requestFocus();
  }
示例#9
0
 private static void usage() {
   System.out.println("\nUSAGE: java " + classname + " [options]\n");
   System.out.println("Options:\n");
   System.out.println("-yuv = test YUV encoding/decoding support\n");
   System.out.println("-bi = test BufferedImage support\n");
   System.exit(1);
 }
示例#10
0
 public void actionPerformed(ActionEvent event) {
   PanImage1 panImage1 = new PanImage1();
   PanImage2 panImage2 = new PanImage2();
   PanImage3 panImage3 = new PanImage3();
   revalidate();
   if (event.getSource() == btnClick) {
     if (nImg == 0) {
       nImg = 3;
     } else {
       nImg--;
     }
   } else if (event.getSource() == btnClick2) {
     if (nImg == 4) {
       nImg = 1;
     } else {
       nImg++;
     }
   } else if (event.getSource() == btnClick3) {
     System.exit(0);
   }
   if (nImg == 1) {
     add(panImage1);
   }
   if (nImg == 2) {
     add(panImage2);
   }
   if (nImg == 3) {
     add(panImage3);
   }
 }
示例#11
0
  public void restartApplication() {

    try {

      final String javaBin =
          System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaw";
      final File currentJar =
          new File(network.class.getProtectionDomain().getCodeSource().getLocation().toURI());

      System.out.println("javaBin " + javaBin);
      System.out.println("currentJar " + currentJar);
      System.out.println("currentJar.getPath() " + currentJar.getPath());

      /* is it a jar file? */
      // if(!currentJar.getName().endsWith(".jar")){return;}

      try {

        // xmining = 0;
        // systemx.shutdown();

      } catch (Exception e) {
        e.printStackTrace();
      }

      /* Build command: java -jar application.jar */
      final ArrayList<String> command = new ArrayList<String>();
      command.add(javaBin);
      command.add("-jar");
      command.add("-Xms256m");
      command.add("-Xmx1024m");
      command.add(currentJar.getPath());

      final ProcessBuilder builder = new ProcessBuilder(command);
      builder.start();

      // try{Thread.sleep(10000);} catch (InterruptedException e){}

      // close and exit
      SystemTray.getSystemTray().remove(network.icon);
      System.exit(0);

    } // try
    catch (Exception e) {
      JOptionPane.showMessageDialog(null, e.getCause());
    }
  } // ******************************
示例#12
0
  public static void main(String[] args) {
    try {
      if (args.length != 2) {
        System.err.println("USAGE: java RenderMap map.txt image.png");
        System.exit(1);
      }
      Game game = new Game(args[0], 100, 0);
      if (game.Init() == 0) {
        System.err.println("Error while loading map " + args[0]);
        System.exit(1);
      }

      ArrayList<Color> colors = new ArrayList<Color>();
      colors.add(new Color(106, 74, 60));
      colors.add(new Color(74, 166, 60));
      colors.add(new Color(204, 51, 63));
      colors.add(new Color(235, 104, 65));
      colors.add(new Color(237, 201, 81));
      Color bgColor = new Color(188, 189, 172);
      Color textColor = Color.BLACK;
      Font planetFont = new Font("Sans Serif", Font.BOLD, 11);
      Font fleetFont = new Font("Sans serif", Font.PLAIN, 7);

      GraphicsConfiguration gc =
          GraphicsEnvironment.getLocalGraphicsEnvironment()
              .getDefaultScreenDevice()
              .getDefaultConfiguration();

      BufferedImage image = gc.createCompatibleImage(640, 480);

      Graphics2D _g = (Graphics2D) image.createGraphics();

      // Turn on AA/Speed
      _g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      _g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
      _g.setRenderingHint(
          RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

      game.Render(640, 480, 0.0, null, colors, bgColor, textColor, planetFont, fleetFont, _g);

      File file = new File(args[1]);
      ImageIO.write(image, "png", file);
    } catch (Exception e) {
      System.err.println(e);
    }
  }
 /** supports pushback. */
 private int read(byte[] buffer, int offset, int length) throws IOException {
   if (pushbackBufferLen > 0) { // read from pushback buffer
     final int lenToCopy = length < pushbackBufferLen ? length : pushbackBufferLen;
     System.arraycopy(pushbackBuffer, pushbackBufferOffset, buffer, offset, lenToCopy);
     pushbackBufferLen -= lenToCopy;
     pushbackBufferOffset += lenToCopy;
     return lenToCopy;
   } else {
     return stream.read(buffer, offset, length);
   }
 }
示例#14
0
  public void method345() {
    int ai[] = new int[anInt1444 * anInt1445];
    for (int j = 0; j < myHeight; j++) {
      System.arraycopy(myPixels, j * myWidth, ai, j + anInt1443 * anInt1444 + anInt1442, myWidth);
    }

    myPixels = ai;
    myWidth = anInt1444;
    myHeight = anInt1445;
    anInt1442 = 0;
    anInt1443 = 0;
  }
 /**
  * Draws the widget.
  *
  * @param g The object that draws things.
  */
 public void draw(Graphics2D screen) {
   // Animate!
   if (System.nanoTime() - timestamp >= CENTISECOND * 50) {
     timestamp = System.nanoTime();
     if (image == frames.get(0)) {
       image = frames.get(1);
     } else {
       image = frames.get(0);
     }
   }
   ROVector2f position = body.getPosition();
   float angle = body.getRotation();
   boolean hflip = false;
   boolean vflip = false;
   if (currentDirection == Direction.WEST) {
     hflip = false;
   } else if (currentDirection == Direction.EAST) {
     hflip = true;
   } else if (currentDirection == Direction.NORTH) {
     angle += Math.PI / 2;
     vflip = false;
   } else if (currentDirection == Direction.SOUTH) {
     angle += Math.PI / 2;
     vflip = true;
   }
   drawImage(
       position.getX(),
       position.getY(),
       getWidth(),
       getHeight(),
       angle,
       hflip,
       vflip,
       image,
       screen);
 }
示例#16
0
文件: GuiClient.java 项目: x-mel/eva
  // we define the method for getting a video link when pressing enter
  public String getvidlink() {
    try {
      System.setSecurityManager(new SecurityManager());

      ipadd = tfIP.getText();
      Interface client = (Interface) Naming.lookup("rmi://" + ipadd + "/getvid");

      // Get the String entered into the TextField tfInput, convert to int
      link = tfInput.getText();
      vlink = client.getvid(link);

    } catch (Exception e) {
      System.out.println("[System] Server failed: " + e);
    }
    return vlink;
  }
示例#17
0
 public static void main(String argv[]) {
   try {
     String testName = "javatest";
     boolean doyuv = false;
     for (int i = 0; i < argv.length; i++) {
       if (argv[i].equalsIgnoreCase("-yuv")) doyuv = true;
       if (argv[i].substring(0, 1).equalsIgnoreCase("-h") || argv[i].equalsIgnoreCase("-?"))
         usage();
       if (argv[i].equalsIgnoreCase("-bi")) {
         bi = true;
         testName = "javabitest";
       }
     }
     if (doyuv) yuv = YUVENCODE;
     doTest(35, 39, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_444, testName);
     doTest(39, 41, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_444, testName);
     doTest(41, 35, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_422, testName);
     doTest(35, 39, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_422, testName);
     doTest(39, 41, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_420, testName);
     doTest(41, 35, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_420, testName);
     doTest(35, 39, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_440, testName);
     doTest(39, 41, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_440, testName);
     doTest(35, 39, bi ? onlyGrayBI : onlyGray, TJ.SAMP_GRAY, testName);
     doTest(39, 41, bi ? _3byteFormatsBI : _3byteFormats, TJ.SAMP_GRAY, testName);
     doTest(41, 35, bi ? _4byteFormatsBI : _4byteFormats, TJ.SAMP_GRAY, testName);
     if (!doyuv && !bi) bufSizeTest();
     if (doyuv && !bi) {
       yuv = YUVDECODE;
       doTest(48, 48, onlyRGB, TJ.SAMP_444, "javatest_yuv0");
       doTest(35, 39, onlyRGB, TJ.SAMP_444, "javatest_yuv1");
       doTest(48, 48, onlyRGB, TJ.SAMP_422, "javatest_yuv0");
       doTest(39, 41, onlyRGB, TJ.SAMP_422, "javatest_yuv1");
       doTest(48, 48, onlyRGB, TJ.SAMP_420, "javatest_yuv0");
       doTest(41, 35, onlyRGB, TJ.SAMP_420, "javatest_yuv1");
       doTest(48, 48, onlyRGB, TJ.SAMP_440, "javatest_yuv0");
       doTest(35, 39, onlyRGB, TJ.SAMP_440, "javatest_yuv1");
       doTest(48, 48, onlyRGB, TJ.SAMP_GRAY, "javatest_yuv0");
       doTest(35, 39, onlyRGB, TJ.SAMP_GRAY, "javatest_yuv1");
       doTest(48, 48, onlyGray, TJ.SAMP_GRAY, "javatest_yuv0");
       doTest(39, 41, onlyGray, TJ.SAMP_GRAY, "javatest_yuv1");
     }
   } catch (Exception e) {
     e.printStackTrace();
     exitStatus = -1;
   }
   System.exit(exitStatus);
 }
  private void jButton1ActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed
    // Note: Google Static Maps API uses an
    // API key to identify your application.
    MapLookup.setLicenseKey(GOOGLE_API_KEY);
    timer.start();

    Subscribe sub = new Subscribe();
    try {
      for (int a = 100; a < 182; ++a) {
        theListeners.add(sub.main("#" + Integer.toString(a)));
      }
    } catch (Exception e) {
      System.exit(0);
    }
    // Build a Google Static Map API URL of the form:
    // http://maps.googleapis.com/maps/api/staticmap?parameters.
    // See link: https://developers.google.com/maps/documentation/staticmaps/
  }
示例#19
0
  public void start() {
    try {
      Display.setDisplayMode(new DisplayMode(width, height));
      Display.create();
    } catch (LWJGLException e) {
      e.printStackTrace();
      System.exit(0);
    }

    initGL(); // init OpenGL
    map_pack =
        new TexturePack2D(
            "assets/tileset.png",
            16,
            16); // load map texture pack--cant be done in constructor since display is not
                 // initialized

    //		font = new Font("assets/text.png", "assets/text.txt", 6, 13);
    //		font.buildFont(2);	// build the textures for text
    //		BufferedImage image = null;
    //		try {
    //			image = ImageIO.read(new File("assets/pokemon_sprites/front/644.png"));
    //			TexturePack2D pack = new TexturePack2D("assets/tileset2.png", 16, 16);
    //		} catch (IOException e) {
    //			e.printStackTrace();
    //			System.exit(0);
    //		}
    //		image = image.getSubimage(0, 0, 40, 40);
    //		r = new Sprite("assets/pokemon_sprites/front/644.png");
    //		s = new Sprite("assets/pokemon_sprites/front/643.png");

    while (!Display.isCloseRequested() && !finished) {
      if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) finished = true;
      renderGL();
      Display.update();
      Display.sync(60); // cap fps to 60fps
    }

    Display.destroy();
  }
示例#20
0
文件: GuiClient.java 项目: x-mel/eva
  // we define the method for downloading when pressing on the download button
  public void qrvidlink() {
    try {
      System.setSecurityManager(new SecurityManager());

      ipadd = tfIP.getText();
      Interface client = (Interface) Naming.lookup("rmi://" + ipadd + "/getvid");

      // Get the String entered into the TextField tfInput, convert to int
      link = tfInput.getText();
      vlink = client.getvid(link);

      // here we receive the image serialized into bytes from the server and
      // saved it on the client as png image
      byte[] bytimg = client.qrvid(vlink);
      BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytimg));
      File outputfile = new File("qrcode.png");
      ImageIO.write(img, "png", outputfile);

      // img= new ImageIcon(bytimg.toByteArray());
    } catch (Exception e) {
      System.out.println("[System] Server failed: " + e);
    }
  }
示例#21
0
  private void readImage(byte[] data) throws IOException {

    byte[] scanline = new byte[bytesPerLine * colorPlanes];

    if (noTransform) {
      try {
        int offset = 0;
        int nbytes = (width * metadata.bitsPerPixel + 8 - metadata.bitsPerPixel) / 8;
        for (int line = 0; line < height; line++) {
          readScanLine(scanline);
          for (int band = 0; band < colorPlanes; band++) {
            System.arraycopy(scanline, bytesPerLine * band, data, offset, nbytes);
            offset += nbytes;
          }
          processImageProgress(100.0F * line / height);
        }
      } catch (EOFException e) {
      }
    } else {
      if (metadata.bitsPerPixel == 1) read1Bit(data);
      else if (metadata.bitsPerPixel == 4) read4Bit(data);
      else read8Bit(data);
    }
  }
示例#22
0
 protected void fileExit() {
   System.exit(0);
 }
示例#23
0
/**
 * a View for rendering Text's based on bitmaps (when available) or TextLayout (when image not
 * available)
 */
public class TextViewHybrid extends LeafElementView implements Runnable {

  boolean wantToComputeLatexDimensions =
      true; // from preferences: do we want to run LateX to compute preferences
  boolean wantToGetBitMap =
      true; // from preferences: do we want to run LateX+pstoimg to get a bitmap.
  //   wantToGetBitMap=true should Imply wantToComputeLatexDimensions=true

  protected double strx, stry; // TextLayout/Image location with respect to PicText's anchor point
  // [pending] pas joli. A enlever sous peu (utilise juste dans HitInfo que je ne comprends pas, je
  // laisse donc en attendant)

  protected TextLayout
      textLayout; // the TextLayout that renders the text string of this TextEditable
  // [inherited] shape; But here it's the frame box !!! (not textLayout !)
  protected AffineTransform text2ModelTr =
      new AffineTransform();; // maps text coordinates to Model coordinates
  protected BufferedImage image; // bitmap (if null, we rely on TextLayout)
  protected boolean areDimensionsComputed; // has the real dimensions been read from the log file ?
  protected int fileDPI =
      300; // Dot Per Inch of the file (for image resizing) [pending] gerer les preferences de ce
           // parametre
  // il faut passer la valeur en DPI en argument a create_bitmap.sh

  /** pattern used for parsing log file */
  private static final Pattern LogFilePattern =
      Pattern.compile("JPICEDT INFO:\\s*([0-9.]*)pt,\\s*([0-9.]*)pt,\\s*([0-9.]*)pt");

  private static final String CR_LF = System.getProperty("line.separator");

  private PicPoint ptBuf = new PicPoint();

  /** construct a new View for the given PicRectangle */
  public TextViewHybrid(PicText te, AttributesViewFactory f) {
    super(te, f);
    areDimensionsComputed = false;
    changedUpdate(null);
  }

  public PicText getElement() {
    return (PicText) element;
  }

  /**
   * Returns the text rotation in radians : subclassers that don't support rotating text may return
   * 0 here. Used by TextLayout only.
   */
  protected double getRotation() {
    //			debug(set.getAttribute(TEXT_ROTATION).toString());
    return Math.toRadians(element.getAttribute(TEXT_ROTATION).doubleValue());
  }

  /**
   * Give notification from the model that a change occured to the text this view is responsible for
   * rendering.
   *
   * <p>
   */
  public void changedUpdate(DrawingEvent.EventType eventType) {
    PicText text = (PicText) element;
    if (textLayout == null) {
      // new *************************** begin (by ss & bp)
      textLayout =
          new TextLayout(
              text.getText(text.getTextMode()).length() == 0
                  ? " "
                  : text.getText(text.getTextMode()),
              // new *************************** end (by ss & bp)
              DefaultViewFactory.textFont, // static field
              new FontRenderContext(null, false, false));
    }
    if (eventType == DrawingEvent.EventType.TEXT_CHANGE) {
      // new *************************** begin (by ss & bp)
      textLayout =
          new TextLayout(
              text.getText(text.getTextMode()).length() == 0
                  ? " "
                  : text.getText(text.getTextMode()),
              // new *************************** end (by ss & bp)
              DefaultViewFactory.textFont,
              new FontRenderContext(null, false, false));

      // first try to create a bitmap
      image =
          null; // aka "reset" image => we might temporarily resort to TextLayout until the image is
                // ready
      areDimensionsComputed = false;
      // reset dimensions to the textlayout dimensions
      text.setDimensions(
          textLayout.getBounds().getWidth(), textLayout.getAscent(), textLayout.getDescent());

      // new *************************** begin (by ss & bp)
      if (wantToComputeLatexDimensions && text.getText(text.getTextMode()).length() > 0) {
        // new *************************** end (by ss & bp)
        // don't produce a bitmap for an empty string (LaTeX might not like it)
        // [pending] this should be made dependent on a preference's option
        new Thread(this).start();
      }
      if (image == null) super.changedUpdate(null); // ie resort to TextLayout (update all)
    } else {
      text.updateFrame();
      super.changedUpdate(eventType);
    }
  }

  // Thread's run method aimed at creating a bitmap asynchronously
  public void run() {
    Drawing drawing = new Drawing();
    PicText rawPicText = new PicText();
    String s = ((PicText) element).getText();
    rawPicText.setText(s);
    drawing.add(
        rawPicText); // bug fix: we must add a CLONE of the PicText, otherwise it loses it former
                     // parent... (then pb with the view )
    drawing.setNotparsedCommands(
        "\\newlength{\\jpicwidth}\\settowidth{\\jpicwidth}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicheight}\\settoheight{\\jpicheight}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicdepth}\\settodepth{\\jpicdepth}{"
            + s
            + "}"
            + CR_LF
            + "\\typeout{JPICEDT INFO: \\the\\jpicwidth, \\the\\jpicheight,  \\the\\jpicdepth }"
            + CR_LF);
    RunExternalCommand.Command commandToRun = RunExternalCommand.Command.BITMAP_CREATION;
    // RunExternalCommand command = new RunExternalCommand(drawing, contentType,commandToRun);
    boolean isWriteTmpTeXfile = true;
    String bitmapExt = "png"; // [pending] preferences
    String cmdLine =
        "{i}/unix/tetex/create_bitmap.sh {p} {f} "
            + bitmapExt
            + " "
            + fileDPI; // [pending] preferences
    ContentType contentType = getContainer().getContentType();
    RunExternalCommand.isGUI = false; // System.out, no dialog box // [pending] debug
    RunExternalCommand command =
        new RunExternalCommand(drawing, contentType, cmdLine, isWriteTmpTeXfile);
    command
        .run(); // synchronous in an async. thread => it's ok (anyway, we must way until the LaTeX
                // process has completed)

    if (wantToComputeLatexDimensions) {
      // load size of text:
      try {
        File logFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + ".log");
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(logFile));
        } catch (FileNotFoundException fnfe) {
          System.out.println("Cannot find log file! " + fnfe.getMessage());
          System.out.println(logFile);
        } catch (IOException ioex) {
          System.out.println("Log file IO exception");
          ioex.printStackTrace();
        } // utile ?
        System.out.println("Log file created! file=" + logFile);
        getDimensionsFromLogFile(reader, (PicText) element);
        syncStringLocation(); // update dimensions
        syncBounds();
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that dimensions are available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    if (wantToGetBitMap) {
      // load image:
      try {
        File bitmapFile =
            new File(command.getTmpPath(), command.getTmpFilePrefix() + "." + bitmapExt);
        this.image = ImageIO.read(bitmapFile);
        System.out.println(
            "Bitmap created! file="
                + bitmapFile
                + ", width="
                + image.getWidth()
                + "pixels, height="
                + image.getHeight()
                + "pixels");
        if (image == null) return;
        syncStringLocation(); // sets strx, stry, and dimensions of text
        syncBounds();
        // update the AffineTransform that will be applied to the bitmap before displaying on screen
        PicText te = (PicText) element;
        text2ModelTr.setToIdentity(); // reset
        PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
        text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR !
        text2ModelTr.translate(te.getLeftX(), te.getTopY());
        text2ModelTr.scale(
            te.getWidth() / image.getWidth(),
            -(te.getHeight() + te.getDepth()) / image.getHeight());
        // [pending]  should do something special to avoid dividing by 0 or setting a rescaling
        // factor to 0 [non invertible matrix] (java will throw an exception)
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that bitmap is available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * update strx stry = location of TextLayout's bottom-Left corner with respect to PicText's
   * anchor-point
   */
  protected void syncStringLocation() {
    PicText te = (PicText) element;
    PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
    if (image == null) {
      if (!areDimensionsComputed) {
        te.setDimensions(
            textLayout.getBounds().getWidth(), textLayout.getAscent(), textLayout.getDescent());
      }
      strx = te.getLeftX() - anchor.x;
      stry = te.getBaseLineY() - anchor.y;
    } else { // image not null
      strx = te.getLeftX() - anchor.x;
      stry = te.getBottomY() - anchor.y;
    }
  }

  /**
   * Synchronize the textLayout and the shape (=frame box, by calling syncFrame) with the model When
   * <code>TextLayout</code> is used, this delegates to <code>getRotation()</code> where computing
   * rotation angle is concerned, and updates the AffineTransform returned by <code>
   * getTextToModelTransform()</code>.
   */
  protected void syncShape() {
    PicText te = (PicText) element;

    //			textLayout = new TextLayout(te.getText().length()==0 ? " " : te.getText(),
    //			    textFont,
    //			    new FontRenderContext(null,false,false));

    text2ModelTr.setToIdentity(); // reset
    PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
    text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR !
    // the reference point of an image is the top-left one, but the refpoint of a text layout is on
    // the baseline
    if (image != null) {
      text2ModelTr.translate(te.getLeftX(), te.getTopY());
      if (te.getWidth() != 0
          && image.getWidth() != 0
          && (te.getDepth() + te.getHeight()) != 0
          && image.getHeight() != 0)
        text2ModelTr.scale(
            te.getWidth() / image.getWidth(),
            -(te.getHeight() + te.getDepth()) / image.getHeight());
    } else {
      // Hack ? Just cheating a little bit ? Ou juste ruse ?
      // we want here to use the dimensions of the textLayout instead of latex dimensions if
      // areDimensionsComputed
      // sinon on va aligner le textlayout en fonction des parametres latex, et l'Utilisateur (qui
      // est bien bete) ne va rien comprendre.
      double latexH = 0;
      double latexD = 0;
      double latexW = 0;
      if (areDimensionsComputed) { // store latex dimensions, and setDimensions to textLayout ones
        latexH = te.getHeight();
        latexD = te.getDepth();
        latexW = te.getWidth();
        te.setDimensions(
            textLayout.getBounds().getWidth(), textLayout.getAscent(), textLayout.getDescent());
      }
      text2ModelTr.translate(te.getLeftX(), te.getBaseLineY());
      if (areDimensionsComputed) { // restore latex dimensions
        te.setDimensions(latexW, latexH, latexD);
      }
      // Autre possibilite= comprimer le texte pour qu'il rentre dans la boite (evite le hack
      // ci-dessus):
      // text2ModelTr.scale(te.getWidth()/textLayout.getWidth(),-(te.getHeight()+te.getDepth())/textLayout.getHeight());
      text2ModelTr.scale(1.0, -1.0);
    }
    syncFrame();
  }

  /**
   * synchronize frame shape and location (TextLayout only) ; this is called by syncShape(), so that
   * subclasser might override easily when only rectangular shapes are availables.
   */
  protected void syncFrame() {
    PicText te = (PicText) element;
    if (!te.isFramed()) {
      return;
    }
    AffineTransform tr =
        new AffineTransform(); // maps Image coordinates to Model coordinates (see paint)
    tr.setToIdentity(); // reset
    PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
    tr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR !
    shape = tr.createTransformedShape(te.getShapeOfFrame());
  }

  protected void getDimensionsFromLogFile(BufferedReader reader, PicText text) {
    if (reader == null) {
      return;
    }
    String line = ""; // il rale si j'initialise pas ...
    boolean finished = false;
    while (!finished) {
      try {
        line = reader.readLine();
      } catch (IOException ioex) {
        ioex.printStackTrace();
        return;
      }
      if (line == null) {
        System.out.println("Size of text not found in log file...");
        return;
      }

      System.out.println(line);
      Matcher matcher = LogFilePattern.matcher(line);

      if (line != null && matcher.find()) {
        System.out.println("FOUND :" + line);
        finished = true;
        try {
          text.setDimensions(
              0.3515 * Double.parseDouble(matcher.group(1)), // height, pt->mm (1pt=0.3515 mm)
              0.3515 * Double.parseDouble(matcher.group(2)), // width
              0.3515 * Double.parseDouble(matcher.group(3))); // depth
          areDimensionsComputed = true;
        } catch (NumberFormatException e) {
          System.out.println("Logfile number format problem: $line" + e.getMessage());
        } catch (IndexOutOfBoundsException e) {
          System.out.println("Logfile regexp problem: $line" + e.getMessage());
        }
      }
    }
    return;
  }

  /** Synchronizes bounding box with the model ; */
  protected void syncBounds() {
    PicText te = (PicText) element;
    // [pending] Il faut tenir compte de la rotation !

    Rectangle2D latexBB =
        null; // BB relative to latex dimensions (including rotation) (without frame)
    Rectangle2D textLayoutBB =
        null; // BB relative to textLayout dimensions (including rotation) (without frame)
    Rectangle2D textBB = null; // BB of the text (including rotation), without frame

    if (areDimensionsComputed) { // compute latexBB
      Rectangle2D nonRotated =
          new Rectangle2D.Double(
              te.getLeftX(), te.getBottomY(), te.getWidth(), te.getHeight() + te.getDepth());
      AffineTransform tr =
          new AffineTransform(); // maps Image coordinates to Model coordinates (see paint)
      tr.setToIdentity(); // reset
      PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
      tr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR !
      latexBB = tr.createTransformedShape(nonRotated).getBounds2D();
    }

    if (image == null) { // compute textLayoutBB
      Rectangle2D nonRotated = textLayout.getBounds();
      textLayoutBB = text2ModelTr.createTransformedShape(nonRotated).getBounds2D();
    }

    // use textLayoutBB or latexBB or their union
    if (image != null) textBB = latexBB;
    else {
      if (!areDimensionsComputed) textBB = textLayoutBB;
      else {
        textBB = latexBB.createUnion(textLayoutBB);
      }
    }

    // union with frame BB
    if (te.isFramed()) {
      super.syncBounds(); // update bounds of the frame if necessary
      Rectangle2D.union(super.bounds, textBB, this.bounds);
    } else this.bounds = textBB;
  }

  /**
   * Render the View to the given graphic context. This implementation render the interior first,
   * then the outline.
   */
  public void paint(Graphics2D g, Rectangle2D a) {
    if (!a.intersects(getBounds())) return;
    if (image != null) { // paint bitmap
      g.drawImage(image, text2ModelTr, null);
      // debug:
      g.setPaint(Color.red);
      g.draw(this.bounds);
      super.paint(g, a); // possibly paint framebox if non-null
    } else { // paint textlayout
      super.paint(g, a); // possibly paint framebox if non-null

      AffineTransform oldAT = g.getTransform();
      // paint text in black
      g.setPaint(Color.black);
      // from now on, we work in Y-direct (<0) coordinates to avoid inextricable problems with font
      // being mirrored...
      g.transform(text2ModelTr); // also include rotation
      textLayout.draw(g, 0.0f, 0.0f);
      // [pending] ajouter un cadre si areDimensionsComputed (wysiwyg du pauvre)
      // get back to previous transform
      g.setTransform(oldAT);
      if (DEBUG) {
        g.setPaint(Color.red);
        g.draw(bounds);
      }
    }
  }

  /**
   * This implementation calls <code>super.hitTest</code> and returns the result if non-null (this
   * should be a HitInfo.Point), then returns a HitInfo.Interior if the mouse-click occured inside
   * the text bound (as defined by text layout)
   *
   * @return a HitInfo corresponding to the given mouse-event
   */
  public HitInfo hitTest(PEMouseEvent e) {

    // from Bitmap:
    if (image != null) {
      if (getBounds().contains(e.getPicPoint())) {
        return new HitInfo.Interior((PicText) element, e);
      }
      return null;
    }

    // from TextLayout:
    if (!getBounds().contains(e.getPicPoint())) return null;

    PicText te = (PicText) element;
    // recompute textlayout b-box, but store it in a temporary field !
    Rectangle2D tb = textLayout.getBounds();
    Shape text_bounds = text2ModelTr.createTransformedShape(tb);
    if (text_bounds.contains(e.getPicPoint())) {
      // [SR:pending] for the hitInfo to be reliable, getPicPoint() should first be transformed by
      //              inverse text2ModelTr ! (especially when rotationAngle != 0)
      TextHitInfo thi =
          textLayout.hitTestChar(
              (float) (e.getPicPoint().x - strx),
              (float) (e.getPicPoint().y - stry)); // guaranteed to return a non-null thi
      return new HitInfo.Text((PicText) element, thi, e);
    }
    // test hit on textlayout's bounding rectangle :
    // else if (bounds.contains(e.getPicPoint())) return new HitInfo.Interior(element,e);
    return null;
  }

  /**
   * [SR:pending] make this view implement aka TextEditableView interface (or something like it),
   * where TextEditableView is a subinterface of View with text-editing specific capabilities.
   *
   * <p>Returns the TextLayout which is responsible for painting the textual content of this element
   */
  public TextLayout getTextLayout() {
    return textLayout;
  }

  /**
   * Return an affine transform which translat b/w the TextLayout coordinate system and the
   * jpicedt.graphic.model coordinate system. [SR:pending] refactor method name to something more
   * explanatory
   */
  public AffineTransform getTextToModelTransform() {
    return text2ModelTr;
  }
} // TextView
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
示例#25
0
public class GameCharacter {
  // Position and Size
  public double X = 0, Y = 0;
  public double W = 0, H = 0;
  // Frames
  public int FX = 0, FY = 0;

  // Where to find character sprites
  String DIRECT = System.getProperty("user.dir") + "\\Graphics\\Character\\";
  String DIRECT2 = System.getProperty("user.dir") + "\\Graphics\\Effects\\";

  // Max number of frames
  int SIZE = 0;

  // Used for delay in framechange()
  int COUNTER = 0;

  // Sprite Type
  int TYPE = 1;

  // Sprite
  BufferedImage imgCHARAC, imgBLOOD, imgQStart, imgQEnd;

  // Collision maps
  Vector<GridMap> MAP = new Vector<GridMap>();

  // Collision objects
  Vector<GameObject> OBJECTS = new Vector<GameObject>();

  // Collision characters
  Vector<GameCharacter> CHARACTERS = new Vector<GameCharacter>();

  // Collision characters
  Vector<Building> BUILD = new Vector<Building>();

  // Spells
  Vector<MagicAttack[]> SPELL_LIST = new Vector<MagicAttack[]>();

  Vector<Quest> QUEST_LIST = new Vector<Quest>();

  // Size
  double GROWTHFACTOR = 1;

  // Create character inventory
  ItemList INVENTORY = new ItemList();

  // Character class
  String CLASS = "", Cl = "";

  // Basic stats
  double MAX_HEALTH = 100, MAX_MANA = 100;
  int HEALTH = (int) MAX_HEALTH, MANA = (int) MAX_MANA, GOLD = 0;

  // Movement
  int REGEN_COUNTER = 0, SPEED = 1;

  // Used for magic attacks
  int MAGIC_COUNTER = 0;

  // Possible AIs
  NPCAI NAI;
  EnemyAI EAI;

  // Restrictions
  boolean ISDEAD = false, COLL_LISTENER = false, CANMOVE = true;

  // List of available magic attacks
  MagicAttack[] FIREBALL = new MagicAttack[11],
      SHOCK = new MagicAttack[11],
      DARKNESS = new MagicAttack[11],
      LIFE_DRAIN = new MagicAttack[11];

  // Character Stats
  Stats STATS = new Stats(this);

  // Weapons and armor
  MeeleAttack MEELE_WEAPON = new MeeleAttack(0, 0, "Sword_1.png", this);
  Image SHIELD = null;

  // Death sound
  AudioEffects audDEATH = new AudioEffects(false);

  // Progress bar used for basic tasks
  ProgressBar BASIC_PROCESS, BASIC_EFFECTS;
  int SPAWN_X = -1, SPAWN_Y = -1;

  /**
   * Constructor to create a character
   *
   * @param x X Position
   * @param y Y Position
   * @param w Width of Image
   * @param h Height of Image
   * @param FileN Name of image file
   * @param S Max number of frames
   */
  public GameCharacter(
      double x, double y, double w, double h, String FileN, int S, int Ty, String c) {
    // Set position and size
    X = x;
    Y = y;
    W = w;
    H = h;

    BASIC_PROCESS = new ProgressBar(new Font("Arial", 36, 36), this);
    BASIC_EFFECTS = new ProgressBar(new Font("Arial", 36, 36), this);
    // Add magic attacks
    // Fireball
    for (int i = 0; i < FIREBALL.length; i++) {
      FIREBALL[i] = new MagicAttack(-500, -500, 39, 41, "Fireball.png", 3, 1, 2, "Fireball");
      FIREBALL[i].STATS.setStats(new String[] {"Damage=10", "Points=10"});
      FIREBALL[i].CASTER = this;
    }
    // Shock
    for (int i = 0; i < SHOCK.length; i++) {
      SHOCK[i] = new MagicAttack(-500, -500, 39, 41, "Shock.png", 2, 1, 0, "Shock");
      SHOCK[i].STATS.setStats(new String[] {"Damage=20", "Points=15"});
      SHOCK[i].CASTER = this;
    }
    // Darkness
    for (int i = 0; i < DARKNESS.length; i++) {
      DARKNESS[i] = new MagicAttack(-500, -500, 165, 164, "Darkness.png", 3, 1, 2, "Darkness");
      DARKNESS[i].STATS.setStats(new String[] {"Damage=100", "Points=50"});
      DARKNESS[i].CASTER = this;
    }
    // Life Drain
    for (int i = 0; i < LIFE_DRAIN.length; i++) {
      LIFE_DRAIN[i] = new MagicAttack(-500, -500, 32, 32, "Life Drain.png", 7, 1, 0, "Life Drain");
      LIFE_DRAIN[i].STATS.setStats(new String[] {"Damage=50", "Points=25"});
      LIFE_DRAIN[i].CASTER = this;
    }
    // Get Image
    try {

      if (isJar()) {
        // Character
        imgCHARAC = getImage("/Graphics/Character/", FileN);

        // Blood
        int BloodType = (int) Math.round(Math.random() * 3) + 1;
        imgBLOOD = getImage("/Graphics/Effects/", "Dead" + BloodType + ".png");

        // Quest
        imgQStart = getImage("/Graphics/Effects/", "Quest_Start.png");
        imgQEnd = getImage("/Graphics/Effects/", "Quest_Complete.png");

      } else {
        // Character
        imgCHARAC = ImageIO.read(Paths.get(DIRECT + FileN).toFile());

        // Blood
        int BloodType = (int) Math.round(Math.random() * 3) + 1;
        imgBLOOD = ImageIO.read(Paths.get(DIRECT2 + "Dead" + BloodType + ".png").toFile());

        // Quest
        imgQStart = ImageIO.read(Paths.get(DIRECT2 + "Quest_Start.png").toFile());
        imgQEnd = ImageIO.read(Paths.get(DIRECT2 + "Quest_Complete.png").toFile());
      }

    } catch (Exception e) {
    }

    // Max number of frames
    SIZE = S;

    // Sprite type
    TYPE = Ty;

    // Assign class
    CLASS = c;
    Cl = c;

    // Add items and attacks according to class
    if (CLASS.equals("Player")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Rusted Dagger",
          20,
          1,
          "Dagger_4.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem(
          "Wooden Staff",
          20,
          1,
          "Staff_1.png",
          "Meele",
          new String[] {"Damage=5", "Attack Speed=1"});

      // Equip items
      INVENTORY.ItemEffect(1, this);
      // MEELE_WEAPON=null;
      // Assign Magic
      SPELL_LIST.add(FIREBALL);

      // Inventory type
      INVENTORY.Type = "Player";
    } else if (CLASS.equals("Citizen")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Ai
      NAI = new NPCAI(this);

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 15 + 5);

      INVENTORY.Type = "Friendly";
    } else if (CLASS.equals("Blacksmith")) {

      // Add items
      INVENTORY.addItem(
          "Silver Dagger",
          250,
          1,
          "Dagger_3.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem(
          "Steel Dagger",
          450,
          1,
          "Dagger_5.png",
          "Meele",
          new String[] {"Damage=35", "Attack Speed=1"});
      // INVENTORY.addItem("Assassin blade", 750,1, "Dagger_6.png","Meele",new
      // String[]{"Damage=45","Attack Speed=1"});
      // INVENTORY.addItem("Serpent Dagger", 5000,1, "Dagger_2.png","Meele",new
      // String[]{"Damage=50","Attack Speed=1"});
      // INVENTORY.addItem("Dagger of Time", 5050,1, "Dagger_1.png","Meele",new
      // String[]{"Damage=75","Attack Speed=1"});

      INVENTORY.addItem(
          "Steel Sword",
          450,
          1,
          "Sword_1.png",
          "Meele",
          new String[] {"Damage=30", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Iron Sword",
          50,
          1,
          "Sword_2.png",
          "Meele",
          new String[] {"Damage=15", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Silver Sword",
          100,
          1,
          "Sword_5.png",
          "Meele",
          new String[] {"Damage=20", "Attack Speed=0.5"});
      // INVENTORY.addItem("Iron Scimitar", 150,1, "Sword_7.png","Meele",new
      // String[]{"Damage=15","Attack Speed=0.75"});
      // INVENTORY.addItem("Steel Scimitar", 500,1, "Sword_4.png","Meele",new
      // String[]{"Damage=50","Attack Speed=0.75"});
      // INVENTORY.addItem("Steel Katana", 450,1, "Sword_6.png","Meele",new
      // String[]{"Damage=40","Attack Speed=0.95"});
      // INVENTORY.addItem("Butcher's Sword", 5000,1, "Sword_3.png","Meele",new
      // String[]{"Damage=100","Attack Speed=0.55"});
      // INVENTORY.addItem("Blood Thirster", 6000,1, "Sword_8.png","Meele",new
      // String[]{"Damage=200","Attack Speed=0.75"});

      INVENTORY.addItem(
          "Iron Hammer",
          150,
          1,
          "Hammer_1.png",
          "Meele",
          new String[] {"Damage=40", "Attack Speed=0.15"});
      // INVENTORY.addItem("Steel Hammer", 450,1, "Hammer_0.png","Meele",new
      // String[]{"Damage=60","Attack Speed=0.15"});
      // INVENTORY.addItem("Iron Mace", 50,1, "Mace_1.png","Meele",new String[]{"Damage=15","Attack
      // Speed=0.5"});

      INVENTORY.addItem("Steel Helmet", 250, 1, "Head_1.png", "H_armor", new String[] {"Armor=20"});
      INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"});
      // INVENTORY.addItem("Iron Horn Helmet", 350,1, "Head_6.png","H_armor",new
      // String[]{"Armor=50","Magic Resist=0"});
      // INVENTORY.addItem("Steel Horn Helmet", 500,1, "Head_7.png","H_armor",new
      // String[]{"Armor=80","Magic Resist=0"});
      // INVENTORY.addItem("Skysteel Helmet", 4000,1, "Head_4.png","H_armor",new
      // String[]{"Armor=60","Magic Resist=25"});

      INVENTORY.addItem(
          "Iron Cuirass", 250, 1, "Chest_4.png", "C_armor", new String[] {"Armor=20"});
      INVENTORY.addItem(
          "Steel Cuirass", 350, 1, "Chest_1.png", "C_armor", new String[] {"Armor=30"});
      // INVENTORY.addItem("Scale Cuirass", 550,1, "Chest_3.png","C_armor",new
      // String[]{"Armor=50"});
      // INVENTORY.addItem("Dark metal Cuirass", 750,1, "Chest_6.png","C_armor",new
      // String[]{"Armor=70"});
      // INVENTORY.addItem("Master Cuirass", 3050,1, "Chest_5.png","C_armor",new
      // String[]{"Armor=80","Magic Resist=25"});
      // INVENTORY.addItem("Legendary Cuirass", 3050,1, "Chest_2.png","C_armor",new
      // String[]{"Armor=100","Magic Resist=100"});

      INVENTORY.addItem(
          "Wooden Shield",
          50,
          1,
          "Shield_1.png",
          "Shield",
          new String[] {"Armor=5", "Magic Resist=0"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";

      // Set Stats
      STATS.setStats(new String[] {"Level = 5 "});
      MAX_HEALTH = 200;
      HEALTH = (int) MAX_HEALTH;
    } else if (CLASS.equals("Alchemist")) {
      // Add Items
      INVENTORY.addItem(
          "Health Potion", 25, 50, "Health Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Mana Potion", 20, 50, "Mana Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Speed Potion", 10, 50, "Speed Pot.png", "Potion", new String[] {"Points=5"});
      // INVENTORY.addItem("Invisib Potion", 50, 10, "Invisibility Pot.png","Potion",new
      // String[]{"Points=5"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";
    } else if (CLASS.equals("Inn Keeper")) {
      // Add Items
      INVENTORY.addItem("Roasted Fish", 15, 10, "Fish.png", "Food", new String[] {"Points=5"});
      INVENTORY.addItem("Apple", 15, 10, "Apple.png", "Food", new String[] {"Points=2"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";
    } else if (CLASS.equals("Mage")) {

      INVENTORY.addItem(
          "Leather Cap",
          250,
          1,
          "Head_8.png",
          "H_armor",
          new String[] {"Armor=5", "Magic Resist=25"});
      INVENTORY.addItem(
          "Dark Leather Cap",
          300,
          1,
          "Head_9.png",
          "H_armor",
          new String[] {"Armor=5", "Magic Resist=50"});
      // INVENTORY.addItem("Jesters Cap", 500,1, "Head_5.png","H_armor",new
      // String[]{"Armor=10","Magic Resist=90"});
      // INVENTORY.addItem("Skull Helmet", 5000,1, "Head_3.png","H_armor",new
      // String[]{"Armor=100","Magic Resist=100"});
      INVENTORY.addItem(
          "Shock Spell Stone",
          250,
          1,
          "Stone_1.png",
          "SpellStoner",
          new String[] {"Damage=" + SHOCK[0].STATS.DAMAGE});
      // INVENTORY.addItem("Darkness Spell Stone", 500,1, "Stone_1.png","SpellStoner",new
      // String[]{"Damage="+DARKNESS[0].STATS.DAMAGE});
      INVENTORY.addItem(
          "Life Drain Spell Stone",
          300,
          1,
          "Stone_1.png",
          "SpellStoner",
          new String[] {"Damage=" + LIFE_DRAIN[0].STATS.DAMAGE});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";

    } else if (CLASS.equals("Skeleton")) {

      // Add items
      INVENTORY.addItem(
          "Bone Club", 5, 1, "Mace_2.png", "Meele", new String[] {"Damage=5", "Attack Speed=1"});

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 10 + 2);

      // Use Item
      INVENTORY.ItemEffect(0, this);

      // Add AI
      EAI = new EnemyAI(this);
    } else if (CLASS.equals("Skeleton Chieftan")) {

      // Add Item
      INVENTORY.addItem(
          "Iron Sword",
          50,
          1,
          "Sword_2.png",
          "Meele",
          new String[] {"Damage=15", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 50 + 25);

      // Use Item
      INVENTORY.ItemEffect(0, this);

      // Assign Stats
      STATS.LEVEL = 3;
      HEALTH = 250;
      MAX_HEALTH = 250;

      // Opify
      Opify(1 / 1.25);

      // Add AI
      EAI = new EnemyAI(this);
    } else if (CLASS.equals("Shaman")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Ai
      NAI = new NPCAI(this);

    } else if (CLASS.equals("Dark Elf")) {

      // Add items
      INVENTORY.addItem(
          "Rusted Dagger",
          20,
          1,
          "Dagger_4.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"});

      // Assign Stats
      STATS.LEVEL = 2;
      HEALTH = 150;
      MAX_HEALTH = 150;

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 15 + 2);

      // Use Item
      INVENTORY.ItemEffect(0, this);
      INVENTORY.ItemEffect(1, this);

      // Add Ai
      EAI = new EnemyAI(this);

    } else if (CLASS.equals("Prisoner")) {
      INVENTORY.addItem("Key", 0, 1, "Key.png", "Key", new String[] {});
      // NAI= new NPCAI(this);
    }
  }

  /**
   * do damage to character
   *
   * @param Dmg Amount of Damage
   */
  public void Damage(int Dmg, int Type) {
    // If character is already dead then dont do damage
    if (ISDEAD) return;

    // Do damage
    if (Type == 1) {
      // DAMAGE FROM PHYSICAL ATTACK
      if (STATS.ARMOR > Dmg) return;
      HEALTH = HEALTH - Dmg + STATS.ARMOR;
    } else if (Type == 2) {
      // DAMAGE FROM MAGIC ATTACK
      if (STATS.MAGIC_RESIST > Dmg) return;
      HEALTH = HEALTH - Dmg + STATS.MAGIC_RESIST;
    }
    // If an Npc then run and hide
    if (NAI != null) {
      NAI.State = "alarmed";
    }

    // Death condition
    if (HEALTH <= 0) {
      // If player is dead
      if (this.CLASS.equals("Player")) {

        HEALTH = 0;

        // Quit game
        JOptionPane.showMessageDialog(null, "You are dead");
        X = 100;
        Y = 100;
        Opify(50);
        HEALTH = (int) MAX_HEALTH;

      } else {
        // If other character
        // set Death stats
        ISDEAD = true;
        HEALTH = 0;
        // display death
        CLASS = Cl + " (Dead)";

        // Rot effect
        for (int i = 0; i < imgCHARAC.getWidth(); i++) {
          for (int j = 0; j < imgCHARAC.getHeight(); j++) {
            imgCHARAC.setRGB(i, j, imgCHARAC.getRGB(i, j) * (int) Math.pow(3, 3));
          }
        }

        // Make inventory open to looting
        INVENTORY.OPEN_INVEN = true;
      }
    }
  }

  /** Prototype give player a leveled up look */
  public void Opify(double Fac) {

    for (int i = 0; i < imgCHARAC.getWidth(); i++) {
      for (int j = 0; j < imgCHARAC.getHeight(); j++) {
        if (imgCHARAC.getRGB(i, j) != imgCHARAC.getRGB(2, 2)) {
          imgCHARAC.setRGB(i, j, (int) Math.round(imgCHARAC.getRGB(i, j) * Fac));
        }
      }
    }
  }

  /**
   * Regenerate the players mana
   *
   * @param Mn amount to regen
   */
  public void ManaRegen(int Mn) {
    // Counter
    REGEN_COUNTER++;

    if (REGEN_COUNTER > 30) {
      // Regen
      if (MANA < MAX_MANA) MANA += Mn;
      REGEN_COUNTER = 0;
    }
  }

  /**
   * Move the character
   *
   * @param dx x displacement
   * @param dy y displacement
   */
  public void Move(int dx, int dy) {
    if (!CANMOVE) return;
    // Move
    X += dx * SPEED;
    Y += dy * SPEED;

    // Set FY depending on the sprite Type
    switch (TYPE) {
      case 1:
        if (dx > 0) {
          FY = Type1.RIGHT.ordinal();
        } else if (dx < 0) {
          FY = Type1.LEFT.ordinal();
        } else if (dy > 0) {
          FY = Type1.DOWN.ordinal();
        } else if (dy < 0) {
          FY = Type1.UP.ordinal();
        }

        break;
      case 2:
        if (dx > 0) {
          FY = Type2.RIGHT.ordinal();
        } else if (dx < 0) {
          FY = Type2.LEFT.ordinal();
        } else if (dy > 0) {
          FY = Type2.DOWN.ordinal();
        } else if (dy < 0) {
          FY = Type2.UP.ordinal();
        }
      case 3:
        if (dx > 0) {
          FY = Type3.RIGHT.ordinal();
        } else if (dx < 0) {
          FY = Type3.LEFT.ordinal();
        } else if (dy > 0) {
          FY = Type3.DOWN.ordinal();
        } else if (dy < 0) {
          FY = Type3.UP.ordinal();
        }

        break;
    }

    // X Frame Change
    FrameChange(SIZE, 4, 1);
  }

  /**
   * add a Map collision object
   *
   * @param M GridMap
   */
  public void addColisionObject(GridMap M) {
    MAP.add(M);
  }
  /**
   * add a Object collision object
   *
   * @param O Object
   */
  public void addColisionObject(GameObject O) {
    OBJECTS.add(O);
  }
  /**
   * add Character collision object
   *
   * @param C Character
   */
  public void addColisionObject(GameCharacter C) {
    CHARACTERS.add(C);
  }
  /**
   * add Building collision object
   *
   * @param B Building
   */
  public void addColisionObject(Building B) {
    BUILD.add(B);
  }

  /**
   * add an array of Building collision object
   *
   * @param M Array of GridMap
   */
  public void addColisionObject(Building[] B) {
    for (int i = 0; i < B.length; i++) {
      BUILD.add(B[i]);
    }
  }

  /**
   * add a Map collision object
   *
   * @param M Array of GridMap
   */
  public void addColisionObject(GridMap[] M) {
    for (int i = 0; i < M.length; i++) {
      MAP.add(M[i]);
    }
  }

  /**
   * add a Object collision object
   *
   * @param O Array of Objects
   */
  public void addColisionObject(GameObject[] O) {
    for (int i = 0; i < O.length; i++) {
      OBJECTS.add(O[i]);
    }
  }

  /** Remove all the collision objects from the player */
  public void removeCollisionObject(GameObject[] obj) {
    for (int i = 0; i < obj.length; i++) {
      OBJECTS.remove(obj[i]);
      // OBJECTS.add(obj[i]);
    }
  }

  public void removeCollisionObject(GameObject obj) {
    //	for(int i=0;i<obj.length;i++){
    OBJECTS.remove(obj);
    // OBJECTS.add(obj[i]);
    // }
  }

  public void removeAllColisionObjects() {
    // Collision maps
    MAP = new Vector<GridMap>();

    // Collision objects
    OBJECTS = new Vector<GameObject>();

    // Collision characters
    CHARACTERS = new Vector<GameCharacter>();

    // Collision characters
    BUILD = new Vector<Building>();
  }

  /**
   * add Character collision object
   *
   * @param C Array of Characters
   */
  public void addColisionObject(GameCharacter[] C) {
    for (int i = 0; i < C.length; i++) {
      CHARACTERS.add(C[i]);
    }
  }
  /**
   * Allows the character to walk over various surfaces
   *
   * @param F Selected fill number
   * @return whether or not the character can walk on this surface
   */
  public boolean isValidSurface(int F) {
    // List of valid surfaces
    int[] fill = {0, 98, 106, 107, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 147, 178};

    for (int i = 0; i < fill.length; i++) {
      if (fill[i] == F) {
        // If valid
        return true;
      }
    }

    // If not
    return false;
  }

  /**
   * Wall Collision
   *
   * @param x X Position
   * @param y Y Position
   * @param M Map
   * @return if character is about to collide with the wall
   */
  public boolean WallCollision(double x, double y, GridMap M) {
    // If invalid coordinate
    try {
      if (M.getBlockNum(x, y) == -1) {
        // Collision check
        if (isValidSurface(M.Fill[M.getBlockNum(x + 3, y + 3)])) {
          return false;
        }
        return true;
      }
      // Collision check
      if (isValidSurface(M.Fill[M.getBlockNum(x, y)])) {
        return false;
      }
    } catch (Exception e) {
      return WallCollision(x + M.Size / 2, y + M.Size / 2, M);
    }
    return true;
  }

  /**
   * Object Collision
   *
   * @param x X Position
   * @param y Y Position
   * @param Obj Game Object
   * @return if character is about to collide with an object
   */
  public boolean ObjectCollision(double x, double y, GameObject Obj) {
    if ((x > Obj.X) && (x < Obj.X + Obj.W * Obj.GROWTHFACTOR)) {
      if ((y > Obj.Y) && (y < Obj.Y + Obj.H * Obj.GROWTHFACTOR)) {
        return true;
      }
    }

    return false;
  }

  /**
   * Character Collision
   *
   * @param x X Position
   * @param y Y Position
   * @param Charac GameCharacter
   * @return if character is about to collide with a character
   */
  public boolean CharacterCollision(double x, double y, GameCharacter Charac) {
    if ((x > Charac.X) && (x < Charac.X + Charac.W * Charac.GROWTHFACTOR)) {
      if ((y > Charac.Y) && (y < Charac.Y + Charac.H * Charac.GROWTHFACTOR)) {

        return true;
      }
    }

    return false;
  }

  /**
   * Building Collision
   *
   * @param x X Position
   * @param y Y Position
   * @param Charac Game Building
   * @return if character is about to collide with a structure
   */
  public boolean BuildingCollision(double x, double y, Building Charac) {
    if ((x > Charac.X) && (x < Charac.X + Charac.W * Charac.GROWTHFACTOR)) {
      if ((y > Charac.Y) && (y < Charac.Y + Charac.H * Charac.GROWTHFACTOR)) {
        return true;
      }
    }

    return false;
  }

  /**
   * Check character collision with all kinds of objects
   *
   * @param x X Coordinate
   * @param y Y Coordinate
   * @return if Character is about to collide with something
   */
  public boolean Collision(double x, double y) {
    boolean blnCol = false;
    // Wall Collision
    for (int i = 0; i < MAP.size(); i++) {
      blnCol = blnCol || WallCollision(x, y, MAP.elementAt(i));
    }
    // Game Object Collision
    for (int i = 0; i < OBJECTS.size(); i++) {
      blnCol = blnCol || ObjectCollision(x, y, OBJECTS.elementAt(i));
    }
    // Game Character collision
    for (int i = 0; i < CHARACTERS.size(); i++) {
      blnCol = blnCol || CharacterCollision(x, y, CHARACTERS.elementAt(i));
    }
    // Game Building Collision
    for (int i = 0; i < BUILD.size(); i++) {
      blnCol = blnCol || BuildingCollision(x, y, BUILD.elementAt(i));
    }

    return blnCol;
  }

  /**
   * Draw character in minimap
   *
   * @param g Graphics
   * @param Dx X Displacement
   * @param Dy Y Displacement
   */
  public void MapDraw(Graphics g, int Dx, int Dy, double Scale, Color col) {
    // Color
    g.setColor(col.darker().darker().darker());
    g.drawOval((int) (X * Scale + Dx), (int) (Y * Scale + Dy), 7, 7);
    g.setColor(col);
    g.fillOval((int) (X * Scale + Dx), (int) (Y * Scale + Dy), 7, 7);
  }
  /**
   * Draw character in game window
   *
   * @param g Graphics
   * @param Dx X Displacement
   * @param Dy Y Displacement
   * @param G Growth factor
   */
  public void Draw(Graphics g, int Dx, int Dy, double G) {
    // Draw blood
    if (ISDEAD) {
      g.drawImage(
          imgBLOOD,
          (int) (X + Dx - 25),
          (int) (Y + Dy - 15),
          (int) (W * GROWTHFACTOR + 35),
          (int) (H * GROWTHFACTOR + 35),
          null);
    }

    // Quest Givers
    if (CLASS != "Player") {
      for (int i = 0; i < QUEST_LIST.size(); i++) {
        if (QUEST_LIST.elementAt(i).STATUS == 0) {
          g.drawImage(imgQStart, (int) (X + Dx + 5), (int) (Y + Dy - 30), (int) W, 35, null);
        } else if (QUEST_LIST.elementAt(i).STATUS == 2) {
          g.drawImage(imgQEnd, (int) (X + Dx), (int) (Y + Dy - 30), (int) W + 5, 35, null);
        }
      }
    }

    // Draw character
    g.drawImage(
        imgCHARAC,
        (int) (X + Dx),
        (int) (Y + Dy),
        (int) (X + Dx + W * G),
        (int) (Y + Dy + H * G),
        (int) (W * FX),
        (int) (H * FY),
        (int) (W * FX + W),
        (int) (H * FY + H),
        null);

    GROWTHFACTOR = G;
  }

  /**
   * Draw Magic Attack
   *
   * @param Magic Array of magic attacks
   * @param g Graphics
   * @param Dx Draw X displacement
   * @param Dy Draw Y displacement
   * @param G Growth Factor
   */
  public void MagicDraw(MagicAttack[] Magic, Graphics g, int Dx, int Dy, double G) {

    for (int i = 0; i < Magic.length; i++) {
      Magic[i].Draw(g, Dx, Dy, G);
    }
  }

  /** If the character is dead don't make the magic attacks collide */
  public void removeMagicCollision() {
    // Fireball
    for (int i = 0; i < FIREBALL.length; i++) {
      FIREBALL[i].removeAllColisionObjects();
    }

    // Shock
    for (int i = 0; i < SHOCK.length; i++) {
      SHOCK[i].removeAllColisionObjects();
    }

    // Darkness
    for (int i = 0; i < DARKNESS.length; i++) {
      DARKNESS[i].removeAllColisionObjects();
    }

    // Life Drain
    for (int i = 0; i < LIFE_DRAIN.length; i++) {
      LIFE_DRAIN[i].removeAllColisionObjects();
    }
  }

  /**
   * Frame Change in X direction
   *
   * @param MAX last frame index
   * @param Delay Delay between frame change
   * @param Dir moves back or forward through frames
   */
  public void FrameChange(int MAX, int Delay, int Dir) {
    COUNTER++;

    if (COUNTER > Delay) {
      // Change Frame
      FX += Dir;

      // Reset when frame number exceeds bounds
      if (FX < 0) {
        FX = MAX;
      }
      if (FX > MAX) {
        FX = 0;
      }

      // Reset
      COUNTER = 0;
    }
  }
  /**
   * Spawn a character on the map
   *
   * @param MiX Minimum X value
   * @param MiY Minimum Y value
   * @param MaX Maximum X value
   * @param MaY Maximum Y value
   */
  public void Spawn(int MiX, int MiY, int MaX, int MaY) {
    double Nx = 0, Ny = 0;

    // Random coordinate
    Nx = Math.random() * MaX + MiX;
    Ny = Math.random() * MaY + MiY;

    // Store block number
    int BNum = MAP.elementAt(0).getBlockNum(Nx + W / 2, Ny + H / 2);

    // if invalid block number
    if (BNum == -1) {
      Spawn(MiX, MiY, MaX, MaY);
    }

    // if invalid surface
    else if (!isValidSurface(MAP.elementAt(0).Fill[BNum])) {
      Spawn(MiX, MiY, MaX, MaY);
    }

    // if colliding with something
    else if (this.Collision(Nx + W / 2, Ny + H / 2)) {
      Spawn(MiX, MiY, MaX, MaY);
    } else {
      X = Nx;
      Y = Ny;
    }
  }
  /**
   * Find the distance between two characters
   *
   * @param Targ Target character
   * @return distance
   */
  public double Dist(GameCharacter Targ) {
    // find x squared and y squared
    double dx =
        Math.pow(((X + W / 2 * GROWTHFACTOR) - (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR)), 2);
    double dy =
        Math.pow(((Y + H / 2 * GROWTHFACTOR) - (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR)), 2);

    // find distance
    return (Math.sqrt(dx + dy));
  }

  /**
   * Find the distance between two characters
   *
   * @param Targ Target character
   * @return distance
   */
  public double Dist(GameObject Targ) {
    // find x squared and y squared
    double dx =
        Math.pow(((X + W / 2 * GROWTHFACTOR) - (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR)), 2);
    double dy =
        Math.pow(((Y + H / 2 * GROWTHFACTOR) - (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR)), 2);
    // find distance
    return (Math.sqrt(dx + dy));
  }
  /**
   * Find the distance between a character and a building
   *
   * @param Targ Target Building
   * @return distance
   */
  public double Dist(Building Targ) {

    // find x squared and y squared
    double dx =
        Math.pow(((X + W / 2 * GROWTHFACTOR) - (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR)), 2);
    double dy =
        Math.pow(((Y + H / 2 * GROWTHFACTOR) - (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR)), 2);

    // find distance
    return (Math.sqrt(dx + dy));
  }

  /**
   * Chase another character
   *
   * @param Targ Target character
   * @param Error alignment error allowed
   */
  public void FollowChar(GameCharacter Targ, int Error) {

    // Find distance
    double dx = (Targ.X + Targ.W / 2 * Targ.GROWTHFACTOR) - (X + W / 2 * GROWTHFACTOR);
    double dy = (Targ.Y + Targ.H / 2 * Targ.GROWTHFACTOR) - (Y + H / 2 * GROWTHFACTOR);

    // Y Movement
    if (dy > Error) {
      // Down
      if (this.Collision(X, Y + H * GROWTHFACTOR)) {
        EAI.STATE = "calm";
      }
      Move(0, SPEED + 1);
    } else if (dy < Error) {
      // Up
      if (this.Collision(X, Y)) {
        EAI.STATE = "calm";
      }
      Move(0, -SPEED - 1);
    }

    // X Movement
    if (dx > Error) {
      // Right
      if (this.Collision(X + W * GROWTHFACTOR, Y)) {
        EAI.STATE = "calm";
      }
      Move(SPEED + 1, 0);
    } else if (dx < -Error) {
      // Left
      if (this.Collision(X, Y)) {
        EAI.STATE = "calm";
      }
      Move(-SPEED - 1, 0);
    }
  }

  /**
   * Set the direction of the character
   *
   * @param Pos String specifying direction
   */
  public void setPos(String Pos) {
    // Set position
    switch (TYPE) {
      case 1:
        switch (Pos) {
          case "Up":
            FY = Type1.UP.ordinal();
            break;
          case "Down":
            FY = Type1.DOWN.ordinal();
            break;
          case "Left":
            FY = Type1.LEFT.ordinal();
            break;
          case "Right":
            FY = Type1.RIGHT.ordinal();
            break;
        }
        break;
      case 2:
        switch (Pos) {
          case "Up":
            FY = Type2.UP.ordinal();
            break;
          case "Down":
            FY = Type2.DOWN.ordinal();
            break;
          case "Left":
            FY = Type2.LEFT.ordinal();
            break;
          case "Right":
            FY = Type2.RIGHT.ordinal();
            break;
        }
        break;
      case 3:
        switch (Pos) {
          case "Up":
            FY = Type3.UP.ordinal();
            break;
          case "Down":
            FY = Type3.DOWN.ordinal();
            break;
          case "Left":
            FY = Type3.LEFT.ordinal();
            break;
          case "Right":
            FY = Type3.RIGHT.ordinal();
            break;
        }
        break;
    }
  }
  /**
   * Sell an item to a shopkeeper
   *
   * @param Targ Target Inventory
   * @param Index Item Index
   */
  public void Sell(ItemList Targ, int Index) {
    // Un-equip item
    if (INVENTORY.ITEM_NAME.elementAt(Index).indexOf("<Eq>") != -1) {
      INVENTORY.ItemEffect(Index, this);
    }

    // Give the target this item
    Targ.addItem(
        this.INVENTORY.ITEM_NAME.elementAt(Index),
        this.INVENTORY.ITEM_PRICE.elementAt(Index),
        1,
        this.INVENTORY.ITEM_IMAGE.elementAt(Index),
        this.INVENTORY.ITEM_TAG.elementAt(Index),
        this.INVENTORY.STATS.elementAt(Index));

    // Get payment from target
    this.GOLD += this.INVENTORY.ITEM_PRICE.elementAt(Index);

    // Remove item from the character inventory
    this.INVENTORY.removeItem(Index, 1);
  }
  /**
   * Buy an item from a shopkeeper
   *
   * @param Targ Target Inventory
   * @param Index Item Index
   */
  public void Buy(ItemList Targ, int Index) {
    // If item is too expensive
    if (Targ.ITEM_PRICE.elementAt(Index) > this.GOLD) {
      JOptionPane.showMessageDialog(null, "Too rich for your blood");
      return;
    }

    // add Item to character inventory
    this.INVENTORY.addItem(
        Targ.ITEM_NAME.elementAt(Index),
        Targ.ITEM_PRICE.elementAt(Index),
        1,
        Targ.ITEM_IMAGE.elementAt(Index),
        Targ.ITEM_TAG.elementAt(Index),
        Targ.STATS.elementAt(Index));

    // remove Gold
    this.GOLD -= Targ.ITEM_PRICE.elementAt(Index);

    // remove item from target inventory
    Targ.removeItem(Index, 1);
  }
  /**
   * Loot item from a dead body
   *
   * @param Targ Target Inventory
   * @param Index Item Index
   */
  public void Take(ItemList Targ, int Index) {
    // Add item to character inventory

    // unequip item
    if (Targ.ITEM_NAME.elementAt(Index).indexOf("<Eq>") != -1) {
      Targ.ItemEffect(Index, this);
    }
    this.INVENTORY.addItem(
        Targ.ITEM_NAME.elementAt(Index),
        Targ.ITEM_PRICE.elementAt(Index),
        1,
        Targ.ITEM_IMAGE.elementAt(Index),
        Targ.ITEM_TAG.elementAt(Index),
        Targ.STATS.elementAt(Index));

    // Remove item from target inven
    Targ.removeItem(Index, 1);
  }

  /**
   * Magic Attack
   *
   * @param Magic Array of magic attacks
   */
  public void MAttack(MagicAttack[] Magic) {
    // If insufficient mana
    if (MANA - Magic[MAGIC_COUNTER].STATS.POINTS < 0) return;
    // Stop
    FIREBALL[MAGIC_COUNTER].ISACTIVE = false;

    switch (TYPE) {
      case 1:
        // set x and y coords depending on the direction the character is facing
        switch (FY) {
          case 0: // Down
            // Set x and y coords
            Magic[MAGIC_COUNTER].X =
                X + W / 2 - Magic[MAGIC_COUNTER].W / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR;
            Magic[MAGIC_COUNTER].Y =
                Y + H - Magic[MAGIC_COUNTER].H / 4 * Magic[MAGIC_COUNTER].GROWTHFACTOR;
            // Set frame 0
            Magic[MAGIC_COUNTER].FX = 0;
            // Movement Speed
            Magic[MAGIC_COUNTER].dX = 0;
            Magic[MAGIC_COUNTER].dY = 20;
            break;

          case 1: // Left
            // Set x and y coords
            Magic[MAGIC_COUNTER].X =
                X - Magic[MAGIC_COUNTER].W / 4 * Magic[MAGIC_COUNTER].GROWTHFACTOR;
            Magic[MAGIC_COUNTER].Y =
                Y + H / 2 - Magic[MAGIC_COUNTER].H / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR;
            // Set frame 0
            Magic[MAGIC_COUNTER].FX = 0;
            // Movement Speed
            Magic[MAGIC_COUNTER].dX = -20;
            Magic[MAGIC_COUNTER].dY = 0;
            break;

          case 2: // Right
            // Set x and y coords
            Magic[MAGIC_COUNTER].X =
                X + W - Magic[MAGIC_COUNTER].W / 4 * Magic[MAGIC_COUNTER].GROWTHFACTOR;
            Magic[MAGIC_COUNTER].Y =
                Y + H / 2 - Magic[MAGIC_COUNTER].H / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR;
            // Set frame 0
            Magic[MAGIC_COUNTER].FX = 0;
            // Movement Speed
            Magic[MAGIC_COUNTER].dX = 20;
            Magic[MAGIC_COUNTER].dY = 0;
            break;

          case 3: // Up
            // Set x and y coords
            Magic[MAGIC_COUNTER].X =
                X + W / 2 - Magic[MAGIC_COUNTER].W / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR;
            Magic[MAGIC_COUNTER].Y =
                Y - Magic[MAGIC_COUNTER].H / 2 * Magic[MAGIC_COUNTER].GROWTHFACTOR;
            // Set frame 0
            Magic[MAGIC_COUNTER].FX = 0;
            // Movement Speed
            Magic[MAGIC_COUNTER].dX = 0;
            Magic[MAGIC_COUNTER].dY = -20;
            break;
        }
    }
    // Activate
    Magic[MAGIC_COUNTER].ISACTIVE = true;

    // Consume mana
    MANA -= Magic[MAGIC_COUNTER].STATS.POINTS;

    // Change counter
    MAGIC_COUNTER++;
    if (MAGIC_COUNTER == Magic.length) MAGIC_COUNTER = 0;
  }

  /**
   * Physical Meele Attack
   *
   * @param Me
   */
  public void PAttack(MeeleAttack Me) {

    switch (TYPE) {
      case 1:
        // Meele Attack
        if (FY == Type1.UP.ordinal()) {
          Me.PAttack(Type1.UP.name());
        } else if (FY == Type1.DOWN.ordinal()) {
          Me.PAttack(Type1.DOWN.name());
        } else if (FY == Type1.LEFT.ordinal()) {
          Me.PAttack(Type1.LEFT.name());
        } else if (FY == Type1.RIGHT.ordinal()) {
          Me.PAttack(Type1.RIGHT.name());
        }

        break;
      case 2:
        // Meele Attack
        if (FY == Type2.UP.ordinal()) {
          Me.PAttack(Type2.UP.name());
        } else if (FY == Type2.DOWN.ordinal()) {
          Me.PAttack(Type2.DOWN.name());
        } else if (FY == Type2.LEFT.ordinal()) {
          Me.PAttack(Type2.LEFT.name());
        } else if (FY == Type2.RIGHT.ordinal()) {
          Me.PAttack(Type2.RIGHT.name());
        }

        break;
      case 3:
        // Meele Attack
        if (FY == Type3.UP.ordinal()) {
          Me.PAttack(Type3.UP.name());
        } else if (FY == Type3.DOWN.ordinal()) {
          Me.PAttack(Type3.DOWN.name());
        } else if (FY == Type3.LEFT.ordinal()) {
          Me.PAttack(Type3.LEFT.name());
        } else if (FY == Type3.RIGHT.ordinal()) {
          Me.PAttack(Type3.RIGHT.name());
        }

        break;
    }
  }

  /**
   * get xp and gold from killing characters
   *
   * @param Charac collision characters
   */
  public void KillXP(GameCharacter Charac) {
    // When the character dies
    if (Charac.ISDEAD && Charac.COLL_LISTENER) {

      Charac.COLL_LISTENER = false;
      audDEATH.playAudio("death.wav");

      // Remove collision listener
      for (int j = 0; j < FIREBALL.length; j++) {
        FIREBALL[j].removeCollChar(Charac);
      }
      for (int j = 0; j < SHOCK.length; j++) {
        SHOCK[j].removeCollChar(Charac);
      }
      for (int j = 0; j < DARKNESS.length; j++) {
        DARKNESS[j].removeCollChar(Charac);
      }
      for (int j = 0; j < LIFE_DRAIN.length; j++) {
        LIFE_DRAIN[j].removeCollChar(Charac);
      }

      // Add Xp
      STATS.IncreaseXP(10 * Charac.STATS.LEVEL);
      // Add Gold
      this.GOLD += Charac.GOLD;
    }
  }

  /**
   * get xp and gold from killing characters
   *
   * @param Charac collision characters
   */
  public void KillXP(GameCharacter[] Charac) {
    // When the character dies
    for (int i = 0; i < Charac.length; i++) {
      if (Charac[i].ISDEAD && Charac[i].COLL_LISTENER) {

        Charac[i].COLL_LISTENER = false;
        audDEATH.playAudio("death.wav");

        // Remove collision listener
        for (int j = 0; j < FIREBALL.length; j++) {
          FIREBALL[j].removeCollChar(Charac[i]);
        }
        for (int j = 0; j < SHOCK.length; j++) {
          SHOCK[j].removeCollChar(Charac[i]);
        }
        for (int j = 0; j < DARKNESS.length; j++) {
          DARKNESS[j].removeCollChar(Charac[i]);
        }
        for (int j = 0; j < LIFE_DRAIN.length; j++) {
          LIFE_DRAIN[j].removeCollChar(Charac[i]);
        }

        // Add Xp
        STATS.IncreaseXP(10 * Charac[i].STATS.LEVEL);
        // Add Gold
        this.GOLD += Charac[i].GOLD;
      }
    }
  }

  /**
   * Check if this x and y coordinate is within the component
   *
   * @param x X coordinate
   * @param y Y coordinate
   */
  public boolean Contains(double x, double y) {
    // Check collision
    if ((x > X) && (x < X + W * GROWTHFACTOR)) {
      if ((y > Y) && (y < Y + H * GROWTHFACTOR)) {
        return true;
      }
    }

    return false;
  }

  /**
   * Used for debugging get list of spells available to character
   *
   * @return List
   */
  public String[] getSpellList() {
    // Make Array
    String[] arg = new String[SPELL_LIST.size()];

    // Assign names
    for (int i = 0; i < arg.length; i++) {
      arg[i] = SPELL_LIST.elementAt(i)[0].NAME;
      System.out.println(arg[i]);
    }

    // Return list
    return arg;
  }

  /**
   * Spells collide with the given characters
   *
   * @param Charac Game character array
   */
  public void addMagicCharacCollision(GameCharacter[] Charac) {

    // FIREBALL
    for (int i = 0; i < FIREBALL.length; i++) {
      FIREBALL[i].addCollChar(Charac);
    }

    // SHOCK
    for (int i = 0; i < SHOCK.length; i++) {
      SHOCK[i].addCollChar(Charac);
    }

    // DARKNESS
    for (int i = 0; i < DARKNESS.length; i++) {
      DARKNESS[i].addCollChar(Charac);
    }

    // LIFE DRAIN
    for (int i = 0; i < LIFE_DRAIN.length; i++) {
      LIFE_DRAIN[i].addCollChar(Charac);
    }
  }

  /**
   * Spells collide with the given characters
   *
   * @param Charac Game character array
   */
  public void addMagicCharacCollision(GameCharacter Charac) {

    // FIREBALL
    for (int i = 0; i < FIREBALL.length; i++) {
      FIREBALL[i].addCollChar(Charac);
    }

    // SHOCK
    for (int i = 0; i < SHOCK.length; i++) {
      SHOCK[i].addCollChar(Charac);
    }

    // DARKNESS
    for (int i = 0; i < DARKNESS.length; i++) {
      DARKNESS[i].addCollChar(Charac);
    }

    // LIFE DRAIN
    for (int i = 0; i < LIFE_DRAIN.length; i++) {
      LIFE_DRAIN[i].addCollChar(Charac);
    }
  }

  /**
   * Spells collide with walls
   *
   * @param Map GridMap
   */
  public void addMagicMapCollision(GridMap Map) {

    // FIREBALL
    for (int i = 0; i < FIREBALL.length; i++) {
      FIREBALL[i].addColisionObject(Map);
    }

    // SHOCK
    for (int i = 0; i < SHOCK.length; i++) {
      SHOCK[i].addColisionObject(Map);
    }

    // DARKNESS
    for (int i = 0; i < DARKNESS.length; i++) {
      // DARKNESS[i].addColisionObject(Map);
    }

    // LIFE DRAIN
    for (int i = 0; i < LIFE_DRAIN.length; i++) {
      LIFE_DRAIN[i].addColisionObject(Map);
    }
  }

  public void Heal(int Amount) {
    HEALTH += Amount;
    if (HEALTH > MAX_HEALTH) HEALTH = (int) MAX_HEALTH;
  }

  public void giveQuest(GameCharacter Reciever) {
    if (QUEST_LIST.size() > 0) {
      if (QUEST_LIST.elementAt(0).STATUS == 0) {
        Reciever.QUEST_LIST.add(QUEST_LIST.elementAt(0));
        QUEST_LIST.elementAt(0).play_UpdateSound();
        if (QUEST_LIST.elementAt(0).QTYPE == Quest_Type.DELIVERY) {
          for (int i = 0; i < QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_NAME.size(); i++) {
            Reciever.INVENTORY.addItem(
                QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_NAME.elementAt(i),
                QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_PRICE.elementAt(i),
                QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_QUANTITY.elementAt(i),
                QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_IMAGE.elementAt(i),
                QUEST_LIST.elementAt(0).TARGET_LIST.ITEM_TAG.elementAt(i),
                QUEST_LIST.elementAt(0).TARGET_LIST.STATS.elementAt(i));
          }
        }
        QUEST_LIST.elementAt(0).STATUS = 1;
      }
    }
  }

  public void CompleteQuest(int Index) {
    Quest qstComp = QUEST_LIST.elementAt(Index);
    qstComp.STATUS = 3;
    qstComp.QUEST_GIVER.QUEST_LIST.elementAt(0).STATUS = 3;
    qstComp.QUEST_GIVER.QUEST_LIST.removeElementAt(0);
    STATS.IncreaseXP(qstComp.XP);
    GOLD += qstComp.GOLD;
  }

  public BufferedImage getImage(String Direct, String FName) {
    // JOptionPane.showMessageDialog(null, "GameCharacter");
    try {
      BufferedImage bg = ImageIO.read(getClass().getResource(Direct + FName));
      return bg;

    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, getClass().toString());
    }
    return null;
  }

  public boolean isJar() {
    Path pth = Paths.get(System.getProperty("user.dir") + "/Advent.jar");

    if (pth.toFile().exists()) return true;
    return false;
  }
}
示例#26
0
 public void start() {
   startTime = System.currentTimeMillis();
 }
示例#27
0
    public void
        run() { // ************************************************************************************

      String jsonText2 = new String("");

      JSONObject obj_out = new JSONObject();

      ServerSocket welcomeSocket;

      while (true) {

        try { // *********************************************************

          welcomeSocket = new ServerSocket(network.api_port, 0, InetAddress.getByName("localhost"));
          Socket connectionSocket = welcomeSocket.accept();
          BufferedReader inFromClient =
              new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
          DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
          clientSentence = inFromClient.readLine();

          JSONParser parser = new JSONParser();

          try { // *********************************************************

            statex = "0";
            responsex = "e00";
            jsonText = "";

            if (!clientSentence.contains("")) {
              throw new EmptyStackException();
            }
            Object obj = parser.parse(clientSentence);

            jsonObject = (JSONObject) obj;

            String request = (String) jsonObject.get("request");

            String item_id = new String("");
            String item_array = new String("");
            String old_key = new String("");
            String node = new String("");
            try {
              item_id = (String) jsonObject.get("item_id").toString();
            } catch (Exception e) {
              System.out.println("extra info no item_id...");
            }
            try {
              item_array = (String) jsonObject.get("item_array").toString();
            } catch (Exception e) {
              System.out.println("extra info no item_array...");
            }
            try {
              old_key = (String) jsonObject.get("key").toString();
            } catch (Exception e) {
              System.out.println("extra info no key...");
            }
            try {
              node = (String) jsonObject.get("node").toString();
            } catch (Exception e) {
              System.out.println("extra info no node...");
            }

            while (network.database_in_use == 1 && !request.equals("status")) {

              System.out.println("Database in use...");
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
              }
            } // **************************************************************

            if (request.equals("status")) {
              statex = "1";
              responsex = get_status();
            } // ***************************
            else if (request.equals("get_version")) {
              statex = "1";
              responsex = network.versionx;
            } //
            else if (request.equals("get_tor_active")) {
              statex = "1";
              responsex = Integer.toString(network.tor_active);
            } //
            else if (request.equals("get_last_block")) {
              statex = "1";
              responsex = network.last_block_id;
            } //
            else if (request.equals("get_last_block_timestamp")) {
              statex = "1";
              responsex = network.last_block_timestamp;
            } //
            else if (request.equals("get_last_block_hash")) {
              statex = "1";
              responsex = network.last_block_idx;
            } //
            else if (request.equals("get_difficulty")) {
              statex = "1";
              responsex = Long.toString(network.difficultyx);
            } //
            else if (request.equals("get_last_mining_id")) {
              statex = "1";
              responsex = network.last_block_mining_idx;
            } //
            else if (request.equals("get_prev_mining_id")) {
              statex = "1";
              responsex = network.prev_block_mining_idx;
            } //
            else if (request.equals("get_last_unconfirmed_id")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_my_token_total")) {
              statex = "1";
              responsex = Integer.toString(network.database_listings_owner);
            } //
            else if (request.equals("get_my_id_list")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_my_ids_limit")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_token")) {
              statex = "1";
              responsex = get_item_array(item_id);
            } //
            else if (request.equals("get_settings")) {
              statex = "1";
              responsex = get_settings_array();
            } //
            else if (request.equals("get_mining_info")) {
              statex = "1";
              responsex = get_item_array(item_id);
            } //
            else if (request.equals("get_new_keys")) {
              statex = "1";
              responsex = build_keysx();
            } //
            else if (request.equals("delete_node")) {
              statex = "1";
              responsex = delete_node(node);
            } //
            else if (request.equals("delete_all_nodes")) {
              statex = "1";
              responsex = delete_all_nodes();
            } //
            else if (request.equals("set_new_node")) {
              statex = "1";
              responsex = set_new_node(node);
            } //
            else if (request.equals("set_old_key")) {
              statex = "1";
              responsex = set_old_key(old_key);
            } //
            else if (request.equals("set_new_block")) {
              statex = "1";
              responsex = set_new_block(item_array);
            } //
            else if (request.equals("set_edit_block")) {
              statex = "1";
              update_state = "set_edit_block";
              responsex = update_token(item_array);
            } //
            else if (request.equals("set_transfer_block")) {
              statex = "1";
              update_state = "set_transfer_block";
              responsex = update_token(item_array);
            } //
            else if (request.equals("system_restart")) {
              statex = "1";
              responsex = "restarting";
              toolkit = Toolkit.getDefaultToolkit();
              xtimerx = new Timer();
              xtimerx.schedule(new RemindTask_restart(), 0);
            } //
            else if (request.equals("system_exit")) {
              statex = "1";
              System.exit(0);
            } //
            else {
              statex = "0";
              responsex = "e01 UnknownRequestException";
            }

          } // try
          catch (ParseException e) {
            e.printStackTrace();
            statex = "0";
            responsex = "e02 ParseException";
          } catch (Exception e) {
            e.printStackTrace();
            statex = "0";
            responsex = "e03 Exception";
          }

          JSONObject obj = new JSONObject();
          obj.put("response", statex);
          try {
            obj.put("message", responsex);
          } catch (Exception e) {
            e.printStackTrace();
          }

          StringWriter outs = new StringWriter();
          obj.writeJSONString(outs);
          jsonText = outs.toString();
          System.out.println("SEND RESPONSE " + responsex);

          outToClient.writeBytes(jsonText + '\n');
          welcomeSocket.close();

        } catch (Exception e) {
          e.printStackTrace();
          System.out.println("Server ERROR x3");
        }
      } // **********while
    } // runx***************************************************************************************************
示例#28
0
  public String update_token(String req_array) {

    System.out.println("Update");

    String jsonarry = new String("");

    try {

      JSONParser parser = new JSONParser();
      Object obj = parser.parse(req_array);
      JSONObject jsonObject = (JSONObject) obj;

      String id = (String) jsonObject.get("id");
      String hash_id = (String) jsonObject.get("hash_id");
      String sig_id = (String) jsonObject.get("sig_id");
      String date_id = (String) jsonObject.get("date_id");
      String owner_id = (String) jsonObject.get("owner_id");
      String owner_rating = (String) jsonObject.get("owner_rating");
      String currency = (String) jsonObject.get("currency");
      String custom_template = (String) jsonObject.get("custom_template");
      String custom_1 = (String) jsonObject.get("custom_1");
      String custom_2 = (String) jsonObject.get("custom_2");
      String custom_3 = (String) jsonObject.get("custom_3");
      String item_errors = (String) jsonObject.get("item_errors");
      String item_date_listed = (String) jsonObject.get("item_date_listed");
      String item_date_listed_day = (String) jsonObject.get("item_date_listed_da");
      String item_date_listed_int = (String) jsonObject.get("item_date_listed_int");
      String item_hits = (String) jsonObject.get("item_hits");
      String item_confirm_code = (String) jsonObject.get("item_confirm_code");
      String item_confirmed = (String) jsonObject.get("item_confirmed");
      String item_cost = (String) jsonObject.get("item_cost");
      String item_description = (String) jsonObject.get("item_description");
      String item_id = (String) jsonObject.get("item_id");
      String item_price = (String) jsonObject.get("item_price");
      String item_weight = (String) jsonObject.get("item_weight");
      String item_listing_id = (String) jsonObject.get("item_listing_id");
      String item_notes = (String) jsonObject.get("item_notes");
      String item_package_d = (String) jsonObject.get("item_package_d");
      String item_package_l = (String) jsonObject.get("item_package_l");
      String item_package_w = (String) jsonObject.get("item_package_w");
      String item_part_number = (String) jsonObject.get("item_part_number");
      String item_title = (String) jsonObject.get("item_title");
      String item_title_url = (String) jsonObject.get("item_title");
      String item_type = (String) jsonObject.get("item_type");
      String item_search_1 = (String) jsonObject.get("item_search_1");
      String item_search_2 = (String) jsonObject.get("item_search_2");
      String item_search_3 = (String) jsonObject.get("item_search_3");
      String item_site_id = (String) jsonObject.get("item_site_id");
      String item_site_url = (String) jsonObject.get("item_site_url");
      String item_picture_1 = (String) jsonObject.get("item_picture_1");
      String item_total_on_hand = (String) jsonObject.get("item_total_on_hand");
      String sale_payment_address = (String) jsonObject.get("sale_payment_address");
      String sale_payment_type = (String) jsonObject.get("sale_payment_type");
      String sale_fees = (String) jsonObject.get("sale_fees");
      String sale_id = (String) jsonObject.get("sale_id");
      String sale_seller_id = (String) jsonObject.get("sale_seller_id");
      String sale_status = (String) jsonObject.get("sale_status");
      String sale_tax = (String) jsonObject.get("sale_tax");
      String sale_shipping_company = (String) jsonObject.get("sale_shipping_company");
      String sale_shipping_in = (String) jsonObject.get("sale_shipping_in");
      String sale_shipping_out = (String) jsonObject.get("sale_shipping_out");
      String sale_source_of_sale = (String) jsonObject.get("sale_source_of_sale");
      String sale_total_sale_amount = (String) jsonObject.get("sale_total_sale_amount");
      String sale_tracking_number = (String) jsonObject.get("sale_tracking_number");
      String sale_transaction_id = (String) jsonObject.get("sale_transaction_id");
      String sale_transaction_info = (String) jsonObject.get("sale_transaction_info");
      String seller_address_1 = (String) jsonObject.get("seller_address_1");
      String seller_address_2 = (String) jsonObject.get("seller_address_2");
      String seller_address_city = (String) jsonObject.get("seller_address_city");
      String seller_address_state = (String) jsonObject.get("seller_address_state");
      String seller_address_zip = (String) jsonObject.get("seller_address_zip");
      String seller_address_country = (String) jsonObject.get("seller_address_country");
      String seller_id = (String) jsonObject.get("seller_id");
      String seller_ip = (String) jsonObject.get("seller_ip");
      String seller_email = (String) jsonObject.get("seller_email");
      String seller_first_name = (String) jsonObject.get("seller_first_name");
      String seller_last_name = (String) jsonObject.get("seller_last_name");
      String seller_notes = (String) jsonObject.get("seller_notes");
      String seller_phone = (String) jsonObject.get("seller_phone");
      String seller_logo = (String) jsonObject.get("seller_logo");
      String seller_url = (String) jsonObject.get("seller_url");

      try {
        if (currency.length() < 1) {}
      } catch (Exception e) {
        currency = new String("1");
      }
      try {
        if (custom_template.length() < 1) {}
      } catch (Exception e) {
        custom_template = new String("2");
      }
      try {
        if (custom_1.length() < 1) {}
      } catch (Exception e) {
        custom_1 = new String("3");
      }
      try {
        if (custom_2.length() < 1) {}
      } catch (Exception e) {
        custom_2 = new String("4");
      }
      try {
        if (custom_3.length() < 1) {}
      } catch (Exception e) {
        custom_3 = new String("5");
      }
      try {
        if (item_errors.length() < 1) {}
      } catch (Exception e) {
        item_errors = new String("6");
      }
      try {
        if (item_date_listed.length() < 1) {}
      } catch (Exception e) {
        item_date_listed = new String("7");
      }
      try {
        if (item_date_listed_day.length() < 1) {}
      } catch (Exception e) {
        item_date_listed_day = new String("8");
      }
      try {
        if (item_date_listed_int.length() < 1) {}
      } catch (Exception e) {
        item_date_listed_int = new String("9");
      }
      try {
        if (item_hits.length() < 1) {}
      } catch (Exception e) {
        item_hits = new String("10");
      }
      try {
        if (item_confirm_code.length() < 1) {}
      } catch (Exception e) {
        item_confirm_code = new String("11");
      }
      try {
        if (item_confirmed.length() < 1) {}
      } catch (Exception e) {
        item_confirmed = new String("12");
      }
      try {
        if (item_cost.length() < 1) {}
      } catch (Exception e) {
        item_cost = new String("13");
      }
      try {
        if (item_description.length() < 1) {}
      } catch (Exception e) {
        item_description = new String("14");
      }
      try {
        if (item_id.length() < 1) {}
      } catch (Exception e) {
        item_id = new String("15");
      }
      try {
        if (item_price.length() < 1) {}
      } catch (Exception e) {
        item_price = new String("16");
      }
      try {
        if (item_weight.length() < 1) {}
      } catch (Exception e) {
        item_weight = new String("17");
      }
      try {
        if (item_notes.length() < 1) {}
      } catch (Exception e) {
        item_notes = new String("18");
      }
      try {
        if (item_package_d.length() < 1) {}
      } catch (Exception e) {
        item_package_d = new String("19");
      }
      try {
        if (item_package_l.length() < 1) {}
      } catch (Exception e) {
        item_package_l = new String("20");
      }
      try {
        if (item_package_w.length() < 1) {}
      } catch (Exception e) {
        item_package_w = new String("21");
      }
      try {
        if (item_part_number.length() < 1) {}
      } catch (Exception e) {
        item_part_number = new String("22");
      }
      try {
        if (item_title.length() < 1) {}
      } catch (Exception e) {
        item_title = new String("23");
      }
      try {
        if (item_title_url.length() < 1) {}
      } catch (Exception e) {
        item_title_url = new String("24");
      }
      try {
        if (item_type.length() < 1) {}
      } catch (Exception e) {
        item_type = new String("25");
      }
      try {
        if (item_search_1.length() < 1) {}
      } catch (Exception e) {
        item_search_1 = new String("26");
      }
      try {
        if (item_search_2.length() < 1) {}
      } catch (Exception e) {
        item_search_2 = new String("27");
      }
      try {
        if (item_search_3.length() < 1) {}
      } catch (Exception e) {
        item_search_3 = new String("28");
      }
      try {
        if (item_site_url.length() < 1) {}
      } catch (Exception e) {
        item_site_url = new String("29");
      }
      try {
        if (item_picture_1.length() < 1) {}
      } catch (Exception e) {
        item_picture_1 = new String("30");
      }
      try {
        if (item_total_on_hand.length() < 1) {}
      } catch (Exception e) {
        item_total_on_hand = new String("31");
      }

      String tokenx[] = new String[network.listing_size];

      if (Integer.parseInt(id) >= network.base_int
          && Integer.parseInt(id) <= (network.hard_token_limit + network.base_int)) {

        krypton_database_get_token2 getxt = new krypton_database_get_token2();
        tokenx = getxt.get_token(id);

        // update the noose
        tokenx[3] = Long.toString(System.currentTimeMillis());

        tokenx[4] = network.settingsx[5];

        tokenx[6] = currency;
        tokenx[7] = custom_template;
        tokenx[8] = custom_1;
        tokenx[9] = custom_2;
        tokenx[10] = custom_3;
        tokenx[11] = item_errors;
        tokenx[12] = item_date_listed;
        tokenx[13] = item_date_listed_day;
        tokenx[14] = item_date_listed_int;
        tokenx[15] = item_hits;
        tokenx[16] = item_confirm_code;
        tokenx[17] = item_confirmed;
        tokenx[18] = item_cost;
        tokenx[19] = item_description;
        tokenx[20] = item_id;
        tokenx[21] = item_price;
        tokenx[22] = item_weight;

        tokenx[24] = item_notes;
        tokenx[25] = item_package_d;
        tokenx[26] = item_package_l;
        tokenx[27] = item_package_w;
        tokenx[28] = item_part_number;
        tokenx[29] = item_title;
        tokenx[30] = item_title_url;
        tokenx[31] = item_type;
        tokenx[32] = item_search_1;
        tokenx[33] = item_search_2;
        tokenx[34] = item_search_3;

        tokenx[36] = item_site_url;
        tokenx[37] = item_picture_1;
        tokenx[38] = item_total_on_hand;

        // to help with search
        tokenx[30] = tokenx[29].toLowerCase();

        // base 58
        if (update_state.equals("set_edit_block")) {
          tokenx[60] = network.base58_id;
        } else if (update_state.equals("set_transfer_block")) {
          tokenx[60] = seller_id;
        }

        // seller info
        tokenx[63] = network.settingsx[11]; // name
        tokenx[64] = network.settingsx[12]; // last
        tokenx[54] = network.settingsx[13]; // address
        tokenx[55] = network.settingsx[14]; // address2
        tokenx[56] = network.settingsx[15]; // city
        tokenx[57] = network.settingsx[16]; // state
        tokenx[58] = network.settingsx[17]; // zip
        tokenx[59] = network.settingsx[18]; // country

        tokenx[39] = network.settingsx[19]; // btc
        tokenx[62] = network.settingsx[20]; // email
        tokenx[66] = network.settingsx[21]; // phone
        tokenx[68] = network.settingsx[22]; // website

        // sign

        try {

          String build_hash = new String("");

          build_hash = tokenx[0];
          for (int loop = 3; loop < tokenx.length; loop++) {

            build_hash = build_hash + tokenx[loop]; // save everything else
          } // *************************************************

          String hashx = new String(build_hash);
          byte[] sha256_1x = MessageDigest.getInstance("SHA-256").digest(hashx.getBytes());
          System.out.println(Base64.toBase64String(sha256_1x));

          tokenx[1] = Base64.toBase64String(sha256_1x);

          byte[] message = Base64.toBase64String(sha256_1x).getBytes("UTF8");

          byte[] clear = Base64.decode(network.settingsx[4]);
          PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
          KeyFactory fact = KeyFactory.getInstance("RSA");
          PrivateKey priv = fact.generatePrivate(keySpec);
          Arrays.fill(clear, (byte) 0);

          Signature sigx = Signature.getInstance("SHA1WithRSA"); // MD5WithRSA
          sigx.initSign(priv);
          sigx.update(message);
          byte[] signatureBytesx = sigx.sign();
          // System.out.println("Public: " + Base64.toBase64String(pub.getEncoded()));
          System.out.println("Singature: " + Base64.toBase64String(signatureBytesx));

          String signxx = Base64.toBase64String(signatureBytesx);

          tokenx[2] = signxx;

          byte[] keyxb3 = Base64.decode(tokenx[4]);

          X509EncodedKeySpec keySpecx3 = new X509EncodedKeySpec(keyxb3);
          KeyFactory factx3 = KeyFactory.getInstance("RSA");
          PublicKey pubx3 = factx3.generatePublic(keySpecx3);
          Arrays.fill(keyxb3, (byte) 0);

          Signature sigpk3 = Signature.getInstance("SHA1WithRSA"); // MD5WithRSA
          byte[] messagex3 = Base64.toBase64String(sha256_1x).getBytes("UTF8");

          byte[] signatureBytesx3 = Base64.decode(signxx);

          sigpk3.initVerify(pubx3);
          sigpk3.update(messagex3);

          boolean testsx = sigpk3.verify(signatureBytesx3);

          System.out.println("testsx " + testsx);

          if (testsx) {

            statex = "1";
            jsonarry = "Updated";

          } // ********
          else {

            statex = "0";
            jsonarry = "Update error. Information did not pass signature test.";
          } // **

          if (update_state.equals("set_edit_block")) {
            network.icon.displayMessage(
                "Krypton", "Token updated ID (" + tokenx[0] + ")", TrayIcon.MessageType.INFO);
          } else if (update_state.equals("set_transfer_block")) {
            network.icon.displayMessage(
                "Krypton", "Token transfer ID (" + tokenx[0] + ")", TrayIcon.MessageType.INFO);
          }

          // send the update
          tokenx_buffer = tokenx;
          toolkit = Toolkit.getDefaultToolkit();
          xtimerx = new Timer();
          xtimerx.schedule(new RemindTask_send_update(), 0);
          // send the update

        } catch (Exception e) {
          e.printStackTrace();
        }

      } // if
      else {
        System.out.println("Update item error cannot find item.");
        statex = "0";
        jsonarry = "Update item error cannot find item.";
      }

    } catch (Exception e) {
      e.printStackTrace();
      statex = "0";
      jsonarry = "Error";
    } // *****************

    return jsonarry;
  } // *****************
示例#29
0
 public long stop() {
   return System.currentTimeMillis() - startTime;
 }
示例#30
0
  public boolean isJar() {
    Path pth = Paths.get(System.getProperty("user.dir") + "/Advent.jar");

    if (pth.toFile().exists()) return true;
    return false;
  }