bool PlanetManagerImplementation::isInObjectsNoBuildZone(float x, float y, float extraMargin) { SortedVector<ManagedReference<QuadTreeEntry* > > closeObjects; Vector3 targetPos(x, y, zone->getHeight(x, y)); zone->getInRangeObjects(x, y, 512, &closeObjects, true); for (int i = 0; i < closeObjects.size(); ++i) { SceneObject* obj = cast<SceneObject*>(closeObjects.get(i).get()); SharedObjectTemplate* objectTemplate = obj->getObjectTemplate(); if (objectTemplate != NULL) { float radius = objectTemplate->getNoBuildRadius(); // Only check objects with an actual NoBuildRadius if (radius > 0) { // Add margin to check radius += extraMargin; Vector3 objWorldPos = obj->getWorldPosition(); if (objWorldPos.squaredDistanceTo(targetPos) < radius * radius) { return true; } } } } return false; }
void RobotManager::moveRobot(WayPoint* wayPoint) { double x,y; double deltaX, deltaY, startX, startY; x = wayPoint->x_Coordinate; y = wayPoint->y_Coordinate - Y_FACTOR; xyPosition targetPos(x, y); cout<<"Total Completed "<<wpm.getCompletedPercent()<<"%"<<endl; getCurrentPos(); //do not move x,y if smaller than the delta deltaX = abs(targetPos.first - currPos.first); deltaY = abs(targetPos.second - currPos.second); if(deltaX < deltaTolerance) deltaX = 0; if(deltaY < deltaTolerance) deltaY = 0; getCurrentPos(); startX = currPos.first; startY = currPos.second; //move to next point robot->SetSpeed(linearSpeed, 0); while (abs(startX - currPos.first) < deltaX-0.2 || abs(startY - currPos.second) < deltaY-0.2) { getCurrentPos(); } // slow down before reaching the target robot->SetSpeed(0.05 * linearSpeed, 0); moveToNextYaw(targetPos, wayPoint->yaw); }
bool PlanetManagerImplementation::isBuildingPermittedAt(float x, float y, SceneObject* object, float margin) { SortedVector<ManagedReference<ActiveArea* > > activeAreas; Vector3 targetPos(x, y, zone->getHeight(x, y)); zone->getInRangeActiveAreas(x, y, &activeAreas, true); for (int i = 0; i < activeAreas.size(); ++i) { ActiveArea* area = activeAreas.get(i); if (area->isNoBuildArea()) { return false; } } if (isInObjectsNoBuildZone(x, y, margin)) { return false; } if (isInWater(targetPos.getX(), targetPos.getY())) { return false; } if (isInRangeWithPoi(targetPos.getX(), targetPos.getY(), 150)) return false; return true; }
bool PlanetManagerImplementation::isBuildingPermittedAt(float x, float y, SceneObject* object, float margin) { SortedVector<ActiveArea*> activeAreas; Vector3 targetPos(x, y, 0); if (!zone->isWithinBoundaries(targetPos)) return false; //targetPos.setZ(zone->getHeight(x, y)); not needed zone->getInRangeActiveAreas(x, y, &activeAreas, true); for (int i = 0; i < activeAreas.size(); ++i) { ActiveArea* area = activeAreas.get(i); if (area->isNoBuildArea()) { return false; } } if (isInObjectsNoBuildZone(x, y, margin)) { return false; } if (isInWater(x, y)) { return false; } if (isInRangeWithPoi(x, y, 150)) return false; return true; }
bool PlanetManagerImplementation::isSpawningPermittedAt(float x, float y, float margin) { SortedVector<ActiveArea*> activeAreas; Vector3 targetPos(x, y, zone->getHeight(x, y)); if (!zone->isWithinBoundaries(targetPos)) return false; zone->getInRangeActiveAreas(x, y, &activeAreas, true); zone->getInRangeActiveAreas(x, y, margin + 64.f, &activeAreas, true); for (int i = 0; i < activeAreas.size(); ++i) { ActiveArea* area = activeAreas.get(i); if (area->isRegion() || area->isMunicipalZone() || area->isNoSpawnArea()) { return false; } } if (isInObjectsNoBuildZone(x, y, margin)) { return false; } if (isInWater(x, y)) { return false; } if (isInRangeWithPoi(x, y, 150)) return false; if (terrainManager->getHighestHeightDifference(x - 10, y - 10, x + 10, y + 10) > 15.0) return false; return true; }
bool PlanetManagerImplementation::isCampingPermittedAt(float x, float y, float margin) { SortedVector<ManagedReference<ActiveArea* > > activeAreas; Vector3 targetPos(x, y, zone->getHeight(x, y)); zone->getInRangeActiveAreas(x, y, &activeAreas, true); for (int i = 0; i < activeAreas.size(); ++i) { ActiveArea* area = activeAreas.get(i); // Skip areas explicitly marked as camping allowed if (area->isCampingPermitted()) { continue; } // Honor no-build after checking for areas that camping is explicitly allowed if (area->isNoBuildArea()) { return false; } } if (isInWater(x, y)) { return false; } if (isInRangeWithPoi(x, y, 150)) return false; return true; }
Reference<SceneObject*> PlanetManagerImplementation::findObjectTooCloseToDecoration(float x, float y, float margin) { SortedVector<ManagedReference<QuadTreeEntry* > > closeObjects; Vector3 targetPos(x, y,0); zone->getInRangeObjects(x, y, 256, &closeObjects, true); for (int i = 0; i < closeObjects.size(); ++i) { ManagedReference<SceneObject*> obj = cast<SceneObject*>(closeObjects.get(i).get()); if(obj == NULL || obj->isCreatureObject() || obj->getObjectTemplate() == NULL) continue; Vector3 objVec(obj->getPositionX(), obj->getPositionY(),0); int squaredDistance = (obj->getObjectTemplate()->getNoBuildRadius() + margin) * (obj->getObjectTemplate()->getNoBuildRadius() + margin); if(objVec.squaredDistanceTo(targetPos) < squaredDistance){ return obj; } if(obj->isStructureObject() && StructureManager::instance()->isInStructureFootprint(cast<StructureObject*>(obj.get()), x, y, margin) ){ return obj; } } return NULL; }
bool CWeapon::AttackUnit(CUnit *unit,bool userTarget) { if((!userTarget && weaponDef->noAutoTarget)) return false; if(weaponDef->interceptor) return false; weaponPos=owner->pos+owner->frontdir*relWeaponPos.z+owner->updir*relWeaponPos.y+owner->rightdir*relWeaponPos.x; if(weaponPos.y<ground->GetHeight2(weaponPos.x,weaponPos.z)) weaponPos=owner->pos+10; //hope that we are underground because we are a popup weapon and will come above ground later if(!unit) { if(targetType!=Target_Unit) //make the unit be more likely to keep the current target if user start to move it targetType=Target_None; haveUserTarget=false; return false; } float3 targetPos(helper->GetUnitErrorPos(unit,owner->allyteam)); targetPos+=errorVector*(weaponDef->targetMoveError*30*unit->speed.Length()*(1.0-owner->limExperience)); if(!TryTarget(targetPos,userTarget,unit)) return false; if(targetUnit) { DeleteDeathDependence(targetUnit); targetUnit=0; } haveUserTarget=userTarget; targetType=Target_Unit; targetUnit=unit; targetPos=unit->midPos+float3(0,0.3,0)*unit->radius; AddDeathDependence(targetUnit); return true; }
RainDrop::RainDrop(sf::Sprite spr) : m_sprite(spr), m_alive(true){ sf::Vector2f targetPos(rand() % 1800 - 500, rand() % 500); m_lifeCounter = targetPos.y / 16 + 1; m_pos = targetPos - (static_cast<float>(m_lifeCounter) * sf::Vector2f(-8, 16)); m_sprite.setPosition(m_pos); m_sprite.setTextureRect(sf::IntRect(0, 8, 8, 16)); m_sprite.setScale(2, 2); }
CommandHypothesis::CommandHypothesis(std::vector<UnitGroup*> blueUnits, UnitGroup* myUnits, Command::CommandType command, std::string name): Hypothesis(blueUnits, myUnits) { //just one command - attack nearest group std::vector<int> myUnitIDs = mRedUnits->getUnitIDs(); std::vector<int> myTargetUnits; //not specified osg::Vec3 targetPos(0,0,0); //not specified addCommand((int)command, myUnitIDs, targetPos, name, myTargetUnits); }
IZ_BOOL StateMoveToItem::Enter( izanagi::IMemoryAllocator* allocator, izanagi::graph::CGraphicsDevice* device, izanagi::CValue& arg) { PhotoItem* hitItem = (PhotoItem*)arg.GetValueAsPtr(); IZ_ASSERT(hitItem != IZ_NULL); // Keep camera matrix. izanagi::math::SMatrix44::Copy(m_CamMtx, GetCamera().GetTransform()); const izanagi::math::SMatrix44& globalRotMtx = PhotoItemManager::Instance().GetRotationMtx(); // Compute target matrix. { izanagi::math::SVector4 pos; hitItem->GetCenterPosition(pos); izanagi::math::SMatrix44::Apply(pos, pos, globalRotMtx); izanagi::math::SVector4 nml; hitItem->GetNormal(nml); izanagi::math::SMatrix44::ApplyXYZ(nml, nml, globalRotMtx); izanagi::math::CVector4 targetPos( pos.x + nml.x * Configure::CameraDistanceFromItem, pos.y + nml.y * Configure::CameraDistanceFromItem, pos.z + nml.z * Configure::CameraDistanceFromItem); izanagi::math::CVector4 targetAt(pos); izanagi::CVectorCamera tmpCam; tmpCam.Init( targetPos, targetAt, 1.0f, 500.0f, izanagi::math::CMath::Deg2Rad(60.0f), 1.0f); tmpCam.Update(); izanagi::math::SMatrix44::Copy(m_TargetMtx, tmpCam.GetTransform()); } m_State = State_Move; m_Timeline.Reset(); m_Timeline.Start(); return IZ_TRUE; }
void ModelSelectionPane::ResetPostion(bool hasAnimation) { QPoint targetPos(-width() * m_curPaneIndex, ui->itemsetpane->y()); if(hasAnimation) { m_animation.setStartValue(ui->itemsetpane->pos()); m_animation.setEndValue(targetPos); m_animation.setTargetObject(ui->itemsetpane); m_animation.setDuration(300); m_animation.start(); } else { ui->itemsetpane->move(targetPos); } }
void world_avatar::initialize() { core::vector3df targetPos(3000, 0, 3000); ISceneManager *sceneManager = device_->getSceneManager(); IVideoDriver *driver = device_->getVideoDriver(); camera_ = sceneManager->addCameraSceneNode(0); camera_->setPosition(core::vector3df(2700 * 2, 200, 2600 * 2)); camera_->setTarget(targetPos); camera_->setFarValue(42000.0f); mesh_ = device_->getSceneManager()->getMesh("data/assets/Skeleton.Male.x"); meshNode_ = device_->getSceneManager()->addAnimatedMeshSceneNode(mesh_); meshNode_->setAnimationSpeed(30); meshNode_->setMaterialFlag(video::EMF_LIGHTING, false); meshNode_->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, false); meshNode_->setDebugDataVisible(scene::EDS_OFF); meshNode_->setScale(core::vector3df(200,200,200)); meshNode_->setPosition(targetPos); //core::quaternion q; //q.fromAngleAxis(90 * core::DEGTORAD, core::vector3df(1, 0, 0)); //core::matrix4 m1 = q.getMatrix(); //meshNode_->updateAbsolutePosition(); //core::matrix4 m2 = meshNode_->getAbsoluteTransformation(); //core::matrix4 m = m1*m2; //meshNode_->setRotation(m.getRotationDegrees()); ITexture* test = driver->getTexture("data/assets/upper-body.png"); meshNode_->getMaterial(0).TextureLayer[0].Texture = test; ITexture* test2 = driver->getTexture("data/assets/lower-body.png"); meshNode_->getMaterial(1).TextureLayer[0].Texture = test2; ITexture* test3 = driver->getTexture("data/assets/head.png"); meshNode_->getMaterial(2).TextureLayer[0].Texture = test3; //meshNode_->setJointMode(EJUOR_CONTROL); IBoneSceneNode* rightUpperArm = meshNode_->getJointNode((u32)0); core::vector3df cpos = rightUpperArm->getRotation(); cpos.Z -= 1.5; rightUpperArm->setRotation(cpos); }
void CActionCoopAnimation::Enter() { TPlayerAction::Enter(); QuatT targetPos(m_rootScope->GetEntity().GetPos(), m_rootScope->GetEntity().GetRotation()); SetParam("TargetPos", targetPos); CRecordingSystem* pRecordingSystem = g_pGame->GetRecordingSystem(); if (pRecordingSystem) { pRecordingSystem->OnMannequinSetParam(m_rootScope->GetEntityId(), "TargetPos", targetPos); } IAnimatedCharacter* pAnimChar = m_player.GetAnimatedCharacter(); IAnimatedCharacter* pAnimCharTarget = m_target.GetAnimatedCharacter(); if( pAnimChar ) { pAnimChar->SetMovementControlMethods(eMCM_Animation, eMCM_Animation); pAnimChar->RequestPhysicalColliderMode(eColliderMode_Disabled, eColliderModeLayer_Game, "CActionStealthKill::Enter()"); } if (pAnimCharTarget) { pAnimCharTarget->SetMovementControlMethods(eMCM_Animation, eMCM_Animation); pAnimCharTarget->RequestPhysicalColliderMode(eColliderMode_Disabled, eColliderModeLayer_Game, "CActionStealthKill::Enter()"); } PlayerCameraAnimationSettings cameraAnimationSettings; cameraAnimationSettings.positionFactor = 1.0f; cameraAnimationSettings.rotationFactor = 1.0f; cameraAnimationSettings.stableBlendOff = true; m_player.PartialAnimationControlled( true, cameraAnimationSettings ); m_player.GetActorStats()->animationControlledID = m_target.GetEntityId(); m_player.HolsterItem(true); // Update visibility to change render mode of 1st person character m_player.RefreshVisibilityState(); // Mannequin can't set the tag's correctly on the exit, so we have to do it immediately after we started instead :) // the tags are set, but Exit() is called too late for our purposes, it is needed during the resolve of the next action m_rootScope->GetActionController().GetContext().state.Set(m_targetTagID, false); }
void Worm::Update(float dt) { g_a->SetColor(0,1,0,1); g_a->SetSize(0.125f); Vector2 targetPos( m_planetOrbit == NULL ? Vector2(0,0) : Vector2(m_planetOrbit->GetPosition().X, m_planetOrbit->GetPosition().Y) + g_orbitPointVec); if(m_planetOrbit != NULL) g_a->SetPosition( targetPos ); theWorld.Add(g_a,10); switch(g_moveState) { case PlanetOrbit: { assert(m_planetOrbit != NULL); float angle = PIOver4 * dt * m_speed / m_planetOrbit->GetSize().X; g_orbitPointVec = Vector2::Rotate(g_orbitPointVec, angle); MoveInDirection(targetPos - m_head->GetPosition(), m_speed * dt); } break; case PlanetClick: { MoveInDirection(targetPos - m_head->GetPosition(), m_speed * dt); if(m_planetOrbit->GetPosition().X - GetPosition().X <= 0.1 && m_planetOrbit->GetPosition().Y - GetPosition().Y <= 0.1 ) g_moveState = PlanetOrbit; } break; case Mouse: { MoveInDirection(MathUtil::ScreenToWorld(g_screenCoords) - m_head->GetPosition(), m_speed * dt); } break; case NotMoving: break; default: assert(!"shouldn't get here"); } }
void ZombieMoveToTargetState::Enter(obj_Zombie *o) { // Create navigation agent o->navAgentIdx = gNavMeshActorsManager.CreateAgent(o->GetPosition(), o->aiParams); GameObject *plr = GameWorld().GetObject(o->chasedTarget); r3dVector targetPos(o->lastTargetPos); int chaseAnim = PLAYER_MOVE_RUN; if (plr) { targetPos = plr->GetPosition(); chaseAnim = PLAYER_MOVE_SPRINT; } gNavMeshActorsManager.NavigateTo(o->navAgentIdx, targetPos); // Switch to run animation //o->uberAnim->SwitchToState(chaseAnim, CUberData::ANIMDIR_Str); o->playingSndHandle = SoundSys.Play(gSndZombieGrowlID, o->GetPosition()); }
Vec3 GetTargetPos( SActivationInfo* pActInfo ) { EntityId targetId = GetPortEntityId(pActInfo, IN_TARGETID); Vec3 targetPos(0,0,0); if (targetId) { IEntity* pTarget = gEnv->pEntitySystem->GetEntity(targetId); if (pTarget) { AABB box; pTarget->GetWorldBounds(box); targetPos = box.GetCenter(); } } else { targetPos = GetPortVec3(pActInfo, IN_TARGETPOS); } return targetPos; }
bool PlanetManagerImplementation::isInObjectsNoBuildZone(float x, float y, float extraMargin) { SortedVector<QuadTreeEntry*> closeObjects; Vector3 targetPos(x, y, zone->getHeight(x, y)); zone->getInRangeObjects(x, y, 512, &closeObjects, true); for (int i = 0; i < closeObjects.size(); ++i) { SceneObject* obj = static_cast<SceneObject*>(closeObjects.get(i)); SharedObjectTemplate* objectTemplate = obj->getObjectTemplate(); if (objectTemplate != NULL) { float radius = objectTemplate->getNoBuildRadius(); // Only check objects with an actual NoBuildRadius if (radius > 0) { // Add margin to check radius += extraMargin; Vector3 objWorldPos = obj->getWorldPosition(); if (objWorldPos.squaredDistanceTo(targetPos) < radius * radius) { return true; } } // Check if it's within a structure's footprint if (objectTemplate->isSharedStructureObjectTemplate()) { if (StructureManager::instance()->isInStructureFootprint(cast<StructureObject*>(obj), x, y, extraMargin)) { return true; } } } } return false; }
void CActorAnimationActionCooperative::Enter() { CAnimationAction::Enter(); QuatT targetPos(m_rootScope->GetEntity().GetPos(), m_rootScope->GetEntity().GetRotation()); SetParam("TargetPos", targetPos); //if (auto pAnimChar = m_sourceActor.GetAnimatedCharacter()) //{ // pAnimChar->SetMovementControlMethods(eMCM_Animation, eMCM_Animation); // pAnimChar->RequestPhysicalColliderMode(eColliderMode_Disabled, eColliderModeLayer_Game, "CActorAnimationActionCooperative::Enter()"); //} //if (m_pTargetActor) //{ // if (auto pAnimCharTarget = m_pTargetActor->GetAnimatedCharacter()) // { // pAnimCharTarget->SetMovementControlMethods(eMCM_Animation, eMCM_Animation); // pAnimCharTarget->RequestPhysicalColliderMode(eColliderMode_Disabled, eColliderModeLayer_Game, "CActorAnimationActionCooperative::Enter()"); // } //} }
void ChannelAgent::ModeEvent(BMessage* msg) { int32 modPos(0), targetPos(1); const char* mode(0), *target(0), *theNick(0); char theOperator(0); bool hit(false); // TODO Change Status to bitmask -- Too hard this way msg->FindString("mode", &mode); msg->FindString("target", &target); msg->FindString("nick", &theNick); BString buffer, targetS(target); buffer += "*** "; buffer += theNick; buffer += S_CHANNEL_SET_MODE; buffer += mode; if (targetS != "-9z99") { buffer += " "; buffer += targetS; } buffer += "\n"; BMessenger display(this); BMessage modeMsg(M_DISPLAY); PackDisplay(&modeMsg, buffer.String(), C_OP, C_BACKGROUND, F_TEXT); display.SendMessage(&modeMsg); // at least one if (mode && *mode && *(mode + 1)) theOperator = mode[modPos++]; while (theOperator && mode[modPos]) { char theModifier(mode[modPos]); if (theModifier == 'o' || theModifier == 'v' || theModifier == 'h') { BString myTarget(GetWord(target, targetPos++)); NameItem* item; int32 pos; if ((pos = FindPosition(myTarget.String())) < 0 || (item = static_cast<NameItem*>(fNamesList->ItemAt(pos))) == 0) { printf("[ERROR] Couldn't find %s in NamesView\n", myTarget.String()); return; } int32 iStatus(item->Status()); if (theOperator == '+' && theModifier == 'o') { hit = true; if ((iStatus & STATUS_OP_BIT) == 0) { item->SetStatus((iStatus & ~STATUS_NORMAL_BIT) | STATUS_OP_BIT); ++fOpsCount; buffer = ""; buffer << fOpsCount; if (!IsHidden()) vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_OPS, buffer.String()); } } else if (theModifier == 'o') { hit = true; if ((iStatus & STATUS_OP_BIT) != 0) { iStatus &= ~STATUS_OP_BIT; if ((iStatus & STATUS_VOICE_BIT) == 0) iStatus |= STATUS_NORMAL_BIT; item->SetStatus(iStatus); --fOpsCount; buffer = ""; buffer << fOpsCount; if (!IsHidden()) vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_OPS, buffer.String()); } } if (theOperator == '+' && theModifier == 'v') { hit = true; item->SetStatus((iStatus & ~STATUS_NORMAL_BIT) | STATUS_VOICE_BIT); } else if (theModifier == 'v') { hit = true; iStatus &= ~STATUS_VOICE_BIT; if ((iStatus & STATUS_OP_BIT) == 0) iStatus |= STATUS_NORMAL_BIT; item->SetStatus(iStatus); } if (theOperator == '+' && theModifier == 'h') { hit = true; item->SetStatus((iStatus & ~STATUS_NORMAL_BIT) | STATUS_HELPER_BIT); } else if (theModifier == 'h') { hit = true; iStatus &= ~STATUS_HELPER_BIT; if ((iStatus & STATUS_HELPER_BIT) == 0) iStatus |= STATUS_NORMAL_BIT; item->SetStatus(iStatus); } } else if (theModifier == 'l' && theOperator == '-') { BString myTarget(GetWord(target, targetPos++)); UpdateMode('-', 'l'); fChanLimit = ""; } else if (theModifier == 'l') { BString myTarget(GetWord(target, targetPos++)); fChanLimitOld = fChanLimit; fChanLimit = myTarget; UpdateMode('+', 'l'); } else if (theModifier == 'k' && theOperator == '-') { UpdateMode('-', 'k'); fChanKey = ""; } else if (theModifier == 'k') { BString myTarget(GetWord(target, targetPos++)); fChanKeyOld = fChanKey; fChanKey = myTarget; UpdateMode('+', 'k'); } else if (theModifier == 'b' || theModifier == 'a' || theModifier == 'q') { // dont do anything else } else { UpdateMode(theOperator, theModifier); } ++modPos; if (mode[modPos] == '+' || mode[modPos] == '-') theOperator = mode[modPos++]; } if (hit) { fNamesList->SortItems(SortNames); fNamesList->Invalidate(); } }
////////////////////////////////////////////////////////////////////////// // IsMountedWeaponUsableWithTarget // A piece of game-code moved from CryAction when scriptbind_AI moved to the AI system ////////////////////////////////////////////////////////////////////////// int CScriptBind_Game::IsMountedWeaponUsableWithTarget(IFunctionHandler *pH) { int paramCount = pH->GetParamCount(); if(paramCount<2) { GameWarning("%s: too few parameters.", __FUNCTION__); return pH->EndFunction(); } GET_ENTITY(1); if(!pEntity) { GameWarning("%s: wrong entity id in parameter 1.", __FUNCTION__); return pH->EndFunction(); } IAIObject* pAI = pEntity->GetAI(); if (!pAI) { GameWarning("%s: Entity '%s' does not have AI.",__FUNCTION__, pEntity->GetName()); return pH->EndFunction(); } EntityId itemEntityId; ScriptHandle hdl2; if(!pH->GetParam(2,hdl2)) { GameWarning("%s: wrong parameter 2 format.", __FUNCTION__); return pH->EndFunction(); } itemEntityId = (EntityId)hdl2.n; if (!itemEntityId) { GameWarning("%s: wrong entity id in parameter 2.", __FUNCTION__); return pH->EndFunction(); } IGameFramework *pGameFramework = gEnv->pGame->GetIGameFramework(); IItem* pItem = pGameFramework->GetIItemSystem()->GetItem(itemEntityId); if (!pItem) { //gEnv->pAISystem->Warning("<CScriptBind> ", "entity in parameter 2 is not an item/weapon"); GameWarning("%s: entity in parameter 2 is not an item/weapon.", __FUNCTION__); return pH->EndFunction(); } float minDist = 7; bool bSkipTargetCheck = false; Vec3 targetPos(ZERO); if(paramCount > 2) { for(int i=3;i <= paramCount ; i++) { if(pH->GetParamType(i) == svtBool) pH->GetParam(i,bSkipTargetCheck); else if(pH->GetParamType(i) == svtNumber) pH->GetParam(i,minDist); else if(pH->GetParamType(i) == svtObject) pH->GetParam(i,targetPos); } } IAIActor* pAIActor = CastToIAIActorSafe(pAI); if (!pAIActor) { GameWarning("%s: entity '%s' in parameter 1 is not an AI actor.", __FUNCTION__, pEntity->GetName()); return pH->EndFunction(); } IEntity* pItemEntity = pItem->GetEntity(); if(!pItemEntity) return pH->EndFunction(); if(!pItem->GetOwnerId()) { // weapon is not used, check if it is on a vehicle IEntity* pParentEntity = pItemEntity->GetParent(); if(pParentEntity) { IAIObject* pParentAI = pParentEntity->GetAI(); if(pParentAI && pParentAI->GetAIType()==AIOBJECT_VEHICLE) { // (MATT) Feature was cut and code was tricky, hence ignore weapons in vehicles {2008/02/15:11:08:51} return pH->EndFunction(); } } } else if( pItem->GetOwnerId()!= pEntity->GetId()) // item is used by someone else? return pH->EndFunction(false); // check target if(bSkipTargetCheck) return pH->EndFunction(true); IAIObject* pTarget = pAIActor->GetAttentionTarget(); if(targetPos.IsZero()) { if(!pTarget) return pH->EndFunction(); targetPos = pTarget->GetPos(); } Vec3 targetDir(targetPos - pItemEntity->GetWorldPos()); Vec3 targetDirXY(targetDir.x, targetDir.y, 0); float length2D = targetDirXY.GetLength(); if(length2D < minDist || length2D<=0) return pH->EndFunction(); targetDirXY /= length2D;//normalize IWeapon* pWeapon = pItem->GetIWeapon(); bool vehicleGun = pWeapon && pWeapon->GetHostId(); if (!vehicleGun) { Vec3 mountedAngleLimits(pItem->GetMountedAngleLimits()); float yawRange = DEG2RAD(mountedAngleLimits.z); if(yawRange > 0 && yawRange < gf_PI) { float deltaYaw = pItem->GetMountedDir().Dot(targetDirXY); if(deltaYaw < cosf(yawRange)) return pH->EndFunction(false); } float minPitch = DEG2RAD(mountedAngleLimits.x); float maxPitch = DEG2RAD(mountedAngleLimits.y); //maxPitch = (maxPitch - minPitch)/2; //minPitch = -maxPitch; float pitch = atanf(targetDir.z / length2D); if ( pitch < minPitch || pitch > maxPitch ) return pH->EndFunction(false); } if(pTarget) { IEntity* pTargetEntity = pTarget->GetEntity(); if(pTargetEntity) { // check target distance and where he's going IPhysicalEntity *phys = pTargetEntity->GetPhysics(); if(phys) { pe_status_dynamics dyn; phys->GetStatus(&dyn); Vec3 velocity ( dyn.v); velocity.z = 0; float speed = velocity.GetLength2D(); if(speed>0) { //velocity /= speed; if(length2D< minDist * 0.75f && velocity.Dot(targetDirXY)<=0) return pH->EndFunction(false); } } } } return pH->EndFunction(true); }
void ScreenWidget::loadPressed() { QString fileName = QFileDialog::getOpenFileName(this, tr("Load Scene"), "",tr("DSS XML Scene File (*.xml);;All Files (*)")); if (fileName.isEmpty()) { return; } else { QDomDocument doc("loadedscene"); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } if (!doc.setContent(&file)) { file.close(); return; } file.close(); QDomElement scene = doc.documentElement(); qDebug()<<scene.text(); QDomNode field=scene.firstChildElement("field"); if (field.isElement()) { this->scene->addField(field.firstChildElement("width").text().toUInt(),field.firstChildElement("height").text().toUInt()); } QDomNode targetEntity = scene.firstChildElement("targetEntity"); if (targetEntity.isElement()) { TargetEntity* newTargetEntity = new TargetEntity(); Point2i targetPos(targetEntity.firstChildElement("x").text().toInt(),targetEntity.firstChildElement("y").text().toInt()); this->scene->setTargetEntity(newTargetEntity,targetPos); } QDomNode entities = scene.firstChildElement("entities"); if (entities.isElement()) { QDomNodeList entityList =entities.toElement().elementsByTagName("entity"); for(int i=0;i<entityList.count();i++) { QDomElement entity = entityList.at(i).toElement(); int type = entity.firstChildElement("type").text().toInt(); Point2i entityPos(entity.firstChildElement("x").text().toInt(),entity.firstChildElement("y").text().toInt()); this->scene->addEntityAtPosition(type,entityPos); } } /* for(int i=0;i<fieldList.count();i++) { QDomElement field = fieldList.at(i).toElement(); qDebug()<<field.attribute("width"); qDebug()<<field.attribute("height"); QDomNodeList lll=e1.elementsByTagName("a"); qDebug(QString::number(lll.count()).toAscii()); for(int j=0;j<lll.count();j++) { QDomElement e2 = lll.at(j).toElement(); qDebug(e2.tagName().toAscii()+" "+e2.attribute("ITEM").toAscii()); QDomNodeList llll=e2.elementsByTagName("b"); for(int k=0;k<llll.count();k++) { QDomElement e3 = llll.at(k).toElement(); qDebug(e3.tagName().toAscii()+" "+e3.text().toAscii()); } } } */ } }
bool Run() { int result = ::DxLib::SetGraphMode( static_cast<int>(m_width), static_cast<int>(m_height), 32); ::DxLib::ChangeWindowMode(TRUE); // ウインドウモードに変更 if (::DxLib::DxLib_Init() == -1) { MessageBox(nullptr, "Initializing error", "Error!", MB_ICONERROR | MB_TASKMODAL | MB_TOPMOST); return false; } // 描画先画面を裏画面にセット SetDrawScreen(DX_SCREEN_BACK); float nearZ = 1.f, farZ = 100.f; SetCameraNearFar(nearZ, farZ); VECTOR3 cameraPos(0.f, 0.5f, -10.f); VECTOR3 targetPos(0.f, 0.f, 0.f); DxLib::SetCameraPositionAndTarget_UpVecY(cameraPos, targetPos); Cube cube(1.f); int keys[] = { KEY_INPUT_UP, KEY_INPUT_DOWN, KEY_INPUT_LEFT, KEY_INPUT_RIGHT }; float val[] = { +0.1f, -0.1f, -0.1f, +0.1f }; float* pos[][2] = { { &cameraPos.y, &targetPos.y }, { &cameraPos.y, &targetPos.y }, { &cameraPos.x, &targetPos.x }, { &cameraPos.x, &targetPos.x }, }; while (_LoopProc() && CheckHitKey(KEY_INPUT_ESCAPE) == 0) { const std::vector<Face>& faces = cube.GetFaces(); for (const Face& face : faces) { int vertexNum = static_cast<int>(face.GetVertexNum()); for (int i = 0; i < vertexNum - 1; ++i) { int j = (i + 1) % vertexNum; // 頂点の取得 VECTOR4 from(face.GetVertexAt(i)); VECTOR4 to(face.GetVertexAt(j)); VECTOR3 from3d(from); VECTOR3 to3d(to); //------------------------------ // 座標変換 //------------------------------ float dist = targetPos.z - cameraPos.z; MATRIX matT; CreateTranslationMatrix(matT, from.x, from.y, from.z); MATRIX matP; CreatePerspectiveLH(matP, m_width, m_height, nearZ, farZ); MATRIX mat; MultiplyMatrix(mat, matT, matP); Vector4Transform(from, from, mat); CreateTranslationMatrix(matT, to.x, to.y, to.z); MultiplyMatrix(mat, matT, matP); Vector4Transform(to, to, mat); /* D3DXMATRIX * D3DXMatrixPerspectiveLH( D3DXMATRIX * pOut, FLOAT w, 近くのビュー プレーンでのビュー ボリュームの幅 FLOAT h, 近くのビュー プレーンでのビュー ボリュームの高さ FLOAT zn, 近くのビュー プレーンの z 値 FLOAT zf 遠くのビュー プレーンの z 値 ); 2*zn/w 0 0 0 0 2*zn/h 0 0 0 0 zf/(zf-zn) 1 0 0 zn*zf/(zn-zf) 0 D3DXMATRIX * D3DXMatrixPerspectiveRH( D3DXMATRIX * pOut, FLOAT w, FLOAT h, FLOAT zn, FLOAT zf); 2*zn/w 0 0 0 0 2*zn/h 0 0 0 0 zf/(zn-zf) -1 0 0 zn*zf/(zn-zf) 0 */ /* D3DXMATRIX* D3DXMatrixPerspectiveFovLH( D3DXMATRIX * pOut, FLOAT fovy, y 方向の視野角 (ラジアン単位) FLOAT Aspect, アスペクト比 (ビュー空間の幅を高さで除算して定義(width/height)) FLOAT zn, 近くのビュー プレーンの z 値 FLOAT zf 遠くのビュー プレーンの z 値 ); where: yScale = cot(fovY/2) xScale = yScale / aspect ratio xScale 0 0 0 0 yScale 0 0 0 0 zf/(zf-zn) 1 0 0 -zn*zf/(zf-zn) 0 D3DXMATRIX * D3DXMatrixPerspectiveFovRH( D3DXMATRIX * pOut, FLOAT fovy, FLOAT Aspect, FLOAT zn, FLOAT zf); xScale 0 0 0 0 yScale 0 0 0 0 zf/(zn-zf) -1 0 0 zn*zf/(zn-zf) 0 */ /* D3DXMATRIX * D3DXMatrixLookAtLH( D3DXMATRIX * pOut, 処理の結果を表す D3DXMATRIX 構造体へのポインター CONST D3DXVECTOR3 * pEye, 視点を定義する D3DXVECTOR3 構造体へのポインターです。この値は変換に使用されます。 CONST D3DXVECTOR3 * pAt, カメラの注視対象を定義する D3DXVECTOR3 構造体へのポインターです。 CONST D3DXVECTOR3 * pUp 現在のワールド座標における上方向を定義する D3DXVECTOR3 構造体へのポインター。この構造体の値は通常 [0, 1, 0] です。 ); zaxis = normal(At - Eye) xaxis = normal(cross(Up, zaxis)) yaxis = cross(zaxis, xaxis) xaxis.x yaxis.x zaxis.x 0 xaxis.y yaxis.y zaxis.y 0 xaxis.z yaxis.z zaxis.z 0 -dot(xaxis, eye) -dot(yaxis, eye) -dot(zaxis, eye) l D3DXMATRIX * D3DXMatrixLookAtRH( D3DXMATRIX * pOut, CONST D3DXVECTOR3 * pEye, CONST D3DXVECTOR3 * pAt, CONST D3DXVECTOR3 * pUp ); zaxis = normal(Eye - At) xaxis = normal(cross(Up, zaxis)) yaxis = cross(zaxis, xaxis) xaxis.x yaxis.x zaxis.x 0 xaxis.y yaxis.y zaxis.y 0 xaxis.z yaxis.z zaxis.z 0 -dot(xaxis, eye) -dot(yaxis, eye) -dot(zaxis, eye) l */ //------------------------------ // 描画 DxLib::DrawLine(from.x, from.y, to.x, to.y, GetColor(250, 0, 0)); printf("from(%.1f, %.1f, %.1f) ", from.x, from.y, from.z); printf("to(%.1f, %.1f, %.1f)\n", to.x, to.y, to.z); DxLib::DrawLine3D(from3d, to3d, -1); } } { int i = 0; for (int key : keys) { if (CheckHitKey(key) != 0) { *pos[i][0] += val[i]; *pos[i][1] += val[i]; } ++i; } DxLib::SetCameraPositionAndTarget_UpVecY(cameraPos, targetPos); DrawExtendFormatString(0, 0, 0.75, 0.75, -1, "camera(%.1f, %.1f, %.1f) target(%.1f, %.1f, %.1f)", cameraPos.x, cameraPos.y, cameraPos.z, targetPos.x, targetPos.y, targetPos.z); } } return true; }
Swc_Tree* ZNeuronTracer::trace(double x1, double y1, double z1, double r1, double x2, double y2, double z2, double r2) { setTraceScoreThreshold(TRACING_INTERACTIVE); ZIntPoint stackOffset = getStack()->getOffset(); ZPoint targetPos(x2, y2, z2); x1 = iround(x1); y1 = iround(y1); z1 = iround(z1); x2 = iround(x2); y2 = iround(y2); z2 = iround(z2); x1 -= stackOffset.getX(); y1 -= stackOffset.getY(); z1 -= stackOffset.getZ(); x2 -= stackOffset.getX(); y2 -= stackOffset.getY(); z2 -= stackOffset.getZ(); if (x1 < 0 || y1 < 0 || z1 < 0 || x1 >= getStack()->width() || y1 >= getStack()->height() || z1 >= getStack()->depth()) { return NULL; } ZStackGraph stackGraph; if (m_resolution[2] / m_resolution[0] > 3.0) { stackGraph.setZMargin(2); } stackGraph.updateRange( x1, y1, z1, x2, y2, z2, getStack()->width(), getStack()->height(), getStack()->depth()); if (stackGraph.getRoiVolume() > MAX_P2P_TRACE_VOLUME) { return NULL; } stackGraph.setResolution(m_resolution); if (m_vertexOption == ZStackGraph::VO_SURFACE) { stackGraph.setWeightFunction(Stack_Voxel_Weight_I); } else { if (m_usingEdgePath) { stackGraph.setWeightFunction(Stack_Voxel_Weight_S); } else { if (m_backgroundType == NeuTube::IMAGE_BACKGROUND_BRIGHT) { stackGraph.setWeightFunction(Stack_Voxel_Weight_Sr); } else { stackGraph.setWeightFunction(Stack_Voxel_Weight_S); } } } ZIntCuboid box = stackGraph.getRange(); // if (m_usingEdgePath) { // box.setFirstCorner(imin2(x1, x2), imin2(y1, y2), imin2(z1, z2)); // box.setLastCorner(imax2(x1, x2), imax2(y1, y2), imax2(z1, z2)); // } Stack *partial = C_Stack::crop( getIntensityData(), box.getFirstCorner().getX(), box.getFirstCorner().getY(), box.getFirstCorner().getZ(), box.getWidth(), box.getHeight(), box.getDepth(), NULL); /* if (m_bcAdjust) { Stack_Scale(partial, 0, m_greyFactor, m_greyOffset); } */ if (m_usingEdgePath) { Stack *partialEdge = C_Stack::computeGradient(partial); C_Stack::kill(partial); partial = partialEdge; #ifdef _DEBUG_2 C_Stack::write(GET_TEST_DATA_DIR + "/test.tif", partial); #endif } stackGraph.inferWeightParameter(partial); ZVoxelArray voxelArray; std::vector<int> path; if (m_usingEdgePath) { int x0 = box.getFirstCorner().getX(); int y0 = box.getFirstCorner().getY(); int z0 = box.getFirstCorner().getZ(); int startIndex = C_Stack::indexFromCoord( x1 - x0, y1 - y0 , z1 - z0, C_Stack::width(partial), C_Stack::height(partial), C_Stack::depth(partial)); int endIndex = C_Stack::indexFromCoord( x2 - x0, y2 - y0, z2 - z0, C_Stack::width(partial), C_Stack::height(partial), C_Stack::depth(partial)); stackGraph.setRange(0, 0, 0, C_Stack::width(partial) - 1, C_Stack::height(partial) - 1, C_Stack::depth(partial) - 1); path = stackGraph.computeShortestPath( partial, startIndex, endIndex, m_vertexOption); for (size_t i = path.size(); i > 0; --i) { int x, y, z; C_Stack::indexToCoord(path[i - 1], C_Stack::width(partial), C_Stack::height(partial), &x, &y, &z); voxelArray.append(ZVoxel(x + x0, y + y0, z + z0)); } } else { int width = getStack()->width(); int height = getStack()->height(); int depth = getStack()->depth(); int startIndex = C_Stack::indexFromCoord( x1, y1, z1, width, height, depth); int endIndex = C_Stack::indexFromCoord( x2, y2, z2, width, height, depth); path = stackGraph.computeShortestPath( getIntensityData(), startIndex, endIndex, m_vertexOption); // C_Stack::kill(stackField); for (size_t i = path.size(); i > 0; --i) { int x, y, z; C_Stack::indexToCoord(path[i - 1], width, height, &x, &y, &z); voxelArray.append(ZVoxel(x, y, z)); } } C_Stack::kill(partial); double length = voxelArray.getCurveLength(); double dist = 0.0; const std::vector<ZVoxel> &voxelData = voxelArray.getInternalData(); for (size_t i = 0; i < path.size(); ++i) { double ratio = dist / length; double r = r1 * ratio + r2 * (1 - ratio); voxelArray.setValue(i, r); if (i < path.size() - 1) { dist += voxelData[i].distanceTo(voxelData[i+1]); } } Swc_Tree *tree = voxelArray.toSwcTree(); if (tree != NULL) { Swc_Tree_Translate( tree, stackOffset.getX(), stackOffset.getY(), stackOffset.getZ()); ZSwcSignalFitter fitter; fitter.setBackground(m_backgroundType); fitter.setFixingTerminal(true); fitter.fitSignal(tree, getStack(), getSignalChannel()); Swc_Tree_Node *leaf = tree->root; while (SwcTreeNode::firstChild(leaf) != NULL) { leaf = SwcTreeNode::firstChild(leaf); } SwcTreeNode::setPos(leaf, targetPos); } return tree; }
void ParticleSkinnedModel::update(float dt) { // Send update call to superclass Model::update(dt); const int PS_SUB_UPDATE_STEPS = 2; const int PS_CONSTRAINT_STEPS = 0; const float TARGET_TIME = (float)(1.0 / (60.0 * PS_SUB_UPDATE_STEPS)); dt = TARGET_TIME; if(m_simulateOnGPU) { int loc; Shader& shader = m_ps->getShader(); shader.bind(); loc = shader.getUniformLocation("modelMatrix"); glUniformMatrix4fv(loc, 1, false, glm::value_ptr(getTransform().getMat4())); loc = shader.getUniformLocation("invModelMatrix"); glUniformMatrix4fv(loc, 1, false, glm::value_ptr(getTransform().getInvMat4())); loc = shader.getUniformLocation("boneMatrix"); calculateAndSetBoneMatrices(loc); //loc = shader.getUniformLocation("randomForce"); for(int i=0; i<PS_SUB_UPDATE_STEPS; ++i) { m_ps->update(dt); } } else { const size_t max_bones = 128; glm::mat4 finalMat[max_bones]; // 16K on the stack thanks to this, perhaps allocate in heap? // The idéa is to make sure it is coherent in memory. std::vector<glm::vec3> targetPos(m_particles.size()); size_t boneCount = m_body->getBoneCount(); assert(boneCount < max_bones); calculateFinalBoneMatrices(finalMat, boneCount); for(size_t i=0; i<targetPos.size(); ++i) { const Body::sVertex& v = m_body->getVertexData()[i]; glm::vec4 finalPos(0.0f); for(size_t u=0; u<MAX_WEIGHTS; ++u) { if(v.weight[u].unused()) break; int index = v.weight[u].getIndex(); float weight = v.weight[u].getWeight(); finalPos += weight * finalMat[index] * glm::vec4(v.position, 1); } targetPos[i] = glm::vec3(finalPos); } const glm::vec3 externalForce(0); const glm::vec3 externalAcc(0,-9.82,0); const float maxDist = 0.1; for(int u=0; u<PS_SUB_UPDATE_STEPS; ++u) { // Simulate timesteps for(size_t i=0; i<m_particles.size(); ++i) { sParticle& p = m_particles[i]; glm::vec3& target = targetPos[i]; float mass = p.mass_k_d.x; float k = p.mass_k_d.y; float d = p.mass_k_d.z * 0.4f; //float len = glm::length(target - p.position); glm::vec3 attrForce = (target - p.position) * k; glm::vec3 force = externalForce + attrForce; glm::vec3 acc = externalAcc + force / mass; glm::vec3 pos = p.position; glm::vec3 vel = (1.0f - d) * (p.position - p.oldPosition) + acc * dt * dt; // This part can probably be optimized further // This is to make a soft clamp of the particle pos to the max allowed distance float dist = glm::distance(pos, target); glm::vec3 goPath = (pos-target) / dist; pos += vel; if(dist < maxDist) { p.oldPosition = p.position; p.position = pos; }else{ glm::vec3 maxDistPos = target + goPath * maxDist; p.position = glm::mix(pos, maxDistPos, glm::clamp(glm::distance(maxDistPos,pos), 0.0f, 1.0f)); p.oldPosition = p.position - vel; } } } const std::vector<Body::sVertex>& vertexData = m_body->getVertexData(); const float stiffness = 0.1f; for(int u=0; u<PS_CONSTRAINT_STEPS; ++u) { // Update constraints for(size_t i=0; i<m_constraints.size(); ++i) { size_t i0 = m_constraints[i].index[0]; size_t i1 = m_constraints[i].index[1]; sParticle& p0 = m_particles[i0]; sParticle& p1 = m_particles[i1]; float m0 = p0.mass_k_d.x; float m1 = p1.mass_k_d.x; glm::vec3 delta = p1.position - p0.position; glm::vec3 restDelta = vertexData[i1].position - vertexData[i0].position; float restLength2 = glm::dot(restDelta, restDelta); delta *= (1.0f - 2.0f * restLength2 / (restLength2 + glm::dot(delta,delta)) ) * (m0 + m1); glm::vec3 val = stiffness * delta; p0.position += val / m0; p1.position -= val / m1; } // Merge seems and maintain velocity for(size_t i=0; i<m_postVertexMerge.size(); ++i) { const unsigned int i0 = m_postVertexMerge[i].index[0]; const unsigned int i1 = m_postVertexMerge[i].index[1]; glm::vec3 v0 = m_particles[i0].position - m_particles[i0].oldPosition; glm::vec3 v1 = m_particles[i1].position - m_particles[i1].oldPosition; glm::vec3 p = m_particles[i0].position * 0.5f + m_particles[i1].position * 0.5f; m_particles[i0].position = p; m_particles[i0].oldPosition = p - v0; m_particles[i1].position = p; m_particles[i1].oldPosition = p - v1; } } // Update bufferdata! m_particleBuffer.bind(); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(sParticle) * m_particles.size(), &m_particles[0]); m_particleBuffer.unbind(); } }
void Pony::update() { if (isDead()) return; if (state == Pass) return; if (state == Still) { // Random pos. //int fromX = x / Common::MAP_CELL_SIZE; //int fromY = y / Common::MAP_CELL_SIZE; Vec2 targetPos(rand() % (48 * 8), rand() % (48 * 8)); // Get target. // target = world->getNearestTarget( x, y, 100000000, true ); // // if ( target ) // { // toX = target->x / Common::MAP_CELL_SIZE + 2; // toY = target->y / Common::MAP_CELL_SIZE + 2; // } // if (world->find(pos, targetPos, path) == 0) { state = Running; step = 0; } } if (state == Running) { // Target destroyed. // if ( target ) // { // if ( target->isDead() ) // { // state = Still; // return; // } // } // else // { // // Target appeared. // Unit* t = world->getNearestTarget( x, y, 100000000, true ); // if ( t ) // { // state = Still; // return; // } // } // Finish moving. if (step >= static_cast< int >( path.size())) { // Attack target. if (target) { state = Attack; //attackDelay = 0; } else { // Get new target. state = Still; return; } } else { // Move in progress. Vec2 t = path.at(step); //int targetX = path.at( step ).x * Common::MAP_CELL_SIZE; //int targetY = path.at( step ).y * Common::MAP_CELL_SIZE; if (pos.x < t.x) { pos.x++; directionRight = true; } if (pos.x > t.x) { pos.x--; directionRight = false; } if (pos.y < t.y) { pos.y++; directionRight = false; } if (pos.y > t.y) { pos.y--; directionRight = true; } if ((pos.x == t.x) && (pos.y == t.y)) { step++; } } } // if ( state == Attack ) // { // if ( !target ) // { // state = Still; // return; // } // // if ( target->isDead() ) // { // state = Still; // return; // } // // if ( attackDelay < getAttackDelay() ) // { // attackDelay++; // return; // } // // attackDelay = 0; // target->hit( getAttackPower() ); // } }
void ColoredCubeApp::updateScene(float dt) { D3DApp::updateScene(dt); if(GetAsyncKeyState(VK_ESCAPE)) PostQuitMessage(0); float moveRate = 1.0f; if(GetAsyncKeyState(VK_LSHIFT)) moveRate *= 2.0f; if(GetAsyncKeyState(VK_LCONTROL)) moveRate *= 0.1f; //Move camera with mouse if(!createdOriginPos) { mCursorOriginPos.x = 100; mCursorOriginPos.y = 100; ClientToScreen(mhMainWnd, &mCursorOriginPos); SetCursorPos(mCursorOriginPos.x, mCursorOriginPos.y); ShowCursor(false); createdOriginPos = true; } GetCursorPos(&mCursorPos); float myX = ((float)mCursorOriginPos.x - (float)mCursorPos.x); float myY = ((float)mCursorOriginPos.y - (float)mCursorPos.y); //if(dt < 0.01f) { mTheta += myX * 0.005f;// * dt * 4.0f; mPhi -= myY * 0.005f;// * dt * 4.0f; //myOutFile << std::fixed << std::setprecision(4) << dt << " " << mTheta << " " << mPhi << "\n"; } SetCursorPos(mCursorOriginPos.x, mCursorOriginPos.y); //Move camera with gamepad XINPUT_STATE state; ZeroMemory( &state, sizeof(XINPUT_STATE) ); DWORD gamepadConnected = XInputGetState(0, &state); if( gamepadConnected == ERROR_SUCCESS ) { float RX = state.Gamepad.sThumbRX; float RY = state.Gamepad.sThumbRY; float magnitude = sqrt(RX*RX + RY*RY); if(magnitude > 10000.0f) { mTheta += RX * dt * -0.0001f; mPhi += RY * dt * -0.00005f; } } // Move camera with keyboard // Update angles based on input to orbit camera around box. if(GetAsyncKeyState('J') & 0x8000) mTheta += 2.0f*dt; if(GetAsyncKeyState('L') & 0x8000) mTheta -= 2.0f*dt; if(GetAsyncKeyState('I') & 0x8000) mPhi -= 2.0f*dt; if(GetAsyncKeyState('K') & 0x8000) mPhi += 2.0f*dt; // Restrict the angle mPhi. if( mPhi < 0.1f ) mPhi = 0.1f; if( mPhi > PI-0.1f) mPhi = PI-0.1f; // Convert Spherical to Cartesian coordinates: mPhi measured from +y // and mTheta measured counterclockwise from -z. D3DXVECTOR3 targetPos( 5.0f*sinf(mPhi)*sinf(mTheta), 5.0f*cosf(mPhi), -5.0f*sinf(mPhi)*cosf(mTheta) ); if(gamepadConnected == ERROR_SUCCESS) { // Move the camera with the left thumbstick float LX = state.Gamepad.sThumbLX; float LY = state.Gamepad.sThumbLY; float magnitude = sqrt(LX*LX + LY*LY); if(magnitude > 10000.0f) { // Forward and Backward movement added to move; directionToMoveForwardBackward D3DXVECTOR3 directionToMoveForwardBackward(0.0f,0.0f,0.0f); directionToMoveForwardBackward = targetPos; D3DXVec3Normalize(&directionToMoveForwardBackward, &directionToMoveForwardBackward); directionToMoveForwardBackward *= state.Gamepad.sThumbLY * dt * 0.001f; mCameraPos += directionToMoveForwardBackward; // Right and Left movement added to move; directionToMoveRightLeft D3DXVECTOR3 directionToMoveRightLeft(0.0f,0.0f,0.0f); D3DXVECTOR3 pointAboveTarget( 5.0f*sinf(mPhi)*sinf(mTheta), 5.0f*cosf(mPhi)+0.1f, -5.0f*sinf(mPhi)*cosf(mTheta) ); D3DXVec3Cross(&directionToMoveRightLeft, &targetPos, &pointAboveTarget); D3DXVec3Normalize(&directionToMoveRightLeft, &directionToMoveRightLeft); directionToMoveRightLeft *= state.Gamepad.sThumbLX * dt * -0.001f; mCameraPos +=directionToMoveRightLeft; } } if( (GetAsyncKeyState('D') & 0x8000) || (GetAsyncKeyState('A') & 0x8000) || (GetAsyncKeyState('W') & 0x8000) || (GetAsyncKeyState('S') & 0x8000) || (gamepadConnected == ERROR_SUCCESS && state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) || (gamepadConnected == ERROR_SUCCESS && state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT) || (gamepadConnected == ERROR_SUCCESS && state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP) || (gamepadConnected == ERROR_SUCCESS && state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN) ) { D3DXVECTOR3 move(0.0f,0.0f,0.0f); if((GetAsyncKeyState('D') & 0x8000) || (gamepadConnected == ERROR_SUCCESS && state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT)) { D3DXVECTOR3 pointAboveTarget( 5.0f*sinf(mPhi)*sinf(mTheta), 5.0f*cosf(mPhi)+0.1f, -5.0f*sinf(mPhi)*cosf(mTheta) ); D3DXVECTOR3 directionToMove(0.0f,0.0f,0.0f); D3DXVec3Cross(&directionToMove, &targetPos, &pointAboveTarget); D3DXVec3Normalize(&directionToMove, &directionToMove); move = move - directionToMove; } if((GetAsyncKeyState('A') & 0x8000) || (gamepadConnected == ERROR_SUCCESS && state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT)) { D3DXVECTOR3 pointAboveTarget( 5.0f*sinf(mPhi)*sinf(mTheta), 5.0f*cosf(mPhi)+0.1f, -5.0f*sinf(mPhi)*cosf(mTheta) ); D3DXVECTOR3 directionToMove(0.0f,0.0f,0.0f); D3DXVec3Cross(&directionToMove, &targetPos, &pointAboveTarget); D3DXVec3Normalize(&directionToMove, &directionToMove); move = move + directionToMove; } if((GetAsyncKeyState('W') & 0x8000) || (gamepadConnected == ERROR_SUCCESS && state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP)) { D3DXVECTOR3 directionToMove(0.0f,0.0f,0.0f); directionToMove = targetPos; D3DXVec3Normalize(&directionToMove, &directionToMove); move = move + directionToMove; } if((GetAsyncKeyState('S') & 0x8000) || (gamepadConnected == ERROR_SUCCESS && state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN)) { D3DXVECTOR3 directionToMove(0.0f,0.0f,0.0f); directionToMove = targetPos; D3DXVec3Normalize(&directionToMove, &directionToMove); move = move - directionToMove; } D3DXVec3Normalize(&move, &move); mCameraPos += move * dt * 20.0f * moveRate; } if(GetAsyncKeyState('1')) { //mLights[1].specular = BLUE; mLights[1].pos = mCameraPos; } if(GetAsyncKeyState('2')) { mLights[1].specular = GREEN; } targetPos = targetPos + mCameraPos; // Build the view matrix. //D3DXVECTOR3 pos(cameraPos.x, cameraPos.y, cameraPos.z); //D3DXVECTOR3 target(mCameraVec.x, mCameraVec.y, mCameraVec.z); D3DXVECTOR3 target(targetPos.x, targetPos.y, targetPos.z); D3DXVECTOR3 pos(mCameraPos.x, mCameraPos.y, mCameraPos.z); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMatrixLookAtLH(&mView, &pos, &target, &up); }
void Mission::FollowCamera::onUpdateActivity(float dt) { assert( _scene ); _cameraFOV = 80.0f; _positionModeTimeout -= dt; _positionModeTimeout = _positionModeTimeout < 0 ? 0 : _positionModeTimeout; // retrieve action channels ActionChannel* headLeft = Gameplay::iGameplay->getActionChannel( iaHeadLeft ); ActionChannel* headRight = Gameplay::iGameplay->getActionChannel( iaHeadRight ); ActionChannel* headUp = Gameplay::iGameplay->getActionChannel( iaHeadUp ); ActionChannel* headDown = Gameplay::iGameplay->getActionChannel( iaHeadDown ); ActionChannel* zoomIn = Gameplay::iGameplay->getActionChannel( iaZoomIn ); ActionChannel* zoomOut = Gameplay::iGameplay->getActionChannel( iaZoomOut ); switch (_mode) { case FeetLeft: { // target position Matrix4f targetPose( 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1 ); if( _target ) targetPose = _target->getPose(); Vector3f targetPos( targetPose[3][0], targetPose[3][1], targetPose[3][2] ); Vector3f targetUp( targetPose[1][0], targetPose[1][1], targetPose[1][2] ); Vector3f targetRight( targetPose[0][0], targetPose[0][1], targetPose[0][2] ); Vector3f targetFront( targetPose[2][0], targetPose[2][1], targetPose[2][2] ); targetUp.normalize(); targetRight.normalize(); targetFront.normalize(); Vector3f cameraPos(targetPos); if( dynamic_cast<Jumper*>( _target ) ) { Jumper* j = dynamic_cast<Jumper*>( _target ); j->getClump()->getFrame()->getLTM(); engine::IFrame* backBone = Jumper::getBackBone( j->getClump() ); targetPos = backBone->getPos(); engine::IFrame* legBone = Jumper::getLeftSmokeJetAnchor(j->getClump()); cameraPos = legBone->getPos(); cameraPos += legBone->getAt() * 0.0f; // right cameraPos += legBone->getUp() * -10.0f; // up cameraPos += legBone->getRight() * -20.0f; // forward targetPos = cameraPos; targetPos += legBone->getAt() * -25.0f; // right targetPos += legBone->getRight() * 40.0f; // forward targetPos += legBone->getUp() * -25.0f; // up targetUp = legBone->getUp() * -8.0f + legBone->getAt() * -2.0f; targetUp.normalize(); } //cameraPos += targetUp * 45.0f - targetRight * 40.0f - targetFront * 100.0f; // camera direction Vector3f cameraAt = cameraPos - targetPos/* + targetFront * 50.0f*/; cameraAt.normalize(); // camera right Vector3f cameraRight; cameraRight.cross( targetUp, cameraAt ); cameraRight.normalize(); // camera up Vector3f cameraUp; cameraUp.cross( cameraAt, cameraRight ); cameraUp.normalize(); // camera matrix _cameraMatrix.set( cameraRight[0], cameraRight[1], cameraRight[2], 0.0f, cameraUp[0], cameraUp[1], cameraUp[2], 0.0f, cameraAt[0], cameraAt[1], cameraAt[2], 0.0f, cameraPos[0], cameraPos[1], cameraPos[2], 1.0f ); break; } case FeetRight: { // target position Matrix4f targetPose( 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1 ); if( _target ) targetPose = _target->getPose(); Vector3f targetPos( targetPose[3][0], targetPose[3][1], targetPose[3][2] ); Vector3f targetUp( targetPose[1][0], targetPose[1][1], targetPose[1][2] ); Vector3f targetRight( targetPose[0][0], targetPose[0][1], targetPose[0][2] ); Vector3f targetFront( targetPose[2][0], targetPose[2][1], targetPose[2][2] ); targetUp.normalize(); targetRight.normalize(); targetFront.normalize(); Vector3f cameraPos(targetPos); if( dynamic_cast<Jumper*>( _target ) ) { Jumper* j = dynamic_cast<Jumper*>( _target ); j->getClump()->getFrame()->getLTM(); engine::IFrame* backBone = Jumper::getBackBone( j->getClump() ); targetPos = backBone->getPos(); engine::IFrame* legBone = Jumper::getRightSmokeJetAnchor(j->getClump()); cameraPos = legBone->getPos(); cameraPos += legBone->getAt() * 0.0f; // right cameraPos += legBone->getUp() * -12.0f; // up cameraPos += legBone->getRight() * -20.0f; // forward targetPos = cameraPos; targetPos += legBone->getAt() * -25.0f; // right targetPos += legBone->getRight() * 40.0f; // forward targetPos += legBone->getUp() * -25.0f; // up targetUp = legBone->getUp() * -8.0f + legBone->getAt() * -2.0f; targetUp.normalize(); } //cameraPos += targetUp * 45.0f - targetRight * 40.0f - targetFront * 100.0f; // camera direction Vector3f cameraAt = cameraPos - targetPos/* + targetFront * 50.0f*/; cameraAt.normalize(); // camera right Vector3f cameraRight; cameraRight.cross( targetUp, cameraAt ); cameraRight.normalize(); // camera up Vector3f cameraUp; cameraUp.cross( cameraAt, cameraRight ); cameraUp.normalize(); // camera matrix _cameraMatrix.set( cameraRight[0], cameraRight[1], cameraRight[2], 0.0f, cameraUp[0], cameraUp[1], cameraUp[2], 0.0f, cameraAt[0], cameraAt[1], cameraAt[2], 0.0f, cameraPos[0], cameraPos[1], cameraPos[2], 1.0f ); break; } case Back: { // target position Matrix4f targetPose( 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1 ); if( _target ) targetPose = _target->getPose(); Vector3f targetPos( targetPose[3][0], targetPose[3][1], targetPose[3][2] ); Vector3f targetUp( targetPose[1][0], targetPose[1][1], targetPose[1][2] ); Vector3f targetRight( targetPose[0][0], targetPose[0][1], targetPose[0][2] ); Vector3f targetFront( targetPose[2][0], targetPose[2][1], targetPose[2][2] ); targetUp.normalize(); targetRight.normalize(); targetFront.normalize(); Vector3f cameraPos(targetPos); if( dynamic_cast<Jumper*>( _target ) ) { Jumper* j = dynamic_cast<Jumper*>( _target ); j->getClump()->getFrame()->getLTM(); engine::IFrame* backBone = Jumper::getBackBone( j->getClump() ); targetPos = backBone->getPos(); engine::IFrame* head = Jumper::getHelmetEquipAnchor(j->getClump()); cameraPos = head->getPos(); cameraPos += head->getAt() * -28.0f; // down cameraPos += head->getRight() * 0.0f; // left cameraPos += head->getUp() * -1.0f; // forward targetPos = cameraPos; targetPos += head->getAt() * -10.0f; // down targetPos += head->getRight() * 0.0f; // left targetPos += head->getUp() * -10.0f; // forward targetUp = head->getAt() * -1.0f; targetUp.normalize(); } //cameraPos += targetUp * 45.0f - targetRight * 40.0f - targetFront * 100.0f; // camera direction Vector3f cameraAt = cameraPos - targetPos/* + targetFront * 50.0f*/; cameraAt.normalize(); // camera right Vector3f cameraRight; cameraRight.cross( targetUp, cameraAt ); cameraRight.normalize(); // camera up Vector3f cameraUp; cameraUp.cross( cameraAt, cameraRight ); cameraUp.normalize(); // camera matrix _cameraMatrix.set( cameraRight[0], cameraRight[1], cameraRight[2], 0.0f, cameraUp[0], cameraUp[1], cameraUp[2], 0.0f, cameraAt[0], cameraAt[1], cameraAt[2], 0.0f, cameraPos[0], cameraPos[1], cameraPos[2], 1.0f ); break; } } // camera is actual now Gameplay::iEngine->getDefaultCamera()->setFOV( _cameraFOV ); Gameplay::iEngine->getDefaultCamera()->getFrame()->setMatrix( _cameraMatrix ); _scene->getScenery()->happen( this, EVENT_CAMERA_IS_ACTUAL ); if( _scene->getTopMode() ) _scene->getTopMode()->happen( this, EVENT_CAMERA_IS_ACTUAL ); // RT-RS pass bool flares = ( _scene->getLocation()->getWeather() == ::wtSunny ) || ( _scene->getLocation()->getWeather() == ::wtVariable ); Gameplay::iGameplay->getRenderTarget()->render( _scene, _cameraMatrix, _cameraFOV, flares, false ); // GUI Gameplay::iEngine->getDefaultCamera()->beginScene( 0, Vector4f( 0,0,0,0 ) ); if( _scene->isHUDEnabled() ) Gameplay::iGui->render(); Gameplay::iEngine->getDefaultCamera()->endScene(); // present result Gameplay::iEngine->present(); }
void Mission::ThirdPersonCamera::onUpdateActivity(float dt) { assert( _scene ); _positionModeTimeout -= dt; _positionModeTimeout = _positionModeTimeout < 0 ? 0 : _positionModeTimeout; // retrieve action channels ActionChannel* headLeft = Gameplay::iGameplay->getActionChannel( iaHeadLeft ); ActionChannel* headRight = Gameplay::iGameplay->getActionChannel( iaHeadRight ); ActionChannel* headUp = Gameplay::iGameplay->getActionChannel( iaHeadUp ); ActionChannel* headDown = Gameplay::iGameplay->getActionChannel( iaHeadDown ); ActionChannel* zoomIn = Gameplay::iGameplay->getActionChannel( iaZoomIn ); ActionChannel* zoomOut = Gameplay::iGameplay->getActionChannel( iaZoomOut ); if( _positionMode ) { // field of view _cameraFOV = ( 60.0f - 55.0f * ( zoomIn->getAmplitude() ) ) * CAMERA_FOV_MULTIPLIER; // target position Matrix4f targetPose( 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1 ); if( _target ) targetPose = _target->getPose(); Vector3f targetPos( targetPose[3][0], targetPose[3][1], targetPose[3][2] ); if( dynamic_cast<Jumper*>( _target ) ) { Jumper* j = dynamic_cast<Jumper*>( _target ); j->getClump()->getFrame()->getLTM(); engine::IFrame* backBone = Jumper::getBackBone( j->getClump() ); targetPos = backBone->getPos(); } // camera direction Vector3f cameraAt = _cameraPos - targetPos; cameraAt.normalize(); // camera right Vector3f cameraRight; cameraRight.cross( Vector3f(0,1,0), cameraAt ); cameraRight.normalize(); // camera up Vector3f cameraUp; cameraUp.cross( cameraAt, cameraRight ); cameraUp.normalize(); // camera matrix _cameraMatrix.set( cameraRight[0], cameraRight[1], cameraRight[2], 0.0f, cameraUp[0], cameraUp[1], cameraUp[2], 0.0f, cameraAt[0], cameraAt[1], cameraAt[2], 0.0f, _cameraPos[0], _cameraPos[1], _cameraPos[2], 1.0f ); } else { // camera offset _cameraDistance -= dt * 500.0f * zoomIn->getAmplitude(); _cameraDistance += dt * 500.0f * zoomOut->getAmplitude(); if( _cameraDistance < TPSM_MINIMAL_DISTANCE ) _cameraDistance = TPSM_MINIMAL_DISTANCE; // rotate camera _cameraTurn += 180 * dt * headLeft->getAmplitude(); _cameraTurn -= 180 * dt * headRight->getAmplitude(); _cameraTilt += 180 * dt * headUp->getAmplitude(); _cameraTilt -= 180 * dt * headDown->getAmplitude(); if( _cameraTilt < -89 ) _cameraTilt = -89; if( _cameraTilt > 89 ) _cameraTilt = 89; Matrix4f targetPose( 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1 ); if( _target ) targetPose = _target->getPose(); Vector3f targetPos( targetPose[3][0], targetPose[3][1], targetPose[3][2] ); Vector3f targetOffset( 0,150,0 ); if( dynamic_cast<Jumper*>( _target ) ) { Jumper* j = dynamic_cast<Jumper*>( _target ); j->getClump()->getFrame()->getLTM(); engine::IFrame* backBone = Jumper::getBackBone( j->getClump() ); targetPos = backBone->getPos(); targetOffset.set( 0,75, 0 ); } // calculate camera matrix _cameraMatrix.set( 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1 ); _cameraMatrix = Gameplay::iEngine->rotateMatrix( _cameraMatrix, Vector3f( 1,0,0 ), _cameraTilt ); _cameraMatrix = Gameplay::iEngine->rotateMatrix( _cameraMatrix, Vector3f( 0,1,0 ), _cameraTurn ); Vector3f at( _cameraMatrix[2][0], _cameraMatrix[2][1], _cameraMatrix[2][2] ); // possible camera position Vector3f cameraPos = targetPos + targetOffset + at * _cameraDistance; // clip camera distance float clipDistance = _cameraDistance; if( _scene->clipCameraRay( targetPos, cameraPos, clipDistance ) ) { _cameraDistance = clipDistance; cameraPos = targetPos + targetOffset + at * _cameraDistance; } // finalize camera matrix (translation component) _cameraMatrix = Gameplay::iEngine->translateMatrix( _cameraMatrix, cameraPos ); } // camera is actual now Gameplay::iEngine->getDefaultCamera()->setFOV( _cameraFOV ); Gameplay::iEngine->getDefaultCamera()->getFrame()->setMatrix( _cameraMatrix ); _scene->getScenery()->happen( this, EVENT_CAMERA_IS_ACTUAL ); if( _scene->getTopMode() ) _scene->getTopMode()->happen( this, EVENT_CAMERA_IS_ACTUAL ); // RT-RS pass bool flares = ( _scene->getLocation()->getWeather() == ::wtSunny ) || ( _scene->getLocation()->getWeather() == ::wtVariable ); Gameplay::iGameplay->getRenderTarget()->render( _scene, _cameraMatrix, _cameraFOV, flares, false ); // GUI Gameplay::iEngine->getDefaultCamera()->beginScene( 0, Vector4f( 0,0,0,0 ) ); if( _scene->isHUDEnabled() ) Gameplay::iGui->render(); Gameplay::iEngine->getDefaultCamera()->endScene(); // present result Gameplay::iEngine->present(); }
int main() { G4double rot2 = 0*deg; Target tar; G4ThreeVector p0n( tar.GetLength()/2.0, tar.GetWidth()/2.0, -tar.GetThickness()/2.0); G4ThreeVector p1n( tar.GetLength()/2.0,-tar.GetWidth()/2.0, -tar.GetThickness()/2.0); G4ThreeVector p2n(-tar.GetLength()/2.0,-tar.GetWidth()/2.0, -tar.GetThickness()/2.0); G4ThreeVector p3n(-tar.GetLength()/2.0, tar.GetWidth()/2.0, -tar.GetThickness()/2.0); G4ThreeVector p0p( tar.GetLength()/2.0, tar.GetWidth()/2.0, tar.GetThickness()/2.0); G4ThreeVector p1p( tar.GetLength()/2.0,-tar.GetWidth()/2.0, tar.GetThickness()/2.0); G4ThreeVector p2p(-tar.GetLength()/2.0,-tar.GetWidth()/2.0, tar.GetThickness()/2.0); G4ThreeVector p3p(-tar.GetLength()/2.0, tar.GetWidth()/2.0, tar.GetThickness()/2.0); G4RotationMatrix rMatrix; G4ThreeVector a1(1,0,0); G4ThreeVector a2(0,1,0); G4ThreeVector a3(-1,0,1); G4RotationMatrix rM1; rM1.set(a1, 90.0*deg); G4RotationMatrix rM2; rM2.set(a2, 45.0*deg); G4RotationMatrix rM3; rM3.set(a3,-45.0*deg + rot2); rMatrix = rM1*rM2*rM3; // rMatrix.print(std::cout); G4RotationMatrix rotMatrix = rMatrix.inverse(); rotMatrix.print(std::cout); std::cout << "phi=" << rotMatrix.getPhi()/deg << std::endl; std::cout << "theta=" << rotMatrix.getTheta()/deg << std::endl; std::cout << "psi=" << rotMatrix.getPsi()/deg << std::endl; G4ThreeVector p0np = rotMatrix*p0n; G4ThreeVector p1np = rotMatrix*p1n; G4ThreeVector p2np = rotMatrix*p2n; G4ThreeVector p3np = rotMatrix*p3n; G4ThreeVector p0pp = rotMatrix*p0p; G4ThreeVector p1pp = rotMatrix*p1p; G4ThreeVector p2pp = rotMatrix*p2p; G4ThreeVector p3pp = rotMatrix*p3p; std::cout << "p0n: " << p0n << " --> " << p0np << std::endl; std::cout << "p1n: " << p1n << " --> " << p1np << std::endl; std::cout << "p2n: " << p2n << " --> " << p2np << std::endl; std::cout << "p3n: " << p3n << " --> " << p3np << std::endl; std::cout << '\n' << std::endl; std::cout << "p0p: " << p0p << " --> " << p0pp << std::endl; std::cout << "p1p: " << p1p << " --> " << p1pp << std::endl; std::cout << "p2p: " << p2p << " --> " << p2pp << std::endl; std::cout << "p3p: " << p3p << " --> " << p3pp << std::endl; std::cout << "\nCenter of the bottom of the target" << std::endl; G4ThreeVector tar_bottom_center = 0.5*(p2np+p3np); std::cout << tar_bottom_center << std::endl; // to compute the offsets // we know that the target is shifted 1.38 cm in the negative x direction // of the rotated coordinate system. This was computed in the Notes/TargetOffsetCalcs.ods // file through the measurement of images of the target in the mount. G4double tar_offset = 1.38*cm; G4ThreeVector xp = rotMatrix.colX(); xp *= -1.0*tar_offset; std::cout << "The target is actually offset from the base" << "\nof the mount slit. The base of the slit then should be" << "\ndisplaced by the following vector" << std::endl; std::cout << xp << " (mm)" << std::endl; std::cout << "\nThe displacement of the target from the is defined in the FragSimDetConstruction class." << "\nThe mount is positioned relative to the position of the target. An absolute" << "\nposition is acquired by adding the recently computed offset to the bottom center" << "\nof the target." << std::endl; std::cout << "\nCenter of mount slit = " << tar_bottom_center+xp << " (mm)" << std::endl; G4double tar_overhang = 0.25*cm; //<-- Calculated in TargetOffsetCalcs.ods // this is the average value of two methods G4double mount_slit_width = 2.54*cm; std::cout << "\nThe target overhangs the edge of the mount as well. To account for this overhang" << "\nthe mount and sh metal plates are shifted in the +y' direction of the rotated coord" << "\nsystem." << std::endl; G4double yp_shift =-1.0*(0.5*(mount_slit_width - tar.GetWidth()) + tar_overhang); G4ThreeVector yp = yp_shift*rotMatrix.colY(); std::cout << "\nOverhang = " << tar_overhang/cm << " cm"; std::cout << "\nShift in yp= " << yp_shift/cm << " cm" << std::endl; std::cout << "\nAlso we know that the target is offset by the thickness of the sheet metal" << "\nin the new z direction. Therefore, there must be a shift downwards" << "\nin the mount along the new z-direction by 0.127 cm." << std::endl; G4double sh_thickness = 0.127*cm; G4ThreeVector zp = rotMatrix.colZ(); zp *= -1.0*sh_thickness; // The following measurements were computed using the 232Th_Inventor_Model_measurements.ods file // in the Ubuntu\ One/AnalysisLog folder. G4double target_x = -0.44*cm; G4double target_y = -0.01*cm; G4double target_z = -1.67*cm; G4ThreeVector targetPos(target_x, target_y, target_z); G4ThreeVector mount_transl = targetPos + tar_bottom_center + xp + yp + zp; std::cout << "\n\nThe target offset was " << targetPos << " (mm)" << std::endl; std::cout << "\n\nSlit center should then be at the following location: " << mount_transl << " (mm)" << std::endl; std::cout << "\n\nThe sheet metal inserts used to clamp the target in " << "\nplace are positioned with the same rotation matrix as " << "\nthe target but with the following translations" << std::endl; G4double sh_length = 2.54*cm; // The way to compute this is by determining the offset from the center of the // target to align the bottom of the insert with the bottom of the target. // These are only aligned in for the 238U data. // Prior to rotation and translation, the centers of both the target and the // sheet metal will be aligned. The difference can then be computed as : G4double sh_shift = 0.5*(tar.GetLength()-sh_length); /////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------------------------------- // Compute shift for the top plat // // The shift will be in the rotated x direction G4ThreeVector sh_bot_shift_xp = -1.0*(sh_shift + tar_offset) * rotMatrix.colX(); G4double bsheet_shift_offset = 0*cm; G4double bsheet_shift = 0.47*cm + bsheet_shift_offset; sh_bot_shift_xp += bsheet_shift*rotMatrix.colX(); // the next is the actual offset of the sheet metal plate from the bottom of the slit // the calculation is found in TargetOffSetCalcs.ods G4ThreeVector sh_bot_shift_yp = 0.0*cm * rotMatrix.colY();// sh_bot_shift += -0.5*yp; G4ThreeVector sh_bot_shift_zp = -0.5*(tar.GetThickness()+sh_thickness)*rotMatrix.colZ(); G4ThreeVector sh_bot_shift = sh_bot_shift_xp + sh_bot_shift_yp + sh_bot_shift_zp; /////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------------------------------- // Compute shift for the bottom plate // G4ThreeVector sh_top_shift_xp = -1.0*(sh_shift+tar_offset)*rotMatrix.colX(); // the next is the actual offset of the sheet metal plate from the bottom of the slit // the calculation is found in TargetOffSetCalcs.ods sh_top_shift_xp += 0.3*cm*rotMatrix.colX(); G4ThreeVector sh_top_shift_yp = 0.0*cm * rotMatrix.colY(); // G4ThreeVector sh_top_shift_yp = 0.5*yp; G4ThreeVector sh_top_shift_zp = 0.5*(tar.GetThickness()+sh_thickness)*rotMatrix.colZ(); G4ThreeVector sh_top_shift = sh_top_shift_xp + sh_top_shift_yp + sh_top_shift_zp; ///////////////////////////////////////////////////////////////////////////////// // ------------------------------------------------------------------------------ // Print results // std::cout << "\nRotation (rot2): " << rot2/deg << " degrees" << "\nBot. sh. shift): " << bsheet_shift_offset/cm << " (cm)" << "\n--------------------------------------------" << std::endl; std::cout << "\nmount_transl : " << mount_transl << " (mm)" << std::endl; std::cout << "\nins_bot_transl : " << sh_bot_shift + targetPos << " (mm)" << std::endl; std::cout << "\nins_top_transl : " << sh_top_shift + targetPos << " (mm)" << std::endl; return 0; }