def analyze_overtones(self,semitone,overtones=None):
		""" calculates power and peak center for each overtone and yields tuples (overtone, frequency, power, peak_center, difference_in_semitones) """
		frequency = Math.semitone_to_frequency(semitone)
		peak_radius = self.get_peak_radius()

		overtone=0

		while overtones==None or overtone<overtones:
			f = frequency*(overtone+1)
			s = Math.frequency_to_semitone(f)

			lower_frequency = f - peak_radius*1.65
			upper_frequency = f + peak_radius*1.65

			lower_frequency = min(lower_frequency, Math.semitone_to_frequency(s-0.5))
			upper_frequency = max(upper_frequency, Math.semitone_to_frequency(s+0.5))

			power = self.get_power_in_frequency_range(lower_frequency,upper_frequency)
			peak_center = self.get_powerfreq_spline().integral(lower_frequency,upper_frequency) / power

			difference_in_semitones = Math.frequency_to_semitone(peak_center) - s

			yield overtone, f, power, peak_center, difference_in_semitones

			overtone += 1
    def overtones_to_equalizer(self, control, semitone, overtones=10):
        if not self.project:
            return

        x = self.project.pipeline.eq.frequencies
        y = self.project.pipeline.eq.props.transmission

        fundamental_frequency = Math.semitone_to_frequency(semitone)

        for overtone in xrange(overtones + 1):
            frequency = fundamental_frequency * (overtone + 1)
            semitone = Math.frequency_to_semitone(frequency)

            lower = Math.semitone_to_frequency(semitone - 0.5)
            upper = Math.semitone_to_frequency(semitone + 0.5)

            if lower > x[-1]:
                break

            for i in xrange(len(x)):
                if x[i] > upper:
                    break

                if lower <= x[i]:
                    y[i] = 1.0

        self.project.pipeline.eq.props.transmission = y
    def analyze_semitone(self, control, semitone):
        if not self.project:
            return
        if not control.has_data:
            return

        text = ""

        for overtone, frequency, power, peak_center, difference_in_semitones in control.analyze_overtones(semitone, 10):
            s = Math.frequency_to_semitone(frequency)
            position = control.start + control.duration / 2.0
            lower = Math.semitone_to_frequency(s - 0.5)
            upper = Math.semitone_to_frequency(s + 0.5)
            onset_min, onset_max = self.project.appsinkpipeline.find_onset(lower, upper, position, limit=5)
            text += "%d. overtone: %f Hz (semitone %f; near %s)\n" % (overtone, frequency, s, Math.note_name(s))
            text += "\tPower: %f (%f dB)\n" % (power, Math.power_to_magnitude(power))
            text += "\tPosition: %f Hz (off by %f semitones)\n" % (peak_center, difference_in_semitones)
            text += "\tOnset: between %fs and %fs\n" % (onset_min, onset_max)
            text += "\n"

        w = gtk.Window()
        w.set_size_request(500, 400)
        w.set_title("Info on %s (%f)" % (Math.note_name(semitone), semitone))

        sw = gtk.ScrolledWindow()
        w.add(sw)

        tv = gtk.TextView()
        tv.get_buffer().set_text(text)
        tv.set_editable(False)
        sw.add(tv)

        w.show_all()
Ejemplo n.º 4
0
def guessing_game():
	'''finish this. idea: want to calculate optimal cost C(10^12, sqrt{k}, sqrt{F_k}) where F_k is the k-th fibonacci number;
	this means that the cost for overshooting the hidden number n in range(1,10^12) is much higher than the cost for undershooting
	(or is it vice versa? check the rules.)... hence we should bias towards the low end by a factor given by a function of (k,F_k).
	Idea: biased binary search?'''
	result = 0.0
	for k in range(1,30):
		result += calculate_optimal_worst_case_cost(10**12, Math.sqrt(k), Math.sqrt((phi**k - ((-phi)**(-k))) / Math.sqrt(5)))
	print result
    def vis_plot_evolution(self, viscontrol, semitone):
        if not self.project:
            return

        playback_marker = self.project.timeline.ruler.get_playback_marker()
        if not playback_marker:
            return

        import scipy.interpolate

        start, duration = playback_marker

        ##########
        dialog = gtk.Dialog(
            title="interval",
            flags=gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT),
        )
        entry = gtk.Entry()
        entry.set_text("0.1")
        dialog.vbox.add(entry)
        dialog.show_all()
        dialog.run()
        interval = float(entry.get_text())
        dialog.destroy()
        #############

        # 		interval = 0.1
        delta = interval / 2.0
        steps = 1.0 * duration / delta

        x = []
        y = []
        for step in xrange(int(steps)):
            pos = start + step * delta
            frq, power = self.project.appsinkpipeline.get_spectrum(pos - interval / 2.0, pos + interval / 2.0)
            # 			frq, power = self.project.appsinkpipeline.get_spectrum(pos,pos+interval)

            spline = scipy.interpolate.InterpolatedUnivariateSpline(frq, power, None, [None, None], 1)

            lower = Math.semitone_to_frequency(semitone - 0.5)
            upper = Math.semitone_to_frequency(semitone + 0.5)
            total = spline.integral(lower, upper)

            x.append(pos)
            y.append(total)

        w = Analyze.Analyze()
        w.show_all()
        w.simple_plot(x, y)
    def get_spectrum(self, start, stop):
        data = self.get_data(start, stop)
        if not len(data) > 0:
            return numpy.array([]), numpy.array([])

        rate = self.caps[0]["rate"]

        samples = min(MAX_FFT_SAMPLES, len(data))  # number of data points to consider for each fft

        ffts = len(data) / int(samples / 2.0) - 1  # number of ffts

        # calculate average over powers
        power = 0.0

        for i in xrange(ffts):
            shift = int(0.5 * i * samples)
            power += Math.windowed_fft(data[shift : shift + samples])

        power /= ffts

        # calculate frequencies
        bands = len(power)
        frq = 0.5 * (numpy.arange(bands) + 0.5) * rate / bands

        return frq, power
Ejemplo n.º 7
0
Archivo: Game.py Proyecto: Lanchoe/LSLW
 def __init__(self,id,s1,s2): #Arrête de s1 vers s2
     self.id = id
     self.sommet1 = s1
     self.sommet2 = s2
     self.length = Math.sqrt((s1.x-s2.x)**2+(s1.y-s2.y)**2)
     self.pop = 0 #Combien d'unités parcourent cette arrête
     self.owner = None #Qui possède ces unités
Ejemplo n.º 8
0
 def setGrowthVolumePerDayRelVolume(self, multiple):
     '''
     Set the growth volume per day relative to the maximum cell volume.
     :param multiple: Factor for the daily growth.
     :return:
     '''
     self.growthVolumePerDay = multiple * Math.calcSphereVolumeFromDiameter(self.maxDiameter)
	def press_semitone(self,semitone,target,event,string,fret):
		if event.button==1:
			self.pipeline.get_by_name("volume").set_property("volume", self.volume.get_value())
			self.pipeline.get_by_name("src").set_property("freq", Math.semitone_to_frequency(semitone.semitone))
			self.pipeline.set_state(gst.STATE_PLAYING)
		elif event.button==3:
			self.open_context_menu(semitone,event,string,fret)
Ejemplo n.º 10
0
	def get_next_move_to(self, position, final_target):
		"""Get the next point an agent following this path should move to.

		Reference: Simple Stupid Funnel Algorithm
		http://digestingduck.blogspot.com/2010/03/simple-stupid-funnel-algorithm.html

		@type position: Vector
		@param position: The position of the agent following the path
		"""

		current_polys = [] 
		for poly in self._polygons:
			if poly.contains_point(position):
				current_polys.append(poly)

		i = max((self._polygons.index(p) for p in current_polys))
		
		if i == len(self._polygons)-1: return final_target

		edge = self._polygons[i].neighbors[self._polygons[i+1]][1]
		
		left, right = (edge[0], edge[1]) if Math.point_orientation(position, edge[0], edge[1]) else (edge[1], edge[0])

		for j in range(i+1, len(self._polygons)-1):
			edge = self._polygons[j].neighbors[self._polygons[j+1]][1]
			new_left, new_right = (edge[0], edge[1]) if Math.point_orientation(position, edge[0], edge[1]) else (edge[1], edge[0])
		
			# make the funnel smaller
			if Math.point_orientation(position, left, new_left): left = new_left
			if not Math.point_orientation(position, left, right): 
				return right
			
			
			if not Math.point_orientation(position, right, new_right): right = new_right
			if not Math.point_orientation(position, left, right): 
				return left

		if Math.point_orientation(position, left, final_target): left = final_target
		if not Math.point_orientation(position, left, right):
			return right

		if not Math.point_orientation(position, right, final_target): right = final_target
		if not Math.point_orientation(position, left, right):
			return left

		return final_target
	def do_simple_paint(self, cr, bounds):
		cr.translate(self.x, self.y)
		cr.rectangle(0.0, 0.0, self.width, self.height)

		if not self.control.has_data:
			cr.set_source_rgb(1.,1.,1.)
		elif self.method=="cumulate":
			fpower, power, center, standard_deviation, upper_dependence, lower_dependence = self.control.analyze_semitone(self.semitone)
			magnitude = Math.power_to_magnitude(power / 1.5 / 1000)
			const,slope = self.control.get_brightness_coefficients_for_magnitude()
			brightness = slope*magnitude + const
			print self.semitone,"mag",magnitude,"tpow",power,"b",brightness,"pow",fpower
			cr.set_source_rgb(brightness,brightness,brightness)
		elif self.method=="test":
			fpower, power, center, standard_deviation, upper_dependence, lower_dependence = self.control.analyze_semitone(self.semitone)
			upper_dependence = min(1.,upper_dependence)
			lower_dependence = min(1.,lower_dependence)
			total_dependence = min(1., upper_dependence+lower_dependence)
			power *= 1. - total_dependence
			magnitude = Math.power_to_magnitude(power / 1.5 / 1000)
			const,slope = self.control.get_brightness_coefficients_for_magnitude()
			brightness = slope*magnitude + const
			cr.set_source_rgb(brightness,brightness,brightness)
		elif self.method=="inharmonicity":
			fpower, power, center, standard_deviation, upper_dependence, lower_dependence = self.control.analyze_semitone(self.semitone)
			brightness = standard_deviation / 0.5
			cr.set_source_rgb(brightness,brightness,brightness)
		elif self.method=="lower_dependence":
			fpower, power, center, standard_deviation, upper_dependence, lower_dependence = self.control.analyze_semitone(self.semitone)
			brightness = lower_dependence
			cr.set_source_rgb(brightness,brightness,brightness)
		elif self.method=="upper_dependence":
			fpower, power, center, standard_deviation, upper_dependence, lower_dependence = self.control.analyze_semitone(self.semitone)
			brightness = upper_dependence
			cr.set_source_rgb(brightness,brightness,brightness)
		elif self.method=="gradient":
			assert not self.matrix==None
			gradient = self.control.get_gradient()
			gradient.set_matrix(self.matrix)
			cr.set_source(gradient)
		else:
			raise ValueError, "Invalid method"

		cr.fill_preserve()
		cr.set_source_rgb(0.,0.,0.)
		cr.stroke()
	def __init__(self, control, tuning=-5, **kwargs):
		FretboardWindowBase.__init__(self, **kwargs)

		self.set_title("Undertones of %s-tuned string (%f - %f Hz)" % (Math.note_name(tuning), tuning, Math.semitone_to_frequency(tuning)))

		root = self.canvas.get_root_item()
		self.visualizer = Undertones(control, self.volume, parent=root, tuning=tuning)

		self.adjust_canvas_size()
    def find_onset(self, viscontrol, semitone):
        if not self.project:
            return

        playback_marker = self.project.timeline.ruler.get_playback_marker()
        if not playback_marker:
            return

        start, duration = playback_marker

        position = start + duration / 2.0

        lower = Math.semitone_to_frequency(semitone - 0.5)
        upper = Math.semitone_to_frequency(semitone + 0.5)

        onset, onset_max = self.project.appsinkpipeline.find_onset(lower, upper, position)

        self.project.timeline.ruler.set_playback_marker(onset, start + duration - onset)
def updateOrientation(rotation):
    from bge.logic import getCurrentController
    import mathutils
    import Math
    
    blendrot = Math.convertOrientation(rotation)

    controller = getCurrentController()
    obj = controller.owner
    obj.orientation = blendrot
Ejemplo n.º 15
0
def classficition(features_path, save_path, picture_path, suff=".bmp"):
    # 标志序列,0表示没有比对过的,1表示已经比对过的
    if not os.path.exists(save_path):
        os.mkdir(save_path)
    all_num = text_process.Pic_Num(features_path, count=[0])
    mark = [0] * all_num
    file_num = 0
    dis = 0.65  # 此阈值可根据你自己需要更改

    for i in range(all_num):
        if mark[i] != 0:
            continue
        else:
            mark[i] = 1
            save_dir_name = "%s%d" % (save_path + "/", file_num)
            if not os.path.exists(save_dir_name):
                os.mkdir(save_dir_name)
            oldf_num = "%09d" % i
            oldfile_name = "%s%s%s" % (picture_path + "/", oldf_num, suff)

            newfile_name = "%s%s%09d%s" % (save_dir_name, "/", 0, suff)
            shutil.copyfile(oldfile_name, newfile_name)

            bais_feature_num = i
            bais_feature_file = "%s%09d%s" % (features_path + "/", bais_feature_num, ".txt")
            bais_features_data = text_process.load(bais_feature_file)

            j = i + 4000  # 在1000张范围内搜索
            end = Math.Min(j, all_num)
            num = 1
            count = 0
            for k in range(i + 1, end):
                if mark[k] != 0:
                    continue
                else:
                    feature_num = k
                    feature_file = "%s%09d%s" % (features_path + "/", feature_num, ".txt")
                    feature_data = text_process.load(feature_file)
                    # 计算相似度
                    sim = Math.dis_cos(np.array(bais_features_data), np.array(feature_data), 256, "false")
                    if sim < dis:
                        continue
                    else:
                        mark[k] = 1
                        count += 1
                        oldf_num = "%09d" % k
                        oldfile_name = "%s%s%s" % (picture_path + "/", oldf_num, suff)
                        newfile_name = "%s%s%09d%s" % (save_dir_name, "/", num, suff)
                        num += 1
                        shutil.copyfile(oldfile_name, newfile_name)
            if count < 10:
                shutil.rmtree(save_dir_name)
            else:
                file_num += 1
    print u"分类结束,共得到%d类" % (file_num)
	def __init__(self, control, method="gradient", **kwargs):
		goocanvas.ItemSimple.__init__(self,**kwargs)

		if not self.props.tooltip:
			self.props.tooltip = Math.note_name(self.semitone)+" ("+str(self.semitone)+") ["+str(Math.semitone_to_frequency(self.semitone))+" Hz]"

		self.method = method

		self.control = control
		self.control.connect("new_data", self.new_data)

		self.matrix = None
Ejemplo n.º 17
0
Archivo: FOV.py Proyecto: tartley/Py2D
		def check_visibility(p):
			bpoints = set(boundary.points)

			if p not in bpoints:
				if (eye - p).get_length_squared() > radius_squared: return False
				if not boundary.contains_point(p): return False 
			
			for line_segment in obs_segs:
				if Math.check_intersect_lineseg_lineseg( eye, p, line_segment[0], line_segment[1]): 
					if line_segment[0] != p and line_segment[1] != p:
						return False

			return True
Ejemplo n.º 18
0
def classficition(features_path,save_path,picture_path,suff='.bmp'):
    #标志序列,0表示没有比对过的,1表示已经比对过的
    if not os.path.exists(save_path):
        os.mkdir(save_path)
    all_num = text_process.Pic_Num(features_path,count=[0])
    mark = [0]*all_num
    file_num = 0
    dis = 0.65# 此阈值可根据你自己需要更改
    
    for i in range(all_num):
        if mark[i] != 0:
            continue
        else:
            mark[i] = 1
            save_dir_name = "%s%d"%(save_path+'/',file_num)
            if not os.path.exists(save_dir_name):
                os.mkdir(save_dir_name)
            oldf_num = '%09d'%i
            oldfile_name = '%s%s%s'%(picture_path+'/',oldf_num,suff)
            
            newfile_name = '%s%s%09d%s'%(save_dir_name,'/',0,suff)
            shutil.copyfile(oldfile_name,newfile_name)
            
            bais_feature_num = i
            bais_feature_file = '%s%09d%s'%(features_path+'/',bais_feature_num,'.txt')
            bais_features_data = text_process.load(bais_feature_file)
            
            j = i + 2000 #在1000张范围内搜索
            end = Math.Min(j,all_num)
            num = 1
            for k in range(i+1,end):
                if mark[k] != 0:
                    continue
                else:
                    feature_num = k
                    feature_file = '%s%09d%s'%(features_path+'/',feature_num,'.txt')
                    feature_data = text_process.load(feature_file)
                    #计算相似度
                    sim = Math.dis_cos(np.array(bais_features_data),np.array(feature_data),256,'false')
                    if sim<dis:
                        continue
                    else:
                        mark[k] = 1
                        oldf_num = '%09d'%k
                        oldfile_name = '%s%s%s'%(picture_path+'/',oldf_num,suff)
                        newfile_name = '%s%s%09d%s'%(save_dir_name,'/',num,suff)
                        num += 1
                        shutil.copyfile(oldfile_name,newfile_name)
            file_num += 1
    print u'分类结束,共得到%d类'%(file_num)
def updatePosition():
    from bge.logic import getCurrentController
    import Math

    head = clientKit.instance.context.getInterface("/me/head")

    timestamp, pose = head.getPoseState()

    blendvec = Math.convertPosition(pose.translation)

    controller = getCurrentController()
    obj = bpy.data.objects[controller.owner.name]
    bpy.context.scene.objects.active = obj
    obj.location.x = blendvec.x
    obj.location.y = blendvec.y
    obj.location.z = blendvec.z
Ejemplo n.º 20
0
def proximal_descent(g, g_prime, h_prox, x0, iterations = 1000, gamma = 1.0, epsilon = 1e-4):
    """
    minimizes a non-differentiable function f(x) = g(x) + h(x)

    PARAMS
    g: function
        g(x), the differentiable part of f
    
    g_prime: function
        g'(x) aka the gradient of g
        returns the direction of steepest increase along g

    h_prox: function
        h_prox(x, gamma) returns proximal operator of h at x using gamma as a distance weighting param
        h_prox gives a new x' which is a tradeoff of reducing h and staying close to x

    x0: vector
        initial stariting point

    iterations: self explanitory

    gamma: step size
    
    epsilon: self explanitory


    RETURNS
    x* = argmin_x { f(x) } if x* is reachable in the given num iterations. else None
    """
    # initialize current guess at x0
    xk = x0
    gk = g(xk)

    for _ in range(iterations):
        xk_old = xk
        # compute gradient for differentiable  part of f
        gk_gradient = g_prime(xk)
        # take gradient step to reduce g(x)
        xk_gradient = xk - gamma * gk_gradient
        # proximal update to reduce h(x) but stay close to xk_gradient
        xk = h_prox(xk_gradient, gamma)

        if Math.abs(xk - xk_old) < epsilon:
            return xk

    return None
    def __init__(self, *args, **kwargs):
        self.frequencies = Math.get_frq(2049, 44100)
        self.transmission = None

        gst.Element.__init__(self, *args, **kwargs)

        if not self.transmission:
            self.transmission = numpy.ones(2049)

        self.sinkpad = gst.Pad(self._sinkpadtemplate, "sink")
        self.sinkpad.use_fixed_caps()
        self.srcpad = gst.Pad(self._srcpadtemplate, "src")
        self.srcpad.use_fixed_caps()
        self.sinkpad.set_chain_function(self.chainfunc)
        self.sinkpad.set_event_function(self.eventfunc)
        self.add_pad(self.sinkpad)
        self.srcpad.set_event_function(self.srceventfunc)
        self.add_pad(self.srcpad)
	def construct(self, posx, posy):
		# captions
		fretcaptions = goocanvas.Group(parent=self)
		for fret in xrange(1,self.frets+1):
			goocanvas.Text(parent=fretcaptions, x=fret*self.rectwidth, y=0, text=str(fret), anchor=gtk.ANCHOR_NORTH, font=10)

		stringcaptions = goocanvas.Group(parent=self)
		for string in xrange(len(self.strings)):
			semitone = self.strings[string]
			name = Math.note_name(semitone).upper()
			text = goocanvas.Text(parent=stringcaptions, x=0, y=string*self.rectheight, text=name, anchor=gtk.ANCHOR_EAST, font=10)
			text.connect("button_release_event", self.open_overtones, self.strings[string])

		startx = posx + stringcaptions.get_bounds().x2-stringcaptions.get_bounds().x1 + 5
		starty = posy + fretcaptions.get_bounds().y2-fretcaptions.get_bounds().y1

		fretcaptions.props.x = startx + 0.5*self.rectwidth
		fretcaptions.props.y = posy

		stringcaptions.props.x = startx - 5
		stringcaptions.props.y = starty + 0.5*self.rectheight

		# fretboard
		FretboardBase.construct(self, startx, starty)
Ejemplo n.º 23
0
def StrategicCamera__cameraUpdate(self):
    replayCtrl = BattleReplay.g_replayCtrl

    global gSPGSniperEnabled
    if not gSPGSniperEnabled:
        srcMat = mathUtils.createRotationMatrix((0, -math.pi * 0.49, 0))
        self._StrategicCamera__cam.source = srcMat
        self._StrategicCamera__cam.target.b = self._StrategicCamera__aimingSystem.matrix

        if not replayCtrl.isPlaying:
            BigWorld.projection().nearPlane = self._prevNearPlane
            BigWorld.projection().farPlane = self._prevFarPlane
            BigWorld.projection(
            ).fov = StrategicCamera.StrategicCamera.ABSOLUTE_VERTICAL_FOV
        return oldStrategicCamera__cameraUpdate(self)

    distRange = self._StrategicCamera__cfg['distRange'][:]
    if distRange[0] < 20:
        distRange[0] = 20
    distRange[1] = 600

    player = BigWorld.player()
    descr = player.vehicleTypeDescriptor

    shotEnd = self._StrategicCamera__aimingSystem.matrix.translation

    shellVelocity = Math.Vector3(
        self._StrategicCamera__aimingSystem._shellVelocity)
    shellVelocity.normalise()

    srcMat = Math.Matrix()
    srcMat.setRotateYPR((shellVelocity.yaw, -shellVelocity.pitch, 0))
    shift = srcMat.applyVector(
        Math.Vector3(self._StrategicCamera__dxdydz.x, 0,
                     -self._StrategicCamera__dxdydz.y)
    ) * self._StrategicCamera__curSense

    if replayCtrl.isPlaying and replayCtrl.isControllingCamera:
        aimOffset = replayCtrl.getAimClipPosition()
    else:
        aimWorldPos = self._StrategicCamera__aimingSystem.matrix.applyPoint(
            Math.Vector3(0, 0, 0))
        aimOffset = cameras.projectPoint(aimWorldPos)
        if replayCtrl.isRecording:
            replayCtrl.setAimClipPosition(
                Math.Vector2(aimOffset.x, aimOffset.y))

    self._StrategicCamera__aim.offset((aimOffset.x, aimOffset.y))
    shotDescr = BigWorld.player().vehicleTypeDescriptor.shot
    BigWorld.wg_trajectory_drawer().setParams(
        shotDescr['maxDistance'], Math.Vector3(0, -shotDescr['gravity'], 0),
        self._StrategicCamera__aim.offset())
    curTime = BigWorld.time()
    deltaTime = curTime - self._StrategicCamera__prevTime
    self._StrategicCamera__prevTime = curTime

    if replayCtrl.isPlaying:
        if self._StrategicCamera__needReset != 0:
            if self._StrategicCamera__needReset > 1:
                player = BigWorld.player()
                if player.inputHandler.ctrl is not None:
                    player.inputHandler.ctrl.resetGunMarkers()

            self._StrategicCamera__needReset = 0
        else:
            self._StrategicCamera__needReset += 1

        if replayCtrl.isControllingCamera:
            self._StrategicCamera__aimingSystem.updateTargetPos(
                replayCtrl.getGunRotatorTargetPoint())
        else:
            self._StrategicCamera__aimingSystem.handleMovement(
                shift.x, shift.z)
            if shift.x != 0 and shift.z != 0 or self._StrategicCamera__dxdydz.z != 0:
                self._StrategicCamera__needReset = 2

    self._StrategicCamera__aimingSystem.handleMovement(shift.x, shift.z)
    self._StrategicCamera__camDist -= self._StrategicCamera__dxdydz.z * float(
        self._StrategicCamera__curSense)
    maxPivotHeight = (distRange[1] -
                      distRange[0]) / BigWorld._ba_config['spg']['zoomSpeed']
    self._StrategicCamera__camDist = mathUtils.clamp(
        0, maxPivotHeight, self._StrategicCamera__camDist)
    self._StrategicCamera__cfg['camDist'] = self._StrategicCamera__camDist
    if self._StrategicCamera__dxdydz.z != 0 and self._StrategicCamera__onChangeControlMode is not None and mathUtils.almostZero(
            self._StrategicCamera__camDist - maxPivotHeight):
        self._StrategicCamera__onChangeControlMode()
    self._StrategicCamera__updateOscillator(deltaTime)
    if not self._StrategicCamera__autoUpdatePosition:
        self._StrategicCamera__dxdydz = Math.Vector3(0, 0, 0)

    fov = min(6.0 * descr.gun['shotDispersionAngle'], math.pi * 0.5)
    zoomFactor = 1.0 / math.tan(fov * 0.5) / 5.0

    #old scheme
    #zoomDistance = ( self._StrategicCamera__camDist + distRange[0] ) * zoomFactor

    #new scheme
    zoomDistance = distRange[0] * zoomFactor
    fovFactor = self._StrategicCamera__camDist / maxPivotHeight
    fov = fov * (1.0 - fovFactor) + math.radians(20.0) * fovFactor

    cameraOffset = -shellVelocity.scale(zoomDistance)
    cameraPosition = shotEnd + cameraOffset

    collPoint = None
    collPoint = BigWorld.wg_collideSegment(
        player.spaceID, shotEnd -
        shellVelocity.scale(1.0 if shellVelocity.y > 0.0 else distRange[0] *
                            zoomFactor * 0.25), cameraPosition, 128)

    if collPoint is None:
        collPoint = player.arena.collideWithSpaceBB(shotEnd, cameraPosition)
        if collPoint is not None:
            collPoint += shellVelocity
    else:
        collPoint = collPoint[0]

    recalculateDist = False
    if collPoint is not None:
        cameraPosition = collPoint
        cameraOffset = cameraPosition - shotEnd
        recalculateDist = True

    if cameraOffset.length > 700.0:
        cameraOffset.normalise()
        cameraOffset = cameraOffset.scale(700.0)
        cameraPosition = shotEnd + cameraOffset
        recalculateDist = True

    #if recalculateDist:
    #    self._StrategicCamera__camDist = cameraOffset.length / zoomFactor - distRange[0]

    #bb = BigWorld.player().arena.arenaType.boundingBox
    #cameraPositionClamped = _clampPoint2DInBox2D(bb[0] - Math.Vector2( 50.0, 50.0 ), bb[1] + Math.Vector2( 50.0, 50.0 ), Math.Vector2(cameraPosition.x, cameraPosition.z))

    #if abs( cameraPositionClamped.x - cameraPosition.x ) > 0.1 or abs( cameraPositionClamped.y - cameraPosition.z ) > 0.1:
    #    clampFactor = min( ( cameraPositionClamped.x - shotEnd.x ) / cameraOffset.x if abs( cameraOffset.x ) > 0.001 else 1.0, ( cameraPositionClamped.y - shotEnd.z ) / cameraOffset.z if abs( cameraOffset.z ) > 0.001 else 1.0 )
    #else:
    #    clampFactor = 1.0

    #if clampFactor < 0.99:
    #    cameraOffset *= clampFactor
    #    cameraPosition = shotEnd + cameraOffset
    #    self._StrategicCamera__camDist = cameraOffset.length / zoomFactor - distRange[0]

    trgMat = Math.Matrix()
    trgMat.setTranslate(cameraPosition)

    self._StrategicCamera__cam.source = srcMat
    self._StrategicCamera__cam.target.b = trgMat
    self._StrategicCamera__cam.pivotPosition = Math.Vector3(0, 0, 0)

    delta = self._prevFarPlane - self._prevNearPlane

    BigWorld.projection().nearPlane = max(cameraOffset.length - delta * 0.5,
                                          1.0)
    BigWorld.projection().farPlane = max(cameraOffset.length + delta * 0.5,
                                         self._prevFarPlane)
    BigWorld.projection().fov = fov
    BigWorld.player().positionControl.moveTo(shotEnd)

    #LOG_ERROR( '{0} {1}'.format( cameraPosition, self._StrategicCamera__camDist ) )
    #FLUSH_LOG( )

    return 0
Ejemplo n.º 24
0
 def tests(self):
     self.assertListEqual(Math.abc_factors_of(3, -5, -2), [[1, -6]])
     self.assertListEqual(Math.abc_factors_of(6, 1, -2), [[-3, 4]])
     self.assertListEqual(Math.abc_factors_of(6, -47, 77), [[-14, -33]])
Ejemplo n.º 25
0
from vehicle_systems.tankStructure import TankPartNames


def sum(array):
    value = array[0]
    for i in array[1:]:
        value = value + i
    return value


def avg(array):
    return sum(array) / len(array)


MODELS_OFFSET = Math.Vector3(0.0, 0.0, 0.0)

WHEEL_RADIUS = 0.4


class DumbPhysics(BasePhysics):
    def __init__(self, mover, physics):
        super(DumbPhysics, self).__init__(mover, physics)
        self.fallingSpeed = 0.0
        self.speed = 0.0
        self.rspeed = 0.0
        self.timeout = 0.0
        self.body = None

    def start(self):
        self.body = PhysicalBody(self)
Ejemplo n.º 26
0
    def updateCamouflage(self, camouflageID=None):
        texture = ''
        colors = [0, 0, 0, 0]
        weights = Math.Vector4(1, 0, 0, 0)
        camouflagePresent = True
        vDesc = self.__vDesc
        if vDesc is None:
            return
        else:
            if camouflageID is None and vDesc.camouflages is not None:
                camouflageID = vDesc.camouflages[g_tankActiveCamouflage.get(
                    vDesc.type.compactDescr, 0)][0]
            if camouflageID is None:
                for camouflageData in vDesc.camouflages:
                    if camouflageData[0] is not None:
                        camouflageID = camouflageData[0]
                        break

            customization = items.vehicles.g_cache.customization(
                vDesc.type.customizationNationID)
            defaultTiling = None
            if camouflageID is not None and customization is not None:
                camouflage = customization['camouflages'].get(camouflageID)
                if camouflage is not None:
                    camouflagePresent = True
                    texture = camouflage['texture']
                    colors = camouflage['colors']
                    weights = Math.Vector4(
                        (colors[0] >> 24) / 255.0, (colors[1] >> 24) / 255.0,
                        (colors[2] >> 24) / 255.0, (colors[3] >> 24) / 255.0)
                    defaultTiling = camouflage['tiling'].get(
                        vDesc.type.compactDescr)
            if self.__isVehicleDestroyed:
                weights *= 0.1
            if vDesc.camouflages is not None:
                _, camStartTime, camNumDays = vDesc.camouflages[
                    g_tankActiveCamouflage.get(vDesc.type.compactDescr, 0)]
                if camNumDays > 0:
                    timeAmount = (time.time() - camStartTime) / (camNumDays *
                                                                 86400)
                    if timeAmount > 1.0:
                        weights *= _CAMOUFLAGE_MIN_INTENSITY
                    elif timeAmount > 0:
                        weights *= (1.0 - timeAmount) * (
                            1.0 - _CAMOUFLAGE_MIN_INTENSITY
                        ) + _CAMOUFLAGE_MIN_INTENSITY
            for model in self.__models:
                exclusionMap = vDesc.type.camouflageExclusionMask
                tiling = defaultTiling
                if tiling is None:
                    tiling = vDesc.type.camouflageTiling
                tgDesc = None
                if model == self.__models[2]:
                    tgDesc = vDesc.turret
                elif model == self.__models[3]:
                    tgDesc = vDesc.gun
                if tgDesc is not None:
                    coeff = tgDesc.get('camouflageTiling')
                    if coeff is not None:
                        if tiling is not None:
                            tiling = (tiling[0] * coeff[0],
                                      tiling[1] * coeff[1],
                                      tiling[2] * coeff[2],
                                      tiling[3] * coeff[3])
                        else:
                            tiling = coeff
                    if tgDesc.has_key('camouflageExclusionMask'):
                        exclusionMap = tgDesc['camouflageExclusionMask']
                if not camouflagePresent or exclusionMap == '' or texture == '':
                    if hasattr(model, 'wg_fashion'):
                        delattr(model, 'wg_fashion')
                else:
                    if not hasattr(model, 'wg_fashion'):
                        if model == self.__models[0]:
                            tracksCfg = vDesc.chassis['tracks']
                            fashion = BigWorld.WGVehicleFashion()
                            fashion.setTracks(tracksCfg['leftMaterial'],
                                              tracksCfg['rightMaterial'],
                                              tracksCfg['textureScale'])
                            model.wg_fashion = fashion
                        else:
                            model.wg_fashion = BigWorld.WGBaseFashion()
                    model.wg_fashion.setCamouflage(texture, exclusionMap,
                                                   tiling, colors[0],
                                                   colors[1], colors[2],
                                                   colors[3], weights)

            return
    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'] = False
        ucfg['vertInvert'] = False
        ucfg['sniperModeByShift'] = False
        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 = math_utils.RangeFilter(
            self.__dynamicCfg['accelerationThreshold'],
            self.__dynamicCfg['accelerationMax'], 100,
            math_utils.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 __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 = math_utils.createRotationMatrix(
         Vector3(self.__aimingSystem.yaw, 0, 0))
     impulseDeviation, movementDeviation, oscillationsZoomMultiplier = self.__updateOscillators(
         deltaTime)
     relCamPosMatrix = math_utils.createTranslationMatrix(impulseDeviation +
                                                          movementDeviation)
     relCamPosMatrix.postMultiply(deviationBasis)
     relCamPosMatrix.translation += fromVehicleToUnshakedPos
     upRotMat = math_utils.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
     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
 def setToVehicleDirection(self):
     matrix = Math.Matrix(self.getTargetMProv())
     self.setYawPitch(matrix.yaw, matrix.pitch)
Ejemplo n.º 30
0
    def update(self):
        speedInfo = self.__vehicle.speedInfo.value
        vehicleSpeed = speedInfo[2]
        appearance = self.__appearance
        self.__variableArgs['speed'] = vehicleSpeed
        self.__variableArgs['isPC'] = isPC = self.__vehicle.isPlayerVehicle
        if vehicleSpeed > _VEHICLE_DIRECTION_THRESHOLD:
            direction = 1
        elif vehicleSpeed < -_VEHICLE_DIRECTION_THRESHOLD:
            direction = -1
        else:
            direction = 0
        self.__variableArgs['direction'] = direction
        self.__variableArgs['rotSpeed'] = speedInfo[1]
        matKindsUnderTracks = getCorrectedMatKinds(appearance)
        self.__variableArgs['deltaR'], self.__variableArgs[
            'directionR'], self.__variableArgs[
                'matkindR'] = self.__getScrollParams(
                    appearance.trackScrollController.rightSlip(),
                    appearance.trackScrollController.rightContact(),
                    matKindsUnderTracks[CustomEffectManager._RIGHT_TRACK],
                    direction)
        self.__variableArgs['deltaL'], self.__variableArgs[
            'directionL'], self.__variableArgs[
                'matkindL'] = self.__getScrollParams(
                    appearance.trackScrollController.leftSlip(),
                    appearance.trackScrollController.leftContact(),
                    matKindsUnderTracks[CustomEffectManager._LEFT_TRACK],
                    direction)
        self.__variableArgs['commonSlip'] = appearance.transmissionSlip
        matInv = Math.Matrix(self.__vehicle.matrix)
        matInv.invert()
        velocityLocal = matInv.applyVector(self.__vehicle.filter.velocity)
        velLen = velocityLocal.length
        if velLen > 1.0:
            vehicleDir = Math.Vector3(0.0, 0.0, 1.0)
            velocityLocal = Math.Vector2(velocityLocal.z, velocityLocal.x)
            cosA = velocityLocal.dot(Math.Vector2(vehicleDir.z,
                                                  vehicleDir.x)) / velLen
            self.__variableArgs['hullAngle'] = math.acos(
                math_utils.clamp(0.0, 1.0, math.fabs(cosA)))
        else:
            self.__variableArgs['hullAngle'] = 0.0
        self.__variableArgs[
            'isUnderWater'] = 1 if appearance.isUnderwater else 0
        self.__correctWaterNodes()
        self.__variableArgs['gearUp'] = self.__gearUP
        self.__variableArgs['RPM'] = rpm = self.__engineState.relativeRPM
        self.__gearUP = False
        self.__variableArgs['engineLoad'] = self.__engineState.mode
        self.__variableArgs['engineState'] = self.__engineState.engineState
        engineStart = self.__engineState.starting
        self.__variableArgs[
            'engineStart'] = engineStart and not self.__variableArgs.get(
                '__engineStarted', False)
        if engineStart or not isPC and rpm:
            self.__variableArgs['__engineStarted'] = True
        self.__variableArgs['physicLoad'] = self.__engineState.physicLoad
        if self.__wheelsData is not None:
            for wheelIndex in xrange(0, len(self.__wheelsData)):
                nodeName = self.__wheelsData[wheelIndex]
                self.__variableArgs[
                    nodeName +
                    ':contact'] = 0 if appearance.wheelsAnimator.wheelIsFlying(
                        wheelIndex) else 1

        for effectSelector in self.__selectors:
            effectSelector.update(self.__variableArgs)

        if _ENABLE_VALUE_TRACKER:
            self.__vt.addValue2('speed', self.__variableArgs['speed'])
            self.__vt.addValue2('direction', self.__variableArgs['direction'])
            self.__vt.addValue2('rotSpeed', self.__variableArgs['rotSpeed'])
            self.__vt.addValue2('deltaR', self.__variableArgs['deltaR'])
            self.__vt.addValue2('deltaL', self.__variableArgs['deltaL'])
            self.__vt.addValue2('hullAngle', self.__variableArgs['hullAngle'])
            self.__vt.addValue2('isUnderWater',
                                self.__variableArgs['isUnderWater'])
            self.__vt.addValue2('directionR',
                                self.__variableArgs['directionR'])
            self.__vt.addValue2('directionL',
                                self.__variableArgs['directionL'])
            if self.__variableArgs['matkindL'] > -1:
                materialL = material_kinds.EFFECT_MATERIAL_INDEXES_BY_IDS[
                    self.__variableArgs['matkindL']]
                self.__vt.addValue('materialL',
                                   material_kinds.EFFECT_MATERIALS[materialL])
            else:
                self.__vt.addValue('materialL', 'No')
            if self.__variableArgs['matkindR'] > -1:
                materialR = material_kinds.EFFECT_MATERIAL_INDEXES_BY_IDS[
                    self.__variableArgs['matkindR']]
                self.__vt.addValue('materialR',
                                   material_kinds.EFFECT_MATERIALS[materialR])
            else:
                self.__vt.addValue('materialR', 'No')
        if _ENABLE_VALUE_TRACKER_ENGINE:
            self.__vt.addValue2('engineStart',
                                self.__variableArgs['engineStart'])
            self.__vt.addValue2('gearUP', self.__variableArgs['gearUp'])
            self.__vt.addValue2('RPM', self.__variableArgs['RPM'])
            self.__vt.addValue2('engineLoad', self.__engineState.mode)
            self.__vt.addValue2('physicLoad', self.__engineState.physicLoad)
        if _ENABLE_PIXIE_TRACKER:
            self.__vt.addValue2('Pixie Count', PixieCache.pixiesCount)
        return
 def __init__(self):
     self.__plane = Math.Plane()
     self.init(Vector3(0.0, 0.0, 0.0), Vector3(0.0, 0.0, 0.0))
Ejemplo n.º 32
0
 def test_non_primes(self):
     """ Prime check for non-prime numbers. """
     for i in self.non_primes:
         self.assertFalse(Math.is_prime(i), i)
Ejemplo n.º 33
0
 def test_non_squares(self):
     """ Square check for non perfect square numbers. """
     for i in self.non_squares:
         self.assertFalse(Math.is_square(i), i)
Ejemplo n.º 34
0
    def __init__(self, body, isRight):
        self.body = body
        self.physics = body.physics
        self.isRight = isRight

        chassisBbox = self.physics.vehicle.typeDescriptor.chassis[
            'hitTester'].bbox

        self.localPosition = Math.Vector3(chassisBbox[0][0], 0, 0)
        if isRight:
            self.localPosition = -self.localPosition

        self.halfLength = max(abs(chassisBbox[0][2]), abs(chassisBbox[1][2]))
        self.height = max(abs(chassisBbox[0][1]), abs(chassisBbox[1][1]))
        self.wheels = [
            Wheel(self, False, True,
                  Math.Vector3(0, self.height / 2.0, -self.halfLength)),
            Wheel(self, True, False, Math.Vector3(0, 0,
                                                  -self.halfLength * 0.75)),
            Wheel(self, True, False, Math.Vector3(0, 0,
                                                  -self.halfLength * 0.5)),
            Wheel(self, False, False,
                  Math.Vector3(0, 0, -self.halfLength * 0.25)),
            Wheel(self, False, False, Math.Vector3(0, 0, 0)),
            Wheel(self, False, False, Math.Vector3(0, 0,
                                                   self.halfLength * 0.25)),
            Wheel(self, True, False, Math.Vector3(0, 0,
                                                  self.halfLength * 0.5)),
            Wheel(self, True, False, Math.Vector3(0, 0,
                                                  self.halfLength * 0.75)),
            Wheel(self, False, True,
                  Math.Vector3(0, self.height / 2.0, self.halfLength)),
        ]

        self.position = Math.Vector3()
        self.pitch = 0
        self.isOnGround = False
        self.positionOnGround = Math.Vector3()
Ejemplo n.º 35
0
# Embedded file name: scripts/client/bwobsolete_helpers/V4ShaderConsts.py
import Math
_mov = 0
_rcp = 1
_bias = 2
_comp = 3
_mul = 4
_div = 5
_add = 6
_sub = 7
_dot = 8
_min = 9
_max = 10
_sge = 11
_slt = 12
_r0 = Math.getRegister(0)
_r1 = Math.getRegister(1)
_r2 = Math.getRegister(2)
_r3 = Math.getRegister(3)
_r4 = Math.getRegister(4)
_r5 = Math.getRegister(5)
_r6 = Math.getRegister(6)
_r7 = Math.getRegister(7)
_r8 = Math.getRegister(8)
_r9 = Math.getRegister(9)
_r10 = Math.getRegister(10)
_r11 = Math.getRegister(11)
_r12 = Math.getRegister(12)
_r13 = Math.getRegister(13)
_r14 = Math.getRegister(14)
_r15 = Math.getRegister(15)
Ejemplo n.º 36
0
 def rotate(self, rspeed):
     self.applyRotation(Math.Vector3(rspeed, 0, 0))
 def _getRandomVectorForFakeBullets(self):
     randomKoef = 2
     randomVector = Math.Vector3((random() - 0.5) * 2 * randomKoef,
                                 (random() - 0.5) * 2 * randomKoef,
                                 (random() - 0.5) * 2 * randomKoef)
     return randomVector
Ejemplo n.º 38
0
 def getRotationMatrix(self):
     matrix = Math.Matrix()
     matrix.setRotateYPR(self.rotation)
     return matrix
Ejemplo n.º 39
0
 def __getAlignedToPointPosition(self, rotationMat):
     dirVector = Math.Vector3(0, 0, self.__rotationRadius)
     camMat = Math.Matrix(self.__cam.invViewProvider.a)
     point = camMat.applyPoint(dirVector)
     return point + rotationMat.applyVector(-dirVector)
Ejemplo n.º 40
0
 def _direction(self):
     return Math.Matrix(self.matrix).applyToAxis(2)
Ejemplo n.º 41
0
def StrategicAimingSystem_updateMatrix(self):
    global gSPGSniperEnabled
    if not gSPGSniperEnabled:
        if self._lastModeWasSniper:
            self._StrategicAimingSystem__planePosition.x = self._matrix.translation.x
            self._StrategicAimingSystem__planePosition.y = 0.0
            self._StrategicAimingSystem__planePosition.z = self._matrix.translation.z

        oldStrategicAimingSystem_updateMatrix(self)
        self._lastModeWasSniper = False
        return

    player = BigWorld.player()
    descr = player.vehicleTypeDescriptor

    bb = BigWorld.player().arena.arenaType.boundingBox
    pos2D = _clampPoint2DInBox2D(
        bb[0] - Math.Vector2(200.0, 200.0), bb[1] + Math.Vector2(200.0, 200.0),
        Math.Vector2(self._StrategicAimingSystem__planePosition.x,
                     self._StrategicAimingSystem__planePosition.z))
    self._StrategicAimingSystem__planePosition.x = pos2D[0]
    self._StrategicAimingSystem__planePosition.z = pos2D[1]

    playerPos = player.getOwnVehiclePosition()

    if not self._lastModeWasSniper:
        collPoint = BigWorld.wg_collideSegment(
            BigWorld.player().spaceID,
            self._StrategicAimingSystem__planePosition +
            Math.Vector3(0, 1000.0, 0),
            self._StrategicAimingSystem__planePosition +
            Math.Vector3(0, -1000.0, 0), 3)
        self._StrategicAimingSystem__planePosition.y = 0.0 if collPoint is None else collPoint[
            0][1]
        self._initialDistance = (Math.Vector3(
            self._StrategicAimingSystem__planePosition.x, playerPos.y,
            self._StrategicAimingSystem__planePosition.z) -
                                 playerPos).length + 0.01

    distance = (
        Math.Vector3(self._StrategicAimingSystem__planePosition.x, playerPos.y,
                     self._StrategicAimingSystem__planePosition.z) -
        playerPos).length + 0.01
    heightFactor = distance / self._initialDistance

    turretYaw, gunPitch = getShotAngles(
        descr, player.getOwnVehicleMatrix(), (0, 0),
        Math.Vector3(
            self._StrategicAimingSystem__planePosition.x,
            playerPos.y * (1.0 - heightFactor) +
            self._StrategicAimingSystem__planePosition.y * heightFactor,
            self._StrategicAimingSystem__planePosition.z), True)
    #gunPitchLimits = calcPitchLimitsFromDesc(turretYaw, descr.gun['pitchLimits'])
    currentGunMat = AimingSystems.getPlayerGunMat(turretYaw, gunPitch)
    clientShotStart = currentGunMat.translation
    clientShotVec = currentGunMat.applyVector(
        Math.Vector3(0, 0, descr.shot['speed']))

    self._matrix.translation, self._shellVelocity = _getGunMarkerPosition(
        clientShotStart, clientShotVec)
    self._lastModeWasSniper = True
Ejemplo n.º 42
0
    def decodeHitPoints(encodedPoints,
                        collisionComponent,
                        maxComponentIdx=TankPartIndexes.ALL[-1]):
        resultPoints = []
        maxHitEffectCode = None
        maxDamagedComponentName = None
        for encodedPoint in encodedPoints:
            compIdx, hitEffectCode, startPoint, endPoint = DamageFromShotDecoder.decodeSegment(
                encodedPoint, collisionComponent, maxComponentIdx)
            if startPoint == endPoint or compIdx < 0:
                continue
            convertedCompIdx = DamageFromShotDecoder.convertComponentIndex(
                compIdx)
            if hitEffectCode > maxHitEffectCode:
                maxHitEffectCode = hitEffectCode
                maxDamagedComponentName = TankPartIndexes.getName(compIdx)
                if not maxDamagedComponentName:
                    maxDamagedComponentName = collisionComponent.getPartName(
                        convertedCompIdx)
            hitTestRes = collisionComponent.collideLocal(
                convertedCompIdx, startPoint, endPoint)
            bbox = collisionComponent.getBoundingBox(convertedCompIdx)
            if not hitTestRes or hitTestRes < 0.0:
                width, height, depth = (bbox[1] - bbox[0]) / 256.0
                directions = [
                    Math.Vector3(0.0, -height, 0.0),
                    Math.Vector3(0.0, height, 0.0),
                    Math.Vector3(-width, 0.0, 0.0),
                    Math.Vector3(width, 0.0, 0.0),
                    Math.Vector3(0.0, 0.0, -depth),
                    Math.Vector3(0.0, 0.0, depth)
                ]
                for direction in directions:
                    hitTestRes = collisionComponent.collideLocal(
                        convertedCompIdx, startPoint + direction,
                        endPoint + direction)
                    if hitTestRes >= 0.0:
                        break

            if hitTestRes is None or hitTestRes < 0.0:
                newPoint = collisionComponent.collideLocalPoint(
                    convertedCompIdx, startPoint, MAX_FALLBACK_CHECK_DISTANCE)
                if newPoint.length > 0.0:
                    hitRay = endPoint - startPoint
                    hitTestRes = hitRay.length
                    endPoint = newPoint
                    startPoint = endPoint - hitRay
            if hitTestRes is None or hitTestRes < 0.0:
                continue
            minDist = hitTestRes
            hitDir = endPoint - startPoint
            hitDir.normalise()
            rot = Matrix()
            rot.setRotateYPR((hitDir.yaw, hitDir.pitch, 0.0))
            matrix = Matrix()
            matrix.setTranslate(startPoint + hitDir * minDist)
            matrix.preMultiply(rot)
            effectGroup = DamageFromShotDecoder.__hitEffectCodeToEffectGroup[
                hitEffectCode]
            componentName = TankPartIndexes.getName(compIdx)
            if not componentName:
                componentName = collisionComponent.getPartName(
                    convertedCompIdx)
            resultPoints.append(
                DamageFromShotDecoder.ShotPoint(componentName, matrix,
                                                effectGroup))

        return (maxHitEffectCode, resultPoints, maxDamagedComponentName)
Ejemplo n.º 43
0
def getMouseTargettingRay():
    mtm = Math.Matrix(BigWorld.MouseTargettingMatrix())
    src = mtm.applyToOrigin()
    far = BigWorld.projection().farPlane
    dst = src + mtm.applyToAxis(2).scale(far)
    return (src, dst)
    def update(self, dt=0):
        if not self._owner:
            return
        else:
            self.__setUpdateCallback()
            if hasattr(self._owner,
                       'turretTargetID') and self._owner.turretTargetID != -1:
                targetEntity = BigWorld.entities.get(
                    self._owner.turretTargetID, None) if hasattr(
                        self._owner, 'turretTargetID') else None
                matrix = Math.Matrix()
                if targetEntity and targetEntity.inWorld:
                    targetImaginePos = targetEntity.position
                    matrix.translation = targetImaginePos
                else:
                    targetImaginePos = self._owner.turretTargetPosition
                    matrix.translation = targetImaginePos
                self.eSetControlMtx(matrix)
                self.eTurretTargetChanged(self._owner.turretTargetID)
                playSound = False
                if targetImaginePos:
                    ownRotation = Math.Quaternion()
                    ownRotation.fromEuler(self._owner.roll, self._owner.pitch,
                                          self._owner.yaw)
                    for gunner in self.__gunners.values():
                        if gunner.isAlive:
                            gunner.position = self._owner.position + Math.Quaternion(
                                ownRotation).rotateVec(gunner.relativePos)
                            yawOnTarget, pitchOnTarget = getRotationAnglesOnTarget(
                                gunner.position, ownRotation, targetImaginePos)
                            gunner.yaw = rotateAxisWithSpeed(
                                gunner.yaw, yawOnTarget,
                                self.settings.yawSpeed, self.settings.yawMin,
                                self.settings.yawMax)
                            gunner.pitch = rotateAxisWithSpeedEx(
                                gunner.pitch, pitchOnTarget,
                                self.settings.pitchSpeed,
                                self.settings.pitchMin, self.settings.pitchMax)
                            gunQuat = Math.Quaternion(ownRotation)
                            gunQuat.normalise()
                            axisX = gunQuat.getAxisX()
                            axisY = gunQuat.getAxisY()
                            q = Math.Quaternion()
                            q.fromAngleAxis(-gunner.pitch, axisX)
                            gunQuat.mulLeft(q)
                            q.fromAngleAxis(gunner.yaw, axisY)
                            gunQuat.mulLeft(q)
                            gunner.rotation = gunQuat
                            if self.__isFiring:
                                self.__reloadTimer -= SERVER_TICK_LENGTH
                                if self.__reloadTimer <= 0.0:
                                    self.__shoot(gunner)
                                    playSound = True
                            elif self.__curBurstTilesCounter < self._owner.turretShootCount:
                                self.__reloadTimer -= SERVER_TICK_LENGTH
                                if self.__reloadTimer <= 0.0:
                                    self.__shoot(gunner)
                                    playSound = True

                if playSound and self.__sound and not self.__soundWasStarted:
                    self.__soundWasStarted = True
                    self.__sound.play()
                    self._owner.updateTurretsRotations(self.__gunners)
            return
Ejemplo n.º 45
0
 def __onVehicleLeaveWorld(self, vehicle):
     if not self.__bActive:
         return
     if vehicle.id == self.__killerVehicleID:
         if self.__bKillerVisionActive:
             self.__arcadeCamera.vehicleMProv = Math.Matrix(self.__arcadeCamera.vehicleMProv)
Ejemplo n.º 46
0
 def _getYawAngle(direction):
     xzProjection = Math.Vector3(direction.x, 0, direction.z)
     return sign(-direction.x) * xzProjection.angle(Math.Vector3(0, 0, 1))
Ejemplo n.º 47
0
 def test_primes(self):
     """ Prime check for prime numbers. """
     for i in self.primes:
         self.assertTrue(Math.is_prime(i), i)
Ejemplo n.º 48
0
 def __getRandomSpawnPos(self):
     randHeight = random.uniform(0, self.spawnHeight)
     randAngle = random.uniform(0, 2 * math.pi)
     randRadius = random.uniform(0, self.spawnRadius)
     return Math.Vector3(randRadius * math.cos(randAngle), randHeight, randRadius * math.sin(randAngle)) + self.position
Ejemplo n.º 49
0
 def test_squares(self):
     """ Square check for perfect square numbers. """
     for i in self.squares:
         self.assertTrue(Math.is_square(i), i)
Ejemplo n.º 50
0
 def test_00_fib_first_10(self):
     """Run fib on first 10 integers starting at 0"""
     for _ in range(10):
         Math.fib(_)
Ejemplo n.º 51
0
 def tests(self):
     self.assertListEqual(Math.factor_pairs_of(100), [[1, 100], [2, 50], [4, 25], [5, 20], [10, 10]])
     self.assertListEqual(Math.factor_pairs_of(1877), [[1, 1877]])
     self.assertListEqual(Math.factor_pairs_of(1), [[1, 1]])
Ejemplo n.º 52
0
 def __resetSenses(self):
     self.__movementSensor.currentVelocity = Math.Vector3()
     self.__verticalMovementSensor.currentVelocity = 0.0
     self.__rotationSensor.currentVelocity = Math.Vector3()
     self.__zoomSensor.currentVelocity = 0.0
     self.__targetRadiusSensor.currentVelocity = 0.0
Ejemplo n.º 53
0
 def tests(self):
     self.assertEqual(Math.gcd(10, 20), 10)
     self.assertEqual(Math.gcd(27, 32), 1)
     self.assertEqual(Math.gcd(12, 40), 4)
     self.assertEqual(Math.gcd(15.0, 20.0), 5)
     self.assertEqual(Math.gcdm(48, 180, 14), 2)
Ejemplo n.º 54
0
 def getAvatarOwnVehicleStabilisedMatrix(self):
     player = BigWorld.player()
     vehicle = player.getVehicleAttached()
     return Math.Matrix(vehicle.matrix) if vehicle is not None else super(
         VehicleObserverGunRotator,
         self).getAvatarOwnVehicleStabilisedMatrix()
 def __shake(self):
     matrix = Math.Matrix(self.__appearance.compoundModel.matrix)
     impulseDir = -matrix.applyToAxis(2)
     self.__appearance.receiveShotImpulse(impulseDir, self.SIEGE_IMPULSE)
Ejemplo n.º 56
0
 def processReplayHover(self):
     replayCtrl = BattleReplay.g_replayCtrl
     _, self.hitPosition, direction = replayCtrl.getGunMarkerParams(
         self.hitPosition, Math.Vector3(0.0, 0.0, 0.0))
     self.__marker.update(self.hitPosition, Vector3(0, 0, 1), 10,
                          SERVER_TICK_LENGTH, None)
Ejemplo n.º 57
0
    def __readCfg(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()
        self.__keySwitches['keyRevertVerticalVelocity'] = getattr(
            Keys, configDataSec.readString('keyRevertVerticalVelocity',
                                           'KEY_Z'))
        self.__mouseSensitivity = configDataSec.readFloat('sensitivity', 1.0)
        self.__scrollSensitivity = configDataSec.readFloat(
            'scrollSensitivity', 1.0)
        rotationMappings = dict()
        rotationMappings[getattr(
            Keys,
            configDataSec.readString('keyRotateLeft',
                                     'KEY_LEFTARROW'))] = Vector3(-1, 0, 0)
        rotationMappings[getattr(
            Keys,
            configDataSec.readString('keyRotateRight',
                                     'KEY_RIGHTARROW'))] = Vector3(1, 0, 0)
        rotationMappings[getattr(
            Keys,
            configDataSec.readString('keyRotateUp',
                                     'KEY_UPARROW'))] = Vector3(0, -1, 0)
        rotationMappings[getattr(
            Keys,
            configDataSec.readString('keyRotateDown',
                                     'KEY_DOWNARROW'))] = Vector3(0, 1, 0)
        rotationMappings[getattr(
            Keys, configDataSec.readString('keyRotateClockwise',
                                           'KEY_HOME'))] = Vector3(0, 0, -1)
        rotationMappings[getattr(
            Keys, configDataSec.readString('keyRotateCClockwise',
                                           'KEY_END'))] = Vector3(0, 0, 1)
        rotationSensitivity = configDataSec.readFloat('angularVelocity', 0.7)
        rotationSensitivityAcc = configDataSec.readFloat(
            'angularVelocityAcceleration', 0.8)
        rotationIncDecKeys = (getattr(
            Keys,
            configDataSec.readString('keyAngularVelocityIncrement', 'KEY_O')),
                              getattr(
                                  Keys,
                                  configDataSec.readString(
                                      'keyAngularVelocityDecrement', 'KEY_L')))
        self.__rotationSensor = KeySensor(rotationMappings,
                                          rotationSensitivity,
                                          rotationIncDecKeys,
                                          rotationSensitivityAcc)
        self.__rotationSensor.currentVelocity = Math.Vector3()
        self.__keySwitches['keySetDefaultRoll'] = getattr(
            Keys, configDataSec.readString('keySetDefaultRoll', 'KEY_R'))
        zoomMappings = dict()
        zoomMappings[getattr(
            Keys, configDataSec.readString('keyZoomGrowUp',
                                           'KEY_INSERT'))] = -1
        zoomMappings[getattr(
            Keys, configDataSec.readString('keyZoomGrowDown',
                                           'KEY_DELETE'))] = 1
        zoomSensitivity = configDataSec.readFloat('zoomVelocity', 2.0)
        zoomSensitivityAcc = configDataSec.readFloat(
            'zoomVelocityAcceleration', 1.5)
        zoomIncDecKeys = (getattr(
            Keys,
            configDataSec.readString('keyZoomVelocityIncrement',
                                     'KEY_NUMPADMINUS')),
                          getattr(
                              Keys,
                              configDataSec.readString(
                                  'keyZoomVelocityDecrement', 'KEY_ADD')))
        self.__zoomSensor = KeySensor(zoomMappings, zoomSensitivity,
                                      zoomIncDecKeys, zoomSensitivityAcc)
        self.__zoomSensor.currentVelocity = 0.0
        self.__keySwitches['keySwitchInertia'] = getattr(
            Keys, configDataSec.readString('keySwitchInertia', 'KEY_P'))
        self.__movementInertia = _Inertia(
            configDataSec.readFloat('linearFriction', 0.1))
        self.__rotationInertia = _Inertia(
            configDataSec.readFloat('rotationFriction', 0.1))
        self.__keySwitches['keySwitchRotateAroundPoint'] = getattr(
            Keys,
            configDataSec.readString('keySwitchRotateAroundPoint', 'KEY_C'))
        aroundPointMappings = dict()
        aroundPointMappings[getattr(
            Keys,
            configDataSec.readString('keyTargetRadiusIncrement',
                                     'KEY_NUMPAD7'))] = 1
        aroundPointMappings[getattr(
            Keys,
            configDataSec.readString('keyTargetRadiusDecrement',
                                     'KEY_NUMPAD1'))] = -1
        aroundPointRadiusVelocity = configDataSec.readFloat(
            'targetRadiusVelocity', 3.0)
        self.__targetRadiusSensor = KeySensor(aroundPointMappings,
                                              aroundPointRadiusVelocity)
        self.__targetRadiusSensor.currentVelocity = 0.0
        self.__keySwitches['keySwitchLandCamera'] = getattr(
            Keys, configDataSec.readString('keySwitchLandCamera', 'KEY_L'))
        self.__keySwitches['keySetDefaultFov'] = getattr(
            Keys, configDataSec.readString('keySetDefaultFov', 'KEY_F'))
        self.__keySwitches['keyBindToVehicle'] = getattr(
            Keys, configDataSec.readString('keyBindToVehicle', 'KEY_B'), None)
        predefVelocitySec = configDataSec['predefinedVelocities']
        if predefVelocitySec is not None:
            for v in predefVelocitySec.items():
                key = getattr(Keys, v[0], None)
                if key is not None:
                    self.__predefinedVelocities[key] = v[1].asFloat

        predefVelocitySec = configDataSec['predefinedVerticalVelocities']
        if predefVelocitySec is not None:
            for v in predefVelocitySec.items():
                key = getattr(Keys, v[0], None)
                if key is not None:
                    self.__predefinedVerticalVelocities[key] = v[1].asFloat

        return
 def getEntityVector(self, entity):
     return getattr(entity.filter, 'vector', Math.Vector3())
Ejemplo n.º 59
0
 def _getPitchAngle(direction):
     yzProjection = Math.Vector3(direction.x, 0, direction.z)
     return sign(direction.y) * direction.angle(yzProjection)
Ejemplo n.º 60
0
class _GuiColorsLoader(object):
    XML_PATH = 'gui/gui_colors.xml'
    DEFAULT_ALIAS_COLOR = None
    DEFAULT_RGBA_COLOR = Math.Vector4(255, 255, 255, 255)
    DEFAULT_COLOR_OFFSET = Math.Vector4(0, 0, 0, 0)
    DEFAULT_TRANSFORM_COLOR_MULT = Math.Vector4(1, 1, 1, 1)
    DEFAULT_TRANSFORM_COLOR_OFFSET = DEFAULT_COLOR_OFFSET
    DEFAULT_ADJUST_OFFSET = DEFAULT_COLOR_OFFSET
    ALIAS = 'alias_color'
    GROUP = 'schemeGroup'
    RGBA = 'rgba'
    MULT = 'mult'
    OFFSET = 'offset'
    TRANSFORM = 'transform'
    ADJUST = 'adjust'
    DEFAULTS = {
        OFFSET: DEFAULT_COLOR_OFFSET,
        RGBA: DEFAULT_RGBA_COLOR,
        MULT: DEFAULT_TRANSFORM_COLOR_MULT,
        ALIAS: DEFAULT_ALIAS_COLOR
    }
    VECTOR4_NAMES = (RGBA, MULT, OFFSET)
    STRING_NAMES = (ALIAS, GROUP)
    DEFAULT_TAG = 'default'
    COLOR_BLIND_TAG = 'color_blind'
    DEFAULT_SCHEME = {
        'alias_color': DEFAULT_ALIAS_COLOR,
        'rgba': DEFAULT_RGBA_COLOR,
        'transform': {
            'mult': DEFAULT_TRANSFORM_COLOR_MULT,
            'offset': DEFAULT_TRANSFORM_COLOR_OFFSET
        },
        'adjust': {
            'offset': DEFAULT_ADJUST_OFFSET
        }
    }

    def __init__(self):
        self.__colors = {}

    def clear(self):
        self.__colors.clear()

    def __readXML(self, xmlCtx):
        xmlHash = self.__readHash(xmlCtx)
        xmlHash = self.__overrideTags(xmlHash, xmlHash)
        for scheme_name in xmlHash.keys():
            scheme = xmlHash[scheme_name]
            color_scheme = self.__readColorScheme(scheme)
            self.__colors[scheme_name] = color_scheme

    def __readHash(self, rootSection):
        outcome = {}
        for scheme_name, scheme_section in rootSection.items():
            if scheme_name in self.VECTOR4_NAMES:
                outcome[scheme_name] = self.__readVector4(
                    rootSection, scheme_name)
            elif scheme_name in self.STRING_NAMES:
                outcome[scheme_name] = self.__readString(
                    rootSection, scheme_name)
            else:
                outcome[scheme_name] = self.__readHash(scheme_section)

        return outcome

    def __overrideTags(self, rootSection, baseHash):
        keys = baseHash.keys()
        defaultExists = self.DEFAULT_TAG in keys
        for key in keys:
            if key == self.GROUP:
                groupNames = baseHash[key].split(' ')
                del baseHash[key]
                for groupName in groupNames:
                    insertingSection = rootSection[groupName]
                    overrideDefaultExists = self.DEFAULT_TAG in insertingSection.keys(
                    )
                    if defaultExists != overrideDefaultExists and len(
                            keys) > 1:
                        if defaultExists:
                            LOG_ERROR(
                                'schemeGroup tag requires "default" tag. Failed Tag:\n'
                                + str(baseHash))
                        else:
                            LOG_ERROR(
                                'schemeGroup tag requires to delete a "default" tag. Failed Tag:\n'
                                + str(baseHash))
                        return baseHash
                    for subKey in insertingSection.keys():
                        if subKey not in baseHash.keys():
                            baseHash[subKey] = insertingSection[subKey]
                        else:
                            baseHash[subKey].update(insertingSection[subKey])

                baseHash = self.__overrideTags(rootSection, baseHash)
            else:
                section = baseHash[key]
                if key not in self.VECTOR4_NAMES and key not in self.STRING_NAMES:
                    baseHash[key] = self.__overrideTags(rootSection, section)

        return baseHash

    def __readColorScheme(self, hash):
        color_scheme = {self.DEFAULT_TAG: None}
        section = hash[
            self.DEFAULT_TAG] if self.DEFAULT_TAG in hash.keys() else None
        if section is not None:
            color_scheme[self.DEFAULT_TAG] = self.__readColorSection(section)
            if self.COLOR_BLIND_TAG in hash.keys():
                section = hash[self.COLOR_BLIND_TAG]
                if section is not None:
                    color_scheme[
                        self.COLOR_BLIND_TAG] = self.__readColorSection(
                            section)
        else:
            color_scheme[self.DEFAULT_TAG] = self.__readColorSection(hash)
        return color_scheme

    def __readVector4(self, section, tagName):
        value = section[tagName]
        return value.asVector4

    def __readString(self, section, tagName):
        value = section[tagName]
        return value.asString

    def __readTransformSection(self, section):
        mult = self.DEFAULT_TRANSFORM_COLOR_MULT
        offset = self.DEFAULT_TRANSFORM_COLOR_OFFSET
        processed = section['transform']
        if processed is not None:
            mult = self.__readVector4(processed, 'mult')
            offset = self.__readVector4(processed, 'offset')
        return {'mult': mult, 'offset': offset}

    def __readColorSection(self, section):
        color_scheme = self.__initColorScheme(section)
        color_scheme = self.__readFilters(section, color_scheme)
        return color_scheme

    def __initColorScheme(self, section):
        keys = section.keys()
        color_scheme = {
            self.ALIAS:
            section[self.ALIAS]
            if self.ALIAS in keys else self.DEFAULT_ALIAS_COLOR,
            self.RGBA:
            section[self.RGBA]
            if self.RGBA in keys else self.DEFAULT_RGBA_COLOR
        }
        return color_scheme

    def __readFilters(self, section, color_scheme):
        keys = section.keys()
        color_scheme[self.TRANSFORM] = {
            self.MULT: self.DEFAULT_TRANSFORM_COLOR_MULT,
            self.OFFSET: self.DEFAULT_TRANSFORM_COLOR_OFFSET
        }
        if self.TRANSFORM in keys:
            transformSection = section[self.TRANSFORM]
            transformKeys = transformSection.keys()
            if self.MULT in transformKeys:
                color_scheme[self.TRANSFORM][self.MULT] = transformSection[
                    self.MULT]
            if self.OFFSET in transformKeys:
                color_scheme[self.TRANSFORM][self.OFFSET] = transformSection[
                    self.OFFSET]
        color_scheme[self.ADJUST] = {self.OFFSET: self.DEFAULT_ADJUST_OFFSET}
        if self.ADJUST in keys:
            if self.OFFSET in section[self.ADJUST].keys():
                color_scheme[self.ADJUST][self.OFFSET] = section[self.ADJUST][
                    self.OFFSET]
        return color_scheme

    def load(self):
        xmlCtx = ResMgr.openSection(self.XML_PATH)
        if xmlCtx is None:
            _xml.raiseWrongXml(None, self.XML_PATH, 'can not open or read')
        self.__readXML(xmlCtx)
        return

    def items(self):
        return self.__colors.items()

    def schemasNames(self):
        return self.__colors.keys()

    def getColorScheme(self, schemeName):
        return self.__colors.get(schemeName)

    def getSubScheme(self, schemeName, group):
        scheme = self.getColorScheme(schemeName)
        if scheme is None:
            LOG_WARNING('Color scheme not found', schemeName, group)
            return self.DEFAULT_SCHEME
        elif group in scheme:
            return scheme[group]
        else:
            return scheme['default']

    def getSubSchemeToFlash(self, schemeName, group):
        result = self.getSubScheme(schemeName, group)
        transform = result['transform']
        return {
            'adjust': {
                'offset': result['adjust']['offset'].tuple()
            },
            'transform': {
                'mult': transform['mult'].tuple(),
                'offset': transform['offset'].tuple()
            },
            'rgba': result['rgba'].tuple(),
            'alias_color': result['alias_color']
        }