Exemplo n.º 1
0
void Button::clicked (const ModifierKeys& modifiers)
{
  getModel().clicked (modifiers);
}
Exemplo n.º 2
0
KeyMap KeyMap::fromName(const QString &name){
    QStringList list = name.trimmed().split(" ");
    if(list.length() != 2)
        return KeyMap();
    return standard(getModel(list[0]), getLayout(list[1]));
}
Exemplo n.º 3
0
DeviceItem *
PlatformUdisks::getNewDevice(QString devicePath)
{
    QString path, model, vendor;

    DeviceItem *devItem = new DeviceItem;
    path = getPath(devicePath);
    if (path == "")
        return(NULL);

    if (!getIsDrive(devicePath))
        return(NULL);

    model = getModel(devicePath);
    vendor = getVendor(devicePath);

    devItem->setUDI(devicePath);
    devItem->setPath(path);
    devItem->setIsRemovable(getIsRemovable(devicePath));
    devItem->setSize(getSize(devicePath));
    devItem->setModelString(model);
    if (vendor == "")
    {
        if (mKioskMode)
            devItem->setVendorString("SUSE Studio USB Key");
        else
            devItem->setVendorString("Unknown Device");
    }
    else
    {
        devItem->setVendorString(vendor);
    }
    QString newDisplayString = QString("%1 %2 - %3 (%4 MB)")
                                      .arg(devItem->getVendorString())
                                      .arg(devItem->getModelString())
                                      .arg(devItem->getPath())
                                      .arg(devItem->getSize() / 1048576);
    devItem->setDisplayString(newDisplayString);

    if (mKioskMode)
    {
        if((devItem->getSize() / 1048576) > 200000)
        {
            delete devItem;
            return(NULL);
        }
    }

    // If a device is 0 megs we might as well just not list it
    if ((devItem->getSize() / 1048576) > 0)
    {
        itemList << devItem;
    }
    else
    {
        delete devItem;
        devItem = NULL;
    }

    return(devItem);
}
Exemplo n.º 4
0
/*virtual*/
r3dMesh*
obj_Grenade::GetObjectLodMesh()
{
	r3d_assert(m_Ammo);
	return getModel();
}
// Run several threads and ensure they modify the state consistantly
//   ncheck - # of checkThreadFunc threads to run
//   nset   - # of setThreadFunc threads to run
//   nmod   - # of modifyThreadFunc threads to run
static void runThreads(int ncheck, int nset, int nmod)
{
  MyInfo info;

  moveit::core::RobotModelPtr model = getModel();
  robot_interaction::LockedRobotState ls1(model);

  int num = ncheck + nset + nmod;

  typedef int *int_ptr;
  typedef boost::thread * thread_ptr;
  int *cnt = new int[num];
  int_ptr *counters = new int_ptr[num+1];
  thread_ptr *threads = new thread_ptr[num];

  int p = 0;
  double val = 0.1;

  // These threads check the validity of the RobotState
  for (int i = 0 ; i < ncheck ; ++i)
  {
    cnt[p] = 0;
    counters[p] = &cnt[p];
    threads[p] = new boost::thread(&MyInfo::checkThreadFunc,
                                   &info,
                                   &ls1,
                                   &cnt[p]);
    val += 0.1;
    p++;
  }

  // These threads set the RobotState to new values
  for (int i = 0 ; i < nset ; ++i)
  {
    cnt[p] = 0;
    counters[p] = &cnt[p];
    threads[p] = new boost::thread(&MyInfo::setThreadFunc,
                                   &info,
                                   &ls1,
                                   &cnt[p],
                                   val);
    val += 0.1;
    p++;
  }

  // These threads modify the RobotState in place
  for (int i = 0 ; i < nmod ; ++i)
  {
    cnt[p] = 0;
    counters[p] = &cnt[p];
    threads[p] = new boost::thread(&MyInfo::modifyThreadFunc,
                                   &info,
                                   &ls1,
                                   &cnt[p],
                                   val);
    val += 0.1;
    p++;
  }

  ASSERT_EQ(p, num);
  counters[p] = NULL;

  // this thread waits for all the other threads to make progress, then stops
  // everything.
  boost::thread wthread(&MyInfo::waitThreadFunc,
                   &info,
                   &ls1,
                   counters,
                   1000);

  // wait for all threads to finish
  for (int i = 0 ; i < p ; ++i)
  {
    threads[i]->join();
    wthread.join();
  }

  // clean up
  for (int i = 0 ; i < p ; ++i)
  {
    delete threads[i];
  }
  delete[] cnt;
  delete[] counters;
  delete[] threads;
}
Exemplo n.º 6
0
void CFakeSensor::declareDevice(boost::shared_ptr<yApi::IYPluginApi> api) const
{
   // Declare device and associated keywords (= values managed by this device)
   if (!api->deviceExists(m_deviceName))
      api->declareDevice(m_deviceName, getModel(), m_historizers);
}
Exemplo n.º 7
0
SelectionViewModel::SelectableElement* SelectionView::getSelectedElement() {
    return getModel()->getSelectableElements().at(positionOfSelectedElement);
}
Exemplo n.º 8
0
// NOTE: this only renders the "meta" portion of the Model, namely it renders debugging items, and it handles
// the per frame simulation/update that might be required if the models properties changed.
void RenderableModelEntityItem::render(RenderArgs* args) {
    PerformanceTimer perfTimer("RMEIrender");
    assert(getType() == EntityTypes::Model);

    if (hasModel()) {
        if (_model) {
            if (getModelURL() != _model->getURL().toString()) {
                qDebug() << "Updating model URL: " << getModelURL();
                _model->setURL(getModelURL());
            }

            render::ScenePointer scene = AbstractViewStateInterface::instance()->getMain3DScene();

            // check to see if when we added our models to the scene they were ready, if they were not ready, then
            // fix them up in the scene
            if (_model->needsFixupInScene()) {
                render::PendingChanges pendingChanges;

                _model->removeFromScene(scene, pendingChanges);

                render::Item::Status::Getters statusGetters;
                makeEntityItemStatusGetters(this, statusGetters);
                _model->addToScene(scene, pendingChanges, statusGetters);

                scene->enqueuePendingChanges(pendingChanges);
            }

            // FIXME: this seems like it could be optimized if we tracked our last known visible state in
            //        the renderable item. As it stands now the model checks it's visible/invisible state
            //        so most of the time we don't do anything in this function.
            _model->setVisibleInScene(getVisible(), scene);
        }


        remapTextures();
        {
            // float alpha = getLocalRenderAlpha();

            if (!_model || _needsModelReload) {
                // TODO: this getModel() appears to be about 3% of model render time. We should optimize
                PerformanceTimer perfTimer("getModel");
                EntityTreeRenderer* renderer = static_cast<EntityTreeRenderer*>(args->_renderer);
                getModel(renderer);
            }
            
            if (_model) {
                // handle animations..
                if (hasAnimation()) {
                    if (!jointsMapped()) {
                        QStringList modelJointNames = _model->getJointNames();
                        mapJoints(modelJointNames);
                    }

                    if (jointsMapped()) {
                        bool newFrame;
                        QVector<glm::quat> frameDataRotations;
                        QVector<glm::vec3> frameDataTranslations;
                        getAnimationFrame(newFrame, frameDataRotations, frameDataTranslations);
                        assert(frameDataRotations.size() == frameDataTranslations.size());
                        if (newFrame) {
                            for (int i = 0; i < frameDataRotations.size(); i++) {
                                _model->setJointState(i, true, frameDataRotations[i], frameDataTranslations[i], 1.0f);
                            }
                        }
                    }
                }

                bool movingOrAnimating = isMoving() || isAnimatingSomething();
                if ((movingOrAnimating || _needsInitialSimulation) && _model->isActive() && _dimensionsInitialized) {
                    _model->setScaleToFit(true, getDimensions());
                    _model->setSnapModelToRegistrationPoint(true, getRegistrationPoint());
                    _model->setRotation(getRotation());
                    _model->setTranslation(getPosition());
                    
                    // make sure to simulate so everything gets set up correctly for rendering
                    {
                        PerformanceTimer perfTimer("_model->simulate");
                        _model->simulate(0.0f);
                    }
                    
                    _needsInitialSimulation = false;
                }
            }
        }
    } else {
        glm::vec4 greenColor(0.0f, 1.0f, 0.0f, 1.0f);
        RenderableDebugableEntityItem::renderBoundingBox(this, args, 0.0f, greenColor);
    }

    RenderableDebugableEntityItem::render(this, args);
}
// NOTE: this only renders the "meta" portion of the Model, namely it renders debugging items, and it handles
// the per frame simulation/update that might be required if the models properties changed.
void RenderableModelEntityItem::render(RenderArgs* args) {
    PerformanceTimer perfTimer("RMEIrender");
    assert(getType() == EntityTypes::Model);

    if (hasModel()) {
        // Prepare the current frame
        {
            if (!_model || _needsModelReload) {
                // TODO: this getModel() appears to be about 3% of model render time. We should optimize
                PerformanceTimer perfTimer("getModel");
                EntityTreeRenderer* renderer = static_cast<EntityTreeRenderer*>(args->_renderer);
                getModel(renderer);

                // Remap textures immediately after loading to avoid flicker
                remapTextures();
            }

            if (_model) {
                if (hasRenderAnimation()) {
                    if (!jointsMapped()) {
                        QStringList modelJointNames = _model->getJointNames();
                        mapJoints(modelJointNames);
                    }
                }

                _jointDataLock.withWriteLock([&] {
                    getAnimationFrame();

                    // relay any inbound joint changes from scripts/animation/network to the model/rig
                    for (int index = 0; index < _absoluteJointRotationsInObjectFrame.size(); index++) {
                        if (_absoluteJointRotationsInObjectFrameDirty[index]) {
                            glm::quat rotation = _absoluteJointRotationsInObjectFrame[index];
                            _model->setJointRotation(index, true, rotation, 1.0f);
                            _absoluteJointRotationsInObjectFrameDirty[index] = false;
                        }
                    }
                    for (int index = 0; index < _absoluteJointTranslationsInObjectFrame.size(); index++) {
                        if (_absoluteJointTranslationsInObjectFrameDirty[index]) {
                            glm::vec3 translation = _absoluteJointTranslationsInObjectFrame[index];
                            _model->setJointTranslation(index, true, translation, 1.0f);
                            _absoluteJointTranslationsInObjectFrameDirty[index] = false;
                        }
                    }
                });
                updateModelBounds();
            }
        }

        // Enqueue updates for the next frame
        if (_model) {

            render::ScenePointer scene = AbstractViewStateInterface::instance()->getMain3DScene();

            // FIXME: this seems like it could be optimized if we tracked our last known visible state in
            //        the renderable item. As it stands now the model checks it's visible/invisible state
            //        so most of the time we don't do anything in this function.
            _model->setVisibleInScene(getVisible(), scene);

            // Remap textures for the next frame to avoid flicker
            remapTextures();

            // check to see if when we added our models to the scene they were ready, if they were not ready, then
            // fix them up in the scene
            bool shouldShowCollisionHull = (args->_debugFlags & (int)RenderArgs::RENDER_DEBUG_HULLS) > 0;
            if (_model->needsFixupInScene() || _showCollisionHull != shouldShowCollisionHull) {
                _showCollisionHull = shouldShowCollisionHull;
                render::PendingChanges pendingChanges;

                _model->removeFromScene(scene, pendingChanges);

                render::Item::Status::Getters statusGetters;
                makeEntityItemStatusGetters(getThisPointer(), statusGetters);
                _model->addToScene(scene, pendingChanges, statusGetters, _showCollisionHull);

                scene->enqueuePendingChanges(pendingChanges);
            }

            auto& currentURL = getParsedModelURL();
            if (currentURL != _model->getURL()) {
                // Defer setting the url to the render thread
                getModel(_myRenderer);
            }
        }
    } else {
        static glm::vec4 greenColor(0.0f, 1.0f, 0.0f, 1.0f);
        gpu::Batch& batch = *args->_batch;
        bool success;
        auto shapeTransform = getTransformToCenter(success);
        if (success) {
            batch.setModelTransform(shapeTransform); // we want to include the scale as well
            DependencyManager::get<GeometryCache>()->renderWireCubeInstance(batch, greenColor);
        }
    }
}
Exemplo n.º 10
0
void LLInventoryPanel::modelChanged(U32 mask)
{
	LLFastTimer t2(LLFastTimer::FTM_REFRESH);

	bool handled = false;
	if(mask & LLInventoryObserver::LABEL)
	{
		handled = true;
		// label change - empty out the display name for each object
		// in this change set.
		const std::set<LLUUID>& changed_items = gInventory.getChangedIDs();
		std::set<LLUUID>::const_iterator id_it = changed_items.begin();
		std::set<LLUUID>::const_iterator id_end = changed_items.end();
		LLFolderViewItem* view = NULL;
		LLInvFVBridge* bridge = NULL;
		for (;id_it != id_end; ++id_it)
		{
			view = mFolders->getItemByID(*id_it);
			if(view)
			{
				// request refresh on this item (also flags for filtering)
				bridge = (LLInvFVBridge*)view->getListener();
				if(bridge)
				{	// Clear the display name first, so it gets properly re-built during refresh()
					bridge->clearDisplayName();
				}
				view->refresh();
			}
		}
	}
	if((mask & (LLInventoryObserver::STRUCTURE
				| LLInventoryObserver::ADD
				| LLInventoryObserver::REMOVE)) != 0)
	{
		handled = true;
		// Record which folders are open by uuid.
		LLInventoryModel* model = getModel();
		if (model)
		{
			const std::set<LLUUID>& changed_items = gInventory.getChangedIDs();

			std::set<LLUUID>::const_iterator id_it = changed_items.begin();
			std::set<LLUUID>::const_iterator id_end = changed_items.end();
			for (;id_it != id_end; ++id_it)
			{
				// sync view with model
				LLInventoryObject* model_item = model->getObject(*id_it);
				LLFolderViewItem* view_item = mFolders->getItemByID(*id_it);

				if (model_item)
				{
					if (!view_item)
					{
						// this object was just created, need to build a view for it
						if ((mask & LLInventoryObserver::ADD) != LLInventoryObserver::ADD)
						{
							llwarns << *id_it << " is in model but not in view, but ADD flag not set" << llendl;
						}
						buildNewViews(*id_it);
						
						// select any newly created object
						// that has the auto rename at top of folder
						// root set
						if(mFolders->getRoot()->needsAutoRename())
						{
							setSelection(*id_it, FALSE);
						}
					}
					else
					{
						// this object was probably moved, check its parent
						if ((mask & LLInventoryObserver::STRUCTURE) != LLInventoryObserver::STRUCTURE)
						{
							llwarns << *id_it << " is in model and in view, but STRUCTURE flag not set" << llendl;
						}

						LLFolderViewFolder* new_parent = (LLFolderViewFolder*)mFolders->getItemByID(model_item->getParentUUID());
						if (view_item->getParentFolder() != new_parent)
						{
							view_item->getParentFolder()->extractItem(view_item);
							view_item->addToFolder(new_parent, mFolders);
						}
					}
				}
				else
				{
					if (view_item)
					{
						if ((mask & LLInventoryObserver::REMOVE) != LLInventoryObserver::REMOVE)
						{
							llwarns << *id_it << " is not in model but in view, but REMOVE flag not set" << llendl;
						}
						// item in view but not model, need to delete view
						view_item->destroyView();
					}
					else
					{
						llwarns << *id_it << "Item does not exist in either view or model, but notification triggered" << llendl;
					}
				}
			}
		}
	}

	if (!handled)
	{
		// it's a small change that only requires a refresh.
		// *TODO: figure out a more efficient way to do the refresh
		// since it is expensive on large inventories
		mFolders->refresh();
	}
}
Exemplo n.º 11
0
GameControl::~GameControl()
{
	Game::getInstance().getMeshManager().destroyMesh(getModel().getElement()->getMeshName());
}
Exemplo n.º 12
0
 bool Link::isUsed()
 {
   return lmm_constraint_used(getModel()->getMaxminSystem(), getConstraint());
 }
Exemplo n.º 13
0
void RenderableModelEntityItem::render(RenderArgs* args) {
    PerformanceTimer perfTimer("RMEIrender");
    assert(getType() == EntityTypes::Model);
    
    bool drawAsModel = hasModel();

    glm::vec3 position = getPosition();
    glm::vec3 dimensions = getDimensions();
    float size = glm::length(dimensions);

    bool highlightSimulationOwnership = false;
    if (args->_debugFlags & RenderArgs::RENDER_DEBUG_SIMULATION_OWNERSHIP) {
        auto nodeList = DependencyManager::get<NodeList>();
        const QUuid& myNodeID = nodeList->getSessionUUID();
        highlightSimulationOwnership = (getSimulatorID() == myNodeID);
    }

    if (drawAsModel && !highlightSimulationOwnership) {
        remapTextures();
        glPushMatrix();
        {
            float alpha = getLocalRenderAlpha();

            if (!_model || _needsModelReload) {
                // TODO: this getModel() appears to be about 3% of model render time. We should optimize
                PerformanceTimer perfTimer("getModel");
                EntityTreeRenderer* renderer = static_cast<EntityTreeRenderer*>(args->_renderer);
                getModel(renderer);
            }
            
            if (_model) {
                // handle animations..
                if (hasAnimation()) {
                    if (!jointsMapped()) {
                        QStringList modelJointNames = _model->getJointNames();
                        mapJoints(modelJointNames);
                    }

                    if (jointsMapped()) {
                        QVector<glm::quat> frameData = getAnimationFrame();
                        for (int i = 0; i < frameData.size(); i++) {
                            _model->setJointState(i, true, frameData[i]);
                        }
                    }
                }

                glm::quat rotation = getRotation();
                bool movingOrAnimating = isMoving() || isAnimatingSomething();
                if ((movingOrAnimating || _needsInitialSimulation) && _model->isActive()) {
                    _model->setScaleToFit(true, dimensions);
                    _model->setSnapModelToRegistrationPoint(true, getRegistrationPoint());
                    _model->setRotation(rotation);
                    _model->setTranslation(position);
                    
                    // make sure to simulate so everything gets set up correctly for rendering
                    {
                        PerformanceTimer perfTimer("_model->simulate");
                        _model->simulate(0.0f);
                    }
                    _needsInitialSimulation = false;
                }

                if (_model->isActive()) {
                    // TODO: this is the majority of model render time. And rendering of a cube model vs the basic Box render
                    // is significantly more expensive. Is there a way to call this that doesn't cost us as much? 
                    PerformanceTimer perfTimer("model->render");
                    // filter out if not needed to render
                    if (args && (args->_renderMode == RenderArgs::SHADOW_RENDER_MODE)) {
                        if (movingOrAnimating) {
                            _model->renderInScene(alpha, args);
                        }
                    } else {
                        _model->renderInScene(alpha, args);
                    }
                } else {
                    // if we couldn't get a model, then just draw a cube
                    glm::vec4 color(getColor()[RED_INDEX]/255, getColor()[GREEN_INDEX]/255, getColor()[BLUE_INDEX]/255, 1.0f);
                    glPushMatrix();
                        glTranslatef(position.x, position.y, position.z);
                        DependencyManager::get<DeferredLightingEffect>()->renderWireCube(size, color);
                    glPopMatrix();
                }
            } else {
                // if we couldn't get a model, then just draw a cube
                glm::vec4 color(getColor()[RED_INDEX]/255, getColor()[GREEN_INDEX]/255, getColor()[BLUE_INDEX]/255, 1.0f);
                glPushMatrix();
                    glTranslatef(position.x, position.y, position.z);
                    DependencyManager::get<DeferredLightingEffect>()->renderWireCube(size, color);
                glPopMatrix();
            }
        }
        glPopMatrix();
    } else {
        glm::vec4 color(getColor()[RED_INDEX]/255, getColor()[GREEN_INDEX]/255, getColor()[BLUE_INDEX]/255, 1.0f);
        glPushMatrix();
        glTranslatef(position.x, position.y, position.z);
        DependencyManager::get<DeferredLightingEffect>()->renderWireCube(size, color);
        glPopMatrix();
    }
}
Exemplo n.º 14
0
 void
DiscreteTimeDyn::output(vle::devs::Time time,
                        vle::devs::ExternalEventList& output) const
{
     mpimpl->output(getModel(), time, output);
}
Exemplo n.º 15
0
  void XRay::output(const vd::Time& /*time*/,
                      vd::ExternalEventList& output) const
  {
      if (mPhase == SEND) {
          vd::RequestEvent * request = new vd::RequestEvent ("status?");
          request << vd::attribute ("modelName", std::string (getModelName()));
          output.addEvent (request);
      }

      if ((mPhase == RECEIVE)and 
          (getModel().existOutputPort("observations"))) { 
          vd::ExternalEvent * ev = new vd::ExternalEvent ("observations");
          ev << vd::attribute ("value", buildDouble(mPrevalence));
          output.addEvent (ev);
      }
 
      if ((mPhase == RECEIVE)and 
          (getModel().existOutputPort("control"))) { 
          vd::ExternalEvent * ev = new vd::ExternalEvent ("control");
          vv::Map* nodeObservations = vv::Map::create();
          typedef std::map<std::string, std::string>::const_iterator mapit;
          for (mapit it = mapResult.begin(); it != mapResult.end(); it++) {
              if (it->second == "I")
                nodeObservations->addString(it->first, it->second);
          }
          ev << vd::attribute ("infectedNodes", nodeObservations);
          output.addEvent (ev);
      }

 
      if ((mPhase == RECEIVE)and 
          (getModel().existOutputPort("info_center"))) { 
          vd::ExternalEvent * ev = new vd::ExternalEvent ("info_center");
          vv::Map* nodeObservations = vv::Map::create();
          typedef std::map<std::string, std::string>::const_iterator mapit;
          for (mapit it = mapResult.begin(); it != mapResult.end(); it++) {
                nodeObservations->addString(it->first, it->second);
          }
          ev << vd::attribute ("nodesStates", nodeObservations);
          output.addEvent (ev);
      }

      if ((mPhase == RECEIVE or mPhase == INIT) 
          and getModel().existOutputPort("connectTo")) {
          vd::ExternalEvent* connectionRequest = 
                new vd::ExternalEvent("connectTo");
          vv::Set linkTo;
          std::vector <int> sample;
          int i=0;
          while (sample.size()<mNbModel) { 
              sample.push_back(i);
              i++;
          }
          for (int j = 0; j < sample.size(); j++) {
              int k = rand().getInt(0,sample.size()-1);
              int temp = sample[j];
              sample[j]=sample[k];
              sample[k]=temp;
          }
          while (sample.size()>mSampleSize)
              sample.pop_back();

          for (std::vector<int>::iterator i = sample.begin(); i!=sample.end(); ++i) {
            std::string vetName = 
              mPrefix + "-" + boost::lexical_cast<std::string>(*i);
            linkTo.addString(vetName);
          }
          connectionRequest << vd::attribute("modelName", 
                                             std::string (getModelName()));
          connectionRequest << vd::attribute("linkTo", linkTo);
          output.addEvent(connectionRequest);
      }
  }
Exemplo n.º 16
0
void Visualizer::paintGL()
{ 

    // Wait for lock on model. Need this to avoid concurrency issues when reading searcher and target data structures.
    model->lock();

    QPainter painter;
    painter.begin(this);


    // qApp->processEvents();
    //cout << "paintGL called" << endl;
    model->gui_ready = true;

    model->drawing = true;

    SearchSpace* space = model->getSearchSpace();
    int n_targets = 0;
    Target* targets = space->getTargetsCopy(n_targets);

    int n_searchers = 0;
    Searcher* searchers = space->getSearchersCopy(n_searchers);


    x_min_bound = getModel()->getSearchSpace()->getXMinBound();
    y_min_bound = getModel()->getSearchSpace()->getYMinBound();
    z_min_bound = getModel()->getSearchSpace()->getZMinBound();
    x_max_bound = getModel()->getSearchSpace()->getXMaxBound();
    y_max_bound = getModel()->getSearchSpace()->getYMaxBound();
    z_max_bound = getModel()->getSearchSpace()->getZMaxBound();

    float x_center = (x_max_bound-x_min_bound)/2;
    float y_center = (y_max_bound-y_min_bound)/2;
    float z_center = (z_max_bound-z_min_bound)/2;

    saveGLState();

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    //glTranslatef(0.0, 0.0, -10.0);
    glFrustum(-1, 1, -1, 1, 0, 0);
   // glViewport(0, 0, 2*width(), 2*height());
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    //glTranslatef(0.0f, 0.0f, -15.0f);
    glRotatef(xRot / 16.0, 1.0, 0.0, 0.0);
    glRotatef(yRot / 16.0, 0.0, 1.0, 0.0);
    glRotatef(zRot / 16.0, 0.0, 0.0, 1.0);
    glTranslatef(horz_pan, vert_pan, 0.0f);
    //glScalef (1.0, 1.0, 1.0);      /* modeling transformation */
    glScalef(scale, scale, scale);
    glColor4f(1.0, 1.0, 1.0, 0.3);

    drawRectangularPrism(x_min_bound-x_center, y_min_bound-y_center, z_min_bound-z_center, x_max_bound-x_center, y_max_bound-y_center, z_max_bound-z_center);

    QPointF pos;
    QPointF center_pos;

    //int n_searchers = space->getNumSearchers();
    //Searcher* searchers = space->getSearchers();

    //cout << "Number of searchers: " << n_searchers << endl;

    // draw boundary
    QRect frame_rect = this->contentsRect();
    int frame_height = frame_rect.height();
    int frame_width = frame_rect.width();

    center_pos = frame_rect.center();

    for ( int i = 0; i < n_searchers; i++ )
    {
        float scaled_x = searchers[i].getXPos()-x_center;
        float scaled_y = searchers[i].getYPos()-y_center;
        float scaled_z = searchers[i].getZPos()-z_center;

        glColor3f(searchers[i].red/255.0, searchers[i].blue/255.0, searchers[i].green/255.0);

        GLUquadricObj *quadric=gluNewQuadric();
        gluQuadricNormals(quadric, GLU_SMOOTH);
        glPushMatrix();
        glTranslatef( scaled_x, scaled_y, scaled_z );
        glPushMatrix();
        gluSphere(quadric, target_display_radius, 10,10);
        glPopMatrix();
        gluDeleteQuadric(quadric);

        //cout << "Raw (" << searchers[i].getXPos() << ", " << searchers[i].getYPos() << ", " << searchers[i].getZPos() <<")" << endl;
        //cout << "Scaled (" << scaled_x << ", " << scaled_y << ", " << scaled_z << ")" << endl;


        // Display path
        vector<Coordinate*> path = searchers[i].getPath();

        for(vector<Coordinate*>::iterator it = path.begin(); it != path.end(); ++it)
        {

            if (*(it+1) == NULL || *it == NULL)
            {
               // cout << "Tried to display path but it seems to have been invalidated" << endl;
                continue; // Trying to avoid occasional concurrent change errors
            }

            float scaled_path_x = (*it)->getX()-x_center;//*frame_width/2;//+center_pos.x();
            float scaled_path_y = (*it)->getY()-y_center;//*frame_height/2;//+center_pos.y();
            float scaled_path_z = (*it)->getZ()-z_center;//*frame_height/2;//+center_pos.y(); // <---- FIX FOR Z

            Coordinate start, end;
            start.setX(scaled_path_x);
            start.setY(scaled_path_y);
            start.setZ(scaled_path_z);


            if (it+1 != path.end())
            {
                scaled_path_x = (*(it+1))->getX()-x_center;//*frame_width/2;//+center_pos.x();
                scaled_path_y = (*(it+1))->getY()-y_center;//*frame_height/2;//+center_pos.y();
                scaled_path_z = (*(it+1))->getZ()-z_center;//*frame_height/2;//+center_pos.y();
            }
            else
            {
                break;
            }

            end.setX(scaled_path_x);
            end.setY(scaled_path_y);
            end.setZ(scaled_path_z);

            //painter.drawLine(path_segment);

            glBegin(GL_LINES);
            glVertex3d(start.getX(), start.getY(), start.getZ());
            glVertex3d(end.getX(), end.getY(), end.getZ());
            glEnd();

        }


    }


    // display targets


    for ( int i = 0; i < n_targets; i++ )
    {
        if ( targets[i].getXPos() < x_min_bound
             || targets[i].getXPos() > x_max_bound
             || targets[i].getYPos() < y_min_bound
             || targets[i].getYPos() > y_max_bound
             || targets[i].getZPos() < z_min_bound
             || targets[i].getZPos() > z_max_bound
             )
            continue; // This can happen when targets are being repositioned at the start of a new target placement - looks ugly

        if ( targets[i].isFound() ) glColor4f( 0.0, 1.0, 1.0, 1.0 );
        else glColor4f( 0.0, 1.0, 0.0, 0.2 );
        GLUquadricObj *quadric=gluNewQuadric();
        gluQuadricNormals(quadric, GLU_SMOOTH);
        glPushMatrix();
        glTranslatef( targets[i].getXPos()-x_center,targets[i].getYPos()-y_center ,targets[i].getZPos()-z_center );
        glPushMatrix();
        gluSphere(quadric, target_display_radius, 10,10);
        glPopMatrix();
        gluDeleteQuadric(quadric);
    }

    restoreGLState();
    //swapBuffers();


    //emit VisFinishedPaintGL();

    QString framesPerSecond;
    framesPerSecond.setNum(frames /(time.elapsed() / 1000.0), 'f', 2);

    painter.setPen(Qt::white);

    painter.drawText(20, 40, framesPerSecond + " fps");

    painter.end();

    swapBuffers();

    frames++;

    if (!(frames % 100)) {
        time.start();
        frames = 0;
    }

    model->drawing = false;

    delete [] targets;
    delete [] searchers;

    // Release the model lock so the model can continue processessing
    model->unlock();

    //glFinish();
    //qApp->processEvents();

}
Exemplo n.º 17
0
void ComboBox::changed(ConstFieldMaskArg whichField, 
                       UInt32            origin,
                       BitVector         details)
{
    Inherited::changed(whichField, origin, details);

    //Do not respond to changes that have a Sync origin
    if(origin & ChangedOrigin::Sync)
    {
        return;
    }

    if( (whichField & EditableFieldMask))
    {
        updateComponentGeneratorSelectedItem();
    }

    if((whichField & ExpandButtonFieldMask) &&
       getExpandButton() != NULL)
    {
        _ExpandButtonSelectedConnection = getExpandButton()->connectButtonSelected(boost::bind(&ComboBox::handleExpandButtonSelected, this, _1));
        _ExpandButtonDeselectedConnection = getExpandButton()->connectButtonDeselected(boost::bind(&ComboBox::handleExpandButtonDeselected, this, _1));
        
        _ExpandPopupMenuCanceledConnection = getComboListPopupMenu()->connectPopupMenuCanceled(boost::bind(&ComboBox::handleExpandPopupMenuCanceled, this, _1));
        _ExpandPopupMenuWillBecomeInvisibleConnection = getComboListPopupMenu()->connectPopupMenuWillBecomeInvisible(boost::bind(&ComboBox::handleExpandPopupMenuWillBecomeInvisible, this, _1));
        _ExpandPopupMenuWillBecomeVisibleConnection = getComboListPopupMenu()->connectPopupMenuWillBecomeVisible(boost::bind(&ComboBox::handleExpandPopupMenuWillBecomeVisible, this, _1));
        _ExpandPopupMenuContentsChangedConnection = getComboListPopupMenu()->connectPopupMenuContentsChanged(boost::bind(&ComboBox::handleExpandPopupMenuContentsChanged, this, _1));
    }

    if( (whichField & ExpandButtonFieldMask) ||
        (whichField & EditorFieldMask) ||
        (whichField & EditableFieldMask) ||
        (whichField & ComponentGeneratorSelectedItemFieldMask))
    {
        clearChildren();
        if(getExpandButton() != NULL)
        {
            getExpandButton()->setEnabled(getEnabled());
            pushToChildren(getExpandButton());
        }
        if(getEditable() && getEditor() != NULL && getEditor()->getEditorComponent() != NULL)
        {
            getEditor()->getEditorComponent()->setEnabled(getEnabled());
            pushToChildren(getEditor()->getEditorComponent());
        }
        if(!getEditable() && getComponentGeneratorSelectedItem() != NULL)
        {
            getComponentGeneratorSelectedItem()->setEnabled(getEnabled());
            pushToChildren(getComponentGeneratorSelectedItem());
        }
    }

    if( (whichField & EditorFieldMask) && getEditor() != NULL)
    {
        _EditorActionConnection = getEditor()->connectActionPerformed(boost::bind(&ComboBox::handleEditorAction, this, _1));
    }

    if(whichField & ModelFieldMask)
    {
        if(getModel() != NULL)
        {
            getComboListPopupMenu()->setModel(getModel());

            _ContentsChangedConnection = getModel()->connectListDataContentsChanged(boost::bind(&ComboBox::handleContentsChanged, this, _1));
            _ContentsIntervalAddedConnection = getModel()->connectListDataIntervalAdded(boost::bind(&ComboBox::handleContentsIntervalAdded, this, _1));
            _ContentsIntervalRemovedConnection = getModel()->connectListDataIntervalRemoved(boost::bind(&ComboBox::handleContentsIntervalRemoved, this, _1));
            _SelectionChangedConnection = getModel()->connectSelectionChanged(boost::bind(&ComboBox::handleSelectionChanged, this, _1));
            updateListFromModel();
        }
    }

    if(((whichField & CellGeneratorFieldMask) ||
        (whichField & ComboListPopupMenuFieldMask)) &&
       getCellGenerator() != NULL)
    {
        getComboListPopupMenu()->setCellGenerator(getCellGenerator());
    }
}
Exemplo n.º 18
0
void Visualizer::GUISetTargetDetectRadius(const QString &textvalue)
{
    target_detect_radius = textvalue.toFloat();
    getModel()->getSearchSpace()->setTargetDetectRadius(target_detect_radius);
    getModel()->calcTargetsFound();
}
void LLInventoryPanel::modelChanged(U32 mask)
{
	static LLFastTimer::DeclareTimer FTM_REFRESH("Inventory Refresh");
	LLFastTimer t2(FTM_REFRESH);

	bool handled = false;

	if (!mViewsInitialized) return;
	
	const LLInventoryModel* model = getModel();
	if (!model) return;

	const LLInventoryModel::changed_items_t& changed_items = model->getChangedIDs();
	if (changed_items.empty()) return;

	for (LLInventoryModel::changed_items_t::const_iterator items_iter = changed_items.begin();
		 items_iter != changed_items.end();
		 ++items_iter)
	{
		const LLUUID& item_id = (*items_iter);
		const LLInventoryObject* model_item = model->getObject(item_id);
		LLFolderViewItem* view_item = mFolderRoot->getItemByID(item_id);

		// LLFolderViewFolder is derived from LLFolderViewItem so dynamic_cast from item
		// to folder is the fast way to get a folder without searching through folders tree.
		LLFolderViewFolder* view_folder = dynamic_cast<LLFolderViewFolder*>(view_item);

		//////////////////////////////
		// LABEL Operation
		// Empty out the display name for relabel.
		if (mask & LLInventoryObserver::LABEL)
		{
			handled = true;
			if (view_item)
			{
				// Request refresh on this item (also flags for filtering)
				LLInvFVBridge* bridge = (LLInvFVBridge*)view_item->getListener();
				if(bridge)
				{	// Clear the display name first, so it gets properly re-built during refresh()
					bridge->clearDisplayName();

					view_item->refresh();
				}
			}
		}

		//////////////////////////////
		// REBUILD Operation
		// Destroy and regenerate the UI.
		if (mask & LLInventoryObserver::REBUILD)
		{
			handled = true;
			if (model_item && view_item)
			{
				view_item->destroyView();
			}
			view_item = buildNewViews(item_id);
			view_folder = dynamic_cast<LLFolderViewFolder *>(view_item);
		}

		//////////////////////////////
		// INTERNAL Operation
		// This could be anything.  For now, just refresh the item.
		if (mask & LLInventoryObserver::INTERNAL)
		{
			if (view_item)
			{
				view_item->refresh();
			}
		}

		//////////////////////////////
		// SORT Operation
		// Sort the folder.
		if (mask & LLInventoryObserver::SORT)
		{
			if (view_folder)
			{
				view_folder->requestSort();
			}
		}	

		// We don't typically care which of these masks the item is actually flagged with, since the masks
		// may not be accurate (e.g. in the main inventory panel, I move an item from My Inventory into
		// Landmarks; this is a STRUCTURE change for that panel but is an ADD change for the Landmarks
		// panel).  What's relevant is that the item and UI are probably out of sync and thus need to be
		// resynchronized.
		if (mask & (LLInventoryObserver::STRUCTURE |
					LLInventoryObserver::ADD |
					LLInventoryObserver::REMOVE))
		{
			handled = true;

			//////////////////////////////
			// ADD Operation
			// Item exists in memory but a UI element hasn't been created for it.
			if (model_item && !view_item)
			{
				// Add the UI element for this item.
				buildNewViews(item_id);
				// Select any newly created object that has the auto rename at top of folder root set.
				if(mFolderRoot->getRoot()->needsAutoRename())
				{
					setSelection(item_id, FALSE);
				}
			}

			//////////////////////////////
			// STRUCTURE Operation
			// This item already exists in both memory and UI.  It was probably reparented.
			else if (model_item && view_item)
			{
				// Don't process the item if it is the root
				if (view_item->getRoot() != view_item)
				{
					LLFolderViewFolder* new_parent = (LLFolderViewFolder*)mFolderRoot->getItemByID(model_item->getParentUUID());
					// Item has been moved.
					if (view_item->getParentFolder() != new_parent)
					{
						if (new_parent != NULL)
						{
							// Item is to be moved and we found its new parent in the panel's directory, so move the item's UI.
							view_item->getParentFolder()->extractItem(view_item);
							view_item->addToFolder(new_parent, mFolderRoot);
						}
						else 
						{
							// Item is to be moved outside the panel's directory (e.g. moved to trash for a panel that 
							// doesn't include trash).  Just remove the item's UI.
							view_item->destroyView();
						}
					}
				}
			}
			
			//////////////////////////////
			// REMOVE Operation
			// This item has been removed from memory, but its associated UI element still exists.
			else if (!model_item && view_item)
			{
				// Remove the item's UI.
				view_item->destroyView();
			}
		}
	}
}
Exemplo n.º 20
0
void
NodeAnim::initialize(AnimatedItemTypeEnum nodeType)
{
    _imp->nodeType = nodeType;
    NodePtr internalNode = getNodeGui()->getNode();

    AnimationModuleBasePtr model = getModel();
    NodeAnimPtr thisShared = shared_from_this();
    _imp->nameItem = new QTreeWidgetItem;
    _imp->nameItem->setData(0, QT_ROLE_CONTEXT_ITEM_POINTER, qVariantFromValue((void*)thisShared.get()));
    _imp->nameItem->setText( 0, QString::fromUtf8( internalNode->getLabel().c_str() ) );
    _imp->nameItem->setData(0, QT_ROLE_CONTEXT_TYPE, nodeType);
    _imp->nameItem->setData(0, QT_ROLE_CONTEXT_IS_ANIMATED, true);
    _imp->nameItem->setExpanded(true);
    int nCols = getModel()->getTreeColumnsCount();
    if (nCols > ANIMATION_MODULE_TREE_VIEW_COL_VISIBLE) {
        _imp->nameItem->setData(ANIMATION_MODULE_TREE_VIEW_COL_VISIBLE, QT_ROLE_CONTEXT_ITEM_VISIBLE, QVariant(true));
        _imp->nameItem->setIcon(ANIMATION_MODULE_TREE_VIEW_COL_VISIBLE, model->getItemVisibilityIcon(true));
    }
    if (nCols > ANIMATION_MODULE_TREE_VIEW_COL_PLUGIN_ICON) {
        QString iconFilePath = QString::fromUtf8(internalNode->getPluginIconFilePath().c_str());
        AnimationModuleTreeView::setItemIcon(iconFilePath, _imp->nameItem);
    }

    connect( internalNode.get(), SIGNAL(labelChanged(QString, QString)), this, SLOT(onNodeLabelChanged(QString, QString)) );

    initializeKnobsAnim();

    initializeTableItems();

    // Connect signals/slots to knobs to compute the frame range
    AnimationModulePtr animModel = toAnimationModule(model);
    assert(animModel);

    if (nodeType == eAnimatedItemTypeCommon) {
        // Also connect the lifetime knob
        KnobIntPtr lifeTimeKnob = internalNode->getEffectInstance()->getLifeTimeKnob();
        if (lifeTimeKnob) {
            connect( lifeTimeKnob->getSignalSlotHandler().get(), SIGNAL(mustRefreshKnobGui(ViewSetSpec,DimSpec,ValueChangedReasonEnum)), this, SLOT(onFrameRangeKnobChanged()) );
        }

    } else if (nodeType == eAnimatedItemTypeReader) {
        // The dopesheet view must refresh if the user set some values in the settings panel
        // so we connect some signals/slots
        KnobIPtr lastFrameKnob = internalNode->getKnobByName(kReaderParamNameLastFrame);
        if (!lastFrameKnob) {
            return;
        }
        boost::shared_ptr<KnobSignalSlotHandler> lastFrameKnobHandler =  lastFrameKnob->getSignalSlotHandler();
        assert(lastFrameKnob);
        boost::shared_ptr<KnobSignalSlotHandler> startingTimeKnob = internalNode->getKnobByName(kReaderParamNameStartingTime)->getSignalSlotHandler();
        assert(startingTimeKnob);

        connect( lastFrameKnobHandler.get(), SIGNAL(mustRefreshKnobGui(ViewSetSpec,DimSpec,ValueChangedReasonEnum)), this, SLOT(onFrameRangeKnobChanged()) );

        connect( startingTimeKnob.get(), SIGNAL(mustRefreshKnobGui(ViewSetSpec,DimSpec,ValueChangedReasonEnum)), this, SLOT(onFrameRangeKnobChanged()) );

        // We don't make the connection for the first frame knob, because the
        // starting time is updated when it's modified. Thus we avoid two
        // refreshes of the view.
    } else if (nodeType == eAnimatedItemTypeRetime) {
        boost::shared_ptr<KnobSignalSlotHandler> speedKnob =  internalNode->getKnobByName(kRetimeParamNameSpeed)->getSignalSlotHandler();
        assert(speedKnob);

        connect( speedKnob.get(), SIGNAL(mustRefreshKnobGui(ViewSetSpec,DimSpec,ValueChangedReasonEnum)), this, SLOT(onFrameRangeKnobChanged()) );
    } else if (nodeType == eAnimatedItemTypeTimeOffset) {
        boost::shared_ptr<KnobSignalSlotHandler> timeOffsetKnob =  internalNode->getKnobByName(kReaderParamNameTimeOffset)->getSignalSlotHandler();
        assert(timeOffsetKnob);

        connect( timeOffsetKnob.get(), SIGNAL(mustRefreshKnobGui(ViewSetSpec,DimSpec,ValueChangedReasonEnum)), this, SLOT(onFrameRangeKnobChanged()) );
    } else if (nodeType == eAnimatedItemTypeFrameRange) {
        boost::shared_ptr<KnobSignalSlotHandler> frameRangeKnob =  internalNode->getKnobByName(kFrameRangeParamNameFrameRange)->getSignalSlotHandler();
        assert(frameRangeKnob);

        connect( frameRangeKnob.get(), SIGNAL(mustRefreshKnobGui(ViewSetSpec,DimSpec,ValueChangedReasonEnum)),  this, SLOT(onFrameRangeKnobChanged()) );
    }
    
    refreshFrameRange();

} // initialize
Exemplo n.º 21
0
/* Internal method to convert the CoordinateReferences into goals of the 
   assembly solver. Subclasses, override and call base to include other goals  
   such as point of interest matching (Marker tracking). This method is
   automatically called by assemble. */
void AssemblySolver::setupGoals(SimTK::State &s)
{
    // wipe-out the previous SimTK::Assembler
    delete _assembler;
    _assembler = new SimTK::Assembler(getModel().getMultibodySystem());
    _assembler->setAccuracy(_accuracy);

    // Define weights on constraints. Note can be specified SimTK::Infinity to strictly enforce constraint
    // otherwise the weighted constraint error becomes a goal.
    _assembler->setSystemConstraintsWeight(_constraintWeight);

    // clear any old coordinate goals
    _coordinateAssemblyConditions.clear();

    // Get model coordinates
    const CoordinateSet& modelCoordSet = getModel().getCoordinateSet();

    // Restrict solution to set range of any of the coordinates that are clamped
    for(int i=0; i<modelCoordSet.getSize(); ++i){
        const Coordinate& coord = modelCoordSet[i];
        if(coord.getClamped(s)){
            _assembler->restrictQ(coord.getBodyIndex(), 
                MobilizerQIndex(coord.getMobilizerQIndex()),
                coord.getRangeMin(), coord.getRangeMax());
        }
    }

    SimTK::Array_<CoordinateReference>::iterator p;

    // Cycle through coordinate references
    for(p = _coordinateReferencesp.begin(); 
        p != _coordinateReferencesp.end(); p++) {
        if(p){
            CoordinateReference *coordRef = p;
            const Coordinate &coord = modelCoordSet.get(coordRef->getName());
            if(coord.getLocked(s)){
                //cout << "AssemblySolver: coordinate " << coord.getName() << " is locked/prescribed and will be excluded." << endl;
                _assembler->lockQ(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex()));
                //No longer need the lock on
                coord.setLocked(s, false);
                
                //Get rid of the corresponding reference too
                _coordinateReferencesp.erase(p);
                p--; //decrement since erase automatically points to next in the list
            }
            else if(!(coord.get_is_free_to_satisfy_constraints())) {
                // Make this reference and its current value a goal of the Assembler
                SimTK::QValue *coordGoal = new SimTK::QValue(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex()),
                                                         coordRef->getValue(s) );
                // keep a handle to the goal so we can update
                _coordinateAssemblyConditions.push_back(coordGoal);
                // Add coordinate matching goal to the ik objective
                SimTK::AssemblyConditionIndex acIx = _assembler->adoptAssemblyGoal(coordGoal, coordRef->getWeight(s));
            }
        }
    }

    unsigned int nqrefs  = _coordinateReferencesp.size(), 
                 nqgoals = _coordinateAssemblyConditions.size();
    //Should have a one-to-one matched arrays
    if(nqrefs != nqgoals)
        throw Exception("AsemblySolver::setupGoals() has a mismatch between number of references and goals.");
}
Exemplo n.º 22
0
 void Object::destroyObject()
 {
   if (getModel())
     getModel()->destroyObject(this) ;
 }
Exemplo n.º 23
0
// NOTE: this only renders the "meta" portion of the Model, namely it renders debugging items, and it handles
// the per frame simulation/update that might be required if the models properties changed.
void RenderableModelEntityItem::render(RenderArgs* args) {
    PerformanceTimer perfTimer("RMEIrender");
    assert(getType() == EntityTypes::Model);

    if (hasModel()) {
        if (_model) {
            // check if the URL has changed
            auto& currentURL = getParsedModelURL();
            if (currentURL != _model->getURL()) {
                qCDebug(entitiesrenderer).noquote() << "Updating model URL: " << currentURL.toDisplayString();
                _model->setURL(currentURL);
            }

            render::ScenePointer scene = AbstractViewStateInterface::instance()->getMain3DScene();

            // check to see if when we added our models to the scene they were ready, if they were not ready, then
            // fix them up in the scene
            bool shouldShowCollisionHull = (args->_debugFlags & (int)RenderArgs::RENDER_DEBUG_HULLS) > 0;
            if (_model->needsFixupInScene() || _showCollisionHull != shouldShowCollisionHull) {
                _showCollisionHull = shouldShowCollisionHull;
                render::PendingChanges pendingChanges;

                _model->removeFromScene(scene, pendingChanges);

                render::Item::Status::Getters statusGetters;
                makeEntityItemStatusGetters(getThisPointer(), statusGetters);
                _model->addToScene(scene, pendingChanges, statusGetters, _showCollisionHull);

                scene->enqueuePendingChanges(pendingChanges);
            }

            // FIXME: this seems like it could be optimized if we tracked our last known visible state in
            //        the renderable item. As it stands now the model checks it's visible/invisible state
            //        so most of the time we don't do anything in this function.
            _model->setVisibleInScene(getVisible(), scene);
        }


        remapTextures();
        {
            // float alpha = getLocalRenderAlpha();

            if (!_model || _needsModelReload) {
                // TODO: this getModel() appears to be about 3% of model render time. We should optimize
                PerformanceTimer perfTimer("getModel");
                EntityTreeRenderer* renderer = static_cast<EntityTreeRenderer*>(args->_renderer);
                getModel(renderer);
            }

            if (_model) {
                if (hasAnimation()) {
                    if (!jointsMapped()) {
                        QStringList modelJointNames = _model->getJointNames();
                        mapJoints(modelJointNames);
                    }
                }

                _jointDataLock.withWriteLock([&] {
                    getAnimationFrame();

                    // relay any inbound joint changes from scripts/animation/network to the model/rig
                    for (int index = 0; index < _absoluteJointRotationsInObjectFrame.size(); index++) {
                        if (_absoluteJointRotationsInObjectFrameDirty[index]) {
                            glm::quat rotation = _absoluteJointRotationsInObjectFrame[index];
                            _model->setJointRotation(index, true, rotation, 1.0f);
                            _absoluteJointRotationsInObjectFrameDirty[index] = false;
                        }
                    }
                    for (int index = 0; index < _absoluteJointTranslationsInObjectFrame.size(); index++) {
                        if (_absoluteJointTranslationsInObjectFrameDirty[index]) {
                            glm::vec3 translation = _absoluteJointTranslationsInObjectFrame[index];
                            _model->setJointTranslation(index, true, translation, 1.0f);
                            _absoluteJointTranslationsInObjectFrameDirty[index] = false;
                        }
                    }
                });

                bool movingOrAnimating = isMoving() || isAnimatingSomething();
                if ((movingOrAnimating ||
                     _needsInitialSimulation ||
                     _model->getTranslation() != getPosition() ||
                     _model->getRotation() != getRotation() ||
                     _model->getRegistrationPoint() != getRegistrationPoint())
                    && _model->isActive() && _dimensionsInitialized) {
                    _model->setScaleToFit(true, getDimensions());
                    _model->setSnapModelToRegistrationPoint(true, getRegistrationPoint());
                    _model->setRotation(getRotation());
                    _model->setTranslation(getPosition());

                    // make sure to simulate so everything gets set up correctly for rendering
                    {
                        PerformanceTimer perfTimer("_model->simulate");
                        _model->simulate(0.0f);
                    }

                    _needsInitialSimulation = false;
                }
            }
        }
    } else {
        static glm::vec4 greenColor(0.0f, 1.0f, 0.0f, 1.0f);
        gpu::Batch& batch = *args->_batch;
        bool success;
        auto shapeTransform = getTransformToCenter(success);
        if (success) {
            batch.setModelTransform(Transform()); // we want to include the scale as well
            DependencyManager::get<GeometryCache>()->renderWireCubeInstance(batch, shapeTransform, greenColor);
        }
    }
}
Exemplo n.º 24
0
 void Object::changeParent(Object* new_parent)
 {
   if (getModel())
     getModel()->changeParent(this,new_parent) ;
 }
Exemplo n.º 25
0
Arquivo: probe.cpp Projeto: 4DA/openmw
 void Probe::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const
 {
     const std::string model = getModel(ptr);
     if(!model.empty())
         physics.addObject(ptr,true);
 }
Exemplo n.º 26
0
 void Object::destroyTrait(Trait* trait)
 {
   if (getModel())
     getModel()->destroyTrait(this,trait) ;
 }
Exemplo n.º 27
0
QString KeyMap::name() const {
    return (getModel(model()) + " " + getLayout(layout())).toUpper();
}
Exemplo n.º 28
0
const SimTK::DefaultSystemSubsystem& ModelComponent::
getDefaultSubsystem() const
{   return getModel().getDefaultSubsystem(); }
ModelGeneratorContext::ModelGeneratorContext(std::string const &sbml,
    unsigned options) :
        ownedDoc(0),
        doc(0),
        symbols(0),
        modelSymbols(0),
        errString(new string()),
        options(options),
        moietyConverter(0),
        functionPassManager(0)
{
    if (options & rr::ModelGenerator::CONSERVED_MOIETIES)
    {
        Log(Logger::LOG_NOTICE) << "performing conserved moiety conversion";

        moietyConverter = new rr::conservation::ConservedMoietyConverter();
        ownedDoc = checkedReadSBMLFromString(sbml.c_str());

        if (moietyConverter->setDocument(ownedDoc) != LIBSBML_OPERATION_SUCCESS)
        {
            throw_llvm_exception("error setting conserved moiety converter document");
        }

        if (moietyConverter->convert() != LIBSBML_OPERATION_SUCCESS)
        {
            throw_llvm_exception("error converting document to conserved moieties");
        }

        doc = moietyConverter->getDocument();

        SBMLWriter sw;
        char* convertedStr = sw.writeToString(doc);

        Log(Logger::LOG_NOTICE) << "***************** Conserved Moiety Converted Document ***************";
        Log(Logger::LOG_NOTICE) << convertedStr;
        Log(Logger::LOG_NOTICE) << "*********************************************************************";

        delete convertedStr;
    }
    else
    {
        ownedDoc = checkedReadSBMLFromString(sbml.c_str());
        doc = ownedDoc;
    }

    symbols = new LLVMModelDataSymbols(doc->getModel(), options);

    modelSymbols = new LLVMModelSymbols(getModel(), *symbols);


    // initialize LLVM
    // TODO check result
    InitializeNativeTarget();

    context = new LLVMContext();
    // Make the module, which holds all the code.
    module = new Module("LLVM Module", *context);

    builder = new IRBuilder<>(*context);

    // engine take ownership of module
    EngineBuilder engineBuilder(module);

    engineBuilder.setErrorStr(errString);
    executionEngine = engineBuilder.create();

    addGlobalMappings();

    createLibraryFunctions(module);

    ModelDataIRBuilder::createModelDataStructType(module, executionEngine, *symbols);

    initFunctionPassManager();
}
Exemplo n.º 30
0
Button::~Button()
{
  getModel().removeListener (this);
  getModel().removeView (this);
}