Пример #1
0
def find_controller(name):
	nl=name.lower()
	devices = hg.GetInputSystem().GetDevices()
	s = devices.size()
	for i in range(0, s):
		device_id = devices.at(i)
		d=device_id.lower()
		if d == nl:
			return hg.GetInputSystem().GetDevice(device_id)
	return None
Пример #2
0
def GameControlCamera(dt):
	mouse_device = hg.GetInputSystem().GetDevice("mouse")

	mouse_wheel = mouse_device.GetValue(hg.InputRotY)
	if mouse_wheel != 0.0:
		gg.camera_zoom_target += gg.zoom_speed * hg.time_to_sec_f(dt) * mouse_wheel
		gg.camera_zoom_target = max(min(gg.camera_zoom_target, gg.zoom_min_max.y), gg.zoom_min_max.x)
		print(gg.camera_zoom_target)

	if mouse_device.IsButtonDown(hg.Button0):
		gg.mouse = hg.Vector2(mouse_device.GetValue(hg.InputAxisX), mouse_device.GetValue(hg.InputAxisY))
		mouse_speed = gg.prev_mouse - gg.mouse
		gg.prev_mouse = hg.Vector2(gg.mouse)
		# print("Mouse X: %f, Mouse Y: %f" % (mouse_speed.x, mouse_speed.y))

		gg.camera_target_angle.x -= radians(mouse_speed.y * hg.time_to_sec_f(dt) * gg.camera_rot_x_speed)
		gg.camera_target_angle.x = max(min(gg.camera_target_angle.x, gg.camera_rot_x_min_max.y), gg.camera_rot_x_min_max.x)
		gg.camera_target_angle.y += radians(mouse_speed.x * hg.time_to_sec_f(dt) * gg.camera_rot_y_speed)
	else:
		gg.mouse = hg.Vector2(mouse_device.GetValue(hg.InputAxisX), mouse_device.GetValue(hg.InputAxisY))
		gg.prev_mouse = hg.Vector2(gg.mouse)

	cam_dt = gg.camera_target_angle - gg.camera_angle
	zoom_dt = gg.camera_zoom_target - gg.camera_zoom

	if gg.camera_lazyness == 0:
		cam_dt *= hg.time_to_sec_f(dt)
		zoom_dt *= hg.time_to_sec_f(dt)
	else:
		cam_dt *= hg.time_to_sec_f(dt) * (1.0 / gg.camera_lazyness)
		zoom_dt *= hg.time_to_sec_f(dt) * (1.0 / gg.camera_lazyness)

	gg.camera_angle += cam_dt
	gg.camera.GetTransform().SetRotation(gg.camera_angle * hg.Vector3(1.0, 0.0, 0.0))
	gg.camera_y_controller.GetTransform().SetRotation(gg.camera_angle * hg.Vector3(0.0, 1.0, 0.0))

	gg.camera_zoom += zoom_dt
	gg.camera.GetCamera().SetZoomFactor(gg.camera_zoom)
Пример #3
0
# How to read values from the mouse

import harfang as hg

hg.LoadPlugins()

plus = hg.GetPlus()
plus.RenderInit(400, 300)

# continue while the window is open
print("Click the left mouse button to print the current mouse cursor position")
print("Close the renderer window or press Ctrl+C in this window to end")

while not plus.IsAppEnded():
    # get the mouse device
    mouse_device = hg.GetInputSystem().GetDevice("mouse")

    # check if left button is down
    if mouse_device.IsButtonDown(hg.Button0):
        # get the mouse position in the window ([0, 1])
        print("Mouse X: %f, Mouse Y: %f" % (mouse_device.GetValue(
            hg.InputAxisX), mouse_device.GetValue(hg.InputAxisY)))

    plus.Flip()
    plus.EndFrame()

plus.RenderUninit()
Пример #4
0
		pic.DrawPath()  # draw the path

	# draw hour needle
	pic.SetFillColorRGBA(0,0,0)
	draw_needle((date.hour % 12 / 12) * math.pi*2, radius * 0.6, radius * 0.075)

	# draw minute needle
	pic.SetFillColorRGBA(0,0,0)
	draw_needle((date.minute / 60) * math.pi*2, radius * 0.8, radius * 0.05)

	# draw second needle
	pic.SetFillColorRGBA(255/255, 25/255, 0)
	draw_needle((date.second / 60) * math.pi*2, radius * 0.9, radius * 0.015)

# get keyboard device
keyboard = hg.GetInputSystem().GetDevice("keyboard")

# continue while the window is open
while hg.IsWindowOpen(win) and (not keyboard.WasPressed(hg.KeyEscape)):
	ok,width,height = hg.GetWindowClientSize(win)
	renderer.SetViewport(hg.Rect(0, 0, width, height))

	# set perspective matrix
	persp_mat = hg.ComputePerspectiveProjectionMatrix(0.1, 100, 3.2, renderer.GetAspectRatio())
	renderer.SetProjectionMatrix(persp_mat)

	# clear the viewport with green color
	renderer.Clear(hg.Color(0.05, 0.05, 0.05, 0))

	# blit the picture with the clock in a texture
	draw_clock()
    # The VR renderer don't render the frame from the camera matrix, but instead add the offset between the helmet matrix and the calibration position to the camera matrix
    # in real
    #      # headset position
    #     /
    #    /
    #   /
    #  # calibration center   (which is the position of the camera)

    # In the scene:     camera mat = calibration center
    # for the rendering: rendering camera = camera mat + headset mat

    # update the position of the controllers
    for i in range(2):
        # get the controller from the input system
        try:
            controller = hg.GetInputSystem().GetDevice(
                "VR Controller {0}".format(i))
        except:
            controller = None
        try:
            # make sure we have a controller and the nodes
            if controller is not None and controller_nodes[i].GetTransform(
            ) is not None and sphere_touch_nodes[i].GetTransform() is not None:
                # compute the world matrix of the controller from the position of the camera and the position of the controller in real
                cam_matrix = scn.GetCurrentCamera().GetTransform().GetWorld()
                controller_mat = controller.GetMatrix(hg.InputDeviceMatrixHead)
                virtual_controller_mat = cam_matrix * controller_mat
                controller_nodes[i].GetTransform().SetWorld(
                    virtual_controller_mat)

                # get tactile surface values
                x_val = controller.GetValue(hg.InputButton0)
Пример #6
0
# How to read values from a game controller

import harfang as hg

hg.LoadPlugins()

plus = hg.GetPlus()
plus.RenderInit(400, 300)

device = hg.GetInputSystem().GetDevice("xinput.port0")

# continue while the window is open
while not plus.IsAppEnded():
    # check if left button is down
    for i in range(hg.Button0, hg.ButtonLast):
        if device.WasButtonPressed(i):
            print("%d was pressed" % i)

    plus.Flip()
    plus.EndFrame()

plus.RenderUninit()
Пример #7
0
def game():
	plus = hg.GetPlus()
	plus.RenderInit(screen_width, screen_height)
	al = hg.CreateMixer()
	al.Open()
	hg.MountFileDriver(hg.StdFileDriver())
	keyboard = hg.GetInputSystem().GetDevice("keyboard")

	scn, ground = setup_game_level(plus)
	turret, cannon, turret_mass = create_turret(plus, scn)

	game_state = "GAME_INIT"

	while not plus.IsAppEnded():
		dt = plus.UpdateClock()

		# Initialize Game
		if game_state == "GAME_INIT":
			enemy_list = []
			debris_list = []
			spawn_timer = 0.0
			turret_cool_down = 0.0
			enemy_spawn_interval = max_enemy_spawn_interval
			player_life = max_player_life
			target_angle = 0.0
			score = 0
			play_sound_fx(al, 'game_start')
			game_state = "TITLE"

		# Title screen
		if game_state == "TITLE":
			display_title_screen(plus, scn)
			if plus.KeyReleased(hg.KeySpace):
				game_state = "GAME"
		# Game
		elif game_state == "GAME":
			# Turret
			if plus.KeyDown(hg.KeyRight):
				target_angle += hg.time_to_sec_f(dt) * aim_rotation_speed
			else:
				if plus.KeyDown(hg.KeyLeft):
					target_angle -= hg.time_to_sec_f(dt) * aim_rotation_speed

			if plus.KeyPress(hg.KeySpace):
				if turret_cool_down < 0.0:
					throw_bullet(plus, scn, cannon.GetTransform().GetWorld().GetTranslation(), cannon.GetTransform().GetWorld().GetRow(1))
					turret_cool_down = turret_cool_down_duration
					play_sound_fx(al, 'shoot')
				else:
					play_sound_fx(al, 'error')
					turret_cool_down += 10.0 * hg.time_to_sec_f(dt)

			turret_cool_down -= hg.time_to_sec_f(dt)

			target_angle = max(min(target_angle, aim_angle_range['max']), aim_angle_range['min'])

			rotate_turret(turret, target_angle, turret_mass)

			# Enemies
			spawn_timer += hg.time_to_sec_f(dt)
			if spawn_timer > enemy_spawn_interval:
				spawn_timer = 0
				spawn_pos = hg.Vector3(uniform(-10, 10), 2.5, uniform(5.5, 6.5))
				spawn_pos.Normalize()
				spawn_pos *= 10.0
				spawn_pos.y = 5.0
				new_enemy = spawn_enemy(plus, scn, spawn_pos)
				enemy_list.append([new_enemy[0], new_enemy[1]])

			for enemy in enemy_list:
				# make enemy crawl toward the player
				enemy_dir = turret[0].GetTransform().GetPosition() - enemy[0].GetTransform().GetPosition()
				enemy_dir.Normalize()
				enemy[1].SetIsSleeping(False)
				enemy[1].ApplyLinearForce(enemy_dir * 0.25 * enemy_mass)

				col_pairs = scn.GetPhysicSystem().GetCollisionPairs(enemy[0])
				for col_pair in col_pairs:
					if 'turret' in [col_pair.GetNodeA().GetName(), col_pair.GetNodeB().GetName()]:
						destroy_enemy(plus, scn, enemy[0])
						debris_list.extend(create_explosion(plus, scn, enemy[0].GetTransform().GetPosition()))
						enemy_list.remove(enemy)
						play_sound_fx(al, 'explosion')
						play_sound_fx(al, 'hit')
						player_life -= 1
						turret_cool_down = 0.0
						if player_life < 1:
							play_sound_fx(al, 'game_over')
							game_state = "GAME_OVER"
					else:
						if 'bullet' in [col_pair.GetNodeA().GetName(), col_pair.GetNodeB().GetName()]:
							play_sound_fx(al, 'explosion')
							pos = col_pair.GetNodeB().GetTransform().GetPosition()
							debris_list.extend(create_explosion(plus, scn, pos, 8, 0.25))

							pos = enemy[0].GetTransform().GetPosition()
							destroy_enemy(plus, scn, enemy[0])
							enemy_list.remove(enemy)
							scn.RemoveNode(col_pair.GetNodeB())
							debris_list.extend(create_explosion(plus, scn, pos))

							score += 10

				# Game difficulty
				enemy_spawn_interval = max(1.0, enemy_spawn_interval - hg.time_to_sec_f(dt) * 0.025)

				# Cleanup debris
				if len(debris_list) > max_debris:
					tmp_debris = debris_list[0]
					debris_list.remove(debris_list[0])
					tmp_debris.RemoveComponent(tmp_debris.GetRigidBody())
					# scn.RemoveNode(tmp_debris)

			render_aim_cursor(plus, scn, target_angle)
			display_hud(plus, player_life / max_player_life, max(0, turret_cool_down) / turret_cool_down_duration, score)

		# Game over screen
		elif game_state == "GAME_OVER":
			display_game_over(plus, scn, score)
			if plus.KeyReleased(hg.KeySpace):
				game_state = "SCENE_RESET"

		# Reset the playfield for a new game
		elif game_state == "SCENE_RESET":
			for enemy in enemy_list:
				destroy_enemy(plus, scn, enemy[0])

			for debris in debris_list:
				debris.RemoveComponent(debris.GetRigidBody())

			game_state = "GAME_INIT"

		plus.UpdateScene(scn, dt)
		plus.Flip()
		plus.EndFrame()

	return plus
Пример #8
0
def update_camera_teleporter(plus, scn, scene_simple_graphic, world, use_vr,
                             controller):
    global flag_rotate
    pos_start = None
    dir_teleporter = None
    teleporter_activate = False
    rotation = 0
    authorise_movement = False

    if use_vr and controller is not None:

        # --Rotation:
        value = controller.GetValue(hg.InputButton4)
        if abs(value) > 0.5:
            if not flag_rotate:
                if value < 0:
                    rotation = -math.radians(rotation_step)
                else:
                    rotation = math.radians(rotation_step)
                flag_rotate = True
        elif flag_rotate:
            flag_rotate = False

        # -- Translation:
        if controller.GetValue(hg.InputButton0) != 0 or controller.GetValue(
                hg.InputButton1) != 0:
            mat_controller = world * controller.GetMatrix(
                hg.InputDeviceMatrixHead)
            dir_teleporter = mat_controller.GetZ()
            pos_start = mat_controller.GetTranslation()

            teleporter_activate = controller.WasButtonPressed(hg.Button0)
    else:
        if plus.KeyDown(hg.KeyX) or plus.KeyDown(hg.KeyC):
            pos_start = world.GetTranslation()
            dir_teleporter = world.GetZ()
            if plus.KeyPress(hg.KeyC):
                teleporter_activate = True

    if pos_start is not None:
        if pos_start.y < 0:
            return None, rotation

        # -- project point on the ground
        cos_angle = hg.Dot(
            dir_teleporter,
            hg.Vector3(dir_teleporter.x, 0, dir_teleporter.z).Normalized())
        cos_angle = min(1.0, max(cos_angle, -1))
        angle = math.acos(cos_angle)
        if dir_teleporter.y < 0:
            angle = -angle

            velocity = 5
            d = ((velocity * cos_angle) /
                 9.81) * (velocity * math.sin(angle) + math.sqrt(
                     (velocity * math.sin(angle))**2 + 2 * 9.81 * pos_start.y))

        else:
            velocity = 5.0
            min_d = (
                (velocity * 1) / 9.81) * (velocity * math.sin(0) + math.sqrt(
                    (velocity * math.sin(0))**2 + 2 * 9.81 * pos_start.y))
            max_d = 30
            d = min_d + (1.0 - abs(cos_angle)) * max_d

        # -- find the height from pos
        ground_pos = hg.Vector3(pos_start.x, 0, pos_start.z) + hg.Vector3(
            dir_teleporter.x, 0, dir_teleporter.z).Normalized() * d

        hit, trace = scn.GetPhysicSystem().Raycast(
            ground_pos + hg.Vector3(0, pos_start.y + 0.5, 0),
            hg.Vector3(0, -1, 0), 4, 5)
        ground_pos.y = 0
        if hit:
            ground_pos.y = trace.GetPosition().y
            color = hg.Color.Green
            authorise_movement = True

            if authorise_ground_node is not None:
                dist = (ground_pos - pos_start).Len()
                f = min(1, dist / 5)
                dir0 = dir_teleporter * f
                n0 = trace.GetNormal() * f

                p1 = pos_start
                p2 = pos_start + dir0
                p3 = ground_pos + n0
                p4 = ground_pos
                #scene_simple_graphic.Line(p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, hg.Color.Red, hg.Color.Red)
                #scene_simple_graphic.Line(p2.x, p2.y, p2.z, p3.x, p3.y, p3.z, hg.Color.Red, hg.Color.Red)
                #scene_simple_graphic.Line(p3.x, p3.y, p3.z, p4.x, p4.y, p4.z, hg.Color.Red, hg.Color.Red)

                draw_curve(scene_simple_graphic, p1, p2, p3, p4, color, 50)
                draw_circle(scene_simple_graphic,
                            hg.Matrix4.TranslationMatrix(ground_pos), 1, color)

        # --Get movement:
        if authorise_movement and teleporter_activate:
            if use_vr:
                head_controller = hg.GetInputSystem().GetDevice("HMD")
                head_pos = head_controller.GetMatrix(
                    hg.InputDeviceMatrixHead).GetTranslation()
                head_pos.y = 0
                ground_pos = ground_pos - head_pos
            else:
                ground_pos += hg.Vector3(0, 1.75, 0)

            return ground_pos, rotation

    return None, rotation
Пример #9
0
plus = hg.GetPlus()
plus.RenderInit(512, 256)

if enable_vr:
	openvr_frame_renderer = hg.GetFrameRenderer("VR")
	if openvr_frame_renderer.Initialize(plus.GetRenderSystem()):
		print("!! Use VR")
	else:
		openvr_frame_renderer = None
		exit()
		print("!! No VR detected")

# mount the system file driver
hg.MountFileDriver(hg.StdFileDriver())

game_device = hg.GetInputSystem().GetDevice("xinput.port0")

scene = plus.NewScene()
cam = plus.AddCamera(scene)

plus.AddLight(scene, hg.Matrix4.TranslationMatrix(hg.Vector3(0, 20, -7)), hg.LightModelPoint)
# plus.AddSphere(scene, hg.Matrix4.TranslationMatrix(hg.Vector3(0, 0.5, -10)))
# plus.AddPhysicPlane(scene, hg.Matrix4.TranslationMatrix(hg.Vector3(0, -2, 0)))

# create a new sound mixer
mixer = hg.CreateMixer()
mixer.Open()
mixer.EnableSpatialization(True)

channel = None
# load & play a bg sound
Пример #10
0
# How to retrieve information on the system input devices

import harfang as hg

device_typename = [
    'Unknown', 'Keyboard', 'Mouse', 'Pad', 'Touch', 'HMD', 'Controller'
]

# retrieve the list of all available devices on the system
devices = hg.GetInputSystem().GetDevices()

# print it to screen
print("The following devices are available on this system:")

for device_name in devices:
    device_type = hg.GetInputSystem().GetDevice(device_name).GetType()
    print('- %s (name: "%s")' % (device_typename[device_type], device_name))
Пример #11
0
# open a new window
win = hg.NewWindow(480, 240)

# create a new output surface for the newly opened window
surface = renderer.NewOutputSurface(win)
renderer.SetOutputSurface(surface)

# work in 2d and in pixels
renderer.Set2DMatrices()

# initialize the render system, which is used to draw through the renderer
render_system = hg.RenderSystem()
render_system.Initialize(renderer)

# get keyboard device
keyboard = hg.GetInputSystem().GetDevice("keyboard")

# get the mouse device
mouse_device = hg.GetInputSystem().GetDevice("mouse")
mouse_pos = hg.Vector2(0, 0)

# continue while the window is open
while hg.IsWindowOpen(win) and (not keyboard.WasPressed(hg.KeyEscape)):
    # update input system
    hg.GetInputSystem().Update()

    # get mouse position
    mouse_pos.x = mouse_device.GetValue(hg.InputAxisX)
    mouse_pos.y = mouse_device.GetValue(hg.InputAxisY)

    # clear the viewport with green color