id
stringlengths
36
36
text
stringlengths
1
1.25M
d3c8d97a-7f11-4609-a817-8ee332ca7f76
@Override public void bridgeData(BridgeDataEvent arg0) { BridgePhidget b = (BridgePhidget)arg0.getSource(); try { double data_0; double data_1; double k_0 = config.getLoadCellKValue(0, 0); double k_1 = config.getLoadCellKValue(0, 1); double offset_0 = config.getLoadCellOffset(0, 0); double offset_1 = config.getLoadCellOffset(0, 1); POSSIBLE_TARE_0 = k_0 * (b.getBridgeValue(0) + offset_0); data_0 = k_0 * (b.getBridgeValue(0) + offset_0) - TARE_0; POSSIBLE_TARE_1 = k_1 * (b.getBridgeValue(1) + offset_1); data_1 = k_1 * (b.getBridgeValue(1) + offset_1) - TARE_1; int i_data_0 = (int)(data_0 * 10); int i_data_1 = (int)(data_1 * 10); data_0 = i_data_0 / 10.0; data_1 = i_data_1 / 10.0; String rfid0 = rfids.get(config.getRfidSerials()[1]).getDeviceLabel(); String rfid1 = rfids.get(config.getRfidSerials()[0]).getDeviceLabel(); System.out.print(" \r"); System.out.print(rfid0 + ": " + data_0 + "\t" + rfid1 + ":" + data_1 + "\r"); //Thread.sleep(500); } catch (PhidgetException e) { e.printStackTrace(); } }
5b02cb9a-a7e3-44ed-9368-895db0b53b6f
@Override public void detached(DetachEvent arg0) { RFIDPhidget r = (RFIDPhidget)arg0.getSource(); try { System.out.println("Detached: " + r.getDeviceLabel()); } catch (PhidgetException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5f17c44a-b026-435e-a259-b4ccaa9b3e47
@Override public void attached(AttachEvent ae) { try { RFIDPhidget r = (RFIDPhidget)ae.getSource(); System.out.println("RFID attached: " + ae.getSource().getDeviceLabel() + ", S/N: " + ae.getSource().getSerialNumber()); r.setAntennaOn(true); r.setLEDOn(true); } catch (PhidgetException e) { e.printStackTrace(); } }
05d20436-bc82-48d4-a40b-1de7dfce7208
public RfidTagGainerListener(RFIDPhidget rfid, Boolean flag) { myRfid = rfid; myFlag = flag; }
b89c0ea7-74ad-4b63-9550-effdc45d9d64
@Override public void tagGained(TagGainEvent tge) { if(myRfid == tge.getSource()) { myFlag = true; System.out.println("Tag gained: " + tge.getValue()); new Thread(new GetData(myRfid, tge.getValue())).start(); } }
14703f8b-f613-425e-95ce-bebcc7c80b1c
public GetData(RFIDPhidget r, String tag) { myRfid = r; myTag = tag; }
369c184a-a100-4c77-8bb1-311817fabd3d
@Override public void run() { try { // Set up info needed for logging data in CSV file DateFormat df = new SimpleDateFormat("yyyy-dd-MM_HH:mm:ss"); Date date = Calendar.getInstance().getTime(); String dateString = df.format(date); DataLogger dl = new DataLogger("log/" + myRfid.getDeviceLabel().toUpperCase() + "_" + df.format(date) + ".csv", myRfid.getDeviceLabel()); // Get all info pertaining to bridges and load cells int mySerial = myRfid.getSerialNumber(); int myBridgeIndex = config.getRfidBridge(mySerial); int myLoadCell = config.getRfidLoadCell(mySerial); double myOffset = config.getLoadCellOffset(myBridgeIndex, myLoadCell); double myK = config.getLoadCellKValue(myBridgeIndex, myLoadCell); BridgePhidget myBridge = bridges.get(config.getBridgeSerial(myBridgeIndex)); // Start grabbing data from the load cell double last_data = myK * (myBridge.getBridgeValue(myLoadCell) + myOffset) - (myLoadCell == 0 ? TARE_0 : TARE_1); int i_last_data = (int)(last_data * 10); last_data = i_last_data / 10.0; while(myRfid.getTagStatus()) { double data; if(myLoadCell == 0) { POSSIBLE_TARE_0 = myK * (myBridge.getBridgeValue(myLoadCell) + myOffset); data = myK * (myBridge.getBridgeValue(myLoadCell) + myOffset) - TARE_0; } else { POSSIBLE_TARE_1 = myK * (myBridge.getBridgeValue(myLoadCell) + myOffset); data = myK * (myBridge.getBridgeValue(myLoadCell) + myOffset) - TARE_1; } int i_data = (int)(data * 10); data = i_data / 10.0; //if(data != last_data) //{ //System.out.print(" \r"); //System.out.print(myRfid.getDeviceLabel() + ": " + data + "\r"); //} last_data = data; dl.logRow(dateString, myTag, data); Thread.sleep(DATA_RATE); } System.out.println("\nWriting..."); dl.writeFile(); System.out.println("Success!"); dl.close(); } catch (PhidgetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
a4a3a2c5-33f6-4085-a88d-a54fb26fcfe4
public static void main(String[] args) { if(args.length != 2) { System.out.print("Incorrect arguments. Example usage: 'java -jar Calibrator.jar x y'\n" + "where x is Phidget Bridge serial number and y is the index number of the load cell"); System.exit(-1); } sn = Integer.parseInt(args[0]); index = Integer.parseInt(args[1]); System.out.println("Searching for Bridge " + sn); try { bridge = new BridgePhidget(); bridge.open(sn); bridge.addAttachListener(new AttachListener() { @Override public void attached(AttachEvent ae) { try { System.out.println("Bridge attached: " + ae.getSource().getDeviceLabel() + ", S/N: " + ae.getSource().getSerialNumber()); BridgePhidget b = (BridgePhidget)ae.getSource(); b.setDataRate(500); b.setGain(index, BridgePhidget.PHIDGET_BRIDGE_GAIN_32); b.setEnabled(index, true); Thread.sleep(1000); } catch (PhidgetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); while (true) { if(bridge.isAttached() && bridge.getEnabled(index)) { double value = bridge.getBridgeValue(index); System.out.println(value); Thread.sleep(500); } } } catch (Exception e) { } }
97cd79a7-c1de-4ffa-a2e4-33e94773cfed
@Override public void attached(AttachEvent ae) { try { System.out.println("Bridge attached: " + ae.getSource().getDeviceLabel() + ", S/N: " + ae.getSource().getSerialNumber()); BridgePhidget b = (BridgePhidget)ae.getSource(); b.setDataRate(500); b.setGain(index, BridgePhidget.PHIDGET_BRIDGE_GAIN_32); b.setEnabled(index, true); Thread.sleep(1000); } catch (PhidgetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
69a0376c-37f2-487f-979e-c95240324857
public ConfigParser(String fileName) throws FileNotFoundException, IOException { props = new Properties(); props.load(new FileInputStream(new File(fileName))); getProperties(); }
540e79e5-c27b-479b-bbb9-1ec58eb742fb
public int getNumRfidReaders() { return rfid_readers; }
fdaefae5-d101-4b9b-a9f8-540e21b84b17
public int getNumBridges() { return bridges; }
167eb310-ace3-422c-86b8-243dac7b7839
public int[] getRfidSerials() { return rfid_serials; }
38852cc4-cd51-4e45-bc98-8f42d660460a
public int[] getBridgeSerials() { return bridge_serials; }
1d31be80-0828-4c11-8e12-4b258c04c612
public int getRfidSerial(int i) throws ArrayIndexOutOfBoundsException { if(i >= rfid_readers) throw new ArrayIndexOutOfBoundsException("RFID Serial index out of bounds\n"); return rfid_serials[i]; }
12a37cb2-5727-4362-9b53-14cfadb559a6
public int getBridgeSerial(int i) throws ArrayIndexOutOfBoundsException { if (i >= bridges) throw new ArrayIndexOutOfBoundsException("Bridge Serial index out of bounds\n"); return bridge_serials[i]; }
ef5321c0-fb57-4f23-8830-2d2124941042
public int getRfidBridge(int serial) { Integer i = rfid_map.get(serial); if(i == null) return -1; return rfid_pairings[i].getBridge(); }
d6d86a0f-200f-4a44-a3b9-c372ebb42d9f
public int getRfidLoadCell(int serial) { Integer i = rfid_map.get(serial); if(i == null) return -1; return rfid_pairings[i].getLoadCell(); }
e2ff5af8-3dc3-4a70-8e36-74e72b3f557c
public int getTimeout() { return timeout; }
208f5724-57de-455c-8152-89ab6d027cd6
public int getDataRate() { return data_rate; }
f9eb06b1-9387-41a2-b8e7-e523d06f1b2a
public double getLoadCellOffset(int bridge, int input) { String offset = props.getProperty("offset_" + bridge + "_" + input, "0"); return Double.parseDouble(offset); }
e734fc2d-9388-44af-975a-c1886832c901
public double getLoadCellKValue(int bridge, int input) { String k = props.getProperty("k_" + bridge + "_" + input, "1"); return Double.parseDouble(k); }
e9029d78-d63a-4503-af20-c6fa0b455375
private void getProperties() { bridges = Integer.parseInt(props.getProperty("bridges", "0")); rfid_readers = Integer.parseInt(props.getProperty("rfid_readers", "0")); bridge_serials = new int[bridges]; rfid_serials = new int[rfid_readers]; rfid_pairings = new BridgePair[rfid_readers]; rfid_map = new HashMap<Integer, Integer>(rfid_readers); bridge_map = new HashMap<Integer, Integer>(bridges); timeout = Integer.parseInt(props.getProperty("timeout", "5")); data_rate = Integer.parseInt(props.getProperty("data_rate", "500")); // Get all the bridges and their associated indexes. for(int i = 0; i < bridges; i++) { bridge_serials[i] = Integer.parseInt( props.getProperty("bridge_" + i, "-1")); bridge_map.put(bridge_serials[i], i); } // Get all rfids and their associated indexes. for(int i = 0; i < rfid_readers; i++) { rfid_serials[i] = Integer.parseInt( props.getProperty("rfid_" + i, "-1")); rfid_map.put(rfid_serials[i], i); } // Get all rfids' Bridge and Load Cell pairings for(int i = 0; i < rfid_readers; i++) { String p = props.getProperty("rfid_" + i + "_pair"); String[] vals = p.split("-"); rfid_pairings[i] = new BridgePair( Integer.parseInt(vals[0]), Integer.parseInt(vals[1])); } }
16e29d87-7c01-44c0-b132-1267d8d0d597
public BridgePair(int b, int l) { bridge = b; loadCell = l; }
d50bd5b3-81b9-42b4-9174-95cf3a3fe599
public int getBridge() {return bridge;}
efcd880f-4fd8-4f24-83fe-7c09732197ed
public int getLoadCell() {return loadCell;}
a652a9f3-201b-441e-b23b-d74f869f0697
public DataLogger(String fileName, String devId) throws IOException { deviceId = devId; file = new FileWriter(fileName); writer = new CSVWriter(file); dates = new ArrayList<>(100); tagIds = new ArrayList<>(100); weightData = new ArrayList<>(100); }
0febda5d-4f32-4512-9007-6cc0ca190929
public DataLogger(String fileName, int devId) throws IOException { deviceId = Integer.toString(devId); file = new FileWriter(fileName); writer = new CSVWriter(file); dates = new ArrayList<>(100); tagIds = new ArrayList<>(100); weightData = new ArrayList<>(100); }
17cf06d6-87cf-47a2-9157-3be23c32105e
public void logRow(String date, String tagId, double weight) { dates.add(date); tagIds.add(tagId); weightData.add(weight); }
d030feaf-c58b-4b0b-a39b-8ed9a8ba4d1f
public void writeFile() { for(int i = 0; i < dates.size(); i++) { String[] row = new String[3]; row[0] = dates.get(i); row[1] = tagIds.get(i); row[2] = Double.toString(weightData.get(i)); writer.writeNext(row); } }
ebc57cd2-84e2-414c-a11e-6e35c682cf66
public void close() throws IOException { writer.close(); }
72002cbd-5f5d-463d-a299-9d80bbfb7f57
public static void main(String[] args) { try { BirdWeightLogger bwl = new BirdWeightLogger(); } catch (FileNotFoundException e) { System.out.println("Configuration file not found"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
0590eac0-e2ad-4815-8cac-48b0bbd3c7c9
public static void main(String[] args) { Scanner s = new Scanner(System.in); while(true) { System.out.println("Phidget type:\n\t1. Bridge\n\t2. RFID"); int type = s.nextInt(); Phidget phidget; try { if(type == 1) phidget = new BridgePhidget(); else phidget = new RFIDPhidget(); System.out.print("Enter serial: "); int serial = s.nextInt(); phidget.open(serial); System.out.println("Waiting..."); phidget.waitForAttachment(1000*5); System.out.println("Phidget attached. Current name is " + phidget.getDeviceLabel()); String name; while(true) { System.out.print("Enter name: "); name = s.next(); if(name.length() <= 10) break; System.out.println("Name too long! Must be 10 or less chars."); } System.out.println("Setting name..."); phidget.setDeviceLabel(name); System.out.println("Success if same: " + name + "... " + phidget.getDeviceLabel()); phidget.close(); } catch (PhidgetException e) { e.printStackTrace(); } } }
cdedbfae-ad4d-4c91-aa74-3e1b092fff4f
public static void main(String[] args) { Scanner s = new Scanner(System.in); while(true) { System.out.println("Phidget type:\n\t1. Bridge\n\t2. RFID"); int type = s.nextInt(); Phidget phidget; try { if(type == 1) phidget = new BridgePhidget(); else phidget = new RFIDPhidget(); System.out.print("Enter serial: "); int serial = s.nextInt(); phidget.open(serial); System.out.println("Waiting..."); phidget.waitForAttachment(1000*5); System.out.println("Phidget attached. Current name is " + phidget.getDeviceLabel()); String name; while(true) { System.out.print("Enter name: "); name = s.next(); if(name.length() <= 10) break; System.out.println("Name too long! Must be 10 or less chars."); } System.out.println("Setting name..."); phidget.setDeviceLabel(name); System.out.println("Success if same: " + name + "... " + phidget.getDeviceLabel()); phidget.close(); } catch (PhidgetException e) { e.printStackTrace(); } } }
0d4d7e89-dcb4-4510-8edd-a65a2394d9e9
public static void main(String[] args) { try { RFIDPhidget rfid = new RFIDPhidget(); rfid.addAttachListener(new AttachListener() { @Override public void attached(AttachEvent ae) { System.out.println("RFID reader attached."); RFIDPhidget r = (RFIDPhidget)ae.getSource(); try { r.setAntennaOn(true); r.setLEDOn(true); } catch (PhidgetException e) { e.printStackTrace(); } } }); rfid.addTagGainListener(new TagGainListener() { @Override public void tagGained(TagGainEvent tge) { System.out.println("Tag: " + tge.getValue()); } }); rfid.open(335827); rfid.waitForAttachment(1000*3); } catch (PhidgetException e) { e.printStackTrace(); } }
e64ad21a-313c-4873-b2af-d5eb841d618d
@Override public void attached(AttachEvent ae) { System.out.println("RFID reader attached."); RFIDPhidget r = (RFIDPhidget)ae.getSource(); try { r.setAntennaOn(true); r.setLEDOn(true); } catch (PhidgetException e) { e.printStackTrace(); } }
e20e2284-c678-45f2-8e87-3d305583bb8d
@Override public void tagGained(TagGainEvent tge) { System.out.println("Tag: " + tge.getValue()); }
3338cc3c-0d99-4fdb-b0b8-486d616b1409
@Override public String getMessage() { String message = JOptionPane.showInputDialog("Enter your message"); return message; }
5ee54b28-e7d7-4a6a-8ecb-a583f3577c68
@Override public void outputMessage(String message) { System.out.println(message); }
bb8b43b9-fbf9-4a4d-8850-01040b92b59a
public static void main(String[] args) { /**Liskov's substitution method in place here. * MessageInput/output stays the same. * Can change ConsoleMessageInput to GuiMessageInput without any other changes. (line 22) */ MessageInput input = new GuiMessageInput(); MessageOutput output = new ConsoleMessageOutput(); //Line 26 instantiates a MessageManager through the constructor we created in MessageManager MessageManager service = new MessageManager(input, output); //Lines 28/29 instantiates a messageManager through the default constructor. They both work in the same way. // service.setInput(input); // service.setOutput(output); service.processMessage(); }
ac57b324-fc45-42cb-ba30-3b77010ea546
@Override public String getMessage() { Scanner keyboardScanner = new Scanner(System.in); return keyboardScanner.nextLine(); }
8785a8eb-8540-4148-9b14-635f7d389f66
public abstract void outputMessage( String message );
2aac4a74-cd23-4446-8a9b-7fd25877f509
@Override public void outputMessage(String message) { JOptionPane.showMessageDialog(null, message); }
221c1e0b-eec2-42bc-b04a-d668d96f1124
public abstract String getMessage();
34eb0648-900a-467e-8bfd-d6c6828d8252
public MessageManager(){ }
ef9ae2ca-e5d9-46a8-bbb8-4b2ef6d769c5
public MessageManager(MessageInput input, MessageOutput output){ this.input = input; this.output = output; }
161e8aa2-1d96-4faf-b3c6-e8d5b9c7a76e
public void processMessage(){ String message = input.getMessage(); output.outputMessage(message); }
026e4836-71d6-4cf5-878e-f124185fe1b5
public MessageInput getInput() { return input; }
776f8eb2-fb76-4ff8-8e7f-f9b6991e6a5d
public void setInput(MessageInput input) { if (input == null){ //notify user input is invalid } this.input = input; }
5b1644cf-e42a-4a6f-92c2-fa81c4b0766f
public MessageOutput getOutput() { return output; }
2ce3d3d5-7028-465a-afe4-967bfd89abfd
public void setOutput(MessageOutput output) { this.output = output; }
a8ac6232-b746-4663-852b-bbd5a06b2733
public DragSupport(Scene target, final KeyCode modifier, final Orientation orientation, final Property<Number> property) { this(target, modifier, MouseButton.PRIMARY, orientation, property, 1); }
00360f57-1b38-4988-90c2-cd35d60d253f
public DragSupport(Scene target, final KeyCode modifier, MouseButton mouseButton, final Orientation orientation, final Property<Number> property) { this(target, modifier, mouseButton, orientation, property, 1); }
9a10c229-49bb-491e-807b-76bb7059a9f6
public void detach() { target.removeEventHandler(MouseEvent.ANY, mouseEventHandler); target.removeEventHandler(KeyEvent.ANY, keyboardEventHandler); }
b32a995a-d0c6-4644-a5fd-724c84f9ee44
public DragSupport(Scene target, final KeyCode modifier, final Orientation orientation, final Property<Number> property, final double factor) { this(target, modifier, MouseButton.PRIMARY, orientation, property, factor); }
d659e1d5-ed65-4d32-a752-75dbda8cacaf
public DragSupport(Scene target, final KeyCode modifier, final MouseButton mouseButton, final Orientation orientation, final Property<Number> property, final double factor) { this.target = target; mouseEventHandler = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent t) { if (t.getEventType() != MouseEvent.MOUSE_ENTERED_TARGET && t.getEventType() != MouseEvent.MOUSE_EXITED_TARGET) { lastMouseEvent = t; } if (t.getEventType() == MouseEvent.MOUSE_PRESSED) { if (t.getButton() == mouseButton && isModifierCorrect(t, modifier)) { anchor = property.getValue(); dragAnchor = getCoord(t, orientation); t.consume(); } } else if (t.getEventType() == MouseEvent.MOUSE_DRAGGED) { if (t.getButton() == mouseButton && isModifierCorrect(t, modifier)) { property.setValue(anchor.doubleValue() + (getCoord(t, orientation) - dragAnchor) * factor); t.consume(); } } } }; keyboardEventHandler = new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent t) { if (t.getEventType() == KeyEvent.KEY_PRESSED) { if (t.getCode() == modifier) { anchor = property.getValue(); if (lastMouseEvent != null) { dragAnchor = getCoord(lastMouseEvent, orientation); } t.consume(); } } else if (t.getEventType() == KeyEvent.KEY_RELEASED) { if (t.getCode() != modifier && isModifierCorrect(t, modifier)) { anchor = property.getValue(); if (lastMouseEvent != null) { dragAnchor = getCoord(lastMouseEvent, orientation); } t.consume(); } } } }; target.addEventHandler(MouseEvent.ANY, mouseEventHandler); target.addEventHandler(KeyEvent.ANY, keyboardEventHandler); }
065f506e-e55b-47ec-8510-062ea0267aeb
@Override public void handle(MouseEvent t) { if (t.getEventType() != MouseEvent.MOUSE_ENTERED_TARGET && t.getEventType() != MouseEvent.MOUSE_EXITED_TARGET) { lastMouseEvent = t; } if (t.getEventType() == MouseEvent.MOUSE_PRESSED) { if (t.getButton() == mouseButton && isModifierCorrect(t, modifier)) { anchor = property.getValue(); dragAnchor = getCoord(t, orientation); t.consume(); } } else if (t.getEventType() == MouseEvent.MOUSE_DRAGGED) { if (t.getButton() == mouseButton && isModifierCorrect(t, modifier)) { property.setValue(anchor.doubleValue() + (getCoord(t, orientation) - dragAnchor) * factor); t.consume(); } } }
8cb31d4d-3715-46f4-be39-85df9e4c6b70
@Override public void handle(KeyEvent t) { if (t.getEventType() == KeyEvent.KEY_PRESSED) { if (t.getCode() == modifier) { anchor = property.getValue(); if (lastMouseEvent != null) { dragAnchor = getCoord(lastMouseEvent, orientation); } t.consume(); } } else if (t.getEventType() == KeyEvent.KEY_RELEASED) { if (t.getCode() != modifier && isModifierCorrect(t, modifier)) { anchor = property.getValue(); if (lastMouseEvent != null) { dragAnchor = getCoord(lastMouseEvent, orientation); } t.consume(); } } }
4e9a51fb-5016-4143-aaaa-91a0915f387a
private boolean isModifierCorrect(KeyEvent t, KeyCode keyCode) { return (keyCode != KeyCode.ALT ^ t.isAltDown()) && (keyCode != KeyCode.CONTROL ^ t.isControlDown()) && (keyCode != KeyCode.SHIFT ^ t.isShiftDown()) && (keyCode != KeyCode.META ^ t.isMetaDown()); }
b9b61fb7-679f-4995-b166-3b7b82e2f8c7
private boolean isModifierCorrect(MouseEvent t, KeyCode keyCode) { return (keyCode != KeyCode.ALT ^ t.isAltDown()) && (keyCode != KeyCode.CONTROL ^ t.isControlDown()) && (keyCode != KeyCode.SHIFT ^ t.isShiftDown()) && (keyCode != KeyCode.META ^ t.isMetaDown()); }
30efd884-b4f4-4e0d-80f0-b654b5b5b5f0
private double getCoord(MouseEvent t, Orientation orientation) { switch (orientation) { case HORIZONTAL: return t.getScreenX(); case VERTICAL: return t.getScreenY(); default: throw new IllegalArgumentException("This orientation is not supported: " + orientation); } }
d902c8e0-3081-49c3-b5b5-998bf74fb4e9
public Axes() { this(1); }
0e9417e6-2427-428c-89a1-a2cab4787818
public Axes(double scale) { Cylinder axisX = new Cylinder(3, 60); axisX.getTransforms().addAll(new Rotate(90, Rotate.Z_AXIS), new Translate(0, 30, 0)); axisX.setMaterial(new PhongMaterial(Color.RED)); Cylinder axisY = new Cylinder(3, 60); axisY.getTransforms().add(new Translate(0, 30, 0)); axisY.setMaterial(new PhongMaterial(Color.GREEN)); Cylinder axisZ = new Cylinder(3, 60); axisZ.setMaterial(new PhongMaterial(Color.BLUE)); axisZ.getTransforms().addAll(new Rotate(90, Rotate.X_AXIS), new Translate(0, 30, 0)); getChildren().addAll(axisX, axisY, axisZ); getTransforms().add(new Scale(scale, scale, scale)); }
4a5a8bf7-c263-4050-b8af-7b092bdbc72b
@Override public void start(Stage primaryStage) throws Exception { listener = new LeapListener(); controller = new Controller(); controller.addListener(listener); // HandImporter handLeft=new HandImporter("modelLeft.json"); /* Model downloaded from https://github.com/leapmotion/leapjs-rigged-hand/tree/master/src/models */ // HandImporter handLeft=new HandImporter("left_hand_terrence_3.js"); HandImporter handLeft=new HandImporter("modelLeft.json",true,false); handLeft.readModel(); forestLeft=handLeft.getJointForest(); skinningLeft=handLeft.getSkinningMeshView(); /* Model downloaded from https://github.com/leapmotion/leapjs-rigged-hand/blob/master/src/models/hand_models_v1.js */ HandImporter handRight=new HandImporter("modelRight.json",false,false); handRight.readModel(); forestRight=handRight.getJointForest(); skinningRight=handRight.getSkinningMeshView(); Group root = new Group(new Group(skinningLeft, forestLeft.get(0)), new Group(skinningRight, forestRight.get(0))); listener.doneLeftProperty().addListener((ov,b,b1)->{ if(b1){ List<Finger> fingersLeft=listener.getFingersLeft(); Platform.runLater(()->{ fingersLeft.stream() .filter(finger -> finger.isValid()) .forEach(finger -> { previousBone=null; Stream.of(Bone.Type.values()).map(finger::bone) .filter(bone -> bone.isValid() && bone.length()>0) .forEach(bone -> { if(previousBone!=null){ Joint joint = getJoint(false,finger,bone); Vector cross = bone.direction().cross(previousBone.direction()); double angle = bone.direction().angleTo(previousBone.direction()); joint.rx.setAngle(Math.toDegrees(angle)); joint.rx.setAxis(new Point3D(cross.getX(),-cross.getY(),cross.getZ())); } previousBone=bone; }); }); matrixRotateNode(false, listener.rollLeftProperty().get(), listener.pitchLeftProperty().get(), listener.yawLeftProperty().get()); Point3D moveLeft = listener.posHandLeftProperty().getValue().multiply(1d/leapScale); ((Joint)forestLeft.get(0)).t.setX(2-moveLeft.getX()); ((Joint)forestLeft.get(0)).t.setY(moveLeft.getY()); ((Joint)forestLeft.get(0)).t.setZ(-moveLeft.getZ()); ((SkinningMesh)skinningLeft.getMesh()).update(); }); } }); listener.doneRightProperty().addListener((ov,b,b1)->{ if(b1){ List<Finger> fingersRight=listener.getFingersRight(); Platform.runLater(()->{ fingersRight.stream() .filter(finger -> finger.isValid()) .forEach(finger -> { previousBone=null; Stream.of(Bone.Type.values()).map(finger::bone) .filter(bone -> bone.isValid() && bone.length()>0) .forEach(bone -> { if(previousBone!=null){ Joint joint = getJoint(true,finger,bone); Vector cross = bone.direction().cross(previousBone.direction()); double angle = bone.direction().angleTo(previousBone.direction()); joint.rx.setAngle(Math.toDegrees(angle)); joint.rx.setAxis(new Point3D(cross.getX(),-cross.getY(),cross.getZ())); } previousBone=bone; }); }); matrixRotateNode(true, listener.rollRightProperty().get(), listener.pitchRightProperty().get(), listener.yawRightProperty().get()); Point3D moveRight = listener.posHandRightProperty().getValue().multiply(1d/leapScale); ((Joint)forestRight.get(0)).t.setX(-2-moveRight.getX()); ((Joint)forestRight.get(0)).t.setY(moveRight.getY()); ((Joint)forestRight.get(0)).t.setZ(-moveRight.getZ()); ((SkinningMesh)skinningRight.getMesh()).update(); }); } }); Scene scene = new Scene(root, 800, 600, true, SceneAntialiasing.BALANCED); PerspectiveCamera perspectiveCamera = new PerspectiveCamera(); perspectiveCamera.setNearClip(0.001); perspectiveCamera.setFarClip(10000); scene.setCamera(perspectiveCamera); primaryStage.setScene(scene); primaryStage.setTitle("RIGGED HANDS - JAVAFX 3D"); primaryStage.show(); Translate centerTranslate = new Translate(); centerTranslate.xProperty().bind(scene.widthProperty().divide(2)); centerTranslate.yProperty().bind(scene.heightProperty().divide(2)); scene.getRoot().getTransforms().addAll(centerTranslate, translate, translateZ, rotateX, rotateY, translateY); DragSupport dragSupport = new DragSupport(scene, null, MouseButton.SECONDARY, Orientation.VERTICAL, translateZ.zProperty(), -3); DragSupport dragSupport1 = new DragSupport(scene, null, Orientation.HORIZONTAL, rotateY.angleProperty()); DragSupport dragSupport2 = new DragSupport(scene, null, Orientation.VERTICAL, rotateX.angleProperty()); DragSupport dragSupport3 = new DragSupport(scene, null, MouseButton.MIDDLE, Orientation.HORIZONTAL, translate.xProperty()); DragSupport dragSupport4 = new DragSupport(scene, null, MouseButton.MIDDLE, Orientation.VERTICAL, translate.yProperty()); ((Joint)forestLeft.get(0)).t.setX(4); ((SkinningMesh)skinningLeft.getMesh()).update(); ((Joint)forestRight.get(0)).t.setX(-4); ((SkinningMesh)skinningRight.getMesh()).update(); }
6a8342cb-835c-465f-94ef-3eaa7404bae4
@Override public void stop(){ controller.removeListener(listener); }
5c3cda19-26e2-40c7-baa4-02a6607feae6
private Joint getJoint(boolean right, Finger finger, Bone bone){ int f = 0,b = 0; String name=""; switch(finger.type()){ case TYPE_THUMB: name="thumb"; f=0; break; case TYPE_INDEX: name="index"; f=1; break; case TYPE_MIDDLE: name="middle"; f=2; break; case TYPE_RING: name="ring"; f=3; break; case TYPE_PINKY: name="pinky"; f=4; break; } switch(bone.type()){ case TYPE_METACARPAL: b=0; break; case TYPE_PROXIMAL: b=1; break; case TYPE_INTERMEDIATE: b=2; break; case TYPE_DISTAL: b=3; break; } String bonePattern1="#Finger_"+Integer.toString(f)+Integer.toString(b-1); String bonePattern2="#"+name+"-"+Integer.toString(b-1); if(right){ Joint joint = (Joint)forestRight.get(0).lookup(bonePattern1); if(joint==null){ joint = (Joint)forestRight.get(0).lookup(bonePattern2); } return joint; } Joint joint = (Joint)forestLeft.get(0).lookup(bonePattern1); if(joint==null){ joint = (Joint)forestLeft.get(0).lookup(bonePattern2); } return joint; }
95000baf-8da5-49f2-be98-e875d3ebbaee
private void matrixRotateNode(boolean right, double alf, double bet, double gam){ double A11=Math.cos(alf)*Math.cos(gam); double A12=Math.cos(bet)*Math.sin(alf)+Math.cos(alf)*Math.sin(bet)*Math.sin(gam); double A13=Math.sin(alf)*Math.sin(bet)-Math.cos(alf)*Math.cos(bet)*Math.sin(gam); double A21=-Math.cos(gam)*Math.sin(alf); double A22=Math.cos(alf)*Math.cos(bet)-Math.sin(alf)*Math.sin(bet)*Math.sin(gam); double A23=Math.cos(alf)*Math.sin(bet)+Math.cos(bet)*Math.sin(alf)*Math.sin(gam); double A31=Math.sin(gam); double A32=-Math.cos(gam)*Math.sin(bet); double A33=Math.cos(bet)*Math.cos(gam); double d = Math.acos((A11+A22+A33-1d)/2d); if(d!=0d){ double den=2d*Math.sin(d); Point3D p= new Point3D((A32-A23)/den,(A13-A31)/den,(A21-A12)/den); if(right){ ((Joint)forestRight.get(0)).rx.setAxis(p); ((Joint)forestRight.get(0)).rx.setAngle(Math.toDegrees(d)); } else { ((Joint)forestLeft.get(0)).rx.setAxis(p); ((Joint)forestLeft.get(0)).rx.setAngle(Math.toDegrees(d)); } } }
b82ae4a2-6c64-404a-87c0-62ba98f0d25c
public static void main(String[] args) { launch(args); }
e8e836ac-2aa8-403c-a3f3-5313f815cbf8
public HandImporter(String nameFile, boolean skeletal, boolean axes){ this.skeletal=skeletal; this.axes=axes; reader = JsonProvider.provider().createReader(HandImporter.class.getResourceAsStream("/resources/"+nameFile)); }
4708b117-9d17-4278-8471-ed7716d11513
public void readModel(){ readModel(1f); }
09461cbe-3112-4c0b-a22e-fb97107fa957
public void readModel(float scale){ if(reader==null){ return; } JsonObject object = reader.readObject(); JsonArray vertices = object.getJsonArray("vertices"); JsonArray uvs = null; if(!object.getJsonArray("uvs").isEmpty()){ uvs=object.getJsonArray("uvs").getJsonArray(0); } JsonArray faces = object.getJsonArray("faces"); JsonArray skinIndices = object.getJsonArray("skinIndices"); JsonArray skinWeights = object.getJsonArray("skinWeights"); JsonArray normals = object.getJsonArray("normals"); if(debug){ System.out.println("vertices = " + vertices.size()); if(uvs!=null){ System.out.println("uvs = " + uvs.size()); } System.out.println("faces = " + faces.size()); System.out.println("skinIndices = " + skinIndices.size()); System.out.println("skinWeights = " + skinWeights.size()); System.out.println("normals = " + normals.size()); } JsonObject metadata = object.getJsonObject("metadata"); int facesNumber = metadata.getInt("faces"); int nPoints = metadata.getInt("vertices"); int texCoordsNumber = 2; // so at least nTVerts=1 if(!metadata.getJsonArray("uvs").isEmpty()){ texCoordsNumber=metadata.getJsonArray("uvs").getInt(0); } final int MINMAXLEN = vertices.size()/nPoints; // 3 float[] min = new float[MINMAXLEN]; float[] max = new float[MINMAXLEN]; Arrays.fill(min, Integer.MAX_VALUE); Arrays.fill(max, Integer.MIN_VALUE); final int LEN = faces.size()/facesNumber; // (texCoordsNumber>0?11:8); // item 0: type of element: is always 42/34 final int V1 = 1; final int V2 = 2; final int V3 = 3; // item 4: material_index: is always 0 final int UV1 = 5; final int UV2 = 6; final int UV3 = 7; final int N1 = (uvs!=null)?8:5; final int N2 = (uvs!=null)?9:6; final int N3 = (uvs!=null)?10:7; int[][] pfaces = new int[facesNumber][]; int[][] pnormals = new int[facesNumber][]; PolygonMesh polygonMesh = new PolygonMesh(); polygonMesh.getPoints().ensureCapacity(nPoints); polygonMesh.getTexCoords().ensureCapacity(texCoordsNumber); polygonMesh.getFaceSmoothingGroups().ensureCapacity(facesNumber); for (int i = 0; i < vertices.size(); i++) { float c = (float) (scale* vertices.getJsonNumber(i).doubleValue()); polygonMesh.getPoints().addAll(c); int j = i % MINMAXLEN; min[j] = Math.min(min[j], c); max[j] = Math.max(max[j], c); } if(uvs!=null){ for (int i = 0; i < uvs.size(); i++) { polygonMesh.getTexCoords().addAll((float) uvs.getJsonNumber(i).doubleValue()); } } else { for (int i = 0; i < texCoordsNumber; i++) { polygonMesh.getTexCoords().addAll(0f); // create at least 2 coordinates } } float[] fnormals = new float[normals.size()]; for (int i = 0; i < normals.size(); i++) { fnormals[i] = (float) normals.getJsonNumber(i).doubleValue(); } for (int i = 0; i < faces.size(); i += LEN) { pfaces[i / LEN] = new int[] { faces.getInt(i + V1), (uvs!=null?faces.getInt(i + UV1):0), faces.getInt(i + V2), (uvs!=null?faces.getInt(i + UV2):0), faces.getInt(i + V3), (uvs!=null?faces.getInt(i + UV3):0)}; pnormals[i / LEN] = new int[] { faces.getInt(i + N1),faces.getInt(i + N2),faces.getInt(i + N3)}; } polygonMesh.faces = pfaces; int[] smGroups = SmoothingGroups.calcSmoothGroups(pfaces, pnormals, fnormals); polygonMesh.getFaceSmoothingGroups().setAll(smGroups); if(debug){ System.out.println("polygonMesh.getFaceSmoothingGroups() = " + polygonMesh.getFaceSmoothingGroups()); } if(debug){ for (int i = 0; i < MINMAXLEN; i++) { System.out.println(i + ", min[i] = " + min[i] + ", max[i] = " + max[i]); } } final int nJoints = metadata.getInt("bones"); float[][] weights = new float[nJoints][nPoints]; Affine[] bindTransforms = new Affine[nJoints]; Affine bindGlobalTransform = new Affine(); List<Joint> joints = new ArrayList<>(nJoints); for (int i = 0; i < nJoints; i++) { JsonObject bone = object.getJsonArray("bones").getJsonObject(i); Joint joint = new Joint(); String name = bone.getString("name"); if(debug){ System.out.println("name = " + name); } joint.setId(name); JsonArray pos = bone.getJsonArray("pos"); double x = scale * pos.getJsonNumber(0).doubleValue(); double y = scale * pos.getJsonNumber(1).doubleValue(); double z = scale * pos.getJsonNumber(2).doubleValue(); joint.t.setX(x); joint.t.setY(y); joint.t.setZ(z); bindTransforms[i] = new Affine(); int parentIndex = bone.getInt("parent"); if (parentIndex == -1) { if(axes){ joint.getChildren().add(new Axes(0.04)); } jointForest.add(joint); bindTransforms[i] = new Affine(new Translate(-x, -y, -z)); } else { if(axes){ joint.getChildren().add(new Axes(0.02)); } Joint parent = joints.get(parentIndex); parent.getChildren().add(joint); if(skeletal){ parent.getChildren().add(new Bone(0.02,new Point3D(x, y, z))); } try { bindTransforms[i] = new Affine(joint.getLocalToSceneTransform().createInverse()); } catch (NonInvertibleTransformException ex) { System.out.println("Error: "+ex); } } joints.add(joint); } for (int i = 0; i < skinIndices.size(); i += 2) { int pIndex = i / 2; int jIndex1 = skinIndices.getInt(i); int jIndex2 = skinIndices.getInt(i + 1); float weight1 = (float) skinWeights.getJsonNumber(i).doubleValue(); float weight2 = (float) skinWeights.getJsonNumber(i + 1).doubleValue(); float total = weight1 + weight2; weight1 /= total; weight2 /= total; if (weights[jIndex1][pIndex] == 0) { weights[jIndex1][pIndex] = weight1; } if (weights[jIndex2][pIndex] == 0) { weights[jIndex2][pIndex] = weight2; } } if(debug){ for (int j = 0; j < nPoints; j++) { double total = 0; for (int i = 0; i < nJoints; i++) { double w = weights[i][j]; total += w; } if (Math.abs(total - 1) > 1e-3) { System.out.println("j = " + j + ", total = " + total); for (int i = 0; i < nJoints; i++) { double w = weights[i][j]; if (w > 0) { System.out.println(" i = " + i + ", w = " + w); } } } } } SkinningMesh skinningMesh = new SkinningMesh(polygonMesh, weights, bindTransforms, bindGlobalTransform, joints, jointForest); skinningMeshView = new PolygonMeshView(skinningMesh); PhongMaterial phongMaterial = new PhongMaterial(); // phongMaterial.setDiffuseMap(new Image(getClass().getResourceAsStream("skin_texture_by_rosedecastille-d4lgv9y.jpg"))); phongMaterial.setDiffuseColor(Color.SANDYBROWN); skinningMeshView.setMaterial(phongMaterial); // skinningMeshView.setSubdivisionLevel(1); // NOT SUPPORTED FOR SKINNING MESHES if(skeletal){ skinningMeshView.setDrawMode(DrawMode.LINE); } skinningMeshView.setCullFace(CullFace.BACK); }
118f206e-3403-4674-9978-fd79818a4726
public PolygonMeshView getSkinningMeshView() { return skinningMeshView; }
3e0968df-62f6-4bff-9b7e-0a6f15484756
public List<Parent> getJointForest() { return jointForest; }
8f215f20-604b-4153-8530-b41e92021069
public Bone(){ this(1, Point3D.ZERO); }
20aa23dc-ea8d-4d4a-bfd8-981865c5b36d
public Bone(double scale, Point3D posJoint) { Box origin=new Box(10,10,10); origin.setMaterial(new PhongMaterial(Color.ORANGE)); Cylinder bone = new Cylinder(5, posJoint.magnitude()/scale); double angle = Math.toDegrees(Math.acos((new Point3D(0,1,0)).dotProduct(posJoint)/posJoint.magnitude())); Point3D axis = (new Point3D(0,1,0)).crossProduct(posJoint); bone.getTransforms().addAll(new Rotate(angle,0,0,0,axis), new Translate(0,posJoint.magnitude()/2d/scale, 0)); bone.setMaterial(new PhongMaterial(Color.CADETBLUE)); Sphere end = new Sphere(6); end.getTransforms().addAll(new Translate(posJoint.getX()/scale,posJoint.getY()/scale,posJoint.getZ()/scale)); end.setMaterial(new PhongMaterial(Color.YELLOW)); getChildren().addAll(origin, bone, end); getTransforms().add(new Scale(scale, scale, scale)); }
b3b0c610-884c-40e3-b812-879a08565b79
public Minus(ArithmeticExpression arg1, ArithmeticExpression arg2) { super(); this.arg1 = arg1; this.arg2 = arg2; super.operands.add(arg1); super.operands.add(arg2); }
ac43c254-a3b7-4c94-a8e3-3ace3b95b384
public int evaluate(Map<String, Integer> m) { return arg1.evaluate(m) - arg2.evaluate(m); }
f41a9888-fdbd-4a5d-af50-88e598292f0d
public Iterator<ArithmeticExpression> iterator() { return new ArithmeticExpressionIterator(this); }
46f80801-75a7-40bb-b706-1fac8de99e32
@Override public void add(ArithmeticExpression exp) { throw new UnsupportedOperationException(); }
f1eb8bfb-347f-400d-a980-4f29a9eaf7c5
public String toString() { return "(" + arg1 + "-" + arg2 + ")"; }
887dc8c7-6cdd-47ff-a18d-f1713f433e64
public String toString();
2d2f3069-304c-4904-8a82-35a1857cc043
public int evaluate(Map<String,Integer> m);
b8cc956b-76ad-4c1f-b675-c4669a89d6dd
public Plus() { super(); }
e290d049-ac8a-4aea-878b-562a520c9cd5
public int evaluate(Map<String,Integer> m) { int total = 0; for (ArithmeticExpression exp : operands) { total = total + exp.evaluate(m); } return total; }
e5cd465b-4a3a-4022-8473-fed139f993ba
public Iterator<ArithmeticExpression> iterator() { return new ArithmeticExpressionIterator(this); }
7a4eefd1-64a8-41f7-b033-6e8768a59068
public String toString() { String str = "("; Iterator<ArithmeticExpression> iter = operands.iterator(); while (iter.hasNext()) { str = str + iter.next(); if (iter.hasNext()) { str = str + "+"; } else { str = str + ")"; } } return str; }
841cbf58-e606-4c4c-adeb-462351c9b011
public Variable(String var) { this.var = var; }
841da434-6ff1-4ee0-a47b-3074861ed6d4
public int evaluate(Map<String, Integer> m) { int val = m.get(var); if (val <= 0 || val > 0) { //Tests if val is an int, since m.get() returns null if key not found return val; } throw new UnsupportedOperationException(); }
5dae0d5d-f2bd-4636-ae5d-7e739961715c
public Iterator<ArithmeticExpression> iterator() { return new ArithmeticExpressionIterator(this); }
73143c79-4733-4da4-97b6-f94872e19649
public String toString() { return var; }
7ed2876b-1c48-4412-a256-1a18c5714b2e
public static void main(String args[]) { //Create the expression (x * (2+3) - 10) * y for x = 5, y = 2 //Should equal 30 //Create the variable map Map<String, Integer> m = new HashMap<String, Integer>(); m.put("x", 5); m.put("y", 2); //Create expression for (2+3) Number n1 = new Number(2); Number n2 = new Number(3); Operator op1 = new Plus(); op1.add(n1); op1.add(n2); //Create x*(2+3) Variable n3 = new Variable("x"); Operator op2 = new Product(); op2.add(n3); op2.add(op1); //create x*(2+3) - 10 Number n4 = new Number(10); Operator op3 = new Minus(op2, n4); //create (x*(2+3) - 10) * y Variable n5 = new Variable("y"); Operator op4 = new Product(); op4.add(op3); op4.add(n5); System.out.println("Variable values are:"); Iterator<ArithmeticExpression> it = op4.iterator(); while (it.hasNext()) { ArithmeticExpression node = it.next(); if (node instanceof Variable) { Variable var = (Variable)node; System.out.println(var + " = " + var.evaluate(m)); } } System.out.println(); Iterator<ArithmeticExpression> it2 = op4.iterator(); int max = 0; while (it2.hasNext()) { ArithmeticExpression node = it2.next(); if (node instanceof Number) { Number n = (Number)node; int num = n.getNumber(); if (num > max) { max = num; } } } System.out.println("The largest integer is : " + max); System.out.println(""); System.out.println("Expression is:"); System.out.println(op4.toString()); System.out.println(); System.out.println("Evalauted: "); System.out.println(op4.evaluate(m)); }
e134f5d2-97b7-44df-8fea-27e488c7f8cc
public Product() { super(); }
ba7a12c7-05e7-406a-880b-5e3956519591
public int evaluate(Map<String, Integer> m) { int total = 1; for (ArithmeticExpression exp : operands) { total = total * exp.evaluate(m); } return total; }
242bf867-1d2c-49e0-be04-0d447d8d3db4
public Iterator<ArithmeticExpression> iterator() { return new ArithmeticExpressionIterator(this); }
9b925614-9a8e-4629-9f5e-9a5e2915956f
public String toString() { String str = "("; Iterator<ArithmeticExpression> iter = operands.iterator(); while (iter.hasNext()) { str = str + iter.next(); if (iter.hasNext()) { str = str + "*"; } else { str = str + ")"; } } return str; }
ef7121f6-e89d-4b29-b4c7-7d4467372518
public Number(int number) { this.number = number; }
ebd490e0-768d-4ded-9ef3-9b97b6c9df28
public int getNumber() { return number; }
c4e663b2-429b-4a9a-8bd2-6bfaf1b75368
public String toString() { /*return "(" + number + ")";*/ return "" + number; }
308d1f0d-90a9-426c-b598-8bc65c6f522f
public int evaluate(Map<String, Integer> m) { return number; }
bbf9a12f-723f-4f6f-83e9-e21fdf6a3e70
public Iterator<ArithmeticExpression> iterator() { return new ArithmeticExpressionIterator(this); }