int TrackBallManipulator::hitCenterPlane(int posX, int posY, Vec3 &intersect)
{

    Vec3 center = getSceneGraph()->getCamera()->center();
    Vec3 np = getSceneGraph()->getCamera()->get_direction();
    Vec3 rayPoint,rayDir;
    getSceneGraph()->getCamera()->get_project_ray(posX,posY,rayPoint,rayDir);
    rayDir.Normalize();
    return Vec3::getIntersectionRayToPlane(rayPoint,rayDir,center,np,intersect);
}
void TrackBallManipulator::pan(int posX, int posY)
{
    Vec3 hitOld;
    int hit0 = hitCenterPlane(mCurrentX,mCurrentY, hitOld);
    Vec3 hitNew;
    int hit1 = hitCenterPlane(posX,posY,hitNew);
    if(hit0 && hit1)
    {
        getSceneGraph()->getCamera()->move(hitNew - hitOld);
        arcball_->setOffset(getSceneGraph()->getCamera()->getOffset());
    }

}
int TrackBallManipulator::hitSphere(int posX, int posY, Vec3 &intersect)
{
    Vec3 rayPoint;
    Vec3 rayDir;
    getSceneGraph()->getCamera()->get_project_ray(posX,posY,rayPoint,rayDir);
    rayDir.Normalize();
    Vec3 center = getSceneGraph()->getCamera()->center();
    Quat quat;
    quat.convertFromMatrix(getSceneGraph()->getCamera()->get_model_matrix());
    HomoMatrix4 inverseModelMatrix = quat.conjugate().convertToMatrix();
    Vec3 np = inverseModelMatrix * Vec3(0,0,1);
    Vec3 hitPlane;
    if(Vec3::getIntersectionRayToPlane(rayPoint,rayDir,center,np,hitPlane))
    {
        Vec3 v = hitPlane - center;
        Scalar len = v.length();
        bool isNearOne = true;
        v.Normalize();
        int k = len / this->getRadius();

        Scalar residual = len - this->getRadius() * k;
        Vec3 planePoint = hitPlane;
        if(k % 4== 0)
        {
            planePoint = center + v * residual;
        }
        else if(k % 4== 1)
        {
            planePoint = center + v * (this->getRadius() - residual);
            isNearOne = false;
        }
        else if(k % 4== 2)
        {
            planePoint = center - v * residual;
            isNearOne = false;
        }
        else
        {
            planePoint = center - v * (this->getRadius() - residual);
        }
        Vec3 dir = planePoint - rayPoint;
        dir.Normalize();
        if(getIntersectionToSphere(rayPoint,dir,intersect,isNearOne))
        {
            return k % 4;
        }
    }
    intersect = Vec3::getClosestPointFromPointToRay(center,rayPoint,rayDir);
    return -1;
}
void TrackBallManipulator::rotate(int posX, int posY)
{
    Vec3 hitOld;
    int hit0 = hitSphere(mCurrentX,mCurrentY, hitOld);
    Vec3 hitNew;
    int hit1 = hitSphere(posX,posY,hitNew);
    if(hit0 != hit1) return;
//    if((hitNew - hitOld).length() / this->getRadius() > M_PI / 7) return;
    Vec3 center = getSceneGraph()->getCamera()->center();
    Vec3 axis = (hitOld - center) ^ (hitNew - center);
    if(axis.Normalize() < ZERO_TOLERANCE) return;
    Scalar angle = (hitNew - hitOld).length() / this->getRadius();
    Quat quat(axis,angle);
    getSceneGraph()->getCamera()->rotation_matrix() *= quat.convertToMatrix();
}
Error PhysicsDebugNode::init()
{
	MyRenderComponent* rcomp = newComponent<MyRenderComponent>(this);
	ANKI_CHECK(rcomp->init());

	ObbSpatialComponent* scomp = newComponent<ObbSpatialComponent>(this);
	const Vec3 center = (getSceneGraph().getSceneMax() + getSceneGraph().getSceneMin()) / 2.0f;
	scomp->m_obb.setCenter(center.xyz0());
	scomp->m_obb.setExtend((getSceneGraph().getSceneMax() - center).xyz0());
	scomp->m_obb.setRotation(Mat3x4::getIdentity());
	scomp->setSpatialOrigin(Vec4(0.0f));
	scomp->setUpdateOctreeBounds(false); // Don't mess with the bounds

	return Error::NONE;
}
bool TrackBallManipulator::getIntersectionToSphere(const Vec3 &rayPoint, const Vec3 &rayDir, Vec3 &intersect, bool isNearOne)
{
    Scalar r = getRadius();
    Vec3 center = getSceneGraph()->getCamera()->center();
    Scalar b = Vec3::getDistanceFromRayToPoint(rayPoint,rayDir,center);
    Scalar c = r * r - b * b;
    if(c < 0) return false;
    c = sqrt(c);
    Vec3 closestPoint = Vec3::getClosestPointFromPointToRay(center,rayPoint,rayDir);

    intersect = closestPoint + rayDir * c;
    if(isNearOne)
    {
        if((closestPoint - rayDir * c - rayPoint).length() < (intersect - rayPoint).length())
        {
            intersect = closestPoint - rayDir * c;
        }
    }
    else
    {
        if((closestPoint - rayDir * c - rayPoint).length() > (intersect - rayPoint).length())
        {
            intersect = closestPoint - rayDir * c;
        }
    }

    return true;
}
Error OccluderNode::init(const CString& meshFname)
{
	// Load mesh
	MeshLoader loader(&getSceneGraph().getResourceManager());
	ANKI_CHECK(loader.load(meshFname));

	const U indexCount = loader.getHeader().m_totalIndexCount;
	m_vertsL.create(getAllocator(), indexCount);
	m_vertsW.create(getAllocator(), indexCount);

	DynamicArrayAuto<Vec3> positions(getAllocator());
	DynamicArrayAuto<U32> indices(getAllocator());
	ANKI_CHECK(loader.storeIndicesAndPosition(indices, positions));

	for(U i = 0; i < indices.getSize(); ++i)
	{
		m_vertsL[i] = positions[indices[i]];
	}

	// Create the components
	newComponent<MoveComponent>();
	newComponent<MoveFeedbackComponent>();
	newComponent<OccluderComponent>();

	return Error::NONE;
}
示例#8
0
void Sector::deferredUpdate()
{
	// Spatials should get updated
	for(SpatialComponent* sp : m_spatials)
	{
		sp->markForUpdate();
	}

	iterateScenePortals(getSceneGraph(), [&](Portal& portal) -> Bool {
		Bool collide = testCollisionShapes(m_aabb, portal.m_aabb);

		if(collide)
		{
			collide = testCollisionShapes(*m_shape, portal.getBoundingShape());
		}

		if(collide)
		{
			portal.tryAddSector(this);
			tryAddPortal(&portal);
		}
		else
		{
			portal.tryRemoveSector(this);
			tryRemovePortal(&portal);
		}

		return false;
	});
}
示例#9
0
Node::~Node() 
{
	deleteChildNodes();

	SceneGraph *sg = getSceneGraph();
	if (sg) {
		if (sg->getSelectedShapeNode() == this)
			sg->setSelectedShapeNode(NULL);
		if (sg->getSelectedNode() == this)
			sg->setSelectedNode(NULL);
	}

	remove();

	if (isInstanceNode() == true)
		setOriginalMembers();

#ifdef SUPPORT_JSAI
	delete mJNode;
#endif

	delete mName;
	delete mType;
	delete mExposedField;
	delete mEventInField;
	delete mEventOutField;
	delete mField;
	delete mPrivateField;
	delete mPrivateNodeVector;
	delete mChildNodes;
	delete mInitialized;
}
示例#10
0
void Portal::deferredUpdate()
{
	// Gather the sectors it collides
	iterateSceneSectors(getSceneGraph(), [&](Sector& sector) -> Bool {
		Bool collide = testCollisionShapes(m_aabb, sector.m_aabb);

		// Perform a more detailed test
		if(collide)
		{
			collide = testCollisionShapes(*m_shape, sector.getBoundingShape());
		}

		// Update graphs
		if(collide)
		{
			tryAddSector(&sector);
			sector.tryAddPortal(this);
		}
		else
		{
			tryRemoveSector(&sector);
			sector.tryRemovePortal(this);
		}

		return false;
	});
}
//==============================================================================
Error SceneAmbientColorEvent::update(F32 /*prevUpdateTime*/, F32 crntTime)
{
	getSceneGraph().setAmbientColor(
		linearInterpolate(m_originalColor, m_finalColor, getDelta(crntTime)));

	return ErrorCode::NONE;
}
示例#12
0
Error PortalSectorBase::init(const CString& meshFname, Bool isSector)
{
	// Create move component
	SceneComponent* comp = getSceneAllocator().newInstance<MoveComponent>(this);
	addComponent(comp, true);

	// Create portal or sector component
	if(isSector)
	{
		comp = getSceneAllocator().newInstance<SectorComponent>(this);
	}
	else
	{
		comp = getSceneAllocator().newInstance<PortalComponent>(this);
	}
	addComponent(comp, true);

	// Load mesh
	MeshLoader loader(&getSceneGraph().getResourceManager());
	ANKI_CHECK(loader.load(meshFname));

	// Convert Vec3 positions to Vec4
	const MeshLoader::Header& header = loader.getHeader();
	U vertsCount = header.m_totalVerticesCount;
	PtrSize vertSize = loader.getVertexSize();

	auto alloc = getSceneAllocator();
	m_shapeStorageLSpace.create(alloc, vertsCount);
	m_shapeStorageWSpace.create(alloc, vertsCount);

	for(U i = 0; i < vertsCount; ++i)
	{
		const Vec3& pos = *reinterpret_cast<const Vec3*>(loader.getVertexData() + vertSize * i);

		m_shapeStorageLSpace[i] = Vec4(pos, 0.0);
	}

	// Create shape
	ConvexHullShape* hull = alloc.newInstance<ConvexHullShape>();
	m_shape = hull;
	hull->initStorage(&m_shapeStorageWSpace[0], vertsCount);
	updateTransform(Transform::getIdentity());

	// Store indices
	ANKI_ASSERT(header.m_totalIndicesCount * sizeof(U16) == loader.getIndexDataSize());
	m_vertIndices.create(alloc, header.m_totalIndicesCount);
	const U16* indicesIn = reinterpret_cast<const U16*>(loader.getIndexData());
	for(U i = 0; i < header.m_totalIndicesCount; ++i)
	{
		m_vertIndices[i] = indicesIn[i];
	}

	return ErrorCode::NONE;
}
示例#13
0
Error Sector::frameUpdate(F32 prevUpdateTime, F32 crntTime)
{
	MoveComponent& move = getComponent<MoveComponent>();
	if(move.getTimestamp() == getGlobalTimestamp())
	{
		// Move comp updated.
		updateTransform(move.getWorldTransform());
		getSceneGraph().getSectorGroup().sectorUpdated(this);
	}

	return ErrorCode::NONE;
}
//==============================================================================
Error SceneAmbientColorEvent::create(EventManager* manager,
	F32 startTime, F32 duration, const Vec4& finalColor)
{
	Error err = Event::create(manager, startTime, duration);

	if(!err)
	{
		m_finalColor = finalColor;
		m_originalColor = getSceneGraph().getAmbientColor();
	}

	return err;
}
示例#15
0
void Node::removeRoutes() 
{
	SceneGraph *sg = getSceneGraph();
	if (sg) {
		Route *route=sg->getRoutes();
		while (route) {
			Route *nextRoute = route->next();
			if (route->getEventInNode() == this || route->getEventOutNode() == this)
				delete route;
			route = nextRoute;
		}
	}
}
示例#16
0
//==============================================================================
Error SpatialComponent::update(SceneNode&, F32, F32, Bool& updated)
{
	m_flags.unset(Flag::VISIBLE_ANY);

	updated = m_flags.get(Flag::MARKED_FOR_UPDATE);
	if(updated)
	{
		m_shape->computeAabb(m_aabb);
		getSceneGraph().getSectorGroup().spatialUpdated(this);
		m_flags.unset(Flag::MARKED_FOR_UPDATE);
	}

	return ErrorCode::NONE;
}
示例#17
0
void Node::removeSFNodes() 
{
	SceneGraph *sg = getSceneGraph();
	if (sg) {
		for (ScriptNode *script = sg->findScriptNode(); script; script=script->nextTraversal()) {
			for (int n=0; n<script->getNFields(); n++) {
				Field *field = script->getField(n);
				if (field->getType() == fieldTypeSFNode) {
					SFNode *sfnode = (SFNode *)field;
					if (sfnode->getValue() == this)
						sfnode->setValue((Node *)NULL);
				}
			}
		}
	}
}
示例#18
0
	void ZeldaGame::loadMap(const std::string& fileName)
	{
		TMX tmx(fileName);

		TMX::Object* pPlayer = nullptr;
		int playerSortOrder = 0;
		std::vector<TMX::ObjectGroup> objectGroups = tmx.getObjectGroups();
		for (auto& objectGroup : objectGroups)
		{
			for (auto& object : objectGroup.objects)
			{
				if (object.name == "Player")
				{
					if (pPlayer != nullptr) { throw std::runtime_error("Multiple Player objects found."); }
					pPlayer = &object;
					playerSortOrder = objectGroup.index;
				}
			}
		}
		if (pPlayer == nullptr) { throw std::runtime_error("No Player object found."); }

		auto upPlayer = Player::make(*this, *pPlayer);
		upPlayer->setDrawOrder(playerSortOrder);
		mPlayerID = upPlayer->getID();
		getSceneGraph().attachNode(std::move(upPlayer));

		mpCamera = std::make_unique<Camera>(getEntityManager(), mPlayerID, sf::Vector2f(16 * 24.f, 9 * 24.f));

		setTileMap(TileMap::make(*this, getTextureManager(), std::move(tmx)));
		getMap().setDrawColliderEnabled(true);
		getMap().setDrawNavGraphEnabled(true);

		// TODO: DELETE SECOND MAP
		auto upMap2 = TileMap::make(*this, getTextureManager(), TMX{fileName});
		upMap2->setDrawColliderEnabled(true);
		upMap2->setDrawNavGraphEnabled(true);
		getMap().stitch(sf::Vector2i{ 0, 0 }, *upMap2, sf::Vector2i{ 0, 20 });
		auto* pMap = upMap2.get();
		getMap().attachNode(std::move(upMap2));

		auto upMap3 = TileMap::make(*this, getTextureManager(), TMX{fileName});
		pMap->stitch({ 0, 0 }, *upMap3, { 30, 0 });
		getMap().attachNode(std::move(upMap3));

		//getMap().move({ -4, 0 });
	}
示例#19
0
void Node::remove() 
{
	LinkedListNode<Node>::remove();

	if (isInstanceNode() == false) {
		removeRoutes();
		removeSFNodes();
		removeInstanceNodes();

		if (isBindableNode()) {
			SceneGraph *sceneGraph = getSceneGraph();
			if (sceneGraph)
				sceneGraph->setBindableNode((BindableNode *)this, false);			
		}
	}

	setParentNode(NULL);
	setSceneGraph(NULL);
}
void SIM::Coin3D::Quarter::SoQTQuarterAdaptor::seekToPoint(const SbVec3f& scenepos)
{
    SbVec3f hitpoint(scenepos);

    m_camerastartposition = getSoRenderManager()->getCamera()->position.getValue();
    m_camerastartorient = getSoRenderManager()->getCamera()->orientation.getValue();

    // move point to the camera coordinate system, consider
    // transformations before camera in the scene graph
    SbMatrix cameramatrix, camerainverse;
    getCameraCoordinateSystem(getSoRenderManager()->getCamera(),
                              getSceneGraph(),
                              cameramatrix,
                              camerainverse);
    camerainverse.multVecMatrix(hitpoint, hitpoint);

    float fd = m_seekdistance;

    if(!m_seekdistanceabs)
        fd *= (hitpoint - getSoRenderManager()->getCamera()->position.getValue()).length()/100.0f;

    getSoRenderManager()->getCamera()->focalDistance = fd;

    SbVec3f dir = hitpoint - m_camerastartposition;
    dir.normalize();

    // find a rotation that rotates current camera direction into new
    // camera direction.
    SbVec3f olddir;
    getSoRenderManager()->getCamera()->orientation.getValue().multVec(SbVec3f(0, 0, -1), olddir);
    SbRotation diffrot(olddir, dir);
    m_cameraendposition = hitpoint - fd * dir;
    m_cameraendorient = getSoRenderManager()->getCamera()->orientation.getValue() * diffrot;

    if(m_seeksensor->isScheduled()) {
        m_seeksensor->unschedule();
        interactiveCountDec();
    }

    m_seeksensor->setBaseTime(SbTime::getTimeOfDay());
    m_seeksensor->schedule();
    interactiveCountInc();
}
示例#21
0
void ProximitySensorNode::update() 
{
	if (!isEnabled())
		return;

	SceneGraph *sg = getSceneGraph();
	if (!sg)
		return;

	ViewpointNode *vpoint = sg->getViewpointNode();
	if (vpoint == NULL)
		vpoint = sg->getDefaultViewpointNode();

	float vpos[3];
	vpoint->getPosition(vpos);

	float center[3];
	getCenter(center);

	float size[3];
	getSize(size);

	if (inRegion() == false) {
		if (isRegion(vpos, center, size) == true) {
			setInRegion(true);
			double time = GetCurrentSystemTime();
			setEnterTime(time);
			sendEvent(getEventOut(enterTimeFieldString));
			setIsActive(true);
			sendEvent(getEventOut(isActiveFieldString));
		}
	}
	else {
		if (isRegion(vpos, center, size) == false) {
			setInRegion(false);
			double time = GetCurrentSystemTime();
			setExitTime(time);
			sendEvent(getEventOut(exitTimeFieldString));
			setIsActive(false);
			sendEvent(getEventOut(isActiveFieldString));
		}
	}
}
示例#22
0
文件: Bar.cpp 项目: flair2005/inVRs
Bar::Bar(XMLNode *xml) : Widget(xml){
    float scale_x, scale_y, scale_z;
    const char *my_name;
    const char *label;
    char tmp[255];
    int i = 0;

    scale_x = xml->getAttributeValueAsFloat("scale_x", 1);
    scale_y = xml->getAttributeValueAsFloat("scale_y", 1);
    scale_z = xml->getAttributeValueAsFloat("scale_z", 1);
    SceneGraph *scene_bar = new SceneGraph();
    SceneGraph *temp_scene = new SceneGraph();
    temp_scene->loadModel("components/bar/base.wrl");
    temp_scene->setScale(scale_x, scale_y, scale_z);
    scene_bar->mergeScene(temp_scene);
    label = xml->getAttributeValue("label");
    if(label != NULL){
        my_name = label;
    }else{
        my_name = getName();
    }
    while(my_name[i] != '\0' && i < 20){
        // create new nodes
        temp_scene = new SceneGraph();
        // parse the current symbol / character
        if(my_name[i] != ' '){
            parse_symbol(tmp, my_name[i]);
            // read the component model, and move it to its destination coordinates
            temp_scene->loadModel(tmp);
            temp_scene->setTranslate(0.2+0.6*i,0.15,0);
            scene_bar->mergeScene(temp_scene);
        }
        i++;
    }
    const char *ani = xml->getAttributeValue ( "clickanimation" );
    if ( ani != NULL )
        animationName = new std::string(ani);
    else
        animationName = NULL;
    getSceneGraph()->mergeScene(scene_bar);
}
示例#23
0
void Node::removeInstanceNodes() 
{
	SceneGraph *sg = getSceneGraph();
	if (sg && isInstanceNode() == false) {
		Node *node = sg->getNodes();
		while (node) {
			Node *nextNode = node->nextTraversal();
			if (node->isInstanceNode() == true) {
				Node *refNode = node->getReferenceNode();
				while (refNode->isInstanceNode() == true)
					refNode = refNode->getReferenceNode();
				if (refNode == this) {
					node->deleteChildNodes();
					nextNode = node->nextTraversal();
					delete node;
				}
			}
			node = nextNode;
		}
	
	}
}
示例#24
0
Error DecalComponent::setLayer(CString texAtlasFname, CString texAtlasSubtexName, F32 blendFactor, LayerType type)
{
	Layer& l = m_layers[type];

	ANKI_CHECK(getSceneGraph().getResourceManager().loadResource(texAtlasFname, l.m_atlas));

	ANKI_CHECK(l.m_atlas->getSubTextureInfo(texAtlasSubtexName, &l.m_uv[0]));

	// Add a border to the UVs to avoid complex shader logic
	if(l.m_atlas->getSubTextureMargin() < ATLAS_SUB_TEXTURE_MARGIN)
	{
		ANKI_LOGE("Need texture atlas with margin at least %u", ATLAS_SUB_TEXTURE_MARGIN);
		return ErrorCode::USER_DATA;
	}

	Vec2 marginf = F32(ATLAS_SUB_TEXTURE_MARGIN / 2) / Vec2(l.m_atlas->getWidth(), l.m_atlas->getHeight());
	Vec2 minUv = l.m_uv.xy() - marginf;
	Vec2 sizeUv = (l.m_uv.zw() - l.m_uv.xy()) + 2.0f * marginf;
	l.m_uv = Vec4(minUv.x(), minUv.y(), minUv.x() + sizeUv.x(), minUv.y() + sizeUv.y());

	l.m_blendFactor = blendFactor;
	return ErrorCode::NONE;
}
示例#25
0
void Node::sendEvent(char *eventOutFieldString) {
	getSceneGraph()->updateRoute(this, getEventOut(eventOutFieldString));
}
示例#26
0
Checkbox::Checkbox(XMLNode *xml) : Widget(xml) {
    const char *my_name;
    const char *label;
    char tmp[255];
    int i = 0;
    selected = false;
    SceneGraph *scene_chkbox = new SceneGraph();
    SceneGraph *temp_scene = new SceneGraph();
    checked = new SceneGraph();

    // First, prepare the radiobox and the checked marker
    temp_scene->loadModel("components/chkbox/base.wrl");
    scene_chkbox->mergeScene(temp_scene);
    checked->loadModel("components/chkbox/checked.wrl");
    checked->setVisibility(selected);
    scene_chkbox->mergeScene(checked);
    temp_scene->loadModel("components/button/side_left.wrl");
    scene_chkbox->mergeScene(temp_scene);
    label = xml->getAttributeValue("label");
    if(label != NULL) {
        my_name = label;
    } else {
        my_name = getName();
    }
    // add the symbols / characters to the scene
    while(my_name[i] != '\0' && i < 19) {
        // create new nodes
        temp_scene = new SceneGraph();
        // parse the current symbol / character
        if(my_name[i] != ' ') {
            parse_symbol(tmp, my_name[i]);
            // read the component model, and move it to its destination coordinates
            temp_scene->loadModel(tmp);
            temp_scene->setTranslate(0.6*(i+1),0,0);
            scene_chkbox->mergeScene(temp_scene);
        }
        i++;
    }
    // add the base of the button
    temp_scene = new SceneGraph();
    temp_scene->loadModel("components/button/base.wrl");
    temp_scene->setScale(i+1,1,1);
    scene_chkbox->mergeScene(temp_scene);
    // add the right side of the button
    temp_scene = new SceneGraph();
    temp_scene->loadModel("components/button/side_right.wrl");
    temp_scene->setTranslate((0.6*(i)),0,0);
    scene_chkbox->mergeScene(temp_scene);
    getSceneGraph()->mergeScene(scene_chkbox);
    // Load the animation
    const char *ani = xml->getAttributeValue ( "clickanimation" );
    if ( ani != NULL )
        animationName = new std::string(ani);
    else
        animationName = NULL;
    // Load the callback functions
    ani = xml->getAttributeValue ( "callbackSelected" );
    if ( ani != NULL )
        callbackSelected = new std::string(ani);
    else
        callbackSelected = NULL;
    ani = xml->getAttributeValue ( "callbackDeselected" );
    if ( ani != NULL )
        callbackDeselected = new std::string(ani);
    else
        callbackDeselected = NULL;
}
示例#27
0
//==============================================================================
const EventManager& Event::getEventManager() const
{
	return getSceneGraph().getEventManager();
}
示例#28
0
void Node::moveChildNodeAtFirst(Node *node) {
	mChildNodes->addNodeAtFirst(node); 
	node->setParentNode(this);
	node->setSceneGraph(getSceneGraph());
}
示例#29
0
//==============================================================================
SpatialComponent::~SpatialComponent()
{
	getSceneGraph().getSectorGroup().spatialDeleted(this);
}
 //---------------------------
 const bool DocumentExporter::getExportSelectedOnly () const
 {
     return getSceneGraph ()->getExportSelectedOnly ();
 }