void World::RenderAllChunks() { viewerPosition = GetScene()->m_camera.m_position; // Enable arrays glEnable(GL_VERTEX_ARRAY); glEnable(GL_TEXTURE_COORD_ARRAY); glEnable(GL_NORMAL_ARRAY); for(int x = 0; x < m_chunksInX; x++) for(int y = 0; y < m_chunksInY; y++) for(int z = 0; z < m_chunksInZ; z++) if(!m_chunkMatrix[x][y][z].IsEmpty()) m_chunkMatrix[x][y][z].Draw(); VBO::Unbind(GL_ARRAY_BUFFER); // Disable arrays glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); }
void plSimulationMgr::UpdateAvatarInDetector(plKey world, plPXPhysical* detector) { // search thru the actors in a scene looking for avatars that might be in the newly enabled detector region // ... and then send appropiate collision message if needed if ( detector->DoDetectorHullWorkaround() ) { NxScene* scene = GetScene(world); if (scene) { uint32_t numActors = scene->getNbActors(); NxActor** actors = scene->getActors(); for (int i = 0; i < numActors; i++) { if ( actors[i]->userData == nil ) { // we go a controller bool isController; plPXPhysicalControllerCore* controller = plPXPhysicalControllerCore::GetController(*actors[i],&isController); if (controller && controller->IsEnabled()) { plKey avatar = controller->GetOwner(); plSceneObject* avObj = plSceneObject::ConvertNoRef(avatar->ObjectIsLoaded()); const plCoordinateInterface* ci; if ( avObj && ( ci = avObj->GetCoordinateInterface() ) ) { if ( detector->IsObjectInsideHull(ci->GetWorldPos()) ) { detector->SetInsideConvexHull(true); // we are entering this world... say we entered this detector ISendCollisionMsg(detector->GetObjectKey(), avatar, true); } } } } } } } }
// 生成一个捕捉后宠物的GUID BOOL PetManager::CreateGUIDOfPet(_PET_DB *pPetDB, ObjID_t idHuman, ObjID_t idPet) { __ENTER_FUNCTION Assert(idHuman != INVALID_ID && idPet != INVALID_ID && "PetManager::CreateGUIDOfPet"); if(idHuman == INVALID_ID || idPet == INVALID_ID) { return FALSE; } Obj_Human *pHuman; Obj_Pet *pPet; pHuman = GetScene()->GetHumanManager()->GetHuman(idHuman); pPet = GetPet(idPet); Assert(pHuman != NULL && pPet != NULL && "PetManager::CreateGUIDOfPet"); if(pHuman == NULL || pPet == NULL) { return FALSE; } PET_ATTR* pPetAttr = g_PetAttrTbl.GetAttr(pPet->GetDataID()); if (!pPetAttr) return FALSE; PET_GUID_t guidPet, guidSpouse; guidPet.Init(pHuman->GetGUID(), g_pTimeManager->CurrentTime()); guidSpouse.Reset(); pPetDB->m_GUID = guidPet; pPetDB->m_SpouseGUID = guidSpouse; return TRUE; __LEAVE_FUNCTION return FALSE; }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void State::OnInit() { GetScene()->SetClearColour(CS::Colour(0.9f, 0.9f, 0.9f, 1.0f)); m_httpRequestSystem = CS::Application::Get()->GetSystem<CS::HttpRequestSystem>(); CS_ASSERT(m_httpRequestSystem, "Cannot complete HttpRequest smoke test as the system could not be created!"); const u32 k_downloadBufferSize = 100 * 1024; m_httpRequestSystem->SetMaxBufferSize(k_downloadBufferSize); Common::OptionsMenuDesc optionsMenuDesc; optionsMenuDesc.AddButton("Test download progress", [=]() { //TODO: This doesn't work on iOS as HTTP requests aren't allowed. We need to find a file that can be downloaded over HTTPS for testing. m_downloadProgressTestSystem->StartDownloadTest("http://download.thinkbroadband.com/5MB.zip", [=](const CS::HttpResponse& in_completeResponse) { PresentHttpResponse(in_completeResponse); }); }); m_optionsMenuPresenter->Present(optionsMenuDesc); }
void UIComponent::OnNodeSet(Node* node) { rootElement_->SetNode(node); if (node) { auto* renderer = GetSubsystem<Renderer>(); auto* model = node->GetComponent<StaticModel>(); rootElement_->SetViewport(renderer->GetViewportForScene(GetScene(), viewportIndex_)); if (model == nullptr) model_ = model = node->CreateComponent<StaticModel>(); model->SetMaterial(material_); rootElement_->SetRenderTexture(texture_); } else { rootElement_->SetRenderTexture(nullptr); if (model_.NotNull()) { model_->Remove(); model_ = nullptr; } } }
void CSyncCoreObjectMediator::IntEndTransferObject() { if( !IsActive() ) StopFollowing(); //这里无需进行StopMoving,让下面的函数通过基类完成这个事情 if( m_pConn ) GetScene()->DelFromMulticast( m_pConn ); CSyncCoreObjectServer::IntEndTransferObject(); m_bDisbindingConn = false; m_fDirKnownMaxSpeed = 0; if( !m_pConn ) return; AddConnBlockCount(); SetClientMainScene(); CSyncCoreObjectServer::SetEyeSight( m_fZeroDimEyeSight, 0 ); }
void CollisionShape::OnNodeSet(Node* node) { if (node) { Scene* scene = GetScene(); if (scene) { if (scene == node) LOGWARNING(GetTypeName() + " should not be created to the root scene node"); physicsWorld_ = scene->GetOrCreateComponent<PhysicsWorld>(); physicsWorld_->AddCollisionShape(this); } else LOGERROR("Node is detached from scene, can not create collision shape"); node->AddListener(this); cachedWorldScale_ = node->GetWorldScale(); // Terrain collision shape depends on the terrain component's geometry updates. Subscribe to them SubscribeToEvent(node, E_TERRAINCREATED, HANDLER(CollisionShape, HandleTerrainCreated)); } }
void StaticModelGroup::ApplyAttributes() { if (!nodeIDsDirty_) return; // Remove all old instance nodes before searching for new. Can not call RemoveAllInstances() as that would modify // the ID list on its own for (unsigned i = 0; i < instanceNodes_.Size(); ++i) { Node* node = instanceNodes_[i]; if (node) node->RemoveListener(this); } instanceNodes_.Clear(); Scene* scene = GetScene(); if (scene) { // The first index stores the number of IDs redundantly. This is for editing for (unsigned i = 1; i < nodeIDsAttr_.Size(); ++i) { Node* node = scene->GetNode(nodeIDsAttr_[i].GetUInt()); if (node) { WeakPtr<Node> instanceWeak(node); node->AddListener(this); instanceNodes_.Push(instanceWeak); } } } worldTransforms_.Resize(instanceNodes_.Size()); nodeIDsDirty_ = false; OnMarkedDirty(GetNode()); }
void StaticModelGroup::ApplyAttributes() { if (!nodesDirty_) return; // Remove all old instance nodes before searching for new for (unsigned i = 0; i < instanceNodes_.Size(); ++i) { Node* node = instanceNodes_[i]; if (node) node->RemoveListener(this); } instanceNodes_.Clear(); Scene* scene = GetScene(); if (scene) { // The first index stores the number of IDs redundantly. This is for editing for (unsigned i = 1; i < nodeIDsAttr_.Size(); ++i) { Node* node = scene->GetNode(nodeIDsAttr_[i].GetUInt()); if (node) { WeakPtr<Node> instanceWeak(node); node->AddListener(this); instanceNodes_.Push(instanceWeak); } } } worldTransforms_.Resize(instanceNodes_.Size()); numWorldTransforms_ = 0; // Correct amount will be found during world bounding box update nodesDirty_ = false; OnMarkedDirty(GetNode()); }
void Vehicle::InitWheel(const String& name, const Vector3& offset, WeakPtr<Node>& wheelNode, unsigned& wheelNodeID) { ResourceCache* cache = GetSubsystem<ResourceCache>(); // Note: do not parent the wheel to the hull scene node. Instead create it on the root level and let the physics // constraint keep it together wheelNode = GetScene()->CreateChild(name); wheelNode->SetPosition(node_->LocalToWorld(offset)); wheelNode->SetRotation(node_->GetRotation() * (offset.x_ >= 0.0 ? Quaternion(0.0f, 0.0f, -90.0f) : Quaternion(0.0f, 0.0f, 90.0f))); wheelNode->SetScale(Vector3(0.8f, 0.5f, 0.8f)); // Remember the ID for serialization wheelNodeID = wheelNode->GetID(); StaticModel* wheelObject = wheelNode->CreateComponent<StaticModel>(); RigidBody* wheelBody = wheelNode->CreateComponent<RigidBody>(); CollisionShape* wheelShape = wheelNode->CreateComponent<CollisionShape>(); Constraint* wheelConstraint = wheelNode->CreateComponent<Constraint>(); wheelObject->SetModel(cache->GetResource<Model>("Models/Cylinder.mdl")); wheelObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml")); wheelObject->SetCastShadows(true); wheelShape->SetSphere(1.0f); wheelBody->SetFriction(1.0f); wheelBody->SetMass(1.0f); wheelBody->SetLinearDamping(0.2f); // Some air resistance wheelBody->SetAngularDamping(0.75f); // Could also use rolling friction wheelBody->SetCollisionLayer(1); wheelConstraint->SetConstraintType(CONSTRAINT_HINGE); wheelConstraint->SetOtherBody(GetComponent<RigidBody>()); // Connect to the hull body wheelConstraint->SetWorldPosition(wheelNode->GetPosition()); // Set constraint's both ends at wheel's location wheelConstraint->SetAxis(Vector3::UP); // Wheel rotates around its local Y-axis wheelConstraint->SetOtherAxis(offset.x_ >= 0.0 ? Vector3::RIGHT : Vector3::LEFT); // Wheel's hull axis points either left or right wheelConstraint->SetLowLimit(Vector2(-180.0f, 0.0f)); // Let the wheel rotate freely around the axis wheelConstraint->SetHighLimit(Vector2(180.0f, 0.0f)); wheelConstraint->SetDisableCollision(true); // Let the wheel intersect the vehicle hull }
void Player::Raycast(const GameContext& gameContext) { GameScene* scene = GetScene(); XMFLOAT3 pos = GetTransform()->GetPosition(); XMFLOAT3 fw = GetTransform()->GetForward(); PxVec3 rayOrigin(pos.x,pos.y + 1.f,pos.z), rayDirection(fw.x,fw.y,fw.z); rayOrigin.x += fw.x * 2.5f; rayOrigin.z += fw.z * 2.5f; const PxU32 bufSize = 20; PxRaycastHit hit[bufSize]; PxRaycastBuffer buf(hit, bufSize); // [out] Blocking and touching hits will be stored here if(scene->GetPhysxProxy()->Raycast(rayOrigin, rayDirection, 5000, buf)) { for(PxU32 i = 0; i < buf.nbTouches; ++i) { BaseComponent* component = static_cast<BaseComponent*>(buf.touches[i].actor->userData); GameObject* go = component->GetGameObject(); string name = go->GetName(); cout << "RAYCAST OBJECT: " << name << endl; if(name == "Enemy") { Enemy* enemy = reinterpret_cast<Enemy*>(go); int dmg = 12.5f; enemy->Damage(dmg); } } PxVec3 vel = rayDirection * 1000; auto laser = new Laser(XMFLOAT3(vel.x, vel.y, vel.z)); AddChild(laser); } }
void RigidBody2D::OnMarkedDirty(Node* node) { if (physicsWorld_ && physicsWorld_->IsApplyingTransforms()) return; // Physics operations are not safe from worker threads Scene* scene = GetScene(); if (scene && scene->IsThreadedUpdate()) { scene->DelayedMarkedDirty(this); return; } // Check if transform has changed from the last one set in ApplyWorldTransform() b2Vec2 newPosition = ToB2Vec2(node_->GetWorldPosition()); float newAngle = node_->GetWorldRotation().RollAngle() * M_DEGTORAD; if (newPosition != bodyDef_.position || newAngle != bodyDef_.angle) { bodyDef_.position = newPosition; bodyDef_.angle = newAngle; if (body_) body_->SetTransform(newPosition, newAngle); } }
void FPhATEdPreviewViewportClient::SimMouseMove(float DeltaX, float DeltaY) { DragX = Viewport->GetMouseX() - SharedData->LastClickPos.X; DragY = Viewport->GetMouseY() - SharedData->LastClickPos.Y; if (!SharedData->MouseHandle->GrabbedComponent) { return; } //We need to convert Pixel Delta into Screen position (deal with different viewport sizes) FSceneViewFamilyContext ViewFamily(FSceneViewFamily::ConstructionValues( Viewport, GetScene(), EngineShowFlags )); FSceneView* View = CalcSceneView(&ViewFamily); FVector4 ScreenOldPos = View->PixelToScreen(SharedData->LastClickPos.X, SharedData->LastClickPos.Y, 1.f); FVector4 ScreenNewPos = View->PixelToScreen(DragX + SharedData->LastClickPos.X, DragY + SharedData->LastClickPos.Y, 1.f); FVector4 ScreenDelta = ScreenNewPos - ScreenOldPos; FVector4 ProjectedDelta = View->ScreenToWorld(ScreenDelta); FVector4 WorldDelta; //Now we project new ScreenPos to xy-plane of SimGrabLocation FVector LocalOffset = View->ViewMatrices.ViewMatrix.TransformPosition(SimGrabLocation + SimGrabZ * SimGrabPush); float ZDistance = GetViewportType() == ELevelViewportType::LVT_Perspective ? fabs(LocalOffset.Z) : 1.f; //in the ortho case we don't need to do any fixup because there is no perspective WorldDelta = ProjectedDelta * ZDistance; //Now we convert back into WorldPos FVector WorldPos = SimGrabLocation + WorldDelta + SimGrabZ * SimGrabPush; FVector NewLocation = WorldPos; float QuickRadius = 5 - SimGrabPush / SimHoldDistanceChangeDelta; QuickRadius = QuickRadius < 2 ? 2 : QuickRadius; DrawDebugPoint(GetWorld(), NewLocation, QuickRadius, FColorList::Red, false, 0.3); SharedData->MouseHandle->SetTargetLocation(NewLocation); SharedData->MouseHandle->GrabbedComponent->WakeRigidBody(SharedData->MouseHandle->GrabbedBoneName); }
bool CubemapGenerator::InitRender() { sceneEditor_ = GetSceneEditor(); if (sceneEditor_.Null()) { LOGERROR("CubemapGenerator::InitRender - unable to get scene editor"); return false; } if (!InitPaths()) return false; cameraNode_ = node_->CreateChild("CubeMapRenderCamera"); cameraNode_->SetTemporary(true); camera_ = cameraNode_->CreateComponent<Camera>(); camera_->SetTemporary(true); camera_->SetFov(90.0f); camera_->SetNearClip(0.0001f); camera_->SetAspectRatio(1.0f); RenderPath* renderPath = sceneEditor_->GetSceneView3D()->GetViewport()->GetRenderPath(); viewport_ = new Viewport(context_, GetScene(), camera_, renderPath); renderImage_ = new Texture2D(context_); renderImage_->SetSize(imageSize_, imageSize_, Graphics::GetRGBAFormat(), TEXTURE_RENDERTARGET); renderSurface_ = renderImage_->GetRenderSurface(); renderSurface_->SetViewport(0, viewport_); renderSurface_->SetUpdateMode(SURFACE_UPDATEALWAYS); return true; }
void RigidBody::OnNodeSet(Node* node) { if (node) { Scene* scene = GetScene(); if (scene) { if (scene == node) LOGWARNING(GetTypeName() + " should not be created to the root scene node"); physicsWorld_ = scene->GetComponent<PhysicsWorld>(); if (physicsWorld_) physicsWorld_->AddRigidBody(this); else LOGERROR("No physics world component in scene, can not create rigid body"); AddBodyToWorld(); } else LOGERROR("Node is detached from scene, can not create rigid body"); node->AddListener(this); } }
void Node::SetNetParentAttr(const PODVector<unsigned char>& value) { Scene* scene = GetScene(); if (!scene) return; MemoryBuffer buf(value); // If nothing in the buffer, parent is the root node if (buf.IsEof()) { scene->AddChild(this); return; } unsigned baseNodeID = buf.ReadNetID(); Node* baseNode = scene->GetNode(baseNodeID); if (!baseNode) { LOGWARNING("Failed to find parent node " + String(baseNodeID)); return; } // If buffer contains just an ID, the parent is replicated and we are done if (buf.IsEof()) baseNode->AddChild(this); else { // Else the parent is local and we must find it recursively by name hash StringHash nameHash = buf.ReadStringHash(); Node* parentNode = baseNode->GetChild(nameHash, true); if (!parentNode) LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString()); else parentNode->AddChild(this); } }
//------------------------------------------------------------- //------------------------------------------------------------- void Entity::AddComponent(const ComponentSPtr& in_component) { CS_ASSERT(in_component != nullptr, "Cannot add null component"); CS_ASSERT(in_component->GetEntity() == nullptr, "Component cannot be attached to more than 1 entity at a time."); m_components.push_back(in_component); in_component->SetEntity(this); in_component->OnAddedToEntity(); if(GetScene() != nullptr) { in_component->OnAddedToScene(); if (m_appActive == true) { in_component->OnResume(); if (m_appForegrounded == true) { in_component->OnForeground(); } } } }
void FPreviewScene::AddComponent(UActorComponent* Component,const FTransform& LocalToWorld) { Components.AddUnique(Component); USceneComponent* SceneComp = Cast<USceneComponent>(Component); if(SceneComp && SceneComp->GetAttachParent() == NULL) { SceneComp->SetRelativeTransform(LocalToWorld); } Component->RegisterComponentWithWorld(GetWorld()); if (bForceAllUsedMipsResident) { // Add a mip streaming override to the new mesh UMeshComponent* pMesh = Cast<UMeshComponent>(Component); if (pMesh != NULL) { pMesh->SetTextureForceResidentFlag(true); } } GetScene()->UpdateSpeedTreeWind(0.0); }
void Layer::EndDrawing() { m_commonObject->EndDrawing(); if (m_postEffects.size() > 0) { for (auto& p : m_postEffects) { GetScene()->m_coreScene->BeginPostEffect(p->GetCoreObject()); GetScene()->m_coreScene->GetSrcTarget()->AddRef(); GetScene()->m_coreScene->GetDstTarget()->AddRef(); auto src = CreateSharedPtrWithReleaseDLL(GetScene()->m_coreScene->GetSrcTarget()); auto dst = CreateSharedPtrWithReleaseDLL(GetScene()->m_coreScene->GetDstTarget()); p->OnDraw(dst, src); GetScene()->m_coreScene->EndPostEffect(p->GetCoreObject()); } } }
BabylonCamera::BabylonCamera(BabylonNode& babnode) { auto node = babnode.fbxNode(); std::string ansiName = node->GetName(); name = std::wstring(ansiName.begin(), ansiName.end()); id = getNodeId(node); auto parent = node->GetParent(); if (parent) { parentId = getNodeId(parent); } auto camera = node->GetCamera(); if (!camera) { return; } type = L"FreeCamera"; auto targetNode = node->GetTarget(); if (targetNode) { lockedTargetId = getNodeId(targetNode); } else { target = camera->InterestPosition.Get(); } position = babnode.localTranslate(); rotationQuaternion = babnode.localRotationQuat(); fov = camera->FieldOfViewY * Euler2Rad; minZ = camera->FrontPlaneDistance.Get(); maxZ = camera->BackPlaneDistance.Get(); auto hasAnimStack = node->GetScene()->GetSrcObjectCount<FbxAnimStack>() > 0; if (!hasAnimStack){ return; } auto animStack = node->GetScene()->GetSrcObject<FbxAnimStack>(0); FbxString animStackName = animStack->GetName(); FbxTakeInfo* takeInfo = node->GetScene()->GetTakeInfo(animStackName); auto animTimeMode = GlobalSettings::Current().AnimationsTimeMode; auto animFrameRate = GlobalSettings::Current().AnimationsFrameRate(); auto startFrame = takeInfo->mLocalTimeSpan.GetStart().GetFrameCount(animTimeMode); auto endFrame = takeInfo->mLocalTimeSpan.GetStop().GetFrameCount(animTimeMode); auto animLengthInFrame = endFrame - startFrame + 1; auto posAnim = std::make_shared<BabylonAnimation<babylon_vector3>>(BabylonAnimationBase::loopBehavior_Cycle, animFrameRate, L"position", L"position", true, 0, animLengthInFrame, true); auto rotAnim = std::make_shared<BabylonAnimation<babylon_vector4>>(BabylonAnimationBase::loopBehavior_Cycle, animFrameRate, L"rotation", L"rotation", true, 0, animLengthInFrame, true); auto targetAnim = std::make_shared<BabylonAnimation<babylon_vector3>>(BabylonAnimationBase::loopBehavior_Cycle, animFrameRate, L"target", L"target", true, 0, animLengthInFrame, true); for (auto ix = 0ll; ix < animLengthInFrame; ix++){ FbxTime currTime; currTime.SetFrame(startFrame + ix, animTimeMode); babylon_animation_key<babylon_vector3> poskey; babylon_animation_key<babylon_vector4> rotkey; poskey.frame = ix; rotkey.frame = ix; poskey.values = babnode.localTranslate(currTime); rotkey.values = babnode.localRotationQuat(currTime); posAnim->appendKey(poskey); rotAnim->appendKey(rotkey); if (lockedTargetId.size() == 0){ babylon_animation_key<babylon_vector3> targetKey; targetKey.frame = ix; targetKey.values = camera->InterestPosition.EvaluateValue(currTime); targetAnim->appendKey(targetKey); } } if (!posAnim->isConstant()){ animations.push_back(posAnim); } if (!rotAnim->isConstant()){ quatAnimations.push_back(rotAnim); } if (!targetAnim->isConstant()){ animations.push_back(targetAnim); } }
bool SceneObject_Door::Create(const std::string &doorModelName, const Vec3f &pos, float angle, bool openCW) { assert(!m_created); Scene* pScene = GetScene(); assert(pScene != NULL); Asset* pDoorModelAsset; if(!pScene->GetAssetManager_AutoCreate("modelOBJ", Model_OBJ::Asset_Factory)->GetAsset(doorModelName, pDoorModelAsset)) return false; m_pDoorModel = static_cast<Model_OBJ*>(pDoorModelAsset); m_pDoorModel->SetRenderer(GetScene()); // Default texture setting: nearest filtering for(unsigned int i = 0, size = m_pDoorModel->GetNumMaterials(); i < size; i++) { Model_OBJ::Material* pMat = m_pDoorModel->GetMaterial(i); pMat->m_pDiffuseMap->Bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if(pMat->m_pSpecularMap != NULL) { pMat->m_pSpecularMap->Bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } if(pMat->m_pNormalMap != NULL) { pMat->m_pNormalMap->Bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } } // Sound effects SoundSystem* pSoundSystem = static_cast<SoundSystem*>(pScene->GetNamed_Effect("sndsys")); assert(pSoundSystem != NULL); Asset* pAsset; if(!pSoundSystem->m_sound_effect_manager.GetAsset("data/sounds/doorOpen.wav", pAsset)) abort(); m_pOpenSoundEffect = static_cast<Sound_Effect*>(pAsset); assert(m_pOpenSoundEffect != NULL); if(!pSoundSystem->m_sound_effect_manager.GetAsset("data/sounds/doorClose.wav", pAsset)) abort(); m_pCloseSoundEffect = static_cast<Sound_Effect*>(pAsset); assert(m_pCloseSoundEffect != NULL); m_pos = pos; m_angle = angle; m_openCW = openCW; RegenAABB(); // Set up sound source m_doorSource.SetPosition(m_pos); m_doorSource.SetVelocity(Vec3f(0.0f, 0.0f, 0.0f)); m_doorSource.SetGain(1.0f); m_doorSource.SetLooping(false); m_created = true; return true; }
void SceneObject_Door::Logic() { switch(m_action) { case e_opening: if(m_openCW) { float endAngle = m_initAngle - pif_over_2; m_angle -= s_openAndCloseSpeed * GetScene()->m_frameTimer.GetTimeMultiplier(); if(m_angle < endAngle) { m_angle = endAngle; m_action = e_none; m_state = e_open; } RegenAABB(); } else { float endAngle = m_initAngle + pif_over_2; m_angle += s_openAndCloseSpeed * GetScene()->m_frameTimer.GetTimeMultiplier(); if(m_angle > endAngle) { m_angle = endAngle; m_action = e_none; m_state = e_open; } RegenAABB(); } break; case e_closing: if(m_openCW) { m_angle += s_openAndCloseSpeed * GetScene()->m_frameTimer.GetTimeMultiplier(); if(m_angle > m_initAngle) { m_angle = m_initAngle; m_action = e_none; m_state = e_closed; } RegenAABB(); } else { m_angle -= s_openAndCloseSpeed * GetScene()->m_frameTimer.GetTimeMultiplier(); if(m_angle < m_initAngle) { m_angle = m_initAngle; m_action = e_none; m_state = e_closed; } RegenAABB(); } break; } }
void RaycastVehicle::Init() { hullBody_ = node_->GetOrCreateComponent<RigidBody>(); Scene* scene = GetScene(); vehicleData_->Init(scene, hullBody_); }
void RaycastVehicle::ApplyAttributes() { int index = 0; hullBody_ = node_->GetOrCreateComponent<RigidBody>(); Scene* scene = GetScene(); vehicleData_->Init(scene, hullBody_); VariantVector& value = loadedWheelData_; int numObjects = value[index++].GetInt(); int wheelIndex = 0; origRotation_.Clear(); skidInfoCumulative_.Clear(); wheelSideSlipSpeed_.Clear(); for (int i = 0; i < numObjects; i++) { int node_id = value[index++].GetInt(); Vector3 direction = value[index++].GetVector3(); Vector3 axle = value[index++].GetVector3(); float restLength = value[index++].GetFloat(); float radius = value[index++].GetFloat(); bool isFrontWheel = value[index++].GetBool(); float steering = value[index++].GetFloat(); Vector3 connectionPoint = value[index++].GetVector3(); Quaternion origRotation = value[index++].GetQuaternion(); float skidInfoC = value[index++].GetFloat(); float sideSlipSpeed = value[index++].GetFloat(); bool isContact = value[index++].GetBool(); Vector3 contactPosition = value[index++].GetVector3(); Vector3 contactNormal = value[index++].GetVector3(); float suspensionStiffness = value[index++].GetFloat(); float dampingRelaxation = value[index++].GetFloat(); float dampingCompression = value[index++].GetFloat(); float frictionSlip = value[index++].GetFloat(); float rollInfluence = value[index++].GetFloat(); float engineForce = value[index++].GetFloat(); float brake = value[index++].GetFloat(); float skidInfo = value[index++].GetFloat(); Node* wheelNode = GetScene()->GetNode(node_id); if (!wheelNode) { URHO3D_LOGERROR("RaycastVehicle: Incorrect node id = " + String(node_id) + " index: " + String(index)); continue; } btRaycastVehicle* vehicle = vehicleData_->Get(); int id = GetNumWheels(); btVector3 connectionPointCS0(connectionPoint.x_, connectionPoint.y_, connectionPoint.z_); btVector3 wheelDirectionCS0(direction.x_, direction.y_, direction.z_); btVector3 wheelAxleCS(axle.x_, axle.y_, axle.z_); btWheelInfo& wheel = vehicle->addWheel(connectionPointCS0, wheelDirectionCS0, wheelAxleCS, restLength, radius, vehicleData_->tuning_, isFrontWheel); wheelNodes_.Push(wheelNode); origRotation_.Push(origRotation); skidInfoCumulative_.Push(skidInfoC); wheelSideSlipSpeed_.Push(sideSlipSpeed); SetSteeringValue(wheelIndex, steering); wheel.m_raycastInfo.m_isInContact = isContact; wheel.m_raycastInfo.m_contactNormalWS = btVector3(contactNormal.x_, contactNormal.y_, contactNormal.z_); wheel.m_raycastInfo.m_contactPointWS = btVector3(contactPosition.x_, contactPosition.y_, contactPosition.z_); wheel.m_suspensionStiffness = suspensionStiffness; wheel.m_wheelsDampingRelaxation = dampingRelaxation; wheel.m_wheelsDampingCompression = dampingCompression; wheel.m_frictionSlip = frictionSlip; wheel.m_rollInfluence = rollInfluence; wheel.m_engineForce = engineForce; wheel.m_brake = brake; wheel.m_skidInfo = skidInfo; wheelIndex++; } URHO3D_LOGDEBUG("maxSideSlipSpeed_ value: " + String(maxSideSlipSpeed_)); URHO3D_LOGDEBUG("loaded items: " + String(index)); URHO3D_LOGDEBUG("loaded wheels: " + String(GetNumWheels())); }
void FJavascriptUMGViewportClient::Draw(FViewport* InViewport, FCanvas* Canvas) { FViewport* ViewportBackup = Viewport; Viewport = InViewport ? InViewport : Viewport; // Determine whether we should use world time or real time based on the scene. float TimeSeconds; float RealTimeSeconds; float DeltaTimeSeconds; const bool bIsRealTime = true; UWorld* World = GWorld; if ((GetScene() != World->Scene) || (bIsRealTime == true)) { // Use time relative to start time to avoid issues with float vs double TimeSeconds = FApp::GetCurrentTime() - GStartTime; RealTimeSeconds = FApp::GetCurrentTime() - GStartTime; DeltaTimeSeconds = FApp::GetDeltaTime(); } else { TimeSeconds = World->GetTimeSeconds(); RealTimeSeconds = World->GetRealTimeSeconds(); DeltaTimeSeconds = World->GetDeltaSeconds(); } // Setup a FSceneViewFamily/FSceneView for the viewport. FSceneViewFamilyContext ViewFamily(FSceneViewFamily::ConstructionValues( Canvas->GetRenderTarget(), GetScene(), EngineShowFlags) .SetWorldTimes(TimeSeconds, DeltaTimeSeconds, RealTimeSeconds) .SetRealtimeUpdate(bIsRealTime)); ViewFamily.EngineShowFlags = EngineShowFlags; //UpdateLightingShowFlags(ViewFamily.EngineShowFlags); //ViewFamily.ExposureSettings = ExposureSettings; //ViewFamily.LandscapeLODOverride = LandscapeLODOverride; FSceneView* View = CalcSceneView(&ViewFamily); //SetupViewForRendering(ViewFamily, *View); FSlateRect SafeFrame; View->CameraConstrainedViewRect = View->UnscaledViewRect; //if ( CalculateEditorConstrainedViewRect(SafeFrame, Viewport) ) //{ // View->CameraConstrainedViewRect = FIntRect(SafeFrame.Left, SafeFrame.Top, SafeFrame.Right, SafeFrame.Bottom); //} if (IsAspectRatioConstrained()) { // Clear the background to black if the aspect ratio is constrained, as the scene view won't write to all pixels. Canvas->Clear(FLinearColor::Black); } Canvas->Clear(BackgroundColor); // workaround for hacky renderer code that uses GFrameNumber to decide whether to resize render targets --GFrameNumber; GetRendererModule().BeginRenderingViewFamily(Canvas, &ViewFamily); Viewport = ViewportBackup; }
void Character2D::Update(float timeStep) { // Handle wounded/killed states if (killed_) return; if (wounded_) { HandleWoundedState(timeStep); return; } // Set temporary variables auto* input = GetSubsystem<Input>(); auto* body = GetComponent<RigidBody2D>(); auto* animatedSprite = GetComponent<AnimatedSprite2D>(); bool onGround = false; bool jump = false; // Collision detection (AABB query) Vector2 characterHalfSize = Vector2(0.16f, 0.16f); auto* physicsWorld = GetScene()->GetComponent<PhysicsWorld2D>(); PODVector<RigidBody2D*> collidingBodies; physicsWorld->GetRigidBodies(collidingBodies, Rect(node_->GetWorldPosition2D() - characterHalfSize - Vector2(0.0f, 0.1f), node_->GetWorldPosition2D() + characterHalfSize)); if (collidingBodies.Size() > 1 && !isClimbing_) onGround = true; // Set direction Vector2 moveDir = Vector2::ZERO; // Reset if (input->GetKeyDown(KEY_A) || input->GetKeyDown(KEY_LEFT)) { moveDir = moveDir + Vector2::LEFT; animatedSprite->SetFlipX(false); // Flip sprite (reset to default play on the X axis) } if (input->GetKeyDown(KEY_D) || input->GetKeyDown(KEY_RIGHT)) { moveDir = moveDir + Vector2::RIGHT; animatedSprite->SetFlipX(true); // Flip sprite (flip animation on the X axis) } // Jump if ((onGround || aboveClimbable_) && (input->GetKeyPress(KEY_W) || input->GetKeyPress(KEY_UP))) jump = true; // Climb if (isClimbing_) { if (!aboveClimbable_ && (input->GetKeyDown(KEY_UP) || input->GetKeyDown(KEY_W))) moveDir = moveDir + Vector2(0.0f, 1.0f); if (input->GetKeyDown(KEY_DOWN) || input->GetKeyDown(KEY_S)) moveDir = moveDir + Vector2(0.0f, -1.0f); } // Move if (!moveDir.Equals(Vector2::ZERO) || jump) { if (onSlope_) body->ApplyForceToCenter(moveDir * MOVE_SPEED / 2, true); // When climbing a slope, apply force (todo: replace by setting linear velocity to zero when will work) else node_->Translate(Vector3(moveDir.x_, moveDir.y_, 0) * timeStep * 1.8f); if (jump) body->ApplyLinearImpulse(Vector2(0.0f, 0.17f) * MOVE_SPEED, body->GetMassCenter(), true); } // Animate if (input->GetKeyDown(KEY_SPACE)) { if (animatedSprite->GetAnimation() != "attack") { animatedSprite->SetAnimation("attack", LM_FORCE_LOOPED); animatedSprite->SetSpeed(1.5f); } } else if (!moveDir.Equals(Vector2::ZERO)) { if (animatedSprite->GetAnimation() != "run") animatedSprite->SetAnimation("run"); } else if (animatedSprite->GetAnimation() != "idle") { animatedSprite->SetAnimation("idle"); } }
BabylonMesh::BabylonMesh(BabylonNode* node) : BabylonAbstractMesh(node), _isEnabled(true), _isVisible(true), _billboardMode(0), _visibility(1), _skeletonId(-1), _pickable(true), _hasVertexAlpha(false), _checkCollision(false), _receiveShadows(false), _infiniteDistance(false), _autoAnimate(false), _autoAnimateFrom(0), _autoAnimateTo(0), _autoAnimateLoop(false), _showBoundingBox(false), _showSubMeshesBoundingBox(false), _applyFog(false), _alphaIndex(0) { pivotMatrix.SetIdentity(); auto fbxNode = node->fbxNode(); std::string ansiName = fbxNode->GetName(); name(std::wstring(ansiName.begin(), ansiName.end())); id(getNodeId(fbxNode)); auto parent = fbxNode->GetParent(); if (parent) { parentId(getNodeId(parent)); } pivotMatrix = ConvertToBabylonCoordinateSystem( GetGeometryTransformation(fbxNode)); auto animStack = fbxNode->GetScene()->GetSrcObject<FbxAnimStack>(0); FbxString animStackName = animStack->GetName(); FbxTakeInfo* takeInfo = fbxNode->GetScene()->GetTakeInfo(animStackName); auto animTimeMode = GlobalSettings::Current().AnimationsTimeMode; auto animFrameRate = GlobalSettings::Current().AnimationsFrameRate(); auto startFrame = takeInfo->mLocalTimeSpan.GetStart().GetFrameCount(animTimeMode); auto endFrame = takeInfo->mLocalTimeSpan.GetStop().GetFrameCount(animTimeMode); auto animLengthInFrame = endFrame - startFrame + 1; _visibility = static_cast<float>(node->fbxNode()->Visibility.Get()); auto posAnim = std::make_shared<BabylonAnimation<babylon_vector3>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), L"position", L"position", true, 0, static_cast<int>(animLengthInFrame), true); auto rotAnim = std::make_shared<BabylonAnimation<babylon_vector4>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), L"rotationQuaternion", L"rotationQuaternion", true, 0, static_cast<int>(animLengthInFrame), true); auto scaleAnim = std::make_shared<BabylonAnimation<babylon_vector3>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), L"scaling", L"scaling", true, 0, static_cast<int>(animLengthInFrame), true); auto visibilityAnim = std::make_shared<BabylonAnimation<float>>(BabylonAnimationBase::loopBehavior_Cycle, static_cast<int>(animFrameRate), L"visibility", L"visibility", true, 0, static_cast<int>(animLengthInFrame), true); auto mesh = fbxNode->GetMesh(); _isVisible = fbxNode->Show.Get(); auto rotCurveNode = fbxNode->LclRotation.GetCurveNode(); auto translateCurveNode = fbxNode->LclTranslation.GetCurveNode(); auto scalingCurveNode = fbxNode->LclScaling.GetCurveNode(); auto visibilityCurveNode = fbxNode->Visibility.GetCurveNode(); if (rotCurveNode || translateCurveNode || scalingCurveNode) { for (auto ix = 0; ix < animLengthInFrame; ix++) { FbxTime currTime; currTime.SetFrame(startFrame + ix, animTimeMode); babylon_animation_key<babylon_vector3> poskey; babylon_animation_key<babylon_vector4> rotkey; babylon_animation_key<babylon_vector3> scalekey; poskey.frame = ix; rotkey.frame = ix; scalekey.frame = ix; auto currTransform = node->GetLocal(currTime); poskey.values = currTransform.translation(); rotkey.values = currTransform.rotationQuaternion(); scalekey.values = currTransform.scaling(); posAnim->appendKey(poskey); rotAnim->appendKey(rotkey); scaleAnim->appendKey(scalekey); } } if (visibilityCurveNode) { for (auto ix = 0; ix < animLengthInFrame; ix++) { FbxTime currTime; currTime.SetFrame(startFrame + ix, animTimeMode); babylon_animation_key<float> visibilityKey; visibilityKey.frame = ix; visibilityKey.values = static_cast<float>(node->fbxNode()->Visibility.EvaluateValue(currTime)); visibilityAnim->appendKey(visibilityKey); } } if (!posAnim->isConstant()){ animations.push_back(posAnim); } if (!rotAnim->isConstant()){ animations.push_back(rotAnim); } if (!scaleAnim->isConstant()){ animations.push_back(scaleAnim); } if (!visibilityAnim->isConstant()) { animations.push_back(visibilityAnim); } if (!mesh) { return; } if (mesh->GetPolygonCount() == 0){ return; } _receiveShadows = mesh->ReceiveShadow.Get(); FbxGeometryConverter conv(mesh->GetFbxManager()); conv.ComputePolygonSmoothingFromEdgeSmoothing(mesh); if (!mesh->IsTriangleMesh()) { mesh = (FbxMesh*) conv.Triangulate(mesh, true); } mesh->RemoveBadPolygons(); mesh->GenerateNormals(); FbxStringList uvSetNameList; mesh->GetUVSetNames(uvSetNameList); std::vector<std::string> uniqueUVSets; int uvCount = uvSetNameList.GetCount(); for (int i = 0; i < uvCount; ++i) { std::string value = uvSetNameList.GetStringAt(i); if (std::find(uniqueUVSets.begin(), uniqueUVSets.end(), value) == uniqueUVSets.end()) { uniqueUVSets.push_back(value); } } uvsets = uniqueUVSets; bool hasUv = uniqueUVSets.size() > 0; bool hasUv2 = uniqueUVSets.size() > 1; bool hasUv3 = uniqueUVSets.size() > 2; bool hasUv4 = uniqueUVSets.size() > 3; bool hasUv5 = uniqueUVSets.size() > 4; bool hasUv6 = uniqueUVSets.size() > 5; std::string uvSetName; std::string uv2SetName; std::string uv3SetName; std::string uv4SetName; std::string uv5SetName; std::string uv6SetName; if (hasUv) { uvSetName = uniqueUVSets[0]; } if (hasUv2) { uv2SetName = uniqueUVSets[1]; } if (hasUv3) { uv3SetName = uniqueUVSets[2]; } if (hasUv4) { uv4SetName = uniqueUVSets[3]; } if (hasUv5) { uv5SetName = uniqueUVSets[4]; } if (hasUv6) { uv6SetName = uniqueUVSets[5]; } auto colors = mesh->GetElementVertexColor(); FbxLayerElement::EMappingMode colorMappingMode; FbxLayerElement::EReferenceMode colorReferenceMode; if (colors) { colorMappingMode = colors->GetMappingMode(); colorReferenceMode = colors->GetReferenceMode(); } auto normals = mesh->GetElementNormal(); FbxGeometryElementUV* uvs = nullptr; FbxGeometryElementUV* uvs2 = nullptr; FbxGeometryElementUV* uvs3 = nullptr; FbxGeometryElementUV* uvs4 = nullptr; FbxGeometryElementUV* uvs5 = nullptr; FbxGeometryElementUV* uvs6 = nullptr; FbxLayerElement::EMappingMode uvsMappingMode; FbxLayerElement::EReferenceMode uvsReferenceMode; FbxLayerElement::EMappingMode uvs2MappingMode; FbxLayerElement::EReferenceMode uvs2ReferenceMode; FbxLayerElement::EMappingMode uvs3MappingMode; FbxLayerElement::EReferenceMode uvs3ReferenceMode; FbxLayerElement::EMappingMode uvs4MappingMode; FbxLayerElement::EReferenceMode uvs4ReferenceMode; FbxLayerElement::EMappingMode uvs5MappingMode; FbxLayerElement::EReferenceMode uvs5ReferenceMode; FbxLayerElement::EMappingMode uvs6MappingMode; FbxLayerElement::EReferenceMode uvs6ReferenceMode; if (hasUv) { uvs = mesh->GetElementUV(uvSetName.c_str()); uvsMappingMode = uvs->GetMappingMode(); uvsReferenceMode = uvs->GetReferenceMode(); } if (hasUv2) { uvs2 = mesh->GetElementUV(uv2SetName.c_str()); uvs2MappingMode = uvs2->GetMappingMode(); uvs2ReferenceMode = uvs2->GetReferenceMode(); } if (hasUv3) { uvs3 = mesh->GetElementUV(uv3SetName.c_str()); uvs3MappingMode = uvs3->GetMappingMode(); uvs3ReferenceMode = uvs3->GetReferenceMode(); } if (hasUv4) { uvs4 = mesh->GetElementUV(uv4SetName.c_str()); uvs4MappingMode = uvs4->GetMappingMode(); uvs4ReferenceMode = uvs4->GetReferenceMode(); } if (hasUv5) { uvs5 = mesh->GetElementUV(uv5SetName.c_str()); uvs5MappingMode = uvs5->GetMappingMode(); uvs5ReferenceMode = uvs5->GetReferenceMode(); } if (hasUv6) { uvs6 = mesh->GetElementUV(uv6SetName.c_str()); uvs6MappingMode = uvs6->GetMappingMode(); uvs6ReferenceMode = uvs6->GetReferenceMode(); } auto normalMappingMode = normals->GetMappingMode(); auto normalReferenceMode = normals->GetReferenceMode(); std::vector<SubmeshData> submeshes; auto materialCount = node->fbxNode()->GetMaterialCount(); if (materialCount == 0) { materialCount = 1; } submeshes.resize(materialCount); auto baseLayer = mesh->GetLayer(0); auto materials = baseLayer->GetMaterials(); FbxLayerElement::EMappingMode materialMappingMode = materials ? materials->GetMappingMode() : FbxLayerElement::eByPolygon; // extract deformers SkinInfo skinInfo(fbxNode); if (skinInfo.hasSkin()){ associatedSkeleton = std::make_shared<BabylonSkeleton>(); skinInfo.buildBabylonSkeleton(*associatedSkeleton); } auto triangleCount = mesh->GetPolygonCount(); for (int triangleIndex = 0; triangleIndex < triangleCount; ++triangleIndex) { int materialIndex = 0; if (materialCount > 0 && materials) { switch (materialMappingMode) { case FbxLayerElement::eAllSame: materialIndex = materials->GetIndexArray().GetAt(0); break; case FbxLayerElement::eByPolygon: materialIndex = materials->GetIndexArray().GetAt(triangleIndex); } } auto& submesh = submeshes[materialIndex]; triangle t; for (int cornerIndex = 0; cornerIndex < 3; ++cornerIndex) { auto controlPointIndex = mesh->GetPolygonVertex(triangleIndex, cornerIndex); auto vertexIndex = triangleIndex * 3 + cornerIndex; auto position = mesh->GetControlPoints()[controlPointIndex]; position[2] = -position[2]; BabylonVertex v; v.position = position; if (normals) { int normalMapIndex = (normalMappingMode == FbxLayerElement::eByControlPoint) ? controlPointIndex : vertexIndex; int normalValueIndex = (normalReferenceMode == FbxLayerElement::eDirect) ? normalMapIndex : normals->GetIndexArray().GetAt(normalMapIndex); v.normal = normals->GetDirectArray().GetAt(normalValueIndex); v.normal.z = -v.normal.z; } if (colors) { int mappingIndex = (colorMappingMode == FbxLayerElement::eByControlPoint) ? controlPointIndex : vertexIndex; int valueIndex = (colorReferenceMode == FbxLayerElement::eDirect) ? mappingIndex : colors->GetIndexArray().GetAt(mappingIndex); v.color = colors->GetDirectArray().GetAt(valueIndex); } if (uvs) { int mappingIndex = (uvsMappingMode == FbxLayerElement::eByControlPoint) ? controlPointIndex : vertexIndex; int valueIndex = (uvsReferenceMode == FbxLayerElement::eDirect) ? mappingIndex : uvs->GetIndexArray().GetAt(mappingIndex); v.uv = uvs->GetDirectArray().GetAt(valueIndex); //v.uv.y = 1 - v.uv.y; } if (uvs2) { int mappingIndex = (uvs2MappingMode == FbxLayerElement::eByControlPoint) ? controlPointIndex : vertexIndex; int valueIndex = (uvs2ReferenceMode == FbxLayerElement::eDirect) ? mappingIndex : uvs2->GetIndexArray().GetAt(mappingIndex); v.uv2 = uvs2->GetDirectArray().GetAt(valueIndex); } if (uvs3) { int mappingIndex = (uvs3MappingMode == FbxLayerElement::eByControlPoint) ? controlPointIndex : vertexIndex; int valueIndex = (uvs3ReferenceMode == FbxLayerElement::eDirect) ? mappingIndex : uvs3->GetIndexArray().GetAt(mappingIndex); v.uv3 = uvs3->GetDirectArray().GetAt(valueIndex); } if (uvs4) { int mappingIndex = (uvs4MappingMode == FbxLayerElement::eByControlPoint) ? controlPointIndex : vertexIndex; int valueIndex = (uvs4ReferenceMode == FbxLayerElement::eDirect) ? mappingIndex : uvs4->GetIndexArray().GetAt(mappingIndex); v.uv4 = uvs4->GetDirectArray().GetAt(valueIndex); } if (uvs5) { int mappingIndex = (uvs5MappingMode == FbxLayerElement::eByControlPoint) ? controlPointIndex : vertexIndex; int valueIndex = (uvs5ReferenceMode == FbxLayerElement::eDirect) ? mappingIndex : uvs5->GetIndexArray().GetAt(mappingIndex); v.uv5 = uvs5->GetDirectArray().GetAt(valueIndex); } if (uvs6) { int mappingIndex = (uvs6MappingMode == FbxLayerElement::eByControlPoint) ? controlPointIndex : vertexIndex; int valueIndex = (uvs6ReferenceMode == FbxLayerElement::eDirect) ? mappingIndex : uvs6->GetIndexArray().GetAt(mappingIndex); v.uv6 = uvs6->GetDirectArray().GetAt(valueIndex); } if (skinInfo.hasSkin()){ auto& skinData = skinInfo.controlPointBoneIndicesAndWeights(controlPointIndex); for (auto boneix = 0; boneix < skinData.size()&&boneix<4; ++boneix){ v.boneIndices[boneix] = skinData[boneix].index; v.boneWeights[boneix] = static_cast<float>(skinData[boneix].weight); } for (auto boneix = skinData.size(); boneix < 4; ++boneix){ v.boneIndices[boneix] = skinInfo.bonesCount(); v.boneWeights[boneix] = 0; } } auto foundVertex = submesh.knownVertices.find(v); if (foundVertex != submesh.knownVertices.end()) { //submesh.indices.push_back(foundVertex->second); t.indices[cornerIndex] = foundVertex->second; } else { auto index = static_cast<int>(submesh.vertices.size()); submesh.vertices.push_back(v); //submesh.indices.push_back(index); submesh.knownVertices[v] = index; t.indices[cornerIndex] = index; } } if (submesh.knownTriangles.insert(t).second) { submesh.indices.push_back(t.indices[0]); submesh.indices.push_back(t.indices[1]); submesh.indices.push_back(t.indices[2]); } else { std::cout << "duplicate triangle found (and eliminated) in " << fbxNode->GetName() << std::endl; } } std::uint32_t vertexOffset = 0; for (auto matIndex = 0u; matIndex < submeshes.size(); ++matIndex) { auto& submesh = submeshes[matIndex]; BabylonSubmesh babsubmesh; babsubmesh.indexCount = static_cast<int>(submesh.indices.size()); babsubmesh.indexStart = static_cast<int>(_indices.size()); babsubmesh.materialIndex = matIndex; babsubmesh.verticesCount = static_cast<int>(submesh.vertices.size()); babsubmesh.verticesStart = static_cast<int>(_positions.size()); for (auto& v : submesh.vertices) { _positions.push_back(v.position); if (normals) { _normals.push_back(v.normal); } if (colors) { _colors.push_back(v.color); } if (uvs) { _uvs.push_back(v.uv); } if (uvs2) { _uvs2.push_back(v.uv2); } if (uvs3) { _uvs3.push_back(v.uv3); } if (uvs4) { _uvs4.push_back(v.uv4); } if (uvs5) { _uvs5.push_back(v.uv5); } if (uvs6) { _uvs6.push_back(v.uv6); } if (skinInfo.hasSkin()){ float weight0 = v.boneWeights[0]; float weight1 = v.boneWeights[1]; float weight2 = v.boneWeights[2]; int bone0 = v.boneIndices[0]; int bone1 = v.boneIndices[1]; int bone2 = v.boneIndices[2]; int bone3 = v.boneIndices[3]; _boneWeights.push_back(babylon_vector4( weight0, weight1, weight2, 1.0f - weight0 - weight1 - weight2)); _boneIndices.push_back((bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0); } } for (auto i : submesh.indices) { _indices.push_back(i + vertexOffset); } vertexOffset = static_cast<int>(_positions.size()); _submeshes.push_back(babsubmesh); } }
void CollisionShape::UpdateShape() { PROFILE(UpdateCollisionShape); ReleaseShape(); if (!physicsWorld_) return; if (node_) { Vector3 newWorldScale = node_->GetWorldScale(); switch (shapeType_) { case SHAPE_BOX: shape_ = new btBoxShape(ToBtVector3(size_ * 0.5f)); shape_->setLocalScaling(ToBtVector3(newWorldScale)); break; case SHAPE_SPHERE: shape_ = new btSphereShape(size_.x_ * 0.5f); shape_->setLocalScaling(ToBtVector3(newWorldScale)); break; case SHAPE_STATICPLANE: shape_ = new btStaticPlaneShape(btVector3(0.0f, 1.0f, 0.0f), 0.0f); break; case SHAPE_CYLINDER: shape_ = new btCylinderShape(btVector3(size_.x_ * 0.5f, size_.y_ * 0.5f, size_.x_ * 0.5f)); shape_->setLocalScaling(ToBtVector3(newWorldScale)); break; case SHAPE_CAPSULE: shape_ = new btCapsuleShape(size_.x_ * 0.5f, Max(size_.y_ - size_.x_, 0.0f)); shape_->setLocalScaling(ToBtVector3(newWorldScale)); break; case SHAPE_CONE: shape_ = new btConeShape(size_.x_ * 0.5f, size_.y_); shape_->setLocalScaling(ToBtVector3(newWorldScale)); break; case SHAPE_TRIANGLEMESH: size_ = size_.Abs(); if (model_) { // Check the geometry cache Pair<Model*, unsigned> id = MakePair(model_.Get(), lodLevel_); HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetTriMeshCache(); HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id); if (j != cache.End()) geometry_ = j->second_; else { geometry_ = new TriangleMeshData(model_, lodLevel_); // Check if model has dynamic buffers, do not cache in that case if (!HasDynamicBuffers(model_, lodLevel_)) cache[id] = geometry_; } TriangleMeshData* triMesh = static_cast<TriangleMeshData*>(geometry_.Get()); shape_ = new btScaledBvhTriangleMeshShape(triMesh->shape_, ToBtVector3(newWorldScale * size_)); // Watch for live reloads of the collision model to reload the geometry if necessary SubscribeToEvent(model_, E_RELOADFINISHED, HANDLER(CollisionShape, HandleModelReloadFinished)); } break; case SHAPE_CONVEXHULL: size_ = size_.Abs(); if (customGeometryID_ && GetScene()) { Node* node = GetScene()->GetNode(customGeometryID_); CustomGeometry* custom = node ? node->GetComponent<CustomGeometry>() : 0; if (custom) { geometry_ = new ConvexData(custom); ConvexData* convex = static_cast<ConvexData*>(geometry_.Get()); shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3)); shape_->setLocalScaling(ToBtVector3(newWorldScale * size_)); LOGINFO("Set convexhull from customgeometry"); } else LOGWARNING("Could not find custom geometry component from node ID " + String(customGeometryID_) + " for convex shape creation"); } else if (model_) { // Check the geometry cache Pair<Model*, unsigned> id = MakePair(model_.Get(), lodLevel_); HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& cache = physicsWorld_->GetConvexCache(); HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >::Iterator j = cache.Find(id); if (j != cache.End()) geometry_ = j->second_; else { geometry_ = new ConvexData(model_, lodLevel_); // Check if model has dynamic buffers, do not cache in that case if (!HasDynamicBuffers(model_, lodLevel_)) cache[id] = geometry_; } ConvexData* convex = static_cast<ConvexData*>(geometry_.Get()); shape_ = new btConvexHullShape((btScalar*)convex->vertexData_.Get(), convex->vertexCount_, sizeof(Vector3)); shape_->setLocalScaling(ToBtVector3(newWorldScale * size_)); SubscribeToEvent(model_, E_RELOADFINISHED, HANDLER(CollisionShape, HandleModelReloadFinished)); } break; case SHAPE_TERRAIN: size_ = size_.Abs(); { Terrain* terrain = GetComponent<Terrain>(); if (terrain && terrain->GetHeightData()) { geometry_ = new HeightfieldData(terrain); HeightfieldData* heightfield = static_cast<HeightfieldData*>(geometry_.Get()); shape_ = new btHeightfieldTerrainShape(heightfield->size_.x_, heightfield->size_.y_, heightfield->heightData_.Get(), 1.0f, heightfield->minHeight_, heightfield->maxHeight_, 1, PHY_FLOAT, false); shape_->setLocalScaling(ToBtVector3(Vector3(heightfield->spacing_.x_, 1.0f, heightfield->spacing_.z_) * newWorldScale * size_)); } } break; default: break; } if (shape_) { shape_->setUserPointer(this); shape_->setMargin(margin_); } cachedWorldScale_ = newWorldScale; } if (physicsWorld_) physicsWorld_->CleanupGeometryCache(); recreateShape_ = false; }
void HeightmapEditorSystem::UpdateBrushTool(float32 timeElapsed) { if (!toolImage) { DAVA::Logger::Error("Tool image is empty!"); return; } EditorHeightmap* editorHeightmap = drawSystem->GetHeightmapProxy(); int32 scaleSize = toolImage->GetWidth(); Vector2 pos = cursorPosition - Vector2((float32)scaleSize, (float32)scaleSize) / 2.0f; { switch (activeDrawingType) { case HEIGHTMAP_DRAW_RELATIVE: { float32 koef = (strength * timeElapsed); if(inverseDrawingEnabled) { koef = -koef; } if (IsKeyModificatorPressed(DVKEY_ALT)) { koef = -koef; } editorHeightmap->DrawRelativeRGBA(toolImage, (int32)pos.x, (int32)pos.y, scaleSize, scaleSize, koef); break; } case HEIGHTMAP_DRAW_AVERAGE: { float32 koef = (averageStrength * timeElapsed) * 2.0f; editorHeightmap->DrawAverageRGBA(toolImage, (int32)pos.x, (int32)pos.y, scaleSize, scaleSize, koef); break; } case HEIGHTMAP_DRAW_ABSOLUTE: case HEIGHTMAP_DRAW_ABSOLUTE_DROPPER: { float32 maxHeight = drawSystem->GetLandscapeMaxHeight(); float32 height = curHeight / maxHeight * Heightmap::MAX_VALUE; float32 koef = (averageStrength * timeElapsed) * 2.0f; editorHeightmap->DrawAbsoluteRGBA(toolImage, (int32)pos.x, (int32)pos.y, scaleSize, scaleSize, koef, height); break; } case HEIGHTMAP_DROPPER: { float32 curHeight = drawSystem->GetHeightAtPoint(cursorPosition); SceneSignals::Instance()->EmitDropperHeightChanged(dynamic_cast<SceneEditor2*>(GetScene()), curHeight); return; } case HEIGHTMAP_COPY_PASTE: { if (copyPasteFrom == Vector2(-1.f, -1.f) || copyPasteTo == Vector2(-1.f, -1.f)) { return; } Vector2 posTo = pos; Vector2 deltaPos = cursorPosition - copyPasteTo; Vector2 posFrom = copyPasteFrom + deltaPos - Vector2((float32)scaleSize, (float32)scaleSize)/2.f; float32 koef = (averageStrength * timeElapsed) * 2.0f; editorHeightmap->DrawCopypasteRGBA(toolImage, posFrom, posTo, scaleSize, scaleSize, koef); break; } default: DAVA::Logger::Error("Invalid drawing type!"); return; } Rect rect(pos.x, pos.y, (float32)scaleSize, (float32)scaleSize); drawSystem->GetHeightmapProxy()->UpdateRect(rect); AddRectToAccumulator(heightmapUpdatedRect, rect); } }
void HeightmapEditorSystem::ProcessUIEvent(DAVA::UIEvent *event) { if (!IsLandscapeEditingEnabled()) { return; } UpdateCursorPosition(); if (event->tid == UIEvent::BUTTON_1) { Vector3 point; switch(event->phase) { case UIEvent::PHASE_BEGAN: if (drawingType == HEIGHTMAP_DRAW_ABSOLUTE_DROPPER || drawingType == HEIGHTMAP_DROPPER) { curHeight = drawSystem->GetHeightAtPoint(cursorPosition); SceneSignals::Instance()->EmitDropperHeightChanged(dynamic_cast<SceneEditor2*>(GetScene()), curHeight); } if (isIntersectsLandscape) { if (drawingType == HEIGHTMAP_COPY_PASTE) { int32 curKeyModifiers = QApplication::keyboardModifiers(); if (curKeyModifiers & Qt::AltModifier) { copyPasteFrom = cursorPosition; copyPasteTo = Vector2(-1.f, -1.f); return; } else { if (copyPasteFrom == Vector2(-1.f, -1.f)) { return; } copyPasteTo = cursorPosition; StoreOriginalHeightmap(); } } else { if (drawingType != HEIGHTMAP_DROPPER) { StoreOriginalHeightmap(); } } UpdateToolImage(); editingIsEnabled = true; } activeDrawingType = drawingType; break; case UIEvent::PHASE_DRAG: break; case UIEvent::PHASE_ENDED: FinishEditing(); break; } } }