root / trunk / code / projects / colonet / ColonetGUI / Colonet.java @ 327
History | View | Annotate | Download (40.8 KB)
1 |
//
|
---|---|
2 |
// Colonet.java
|
3 |
//
|
4 |
|
5 |
import javax.swing.*; |
6 |
import javax.swing.event.*; |
7 |
import javax.imageio.*; |
8 |
import java.awt.*; |
9 |
import java.awt.image.*; |
10 |
import java.awt.event.*; |
11 |
import java.net.*; |
12 |
import java.io.*; |
13 |
import java.util.Random; |
14 |
|
15 |
|
16 |
/**
|
17 |
* The Colonet Graphical User Interface Applet for use locally and over an internet connection.
|
18 |
* @author Gregory Tress
|
19 |
*
|
20 |
*
|
21 |
*/
|
22 |
public class Colonet extends JApplet implements ActionListener, MouseInputListener, KeyListener, Runnable { |
23 |
|
24 |
final int CANVAS_SIZE = 500; //the applet may be slow if the canvas gets too large |
25 |
final int BUFFER = 50; |
26 |
final int RADIUS = 30; |
27 |
|
28 |
// Connection
|
29 |
JTextField txtHost;
|
30 |
JTextField txtPort;
|
31 |
JButton btnConnect;
|
32 |
JButton btnGraph;
|
33 |
JLabel lblConnectionStatus;
|
34 |
JTextArea txtMatrix;
|
35 |
JTextArea txtInfo;
|
36 |
JPanel panelConnect;
|
37 |
JPanel panelServerInterface;
|
38 |
|
39 |
// South
|
40 |
JPanel panelSouth;
|
41 |
JTextArea log;
|
42 |
JScrollPane spLog;
|
43 |
|
44 |
// Control
|
45 |
JPanel panelControl;
|
46 |
JTabbedPane tabPaneControl;
|
47 |
JPanel panelRobotControl;
|
48 |
JPanel panelRobotDirection;
|
49 |
JPanel panelRobotDirectionButtons;
|
50 |
JPanel panelRobotCommands;
|
51 |
JButton btnF, btnB, btnL, btnR, btnActivate;
|
52 |
JComboBox cmbRobotNum;
|
53 |
JLabel lblBattery;
|
54 |
JPanel panelBattery;
|
55 |
VectorController vectorController; |
56 |
BufferedImage imageVectorControl;
|
57 |
JButton btnCommand_StopTask;
|
58 |
JButton btnCommand_ResumeTask;
|
59 |
JButton btnCommand_ChargeNow;
|
60 |
JButton btnCommand_StopCharging;
|
61 |
|
62 |
// Task Manager
|
63 |
JPanel panelTaskManager;
|
64 |
JScrollPane spTaskManager;
|
65 |
JPanel panelTaskManagerControls;
|
66 |
JPanel panelTaskManagerControlsPriority;
|
67 |
DefaultListModel taskListModel;
|
68 |
JList taskList;
|
69 |
JButton btnAddTask;
|
70 |
JButton btnRemoveTask;
|
71 |
JButton btnMoveTaskUp;
|
72 |
JButton btnMoveTaskDown;
|
73 |
JButton btnUpdateTasks;
|
74 |
TaskAddWindow taskAddWindow; |
75 |
|
76 |
//Webcam and Graph
|
77 |
WebcamPanel panelWebcam; |
78 |
GraphicsPanel panelGraph; |
79 |
GraphicsConfiguration gc;
|
80 |
volatile BufferedImage image; |
81 |
volatile Graphics2D canvas; |
82 |
int cx, cy;
|
83 |
JTabbedPane tabPaneMain;
|
84 |
|
85 |
|
86 |
Socket socket;
|
87 |
OutputStreamWriter out;
|
88 |
DataUpdater dataUpdater; |
89 |
|
90 |
Font botFont;
|
91 |
Random random = new Random(); |
92 |
volatile int tokenLoc; //the token is currently here |
93 |
volatile int numBots; |
94 |
volatile int selectedBot; //the user has selected this bot |
95 |
volatile Rectangle[] botRect; //contains boundary shapes around bots for click detection |
96 |
volatile int[] xbeeID; |
97 |
|
98 |
Thread drawThread;
|
99 |
Simulator simulator; |
100 |
SelectionIndicator indicator; |
101 |
WebcamLoader webcamLoader; |
102 |
ColonetServerInterface csi; |
103 |
|
104 |
|
105 |
public void init () { |
106 |
// set the default look and feel - choose one
|
107 |
//String laf = UIManager.getSystemLookAndFeelClassName();
|
108 |
String laf = UIManager.getCrossPlatformLookAndFeelClassName(); |
109 |
//String laf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
|
110 |
try {
|
111 |
UIManager.setLookAndFeel(laf);
|
112 |
} catch (UnsupportedLookAndFeelException exc) { |
113 |
System.err.println ("Warning: UnsupportedLookAndFeel: " + laf); |
114 |
} catch (Exception exc) { |
115 |
System.err.println ("Error loading " + laf + ": " + exc); |
116 |
} |
117 |
// We should invoke and wait to avoid browser display difficulties
|
118 |
Runnable r = new Runnable() { |
119 |
public void run() { |
120 |
createAndShowGUI(); |
121 |
} |
122 |
}; |
123 |
try {
|
124 |
SwingUtilities.invokeAndWait(r);
|
125 |
} catch (InterruptedException e) { |
126 |
//Not really sure why we would be in this situation
|
127 |
System.out.println("InterruptedException in init: " + e); |
128 |
} catch (java.lang.reflect.InvocationTargetException e) {
|
129 |
//This could happen for various reasons if there is a problem in createAndShowGUI
|
130 |
e.printStackTrace(); |
131 |
} |
132 |
} |
133 |
|
134 |
public void destroy () { |
135 |
try { drawThread.interrupt(); } catch (Exception e) { } |
136 |
try { indicator.interrupt(); } catch (Exception e) { } |
137 |
} |
138 |
|
139 |
private synchronized void createAndShowGUI () { |
140 |
// init graphical elements
|
141 |
// Get the graphics configuration of the screen to create a buffer
|
142 |
gc = GraphicsEnvironment.getLocalGraphicsEnvironment()
|
143 |
.getDefaultScreenDevice().getDefaultConfiguration(); |
144 |
image = gc.createCompatibleImage(CANVAS_SIZE,CANVAS_SIZE); |
145 |
canvas = image.createGraphics(); |
146 |
canvas.setStroke(new BasicStroke(2)); //set pen width |
147 |
panelGraph = new GraphicsPanel(false, image); //set automatic double-buffering to false. we are doing it manually. |
148 |
panelWebcam = new WebcamPanel();
|
149 |
tabPaneMain = new JTabbedPane(); |
150 |
tabPaneMain.add(panelWebcam, "Webcam");
|
151 |
tabPaneMain.add(panelGraph, "Graph");
|
152 |
|
153 |
// Calculate center of canvas
|
154 |
cx = image.getWidth() / 2;
|
155 |
cy = image.getHeight() / 2;
|
156 |
|
157 |
botFont = new Font("Arial", Font.PLAIN, 14); |
158 |
tokenLoc = 0;
|
159 |
numBots = 0;
|
160 |
selectedBot = 0;
|
161 |
|
162 |
// Connection area
|
163 |
txtMatrix = new JTextArea(); |
164 |
txtMatrix.setBorder(BorderFactory.createTitledBorder("Input Matrix")); |
165 |
txtInfo = new JTextArea(); |
166 |
txtInfo.setBorder(BorderFactory.createTitledBorder("Info")); |
167 |
txtInfo.setEditable(false);
|
168 |
btnGraph = new JButton("Run"); |
169 |
txtHost = new JTextField("roboclub9.frc.ri.cmu.edu"); |
170 |
txtHost.setBorder(BorderFactory.createTitledBorder("Host")); |
171 |
txtPort = new JTextField("10123"); |
172 |
txtPort.setBorder(BorderFactory.createTitledBorder("Port")); |
173 |
btnConnect = new JButton("Connect"); |
174 |
lblConnectionStatus = new JLabel("Status: Offline"); |
175 |
panelConnect = new JPanel(); |
176 |
panelConnect.setLayout(new GridLayout(6,1)); |
177 |
panelConnect.add(lblConnectionStatus); |
178 |
panelConnect.add(txtHost); |
179 |
panelConnect.add(txtPort); |
180 |
panelConnect.add(btnConnect); |
181 |
//panelConnect.add(btnGraph);
|
182 |
panelServerInterface = new JPanel(); |
183 |
panelServerInterface.setLayout(new GridLayout(2,1)); |
184 |
panelServerInterface.add(panelConnect); |
185 |
panelServerInterface.add(txtMatrix); |
186 |
|
187 |
// Robot direction panel
|
188 |
panelRobotDirection = new JPanel(); |
189 |
panelRobotDirectionButtons = new JPanel(); |
190 |
btnF = new JButton("^"); |
191 |
btnB = new JButton("v"); |
192 |
btnL = new JButton("<"); |
193 |
btnR = new JButton(">"); |
194 |
btnActivate = new JButton("o"); |
195 |
panelRobotDirectionButtons.setLayout(new GridLayout(1,5)); |
196 |
panelRobotDirectionButtons.add(btnActivate); |
197 |
panelRobotDirectionButtons.add(btnF); |
198 |
panelRobotDirectionButtons.add(btnB); |
199 |
panelRobotDirectionButtons.add(btnL); |
200 |
panelRobotDirectionButtons.add(btnR); |
201 |
|
202 |
imageVectorControl = gc.createCompatibleImage(395, 220); |
203 |
vectorController = new VectorController(imageVectorControl);
|
204 |
panelRobotDirection.setLayout(new BorderLayout()); |
205 |
panelRobotDirection.add(vectorController, BorderLayout.CENTER);
|
206 |
panelRobotDirection.add(panelRobotDirectionButtons, BorderLayout.SOUTH);
|
207 |
|
208 |
// Robot Control and Commands
|
209 |
panelRobotCommands = new JPanel(); |
210 |
panelRobotCommands.setLayout(new GridLayout(5,2)); |
211 |
cmbRobotNum = new JComboBox(); |
212 |
lblBattery = new JLabel(new BatteryIcon(75, 70, 70)); |
213 |
lblBattery.setPreferredSize(new Dimension(100,100)); |
214 |
btnCommand_StopTask = new JButton("Stop Current Task"); |
215 |
btnCommand_ResumeTask = new JButton("Resume Current Task"); |
216 |
btnCommand_ChargeNow = new JButton("Recharge Now"); |
217 |
btnCommand_StopCharging = new JButton("Stop Recharging"); |
218 |
panelRobotCommands.add(new JLabel("Select Robot to Control: ")); |
219 |
panelRobotCommands.add(cmbRobotNum); |
220 |
panelRobotCommands.add(new JLabel("Battery Level: ")); |
221 |
panelRobotCommands.add(lblBattery); |
222 |
panelRobotCommands.add(btnCommand_StopTask); |
223 |
panelRobotCommands.add(btnCommand_ResumeTask); |
224 |
panelRobotCommands.add(btnCommand_ChargeNow); |
225 |
panelRobotCommands.add(btnCommand_StopCharging); |
226 |
panelRobotControl = new JPanel(); |
227 |
panelRobotControl.setLayout(new GridLayout(2,1)); |
228 |
panelRobotControl.add(panelRobotDirection); |
229 |
panelRobotControl.add(panelRobotCommands); |
230 |
lblBattery.setIcon(new BatteryIcon(75, lblBattery.getMaximumSize().height, |
231 |
lblBattery.getMaximumSize().height)); |
232 |
|
233 |
// Task Manager
|
234 |
panelTaskManager = new JPanel(); |
235 |
panelTaskManager.setLayout(new BorderLayout()); |
236 |
taskListModel = new DefaultListModel(); |
237 |
taskList = new JList(taskListModel); |
238 |
taskList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
|
239 |
taskList.setSelectedIndex(0);
|
240 |
spTaskManager = new JScrollPane(taskList); |
241 |
panelTaskManagerControls = new JPanel(); |
242 |
panelTaskManagerControls.setLayout(new GridLayout(1,4)); |
243 |
panelTaskManagerControlsPriority = new JPanel(); |
244 |
panelTaskManagerControlsPriority.setLayout(new GridLayout(1,2)); |
245 |
btnAddTask = new JButton("Add..."); |
246 |
btnRemoveTask = new JButton("Remove"); |
247 |
btnMoveTaskUp = new JButton("^"); |
248 |
btnMoveTaskDown = new JButton("v"); |
249 |
btnUpdateTasks = new JButton("Update"); |
250 |
panelTaskManagerControlsPriority.add(btnMoveTaskUp); |
251 |
panelTaskManagerControlsPriority.add(btnMoveTaskDown); |
252 |
panelTaskManagerControls.add(btnAddTask); |
253 |
panelTaskManagerControls.add(btnRemoveTask); |
254 |
panelTaskManagerControls.add(btnUpdateTasks); |
255 |
panelTaskManagerControls.add(panelTaskManagerControlsPriority); |
256 |
panelTaskManager.add(spTaskManager, BorderLayout.CENTER);
|
257 |
panelTaskManager.add(panelTaskManagerControls, BorderLayout.SOUTH);
|
258 |
panelTaskManager.add(new JLabel("Current Task Queue"), BorderLayout.NORTH); |
259 |
taskAddWindow = new TaskAddWindow();
|
260 |
|
261 |
// Message log
|
262 |
log = new JTextArea(); |
263 |
spLog = new JScrollPane(log, |
264 |
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
|
265 |
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
|
266 |
spLog.setBorder(BorderFactory.createTitledBorder("Log")); |
267 |
spLog.setPreferredSize(new Dimension(0, 120)); |
268 |
log.setEditable(false);
|
269 |
|
270 |
// Main control mechanism
|
271 |
panelControl = new JPanel(); |
272 |
panelControl.setLayout(new GridLayout(1,1)); |
273 |
tabPaneControl = new JTabbedPane(JTabbedPane.TOP); |
274 |
tabPaneControl.setPreferredSize(new Dimension(330, 0)); |
275 |
tabPaneControl.addTab("Connection", panelServerInterface);
|
276 |
tabPaneControl.addTab("Robots", panelRobotControl);
|
277 |
tabPaneControl.addTab("Tasks", panelTaskManager);
|
278 |
panelControl.add(tabPaneControl); |
279 |
|
280 |
// Set up elements in the south
|
281 |
panelSouth = new JPanel(); |
282 |
panelSouth.setLayout(new GridLayout(1,2)); |
283 |
//panelSouth.add(spLog);
|
284 |
|
285 |
// Put all elements in the ContentPane
|
286 |
this.getContentPane().setLayout(new BorderLayout()); |
287 |
this.getContentPane().add(tabPaneMain, BorderLayout.CENTER); |
288 |
this.getContentPane().add(panelSouth, BorderLayout.SOUTH); |
289 |
this.getContentPane().add(panelControl, BorderLayout.EAST); |
290 |
this.setVisible(true); |
291 |
|
292 |
/* Add all listeners here */
|
293 |
// Task Management
|
294 |
btnAddTask.addActionListener(this);
|
295 |
btnRemoveTask.addActionListener(this);
|
296 |
btnMoveTaskUp.addActionListener(this);
|
297 |
btnMoveTaskDown.addActionListener(this);
|
298 |
btnUpdateTasks.addActionListener(this);
|
299 |
// Robot Control
|
300 |
btnF.addActionListener(this);
|
301 |
btnB.addActionListener(this);
|
302 |
btnL.addActionListener(this);
|
303 |
btnR.addActionListener(this);
|
304 |
btnF.addKeyListener(this);
|
305 |
btnB.addKeyListener(this);
|
306 |
btnL.addKeyListener(this);
|
307 |
btnR.addKeyListener(this);
|
308 |
btnActivate.addActionListener(this);
|
309 |
btnActivate.addKeyListener(this);
|
310 |
cmbRobotNum.addKeyListener(this);
|
311 |
vectorController.addMouseMotionListener(this);
|
312 |
vectorController.addMouseListener(this);
|
313 |
btnCommand_StopTask.addActionListener(this);
|
314 |
btnCommand_ResumeTask.addActionListener(this);
|
315 |
btnCommand_ChargeNow.addActionListener(this);
|
316 |
btnCommand_StopCharging.addActionListener(this);
|
317 |
// Other
|
318 |
btnGraph.addActionListener(this);
|
319 |
btnConnect.addActionListener(this);
|
320 |
panelGraph.addMouseListener(this);
|
321 |
this.addMouseMotionListener(this); |
322 |
|
323 |
|
324 |
// Set up dependent threads
|
325 |
indicator = new SelectionIndicator(canvas);
|
326 |
indicator.setRadius(RADIUS+3, 15); //a tad more than the bot radius |
327 |
simulator = new Simulator();
|
328 |
webcamLoader = new WebcamLoader(this); |
329 |
dataUpdater = new DataUpdater();
|
330 |
csi = new ColonetServerInterface(this); |
331 |
|
332 |
} |
333 |
|
334 |
public synchronized void paint (Graphics g) { |
335 |
/* Redraw the graphical components in the applet.
|
336 |
This paint method overrides the built-in paint of the
|
337 |
JApplet, and we don't want to deal with redrawing the
|
338 |
components manually. Fuck that shit. */
|
339 |
step(); |
340 |
super.paint(g);
|
341 |
} |
342 |
|
343 |
public synchronized void update (Graphics g) { |
344 |
paint(g); |
345 |
} |
346 |
|
347 |
private void randomize () { |
348 |
Random r = new Random(); |
349 |
StringBuilder s = new StringBuilder(); |
350 |
|
351 |
int count = r.nextInt(8) + 1; |
352 |
for (int i = 0; i < count; i++) { |
353 |
for (int j = 0; j < count; j++) { |
354 |
if (r.nextBoolean())
|
355 |
s.append("" + (r.nextInt(16) + 1)); |
356 |
else
|
357 |
s.append("-");
|
358 |
if (j != count-1) |
359 |
s.append(" ");
|
360 |
} |
361 |
if (i != count-1) s.append("\n"); |
362 |
} |
363 |
|
364 |
txtMatrix.setText(s.toString()); |
365 |
} |
366 |
|
367 |
public void drawRobot (int id, int x, int y) { |
368 |
//save the bot in memory, so we can tell if we click on it later
|
369 |
botRect[id] = new Rectangle(x-RADIUS, y-RADIUS, 2*RADIUS, 2*RADIUS); |
370 |
|
371 |
//draw the bot on the canvas
|
372 |
canvas.setColor(Color.BLACK);
|
373 |
canvas.drawOval(x-RADIUS, y-RADIUS, RADIUS*2, RADIUS*2); |
374 |
|
375 |
//draw the label
|
376 |
canvas.setFont(botFont); |
377 |
try {
|
378 |
canvas.drawString("" + xbeeID[id], x-20, y+2); |
379 |
} catch (Exception e) { |
380 |
canvas.drawString("???", x-22, y+2); |
381 |
} |
382 |
} |
383 |
|
384 |
public void drawConnection (int start, int end, int radius, Color color) { |
385 |
final int ARROW_LENGTH = 18; |
386 |
|
387 |
double angle = 2.0 * Math.PI / numBots; |
388 |
int startx, starty, endx, endy;
|
389 |
startx = cx - (int)(radius * Math.cos(start * angle)); |
390 |
starty = cy - (int)(radius * Math.sin(start * angle)); |
391 |
endx = cx - (int)(radius * Math.cos(end * angle)); |
392 |
endy = cy - (int)(radius * Math.sin(end * angle)); |
393 |
canvas.setColor(color); |
394 |
canvas.drawLine(startx, starty, endx, endy); |
395 |
|
396 |
//create arrow
|
397 |
if (color.equals(Color.BLACK)) return; |
398 |
int big_dy = starty - endy;
|
399 |
int big_dx = endx - startx;
|
400 |
double theta = 0; |
401 |
if (big_dx == 0 && starty > endy) //pointing up |
402 |
theta = Math.PI/2; |
403 |
else if (big_dx == 0 && starty < endy) //pointing down |
404 |
theta = 3*Math.PI/2; |
405 |
else if (big_dy == 0 && startx > endx) //pointing left |
406 |
theta = Math.PI;
|
407 |
else if (big_dy == 0 && startx < endx) //pointing right |
408 |
theta = 0;
|
409 |
else
|
410 |
theta = Math.atan(1.0 * big_dy / big_dx); |
411 |
|
412 |
//create ploygon
|
413 |
Polygon poly = new Polygon(); |
414 |
int dx_arrow = Math.abs((int)(ARROW_LENGTH * Math.cos(theta))); |
415 |
int dy_arrow = Math.abs((int)(ARROW_LENGTH * Math.sin(theta))); |
416 |
int dy_half = (int)(ARROW_LENGTH/2 * Math.cos(theta)); |
417 |
int dx_half = (int)(ARROW_LENGTH/2 * Math.sin(theta)); |
418 |
int rx = (big_dx > 0) ? endx - dx_arrow : endx + dx_arrow; |
419 |
int ry = (big_dy > 0) ? endy + dy_arrow : endy - dy_arrow; |
420 |
poly.addPoint(endx, endy); |
421 |
poly.addPoint(rx - dx_half, ry - dy_half); |
422 |
poly.addPoint(rx + dx_half, ry + dy_half); |
423 |
canvas.fillPolygon(poly); |
424 |
} |
425 |
|
426 |
public void run () { |
427 |
while (true) { |
428 |
repaint(); |
429 |
try {
|
430 |
Thread.sleep(90); |
431 |
} catch (InterruptedException e) { |
432 |
return;
|
433 |
} |
434 |
} |
435 |
} |
436 |
|
437 |
public void step () { |
438 |
final int DIAMETER = image.getWidth() - 2*BUFFER; |
439 |
final int BIGRADIUS = DIAMETER / 2; |
440 |
final int TOKENRADIUS = 40; |
441 |
boolean valid;
|
442 |
|
443 |
// clear image
|
444 |
canvas.setColor(Color.WHITE);
|
445 |
canvas.fillRect(0, 0, image.getWidth(), image.getHeight()); |
446 |
|
447 |
// parse the matrix, to see what robots exist
|
448 |
String [] rows = txtMatrix.getText().split("\n"); |
449 |
numBots = rows.length; |
450 |
String [][] entries = new String[numBots][numBots]; |
451 |
valid = true;
|
452 |
for (int i = 0; i < numBots; i++) { |
453 |
entries[i] = rows[i].split(" ");
|
454 |
if (entries[i].length != rows.length) valid = false; |
455 |
} |
456 |
|
457 |
if (valid) {
|
458 |
this.showStatus("Running"); |
459 |
|
460 |
// draw robots and find which one is seleced
|
461 |
double angle = 2.0 * Math.PI / numBots; |
462 |
canvas.setColor(Color.BLACK);
|
463 |
botRect = new Rectangle[numBots]; |
464 |
int x, y;
|
465 |
if (selectedBot >= numBots) selectedBot = 0; |
466 |
for (int i = 0; i < numBots; i++) { |
467 |
x = cx - (int)(BIGRADIUS * Math.cos(i * angle)); |
468 |
y = cy - (int)(BIGRADIUS * Math.sin(i * angle)); |
469 |
drawRobot(i, x, y); |
470 |
if (i == selectedBot) indicator.setCenter(x, y);
|
471 |
} |
472 |
|
473 |
// draw token marker
|
474 |
int tokenx, tokeny;
|
475 |
int tokenNum = tokenLoc;
|
476 |
tokenx = cx - (int)(BIGRADIUS * Math.cos(tokenNum * angle)); |
477 |
tokeny = cy - (int)(BIGRADIUS * Math.sin(tokenNum * angle)); |
478 |
canvas.setColor(Color.RED);
|
479 |
canvas.drawOval(tokenx-TOKENRADIUS, tokeny-TOKENRADIUS, 2*TOKENRADIUS, 2*TOKENRADIUS); |
480 |
|
481 |
// create an inner circle along which the connections are made.
|
482 |
// let the diameter of this circle be 2*RADIUS less than the outerDiameter.
|
483 |
// see what connections exist
|
484 |
for (int row = 0; row < numBots; row++) { |
485 |
for(int col = 0; col < numBots; col++) { |
486 |
if (!entries[row][col].equals("-") && entries[col][row].equals("-") && row != col) { |
487 |
//TODO: Make a standard gray
|
488 |
drawConnection(row, col, BIGRADIUS-RADIUS, new Color(200,200,200)); |
489 |
} else if (!entries[row][col].equals("-") && ! entries[col][row].equals("-") && row != col) { |
490 |
drawConnection(row, col, BIGRADIUS-RADIUS, Color.BLACK);
|
491 |
} |
492 |
} |
493 |
} |
494 |
|
495 |
// draw the selection indicator
|
496 |
indicator.draw(); |
497 |
|
498 |
} else { // if matrix is not valid |
499 |
this.showStatus("Error: Invalid matrix"); |
500 |
} |
501 |
|
502 |
} |
503 |
|
504 |
public JTextArea getLog () { |
505 |
return log;
|
506 |
} |
507 |
|
508 |
public JTextArea getMatrixInput () { |
509 |
return txtMatrix;
|
510 |
} |
511 |
|
512 |
public void parseMatrix (String line) { |
513 |
txtMatrix.setText("");
|
514 |
String [] str = line.split(" "); |
515 |
int num = Integer.parseInt(str[2]); |
516 |
for (int i = 0; i < num; i++) { |
517 |
for (int j = 0; j < num; j++) { |
518 |
String next = str[3 + i*num + j]; |
519 |
if (next.equals("-1")) |
520 |
txtMatrix.append("-");
|
521 |
else
|
522 |
txtMatrix.append(next); |
523 |
if (j < num - 1) |
524 |
txtMatrix.append(" ");
|
525 |
} |
526 |
if (i < num - 1) |
527 |
txtMatrix.append("\n");
|
528 |
} |
529 |
|
530 |
} |
531 |
|
532 |
public void parseQueue (String line) { |
533 |
log.append("Got queue update\n");
|
534 |
} |
535 |
|
536 |
public void parseXBeeIDs (String line) { |
537 |
String [] str = line.split(" "); |
538 |
int num = Integer.parseInt(str[2]); |
539 |
xbeeID = new int[num]; |
540 |
for (int i = 0; i < num; i++) |
541 |
xbeeID[i] = Integer.parseInt(str[i+3]); |
542 |
|
543 |
//update the list of robots to control
|
544 |
//but save the old value first
|
545 |
Object oldSelection = cmbRobotNum.getSelectedItem();
|
546 |
cmbRobotNum.removeAllItems(); |
547 |
cmbRobotNum.addItem(new String(" All ")); |
548 |
for (int i = 0; i < num; i++) |
549 |
cmbRobotNum.addItem(new String("" + xbeeID[i])); |
550 |
cmbRobotNum.setSelectedItem(oldSelection); |
551 |
} |
552 |
|
553 |
public void parseBattery (String line) { |
554 |
String [] str = line.split(" "); |
555 |
int botNum = Integer.parseInt(str[2]); |
556 |
int batteryVal = Integer.parseInt(str[3]); |
557 |
if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex()-1 == botNum) |
558 |
lblBattery.setText("" + batteryVal);
|
559 |
} |
560 |
|
561 |
//
|
562 |
// MouseListener methods
|
563 |
//
|
564 |
public void mouseExited(MouseEvent e) { |
565 |
} |
566 |
public void mouseEntered(MouseEvent e) { |
567 |
} |
568 |
public void mouseReleased(MouseEvent e) { |
569 |
vectorController.notifyMouseEvent(e, true);
|
570 |
} |
571 |
public void mouseClicked(MouseEvent e) { |
572 |
vectorController.notifyMouseEvent(e, false);
|
573 |
} |
574 |
public void mousePressed(MouseEvent e) { |
575 |
try {
|
576 |
for (int i = 0; i < numBots; i++) { |
577 |
if (botRect[i].contains(e.getPoint())) {
|
578 |
selectedBot = i; |
579 |
cmbRobotNum.setSelectedIndex(i+1);
|
580 |
} |
581 |
} |
582 |
} catch (Exception ex) { |
583 |
} |
584 |
} |
585 |
public void mouseDragged(MouseEvent e) { |
586 |
vectorController.notifyMouseEvent(e, false);
|
587 |
} |
588 |
public void mouseMoved(MouseEvent e) { |
589 |
} |
590 |
|
591 |
//
|
592 |
// KeyListener methods
|
593 |
//
|
594 |
public void keyPressed (KeyEvent e) { |
595 |
int code = e.getKeyCode();
|
596 |
if (code == KeyEvent.VK_UP) { |
597 |
vectorController.setMaxForward(); |
598 |
vectorController.sendToServer(); |
599 |
} else if (code == KeyEvent.VK_DOWN) { |
600 |
vectorController.setMaxReverse(); |
601 |
vectorController.sendToServer(); |
602 |
} else if (code == KeyEvent.VK_LEFT) { |
603 |
vectorController.setMaxLeft(); |
604 |
vectorController.sendToServer(); |
605 |
} else if (code == KeyEvent.VK_RIGHT) { |
606 |
vectorController.setMaxRight(); |
607 |
vectorController.sendToServer(); |
608 |
} else if (code == KeyEvent.VK_S) { |
609 |
vectorController.setZero(); |
610 |
vectorController.sendToServer(); |
611 |
} |
612 |
} |
613 |
public void keyReleased (KeyEvent e) { |
614 |
} |
615 |
public void keyTyped (KeyEvent e) { |
616 |
} |
617 |
|
618 |
|
619 |
//
|
620 |
// ActionListener method
|
621 |
//
|
622 |
public void actionPerformed (ActionEvent e) { |
623 |
Object source = e.getSource();
|
624 |
if (source == btnGraph) {
|
625 |
btnGraph.setEnabled(false);
|
626 |
//Start dependent threads
|
627 |
drawThread = new Thread(this, "drawThread"); |
628 |
drawThread.start(); |
629 |
indicator.start(); |
630 |
simulator.start(); |
631 |
webcamLoader.start(); |
632 |
} else if (source == btnConnect) { |
633 |
csi.connect(txtHost.getText(), txtPort.getText()); |
634 |
dataUpdater.start(); |
635 |
drawThread = new Thread(this, "drawThread"); |
636 |
drawThread.start(); |
637 |
indicator.start(); |
638 |
simulator.start(); |
639 |
webcamLoader.start(); |
640 |
} |
641 |
// Robot Movement Controls
|
642 |
else if (source == btnF) { |
643 |
vectorController.setMaxForward(); |
644 |
vectorController.sendToServer(); |
645 |
} else if (source == btnB) { |
646 |
vectorController.setMaxReverse(); |
647 |
vectorController.sendToServer(); |
648 |
} else if (source == btnL) { |
649 |
vectorController.setMaxLeft(); |
650 |
vectorController.sendToServer(); |
651 |
} else if (source == btnR) { |
652 |
vectorController.setMaxRight(); |
653 |
vectorController.sendToServer(); |
654 |
} else if (source == btnActivate) { |
655 |
vectorController.setZero(); |
656 |
vectorController.sendToServer(); |
657 |
} |
658 |
// Robot Commands (non-movement)
|
659 |
else if (source == btnCommand_StopTask) { |
660 |
|
661 |
} else if (source == btnCommand_ResumeTask) { |
662 |
|
663 |
} else if (source == btnCommand_ChargeNow) { |
664 |
|
665 |
} else if (source == btnCommand_StopCharging) { |
666 |
|
667 |
} |
668 |
|
669 |
// Queue Management
|
670 |
else if (source == btnAddTask) { |
671 |
taskAddWindow.prompt(); |
672 |
} else if (source == btnRemoveTask) { |
673 |
if (taskList.getSelectedIndex() >= 0); |
674 |
csi.sendQueueRemove(taskList.getSelectedIndex()); |
675 |
csi.sendQueueUpdate(); |
676 |
} else if (source == btnMoveTaskUp) { |
677 |
csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() - 1);
|
678 |
csi.sendQueueUpdate(); |
679 |
} else if (source == btnMoveTaskDown) { |
680 |
csi.sendQueueReorder(taskList.getSelectedIndex(), taskList.getSelectedIndex() + 1);
|
681 |
csi.sendQueueUpdate(); |
682 |
} else if (source == btnUpdateTasks) { |
683 |
csi.sendQueueUpdate(); |
684 |
} |
685 |
} |
686 |
|
687 |
/*
|
688 |
* SelectionIndicator thread.
|
689 |
* Graphical representation of the selection marker
|
690 |
*
|
691 |
* step() and draw() are synchronized methods. step() is private and
|
692 |
* used to update the position of the crosshairs. draw() is called
|
693 |
* externally and should only run if all calculations in step() have
|
694 |
* been completed.
|
695 |
*/
|
696 |
private class SelectionIndicator extends Thread { |
697 |
|
698 |
final int INDICATOR_DELAY = 180; |
699 |
final double DTHETA = 0.4; //larger values make the marker rotate faster |
700 |
Graphics2D g; //canvas to draw on |
701 |
boolean running;
|
702 |
|
703 |
int sx, sy; //center |
704 |
int r, dr; //radius and width of marker |
705 |
double theta; //current angle |
706 |
|
707 |
volatile Polygon poly1, poly2, poly3, poly4; |
708 |
|
709 |
int px1, py1;
|
710 |
int rx1, ry1;
|
711 |
int px2, py2;
|
712 |
int rx2, ry2;
|
713 |
int px3, py3;
|
714 |
int rx3, ry3;
|
715 |
int px4, py4;
|
716 |
int rx4, ry4;
|
717 |
|
718 |
int steps;
|
719 |
|
720 |
public SelectionIndicator (Graphics2D g) { |
721 |
super("SelectionIndicator"); |
722 |
this.g = g;
|
723 |
running = false;
|
724 |
steps = 0;
|
725 |
|
726 |
theta = 0;
|
727 |
rx1 = 0; ry1 = 0; |
728 |
px1 = 0; py1 = 0; |
729 |
rx2 = 0; ry2 = 0; |
730 |
px2 = 0; py2 = 0; |
731 |
rx3 = 0; ry3 = 0; |
732 |
px3 = 0; py3 = 0; |
733 |
rx4 = 0; ry4 = 0; |
734 |
px4 = 0; py4 = 0; |
735 |
} |
736 |
|
737 |
public synchronized void setCenter (int sx, int sy) { |
738 |
if (sx == this.sx && sy == this.sy) return; |
739 |
this.sx = sx;
|
740 |
this.sy = sy;
|
741 |
steps = 0;
|
742 |
} |
743 |
|
744 |
public synchronized void setRadius (int r, int dr) { |
745 |
this.r = r;
|
746 |
this.dr = dr;
|
747 |
steps = 0;
|
748 |
} |
749 |
|
750 |
public void run () { |
751 |
running = true;
|
752 |
while (running) {
|
753 |
step(); |
754 |
try {
|
755 |
Thread.sleep(INDICATOR_DELAY);
|
756 |
} catch (InterruptedException e) { |
757 |
running = false;
|
758 |
return;
|
759 |
} |
760 |
} |
761 |
} |
762 |
|
763 |
private synchronized void step () { |
764 |
Polygon poly1_new = new Polygon(); |
765 |
Polygon poly2_new = new Polygon(); |
766 |
Polygon poly3_new = new Polygon(); |
767 |
Polygon poly4_new = new Polygon(); |
768 |
|
769 |
//the step
|
770 |
theta = (theta + DTHETA/Math.PI) % (Math.PI); |
771 |
|
772 |
//the calculation
|
773 |
//let p be the point of the pointy thing toward the center
|
774 |
//let r be the point at the opposite side
|
775 |
|
776 |
//recalculate radius, if it will look cool, lolz
|
777 |
int newr = r;
|
778 |
if (steps < 100) |
779 |
newr = (int)( r + 200/(steps+1) ); |
780 |
|
781 |
//precompute values for dx and dy
|
782 |
int dx_inner = (int)(newr * Math.cos(theta)); |
783 |
int dy_inner = (int)(newr * Math.sin(theta)); |
784 |
int dx_outer = (int)((newr+dr) * Math.cos(theta)); |
785 |
int dy_outer = (int)((newr+dr) * Math.sin(theta)); |
786 |
|
787 |
//calculate polygon constants
|
788 |
int dy_poly = (int)(dr/2 * Math.cos(theta)); |
789 |
int dx_poly = (int)(dr/2 * Math.sin(theta)); |
790 |
|
791 |
//determine critical points
|
792 |
//kansas city shuffle!
|
793 |
px1 = sx + dx_inner; |
794 |
py1 = sy - dy_inner; |
795 |
rx1 = sx + dx_outer; |
796 |
ry1 = sy - dy_outer; |
797 |
px2 = sx - dx_inner; |
798 |
py2 = sy + dy_inner; |
799 |
rx2 = sx - dx_outer; |
800 |
ry2 = sy + dy_outer; |
801 |
px3 = sx - dy_inner; |
802 |
py3 = sy - dx_inner; |
803 |
rx3 = sx - dy_outer; |
804 |
ry3 = sy - dx_outer; |
805 |
px4 = sx + dy_inner; |
806 |
py4 = sy + dx_inner; |
807 |
rx4 = sx + dy_outer; |
808 |
ry4 = sy + dx_outer; |
809 |
|
810 |
//create polygons
|
811 |
poly1_new.addPoint(px1, py1); |
812 |
poly1_new.addPoint(rx1+dx_poly, ry1+dy_poly); |
813 |
poly1_new.addPoint(rx1-dx_poly, ry1-dy_poly); |
814 |
poly2_new.addPoint(px2, py2); |
815 |
poly2_new.addPoint(rx2+dx_poly, ry2+dy_poly); |
816 |
poly2_new.addPoint(rx2-dx_poly, ry2-dy_poly); |
817 |
poly3_new.addPoint(px3, py3); |
818 |
poly3_new.addPoint(rx3-dy_poly, ry3+dx_poly); |
819 |
poly3_new.addPoint(rx3+dy_poly, ry3-dx_poly); |
820 |
poly4_new.addPoint(px4, py4); |
821 |
poly4_new.addPoint(rx4-dy_poly, ry4+dx_poly); |
822 |
poly4_new.addPoint(rx4+dy_poly, ry4-dx_poly); |
823 |
|
824 |
//reassign updated polygons
|
825 |
poly1 = poly1_new; |
826 |
poly2 = poly2_new; |
827 |
poly3 = poly3_new; |
828 |
poly4 = poly4_new; |
829 |
|
830 |
if (steps < 300) steps++; |
831 |
} |
832 |
|
833 |
public synchronized void draw () { |
834 |
if (!running) return; |
835 |
g.setColor(Color.GRAY);
|
836 |
//draw polygons
|
837 |
g.fillPolygon(poly1); |
838 |
g.fillPolygon(poly2); |
839 |
g.fillPolygon(poly3); |
840 |
g.fillPolygon(poly4); |
841 |
} |
842 |
|
843 |
} |
844 |
|
845 |
/*
|
846 |
* Simulator thread.
|
847 |
*
|
848 |
*/
|
849 |
private class Simulator extends Thread { |
850 |
final int SIMULATOR_DELAY = 300; |
851 |
boolean running;
|
852 |
|
853 |
public Simulator () {
|
854 |
super("Simulator"); |
855 |
running = false;
|
856 |
} |
857 |
|
858 |
public void run () { |
859 |
running = true;
|
860 |
while (running) {
|
861 |
step(); |
862 |
try {
|
863 |
Thread.sleep(SIMULATOR_DELAY);
|
864 |
} catch (InterruptedException e) { |
865 |
running = false;
|
866 |
return;
|
867 |
} |
868 |
} |
869 |
} |
870 |
|
871 |
private void step () { |
872 |
// don't do anything! the colonet should work on its own!
|
873 |
} |
874 |
|
875 |
} |
876 |
|
877 |
/*
|
878 |
* DataUpdater thread.
|
879 |
* The purpose of this thread is to request data from the server at regular intervals.
|
880 |
*
|
881 |
*/
|
882 |
class DataUpdater extends Thread { |
883 |
final int DATAUPDATER_DELAY = 4000; |
884 |
|
885 |
public DataUpdater () {
|
886 |
super("Colonet DataUpdater"); |
887 |
} |
888 |
|
889 |
public void run () { |
890 |
String line;
|
891 |
while (true) { |
892 |
try {
|
893 |
//request more data
|
894 |
if (csi != null && csi.isReady()) { |
895 |
csi.sendSensorDataRequest(); |
896 |
csi.sendXBeeIDRequest(); |
897 |
if (cmbRobotNum.getSelectedIndex() > 0) |
898 |
csi.sendBatteryRequest(cmbRobotNum.getSelectedIndex()-1);
|
899 |
} |
900 |
Thread.sleep(DATAUPDATER_DELAY);
|
901 |
} catch (InterruptedException e) { |
902 |
return;
|
903 |
} |
904 |
} |
905 |
} |
906 |
|
907 |
} |
908 |
|
909 |
/*
|
910 |
* GraphicsPanel class
|
911 |
* Enables more efficient image handling in a component-controlled environment
|
912 |
*/
|
913 |
class GraphicsPanel extends JPanel { |
914 |
protected Image img; |
915 |
|
916 |
public GraphicsPanel (Image img) { |
917 |
super();
|
918 |
this.img = img;
|
919 |
} |
920 |
|
921 |
public GraphicsPanel (boolean isDoubleBuffered, Image img) { |
922 |
super(isDoubleBuffered);
|
923 |
this.img = img;
|
924 |
} |
925 |
|
926 |
public void paint (Graphics g) { |
927 |
// Place the buffered image on the screen, inside the panel
|
928 |
g.drawImage(img, 0, 0, Color.WHITE, this); |
929 |
} |
930 |
|
931 |
} |
932 |
|
933 |
/*
|
934 |
* WebcamPanel class
|
935 |
* Enables more efficient image handling in a component-controlled environment
|
936 |
*/
|
937 |
class WebcamPanel extends JPanel { |
938 |
int BORDER = 16; // this is arbitrary. it makes the image look nice inside a border. |
939 |
int BOT_RADIUS = 40; |
940 |
volatile BufferedImage img; |
941 |
volatile Point [] points; |
942 |
|
943 |
public WebcamPanel () {
|
944 |
super();
|
945 |
} |
946 |
|
947 |
public synchronized void setImage (BufferedImage newimg) { |
948 |
if (img != null) { |
949 |
img.flush(); |
950 |
img = null;
|
951 |
img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); |
952 |
} |
953 |
System.gc();
|
954 |
img = newimg; |
955 |
} |
956 |
|
957 |
public synchronized void setPoints (Point [] newpoints) { |
958 |
this.points = newpoints;
|
959 |
} |
960 |
|
961 |
public synchronized void paint (Graphics g) { |
962 |
|
963 |
if (img == null) |
964 |
return;
|
965 |
// Place the image on the screen, inside the panel
|
966 |
g.drawImage(img, |
967 |
BORDER, //dx1 - the x coordinate of the first corner of the destination rectangle.
|
968 |
BORDER, //dy1 - the y coordinate of the first corner of the destination rectangle.
|
969 |
this.getWidth() - BORDER, //dx2 - the x coordinate of the second corner of the destination rectangle. |
970 |
this.getHeight() - BORDER, //dy2 - the y coordinate of the second corner of the destination rectangle. |
971 |
0, //sx1 - the x coordinate of the first corner of the source rectangle. |
972 |
0, //sy1 - the y coordinate of the first corner of the source rectangle. |
973 |
image.getWidth(), //sx2 - the x coordinate of the second corner of the source rectangle.
|
974 |
image.getHeight(), //sy2 - the y coordinate of the second corner of the source rectangle.
|
975 |
null //observer - object to be notified as more of the image is scaled and converted. |
976 |
); |
977 |
|
978 |
// Draw Identifiers
|
979 |
if (points == null) |
980 |
return;
|
981 |
g.setColor(Color.RED);
|
982 |
((Graphics2D)g).setStroke(new BasicStroke(2)); |
983 |
for (int i = 0; i < points.length; i++) { |
984 |
g.drawOval(points[i].x - BOT_RADIUS, points[i].y - BOT_RADIUS, 2*BOT_RADIUS, 2*BOT_RADIUS); |
985 |
} |
986 |
|
987 |
} |
988 |
|
989 |
} |
990 |
|
991 |
/*
|
992 |
* WebcamLoader class
|
993 |
* Handles the loading of the webcam image.
|
994 |
*/
|
995 |
class WebcamLoader extends Thread |
996 |
{ |
997 |
final int WEBCAMLOADER_DELAY = 1000; |
998 |
final String IMAGE_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet.jpg"; |
999 |
final String LOCATIONS_PATH = "http://roboclub9.frc.ri.cmu.edu/colonet/locations.txt"; |
1000 |
|
1001 |
URL imagePath;
|
1002 |
URI locationsPath;
|
1003 |
|
1004 |
MediaTracker mt;
|
1005 |
BufferedImage image;
|
1006 |
|
1007 |
public WebcamLoader (JApplet applet) |
1008 |
{ |
1009 |
super("ColonetWebcamLoader"); |
1010 |
mt = new MediaTracker(applet); |
1011 |
ImageIO.setUseCache(false); |
1012 |
try {
|
1013 |
imagePath = new URL(IMAGE_PATH); |
1014 |
} catch (MalformedURLException e) { |
1015 |
System.out.println("Malformed URL: could not form URL from: [" + IMAGE_PATH + "]\n"); |
1016 |
} |
1017 |
try {
|
1018 |
locationsPath = new URI(LOCATIONS_PATH); |
1019 |
} catch (URISyntaxException x) { |
1020 |
System.out.println("Malformed URI: could not form URI from: [" + LOCATIONS_PATH + "]\n"); |
1021 |
} |
1022 |
|
1023 |
} |
1024 |
|
1025 |
public synchronized void run () |
1026 |
{ |
1027 |
while (true) { |
1028 |
try {
|
1029 |
Thread.sleep(WEBCAMLOADER_DELAY);
|
1030 |
if (image != null) |
1031 |
image.flush(); |
1032 |
System.gc();
|
1033 |
image = ImageIO.read(imagePath);
|
1034 |
// The MediaTracker waitForID pauses the thread until the image is loaded.
|
1035 |
// We don't want to display a half-downloaded image.
|
1036 |
mt.addImage(image, 1);
|
1037 |
mt.waitForID(1);
|
1038 |
mt.removeImage(image); |
1039 |
// Save
|
1040 |
panelWebcam.setImage(image); |
1041 |
parseLocations(locationsPath.toURL()); |
1042 |
} catch (InterruptedException e) { |
1043 |
return;
|
1044 |
} catch (java.security.AccessControlException e) {
|
1045 |
csi.warn("java.security.AccessControlException in WebcamLoader.\n" +
|
1046 |
"The image cannot be loaded from the specified location.\n" +
|
1047 |
"Make sure you are accessing this applet from the correct server.");
|
1048 |
return;
|
1049 |
} catch (IOException e) { |
1050 |
log.append("IOException while trying to load image.");
|
1051 |
} |
1052 |
} |
1053 |
} |
1054 |
|
1055 |
private void parseLocations (URL url) { |
1056 |
URLConnection conn = null; |
1057 |
DataInputStream data = null; |
1058 |
String line;
|
1059 |
String [] lines = new String[30]; |
1060 |
StringBuffer buf = new StringBuffer(); |
1061 |
int i = 0; |
1062 |
|
1063 |
try {
|
1064 |
conn = url.openConnection(); |
1065 |
conn.connect(); |
1066 |
data = new DataInputStream(new BufferedInputStream(conn.getInputStream())); |
1067 |
while ((line = data.readLine()) != null) { |
1068 |
buf.append(line + ";");
|
1069 |
lines[i] = line; |
1070 |
i++; |
1071 |
} |
1072 |
data.close(); |
1073 |
} catch (IOException e) { |
1074 |
System.out.println("IOException:" + e.getMessage()); |
1075 |
} |
1076 |
//log.append("Got robot locations: " + buf + "\n");
|
1077 |
|
1078 |
// Get Point values from strings
|
1079 |
Point [] points = new Point[i]; |
1080 |
for (int j = 0; j < i; j++) { |
1081 |
String [] parts = lines[j].split(","); |
1082 |
int xval = Integer.parseInt(parts[0]); |
1083 |
int yval = Integer.parseInt(parts[1]); |
1084 |
Point p = new Point(xval, yval); |
1085 |
points[j] = p; |
1086 |
} |
1087 |
if (points.length != 0) |
1088 |
panelWebcam.setPoints(points); |
1089 |
|
1090 |
} |
1091 |
} |
1092 |
|
1093 |
|
1094 |
/*
|
1095 |
* VectorController class
|
1096 |
* Manages robot motion control graphically
|
1097 |
*/
|
1098 |
class VectorController extends GraphicsPanel { |
1099 |
int x, y, cx, cy;
|
1100 |
int width, height;
|
1101 |
int side;
|
1102 |
|
1103 |
public VectorController (Image img) { |
1104 |
super (img);
|
1105 |
width = img.getWidth(null);
|
1106 |
height = img.getHeight(null);
|
1107 |
cx = img.getWidth(null)/2; |
1108 |
cy = img.getHeight(null)/2; |
1109 |
x = cx; |
1110 |
y = cy; |
1111 |
if (width < height)
|
1112 |
side = width; |
1113 |
else
|
1114 |
side = height; |
1115 |
} |
1116 |
|
1117 |
public void setPoint (int x, int y) { |
1118 |
if (!isValidPoint(x, y))
|
1119 |
return;
|
1120 |
this.x = x;
|
1121 |
this.y = y;
|
1122 |
repaint(); |
1123 |
} |
1124 |
|
1125 |
public boolean isValidPoint (int x, int y) { |
1126 |
double xterm = Math.pow(1.0*(x - cx)/(side/2), 2); |
1127 |
double yterm = Math.pow(1.0*(y - cy)/(side/2), 2); |
1128 |
return (xterm + yterm <= 1); |
1129 |
} |
1130 |
|
1131 |
public void notifyMouseEvent (MouseEvent e, boolean send) { |
1132 |
if (!isValidPoint(e.getX(), e.getY()))
|
1133 |
return;
|
1134 |
vectorController.setPoint(e.getX(), e.getY()); |
1135 |
vectorController.repaint(); |
1136 |
if (send)
|
1137 |
vectorController.sendToServer(); |
1138 |
} |
1139 |
|
1140 |
public int getSpeed () { |
1141 |
int dx = x - cx;
|
1142 |
int dy = y - cy;
|
1143 |
int v = (int) Math.sqrt( Math.pow(dx, 2) + Math.pow(dy, 2) ); |
1144 |
return v;
|
1145 |
} |
1146 |
|
1147 |
public int getAngle () { |
1148 |
int dx = x - cx;
|
1149 |
int dy = cy - y;
|
1150 |
double theta = Math.atan2(Math.abs(dx), Math.abs(dy)); |
1151 |
theta = (int) (1.0 * theta * 180 / Math.PI); //transform to degrees |
1152 |
if (dy < 0) |
1153 |
theta = 180 - theta;
|
1154 |
theta *= Math.signum(dx);
|
1155 |
return (int) theta; |
1156 |
} |
1157 |
|
1158 |
public void paint (Graphics g) { |
1159 |
g.setColor(Color.BLACK);
|
1160 |
g.fillRect(0, 0, width, height); |
1161 |
((Graphics2D)g).setStroke(new BasicStroke(1)); |
1162 |
g.setColor(Color.RED);
|
1163 |
g.drawOval(cx-side/2, cy-side/2, side, side); |
1164 |
((Graphics2D)g).setStroke(new BasicStroke(2)); |
1165 |
g.setColor(Color.GREEN);
|
1166 |
g.drawLine(cx, cy, x, y); |
1167 |
g.fillOval(x-3, y-3, 6, 6); |
1168 |
} |
1169 |
|
1170 |
public void setMaxForward () { |
1171 |
setPoint(cx, cy - (side/2) + 1); |
1172 |
} |
1173 |
|
1174 |
public void setMaxReverse () { |
1175 |
setPoint(cx, cy + (side/2) - 1); |
1176 |
} |
1177 |
|
1178 |
public void setMaxLeft () { |
1179 |
setPoint(cx - (side/2) + 1, cy); |
1180 |
} |
1181 |
|
1182 |
public void setMaxRight () { |
1183 |
setPoint(cx + (side/2) - 1, cy); |
1184 |
} |
1185 |
|
1186 |
public void setZero () { |
1187 |
setPoint(cx, cy); |
1188 |
} |
1189 |
|
1190 |
public void sendToServer () { |
1191 |
//log.append("Attempitng to send angle = " + vectorController.getAngle() + ", velocity = " + vectorController.getVelocity() + "\n");
|
1192 |
String dest = ColonetServerInterface.GLOBAL_DEST;
|
1193 |
if (cmbRobotNum != null && cmbRobotNum.getSelectedIndex() > 0) |
1194 |
dest = "" + (cmbRobotNum.getSelectedIndex()-1); |
1195 |
|
1196 |
if (csi != null) { |
1197 |
if (cx == 0 && cy == 0) { |
1198 |
csi.sendData(ColonetServerInterface.MOTORS_OFF, dest); |
1199 |
} else {
|
1200 |
//Directional commands
|
1201 |
/*
|
1202 |
if (x > cx && y == cy) { //move right
|
1203 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 200", dest);
|
1204 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 200", dest);
|
1205 |
} else if (x < cx && y == cy) { //move left
|
1206 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 200", dest);
|
1207 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 200", dest);
|
1208 |
} else if (x == cx && y > cy) { //move forward
|
1209 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 0 225", dest);
|
1210 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 0 225", dest);
|
1211 |
} else if (x == cx && y < cy) { //move backward
|
1212 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 225", dest);
|
1213 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 225", dest);
|
1214 |
} else if (x == cx && y == cy) { //stop!
|
1215 |
csi.sendData(ColonetServerInterface.MOTOR2_SET + " 1 0", dest);
|
1216 |
csi.sendData(ColonetServerInterface.MOTOR1_SET + " 1 0", dest);
|
1217 |
}
|
1218 |
*/
|
1219 |
|
1220 |
} |
1221 |
} |
1222 |
|
1223 |
//The move command doesn't really work...or does it?
|
1224 |
csi.sendData(ColonetServerInterface.MOVE + " " +
|
1225 |
vectorController.getSpeed() + " " +
|
1226 |
vectorController.getAngle(), dest); |
1227 |
|
1228 |
|
1229 |
} |
1230 |
|
1231 |
} |
1232 |
|
1233 |
/*
|
1234 |
* TaskAddWindow class
|
1235 |
* makes it easy to add tasks to the queue
|
1236 |
*/
|
1237 |
class TaskAddWindow extends JFrame implements ActionListener, ListSelectionListener { |
1238 |
JPanel panelButtons;
|
1239 |
JPanel panelParameters;
|
1240 |
JPanel panelSouth;
|
1241 |
JPanel panelSelection;
|
1242 |
JButton btnSubmit;
|
1243 |
JButton btnCancel;
|
1244 |
DefaultListModel availableListModel;
|
1245 |
JList availableList;
|
1246 |
JScrollPane spAvailableTasks;
|
1247 |
JTextArea txtDescription;
|
1248 |
JTextField txtParameters;
|
1249 |
MouseListener mouseListener;
|
1250 |
|
1251 |
public TaskAddWindow () {
|
1252 |
super("Add a Task"); |
1253 |
super.setSize(500,500); |
1254 |
super.setLayout(new BorderLayout()); |
1255 |
|
1256 |
// set up buttons
|
1257 |
btnSubmit = new JButton("Submit"); |
1258 |
btnCancel = new JButton("Cancel"); |
1259 |
panelButtons = new JPanel(); |
1260 |
panelButtons.setLayout(new FlowLayout()); |
1261 |
panelButtons.add(btnSubmit); |
1262 |
panelButtons.add(btnCancel); |
1263 |
this.getRootPane().setDefaultButton(btnSubmit);
|
1264 |
|
1265 |
// set up task list
|
1266 |
availableListModel = new DefaultListModel(); |
1267 |
availableListModel.addElement("Map the Environment");
|
1268 |
availableListModel.addElement("Clean Up Chemical Spill");
|
1269 |
availableListModel.addElement("Grow Plants");
|
1270 |
availableListModel.addElement("Save the Cheerleader");
|
1271 |
availableListModel.addElement("Save the World");
|
1272 |
availableList = new JList(availableListModel); |
1273 |
availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
|
1274 |
availableList.setSelectedIndex(-1);
|
1275 |
spAvailableTasks = new JScrollPane(availableList); |
1276 |
spAvailableTasks.setBorder(BorderFactory.createTitledBorder("Select A Task")); |
1277 |
txtDescription = new JTextArea(); |
1278 |
txtDescription.setEditable(false);
|
1279 |
txtDescription.setLineWrap(true);
|
1280 |
txtDescription.setWrapStyleWord(true);
|
1281 |
txtDescription.setBorder(BorderFactory.createTitledBorder("Description")); |
1282 |
|
1283 |
//set up parameter area
|
1284 |
panelParameters = new JPanel(); |
1285 |
panelParameters.setLayout(new BorderLayout()); |
1286 |
txtParameters = new JTextField(); |
1287 |
panelParameters.add(new JLabel("Optional parameters for this task: "), BorderLayout.WEST); |
1288 |
panelParameters.add(txtParameters); |
1289 |
|
1290 |
// assemble objects
|
1291 |
panelSelection = new JPanel(); |
1292 |
panelSelection.setLayout(new GridLayout(1,2)); |
1293 |
panelSelection.add(spAvailableTasks); |
1294 |
panelSelection.add(txtDescription); |
1295 |
|
1296 |
panelSouth = new JPanel(); |
1297 |
panelSouth.setLayout(new GridLayout(2,1)); |
1298 |
panelSouth.add(panelParameters); |
1299 |
panelSouth.add(panelButtons); |
1300 |
|
1301 |
this.getContentPane().add(panelSouth, BorderLayout.SOUTH); |
1302 |
this.getContentPane().add(panelSelection, BorderLayout.CENTER); |
1303 |
this.setLocationRelativeTo(null); |
1304 |
|
1305 |
// add listeners here
|
1306 |
availableList.addListSelectionListener(this);
|
1307 |
btnSubmit.addActionListener(this);
|
1308 |
btnCancel.addActionListener(this);
|
1309 |
} |
1310 |
|
1311 |
public void prompt () { |
1312 |
this.setVisible(true); |
1313 |
} |
1314 |
|
1315 |
private String getDescription (int index) { |
1316 |
if (index < 0) |
1317 |
return ""; |
1318 |
switch (index) {
|
1319 |
case 0: return "SLAM and junk"; |
1320 |
case 1: return "I'm not sure this works"; |
1321 |
case 2: return "Push them into the light"; |
1322 |
case 3: return "Watch out for clock repair guys"; |
1323 |
case 4: return "But make sure he's dead, geez, why would you let him get away? I mean come on, " |
1324 |
+"he's just lying there and everyone's too busy looking at people flying through the sky to "
|
1325 |
+"notice? Oh yeah, that's a good transition to a new season, let's make the audience think "
|
1326 |
+"he's dead and then pull a fast one on them, they'll never see that coming.";
|
1327 |
|
1328 |
default: return "Task not recognized"; |
1329 |
} |
1330 |
} |
1331 |
|
1332 |
public void actionPerformed (ActionEvent e) { |
1333 |
Object source = e.getSource();
|
1334 |
if (source == btnSubmit) {
|
1335 |
txtParameters.setText(txtParameters.getText().trim()); |
1336 |
|
1337 |
|
1338 |
this.setVisible(false); |
1339 |
} else if (source == btnCancel) { |
1340 |
this.setVisible(false); |
1341 |
} |
1342 |
} |
1343 |
|
1344 |
public void valueChanged (ListSelectionEvent e) { |
1345 |
int index = availableList.getSelectedIndex();
|
1346 |
if (index >= 0) |
1347 |
txtDescription.setText(getDescription(index)); |
1348 |
} |
1349 |
|
1350 |
} |
1351 |
|
1352 |
class BatteryIcon implements Icon{ |
1353 |
private int width; |
1354 |
private int height; |
1355 |
private int level; |
1356 |
|
1357 |
public BatteryIcon(){
|
1358 |
width = 100;
|
1359 |
height =100;
|
1360 |
level = 100;
|
1361 |
} |
1362 |
|
1363 |
public BatteryIcon(int startLevel){ |
1364 |
width = 50;
|
1365 |
height = 50;
|
1366 |
level = startLevel; |
1367 |
} |
1368 |
|
1369 |
public BatteryIcon(int startLevel, int w, int h){ |
1370 |
level = startLevel; |
1371 |
width = w; |
1372 |
height = h; |
1373 |
} |
1374 |
|
1375 |
public void paintIcon(Component c, Graphics g, int x, int y) { |
1376 |
Graphics2D g2d = (Graphics2D) g.create(); |
1377 |
//background
|
1378 |
g2d.setColor(Color.WHITE);
|
1379 |
g2d.fillRect(x +1 ,y + 1,width-2,height-2); |
1380 |
//outline
|
1381 |
g2d.setColor(Color.BLACK);
|
1382 |
g2d.drawRect((int)(x + width*.3) ,y + 2,(int)(width*.4),height -4); |
1383 |
//battery life rectangle
|
1384 |
g2d.setColor(Color.GREEN);
|
1385 |
int greenX = (int)(x + 1 + width*.3); |
1386 |
int greenY = (int)((y+3) + Math.abs(level-100.0)*(height-6)/(100)); |
1387 |
int greenWidth = (int)(width*.4 - 2)+1; |
1388 |
int greenHeight = 1+(int)(level-0.0)*(height-6)/(100); |
1389 |
g2d.fillRect(greenX, greenY, greenWidth, greenHeight); |
1390 |
//text
|
1391 |
g2d.setColor(Color.BLACK);
|
1392 |
g2d.drawString(level + "%", greenX + greenWidth/2 - 10, greenY + greenHeight/2 + 5); |
1393 |
|
1394 |
g2d.dispose(); |
1395 |
} |
1396 |
|
1397 |
public void setLevel(int newLevel){ |
1398 |
level = newLevel; |
1399 |
} |
1400 |
|
1401 |
public int getIconWidth() { |
1402 |
return width;
|
1403 |
} |
1404 |
|
1405 |
public int getIconHeight() { |
1406 |
return height;
|
1407 |
} |
1408 |
} |
1409 |
|
1410 |
|
1411 |
} |