00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 package com.generalrobotix.ui.item;
00019
00020 import java.math.BigInteger;
00021 import java.util.ArrayList;
00022 import java.util.Collection;
00023 import java.util.Date;
00024 import java.util.List;
00025 import java.util.Vector;
00026
00027 import jp.go.aist.hrp.simulator.BodyInfo;
00028 import jp.go.aist.hrp.simulator.ClockGenerator;
00029 import jp.go.aist.hrp.simulator.Controller;
00030 import jp.go.aist.hrp.simulator.ControllerHelper;
00031 import jp.go.aist.hrp.simulator.DynamicsSimulator;
00032 import jp.go.aist.hrp.simulator.DynamicsSimulatorFactory;
00033 import jp.go.aist.hrp.simulator.DynamicsSimulatorFactoryHelper;
00034 import jp.go.aist.hrp.simulator.ExtraJointType;
00035 import jp.go.aist.hrp.simulator.SensorStateHolder;
00036 import jp.go.aist.hrp.simulator.ViewSimulator;
00037 import jp.go.aist.hrp.simulator.ViewSimulatorHelper;
00038 import jp.go.aist.hrp.simulator.WorldStateHolder;
00039 import jp.go.aist.hrp.simulator.ControllerPackage.ControllerException;
00040 import jp.go.aist.hrp.simulator.DynamicsSimulatorPackage.IntegrateMethod;
00041 import jp.go.aist.hrp.simulator.DynamicsSimulatorPackage.JointDriveMode;
00042 import jp.go.aist.hrp.simulator.DynamicsSimulatorPackage.LinkDataType;
00043 import jp.go.aist.hrp.simulator.DynamicsSimulatorPackage.SensorOption;
00044
00045 import org.eclipse.jface.dialogs.InputDialog;
00046 import org.eclipse.jface.dialogs.MessageDialog;
00047 import org.eclipse.swt.widgets.Display;
00048 import org.eclipse.ui.IWorkbench;
00049 import org.eclipse.ui.IWorkbenchPage;
00050 import org.eclipse.ui.IWorkbenchWindow;
00051 import org.eclipse.ui.PartInitException;
00052 import org.eclipse.ui.PlatformUI;
00053 import org.omg.CosNaming.NameComponent;
00054 import org.omg.CosNaming.NamingContext;
00055
00056 import com.generalrobotix.ui.GrxBaseItem;
00057 import com.generalrobotix.ui.GrxPluginManager;
00058 import com.generalrobotix.ui.depends.rtm.SwitchDependVerClockGenerator;
00059 import com.generalrobotix.ui.grxui.GrxUIPerspectiveFactory;
00060 import com.generalrobotix.ui.item.GrxWorldStateItem.WorldStateEx;
00061 import com.generalrobotix.ui.util.GrxCorbaUtil;
00062 import com.generalrobotix.ui.util.GrxDebugUtil;
00063 import com.generalrobotix.ui.util.GrxProcessManager;
00064 import com.generalrobotix.ui.util.MessageBundle;
00065 import com.generalrobotix.ui.util.GrxProcessManager.AProcess;
00066 import com.generalrobotix.ui.util.GrxProcessManager.ProcessInfo;
00067 import com.generalrobotix.ui.view.Grx3DView;
00068 import com.generalrobotix.ui.view.GrxLoggerView;
00069 import com.generalrobotix.ui.view.GrxOpenHRPView;
00070 import com.generalrobotix.ui.view.simulation.SimulationParameterPanel;
00071 import com.generalrobotix.ui.view.vsensor.Camera_impl;
00072
00073 @SuppressWarnings("serial")
00074 public class GrxSimulationItem extends GrxBaseItem {
00075 public static final String TITLE = "Simulation";
00076 private static final String FORMAT1 = "%8.3f";
00077 private static final int WAIT_COUNT_ = 4;
00078 private GrxWorldStateItem currentWorld_;
00079 private DynamicsSimulator currentDynamics_;
00080 private List<ControllerAttribute> controllers_ = new ArrayList<ControllerAttribute>();
00081 private WorldStateHolder stateH_ = new WorldStateHolder();
00082 private SensorStateHolder cStateH_ = new SensorStateHolder();
00083 private List<String> robotEntry_ = new ArrayList<String>();
00084 private static ClockGenerator_impl clockGenerator_ = null;
00085
00086 private boolean isInteractive_ = true;
00087 private boolean isExecuting_ = false;
00088 private boolean isSuspending_ = false;
00089 private double simulateTime_ = 0;
00090 private boolean isIntegrate_ = true;
00091 private boolean isRealTime_ = false;
00092 private double stepTime_ = 0.001;
00093 private double totalTime_ = 20;
00094 private double logStepTime_ = 0.05;
00095 private boolean isSimulatingView_;
00096 private double viewSimulationStep_=0;
00097
00098
00099 private Thread simThread_;
00100 private static final int interval_ = 10;
00101 private Grx3DView view3D;
00102
00103
00104 private Object lock2_ = new Object();
00105
00106 public GrxSimulationItem(String name, GrxPluginManager manager) {
00107 super(name, manager);
00108 setExclusive(true);
00109 setIcon("grxrobot.png");
00110 registerCORBA();
00111 }
00112
00113 public boolean create() {
00114 setDbl("totalTime", 20.0);
00115 setDbl("timeStep", 0.001);
00116 setDbl("gravity", 9.8);
00117 setProperty("method","RUNGE_KUTTA");
00118 setBool("integrate", true);
00119 setBool("viewsimulate", false);
00120 setBool("realTime", false);
00121 return true;
00122 }
00123
00127 private class ClockGenerator_impl extends SwitchDependVerClockGenerator {
00128 }
00129
00130 private double simTime_ = 0.0;
00131
00132 private static final int EXEC = -1;
00133 private static final int TIMEOVER = 0;
00134 private static final int STOP = 1;
00135 private static final int INTERRUPT = 2;
00136 private int simThreadState_ = EXEC;
00137 private Object lock_ = new Object();
00138 private Object lock3_ = new Object();
00139 private boolean viewSimulationUpdate_ = false;
00140 private WorldStateEx wsx_=null;
00141
00142 public boolean startSimulation(boolean isInteractive) {
00143
00144 if (isExecuting_){
00145 GrxDebugUtil.println("[HRP]@startSimulation now executing.");
00146 return false;
00147 }
00148
00149 currentWorld_ = manager_.<GrxWorldStateItem>getSelectedItem(GrxWorldStateItem.class, null);
00150 if (currentWorld_ == null) {
00151 MessageDialog.openError(null, MessageBundle.get("GrxOpenHRPView.dialog.title.Fail"), MessageBundle.get("GrxOpenHRPView.dialog.message.noWorldState"));
00152 GrxDebugUtil.println("[HRP]@startSimulation there is no world.");
00153 return false;
00154 }
00155
00156 isInteractive_ = isInteractive;
00157
00158 if (isInteractive_ && currentWorld_.getLogSize() > 0) {
00159 boolean ans = MessageDialog.openConfirm(GrxUIPerspectiveFactory.getCurrentShell(), MessageBundle.get("GrxOpenHRPView.dialog.title.start"), MessageBundle.get("GrxOpenHRPView.dialog.message.start0") + MessageBundle.get("GrxOpenHRPView.dialog.message.start1"));
00160 if (ans != true) {
00161 return false;
00162 }
00163 }
00164 currentWorld_.clearLog();
00165
00166 GrxOpenHRPView openHRPView = (GrxOpenHRPView)manager_.getView( GrxOpenHRPView.class, true );
00167 if(openHRPView != null)
00168 openHRPView.fixParam();
00169
00170 isIntegrate_ = isTrue("integrate", true);
00171 isRealTime_ = isTrue("realTime", false);
00172 totalTime_ = getDbl("totalTime", 20.0);
00173 stepTime_ = getDbl("timeStep", 0.001);
00174 logStepTime_ = currentWorld_.getDbl("logTimeStep", 0.001);
00175 isSimulatingView_ = isTrue("viewsimulate", false);
00176 if(stepTime_ > logStepTime_ ){
00177 MessageDialog.openInformation(GrxUIPerspectiveFactory.getCurrentShell(), MessageBundle.get("GrxOpenHRPView.dialog.title.start"), MessageBundle.get("GrxOpenHRPView.dialog.message.errorLogStepTime"));
00178 return false;
00179 }
00180
00181 try {
00182 if (!initDynamicsSimulator()) {
00183 MessageDialog.openInformation(GrxUIPerspectiveFactory.getCurrentShell(),"", MessageBundle.get("GrxOpenHRPView.dialog.message.failedInit"));
00184 return false;
00185 }
00186 if (!initController()) {
00187 return false;
00188 }
00189 } catch (Exception e) {
00190 GrxDebugUtil.printErr("SimulationLoop:", e);
00191 return false;
00192 }
00193
00194 if(isSimulatingView_){
00195 view3D = (Grx3DView)manager_.getView( Grx3DView.class, false );
00196 if(view3D==null){
00197 IWorkbench workbench = PlatformUI.getWorkbench();
00198 IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
00199 IWorkbenchPage page = window.getActivePage();
00200 try {
00201 page.showView("com.generalrobotix.ui.view.Grx3DViewPart", null, IWorkbenchPage.VIEW_CREATE);
00202 } catch (PartInitException e1) {
00203 e1.printStackTrace();
00204 }
00205 view3D = (Grx3DView)manager_.getView( Grx3DView.class, true );
00206 }
00207 }
00208
00209 if(!isSimulatingView_){
00210 GrxLoggerView view = (GrxLoggerView)manager_.getView( GrxLoggerView.class, false );
00211 if( view == null){
00212 IWorkbench workbench = PlatformUI.getWorkbench();
00213 IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
00214 IWorkbenchPage page = window.getActivePage();
00215 try {
00216 page.showView("com.generalrobotix.ui.view.GrxLoggerViewPart", null, IWorkbenchPage.VIEW_CREATE);
00217 } catch (PartInitException e1) {
00218 e1.printStackTrace();
00219 }
00220 }
00221 }
00222 notifyObservers("StartSimulation", isSimulatingView_);
00223
00224 clockGenerator_.resetClockReceivers();
00225
00226 simTime_ = 0.0;
00227 simulateTime_ = 0;
00228 currentWorld_.init();
00229 simThreadState_ = EXEC;
00230 viewSimulationUpdate_ = false;
00231 simThread_ = _createSimulationThread();
00232 simThread_.start();
00233
00234 Runnable run = new Runnable(){
00235 public void run() {
00236 switch(simThreadState_){
00237 case TIMEOVER:
00238 if(extendTime())
00239 simThreadState_=EXEC;
00240 else
00241 simThreadState_=STOP;
00242 synchronized(lock_){
00243 lock_.notifyAll();
00244 }
00245 case EXEC:
00246 if(isSimulatingView_){
00247 if(viewSimulationUpdate_){
00248 view3D._showCollision(wsx_.collisions);
00249 view3D.updateModels(wsx_);
00250 view3D.updateViewSimulator(wsx_.time);
00251 currentWorld_.setPosition(currentWorld_.getLogSize()-1,view3D);
00252 synchronized(lock3_){
00253 viewSimulationUpdate_=false;
00254 lock3_.notify();
00255 }
00256 }
00257 }
00258 Display display = Display.getCurrent();
00259 if ( display!=null && !display.isDisposed()){
00260 display.timerExec(interval_, this);
00261 }
00262 break;
00263 case STOP:
00264 endOfSimulation();
00265 synchronized(lock2_){
00266 lock2_.notifyAll();
00267 }
00268 break;
00269 case INTERRUPT:
00270 MessageDialog.openError( GrxUIPerspectiveFactory.getCurrentShell(),
00271 MessageBundle.get("GrxOpenHRPView.dialog.title.Interrupt"), MessageBundle.get("GrxOpenHRPView.dialog.message.Interrupt"));
00272 endOfSimulation();
00273 break;
00274 default :
00275 break;
00276 }
00277 }
00278 };
00279 Display display = Display.getCurrent();
00280 if ( display!=null && !display.isDisposed()){
00281 display.timerExec(interval_, run);
00282 }
00283
00284 GrxDebugUtil.println("[OpenHRP]@startSimulation Start Thread and end this function.");
00285 return true;
00286 }
00287
00288 String timeMsg_;
00289 String updateTimeMsg(){
00290 timeMsg_ =
00291 MessageBundle.get("GrxOpenHRPView.dialog.message.simTime0") + String.format(FORMAT1, simTime_) + MessageBundle.get("GrxOpenHRPView.dialog.message.simTime1") +
00292 MessageBundle.get("GrxOpenHRPView.dialog.message.simTime2") + String.format(FORMAT1, simulateTime_) + MessageBundle.get("GrxOpenHRPView.dialog.message.simTime3") +
00293 MessageBundle.get("GrxOpenHRPView.dialog.message.simTime4") + String.format(FORMAT1, simulateTime_/simTime_);
00294 return timeMsg_;
00295 }
00296
00297 private Thread _createSimulationThread(){
00298 Thread thread = new Thread(){
00299 public void run() {
00300 isExecuting_ = true;
00301 long suspendT = 0;
00302 long startT = System.currentTimeMillis();
00303 try {
00304 while (isExecuting_) {
00305 if (isSuspending_) {
00306 long s = System.currentTimeMillis();
00307 Thread.sleep(200);
00308 suspendT += System.currentTimeMillis() - s;
00309 } else {
00310 if (!simulateOneStep()){
00311 long s = System.currentTimeMillis();
00312 synchronized(lock_){
00313 simThreadState_ = TIMEOVER;
00314 lock_.wait();
00315 }
00316 suspendT += System.currentTimeMillis() - s;
00317 if(simThreadState_==STOP)
00318 break;
00319 }else{
00320 if(isRealTime_){
00321 long s = System.currentTimeMillis();
00322 long sleep = (long)(simTime_*1000.0) - (s - startT);
00323 if(sleep > 0)
00324 Thread.sleep(sleep);
00325 }
00326 }
00327 }
00328 Thread.yield();
00329 }
00330 isExecuting_ = false;
00331 simulateTime_ += (System.currentTimeMillis() - startT - suspendT)/1000.0;
00332
00333
00334
00335
00336 simThreadState_ = STOP;
00337 } catch (Exception e) {
00338 GrxDebugUtil.printErr("Simulation Interrupted by Exception:",e);
00339 isExecuting_ = false;
00340 simThreadState_ = INTERRUPT;
00341 }
00342 }
00343 };
00344 thread.setPriority(Thread.currentThread().getPriority() - 1);
00345 return thread;
00346 }
00347
00348 public void continueSimulation(){
00349 simThread_ = _createSimulationThread();
00350 simThread_.start();
00351 }
00352
00353 public void stopSimulation() {
00354 if (isExecuting_)
00355 isExecuting_ = false;
00356 }
00357
00358 public void endOfSimulation(){
00359 for (ControllerAttribute i: controllers_) {
00360 i.deactive();
00361 }
00362 updateTimeMsg();
00363 System.out.println(new java.util.Date()+timeMsg_.replace(" ", "").replace("\n", " : "));
00364 if (isInteractive_) {
00365 isInteractive_ = false;
00366 execSWT( new Runnable(){
00367 public void run(){
00368 MessageDialog.openInformation(GrxUIPerspectiveFactory.getCurrentShell(),
00369 MessageBundle.get("GrxOpenHRPView.dialog.title.finish"), timeMsg_);
00370 }
00371 } ,
00372 Thread.currentThread() != simThread_
00373 );
00374 }
00375 syncExec(new Runnable(){
00376 public void run() {
00377 currentWorld_.stopSimulation();
00378 notifyObservers("StopSimulation");
00379 currentWorld_.setPosition(0);
00380 }
00381 } );
00382 }
00383
00388 private boolean simulateOneStep() {
00389 if (simTime_ > totalTime_ ) {
00390 return false;
00391 }
00392
00393
00394 for (int i = 0; i<controllers_.size(); i++) {
00395 ControllerAttribute attr =
00396 (ControllerAttribute)controllers_.get(i);
00397 attr.input(simTime_);
00398 }
00399
00400 simTime_ += stepTime_;
00401
00402
00403 for (int i = 0; i < controllers_.size(); i++) {
00404 ControllerAttribute attr = controllers_.get(i);
00405 attr.control();
00406 }
00407 clockGenerator_.updateExecutionContext(simTime_);
00408
00409
00410 if (isIntegrate_) {
00411 currentDynamics_.stepSimulation();
00412 } else {
00413 currentDynamics_.calcWorldForwardKinematics();
00414 }
00415
00416
00417 wsx_=null;
00418 if ((simTime_ % logStepTime_) < stepTime_) {
00419 currentDynamics_.getWorldState(stateH_);
00420 wsx_ = new WorldStateEx(stateH_.value);
00421 for (int i=0; i<robotEntry_.size(); i++) {
00422 String name = robotEntry_.get(i);
00423 currentDynamics_.getCharacterSensorState(name, cStateH_);
00424 wsx_.setSensorState(name, cStateH_.value);
00425 }
00426 if (!isIntegrate_)
00427 wsx_.time = simTime_;
00428 currentWorld_.addValue(simTime_, wsx_);
00429 }
00430
00431
00432 if(isSimulatingView_){
00433 if ((simTime_ % viewSimulationStep_) < stepTime_) {
00434 if(wsx_==null){
00435 currentDynamics_.getWorldState(stateH_);
00436 wsx_ = new WorldStateEx(stateH_.value);
00437 for (int i=0; i<robotEntry_.size(); i++) {
00438 String name = robotEntry_.get(i);
00439 currentDynamics_.getCharacterSensorState(name, cStateH_);
00440 wsx_.setSensorState(name, cStateH_.value);
00441 }
00442 if (!isIntegrate_)
00443 wsx_.time = simTime_;
00444 }
00445 synchronized(lock3_){
00446 try {
00447 viewSimulationUpdate_ = true;
00448 lock3_.wait();
00449 } catch (InterruptedException e) {
00450 e.printStackTrace();
00451 }
00452 }
00453 }
00454 }
00455
00456
00457 for (int i = 0; i < controllers_.size(); i++) {
00458 ControllerAttribute attr = controllers_.get(i);
00459 attr.output();
00460 }
00461 return true;
00462 }
00463
00464 public void waitStopSimulation() throws InterruptedException {
00465 try {
00466 synchronized(lock2_){
00467 lock2_.wait();
00468 }
00469 } catch (InterruptedException e) {
00470 stopSimulation();
00471 throw e;
00472 }
00473 }
00474
00475 private class ControllerAttribute {
00476 String modelName_;
00477 String controllerName_;
00478 Controller controller_;
00479 double stepTime_;
00480 int doCount_ = 0;
00481 boolean doFlag_ = false;
00482 ControllerAttribute(String modelName, String controllerName, Controller controller, double stepTime) {
00483 modelName_ = modelName;
00484 controllerName_ = controllerName;
00485 controller_ = controller;
00486 stepTime_ = stepTime;
00487 }
00488
00489 private void reset(Controller controller, double stepTime) {
00490 controller_ = controller;
00491 stepTime_ = stepTime;
00492 doCount_ = 0;
00493 doFlag_ = false;
00494 }
00495
00496 private void input(double time){
00497 try {
00498 doFlag_ = false;
00499 if (doCount_ <= time/stepTime_) {
00500 doFlag_ = true;
00501 doCount_++;
00502 controller_.input();
00503 }
00504 } catch (Exception e) {
00505 GrxDebugUtil.printErr("Exception in input", e);
00506 }
00507 }
00508
00509 private void control() {
00510 try {
00511 if (doFlag_) controller_.control();
00512 } catch (Exception e) {
00513 GrxDebugUtil.printErr("Exception in control", e);
00514 }
00515 }
00516
00517 private void output() {
00518 try {
00519 if (doFlag_) controller_.output();
00520 } catch (Exception e) {
00521 GrxDebugUtil.printErr("Exception in output", e);
00522 }
00523 }
00524
00525 private void deactive(){
00526 try {
00527 controller_.stop();
00528 } catch (Exception e) {
00529 GrxDebugUtil.printErr("Exception in deactive", e);
00530 }
00531 }
00532 private void active() {
00533 try {
00534 controller_.initialize();
00535 } catch(ControllerException e){
00536 System.out.println("setupController:"+e.description);
00537 MessageDialog.openInformation(GrxUIPerspectiveFactory.getCurrentShell(), "", MessageBundle.get("GrxOpenHRPView.dialog.message.failedController"));
00538 }catch (Exception e) {
00539 GrxDebugUtil.printErr("Exception in active", e);
00540 }
00541 }
00542 }
00543
00544
00545 void execSWT( Runnable r, boolean execInCurrentThread ){
00546 if( execInCurrentThread ) {
00547 r.run();
00548 }else{
00549 Display display = Display.getDefault();
00550 if ( display!=null && !display.isDisposed())
00551 display.asyncExec(r);
00552 }
00553 }
00554
00555 public boolean registerCORBA() {
00556 if(clockGenerator_ == null){
00557 clockGenerator_ = new ClockGenerator_impl();
00558 NamingContext rootnc = GrxCorbaUtil.getNamingContext();
00559 ClockGenerator cg = clockGenerator_._this(GrxCorbaUtil.getORB());
00560 NameComponent[] path = {new NameComponent("ClockGenerator", "")};
00561 try {
00562 rootnc.rebind(path, cg);
00563 GrxDebugUtil.println("OpenHRPView : ClockGenerator is successfully registered to NamingService");
00564 } catch (Exception ex) {
00565 GrxDebugUtil.println("OpenHRPView : failed to bind ClockGenerator to NamingService");
00566 }
00567 return true;
00568 }else
00569 return false;
00570 }
00571
00572 public void unregisterCORBA() {
00573 NamingContext rootnc = GrxCorbaUtil.getNamingContext();
00574 NameComponent[] path = {new NameComponent("ClockGenerator", "")};
00575 try{
00576 rootnc.unbind(path);
00577 GrxDebugUtil.println("OpenHRPView : successfully ClockGenerator unbound to localhost NameService");
00578 }catch(Exception ex){
00579 GrxDebugUtil.println("OpenHRPView : failed to unbind ClockGenerator to localhost NameService");
00580 }
00581 clockGenerator_ = null;
00582 }
00583
00584 public void shutdown() {
00585 if (currentDynamics_ != null) {
00586 try {
00587 currentDynamics_.destroy();
00588 } catch (Exception e) {
00589 GrxDebugUtil.printErr("", e);
00590 }
00591 currentDynamics_ = null;
00592 }
00593 Collection<GrxSimulationItem> col=(Collection<GrxSimulationItem>) manager_.getItemMap(GrxSimulationItem.class).values();
00594 if(col.size()==1 && col.contains(this))
00595 unregisterCORBA();
00596 }
00597
00598 public void delete() {
00599 shutdown();
00600 super.delete();
00601 }
00602
00603 public boolean initDynamicsSimulator() {
00604 getDynamicsSimulator(true);
00605
00606 try {
00607 List<GrxModelItem> modelList = manager_.<GrxModelItem>getSelectedItemList(GrxModelItem.class);
00608 robotEntry_.clear();
00609 float cameraFrameRate = 1;
00610 for (int i=0; i<modelList.size(); i++) {
00611 GrxModelItem model = modelList.get(i);
00612 if (model.links_ == null)
00613 continue;
00614 if(model.checkModifiedModel(true)==GrxModelItem.MODIFIED_NG)
00615 return false;
00616 BodyInfo bodyInfo = model.getBodyInfo();
00617 if(bodyInfo==null) return false;
00618 currentWorld_ = manager_.<GrxWorldStateItem>getSelectedItem(GrxWorldStateItem.class, null);
00619 if(currentWorld_!=null)
00620 currentWorld_.registerCharacter(model.getName(), bodyInfo);
00621 currentDynamics_.registerCharacter(model.getName(), bodyInfo);
00622 if (model.isRobot()) {
00623 robotEntry_.add(model.getName());
00624 }
00625 List<Camera_impl> cameraList = model.getCameraSequence();
00626 for (int j=0; j<cameraList.size(); j++) {
00627 Camera_impl camera = cameraList.get(j);
00628 float frameRate = camera.getCameraParameter().frameRate;
00629 cameraFrameRate = lcm(cameraFrameRate, frameRate);
00630 }
00631 }
00632 viewSimulationStep_ = 1.0d/cameraFrameRate;
00633
00634 String smethod = getStr("method");
00635 IntegrateMethod m=null;
00636 if(smethod.equals(SimulationParameterPanel.METHOD_NAMES[0]))
00637 m=IntegrateMethod.RUNGE_KUTTA;
00638 else
00639 m=IntegrateMethod.EULER;
00640 currentDynamics_.init(getDbl("timeStep", 0.001), m, SensorOption.ENABLE_SENSOR);
00641 currentDynamics_.setGVector(new double[] { 0.0, 0.0, getDbl("gravity", 9.8) });
00642
00643 for (int i=0; i<modelList.size(); i++) {
00644 GrxModelItem model = modelList.get(i);
00645 if (model.links_ == null)
00646 continue;
00647
00648
00649 GrxLinkItem base = model.rootLink();
00650 currentDynamics_.setCharacterLinkData(
00651 model.getName(), base.getName(), LinkDataType.ABS_TRANSFORM,
00652 model.getInitialTransformArray(base));
00653
00655 currentDynamics_.setCharacterLinkData(
00656 model.getName(), base.getName(), LinkDataType.ABS_VELOCITY,
00657 model.getInitialVelocity(base));
00658
00659
00660 if (isIntegrate_) {
00661 double[] jms = model.getInitialJointMode();
00662 for (int j=0; j<jms.length; j++) {
00663 double[] mode = new double[1];
00664 mode[0] = jms[j];
00665 currentDynamics_.setCharacterLinkData(model.getName(), model.links_.get(j).getName(), LinkDataType.POSITION_GIVEN, mode );
00666 }
00667 } else {
00668 currentDynamics_.setCharacterAllJointModes(model.getName(), JointDriveMode.HIGH_GAIN_MODE);
00669 }
00670
00671
00672 currentDynamics_.setCharacterAllLinkData(
00673 model.getName(), LinkDataType.JOINT_VALUE,
00674 model.getInitialJointValues());
00675
00676 currentDynamics_.setCharacterAllLinkData(
00677 model.getName(), LinkDataType.JOINT_VELOCITY,
00678 model.getInitialJointVelocity());
00679 }
00680 currentDynamics_.calcWorldForwardKinematics();
00681
00682
00683 List<GrxBaseItem> collisionPair = manager_.getSelectedItemList(GrxCollisionPairItem.class);
00684 for (int i=0; i<collisionPair.size(); i++) {
00685 GrxCollisionPairItem item = (GrxCollisionPairItem) collisionPair.get(i);
00686 currentDynamics_.registerCollisionCheckPair(
00687 item.getStr("objectName1", ""),
00688 item.getStr("jointName1", ""),
00689 item.getStr("objectName2", ""),
00690 item.getStr("jointName2", ""),
00691 item.getDbl("staticFriction", 0.5),
00692 item.getDbl("slidingFriction", 0.5),
00693 item.getDblAry("springConstant",new double[]{0.0,0.0,0.0,0.0,0.0,0.0}),
00694 item.getDblAry("damperConstant",new double[]{0.0,0.0,0.0,0.0,0.0,0.0}),
00695 item.getDbl("cullingThresh", 0.01),
00696 item.getDbl("Restitution", 0.0));
00697 }
00698
00699 List<GrxBaseItem> extraJoints = manager_.getSelectedItemList(GrxExtraJointItem.class);
00700 for (int i=0; i<extraJoints.size(); i++) {
00701 GrxExtraJointItem item = (GrxExtraJointItem) extraJoints.get(i);
00702 ExtraJointType jointType = ExtraJointType.EJ_XYZ;
00703 if(item.getStr("jointType","").equals("xyz"))
00704 jointType = ExtraJointType.EJ_XYZ;
00705 else if(item.getStr("jointType","").equals("xy"))
00706 jointType = ExtraJointType.EJ_XY;
00707 else if(item.getStr("jointType","").equals("z"))
00708 jointType = ExtraJointType.EJ_Z;
00709 currentDynamics_.registerExtraJoint(
00710 item.getStr("object1Name", ""),
00711 item.getStr("link1Name", ""),
00712 item.getStr("object2Name", ""),
00713 item.getStr("link2Name", ""),
00714 item.getDblAry("link1LocalPos", new double[]{0.0,0.0,0.0}),
00715 item.getDblAry("link2LocalPos", new double[]{0.0,0.0,0.0}),
00716 jointType,
00717 item.getDblAry("jointAxis", new double[]{0.0,0.0,0.0}),
00718 item.getName());
00719 }
00720 currentDynamics_.initSimulation();
00721
00722 stateH_.value = null;
00723 } catch (Exception e) {
00724 GrxDebugUtil.printErr("initDynamicsSimulator:", e);
00725 return false;
00726 }
00727 return true;
00728 }
00729
00730 public DynamicsSimulator getDynamicsSimulator(boolean update) {
00731 if (update && currentDynamics_ != null) {
00732 try {
00733 currentDynamics_.destroy();
00734 } catch (Exception e) {
00735 GrxDebugUtil.printErr("", e);
00736 }
00737 currentDynamics_ = null;
00738 }
00739
00740 if (currentDynamics_ == null) {
00741 try {
00742 org.omg.CORBA.Object obj =
00743 GrxCorbaUtil.getReference("DynamicsSimulatorFactory");
00744 DynamicsSimulatorFactory ifactory = DynamicsSimulatorFactoryHelper.narrow(obj);
00745 currentDynamics_ = ifactory.create();
00746 currentDynamics_._non_existent();
00747
00748 } catch (Exception e) {
00749 GrxDebugUtil.printErr("getDynamicsSimulator: create failed.");
00750 e.printStackTrace();
00751 currentDynamics_ = null;
00752 }
00753 }
00754 return currentDynamics_;
00755 }
00756
00757 private boolean initController() {
00758 boolean ret = true;
00759 List<String> localStrList = new Vector<String>();
00760 List<GrxModelItem> modelList = manager_.<GrxModelItem>getSelectedItemList(GrxModelItem.class);
00761 for (GrxModelItem model : modelList ) {
00762 if( model.isRobot() ){
00763 localStrList.add( model.getProperty("controller") );
00764 }
00765 }
00766 _refreshControllers( localStrList );
00767 for (GrxModelItem model: modelList ) {
00768 if( model.isRobot() ){
00769 ret &= _setupController(model, _getControllerFromControllerName(model.getProperty("controller")));
00770 }
00771 }
00772 return ret;
00773 }
00774
00775 private ControllerAttribute _getController(String localID){
00776 ControllerAttribute ret = null;
00777 for (ControllerAttribute i: controllers_) {
00778 if ( i.modelName_.equals(localID) ){
00779 ret = i;
00780 break;
00781 }
00782 }
00783 return ret;
00784 }
00785
00786 private ControllerAttribute _getControllerFromControllerName(String controllerName){
00787 ControllerAttribute ret = null;
00788 for (ControllerAttribute i: controllers_) {
00789 if ( i.controllerName_.equals(controllerName) ){
00790 ret = i;
00791 break;
00792 }
00793 }
00794 return ret;
00795 }
00796
00797
00798 private void _refreshControllers(List<String> refStrList){
00799 Vector<String> localStrVec = new Vector<String>();
00800 for (ControllerAttribute i: controllers_) {
00801 int index = refStrList.indexOf(i.controllerName_);
00802 if ( index < 0 )
00803 localStrVec.add(i.controllerName_);
00804 }
00805 for (String i: localStrVec) {
00806 GrxProcessManager pManager = (GrxProcessManager) manager_.getItem("processManager");
00807 AProcess proc = pManager.get(i);
00808 if( proc != null && proc.stop() ){
00809 pManager.unregister(proc.pi_.id);
00810 _getControllerFromControllerName(i);
00811 int index = controllers_.indexOf( _getControllerFromControllerName(i) );
00812 if ( index >= 0 )
00813 controllers_.remove(index);
00814 }
00815 }
00816 }
00817
00818 private boolean _setupController(GrxModelItem model, ControllerAttribute deactivatedController) {
00819 String controllerName = model.getProperty("controller");
00820 if (controllerName == null || controllerName.equals(""))
00821 return true;
00822
00823 double step = model.getDbl("controlTime", 0.005);
00824 if(stepTime_ > step){
00825 MessageDialog.openInformation(GrxUIPerspectiveFactory.getCurrentShell(), "", MessageBundle.get("GrxOpenHRPView.dialog.message.errorControlTime"));
00826 return false;
00827 }
00828
00829 String optionAdd = null;
00830 if (!isTrue("integrate", true))
00831 optionAdd = " -nosim";
00832
00833 GrxDebugUtil.println("model name = " + model.getName() + " : controller = " + controllerName + " : cycle time[s] = " + step);
00834 GrxProcessManager pManager = (GrxProcessManager) manager_.getItem("processManager");;
00835
00836 boolean doRestart = false;
00837 org.omg.CORBA.Object cobj = GrxCorbaUtil.getReference(controllerName);
00838 AProcess proc = pManager.get(controllerName);
00839 String dir = model.getStr("setupDirectory", "");
00840 String com = model.getStr("setupCommand", "");
00841
00842 if (cobj != null) {
00843 try {
00844 cobj._non_existent();
00845 if (isInteractive_ && (!com.equals("") || proc != null)) {
00846 MessageDialog dialog =new MessageDialog(GrxUIPerspectiveFactory.getCurrentShell(),MessageBundle.get("GrxOpenHRPView.dialog.title.restartController"),null,
00847 MessageBundle.get("GrxOpenHRPView.dialog.message.restartController0")+controllerName+MessageBundle.get("GrxOpenHRPView.dialog.message.restartController1") + MessageBundle.get("GrxOpenHRPView.dialog.message.restartController2") ,MessageDialog.QUESTION, new String[]{MessageBundle.get("GrxOpenHRPView.dialog.button.yes"),MessageBundle.get("GrxOpenHRPView.dialog.button.no"),MessageBundle.get("GrxOpenHRPView.dialog.button.cancel")}, 2);
00848 switch( dialog.open() ){
00849 case 0:
00850 doRestart = true;
00851 break;
00852 case 1:
00853 if(deactivatedController != null)
00854 deactivatedController.active();
00855 break;
00856 default:
00857 return false;
00858 }
00859 }else{
00860 if ((!com.equals("") || proc != null) && deactivatedController != null)
00861 deactivatedController.active();
00862 }
00863
00864 } catch (Exception e) {
00865 cobj = null;
00866 }
00867 }
00868
00869 if (cobj == null || doRestart) {
00870 if (proc != null)
00871 proc.stop();
00872
00873 if (!com.equals("")) {
00874 com = dir+java.io.File.separator+com;
00875 String osname = System.getProperty("os.name");
00876 if(osname.indexOf("Windows") >= 0){
00877 com = "\"" + com + "\"";
00878 }
00879 ProcessInfo pi = new ProcessInfo();
00880 pi.id = controllerName;
00881 pi.dir = dir;
00882 pi.com.add(com);
00883 pi.waitCount = 2000;
00884 pi.isCorbaServer = true;
00885 pi.hasShutdown = true;
00886 pi.doKillall = false;
00887 pi.autoStart = false;
00888 pi.autoStop = true;
00889 if (proc != null)
00890 pManager.unregister(proc.pi_.id);
00891 pManager.register(pi);
00892 proc = pManager.get(controllerName);
00893 }
00894
00895 if (proc != null) {
00896 GrxDebugUtil.println("Executing controller process ...");
00897 GrxDebugUtil.println("dir: " + dir);
00898 GrxDebugUtil.println("command: " + com);
00899 proc.start(optionAdd);
00900 }
00901 }
00902
00903 Date before = new Date();
00904 for (int j=0; ; j++) {
00905 cobj = GrxCorbaUtil.getReference(controllerName);
00906 if (cobj != null) {
00907 try {
00908 Controller controller = ControllerHelper.narrow(cobj);
00909 controller.setModelName(model.getName());
00910 controller.setDynamicsSimulator(currentDynamics_);
00911 if (isTrue("viewsimulate")){
00912 cobj = GrxCorbaUtil.getReference("ViewSimulator");
00913 ViewSimulator viewsim = ViewSimulatorHelper.narrow(cobj);
00914 controller.setViewSimulator(viewsim);
00915 }
00916 ControllerAttribute refAttr = _getControllerFromControllerName(controllerName);
00917 if( refAttr == null){
00918 controllers_.add(new ControllerAttribute(model.getName(), controllerName, controller, step));
00919 }else{
00920 refAttr.reset(controller, step);
00921 }
00922 GrxDebugUtil.println(" connected to the Controller("+controllerName+")\n");
00923 controller.setTimeStep(step);
00924 controller.initialize();
00925 controller.start();
00926 break;
00927 }catch (ControllerException e) {
00928 System.out.println("setupController:"+e.description);
00929 MessageDialog.openInformation(GrxUIPerspectiveFactory.getCurrentShell(), e.description, MessageBundle.get("GrxOpenHRPView.dialog.message.failedController"));
00930 if (proc != null)
00931 proc.stop();
00932 return false;
00933 } catch (Exception e) {
00934 GrxDebugUtil.printErr("setupController:", e);
00935 }
00936 }
00937
00938 if (j > WAIT_COUNT_ || (new Date().getTime() - before.getTime() > WAIT_COUNT_*1000)) {
00939 GrxDebugUtil.println(" failed to setup controller:"+controllerName);
00940
00941 MessageDialog dialog = new MessageDialog(GrxUIPerspectiveFactory.getCurrentShell(),MessageBundle.get("GrxOpenHRPView.dialog.title.setupController"),null,MessageBundle.get("GrxOpenHRPView.dialog.message.setupController0")+controllerName+").\n" +MessageBundle.get("GrxOpenHRPView.dialog.message.setupController1"),MessageDialog.QUESTION,new String[]{MessageBundle.get("GrxOpenHRPView.dialog.button.yes"),MessageBundle.get("GrxOpenHRPView.dialog.button.no"),MessageBundle.get("GrxOpenHRPView.dialog.button.cancel")}, 2);
00942 int ans = dialog.open();
00943 if (ans == 0) {
00944 before = new Date();
00945 j=0;
00946 } else if (ans == 1) {
00947 MessageDialog.openInformation(GrxUIPerspectiveFactory.getCurrentShell(), "", MessageBundle.get("GrxOpenHRPView.dialog.message.failedController"));
00948 return false;
00949 } else {
00950 MessageDialog.openInformation(GrxUIPerspectiveFactory.getCurrentShell(), "", MessageBundle.get("GrxOpenHRPView.dialog.message.failedController"));
00951 return false;
00952 }
00953 } else {
00954 try {Thread.sleep(1000);} catch (Exception e) {}
00955 }
00956 }
00957
00958 return true;
00959 }
00960
00961 private boolean extendTime() {
00962 if(!isInteractive_)
00963 return false;
00964 boolean state = MessageDialog.openQuestion(GrxUIPerspectiveFactory.getCurrentShell(), MessageBundle.get("GrxOpenHRPView.dialog.title.timeUp"), MessageBundle.get("GrxOpenHRPView.dialog.message.TimeUp"));
00965 if (state == true)
00966 return false;
00967
00968 String str = null;
00969 while (true) {
00970 InputDialog dialog = new InputDialog(GrxUIPerspectiveFactory.getCurrentShell(),MessageBundle.get("GrxOpenHRPView.dialog.title.ExtendTime"),MessageBundle.get("GrxOpenHRPView.dialog.message.extendTime"),"5.0",null);
00971 int result = dialog.open();
00972 str = dialog.getValue();
00973 if (result == InputDialog.CANCEL)
00974 return false;
00975 try {
00976 double d = Double.parseDouble(str);
00977 if (d > 0) {
00978
00979 totalTime_ = totalTime_ + d;
00980 setDbl("totalTime", totalTime_);
00981 currentWorld_.extendTime(totalTime_);
00982 break;
00983 }
00984 } catch (NumberFormatException e) {}
00985 }
00986 return true;
00987 }
00988
00989 public boolean isSimulating(){
00990 return isExecuting_;
00991 }
00992
00993 public void restoreProperties() {
00994 super.restoreProperties();
00995 String str = getProperty("totalTime");
00996 if(str==null)
00997 setDbl("totalTime", 20.0);
00998 str = getProperty("timeStep");
00999 if(str==null)
01000 setDbl("timeStep", 0.001);
01001 str = getProperty("gravity");
01002 if(str==null)
01003 setDbl("gravity", 9.8);
01004 str = getProperty("method");
01005 if(str==null)
01006 setProperty("method","RUNGE_KUTTA");
01007 str = getProperty("integrate");
01008 if(str==null)
01009 setBool("integrate", true);
01010 str = getProperty("realTime");
01011 if(str==null)
01012 setBool("realTime", false);
01013 str = getProperty("viewsimulate");
01014 if(str==null)
01015 setBool("viewsimulate", false);
01016 }
01017
01018 public ValueEditType GetValueEditType(String key) {
01019 if(key.equals("method")){
01020 return new ValueEditCombo(methodComboItem_);
01021 }else if(key.equals("integrate") || key.equals("viewsimulate") || key.equals("realTime")){
01022 return new ValueEditCombo(booleanComboItem_);
01023 }
01024 return super.GetValueEditType(key);
01025 }
01026
01027 public int gcd(int a, int b){
01028 BigInteger bigA = BigInteger.valueOf(a);
01029 BigInteger bigB = BigInteger.valueOf(b);
01030 return bigA.gcd(bigB).intValue();
01031 }
01032
01033 public int lcm(int a, int b){
01034 return a*b/gcd(a,b);
01035 }
01036
01037 public float lcm(float a, float b){
01038 return (float)lcm((int)a, (int)b);
01039 }
01040
01041 }