public void setup() { size(600, 400); smooth(); f = createFont("Georgia", 12, true); obstacles = new ArrayList(); boids = new ArrayList(); // A little algorithm to pick a bunch of random obstacles that don't overlap for (int i = 0; i < 100; i++) { float x = random(width); float y = random(height); float r = random(50 - i / 2, 50); boolean ok = true; for (int j = 0; j < obstacles.size(); j++) { Obstacle o = (Obstacle) obstacles.get(j); if (dist(x, y, o.loc.x, o.loc.y) < o.radius + r + 20) { ok = false; } } if (ok) obstacles.add(new Obstacle(x, y, r)); } // Starting with three boids boids.add(new Boid(new PVector(random(width), random(height)), 3f, 0.2f)); boids.add(new Boid(new PVector(random(width), random(height)), 3f, 0.1f)); boids.add(new Boid(new PVector(random(width), random(height)), 2f, 0.05f)); }
public void getSavedLocations() { // System.out.println("inside getSavedLocations"); //CONSOLE * * * * * * * * * * * * * loc.clear(); // clear locations. helps refresh the list when reprinting all the locations BufferedWriter f = null; // just in case file has not been created yet BufferedReader br = null; try { // attempt to open the locations file if it doesn't exist, create it f = new BufferedWriter( new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist br = new BufferedReader(new FileReader("savedLocations.txt")); String line; // each line is one index of the list loc.add("Saved Locations"); // loop and read a line from the file as long as we don't get null while ((line = br.readLine()) != null) // add the read word to the wordList loc.add(line); } catch (IOException e) { e.printStackTrace(); } finally { try { // attempt the close the file br.close(); // close bufferedwriter } catch (IOException ex) { ex.printStackTrace(); } } }
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); } }
public void createBuildings() { bList = new ArrayList<Building>(); // resource bList.add(new Building("Gold Mine", 3, 3, 960, 7)); bList.add(new Building("Elixir Collector", 3, 3, 960, 7)); // bList.add(new Building("Dark Elixir Drill", 3, 3, 1160, 3)); bList.add(new Building("Gold Storage", 3, 3, 2100, 4)); bList.add(new Building("Elixir Storage", 3, 3, 2100, 4)); // bList.add(new Building("Dark Elixir Storage", 3, 3, 3200, 1)); // bList.add(new Building("Builder Hut", 2, 2, 250, 5)); // army bList.add(new Building("Army Camp", 5, 5, 500, 4)); bList.add(new Building("Barracks", 3, 3, 860, 4)); // bList.add(new Building("Dark Barracks", 3, 3, 900, 2)); // bList.add(new Building("Laboratory", 4, 4, 950, 1)); // bList.add(new Building("Spell Factory", 3, 3, 615, 1)); // bList.add(new Building("Barbarian King Altar", 3, 3, 250, 1)); // bList.add(new Building("Dark Spell Factory", 3, 3, 750, 1)); // bList.add(new Building("Archer Queen Altar", 3, 3, 250, 1)); // other bList.add(new Building("Town Hall", 4, 4, 5500, 1)); bList.add(new Building("Clan Castle", 3, 3, 3400, 1)); // defense bList.add(new Building("Archer Tower", 3, 3, 1050, 7)); bList.add(new Building("Cannon", 3, 3, 1260, 6)); bList.add(new Building("Wall", 1, 1, 7000, 275)); // bList.add(new Building("Air Sweeper", 2, 2, 1000, 2)); // bList.add(new Building("Cannon", 3, 3, 1260, 6)); // bList.add(new Building("Cannon", 3, 3, 1260, 6)); }
private ArrayList GetFolderTree(String s_Dir, String s_Flag, int n_Indent, int n_TreeIndex) { String s_List = ""; ArrayList aSubFolders = new ArrayList(); File file = new File(s_Dir); File[] filelist = file.listFiles(); if (filelist != null && filelist.length > 0) { for (int i = 0; i < filelist.length; i++) { if (filelist[i].isDirectory()) { aSubFolders.add(filelist[i].getName()); } } int n_Count = aSubFolders.size(); String s_LastFlag = ""; String s_Folder = ""; for (int i = 1; i <= n_Count; i++) { if (i < n_Count) { s_LastFlag = "0"; } else { s_LastFlag = "1"; } s_Folder = aSubFolders.get(i - 1).toString(); s_List = s_List + "arr" + s_Flag + "[" + String.valueOf(n_TreeIndex) + "]=new Array(\"" + s_Folder + "\"," + String.valueOf(n_Indent) + ", " + s_LastFlag + ");\n"; n_TreeIndex = n_TreeIndex + 1; ArrayList a_Temp = GetFolderTree(s_Dir + s_Folder + sFileSeparator, s_Flag, n_Indent + 1, n_TreeIndex); s_List = s_List + a_Temp.get(0).toString(); n_TreeIndex = Integer.valueOf(a_Temp.get(1).toString()).intValue(); } } ArrayList a_Return = new ArrayList(); a_Return.add(s_List); a_Return.add(String.valueOf(n_TreeIndex)); return a_Return; }
/** * Loads into a double[][] a plain text file of numbers, with newlines dividing the numbers into * rows and tabs or spaces delimiting columns. The Y dimension is not flipped. */ public static double[][] loadTextFile(InputStream stream) throws IOException { Scanner scan = new Scanner(stream); ArrayList rows = new ArrayList(); int width = -1; while (scan.hasNextLine()) { String srow = scan.nextLine().trim(); if (srow.length() > 0) { int w = 0; if (width == -1) // first time compute width { ArrayList firstRow = new ArrayList(); Scanner rowScan = new Scanner(new StringReader(srow)); while (rowScan.hasNextDouble()) { firstRow.add(new Double(rowScan.nextDouble())); // ugh, boxed w++; } width = w; double[] row = new double[width]; for (int i = 0; i < width; i++) row[i] = ((Double) (firstRow.get(i))).doubleValue(); rows.add(row); } else { double[] row = new double[width]; Scanner rowScan = new Scanner(new StringReader(srow)); while (rowScan.hasNextDouble()) { if (w == width) // uh oh throw new IOException("Row lengths do not match in text file"); row[w] = rowScan.nextDouble(); w++; } if (w < width) // uh oh throw new IOException("Row lengths do not match in text file"); rows.add(row); } } } if (width == -1) // got nothing return new double[0][0]; double[][] fieldTransposed = new double[rows.size()][]; for (int i = 0; i < rows.size(); i++) fieldTransposed[i] = ((double[]) (rows.get(i))); // now transpose because we have width first double[][] field = new double[width][fieldTransposed.length]; for (int i = 0; i < field.length; i++) for (int j = 0; j < field[i].length; j++) field[i][j] = fieldTransposed[j][i]; return field; }
public Iterator handlePixels(Image img, Rectangle rect) { int x = rect.x; int y = rect.y; int w = rect.width; int h = rect.height; int[] pixels = new int[w * h]; PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w); try { pg.grabPixels(); } catch (InterruptedException e) { System.err.println("interrupted waiting for pixels!"); return null; } if ((pg.getStatus() & ImageObserver.ABORT) != 0) { System.err.println("image fetch aborted or errored"); return null; } ArrayList tmpList = new ArrayList(); for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { tmpList.add(handleSinglePixel(x + i, y + j, pixels[j * w + i])); } } return tmpList.iterator(); }
public void updatePickups() { for (int i = 0; i < pickupList.size(); i++) { if (pickupList.get(i).pickedUp) pickupList.remove(i); } // end for while (pickupList.size() < startNumPickups) pickupList.add(new Pickup(frameWidth, frameHeight)); } // end updatePickups
public BufferedImage filter(BufferedImage src, BufferedImage dst) { if (dst == null) dst = createCompatibleDestImage(src, null); int width = src.getWidth(); int height = src.getHeight(); int numScratches = (int) (density * width * height / 100); ArrayList<Line2D> lines = new ArrayList<Line2D>(); { float l = length * width; Random random = new Random(seed); Graphics2D g = dst.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(new Color(color)); g.setStroke(new BasicStroke(this.width)); for (int i = 0; i < numScratches; i++) { float x = width * random.nextFloat(); float y = height * random.nextFloat(); float a = angle + ImageMath.TWO_PI * (angleVariation * (random.nextFloat() - 0.5f)); float s = (float) Math.sin(a) * l; float c = (float) Math.cos(a) * l; float x1 = x - c; float y1 = y - s; float x2 = x + c; float y2 = y + s; g.drawLine((int) x1, (int) y1, (int) x2, (int) y2); lines.add(new Line2D.Float(x1, y1, x2, y2)); } g.dispose(); } if (false) { // int[] inPixels = getRGB( src, 0, 0, width, height, null ); int[] inPixels = new int[width * height]; int index = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float sx = x, sy = y; for (int i = 0; i < numScratches; i++) { Line2D.Float l = (Line2D.Float) lines.get(i); float dot = (l.x2 - l.x1) * (sx - l.x1) + (l.y2 - l.y1) * (sy - l.y1); if (dot > 0) inPixels[index] |= (1 << i); } index++; } } Colormap colormap = new LinearColormap(); index = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float f = (float) (inPixels[index] & 0x7fffffff) / 0x7fffffff; inPixels[index] = colormap.getColor(f); index++; } } setRGB(dst, 0, 0, width, height, inPixels); } return dst; }
public void setup() { size(320, 240); smooth(); // Start with 10 balls balls = new ArrayList(); for (int i = 0; i < 10; i++) { Ball ball = new Ball(random(width), random(height)); balls.add(ball); } }
/** Min clustering... */ public Cluster minMaxAvrClustering() { int nrOfSubmissions = submissions.size(); boolean minClustering = (Options.MIN_CLUSTER == this.program.get_clusterType()); boolean maxClustering = (Options.MAX_CLUSTER == this.program.get_clusterType()); SimilarityMatrix simMatrix = this.program.get_similarity(); ArrayList<Cluster> clusters = new ArrayList<Cluster>(submissions.size()); for (int i = 0; i < nrOfSubmissions; i++) clusters.add(new Cluster(i, this)); while (clusters.size() > 1) { int indexA = -1, indexB = -1; float maxSim = -1; int nrOfClusters = clusters.size(); // find similarity for (int a = 0; a < (nrOfClusters - 1); a++) { Cluster cluster = clusters.get(a); for (int b = a + 1; b < nrOfClusters; b++) { float sim; if (minClustering) sim = cluster.maxSimilarity(clusters.get(b), simMatrix); else if (maxClustering) sim = cluster.minSimilarity(clusters.get(b), simMatrix); else sim = cluster.avrSimilarity(clusters.get(b), simMatrix); if (sim > maxSim) { maxSim = sim; indexA = a; indexB = b; } } } if (maxSim > maxMergeValue) maxMergeValue = maxSim; // now merge these clusters Cluster clusterA = clusters.get(indexA); Cluster clusterB = clusters.get(indexB); clusters.remove(clusterA); clusters.remove(clusterB); clusters.add(new Cluster(clusterA, clusterB, maxSim, this)); } return clusters.get(0); }
private void writeGeographicImageGeoKeys(ArrayList<TiffIFDEntry> ifds, AVList params) throws IOException { long offset = this.theChannel.position(); if (isImage(params) && isGeographic(params)) { int epsg = GeoTiff.GCS.WGS_84; if (params.hasKey(AVKey.PROJECTION_EPSG_CODE)) epsg = (Integer) params.getValue(AVKey.PROJECTION_EPSG_CODE); short[] values = new short[] { // GeoKeyDirectory header GeoTiff.GeoKeyHeader.KeyDirectoryVersion, GeoTiff.GeoKeyHeader.KeyRevision, GeoTiff.GeoKeyHeader.MinorRevision, 0, // IMPORTANT!! we will update count below, after the array initialization // end of header - // geo keys array /* key 1 */ GeoTiff.GeoKey.ModelType, 0, 1, GeoTiff.ModelType.Geographic, /* key 2 */ GeoTiff.GeoKey.RasterType, 0, 1, (short) (0xFFFF & GeoTiff.RasterType.RasterPixelIsArea), /* key 3 */ GeoTiff.GeoKey.GeographicType, 0, 1, (short) (0xFFFF & epsg), /* key 4 */ GeoTiff.GeoKey.GeogAngularUnits, 0, 1, GeoTiff.Unit.Angular.Angular_Degree }; // IMPORTANT!! update count - number of geokeys values[3] = (short) (values.length / 4); byte[] bytes = this.getBytes(values); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add( new TiffIFDEntry(GeoTiff.Tag.GEO_KEY_DIRECTORY, Tiff.Type.SHORT, values.length, offset)); } }
/** Reads next frame image */ protected void readImage() { ix = readShort(); // (sub)image position & size iy = readShort(); iw = readShort(); ih = readShort(); int packed = read(); lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace = (packed & 0x40) != 0; // 2 - interlace flag // 3 - sort flag // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color table size if (lctFlag) { lct = readColorTable(lctSize); // read table act = lct; // make local table active } else { act = gct; // make global table active if (bgIndex == transIndex) bgColor = 0; } int save = 0; if (transparency) { save = act[transIndex]; act[transIndex] = 0; // set transparent color if specified } if (act == null) { status = STATUS_FORMAT_ERROR; // no color table defined } if (err()) return; decodeImageData(); // decode pixel data skip(); if (err()) return; frameCount++; // create new image to receive frame data image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); setPixels(); // transfer pixel data to image frames.add(new GifFrame(image, delay)); // add image to frame list if (transparency) { act[transIndex] = save; } resetFrame(); }
void turnOnFadeLog() throws IOException { Global.log("Connecting to fade log..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + Global.fadeLogPort() + "..."); try { fadeLog = new ClientByteStream(ip, Global.fadeLogPort(), 12); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { String s = null; byte[] data = null; try { data = fadeLog.read(); if (data == null) return; s = fadeLog.readLine(); } catch (IOException ex) { System.err.println("Error reading from fade log: " + ex); Global.onException(); stop(); return; } if (s == null) return; ByteBuffer bb = ByteBuffer.wrap(data); float x = bb.getFloat(); float y = bb.getFloat(); Color color = Global.IntToColor(bb.getInt()); // if fade color is same as ship color, play power-up sound if (color.equals(getPlayerShip().fill)) Sounds.powerUp.play(); fadeLog(s, x, y, color); } })); }
private ArrayList<Cluster> getClusters(Cluster clustering, float threshold) { ArrayList<Cluster> clusters = new ArrayList<Cluster>(); // First determine the clusters Stack<Cluster> stack = new Stack<Cluster>(); stack.push(clustering); while (!stack.empty()) { Cluster current = stack.pop(); if (current.size() == 1) { clusters.add(current); // singleton clusters } else { if (current.getSimilarity() >= threshold) { clusters.add(current); } else { // current.size() != 1 !!! stack.push(current.getLeft()); stack.push(current.getRight()); } } } return clusters; }
void turnOnBulletReceiver() throws IOException { Global.log("Turning on bullet receiver..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + (Global.bulletPort()) + "..."); try { bulletStream = new ClientByteStream(ip, Global.bulletPort(), Bullet.bufferSize()); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return true; } public float FPS() { return Global.ReceiveFPS * 20; } public void run() { byte[] data = null; try { data = bulletStream.read(); } catch (IOException ex) { System.err.println("Bullet receiver error: " + ex); Global.onException(); stop(); return; } if (data == null) return; Bullet toSpawn = Bullet.fromBytes(data); Ship find = cShip.get(toSpawn.getFill()); if (find == null) { for (Ship s : turrets) { if (s.fill.equals(toSpawn.getFill())) { find = s; break; } } } if (find == null) return; find.getBulletSet().add(toSpawn); } })); }
/** Add a ball to the ArrayList at current mouse position */ public void addBall() { // Store current mouse position x1 = mouseX; y1 = mouseY; // Get a random offset for the ball int xDiff = (int) random(-10, 10); int yDiff = (int) random(-10, 10); // Add the mouse's (x,y) and the random offset int x = mouseX + xDiff; int y = mouseY + yDiff; // Create new ball Ball b = new Ball(x, y, ballSize); b.STEM = stems; b.attract = kelly; balls.add(b); }
public void recreateTree() { System.out.println("Recreating tree"); ArrayList nodes = new ArrayList(); String attr, crit, result; int level; node leaf; while (!list.isEmpty()) { if (((String) list.remove(0)).compareTo("Node") == 0) { leaf = new node(); attr = (String) list.remove(0); // System.out.println("ATTR:"+attr); crit = (String) list.remove(0); try { level = (new Double(crit)).intValue(); crit = null; } catch (Exception e) { // System.out.println("crit:"+crit); level = (new Double((String) list.remove(0))).intValue(); } // System.out.println("lvl:"+level); if (level > depth) { depth = level; } if (((String) list.get(0)).compareTo("Node") != 0) { result = (String) list.remove(0); leaf.setResult(result); } leaf.setSplitCriteria(crit, 0); leaf.setLevel(level); leaf.setAttr(attr); if (attr.compareTo("_root") == 0) { root = leaf; } else { nodes.add(leaf); } } } depth++; levelCount(nodes); System.out.println("Linking " + nodes.size() + " tree nodes"); trav(nodes, root); }
void turnOnTurretReceiver() throws IOException { Global.log("Turning on turret receiver..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + Global.turretPort() + "..."); try { turretStream = new ClientByteStream(ip, Global.turretPort(), Ship.bufferSize()); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { byte[] data = null; String name = null; try { data = turretStream.read(); name = turretStream.readLine(); } catch (IOException ex) { System.err.println("Cannot read info from turret stream"); Global.onException(); stop(); return; } if (data == null) return; Ship s = new Ship(name, Global.transparent); s.setDesign(new Design.Turret(s)); s.fromBytes(data, false); addShip(s); } })); }
private boolean showDialog() { String[] types = {"RAW", "JPEG", "ZLIB"}; GenericDialog gd = new GenericDialog("Generate Bricks"); gd.addChoice("FileType", types, filetype); gd.addNumericField("JPEG quality", jpeg_quality, 0); gd.addNumericField("Max file size (MB)", bdsizelimit, 0); int[] wlist = WindowManager.getIDList(); if (wlist == null) return false; String[] titles = new String[wlist.length]; for (int i = 0; i < wlist.length; i++) titles[i] = ""; int tnum = 0; for (int i = 0; i < wlist.length; i++) { ImagePlus imp = WindowManager.getImage(wlist[i]); if (imp != null) { titles[tnum] = imp.getTitle(); tnum++; } } gd.addChoice("Source image: ", titles, titles[0]); gd.showDialog(); if (gd.wasCanceled()) return false; filetype = types[gd.getNextChoiceIndex()]; jpeg_quality = (int) gd.getNextNumber(); if (jpeg_quality > 100) jpeg_quality = 100; if (jpeg_quality < 0) jpeg_quality = 0; bdsizelimit = (int) gd.getNextNumber(); int id = gd.getNextChoiceIndex(); lvImgTitle = new ArrayList<String>(); lvImgTitle.add(titles[id]); Prefs.set("filetype.string", filetype); Prefs.set("jpeg_quality.int", jpeg_quality); Prefs.set("bdsizelimit.int", bdsizelimit); return true; }
void turnOnServerTime() throws IOException { Global.log("Turning on server time..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + Global.serverTimePort() + "..."); try { serverTime = new ClientByteStream(ip, Global.serverTimePort(), 2); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { byte[] data = null; try { data = serverTime.read(); } catch (IOException ex) { System.err.println("Error reading from server time: " + ex); Global.onException(); stop(); return; } if (data == null) return; ByteBuffer bb = ByteBuffer.wrap(data); short time = bb.getShort(); Game.activeGame().getHud().setTime(time); } })); }
void turnOnChatLog() throws IOException { Global.log("Connecting to chat log..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + Global.chatLogPort() + "..."); try { chatLog = new ClientByteStream(ip, Global.chatLogPort(), 1); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { String s = null; try { s = chatLog.readLine(); } catch (IOException ex) { System.err.println("Error reading from chat log: " + ex); Global.onException(); stop(); return; } if (s == null) return; log(s); } })); }
// Constructor connection receiving a socket number public ClientGUI(String host, int port, int udpPort) { super("Clash of Clans"); defaultPort = port; defaultUDPPort = udpPort; defaultHost = host; // the server name and the port number JPanel serverAndPort = new JPanel(new GridLayout(1, 5, 1, 3)); tfServer = new JTextField(host); tfPort = new JTextField("" + port); tfPort.setHorizontalAlignment(SwingConstants.RIGHT); // CHAT COMPONENTS chatStatus = new JLabel("Please login first", SwingConstants.LEFT); chatField = new JTextField(18); chatField.setBackground(Color.WHITE); JPanel chatControls = new JPanel(); chatControls.add(chatStatus); chatControls.add(chatField); chatControls.setBounds(0, 0, 200, 50); chatArea = new JTextArea("Welcome to the Chat room\n", 80, 80); chatArea.setEditable(false); JScrollPane jsp = new JScrollPane(chatArea); jsp.setBounds(0, 50, 200, 550); JPanel chatPanel = new JPanel(null); chatPanel.setSize(1000, 600); chatPanel.add(chatControls); chatPanel.add(jsp); // LOGIN COMPONENTS mainLogin = new MainPanel(); mainLogin.add(new JLabel("Main Login")); usernameField = new JTextField("user", 15); passwordField = new JTextField("password", 15); login = new CButton("Login"); login.addActionListener(this); sideLogin = new SidePanel(new FlowLayout(FlowLayout.LEFT)); sideLogin.add(usernameField); sideLogin.add(passwordField); sideLogin.add(login); // MAIN MENU COMPONENTS mainMenu = new MainPanel(); mmLabel = new JLabel("Main Menu"); timer = new javax.swing.Timer(1000, this); mainMenu.add(mmLabel); sideMenu = new SidePanel(new FlowLayout(FlowLayout.LEFT)); cmButton = new CButton("Customize Map"); tmButton = new CButton("Troop Movement"); gsButton = new CButton("Game Start"); logout = new CButton("Logout"); cmButton.addActionListener(this); tmButton.addActionListener(this); gsButton.addActionListener(this); logout.addActionListener(this); sideMenu.add(cmButton); // sideMenu.add(tmButton); sideMenu.add(gsButton); sideMenu.add(logout); // CM COMPONENTS mainCM = new MainPanel(new GridLayout(mapSize, mapSize)); tiles = new Tile[mapSize][mapSize]; int tileSize = mainCM.getWidth() / mapSize; for (int i = 0; i < mapSize; i++) { tiles[i] = new Tile[mapSize]; for (int j = 0; j < mapSize; j++) { tiles[i][j] = new Tile(i, j); tiles[i][j].setPreferredSize(new Dimension(tileSize, tileSize)); tiles[i][j].setSize(tileSize, tileSize); tiles[i][j].addActionListener(this); if ((i + j) % 2 == 0) tiles[i][j].setBackground(new Color(102, 255, 51)); else tiles[i][j].setBackground(new Color(51, 204, 51)); mainCM.add(tiles[i][j]); } } sideCM = new SidePanel(new FlowLayout(FlowLayout.LEFT)); cmBack = new CButton("Main Menu"); cmBack.setSize(150, 30); cmBack.setPreferredSize(new Dimension(150, 30)); cmBack.addActionListener(this); sideCM.add(cmBack); // TM COMPONENTS mainTM = new MainPanel(null); mapTM = new Map(600); mapTM.setPreferredSize(new Dimension(600, 600)); mapTM.setSize(600, 600); mapTM.setBounds(0, 0, 600, 600); mainTM.add(mapTM); sideTM = new SidePanel(new FlowLayout(FlowLayout.LEFT)); tmBack = new CButton("Main Menu"); tmBack.setSize(150, 30); tmBack.setPreferredSize(new Dimension(150, 30)); tmBack.addActionListener(this); sideTM.add(tmBack); JRadioButton button; ButtonGroup group; ub = new ArrayList<JRadioButton>(); group = new ButtonGroup(); button = new JRadioButton("Barbarian"); button.addActionListener(this); ub.add(button); sideTM.add(button); group.add(button); button = new JRadioButton("Archer"); button.addActionListener(this); ub.add(button); sideTM.add(button); group.add(button); createBuildings(); bb = new ArrayList<JRadioButton>(); group = new ButtonGroup(); JRadioButton removeButton = new JRadioButton("Remove Building"); bb.add(removeButton); sideCM.add(removeButton); group.add(removeButton); for (int i = 0; i < bList.size(); i++) { button = new JRadioButton(bList.get(i).getName() + '-' + bList.get(i).getQuantity()); bb.add(button); sideCM.add(button); group.add(button); } mainPanels = new MainPanel(new CardLayout()); mainPanels.add(mainLogin, "Login"); mainPanels.add(mainMenu, "Menu"); mainPanels.add(mainCM, "CM"); mainPanels.add(mainTM, "TM"); sidePanels = new SidePanel(new CardLayout()); sidePanels.add(sideLogin, "Login"); sidePanels.add(sideMenu, "Menu"); sidePanels.add(sideCM, "CM"); sidePanels.add(sideTM, "TM"); JPanel mainPanel = new JPanel(null); mainPanel.setSize(1000, 600); mainPanel.add(sidePanels); mainPanel.add(mainPanels); mainPanel.add(chatPanel); add(mainPanel, BorderLayout.CENTER); try { setIconImage(ImageIO.read(new File("images/logo.png"))); } catch (IOException exc) { exc.printStackTrace(); } setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(1000, 600); setVisible(true); setResizable(false); chatField.requestFocus(); }
public void actionPerformed(ActionEvent e) { Object o = e.getSource(); for (JRadioButton u : ub) { if (o == u) { mapTM.setUnitType(u.getText()); System.out.println("Set unit type - " + u.getText()); return; } } if (o == timer) { /* mmLabel.setText("Main Menu ("+(cdTime--)+")"); if(cdTime == 0){ timer.stop(); gsButton.setText("Game Start"); mmLabel.setText("Main Menu"); ArrayList<Building> bArr = new ArrayList<Building>(); String temp = "Elixir Collector-24,8-960|Elixir Collector-31,8-960|Gold Mine-17,10-960|Elixir Collector-25,21-960|Elixir Collector-11,22-960"; String[] bs = temp.split("\\|"); for(String b : bs){ String[] bParts = b.split("-"); String[] cParts = bParts[1].split(","); int x = Integer.parseInt(cParts[0].trim()); int y = Integer.parseInt(cParts[1].trim()); Building tb = new Building(bParts[0], new Coordinate(x,y)); tb.setHp(Integer.parseInt(bParts[2].trim())); bArr.add(tb); } mapTM.setBuildings(bArr); switchCards("TM"); } */ return; } if (o == gsButton) { if (timer.isRunning()) { // timer.stop(); gsButton.setText("Game Start"); mmLabel.setText("Main Menu"); // sends the leave command client.sendUDP("leave~" + unameUDP); return; } // sends the joinlobby command client.sendUDP("joinlobby~" + unameUDP); // gsButton.setText("Game Stop"); String serverResp = client.receiveUDP(); if (serverResp.trim().equals("false")) { // place false handler here } else { String[] enemies = serverResp.trim().split(","); ArrayList<Building> bArr = new ArrayList<Building>(); String mapConfig = getBaseConfig(enemies[0]); String[] bs = mapConfig.split("\\|"); for (String b : bs) { String[] bParts = b.split("-"); String[] cParts = bParts[1].split(","); int x = Integer.parseInt(cParts[0].trim()); int y = Integer.parseInt(cParts[1].trim()); Building tb = new Building(bParts[0], new Coordinate(x, y)); tb.setHp(Integer.parseInt(bParts[2].trim())); bArr.add(tb); } mapTM.setBuildings(bArr); switchCards("TM"); } // System.out.println(serverResp); // cdTime = 10; // timer.start(); return; } if (o == logout) { client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, "")); chatArea.setText(""); switchCards("Login"); return; } if (o == cmButton) { String baseConfig = getBaseConfig(); System.out.println("base config: " + baseConfig); for (int i = 0; i < mapSize; i++) { for (int j = 0; j < mapSize; j++) { tiles[i][j].setValue(""); } } if (!baseConfig.equals("")) { String[] bs = baseConfig.split("\\|"); for (String b : bs) { String[] bParts = b.split("-"); String[] cParts = bParts[1].split(","); int x = Integer.parseInt(cParts[0].trim()); int y = Integer.parseInt(cParts[1].trim()); int index = 0; for (int i = 0; i < bb.size(); i++) { if (bb.get(i).getText().split("-")[0].trim().equals(bParts[0])) { index = i; break; } } insertBuilding(y, x, index); } } switchCards("CM"); return; } if (o == tmButton) { ArrayList<Building> bArr = new ArrayList<Building>(); for (int i = 0; i < 40; i++) { for (int j = 0; j < 40; j++) { if (tiles[i][j].getValue().equals("") || tiles[i][j].getValue().contains("-")) { continue; } // weird part here bArr.add(new Building(tiles[i][j].getValue(), new Coordinate(j, i))); } } mapTM.setBuildings(bArr); switchCards("TM"); return; } // if it the who is in button if (o == whoIsIn) { client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, "")); return; } if (o == cmBack) { ArrayList<Building> bArr = new ArrayList<Building>(); for (int i = 0; i < 40; i++) { for (int j = 0; j < 40; j++) { if (tiles[i][j].getValue().equals("") || tiles[i][j].getValue().contains("-")) { continue; } // weird part here bArr.add(new Building(tiles[i][j].getValue(), new Coordinate(j, i))); } } String temp = "mapdata~" + unameUDP + "~"; int tileCount = 40; int dim = 600; int tileDim = (int) (dim / tileCount); int counter = 0; for (Building b : bArr) { int x, y, hp; x = b.getPos().getX() / tileDim; y = b.getPos().getY() / tileDim; hp = b.getHp(); temp += b.getName() + "-" + x + "," + y + "-" + hp + "|"; counter += 1; } if (counter > 0) { temp = temp.substring(0, temp.length() - 1); // removes the last '|' } else { temp += "none"; } client.sendUDP(temp); // allows saving of the current state of the map into the user's account switchCards("Menu"); return; } if (o == tmBack) { switchCards("Menu"); return; } for (int i = 0; i < 40; i++) { for (int j = 0; j < 40; j++) { if (o == tiles[i][j]) { for (int k = 0; k < bb.size(); k++) { if (bb.get(k).isSelected()) { if (bb.get(k).getText().equals("Remove Building")) { removeBuilding(i, j); return; } insertBuilding(i, j, k); // JOptionPane.showMessageDialog(null, bb.get(k).getText()); return; } } // JOptionPane.showMessageDialog(null, "i-"+i+" j-"+j); return; } } } // ok it is coming from the JTextField if (connected) { // just have to send the message client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, chatField.getText())); chatField.setText(""); return; } if (o == login) { // ok it is a connection request String username = usernameField.getText().trim(); String password = passwordField.getText().trim(); // empty username ignore it if (username.length() == 0) return; // empty serverAddress ignore it String server = tfServer.getText().trim(); if (server.length() == 0) return; // empty or invalid port numer, ignore it String portNumber = tfPort.getText().trim(); if (portNumber.length() == 0) return; int port = 0; try { port = Integer.parseInt(portNumber); } catch (Exception en) { return; // nothing I can do if port number is not valid } // try creating a new Client with GUI client = new Client(server, port, username, password, this); // test if we can start the Client if (!client.start()) return; unameUDP = username; switchCards("Menu"); // fetching of the base_config string from the database chatField.setText(""); chatArea.setText(""); } }
private void writeGrayscaleImage(BufferedImage image, AVList params) throws IOException { int type = image.getType(); int bitsPerSample = (BufferedImage.TYPE_USHORT_GRAY == type) ? Tiff.BitsPerSample.MONOCHROME_UINT16 : Tiff.BitsPerSample.MONOCHROME_UINT8; int numBands = image.getSampleModel().getNumBands(); // well, numBands for GrayScale images must be 1 int bytesPerSample = numBands * bitsPerSample / Byte.SIZE; this.writeTiffHeader(); // write the image data... int numRows = image.getHeight(); int numCols = image.getWidth(); int[] stripCounts = new int[numRows]; int[] stripOffsets = new int[numRows]; ByteBuffer dataBuff = ByteBuffer.allocateDirect(numCols * bytesPerSample); Raster rast = image.getRaster(); for (int i = 0; i < numRows; i++) { stripOffsets[i] = (int) this.theChannel.position(); stripCounts[i] = numCols * bytesPerSample; int[] rowData = rast.getPixels(0, i, image.getWidth(), 1, (int[]) null); dataBuff.clear(); if (BufferedImage.TYPE_USHORT_GRAY == type) { for (int j = 0; j < numCols * numBands; j++) { this.putUnsignedShort(dataBuff, rowData[j]); } } else if (BufferedImage.TYPE_BYTE_GRAY == type) { for (int j = 0; j < numCols * numBands; j++) { this.putUnsignedByte(dataBuff, rowData[j]); } } dataBuff.flip(); this.theChannel.write(dataBuff); } // write out values for the tiff tags and build up the IFD. These are supposed to be sorted; for // now // do this manually here. ArrayList<TiffIFDEntry> ifds = new ArrayList<TiffIFDEntry>(10); ifds.add(new TiffIFDEntry(Tiff.Tag.IMAGE_WIDTH, Tiff.Type.LONG, 1, numCols)); ifds.add(new TiffIFDEntry(Tiff.Tag.IMAGE_LENGTH, Tiff.Type.LONG, 1, numRows)); ifds.add(new TiffIFDEntry(Tiff.Tag.BITS_PER_SAMPLE, Tiff.Type.SHORT, 1, bitsPerSample)); ifds.add(new TiffIFDEntry(Tiff.Tag.COMPRESSION, Tiff.Type.LONG, 1, Tiff.Compression.NONE)); ifds.add( new TiffIFDEntry( Tiff.Tag.PHOTO_INTERPRETATION, Tiff.Type.SHORT, 1, Tiff.Photometric.Grayscale_BlackIsZero)); ifds.add( new TiffIFDEntry(Tiff.Tag.SAMPLE_FORMAT, Tiff.Type.SHORT, 1, Tiff.SampleFormat.UNSIGNED)); long offset = this.theChannel.position(); dataBuff = ByteBuffer.allocateDirect(stripOffsets.length * INTEGER_SIZEOF); for (int stripOffset : stripOffsets) { dataBuff.putInt(stripOffset); } dataBuff.flip(); this.theChannel.write(dataBuff); ifds.add(new TiffIFDEntry(Tiff.Tag.STRIP_OFFSETS, Tiff.Type.LONG, stripOffsets.length, offset)); ifds.add(new TiffIFDEntry(Tiff.Tag.SAMPLES_PER_PIXEL, Tiff.Type.SHORT, 1, numBands)); ifds.add(new TiffIFDEntry(Tiff.Tag.ROWS_PER_STRIP, Tiff.Type.LONG, 1, 1)); offset = this.theChannel.position(); dataBuff.clear(); // stripOffsets and stripCounts are same length by design; can reuse the // ByteBuffer... for (int stripCount : stripCounts) { dataBuff.putInt(stripCount); } dataBuff.flip(); this.theChannel.write(dataBuff); ifds.add( new TiffIFDEntry(Tiff.Tag.STRIP_BYTE_COUNTS, Tiff.Type.LONG, stripCounts.length, offset)); this.appendGeoTiff(ifds, params); this.writeIFDs(ifds); }
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(); } }
/** * Loads PNG files and returns the result as an int[][]. The only PNG formats permitted are those * with up to 256 grays (including simple black and white) or indexed colors from an up to * 256-sized color table. Each integer value represents the gray level or the color table index * value of the pixel. The Y dimension is not flipped. */ public static int[][] loadPNGFile(InputStream str) throws IOException { // read the bytes into a byte array BufferedInputStream stream = new BufferedInputStream(str); ArrayList list = new ArrayList(); int count = 0; while (true) { byte[] buffer = new byte[16384 * 16]; int len = stream.read(buffer); if (len <= 0) // all done break; else if (len < buffer.length) { byte[] buf2 = new byte[len]; System.arraycopy(buffer, 0, buf2, 0, len); buffer = buf2; } count += len; list.add(buffer); } byte[] data = new byte[count]; int cur = 0; for (int i = 0; i < list.size(); i++) { byte[] b = (byte[]) (list.get(i)); System.arraycopy(b, 0, data, cur, b.length); cur += b.length; } // Next convert the byte array to a buffered image BufferedImage image = ((ToolkitImage) (new ImageIcon(data).getImage())).getBufferedImage(); // Is the color model something we can use? int type = image.getType(); if (type == BufferedImage.TYPE_BYTE_BINARY || type == BufferedImage.TYPE_BYTE_GRAY) { int w = image.getWidth(); int h = image.getHeight(); int[][] result = new int[w][h]; // obviously this could be done more efficiently for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) result[i][j] = (image.getRGB(i, j) & 0xFF); return result; } else if (type == BufferedImage.TYPE_BYTE_INDEXED) { Raster raster = image.getRaster(); if (raster.getTransferType() != DataBuffer.TYPE_BYTE) // uh oh throw new IOException("Input Stream must contain an image with byte data if indexed."); byte[] pixel = new byte[1]; int w = image.getWidth(); int h = image.getHeight(); int[][] result = new int[w][h]; // obviously this could be done more efficiently for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) { result[i][j] = ((byte[]) (raster.getDataElements(i, j, pixel)))[0]; if (result[i][j] < 0) result[i][j] += 256; } return result; } // else if (type == TYPE_USHORT_GRAY) // at present we don't handle shorts // { // } else throw new IOException( "Input Stream must contain a binary, byte-sized grayscale, or byte-sized indexed color scheme: " + image); }
private void appendGeoTiff(ArrayList<TiffIFDEntry> ifds, AVList params) throws IOException, IllegalArgumentException { if (null == params || 0 == params.getEntries().size()) { String reason = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().finest(Logging.getMessage("GeotiffWriter.GeoKeysMissing", reason)); return; } long offset = this.theChannel.position(); if (params.hasKey(AVKey.DISPLAY_NAME)) { String value = params.getStringValue(AVKey.DISPLAY_NAME); if (null != value && 0 < value.trim().length()) { offset = this.theChannel.position(); byte[] bytes = value.trim().getBytes(); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add(new TiffIFDEntry(Tiff.Tag.DOCUMENT_NAME, Tiff.Type.ASCII, bytes.length, offset)); } } if (params.hasKey(AVKey.DESCRIPTION)) { String value = params.getStringValue(AVKey.DESCRIPTION); if (null != value && 0 < value.trim().length()) { offset = this.theChannel.position(); byte[] bytes = value.trim().getBytes(); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add( new TiffIFDEntry(Tiff.Tag.IMAGE_DESCRIPTION, Tiff.Type.ASCII, bytes.length, offset)); } } if (params.hasKey(AVKey.VERSION)) { String value = params.getStringValue(AVKey.VERSION); if (null != value && 0 < value.trim().length()) { offset = this.theChannel.position(); byte[] bytes = value.trim().getBytes(); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add( new TiffIFDEntry(Tiff.Tag.SOFTWARE_VERSION, Tiff.Type.ASCII, bytes.length, offset)); } } if (params.hasKey(AVKey.DATE_TIME)) { String value = params.getStringValue(AVKey.DATE_TIME); if (null != value && 0 < value.trim().length()) { offset = this.theChannel.position(); byte[] bytes = value.getBytes(); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add(new TiffIFDEntry(Tiff.Tag.DATE_TIME, Tiff.Type.ASCII, bytes.length, offset)); } } if (params.hasKey(AVKey.SECTOR)) { if (params.hasKey(AVKey.PIXEL_WIDTH) && params.hasKey(AVKey.PIXEL_HEIGHT)) { offset = this.theChannel.position(); double[] values = new double[] { (Double) params.getValue(AVKey.PIXEL_WIDTH), (Double) params.getValue(AVKey.PIXEL_HEIGHT), isElevation(params) ? 1d : 0d }; byte[] bytes = this.getBytes(values); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add( new TiffIFDEntry( GeoTiff.Tag.MODEL_PIXELSCALE, Tiff.Type.DOUBLE, values.length, offset)); } if (params.hasKey(AVKey.WIDTH) && params.hasKey(AVKey.HEIGHT)) { offset = this.theChannel.position(); double w = (Integer) params.getValue(AVKey.WIDTH); double h = (Integer) params.getValue(AVKey.HEIGHT); Sector sec = (Sector) params.getValue(AVKey.SECTOR); double[] values = new double[] { // i , j, k=0, x, y, z=0 0d, 0d, 0d, sec.getMinLongitude().degrees, sec.getMaxLatitude().degrees, 0d, w - 1, 0d, 0d, sec.getMaxLongitude().degrees, sec.getMaxLatitude().degrees, 0d, w - 1, h - 1, 0d, sec.getMaxLongitude().degrees, sec.getMinLatitude().degrees, 0d, 0d, h - 1, 0d, sec.getMinLongitude().degrees, sec.getMinLatitude().degrees, 0d, }; byte[] bytes = this.getBytes(values); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add( new TiffIFDEntry(GeoTiff.Tag.MODEL_TIEPOINT, Tiff.Type.DOUBLE, values.length, offset)); } // Tiff.Tag.MODEL_TRANSFORMATION excludes Tiff.Tag.MODEL_TIEPOINT & Tiff.Tag.MODEL_PIXELSCALE if (params.hasKey(AVKey.MISSING_DATA_SIGNAL) || params.hasKey(AVKey.MISSING_DATA_REPLACEMENT)) { offset = this.theChannel.position(); Object nodata = params.hasKey(AVKey.MISSING_DATA_SIGNAL) ? params.getValue(AVKey.MISSING_DATA_SIGNAL) : params.getValue(AVKey.MISSING_DATA_REPLACEMENT); String value = "" + nodata + "\0"; byte[] bytes = value.getBytes(); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add(new TiffIFDEntry(GeoTiff.Tag.GDAL_NODATA, Tiff.Type.ASCII, bytes.length, offset)); } if (params.hasKey(AVKey.COORDINATE_SYSTEM)) { String cs = params.getStringValue(AVKey.COORDINATE_SYSTEM); if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { if (isElevation(params)) this.writeGeographicElevationGeoKeys(ifds, params); else this.writeGeographicImageGeoKeys(ifds, params); } else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(cs)) { String msg = Logging.getMessage("GeotiffWriter.FeatureNotImplementedd", cs); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); // TODO extract PCS (Projection Coordinate System) } else { String msg = Logging.getMessage("GeotiffWriter.UnknownCoordinateSystem", cs); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } } } }
public WebcamCaptureAndFadePanel(String saveDir, String layout) { System.out.println("Using " + saveDir + " as directory for the images."); saveDirectory = saveDir; getImages(); images_used = new ArrayList<Integer>(); images_lastadded = new ArrayList<Integer>(); images_nevershown = new ArrayList<Integer>(); Vector devices = (Vector) CaptureDeviceManager.getDeviceList(null).clone(); Enumeration enumeration = devices.elements(); System.out.println("- Available cameras -"); ArrayList<String> names = new ArrayList<String>(); while (enumeration.hasMoreElements()) { CaptureDeviceInfo cdi = (CaptureDeviceInfo) enumeration.nextElement(); String name = cdi.getName(); if (name.startsWith("vfw:")) { names.add(name); System.out.println(name); } } // String str1 = "vfw:Logitech USB Video Camera:0"; // String str2 = "vfw:Microsoft WDM Image Capture (Win32):0"; if (names.size() == 0) { JOptionPane.showMessageDialog( null, "Ingen kamera funnet. " + "Du må koble til et kamera for å kjøre programmet.", "Feil", JOptionPane.ERROR_MESSAGE); System.exit(0); } else if (names.size() > 1) { JOptionPane.showMessageDialog( null, "Fant mer enn 1 kamera. " + "Velger da:\n" + names.get(0), "Advarsel", JOptionPane.WARNING_MESSAGE); } String str2 = names.get(0); di = CaptureDeviceManager.getDevice(str2); ml = di.getLocator(); try { player = Manager.createRealizedPlayer(ml); formatControl = (FormatControl) player.getControl("javax.media.control.FormatControl"); /* Format[] formats = formatControl.getSupportedFormats(); for (int i=0; i<formats.length; i++) System.out.println(formats[i].toString()); */ player.start(); } catch (javax.media.NoPlayerException e) { JOptionPane.showMessageDialog( null, "Klarer ikke å starte" + " programmet pga. feil med kamera. Sjekk at det er koblet til.", "IOException", JOptionPane.ERROR_MESSAGE); System.exit(0); } catch (Exception e) { e.printStackTrace(); System.exit(0); } /* * Layout * * Add * - comp * - imagepanels */ if (layout.equals("1024v2")) { layout1024v2(); } else if (layout.equals("1280")) { layout1280(); } else { layout1024(); } // Capture Window if (captureWindow) { cw = new JFrame("Capture from webcam"); cw.setAlwaysOnTop(true); cw.setSize(sizeCaptureWindow_x, sizeCaptureWindow_y); cw.addKeyListener(new captureWindowKeyListner()); cw.setUndecorated(true); // Add webcam if ((comp = player.getVisualComponent()) != null) { cw.add(comp); } // Add panel to window and set location of window cw.setLocation(cwLocation_x, cwLocation_y); } // Text window cwText = new rotatedText(""); /* * Timer for update */ Timer thread = new Timer(); thread.schedule(new frameUpdateTask(), 0, (1000 / fps)); }
private void writeGeographicElevationGeoKeys(ArrayList<TiffIFDEntry> ifds, AVList params) throws IOException { long offset = this.theChannel.position(); if (isElevation(params) && isGeographic(params)) { int epsg = GeoTiff.GCS.WGS_84; if (params.hasKey(AVKey.PROJECTION_EPSG_CODE)) epsg = (Integer) params.getValue(AVKey.PROJECTION_EPSG_CODE); int elevUnits = GeoTiff.Unit.Linear.Meter; if (params.hasKey(AVKey.ELEVATION_UNIT)) { if (AVKey.UNIT_FOOT.equals(params.getValue(AVKey.ELEVATION_UNIT))) elevUnits = GeoTiff.Unit.Linear.Foot; } int rasterType = GeoTiff.RasterType.RasterPixelIsArea; if (params.hasKey(AVKey.RASTER_PIXEL) && AVKey.RASTER_PIXEL_IS_POINT.equals(params.getValue(AVKey.RASTER_PIXEL))) rasterType = GeoTiff.RasterType.RasterPixelIsPoint; short[] values = new short[] { // GeoKeyDirectory header GeoTiff.GeoKeyHeader.KeyDirectoryVersion, GeoTiff.GeoKeyHeader.KeyRevision, GeoTiff.GeoKeyHeader.MinorRevision, 0, // IMPORTANT!! we will update count below, after the array initialization // end of header - // geo keys array /* key 1 */ GeoTiff.GeoKey.ModelType, 0, 1, GeoTiff.ModelType.Geographic, /* key 2 */ // TODO: Replace GeoTiff.RasterType.RasterPixelIsPoint GeoTiff.GeoKey.RasterType, 0, 1, (short) (0xFFFF & rasterType), /* key 3 */ GeoTiff.GeoKey.GeographicType, 0, 1, (short) (0xFFFF & epsg), /* key 4 */ GeoTiff.GeoKey.GeogAngularUnits, 0, 1, GeoTiff.Unit.Angular.Angular_Degree, /* key 5 */ GeoTiff.GeoKey.VerticalCSType, 0, 1, GeoTiff.VCS.WGS_84_ellipsoid, /* key 6 */ GeoTiff.GeoKey.VerticalUnits, 0, 1, (short) (0xFFFF & elevUnits), }; // IMPORTANT!! update count - number of geokeys values[3] = (short) (values.length / 4); byte[] bytes = this.getBytes(values); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add( new TiffIFDEntry(GeoTiff.Tag.GEO_KEY_DIRECTORY, Tiff.Type.SHORT, values.length, offset)); } }