void ConnElement::addMsgToLog(QString title, QString msg) { QString time = QTime::currentTime().toString(); QString errorMsg = QString("<b>%1 %2:</b><br><font color='blue'><b>EVENT</b></font>: %3") .arg(time).arg(title).arg(msg); sendWarning(errorMsg); mainWindowUp(); }
void ConnElement::writeErrorToLog(QString &msg, uint _num) { Q_UNUSED(_num); QString time = QTime::currentTime().toString(); QString title(QString("Connection '%1'").arg(name)); QString errorMsg = QString("<b>%1 %2:</b><br><font color='red'><b>ERROR</b></font>: %3") .arg(time).arg(title).arg(msg); sendWarning(errorMsg); }
bool UFunctionSeq::addCmdLine(UServerInMsg * msg, const char * line) { FILE * errLog; bool result = true; int m, i = 0; const int MRL = 300; char reply[MRL]; const char * logName = "errLog.log"; bool isOK; // make a file for syntax error etc errLog = fopen(logName, "w"); isOK = seq->add(line, errLog, &m); if (errLog != NULL) fclose(errLog); if (not isOK) { if (errLog != NULL) { // open for read of messages errLog = fopen(logName, "r"); while (fgets(reply, MRL, errLog) != NULL) { // send all warning lines sendWarning(msg, reply); i++; } fclose(errLog); } if ((errLog == NULL) or (i == 0)) { snprintf(reply, MRL, "Syntax error line %d, but no log - line will be ignored", m); sendWarning(msg, reply); } } else { snprintf(reply, MRL, "added as line %d", m); sendInfo(msg, reply); } // return result; }
bool ReadCadmould::checkFiles(const std::string &filename) { // need at least two chars (should be 5) if (filename.length() < 2) { sendError("Illegal Filename: %s", filename.c_str()); return false; } // make sure we can work with the file name char buffer[MAXPATHLEN + 1]; strncpy(buffer, filename.c_str(), MAXPATHLEN); buffer[MAXPATHLEN] = '\0'; // try to open the "Füllbild" file - this is the one we select FILE *fi = fopen(filename.c_str(), "r"); if (!fi) { sendWarning("Fuellbild %s: %s", filename.c_str(), strerror(errno)); return false; } fclose(fi); setCaseType(buffer); // try to open the "Mesh" file - Fuellbild except last char if (d_type != TYPE_CAR) { buffer[strlen(buffer) - 1] = '\0'; } fi = fopen(buffer, "r"); if (!fi) { sendError("Mesh %s: %s", buffer, strerror(errno)); return false; } fclose(fi); return true; }
bool UFunctionSeq::sendStatusMessage(UServerInMsg * msg, const char * tagName) { const int MRL = 1000; char reply[MRL]; bool result = true; USeqLine * lineActive; int lineNum; const int MCL = 200; char cmd[MCL] = "(none)"; // if (seq != NULL) { lineNum = seq->getActiveLine(); lineActive = seq->getLine(lineNum); if (lineActive != NULL) str2xml(cmd, MCL, lineActive->getCmdLine()); snprintf(reply, MRL, "<%s " "file=\"%s\" " "cmd=\"%s\" " "cmdLineNum=\"%d\" " "isIdle=\"%s\" " "simulated=\"%s\">\n", tagName, seq->getPlanName(), cmd, lineNum, bool2str(seq->isIdle()), bool2str(seq->isSimulated())); result = sendMsg(msg, reply); // send stop criteria status // -- not // send end tag snprintf(reply, MRL, "</%s>\n", tagName); result = sendMsg(msg, reply); } else sendWarning(msg, "Sequencer (seq) module lot loaded"); return result; }
bool UFunctionSeq::handleCommand(UServerInMsg * msg, void * extra) { // extract parameters bool result = true; // decode vars char attName[MAX_SML_NAME_LENGTH]; const int VAL_BUFF_LNG = 1000; char attValue[VAL_BUFF_LNG]; // camera and source image variables bool ask4help = false; bool loadFile = false; bool appendFile = false; bool getMissions = false; bool getStatus = false; bool getPgm = false; const char * label = NULL; bool sendReply = false; const int MNL = MAX_FILENAME_LENGTH; char loadName[MNL]; FILE * errLog = NULL; const char * errLogName = "loadPlanErr.log"; const int MELL = 300; char se[MELL]; int i, n; FILE * mf; char * pMf; const int MFL = 100; char mfn[MFL]; USeqLine * line; const int MRL = 300; char reply[MRL]; char lineXml[MRL]; // // extract parameters while (msg->tag.getNextAttribute(attName, attValue, VAL_BUFF_LNG)) { // camera device if (strcasecmp(attName, "help") == 0) ask4help = true; else if (strcasecmp(attName, "load") == 0) { strncpy(loadName, attValue, MNL); loadFile = true; } else if (strcasecmp(attName, "append") == 0) { strncpy(loadName, attValue, MNL); appendFile = true; } else if (strcasecmp(attName, "add") == 0) { // new mission line sendReply = addCmdLine(msg, attValue); } else if (strcasecmp(attName, "goto") == 0) { // new mission line if (label == NULL) label = seq->addLabel(); sendReply = addCmdLine(msg, attValue); } else if (strcasecmp(attName, "clear") == 0) { // clear current pgm seq->clear(); } else if (strcasecmp(attName, "sim") == 0) { // set simulation flag - if true, logfile must be set from cmd-line seq->setSimulated(str2bool(attValue)); } else if (strcasecmp(attName, "missions") == 0) getMissions = true; else if (strcasecmp(attName, "status") == 0) getStatus = true; else if (strcasecmp(attName, "pgm") == 0) getPgm = true; else if (strcasecmp(attName, "list") == 0) getPgm = true; else // unknown attribute result = false; } // if (ask4help) { sendHelpStart(msg, "SEQ"); sendText(msg, "---- Available SEQ options:\n"); sendText(msg, "missions Get list of all mission files\n"); sendText(msg, "status Get plan sequencer status\n"); sendText(msg, "pgm | list Get list of all loaded statements\n"); sendText(msg, "goto=\"cmd\" Give a manual mission line (in quotes), and skip to this\n"); sendText(msg, "load=\"file\" Load a mission file, and skip to this\n"); sendText(msg, "append=\"file\" Append a mission file, and skip to this\n"); sendText(msg, "add=\"command\" Add a manual command line\n"); sendText(msg, "stop Stop current mission (goto end of mission)\n"); sendText(msg, "clear remove all mission lines\n"); sendText(msg, "sim=true | false Set simulation flag (not implemented yet)\n"); sendMsg(msg, "</help>\n"); sendHelpDone(msg); } else { if (loadFile or appendFile) { errLog = fopen(errLogName, "w"); if (seq->loadPlan(loadName, errLog, appendFile)) { // loaded OK sendInfo(msg, "Loaded without errors"); } else { if (errLog != NULL) { fclose(errLog); errLog = fopen(errLogName, "r"); if (errLog != NULL) { // there is a file sendInfo(msg, "Load error list:"); while (fgets(se, MELL, errLog) != NULL) { // return all filenames in separate frames i = strlen(se); if (i > 1) { // cut off the linefeed at end of line se[i-1] = 0; result = sendInfo(msg, se); } if (not result) break; } } else result = sendWarning(msg, "Could not read error file"); if (errLog != NULL) fclose(errLog); } else sendWarning(msg, "There were errors, but could not create a logfile"); sendReply = true; } } if (label != NULL) { // start execution from label result = seq->skipToLabel(label, false); } } if (getMissions) { // return a list of available missions n = system("ls *.txt >missions.list"); if (n >= 0) { // there should be a file mf = fopen("missions.list", "r"); n = -1; if (mf != NULL) { // there is a file while (true) { // return all filenames in separate frames pMf = fgets(mfn, MFL, mf); if (pMf == NULL) break; if (n < 0) sendInfo(msg, "List of mission files:"); i = strlen(pMf); if (i > 1) { // cut off the linefeed at end of line pMf[i-1] = 0; result = sendInfo(msg, pMf); n++; } if (not result) break; } if (n < 0) result = sendWarning(msg, "No mission files in default dir"); } else result = sendWarning(msg, "Could not create listing of mission files"); if (mf != NULL) fclose(mf); sendReply = true; } } if (getStatus) { sendStatusMessage(msg, msg->tag.getTagName()); sendReply = true; } // last if - if noone else has send a reply ... if (getPgm) { if (seq->getLineCnt() > 0) { // make start tag for lines snprintf(reply, MRL, "<%s lineCnt=\"%d\" cmdLineNum=\"%d\" file=\"%s\">\n", msg->tag.getTagName(), seq->getLineCnt(), seq->getActiveLine(), seq->getPlanName()); sendMsg(msg, reply); for (i = 0; i < seq->getLineCnt(); i++) { line = seq->getLine(i); str2xml(lineXml, MRL, line->getCmdLine()); snprintf(reply, MRL, "<seqLine ln=\"%d\" cmd=\"%s\"/>\n", i, lineXml); result = sendMsg(msg, reply); if (not result) // stop if line-buffers are full break; } // and end tag (always try) snprintf(reply, MRL, "</%s>\n", msg->tag.getTagName()); result = sendMsg(msg, reply); } else { // no plan lines - send status only snprintf(reply, MRL, "<%s lineCnt=\"%d\" cmdLineNum=\"%d\"/>\n", msg->tag.getTagName(), seq->getLineCnt(), seq->getActiveLine()); sendMsg(msg, reply); } sendReply = true; } if (result and not sendReply) sendInfo(msg, "done"); if (not result) sendWarning(msg, "One or more attributes to SEQ is not used!"); return result; }
int Sample::compute(const char *) { int x_value, y_value, z_value; int s; bool nan_flag = false; //TODO: Is this the right default-value? float fill = .0; //TODO: Is this the right default-value? int outside; const char *object_type = NULL; unstruct_grid::vecFlag typeFlag = unstruct_grid::DONTKNOW; ias grids; ias data; grids.resize(1); data.resize(1); eps = epsParam->getValue(); if (eps < 0.0) { sendError("eps < 0.0 not allowed - please choose a valid eps"); return FAIL; } s = iSizeChoiceParam->getValue() + 1; if (s == 1) { x_value = iSizeParam->getValue(); } else { x_value = 2 << s; } s = jSizeChoiceParam->getValue() + 1; if (s == 1) { y_value = jSizeParam->getValue(); } else { y_value = 2 << s; } s = kSizeChoiceParam->getValue() + 1; if (s == 1) { z_value = kSizeParam->getValue(); } else { z_value = 2 << s; } if (x_value < 2) { sendWarning("Size in X dimension is less than 2, assuming 2"); iSizeParam->setValue(2); x_value = 2; } if (y_value < 2) { sendWarning("Size in Y dimension is less than 2, assuming 2"); jSizeParam->setValue(2); y_value = 2; } if (z_value < 2) { sendWarning("Size in Z dimension is less than 2, assuming 2"); kSizeParam->setValue(2); z_value = 2; } outside = outsideChoiceParam->getValue(); if (outside == Sample::OUTSIDE_MAX_FLT) { nan_flag = true; } else if (outside == Sample::OUTSIDE_NUMBER) { fill = fillValueParam->getValue(); nan_flag = false; } bool isStrGrid = false; // here we try to retrieve the data object from the required port const coDistributedObject *GridObj = Grid_In_Port->getCurrentObject(); TimeSteps = 0; if (!GridObj) { sendError("cannot retrieve the grid object"); return FAIL; } else if (strcmp(GridObj->getType(), "SETELE") == 0) { // Time Steps or not... const coDoSet *setGrid = (const coDoSet *)(GridObj); gridTimeSteps = setGrid->getAllElements(&num_set_ele); if (GridObj->getAttribute("TIMESTEP")) { // We have timesteps TimeSteps = 1; gridTimeSteps = setGrid->getAllElements(&num_set_ele); grids.resize(num_set_ele); data.resize(num_set_ele); for (int time = 0; time < num_set_ele; ++time) { if (gridTimeSteps[time]->isType("SETELE")) { // extract list from the set gridTimeSteps[time] const coDistributedObject *const *elemsInGridTimeSteps; int numInGridTimeSteps; elemsInGridTimeSteps = ((coDoSet *)(gridTimeSteps[time]))->getAllElements(&numInGridTimeSteps); //ExpandSetList (elemsInGridTimeSteps, numInGridTimeSteps, "UNSGRD", grids[time]); ExpandSetList(elemsInGridTimeSteps, numInGridTimeSteps, &object_type, grids[time]); } else if (!object_type) { if (gridTimeSteps[time]->isType("POINTS") || gridTimeSteps[time]->isType("UNSGRD") || gridTimeSteps[time]->isType("UNIGRD") || gridTimeSteps[time]->isType("RCTGRD") || gridTimeSteps[time]->isType("STRGRD")) { object_type = gridTimeSteps[time]->getType(); grids[time].resize(1); grids[time][0] = gridTimeSteps[time]; } else { // Strange object in the grid object sendError("Objects in the grid object have to be sets, unstructured grids or points"); return FAIL; } } else if (strcmp(gridTimeSteps[time]->getType(), object_type) == 0) { grids[time].resize(1); grids[time][0] = gridTimeSteps[time]; } else { // Strange object in the grid object sendError("Objects in the grid object have to be sets, unstructured grids or points"); return FAIL; } } if (object_type && (!strcmp(object_type, "UNIGRD") || !strcmp(object_type, "RCTGRD") || !strcmp(object_type, "STRGRD"))) { isStrGrid = true; } } else { // Static grid // We may set up grids num_blocks = ExpandSetList(gridTimeSteps, num_set_ele, &object_type, grids[0]); if (!object_type || (strcmp(object_type, "UNSGRD") != 0 && strcmp(object_type, "POINTS") != 0 && strcmp(object_type, "UNIGRD") != 0 && strcmp(object_type, "RCTGRD") != 0 && strcmp(object_type, "STRGRD") != 0)) { // Strange object in the grid object sendError("Objects in the grid object have to be sets, unstructured grids or points"); return FAIL; } } } else if (strcmp(GridObj->getType(), "UNSGRD") == 0) { object_type = "UNSGRD"; num_blocks = 1; grids[0].push_back(GridObj); } else if (strcmp(GridObj->getType(), "UNIGRD") == 0) { object_type = "UNIGRD"; num_blocks = 1; grids[0].push_back(GridObj); isStrGrid = true; } else if (strcmp(GridObj->getType(), "RCTGRD") == 0) { object_type = "RCTGRD"; num_blocks = 1; grids[0].push_back(GridObj); isStrGrid = true; } else if (strcmp(GridObj->getType(), "STRGRD") == 0) { object_type = "STRGRD"; num_blocks = 1; grids[0].push_back(GridObj); isStrGrid = true; } else if (strcmp(GridObj->getType(), "POINTS") == 0) { object_type = "POINTS"; num_blocks = 1; grids[0].push_back(GridObj); } else { sendError("Sorry, only objects of type unstructured grid or points are supported"); return FAIL; } fprintf(stderr, "isStrGrid=%d, type=%s\n", int(isStrGrid), object_type); if (!object_type) { sendError("Sorry, only objects of type unstructured grid or points are supported"); return FAIL; } if (strcmp(object_type, "POINTS") == 0) { typeFlag = unstruct_grid::POINT; } // here we try to retrieve the data object from the port const coDistributedObject *DataObj = Data_In_Port->getCurrentObject(); if (!DataObj) { cerr << "data: NULL" << endl; if (typeFlag != unstruct_grid::POINT) { sendError("cannot retrieve data object"); return FAIL; } } else if (strcmp(DataObj->getType(), "SETELE") == 0) { // Time Steps or not...: that is decided according to the grid. if (strcmp(GridObj->getType(), "SETELE") != 0) { sendError("Grid object is a set, but not the data"); return FAIL; } int data_num_set_ele; int data_num_blocks; coDoSet *setData = (coDoSet *)(DataObj); dataTimeSteps = setData->getAllElements(&data_num_set_ele); if (TimeSteps) { // We have timesteps if (data_num_set_ele != num_set_ele) { sendError("Number of time steps in grid does not match data set"); return FAIL; } for (int time = 0; time < num_set_ele; ++time) { if (strcmp(dataTimeSteps[time]->getType(), "SETELE") == 0) { // extract list from the set gridTimeSteps[time] int numInDataTimeSteps; const coDistributedObject *const *elemsInDataTimeSteps = ((coDoSet *)(dataTimeSteps[time]))->getAllElements(&numInDataTimeSteps); const char *type = NULL; int num_data = ExpandSetList(elemsInDataTimeSteps, numInDataTimeSteps, &type, data[time]); if (!type) { sendError("Invalid data"); return FAIL; } if (num_data != grids[time].size()) { sendError("Cannot match grids and data sets -- data must be node based"); return FAIL; } // try first vector if (strcmp(type, "USTVDT") == 0) { if (typeFlag == unstruct_grid::DONTKNOW) { typeFlag = unstruct_grid::VECTOR; } else { sendError("Cannot decide between vector, scalar, and point"); return FAIL; } } // then try scalar else if (strcmp(type, "USTSDT") == 0) { if (typeFlag == unstruct_grid::DONTKNOW) { typeFlag = unstruct_grid::SCALAR; } else { sendError("Cannot decide between vector, scalar, and point"); return FAIL; } } else if (strcmp(type, "POINTS") == 0) { if (typeFlag == unstruct_grid::DONTKNOW) { typeFlag = unstruct_grid::POINT; } else { sendError("Cannot decide between vector, scalar, and point"); return FAIL; } } else { sendError("Invalid data type"); return FAIL; } } else if (strcmp(dataTimeSteps[time]->getType(), "USTSDT") == 0) { data[time].resize(1); data[time][0] = dataTimeSteps[time]; if (typeFlag == unstruct_grid::DONTKNOW) { typeFlag = unstruct_grid::SCALAR; } else if (typeFlag == unstruct_grid::VECTOR) { sendError("Cannot decide between vector and scalar"); return FAIL; } } else if (strcmp(dataTimeSteps[time]->getType(), "USTVDT") == 0) { data[time].resize(1); data[time][0] = dataTimeSteps[time]; if (typeFlag == unstruct_grid::DONTKNOW) { typeFlag = unstruct_grid::VECTOR; } else if (typeFlag != unstruct_grid::VECTOR) { sendError("Cannot decide between vector and scalar"); return FAIL; } } else if (strcmp(dataTimeSteps[time]->getType(), "POINTS") == 0) { data[time].resize(1); data[time][0] = dataTimeSteps[time]; if (typeFlag == unstruct_grid::DONTKNOW) { typeFlag = unstruct_grid::POINT; } else if (typeFlag != unstruct_grid::POINT) { sendError("Cannot decide between vector, scalar and point"); return FAIL; } } else { sendError("Object of incorrect type in data set"); return FAIL; } } } // static set... set up data else { const char *type = NULL; data_num_blocks = ExpandSetList(dataTimeSteps, data_num_set_ele, &type, data[0]); if (!type) { sendError("Invalid data"); return FAIL; } if (data_num_blocks != num_blocks) { sendError("Grid and data sets do not match for the accepted types"); return FAIL; } if (typeFlag == unstruct_grid::DONTKNOW) { if (strcmp(type, "USTSDT") == 0) { typeFlag = unstruct_grid::SCALAR; } else if (strcmp(type, "USTVDT") == 0) { typeFlag = unstruct_grid::VECTOR; } else if (strcmp(type, "POINTS") == 0) { typeFlag = unstruct_grid::POINT; } else { sendError("Invalid data type"); return FAIL; } } } } else if (strcmp(DataObj->getType(), "USTSDT") == 0) { data[0].resize(1); data[0][0] = (DataObj); if (typeFlag == unstruct_grid::DONTKNOW) typeFlag = unstruct_grid::SCALAR; } else if (strcmp(DataObj->getType(), "USTVDT") == 0) { data[0].resize(1); data[0][0] = (DataObj); if (typeFlag == unstruct_grid::DONTKNOW) typeFlag = unstruct_grid::VECTOR; } else if (strcmp(DataObj->getType(), "POINTS") == 0) { data[0].resize(1); data[0][0] = (DataObj); if (typeFlag == unstruct_grid::DONTKNOW) typeFlag = unstruct_grid::POINT; } else { sendError("Only scalar or vector unstructured data, points or sets thereof are supported"); return FAIL; } coDoUniformGrid **destGrids = NULL; const coDistributedObject *refGrid = Reference_Grid_In_Port->getCurrentObject(); if (refGrid) { if (TimeSteps) { destGrids = new coDoUniformGrid *[num_set_ele]; } else { destGrids = new coDoUniformGrid *[1]; } if (!strcmp(refGrid->getType(), "SETELE")) { coDoSet *set = (coDoSet *)refGrid; int refgrid_num_set_ele; const coDistributedObject *const *refGridTimeSteps = set->getAllElements(&refgrid_num_set_ele); if (TimeSteps) { if (refgrid_num_set_ele != num_set_ele) { sendError("Number of time steps in reference grid does not match data set"); return FAIL; } for (int i = 0; i < num_set_ele; i++) { if (strcmp(refGridTimeSteps[i]->getType(), "UNIGRD")) { sendError("Reference grid must be a uniform grid or a set thereof"); return FAIL; } coDoUniformGrid *ugr = (coDoUniformGrid *)refGridTimeSteps[i]; destGrids[i] = ugr; } } } else { if (strcmp(refGrid->getType(), "UNIGRD")) { sendError("Reference grid must be a uniform grid or a set thereof"); return FAIL; } coDoUniformGrid *ugr = (coDoUniformGrid *)refGrid; if (TimeSteps) { for (int i = 0; i < num_set_ele; i++) { destGrids[i] = ugr; } } else { destGrids[0] = ugr; } } } if (Diagnose(grids, data, typeFlag, isStrGrid) < 0) { sendError("Grid and data are not compatible or an undefined problem occurred"); return FAIL; } // check struncture of grids, sdata and vdata // Diagnose // check dimension of grid and data /* int numElems, numIndices, numCoords, numData; ((coDoUnstructuredGrid *)GridObj)->getGridSize(&numElems, &numIndices, &numCoords); numData = ((coDoFloat*)DataObj)->getNumPoints(); if (numData != numCoords) { if (numData == numElems) { sendError("Sample supports only vertex based data - you seem to have cell based data"); return FAIL; } else { char str[500]; sprintf (str, "Dimension of data doesn't match dimension of grid - found %d coordinates and %d data", numCoords, numData); sendError(str); return FAIL; } } */ // now we create an object for the output port: get the name and make the Obj const char *Grid_outObjName = Grid_Out_Port->getObjName(); const char *Data_outObjName = Data_Out_Port->getObjName(); char time_grid_name[64]; char time_data_name[64]; strcpy(time_grid_name, Grid_outObjName); strcpy(time_data_name, Data_outObjName); coDistributedObject **usg = new coDistributedObject *[grids.size() + 1]; usg[grids.size()] = 0; coDistributedObject **str = new coDistributedObject *[grids.size() + 1]; str[grids.size()] = 0; int strelem; for (strelem = 0; strelem < grids.size(); ++strelem) { str[strelem] = NULL; } float gmin[3] = { FLT_MAX, FLT_MAX, FLT_MAX }, gmax[3] = { -FLT_MAX, -FLT_MAX, -FLT_MAX }; if (!destGrids && p_bounding_box->getValue() == 1) // automatic globally { for (int time = 0; time < grids.size(); time++) { unstruct_grid *calc_grid = new unstruct_grid(grids[time], typeFlag, isStrGrid); calc_grid->automaticBoundBox(); const float *min, *max; calc_grid->getMinMax(min, max); for (int i = 0; i < 3; i++) { if (min[i] < gmin[i]) gmin[i] = min[i]; if (max[i] > gmax[i]) gmax[i] = max[i]; } delete calc_grid; } } for (int time = 0; time < grids.size(); time++) { if (TimeSteps) { sprintf(time_grid_name, "%s_%d", Grid_outObjName, time); sprintf(time_data_name, "%s_%d", Data_outObjName, time); } // unstruct_grid *calc_grid=new unstruct_grid((coDoUnstructuredGrid*)GridObj); //int size = grids[time].size (); //@@@ int num_compressed = grids[time].num_compressed(); unstruct_grid *calc_grid = new unstruct_grid(grids[time], typeFlag, isStrGrid); if (destGrids) { float min[3], max[3]; destGrids[time]->getMinMax(&min[0], &max[0], &min[1], &max[1], &min[2], &max[2]); p_P1bound_manual->setValue(min[0], min[1], min[2]); p_P2bound_manual->setValue(max[0], max[1], max[2]); calc_grid->manualBoundBox(min[0], min[1], min[2], max[0], max[1], max[2]); destGrids[time]->getGridSize(&x_value, &y_value, &z_value); } else if (p_bounding_box->getValue() == 0) // automatic per timestep { calc_grid->automaticBoundBox(); const float *min, *max; calc_grid->getMinMax(min, max); p_P1bound_manual->setValue(min[0], min[1], min[2]); p_P2bound_manual->setValue(max[0], max[1], max[2]); } else if (p_bounding_box->getValue() == 1) // automatic globally { calc_grid->manualBoundBox(gmin[0], gmin[1], gmin[2], gmax[0], gmax[1], gmax[2]); } else if (p_bounding_box->getValue() == 2) // manual { calc_grid->manualBoundBox(p_P1bound_manual->getValue(0), p_P1bound_manual->getValue(1), p_P1bound_manual->getValue(2), p_P2bound_manual->getValue(0), p_P2bound_manual->getValue(1), p_P2bound_manual->getValue(2)); } const coDistributedObject **ndata = NULL; if (data.size() > time && data[time].size() > 0) ndata = &data[time][0]; calc_grid->set_value(nan_flag, fill); // create data on strcutured grid if (grids[time].size() <= 0) { x_value = y_value = z_value = 1; } if ((typeFlag == unstruct_grid::SCALAR || typeFlag == unstruct_grid::VECTOR) && isStrGrid) { calc_grid->sample_structured(ndata, time_grid_name, &usg[time], time_data_name, &str[time], x_value, y_value, z_value); } else if (typeFlag == unstruct_grid::POINT) { calc_grid->sample_points(ndata, time_grid_name, &usg[time], time_data_name, &str[time], x_value, y_value, z_value, p_pointSampling->getValue()); } else { switch (p_algorithm->getValue()) { case SAMPLE_ACCURATE: // sl: this algorithm (the "old" one) // is not as exact as it promises. // The problem is that internally it calculates // the indices around the element nodes approximating // by default... As a result of this, strange // effects appear sometimes near the borders. // For this reason, and because it is very slow // (that is why it is not worth the effort correcting // the inaccuracies near the borders), // the other new algorithms are recommended, // especially SAMPLE_NO_HOLES_BETTER. calc_grid->sample_accu(ndata, /*&sdata[time][0] */ time_grid_name, &usg[time], time_data_name, &str[time], x_value, y_value, z_value, eps); break; case SAMPLE_HOLES: calc_grid->sample_holes(ndata, time_grid_name, &usg[time], time_data_name, &str[time], x_value, y_value, z_value); break; case SAMPLE_NO_HOLES: calc_grid->sample_no_holes(ndata, time_grid_name, &usg[time], time_data_name, &str[time], x_value, y_value, z_value, 0); break; case SAMPLE_NO_HOLES_BETTER: calc_grid->sample_no_holes(ndata, time_grid_name, &usg[time], time_data_name, &str[time], x_value, y_value, z_value, 1); break; } } // attach the name of the input data object to the output grid object if ((typeFlag == unstruct_grid::SCALAR || typeFlag == unstruct_grid::VECTOR) && isStrGrid) { const char **names, **values; int n = grids[time][0]->getAllAttributes(&names, &values); for (int i = 0; i < n; i++) { if (strcmp(names[i], "Transformation") != 0) { usg[time]->addAttribute(names[i], values[i]); } } } else { usg[time]->copyAllAttributes(grids[time][0]); } if (ndata) { usg[time]->addAttribute("DataObjectName", (*ndata)->getName()); str[time]->copyAllAttributes((*ndata) /*sdata[time][0] */); } delete calc_grid; } // tell the output port that this is his object if (TimeSteps == 0) { Grid_Out_Port->setCurrentObject(usg[0]); Data_Out_Port->setCurrentObject(str[0]); } else { coDoSet *gridOutTime = new coDoSet(Grid_outObjName, usg); sprintf(time_grid_name, "1 %d", (int)grids.size()); gridOutTime->addAttribute("TIMESTEP", time_grid_name); Grid_Out_Port->setCurrentObject(gridOutTime); // if(typeFlag == unstruct_grid::SCALAR){ coDoSet *dataOutTime = new coDoSet(Data_outObjName, str); dataOutTime->addAttribute("TIMESTEP", time_grid_name); Data_Out_Port->setCurrentObject(dataOutTime); // } } // Add INTERACTOR attribute to the grid coFeedback feedback("Sample"); feedback.addPara(iSizeParam); feedback.addPara(jSizeParam); feedback.addPara(kSizeParam); feedback.addPara(p_P1bound_manual); feedback.addPara(p_P2bound_manual); coDistributedObject *obj = Grid_Out_Port->getCurrentObject(); if (obj) feedback.apply(obj); return SUCCESS; }
void IMT_MRGui::readcalcwrite_thread() { unsigned int num_rows = 0; unsigned int num_columns = 0; unsigned int num_coils = 0; std::vector<TType_data> matrix_read; std::vector<TType_image> image_data; QString name_index; unsigned short int acq, sli, par, echo, pha, rep, set, seg; unsigned short int acq_info, sli_info, par_info, echo_info, pha_info, rep_info, set_info, seg_info; std::vector<INDEX_select> index_vector; int error = 0; matrix_read.clear(); //clear all elements image_data.clear(); //clear all elements _seconds = time (NULL); if( ((read_siemens == 0) && !_readmatlab) || (_readmatlab && (_matlab_num_rows == 0))) { emit sendInfo("Load Data first!", false); emit sendWarning("Load Data first!"); } else { if(!_readmatlab) read_siemens->getRawdata_info(num_rows, num_columns, num_coils, acq_info, sli_info, par_info, echo_info, pha_info, rep_info, set_info, seg_info); else { num_rows = _matlab_num_rows; num_columns = _matlab_num_columns; num_coils = _matlab_num_coils; } if(ui->cb_cropFOV->isChecked() == true) { _num_rows_calc = num_rows; _num_columns_calc = num_rows; } else { _num_rows_calc = num_rows; _num_columns_calc = num_columns; } if(!_readmatlab) generate_idx(read_siemens, index_vector); for(int i=0; i<_num_columns_calc*_num_rows_calc; ++i) zero_vec_cpu_.push_back(TType_real(0)); matrix_read.reserve(2*_num_columns_data*_num_rows_data*_num_coils_data); image_data.reserve(_num_columns_calc*_num_rows_calc); if(!_readmatlab) { for(int i=0; i<index_vector.size();++i) //get threw all user-selected idx { // endselect = setcheckindex(read_siemens, acq, sli, par, echo, pha, rep, set, seg ); acq = index_vector[i].acq; sli = index_vector[i].sli; par = index_vector[i].par; echo = index_vector[i].echo; pha = index_vector[i].pha; rep = index_vector[i].rep; set = index_vector[i].set; seg = index_vector[i].seg; qDebug() <<"\n\nactual selection: "<<sli<<" "<< acq<<" "<< rep<<" "<< par<<" "<< echo<<" "<< pha<<" "<< set<<" "<< seg; if (ui->combo_seg_select->currentText() == "All") { for(int i=0; i<= seg_info;++i) { read_siemens->getRawdata(matrix_read,acq, sli, par, echo, pha, rep, set, i); } } else { read_siemens->getRawdata(matrix_read,acq, sli, par, echo, pha, rep, set, seg); } // TEST READ //agile::readMatrixFile3D("brain_151x256x6.bin", num_rows, num_columns, num_coils, matrix_read); //agile::readMatrixFile3D("braindata.bin", num_rows, num_columns, num_coils, matrix_read); QString str_acq, str_sli, str_par, str_echo, str_pha, str_rep, str_set, str_seg; str_acq.setNum(acq); str_sli.setNum(sli); str_par.setNum(par); str_echo.setNum(echo); str_pha.setNum(pha); str_rep.setNum(rep); str_set.setNum(set); str_seg.setNum(seg); _infotext.append("\n===================\n"); //_strselection = "===================\n"; _infotext.append("| "+str_sli+" - "+str_acq+" - "+str_par+" - "+str_echo+" - "+str_pha+" - "+str_rep+" - " +str_set+" - "+str_seg+" |"); _infotext.append("\n-------------------------------------"); error = startcalculation(_num_rows_calc, _num_columns_calc, _num_coils_data, matrix_read, image_data); if(error == 0) { time_t timet=time (NULL); unsigned time = unsigned(timet) - unsigned(_seconds); QString str_time; str_time.setNum(time); _infotext.append("\nFinished in "+str_time+"sec\n"); } if(error != 0) std::cerr<<"\n Calculation Error - nb: "<<error; else { unsigned dummy=0; std::ostringstream filename; filename <<std::setfill ('0') << std::setw (4)<<_write_file_index <<std::setfill ('0') << std::setw (2)<<dummy <<std::setfill ('0') << std::setw (2)<<ui->cb_savingtype->currentIndex()+1 <<std::setfill ('0') << std::setw (2)<<sli <<std::setfill ('0') << std::setw (2)<<echo <<std::setfill ('0') << std::setw (2)<<dummy <<std::setfill ('0') << std::setw (2)<<acq; // filename << "_"<<std::setfill ('0') << std::setw (4)<<sli // <<std::setfill ('0') << std::setw (4)<<acq // <<std::setfill ('0') << std::setw (4)<<par // <<std::setfill ('0') << std::setw (4)<<echo // <<std::setfill ('0') << std::setw (4)<<pha // <<std::setfill ('0') << std::setw (4)<<rep // <<std::setfill ('0') << std::setw (4)<<set // <<std::setfill ('0') << std::setw (4)<<seg; name_index = (filename.str().c_str()); writeoutfile(_num_rows_calc, _num_columns_calc, _num_coils_data, image_data, matrix_read,name_index); _write_file_index++; } } } else { QString path = _pathsetting->get_matlabpath() +"/"+ _outfilename+".bin"; agile::readMatrixFile3D(path.toStdString().c_str(), num_rows, num_columns, num_coils, matrix_read); //qDebug()<<"\n path: "<<path<<" size: "<<matrix_read.size(); _infotext.append("\n==================="); error = startcalculation(_num_rows_calc, _num_columns_calc, _num_coils_data, matrix_read, image_data); if(error == 0) { time_t timet=time (NULL); unsigned time = unsigned(timet) - unsigned(_seconds); QString str_time; str_time.setNum(time); _infotext.append("\nFinished in "+str_time+"sec\n"); } if(error != 0) std::cerr<<"\n Calculation Error - nb: "<<error; else { unsigned dummy=0; std::ostringstream filename; filename <<std::setfill ('0') << std::setw (4)<<_write_file_index <<std::setfill ('0') << std::setw (2)<<dummy <<std::setfill ('0') << std::setw (2)<<ui->cb_savingtype->currentIndex()+1 <<std::setfill ('0') << std::setw (2)<<sli <<std::setfill ('0') << std::setw (2)<<echo <<std::setfill ('0') << std::setw (2)<<dummy <<std::setfill ('0') << std::setw (2)<<acq; // filename << "_"<<std::setfill ('0') << std::setw (4)<<sli // <<std::setfill ('0') << std::setw (4)<<acq // <<std::setfill ('0') << std::setw (4)<<par // <<std::setfill ('0') << std::setw (4)<<echo // <<std::setfill ('0') << std::setw (4)<<pha // <<std::setfill ('0') << std::setw (4)<<rep // <<std::setfill ('0') << std::setw (4)<<set // <<std::setfill ('0') << std::setw (4)<<seg; name_index = (filename.str().c_str()); writeoutfile(_num_rows_calc, _num_columns_calc, _num_coils_data, image_data, matrix_read,name_index); _write_file_index++; } } if(error==0) { if(_pathsetting->get_archiveactive()) copytoarchive(); emit sendInfo(_infotext,false); _act_index++; } else { _infotext.append("\nError\n"); emit sendInfo(_infotext,false); } if(_automatic_on == true) _cycleread_thread->cycle_read(_pathsetting->get_dcmrawpath()); } }
/** Handle incomming command (intended for command separation) Must return true if the function is handled - otherwise the client will get a failed - reply */ virtual bool handleCommand(UServerInMsg * msg, void * extra) { // handle a plugin command const int MRL = 500; char reply[MRL]; bool ask4help; const int MVL = 30; char value[MVL]; ULaserData * data; // // check for parameters - one parameter is tested for - 'help' ask4help = msg->tag.getAttValue("help", value, MVL); if (ask4help) { // create the reply in XML-like (html - like) format sendHelpStart(msg, "inbox"); sendText("--- available INBOX options\n"); sendText("add=name x1=A y1=B x2=C y2=D"); sendText(" add named box with limits A,B,C,D in robot coordinates\n"); sendText("detect Detect for objects in box\n"); sendText("poly=S make also result polygons in -1=none, 0=odo (default), 1=UPM, 2=Map coordinates\n"); sendText("silent send no (less) reply\n"); sendText("fake=F Fake some data 1=random, 2-4 a fake corridor\n"); sendText("device=N Laser device to use (see: SCANGET help)\n"); sendText("see also: SCANGET and SCANSET\n"); sendHelpDone(); } else { // do some action and send a reply int polySys = -2; bool silent; msg->tag.getAttInteger("poly", &polySys, 0); // test if silent option - i.e. no reply needed msg->tag.getAttBool("silent", &silent); // test add option if (msg->tag.getAttValue("add", value, MVL)) { // get all needed parameters double x1, x2, y1, y2; bool gotX1, gotX2, gotY1, gotY2; gotX1 = msg->tag.getAttDouble("x1", &x1); gotX2 = msg->tag.getAttDouble("x2", &x2); gotY1 = msg->tag.getAttDouble("y1", &y1); gotY2 = msg->tag.getAttDouble("y2", &y2); if (gotX1 and gotX2 and gotY1 and gotY2) { UNamedBox * bx; bx = boxes.addBox(value, x1, y1, x2, y2); if (not silent) { if (bx != NULL) sendInfo("box added"); else sendWarning("failed to add box"); } if (polySys != -1 and bx != NULL) { snprintf(reply, MRL, "%s_Box", bx->varName->getString()); sendToPolyPlugin(reply, &bx->cornerPolygon, 0); } } else { if (not silent) sendInfo("failed to add box, not enough parameters"); } } // test detect option if (msg->tag.getAttValue("detect", NULL, 0)) { ULaserDevice * lasDev; // laser device data = getScan(msg, (ULaserData*)extra, false, &lasDev); // if (data->isValid()) { // make analysis for closest measurement int i; // double minAngle = 0.0; // degrees i = boxes.doDetect(data, polySys, lasDev, polySys); if (not silent and boxes.boxesCnt > 1) { snprintf(reply, MRL, "detections in %d boxes", i); sendInfo(reply); } if (not silent) { // send reply to client UNamedBox * nb; snprintf(reply, MRL, "boxCnt=\"%d\"", boxes.boxesCnt); sendStartTag(reply); for (int i= 0; i < boxes.boxesCnt; i++) { nb = &boxes.boxes[i]; snprintf(reply, MRL, "<box idx=\"%d\" name=\"%s\" detectCnt=\"%d\"/>\n", i, nb->varName->getString(), nb->varDetections->getInt()); sendMsg(reply); } sendEndTag(); } if (polySys != -1) { // send polygons to polygon plugin UNamedBox * bx; const int MSL = 20; char s[MSL]; for (int i = 0; i < boxes.boxesCnt; i++) { bx = &boxes.boxes[i]; snprintf(s, MSL, "%s_Box", bx->varName->getString()); sendToPolyPlugin(bx->varName->getString(), &bx->poly, 0); sendToPolyPlugin(s, &bx->cornerPolygon, 0); } } } else sendWarning(msg, "No scandata available"); } } // return true if the function is handled with a positive result return true; }
int CoolEmAllToDatabase::compute(const char *port) { const coDoSet *boco; const coDoUnstructuredGrid *grid; const coDoFloat *tempObject; const coDoFloat *pressureObject; const coDoVec3 *veloObject; temp = NULL; press = NULL; grid = dynamic_cast<const coDoUnstructuredGrid *>(p_grid->getCurrentObject()); boco = dynamic_cast<const coDoSet *>(p_boco->getCurrentObject()); tempObject = dynamic_cast<const coDoFloat *>(p_temp->getCurrentObject()); if (tempObject) { tempObject->getAddress(&temp); } pressureObject = dynamic_cast<const coDoFloat *>(p_p->getCurrentObject()); if (pressureObject) { pressureObject->getAddress(&press); } vx = NULL; vy = NULL; vz = NULL; veloObject = dynamic_cast<const coDoVec3 *>(p_velo->getCurrentObject()); if (veloObject) { veloObject->getAddresses(&vx, &vy, &vz); } if (boco && grid) { const coDistributedObject *const *setObj; colDiricletVals = 5; grid->getAddresses(&elem, &conn, &x, &y, &z); grid->getGridSize(&numElem, &numConn, &numCoord); grid->getTypeList(&inTypeList); setObj = boco->getAllElements(&numObj); ///////// Diriclet Nodes const coDoIntArr *diricletIndexObj = dynamic_cast<const coDoIntArr *>(setObj[3]); if (!diricletIndexObj) { sendWarning("illegal part type (3) in boco"); return FAIL; } else { colDiriclet = diricletIndexObj->getDimension(0); //2 numDiriclet = diricletIndexObj->getDimension(1); diricletIndex = diricletIndexObj->getAddress(); } // 0,10,20,30,40....32 inletnodes numberinletnodes = (numDiriclet * colDiriclet) / (2 * colDiricletVals); int *inletnodes = (int *)malloc(numberinletnodes * sizeof(int)); if (numberinletnodes == 0) { fprintf(stderr, "missing inlet boundary condition! Stopping. Please generate inlet boco.\n"); sendError("missing inlet boundary condition! Stopping. Please generate inlet boco."); return STOP_PIPELINE; } ///////// balance indices const coDoIntArr *balanceObj = dynamic_cast<const coDoIntArr *>(setObj[6]); if (!balanceObj) { sendWarning("illegal part type (6) in boco"); return FAIL; } else { coDoIntArr *balanceObj = (coDoIntArr *)setObj[6]; colBalance = balanceObj->getDimension(0); numBalance = balanceObj->getDimension(1); balance = balanceObj->getAddress(); int oldType = -2; //types: 100-111 rack inlet // 200-211 rack outlet // 150-154 floor inlet (four different types) // 300- for (int i = 0; i < numBalance; i++) { int type = balance[(i * colBalance) + 5]; if (type != oldType) { fprintf(stderr, "%d Type %d\n", i, type); patches.push_back(new BoundaryPatch(this, type, i)); oldType = type; } } } } int nPolOut = 0; int *polOut; int *vertOut; float *xOut; float *yOut; float *zOut; std::list<BoundaryPatch *>::iterator it; for (it = patches.begin(); it != patches.end(); it++) { nPolOut += (*it)->quads.size(); } coDoPolygons *outgrid = new coDoPolygons(p_gridOut->getObjName(), nPolOut * 4, nPolOut * 4, nPolOut); outgrid->getAddresses(&xOut, &yOut, &zOut, &vertOut, &polOut); p_gridOut->setCurrentObject(outgrid); int pn = 0; for (it = patches.begin(); it != patches.end(); it++) { std::list<BoundaryQuad *>::iterator qit; for (qit = (*it)->quads.begin(); qit != (*it)->quads.end(); qit++) { polOut[pn] = pn * 4; for (int n = 0; n < 4; n++) { vertOut[pn * 4 + n] = pn * 4 + n; xOut[pn * 4 + n] = (*qit)->corners[n].x(); yOut[pn * 4 + n] = (*qit)->corners[n].y(); zOut[pn * 4 + n] = (*qit)->corners[n].z(); } pn++; } } FILE *fp = fopen(p_csvPath->getValue(), "w"); if (fp) { // obtain the existing locale name for numbers char *oldLocale = setlocale(LC_NUMERIC, NULL); // inherit locale from environment setlocale(LC_NUMERIC, "German"); fprintf(fp, ";"); for (it = patches.begin(); it != patches.end(); it++) { fprintf(fp, "%s;", (*it)->name.c_str()); } fprintf(fp, "\n"); fprintf(fp, "Area;"); for (it = patches.begin(); it != patches.end(); it++) { fprintf(fp, "%f;", (*it)->area); } fprintf(fp, "\n"); fprintf(fp, "Temperature;"); for (it = patches.begin(); it != patches.end(); it++) { fprintf(fp, "%f;", (*it)->averageTemperature - 273.15); } fprintf(fp, "\n"); fprintf(fp, "Pressure;"); for (it = patches.begin(); it != patches.end(); it++) { fprintf(fp, "%f;", (*it)->averagePressure); } fprintf(fp, "\n"); fprintf(fp, "Vx;"); for (it = patches.begin(); it != patches.end(); it++) { fprintf(fp, "%f;", (*it)->averageVelo[0]); } fprintf(fp, "\n"); fprintf(fp, "Vy;"); for (it = patches.begin(); it != patches.end(); it++) { fprintf(fp, "%f;", (*it)->averageVelo[1]); } fprintf(fp, "\n"); fprintf(fp, "Vz;"); for (it = patches.begin(); it != patches.end(); it++) { fprintf(fp, "%f;", (*it)->averageVelo[2]); } fprintf(fp, "\n"); fclose(fp); // set the locale back setlocale(LC_NUMERIC, oldLocale); } CoolEmAllClient *cc = new CoolEmAllClient("recs1.coolemall.eu"); for (it = patches.begin(); it != patches.end(); it++) { char pathName[1000]; char value[1000]; sprintf(pathName, "%s/%s", p_databasePrefix->getValue(), (*it)->name.c_str()); sprintf(value, "%f", (*it)->averageTemperature - 273.15); //cc->setValue(pathName,"temperature",value); sprintf(value, "%f", (*it)->averagePressure); //cc->setValue(pathName,"pressure",value); float vol = sqrt((*it)->averageVelo[0] * (*it)->averageVelo[0] + (*it)->averageVelo[1] * (*it)->averageVelo[1] + (*it)->averageVelo[2] * (*it)->averageVelo[2]) / (*it)->area; sprintf(value, "%f", vol); //cc->setValue(pathName,"airflow_velocity",value); } for (it = patches.begin(); it != patches.end(); it++) { delete (*it); } patches.clear(); return SUCCESS; }
void ReadCadmould::openFiles() { retOpenFile = 0; // cout << "p_byteswap: "<<p_byteswap->getValue()<<endl; /// shut down all old if exist delete d_grid; for (int i = 0; i < d_numDataSets; i++) { delete d_data[i]; d_data[i] = NULL; } d_numDataSets = 0; // the filename parameter const char *selFile = p_filename->getValue(); // make sure we can work with the file name char basename[MAXPATHLEN + 1], filename[MAXPATHLEN + 1]; //// Open mesh file: clip off last char if old style strncpy(basename, selFile, MAXPATHLEN); basename[MAXPATHLEN] = '\0'; setCaseType(basename); if (d_type != TYPE_CAR) { basename[strlen(basename) - 1] = '\0'; } d_grid = new CadmouldGrid(basename); int gridState = -1; int gridNoVert = -1; if (d_grid) gridState = d_grid->getState(); if (gridState != 0) { if (gridState < 0) sendError("Could not read %s as Cadmould mesh", basename); else sendError("Could not read %s as Cadmould mesh: %s", basename, strerror(gridState)); delete d_grid; d_grid = NULL; } else { gridNoVert = d_grid->getNumVert(); } // from now on: base is Fuellbild file ( case+Kenner ) strncpy(basename, selFile, MAXPATHLEN); basename[MAXPATHLEN] = '\0'; if (d_type == TYPE_CAR) { char car_base[MAXPATHLEN]; strcpy(car_base, basename); *(strstr(car_base, ".cfe")) = '\0'; CarFiles files(car_base); for (int grp_nb = 0; grp_nb < files.numGroups(); grp_nb++) { MultiCarData *data = new MultiCarData(files, grp_nb, byteswap_); if (data) { if (data->getState() == 0) { d_data[d_numDataSets] = data; d_numDataSets++; } else { delete data; } } } } else if (d_type == TYPE_STD) { // check, whether we have a E0 file = Rheologie-File { sprintf(filename, "%sE0", basename); static const char *labelsE0[] = { "Fliessfront-Temperatur", "Fliessfront-Druckbedarf", "Fliessfront-Schubspannung", "Fliessfront-Geschwindigkeit" }; FuellDruckData *data = new FuellDruckData(filename, 4, labelsE0, byteswap_); if (data) { if (data->getState() == 0) { d_data[d_numDataSets] = data; d_numDataSets++; } else delete data; } } // check, whether we have E## files = Zwischenergebnisse { sprintf(filename, "%sE", basename); static const char *labelsExx[] = { "Momentan-Temperatur(t)", "Momentan-Druck(t)", "Momentan-Schubspannung(t)", "Momentan-Geschwindigkeit(t)" }; MultiFuellData *data = new MultiFuellData(filename, 4, labelsExx, byteswap_); if (data) { if (data->getState() == 0) { d_data[d_numDataSets] = data; d_numDataSets++; } else delete data; } } // check, whether we have S## files = Schichtergebnisse { sprintf(filename, "%sS", basename); static const char *labelsSxx[] = { "Randschichtddicke(t)" }; MultiFuellData *data = new MultiFuellData(filename, 1, labelsSxx, byteswap_); if (data) { if (data->getState() == 0) { d_data[d_numDataSets] = data; d_numDataSets++; } else delete data; } } //////// other data sets here ... // filling process, file: basename // data: Fuellstand, connect, fill_time { static const char *labelsFilling[] = { "Fuellstand", "Connect", "fill_time" }; static const CadmouldData::FieldType fieldType[] = { CadmouldData::SCALAR_FLOAT, CadmouldData::SCALAR_INT, CadmouldData::SCALAR_FLOAT }; FillingData *data = new FillingData(basename, 3, labelsFilling, fieldType, byteswap_); fillTimeDataSets = -1; fillChoice = 0; if (data) { if (data->getState() == 0) { fillTimeDataSets = d_numDataSets; fillField = 0; d_data[d_numDataSets] = data; d_numDataSets++; if (gridNoVert != -1 && data->numVert() != ((gridNoVert + 3) / 4) * 4) { retOpenFile = -1; sendWarning("Number of nodes from mesh and fill-data does not match. Trying with the contrary byte-swapping option"); } } else delete data; } } // check, whether we have .car files { CarFiles files(basename); for (int i = 0; i < files.numFiles(); i++) { CarData *data = new CarData(files.get(i), byteswap_); if (data) { if (data->getState() == 0) { d_data[d_numDataSets] = data; d_numDataSets++; } else delete data; } } } } if (retOpenFile == 0) { // create the labels for the choices int numLabels = 1; // the "---" label for (int i = 0; i < d_numDataSets; i++) numLabels += d_data[i]->numFields(); const char **labels = new const char *[numLabels]; labels[0] = "---"; int labelNo = 1; for (int i = 0; i < d_numDataSets; i++) { for (int j = 0; j < d_data[i]->numFields(); j++) { labels[labelNo] = d_data[i]->getName(j); if (fillChoice == 0 && strstr(labels[labelNo], "Fuellzeit") != NULL) { fillChoice = labelNo; } else if (fillChoice == 0 && strstr(labels[labelNo], "llzeit")) { fillChoice = labelNo; } // +1 because choices return 1 for 1st label ([0]) dataLoc[labelNo].datasetNo = i; dataLoc[labelNo].fieldNo = j; labelNo++; } } // attach to all choices, keep old values if valid for (int i = 0; i < NUM_PORTS; i++) { int oldVal = p_choice[i]->getValue(); //if (oldVal<d_numDataSets-2) if (oldVal < numLabels) p_choice[i]->setValue(numLabels, labels, oldVal); else p_choice[i]->setValue(numLabels, labels, 0); } labels[0] = "automatic"; p_fillField->setValue(numLabels, labels, fillChoice); } }
void MergeAndNormals::preHandleObjects(coInputPort **in_ports) { preOK_ = true; merge_ = false; const coDistributedObject *intext = in_ports[2]->getCurrentObject(); if (!intext || !intext->isType("DOTEXT")) { return; } coDoText *theText = (coDoText *)intext; int size = theText->getTextLength(); if (size == 0) { return; } char *text; theText->getAddress(&text); istringstream strText; strText.str(string(text)); int maxLen = strlen(text) + 1; std::vector<char> name(maxLen); readGrundZellenHoehe_ = false; readGrundZellenBreite_ = false; grundZellenHoehe_ = 0.0; grundZellenBreite_ = 0.0; mergeNodes_ = 0; while (strText >> &name[0]) { if (strcmp(&name[0], "grundZellenHoehe") == 0) { if (ReadASCIIDyna::readFloatSlider(strText, &grundZellenHoehe_, maxLen) != 0) { sendWarning("Could not read grundZellenHoehe"); return; } readGrundZellenHoehe_ = true; } else if (strcmp(&name[0], "grundZellenBreite") == 0) { if (ReadASCIIDyna::readFloatSlider(strText, &grundZellenBreite_, maxLen) != 0) { sendWarning("Could not read grundZellenBreite"); return; } readGrundZellenBreite_ = true; } /* else if(strcmp(&name[0],"mergeNodes")==0){ if(ReadASCIIDyna::readBoolean(strText,&mergeNodes_,maxLen)!=0){ sendWarning("Could not read mergeNodes"); return; } readMergeNodes_ = true; } */ } if (!readGrundZellenHoehe_ || !readGrundZellenBreite_ // || !readMergeNodes_ ) { preOK_ = false; return; } // merge_ = true; }
int ComputeTrace::compute(const char *) { //input port object const coDistributedObject *obj = p_pointsIn->getCurrentObject(); if (!obj) { //no input, no output sendError("Did not receive object at port '%s'", p_pointsIn->getName()); return FAIL; } const coDoSet *IDset = dynamic_cast<const coDoSet *>(p_IDIn->getCurrentObject()); if (IDset) { delete IDs; IDs = new int *[IDset->getNumElements()]; for (int i = 0; i < IDset->getNumElements(); i++) { const coDoInt *IDObj = dynamic_cast<const coDoInt *>(IDset->getElement(i)); if (IDObj) { IDObj->getAddress(&IDs[i]); } else { delete IDs; IDs = NULL; break; } } } if (const coDoSet *set = dynamic_cast<const coDoSet *>(obj)) { if (set->getAttribute("TIMESTEP")) { // the TIMESTEP attribute arguments are not correct on many datasets, use 0 to numElems instead // the module fails if m_timestepStart>0 /*int ret = sscanf(set->getAttribute("TIMESTEP"),"%d %d", &m_timestepStart, &m_timestepStop); if(ret == 0) { sendError("couldn't successfully read TIMESTEP arguments"); return FAIL; }*/ m_timestepStart = 0; m_timestepStop = set->getNumElements() - 1; if (m_firsttime) { m_firsttime = false; p_start->setValue(m_timestepStart, m_timestepStop, m_timestepStart); p_stop->setValue(m_timestepStart, m_timestepStop, m_timestepStop); } else { p_start->setValue(p_start->getValue(), m_timestepStop, m_timestepStart); p_stop->setValue(p_stop->getValue(), m_timestepStop, m_timestepStop); } } /* Creating the output object. * The TIMESTEP attribute is set automatically since this class * is derived of the coSimpleModule class*/ if (p_traceOut->getObjName()) { std::string name; // test if input objects are of coDoSpheres* type if (dynamic_cast<const coDoSpheres *>(set->getElement(0))) { // creating a string that contains all names of // all coDoSpheres objects separated by newline escape sequence int numElem = set->getNumElements(); for (int i = 0; i < numElem; i++) { name += (set->getElement(i))->getName(); name += "\n"; } } //Compensating input errors caused by the user m_start = p_start->getValue(); m_stop = p_stop->getValue(); if (m_start < m_timestepStart) { sendWarning("start is smaller than the beginning of the timestep; start is set to min_timestep"); m_start = m_timestepStart; p_start->setValue(m_start); } if (m_stop > m_timestepStop) { sendWarning("stop is larger than the maximum of timesteps; stop is set to max_timestep"); m_stop = m_timestepStop; p_stop->setValue(m_stop); } // getting the selected particle string and // create the integer vector holding the element // indices with coRestraint m_particleIndices.clear(); //fprintf(stderr, "\np_particle->getValue: %s\n", p_particle->getValue() ); m_particleIndices.add(p_particle->getValue()); m_particleSelection = m_particleIndices.getValues(); // setting sorted, newly organized and formatted // string as particle string value std::string cleanedupString = m_particleIndices.getRestraintString(); p_particle->setValue(cleanedupString.c_str()); //Getting number of particles in the first timestep assuming that every //new timestep holds the same number of particles int no_of_points = 0; float min[3] = { FLT_MAX, FLT_MAX, FLT_MAX }; float max[3] = { -FLT_MAX, -FLT_MAX, -FLT_MAX }; if (const coDoCoordinates *coord = dynamic_cast<const coDoCoordinates *>(set->getElement(0))) { no_of_points = coord->getNumElements(); for (int i = 0; i < no_of_points; ++i) { float x, y, z; coord->getPointCoordinates(i, &x, &y, &z); if (x > max[0]) max[0] = x; if (y > max[1]) max[1] = y; if (z > max[2]) max[2] = z; if (x < min[0]) min[0] = x; if (y < min[1]) min[1] = y; if (z < min[2]) min[2] = z; } p_boundingBoxDimensions->setValue(max[0] - min[0], max[1] - min[1], max[2] - min[2]); } else if (dynamic_cast<const coDoTriangleStrips *>(set->getElement(0))) { sendError("Use Manual CPU Billboards instead of Polygons."); return FAIL; } else { sendError("wrong input type at input port. Type must be either Spheres or Points."); return FAIL; } //test if specified particles smaller than the maximum number of particles if (IDs == NULL) { if (!m_particleSelection.empty() && m_particleSelection.back() >= no_of_points) { stringstream range; range << "0-" << no_of_points - 1; sendWarning("The particle index you specified is out of range. Particles out of range will be removed. Valid range is %s", range.str().c_str()); while (!m_particleSelection.empty() && m_particleSelection.back() >= no_of_points) { m_particleSelection.pop_back(); } std::string modifiedString = m_particleIndices.getRestraintString(m_particleSelection); p_particle->setValue(modifiedString.c_str()); } if (m_particleSelection.size() > p_maxParticleNumber->getValue()) { while (m_particleSelection.size() > p_maxParticleNumber->getValue()) m_particleSelection.pop_back(); } } //structure that holds the output components coDistributedObject **traceLines = NULL; // depending on the selection string create the // traces or a NULL object that holds NULL-line elements // for every timestep bool empty = false; if (!p_traceParticle->getValue() || m_particleSelection.empty()) { traceLines = computeDynamicTrace(set, false); empty = true; fprintf(stderr, "empty: traceLines=%p\n", traceLines); } else if (p_animate->getValue()) { traceLines = computeDynamicTrace(set, true); } else { traceLines = new coDistributedObject *[1]; traceLines[0] = computeStaticTrace(std::string(p_traceOut->getObjName()), set); } // creating the output coDistributedObject *traces = (p_animate->getValue() || empty) ? new coDoSet(p_traceOut->getObjName(), traceLines) : traceLines[0]; delete[] traceLines; if (dynamic_cast<const coDoSpheres *>(set->getElement(0))) { // creating the feedback object needed for // openCOVER<->COVISE interaction coFeedback feedback("PickSphere"); feedback.addPara(p_start); feedback.addPara(p_stop); feedback.addPara(p_particle); feedback.addPara(p_traceParticle); feedback.addPara(p_regardInterrupt); // all coDoSphere object names are attached to the trace lines traces->addAttribute("PICKSPHERE", name.c_str()); // viewpoint animation parameters feedback.addPara(p_animateViewer); feedback.addPara(p_animLookAt); // attaching the feedback object to trace lines feedback.apply(traces); } // setting the output object p_traceOut->setCurrentObject(traces); } else { fprintf(stderr, "Covise::getObjName failed\n"); return FAIL; } if (p_indexOut->getObjName()) { coDistributedObject *indices = computeFloats(returnIndex, p_indexOut->getObjName()); p_indexOut->setCurrentObject(indices); } else { fprintf(stderr, "Covise::getObjName failed\n"); return FAIL; } if (p_fadingOut->getObjName()) { coDistributedObject *fading = computeFloats(fade, p_fadingOut->getObjName()); p_fadingOut->setCurrentObject(fading); } else { fprintf(stderr, "Covise::getObjName failed\n"); return FAIL; } if (p_dataOut->getObjName()) { if (const coDoSet *set = dynamic_cast<const coDoSet *>(p_dataIn->getCurrentObject())) p_dataOut->setCurrentObject(extractData(p_dataOut->getObjName(), set, p_animate->getValue())); else if (p_dataIn->getCurrentObject()) fprintf(stderr, "need a set of data"); } else { fprintf(stderr, "Covise::getObjName failed\n"); return FAIL; } } else { sendInfo("need a set object with time steps"); return FAIL; } return SUCCESS; }
bool UFuncPar::handleCommand(UServerInMsg * msg, void * extra) { const int MRL = 500; char reply[MRL]; // bool aLog, doLog, aDummy, aSilent = false; // bool aFake; // check for parameter 'help' if (msg->tag.getAttValue("help", NULL, 0)) { // create the reply in XML-like (html - like) format sendHelpStart("Par"); sendText("--- PAR is for roll and pitch calculations\n"); snprintf(reply, MRL, "log=true|false Opens or closes the logfile %s (open=%s)\n", logf.getLogFileName(), bool2str(logf.isOpen())); sendText(reply); sendText("eval evaluate parametric roll state\n"); sendText("update update parametric roll state with new sensor data\n"); //sendText("dummy update dummy data generator (output values for marg)\n"); sendText("fake=F fake some roll/pitch values F=roll frq\n"); sendText("sweep fake a frequenct sweep for the roll\n"); sendText("sweepStep fake a frequenct sweep step\n"); sendText("pitch=F with fake F=pitch frq\n"); sendText("silent do not make an info reply\n"); sendText("help This message\n"); sendHelpDone(); } else { // get any command attributes (when not a help request) bool doLog, aSilent, aSweep = false, aSweepStep = false, anEval = false; int aSweepSteps = 1; double rollFrq, pitchFrq=1.0/10.0; // 10Hz bool aLog = msg->tag.getAttBool("log", &doLog, true); bool aDummy = msg->tag.getAttBool("dummy", NULL); msg->tag.getAttBool("silent", &aSilent, true); bool aFake = msg->tag.getAttDouble("fake", &rollFrq, 1.0/20.0); msg->tag.getAttDouble("pitch", &pitchFrq, 1.0/10.0); msg->tag.getAttBool("sweep", &aSweep, true); aSweepStep = msg->tag.getAttInteger("sweepStep", &aSweepSteps, 1); msg->tag.getAttBool("eval", &anEval, true); bool anUpdate = msg->tag.getAttBool("update", NULL); // // implement command if (aLog) { // open or close the log aLog = logf.openLog(doLog); if (doLog) snprintf(reply, MRL, "Opened logfile %s (%s)", logf.getLogFileName(), bool2str(aLog)); else snprintf(reply, MRL, "closed logfile %s", logf.getLogFileName()); // send an information tag back to client sendInfo(reply); } else if (aDummy) { //dummy(); bool isOK = setGlobalVar("imu.aaa[1]", 33.0, true); printf("Set ima.aaa=33 %s\n", bool2str(isOK)); isOK = setGlobalVar("imu.bbb", 34.0, false); printf("Set ima.bbb=34 %s\n", bool2str(isOK)); isOK = getVarPool()->getGlobalVariable("imu.aaa")->setDouble(33.7, 1, true); printf("Set ima.aaa=33.7 %s\n", bool2str(isOK)); if (not aSilent) sendInfo("done"); } else if (aFake) { fakeImuValues(rollFrq, pitchFrq); // fake sweep } else if (aSweep) { double startFrq=0.001; //1.0; // oldest time double sampleRate=10.0; double endFrq = 0.3; // 0.0002; // newest time int samples=30000; UVariable * var = getVarPool()->getGlobalVariable("imu.rot"); fakeFrqSweep(var, 0.5, startFrq, endFrq, samples, sampleRate); // fake sweep } else if (anEval) { rollDetectBatch(); if (not aSilent) sendInfo("Done roll detect - not fully implemented yet"); } else if (anUpdate) { bool done = newImuData(); if (not aSilent) { if (done) sendInfo("updated sensor values"); else sendInfo("redundant info"); } } else if (not aSweepStep) sendWarning("No action see 'par help'"); if (aSweepStep) { UVariable * var = getVarPool()->getGlobalVariable("imu.rot"); double startFrq = 0.0003; // Hz double sampleRate = 3; // Hz double endFrq = sampleRate / 3.0; if (not setSweepMeasurement(var, -0.5, aSweepSteps, log(startFrq), log(endFrq), 20000, sampleRate)) { // last sample sweepStep = 0; sweepAngle = 0.0; } } } return true; }
/** Handle incomming command Must return true if the function is handled - otherwise the client will get a 'failed' reply */ virtual bool handleCommand(UServerInMsg * msg, void * extra) { // handle command(s) send to this plug-in // check for parameters - one parameter is tested for - 'help' // the help value is ignored, e.g. if help="bark", then // the value "bark" will be in the 'helpValue' string. bool ask4help; const int MVL = 50; char val[MVL]; int camDevice = -1; bool debug = true; // default is debug on bool result = true; ULaserData * data; ULaserDevice * lasDev; // pointer to laser device ask4help = msg->tag.getAttValue("help", val, MVL); if (not ask4help) { // get all other parameters msg->tag.getAttValueInt("device", &camDevice); //gotImg = msg->tag.getAttValueInt("img", &imgPoolNum); msg->tag.getAttValueBool("debug", &debug, true); //msg->tag.getAttValueBool("smrcl", &smrcl, true); //msg->tag.getAttValueBool("blue", &gotBlue, true); } // ask4help = false, if no 'help' option were available. if (ask4help) { // create the reply in XML-like (html - like) format printf("test3\n"); sendHelpStart("B2"); sendText("--- available B2 options\n"); sendText("device=X Use this camera - for position and parameters\n"); sendText("img=X Get image from image pool - else take new image\n"); sendText("blue Try find a blue ball (def is red)\n"); sendText("debug=false More images and print on server console (def=true)\n"); sendText("smrcl Format the reply for MRC (<vision vis1=\"x.x\" vis2=\"y.y\" .../>\n"); sendText("v2 use version 2 code (edge extraction)"); sendText("help This message\n"); sendHelpDone(); sendInfo("done"); result = true; } // Handle all other commands else { // Print out data if(msg->tag.getAttValue("dataprint", NULL, 0)) { ULaserDevice * lasDev; // laser device data = getScan(msg, (ULaserData*)extra, false, &lasDev); if (data->isValid()) { printf("MAX Scan: %d\n",data->getRangeCnt()); int i; for(i=0;i<data->getRangeCnt();i=i+1){ if(data->getRangeMeter(i)>=1) printf("ID: %d \t%f \t%f \n",i,data->getRangeMeter(i),data->getAngleDeg(i)); } } else { sendWarning(msg, "No scandata available"); } } // test stop condition else if(msg->tag.getAttValue("test", NULL, 0)) { ULaserDevice * lasDev; // laser device data = getScan(msg, (ULaserData*)extra, false, &lasDev); if (data->isValid()) { printf("MAX Scan: %d\n",data->getRangeCnt()); // loop that run for all messurements int i; for(i = 0; i < data->getRangeCnt(); i = i+1) { // Filter out the angles of interrest if((data->getAngleDeg(i) > -30) && (data->getAngleDeg(i) < 30)) { printf("ID: %d \t%f \t%f \n",i,data->getRangeMeter(i),data->getAngleDeg(i)); } } } } // MRC else if(msg->tag.getAttValue("mrc", NULL, 0)) { ULaserDevice * lasDev; // laser device data = getScan(msg, (ULaserData*)extra, false, &lasDev); int objectDetected = 0; if (data->isValid()) { // loop that run for all messurements int i; for(i = 0; i < data->getRangeCnt(); i = i+1) { // Filter out the angles of interrest if((data->getAngleDeg(i) >= -30) && (data->getAngleDeg(i) <= 30)) { // 0.25 stop if obstacel is closer than 0.25m // remove samples that are closer than 0.06m due to datasheet presision. // Remove samples that are out of index (0). if((data->getRangeMeter(i)<0.25) && (data->getRangeMeter(i) > 0.06)){ objectDetected = 1; //printf("ID: %d \t%f \t%f \n",i,data->getRangeMeter(i),data->getAngleDeg(i)); } } } if(objectDetected == 1){ sendText("Object in front of SMR!\n"); sendMsg("<laser l1=\"1\"/>\n"); } else{ sendMsg("<laser l1=\"0\"/>\n"); } } else{ sendWarning(msg, "No scandata available!"); } } else{ result = false; } } // end of handle all other commands return result; }
int ReadFamu::compute(const char * /*port*/) { if (reset->getValue()) { bottomLeft->setValue(origBottomLeft[0], origBottomLeft[1], origBottomLeft[2]); bottomRight->setValue(origBottomRight[0], origBottomRight[1], origBottomRight[2]); topRight->setValue(origTopRight[0], origTopRight[1], origTopRight[2]); topLeft->setValue(origTopLeft[0], origTopLeft[1], origTopLeft[2]); //reset params moveDist->setValue(0.0, 0.0, 0.0); scaleFactor->setValue(1.0); XYDegree->setValue(0.0); YZDegree->setValue(0.0); ZXDegree->setValue(0.0); reset->setValue(false); } const char *firstFile = _in_FirstFile->getValue(); const char *secondFile = _in_SecondFile->getValue(); if (FileExists(firstFile) && FileExists(secondFile) && _startSim->getValue()) { Plane myPlane; //move the plane float xDist = 0, yDist = 0, zDist = 0; xDist = moveDist->getValue(0); yDist = moveDist->getValue(1); zDist = moveDist->getValue(2); //scale the plane float scale = 1; scale = sqrt(scaleFactor->getValue()); float origCenter[3]; origCenter[0] = (bottomLeft->getValue(0) + topRight->getValue(0)) / 2; origCenter[1] = (bottomLeft->getValue(1) + topRight->getValue(1)) / 2; origCenter[2] = (bottomLeft->getValue(2) + topRight->getValue(2)) / 2; float xDiff = 0, yDiff = 0, zDiff = 0; if (scale != 1) { xDiff = (1 - scale) * origCenter[0]; yDiff = (1 - scale) * origCenter[1]; zDiff = (1 - scale) * origCenter[2]; } //initialize the reference points myPlane._referenceNode[0].x = bottomLeft->getValue(0) * scale + xDist + xDiff; myPlane._referenceNode[0].y = bottomLeft->getValue(1) * scale + yDist + yDiff; myPlane._referenceNode[0].z = bottomLeft->getValue(2) * scale + zDist + zDiff; myPlane._referenceNode[1].x = scale * (bottomLeft->getValue(0) + bottomRight->getValue(0)) / 2 + xDist + xDiff; myPlane._referenceNode[1].y = scale * (bottomLeft->getValue(1) + bottomRight->getValue(1)) / 2 + yDist + yDiff; myPlane._referenceNode[1].z = scale * (bottomLeft->getValue(2) + bottomRight->getValue(2)) / 2 + zDist + zDiff; myPlane._referenceNode[2].x = bottomRight->getValue(0) * scale + xDist + xDiff; myPlane._referenceNode[2].y = bottomRight->getValue(1) * scale + yDist + yDiff; myPlane._referenceNode[2].z = bottomRight->getValue(2) * scale + zDist + zDiff; myPlane._referenceNode[3].x = scale * (bottomRight->getValue(0) + topRight->getValue(0)) / 2 + xDist + xDiff; myPlane._referenceNode[3].y = scale * (bottomRight->getValue(1) + topRight->getValue(1)) / 2 + yDist + yDiff; myPlane._referenceNode[3].z = scale * (bottomRight->getValue(2) + topRight->getValue(2)) / 2 + zDist + zDiff; myPlane._referenceNode[4].x = topRight->getValue(0) * scale + xDist + xDiff; myPlane._referenceNode[4].y = topRight->getValue(1) * scale + yDist + yDiff; myPlane._referenceNode[4].z = topRight->getValue(2) * scale + zDist + zDiff; myPlane._referenceNode[5].x = scale * (topRight->getValue(0) + topLeft->getValue(0)) / 2 + xDist + xDiff; myPlane._referenceNode[5].y = scale * (topRight->getValue(1) + topLeft->getValue(1)) / 2 + yDist + yDiff; myPlane._referenceNode[5].z = scale * (topRight->getValue(2) + topLeft->getValue(2)) / 2 + zDist + zDiff; myPlane._referenceNode[6].x = topLeft->getValue(0) * scale + xDist + xDiff; myPlane._referenceNode[6].y = topLeft->getValue(1) * scale + yDist + yDiff; myPlane._referenceNode[6].z = topLeft->getValue(2) * scale + zDist + zDiff; myPlane._referenceNode[7].x = scale * (bottomLeft->getValue(0) + topLeft->getValue(0)) / 2 + xDist + xDiff; myPlane._referenceNode[7].y = scale * (bottomLeft->getValue(1) + topLeft->getValue(1)) / 2 + yDist + yDiff; myPlane._referenceNode[7].z = scale * (bottomLeft->getValue(2) + topLeft->getValue(2)) / 2 + zDist + zDiff; //rotate the electrode Node center1, center2, center3; float degree1 = 0, degree2 = 0, degree3 = 0; degree1 = XYDegree->getValue(); //rotate eletrode around the axis Z if (XYDegree->getValue() > 0) { degree1 = XYDegree->getValue(); center1.x = (myPlane._referenceNode[2].x + myPlane._referenceNode[0].x) / 2; center1.y = (myPlane._referenceNode[2].y + myPlane._referenceNode[0].y) / 2; center1.z = (myPlane._referenceNode[2].z + myPlane._referenceNode[0].z) / 2; rotatePoint(&(myPlane._referenceNode[0]), center1, degree1, 1); rotatePoint(&(myPlane._referenceNode[2]), center1, degree1, 1); rotatePoint(&(myPlane._referenceNode[3]), center1, degree1, 1); rotatePoint(&(myPlane._referenceNode[4]), center1, degree1, 1); rotatePoint(&(myPlane._referenceNode[5]), center1, degree1, 1); rotatePoint(&(myPlane._referenceNode[6]), center1, degree1, 1); rotatePoint(&(myPlane._referenceNode[7]), center1, degree1, 1); } //rotate eletrode around the axis X if (YZDegree->getValue() > 0) { degree2 = YZDegree->getValue(); center2.x = (myPlane._referenceNode[0].x + myPlane._referenceNode[4].x) / 2; center2.y = (myPlane._referenceNode[0].y + myPlane._referenceNode[4].y) / 2; center2.z = (myPlane._referenceNode[0].z + myPlane._referenceNode[4].z) / 2; rotatePoint(&(myPlane._referenceNode[0]), center2, degree2, 2); rotatePoint(&(myPlane._referenceNode[1]), center2, degree2, 2); rotatePoint(&(myPlane._referenceNode[2]), center2, degree2, 2); rotatePoint(&(myPlane._referenceNode[3]), center2, degree2, 2); rotatePoint(&(myPlane._referenceNode[4]), center2, degree2, 2); rotatePoint(&(myPlane._referenceNode[5]), center2, degree2, 2); rotatePoint(&(myPlane._referenceNode[6]), center2, degree2, 2); rotatePoint(&(myPlane._referenceNode[7]), center2, degree2, 2); } //rotate eletrode around the axis Y if (ZXDegree->getValue() > 0) { degree3 = ZXDegree->getValue(); center3.x = (myPlane._referenceNode[6].x + myPlane._referenceNode[0].x) / 2; center3.y = (myPlane._referenceNode[6].y + myPlane._referenceNode[0].y) / 2; center3.z = (myPlane._referenceNode[6].z + myPlane._referenceNode[0].z) / 2; rotatePoint(&(myPlane._referenceNode[0]), center3, degree3, 3); rotatePoint(&(myPlane._referenceNode[1]), center3, degree3, 3); rotatePoint(&(myPlane._referenceNode[2]), center3, degree3, 3); rotatePoint(&(myPlane._referenceNode[3]), center3, degree3, 3); rotatePoint(&(myPlane._referenceNode[4]), center3, degree3, 3); rotatePoint(&(myPlane._referenceNode[5]), center3, degree3, 3); rotatePoint(&(myPlane._referenceNode[6]), center3, degree3, 3); } //set the new values to the Param bottomLeft->setValue(myPlane._referenceNode[0].x, myPlane._referenceNode[0].y, myPlane._referenceNode[0].z); bottomRight->setValue(myPlane._referenceNode[2].x, myPlane._referenceNode[2].y, myPlane._referenceNode[2].z); topRight->setValue(myPlane._referenceNode[4].x, myPlane._referenceNode[4].y, myPlane._referenceNode[4].z); topLeft->setValue(myPlane._referenceNode[6].x, myPlane._referenceNode[6].y, myPlane._referenceNode[6].z); myPlane.controllPlaneCreating(); myPlane.targetPlaneCreating(); exportHmo(myPlane, _planeFile->getValue()); //exportHmascii(myPlane); //load and transform the block file float blockMoveVec3[3] = { moveIsol->getValue(0), moveIsol->getValue(1), moveIsol->getValue(2) }; float blockScaleVec3[3] = { scaleIsol->getValue(0), scaleIsol->getValue(1), scaleIsol->getValue(2) }; const char *thirdFile; thirdFile = _in_ThirdFile->getValue(); char tempFile[256]; if (FileExists(thirdFile) && _startSim->getValue()) { strncpy_s(tempFile, 256, thirdFile, strlen(thirdFile) - 10); strncat_s((char *)tempFile, 256, "tempBlock.hmo", 13); transformBlock(thirdFile, tempFile, blockMoveVec3, blockScaleVec3); } else { sendError("files %s and / or %s not existing, we do not execute simulation", firstFile, secondFile); return FAIL; } filesBinding(_in_FirstFile->getValue(), _in_SecondFile->getValue(), (const char *)tempFile, _targetFile->getValue()); char command[1024]; sprintf(command, "%s %s", _FamuExePath->getValue(), _FamuArgs->getValue()); if (system(command) == -1) sendError("execution of %s failed", command); moveDist->setValue(0.0, 0.0, 0.0); scaleFactor->setValue(1.0); XYDegree->setValue(0); YZDegree->setValue(0); ZXDegree->setValue(0); } else { if (_startSim->getValue()) { sendWarning("files %s and / or %s not existing, we do not execute simulation", firstFile, secondFile); } } try { // load mesh MeshDataTrans *meshDataTrans = NULL; getMeshDataTrans(&meshDataTrans); // get results and send them to output ports FactoryResultsFileParser *facParser = FactoryResultsFileParser::getInstance(); ResultsFileParser *resFileParser = facParser->create(_resultsFileName->getValue(), meshDataTrans, this); if (_startSim->getValue()) { std::string filename = _resultsFileName->getValue(); // filename = parserTools::replace(filename, ".", "_."); resFileParser->parseResultsFile(filename.c_str(), _p_skip->getValue(), _p_numt->getValue(), meshDataTrans, std::string(_dataPort[0]->getObjName())); } else { resFileParser->parseResultsFile(_resultsFileName->getValue(), _p_skip->getValue(), _p_numt->getValue(), meshDataTrans, std::string(_dataPort[0]->getObjName())); } // ------------------ ResultsFileData *resFileData = NULL; float symmAngle = _periodicAngle->getValue(); int noOfSymmTimeSteps = _periodicTimeSteps->getValue(); const bool isPeriodicRot = symmAngle != 0 && noOfSymmTimeSteps > 0; if (isPeriodicRot) { resFileData = new PeriodicRotResults(symmAngle, noOfSymmTimeSteps, resFileParser, this); } else { resFileData = resFileParser; } sendResultsToPorts(resFileData, meshDataTrans); // ------------------ // create grids of all time steps and send them to output ports BuilderGrid builderGrid(this); coDoSet *gridSet = builderGrid.construct(_mesh->getObjName(), _scaleDisplacements->getValue(), _periodicAngle->getValue(), (int)_periodicTimeSteps->getValue(), meshDataTrans, resFileParser); _mesh->setCurrentObject(gridSet); coFeedback feedback("Famu"); //feedback.addPara(moveDist); feedback.addPara(bottomLeft); //first Point Param.0 feedback.addPara(bottomRight); // second Point Param.1 feedback.addPara(topRight); //third Point Param.2 feedback.addPara(topLeft); //fourth Point Param.3 feedback.addPara(scaleFactor); //Param.4 feedback.addPara(XYDegree); //Param.5 feedback.addPara(YZDegree); //Param.6 feedback.addPara(ZXDegree); //Param.7 feedback.addPara(reset); //Param.8 feedback.addPara(moveIsol); //Param.9 feedback.addPara(scaleIsol); //Param.10 feedback.addString("important information"); feedback.apply(gridSet); delete meshDataTrans; delete resFileParser; //return SUCCESS; return CONTINUE_PIPELINE; } catch (ErrorInfo error) { error.outputError(); return FAIL; } catch (int error) { sendError("sorry, error %d occured.", error); return FAIL; } }
int MergeAndNormals::ProjectNormals(coDoPolygons *poly, coDoVec3 *norm) { // unpack coordinates, loop over them, and correct // normals for coordintes satisfying the gemetry condition //int no_poly = poly->getNumPolygons(); //int no_vert = poly->getNumVertices(); int no_point = poly->getNumPoints(); float *x_c; float *y_c; float *z_c; int *v_l; int *l_l; poly->getAddresses(&x_c, &y_c, &z_c, &v_l, &l_l); if (no_point != norm->getNumPoints()) { sendWarning("Number of points of the input normals does not match the number of points in polygons"); return -1; } coDistributedObject *polyList[2]; polyList[0] = poly; poly->incRefCount(); polyList[1] = NULL; coDoSet *polySet = new coDoSet(p_outGeom_->getObjName(), polyList); p_outGeom_->setCurrentObject(polySet); float *nx; float *ny; float *nz; norm->getAddresses(&nx, &ny, &nz); vector<float> nX, nY, nZ; int point; for (point = 0; point < no_point; ++point) { nX.push_back(nx[point]); nY.push_back(ny[point]); nZ.push_back(nz[point]); if (z_c[point] == 0.0) { nX[point] = 0.0; nY[point] = 0.0; nZ[point] = 1.0; continue; } float resX = 0.0, resY = 0.0; if (grundZellenBreite_ != 0.0) { #if defined(__APPLE__) || defined(__MINGW32__) resX = remainder(x_c[point], grundZellenBreite_); #else resX = drem(x_c[point], grundZellenBreite_); #endif } if (grundZellenHoehe_ != 0.0) { #if defined(__APPLE__) || defined(__MINGW32__) resY = remainder(y_c[point], grundZellenHoehe_); #else resY = drem(y_c[point], grundZellenHoehe_); #endif } if (fabs(resX) <= 1e-6) { // project onto YZ plane Project(nX[point], nY[point], nZ[point], 1.0, 0.0, 0.0); } if (fabs(resY) <= 1e-6) { // project onto ZX plane Project(nX[point], nY[point], nZ[point], 0.0, 1.0, 0.0); } } coDistributedObject *normList[2]; normList[1] = NULL; string name = p_Normals_->getObjName(); name += "_0"; { normList[0] = new coDoVec3(name.c_str(), nX.size()); float *x, *y, *z; ((coDoVec3 *)normList[0])->getAddresses(&x, &y, &z); copy(nX.begin(), nX.end(), x); copy(nY.begin(), nY.end(), y); copy(nZ.begin(), nZ.end(), z); } p_Normals_->setCurrentObject(new coDoSet(p_Normals_->getObjName(), normList)); delete normList[0]; return 0; }
int MergeAndNormals::compute(const char *port) { (void)port; // silence warning if (!preOK_) { sendWarning("preHandleObjects failed"); return FAIL; } const coDistributedObject *in_obj = p_inGeom_->getCurrentObject(); if (!in_obj->isType("LINES") && !in_obj->isType("POLYGN")) { sendWarning("Invalid input type"); return FAIL; } if (in_obj->isType("LINES")) { if (!p_inNormals_->isConnected()) { coDoLines *lines = (coDoLines *)(in_obj); // get dimensions int nPoints = lines->getNumPoints(); int nCorners = lines->getNumVertices(); int nLines = lines->getNumLines(); // create new arrays int *cl, *ll; ll = NULL; cl = NULL; float *coords[3]; int i; for (i = 0; i < 3; ++i) coords[i] = NULL; lines->getAddresses(&coords[0], &coords[1], &coords[2], &cl, &ll); // create new DO coDoLines *outObj = new coDoLines(p_outGeom_->getObjName(), nPoints, coords[0], coords[1], coords[2], nCorners, cl, nLines, ll); p_outGeom_->setCurrentObject(outObj); } else { coDoLines *outObj = new coDoLines(p_outGeom_->getObjName(), 0, 0, 0); p_outGeom_->setCurrentObject(outObj); } p_Normals_->setCurrentObject(new coDoVec3(p_Normals_->getObjName(), 0)); return SUCCESS; } coDoPolygons *preNormals = (coDoPolygons *)in_obj; // if we are using input normals... then everything // is much easier. if (p_inNormals_->isConnected()) { const coDistributedObject *in_normals = p_inNormals_->getCurrentObject(); if (!in_normals || !in_normals->isType("USTVDT")) { sendWarning("Incorrect type of input normals or NULL pointer"); return FAIL; } coDoVec3 *inNormals = (coDoVec3 *)in_normals; if (ProjectNormals(preNormals, inNormals) == 0) { return SUCCESS; } else { return FAIL; } } if (merge_) { // get arrays... int no_poly = preNormals->getNumPolygons(); int no_vert = preNormals->getNumVertices(); int no_point = preNormals->getNumPoints(); float *x_c; float *y_c; float *z_c; int *v_l; int *l_l; preNormals->getAddresses(&x_c, &y_c, &z_c, &v_l, &l_l); // make vectors out of them vector<float> xc, yc, zc; vector<int> vl, ll; int point; for (point = 0; point < no_point; ++point) { xc.push_back(x_c[point]); yc.push_back(y_c[point]); zc.push_back(z_c[point]); } int vert; for (vert = 0; vert < no_vert; ++vert) { vl.push_back(v_l[vert]); } int poly; for (poly = 0; poly < no_poly; ++poly) { ll.push_back(l_l[poly]); } // call MergeNodes if (mergeNodes_) { ReadASCIIDyna::MergeNodes(xc, yc, zc, vl, ll, 1e-6, grundZellenBreite_, grundZellenHoehe_); } // redefine forNormals... { float *x, *y, *z; int *v, *l; preNormals = new coDoPolygons(p_outGeom_->getObjName(), xc.size(), vl.size(), ll.size()); preNormals->getAddresses(&x, &y, &z, &v, &l); copy(xc.begin(), xc.end(), x); copy(yc.begin(), yc.end(), y); copy(zc.begin(), zc.end(), z); copy(vl.begin(), vl.end(), v); copy(ll.begin(), ll.end(), l); } } else { // make a copy for output of the geometry // get dimensions int nPoints = preNormals->getNumPoints(); int nCorners = preNormals->getNumVertices(); int nPolygons = preNormals->getNumPolygons(); // create new arrays int *cl, *pl; pl = NULL; cl = NULL; float *coords[3]; int i; for (i = 0; i < 3; ++i) coords[i] = NULL; preNormals->getAddresses(&coords[0], &coords[1], &coords[2], &cl, &pl); // create new DO preNormals = new coDoPolygons(p_outGeom_->getObjName(), nPoints, coords[0], coords[1], coords[2], nCorners, cl, nPolygons, pl); } p_outGeom_->setCurrentObject(preNormals); // normals for nodes satisfying z==0.0 // get arrays... //int no_poly = preNormals->getNumPolygons(); //int no_vert = preNormals->getNumVertices(); int no_point = preNormals->getNumPoints(); float *x_c; float *y_c; float *z_c; int *v_l; int *l_l; preNormals->getAddresses(&x_c, &y_c, &z_c, &v_l, &l_l); vector<float> nx, ny, nz; int point; for (point = 0; point < no_point; ++point) { nx.push_back(0.0); ny.push_back(0.0); if (z_c[point] == 0.0) { nz.push_back(1.0); } else { nz.push_back(0.0); } } { coDoVec3 *vobj = new coDoVec3( p_Normals_->getObjName(), nx.size()); float *x, *y, *z; vobj->getAddresses(&x, &y, &z); copy(nx.begin(), nx.end(), x); copy(ny.begin(), ny.end(), y); copy(nz.begin(), nz.end(), z); p_Normals_->setCurrentObject(vobj); } return SUCCESS; }
bool UFuncPoly::handleCommand(UServerInMsg * msg, void * extra) { const int MRL = 150000; char reply[MRL]; bool ask4help; const int MVL = 1000; char val[MVL]; bool replySend = false; bool gotOpenLog; bool gotOpenLogValue = false; bool gotVerbose; bool gotVerboseValue = false; bool gotAdd = false; bool gotDel = false; const int MNL = 100; char name[MNL] = ""; bool gotList = false; bool isOK; bool gotX, gotY; double x, y; bool gotGet = false; bool gotUpdate = false; UTime t; int c; // check for parameters - one parameter is tested for - 'help' // the help value is ignored, e.g. if help="bark", then // the value "bark" will be in the 'helpValue' string. ask4help = msg->tag.getAttValue("help", val, MVL); if (not ask4help) { // get all other parameters gotOpenLog = msg->tag.getAttValue("log", val, MVL); if (gotOpenLog) gotOpenLogValue = str2bool2(val, true); gotVerbose = msg->tag.getAttValue("verbose", val, MVL); if (gotVerbose) gotVerboseValue = str2bool2(val, true); gotAdd = msg->tag.getAttValue("add", name, MNL); gotDel = msg->tag.getAttValue("del", name, MNL); gotList = msg->tag.getAttValue("list", NULL, 0); gotX = msg->tag.getAttDouble("X", &x); gotY = msg->tag.getAttDouble("Y", &y); if (not gotX) gotX = msg->tag.getAttDouble("E", &x); if (not gotY) gotY = msg->tag.getAttDouble("N", &y); gotGet = msg->tag.getAttValue("get", val, MVL); gotUpdate = msg->tag.getAttValue("update", val, MVL); if (gotUpdate and strlen(val) > 0) gotUpdate = str2bool2(val, true); } // ask4help = false, i.e. no 'help' option. if (ask4help) { // create the reply in XML-like (html - like) format sendHelpStart("POLY"); sendText("--- available POLY options (mission poly lines and points)\n"); if (poly == NULL) { sendText("*** The needed POLY resource is not available ***\n"); sendText("help This message\n"); } else { // full functionality snprintf(reply, MRL, "list List all polygons (has %d)\n", poly->getPolysCnt()); sendText(reply); sendText("get Get all items in one xml message\n"); sendText("update Get all updated items only - first time you get all\n"); sendText("add=name Add a new (empty) item with this name\n"); sendText("add=name x=X y=Y Add one new point point to an item\n"); sendText("add=name E=X N=Y Add one new point point to an item\n"); sendText("add=name color=dddd Add color, up to 4 chars: 1=matlab color, 1=line width, 2=* vertex circle, 4=' ' no edge line\n"); sendText("del=name Delete item with this name (may hold wildcards (* and ?)\n"); sendText("verbose[=false] Posibly more messages to server console\n"); sendText("log[=false] Open [or close] logfile\n"); sendText("help This message\n"); sendText("--------\n"); } sendHelpDone(); replySend = true; } else if (poly == NULL) { sendWarning("no POLY resource to do that - try unload and reload plug-in"); replySend = true; } else { // resource is available, so make a reply if (gotVerbose) { poly->verbose = gotVerboseValue; sendInfo("done"); replySend = true; } if (gotOpenLog) { poly->openLog(gotOpenLogValue); sendInfo("done"); replySend = true; } if (gotList) { poly->getList("poly", reply, MRL); sendHelpStart("POLY list"); sendText(reply); replySend = sendHelpDone(msg); } if (gotAdd and strlen(name) > 0) { if ((gotX or gotY) and (strchr(name, '*') == NULL) and (strchr(name, '?') == NULL)) { isOK = poly->add(name, x, y); } if (msg->tag.getAttValue("color", val, MVL)) { int p1; // next polygon index number UPolyItem * pi = poly->getNext(0, &p1, name); while (pi != NULL) { // fill in new color codes for (int i = 0; i < mini(5, strlen(val)); i++) pi->color[i] = val[i]; isOK = true; if (p1 < 0) break; // get next polygon to color pi = poly->getNext(p1, &p1, name); } } if (isOK) replySend = sendInfo("added OK"); else replySend = sendWarning("failed - no more space?"); poly->gotNewData(); } if (gotDel) { poly->del(name); replySend = sendInfo("deleted (or did not exist)"); poly->gotNewData(); } if (gotGet or gotUpdate) { c = msg->client + 20; if (gotUpdate and c >= 0) // get index to last update timestamp t = updateTimes[c]; else // else all updated since start of time (1970) t.clear(); updateTimes[c].now(); for (int u = 0; u < poly->getPolysCnt(); u++) { if (poly->codePolyXml(msg->tag.getTagName(), reply, MRL, t, u)) replySend = sendMsg(reply); } } } if (not replySend) sendInfo(msg, "no poly action performed (no command option?)"); // return true if the function is handled with a positive result return true; }
IMT_MRGui::IMT_MRGui(QWidget *parent) : QMainWindow(parent), ui(new Ui::IMT_MRGui) { // Initialize the first GPU GPU0_.allocateGPU(0); GPU0_.printInformation(std::cout); size_t free; size_t total; cuMemGetInfo(&free, &total); std::cout << "free memory: " << free / 1024 / 1024 << "mb, total memory: " << total / 1024 / 1024 << "mb" << std::endl; ui->setupUi(this); read_siemens = 0; fftobj_ = new agile::FFT<TType>(); kspacefovobj_ = new agile::KSpaceFOV<TType>(); open_irgnpara_window = new IRGN_para(); // Be sure to destroy you window somewhere open_irgnpara_window->hide(); _pathsetting = new PathSetting(); // Be sure to destroy you window somewhere _pathsetting->hide(); _specialsetting = new SpecialSetting(); // Be sure to destroy you window somewhere _specialsetting->hide(); setStatusBar(); setTitleText(""); future = new QFuture<void>; watcher = new QFutureWatcher<void>; _cycleread_thread = new CycleRead; _cycleread_thread->set_max_acq_time(_specialsetting->get_autoload_timeout()); _infotext=""; QObject::connect(this,SIGNAL(sendInfo(QString, bool)),this,SLOT(set_Info(QString, bool))); QObject::connect(this,SIGNAL(sendWarning(QString)),this,SLOT(set_Warning(QString))); QObject::connect(this,SIGNAL(sendSaveFile(QString,QString)),this,SLOT(set_SaveFile(QString,QString)),Qt::BlockingQueuedConnection); QObject::connect(_cycleread_thread, SIGNAL(send_filenames(QStringList, QStringList)), this, SLOT(startauto(QStringList, QStringList))); _act_index = 0; _automatic_on = false; _write_file_index=0; ui->cb_savingtype->setCurrentIndex(2); ui->pb_automatic->setText("Auto Off"); _postprocess = new agile::PostProcess<TType, TType_real>(); QLabel* imageLabel = new QLabel(this); imageLabel->setBackgroundRole(QPalette::Base); imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); imageLabel->setScaledContents(true); QImage image(":/images/wappen.png"); imageLabel->setPixmap(QPixmap::fromImage(image)); imageLabel->resize(imageLabel->pixmap()->size()); imageLabel->setGeometry((this->width() - imageLabel->sizeHint().width()), 40, imageLabel->sizeHint().width(), imageLabel->sizeHint().height()); imageLabel->show(); }
int Patran::compute(const char *) { coDoUnstructuredGrid *mesh; coDistributedObject **time_outputgrid; StepFile *displ = NULL, *nsh = NULL, *elem = NULL; char *next_path = NULL; char buf[512]; int i; float *x, *y, *z, *s; //read parameters grid_path = p_gridpath->getValue(); displ_path = p_displpath->getValue(); nsh_path = p_nshpath->getValue(); elem_path = p_elempath->getValue(); int timesteps = p_timesteps->getValue(); int skip_value = p_skip->getValue(); int nb_col = p_columns->getValue(); int has_neutral_file = 0, has_displ_file = 0, has_nsh_file = 0, has_elem_file = 0; has_timesteps = 0; if (timesteps <= 0) { sendError("ERROR: The value of the timesteps should be >= 1!"); return STOP_PIPELINE; } // // extracts the number of existing displ, nsh and elem files and then set the number of timesteps // if (strcmp(displ_path, init_path) && strcmp(displ_path, " ") && timesteps > 1) { int nb_disp = 0; displ = new StepFile(this, displ_path); displ->set_skip_value(skip_value); displ->get_nextpath(&next_path); while (next_path != NULL) { delete[] next_path; nb_disp++; displ->get_nextpath(&next_path); } delete displ; if (timesteps > 1 && nb_disp > 1) has_timesteps = 1; if (timesteps > nb_disp) if (nb_disp > 0) timesteps = nb_disp; //else timesteps = 1; } int stress = p_option->getValue(); if (stress == 0) { if (strcmp(nsh_path, init_path) && strcmp(nsh_path, " ") && timesteps > 1) { int nb_nsh = 0; nsh = new StepFile(this, nsh_path); nsh->set_skip_value(skip_value); nsh->get_nextpath(&next_path); while (next_path != NULL) { delete[] next_path; nb_nsh++; nsh->get_nextpath(&next_path); } delete nsh; if (timesteps > 1 && nb_nsh > 1) has_timesteps = 1; if (timesteps > nb_nsh) if (nb_nsh > 0) timesteps = nb_nsh; //else timesteps = 1; } } else if (strcmp(elem_path, init_path) && strcmp(elem_path, " ") && timesteps > 1) { int nb_elem = 0; elem = new StepFile(this, elem_path); elem->set_skip_value(skip_value); elem->get_nextpath(&next_path); while (next_path != NULL) { delete[] next_path; nb_elem++; elem->get_nextpath(&next_path); } delete elem; if (timesteps > 1 && nb_elem > 1) has_timesteps = 1; if (timesteps > nb_elem) if (nb_elem > 0) timesteps = nb_elem; //else timesteps = 1; } if (!has_timesteps) { next_path = new char[100]; } // // grid file // if (gridFile) delete gridFile; sendInfo("Reading grid file: %s ...", grid_path); gridFile = new NeutralFile(grid_path); if ((!gridFile) || (!gridFile->isValid())) { sendError("Could not read %s as PATRAN Neutral File", grid_path); if (gridFile) delete gridFile; gridFile = NULL; return STOP_PIPELINE; } else has_neutral_file = 1; sendInfo("Successfully read the file '%s': %i nodes, %i elements, %i components.", grid_path, gridFile->num_nodes, gridFile->num_elements, gridFile->num_components); gridFile->eval_num_connections(); if (timesteps > 1 && has_timesteps) sprintf(buf, "%s_0", p_outPort1->getObjName()); else sprintf(buf, "%s", p_outPort1->getObjName()); mesh = new coDoUnstructuredGrid(buf, gridFile->num_elements, gridFile->num_connections, gridFile->num_nodes, 1); if (!mesh->objectOk()) { sendError("ERROR: Failed to create the object '%s' for the port '%s'", p_outPort1->getObjName(), p_outPort1->getName()); return STOP_PIPELINE; } int *clPtr, *tlPtr, *elPtr; float *xPtr, *yPtr, *zPtr; mesh->getAddresses(&elPtr, &clPtr, &xPtr, &yPtr, &zPtr); mesh->getTypeList(&tlPtr); // // ID´s // int *id; int size[2]; size[0] = gridFile->num_elements; size[1] = 3; coDoIntArr *type = new coDoIntArr(p_outPort4->getObjName(), 2, size); if (!type->objectOk()) { sendError("ERROR: Failed to create the object '%s' for the port '%s'", p_outPort4->getObjName(), p_outPort4->getName()); return STOP_PIPELINE; } type->getAddress(&id); int *type_array = type->getAddress(); gridFile->getMesh(elPtr, clPtr, tlPtr, xPtr, yPtr, zPtr, type_array); if (has_neutral_file) { if (timesteps > 1 && has_timesteps) { time_outputgrid = new coDistributedObject *[timesteps + 1]; time_outputgrid[timesteps] = NULL; time_outputgrid[0] = mesh; for (i = 1; i < timesteps; i++) { time_outputgrid[i] = mesh; mesh->incRefCount(); } time_outputgrid[i] = NULL; coDoSet *outputgrid = new coDoSet(p_outPort1->getObjName(), time_outputgrid); sprintf(buf, "1 %d", timesteps); outputgrid->addAttribute("TIMESTEP", buf); p_outPort1->setCurrentObject(outputgrid); } else p_outPort1->setCurrentObject(mesh); } // // vector data, displacement // coDistributedObject **time_outputdata; coDoVec3 *displ_data = NULL; if (strcmp(displ_path, init_path) && strcmp(displ_path, " ")) { time_outputdata = new coDistributedObject *[timesteps + 1]; if (has_timesteps) { displ = new StepFile(this, displ_path); displ->set_skip_value(skip_value); } for (i = 0; i < timesteps; i++) { if (has_timesteps) displ->get_nextpath(&next_path); else strcpy(next_path, displ_path); if (next_path) { FILE *fd = fopen(next_path, "r"); if (fd) { bool isAsciiFile = true; char firstChars[80]; if (fread(&firstChars, 1, 80, fd) != 80) { fprintf(stderr, "ReadPatran::compute: fread failed\n"); } fclose(fd); int number; for (number = 0; number < 80; number++) { isAsciiFile = isAsciiFile && (firstChars[number] > 7) && (firstChars[number] < 127); } sendInfo("Reading nodal displacement file: %s ...", next_path); if (isAsciiFile) { nodal_displFile = new NodalFile(next_path, NASCII); } else { nodal_displFile = new NodalFile(next_path, NBINARY); } if ((!nodal_displFile) || (!nodal_displFile->isValid())) { sendError("Could not read %s as PATRAN Displacements File", next_path); if (nodal_displFile) delete nodal_displFile; nodal_displFile = NULL; //return STOP_PIPELINE; } else { has_displ_file = 1; sendInfo("Successfully read the file '%s': %i data nodes, %i data columns.", next_path, nodal_displFile->nnodes, nodal_displFile->header.nwidth); if (timesteps > 1 && has_timesteps) sprintf(buf, "%s_%d", p_outPort2->getObjName(), i); else sprintf(buf, "%s", p_outPort2->getObjName()); displ_data = new coDoVec3(buf, gridFile->num_nodes); if (!displ_data->objectOk()) { sendError("ERROR: Failed to create the object '%s' for the port '%s'", buf, p_outPort2->getName()); return STOP_PIPELINE; } displ_data->getAddresses(&x, &y, &z); if (nodal_displFile->getDataField(NDISPLACEMENTS, gridFile->nodeMap, x, y, z, gridFile->num_nodes - nodal_displFile->nnodes, gridFile->getMaxnode()) < 0) sendError("ERROR: Cannot read Nodal Displacements for Port Data%s", p_outPort2->getName()); time_outputdata[i] = displ_data; delete nodal_displFile; } } else { sendWarning("Could not read %s as PATRAN Displacements File", next_path); if (nodal_displFile) delete nodal_displFile; nodal_displFile = NULL; i = timesteps; //get out of the loop } if (has_timesteps) delete[] next_path; } } time_outputdata[i] = NULL; if (has_displ_file) { if (timesteps > 1 && has_timesteps) { coDoSet *outputdata = new coDoSet(p_outPort2->getObjName(), time_outputdata); sprintf(buf, "1 %d", timesteps); outputdata->addAttribute("TIMESTEP", buf); p_outPort2->setCurrentObject(outputdata); } else p_outPort2->setCurrentObject(displ_data); } if (has_timesteps) delete displ; //setobj later } // // scalar nsh data // if (strcmp(nsh_path, init_path) && strcmp(nsh_path, " ") && stress == 0) { coDistributedObject **time_scalardata = new coDistributedObject *[timesteps + 1]; if (has_timesteps) { nsh = new StepFile(this, nsh_path); nsh->set_skip_value(skip_value); } coDoFloat *nsh_data = NULL; for (i = 0; i < timesteps; i++) { if (has_timesteps) nsh->get_nextpath(&next_path); else strcpy(next_path, nsh_path); if (next_path) { FILE *fd = fopen(next_path, "r"); if (fd) { bool isAsciiFile = true; char firstChars[180]; if (fread(&firstChars, 1, 80, fd) != 80) { fprintf(stderr, "fread failed\n"); } fclose(fd); int number; for (number = 0; number < 80; number++) { isAsciiFile = isAsciiFile && ((firstChars[number] > 7) && ((firstChars[number] < 127))); } if (isAsciiFile) { nodal_stressFile = new NodalFile(next_path, NASCII); } else { nodal_stressFile = new NodalFile(next_path, NBINARY); } //binary file sendInfo("Reading nodal stress file: %s ...", next_path); if ((!nodal_stressFile) || (!nodal_stressFile->isValid())) { sendError("Could not read %s as PATRAN nodal results File", next_path); if (nodal_stressFile) delete nodal_stressFile; nodal_stressFile = NULL; //return STOP_PIPELINE; } else { has_nsh_file = 1; sendInfo("Successfully read the file '%s': %i nodes", next_path, nodal_stressFile->nnodes); if (timesteps > 1 && has_timesteps) sprintf(buf, "%s_%d", p_outPort3->getObjName(), i); else sprintf(buf, "%s", p_outPort3->getObjName()); nsh_data = new coDoFloat(buf, gridFile->num_nodes); if (!nsh_data->objectOk()) { sendError("ERROR: Failed to create the object '%s' for the port '%s'", buf, p_outPort3->getName()); return STOP_PIPELINE; } nsh_data->getAddress(&s); if (nodal_stressFile->getDataField(NNODALSTRESS, gridFile->nodeMap, nb_col, s, gridFile->num_nodes - nodal_stressFile->nnodes, gridFile->getMaxnode()) < 0) sendError("ERROR: Cannot read Nodal Result for Port Data %s", p_outPort3->getName()); time_scalardata[i] = nsh_data; delete nodal_stressFile; } } else { sendWarning("Could not read %s as PATRAN nodal results File", next_path); if (nodal_stressFile) delete nodal_stressFile; nodal_stressFile = NULL; i = timesteps; //get out of the loop } if (has_timesteps) delete[] next_path; } } time_scalardata[i] = NULL; if (has_nsh_file) { if (timesteps > 1 && has_timesteps) { coDoSet *scalardata = new coDoSet(p_outPort3->getObjName(), time_scalardata); sprintf(buf, "1 %d", timesteps); scalardata->addAttribute("TIMESTEP", buf); p_outPort3->setCurrentObject(scalardata); } else p_outPort3->setCurrentObject(nsh_data); } if (has_timesteps) delete nsh; } // // scalar element results data // if (strcmp(elem_path, init_path) && strcmp(elem_path, " ") && stress == 1) { coDistributedObject **time_elementdata = new coDistributedObject *[timesteps + 1]; if (has_timesteps) { elem = new StepFile(this, elem_path); elem->set_skip_value(skip_value); } else strcpy(next_path, elem_path); coDoFloat *elem_data = NULL; for (i = 0; i < timesteps; i++) { if (has_timesteps) elem->get_nextpath(&next_path); else strcpy(next_path, elem_path); if (next_path) { FILE *fd = fopen(next_path, "r"); if (fd) { bool isAsciiFile = true; char firstChars[80]; if (fread(&firstChars, 1, 80, fd) != 80) { fprintf(stderr, "ReadPatran::compute: fread failed\n"); } fclose(fd); int number; for (number = 0; number < 80; number++) { isAsciiFile = isAsciiFile && (firstChars[number] > 7) && (firstChars[number] < 127); } if (isAsciiFile) { //ASCII file sendInfo("Reading element result file: %s ...", next_path); elemAscFile = new ElementAscFile(next_path, nb_col); if ((!elemAscFile) || (!elemAscFile->isValid())) { sendError("Could not read %s as PATRAN Element Result File", next_path); if (elemAscFile) delete elemAscFile; elemAscFile = NULL; } else { has_elem_file = 1; sendInfo("Successfully read the file '%s': %i nodes and width %i.", next_path, elemAscFile->nnodes, elemAscFile->nwidth); if (timesteps > 1 && has_timesteps) sprintf(buf, "%s_%d", p_outPort3->getObjName(), i); else sprintf(buf, "%s", p_outPort3->getObjName()); elem_data = new coDoFloat(buf, gridFile->num_elements); if (!elem_data->objectOk()) { sendError("ERROR: Failed to create the object '%s' for the port '%s'", buf, p_outPort3->getName()); return STOP_PIPELINE; } elem_data->getAddress(&s); // 3 = ELEMENTSTRESS if (elemAscFile->getDataField(3, gridFile->elemMap, nb_col, s, gridFile->num_elements - elemAscFile->nnodes, gridFile->getMaxelem()) < 0) sendError("ERROR: Cannot read Nodal result for Port Data %s", p_outPort3->getName()); time_elementdata[i] = elem_data; delete elemAscFile; } } else { // binary sendInfo("Reading element result file: %s ...", next_path); elemFile = new ElementFile(::open(next_path, O_RDONLY)); if ((!elemFile) || (!elemFile->isValid())) { sendError("Could not read %s as PATRAN element result File", next_path); if (elemFile) delete elemFile; elemFile = NULL; return STOP_PIPELINE; } else { has_elem_file = 1; sendInfo("Successfully read the file '%s': %i lines.", next_path, elemFile->numlines); if (timesteps > 1 && has_timesteps) sprintf(buf, "%s_%d", p_outPort3->getObjName(), i); else sprintf(buf, "%s", p_outPort3->getObjName()); elem_data = new coDoFloat(buf, gridFile->num_elements); if (!elem_data->objectOk()) { sendError("ERROR: Failed to create the object '%s' for the port '%s'", buf, p_outPort3->getName()); return STOP_PIPELINE; } elem_data->getAddress(&s); if (elemFile->getDataField(3, gridFile->elemMap, nb_col, s, gridFile->num_elements - elemFile->numlines, gridFile->getMaxelem()) < 0) sendError("ERROR: Cannot read Element Results for Port Data %s", p_outPort3->getName()); time_elementdata[i] = elem_data; delete elemFile; // delete [] next_path; } } } else { sendError("Could not read %s as PATRAN Element Result File", next_path); if (elemAscFile) delete elemAscFile; elemAscFile = NULL; i = timesteps; //get out of the loop } if (has_timesteps) delete[] next_path; } } time_elementdata[i] = NULL; if (has_elem_file) { if (timesteps > 1 && has_timesteps) { coDoSet *elementdata = new coDoSet(p_outPort3->getObjName(), time_elementdata); sprintf(buf, "1 %d", timesteps); elementdata->addAttribute("TIMESTEP", buf); p_outPort3->setCurrentObject(elem_data); } else p_outPort3->setCurrentObject(elem_data); } // delete [] time_elementdata; if (has_timesteps) delete elem; } if (!has_timesteps) delete[] next_path; return SUCCESS; }
bool UFunctionDisp::handleCommand(UServerInMsg * msg, void * extra) { // handle disp command char att[MAX_SML_NAME_LENGTH]; char att2[MAX_SML_NAME_LENGTH] = ""; const int VBL = 500; char val[VBL]; const int MRL = 600; char reply[MRL]; bool ask4help = false; bool result = false; bool replyOK = false; bool aLoad = false; const int MFL = 300; char aLoadName[MFL]; int theImgNum = 0; double v; UNavPaint * np; bool aPaint = false; // bool aCapture = false; // int aCaptureValue = 0; // if (disp == NULL) sendError(msg, "No display resource!!"); else { np = disp->getNavPaint(); while (msg->tag.getNextAttribute(att, val, VBL)) { // camera device if (strcasecmp(att, "help") == 0) ask4help = true; else if (strcasecmp(att, "load") == 0) { aLoad = true; strncpy(aLoadName, val, MFL); } else if (strcasecmp(att, "img") == 0) theImgNum = strtol(val, NULL, 0); else if (strcasecmp(att, "uvimg") == 0) { disp->setUVSource(strtol(val, NULL, 0)); aPaint = true; } else if (strcasecmp(att, "croma") == 0) { disp->setCROMASource(strtol(val, NULL, 0)); aPaint = true; } else if (strcasecmp(att, "intensMin") == 0) { disp->setIntensMin(strtol(val, NULL, 0)); aPaint = true; } else if (strcasecmp(att, "intensMax") == 0) { disp->setIntensMax(strtol(val, NULL, 0)); aPaint = true; } /* else if (strcasecmp(att, "testcap") == 0) { aCapture = true; if (strlen(val) > 0) aCaptureValue = strtol(val, NULL, 0); }*/ else if (disp != NULL) { aPaint = true; if (strcasecmp(att, "scale") == 0) disp->setScale(strtod(val, NULL)); // np->maxRange = maxd(1.0, strtod(val, NULL)); else if (strcasecmp(att, "pos") == 0) disp->setRobotPose(val); // np->robotPos = strtod(val, NULL); else if (strcasecmp(att, "bold") == 0) disp->paintBold(str2bool2(val, true)); else if (strcasecmp(att, "curves") == 0) np->paintCurves = str2bool2(val, true); else if (strcasecmp(att, "cam") == 0) np->paintCam = str2bool2(val, true); else if (strcasecmp(att, "gmk") == 0) np->paintGmk = str2bool2(val, true); else if (strcasecmp(att, "hereNow") == 0) np->setRefSystemsHere(); else if (strcasecmp(att, "autoHereNow") == 0) disp->setAutoHereNow(str2bool2(val, true)); else if (strcasecmp(att, "gridSys") == 0) np->paintPoseRef = strtol(val, NULL, 0); else if (strcasecmp(att, "grid") == 0) { v = strtod(val, NULL); np->paintGridOdo = (v > 0); if (v > 0) np->paintGridSize = v; } else if (strcasecmp(att, "rangeRings") == 0) disp->setRangeRingCnt(strtol(val, NULL, 10)); else if (strcasecmp(att, "pass") == 0) np->paintIntervalLines = str2bool2(val, true); else if (strcasecmp(att, "robot") == 0) disp->setRobot(val); else if (strcasecmp(att, "obst") == 0) np->paintObstCnt = strtol(val, NULL, 0); else if (strcasecmp(att, "poseHist") == 0) { np->paintPoseHistCnt = strtol(val, NULL, 0); } else if (strcasecmp(att, "poseHistVecCnt") == 0) np->paintPoseHistVecCnt = strtol(val, NULL, 0); else if (strcasecmp(att, "poseHistVecLng") == 0) np->paintPoseHistVecLng = strtol(val, NULL, 0); else if (strcasecmp(att, "path") == 0) np->paintPathLinesCnt = strtol(val, NULL, 0); else if (strcasecmp(att, "pathMid") == 0) np->paintPathMidPoses = str2bool2(val, true); else if (strcasecmp(att, "road") == 0) np->paintRoadHistCnt = strtol(val, NULL, 0); else if (strcasecmp(att, "roadAll") == 0) np->paintRoadAll = str2bool2(val, true); else if (strcasecmp(att, "scan") == 0) np->paintScanHistCnt = strtol(val, NULL, 0); else if (strcasecmp(att, "visPoly") == 0) np->paintVisPolyCnt = strtol(val, NULL, 0); else if (strcasecmp(att, "var") == 0) np->paintVar = str2bool2(val, true); else if (strcasecmp(att, "varAdd") == 0) { if (np->paintVarAdd(val, true)) np->paintVar = true; else strncpy(att2, att, MAX_SML_NAME_LENGTH); } else if (strcasecmp(att, "varDel") == 0) { if (not np->paintVarAdd(val, false)) strncpy(att2, att, MAX_SML_NAME_LENGTH); } else if (strcasecmp(att, "poly") == 0) np->paintPoly = str2bool2(val, true); else if (strcasecmp(att, "polyNameCnt") == 0) np->paintPolyNameCnt = strtol(val, NULL, 10); else if (strcasecmp(att, "polyHide") == 0) strncpy(np->paintPolyHide, val, np->maxStrLng); else if (strcasecmp(att, "polyShow") == 0) strncpy(np->paintPolyShow, val, np->maxStrLng); else if (strcasecmp(att, "odoPose") == 0) np->paintOdoPose = strtol(val, NULL, 0); else if (strcasecmp(att, "utmPose") == 0) np->paintUtmPose = strtol(val, NULL, 0); else if (strcasecmp(att, "mapPose") == 0) np->paintMapPose = strtol(val, NULL, 0); else if (strcasecmp(att, "do") == 0) disp->setNewDataNav(); else // not found - make a copy for reply strncpy(att2, att, MAX_SML_NAME_LENGTH); } } if (ask4help) { sendMsg(msg, "<help subject=\"disp\">\n"); sendText(msg, "----------- available disp options\n"); sendText(msg, "load=filename Load this image to imagepool image img=N (default N=0)"); sendText(msg, "img=N Use this image buffer number\n"); sendText(msg, "------ Image colour analysis options ----------\n"); sendText(msg, "uvimg=N Do UV analysis for this image number\n"); sendText(msg, "croma=N Do cromaticity analysis on this image number\n"); sendText(msg, "intensMin Minimum intensity to display colour\n"); sendText(msg, "intensMax Maximum intensity to display colour\n"); sendText(msg, "------ top-view (laser) image options ----------\n"); sendText(msg, "do update display\n"); snprintf(reply, MRL, "scale=height Scale image for image height in meter (is %gm)\n", np->maxRange); sendText(msg, reply); snprintf(reply, MRL, "pos=X[,Y] Place robot relative to bottom-center of image (is %gx, %gy)\n", np->robotPose.x, np->robotPose.y); sendText(msg, reply); sendText(msg, "bold[=false] Paint navigation image using bold lines (for presentations)\n"); snprintf(reply, MRL, "curves[=false] Paint laser line-fit variance curves (is %s)\n", bool2str(np->paintCurves)); sendText(msg, reply); snprintf(reply, MRL, "gridSys=0 | 1 | 2 Paint grid based on 0=odometry, 1=UTM, 2=Map coordinates (is %d)\n", np->paintPoseRef); sendText(msg, reply); snprintf(reply, MRL, "odoPose[=false] Show odometry pose at bottom of display (is %s)\n", bool2str(np->paintOdoPose)); sendText(msg, reply); snprintf(reply, MRL, "utmPose[=false] Show UTM (GPS) pose at bottom of display (is %s)\n", bool2str(np->paintUtmPose)); sendText(msg, reply); snprintf(reply, MRL, "mapPose[=false] Show map pose at bottom of display (is %s)\n", bool2str(np->paintMapPose)); sendText(msg, reply); sendText(msg, "hereNow Synchronoze all coordinate systems to here now\n"); snprintf(reply, MRL, "grid[=M] Paint coordinate grid every M meter (is %gm)\n", np->paintGridSize); sendText(msg, reply); snprintf(reply, MRL, "rangeRings[=M] Paint M range rings around laser scanner (is %dm)\n", np->rangeRingCnt); sendText(msg, reply); snprintf(reply, MRL, "pass[=false] Paint passable lines from laser scanner (is %s)\n", bool2str(np->paintIntervalLines)); sendText(msg, reply); snprintf(reply, MRL, "poly[=false] Paint poly items - planned mission lines etc. (is %s)\n", bool2str(np->paintPoly)); sendText(msg, reply); snprintf(reply, MRL, "polyNameCnt=N Paint polygon name, max N characters (last), N=%d\n", np->paintPolyNameCnt); sendText(msg, reply); snprintf(reply, MRL, "polyHide=\"name\" Hide selected poly items - accept wildchards (is '%s')\n", np->paintPolyHide); sendText(msg, reply); snprintf(reply, MRL, "polyShow=\"name\" Show among hidden poly items - accept wildchards (is '%s')\n", np->paintPolyShow); sendText(msg, reply); sendText(msg, "robot=[smr|mmr|hako|iRobot|guidebot] Paint robot outline as SMR, MMR...\n"); snprintf(reply, MRL, "obst=N Paint N obstacle groups (is %d)\n", np->paintObstCnt); sendText(msg, reply); snprintf(reply, MRL, "poseHist=N Paint N pose history positions for robot (is %d)\n", np->paintPoseHistCnt); sendText(msg, reply); snprintf(reply, MRL, "poseHistVecCnt=N Paint every N pose hist cnt a heading vector (is %d)\n", np->paintPoseHistVecCnt); sendText(msg, reply); snprintf(reply, MRL, "poseHistVecLng=N Paint pose hist heading vector N pixels long (is %d)\n", np->paintPoseHistVecLng); sendText(msg, reply); snprintf(reply, MRL, "path=[0 | 1 | N] Paint navigation path plan 0=no, 1=best, N=all (is %d)\n", np->paintPathLinesCnt); sendText(msg, reply); snprintf(reply, MRL, "pathMid[=false] Paint mid-poses used in path calculation (requires path > 0) is %s\n", bool2str(np->paintPathMidPoses)); sendText(msg, reply); snprintf(reply, MRL, "road[=N] Paint Road lines (if n > 0) and N road line updates (is %d)\n", np->paintRoadHistCnt); sendText(msg, reply); snprintf(reply, MRL, "roadAll Paint all available road lines (not just current best road) (is %s)\n", bool2str(np->paintRoadAll)); sendText(msg, reply); snprintf(reply, MRL, "scan=N Paint laserscan and history - up to N scans (is %d)\n", np->paintScanHistCnt); sendText(msg, reply); sendText(msg, "var[=false] Paint variables in struct list\n"); sendText(msg, "varAdd=struct Paint all variables in this struct\n"); sendText(msg, "varDel=struct Hide all variables in this struct\n"); snprintf(reply, MRL, "visPoly=N Paint N polygons from vision road detection (is %d)\n", np->paintVisPolyCnt); sendText(msg, reply); // sendText(msg, "testcap openCV test capture function\n"); sendText(msg, "help This help tekst\n"); sendText(msg, "--------\n"); sendText(msg, "See also POOLGET for image save or POOLLIST for available images\n"); sendMsg(msg, "</help>\n"); sendInfo(msg, "done"); } else if (disp != NULL) { if (aLoad) { result = disp->loadImgToPool(aLoadName, theImgNum); sendInfo(msg, "loaded"); replyOK = true; } if (strlen(att2) > 0) { snprintf(reply, MRL, "Unknown attribute %s", att2); sendWarning(msg, reply); replyOK = true; } else if (aPaint) { // an OK paint setting sendInfo(msg, "done"); replyOK = true; disp->setNewDataNav(); disp->setUvRedisplay(true); } /* else if (aCapture) { // an OK paint setting disp->capture(aCaptureValue); sendWarning(msg, "did a capture hmmm? may work"); replyOK = true; }*/ if (not replyOK) { snprintf(reply, MRL, "Unknown subject %s - try 'disp help'\n", msg->tag.getTagStart()); sendWarning(msg, reply); } } else sendWarning(msg, "No camera interface resource"); } return result; }