Beispiel #1
2
    def __init__(self, x, y, image, enemygroup, mapsprite, tileImage):
	pygame.sprite.Sprite.__init__(self)
	self.foward = Animation(image,0,4, -2)	
 	self.right = Animation(image,8,12, -2)
	self.up = Animation(image, 16, 20, -2)
	self.left = Animation(image, 24, 28, -2)
	self.downright = Animation(image, 28, 32, -2)
	self.downleft = Animation(image, 40, 44, -2)
	self.upright = Animation(image, 48, 52, -2)
	self.upleft = Animation(image, 56, 60, -2)
	self.grabImage = Animation(image, 60, 64, 1)
	self.heldPunchImage = Animation(image, 44, 48, 1)
#	self.selectImage = Animation(image, 37, 41, -2, 1)
	self.tileImage = tileImage
	self.x = x
	self.y = y
	self.list = image
	self.image = self.foward.image()	# default direction facing (right)
        self.rect = self.image.get_rect()
        self.rect.topleft = (self.x,self.y)  # update tile rect location
	self.modeStack = []
	self.modeStack.append('0')
	self.enemysprite = enemygroup
	self.z = 0
	self.mapsprite = mapsprite
 	self.selectedTile = Tile(0,0, image,0, mode=1)
	self.tilesprite = pygame.sprite.Group()
	self.tilesprite.add(self.selectedTile)
	self.dirdisX = 0
	self.dirdisY = 0
Beispiel #2
0
 def start(self):
     (startX, startY) = self.getPosition()
     (nextX, nextY) = self.getNextPosition()
     anim = Animation(self.speed, [("x", startX, nextX), ("y", startY, nextY)], IN_OUT_QUAD)
     self.addAnimation(anim)
     anim.onCompletion(self.nextSquare)
     anim.start()
Beispiel #3
0
 def __init__(self, x, y, angle, velocity, damage):
     super(RedL1BulletActor, self).__init__(x, y, 5, 5)
     self.damage = damage
     nextX = x + cos(radians(angle)) * 800 # TODO: HACKY
     nextY = y + sin(radians(angle)) * 800
     anim = Animation(velocity, [("x", x, nextX), ("y", y, nextY)], LINEAR)
     anim.onFrame(self.collisionCheck)
     self.addAnimation(anim)
     anim.start()
Beispiel #4
0
class Pooter(Enemy):
	"""Simple enemy fly class"""

	hurtDistance = 0.6
	health = 12

	def __init__(self, xy, sounds, textures):
		self.x, self.y = xy

		self.sounds = sounds

		self.frames = [textures.subsurface(i*64, 0, 64, 64) for i in range(2)]
		# self.deathFrames = [textures.subsurface(i*128 - ((i//4)*128*4), 128 * (i//4 + 1), 128, 128) for i in range(12)]

		self.anim = Animation(self.frames, 0.04)

		self.health = 2

	def die(self):
		if not self.dead:
			# self.anim = Animation(self.deathFrames, 0.24)
			self.dead = True
			self.sounds[-1].play() # Play death sound

	def render(self, surface, time, character, nodes, paths, bounds, obsticals):
		speed = 1.5/GRATIO

		ix, iy = (character.x-GRIDX)/GRATIO, (character.y-GRIDY)/GRATIO
		dx, dy = (ix-self.x), (iy-self.y)


		# X and Y ratios
		dist = sqrt(dx**2+dy**2)
		rx = dx/dist
		ry = dy/dist

		hurtDistance = 0.8

		if not self.dead:

			# Add to x and y
			self.x += speed*rx
			self.y += speed*ry

			self.checkHurt(character, time)


			frame = self.anim.render(time)
		else:
			frame = self.anim.render(time)
			if self.anim.looped:
				return False

		surface.blit(frame, (GRIDX+GRATIO*self.x-self.anim.width//2, GRIDY+GRATIO*self.y-self.anim.height//2))
		return True # Should remain in enemies list
    def loadAnimations(self):
        """Loads all animations for game given the images are already loaded"""
        flash=Animation()
        flash.addFrame(self.getImage("crono"),500)
        flash.addFrame(self.getImage("cronoflip"),500)
        self.animations["ahhh"]=flash

        leftRun = Animation()
        leftRun.addFrame(self.getImage("left1"), 200)
        leftRun.addFrame(self.getImage("left2"), 200)
        leftRun.addFrame(self.getImage("left3"), 200)
        self.animations["left"] = leftRun
Beispiel #6
0
class Fly(Enemy):
	"""Simple enemy fly class"""

	isFlying = True
	pathed = False
	health = 4
	weight = 1
	hurtDistance = 0.8

	def __init__(self, xy, sounds, textures):
		self.x, self.y = xy

		self.sounds = sounds

		# Frames and death frames
		self.frames = [textures.subsurface(i*64, 0, 64, 64) for i in range(2)]
		self.deathFrames = [textures.subsurface(i*128 - ((i//4)*128*4), 128 * (i//4 + 1), 128, 128) for i in range(12)]

		self.anim = Animation(self.frames, 0.04)

		# Speed ratio
		self.speed = 1.5/GRATIO

	def die(self):
		if not self.dead:
			self.anim = Animation(self.deathFrames, 0.24)
			self.dead = True
			self.sounds[-1].play() # Play death sound

	def render(self, surface, time, character, nodes, paths, bounds, obsticals):

		self.cx, self.cy = ix, iy = (character.x-GRIDX)/GRATIO, (character.y-GRIDY)/GRATIO
		dx, dy = (self.cx-self.x), (self.cy-self.y)

		if not self.dead:
			if not self.pathed:
				self.pathFind((ix, iy), nodes, paths)
				self.pathed = True
			self.move()

			# Check for damage
			self.checkHurt(character, time)

			frame = self.anim.render(time)
		else:
			frame = self.anim.render(time)
			if self.anim.looped:
				return False

		surface.blit(frame, (GRIDX+GRATIO*self.x-self.anim.width//2, GRIDY+GRATIO*self.y-self.anim.height//2))
		return True
Beispiel #7
0
class BaseTile(GameActor):
	""" Basically just a surface and the property material_group, which defines the
	behaviour of the Tile. There are following types:

	-solid: Just a normal, solid, unbreakable block.
	-deco: No physics, only decoration (background mostly)

	-soft_break Breakable with the soft punch, jump and fall-attack
	-hard_break: Breakable with the hard punch, jump and fall-attack
	-shot_break: Breakable throwing an enemy (after charging up)
	-fire_break: Breakable when Wario is on fire (literally)

	-ladder: A material on which Wario can climb in all directions

	-water_still: Still water
	-water_left: Water that flows to the left
	-water_right: Water that flows to the right
	-water_up: Water that flows up
	-water_down: Water that flows down
	-water_impervious: Water that is impervious (Wario can't dive in it, only swim on top of it)

	-platform_fallthrough: A platform through which can be jumped if coming from the bottom up
		Is also pervious in certain states of Wario, like the zombie-wario.

	Note: The transparency color is always (225, 0, 255), also called "magic-pink"
	"""

	def __init__(self, position, engine, material_group, tiles_list):
		super(BaseTile, self).__init__(position, engine)
		# Set material_group (only for physics, see class description)
		self.material_group = material_group
		# Create the animation-instance containing all surfaces
		self.animation = Animation(tiles_list, 10)
		self.animation.update()
		# Create owm rect
		self.rect = pygame.Rect((0, 0), tiles_list[0].get_size())

	def set_property(self, property_name, property_value):
		if property_name == "material_group":
			self.material_group = property_value
		elif property_name == "alpha":
			for sprite in self.animation.sprites:
				sprite.set_alpha(0)

	def get_material_group(self):
		return self.material_group

	def _update(self):
		self.engine.graphics.blit(self.animation.get_surface(), self.rect)
Beispiel #8
0
	def __init__(self, x, y, color = (255, 255, 255), objectList = [], spriteList = []):
		self.objectList = objectList
		self.spriteList = spriteList

		self.rect = pygame.Rect(x, y, 15, 15)
		self.screen = pygame.display.get_surface()

		self.butterflyAnim = Animation("butterfly", 8)
		self.butterflyAnim.updateColor(color)
		self.butterflyAnim.setFrameRange(1, 8);
		self.butterflyAnim.setCurrentFrame(randint(1, 8))

		self.sprite = pygame.sprite.RenderPlain(self.butterflyAnim)

		self.butterflyAnim.playAnim()

		self.area = self.screen.get_rect()
		self.color = color

		self.floorLevel = self.screen.get_height() - self.rect.h

		self.movingLeft = False
		self.movingRight = False
		self.movingUp = False
		self.movingDown = False

		self.degree = randint(0, 360)
		self.speed = 4

		self.detlaUpdate = 0

		self.collide = False

		self.movePos = [0,0.01]
Beispiel #9
0
 def getAnimation(self, action):
     global animations
     try:
         return animations[action]
     except:
         animations = Animation.loadAnimations("human")
         return animations[action]
Beispiel #10
0
class Coin(Item):
	"""Pickup coin class"""

	def __init__(self, variant, xy, sounds, textures):
		self.variant = variant
		self.x = xy[0]
		self.y = xy[1]
		self.sounds = sounds
		self.textures = textures[variant]
		self.worth = [1, 5, 10][variant]

		self.bounds = Rect(GRIDX+GRATIO*self.x,GRIDY+GRATIO*self.y, 52, 52)

		self.collideable = False
		self.pickedUp = False

		# Split up textures
		self.frames = [self.textures.subsurface(i*128, 0, 128, 128) for i in range(6)]
		self.frames = [self.frames[0].copy() for i in range(16)] + self.frames
		self.anim = Animation(self.frames, 1)

	def pickup(self):
		self.pickedUp = True
		self.sounds[1].play()

	def render(self, surface, time, objects, ox=0, oy=0):
		if not self.pickedUp:
			surface.blit(self.anim.render(time), (GRIDX+GRATIO*self.x+GRATIO//2-self.anim.width//2+ox,GRIDY+GRATIO*self.y+GRATIO//2-self.anim.height//2+oy))
		return not self.pickedUp
Beispiel #11
0
	def __init__(self, xy, sounds, textures):
		self.x, self.y = xy
		self.sounds = sounds

		# Split textures
		self.frames = [textures["enemies"]["boil"].subsurface(i*64-(i//4)*(64*4), (i//4)*64, 64, 64) for i in range(10)][::-1]

		# Record sound and textures for tears
		self.tearTextures = textures["tears"]
		self.tearSounds = sounds["tear"]

		# How long it takes to grow + current size
		self.size = 0
		self.advanceTime = 0.5

		# When the animation was started
		self.start = cTime()

		# Animation for grow
		self.animation = Animation(self.frames, 10, shouldLoop=False)

		# How long the boil has been full
		self.sinceFull = -1

		# How many tears the boil has active
		self.tears = []
Beispiel #12
0
	def __init__(self, direction, posX, posY, objectList = [], rabbitList = []):
		self.objectList = objectList
		self.rabbitList = rabbitList

		self.carrotAnim = Animation("carrot", 24)
		self.carrotAnim.setFrameRange(1, 12);

		self.rect = pygame.Rect(posX, posY, 25, 25)
		self.carrotAnim.setRect(self.rect)

		self.carrotAnim.playAnim()

		self.sprite = pygame.sprite.RenderPlain(self.carrotAnim)

		self.screen = pygame.display.get_surface()
		self.area = self.screen.get_rect()
		self.area.h += 500
		self.area.y -= 550
		self.area.w -= 200

		self.smoked = False
		self.countDown = 60

		self.moveX = posX

		self.direction = direction

		if self.direction == "left":
			self.carrotAnim.flipAnim()
Beispiel #13
0
	def __init__(self, position, engine, material_group, tiles_list):
		super(BaseTile, self).__init__(position, engine)
		# Set material_group (only for physics, see class description)
		self.material_group = material_group
		# Create the animation-instance containing all surfaces
		self.animation = Animation(tiles_list, 10)
		self.animation.update()
		# Create owm rect
		self.rect = pygame.Rect((0, 0), tiles_list[0].get_size())
Beispiel #14
0
 def __init__(self, hp):
     super(RedEasyEnemyActor, self).__init__(hp)
     
     self.baseColor = [1.0, 0.0, 0.0]
     
     anim = Animation(5000, [("rotation", 0, 360)], LINEAR)
     anim.loop = True
     self.addAnimation(anim)
     anim.start()
     
     anim = Animation(250, [("scale", .8, 1.2)], IN_OUT_QUAD)
     anim.loop = True
     anim.pingPong = True
     self.addAnimation(anim)
     anim.start()
Beispiel #15
0
    def __init__(self, x, y, player, image):
        self.x = x
        self.y = y
        pygame.sprite.Sprite.__init__(self)

        # self.imglist = Animation(image,0,5)
        # 	self.heldImage = Animation(image,35, 39, -2)
        self.imagelist = image
        self.image = image[3]
        self.dx, self.dy = 0, 0
        self.movex, self.movey = 0, 0
        self.rect = self.image.get_rect()
        self.rect.topleft = (self.x, self.y)
        self.player = player
        self.modeStack = []

        self.modeStack.append("0")
        self.heldImage = Animation(image, 48, 52, -1)
        self.punchedImage = Animation(image, 40, 44, 1)
Beispiel #16
0
	def __init__(self, xy, sounds, textures):
		self.x, self.y = xy

		self.sounds = sounds

		self.frames = [textures.subsurface(i*64, 0, 64, 64) for i in range(2)]
		# self.deathFrames = [textures.subsurface(i*128 - ((i//4)*128*4), 128 * (i//4 + 1), 128, 128) for i in range(12)]

		self.anim = Animation(self.frames, 0.04)

		self.health = 2
Beispiel #17
0
	def __init__(self, variant, xy, sound, textures):
		self.variant = variant
		self.x = xy[0]
		self.y = xy[1]
		self.sound = sound
		self.textures = textures[variant]

		self.frames = [self.textures.subsurface(192*i - (i//4)*768,192*(i//4), 192, 192) for i in range(12)]

		self.anim = Animation(self.frames, .45)
		sound.play() # Play explosion sound
Beispiel #18
0
	def smoke(self):
		self.smoked = True
		self.rect.x -= 25
		self.rect.y -= 25
		self.rect.w = 75
		self.rect.h = 75
		self.carrotAnim = Animation("carrot_smoke", 25)
		self.carrotAnim.setFrameRange(1, 25);
		self.carrotAnim.setRect(self.rect)
		self.sprite = pygame.sprite.RenderPlain(self.carrotAnim)
		self.carrotAnim.playAnim(False)
Beispiel #19
0
	def __init__(self, xy, sounds, textures):
		self.x, self.y = xy

		self.sounds = sounds

		# Frames and death frames
		self.frames = [textures.subsurface(i*64, 0, 64, 64) for i in range(2)]
		self.deathFrames = [textures.subsurface(i*128 - ((i//4)*128*4), 128 * (i//4 + 1), 128, 128) for i in range(12)]

		self.anim = Animation(self.frames, 0.04)

		# Speed ratio
		self.speed = 1.5/GRATIO
Beispiel #20
0
	def __init__(self, variant, xy, sounds, textures):
		self.variant = variant
		self.x = xy[0]
		self.y = xy[1]
		self.sounds = sounds
		self.textures = textures

		# Random base
		self.randVar = randint(0,2)

		self.collideable = False

		self.destroyed = False
		self.bounds = Rect(GRIDX+GRATIO*self.x-16-4, GRIDY+GRATIO*self.y-16-5, 64+4, 64)

		self.health = 4

		# Get frames for flame
		self.fireFrames = [self.textures[0].subsurface(Rect(96*i, 0, 96, 104)) for i in range(6)]

		xMod = 0
		yMod = 0

		if self.randVar == 1:
			xMod = 64*2
		elif self.randVar == 2:
			yMod = 64*2

		# Wood animation frames
		self.woodFrames = [self.textures[1].subsurface(Rect((64*i - (i//2)*128)+xMod, (i//2)*64+yMod, 64, 64)) for i in range(4)]

		self.fire = Animation(self.fireFrames, .4)
		self.wood = Animation(self.woodFrames, .4)

		# Define dead wood and fire frames
		self.deadWood = self.woodFrames[1]
		self.deadFire = Surface((0,0))
Beispiel #21
0
	def __init__(self, variant, xy, sounds, textures):
		self.variant = variant
		self.x = xy[0]
		self.y = xy[1]
		self.sounds = sounds
		self.textures = textures[variant]
		self.worth = [1, 5, 10][variant]

		self.bounds = Rect(GRIDX+GRATIO*self.x,GRIDY+GRATIO*self.y, 52, 52)

		self.collideable = False
		self.pickedUp = False

		# Split up textures
		self.frames = [self.textures.subsurface(i*128, 0, 128, 128) for i in range(6)]
		self.frames = [self.frames[0].copy() for i in range(16)] + self.frames
		self.anim = Animation(self.frames, 1)
Beispiel #22
0
	def __init__(self, xyv, xy, ixy, speed, damage, shotRange, friendly, textures, sounds):	
		self.xVel, self.yVel = xyv # X, Y velocity
		
		# Stats
		self.speed = int(speed*2)+4
		self.damage = damage+3
		self.friendly = friendly
		self.range = (shotRange*20)+200
		self.distance = 0

		# sounds
		self.sounds = sounds

		self.x = xy[0]
		self.y = xy[1]

		# Inherited x and y velocity
		self.iXVel = ixy[0]
		self.iYVel = ixy[1]

		self.poped = False

		self.frames = [textures[1].subsurface(Rect((i*128 - ((i)//4)*128*4), ((i//4)*128), 128, 128)) for i in range(12)]
		self.popping = Animation(self.frames, 0.24)

		self.ox = self.x
		self.oy = self.y

		offX = 0
		offY = 0

		if damage > 7:
			offX = -7
			offY = 1

		if not friendly:
			offY += 2

		# Play random shoot sound
		sounds[randint(0,1)].play()

		# Texture setup
		self.texture = textures[0].subsurface(Rect((self.damage+offX)*64, offY*64, 64, 64))
		self.width = self.texture.get_width()
		self.height = self.texture.get_height()
Beispiel #23
0
    def __init__(self, x, y, image, id, mode=None):
	self.x = x
	self.y = y
        pygame.sprite.Sprite.__init__(self)
	self.id = id


	if mode == 1:
		self.animation = Animation(image, 32, 39, -2)
		self.image = self.animation.image()
		self.rect = self.image
		self.mode = 1
		print mode
	else:  
       		self.image = image
        	self.rect = self.image.get_rect()
		self.mode = 0

	self.dx, self.dy = 0, 0
        self.rect = self.image.get_rect()
        self.rect.topleft = (self.x,self.y)
Beispiel #24
0
    def __init__(self):
        super(GLTD, self).__init__()
        
        self.totalEnemies = 1
        
        self.window = Window()
        self.window.addActor(GridActor(0, 0, 600, 600))
        self.window.board = BoardActor(0, 0, 600, 600)
        self.window.addActor(self.window.board)
        
        self.window.addActor(masterParticleClock) # TODO: unmessify. IMPORTANT
        
        #anim = Animation(20, [], LINEAR)
        #self.px = 10.0
        #self.py = 10
        #anim.onCompletion(self.createNewParticles)
        #anim.loop = True
        #self.window.addAnimation(anim)
        #anim.start()

        anim = Animation(1864, [], LINEAR)
        anim.onCompletion(self.createNewEnemy)
        anim.loop = True
        self.window.addAnimation(anim)
        anim.start()
        
        #tower = RedL1TowerActor(4,7)
        #self.window.addTower(tower)
        #tower.start()
        #
        #tower = RedL1TowerActor(10,5)
        #tower.range = 150
        #tower.reloadSpeed = 300
        #tower.damage = 1000
        #tower.shake = 2
        #self.window.addTower(tower)
        #tower.start()
        
        towerChooser = TowerChooser(600, 300, 200, 300)
        self.window.addActor(towerChooser)
        
        tower = RedL1TowerActor(0, 0)
        tower.active = False
        tower.x = tower.y = 40.0
        towerChooser.addActor(tower)

        glutMainLoop()
Beispiel #25
0
class Explosion:
	"""Bomb explosion class"""

	def __init__(self, variant, xy, sound, textures):
		self.variant = variant
		self.x = xy[0]
		self.y = xy[1]
		self.sound = sound
		self.textures = textures[variant]

		self.frames = [self.textures.subsurface(192*i - (i//4)*768,192*(i//4), 192, 192) for i in range(12)]

		self.anim = Animation(self.frames, .45)
		sound.play() # Play explosion sound

	def render(self, surface, time, ox=0, oy=0):
		# Get frame and blit to screen
		frame = self.anim.render(time)
		if self.anim.looped:
			return False
		surface.blit(frame, ((GRIDX + GRATIO*self.x) - self.anim.width//2 + ox, (GRIDY + GRATIO*self.y) - self.anim.height//2 - 50 + oy))
		return True
Beispiel #26
0
	def __init__(self, textures, sounds):
		self.texture = textures["bosses"]["duke"].subsurface(0, 128, 160, 128)
		self.sounds = sounds
		self.textures = textures

		self.frames = [
			textures["bosses"]["duke"].subsurface(160, 128, 160, 128),
			textures["bosses"]["duke"].subsurface(160, 0, 160, 128),
			textures["bosses"]["duke"].subsurface(0, 0, 160, 128)
		]

		self.tearTextures = textures["tears"]
		self.tearSounds = sounds["tear"]

		self.animation = Animation(self.frames, 0.5)

		self.textures = textures

		self.lastShot = -1

		self.flies = []
		self.animating = False
Beispiel #27
0
    def setup(self, x=None, y=None):

        #sprite list:
        self.player_list = arcade.SpriteList()
        self.wall_list = arcade.SpriteList()
        self.background_list = arcade.SpriteList()

        #player setup:
        self.player = Animation.PlayerCharacter()

        #setup map:
        map_name = f"maps/{self.map}.tmx"
        platforms_layer_name = 'walls'
        my_map = arcade.tilemap.read_tmx(map_name)

        # Only create the dialogue event list on the first load, reference list on successive map changes
        if self.first_load_of_game:
            # Set up Event Class
            # (Don't recreate Event class on new map load)
            self.event = Event.Event()
            self.event.dialogue_events_overworld = arcade.tilemap.process_layer(
                arcade.tilemap.read_tmx("maps/overworld.tmx"),
                "Dialogue_Events", TILE_SCALING)
            self.event.dialogue_events_dollarstore = arcade.tilemap.process_layer(
                arcade.tilemap.read_tmx("maps/DollarStore.tmx"),
                "Dialogue_Events", TILE_SCALING)
            self.event.dialogue_events_malmart = arcade.tilemap.process_layer(
                arcade.tilemap.read_tmx("maps/MalMart.tmx"), "Dialogue_Events",
                TILE_SCALING)
            self.event.dialogue_events_school = arcade.tilemap.process_layer(
                arcade.tilemap.read_tmx("maps/TheSchool.tmx"),
                "Dialogue_Events", TILE_SCALING)
            self.first_load_of_game = False

            # Only set-up encounters constructor/set-up on initial game load:
            self.encounter = Encounter.Encounter()
            self.encounter.setup(self.view_bottom, self.view_left)

        # Always display finished events
        self.finished_event = arcade.tilemap.process_layer(
            arcade.tilemap.read_tmx(map_name), "Finished_Event", TILE_SCALING)

        if self.map == "overworld":
            self.building_list = arcade.SpriteList()
            self.rand_range = 600
            if x and y:
                self.player.center_x = x
                self.player.center_y = y
            else:
                self.player.center_x = 512
                self.player.center_y = 5000
            # Use the event list for the overworld
            self.dialogue_events_list = self.event.dialogue_events_overworld
            self.building_list = arcade.tilemap.process_layer(
                my_map, "buildings", TILE_SCALING)
            arcade.set_background_color(arcade.csscolor.BURLYWOOD)
        else:
            # Use event list for Dollar Store
            if self.map == "DollarStore":
                self.dialogue_events_list = self.event.dialogue_events_dollarstore
            # Use event list for MalMart
            elif self.map == "MalMart":
                self.dialogue_events_list = self.event.dialogue_events_malmart
            # Use event list for School
            elif self.map == "TheSchool":
                self.dialogue_events_list = self.event.dialogue_events_school

            self.rand_range = 300
            self.door_list = arcade.SpriteList()
            self.player.center_x = 256
            self.player.center_y = 2960
            self.door_list = arcade.tilemap.process_layer(
                my_map, "doors", TILE_SCALING)
            arcade.set_background_color(arcade.csscolor.WHITE)

        self.player_list.append(self.player)

        # Set up overlay class
        self.overlay = Overlay.Overlay()
        self.overlay.load_media()

        #Set up Inventory Class
        self.inventory = Inventory.Inventory()

        #set up walls
        self.wall_list = arcade.tilemap.process_layer(
            map_object=my_map,
            layer_name=platforms_layer_name,
            scaling=TILE_SCALING)
        #set up background objects:
        self.background_list = arcade.tilemap.process_layer(
            my_map, "Background", TILE_SCALING)
        #setup background:
        if my_map.background_color:
            arcade.set_background_color(my_map.background_color)

        self.physics_engine = arcade.PhysicsEngineSimple(
            self.player, self.wall_list)
        self.view_bottom = 0
        self.view_left = 0
Beispiel #28
0
def process_data(anim, phase, gait, injuries, type='flat'):
    """ Do FK """
    global_xforms = Animation.transforms_global(anim)
    global_positions = global_xforms[:, :, :3, 3] / global_xforms[:, :, 3:, 3]
    global_rotations = Quaternions.from_transforms(global_xforms)
    """ Extract Forward Direction """
    #original pfnn bvh hierarchy
    sdr_l, sdr_r, hip_l, hip_r = 18, 25, 2, 7

    #for mixamo bvh hierarchy
    #sdr_l, sdr_r, hip_l, hip_r = 10, 29, 52, 48

    across = ((global_positions[:, sdr_l] - global_positions[:, sdr_r]) +
              (global_positions[:, hip_l] - global_positions[:, hip_r]))
    across = across / np.sqrt((across**2).sum(axis=-1))[..., np.newaxis]
    """ Smooth Forward Direction """

    direction_filterwidth = 20
    forward = filters.gaussian_filter1d(np.cross(across, np.array([[0, 1,
                                                                    0]])),
                                        direction_filterwidth,
                                        axis=0,
                                        mode='nearest')
    forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]

    root_rotation = Quaternions.between(
        forward,
        np.array([[0, 0, 1]]).repeat(len(forward), axis=0))[:, np.newaxis]
    """ Local Space """

    local_positions = global_positions.copy()
    local_positions[:, :,
                    0] = local_positions[:, :, 0] - local_positions[:, 0:1, 0]
    local_positions[:, :,
                    2] = local_positions[:, :, 2] - local_positions[:, 0:1, 2]

    local_positions = root_rotation[:-1] * local_positions[:-1]
    local_velocities = root_rotation[:-1] * (global_positions[1:] -
                                             global_positions[:-1])
    local_rotations = abs((root_rotation[:-1] * global_rotations[:-1])).log()

    root_velocity = root_rotation[:-1] * (global_positions[1:, 0:1] -
                                          global_positions[:-1, 0:1])
    root_rvelocity = Pivots.from_quaternions(root_rotation[1:] *
                                             -root_rotation[:-1]).ps
    """ Foot Contacts """

    #original pfnn bvh hierarchy
    fid_l, fid_r = np.array([4, 5]), np.array([9, 10])
    #mixamo bvh
    #fid_l, fid_r = np.array([53,54]), np.array([49,50])

    velfactor = np.array([0.02, 0.02])

    feet_l_x = (global_positions[1:, fid_l, 0] -
                global_positions[:-1, fid_l, 0])**2
    feet_l_y = (global_positions[1:, fid_l, 1] -
                global_positions[:-1, fid_l, 1])**2
    feet_l_z = (global_positions[1:, fid_l, 2] -
                global_positions[:-1, fid_l, 2])**2
    feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor)).astype(np.float)

    feet_r_x = (global_positions[1:, fid_r, 0] -
                global_positions[:-1, fid_r, 0])**2
    feet_r_y = (global_positions[1:, fid_r, 1] -
                global_positions[:-1, fid_r, 1])**2
    feet_r_z = (global_positions[1:, fid_r, 2] -
                global_positions[:-1, fid_r, 2])**2
    feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor)).astype(np.float)
    """ Phase """

    dphase = phase[1:] - phase[:-1]
    dphase[dphase < 0] = (1.0 - phase[:-1] + phase[1:])[dphase < 0]
    """ Adjust Crouching Gait Value """

    if type == 'flat':
        crouch_low, crouch_high = 80, 130
        head = 16
        gait[:-1, 3] = 1 - np.clip(
            (global_positions[:-1, head, 1] - 80) / (130 - 80), 0, 1)
        gait[-1, 3] = gait[-2, 3]
    """ Start Windows """
    Pc, Xc, Yc = [], [], []

    for i in range(window, len(anim) - window - 1, 1):

        rootposs = root_rotation[i:i + 1, 0] * (
            global_positions[i - window:i + window:10, 0] -
            global_positions[i:i + 1, 0])
        rootdirs = root_rotation[i:i + 1,
                                 0] * forward[i - window:i + window:10]
        rootgait = gait[i - window:i + window:10]

        Pc.append(phase[i])

        Xc.append(
            np.hstack([
                rootposs[:, 0].ravel(),
                rootposs[:, 2].ravel(),  # Trajectory Pos
                rootdirs[:, 0].ravel(),
                rootdirs[:, 2].ravel(),  # Trajectory Dir
                rootgait[:, 0].ravel(),
                rootgait[:, 1].ravel(),  # Trajectory Gait
                rootgait[:, 2].ravel(),
                rootgait[:, 3].ravel(),
                rootgait[:, 4].ravel(),
                rootgait[:, 5].ravel(),
                local_positions[i - 1].ravel(),  # Joint Pos
                local_velocities[i - 1].ravel(),  # Joint Vel
                injuries[i - 1].ravel()  #Joints Link's status
            ]))

        rootposs_next = root_rotation[i + 1:i + 2, 0] * (
            global_positions[i + 1:i + window + 1:10, 0] -
            global_positions[i + 1:i + 2, 0])
        rootdirs_next = root_rotation[i + 1:i + 2,
                                      0] * forward[i + 1:i + window + 1:10]

        Yc.append(
            np.hstack([
                root_velocity[i, 0, 0].ravel(),  # Root Vel X
                root_velocity[i, 0, 2].ravel(),  # Root Vel Y
                root_rvelocity[i].ravel(),  # Root Rot Vel
                dphase[i],  # Change in Phase
                np.concatenate([feet_l[i], feet_r[i]], axis=-1),  # Contacts
                rootposs_next[:, 0].ravel(),
                rootposs_next[:, 2].ravel(),  # Next Trajectory Pos
                rootdirs_next[:, 0].ravel(),
                rootdirs_next[:, 2].ravel(),  # Next Trajectory Dir
                local_positions[i].ravel(),  # Joint Pos
                local_velocities[i].ravel(),  # Joint Vel
                local_rotations[i].ravel()  # Joint Rot
            ]))

    return np.array(Pc), np.array(Xc), np.array(Yc)
Beispiel #29
0
def fix_foot_contact(input_file, foot_file, output_file, ref_height):
    anim, name, ftime = BVH.load(input_file)

    fid = get_ee_id_by_names(name)
    contact = get_foot_contact(foot_file, ref_height)

    glb = Animation.positions_global(anim)  # [T, J, 3]

    T = glb.shape[0]

    for i, fidx in enumerate(fid):  # fidx: index of the foot joint
        fixed = contact[:, i]  # [T]
        s = 0
        while s < T:
            while s < T and fixed[s] == 0:
                s += 1
            if s >= T:
                break
            t = s
            avg = glb[t, fidx].copy()
            while t + 1 < T and fixed[t + 1] == 1:
                t += 1
                avg += glb[t, fidx].copy()
            avg /= (t - s + 1)

            for j in range(s, t + 1):
                glb[j, fidx] = avg.copy()
            s = t + 1

        for s in range(T):
            if fixed[s] == 1:
                continue
            l, r = None, None
            consl, consr = False, False
            for k in range(L):
                if s - k - 1 < 0:
                    break
                if fixed[s - k - 1]:
                    l = s - k - 1
                    consl = True
                    break
            for k in range(L):
                if s + k + 1 >= T:
                    break
                if fixed[s + k + 1]:
                    r = s + k + 1
                    consr = True
                    break
            if not consl and not consr:
                continue
            if consl and consr:
                litp = lerp(alpha(1.0 * (s - l + 1) / (L + 1)), glb[s, fidx],
                            glb[l, fidx])
                ritp = lerp(alpha(1.0 * (r - s + 1) / (L + 1)), glb[s, fidx],
                            glb[r, fidx])
                itp = lerp(alpha(1.0 * (s - l + 1) / (r - l + 1)), ritp, litp)
                glb[s, fidx] = itp.copy()
                continue
            if consl:
                litp = lerp(alpha(1.0 * (s - l + 1) / (L + 1)), glb[s, fidx],
                            glb[l, fidx])
                glb[s, fidx] = litp.copy()
                continue
            if consr:
                ritp = lerp(alpha(1.0 * (r - s + 1) / (L + 1)), glb[s, fidx],
                            glb[r, fidx])
                glb[s, fidx] = ritp.copy()

    # glb is ready

    anim = anim.copy()

    rot = torch.tensor(anim.rotations.qs, dtype=torch.float)
    pos = torch.tensor(anim.positions[:, 0, :], dtype=torch.float)
    offset = torch.tensor(anim.offsets, dtype=torch.float)

    glb = torch.tensor(glb, dtype=torch.float)

    ik_solver = InverseKinematics(rot, pos, offset, anim.parents, glb)

    print('Fixing foot contact using IK...')
    for i in tqdm(range(50)):
        ik_solver.step()

    rotations = ik_solver.rotations.detach()
    norm = torch.norm(rotations, dim=-1, keepdim=True)
    rotations /= norm

    anim.rotations = Quaternions(rotations.numpy())
    anim.positions[:, 0, :] = ik_solver.position.detach().numpy()

    BVH.save(output_file, anim, name, ftime)
def main(gpu, prefix, mem_frac):
    is_test = True

    data_path = "./datasets/test/"
    min_steps = 120
    max_steps = 120
    (testlocal, testglobal, testoutseq, testskel, from_names, to_names,
     tgtjoints, tgtanims, inpjoints, inpanims,
     gtanims) = load_testdata(min_steps, max_steps)

    local_mean = np.load(data_path[:-5] + "mixamo_local_motion_mean.npy")
    local_std = np.load(data_path[:-5] + "mixamo_local_motion_std.npy")
    global_mean = np.load(data_path[:-5] + "mixamo_global_motion_mean.npy")
    global_std = np.load(data_path[:-5] + "mixamo_global_motion_std.npy")
    local_std[local_std == 0] = 1

    for i in xrange(len(testlocal)):
        testlocal[i] = (testlocal[i] - local_mean) / local_std
        testglobal[i] = (testglobal[i] - global_mean) / global_std
        testskel[i] = (testskel[i] - local_mean) / local_std

    num_layer = int(prefix.split("num_layer=")[1].split("_")[0])
    gru_units = int(prefix.split("gru_units=")[1].split("_")[0])
    keep_prob = 1.0

    n_joints = testskel[0].shape[-2]

    layers_units = []
    for i in range(num_layer):
        layers_units.append(gru_units)

    if is_test:
        results_dir = "./results/outputs/test/" + prefix
    else:
        results_dir = "./results/outputs/train/" + prefix
    models_dir = "./models/" + prefix

    parents = np.array([
        -1, 0, 1, 2, 3, 4, 0, 6, 7, 8, 0, 10, 11, 12, 3, 14, 15, 16, 3, 18, 19,
        20
    ])

    with tf.device("/gpu:%d" % gpu):
        gru = EncoderDecoderGRU(1,
                                None,
                                None,
                                None,
                                None,
                                n_joints,
                                layers_units,
                                max_steps,
                                local_mean,
                                local_std,
                                global_mean,
                                global_std,
                                parents,
                                keep_prob,
                                None,
                                None,
                                None,
                                is_train=False)

    local_mean = local_mean.reshape((1, 1, -1))
    local_std = local_std.reshape((1, 1, -1))

    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=mem_frac)
    with tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                          log_device_placement=False,
                                          gpu_options=gpu_options)) as sess:

        sess.run(tf.global_variables_initializer())

        if "paper_models" in models_dir:
            if "Adv" in prefix:
                best_model = "EncoderDecoderGRU.model-46000"
            elif "Cycle" in prefix:
                best_model = "EncoderDecoderGRU.model-47000"
            else:
                best_model = "EncoderDecoderGRU.model-43000"
        else:
            best_model = None  # will pick last model

        loaded, model_name = gru.load(sess, models_dir, best_model)
        if loaded:
            print("[*] Load SUCCESS")
        else:
            print("[!] Load failed...")
            return

        for i in xrange(len(testlocal)):

            print "Testing: " + str(i) + "/" + str(len(testlocal))

            mask_batch = np.zeros((1, max_steps), dtype="float32")
            localA_batch = testlocal[i][:max_steps].reshape([1, max_steps, -1])
            globalA_batch = testglobal[i][:max_steps].reshape(
                [1, max_steps, -1])
            seqA_batch = np.concatenate((localA_batch, globalA_batch), axis=-1)
            skelB_batch = testskel[i][:max_steps].reshape([1, max_steps, -1])

            step = max_steps
            mask_batch[0, :step] = 1.0

            res_path = results_dir + "/{0:05d}".format(i)
            if not os.path.exists(results_dir):
                os.makedirs(results_dir)

            outputB, quatsB = gru.predict(sess, seqA_batch, skelB_batch,
                                          mask_batch)
            outputB[:, :step, :
                    -4] = outputB[:, :step, :-4] * local_std + local_mean
            outputB[:, :step,
                    -4:] = outputB[:, :step, -4:] * global_std + global_mean
            seqA_batch[:, :step, :
                       -4] = seqA_batch[:, :step, :-4] * local_std + local_mean
            seqA_batch[:, :step,
                       -4:] = seqA_batch[:, :step,
                                         -4:] * global_std + global_mean
            gt = testoutseq[i][None, :max_steps].copy()

            tjoints = np.reshape(skelB_batch * local_std + local_mean,
                                 [max_steps, -1, 3])
            bl_tjoints = tjoints.copy()
            tgtanim, tgtnames, tgtftime = tgtanims[i]
            gtanim, gtnames, gtftime = gtanims[i]
            inpanim, inpnames, inpftime = inpanims[i]

            tmp_gt = Animation.positions_global(gtanim)
            start_rots = get_orient_start(tmp_gt, tgtjoints[i][14],
                                          tgtjoints[i][18], tgtjoints[i][6],
                                          tgtjoints[i][10])
            """Exclude angles in exclude_list as they will rotate non-existent
         children During training."""
            exclude_list = [5, 17, 21, 9, 13]
            canim_joints = []
            cquat_joints = []
            for l in xrange(len(tgtjoints[i])):
                if l not in exclude_list:
                    canim_joints.append(tgtjoints[i][l])
                    cquat_joints.append(l)

            outputB_bvh = outputB[0].copy()
            """Follow the same motion direction as the input and zero speeds
         that are zero in the input."""
            outputB_bvh[:, -4:] = outputB_bvh[:, -4:] * (
                np.sign(seqA_batch[0, :, -4:]) * np.sign(outputB[0, :, -4:]))
            outputB_bvh[:, -3][np.abs(seqA_batch[0, :, -3]) <= 1e-2] = 0.

            outputB_bvh[:, :3] = gtanim.positions[:1, 0, :].copy()
            wjs, rots = put_in_world_bvh(outputB_bvh.copy(), start_rots)
            tjoints[:, 0, :] = wjs[0, :, 0].copy()

            cpy_bvh = seqA_batch[0].copy()
            cpy_bvh[:, :3] = gtanim.positions[:1, 0, :].copy()
            bl_wjs, _ = put_in_world_bvh(cpy_bvh.copy(), start_rots)
            bl_tjoints[:, 0, :] = bl_wjs[0, :, 0].copy()

            cquat = quatsB[0][:, cquat_joints].copy()

            if "Big_Vegas" in from_names[i]:
                from_bvh = from_names[i].replace("Big_Vegas", "Vegas")
            else:
                from_bvh = from_names[i]

            if "Warrok_W_Kurniawan" in to_names[i]:
                to_bvh = to_names[i].replace("Warrok_W_Kurniawan", "Warrok")
            else:
                to_bvh = to_names[i]

            bvh_path = "./results/blender_files/" + to_bvh.split("_")[-1]
            if not os.path.exists(bvh_path):
                os.makedirs(bvh_path)

            bvh_path += "/{0:05d}".format(i)
            BVH.save(
                bvh_path + "_from=" + from_bvh + "_to=" + to_bvh + "_gt.bvh",
                gtanim, gtnames, gtftime)

            tgtanim.positions[:, tgtjoints[i]] = bl_tjoints.copy()
            tgtanim.offsets[tgtjoints[i][1:]] = bl_tjoints[0, 1:]

            BVH.save(
                bvh_path + "_from=" + from_bvh + "_to=" + to_bvh + "_cpy.bvh",
                tgtanim, tgtnames, tgtftime)
            tgtanim.positions[:, tgtjoints[i]] = tjoints
            tgtanim.offsets[tgtjoints[i][1:]] = tjoints[0, 1:]
            """World rotation of character (global rotation)"""
            cquat[:, 0:1, :] = (rots * Quaternions(cquat[:, 0:1, :])).qs
            tgtanim.rotations.qs[:, canim_joints] = cquat

            BVH.save(bvh_path + "_from=" + from_bvh + "_to=" + to_bvh + ".bvh",
                     tgtanim, tgtnames, tgtftime)
            BVH.save(
                bvh_path + "_from=" + from_bvh + "_to=" + to_bvh + "_inp.bvh",
                inpanim, inpnames, inpftime)

            np.savez(res_path + "_from=" + from_names[i] + "_to=" +
                     to_names[i] + ".npz",
                     outputA_=outputB[:, :step],
                     outputB_=outputB[:, :step],
                     quatsB=quatsB[:, :step],
                     input_=seqA_batch[:, :step],
                     gt=gt)

    print "Done."
Beispiel #31
0
def apply_results(towr_results, anim_bvh, start_idx, end_idx, character, run_ik=True):
    ''' Applies trajectory optim results back to our original skeleton. '''

    # read in og animation
    anim, names, _ = BVH.load(anim_bvh)
    anim.rotations = anim.rotations[start_idx:end_idx]
    anim.positions = anim.positions[start_idx:end_idx]

    toe_inds = get_character_toe_inds(character)
    ankle_inds = get_character_ankle_inds(character)

    # add heel to IK with towr results
    if (not character in heeled_characters) and (towr_results.feet_pos.shape[1] == 4):
        anim, _ = add_heel_to_anim(anim, toe_inds, ankle_inds)
   
    init_pos = Animation.positions_global(anim)
    upper_body_joints = get_character_upper_body(character)
    map_segment_to_joints = get_character_seg_to_joint_map(character)
    map_segment_to_mass_perc = get_character_seg_to_mass_perc_map(character)
    left_toe_idx, right_toe_idx = get_character_toe_inds(character)

    # calc COM over time and offsets of upper body joints (including root)
    # since we only need offsets, don't have to zero out position
    anim_COM = np.zeros((anim.shape[0], 3))
    upper_offsets = np.zeros((anim.shape[0], len(upper_body_joints), 3))
    for i in range(anim.shape[0]):
        cur_COM = np.zeros(3)
        for key in map_segment_to_joints.keys():
            seg_pos = np.mean(init_pos[i, map_segment_to_joints[key], :], axis=0)
            mass_frac = map_segment_to_mass_perc[key] * 0.01
            cur_COM += mass_frac * seg_pos
        anim_COM[i] = cur_COM

        for j in range(len(upper_body_joints)):
            upper_offsets[i, j] = init_pos[i, upper_body_joints[j]] - cur_COM

    anim_og = deepcopy(anim)
    com_og = anim_COM.copy()
    
    # desired global position of upper joints is based on optimized COM position
    seq_len = end_idx - start_idx
    desired_pos = upper_offsets + np.expand_dims(towr_results.base_pos[:seq_len], axis=1)*100.0

    # keep everything the same except replace
    # root information with optimized output
    anim.rotations[:,0,:] = Quaternions.from_euler(towr_results.base_rot, order='xyz', world=True)[:seq_len]
    anim.positions[:,0,:] = desired_pos[:,0,:]

    if run_ik:
        # add IK targets for upper body joints
        targetmap = {}
        for i in range(len(upper_body_joints)):
            targetmap[upper_body_joints[i]] = desired_pos[:,i,:]

        # setup IK with foot joints targetetd at feet position optimized outputs
        left_foot_target = towr_results.feet_pos[:seq_len,0,:] * 100.0 # out of meters
        right_foot_target = towr_results.feet_pos[:seq_len,1,:] * 100.0 # out of meters
        targetmap[left_toe_idx] = left_foot_target
        targetmap[right_toe_idx] = right_foot_target

        # and heels
        left_heel_idx = anim.positions.shape[1] - 2
        right_heel_idx = anim.positions.shape[1] - 1
        if character in heeled_characters:
            print('Using COMBINED character')
            # already has a heel joint
            left_heel_idx, right_heel_idx = get_character_heel_inds(character)
        if towr_results.feet_pos.shape[1] == 4:
            print('Found heel data, including it in IK')
            left_heel_target = towr_results.feet_pos[:seq_len,2,:] * 100.0
            right_heel_target = towr_results.feet_pos[:seq_len,3,:] * 100.0
            targetmap[left_heel_idx] = left_heel_target
            targetmap[right_heel_idx] = right_heel_target

        # run IK
        ik = JacobianInverseKinematicsCK(anim, targetmap, translate=True, iterations=30, smoothness=0.001, damping=7.0, silent=False)
        ik()

    return anim, names, anim_og, com_og
Beispiel #32
0
    def __call__(self, descendants=None, gamma=1.0):
        
        self.descendants = descendants
        
        """ Calculate Masses """
        if self.weights is None:
            self.weights = np.ones(self.animation.shape[1])
            
        if self.weights_translate is None:
            self.weights_translate = np.ones(self.animation.shape[1])
        
        """ Calculate Descendants """
        if self.descendants is None:
            self.descendants = AnimationStructure.descendants_mask(self.animation.parents)
        
        self.tdescendants = np.eye(self.animation.shape[1]) + self.descendants
        
        self.first_descendants = self.descendants[:,np.array(list(self.targets.keys()))].repeat(3, axis=0).astype(int)
        self.first_tdescendants = self.tdescendants[:,np.array(list(self.targets.keys()))].repeat(3, axis=0).astype(int)
        
        """ Calculate End Effectors """
        self.endeff = np.array(list(self.targets.values()))
        self.endeff = np.swapaxes(self.endeff, 0, 1) 
        
        if not self.references is None:
            self.second_descendants = self.descendants.repeat(3, axis=0).astype(int)
            self.second_tdescendants = self.tdescendants.repeat(3, axis=0).astype(int)
            self.second_targets = dict([(i, self.references[:,i]) for i in xrange(self.references.shape[1])])
        
        nf = len(self.animation)
        nj = self.animation.shape[1]
        
        if not self.silent:
            gp = Animation.positions_global(self.animation)
            gp = gp[:,np.array(list(self.targets.keys()))]            
            error = np.mean(np.sqrt(np.sum((self.endeff - gp)**2.0, axis=2)))
            print('[JacobianInverseKinematics] Start | Error: %f' % error)
        
        for i in range(self.iterations):

            """ Get Global Rotations & Positions """
            gt = Animation.transforms_global(self.animation)
            gp = gt[:,:,:,3]
            gp = gp[:,:,:3] / gp[:,:,3,np.newaxis]
            gr = Quaternions.from_transforms(gt)
            
            x = self.animation.rotations.euler().reshape(nf, -1)
            w = self.weights.repeat(3)
            
            if self.translate:
                x = np.hstack([x, self.animation.positions.reshape(nf, -1)])
                w = np.hstack([w, self.weights_translate.repeat(3)])
            
            """ Generate Jacobian """
            if self.recalculate or i == 0:
                j = self.jacobian(x, gp, gr, self.targets, self.first_descendants, self.first_tdescendants)
            
            """ Update Variables """            
            l = self.damping * (1.0 / (w + 0.001))
            d = (l*l) * np.eye(x.shape[1])
            e = gamma * (self.endeff.reshape(nf,-1) - gp[:,np.array(list(self.targets.keys()))].reshape(nf, -1))
            
            x += np.array(list(map(lambda jf, ef:
                linalg.lu_solve(linalg.lu_factor(jf.T.dot(jf) + d), jf.T.dot(ef)), j, e)))
            
            """ Generate Secondary Jacobian """
            if self.references is not None:
                
                ns = np.array(list(map(lambda jf:
                    np.eye(x.shape[1]) - linalg.solve(jf.T.dot(jf) + d, jf.T.dot(jf)), j)))
                    
                if self.recalculate or i == 0:
                    j2 = self.jacobian(x, gp, gr, self.second_targets, self.second_descendants, self.second_tdescendants)
                        
                e2 = self.secondary * (self.references.reshape(nf, -1) - gp.reshape(nf, -1))
                
                x += np.array(list(map(lambda nsf, j2f, e2f:
                    nsf.dot(linalg.lu_solve(linalg.lu_factor(j2f.T.dot(j2f) + d), j2f.T.dot(e2f))), ns, j2, e2)))

            """ Set Back Rotations / Translations """
            self.animation.rotations = Quaternions.from_euler(
                x[:,:nj*3].reshape((nf, nj, 3)), order='xyz', world=True)
                
            if self.translate:
                self.animation.positions = x[:,nj*3:].reshape((nf,nj, 3))
                
            """ Generate Error """
            
            if not self.silent:
                gp = Animation.positions_global(self.animation)
                gp = gp[:,np.array(list(self.targets.keys()))]
                error = np.mean(np.sum((self.endeff - gp)**2.0, axis=2)**0.5)
                print('[JacobianInverseKinematics] Iteration %i | Error: %f' % (i+1, error))
Beispiel #33
0
            18: 25,
            19: 26,
            20: 27,
            22: 30,
            24: 12,
            25: 17,
            26: 18,
            27: 19,
            29: 22
        }

        targetmap = {}
        #targetmap[1] = anim.positions[:,0,:]
        for k in mapping:
            #anim.rotations[:,k] = stanim.rotations[:,mapping[k]]
            targetmap[k] = normalizedPose[:, mapping[k], :]

        #ik = JacobianInverseKinematics(anim, targetmap, iterations=10, damping=10.0, silent=True)
        ik = JacobianInverseKinematics(anim,
                                       targetmap,
                                       iterations=20,
                                       damping=10.0,
                                       silent=True)
        ik()
        """Debug"""
        targets = Animation.positions_global(anim)
        targets_vis = conv_visGl_form(targets) * 5
        showSkeleton([targets_vis, original_vis])  #Debug

        #BVH.save('./h36m/'+'S'+str(subjectIdx) + '-' + os.path.split(cdf_file)[1].replace('.cdf', '.bvh'), anim, names)
Beispiel #34
0
rect1.x=50
rect1.y=200
but1=pygame.Surface((50,50))
but1.fill((0,255,0))
rect2=but.get_rect()
rect2.x=100
rect2.y=200
but2=pygame.Surface((50,50))
but2.fill((0,0,255))
rect3=but.get_rect()
rect3.x=150
rect3.y=200


animations=[]
animations.append(Animation('picture/looking.png',12))
animations.append(Animation('picture/attack.png',12))
animations.append(Animation('picture/run.png',8))
animations.append(Animation('picture/talking.png',8))
player1=Player(animations,50,50)

GAME=True
sc.blit(player1.image,player1.rect)
sc.blit(but,rect1)
sc.blit(but1,rect2)
sc.blit(but2,rect3)
pygame.display.update()
while GAME:
    for i in pygame.event.get():
        if i.type==pygame.QUIT:
            GAME=False
Beispiel #35
0
    def retarget_skeleton(self, normalizedPose):
        """
        Retargets the Panoptic Skeleton onto CMU skeleton
        :param normalizedPose: Panoptic skeleton (57, F)
        :return: retargeted animation
        """

        # reshape
        normalizedPose = np.transpose(normalizedPose)  # (frames,57)
        normalizedPose = normalizedPose.reshape(normalizedPose.shape[0], 19,
                                                3)  # (frames,19,3)

        # Flip Y axis
        normalizedPose[:, :, 1] = -normalizedPose[:, :, 1]

        # calculate panoptic height
        panopticThigh = normalizedPose[:, 6, :] - normalizedPose[:, 7, :]
        panopticThigh = panopticThigh**2
        panopticHeight = np.mean(np.sqrt(np.sum(panopticThigh, axis=1)))

        # load the rest skeleton
        rest, names, _ = BVH.load('meta/rest.bvh')  # temp

        # create a mock animation for the required duration
        anim = rest.copy()
        anim.positions = anim.positions.repeat(normalizedPose.shape[0], axis=0)
        anim.rotations.qs = anim.rotations.qs.repeat(normalizedPose.shape[0],
                                                     axis=0)

        # get the FK solved global positions
        cmuMocapJoints = Animation.positions_global(anim)

        # calculate CMU skeleton height
        cmuThigh = cmuMocapJoints[:, 2, :] - cmuMocapJoints[:, 3, :]
        cmuThigh = cmuThigh**2
        cmuMocapHeight = np.mean(np.sqrt(np.sum(cmuThigh, axis=1)))
        cmuMocapHeight = cmuMocapHeight * 0.9

        # scale the skelton appropriately
        scaleRatio = cmuMocapHeight / panopticHeight
        print("cmuMocapHeight: %f, panopticHeight %f, scaleRatio: %f " %
              (cmuMocapHeight, panopticHeight, scaleRatio))
        normalizedPose = normalizedPose * scaleRatio  # rescaling

        # compute mean across vector
        across1 = normalizedPose[:,
                                 3] - normalizedPose[:,
                                                     9]  # Right -> left (3)  Shoulder
        across0 = normalizedPose[:,
                                 6] - normalizedPose[:,
                                                     12]  # Right -> left (6) Hips
        across = across0 + across1  # frame x 3
        across = across / np.sqrt(
            (across**2).sum(axis=-1))[...,
                                      np.newaxis]  ##frame x 3. Unit vectors

        # compute forward direction
        forward = np.cross(across, np.array([[0, -1, 0]]))
        forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]
        target = np.array([[0, 0, 1]]).repeat(len(forward), axis=0)

        # Set root's movement by hipCenter joints (idx=2)
        anim.positions[:, 0] = normalizedPose[:, 2] + np.array([0.0, 2.4, 0.0])
        anim.rotations[:, 0:1] = -Quaternions.between(forward,
                                                      target)[:, np.newaxis]

        targetmap = {}
        for k in self.mapping:
            targetmap[k] = normalizedPose[:, self.mapping[k], :]

        # Retarget using JacobianIK
        ik = JacobianInverseKinematics(anim,
                                       targetmap,
                                       iterations=20,
                                       damping=10.0,
                                       silent=True)
        ik()

        # scale skeleton appropriately
        anim.positions = anim.positions * 6.25
        anim.offsets = anim.offsets * 6.25

        # Do FK recover 3D joint positions, select required Joints only
        positions = Animation.positions_global(anim)
        positions = positions[:, self.jointIdx]

        return positions
Beispiel #36
0
def main():
    init()
    global width, height, animator
    size = width, height = 1920, 1080
    screen = pygame.display.set_mode(size, FULLSCREEN)
    gameClock = time.Clock()
    animator = Animation()

    #load default background
    background = pygame.sprite.Group()
    bg1 = SpriteRemix.Background(
        transform.scale(
            image.load("Assets\\backgrounds\outsidebg.png").convert(),
            (1920, 1080)))
    bg2 = SpriteRemix.Background(
        transform.scale(
            image.load("Assets\\backgrounds\outsidebg.png").convert(),
            (1920, 1080)))
    bg1.stateVal = 1  #slowscroll
    bg2.stateVal = 1  #slowscroll
    bg1.add(background)
    bg2.add(background)

    #load ui, TODO: encapsulate this shit
    ui = pygame.sprite.Group()
    health = SpriteRemix.UI(
        transform.scale(
            image.load("Assets\\sprites\\ui\\health.png").convert(),
            (596, 72)))
    healthbar = SpriteRemix.UI(
        transform.scale(
            image.load("Assets\\sprites\\ui\\healthbar.png").convert_alpha(),
            (840, 84)))
    health.add(ui)
    healthbar.add(ui)

    #create cursor and add it to a sprite group, can only hold 1 cursor at a time
    cursors = pygame.sprite.GroupSingle()
    crsr = SpriteRemix.Cursor(
        transform.scale(
            pygame.image.load(
                "Assets\\sprites\\cursors\\crosshair1.png").convert_alpha(),
            (70, 70)))
    crsr.add(cursors)

    #create pc and add it to a sprite group
    #TODO: need an initializer class for player that loads projectiles and weapons and shit
    pc = pygame.sprite.Group()
    playerSprite = PlayerCharacterSprite()
    animator.load(playerSprite)
    playerSprite.add(pc)

    #weapon, this shit is f*****g retarded
    pcAccessory = pygame.sprite.Group()
    playerWeapon = SpriteRemix.Weapon()
    animator.load(playerWeapon)
    playerWeapon.add(pcAccessory)

    #create baddies and add them to a sprite group
    baddies = sprite.Group()
    baddySprite = EnemyCharacterSprite("notzigrunt")
    animator.load(baddySprite)
    baddySprite.add(baddies)

    #create doodads and add them to a sprite group
    doodads = sprite.Group()
    box = SpriteRemix.Doodad(
        pygame.image.load("Assets\\sprites\\doodads\\box.png").convert())
    #alsoBox = Doodad(pygame.image.load("Assets\\sprites\\doodads\\box.png").convert())
    box.add(doodads)
    #alsoBox.add(doodads)

    #initialize projectile sprite group (obv nothing to put here at startup
    projectiles = sprite.Group()

    #floating combat text
    combatTextArr = []

    #place everything
    bg1.rect.topleft = [-1920, 0]
    bg2.rect.topleft = [0, 0]

    healthbar.rect.topleft = [50, 50]
    health.rect.topleft = [healthbar.rect.left + 239, healthbar.rect.top + 5]

    playerSprite.rect.bottomleft = [100, height - 50]
    playerWeapon.rect.midright = playerSprite.rect.midleft

    baddySprite.rect.bottom = height
    baddySprite.rect.left = 960

    box.rect.left = 540
    box.rect.bottom = height
    '''alsoBox.rect.left = 920
    alsoBox.rect.bottom = height'''

    #create a list of all sprite groups
    entities = [pc.sprites(), baddies.sprites()]
    sprites = [
        pc, pcAccessory, baddies, doodads, projectiles, background, ui, cursors
    ]

    while 1:

        now = time.get_ticks()

        #this for loop processes all inputs in the event queue
        events = pygame.event.get()
        for event in events:

            #close window and quit if x is clicked or esc is pressed
            if event.type == QUIT or (event.type == KEYDOWN
                                      and event.key == K_ESCAPE):
                quit()
                sys.exit()

            #track the cursor
            if event.type == MOUSEMOTION:
                crsr.rect.centerx = event.pos[0]
                crsr.rect.centery = event.pos[1]

            #if no input is given, this remains True, animation reflects that.
            if not playerSprite.state["ducking"]:
                playerSprite.state["idle"] = True

            #only control pc if pc not dead
            #may be simplified by banning control input events when pc dies.
            if not playerSprite.state["dying"] and not playerSprite.state[
                    "dead"]:

                #movement d-right a-left space-jump
                if not playerSprite.state["ducking"]:
                    if event.type == KEYUP and event.key == K_d:
                        playerSprite.rightDash = now
                        Movement.accel(playerSprite, -playerSprite.velocity[0])
                        Movement.coast(playerSprite, playerSprite.velocity[0])
                        if playerSprite.velocity[0] == 0:
                            playerSprite.state["running"] = False
                        playerSprite.idleTime = 0
                        playerSprite.state["idle"] = False

                    elif event.type == KEYUP and event.key == K_a:
                        playerSprite.leftDash = now
                        Movement.accel(playerSprite, -playerSprite.velocity[0])
                        Movement.coast(playerSprite, playerSprite.velocity[0])
                        if playerSprite.velocity[0] == 0:
                            playerSprite.state["running"] = False
                        playerSprite.idleTime = 0
                        playerSprite.state["idle"] = False

                    elif event.type == KEYDOWN and event.key == K_d:
                        if now - playerSprite.rightDash > 250:
                            Movement.accel(playerSprite, 12)
                        else:
                            Movement.accel(playerSprite, 24)
                        playerSprite.leftDash = 0
                        playerSprite.xflip = False
                        if not playerSprite.state[
                                "jumping"] and not playerSprite.state[
                                    "falling"]:
                            playerSprite.state["running"] = True
                        playerSprite.idleTime = 0
                        playerSprite.state["idle"] = False

                    elif event.type == KEYDOWN and event.key == K_a:
                        if now - playerSprite.leftDash > 250:
                            Movement.accel(playerSprite, -12)
                        else:
                            Movement.accel(playerSprite, -24)
                        playerSprite.rightDash = 0
                        playerSprite.xflip = True
                        if not playerSprite.state[
                                "jumping"] and not playerSprite.state[
                                    "falling"]:
                            playerSprite.state["running"] = True
                        playerSprite.idleTime = 0
                        playerSprite.state["idle"] = False

                if playerSprite.velocity[0] == 0 and playerSprite.velocity[
                        1] == 0:
                    if event.type == KEYUP and event.key == K_s:
                        playerSprite.idleTime = 0
                        playerSprite.state["ducking"] = False
                        playerSprite.state["idle"] = False

                    elif event.type == KEYDOWN and event.key == K_s:
                        #crouching provides traction
                        playerSprite.xcoast = playerSprite.xcoast / 2.0
                        playerSprite.state["ducking"] = True
                        playerSprite.idleTime = 0
                        playerSprite.state["idle"] = False

                if event.type == KEYUP and event.key == K_SPACE:
                    playerSprite.velocity[1] = max(0, playerSprite.velocity[1])
                    playerSprite.state["jumping"] = False
                    playerSprite.idleTime = 0
                    playerSprite.state["idle"] = False

                if event.type == KEYDOWN and event.key == K_SPACE:
                    Movement.jump(playerSprite)
                    playerSprite.state["idle"] = False
                    playerSprite.state["jumping"] = True
                    playerSprite.idleTime = 0
                    playerSprite.state["idle"] = False

                #melee attack
                if event.type == MOUSEBUTTONDOWN and event.button == 1 and now - playerSprite.lastMelee > 300:
                    playerSprite.state["attacking"] = True
                    playerSprite.last["meleed"] = now
                    playerSprite.idleTime = 0
                    playerWeapon.hostile = True
                    playerSprite.state["idle"] = False

                if event.type == MOUSEBUTTONUP and event.button == 1:
                    playerWeapon.hostile = False
                    playerSprite.state["idle"] = False
                    playerSprite.state["attacking"] = False

                #ranged attack
                if event.type == MOUSEBUTTONDOWN and event.button == 3 and playerSprite.ammo > 0 and now - playerSprite.lastShot > 250:
                    playerSprite.ammo -= 1
                    projLoc = [
                        playerSprite.rect.right, playerSprite.rect.bottom - 130
                    ]
                    newProj = SpriteRemix.Projectile(projLoc,
                                                     event.pos,
                                                     speed=45)
                    animator.load(newProj)
                    newProj.add(projectiles)
                    newProj.rect.center = projLoc
                    playerSprite.last["shot"] = now
                    playerSprite.state["shooting"] = True
                    playerSprite.idleTime = 0
                    playerSprite.state["idle"] = False

            #ragdoll pc
            else:
                playerSprite.xcoast = playerSprite.velocity[0]
                playerSprite.ycoast = playerSprite.velocity[1]
                playerSprite.velocity = [0, 0]

        if playerSprite.state["idle"]:
            playerSprite.idleTime += gameClock.get_time()
            if playerSprite.idleTime >= 2000:
                playerSprite.state["idle"] = True
            elif playerSprite.idleTime >= 300:
                playerSprite.state["ready"] = True

        #baddy behavior
        '''if (now%1000 < 20) and baddySprite.stateVal != 1:
            Movement.jump(baddySprite)'''

        #replenish ammo over time
        if (now % 100 < 20) and playerSprite.ammo < 4:
            playerSprite.ammo += 1

        if (now % 5000 < 20):
            print(playerSprite.state)

        #sprites move, but these moves haven't been drawn yet
        for i in range(len(sprites) - 2):
            groupList = sprites[i].sprites()
            for aSprite in groupList:
                if aSprite.xcoast > 0:
                    if aSprite.xcoast > .6:
                        aSprite.xcoast += min(-aSprite.xcoast * .1, -.6)
                    else:
                        aSprite.xcoast = 0
                elif aSprite.xcoast < 0:
                    if aSprite.xcoast < -.6:
                        aSprite.xcoast += max(-aSprite.xcoast * .1, .6)
                    else:
                        aSprite.xcoast = 0
                if aSprite.ycoast > 0:
                    if aSprite.ycoast > .6:
                        aSprite.ycoast += min(-aSprite.ycoast * .1, -.6)
                    else:
                        aSprite.ycoast = 0
                elif aSprite.ycoast < 0:
                    if aSprite.ycoast < -.6:
                        aSprite.ycoast += max(-aSprite.ycoast * .1, .6)
                    else:
                        aSprite.ycoast = 0
                aSprite.rect = aSprite.rect.move([
                    aSprite.velocity[0] + aSprite.xcoast,
                    aSprite.velocity[1] + aSprite.ycoast
                ])

        # keeps characters in frame and handles collisions
        resolveFrame(sprites, entities, combatTextArr)

        # position the pc's weapon
        # TODO: encapsulate this, preferably in Animation once I figure out why it wasn't working there.
        playerWeapon.state = playerSprite.state
        if playerSprite.xflip:
            if playerWeapon.state["dead"] or playerWeapon.state["idle"]:
                playerWeapon.rect.topleft = [0, 0]
            elif playerWeapon.state["attacking"] or playerWeapon.state[
                    "shooting"]:
                playerWeapon.rect.midright = [
                    playerSprite.rect.midleft[0] + 8,
                    playerSprite.rect.midleft[1] - 62
                ]
            else:
                playerWeapon.rect.midleft = [
                    playerSprite.rect.midright[0],
                    playerSprite.rect.midright[1] + 58
                ]
            playerWeapon.xflip = True
        else:
            if playerWeapon.state["dead"] or playerWeapon.state["idle"]:
                playerWeapon.rect.topleft = [0, 0]
            elif playerWeapon.state["attacking"] or playerWeapon.state[
                    "shooting"]:
                playerWeapon.rect.midleft = [
                    playerSprite.rect.midright[0] - 8,
                    playerSprite.rect.midright[1] - 62
                ]
            else:
                playerWeapon.rect.midright = [
                    playerSprite.rect.midleft[0],
                    playerSprite.rect.midleft[1] + 58
                ]
            playerWeapon.xflip = False

        # only animate characters and projectiles so far (i = 0 is pc, i = 1 is baddies, i = 3 is projectiles, i = 4 is background)
        animator.animate([
            sprites[0].sprites(), sprites[1].sprites(), sprites[2].sprites(),
            sprites[4].sprites(), sprites[5].sprites()
        ], now)

        # refresh screen by drawing over previous frame with background
        screen.blit(bg1.image, bg1.rect)
        screen.blit(bg2.image, bg2.rect)

        # draw active CombatText objects and remove faded ones
        for combatText in combatTextArr[:]:
            if combatText.progress(now):
                combatText.draw(screen)
            else:
                combatTextArr.remove(combatText)

        # draw all the rest of the in-use assets
        for i in range(len(sprites)):
            if i != 5:  #don't draw UI
                # only draw visible sprites in each group
                # NOTE: this is probably bad, as I'd assume .draw() (sprite method that blits all sprites in a sprite group)is better
                # optimized, but we can't make it optionally draw
                # sprites unless we change everything to DirtySprites (a type built into pygame)
                for aSprite in sprites[i].sprites():
                    if aSprite.visible:
                        screen.blit(aSprite.image, aSprite.rect)

        # draw UI last
        if health.rect.width > 5.96 * playerSprite.health:
            health.image = transform.scale(
                health.image,
                (max(0, health.rect.width - 3), health.rect.height))
            health.rect = health.image.get_rect()
            health.rect.topleft = (289, 56)
        screen.blit(health.image, health.rect)
        screen.blit(healthbar.image, healthbar.rect)

        gameClock.tick(60)

        #game over check
        if playerSprite.health <= 0:
            defaultText = font.Font(None, 120)
            gameOverSurface = defaultText.render("Game Over man, Game Over!",
                                                 True, (255, 0, 0))
            gameOverRect = gameOverSurface.get_rect()
            gameOverRect.center = (960, 540)
            screen.blit(gameOverSurface, gameOverRect)
            playerSprite.state["dead"] = True

        #victory check
        enemies = sprites[2].sprites()
        allDead = True
        for enemy in enemies:
            if enemy.stateVal != 4:
                allDead = False
        if allDead:
            defaultText = font.Font(None, 200)
            conglaturationSurface = defaultText.render("Conglaturation", True,
                                                       (255, 255, 255))
            conglaturationRect = conglaturationSurface.get_rect()
            conglaturationRect.center = (960, 540)
            screen.blit(conglaturationSurface, conglaturationRect)

        pygame.display.flip()
Beispiel #37
0
class Tear:
    """Main tear class"""
    def __init__(self, xyv, xy, ixy, speed, damage, shotRange, friendly,
                 textures, sounds):
        self.xVel, self.yVel = xyv  # X, Y velocity

        # Stats
        self.speed = int(speed * 2) + 4
        self.damage = damage + 3
        self.friendly = friendly
        self.range = (shotRange * 20) + 200
        self.distance = 0

        # sounds
        self.sounds = sounds

        self.x = xy[0]
        self.y = xy[1]

        # Inherited x and y velocity
        self.iXVel = ixy[0]
        self.iYVel = ixy[1]

        self.poped = False

        self.frames = [
            textures[1].subsurface(
                Rect((i * 128 - ((i) // 4) * 128 * 4), ((i // 4) * 128), 128,
                     128)) for i in range(12)
        ]
        self.popping = Animation(self.frames, 0.24)

        self.ox = self.x
        self.oy = self.y

        offX = 0
        offY = 0

        if damage > 7:
            offX = -7
            offY = 1

        if not friendly:
            offY += 2

        # Play random shoot sound
        sounds[randint(0, 1)].play()

        # Texture setup
        self.texture = textures[0].subsurface(
            Rect((self.damage + offX) * 64, offY * 64, 64, 64))
        self.width = self.texture.get_width()
        self.height = self.texture.get_height()

    def step(self):
        self.texture = self.frames[self.frameIndex]
        self.frameIndex += 1

    def pop(self, collision):
        self.poped = True
        if collision:
            self.sounds[2].play()  # Play collison pop
        else:
            self.sounds[1].play()  # Play normal pop
        return True

    def render(self, surface, time, bounds, obsticals):
        if self.poped:
            # Return popping tear
            frame = self.popping.render(time)
            if self.popping.looped:
                return False
            surface.blit(frame, (self.x - self.popping.width // 2,
                                 self.y - self.popping.height // 2))
            return True

        if abs(self.x - self.ox) < self.range and abs(self.y -
                                                      self.oy) < self.range:
            dx = 0
            dy = 0

            dx += self.xVel * self.speed
            dy += self.yVel * self.speed

            # Add inherited X and Y velocity
            dx += self.iXVel
            dy += self.iYVel

            inBoundsX = bounds.collidepoint(self.x + dx, self.y)
            inBoundsY = bounds.collidepoint(self.x, self.y + dx)

            rockColX = False
            rockColY = False

            for ob in obsticals:
                # Collide with ob
                try:
                    if ob.destroyed:
                        continue
                except:
                    pass
                # Collude with object
                rcx = ob.bounds.collidepoint(self.x + self.speed, self.y)
                rcy = ob.bounds.collidepoint(self.x, self.y + self.speed)
                if rcx or rcy:
                    try:
                        ob.hurt(1)
                    except:
                        pass

                    if not ob.collideable:
                        rockColX = rockColY = False
                    return self.pop(True)

            if not inBoundsX or not inBoundsY:
                # Ensure tear is within level bounds
                return self.pop(True)

            # Add to x and y
            self.x += dx
            self.y += dy

            surface.blit(self.texture,
                         (self.x - self.width // 2, self.y - self.height // 2))

            return True
        return self.pop(False)
Beispiel #38
0
        continue

    m1 = re.match('(\d+_\d+)\s+([^\n]*)\n', line)
    if m1:
        id0, id1 = m1.group(1).split('_')
        database.append((id0, id1))

info.close()

baddata = set([('90', '10')])

database = [data for data in database if (data[0], data[1]) not in baddata]
""" Begin Processing """

rest, names, _ = BVH.load(dbroot + '01/01_01.bvh')
rest_targets = Animation.positions_global(rest)
rest_height = rest_targets[0, :, 1].max()

skel = rest.copy()
skel.positions = rest.positions[0:1]
skel.rotations = rest.rotations[0:1]
skel.positions[:, 0, 0] = 0
skel.positions[:, 0, 2] = 0
skel.offsets[0, 0] = 0
skel.offsets[0, 2] = 0
skel.offsets = skel.offsets * 6.25
skel.positions = skel.positions * 6.25

BVH.save('./skel_motionbuilder.bvh', skel, names)

rest.positions = rest.offsets[np.newaxis]
Beispiel #39
0
def process_file_body_speech_face(faceParamDir,
                                  filename,
                                  window=240,
                                  window_step=120):

    #########################
    ## Load Speech Data
    seqName = os.path.basename(filename)
    fileName_pkl = seqName[:-7] + '.pkl'
    speechPath = './panopticDB_pkl_speech_hagglingProcessed/' + fileName_pkl
    speechData = pickle.load(open(speechPath, "rb"))
    if '_p0.bvh' in filename:
        speechData = speechData['speechData'][0]
    elif '_p1.bvh' in filename:
        speechData = speechData['speechData'][1]
    elif '_p2.bvh' in filename:
        speechData = speechData['speechData'][2]

    #########################
    ## Load Face Data
    facePath = faceParamDir + fileName_pkl
    faceParamData = pickle.load(open(facePath, "rb"))
    if '_p0.bvh' in filename:
        subjectRole = 0
    elif '_p1.bvh' in filename:
        subjectRole = 1
    elif '_p2.bvh' in filename:
        subjectRole = 2
    faceParamData = faceParamData['subjects'][subjectRole][
        'face_exp']  #200 x frames
    faceParamData = np.swapaxes(faceParamData, 0, 1)  # frames x 200

    #########################
    ## Load Bdoy Data
    anim, names, frametime = BVH.load(filename)

    # """ Convert to 60 fps """
    # anim = anim[::2]
    # Origianl Human3.6 has 50 fps. So, no smapling is done
    """ Do FK """
    global_positions = Animation.positions_global(anim)
    """ Remove Uneeded Joints """
    positions = global_positions[:,
                                 np.array([
                                     0, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 15,
                                     16, 18, 19, 20, 22, 25, 26, 27, 29
                                 ])]
    """ Put on Floor """
    fid_l, fid_r = np.array([4, 5]), np.array([8, 9])
    foot_heights = np.minimum(positions[:, fid_l, 1], positions[:, fid_r,
                                                                1]).min(axis=1)
    floor_height = softmin(foot_heights, softness=0.5, axis=0)

    positions[:, :, 1] -= floor_height
    """ Add Reference Joint """
    trajectory_filterwidth = 3
    reference = positions[:, 0] * np.array([1, 0, 1])
    reference = filters.gaussian_filter1d(reference,
                                          trajectory_filterwidth,
                                          axis=0,
                                          mode='nearest')
    positions = np.concatenate([reference[:, np.newaxis], positions], axis=1)
    """ Get Foot Contacts """
    velfactor, heightfactor = np.array([0.05, 0.05]), np.array([3.0, 2.0])

    feet_l_x = (positions[1:, fid_l, 0] - positions[:-1, fid_l, 0])**2
    feet_l_y = (positions[1:, fid_l, 1] - positions[:-1, fid_l, 1])**2
    feet_l_z = (positions[1:, fid_l, 2] - positions[:-1, fid_l, 2])**2
    feet_l_h = positions[:-1, fid_l, 1]
    feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor) &
              (feet_l_h < heightfactor)).astype(np.float)

    feet_r_x = (positions[1:, fid_r, 0] - positions[:-1, fid_r, 0])**2
    feet_r_y = (positions[1:, fid_r, 1] - positions[:-1, fid_r, 1])**2
    feet_r_z = (positions[1:, fid_r, 2] - positions[:-1, fid_r, 2])**2
    feet_r_h = positions[:-1, fid_r, 1]
    feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor) &
              (feet_r_h < heightfactor)).astype(np.float)
    """ Get Root Velocity """
    velocity = (positions[1:, 0:1] - positions[:-1, 0:1]).copy()
    """ Remove Translation """
    positions[:, :, 0] = positions[:, :, 0] - positions[:, 0:1, 0]
    positions[:, :, 2] = positions[:, :, 2] - positions[:, 0:1, 2]
    """ Get Forward Direction """
    sdr_l, sdr_r, hip_l, hip_r = 14, 18, 2, 6
    across1 = positions[:, hip_l] - positions[:, hip_r]
    across0 = positions[:, sdr_l] - positions[:, sdr_r]
    across = across0 + across1
    across = across / np.sqrt((across**2).sum(axis=-1))[..., np.newaxis]

    direction_filterwidth = 20
    forward = np.cross(across, np.array([[0, 1, 0]]))
    forward = filters.gaussian_filter1d(forward,
                                        direction_filterwidth,
                                        axis=0,
                                        mode='nearest')
    forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]
    """ Remove Y Rotation """
    target = np.array([[0, 0, 1]]).repeat(len(forward), axis=0)
    rotation = Quaternions.between(forward, target)[:, np.newaxis]
    positions = rotation * positions
    """ Get Root Rotation """
    velocity = rotation[1:] * velocity
    rvelocity = Pivots.from_quaternions(rotation[1:] * -rotation[:-1]).ps
    """ Add Velocity, RVelocity, Foot Contacts to vector """
    positions = positions[:-1]
    positions = positions.reshape(len(positions), -1)
    positions = np.concatenate([positions, velocity[:, :, 0]], axis=-1)
    positions = np.concatenate([positions, velocity[:, :, 2]], axis=-1)
    positions = np.concatenate([positions, rvelocity], axis=-1)
    positions = np.concatenate([positions, feet_l, feet_r], axis=-1)

    ##################################################
    ## Chunk Generation
    """ Slide over windows """
    windows_body = []
    windows_face = []
    windows_speech = []

    print("skelSize {0} vs speechSize {1}".format(
        positions.shape[0], speechData['indicator'].shape[0]))
    for j in range(0, len(positions) - window // 8, window_step):

        ## Face Part ############################v
        face_slice = faceParamData[j:j + window]  # faceParamData: (frames,200)
        if len(face_slice) < window:
            break

        if len(face_slice) != window: raise Exception()

        #Check Bad data (abs(value)>2)
        maxValue = np.max(abs(face_slice))
        if (maxValue > 2.0):
            continue

        #Face Param Cropping (just use initial 5 dim)
        face_slice = face_slice[:, :5]

        ## Body Part ############################v
        body_slice = positions[j:j + window]  # position: (frames,73)
        if len(body_slice) < window:
            break

        if len(body_slice) != window: raise Exception()

        ## Speech Part ############################v
        speech_slice = speechData['indicator'][
            j:j + window]  # speechData['indicator']: (frames,)

        ## Append ############################v
        windows_body.append(body_slice)
        windows_face.append(face_slice)
        windows_speech.append(speech_slice)

    return windows_body, windows_face, windows_speech
Beispiel #40
0
 def setUp(self):
     super(BaseTestCase, self).setUp()
     self.launcher, self.test_type = self.get_launcher_and_type()
     self.app = Animation.TouchApp(self.launcher(), self.test_type)
Beispiel #41
0
def process_file(filename, window=1, window_step=1):

    anim, names, frametime = BVH.load(filename)

    # """ Convert to 60 fps """
    # anim = anim[::2]
    # Origianl Human3.6 has 50 fps. So, no smapling is done
    """ Do FK """
    global_positions = Animation.positions_global(anim)
    """ Remove Uneeded Joints """
    positions = global_positions[:,
                                 np.array([
                                     0, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 15,
                                     16, 18, 19, 20, 22, 25, 26, 27, 29
                                 ])]
    """ Put on Floor """
    fid_l, fid_r = np.array([4, 5]), np.array([8, 9])
    foot_heights = np.minimum(positions[:, fid_l, 1], positions[:, fid_r,
                                                                1]).min(axis=1)
    floor_height = softmin(foot_heights, softness=0.5, axis=0)

    positions[:, :, 1] -= floor_height
    """ Add Reference Joint """
    trajectory_filterwidth = 3
    reference = positions[:, 0] * np.array([1, 0, 1])
    reference = filters.gaussian_filter1d(reference,
                                          trajectory_filterwidth,
                                          axis=0,
                                          mode='nearest')
    positions = np.concatenate([reference[:, np.newaxis], positions], axis=1)
    """ Get Foot Contacts """
    velfactor, heightfactor = np.array([0.05, 0.05]), np.array([3.0, 2.0])

    feet_l_x = (positions[1:, fid_l, 0] - positions[:-1, fid_l, 0])**2
    feet_l_y = (positions[1:, fid_l, 1] - positions[:-1, fid_l, 1])**2
    feet_l_z = (positions[1:, fid_l, 2] - positions[:-1, fid_l, 2])**2
    feet_l_h = positions[:-1, fid_l, 1]
    feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor) &
              (feet_l_h < heightfactor)).astype(np.float)

    feet_r_x = (positions[1:, fid_r, 0] - positions[:-1, fid_r, 0])**2
    feet_r_y = (positions[1:, fid_r, 1] - positions[:-1, fid_r, 1])**2
    feet_r_z = (positions[1:, fid_r, 2] - positions[:-1, fid_r, 2])**2
    feet_r_h = positions[:-1, fid_r, 1]
    feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor) &
              (feet_r_h < heightfactor)).astype(np.float)
    """ Get Root Velocity """
    velocity = (positions[1:, 0:1] - positions[:-1, 0:1]).copy()
    """ Remove Translation """
    positions[:, :, 0] = positions[:, :, 0] - positions[:, 0:1, 0]
    positions[:, :, 2] = positions[:, :, 2] - positions[:, 0:1, 2]
    """ Get Forward Direction """
    sdr_l, sdr_r, hip_l, hip_r = 14, 18, 2, 6
    across1 = positions[:, hip_l] - positions[:, hip_r]
    across0 = positions[:, sdr_l] - positions[:, sdr_r]
    across = across0 + across1
    across = across / np.sqrt((across**2).sum(axis=-1))[..., np.newaxis]

    direction_filterwidth = 20
    forward = np.cross(across, np.array([[0, 1, 0]]))
    forward = filters.gaussian_filter1d(forward,
                                        direction_filterwidth,
                                        axis=0,
                                        mode='nearest')
    forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]
    """ Remove Y Rotation """
    target = np.array([[0, 0, 1]]).repeat(len(forward), axis=0)
    rotation = Quaternions.between(forward, target)[:, np.newaxis]
    positions = rotation * positions
    """ Get Root Rotation """
    velocity = rotation[1:] * velocity
    rvelocity = Pivots.from_quaternions(rotation[1:] * -rotation[:-1]).ps
    """ Add Velocity, RVelocity, Foot Contacts to vector """
    positions = positions[:-1]
    positions = positions.reshape(len(positions), -1)
    positions = np.concatenate([positions, velocity[:, :, 0]], axis=-1)
    positions = np.concatenate([positions, velocity[:, :, 2]], axis=-1)
    positions = np.concatenate([positions, rvelocity], axis=-1)
    positions = np.concatenate([positions, feet_l, feet_r], axis=-1)
    """ Slide over windows """
    windows = []
    windows_classes = []

    for j in range(0, len(positions) - window // 8, window_step):
        """ If slice too small pad out by repeating start and end poses """
        slice = positions[j:j + window]
        if len(slice) < window:
            left = slice[:1].repeat(
                (window - len(slice)) // 2 + (window - len(slice)) % 2, axis=0)
            left[:, -7:-4] = 0.0
            right = slice[-1:].repeat((window - len(slice)) // 2, axis=0)
            right[:, -7:-4] = 0.0
            slice = np.concatenate([left, slice, right], axis=0)

        if len(slice) != window: raise Exception()

        windows.append(slice)
        """ Find Class """
        cls = -1
        if filename.startswith('hdm05'):
            cls_name = os.path.splitext(os.path.split(filename)[1])[0][7:-8]
            cls = class_names.index(
                class_map[cls_name]) if cls_name in class_map else -1
        if filename.startswith('styletransfer'):
            cls_name = os.path.splitext(os.path.split(filename)[1])[0]
            cls = np.array([
                styletransfer_motions.index('_'.join(
                    cls_name.split('_')[1:-1])),
                styletransfer_styles.index(cls_name.split('_')[0])
            ])
        windows_classes.append(cls)

    return windows, windows_classes
Beispiel #42
0
def process_file_withSpeech_face_byGroup(filename,
                                         window=240,
                                         window_step=120):

    if not '_p0.bvh' in filename:
        return

    #########################
    ## Load Speech Data
    seqName = os.path.basename(filename)
    fileName_pkl = seqName[:-7] + '.pkl'
    speechPath = './panopticDB_pkl_speech_hagglingProcessed/' + fileName_pkl
    speechData_raw = pickle.load(open(speechPath, "rb"))

    #########################
    ## Load Face Data
    faceParamDir = '/ssd/codes/pytorch_motionSynth/motionsynth_data/data/processed_panoptic/panopticDB_faceMesh_pkl_hagglingProcessed/'
    facePath = faceParamDir + fileName_pkl
    faceParamData_group = pickle.load(open(facePath, "rb"))
    faceParamData_group = faceParamData_group['subjects']

    positions_list = list()
    speechData_list = list()
    absoluteInfo_list = list()  # to go back to the absolute pos + orientation

    for pIdx in range(0, 3):
        """ Do FK """
        if pIdx == 0:
            anim, names, frametime = BVH.load(filename)
        else:
            newFileName = filename.replace('_p0.bvh', '_p{0}.bvh'.format(pIdx))
            anim, names, frametime = BVH.load(newFileName)

        if pIdx == 0:  #_p0.bvh' in filename:
            speechData = speechData_raw['speechData'][0]
        elif pIdx == 1:  #'_p1.bvh' in filename:
            speechData = speechData_raw['speechData'][1]
        elif pIdx == 2:  #'_p2.bvh' in filename:
            speechData = speechData_raw['speechData'][2]

        # """ Convert to 60 fps """
        # anim = anim[::2]
        # Origianl Human3.6 has 50 fps. So, no smapling is done
        """ Do FK """
        global_positions = Animation.positions_global(anim)
        """ Remove Uneeded Joints """
        positions = global_positions[:,
                                     np.array([
                                         0, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13,
                                         15, 16, 18, 19, 20, 22, 25, 26, 27, 29
                                     ])]
        """ Put on Floor """
        fid_l, fid_r = np.array([4, 5]), np.array([8, 9])
        foot_heights = np.minimum(positions[:, fid_l, 1],
                                  positions[:, fid_r, 1]).min(axis=1)
        floor_height = softmin(foot_heights, softness=0.5, axis=0)

        positions[:, :, 1] -= floor_height
        """ Add Reference Joint """
        trajectory_filterwidth = 3
        reference = positions[:, 0] * np.array([1, 0, 1])
        #reference = filters.gaussian_filter1d(reference, trajectory_filterwidth, axis=0, mode='nearest')
        positions = np.concatenate([reference[:, np.newaxis], positions],
                                   axis=1)

        # """ Save Initial Pos Info, not to lose global information"""
        abPos = positions[:, 1:2, :].copy()  #(frames, 1(rootJoint), 3)
        """ Get Foot Contacts """
        velfactor, heightfactor = np.array([0.05, 0.05]), np.array([3.0, 2.0])

        feet_l_x = (positions[1:, fid_l, 0] - positions[:-1, fid_l, 0])**2
        feet_l_y = (positions[1:, fid_l, 1] - positions[:-1, fid_l, 1])**2
        feet_l_z = (positions[1:, fid_l, 2] - positions[:-1, fid_l, 2])**2
        feet_l_h = positions[:-1, fid_l, 1]
        feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor) &
                  (feet_l_h < heightfactor)).astype(np.float)

        feet_r_x = (positions[1:, fid_r, 0] - positions[:-1, fid_r, 0])**2
        feet_r_y = (positions[1:, fid_r, 1] - positions[:-1, fid_r, 1])**2
        feet_r_z = (positions[1:, fid_r, 2] - positions[:-1, fid_r, 2])**2
        feet_r_h = positions[:-1, fid_r, 1]
        feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor) &
                  (feet_r_h < heightfactor)).astype(np.float)
        """ Get Root Velocity """
        velocity = (positions[1:, 0:1] - positions[:-1, 0:1]).copy()
        """ Remove Translation """
        positions[:, :, 0] = positions[:, :, 0] - positions[:, 0:1, 0]
        positions[:, :, 2] = positions[:, :, 2] - positions[:, 0:1, 2]
        """ Get Forward Direction """
        sdr_l, sdr_r, hip_l, hip_r = 14, 18, 2, 6
        across1 = positions[:, hip_l] - positions[:, hip_r]
        across0 = positions[:, sdr_l] - positions[:, sdr_r]
        across = across0 + across1
        across = across / np.sqrt((across**2).sum(axis=-1))[..., np.newaxis]

        direction_filterwidth = 20
        forward = np.cross(across, np.array([[0, 1, 0]]))
        #forward = filters.gaussian_filter1d(forward, direction_filterwidth, axis=0, mode='nearest')
        forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]
        """ Remove Y Rotation """
        target = np.array([[0, 0, 1]]).repeat(len(forward), axis=0)
        rotation = Quaternions.between(forward, target)[:, np.newaxis]
        positions = rotation * positions

        #""" Save normalized -> origial rotation"""
        abRot = -rotation  #(frames,1) Inverse to move [0,0,1] -> original Forward
        """ Get Root Rotation """
        velocity = rotation[1:] * velocity
        rvelocity = Pivots.from_quaternions(rotation[1:] * -rotation[:-1]).ps
        """ Add Velocity, RVelocity, Foot Contacts to vector """
        positions = positions[:-1]
        positions = positions.reshape(len(positions), -1)
        positions = np.concatenate([positions, velocity[:, :, 0]], axis=-1)
        positions = np.concatenate([positions, velocity[:, :, 2]], axis=-1)
        positions = np.concatenate([positions, rvelocity], axis=-1)
        positions = np.concatenate([positions, feet_l, feet_r], axis=-1)

        speechData_list.append(speechData)  #Save speech info
        positions_list.append(positions)  #Save skeleton info

        absoluteInfo_list.append({
            'pos': abPos,
            'rot': abRot
        })  #Save initial trans and rot information for the first frame

    if len(positions_list[0]) != len(positions_list[1]): raise Exception()
    if len(positions_list[1]) != len(positions_list[2]): raise Exception()

    if len(speechData_list[0]) != len(speechData_list[1]): raise Exception()
    if len(speechData_list[1]) != len(speechData_list[2]): raise Exception()
    """ Slide over windows """
    windows = [list(), list(), list()]
    windows_speech = [list(), list(), list()]
    windows_face = [list(), list(), list()]
    windows_abPos = [list(), list(), list()]
    windows_abRot = [list(), list(), list()]

    print("skelSize {0} vs speechSize {1}".format(
        positions.shape[0], speechData['indicator'].shape[0]))
    for j in range(0, len(positions) - window // 8, window_step):

        #check validity
        bSkip = False
        for pIdx in range(len(positions_list)):

            faceParamData = faceParamData_group[pIdx][
                'face_exp']  #200 x frames
            faceParamData = np.swapaxes(faceParamData, 0, 1)  # frames x 200
            face_slice = faceParamData[j:j +
                                       window]  # faceParamData: (frames,200)

            #Check Bad data (abs(value)>2)
            maxValue = np.max(abs(face_slice))
            if (maxValue > 2.0):
                bSkip = True
                break
        if bSkip:
            continue

        for pIdx in range(len(positions_list)):
            """ Face data """
            faceParamData = faceParamData_group[pIdx][
                'face_exp']  #200 x frames
            faceParamData = np.swapaxes(faceParamData, 0, 1)  # frames x 200
            face_slice = faceParamData[j:j +
                                       window]  # faceParamData: (frames,200)
            if len(face_slice) < window:
                break

            #Check Bad data (abs(value)>2)
            maxValue = np.max(abs(face_slice))
            if (maxValue > 2.0):
                continue

            if len(face_slice) != window: raise Exception()
            #only save part of them
            face_slice = face_slice[:, :5]  #Only use 5 dim for face features
            """ motion data"""
            slice = positions_list[pIdx][j:j + window]
            if len(slice) < window:
                break
            if len(slice) != window: raise Exception()

            windows_face[pIdx].append(face_slice)

            windows[pIdx].append(slice)
            """ init pos data"""
            #slice = absoluteInfo_list[pIdx]['pos'][j:j+window]
            slice = absoluteInfo_list[pIdx]['pos'][
                j]  #take only the first frame's
            windows_abPos[pIdx].append(slice)
            """ init rot data"""
            #slice = absoluteInfo_list[pIdx]['rot'][j:j+window]
            slice = absoluteInfo_list[pIdx]['rot'][
                j]  #take only the first frame's
            #windows_abRot[pIdx].append(slice)
            windows_abRot[pIdx].append(slice.qs)
            """ Speacking data """
            cls = speechData_list[pIdx]['indicator'][j:j + window]
            windows_speech[pIdx].append(cls)

    return windows, windows_speech, windows_face, windows_abPos, windows_abRot
Beispiel #43
0
class NPC:  # Non-player characters. People to interact with in-game that are run by the computer
    def __init__(self, name):
        self.name = name  # For display purposes and for finding the right save file
        self.savefilename = str(
            self.name
        ) + "SaveFile.txt"  # Saves general things like location, trades, and possessions
        self.defaultfile = "npcDefaultSave.txt"  # In case the save file gets lost
        try:
            self.readSaveFile(self.savefilename)
        except:
            self.readSaveFile(self.defaultfile)
        self.displayImage = Animation(
            str(self.name) + "-" + "no-still", 1, 1
        )  # "no-still" stands for  facing north, view overhead, standing still. I need that image generator
        self.moveLeft = 0  # How much is left in the move, not how much to move in the leftwards direction
        self.nextMove = round(random(
            300))  # To make it look like they're doing something important

    def readSaveFile(self, filename):
        file = open(filename, "r")
        saveData = " ".join(file.readlines())
        self.attributes = json.loads(saveData)
        file.close()

    def writeSaveFile(self):
        newSaveFile = open(self.saveFilename, "w")
        newSaveFile.write(json.dumps(self.attributes))
        newSaveFile.close()
        self.updateImage()

    def updateImage(self):  # Like the player
        if self.attributes["state"] == "still":
            self.displayImage = Animation(
                self.name + "-" + self.attributes["facing"] +
                self.attributes["view"] + "-still", 1, 1)
        elif self.attributes["state"] == "mov":
            self.displayImage = Animation(
                self.name + "-" + self.attributes["facing"] +
                self.attributes["view"] + "-mov", 4, 10)

    # TODO: Make this more modular

    def run(self):
        self.display()
        self.nextPixel = self.findNextPxl()  # For finding boundries
        if self.nextMove <= 0:
            self.setMovePoint()
            self.nextMove = round(random(300))
        if self.moveLeft <= 0:
            self.attributes["state"] = "still"
            self.updateImage()
            self.nextMove -= 1
        if self.moveLeft > 0:
            self.move()
            if self.nextPixel == intToRGB(
                    -3815995):  # For running into a boundry. Not yet modular
                if self.attributes["facing"] == "n":
                    self.attributes["y"] += self.attributes["speed"] + 1
                if self.attributes["facing"] == "s":
                    self.attributes["y"] -= self.attributes["speed"] + 1
                if self.attributes["facing"] == "e":
                    self.attributes["x"] -= self.attributes["speed"] + 1
                if self.attributes["facing"] == "w":
                    self.attributes["x"] += self.attributes["speed"] + 1
                self.moveLeft = 0
            # TODO: Make this work with any color

    def display(self):
        self.displayImage.display(self.attributes["x"], self.attributes["y"],
                                  self.attributes["w"], self.attributes["h"])

    def move(self):  # For moving based on direction faced
        self.attributes["state"] = "mov"
        self.nextPixel = self.findNextPxl()
        self.pastX = self.attributes["x"]
        self.pastY = self.attributes["y"]
        if self.attributes["view"] == "o":
            if self.attributes["facing"] == "n":
                self.attributes["y"] -= self.attributes["speed"]
            if self.attributes["facing"] == "s":
                self.attributes["y"] += self.attributes["speed"]
            if self.attributes["facing"] == "e":
                self.attributes["x"] += self.attributes["speed"]
            if self.attributes["facing"] == "w":
                self.attributes["x"] -= self.attributes["speed"]
        self.moveLeft -= self.attributes["speed"]

    def setMovePoint(self):  # Deciding which direction to go
        orientation = floor(random(3.99))
        if orientation == 0:
            self.attributes["facing"] = "n"
        if orientation == 1:
            self.attributes["facing"] = "s"
        if orientation == 2:
            self.attributes["facing"] = "e"
        if orientation == 3:
            self.attributes["facing"] = "w"
        self.updateImage()
        self.moveLeft = random(300)

    def findNextPxl(self):  # For finding color
        if self.attributes["facing"] == "n":
            nextPxl = get(self.attributes["x"], self.attributes["y"] - 10)
            fill(255, 0, 0)
            #ellipse(self.attributes["x"], self.attributes["y"] - 10, 10, 10)
            return intToRGB(nextPxl)
        if self.attributes["facing"] == "s":
            nextPxl = get(self.attributes["x"], self.attributes["y"] + 10)
            fill(255, 0, 0)
            #ellipse(self.attributes["x"], self.attributes["y"] + 10, 10, 10)
            return intToRGB(nextPxl)
        if self.attributes["facing"] == "w":
            nextPxl = get(self.attributes["x"] - 10, self.attributes["y"])
            fill(255, 0, 0)
            #ellipse(self.attributes["x"] - 10, self.attributes["y"], 10, 10)
            return intToRGB(nextPxl)
        if self.attributes["facing"] == "e":
            nextPxl = get(self.attributes["x"] + 10, self.attributes["y"])
            fill(255, 0, 0)
            #ellipse(self.attributes["x"] + 10, self.attributes["y"], 10, 10)
            return intToRGB(nextPxl)
Beispiel #44
0
def process_data(anim, phase, gait, type='flat'):
    """ Do FK """
    global_xforms = Animation.transforms_global(anim)
    global_positions = global_xforms[:, :, :3,
                                     3] / global_xforms[:, :, 3:,
                                                        3]  # (F, J, 3)
    global_rotations = Quaternions.from_transforms(
        global_xforms)  # (F, J) quats
    """ Extract Forward Direction """

    across = (
        (global_positions[:, skd.SDR_L] - global_positions[:, skd.SDR_R]) +
        (global_positions[:, skd.HIP_L] - global_positions[:, skd.HIP_R]))
    across = across / np.sqrt((across**2).sum(axis=-1))[..., np.newaxis]
    """ Smooth Forward Direction """

    direction_filterwidth = 20
    forward = filters.gaussian_filter1d(np.cross(across, np.array([[0, 1,
                                                                    0]])),
                                        direction_filterwidth,
                                        axis=0,
                                        mode='nearest')
    forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]

    root_rotation = Quaternions.between(
        forward,
        np.array([[0, 0, 1]]).repeat(len(forward), axis=0))[:, np.newaxis]
    """ Local Space """

    local_positions = global_positions.copy()
    local_positions[:, :,
                    0] = local_positions[:, :, 0] - local_positions[:, 0:1, 0]
    local_positions[:, :,
                    2] = local_positions[:, :, 2] - local_positions[:, 0:1, 2]

    local_positions = root_rotation[:-1] * local_positions[:-1]  # (F-1, J, 3)
    local_velocities = root_rotation[:-1] * (
        global_positions[1:] - global_positions[:-1])  # (F-1, J, 3)
    local_rotations = (
        (root_rotation[:-1] * global_rotations[:-1]))  # (F-1, J) quats
    #print('hips (w,x,y,z)=' + str(abs((root_rotation[:-1] * global_rotations[:-1]))[0][0]))
    #print('hips log(w,x,y,z)=' + str(local_rotations[0][0]))

    root_velocity = root_rotation[:-1] * (global_positions[1:, 0:1] -
                                          global_positions[:-1, 0:1])
    root_rvelocity = Pivots.from_quaternions(root_rotation[1:] *
                                             -root_rotation[:-1]).ps
    """ Foot Contacts """

    fid_l, fid_r = np.array(skd.FOOT_L), np.array(skd.FOOT_R)
    velfactor = np.array([0.02, 0.02])

    feet_l_x = (global_positions[1:, fid_l, 0] -
                global_positions[:-1, fid_l, 0])**2
    feet_l_y = (global_positions[1:, fid_l, 1] -
                global_positions[:-1, fid_l, 1])**2
    feet_l_z = (global_positions[1:, fid_l, 2] -
                global_positions[:-1, fid_l, 2])**2
    feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor)).astype(np.float)

    feet_r_x = (global_positions[1:, fid_r, 0] -
                global_positions[:-1, fid_r, 0])**2
    feet_r_y = (global_positions[1:, fid_r, 1] -
                global_positions[:-1, fid_r, 1])**2
    feet_r_z = (global_positions[1:, fid_r, 2] -
                global_positions[:-1, fid_r, 2])**2
    feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor)).astype(np.float)
    """ Phase """

    dphase = phase[1:] - phase[:-1]
    dphase[dphase < 0] = (1.0 - phase[:-1] + phase[1:])[dphase < 0]
    """ Adjust Crouching Gait Value """

    if type == 'flat':
        crouch_low, crouch_high = 80, 130
        head = skd.HEAD
        gait[:-1, 3] = 1 - np.clip(
            (global_positions[:-1, head, 1] - 80) / (130 - 80), 0, 1)
        gait[-1, 3] = gait[-2, 3]
    """ Load prev rotations across files (poles maybe adjusted) """
    global prev_rotations
    if prev_rotations is None:
        prev_rotations = local_rotations[window - 1]
    """ Start Windows """

    Pc, Xc, Yc = [], [], []

    for i in range(window, len(anim) - window - 1, 1):

        rootposs = root_rotation[i:i + 1, 0] * (
            global_positions[i - window:i + window:10, 0] -
            global_positions[i:i + 1, 0])
        rootdirs = root_rotation[i:i + 1,
                                 0] * forward[i - window:i + window:10]
        rootgait = gait[i - window:i + window:10]

        Pc.append(phase[i])
        """ Unify Quaternions To Single Pole """
        """ Between Prev vs Next Keys """
        """ [Grassia1998]:
            The procedure followed by Yahia [13] of limiting the range of the log map to |log(r)| ≤ π does not suffice.
            A log mapping that does guarantee the geodesic approximation picks the mapping for each successive key that
            minimizes the Euclidean distance to the mapping of the previous key.
            Given such a log map that considers the previous mapping when calculating the current mapping, the results of interpolating
            in S3 and R3 may be visually indistinguishable for many applications, including keyframing.  """
        antipode = prev_rotations.dot(local_rotations[i]) < 0
        local_rotations[i][antipode] = Quaternions(
            -local_rotations[i][antipode].qs)
        prev_rotations = local_rotations[i]

        # print("*********************************")
        # print(i)
        # #print(*antipode, sep=' ')
        # for j in range(antipode.size):
        #     print("%6d " % (j+1), end='' if j < antipode.size-1 else '\n')
        # for j in range(antipode.size):
        #     print("%6s " % antipode[j], end='' if j < antipode.size-1 else '\n')
        # for j in range(antipode.size):
        #     print("%06.3f " % local_rotations[i-1][j].reals, end='' if j < antipode.size-1 else '\n')
        # for j in range(antipode.size):
        #     print("%06.3f " % local_rotations[i][j].reals, end='' if j < antipode.size-1 else '\n')

        # print(*local_rotations[i-1][antipode], sep=' ')
        # print(*local_rotations[i][antipode], sep=' ')

        # # print("*********************************")
        # # print(local_rotations[i][antipode])
        # # print("*********************************")

        Xc.append(
            np.hstack([
                rootposs[:, 0].ravel(),
                rootposs[:, 2].ravel(),  # Trajectory Pos
                rootdirs[:, 0].ravel(),
                rootdirs[:, 2].ravel(),  # Trajectory Dir
                rootgait[:, 0].ravel(),
                rootgait[:, 1].ravel(),  # Trajectory Gait
                rootgait[:, 2].ravel(),
                rootgait[:, 3].ravel(),
                rootgait[:, 4].ravel(),
                rootgait[:, 5].ravel(),
                local_positions[i - 1].ravel(),  # Joint Pos
                local_velocities[i - 1].ravel(),  # Joint Vel
            ]))

        rootposs_next = root_rotation[i + 1:i + 2, 0] * (
            global_positions[i + 1:i + window + 1:10, 0] -
            global_positions[i + 1:i + 2, 0])
        rootdirs_next = root_rotation[i + 1:i + 2,
                                      0] * forward[i + 1:i + window + 1:10]

        Yc.append(
            np.hstack([
                root_velocity[i, 0, 0].ravel(),  # Root Vel X
                root_velocity[i, 0, 2].ravel(),  # Root Vel Y
                root_rvelocity[i].ravel(),  # Root Rot Vel
                dphase[i],  # Change in Phase
                np.concatenate([feet_l[i], feet_r[i]], axis=-1),  # Contacts
                rootposs_next[:, 0].ravel(),
                rootposs_next[:, 2].ravel(),  # Next Trajectory Pos
                rootdirs_next[:, 0].ravel(),
                rootdirs_next[:, 2].ravel(),  # Next Trajectory Dir
                local_positions[i].ravel(),  # Joint Pos
                local_velocities[i].ravel(),  # Joint Vel
                local_rotations[i].log().ravel()  # Joint Rot
            ]))

    return np.array(Pc), np.array(Xc), np.array(Yc)
Beispiel #45
0
def prepare_input(anim_bvh, floor_file, contacts_file, out_dir, character, \
                    start_idx=None,
                    end_idx=None,
                    dt=(1.0 / 30.0),
                    combined_contacts=False):
    '''
    This prepares all data input to feed to the trajectory optimization:
       - skel_info.txt : hip offsets, leg length, heel distance, mass, and moments of inertia over time
       - motion_info.txt : COM trajectory/orientation, feet trajectory
       - terrain_info.txt : ground plane normal and one point on the plane
       - contact_info.txt : durations of contacts for toes and heels, and whether they're in contact with the ground at start
    '''
    ''' Writes out the necessary data files passed to physics optimization '''
    if not os.path.exists(anim_bvh):
        print('Could not find animated bvh file ' + anim_bvh)
        return
    if not os.path.exists(floor_file):
        print('Could not find floor file ' + floor_file)
        return
    if not os.path.exists(contacts_file):
        print('Could not find contacts file ' + contacts_file)
        return
    if not os.path.exists(out_dir):
        os.mkdir(out_dir)

    if start_idx is None:
        start_idx = 0
    if end_idx is None:
        end_idx = anim_COM.shape[0]
    
    num_frames = end_idx - start_idx

    # load the actual motion, zero out the root orientation and position, and
    # calculate the inertia matrix for every single timestep
    anim, names, _ = BVH.load(anim_bvh)
    zero_root = np.zeros((anim.shape[0], 3))
    zero_root = Quaternions.from_euler(zero_root, order='xyz', world=True)
    anim.rotations[:,0,:] = zero_root
    anim.positions[:,0,:] = np.zeros((anim.shape[0], 3))
    normalized_positions = Animation.positions_global(anim)

    # find the leg length
    left_leg_chain = get_character_leg_chain(character, 'left')
    bone_lengths = np.linalg.norm(anim.offsets[left_leg_chain[1:]], axis=1)
    max_leg_length = np.sum(bone_lengths) * 0.01 # to meters
    # print('Max leg length (m)')
    # print(max_leg_length)

    # find COM at each frame and move the root there (since our orientations are about the root)
    hip_joints = get_character_hip_inds(character)
    map_segment_to_joints = get_character_seg_to_joint_map(character)
    map_segment_to_mass_perc = get_character_seg_to_mass_perc_map(character)
    frame_coms = []
    hip_offsets = np.zeros((anim.shape[0], 2, 3))
    for frame in range(anim.shape[0]):
        frame_COM = np.zeros(3)
        for key in map_segment_to_joints.keys():
            seg_pos = np.mean(normalized_positions[frame, map_segment_to_joints[key], :], axis=0)
            frame_COM += map_segment_to_mass_perc[key] * 0.01 * seg_pos
        frame_coms.append(frame_COM)

        for j in range(len(hip_joints)):
            hip_offsets[frame, j] = (normalized_positions[frame, hip_joints[j]] - frame_COM)

    frame_coms = np.array(frame_coms)

    hip_offsets *= 0.01 # to meters
    hip_offsets[:,:,:] *= -1.0 # flip
    hip_offsets = hip_offsets[:,:,[0,2,1]] # swap y and z

    anim.positions[:,0,:] -= frame_coms # move so COM is at origin
    normalized_positions = Animation.positions_global(anim) * 0.01
    normalized_positions[:,:,:] *= -1.0 # flip y
    normalized_positions = normalized_positions[:,:,[0,2,1]] # swap y and z
    # then calculate inertia about COM
    total_mass = get_character_mass(character)
    inertia_mats = []
    for frame in range(anim.shape[0]):
        I_frame= np.zeros((3, 3))
        for key in map_segment_to_joints.keys():
            seg_pos = np.mean(normalized_positions[frame, map_segment_to_joints[key], :], axis=0)
            seg_mass = map_segment_to_mass_perc[key] * 0.01 * total_mass            
            I_seg = (np.eye(3)*np.dot(seg_pos, seg_pos) - np.outer(seg_pos, seg_pos)) * seg_mass
            I_frame += I_seg
        inertia_mats.append(I_frame)

    toe_inds = get_character_toe_inds(character)
    left_toe_idx, right_toe_idx = toe_inds
    ankle_inds = get_character_ankle_inds(character)
    left_ankle_idx, right_ankle_idx = ankle_inds

     # animated motion
    # get COM trajectory, root orientation, left/right foot trajectories
    anim, names, _ = BVH.load(anim_bvh)
    # print('LEFT FOOT OFF:')
    # print(anim.offsets[left_toe_idx])
    # print('RIGHT FOOT OFF:')
    # print(anim.offsets[right_toe_idx])

    # append a heel to the character at the same height as foot
    if not character in heeled_characters:
        # must add a heel if doesn't already have one
        anim, heel_offsets = add_heel_to_anim(anim, toe_inds, ankle_inds)
    anim_pos = Animation.positions_global(anim)

    anim_pos[:,:,:] *= -1.0 # flip y
    anim_pos = anim_pos[:,:,[0,2,1]] # swap y and z

    anim_pos *= 0.01 # CONVERTED TO meters since towr uses them (and to make physically reasonable)

    root_pos = anim_pos[:,0,:]
    left_foot_pos = anim_pos[:,left_toe_idx,:]
    right_foot_pos = anim_pos[:, right_toe_idx,:]

    left_ankle_pos = anim_pos[:,left_ankle_idx,:]
    right_ankle_pos = anim_pos[:,right_ankle_idx,:]

    left_heel_idx = anim_pos.shape[1] - 2
    right_heel_idx = anim_pos.shape[1] - 1
    if character in heeled_characters:
        # already has a heel joint
        left_heel_idx, right_heel_idx = get_character_heel_inds(character)

    left_heel_pos = anim_pos[:, left_heel_idx, :]
    right_heel_pos = anim_pos[:, right_heel_idx, :]

    heel_dist = np.mean(np.linalg.norm(left_foot_pos - left_heel_pos, axis=1))

    left_leg_chain = get_character_leg_chain(character, 'left')
    bone_lengths = np.linalg.norm(anim.offsets[left_leg_chain[1:-1]], axis=1) # only down to ankle
    max_heel_length = (np.sum(bone_lengths) + np.linalg.norm(anim.offsets[left_heel_idx])) * 0.01 # to meters
    # print('Max heel length (m)')
    # print(max_heel_length)

    skel_out_path = os.path.join(out_dir, 'skel_info.txt')
    with open(skel_out_path, 'w') as skel_file:
        # left hip offset
        for frame in range(start_idx, end_idx):
            skel_file.write(str(hip_offsets[frame, 0, 0]) + ' ' + str(hip_offsets[frame, 0, 1]) + ' ' + str(hip_offsets[frame, 0, 2]) + '\n')
        # right hip offset
        for frame in range(start_idx, end_idx):
            skel_file.write(str(hip_offsets[frame, 1, 0]) + ' ' + str(hip_offsets[frame, 1, 1]) + ' ' + str(hip_offsets[frame, 1, 2]) + '\n')
        # leg length (hip to toe)
        skel_file.write(str(max_leg_length) + '\n')
        # heel length (hip to heel)
        skel_file.write(str(max_heel_length) + '\n')
        # heel distance (from toe)
        skel_file.write(str(heel_dist) + '\n')
        # total mass
        skel_file.write(str(total_mass) + '\n')
        # Ixx, Iyy, Izz, Ixy, Ixz, Iyz
        for frame in range(start_idx, end_idx):
            I_cur = inertia_mats[frame]
            skel_file.write(str(I_cur[0, 0]) + ' ' + str(I_cur[1, 1]) + ' ' + str(I_cur[2, 2]) + ' ' + 
                        str(I_cur[0, 1]) + ' ' + str(I_cur[0, 2]) + ' ' + str(I_cur[1, 2]) + '\n')

    rot_angle, rot_axis = anim.rotations.angle_axis()
    rot_axis[:,:,:] *= -1.0 # flip y
    rot_axis = rot_axis[:, :, [0,2,1]] # swap y and z]
    root_rot = Quaternions.from_angle_axis(rot_angle, rot_axis).euler(order='xyz')[:,0,:]

    # fix root rot to be smooth
    for dim in range(3):
        cur_val = root_rot[0, dim]
        for frame_idx in range(1, root_rot.shape[0]):
            pre_mult = 1.0 if cur_val >= 0.0 else -1.0
            next_val = root_rot[frame_idx, dim]
            while abs(next_val - cur_val) > np.pi:
                next_val += pre_mult * 2*np.pi
            root_rot[frame_idx, dim] = next_val
            cur_val = next_val 

    # plot_3curve(left_foot_pos, dt, 'time(s)', 'Left foot goal pos (m)')
    # plot_3curve(left_heel_pos, dt, 'time(s)', 'Left heel goal pos (m)')
    # plot_3curve(right_foot_pos, dt, 'time(s)', 'Right foot goal pos (m)')
    # plot_3curve(right_heel_pos, dt, 'time(s)', 'Right heel goal pos (m)')
    # plot_3curve(root_rot, dt, 'time(s)', 'target euler angle')

    # calc COM over time
    anim_COM = np.zeros((anim_pos.shape[0], 3))
    for i in range(anim_pos.shape[0]):
        cur_COM = np.zeros(3)
        for key in map_segment_to_joints.keys():
            seg_pos = np.mean(anim_pos[i, map_segment_to_joints[key], :], axis=0)
            mass_frac = map_segment_to_mass_perc[key] * 0.01
            cur_COM += mass_frac * seg_pos
        anim_COM[i] = cur_COM

    motion_out_path = os.path.join(out_dir, 'motion_info.txt')
    with open(motion_out_path, 'w') as motion_file:
        motion_file.write(str(dt) + '\n')
        # COM trajectory
        for i in range(start_idx, end_idx):
            motion_file.write(str(anim_COM[i, 0]) + ' ' + str(anim_COM[i, 1]) + ' ' + str(anim_COM[i, 2]))
            if i < end_idx - 1:
                motion_file.write(' ')
        motion_file.write('\n')
        # COM (root) orientation
        for i in range(start_idx, end_idx):
            motion_file.write(str(root_rot[i, 0]) + ' ' + str(root_rot[i, 1]) + ' ' + str(root_rot[i, 2]))
            if i < end_idx - 1:
                motion_file.write(' ')
        motion_file.write('\n')
        # left foot trajectory
        for i in range(start_idx, end_idx):
            motion_file.write(str(left_foot_pos[i, 0]) + ' ' + str(left_foot_pos[i, 1]) + ' ' + str(left_foot_pos[i, 2]))
            if i < end_idx - 1:
                motion_file.write(' ')
        motion_file.write('\n')
        # left heel trajectory
        for i in range(start_idx, end_idx):
            motion_file.write(str(left_heel_pos[i, 0]) + ' ' + str(left_heel_pos[i, 1]) + ' ' + str(left_heel_pos[i, 2]))
            if i < end_idx - 1:
                motion_file.write(' ')
        motion_file.write('\n')
        # right foot trajectory
        for i in range(start_idx, end_idx):
            motion_file.write(str(right_foot_pos[i, 0]) + ' ' + str(right_foot_pos[i, 1]) + ' ' + str(right_foot_pos[i, 2]))
            if i < end_idx - 1:
                motion_file.write(' ')
        motion_file.write('\n')
        # right heel trajectory
        for i in range(start_idx, end_idx):
            motion_file.write(str(right_heel_pos[i, 0]) + ' ' + str(right_heel_pos[i, 1]) + ' ' + str(right_heel_pos[i, 2]))
            if i < end_idx - 1:
                motion_file.write(' ')
        motion_file.write('\n')

    # floor information
    # already have it, just copy file
    floor_out_path = os.path.join(out_dir, 'terrain_info.txt')
    with open(floor_file, 'r') as f:
        normal_line = f.readline()
        normal_str = normal_line.split(' ')
        plane_normal = np.array([float(x) for x in normal_str]) # to meters
        point_line = f.readline().split('\n')[0]
        point_str = point_line.split(' ')
        plane_loc = np.array([float(x) for x in point_str]) * 0.01 # to meters

    plane_normal[:] *= -1.0 # flip y
    plane_normal = plane_normal[[0,2,1]] # swap y and z
    plane_loc[:] *= -1.0 # flip y
    plane_loc = plane_loc[[0,2,1]] # swap y and z
    with open(os.path.join(floor_out_path), 'w') as floor_file:
        floor_file.write(str(plane_normal[0]))
        floor_file.write(' ')
        floor_file.write(str(plane_normal[1]))
        floor_file.write(' ')
        floor_file.write(str(plane_normal[2]))
        floor_file.write('\n')
        floor_file.write(str(plane_loc[0]))
        floor_file.write(' ')
        floor_file.write(str(plane_loc[1]))
        floor_file.write(' ')
        floor_file.write(str(plane_loc[2]))

    foot_contacts = np.load(contacts_file)
    # heel = 0, toe = 1
    contacts_left = foot_contacts[:,[0,1]]
    contacts_left = np.amax(contacts_left, axis=1) # if either are in contact
    contacts_right = foot_contacts[:,[2,3]]
    contacts_right = np.amax(contacts_right, axis=1) # if either are in contact
    contacts_left = contacts_left[start_idx:end_idx]
    contacts_right = contacts_right[start_idx:end_idx]

    # left toe, left heel, right toe, right heel
    contacts_all = foot_contacts[start_idx:end_idx,[1, 0, 3, 2]]

    left_toe_start_in_contact = contacts_left[0] #contacts_all[0, 0]
    if combined_contacts:
        left_toe_start_in_contact = contacts_all[0, 0]
    left_heel_start_in_contact = contacts_all[0, 1]
    right_toe_start_in_contact = contacts_right[0] #contacts_all[0, 2]
    if combined_contacts:
        right_toe_start_in_contact = contacts_all[0, 2]
    right_heel_start_in_contact = contacts_all[0, 3]

    # figure out durations
    if not combined_contacts:
        left_toe_durations = find_contact_durations(contacts_all[:,0], dt)
    else:
        left_toe_durations = find_contact_durations(contacts_left, dt)
    left_heel_durations = find_contact_durations(contacts_all[:,1], dt)
    if not combined_contacts:
        right_toe_durations = find_contact_durations(contacts_all[:,2], dt)
    else:
        right_toe_durations = find_contact_durations(contacts_right, dt)
    right_heel_durations = find_contact_durations(contacts_all[:,3], dt)


    contacts_out_path = os.path.join(out_dir, 'contact_info.txt')
    with open(contacts_out_path, 'w') as contacts_file:
        # left toe start in contact
        contacts_file.write(str(left_toe_start_in_contact) + '\n')
        # left toe durations
        contacts_file.write(str(len(left_toe_durations)) + '\n')
        for i in range(len(left_toe_durations)):
            contacts_file.write(str(left_toe_durations[i]))
            if i < len(left_toe_durations) - 1:
                contacts_file.write(' ')
        contacts_file.write('\n')
        # left heel start in contact
        contacts_file.write(str(left_heel_start_in_contact) + '\n')
        # left heel durations
        contacts_file.write(str(len(left_heel_durations)) + '\n')
        for i in range(len(left_heel_durations)):
            contacts_file.write(str(left_heel_durations[i]))
            if i < len(left_heel_durations) - 1:
                contacts_file.write(' ')
        contacts_file.write('\n')
        # right toe start in contact
        contacts_file.write(str(right_toe_start_in_contact) + '\n')
        # right toe durations
        contacts_file.write(str(len(right_toe_durations)) + '\n')
        for i in range(len(right_toe_durations)):
            contacts_file.write(str(right_toe_durations[i]))
            if i < len(right_toe_durations) - 1:
                contacts_file.write(' ')
        contacts_file.write('\n')
        # right heel start in contact
        contacts_file.write(str(right_heel_start_in_contact) + '\n')
        # right heel durations
        contacts_file.write(str(len(right_heel_durations)) + '\n')
        for i in range(len(right_heel_durations)):
            contacts_file.write(str(right_heel_durations[i]))
            if i < len(right_heel_durations) - 1:
                contacts_file.write(' ')
Beispiel #46
0
def process_heights(anim, nsamples=10, type='flat'):
    """ Do FK """

    global_xforms = Animation.transforms_global(anim)
    global_positions = global_xforms[:, :, :3, 3] / global_xforms[:, :, 3:, 3]
    global_rotations = Quaternions.from_transforms(global_xforms)
    """ Extract Forward Direction """

    across = (
        (global_positions[:, skd.SDR_L] - global_positions[:, skd.SDR_R]) +
        (global_positions[:, skd.HIP_L] - global_positions[:, skd.HIP_R]))
    across = across / np.sqrt((across**2).sum(axis=-1))[..., np.newaxis]
    """ Smooth Forward Direction """

    direction_filterwidth = 20
    forward = filters.gaussian_filter1d(np.cross(across, np.array([[0, 1,
                                                                    0]])),
                                        direction_filterwidth,
                                        axis=0,
                                        mode='nearest')
    forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]

    root_rotation = Quaternions.between(
        forward,
        np.array([[0, 0, 1]]).repeat(len(forward), axis=0))[:, np.newaxis]
    """ Foot Contacts """

    fid_l, fid_r = np.array(skd.FOOT_L), np.array(skd.FOOT_R)
    velfactor = np.array([0.02, 0.02])

    feet_l_x = (global_positions[1:, fid_l, 0] -
                global_positions[:-1, fid_l, 0])**2
    feet_l_y = (global_positions[1:, fid_l, 1] -
                global_positions[:-1, fid_l, 1])**2
    feet_l_z = (global_positions[1:, fid_l, 2] -
                global_positions[:-1, fid_l, 2])**2
    feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor))

    feet_r_x = (global_positions[1:, fid_r, 0] -
                global_positions[:-1, fid_r, 0])**2
    feet_r_y = (global_positions[1:, fid_r, 1] -
                global_positions[:-1, fid_r, 1])**2
    feet_r_z = (global_positions[1:, fid_r, 2] -
                global_positions[:-1, fid_r, 2])**2
    feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor))

    feet_l = np.concatenate([feet_l, feet_l[-1:]], axis=0)
    feet_r = np.concatenate([feet_r, feet_r[-1:]], axis=0)
    """ Toe and Heel Heights """

    toe_h, heel_h = 4.0, 5.0
    """ Foot Down Positions """

    feet_down = np.concatenate([
        global_positions[feet_l[:, 0], fid_l[0]] - np.array([0, heel_h, 0]),
        global_positions[feet_l[:, 1], fid_l[1]] - np.array([0, toe_h, 0]),
        global_positions[feet_r[:, 0], fid_r[0]] - np.array([0, heel_h, 0]),
        global_positions[feet_r[:, 1], fid_r[1]] - np.array([0, toe_h, 0])
    ],
                               axis=0)
    """ Foot Up Positions """

    feet_up = np.concatenate([
        global_positions[~feet_l[:, 0], fid_l[0]] - np.array([0, heel_h, 0]),
        global_positions[~feet_l[:, 1], fid_l[1]] - np.array([0, toe_h, 0]),
        global_positions[~feet_r[:, 0], fid_r[0]] - np.array([0, heel_h, 0]),
        global_positions[~feet_r[:, 1], fid_r[1]] - np.array([0, toe_h, 0])
    ],
                             axis=0)
    """ Down Locations """
    feet_down_xz = np.concatenate([feet_down[:, 0:1], feet_down[:, 2:3]],
                                  axis=-1)
    feet_down_xz_mean = feet_down_xz.mean(axis=0)
    feet_down_y = feet_down[:, 1:2]
    feet_down_y_mean = feet_down_y.mean(axis=0)
    feet_down_y_std = feet_down_y.std(axis=0)
    """ Up Locations """

    feet_up_xz = np.concatenate([feet_up[:, 0:1], feet_up[:, 2:3]], axis=-1)
    feet_up_y = feet_up[:, 1:2]

    if len(feet_down_xz) == 0:
        """ No Contacts """

        terr_func = lambda Xp: np.zeros_like(Xp)[:, :1][np.newaxis].repeat(
            nsamples, axis=0)

    elif type == 'flat':
        """ Flat """

        terr_func = lambda Xp: np.zeros_like(Xp)[:, :1][np.newaxis].repeat(
            nsamples, axis=0) + feet_down_y_mean

    else:
        """ Terrain Heights """

        terr_down_y = patchfunc(patches, feet_down_xz - feet_down_xz_mean)
        terr_down_y_mean = terr_down_y.mean(axis=1)
        terr_down_y_std = terr_down_y.std(axis=1)
        terr_up_y = patchfunc(patches, feet_up_xz - feet_down_xz_mean)
        """ Fitting Error """

        terr_down_err = 0.1 * (
            ((terr_down_y - terr_down_y_mean[:, np.newaxis]) -
             (feet_down_y - feet_down_y_mean)[np.newaxis])**2)[...,
                                                               0].mean(axis=1)

        terr_up_err = (np.maximum(
            (terr_up_y - terr_down_y_mean[:, np.newaxis]) -
            (feet_up_y - feet_down_y_mean)[np.newaxis],
            0.0)**2)[..., 0].mean(axis=1)
        """ Jumping Error """

        if type == 'jumpy':
            terr_over_minh = 5.0
            terr_over_err = (np.maximum(
                ((feet_up_y - feet_down_y_mean)[np.newaxis] - terr_over_minh) -
                (terr_up_y - terr_down_y_mean[:, np.newaxis]),
                0.0)**2)[..., 0].mean(axis=1)
        else:
            terr_over_err = 0.0
        """ Fitting Terrain to Walking on Beam """

        if type == 'beam':

            beam_samples = 1
            beam_min_height = 40.0

            beam_c = global_positions[:, 0]
            beam_c_xz = np.concatenate([beam_c[:, 0:1], beam_c[:, 2:3]],
                                       axis=-1)
            beam_c_y = patchfunc(patches, beam_c_xz - feet_down_xz_mean)

            beam_o = (beam_c.repeat(beam_samples, axis=0) +
                      np.array([50, 0, 50]) *
                      rng.normal(size=(len(beam_c) * beam_samples, 3)))

            beam_o_xz = np.concatenate([beam_o[:, 0:1], beam_o[:, 2:3]],
                                       axis=-1)
            beam_o_y = patchfunc(patches, beam_o_xz - feet_down_xz_mean)

            beam_pdist = np.sqrt(((beam_o[:, np.newaxis] -
                                   beam_c[np.newaxis, :])**2).sum(axis=-1))
            beam_far = (beam_pdist > 15).all(axis=1)

            terr_beam_err = (np.maximum(
                beam_o_y[:, beam_far] -
                (beam_c_y.repeat(beam_samples, axis=1)[:, beam_far] -
                 beam_min_height), 0.0)**2)[..., 0].mean(axis=1)

        else:
            terr_beam_err = 0.0
        """ Final Fitting Error """

        terr = terr_down_err + terr_up_err + terr_over_err + terr_beam_err
        """ Best Fitting Terrains """

        terr_ids = np.argsort(terr)[:nsamples]
        terr_patches = patches[terr_ids]
        terr_basic_func = lambda Xp: (
            (patchfunc(terr_patches, Xp - feet_down_xz_mean) -
             terr_down_y_mean[terr_ids][:, np.newaxis]) + feet_down_y_mean)
        """ Terrain Fit Editing """
        terr_residuals = feet_down_y - terr_basic_func(feet_down_xz)
        terr_fine_func = [
            RBF(smooth=0.1, function='linear', epsilon=1e-10)
            for _ in range(nsamples)
        ]
        for i in range(nsamples):
            terr_fine_func[i].fit(feet_down_xz, terr_residuals[i])
        terr_func = lambda Xp: (terr_basic_func(Xp) + np.array(
            [ff(Xp) for ff in terr_fine_func]))
    """ Get Trajectory Terrain Heights """

    root_offsets_c = global_positions[:, 0]
    root_offsets_r = (-root_rotation[:, 0] *
                      np.array([[+25, 0, 0]])) + root_offsets_c
    root_offsets_l = (-root_rotation[:, 0] *
                      np.array([[-25, 0, 0]])) + root_offsets_c

    root_heights_c = terr_func(root_offsets_c[:, np.array([0, 2])])[..., 0]
    root_heights_r = terr_func(root_offsets_r[:, np.array([0, 2])])[..., 0]
    root_heights_l = terr_func(root_offsets_l[:, np.array([0, 2])])[..., 0]
    """ Find Trajectory Heights at each Window """

    root_terrains = []
    root_averages = []
    for i in range(window, len(anim) - window, 1):
        root_terrains.append(
            np.concatenate([
                root_heights_r[:, i - window:i + window:10],
                root_heights_c[:, i - window:i + window:10],
                root_heights_l[:, i - window:i + window:10]
            ],
                           axis=1))
        root_averages.append(root_heights_c[:, i - window:i +
                                            window:10].mean(axis=1))

    root_terrains = np.swapaxes(np.array(root_terrains), 0, 1)
    root_averages = np.swapaxes(np.array(root_averages), 0, 1)

    return root_terrains, root_averages
Beispiel #47
0
def viz_results(towr_results, skeletons, start_idx, end_idx,
                floor_normal=None, floor_point=None, flip_floor=True,
                interval=33.33, save_path=None,
                draw_trace=True, draw_forces=True, draw_towr=True, draw_skel=True, 
                fps=30, draw_floor=True, flip_anim=[1], show=True, names=[]):
    fig = plt.figure(figsize=(12,8))
    ax = fig.add_subplot(111, projection='3d')

    offset = np.array([[2.0, 0.0, 0.0]]) # in meters

    for extra_res_idx in range(1, len(towr_results)):
        res_copy = TowrResults()
        res_copy.copy_from(towr_results[extra_res_idx])
        # then apply our offset
        res_copy.base_pos += offset * extra_res_idx
        for foot_idx in range(res_copy.num_feet):
            res_copy.feet_pos[:, foot_idx] += offset * extra_res_idx

        towr_results[extra_res_idx] = res_copy 

    contacts = [res.feet_contact for res in towr_results]

    body_pos = [Animation.positions_global(skeleton) * 0.01 for skeleton in skeletons] # to meters
    for jnt_idx in flip_anim:
        for cur_body_pos in body_pos:
            cur_body_pos[:, :, jnt_idx] *= -1.0

    # offset body positions too
    for extra_res_idx in range(1, len(skeletons)):
        body_pos[extra_res_idx] += offset * extra_res_idx

    base_pos = [res.base_pos for res in towr_results]

    maxes = np.amax(np.concatenate(base_pos, axis=0), axis=0)
    mins = np.amin(np.concatenate(base_pos, axis=0), axis=0)
    move_rad = (np.amax(np.abs(maxes - mins) / 2.0) + 1.0) / 1.5
    mov_avg = (maxes + mins) / 2.0
    ax.set_xlim3d(mov_avg[0] - move_rad, mov_avg[0] + move_rad)
    ax.set_zlim3d(mov_avg[1] - move_rad, mov_avg[1] + move_rad)
    ax.set_ylim3d(mov_avg[2] - move_rad, mov_avg[2] + move_rad)

    ax.set_xlabel('x')
    ax.set_ylabel('z')

    plt.axis('off')
    plt.grid(b=None)

    ax.azim = -127.15384
    ax.elev = 15.35064

    if draw_floor and floor_normal is not None and floor_point is not None:
        draw_floor = True
    else:
        draw_floor = False

    skel_color = ['r', 'purple', 'blue', 'green']
    base_color = 'orange'
    feet_color = ['g', 'b', 'pink', 'purple']
    forces_color = 'r'
    robot_color = 'yellow'

    if not names is None and len(names) == len(towr_results):
        text_offset = np.array([0.0, 1.3, 0.0])
        for res_idx in range(len(towr_results)):
            text_pos = np.mean(towr_results[res_idx].base_pos, axis=0) + text_offset
            ax.text(text_pos[0], text_pos[2], text_pos[1], names[res_idx], color=skel_color[res_idx])

    if draw_trace:
        for cur_towr_result in towr_results:
            for i in range(cur_towr_result.base_pos.shape[0] - 1):
                from_pt = cur_towr_result.base_pos[i, :]
                to_pt = cur_towr_result.base_pos[i+1, :]
                plt.plot([from_pt[0], to_pt[0]], [from_pt[2], to_pt[2]], [from_pt[1], to_pt[1]], lw=3, color=base_color, linestyle='dashed')

                for j in range(cur_towr_result.feet_pos.shape[1]):
                    from_pt = cur_towr_result.feet_pos[i, j, :]
                    to_pt = cur_towr_result.feet_pos[i+1, j, :]
                    plt.plot([from_pt[0], to_pt[0]], [from_pt[2], to_pt[2]], [from_pt[1], to_pt[1]], lw=3, color=feet_color[j], linestyle='dashed')

    if draw_floor:
        floor_center_xz = mov_avg[[0, 2]]
        floor_center_y = eval_plane(floor_normal, floor_point, floor_center_xz)
        floor_cent = np.array([floor_center_xz[0], floor_center_y, floor_center_xz[1]])

        tan1_xz = floor_center_xz + np.array([-10.0, 0.0])
        tan1_y = eval_plane(floor_normal, floor_point, tan1_xz)
        tan2_xz = floor_center_xz + np.array([0.0, 10.0])
        tan2_y = eval_plane(floor_normal, floor_point, tan2_xz)

        tan1 = np.array([tan1_xz[0], tan1_y, tan1_xz[1]]) - floor_cent
        tan1 /= np.linalg.norm(tan1)
        tan2 = np.array([tan2_xz[0], tan2_y, tan2_xz[1]]) - floor_cent
        tan2 /= np.linalg.norm(tan2)

        tile_width = 0.5
        tile_diam = 20
        tile_rad = tile_diam // 2
        start_pt = floor_cent + tile_rad*tile_width*tan1 + tile_rad*tile_width*tan2
        for i in range(tile_diam):
            for j in range(tile_diam):
                line1_start = start_pt - i*tile_width*tan1 - j*tile_width*tan2
                line1_end = (start_pt - tile_width*tan1) - i*tile_width*tan1 - j*tile_width*tan2
                if flip_floor:
                    premult = -1.0
                else:
                    premult=1.0
                plt.plot([line1_start[0],line1_end[0]], [line1_start[2],line1_end[2]], [premult*line1_start[1],premult*line1_end[1]], color='grey', 
                            lw=2, path_effects=[pe.Stroke(linewidth=1, foreground='black'), pe.Normal()])

                line2_start = line1_end
                line2_end = line1_end - tile_width*tan2
                plt.plot([line2_start[0],line2_end[0]], [line2_start[2],line2_end[2]], [premult*line2_start[1],premult*line2_end[1]], color='grey', 
                            lw=2, path_effects=[pe.Stroke(linewidth=1, foreground='black'), pe.Normal()])

                if j == tile_diam - 1:
                    line3_start = line2_end
                    line3_end = line2_end + tile_width*tan1
                    plt.plot([line3_start[0],line3_end[0]], [line3_start[2],line3_end[2]], [premult*line3_start[1],premult*line3_end[1]], color='grey', 
                                lw=2, path_effects=[pe.Stroke(linewidth=1, foreground='black'), pe.Normal()])
                if i == 0:
                    line3_end = line2_end + tile_width*tan1
                    line4_start = line3_end
                    line4_end = line3_end + tile_width*tan2
                    plt.plot([line4_start[0],line4_end[0]], [line4_start[2],line4_end[2]], [premult*line4_start[1],premult*line4_end[1]], color='grey', 
                                lw=2, path_effects=[pe.Stroke(linewidth=1, foreground='black'), pe.Normal()])

    if draw_towr:
        base_joints = [plt.plot([0] ,[0], [0], 'o', color=base_color, markersize=10.0)[0] for i in range(len(towr_results))]

    all_joints = []
    bone_lines = []
    if draw_skel:
        for skel_idx in range(len(skeletons)):
            cur_all_joints = []
            cur_bone_lines = []
            for i in range(body_pos[skel_idx].shape[1]):
                cur_all_joints.append(plt.plot([0] ,[0], [0], 'o', color=skel_color[skel_idx])[0])
            all_joints.append(cur_all_joints)
            for i in range(body_pos[skel_idx].shape[1] - 1):
                cur_bone_lines.append(plt.plot([0,0], [0,0], [0,0], color=skel_color[skel_idx], lw=3, path_effects=[pe.Stroke(linewidth=3, foreground='black'), pe.Normal()])[0])
            bone_lines.append(cur_bone_lines)
            
    feet_joints = []
    hip_joints = []
    legs = []
    forces = []
    robot_lines = []
    for res_idx in range(len(towr_results)):
        cur_feet_joints = []
        cur_legs = []
        cur_forces = []
        for i in range(towr_results[res_idx].num_feet):
            if draw_towr:
                cur_feet_joints.append(plt.plot([0] ,[0], [0], 'o', color=feet_color[i], markersize=10.0)[0])
                cur_legs.append(plt.plot([0,0], [0,0], [0,0], color=feet_color[i], lw=3, path_effects=[pe.Stroke(linewidth=3, foreground='black'), pe.Normal()])[0])
            if draw_forces:
                cur_forces.append(plt.plot([0,0], [0,0], [0,0], color=forces_color, lw=1, path_effects=[pe.Stroke(linewidth=3), pe.Normal()])[0])

        feet_joints.append(cur_feet_joints)
        legs.append(cur_legs)
        forces.append(cur_forces)

        if draw_towr:
            cur_robot_lines = []
            robot_verts = np.array([[0.0, 0.0, 0.0], [0.0, -0.25, 0.0], [0.05, -0.2, 0.0], [-0.05, -0.2, 0.0], [0.0, -0.25, 0.0]])
            for i in range(robot_verts.shape[0] - 1):
                cur_robot_lines.append(plt.plot([0,0], [0,0], [0,0], color=robot_color, lw=3, path_effects=[pe.Stroke(linewidth=3, foreground='black'), pe.Normal()])[0])

            robot_lines.append(cur_robot_lines)


    animate_forces = [res.feet_force*0.001 for res in towr_results]
    
    def animate(i):
        # print('azim: ' + str(ax.azim))
        # print('elev: ' + str(ax.elev))
        # print('dist: ' + str(ax.dist))

        changed = []

        if draw_towr:
            for res_idx in range(len(towr_results)):
                base_joints[res_idx].set_data([towr_results[res_idx].base_pos[i, 0]], [towr_results[res_idx].base_pos[i, 2]])
                base_joints[res_idx].set_3d_properties([towr_results[res_idx].base_pos[i, 1]])

                cur_robot_joints = np.dot(towr_results[res_idx].base_R[i], robot_verts.T).T + np.expand_dims(towr_results[res_idx].base_pos[i], axis=0)
                for j in range(len(robot_lines[res_idx])):
                    robot_lines[res_idx][j].set_data(
                        [ cur_robot_joints[j, 0],     cur_robot_joints[j+1, 0]],
                        [cur_robot_joints[j, 2],       cur_robot_joints[j+1, 2]])
                    robot_lines[res_idx][j].set_3d_properties(
                        [ cur_robot_joints[j, 1],        cur_robot_joints[j+1, 1]])

        if draw_skel:
            for skel_idx in range(len(skeletons)):
                for j in range(body_pos[skel_idx].shape[1]):
                    cur_all_joint = body_pos[skel_idx][i, j] 
                    all_joints[skel_idx][j].set_data([cur_all_joint[0]], [cur_all_joint[2]])
                    all_joints[skel_idx][j].set_3d_properties([cur_all_joint[1]])

                for j in range(1, body_pos[skel_idx].shape[1]):
                    cur_all_joint = body_pos[skel_idx][i, j]
                    cur_par_joint = body_pos[skel_idx][i, skeletons[skel_idx].parents[j]]
                    bone_lines[skel_idx][j-1].set_data(
                        [ cur_all_joint[0],     cur_par_joint[0]],
                        [cur_all_joint[2],       cur_par_joint[2]])
                    bone_lines[skel_idx][j-1].set_3d_properties(
                        [ cur_all_joint[1],        cur_par_joint[1]])


        if draw_towr:
            for res_idx in range(len(towr_results)):
                for j in range(towr_results[res_idx].num_feet):
                    feet_joints[res_idx][j].set_data([towr_results[res_idx].feet_pos[i, j, 0]], [towr_results[res_idx].feet_pos[i, j, 2]])
                    feet_joints[res_idx][j].set_3d_properties([towr_results[res_idx].feet_pos[i, j, 1]])

                    if contacts[res_idx] is not None and contacts[res_idx][i, j]:
                        feet_joints[res_idx][j].set_color(forces_color)
                    else:
                        feet_joints[res_idx][j].set_color(feet_color[j])

                    legs[res_idx][j].set_data(
                            [ towr_results[res_idx].base_pos[i, 0], towr_results[res_idx].feet_pos[i, j, 0]],
                            [towr_results[res_idx].base_pos[i, 2],       towr_results[res_idx].feet_pos[i, j, 2]])
                    legs[res_idx][j].set_3d_properties(
                        [ towr_results[res_idx].base_pos[i, 1],        towr_results[res_idx].feet_pos[i, j, 1]])

        if draw_forces:
            for res_idx in range(len(towr_results)):
                for j in range(towr_results[res_idx].num_feet):
                    forces[res_idx][j].set_data(
                        [ towr_results[res_idx].feet_pos[i, j, 0] - animate_forces[res_idx][i, j, 0], towr_results[res_idx].feet_pos[i, j, 0]],
                        [towr_results[res_idx].feet_pos[i, j, 2] - animate_forces[res_idx][i, j, 2],       towr_results[res_idx].feet_pos[i, j, 2]])
                    forces[res_idx][j].set_3d_properties(
                        [towr_results[res_idx].feet_pos[i, j, 1] - animate_forces[res_idx][i, j, 1],       towr_results[res_idx].feet_pos[i, j, 1]])

        changed = legs

        return changed
        
    plt.tight_layout()
        
    ani = animation.FuncAnimation(fig, animate, np.arange(towr_results[0].base_pos.shape[0]), interval=interval)

    if save_path != None:
        Writer = animation.writers['ffmpeg']
        writer = Writer(fps=fps, metadata=dict(artist='Me'), bitrate=1800)
        ani.save(save_path, writer=writer)

    if show:
        plt.show()
Beispiel #48
0
    def __call__(self,
                 descendants=None,
                 maxjoints=4,
                 gamma=1.0,
                 transpose=False):
        """ Calculate Masses """
        if self.weights is None:
            self.weights = np.ones(self.animation.shape[1])

        if self.weights_translate is None:
            self.weights_translate = np.ones(self.animation.shape[1])

        nf = len(self.animation)
        nj = self.animation.shape[1]
        nv = self.goal.shape[1]

        weightids = np.argsort(-self.vweights, axis=1)[:, :maxjoints]
        weightvls = np.array(
            list(map(lambda w, i: w[i], self.vweights, weightids)))
        weightvls = weightvls / weightvls.sum(axis=1)[..., np.newaxis]

        if descendants is None:
            self.descendants = AnimationStructure.descendants_mask(
                self.animation.parents)
        else:
            self.descendants = descendants

        des_r = np.eye(nj) + self.descendants
        des_r = des_r[:, weightids].repeat(3, axis=0)

        des_t = np.eye(nj) + self.descendants
        des_t = des_t[:, weightids].repeat(3, axis=0)

        if not self.silent:
            curr = Animation.skin(self.animation,
                                  self.rest,
                                  self.vweights,
                                  self.mesh,
                                  maxjoints=maxjoints)
            error = np.mean(np.sqrt(np.sum((curr - self.goal)**2.0, axis=-1)))
            print('[ICP] Start | Error: %f' % error)

        for i in range(self.iterations):
            """ Get Global Rotations & Positions """
            gt = Animation.transforms_global(self.animation)
            gp = gt[:, :, :, 3]
            gp = gp[:, :, :3] / gp[:, :, 3, np.newaxis]
            gr = Quaternions.from_transforms(gt)

            x = self.animation.rotations.euler().reshape(nf, -1)
            w = self.weights.repeat(3)

            if self.translate:
                x = np.hstack([x, self.animation.positions.reshape(nf, -1)])
                w = np.hstack([w, self.weights_translate.repeat(3)])
            """ Get Current State """
            curr = Animation.skin(self.animation,
                                  self.rest,
                                  self.vweights,
                                  self.mesh,
                                  maxjoints=maxjoints)
            """ Find Cloest Points """
            if self.find_closest:
                mapping = np.argmin((curr[:, :, np.newaxis] -
                                     self.goal[:, np.newaxis, :])**2.0,
                                    axis=2)
                e = gamma * (np.array(
                    list(map(lambda g, m: g[m], self.goal, mapping))) -
                             curr).reshape(nf, -1)
            else:
                e = gamma * (self.goal - curr).reshape(nf, -1)
            """ Generate Jacobian """
            if self.recalculate or i == 0:
                j = self.jacobian(x, gp, gr, self.goal, weightvls, des_r,
                                  des_t)
            """ Update Variables """
            l = self.damping * (1.0 / (w + 1e-10))
            d = (l * l) * np.eye(x.shape[1])

            if transpose:
                x += np.array(list(map(lambda jf, ef: jf.T.dot(ef), j, e)))
            else:
                x += np.array(
                    list(
                        map(
                            lambda jf, ef: linalg.lu_solve(
                                linalg.lu_factor(jf.T.dot(jf) + d), jf.T.dot(
                                    ef)), j, e)))
            """ Set Back Rotations / Translations """
            self.animation.rotations = Quaternions.from_euler(
                x[:, :nj * 3].reshape((nf, nj, 3)), order='xyz', world=True)

            if self.translate:
                self.animation.positions = x[:, nj * 3:].reshape((nf, nj, 3))

            if not self.silent:
                curr = Animation.skin(self.animation, self.rest, self.vweights,
                                      self.mesh)
                error = np.mean(
                    np.sqrt(np.sum((curr - self.goal)**2.0, axis=-1)))
                print('[ICP] Iteration %i | Error: %f' % (i + 1, error))
                         (position2[2] - position1[2])**2)
    return distance


def treshold_check(distance1, distance2):
    activate = False
    if distance1 <= treshold_value and distance2 <= treshold_value:
        activate = True
    return activate


file_object = open(file_path + file_name + "_footsteps.txt", 'w')

anim, names, frametime = BVH.load(file_path + file_name + ".bvh")
frames_number = len(anim)
global_positions = Animation.positions_global(anim)

left_foot_id = 0
left_toe_id = 0
right_foot_id = 0
right_toe_id = 0

for i in range(0, len(names)):
    if names[i] == "LeftFoot":
        left_foot_id = i
    if names[i] == "LeftToeBase":
        left_toe_id = i

    if names[i] == "RightFoot":
        right_foot_id = i
    if names[i] == "RightToeBase":
Beispiel #50
0
    def __init__(self):
        super(LookComponent, self).__init__()

        # Initialize all Animation objects:
        self.animations = {}
        self.animations["stand_right"] = Animation(
            split_tiled_image(
                pygame.image.load(j_path(
                    "images", "ANI_Wario_stand_r.png")).convert_alpha(),
                (20, 29)), [(0, 250), (1, 100), (2, 5), (1, 20), (2, 10),
                            (1, 100)])
        self.animations["stand_left"] = self.animations[
            "stand_right"].make_x_mirror()

        self.animations["walk_right"] = Animation(
            split_tiled_image(
                pygame.image.load(j_path(
                    "images", "ANI_Wario_walk_r.png")).convert_alpha(),
                (24, 29)), 5)
        self.animations["walk_left"] = self.animations[
            "walk_right"].make_x_mirror()

        self.animations["jump_right"] = Animation([
            pygame.image.load(j_path("images",
                                     "ANI_Wario_jump_r.png")).convert_alpha()
        ], 1)
        self.animations["jump_left"] = self.animations[
            "jump_right"].make_x_mirror()

        # Load images for the next couple of animations:
        gotosleep_imgs = split_tiled_image(
            pygame.image.load(j_path(
                "images", "ANI_Wario_gotosleep_r.png")).convert_alpha(),
            (28, 30))

        self.animations["gotosleep_right"] = Animation(gotosleep_imgs,
                                                       [(0, 15), (1, 15),
                                                        (2, 15), (3, 15),
                                                        (4, 15)])
        self.animations["gotosleep_left"] = self.animations[
            "gotosleep_right"].make_x_mirror()

        self.animations["sleep_right"] = Animation(gotosleep_imgs, [(4, 30),
                                                                    (5, 20),
                                                                    (6, 100),
                                                                    (5, 20)])
        self.animations["sleep_left"] = self.animations[
            "sleep_right"].make_x_mirror()

        self.animations["wakeup_right"] = Animation(gotosleep_imgs, [(4, 25),
                                                                     (3, 25),
                                                                     (2, 25),
                                                                     (1, 25),
                                                                     (0, 25)])
        self.animations["wakeup_left"] = self.animations[
            "wakeup_right"].make_x_mirror()

        turn_around_img = split_tiled_image(
            pygame.image.load(j_path("images",
                                     "ANI_Wario_turn.png")).convert_alpha(),
            (28, 29), (225, 0, 225))
        self.animations["turn_left"] = Animation(turn_around_img, [(3, 4),
                                                                   (2, 4),
                                                                   (1, 4)])
        self.animations["turn_right"] = Animation(turn_around_img, [(1, 4),
                                                                    (2, 4),
                                                                    (3, 4)])

        fist_img = split_tiled_image(
            pygame.image.load(j_path(
                "images", "ANI_Wario_softfist_l.png")).convert_alpha(),
            (32, 30))
        self.animations["fist_left"] = Animation(fist_img, 3)
        self.animations["fist_right"] = self.animations[
            "fist_left"].make_x_mirror()

        # Save the current animation
        self.current_animation = self.animations["stand_right"]
        # Save the last animation to check if a new animation has started:
        self.current_animation_name = "stand_right"
        # Play the current animation
        self.current_animation.play()
    def readAnimation(self, name, root, skeletonData):
        if not skeletonData:
            raise Exception('skeletonData cannot be null.')

        timelines = []
        duration = 0.0

        bones = root.get('bones', {})

        for boneName in bones.keys():
            boneIndex = skeletonData.findBoneIndex(boneName)
            if boneIndex == -1:
                raise Exception('Bone not found: %s' % boneName)

            timelineMap = bones[boneName]

            for timelineName in timelineMap.keys():
                values = timelineMap[timelineName]

                if timelineName == 'rotate':
                    timeline = Animation.Timeline.RotateTimeline(len(values))
                    timeline.boneIndex = boneIndex

                    keyframeIndex = 0
                    for valueMap in values:
                        time = valueMap['time']
                        timeline.setKeyframe(keyframeIndex, time,
                                             valueMap['angle'])
                        timeline = readCurve(timeline, keyframeIndex, valueMap)
                        keyframeIndex += 1
                    timelines.append(timeline)
                    if timeline.getDuration() > duration:
                        duration = timeline.getDuration()
                elif timelineName == 'translate' or timelineName == 'scale':
                    timeline = None
                    timelineScale = 1.0
                    if timelineName == 'scale':
                        timeline = Animation.Timeline.ScaleTimeline(
                            len(values))
                    else:
                        timeline = Animation.Timeline.TranslateTimeline(
                            len(values))
                        timelineScale = self.scale
                    timeline.boneIndex = boneIndex

                    keyframeIndex = 0
                    for valueMap in values:
                        time = valueMap['time']
                        timeline.setKeyframe(keyframeIndex, valueMap['time'],
                                             valueMap.get('x', 0.0),
                                             valueMap.get('y', 0.0))
                        timeline = readCurve(timeline, keyframeIndex, valueMap)
                        keyframeIndex += 1
                    timelines.append(timeline)
                    if timeline.getDuration() > duration:
                        duration = timeline.getDuration()
                else:
                    raise Exception(
                        'Invalid timeline type for a bone: %s (%s)' %
                        (timelineName, boneName))

        slots = root.get('slots', {})

        for slotName in slots.keys():
            slotIndex = skeletonData.findSlotIndex(slotName)
            if slotIndex == -1:
                raise Exception('Slot not found: %s' % slotName)

            timelineMap = slots[slotName]
            for timelineName in timelineMap.keys():
                values = timelineMap[timelineName]
                if timelineName == 'color':
                    timeline = Animation.Timeline.ColorTimeline(len(values))
                    timeline.slotIndex = slotIndex

                    keyframeIndex = 0
                    for valueMap in values:
                        timeline.setKeyframe(keyframeIndex, valueMap['time'],
                                             int(valueMap['color'][0:2], 16),
                                             int(valueMap['color'][2:4], 16),
                                             int(valueMap['color'][4:6], 16),
                                             int(valueMap['color'][6:8], 16))
                        timeline = readCurve(timeline, keyframeIndex, valueMap)
                        keyframeIndex += 1
                    timelines.append(timeline)
                    if timeline.getDuration > duration:
                        duration = timeline.getDuration()

                elif timelineName == 'attachment':
                    timeline = Animation.Timeline.AttachmentTimeline(
                        len(values))
                    timeline.slotIndex = slotIndex

                    keyframeIndex = 0
                    for valueMap in values:
                        valueName = valueMap['name']
                        timeline.setKeyframe(
                            keyframeIndex, valueMap['time'],
                            '' if not valueName else valueName)
                        keyframeIndex += 1
                    timelines.append(timeline)
                    if timeline.getDuration > duration:
                        duration = timeline.getDuration()
                else:
                    raise Exception(
                        'Invalid timeline type for a slot: %s (%s)' %
                        (timelineName, slotName))

        animation = Animation.Animation(name, timelines, duration)
        return animation
Beispiel #52
0
def Event_re ( **args ):
    """ 새롭게 다시 만든 이벤트입니다. 매개변수를 사전형으로 받아 드리립니다. 따라서 여러가지 인수를 추가적으로 여기서 기역할 필요 없음"""
    print( " Start , MainFrame.enable = ",engine.Main_Frame.enable )
    try:
        id = args["id"]
        Object = args["Object"]
    except:
        id = args["id"]
    print("----Event_re")

    if id == "Button":# 클릭시 파란색 이팩트 
        print(Object)
        #Object.c = Color.Color.c4
        Color.ColorChanger ( engine ,engine.root , Object.c , Color.Color.c4, Object , 3 )
        Event_re ( id = "DrawAll" )
    elif id == "ButtonRelease":# 원래 색으로 돌아옴
        Color.ColorChanger ( engine ,engine.root , Object.c , Object.GetOrigenColor() , Object , 10 )
        Event_re ( id = "DrawMainFrame" )
    elif id == "DrawMainFrame":
        engine.Main_Frame.Draw( g )
    elif id == "ButtonLock":
        if engine.Main_Frame.enable == True:
            engine.Main_Frame.Enable( False )
        else:
            engine.Main_Frame.Enable( True )
    elif id[0:8] == "ClickBox":
        if id == "ClickBox":
            engine.ThreadStart ()
            if args["Object"].id[0:2] == engine.View_Frame.날자범위.id[0:2]:
                if args["Object"].id == engine.View_Frame.날자범위.id:
                    engine.View_Frame.날자.text.FontSize ( int( engine.View_Frame.날자.text.FontSize() ) - 5 )
                    engine.View_Frame.날자글.text.FontSize ( int( engine.View_Frame.날자글.text.FontSize() ) - 5 )
                elif args["Object"].id == engine.View_Frame.금액범위.id:
                    engine.View_Frame.금액.text.FontSize ( int ( engine.View_Frame.금액.text.FontSize() ) - 5 )
                    engine.View_Frame.금액글.text.FontSize(int ( engine.View_Frame.금액글.text.FontSize () ) -5 )
                elif args["Object"].id == engine.View_Frame.태그범위.id:
                    engine.View_Frame.태그.text.FontSize ( int ( engine.View_Frame.태그.text.FontSize () ) - 5 )
                    engine.View_Frame.태그글.text.FontSize(int( engine.View_Frame.태그글.text.FontSize()) - 5 )
                elif args["Object"].id == engine.View_Frame.내용범위.id:
                    engine.View_Frame.내용.text.FontSize ( int ( engine.View_Frame.내용.text.FontSize () ) - 5 )
                    engine.View_Frame.내용글.text.FontSize(int ( engine.View_Frame.내용글.text.FontSize())- 5 )
            else:
                if args["Object"].id == engine.Plus_Frame.날자범위.id:
                    engine.Plus_Frame.날자.text.FontSize ( int ( engine.Plus_Frame.날자.text.FontSize () ) - 5 )
                    engine.Plus_Frame.날자글.text.FontSize(int( engine.Plus_Frame.날자글.text.FontSize()) - 5 )
                elif args["Object"].id == engine.Plus_Frame.금액범위.id :
                    engine.Plus_Frame.금액.text.FontSize ( int ( engine.Plus_Frame.금액.text.FontSize() ) - 5 )
                    engine.Plus_Frame.금액글.text.FontSize(int( engine.Plus_Frame.금액글.text.FontSize())- 5 )
                elif args["Object"].id == engine.Plus_Frame.태그범위.id:
                    engine.Plus_Frame.태그.text.FontSize ( int ( engine.Plus_Frame.태그.text.FontSize () ) - 5 )
                    engine.Plus_Frame.태그글.text.FontSize(int ( engine.Plus_Frame.태그글.text.FontSize())- 5 )
                elif args["Object"].id == engine.Plus_Frame.내용범위.id:
                    engine.Plus_Frame.내용.text.FontSize ( int ( engine.Plus_Frame.내용.text.FontSize () ) - 5 )
                    engine.Plus_Frame.내용글.text.FontSize(int( engine.Plus_Frame.내용글.text.FontSize()) - 5 )
        else:
            if args["Object"].id[0:2] == engine.View_Frame.날자범위.id[0:2]:
                if args["Object"].id == engine.View_Frame.날자범위.id:
                    Animation.FontSize ( engine.View_Frame.날자 , engine, 5 , int ( engine.View_Frame.날자.text.FontSize() ) , int ( engine.View_Frame.날자.text.FontSize ( ) ) + 5 )
                    Animation.FontSize ( engine.View_Frame.날자글 , engine, 5 , int ( engine.View_Frame.날자글.text.FontSize() ) , int ( engine.View_Frame.날자글.text.FontSize ( ) ) + 5 )
                elif args["Object"].id == engine.View_Frame.금액범위.id:
                    Animation.FontSize ( engine.View_Frame.금액 , engine, 5 , int ( engine.View_Frame.금액.text.FontSize () ) , int ( engine.View_Frame.금액.text.FontSize ( ) ) + 5 )
                    Animation.FontSize ( engine.View_Frame.금액글, engine,5, int ( engine.View_Frame.금액글.text.FontSize()) , int ( engine.View_Frame.금액글.text.FontSize()) + 5 )
                elif args["Object"].id == engine.View_Frame.태그범위.id:
                    Animation.FontSize ( engine.View_Frame.태그 , engine , 5 , int ( engine.View_Frame.태그.text.FontSize ( ) ) , int ( engine.View_Frame.태그.text.FontSize() ) + 5)
                    Animation.FontSize ( engine.View_Frame.태그글,engine , 5, int ( engine.View_Frame.태그글.text.FontSize() ) , int ( engine.View_Frame.태그글.text.FontSize())+ 5)
                elif args["Object"].id == engine.View_Frame.내용범위.id:
                    Animation.FontSize ( engine.View_Frame.내용 , engine , 5 , int ( engine.View_Frame.내용.text.FontSize () ) , int ( engine.View_Frame.내용.text.FontSize ( ) ) + 5 )
                    Animation.FontSize ( engine.View_Frame.내용글,engine , 5 , int ( engine.View_Frame.내용글.text.FontSize()),int ( engine.View_Frame.내용글.text.FontSize() ) + 5 )
            else:
                if args["Object"].id == engine.Plus_Frame.날자범위.id:
                    Animation.FontSize ( engine.Plus_Frame.날자 , engine , 5 , int ( engine.Plus_Frame.날자.text.FontSize ( ) ) , int ( engine.Plus_Frame.날자.text.FontSize ( ) ) + 5 )
                    Animation.FontSize ( engine.Plus_Frame.날자글 , engine,5, int ( engine.Plus_Frame.날자글.text.FontSize()) , int ( engine.Plus_Frame.날자글.text.FontSize() ) + 5 )
                elif args["Object"].id == engine.Plus_Frame.금액범위.id:
                    Animation.FontSize ( engine.Plus_Frame.금액 , engine , 5 , int ( engine.Plus_Frame.금액.text.FontSize ( ) ) , int ( engine.Plus_Frame.금액.text.FontSize () )  + 5 )
                    Animation.FontSize ( engine.Plus_Frame.금액글,engine, 5 , int ( engine.Plus_Frame.금액글.text.FontSize() ) , int ( engine.Plus_Frame.금액글.text.FontSize()) + 5 )
                elif args["Object"].id == engine.Plus_Frame.태그범위.id:
                    Animation.FontSize ( engine.Plus_Frame.태그 , engine , 5 , int ( engine.Plus_Frame.태그.text.FontSize ( ) ) , int ( engine.Plus_Frame.태그.text.FontSize () ) + 5 )
                    Animation.FontSize ( engine.Plus_Frame.태그글,engine , 5, int ( engine.Plus_Frame.태그글.text.FontSize() ) , int ( engine.Plus_Frame.태그글.text.FontSize()) + 5 )
                elif args["Object"].id == engine.Plus_Frame.내용범위.id:
                    Animation.FontSize ( engine.Plus_Frame.내용 , engine , 5 , int ( engine.Plus_Frame.내용.text.FontSize ( ) ) , int ( engine.Plus_Frame.내용.text.FontSize ( ) ) + 5 )
                    Animation.FontSize ( engine.Plus_Frame.내용글,engine, 5 , int ( engine.Plus_Frame.내용글.text.FontSize() ) , int ( engine.Plus_Frame.내용글.text.FontSize() ) + 5 )



        engine.ThreadEnd ()
    elif id == "TextClick":
        engine.ThreadStart ()
        args["Object"].text.FontSize ( int(args["Object"].text.FontSize()) -5 )
        engine.ThreadEnd ()
    elif id == "TextClickRelease":
        Animation.FontSize ( args["Object"] , engine , 5 , int ( args["Object"].text.FontSize () )  , int ( args["Object"].text.FontSize ( ) ) + 5 )
    elif id == "MakeGraph":
        data = engine.data.sumsameList ( "태그" )
        data = engine.data.tool.percentData ( data )
        if len( data ) > 0 and data[0]["금액"] < 0:
            engine.Graph_Frame.첫이름.text.text = data[0]["태그"] + "\n" + str(-data[0]["금액"]) + "%"
            engine.Graph_Frame.첫그래프.pSize보조.y = ( data[0]["금액"]/100 + 1 )* engine.Graph_Frame.첫그래프.pSizeORIGEN.y
        if len( data ) > 1 and data[1]["금액"] < 0:
            engine.Graph_Frame.둘이름.text.text = data[1]["태그"] + "\n" + str(-data[1]["금액"]) + "%"
            engine.Graph_Frame.둘그래프.pSize보조.y = ( data[1]["금액"]/100 + 1 )* engine.Graph_Frame.둘그래프.pSizeORIGEN.y
        if len( data ) > 2 and data[2]["금액"] < 0:
            engine.Graph_Frame.삼이름.text.text = data[2]["태그"] + "\n" + str(-data[2]["금액"]) + "%"
            engine.Graph_Frame.삼그래프.pSize보조.y = ( data[2]["금액"]/100 + 1 )* engine.Graph_Frame.삼그래프.pSizeORIGEN.y
        if len( data ) > 3 and data[3]["금액"] < 0:
            engine.Graph_Frame.넷이름.text.text = data[3]["태그"] + "\n" + str(-data[3]["금액"]) + "%"
            engine.Graph_Frame.넷그래프.pSize보조.y = ( data[3]["금액"]/100 + 1 )* engine.Graph_Frame.넷그래프.pSizeORIGEN.y
        if len( data ) > 4 and data[4]["금액"] < 0:
            engine.Graph_Frame.오이름.text.text = data[4]["태그"] + "\n" + str(-data[4]["금액"]) + "%"
            engine.Graph_Frame.오그래프.pSize보조.y = ( data[4]["금액"]/100 + 1 )* engine.Graph_Frame.오그래프.pSizeORIGEN.y
        if len( data ) > 0:
            지출 = engine.data.tool.plusData ( data, False )
            engine.Graph_Frame.전체이름.text.text = "전체\n" + str (-지출) + "%"
            engine.Graph_Frame.전체그래프.pSize보조.y = ( 지출/100 + 1 )* engine.Graph_Frame.전체그래프.pSizeORIGEN.y
    elif id == "PlusData":
        error = engine.data.PlusData ( 날자 = engine.Plus_Frame.날자글.text.text,
                                      금액 = engine.Plus_Frame.금액글.text.text,
                                      태그 = engine.Plus_Frame.태그글.text.text,
                                      내용 = engine.Plus_Frame.내용글.text.text)
        if error == "성공":
            Event_re ( id = "MakeGraph" ) # 그래프 최신화
            Color.ColorChanger ( engine , engine.root , Color.Color.c4,Color.Color.c3 , engine.Plus_Frame.큰바 , 20 )
            selected = int ( (engine.Plus_Frame.작은바.pStart.y - engine.Plus_Frame.창바.pStart.y) / 100 )
            engine.Plus_Frame.날자글.text.text = ""
            engine.Plus_Frame.금액글.text.text = ""
            engine.Plus_Frame.태그글.text.text = ""
            engine.Plus_Frame.내용글.text.text = ""
            engine.Plus_Frame.설명글.text.text = "저장이 되었습니다."
            if selected == 0: # 조회 항목이 보고 있는 것으로 업데이트
                id = "날자"
            elif selected == 1:
                id = "금액"
            elif selected == 2:
                id = "태그"
            elif selected == 3:
                id = "내용"
            engine.data.MakeViewData( "날자" )
            engine.Warning_Frame.창바.text.text = "" # 버튼 클릭으로 했을때, 저장했으므로 다시 쓰기 상태가 풀려야 함
        elif error[0:2] == "날자":
            engine.Plus_Frame.설명글.text.text = error
            Color.ColorChanger ( engine , engine.root , Color.Color.c2,Color.Color.c3 , engine.Plus_Frame.작은바 , 20 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c3,Color.Color.c2 , engine.Plus_Frame.큰바 , 20 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c2 , engine.Plus_Frame.창바 , 20 )
            Animation.Move ( engine.Plus_Frame.큰바 , engine , 20 , engine.Plus_Frame.큰바.pStart , Point ( 0 , 300 ) )
            Animation.Move ( engine.Plus_Frame.작은바 , engine , 15 , engine.Plus_Frame.작은바.pStart , Point ( 600 , 300 ) )
            Animation.Move ( engine.Plus_Frame.설명글 , engine , 25 , engine.Plus_Frame.설명글.pStart , Point ( 0 , 300 ) )
        elif error[0:2] == "금액":
            Color.ColorChanger ( engine , engine.root , Color.Color.c2,Color.Color.c3 , engine.Plus_Frame.작은바 , 20 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c3,Color.Color.c2 , engine.Plus_Frame.큰바 , 20 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c2 , engine.Plus_Frame.창바 , 20 )
            engine.Plus_Frame.설명글.text.text = error
            Animation.Move ( engine.Plus_Frame.큰바 , engine , 20 , engine.Plus_Frame.큰바.pStart , Point ( 0 , 400 ) )
            Animation.Move ( engine.Plus_Frame.작은바 , engine , 15 , engine.Plus_Frame.작은바.pStart , Point ( 600 , 400 ) )
            Animation.Move ( engine.Plus_Frame.설명글 , engine , 25 , engine.Plus_Frame.설명글.pStart , Point ( 0 , 400 ) )
        elif error[0:2] == "태그":
            Color.ColorChanger ( engine , engine.root , Color.Color.c2,Color.Color.c3 , engine.Plus_Frame.작은바 , 20 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c3,Color.Color.c2 , engine.Plus_Frame.큰바 , 20 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c2 , engine.Plus_Frame.창바 , 20 )
            engine.Plus_Frame.설명글.text.text = error
            Animation.Move ( engine.Plus_Frame.큰바 , engine , 20 , engine.Plus_Frame.큰바.pStart , Point ( 0 , 500 ) )
            Animation.Move ( engine.Plus_Frame.작은바 , engine , 15 , engine.Plus_Frame.작은바.pStart , Point ( 600 , 500 ) )
            Animation.Move ( engine.Plus_Frame.설명글 , engine , 25 , engine.Plus_Frame.설명글.pStart , Point ( 0 , 500 ) )
    elif id == "KeyEvent":
        if engine.Plus_Frame.enable == True:
            engine.ThreadStart( )
            print("실행된 char = ", args["char"])
            selected = int ( (engine.Plus_Frame.작은바.pStart.y - engine.Plus_Frame.창바.pStart.y) / 100 )
            args["char"] = engine.event.Tool.Filter ( args["char"] , int(selected/2) )
            if selected == 0:

                if args["char"] != "Eraser":
                    if args["char"] != "Enter":
                        if args["char"] != "Tab" and args["char"] != "Space":
                            engine.Plus_Frame.날자글.text.text = engine.Plus_Frame.날자글.text.text + args["char"]
                        else:
                            Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c3 , engine.Plus_Frame.작은바 , 15 )
                            Event_re( id = "추가.금액범위" )
                    else:
                        Event_re( id = "PlusData" )
                else:
                    Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c3 , engine.Plus_Frame.작은바 , 5 )
                    engine.Plus_Frame.날자글.text.text = engine.Plus_Frame.날자글.text.text[ 0 : len(engine.Plus_Frame.날자글.text.text) - 1 ]
            elif selected == 1:
                if args["char"] != "Eraser":
                    if args["char"] != "Enter":
                        if args["char"] != "Tab":
                            if args["char"] != "Space":
                                if engine.Plus_Frame.금액글.text.text == "":##아무것도 없을 경우 +를 추가합니다.
                                    Color.ColorChanger ( engine , engine.root , Color.Color.c4,Color.Color.c3 , engine.Plus_Frame.작은바 , 15 )
                                    engine.Plus_Frame.금액글.text.text = "+"
                                engine.Plus_Frame.금액글.text.text = engine.Plus_Frame.금액글.text.text + args["char"]
                            else:
                                if engine.Plus_Frame.금액글.text.text[0:1] == "+":
                                    Color.ColorChanger ( engine , engine.root , Color.Color.c4,Color.Color.c3 , engine.Plus_Frame.작은바 , 15 )
                                    engine.Plus_Frame.금액글.text.text = "-" + engine.Plus_Frame.금액글.text.text[1:]
                                else:
                                    Color.ColorChanger ( engine , engine.root , Color.Color.c4,Color.Color.c3 , engine.Plus_Frame.작은바 , 15 )
                                    engine.Plus_Frame.금액글.text.text = "+" + engine.Plus_Frame.금액글.text.text[1:]
                        else:
                            Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c3 , engine.Plus_Frame.작은바 , 15 )
                            Event_re( id = "추가.태그범위" )
                    else:
                        Event_re( id = "PlusData" )
                else:
                    Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c3 , engine.Plus_Frame.작은바 , 5 )
                    engine.Plus_Frame.금액글.text.text = engine.Plus_Frame.금액글.text.text[ 0 : 1] +engine.Plus_Frame.금액글.text.text[ 1 : len(engine.Plus_Frame.금액글.text.text) - 1 ]
            elif selected == 2:
                if args["char"] != "Eraser":
                    if args["char"] != "Enter":
                        if args["char"] != "Tab":
                            if args["char"] != "Space":
                                if engine.Plus_Frame.태그글.text.text == "":##아무것도 없을 경우 +를 추가합니다.
                                    engine.Plus_Frame.태그글.text.text = "#"
                                engine.Plus_Frame.태그글.text.text = engine.Plus_Frame.태그글.text.text + args["char"]
                            else:
                                if engine.Plus_Frame.태그글.text.text[0:1] == "#":
                                    engine.Plus_Frame.태그글.text.text = engine.Plus_Frame.태그글.text.text[1:]
                                else:
                                    engine.Plus_Frame.태그글.text.text = "#" + engine.Plus_Frame.태그글.text.text
                        else:
                            Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c3 , engine.Plus_Frame.작은바 , 15 )
                            Event_re( id = "추가.내용범위" )
                    else:
                        Event_re( id = "PlusData" )
                else:
                    Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c3 , engine.Plus_Frame.작은바 , 5 )
                    engine.Plus_Frame.태그글.text.text = engine.Plus_Frame.태그글.text.text[ 0 : len(engine.Plus_Frame.태그글.text.text) - 1 ]
            elif selected == 3:
                if args["char"] != "Eraser":
                    if args["char"] != "Enter":
                        if args["char"] != "Tab":
                            if args["char"] != "Space":
                                engine.Plus_Frame.내용글.text.text = engine.Plus_Frame.내용글.text.text + args["char"]
                            else:
                                engine.Plus_Frame.내용글.text.text = engine.Plus_Frame.내용글.text.text + " "
                        else:
                            Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c3 , engine.Plus_Frame.작은바 , 15 )
                            Event_re( id = "추가.날자범위" )
                    else:
                        Event_re( id = "PlusData" )
                else:
                    Color.ColorChanger ( engine , engine.root , Color.Color.c6,Color.Color.c3 , engine.Plus_Frame.작은바 , 5 )
                    engine.Plus_Frame.내용글.text.text = engine.Plus_Frame.내용글.text.text[ 0 : len(engine.Plus_Frame.내용글.text.text) - 1 ]
            engine.ThreadEnd()
            print("selected = ", selected)


           
    elif id == engine.Main_Frame.메인.id:
        Event_re ( id = "ButtonLock" )
        Color.ColorChanger ( engine , engine.root , engine.Main_Frame.메인.c , Color.Color.c3 , engine.Main_Frame.메인 , 10 )
        Color.ColorChanger ( engine , engine.root , engine.Main_Frame.내역.c , Color.Color.c6 , engine.Main_Frame.내역 , 10 )
        Color.ColorChanger ( engine , engine.root , engine.Main_Frame.추가.c , Color.Color.c6 , engine.Main_Frame.추가 , 10 )
        engine.root.after ( 3000 , _ButtonLock )
        _Closer ( 1 )
        if engine.Warning_Frame.창바.text.text == engine.controlbox.추가.삭제ment or engine.Warning_Frame.창바.text.text == engine.controlbox.추가.저장_다시쓰기ment or engine.Warning_Frame.창바.text.text == engine.controlbox.추가.새로만들기에러ment or engine.Warning_Frame.창바.text.text ==  engine.controlbox.내역.다시쓰기ment:
            engine.Warning_Frame.창바.text.text = engine.controlbox.추가.취소ment
            engine.Warning_Frame.Active( True , engine )
    elif id == engine.Main_Frame.내역.id:
        Event_re ( id = "ButtonLock" )
        Color.ColorChanger ( engine , engine.root , engine.Main_Frame.내역.c , Color.Color.c3 , engine.Main_Frame.내역 , 10 )
        Color.ColorChanger ( engine , engine.root , engine.Main_Frame.메인.c , Color.Color.c6 , engine.Main_Frame.메인 , 10 )
        Color.ColorChanger ( engine , engine.root , engine.Main_Frame.추가.c , Color.Color.c6 , engine.Main_Frame.추가 , 10 )
        engine.root.after ( 3000 , _ButtonLock )
        _Closer ( 2 )
        if engine.Warning_Frame.창바.text.text == engine.controlbox.추가.삭제ment or engine.Warning_Frame.창바.text.text == engine.controlbox.추가.저장_다시쓰기ment or engine.Warning_Frame.창바.text.text == engine.controlbox.추가.새로만들기에러ment or engine.Warning_Frame.창바.text.text ==  engine.controlbox.내역.다시쓰기ment:
            engine.Warning_Frame.창바.text.text = engine.controlbox.추가.취소ment
            engine.Warning_Frame.Active( True , engine )
    elif id == engine.Main_Frame.추가.id:
        Event_re ( id = "ButtonLock" )
        Color.ColorChanger ( engine , engine.root , engine.Main_Frame.추가.c , Color.Color.c3 , engine.Main_Frame.추가 , 10 )
        Color.ColorChanger ( engine , engine.root , engine.Main_Frame.메인.c , Color.Color.c6 , engine.Main_Frame.메인 , 10 )
        Color.ColorChanger ( engine , engine.root , engine.Main_Frame.내역.c , Color.Color.c6 , engine.Main_Frame.내역 , 10 )
        engine.root.after ( 3000 , _ButtonLock )
        _Closer ( 3 )
        
    elif id == "내역.이전글":
        if engine.View_Frame.이전글.text.text != '   ':
            engine.View_Frame.창바.c
            engine.View_Frame.큰바.c
            engine.View_Frame.작은바.c
            #Color.ColorChanger ( engine , engine.root , Color.Color.c6 , Color.Color.c2 , engine.View_Frame.창바 , 2 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c6 , Color.Color.c2 , engine.View_Frame.큰바 , 4 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c6 , Color.Color.c3 , engine.View_Frame.작은바,6 )

        engine.data.PageDown( )
        _ViewPage()
    elif id == "내역.다음글":
        if engine.View_Frame.다음글.text.text != "   ": 
            engine.View_Frame.창바.c
            engine.View_Frame.큰바.c
            engine.View_Frame.작은바.c
            #Color.ColorChanger ( engine , engine.root , Color.Color.c6 , Color.Color.c2 , engine.View_Frame.창바 , 2 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c6 , Color.Color.c2 , engine.View_Frame.큰바 , 4 )
            Color.ColorChanger ( engine , engine.root , Color.Color.c6 , Color.Color.c3 , engine.View_Frame.작은바,6 )
        engine.data.PageUp( )
        _ViewPage()
    elif id == "내역.날자범위":
        Animation.Move ( engine.View_Frame.다음글 , engine , 15 , engine.View_Frame.다음글.pStart , Point (1200,300) )
        Animation.Move ( engine.View_Frame.이전글 , engine , 15 , engine.View_Frame.이전글.pStart , Point (0,300) )
        Animation.Move ( engine.View_Frame.큰바 , engine , 15 , engine.View_Frame.큰바.pStart , Point (0,300) )
        Animation.Move ( engine.View_Frame.작은바 , engine , 15 , engine.View_Frame.작은바.pStart , Point (500,300) )
        engine.data.MakeViewData( "날자" )
        _ViewPage()
    elif id == "내역.금액범위":
        Animation.Move ( engine.View_Frame.다음글 , engine , 15 , engine.View_Frame.다음글.pStart , Point (1200,400) )
        Animation.Move ( engine.View_Frame.이전글 , engine , 15 , engine.View_Frame.이전글.pStart , Point (0,400) )
        Animation.Move ( engine.View_Frame.큰바 , engine , 15 , engine.View_Frame.큰바.pStart , Point (0,400) )
        Animation.Move ( engine.View_Frame.작은바 , engine , 15 , engine.View_Frame.작은바.pStart , Point (500,400) )
        engine.data.MakeViewData( "금액" )
        _ViewPage()
    elif id == "내역.태그범위":
        Animation.Move ( engine.View_Frame.다음글 , engine , 15 , engine.View_Frame.다음글.pStart , Point (1200,500) )
        Animation.Move ( engine.View_Frame.이전글 , engine , 15 , engine.View_Frame.이전글.pStart , Point (0,500) )
        Animation.Move ( engine.View_Frame.큰바 , engine , 15 , engine.View_Frame.큰바.pStart , Point (0,500) )
        Animation.Move ( engine.View_Frame.작은바 , engine , 15 , engine.View_Frame.작은바.pStart , Point (500,500) )
        engine.data.MakeViewData( "태그" )
        _ViewPage()
    elif id == "내역.내용범위":
        Animation.Move ( engine.View_Frame.다음글 , engine , 15 , engine.View_Frame.다음글.pStart , Point (1200,600) )
        Animation.Move ( engine.View_Frame.이전글 , engine , 15 , engine.View_Frame.이전글.pStart , Point (0,600) )
        Animation.Move ( engine.View_Frame.큰바 , engine , 15 , engine.View_Frame.큰바.pStart , Point (0,600) )
        Animation.Move ( engine.View_Frame.작은바 , engine , 15 , engine.View_Frame.작은바.pStart , Point (500,600) )
        engine.data.MakeViewData( "내용" )
        _ViewPage()
    elif id == "추가.날자범위":
        engine.Plus_Frame.설명글.text.text = "8글자를 입력하세요!"
        Animation.Move ( engine.Plus_Frame.큰바 , engine , 15 , engine.Plus_Frame.큰바.pStart , Point ( 0 , 300 ) )
        Animation.Move ( engine.Plus_Frame.작은바 , engine , 15 , engine.Plus_Frame.작은바.pStart , Point ( 600 , 300 ) )
        Animation.Move ( engine.Plus_Frame.설명글 , engine , 15 , engine.Plus_Frame.설명글.pStart , Point ( 0 , 300 ) )
    elif id == "추가.금액범위":
        engine.Plus_Frame.설명글.text.text = "스페이스바로 금액이 +,-를 설정할수 있어요!"
        Animation.Move ( engine.Plus_Frame.큰바 , engine , 15 , engine.Plus_Frame.큰바.pStart , Point ( 0 , 400 ) )
        Animation.Move ( engine.Plus_Frame.작은바 , engine , 15 , engine.Plus_Frame.작은바.pStart , Point ( 600 , 400 ) )
        Animation.Move ( engine.Plus_Frame.설명글 , engine , 15 , engine.Plus_Frame.설명글.pStart , Point ( 0 , 400 ) )
    elif id == "추가.태그범위":
        engine.Plus_Frame.설명글.text.text = "4글자 이내로 입력하세요!"
        Animation.Move ( engine.Plus_Frame.큰바 , engine , 15 , engine.Plus_Frame.큰바.pStart , Point ( 0 , 500 ) )
        Animation.Move ( engine.Plus_Frame.작은바 , engine , 15 , engine.Plus_Frame.작은바.pStart , Point ( 600 , 500 ) )
        Animation.Move ( engine.Plus_Frame.설명글 , engine , 15 , engine.Plus_Frame.설명글.pStart , Point ( 0 , 500 ) )
    elif id == "추가.내용범위":
        engine.Plus_Frame.설명글.text.text = "자유롭게 입력하세요!"
        Animation.Move ( engine.Plus_Frame.큰바 , engine , 15 , engine.Plus_Frame.큰바.pStart , Point ( 0 , 600 ) )
        Animation.Move ( engine.Plus_Frame.작은바 , engine , 15 , engine.Plus_Frame.작은바.pStart , Point ( 600 , 600 ) )
        Animation.Move ( engine.Plus_Frame.설명글 , engine , 15 , engine.Plus_Frame.설명글.pStart , Point ( 0 , 600 ) )    
    elif id == "메인.종료": # 4
        Event_re ( id = "ButtonLock" )
        engine.root.after ( 1600 , _ButtonLock )
        _Closer ( 4 )
        #컨트롤박스_조회.다시쓰기
    elif id[0:5] == "컨트롤박스":
        Color.ColorChanger ( engine , engine.root , Color.Color.c4 , Color.Color.c1 , args["Object"] , 10 )
        engine.root.after ( 400 , engine.controlbox.AnimationUp )
        if id[6:8] == "조회":
            if id[9:] == "다시쓰기":
                print("다시쓰기를 클릭함")
                engine.Warning_Frame.창바.text.text = engine.controlbox.내역.다시쓰기ment
                engine.Warning_Frame.Active( True , engine )
            elif id[9:] == "찾기":
                engine.Warning_Frame.창바.text.text = engine.controlbox.내역.찾기ment
                engine.Warning_Frame.Active( True , engine )
            elif id[9:] == "삭제":
                engine.Warning_Frame.창바.text.text = engine.controlbox.내역.삭제ment
                engine.Warning_Frame.Active( True , engine )
        elif id[6:8] == "추가":# 내역에서 넘오는 경우가 있어 조금 김
            if id[9:] == "삭제":
                if engine.Warning_Frame.창바.text.text == engine.controlbox.내역.다시쓰기ment: # 내역에서 다시쓰기로 넘어온 경우가 있으므로
                    engine.Warning_Frame.창바.text.text = engine.controlbox.추가.삭제ment
                    engine.Warning_Frame.Active( True , engine )
                elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.삭제ment:
                    engine.Warning_Frame.Active( True , engine )

                elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.새로만들기에러ment or engine.Warning_Frame.창바.text.text == engine.controlbox.추가.저장_다시쓰기ment:# 새로 만들기가 넘어운 경우로 받았을때
                    engine.Warning_Frame.창바.text.text = engine.controlbox.추가.삭제ment
                    engine.Warning_Frame.Active( True , engine )
                else:
                    engine.Warning_Frame.창바.text.text = engine.controlbox.추가.삭제에러ment

                    engine.Warning_Frame.Active( True , engine )
            elif id[9:] == "새로만들기":
                if engine.Warning_Frame.창바.text.text == engine.controlbox.내역.다시쓰기ment: # 내역에서 다시쓰기로 넘어온 경우때문에
                    engine.Warning_Frame.창바.text.text = engine.controlbox.추가.새로만들기에러ment
                    engine.Warning_Frame.Active( True , engine )
                elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.새로만들기에러ment:
                    engine.Warning_Frame.Active( True , engine )
                elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.삭제ment or engine.Warning_Frame.창바.text.text == engine.controlbox.추가.저장_다시쓰기ment:
                    engine.Warning_Frame.창바.text.text = engine.controlbox.추가.새로만들기에러ment
                    engine.Warning_Frame.Active( True , engine )
                else:
                    engine.Warning_Frame.창바.text.text = engine.controlbox.추가.새로만들기ment
                    engine.Warning_Frame.Active( True , engine )
            elif id[9:] == "저장":
                if engine.Warning_Frame.창바.text.text == engine.controlbox.내역.다시쓰기ment:
                    engine.Warning_Frame.창바.text.text = engine.controlbox.추가.저장_다시쓰기ment
                    engine.Warning_Frame.Active( True , engine )
                elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.저장_다시쓰기ment:
                    engine.Warning_Frame.Active ( True , engine )
                elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.삭제ment or engine.Warning_Frame.창바.text.text == engine.controlbox.추가.새로만들기에러ment:
                    engine.Warning_Frame.창바.text.text = engine.controlbox.추가.저장_다시쓰기ment
                    engine.Warning_Frame.Active( True , engine )
                else:
                    engine.Warning_Frame.창바.text.text = engine.controlbox.추가.저장ment
                    engine.Warning_Frame.Active( True , engine )

        else:
            engine.Warning_Frame.창바.text.text = "구현중입니다."
            engine.Warning_Frame.Active( True , engine )
    elif id[0:3] == "경고창":
        engine.Warning_Frame.Active( False , engine )
        engine.Warning_Frame.Enable ( False )
        if engine.Warning_Frame.창바.text.text == engine.start_ment: ### 시작시 나오는 알림창 선택시
            Event_re ( id = "MakeGraph" )
        elif id[4:] == "확인버튼":
            if engine.Warning_Frame.창바.text.text == engine.controlbox.내역.삭제ment:
                engine.data.delete()
                engine.data.reMakeViewData()
                engine.data.MakeList()
                _ViewPage()
            elif engine.Warning_Frame.창바.text.text == engine.controlbox.내역.다시쓰기ment:
                engine.Plus_Frame.날자글.text.text = str(engine.View_Frame.날자글.text.text)
                engine.Plus_Frame.금액글.text.text = str(engine.View_Frame.금액글.text.text)
                engine.Plus_Frame.태그글.text.text = engine.View_Frame.태그글.text.text
                engine.Plus_Frame.내용글.text.text = engine.View_Frame.내용글.text.text
                
                Color.ColorChanger ( engine , engine.root , engine.Main_Frame.추가.c , Color.Color.c3 , engine.Main_Frame.추가 , 10 )
                Color.ColorChanger ( engine , engine.root , engine.Main_Frame.메인.c , Color.Color.c6 , engine.Main_Frame.메인 , 10 )
                Color.ColorChanger ( engine , engine.root , engine.Main_Frame.내역.c , Color.Color.c6 , engine.Main_Frame.내역 , 10 )
                _Closer ( 3 )

            elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.새로만들기ment:
                engine.Plus_Frame.날자글.text.text = ""
                engine.Plus_Frame.금액글.text.text = ""
                engine.Plus_Frame.태그글.text.text = ""
                engine.Plus_Frame.내용글.text.text = ""
                engine.Warning_Frame.창바.text.text = ""
                engine.Plus_Frame.설명글.text.text = "새로 작성해주세요."
            elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.새로만들기에러ment:
                engine.Plus_Frame.날자글.text.text = ""
                engine.Plus_Frame.금액글.text.text = ""
                engine.Plus_Frame.태그글.text.text = ""
                engine.Plus_Frame.내용글.text.text = ""
                engine.Warning_Frame.창바.text.text = ""
                engine.Plus_Frame.설명글.text.text = "새로 작성해주세요"
            elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.삭제ment:
                engine.Warning_Frame.창바.text.text = ""
                engine.data.delete()
                engine.data.reMakeViewData()
                engine.data.MakeList()
                _ViewPage()
                engine.root.update()
                engine.root.after ( 650 )
                engine.root.update()
                engine.Warning_Frame.창바.text.text = engine.controlbox.추가.삭제완료ment
                engine.Warning_Frame.Active ( True , engine )
            elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.저장_다시쓰기ment or engine.Warning_Frame.창바.text.text == engine.controlbox.추가.저장ment:
                Event_re( id = "PlusData" )
            elif engine.Warning_Frame.창바.text.text == engine.controlbox.추가.취소ment:
                engine.Plus_Frame.날자글.text.text = ""
                engine.Plus_Frame.금액글.text.text = ""
                engine.Plus_Frame.태그글.text.text = ""
                engine.Plus_Frame.내용글.text.text = ""
                engine.Warning_Frame.창바.text.text = ""
                
Beispiel #53
0
class Butterfly():
	def __init__(self, x, y, color = (255, 255, 255), objectList = [], spriteList = []):
		self.objectList = objectList
		self.spriteList = spriteList

		self.rect = pygame.Rect(x, y, 15, 15)
		self.screen = pygame.display.get_surface()

		self.butterflyAnim = Animation("butterfly", 8)
		self.butterflyAnim.updateColor(color)
		self.butterflyAnim.setFrameRange(1, 8);
		self.butterflyAnim.setCurrentFrame(randint(1, 8))

		self.sprite = pygame.sprite.RenderPlain(self.butterflyAnim)

		self.butterflyAnim.playAnim()

		self.area = self.screen.get_rect()
		self.color = color

		self.floorLevel = self.screen.get_height() - self.rect.h

		self.movingLeft = False
		self.movingRight = False
		self.movingUp = False
		self.movingDown = False

		self.degree = randint(0, 360)
		self.speed = 4

		self.detlaUpdate = 0

		self.collide = False

		self.movePos = [0,0.01]

	def update(self):
		if(self.detlaUpdate == 1):
			self.detlaUpdate = 0

			limitBottom = self.degree - 20
			limitTop = self.degree + 20

			self.degree = randint(limitBottom, limitTop)

			self.degree = self.degree % 360

			if(randint(0, 1) == 0):
				if(self.speed < 6):
					self.speed += 1

			else:
				if(self.speed > 2):
					self.speed -= 1

			self.movePos[0] = math.cos(math.radians(self.degree)) * self.speed
			self.movePos[1] = math.sin(math.radians(self.degree)) * self.speed

			#self.movePos[0] = randint(-8, 8)
			#self.movePos[1] = randint(-8, 8)

			self.checkForCollision()

			newpos = self.rect.move(self.movePos)
			if self.area.contains(newpos) and not self.collide:
				self.rect = newpos

			self.butterflyAnim.getRect().x = self.rect.x
			self.butterflyAnim.getRect().y = self.rect.y

			if self.degree >= 90 and self.degree <= 240:
				self.movingLeft = True
				self.movingRight = False
			else:
				self.movingLeft = False
				self.movingRight = True

			if self.degree >= 0 and self.degree <= 180:
				self.movingDown = True
				self.movingUp = False
			else:
				self.movingDown = False
				self.movingUp = True

		else:
			self.detlaUpdate += 1

		self.butterflyAnim.update()
		self.sprite.update()
		self.sprite.draw(self.screen)

		pygame.event.pump()

	def collisionDetection(self, obj, rabbit = False):
		#FLEE BEHAVIOR !!!

		objCenterX = obj.rect.x + obj.rect.w/2
		objCenterY = obj.rect.y + obj.rect.h/2

		butterflyCenterX = self.rect.x + self.rect.w/2
		butterflyCenterY = self.rect.y + self.rect.h/2

		dist = math.fabs(math.sqrt(((objCenterX - butterflyCenterX) * (objCenterX - butterflyCenterX)) + ((objCenterY - butterflyCenterY) * (objCenterY - butterflyCenterY))))
		
		if dist < 50:
			distX = math.fabs(objCenterX - butterflyCenterX)
			angle = math.degrees(math.acos(distX/dist))

			if (objCenterX <= butterflyCenterX) and (objCenterY <= butterflyCenterY):
				angle = 240 - angle

			elif (objCenterX > butterflyCenterX) and (objCenterY <= butterflyCenterY):
				angle = 360 - angle

			elif (objCenterX <= butterflyCenterX) and (objCenterY > butterflyCenterY):
				angle = 180 - angle

			angle += 180
			angle = angle % 360

			self.degree = int(angle)

		#FLEE BEHAVIOR !!!

		# if (self.rect.x < (obj.rect.x + obj.rect.w)) and (obj.rect.x < self.rect.x):
		# 	if (self.rect.y + self.rect.h) > (obj.rect.y + 1):
		# 		if self.rect.y < (obj.rect.y + obj.rect.h):
		# 			self.movePos[0] = 5

		# if (obj.rect.x < (self.rect.x + self.rect.w)) and (obj.rect.x > self.rect.x):
		# 	if (self.rect.y + self.rect.h) > (obj.rect.y + 1):
		# 		if self.rect.y < (obj.rect.y + obj.rect.h):
		# 			self.movePos[0] = -5

		# if (self.rect.y <= (obj.rect.y + obj.rect.h)) and (obj.rect.y <= self.rect.y):
		# 	if (self.rect.x + self.rect.w) > (obj.rect.x + 3):
		# 		if self.rect.x < (obj.rect.x + obj.rect.w - 5):
		# 			self.movePos[1] = 5

		# if ((self.rect.y + self.rect.h) >= obj.rect.y) and (self.rect.y <= obj.rect.y):
		# 	if (self.rect.x + self.rect.w) > (obj.rect.x + 3):
		# 		if self.rect.x < (obj.rect.x + obj.rect.w - 5):
		# 			if self.movePos[1] >= 0:
		# 				self.rect.y = obj.rect.y - self.rect.h
		# 				self.movePos[1] = -5

	def screenCollisionDetection(self):
		butterflyCenterX = self.rect.x + self.rect.w/2
		butterflyCenterY = self.rect.y + self.rect.h/2

		distBorder = butterflyCenterX
		if distBorder < 10:
			self.degree = 0

		if (butterflyCenterY) < distBorder:
			distBorder = butterflyCenterY
			if distBorder < 10:
				self.degree = 90

		if (self.screen.get_rect().w - butterflyCenterX) < distBorder:
			distBorder = self.screen.get_rect().w - butterflyCenterX
			if distBorder < 10:
				self.degree = 180

		if (self.screen.get_rect().h - butterflyCenterY) < distBorder:
			distBorder = self.screen.get_rect().h - butterflyCenterY
			if distBorder < 10:
				self.degree = 240

	def checkForCollision(self):
		#if not self.movingLeft and not self.movingRight and self.movePos[1] == 0 and self.velocity == 0:
		#	return

		for obj in self.objectList:
			if obj.getType() is not "carrot":
				self.collisionDetection(obj, False)

		self.screenCollisionDetection()

		#for rabbit in self.rabbitList:
		#	self.collisionDetection(rabbit, True)
 	
 	def moveLeftStart(self):
 		self.movingLeft = True
 		self.movingRight = False

 	def moveLeftStop(self):
 		self.movingLeft = False
 		self.movePos[0] = 0

 	def moveRightStart(self):
 		self.movingRight = True
 		self.movingLeft = False
	
	def moveRightStop(self):
		self.movingRight = False
		self.movePos[0] = 0

	def getAnim(self):
		return self.butterflyAnim
Beispiel #54
0
import VRScript
import Animation

ghost = Animation.AnimationObject("Ghost")
ghost.LoadAnimation("Ghosts\\005-03end.fbx", [90, 0, 0],
                    VRScript.Math.Vector(1, 1, 1))
ghost.Play(VRScript.Core.PlayMode.Loop)
Beispiel #55
0

App.setActiveDocument("Unnamed")
App.ActiveDocument=App.getDocument("Unnamed")
Gui.ActiveDocument=Gui.getDocument("Unnamed")
import Animation
Animation.createManager()

App.ActiveDocument.addObject("Part::Box","Box")
App.ActiveDocument.addObject("Part::Box","Box")
App.ActiveDocument.addObject("Part::Box","Box")
App.ActiveDocument.addObject("Part::Box","Box")
App.ActiveDocument.addObject("Part::Cone","Cone")


import Placer

s1=Placer.createPlacer("B1")
s1.target=App.ActiveDocument.Box001

s2=Placer.createPlacer("B2")
s2.target=App.ActiveDocument.Box002
s2.y="10"

s3=Placer.createPlacer("B3")
s3.target=App.ActiveDocument.Box003
s3.y="20"


import Diagram
c=Diagram.createDiagram("dia","0.200*time","0.2*(0.01*time-0.5)**2","10+time+1","-10*time")
Beispiel #56
0
def old__process_file_withSpeech_byGroup(filename,
                                         window=240,
                                         window_step=120):

    if not '_p0.bvh' in filename:
        return

    #Load speech info
    seqName = os.path.basename(filename)
    speech_fileName = seqName[:-7] + '.pkl'
    speechPath = './panopticDB_pkl_speech_hagglingProcessed/' + speech_fileName
    speechData_raw = pickle.load(open(speechPath, "rb"))

    positions_list = list()
    speechData_list = list()

    for pIdx in range(0, 3):
        """ Do FK """
        if pIdx == 0:
            anim, names, frametime = BVH.load(filename)
        else:
            newFileName = filename.replace('_p0.bvh', '_p{0}.bvh'.format(pIdx))
            anim, names, frametime = BVH.load(newFileName)

        if pIdx == 0:  #_p0.bvh' in filename:
            speechData = speechData_raw['speechData'][0]
        elif pIdx == 1:  #'_p1.bvh' in filename:
            speechData = speechData_raw['speechData'][1]
        elif pIdx == 2:  #'_p2.bvh' in filename:
            speechData = speechData_raw['speechData'][2]

        # """ Convert to 60 fps """
        # anim = anim[::2]
        # Origianl Human3.6 has 50 fps. So, no smapling is done
        """ Do FK """
        global_positions = Animation.positions_global(anim)
        """ Remove Uneeded Joints """
        positions = global_positions[:,
                                     np.array([
                                         0, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13,
                                         15, 16, 18, 19, 20, 22, 25, 26, 27, 29
                                     ])]
        """ Put on Floor """
        fid_l, fid_r = np.array([4, 5]), np.array([8, 9])
        foot_heights = np.minimum(positions[:, fid_l, 1],
                                  positions[:, fid_r, 1]).min(axis=1)
        floor_height = softmin(foot_heights, softness=0.5, axis=0)

        positions[:, :, 1] -= floor_height
        """ Add Reference Joint """
        trajectory_filterwidth = 3
        reference = positions[:, 0] * np.array([1, 0, 1])
        reference = filters.gaussian_filter1d(reference,
                                              trajectory_filterwidth,
                                              axis=0,
                                              mode='nearest')
        positions = np.concatenate([reference[:, np.newaxis], positions],
                                   axis=1)
        """ Get Foot Contacts """
        velfactor, heightfactor = np.array([0.05, 0.05]), np.array([3.0, 2.0])

        feet_l_x = (positions[1:, fid_l, 0] - positions[:-1, fid_l, 0])**2
        feet_l_y = (positions[1:, fid_l, 1] - positions[:-1, fid_l, 1])**2
        feet_l_z = (positions[1:, fid_l, 2] - positions[:-1, fid_l, 2])**2
        feet_l_h = positions[:-1, fid_l, 1]
        feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor) &
                  (feet_l_h < heightfactor)).astype(np.float)

        feet_r_x = (positions[1:, fid_r, 0] - positions[:-1, fid_r, 0])**2
        feet_r_y = (positions[1:, fid_r, 1] - positions[:-1, fid_r, 1])**2
        feet_r_z = (positions[1:, fid_r, 2] - positions[:-1, fid_r, 2])**2
        feet_r_h = positions[:-1, fid_r, 1]
        feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor) &
                  (feet_r_h < heightfactor)).astype(np.float)
        """ Get Root Velocity """
        velocity = (positions[1:, 0:1] - positions[:-1, 0:1]).copy()
        """ Remove Translation """
        positions[:, :, 0] = positions[:, :, 0] - positions[:, 0:1, 0]
        positions[:, :, 2] = positions[:, :, 2] - positions[:, 0:1, 2]
        """ Get Forward Direction """
        sdr_l, sdr_r, hip_l, hip_r = 14, 18, 2, 6
        across1 = positions[:, hip_l] - positions[:, hip_r]
        across0 = positions[:, sdr_l] - positions[:, sdr_r]
        across = across0 + across1
        across = across / np.sqrt((across**2).sum(axis=-1))[..., np.newaxis]

        direction_filterwidth = 20
        forward = np.cross(across, np.array([[0, 1, 0]]))
        forward = filters.gaussian_filter1d(forward,
                                            direction_filterwidth,
                                            axis=0,
                                            mode='nearest')
        forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]
        """ Remove Y Rotation """
        target = np.array([[0, 0, 1]]).repeat(len(forward), axis=0)
        rotation = Quaternions.between(forward, target)[:, np.newaxis]
        positions = rotation * positions
        """ Get Root Rotation """
        velocity = rotation[1:] * velocity
        rvelocity = Pivots.from_quaternions(rotation[1:] * -rotation[:-1]).ps
        """ Add Velocity, RVelocity, Foot Contacts to vector """
        positions = positions[:-1]
        positions = positions.reshape(len(positions), -1)
        positions = np.concatenate([positions, velocity[:, :, 0]], axis=-1)
        positions = np.concatenate([positions, velocity[:, :, 2]], axis=-1)
        positions = np.concatenate([positions, rvelocity], axis=-1)
        positions = np.concatenate([positions, feet_l, feet_r], axis=-1)

        speechData_list.append(speechData)  #Save speech info
        positions_list.append(positions)  #Save skeleton info

    if len(positions_list[0]) != len(positions_list[1]): raise Exception()
    if len(positions_list[1]) != len(positions_list[2]): raise Exception()

    if len(speechData_list[0]) != len(speechData_list[1]): raise Exception()
    if len(speechData_list[1]) != len(speechData_list[2]): raise Exception()
    """ Slide over windows """
    windows = [list(), list(), list()]
    windows_speech = [list(), list(), list()]

    print("skelSize {0} vs speechSize {1}".format(
        positions.shape[0], speechData['indicator'].shape[0]))
    for j in range(0, len(positions) - window // 8, window_step):

        for pIdx in range(len(positions_list)):
            """ If slice too small pad out by repeating start and end poses """
            slice = positions_list[pIdx][j:j + window]
            if len(slice) < window:
                break
                # left  = slice[:1].repeat((window-len(slice))//2 + (window-len(slice))%2, axis=0)
                # left[:,-7:-4] = 0.0
                # right = slice[-1:].repeat((window-len(slice))//2, axis=0)
                # right[:,-7:-4] = 0.0
                # slice = np.concatenate([left, slice, right], axis=0)

            if len(slice) != window: raise Exception()

            windows[pIdx].append(slice)

            # """ Find Class """
            # cls = -1
            # if filename.startswith('hdm05'):
            #     cls_name = os.path.splitext(os.path.split(filename)[1])[0][7:-8]
            #     cls = class_names.index(class_map[cls_name]) if cls_name in class_map else -1
            # if filename.startswith('styletransfer'):
            #     cls_name = os.path.splitext(os.path.split(filename)[1])[0]
            #     cls = np.array([
            #         styletransfer_motions.index('_'.join(cls_name.split('_')[1:-1])),
            #         styletransfer_styles.index(cls_name.split('_')[0])])
            cls = speechData_list[pIdx]['indicator'][j:j + window]
            windows_speech[pIdx].append(cls)

    return windows, windows_speech
Beispiel #57
0
class Duke(Enemy):
	x = 6
	y = 3

	health = 100
	hurtDistance = 1.3

	def __init__(self, textures, sounds):
		self.texture = textures["bosses"]["duke"].subsurface(0, 128, 160, 128)
		self.sounds = sounds
		self.textures = textures

		self.frames = [
			textures["bosses"]["duke"].subsurface(160, 128, 160, 128),
			textures["bosses"]["duke"].subsurface(160, 0, 160, 128),
			textures["bosses"]["duke"].subsurface(0, 0, 160, 128)
		]

		self.tearTextures = textures["tears"]
		self.tearSounds = sounds["tear"]

		self.animation = Animation(self.frames, 0.5)

		self.textures = textures

		self.lastShot = -1

		self.flies = []
		self.animating = False

	def die(self):
		self.dead = True

	def render(self, surface, time, character, nodes, paths, bounds, obsticals):

		# Blit head
		if not self.dead:
			if not self.animating:
				surface.blit(self.texture, (GRIDX+GRATIO*self.x-284/4 +10, GRIDY+GRATIO*self.y-320/4))
			else:
				surface.blit(self.animation.render(time), (GRIDX+GRATIO*self.x-284/4 + 10, GRIDY+GRATIO*self.y-320/4))

			dx = character.x-(GRIDX+GRATIO*self.x)
			dy = character.y-(GRIDY+GRATIO*self.y)
			dist = sqrt(dx**2+dy**2)

			self.x += (dx/dist)/60
			self.y += (dy/dist)/60
		
			if time-self.lastShot >= 3:
				self.lastShot = time
				self.animating = False
				self.flies.append(Fly((self.x+randint(-1, 1), self.y), [self.sounds["deathBurst"]], self.textures["enemies"]["fly"]))
			elif time-self.lastShot >= 2.5:
				self.animation.reset(time)
				self.animating = True

			self.checkHurt(character, time)

		for fly in self.flies[:]:
			if not fly.render(surface, time, character, nodes, paths, bounds, obsticals):
				self.flies.remove(fly)

		if len(self.flies) > 0:
			return True

		return not self.dead
Beispiel #58
0
def selectChar(screen):
    selection = [1, 1]
    continuer = True
    images = [[] for i in range(6)]
    characters = [0, -1, 1]
    listPerso = ["Goku", "Gohan", "Picolo", "Végéta", "Freezer", "Cell"]
    loadImages(images)
    animP1 = Animation.Animation(True)
    animP1._getAll("Res/Goku/AnimNormale", 60, True, [60, 80])
    animP1._setPos([120, 248 - animP1._getFrame().get_size()[1]])
    fontObj = pygame.font.SysFont("Comic Sans MS", 24)

    animP2 = Animation.Animation()
    animP2._set([], [])

    afficherMenu(selection, screen, images)
    while continuer:
        for event in pygame.event.get():
            if event.type == QUIT:
                return ["Quit"]
            elif event.type == KEYDOWN:
                if event.key == K_UP:
                    if selection[1] > 1:
                        selection[1] -= 1
                    else:
                        selection[0] = 1
                    if characters[2] == 1:
                        animP1._getAll(
                            "Res/" + listPerso[(selection[1] - 1) * 3 +
                                               selection[0] - 1] +
                            "/AnimNormale", 60, True)
                        animP1._setPos(
                            [120, 248 - animP1._getFrame().get_size()[1]])
                    else:
                        animP2._getAll(
                            "Res/" + listPerso[(selection[1] - 1) * 3 +
                                               selection[0] - 1] +
                            "/AnimNormale", 60, False)
                        animP2._setPos(
                            [550, 248 - animP2._getFrame().get_size()[1]])
                elif event.key == K_DOWN:
                    if selection[1] < 2:
                        selection[1] += 1
                    else:
                        selection[0] = 3
                    if characters[2] == 1:
                        animP1._getAll(
                            "Res/" + listPerso[(selection[1] - 1) * 3 +
                                               selection[0] - 1] +
                            "/AnimNormale", 60, True)
                        animP1._setPos(
                            [120, 248 - animP1._getFrame().get_size()[1]])
                    else:
                        animP2._getAll(
                            "Res/" + listPerso[(selection[1] - 1) * 3 +
                                               selection[0] - 1] +
                            "/AnimNormale", 60, False)
                        animP2._setPos(
                            [550, 248 - animP2._getFrame().get_size()[1]])
                elif event.key == K_LEFT:
                    if selection[0] > 1:
                        selection[0] -= 1
                        if characters[2] == 1:
                            animP1._getAll(
                                "Res/" + listPerso[(selection[1] - 1) * 3 +
                                                   selection[0] - 1] +
                                "/AnimNormale", 60, True)
                            animP1._setPos(
                                [120, 248 - animP1._getFrame().get_size()[1]])
                        else:
                            animP2._getAll(
                                "Res/" + listPerso[(selection[1] - 1) * 3 +
                                                   selection[0] - 1] +
                                "/AnimNormale", 60, False)
                            animP2._setPos(
                                [550, 248 - animP2._getFrame().get_size()[1]])
                elif event.key == K_RIGHT:
                    if selection[0] < 3:
                        selection[0] += 1
                        if characters[2] == 1:
                            animP1._getAll(
                                "Res/" + listPerso[(selection[1] - 1) * 3 +
                                                   selection[0] - 1] +
                                "/AnimNormale", 60, True)
                            animP1._setPos(
                                [120, 248 - animP1._getFrame().get_size()[1]])
                        else:
                            animP2._getAll(
                                "Res/" + listPerso[(selection[1] - 1) * 3 +
                                                   selection[0] - 1] +
                                "/AnimNormale", 60, False)
                            animP2._setPos(
                                [550, 248 - animP2._getFrame().get_size()[1]])
                elif event.key == K_RETURN or K_KP_ENTER:
                    if characters[2] < 2:
                        characters[2] += 1
                        animP2._getAll(
                            "Res/" + listPerso[(selection[1] - 1) * 3 +
                                               selection[0] - 1] +
                            "/AnimNormale", 60, False)
                        animP2._setPos(
                            [550, 248 - animP2._getFrame().get_size()[1]])
                    elif characters[2] == 2:
                        retChars = [
                            listPerso[characters[0]], listPerso[characters[1]]
                        ]
                        return ["Battle", retChars]
                if characters[2] <= 1:
                    characters[0] = ((selection[1] - 1) * 3) + selection[0] - 1
                elif characters[2] == 2:
                    characters[1] = ((selection[1] - 1) * 3) + selection[0] - 1

        afficherMenu(selection, screen, images)

        P1Txt = fontObj.render(listPerso[characters[0]], False,
                               (255, 255, 255))
        screen.blit(P1Txt, (10, 0))
        animP1._update()
        animP1._draw(screen)
        if characters[2] > 1:
            P2Txt = fontObj.render(listPerso[characters[1]], False,
                                   (255, 255, 255))
            screen.blit(P2Txt, (500, 0))
        animP2._update()
        animP2._draw(screen)
        pygame.display.update()
# plt.plot(time, pe_list)
# plt.ylabel('Potential Energy')
# plt.title('Potential Energy Plot')
# plt.xlabel('Time Units')
# plt.savefig('prob3_pe.png')
# plt.show(block=True)


# ke plot
# plt.clf()
# plt.plot(time, ke_list)
# plt.xlabel('Time Units')
# plt.ylabel('Kinetic Energy')
# plt.title('Kinetic Energy Plot')
# plt.savefig('prob3_ke.png')
# plt.show(block=True)


# pressure plot
#plt.figure(2)
# plt.clf()
# plt.plot(time, pressure_list)
# plt.xlabel('Time Units')
# plt.ylabel('Pressure Relation')
# plt.title('Pressure Relationship Plot')
# plt.savefig('prob3_pressure.png')
# plt.show(block=True)

print 'Starting animation'
Animation.show_positions(positions, DELTA_T, NUM_TIMESTEPS, FRAME_RATE, save_file_path='sled_movie')
Beispiel #60
0
def process_file(filename,
                 window=240,
                 window_step=120,
                 export_trajectory=False):

    anim, names, frametime = BVH.load(filename)
    """ Subsample to 60 fps """
    anim = anim[::2]
    """ Do FK """
    global_xforms = Animation.transforms_global(anim)  # intermediate
    global_positions = global_xforms[:, :, :3, 3] / global_xforms[:, :, 3:, 3]
    global_rotations = Quaternions.from_transforms(global_xforms)
    """ Remove Uneeded Joints """  #>># done post-hoc in PFNN
    used_joints = np.array([
        0, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 15, 16, 18, 19, 20, 22, 25, 26, 27,
        29
    ])

    positions = global_positions[:, used_joints]
    global_rotations = global_rotations[:, used_joints]
    # ________________________________________________________
    """ Put on Floor """
    positions[:, :, 1] -= positions[:, :, 1].min()
    """ Get Foot Contacts """
    if True:
        velfactor, heightfactor = np.array([0.05, 0.05]), np.array([3.0, 2.0])

        fid_l, fid_r = np.array([3, 4]), np.array([7, 8])
        feet_l_x = (positions[1:, fid_l, 0] - positions[:-1, fid_l, 0])**2
        feet_l_y = (positions[1:, fid_l, 1] - positions[:-1, fid_l, 1])**2
        feet_l_z = (positions[1:, fid_l, 2] - positions[:-1, fid_l, 2])**2
        feet_l_h = positions[:-1, fid_l, 1]
        feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor) &
                  (feet_l_h < heightfactor)).astype(np.float)

        feet_r_x = (positions[1:, fid_r, 0] - positions[:-1, fid_r, 0])**2
        feet_r_y = (positions[1:, fid_r, 1] - positions[:-1, fid_r, 1])**2
        feet_r_z = (positions[1:, fid_r, 2] - positions[:-1, fid_r, 2])**2
        feet_r_h = positions[:-1, fid_r, 1]
        feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor) &
                  (feet_r_h < heightfactor)).astype(np.float)
    """ Get Root Velocity """
    velocity = (positions[1:, 0:1] - positions[:-1, 0:1]).copy()
    """ Remove Translation """
    positions[:, :, 0] = positions[:, :, 0] - positions[:, 0:1, 0]
    positions[:, :, 2] = positions[:, :, 2] - positions[:, 0:1, 2]
    """ Get Forward Direction """
    sdr_l, sdr_r, hip_l, hip_r = 13, 17, 1, 5
    across1 = positions[:, hip_l] - positions[:, hip_r]
    across0 = positions[:, sdr_l] - positions[:, sdr_r]
    across = across0 + across1
    across = across / np.sqrt((across**2).sum(axis=-1))[..., np.newaxis]

    direction_filterwidth = 20
    forward = np.cross(across, np.array([[0, 1, 0]]))
    forward = filters.gaussian_filter1d(forward,
                                        direction_filterwidth,
                                        axis=0,
                                        mode='nearest')
    forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]
    """ Get Root Rotation """
    target = np.array([[0, 0, 1]]).repeat(len(forward), axis=0)
    root_rotation = Quaternions.between(
        forward, target)[:, np.newaxis]  # rotation needed fwd->z?
    rvelocity = (root_rotation[1:] * -root_rotation[:-1]).to_pivots()
    """ Local Space """  # NEW: define position of joints relative to
    local_positions = positions.copy()
    local_positions[:, :,
                    0] = local_positions[:, :,
                                         0] - local_positions[:, 0:1,
                                                              0]  # x rel to root x
    local_positions[:, :,
                    2] = local_positions[:, :,
                                         2] - local_positions[:, 0:1,
                                                              2]  # z rel to root z

    local_positions = root_rotation[:-1] * local_positions[:
                                                           -1]  # remove Y rotation from pos
    local_velocities = local_positions[1:] - local_positions[:-1]
    local_rotations = abs((root_rotation[:-1] * global_rotations[:-1])).log()

    root_rvelocity = Pivots.from_quaternions(root_rotation[1:] *
                                             -root_rotation[:-1]).ps
    global_velocities = root_rotation[:-1] * velocity  # remove Y rotation from vel

    assert global_velocities.shape[
        1] == 1, "output assumes global_velocities dim2 = 1."
    n = root_rvelocity.shape[0]
    omit_end = range(0, n - 1)
    out = np.hstack(
        (root_rvelocity[omit_end, :], global_velocities[omit_end, :, 0],
         global_velocities[omit_end, :, 2], feet_l[omit_end, :],
         feet_r[omit_end, :], local_positions[omit_end].reshape(n - 1, -1),
         local_velocities.reshape(n - 1, -1),
         local_rotations[omit_end].reshape(n - 1, -1)))
    return out