Get length scale factor of STEP CAD file with OpenCASCADE - scaling

I am trying to get the length unit conversion factor in OpenCASCADE, when importing a STEP format CAD file. In my test file the entity #184 sets the length to meters and during import will be converted to milimeters used by OpenCASCADE internally by default
...
#184=(
LENGTH_UNIT()
NAMED_UNIT(*)
SI_UNIT($,.METRE.)
);
...
I belive the function below is how it should be done, but no matter what i try the "Length_Unit" STEP entity is not matched, and therefore I can't get the scaling factor.
void step_unit_scaling(std::string const &file_name) {
STEPControl_Reader reader;
reader.ReadFile( file_name.c_str() );
const Handle(Interface_InterfaceModel) Model = reader.Model();
Handle(StepData_StepModel) aSM = Handle(StepData_StepModel)::DownCast(Model);
Standard_Integer NbEntities = Model->NbEntities();
for (int i=1; i<=NbEntities; i++) {
Handle(Standard_Transient) enti = aSM->Entity(i);
if (enti->IsKind (STANDARD_TYPE(StepBasic_LengthMeasureWithUnit))) {
Handle(StepBasic_LengthMeasureWithUnit) MWU = Handle(StepBasic_LengthMeasureWithUnit)::DownCast(enti);
Standard_Real scal_mm = MWU->ValueComponent();
std::cout << " --- !!! MATCH !!! --- scal_mm = " << scal_mm << std::endl;
}
}
}
Does anyone know if this is the correct approach, or if there perhaps is a better way.

If you search for an entity of a given type, you should check the types to find an error. The following line will show the actual entity type.
std::cout << "Entity type " << enti->DynamicType()->Name() << std::endl;
When I play with STEP files here, I see that your STEP line leads to an entity of type StepBasic_SiUnitAndLengthUnit. With this code I can test for some expected SI units:
if (enti->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit)))
{
Handle(StepBasic_SiUnitAndLengthUnit) unit =
Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(enti);
if (unit->HasPrefix() &&
(StepBasic_SiUnitName::StepBasic_sunMetre == unit->Name()) &&
(StepBasic_SiPrefix::StepBasic_spMilli == unit->Prefix()))
{
std::cout << "SI Unit is millimetre." << std::endl;
}
else if (!unit->HasPrefix() &&
(StepBasic_SiUnitName::StepBasic_sunMetre == unit->Name()))
{
std::cout << "SI Unit is metre." << std::endl;
}
else
{
std::cout << "I did not understand that unit..." << std::endl;
}
}

Related

Why does QSettings not store anything?

I want to use QSettings to save my window's dimensions so I came up with these two functions to save & load the settings:
void MainWindow::loadSettings()
{
settings = new QSettings("Nothing","KTerminal");
int MainWidth = settings->value("MainWidth").toInt();
int MainHeight = settings->value("MainHeight").toInt();
std::cout << "loadSettings " << MainWidth << "x" << MainHeight << std::endl;
std::cout << "file: " << settings->fileName().toLatin1().data() << std::endl;
if (MainWidth && MainHeight)
this->resize(MainWidth,MainHeight);
else
this->resize(1300, 840);
}
void MainWindow::saveSettings()
{
int MainHeight = this->size().height();
int MainWidth = this->size().width();
std::cout << "file: " << settings->fileName().toLatin1().data() << std::endl;
std::cout << "saveSettings " << MainWidth << "x" << MainHeight << std::endl;
settings->setValue("MainHeight",MainHeight);
settings->setValue("MainWidth",MainWidth);
}
Now, I can see the demensions being extracted in saveSettings as expected but no file gets created and hence loadSettings will always load 0 only. Why is this?
QSettings isn't normally instantiated on the heap. To achieve the desired effect that you are looking for, follow the Application Example and how it is shown in the QSettings documentation.
void MainWindow::readSettings()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray();
if (geometry.isEmpty()) {
const QRect availableGeometry = QApplication::desktop()->availableGeometry(this);
resize(availableGeometry.width() / 3, availableGeometry.height() / 2);
move((availableGeometry.width() - width()) / 2,
(availableGeometry.height() - height()) / 2);
} else {
restoreGeometry(geometry);
}
}
void MainWindow::writeSettings()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
settings.setValue("geometry", saveGeometry());
}
Also note the use of saveGeometry() and restoreGeometry(). Other similarly useful functions for QWidget based GUIs are saveState() and restoreState() (not shown in the above example).
I strongly recommend the zero parameter constructor of QSettings, and to setup the defaults in your main.cpp, like so:
QSettings::setDefaultFormat(QSettings::IniFormat); // personal preference
qApp->setOrganizationName("Moose Soft");
qApp->setApplicationName("Facturo-Pro");
Then when you want to use QSettings in any part of your application, you simply do:
QSettings settings;
settings.setValue("Category/name", value);
// or
QString name_str = settings.value("Category/name", default_value).toString();
QSettings in general is highly optimized, and works really well.
Hope that helps.
Some other places where I've talked up usage of QSettings:
Using QSettings in a global static class
https://stackoverflow.com/a/14365937/999943

QMediaPlayer : media stays in UnknownMediaStatus

I created a QMediaPlayer, passed video address to it and it won't play. I checked the mediaStatus and player state, they all stays 0 all the time. The basic idea is:
QMediaPlayer player = new QMediaPlayer();
cout << player.mediaStatus(); // should print 1: NoMedia but is 0: UnknownMediaStatus
player.setVideoOutput(some_constructed_video_widget);
cout << player.mediaStatus(); // should print 1: NoMedia but is 0: UnknownMediaStatus
player.setMedia(QUrl::fromLocalFile("path/to/test/video/test.mp4"));
cout << player.mediaStatus(); // should print 2: LoadingMedia but is 0: UnknownMediaStatus
player.play();
cout << player.mediaStatus(); // should print 3: LoadedMedia but is 0: UnknownMediaStatus
// and of course, no video gets played
The mediaStatus is simply a enum: MediaStatus { UnknownMediaStatus, NoMedia, LoadingMedia, LoadedMedia, ..., InvalidMedia }
The questions are:
What may be causing this problem and how to fix that?
What are all the cases that a QMediaPlayer::mediaStatus() will return an QMediaPlayer::UnknownMediaStatus (please be conclusive)?
Edit with more information: The following is the output I get for the following code. Anyone has any idea what the error message means and how to fix that?
code:
int main(int argc, char *argv[])
{
QMediaPlayer * temp = new QMediaPlayer(0, QMediaPlayer::VideoSurface);
std::cout << "Constructed: " << temp->mediaStatus() << std::endl;
temp->setMedia(QUrl::fromLocalFile("path/to/video/test.mp4"));
std::cout << "SetMedia: " << temp->mediaStatus() << std::endl;
temp->play();
std::cout << "Play: " << temp->mediaStatus() << std::endl;
-> debug breakpoint here
......
}
output:
defaultServiceProvider::requestService(): no service found for - "org.qt-project.qt.mediaplayer"
Constructed: 0
SetMedia: 0
Play: 0
I am using Mac 10.9 and Qt 5.3.0, but I do not think the mac/qt version matters for this problem.

Twig foreach group by date

I have a table with football matches called 'matches'. In that table there is a field 'kickoff', which is a datetime-column of the time when the match starts. With the following code I get all the matches out of the table.
$matches = $em->createQueryBuilder()
->select('m')
->from('FootballWcBundle:Matches', 'm')
->addOrderBy('m.kickoff', 'ASC')
->getQuery()
->getResult();
return $this->render('FootballWcBundle:Page:matches.html.twig', array(
'matches' => $matches
));
Now I want to show the matches on the screen grouped by the date.
Like this:
12-12-2014
match1
match2
14-12-2014
match3
match4
match5
Is there a way to let Twig know to group by the kickoff column or is there another way to do this?
You could do that as below:
{% set date = null %}
{% for match in matches %}
{% if date != match.kickoff %}
{% set date = match.kickoff %}
<h3>{{ date }}</h3>
{% endif %}
<p>{{ match.name }}</p>
{% endfor %}
In this way, you set the first date as null, and you iterate all matches and write a 'p' tag with the name (I supposed the match had a name to do the example), and when the date of the matches changes, you write a 'h3' tag with the date of the match. As date is set to null in the first iteration, the first date will be write.
There is a controlled break algorithm that originated from COBOL. It can be used in your case, you would have to rewrite it in TWIG though. I successfully used it in JAVA.
Below is C/C++ implementation of the controlled break algorithm. Take a look and use this principle for your case.
#include <iostream>
#define LMARG " "
#define UNDERLN "=============="
using namespace std;
void displayTable(int table[],short size);
//
// Purpose: Illustrated a controlled break algorithm
// Given an ordered sequence of data members, display with summary
//
int main(void)
{
int table[] = {10,12,12,30,30,30,30,40,55,60,60,60};
displayTable(table,sizeof(table)/sizeof(int));
fflush(stdin);
getchar();
return 0;
}
void displayTable(int table[],short size)
{
int currentKey,lastKey;
int i, categoryCount,groupTotal;
currentKey = lastKey = table[0];
groupTotal = categoryCount = i = 0;
while (i < size)
{
if (currentKey == lastKey)
{
groupTotal += table[i];
categoryCount++;
cout << LMARG << table[i] << endl;
}
else
{
cout << LMARG << UNDERLN << endl;
cout << "Total: " << groupTotal << endl;
cout << "Croup Count: " << categoryCount << endl << endl;
cout << LMARG << table[i] << endl; // start of next group
groupTotal = currentKey,categoryCount = 1;
fflush(stdin);getchar();
}
lastKey = currentKey;
currentKey = table[++i]; // get next key
} // while
cout << LMARG << UNDERLN << endl; // last group summary
cout << "Total: " << groupTotal << endl;
cout << "Croup Count: " << categoryCount << endl << endl;
}

Find a specific element within a vector

I have a class team that contains information for football teams. I need to read in a file and add each unique team to a vector season.
//Loop to determine unique teams
if(season.size() <= 1)
{
season.push_back(new_team);
cout << "First team added!" << endl;
}
vector<team>::iterator point;
point = find(season.begin(), season.end(), new_team);
bool unique_team = (point != season.end());
if(unique_team == true && season.size()>1)
{
season.push_back(new_team);
cout << "New team added!" << endl;
}
cout << "# of Teams: " << season.size() << endl;
system("pause");
Any ideas why this doesn't work? I'm still new to this :-) So feel free to give constructive criticism.
I think your logic may be a little off. There first team should be added when the size of the teams vector is 0. Say your team is a vector of integers an insertTeam function would look something like this.
void Season::insertTeam(int team)
{
if (teams.size() == 0)
{
teams.push_back(team);
cout << "First team " << team << " added!" << endl;
}
else
{
vector<int>::iterator point;
point = find(teams.begin(), teams.end(), team);
bool unique_team = (point == teams.end());
if(unique_team == true && teams.size()>0)
{
teams.push_back(team);
cout << "New team " << team << " added!" << endl;
}
}
}

QXmlQuery and XSLT20: Resultant Output String is empty everytime, works well on shell(xmlpattern)

I am writing a class to parse Itunes Libray File using QXmlQuery and QT-XSLT.
Here's my sample code:
ItunesLibParser::ItunesLibParser()
{
pathToLib = QString("/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml");
}
void ItunesLibParser::createXSLFile(QFile &inFile)
{
if (inFile.exists()) {
inFile.remove();
}
inFile.open(QIODevice::WriteOnly);
QTextStream out(&inFile);
out << QString("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
out << QString("<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">");
out << QString("<xsl:output method=\"text\" />");
out << QString("<xsl:template name=\"playlistNames\">");
out << QString("<xsl:value-of select=\"child::integer[preceding-sibling::key[1]='Playlist ID']\"/>");
out << QString("<xsl:text>
</xsl:text>");
out << QString("<xsl:value-of select=\"child::string[preceding-sibling::key[1]='Name']\"/>");
out << QString("<xsl:text>
</xsl:text>");
out << QString("</xsl:template>");
out << QString("<xsl:template match=\"/\">");
out << QString("<xsl:for-each select=\"plist/dict/array/dict\">");
out << QString("<xsl:call-template name=\"playlistNames\"/>");
out << QString("</xsl:for-each>");
out << QString("</xsl:template>");
out << QString("</xsl:stylesheet>");
inFile.close();
return;
}
void ItunesLibParser::dumpPlayList()
{
QXmlQuery query(QXmlQuery::XSLT20);
query.setFocus(QUrl(pathToLib));
QFile xslFile("plist.xsl");
createXSLFile(xslFile);
query.setQuery(QUrl("plist.xsl"));
QStringList* outDump = new QStringList();
query.evaluateTo(outDump);
if(outDump != NULL) {
QStringList::iterator iter = (*outDump).begin();
for (; iter != (*outDump).end();
++iter)
//code flow doesn't come here. It means being() == end()
std::cout << (*iter).toLocal8Bit().constData() << std::endl;
}
return;
}
OutDump here doesn't contain data. While in Shell (xmlpatterns-4.7 mystlye.xsl itunes_music_library.xml ), If I run my Query I get proper output.
Is there anything, wrong I am doing while calling it programatically? I checked out plist.xsl is created properly, but my doubt is whether "/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml" this is getting loaded or not? Or there might be another reasons, I am confused. Is there any experts to throw some light onto problem, I will be glad.
Intead from reading from the file, I read the file into buffer and converted that int string as passed to setquery. That solved the problem.
Here's sample code for those who could face similar problem in future.
void ITunesMlibParser::parsePlayListItemXml(int plistId)
{
QXmlQuery xQuery(QXmlQuery::XSLT20);
QFile inFile("/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml");
if (!inFile.open(QIODevice::ReadOnly)) {
return;
}
QByteArray bArray;
while (!inFile.atEnd()) {
bArray += inFile.readLine();
}
QBuffer xOriginalContent(&bArray);
xOriginalContent.open(QBuffer::ReadWrite);
xOriginalContent.reset();
if (xQuery.setFocus(&xOriginalContent))
std::cout << "File Loaded" << std::endl;
//..
//..
}
Thanks
Rakesh

Resources