def __getCollisionTestOrigin(self, aimPoint, direction): distRange = self._cfg['distRange'] vehiclePosition = BigWorld.player().getVehicleAttached().position collisionTestOrigin = Vector3(vehiclePosition) if direction.x * direction.x > direction.z * direction.z and not math_utils.almostZero( direction.x): collisionTestOrigin.y = direction.y / direction.x * ( vehiclePosition.x - aimPoint.x) + aimPoint.y elif not math_utils.almostZero(direction.z): collisionTestOrigin.y = direction.y / direction.z * ( vehiclePosition.z - aimPoint.z) + aimPoint.y else: collisionTestOrigin = aimPoint - direction.scale( (distRange[1] - distRange[0]) / 2.0) LOG_WARNING( "Can't find point on direction ray. Using half point as collision test origin" ) return collisionTestOrigin
def create(self, onChangeControlMode=None): self.__onChangeControlMode = onChangeControlMode aimingSystemClass = ArtyAimingSystemRemote if BigWorld.player( ).isObserver() else ArtyAimingSystem self.__aimingSystem = aimingSystemClass() self.__camDist = self.__cfg['camDist'] self.__desiredCamDist = self.__camDist self.__positionHysteresis = PositionHysteresis( self.__cfg['hPositionThresholdSq']) self.__timeHysteresis = TimeHysteresis(self.__cfg['hTimeThreshold']) self.__cam.pivotMaxDist = 0.0 self.__cam.maxDistHalfLife = 0.01 self.__cam.movementHalfLife = 0.0 self.__cam.turningHalfLife = -1 self.__cam.pivotPosition = Vector3(0.0, 0.0, 0.0) self.__sourceMatrix = Matrix() self.__targetMatrix = Matrix() self.__rotation = 0.0
def getDesiredShotPoint(self, scanStart, scanDir): scanPos, isPointConvenient = self.__testMouseTargetPoint( scanStart, scanDir) if isPointConvenient: return scanPos planePos = self.__aimPlane.intersectRay(scanStart, scanDir) if scanStart.distSqrTo(planePos) < scanStart.distSqrTo(scanPos): return scanPos turretYaw, gunPitch = AimingSystems.getTurretYawGunPitch( self.__vehicleDesc, self.__vehicleMat, planePos, True) gunMat = AimingSystems.getGunJointMat(self.__vehicleDesc, self.__getTurretMat(turretYaw), gunPitch) aimDir = gunMat.applyVector(Vector3(0.0, 0.0, 1.0)) shotDistance = self.__vehicleDesc.shot.maxDistance return AimingSystems.getDesiredShotPoint(gunMat.translation, aimDir, shotDistance=shotDistance)
def randomStrike(self, source, basis, origin, left): pos = basis dpos = Vector3(random.random() * 2.0 - 1.0, 0.0, random.random() * 2.0 - 1.0) dpos.normalise() dpos[1] = random.random() * 0.1 dpos.normalise() dotp = basis.dot(dpos) dpLeft = dotp < 0.0 if left == dpLeft: dpos = dpos.scale(self.maxRange) else: dpos = dpos.scale(-self.maxRange) dpos = dpos + origin res = BigWorld.collide(source.spaceID, origin, dpos) if not res: return dpos return res[0]
def __init__(self, width, height, depth, scale): self.__scale = scale self.__width = round(width * self.__scale, 3) self.__height = round(height * self.__scale, 3) self.__depth = round(depth * self.__scale, 3) self.__dirVectors = [ Vector3(0.0, 0.0, 0.0), Vector3(0.0, self.__height, 0.0), Vector3(self.__width, 0.0, 0.0), Vector3(0.0, -self.__height, 0.0), Vector3(-self.__width, 0.0, 0.0), Vector3(0.0, 0.0, -self.__depth), Vector3(0.0, 0.0, self.__depth) ] self.__dirNames = [ 'Center', 'Up', 'Right', 'Down', 'Left', 'Back', 'Forward' ]
def createOscillatorFromSection(oscillatorSection, constraintsAsAngle = True): constraints = readVec3(oscillatorSection, 'constraints', (0.0, 0.0, 0.0), (175.0, 175.0, 175.0), 10.0) if constraintsAsAngle: constraints = Vector3((math.radians(constraints.x), math.radians(constraints.y), math.radians(constraints.z))) constructorParams = {'oscillator': __getOscillatorParams, 'noiseOscillator': __getNoiseOscillatorParams, 'randomNoiseOscillatorFlat': __getRandomNoiseOscillatorFlatParams, 'randomNoiseOscillatorSpherical': __getRandomNoiseOscillatorSphericalParams}.get(oscillatorSection.name, __getOscillatorParams)(oscillatorSection) oscillator = None if oscillatorSection.name == 'noiseOscillator': oscillator = Math.PyNoiseOscillator(*constructorParams) elif oscillatorSection.name == 'randomNoiseOscillatorFlat': oscillator = Math.PyRandomNoiseOscillatorFlat(*constructorParams) elif oscillatorSection.name == 'randomNoiseOscillatorSpherical': oscillator = Math.PyRandomNoiseOscillatorSpherical(*constructorParams) else: constructorParams.append(constraints) oscillator = Math.PyOscillator(*constructorParams) return oscillator
def createOscillatorFromSection(oscillatorSection, constraintsAsAngle = True): constraints = readVec3(oscillatorSection, 'constraints', (0.0, 0.0, 0.0), (175.0, 175.0, 175.0), 10.0) if constraintsAsAngle: constraints = Vector3((math.radians(constraints.x), math.radians(constraints.y), math.radians(constraints.z))) constructorParams = {'oscillator': __getOscillator3dParams, 'noiseOscillator': __getOscillator3dParams, 'randomNoiseOscillatorFlat': __getOscillator1dParams, 'randomNoiseOscillatorSpherical': __getRandomNoiseOscillatorSphericalParams}.get(oscillatorSection.name, __getOscillator3dParams)(oscillatorSection) constructor = Oscillator if oscillatorSection.name == 'noiseOscillator': constructor = NoiseOscillator elif oscillatorSection.name == 'randomNoiseOscillatorFlat': constructor = RandomNoiseOscillatorFlat elif oscillatorSection.name == 'randomNoiseOscillatorSpherical': constructor = RandomNoiseOscillatorSpherical else: constructorParams['constraints'] = constraints oscillator = constructor(**constructorParams) return oscillator
def activateMapCase(equipmentID, deactivateCallback): inputHandler = BigWorld.player().inputHandler if isinstance(inputHandler.ctrl, MapCaseControlMode): if MapCaseControlMode.deactivateCallback is not None: MapCaseControlMode.deactivateCallback() MapCaseControlMode.deactivateCallback = deactivateCallback inputHandler.ctrl.activateEquipment(equipmentID) else: MapCaseControlMode.deactivateCallback = deactivateCallback pos = inputHandler.getDesiredShotPoint() if pos is None: camera = getattr(inputHandler.ctrl, 'camera', None) if camera is not None: pos = camera.aimingSystem.getDesiredShotPoint() if pos is None: pos = Vector3(0.0, 0.0, 0.0) MapCaseControlMode.prevCtlMode = [pos, inputHandler.ctrlModeName, inputHandler.ctrl.aimingMode] inputHandler.onControlModeChanged('mapcase', preferredPos=pos, aimingMode=AIMING_MODE.USER_DISABLED, equipmentID=equipmentID) return
def __init__(self, dataSec): CallbackDelayer.__init__(self) self.__positionOscillator = None self.__positionNoiseOscillator = None self.__activeDistRangeSettings = None self.__dynamicCfg = CameraDynamicConfig() self.__cameraYaw = 0.0 self.__readCfg(dataSec) self.__cam = BigWorld.CursorCamera() self.__cam.isHangar = False self.__curSense = self.__cfg['sensitivity'] self.__onChangeControlMode = None self.__aimingSystem = None self.__prevTime = BigWorld.time() self.__autoUpdatePosition = False self.__dxdydz = Vector3(0, 0, 0) self.__needReset = 0 self.__smoothingPivotDelta = 0 return
class StrategicAimingSystem(IAimingSystem): _LOOK_DIR = Vector3(0, -math.cos(0.001), math.sin(0.001)) height = property(lambda self: self.__height) heightFromPlane = property(lambda self: self.__heightFromPlane) def __init__(self, height, yaw): self._matrix = mathUtils.createRotationMatrix((yaw, 0, 0)) self.__planePosition = Vector3(0, 0, 0) self.__height = height self.__heightFromPlane = 0.0 def destroy(self): pass def enable(self, targetPos): self.updateTargetPos(targetPos) def disable(self): pass def getDesiredShotPoint(self, terrainOnlyCheck = False): return AimingSystems.getDesiredShotPoint(self._matrix.translation, Vector3(0, -1, 0), True, True, terrainOnlyCheck) def handleMovement(self, dx, dy): shift = self._matrix.applyVector(Vector3(dx, 0, dy)) self.__planePosition += Vector3(shift.x, 0, shift.z) self.__updateMatrix() def updateTargetPos(self, targetPos): self.__planePosition.x = targetPos.x self.__planePosition.z = targetPos.z self.__updateMatrix() def __updateMatrix(self): bb = BigWorld.player().arena.arenaType.boundingBox pos2D = _clampPoint2DInBox2D(bb[0], bb[1], Math.Vector2(self.__planePosition.x, self.__planePosition.z)) self.__planePosition.x = pos2D[0] self.__planePosition.z = pos2D[1] collPoint = BigWorld.wg_collideSegment(BigWorld.player().spaceID, self.__planePosition + Math.Vector3(0, 1000.0, 0), self.__planePosition + Math.Vector3(0, -250.0, 0), 3) self.__heightFromPlane = 0.0 if collPoint is None else collPoint[0][1] self._matrix.translation = self.__planePosition + Vector3(0, self.__heightFromPlane + self.__height, 0) return
def __getVehicleMatrixProvider(self, cmd, vehicleID=None): if vehicleID is None: vehicleID = self.__getVehicleIDByCmd(cmd) vehicle = BigWorld.entities.get(vehicleID) if vehicle is None: position = BigWorld.player().arena.positions.get(vehicleID) if position is not None: maxDistance = 600.0 playerVehiclePosition = BigWorld.player( ).getOwnVehiclePosition() if Vector3(position).distSqrTo( playerVehiclePosition) > maxDistance * maxDistance: direction = position - playerVehiclePosition direction.normalise() return createTranslationMatrix(playerVehiclePosition + direction * maxDistance) return createTranslationMatrix(position) return else: return Matrix(vehicle.matrix)
def focusAtPos(self, scanStart, scanDir, yawPitch=None): scanPos, isPointConvenient = self.__testMouseTargetPoint( scanStart, scanDir) if not isPointConvenient: if yawPitch is not None: turretYaw, gunPitch = yawPitch gunMat = AimingSystems.getGunJointMat( self.__vehicleDesc, self.__getTurretMat(turretYaw), gunPitch) planePos = self.__aimPlane.intersectRay( gunMat.translation, gunMat.applyVector(Vector3(0, 0, 1)), False, False) else: planePos = self.__aimPlane.intersectRay(scanStart, scanDir) if scanStart.distSqrTo(planePos) < scanStart.distSqrTo(scanPos): return scanPos return planePos else: self.__aimPlane.init(scanStart, scanPos) return scanPos
def __init__(self, dataSec, aim): CallbackDelayer.__init__(self) self.__positionOscillator = None self.__positionNoiseOscillator = None self.__dynamicCfg = CameraDynamicConfig() self.__readCfg(dataSec) self.__cam = BigWorld.CursorCamera() self.__curSense = self.__cfg['sensitivity'] self.__onChangeControlMode = None self.__aimingSystem = StrategicAimingSystem( self.__cfg['distRange'][0], StrategicCamera._CAMERA_YAW) self.__prevTime = BigWorld.time() self.__aimOffsetFunc = None if aim is None: self.__aimOffsetFunc = lambda x=None: (0, 0) else: self.__aimOffsetFunc = aim.offset self.__autoUpdatePosition = False self.__dxdydz = Vector3(0, 0, 0) self.__needReset = 0
def __interpolateStates(self, deltaTime, rotation, desiredDistance, collisionDist): lerpParam = math_utils.clamp( 0.0, 1.0, deltaTime * self._cfg['interpolationSpeed']) collisionLerpParam = math_utils.clamp( 0.0, 1.0, deltaTime * self._cfg['distInterpolationSpeed']) self.__sourceMatrix = slerp(self.__sourceMatrix, rotation, lerpParam) camDirection = Vector3() camDirection.setPitchYaw(-self.__sourceMatrix.pitch, self.__sourceMatrix.yaw) camDirection.normalise() self.__camViewPoint = math_utils.lerp(self.__camViewPoint, self.__aimingSystem.aimPoint, lerpParam) self.__collisionDist = math_utils.lerp(self.__collisionDist, collisionDist, collisionLerpParam) desiredDistance = max(desiredDistance, self.__collisionDist) self.__targetMatrix.translation = self.__camViewPoint - camDirection.scale( desiredDistance) return (self.__sourceMatrix, self.__targetMatrix)
def shootProjectile(owner, target, projectile, trail=None, boom=None, srcoff=Vector3(0, 1.5, 0), dstoff=Vector3(0, 1.2, 0), motor=None): if hasattr(target, 'matrix'): targetMatrix = target.matrix else: targetMatrix = target if not boom and dstoff: dstoff.y = 1.8 if not dstoff: dstoff = Vector3(0, 0, 0) owner.addModel(projectile) projectile.position = Vector3(owner.position) + srcoff if not motor: motor = BigWorld.Homer() motor.speed = projectileSpeed motor.turnRate = 10 if dstoff.lengthSquared == 0: motor.target = targetMatrix else: motor.target = MatrixProduct() motor.target.a = targetMatrix motor.target.b = Matrix() motor.target.b.setTranslate(dstoff) if motor.tripTime <= 0.0: sourcePosition = Vector3(owner.position) + srcoff targetPosition = Vector3(Matrix(targetMatrix).applyToOrigin()) + dstoff speed = motor.speed t = calculateTripTime(sourcePosition, targetPosition, speed) if t == 0: owner.delModel(projectile) return 0 motor.tripTime = t projectile.addMotor(motor) if trail: trail(projectile, None, motor.tripTime) motor.proximity = 1.0 if boom: motor.proximityCallback = boom else: motor.proximityCallback = partial(owner.delModel, projectile) return motor.tripTime
def __init__(self, dataSec): CallbackDelayer.__init__(self) self.__positionOscillator = None self.__positionNoiseOscillator = None self.__dynamicCfg = CameraDynamicConfig() self.__readCfg(dataSec) self.__cam = BigWorld.CursorCamera() self.__curSense = self.__cfg['sensitivity'] self.__onChangeControlMode = None self.__camDist = 0.0 self.__desiredCamDist = 0.0 self.__aimingSystem = None self.__prevTime = 0.0 self.__dxdydz = Vector3(0.0, 0.0, 0.0) self.__autoUpdatePosition = False self.__needReset = 0 self.__sourceMatrix = None self.__targetMatrix = None self.__rotation = 0.0 self.__positionHysteresis = None self.__timeHysteresis = None return
def setupTank(chassisFashion, gunFashion, vehicleDesc, worldMatrix, resources): print resources tank = resources[vehicleDesc.name] tank.matrix = worldMatrix tanks.append(tank) effect = Pixie.create('particles/Tank/exhaust/large_gas_gear.xml') tank.node('HP_gunFire').attach(effect) tank.node('HP_gunFire').attach(BigWorld.Model('helpers/models/position_gizmo.model')) tank.node('HP_Track_Exhaus_1').attach(BigWorld.Model('helpers/models/unit_cube.model')) m = mathUtils.createTranslationMatrix(Vector3(0, 10, 5)) fakeMatrixes.append(m) tank.node('gun').attach(effect.clone(), m) BigWorld.addModel(tank) recoilDescr = vehicleDesc.gun['recoil'] recoil = BigWorld.RecoilAnimator(recoilDescr['backoffTime'], recoilDescr['returnTime'], recoilDescr['amplitude'], recoilDescr['lodDist']) recoil.basisMatrix = tank.node('G').localMatrix recoil = assemblerModule.createGunAnimator(vehicleDesc, tank.node('G').localMatrix) recoil.lodSetting = 10 tank.node('G', recoil) gunFashion.gunLocalMatrix = recoil recoil.lodLink = DataLinks.createFloatLink(chassisFashion, 'lastLod') swingingAnimator = assemblerModule.createSwingingAnimator(vehicleDesc, tank.node('hull').localMatrix, worldMatrix) chassisFashion.setupSwinging(swingingAnimator, 'hull') swingingAnimator.lodLink = DataLinks.createFloatLink(chassisFashion, 'lastLod') tank.setupFashions([chassisFashion, None, None, gunFashion]) fashions.append(swingingAnimator) tank.node('hull', swingingAnimator) animMatrix = Math.MatrixAnimation() keys = [] for x in xrange(100): angle = math.pi * 0.5 * (1 if x & 1 else -1) keys.append((x * 3, mathUtils.createRotationMatrix((angle, 0, 0)))) animMatrix.keyframes = tuple(keys) tank.node('turret', animMatrix) return
def writeWheelsAndGroups(wheelsConfig, section): wheelId = 0 groupId = 0 defSyncAngle = section.readFloat('wheels/leadingWheelSyncAngle', 60) for sname, subsection in _xml.getChildren(None, section, 'wheels'): if sname == 'group': group = wheelsConfig.groups[groupId] _xml.rewriteString(subsection, 'template', group.template) _xml.rewriteInt(subsection, 'count', group.count, 1) _xml.rewriteInt(subsection, 'startIndex', group.startIndex, 0) _xml.rewriteFloat(subsection, 'radius', group.radius) groupId += 1 if sname == 'wheel': from items.vehicles import _writeHitTester, _writeArmor index = _xml.readIntOrNone(None, subsection, 'index') if index is not None: wheelId = index wheel = wheelsConfig.wheels[wheelId] radiusKey = 'radius' if subsection.has_key( 'radius') else 'geometry/radius' _xml.rewriteInt(subsection, 'index', wheelId, createNew=False) _xml.rewriteFloat(subsection, radiusKey, wheel.radius) _xml.rewriteString(subsection, 'name', wheel.nodeName) _xml.rewriteBool(subsection, 'isLeading', wheel.isLeading) _xml.rewriteFloat(subsection, 'syncAngle', wheel.leadingSyncAngle, defSyncAngle) _xml.rewriteVector3(subsection, 'wheelPos', wheel.position, Vector3(0, 0, 0)) _writeHitTester(wheel.hitTesterManager, None, subsection, 'hitTester') _writeArmor(wheel.materials, None, subsection, 'armor', optional=True, index=wheelId) wheelId += 1 return
def __init__(self, dataSec, defaultOffset=None): super(ArcadeCamera, self).__init__() CallbackDelayer.__init__(self) TimeDeltaMeter.__init__(self) self.__shiftKeySensor = None self.__movementOscillator = None self.__impulseOscillator = None self.__noiseOscillator = None self.__dynamicCfg = CameraDynamicConfig() self.__accelerationSmoother = None self.__readCfg(dataSec) self.__onChangeControlMode = None self.__aimingSystem = None self.__curSense = 0 self.__curScrollSense = 0 self.__postmortemMode = False self.__focalPointDist = 1.0 self.__autoUpdateDxDyDz = Vector3(0.0) self.__updatedByKeyboard = False self.__isCamInTransition = False if defaultOffset is not None: self.__defaultAimOffset = defaultOffset self.__cam = BigWorld.HomingCamera(self.__adCfg['enable']) if self.__adCfg['enable']: self.__cam.initAdvancedCollider( self.__adCfg['fovRatio'], self.__adCfg['rollbackSpeed'], self.__adCfg['minimalCameraDistance'], self.__adCfg['speedThreshold'], self.__adCfg['minimalVolume']) for group_name in VOLUME_GROUPS_NAMES: self.__cam.addVolumeGroup( self.__adCfg['volumeGroups'][group_name]) self.__cam.aimPointClipCoords = defaultOffset else: self.__defaultAimOffset = Vector2() self.__cam = None self.__cameraTransition = BigWorld.TransitionCamera() return
def activateMapCase(equipmentID, deactivateCallback, controlMode): inputHandler = BigWorld.player().inputHandler if isinstance(inputHandler.ctrl, controlMode): if controlMode.deactivateCallback is not None: controlMode.deactivateCallback() controlMode.deactivateCallback = deactivateCallback mapCaseCtrl = inputHandler.ctrl preferredPos = None if mapCaseCtrl.isEnabled else mapCaseCtrl.getDesiredShotPoint( ignoreAimingMode=True) inputHandler.ctrl.activateEquipment(equipmentID, preferredPos) else: currentMode = inputHandler.ctrlModeName mapCaseModes = (CTRL_MODE_NAME.MAP_CASE_ARCADE_EPIC_MINEFIELD, CTRL_MODE_NAME.MAP_CASE, CTRL_MODE_NAME.MAP_CASE_ARCADE, CTRL_MODE_NAME.MAP_CASE_ARCADE_EPIC_MINEFIELD) if currentMode in mapCaseModes: _logger.warning( 'MapCaseMode is active! Attempt to switch MapCaseModes simultaneously!' ) return controlMode.deactivateCallback = deactivateCallback pos = inputHandler.getDesiredShotPoint() if pos is None: camera = getattr(inputHandler.ctrl, 'camera', None) if camera is not None: pos = camera.aimingSystem.getDesiredShotPoint() if pos is None: pos = Vector3(0.0, 0.0, 0.0) controlMode.prevCtlMode = [ pos, currentMode, inputHandler.ctrl.aimingMode ] inputHandler.onControlModeChanged( controlMode.MODE_NAME, preferredPos=pos, aimingMode=inputHandler.ctrl.aimingMode, equipmentID=equipmentID, saveDist=False) return
def _calculateTargetImaginePosByAngel(self, targetEntity, burst, current, syncedRandom): koef = self._ownerLogic.scheme.Prediction oVector = self._ownerLogic.getEntityVector(self._ownerEntity) tVector = Vector3(self._ownerLogic.getEntityVector(targetEntity)) if current == 0: targetHitTime = BigWorld.collisionTime( self._ownerEntity.position, oVector, targetEntity.position, tVector, self._ownerLogic.gunDescription.bulletSpeed) result = targetEntity.position + targetHitTime * tVector * koef self.firstShootPosition = result self.angelK = self._ownerLogic.scheme.SpeedAngle return self.firstShootPosition turretsCount = targetEntity.lockedByTurretsCounter currentKoef = self.__getDistanceDelta(current, burst, turretsCount) if currentKoef <= 0.5: if self.angelK != self._ownerLogic.scheme.SpeedAngleMax: self.angelK = self._ownerLogic.scheme.SpeedAngleMax oVector = self._ownerLogic.getEntityVector(self._ownerEntity) tVector = self._ownerLogic.getEntityVector(targetEntity) targetHitTime = BigWorld.collisionTime( self._ownerEntity.position, oVector, targetEntity.position, tVector, self._ownerLogic.gunDescription.bulletSpeed) result = targetEntity.position + targetHitTime * tVector self.__shootDirection = self.firstShootPosition - self._ownerEntity.position len = self.__shootDirection.length k2 = self.angelK speedAngle = 0.0175 * k2 rotateVector = (result - self._ownerEntity.position).getNormalized() tempShoot = self.__shootDirection.getNormalized() right = tempShoot.cross(rotateVector) roatateAngle = tempShoot.angle(rotateVector) rotAngle = roatateAngle if roatateAngle < speedAngle else speedAngle rot = Quaternion() rot.fromAngleAxis(rotAngle, right) tempVec = rot.rotateVec(tempShoot) self.firstShootPosition = self._ownerEntity.position + tempVec * len return self.firstShootPosition
def __calculateIdealState(self, deltaTime): aimPoint = self.__aimingSystem.aimPoint direction = self.__aimingSystem.direction impactPitch = max(direction.pitch, self.__cfg['minimalPitch']) self.__rotation = max(self.__rotation, impactPitch) distRange = self.__cfg['distRange'] distanceCurSq = (aimPoint - BigWorld.player().getVehicleAttached().position).lengthSquared distanceMinSq = distRange[0] ** 2.0 forcedPitch = impactPitch if distanceCurSq < distanceMinSq: forcedPitch = atan2(sqrt(distanceMinSq - distanceCurSq), sqrt(distanceCurSq)) angularShift = self.__cfg['angularSpeed'] * deltaTime angularShift = angularShift if self.__choosePitchLevel(aimPoint) else -angularShift minPitch = max(forcedPitch, impactPitch) maxPitch = max(forcedPitch, self.__cfg['maximalPitch']) self.__rotation = mathUtils.clamp(minPitch, maxPitch, self.__rotation + angularShift) desiredDistance = self.__getDesiredCameraDistance() cameraDirection = self.__getCameraDirection() desiredDistance = self.__resolveCollisions(aimPoint, desiredDistance, cameraDirection) desiredDistance = mathUtils.clamp(distRange[0], distRange[1], desiredDistance) translation = aimPoint - cameraDirection.scale(desiredDistance) rotation = Vector3(cameraDirection.yaw, -cameraDirection.pitch, 0.0) return (translation, rotation)
def __init__(self): self.cfg = {} self.camDistConstrPlatoon = Vector2() self.camStartDistPlatoon = component_constants.ZERO_FLOAT self.camPitchConstrPlatoon = Vector2() self.camStartAngles = Vector2() self.camStartAnglesPlatoon = Vector2() self.vStartAngles = Vector3() self.vStartPos = Vector3() self.camStartTargetPos = Vector3() self.camStartDist = component_constants.ZERO_FLOAT self.camDistConstr = Vector2() self.camMinDistVehicleHullLengthK = component_constants.ZERO_FLOAT self.camPitchConstr = Vector2() self.camYawConstr = Vector2() self.camSens = component_constants.ZERO_FLOAT self.camDistSens = component_constants.ZERO_FLOAT self.camPivotPos = Vector3() self.camFluency = component_constants.ZERO_FLOAT self.emblemsAlphaDamaged = component_constants.ZERO_FLOAT self.emblemsAlphaUndamaged = component_constants.ZERO_FLOAT self.shadowLightDir = Vector3() self.shadowModelName = component_constants.EMPTY_STRING self.shadowForwardYOffset = component_constants.ZERO_FLOAT self.shadowDeferredYOffset = component_constants.ZERO_FLOAT self.shadowDefaultTextureName = component_constants.EMPTY_STRING self.shadowEmptyTextureName = component_constants.EMPTY_STRING self.camCapsuleScale = Vector3() self.camCapsuleGunScale = Vector3() self.camIdlePitchConstr = Vector2() self.camIdleDistConstr = Vector2() self.camIdleYawPeriod = component_constants.ZERO_FLOAT self.camIdlePitchPeriod = component_constants.ZERO_FLOAT self.camIdleDistPeriod = component_constants.ZERO_FLOAT self.camIdleEasingInTime = component_constants.ZERO_FLOAT self.camParallaxDistance = Vector2() self.camParallaxAngles = Vector2() self.camParallaxSmoothing = component_constants.ZERO_FLOAT self.vehicleGunPitch = component_constants.ZERO_FLOAT self.vehicleTurretYaw = component_constants.ZERO_FLOAT
def __update(self): self.__updateCallbackId = None self.__updateCallbackId = BigWorld.callback(0.0, self.__update) curTime = BigWorld.time() dt = curTime - self.__prevTime self.__prevTime = curTime self.__currentAngle += self.__angularVelocity * dt if self.__currentAngle > 2 * math.pi: self.__currentAngle -= 2 * math.pi elif self.__currentAngle < -2 * math.pi: self.__currentAngle += 2 * math.pi radialPosition = Vector3(self.radius * math.sin(self.__currentAngle), 0, self.radius * math.cos(self.__currentAngle)) modelYaw = self.__currentAngle if self.rotateClockwise: modelYaw += math.pi / 2 else: modelYaw -= math.pi / 2 localMatrix = Matrix() localMatrix.setRotateY(modelYaw) localMatrix.translation = radialPosition self.__modelMatrix.setRotateYPR((self.yaw, self.pitch, self.roll)) self.__modelMatrix.translation = self.position self.__modelMatrix.preMultiply(localMatrix)
def __updateOscillators(self, deltaTime): if not SniperCamera.isCameraDynamic(): self.__impulseOscillator.reset() self.__movementOscillator.reset() self.__noiseOscillator.reset() return (mathUtils.createRotationMatrix(Vector3(0, 0, 0)), mathUtils.createRotationMatrix(Vector3(0, 0, 0))) oscillatorAcceleration = self.__calcCurOscillatorAcceleration( deltaTime) self.__movementOscillator.externalForce += oscillatorAcceleration self.__impulseOscillator.update(deltaTime) self.__movementOscillator.update(deltaTime) self.__noiseOscillator.update(deltaTime) noiseDeviation = Vector3(self.__noiseOscillator.deviation) deviation = self.__impulseOscillator.deviation + self.__movementOscillator.deviation + noiseDeviation oscVelocity = self.__impulseOscillator.velocity + self.__movementOscillator.velocity + self.__noiseOscillator.velocity if abs(deviation.x) < 1e-05 and abs(oscVelocity.x) < 0.0001: deviation.x = 0 if abs(deviation.y) < 1e-05 and abs(oscVelocity.y) < 0.0001: deviation.y = 0 if abs(deviation.z) < 1e-05 and abs(oscVelocity.z) < 0.0001: deviation.z = 0 curZoomIdx = 0 zooms = self.__cfg['zooms'] for idx in xrange(len(zooms)): if self.__zoom == zooms[idx]: curZoomIdx = idx break zoomExposure = self.__zoom * self.__dynamicCfg['zoomExposure'][ curZoomIdx] deviation /= zoomExposure impulseDeviation = (self.__impulseOscillator.deviation + noiseDeviation) / zoomExposure self.__impulseOscillator.externalForce = Vector3(0) self.__movementOscillator.externalForce = Vector3(0) self.__noiseOscillator.externalForce = Vector3(0) return (mathUtils.createRotationMatrix( Vector3(deviation.x, deviation.y, deviation.z)), mathUtils.createRotationMatrix(impulseDeviation))
def onEnterWorld(self, prereqs): if BattleReplay.g_replayCtrl.isPlaying: return self._loadModels(prereqs) self.__decisionStrategy = self.__doUsualFly if self.flyAroundCenter != Flock.STRATEGY_USUAL_FLY: self.__setupFlyAroundCenter() self.filter = BigWorld.BoidsFilter() self.filter.speed = self.speedAtBottom self.filter.yprSpeed = Vector3(self.yawSpeed, self.pitchSpeed, self.rollSpeed) self.filter.deadZonePosition = self.position self.filter.deadZoneRadius = self.deadZoneRadius self.middlePosition = Math.Vector3() self.minHeight = self.position.y self.maxHeight = self.minHeight + self.height for boid in self.models: boid.visible = True self.middlePosition = Math.Vector3(self.position) self.physics = 0 newPosition = Math.Vector3(self.position) newPosition.y = (self.minHeight + self.maxHeight) / 2.0 self.physics.teleport(newPosition) self.__makeDecision()
def _readMovementSettings(self, configDataSec): movementMappings = dict() movementMappings[getattr( Keys, configDataSec.readString('keyMoveLeft', 'KEY_A'))] = Vector3(-1, 0, 0) movementMappings[getattr( Keys, configDataSec.readString('keyMoveRight', 'KEY_D'))] = Vector3(1, 0, 0) keyMoveUp = getattr(Keys, configDataSec.readString('keyMoveUp', 'KEY_PGUP')) keyMoveDown = getattr( Keys, configDataSec.readString('keyMoveDown', 'KEY_PGDN')) movementMappings[keyMoveUp] = Vector3(0, 1, 0) movementMappings[keyMoveDown] = Vector3(0, -1, 0) movementMappings[getattr( Keys, configDataSec.readString('keyMoveForward', 'KEY_W'))] = Vector3(0, 0, 1) movementMappings[getattr( Keys, configDataSec.readString('keyMoveBackward', 'KEY_S'))] = Vector3(0, 0, -1) linearSensitivity = configDataSec.readFloat('linearVelocity', 40.0) linearSensitivityAcc = configDataSec.readFloat( 'linearVelocityAcceleration', 30.0) linearIncDecKeys = (getattr( Keys, configDataSec.readString('keyLinearVelocityIncrement', 'KEY_I')), getattr( Keys, configDataSec.readString( 'keyLinearVelocityDecrement', 'KEY_K'))) self._movementSensor = KeySensor(movementMappings, linearSensitivity, linearIncDecKeys, linearSensitivityAcc) self._verticalMovementSensor = KeySensor( { keyMoveUp: 1, keyMoveDown: -1 }, linearSensitivity, linearIncDecKeys, linearSensitivityAcc) self._movementSensor.currentVelocity = Math.Vector3()
def __readCfg(self, dataSec): if dataSec is None: LOG_WARNING( 'Invalid section <arcadeMode/camera> in avatar_input_handler.xml' ) self.__baseCfg = dict() bcfg = self.__baseCfg bcfg['keySensitivity'] = readFloat(dataSec, 'keySensitivity', 0, 10, 0.01) bcfg['sensitivity'] = readFloat(dataSec, 'sensitivity', 0, 10, 0.01) bcfg['scrollSensitivity'] = readFloat(dataSec, 'scrollSensitivity', 0, 10, 0.01) bcfg['angleRange'] = readVec2(dataSec, 'angleRange', (0, 0), (180, 180), (10, 110)) distRangeVec = readVec2(dataSec, 'distRange', (1, 1), (100, 100), (2, 20)) bcfg['distRange'] = MinMax(distRangeVec.x, distRangeVec.y) bcfg['minStartDist'] = readFloat(dataSec, 'minStartDist', bcfg['distRange'][0], bcfg['distRange'][1], bcfg['distRange'][0]) bcfg['optimalStartDist'] = readFloat(dataSec, 'optimalStartDist', bcfg['distRange'][0], bcfg['distRange'][1], bcfg['distRange'][0]) bcfg['angleRange'][0] = math.radians( bcfg['angleRange'][0]) - math.pi * 0.5 bcfg['angleRange'][1] = math.radians( bcfg['angleRange'][1]) - math.pi * 0.5 bcfg['fovMultMinMaxDist'] = MinMax( readFloat(dataSec, 'fovMultMinDist', 0.1, 100, 1.0), readFloat(dataSec, 'fovMultMaxDist', 0.1, 100, 1.0)) ds = Settings.g_instance.userPrefs[Settings.KEY_CONTROL_MODE] if ds is not None: ds = ds['arcadeMode/camera'] self.__userCfg = dict() ucfg = self.__userCfg ucfg['horzInvert'] = self.settingsCore.getSetting('mouseHorzInvert') ucfg['vertInvert'] = self.settingsCore.getSetting('mouseVertInvert') ucfg['sniperModeByShift'] = self.settingsCore.getSetting( 'sniperModeByShift') ucfg['keySensitivity'] = readFloat(ds, 'keySensitivity', 0.0, 10.0, 1.0) ucfg['sensitivity'] = readFloat(ds, 'sensitivity', 0.0, 10.0, 1.0) ucfg['scrollSensitivity'] = readFloat(ds, 'scrollSensitivity', 0.0, 10.0, 1.0) ucfg['startDist'] = readFloat(ds, 'startDist', bcfg['distRange'][0], 500, bcfg['optimalStartDist']) if ucfg['startDist'] < bcfg['minStartDist']: ucfg['startDist'] = bcfg['optimalStartDist'] ucfg['startAngle'] = readFloat(ds, 'startAngle', 5, 180, 60) ucfg['startAngle'] = math.radians(ucfg['startAngle']) - math.pi * 0.5 ucfg['fovMultMinMaxDist'] = MinMax( readFloat(ds, 'fovMultMinDist', 0.1, 100, bcfg['fovMultMinMaxDist'].min), readFloat(ds, 'fovMultMaxDist', 0.1, 100, bcfg['fovMultMinMaxDist'].max)) self.__cfg = dict() cfg = self.__cfg cfg['keySensitivity'] = bcfg['keySensitivity'] cfg['sensitivity'] = bcfg['sensitivity'] cfg['scrollSensitivity'] = bcfg['scrollSensitivity'] cfg['angleRange'] = bcfg['angleRange'] cfg['distRange'] = bcfg['distRange'] cfg['minStartDist'] = bcfg['minStartDist'] cfg['horzInvert'] = ucfg['horzInvert'] cfg['vertInvert'] = ucfg['vertInvert'] cfg['keySensitivity'] *= ucfg['keySensitivity'] cfg['sensitivity'] *= ucfg['sensitivity'] cfg['scrollSensitivity'] *= ucfg['scrollSensitivity'] cfg['startDist'] = ucfg['startDist'] cfg['startAngle'] = ucfg['startAngle'] cfg['fovMultMinMaxDist'] = ucfg['fovMultMinMaxDist'] cfg['sniperModeByShift'] = ucfg['sniperModeByShift'] enableShift = dataSec.readBool('shift', False) if enableShift: movementMappings = dict() movementMappings[Keys.KEY_A] = Math.Vector3(-1, 0, 0) movementMappings[Keys.KEY_D] = Math.Vector3(1, 0, 0) movementMappings[Keys.KEY_Q] = Math.Vector3(0, 1, 0) movementMappings[Keys.KEY_E] = Math.Vector3(0, -1, 0) movementMappings[Keys.KEY_W] = Math.Vector3(0, 0, 1) movementMappings[Keys.KEY_S] = Math.Vector3(0, 0, -1) shiftSensitivity = dataSec.readFloat('shiftSensitivity', 0.5) self.__shiftKeySensor = KeySensor(movementMappings, shiftSensitivity) self.__shiftKeySensor.reset(Math.Vector3()) dynamicsSection = dataSec['dynamics'] self.__impulseOscillator = createOscillatorFromSection( dynamicsSection['impulseOscillator'], False) self.__movementOscillator = createOscillatorFromSection( dynamicsSection['movementOscillator'], False) self.__movementOscillator = Math.PyCompoundOscillator( self.__movementOscillator, Math.PyOscillator(1.0, Vector3(50), Vector3(20), Vector3(0.01, 0.0, 0.01))) self.__noiseOscillator = createOscillatorFromSection( dynamicsSection['randomNoiseOscillatorSpherical']) self.__dynamicCfg.readImpulsesConfig(dynamicsSection) self.__dynamicCfg['accelerationSensitivity'] = readFloat( dynamicsSection, 'accelerationSensitivity', -1000, 1000, 0.1) self.__dynamicCfg['frontImpulseToPitchRatio'] = math.radians( readFloat(dynamicsSection, 'frontImpulseToPitchRatio', -1000, 1000, 0.1)) self.__dynamicCfg['sideImpulseToRollRatio'] = math.radians( readFloat(dynamicsSection, 'sideImpulseToRollRatio', -1000, 1000, 0.1)) self.__dynamicCfg['sideImpulseToYawRatio'] = math.radians( readFloat(dynamicsSection, 'sideImpulseToYawRatio', -1000, 1000, 0.1)) accelerationThreshold = readFloat(dynamicsSection, 'accelerationThreshold', 0.0, 1000.0, 0.1) self.__dynamicCfg['accelerationThreshold'] = accelerationThreshold self.__dynamicCfg['accelerationMax'] = readFloat( dynamicsSection, 'accelerationMax', 0.0, 1000.0, 0.1) self.__dynamicCfg['maxShotImpulseDistance'] = readFloat( dynamicsSection, 'maxShotImpulseDistance', 0.0, 1000.0, 10.0) self.__dynamicCfg['maxExplosionImpulseDistance'] = readFloat( dynamicsSection, 'maxExplosionImpulseDistance', 0.0, 1000.0, 10.0) self.__dynamicCfg['zoomExposure'] = readFloat(dynamicsSection, 'zoomExposure', 0.0, 1000.0, 0.25) accelerationFilter = mathUtils.RangeFilter( self.__dynamicCfg['accelerationThreshold'], self.__dynamicCfg['accelerationMax'], 100, mathUtils.SMAFilter(ArcadeCamera._FILTER_LENGTH)) maxAccelerationDuration = readFloat( dynamicsSection, 'maxAccelerationDuration', 0.0, 10000.0, ArcadeCamera._DEFAULT_MAX_ACCELERATION_DURATION) self.__accelerationSmoother = AccelerationSmoother( accelerationFilter, maxAccelerationDuration) self.__inputInertia = _InputInertia( self.__calculateInputInertiaMinMax(), 0.0) advancedCollider = dataSec['advancedCollider'] self.__adCfg = dict() cfg = self.__adCfg if advancedCollider is None: LOG_ERROR('<advancedCollider> dataSection is not found!') cfg['enable'] = False else: cfg['enable'] = advancedCollider.readBool('enable', False) cfg['fovRatio'] = advancedCollider.readFloat('fovRatio', 2.0) cfg['rollbackSpeed'] = advancedCollider.readFloat( 'rollbackSpeed', 1.0) cfg['minimalCameraDistance'] = self.__cfg['distRange'][0] cfg['speedThreshold'] = advancedCollider.readFloat( 'speedThreshold', 0.1) cfg['minimalVolume'] = advancedCollider.readFloat( 'minimalVolume', 200.0) cfg['volumeGroups'] = dict() for group in VOLUME_GROUPS_NAMES: groups = advancedCollider['volumeGroups'] cfg['volumeGroups'][group] = CollisionVolumeGroup.fromSection( groups[group]) return
def glide(self, posDelta): self.__deltaEasing.reset(posDelta, Vector3(0.0), _InputInertia.__ZOOM_DURATION)
def __cameraUpdate(self): if not (self.__autoUpdateDxDyDz.x == 0.0 and self.__autoUpdateDxDyDz.y == 0.0 and self.__autoUpdateDxDyDz.z == 0.0): self.__update(self.__autoUpdateDxDyDz.x, self.__autoUpdateDxDyDz.y, self.__autoUpdateDxDyDz.z) inertDt = deltaTime = self.measureDeltaTime() replayCtrl = BattleReplay.g_replayCtrl if replayCtrl.isPlaying: repSpeed = replayCtrl.playbackSpeed if repSpeed == 0.0: inertDt = 0.01 deltaTime = 0.0 else: inertDt = deltaTime = deltaTime / repSpeed self.__aimingSystem.update(deltaTime) virginShotPoint = self.__aimingSystem.getThirdPersonShotPoint() delta = self.__inputInertia.positionDelta sign = delta.dot(Vector3(0, 0, 1)) self.__inputInertia.update(inertDt) delta = (delta - self.__inputInertia.positionDelta).length if delta != 0.0: self.__cam.setScrollDelta(math.copysign(delta, sign)) FovExtended.instance().setFovByMultiplier( self.__inputInertia.fovZoomMultiplier) unshakenPos = self.__inputInertia.calcWorldPos( self.__aimingSystem.matrix) vehMatrix = Math.Matrix(self.__aimingSystem.vehicleMProv) vehiclePos = vehMatrix.translation fromVehicleToUnshakedPos = unshakenPos - vehiclePos deviationBasis = mathUtils.createRotationMatrix( Vector3(self.__aimingSystem.yaw, 0, 0)) impulseDeviation, movementDeviation, oscillationsZoomMultiplier = self.__updateOscillators( deltaTime) relCamPosMatrix = mathUtils.createTranslationMatrix(impulseDeviation + movementDeviation) relCamPosMatrix.postMultiply(deviationBasis) relCamPosMatrix.translation += fromVehicleToUnshakedPos upRotMat = mathUtils.createRotationMatrix( Vector3( 0, 0, -impulseDeviation.x * self.__dynamicCfg['sideImpulseToRollRatio'] - self.__noiseOscillator.deviation.z)) upRotMat.postMultiply(relCamPosMatrix) self.__cam.up = upRotMat.applyVector(Vector3(0, 1, 0)) relTranslation = relCamPosMatrix.translation shotPoint = self.__calcFocalPoint(virginShotPoint, deltaTime) vehToShotPoint = shotPoint - vehiclePos if self.__cameraInterpolator.active: self.__targetAimVector = vehToShotPoint self.__endCamPosition = relTranslation if not self.__cameraInterpolator.tick(): self.__cam.pivotPositionProvider = self.__aimingSystem.positionAboveVehicleProv else: self.__setCameraAimPoint(vehToShotPoint) self.__setCameraPosition(relTranslation) replayCtrl = BattleReplay.g_replayCtrl if replayCtrl.isPlaying and replayCtrl.isControllingCamera: aimOffset = replayCtrl.getAimClipPosition() if not BigWorld.player().isForcedGuiControlMode() and GUI.mcursor( ).inFocus: GUI.mcursor().position = aimOffset else: aimOffset = self.__calcAimOffset(oscillationsZoomMultiplier) if replayCtrl.isRecording: replayCtrl.setAimClipPosition(aimOffset) self.__cam.aimPointClipCoords = aimOffset self.__aimOffset = aimOffset if self.__shiftKeySensor is not None: self.__shiftKeySensor.update(1.0) if self.__shiftKeySensor.currentVelocity.lengthSquared > 0.0: self.shiftCamPos(self.__shiftKeySensor.currentVelocity) self.__shiftKeySensor.currentVelocity = Math.Vector3() return 0.0