Пример #1
0
 def optimize_camera(self):
     """ Calculate good camera parameters given the current stim."""
     top = self.cameras.getTop()
     p0 = Point3()
     p1 = Point3()
     self.sso.calcTightBounds(p0, p1)
     shape = p1 - p0
     extent = (shape[0], shape[2])
     extent = [max(extent)] * 2
     center = shape / 2. + p0
     # Adjust camera's x-position.
     self.cameras.setX(top, center[0])
     self.cameras.setZ(top, p1[2])
     # Compute where camera will point.
     # look_at = Point3(center[0], self.look_at.getY(), self.look_at.getZ())
     # look_at = (center[0], center[1], self.look_at.getZ())
     look_at = center
     origin = Point3(center[0], center[1], p1[2])
     displacement = self.cameras.getPos(top) - origin
     distance = displacement.length()
     fov = self.cam.node().getLens().getFov()
     target_ratio = 0.65
     dx = extent[0] / 2. / target_ratio / tan(radians(fov[0]) / 2.)
     dz = extent[1] / 2. / target_ratio / tan(radians(fov[1]) / 2.)
     dr = max(dx, dz) / distance
     pos = origin + displacement * dr
     self.cameras.setPos(top, pos)
     #BP()
     # Point camera toward stim.
     self.look_at.setPos(top, look_at)
     self.cameras.lookAt(self.look_at)
Пример #2
0
    def stopChase(self):

        #self.AIbehaviors.pauseAi("pursue")
        if not self._is_dead:
            self.AIbehaviors.removeAi("pursue")
            p1 = LerpHprInterval(self.npc, 4, Point3(180, 0, 0))
            p2 = LerpPosInterval(
                self.npc, 4, Point3(self.anchorx, self.anchory, self.anchorz))
            animInterval = self.npc.actorInterval("walk", loop=1, duration=4)
            p2.start()
            p1.start()
            animInterval.start()
            self.isMoving = False
            self.target = None
            self.isCurrentUser = False
Пример #3
0
 def _make_connector(self, parent, points, extent, name):
     """ Makes connector object."""
     connector = self.base_connector.copy()
     scale = Vec3(*(np.ptp(points, axis=0)))
     scale_extended = scale + extent
     pos = Point3(*(np.min(points, axis=0) + scale / 2.))
     connector.apply_prop(dict(name=name, scale=scale_extended, pos=pos),
                          other=self.scene)
     connector.wrtReparentTo(parent)
     return connector
Пример #4
0
def is_penetrating(node0, node1):
    """ Tests whether two nodes' geometries are overlapping by
    comparing their axis-aligned bounding boxes (AABB)."""
    # bb0 = [Vec3(0., 0., 0.), Vec3(5., 5., 5.)]
    # bb1 = [Vec3(1., 1., 1.), Vec3(16., 16., 16.)]

    # Allocate Vec3 storage
    bb0 = [Point3(0., 0., 0.), Point3(0., 0., 0.)]
    bb1 = [Point3(0., 0., 0.), Point3(0., 0., 0.)]

    # Get tight AABBs
    node0.calcTightBounds(bb0[0], bb0[1])
    node1.calcTightBounds(bb1[0], bb1[1])

    # Perform the test
    BB0 = np.array(bb0)
    BB1 = np.array(bb1)
    f_penetrating = not (np.any(BB0[0] > BB1[1]) or np.any(BB1[0] > BB0[1]))

    return f_penetrating
Пример #5
0
 def bump(self, task):
     """ Task: perform bump."""
     mag0 = Vec3(0, 0, 1. / self.bbase.sim_par["size"]) * 10.
     pos = Point3(-1, 0, 0)
     nodes = self.background.descendants()
     bodies = [n.node() for n in nodes if n.type_ is BulletRigidBodyNode]
     for body in bodies:
         mag = mag0 * body.getMass()
         print mag
         body.applyForce(mag, pos)
     #BP()
     return task.done
Пример #6
0
    def _add_noise(self, cpos, pcpos, noises):
        """Adds geometry noise."""
        if (noises == 0).all():
            return

        for cpo, noise in zip(cpos, noises):
            pos = cpo.getPos(self.scene)
            pos += Point3(*noise)
            cpo.setPos(self.scene, pos)

        # Repel.
        with self._sim_context(pcpos):
            self.bbase.repel(50)
Пример #7
0
 def _build_cursor(self, shape="sphere"):
     if shape == "sphere":
         cursor = self._load("sphere.bam")
     elif shape == "cross":
         cursor = LineNodePath()
         lines = [[Point3(-0.5, 0, 0),
                   Point3(0.5, 0, 0)],
                  [Point3(0, 0, -0.5),
                   Point3(0, 0, 0.5)]]
         cursor.drawLines(lines)
         cursor.setThickness(1)
         cursor.create()
         # cursor = NodePath("cross")
         # S = {"cylinderX.bam": ((0., 0., 0.), (1., 0.1, 0.1)),
         #      "cylinderY.bam": ((0., 0., 0.), (0.1, 1., 0.1)),
         #      "cylinderZ.bam": ((0., 0., 0.), (0.1, 0.1, 1.))}
         # for k, v in S.iteritems():
         #     m = self._load(k)
         #     m.setName(k)
         #     m.setPos(*v[0])
         #     m.setScale(*v[1])
         #     m.reparentTo(cursor)
     #BP()
     return cursor
Пример #8
0
 def _compute_shapes(self):
     """ Computes shapes from self.components."""
     # Compute mass and center-of-mass.
     masses = []
     poses = []
     psos = self.descendants(depths=[1], type_=PSO)
     parent = self.getParent()
     for pso in psos:
         mass = pso.get_mass()
         pos = pso.get_pos(parent)
         if mass == 0.:
             com = pos
             break
         poses.append(pos)
         masses.append(mass)
     else:
         mass = np.sum(masses)
         com = Point3(*(np.sum(np.array(poses).T * masses, axis=-1) / mass))
     self.set_mass(mass)
     with self._preserve_child_tranforms() as parent:
         self.set_pos(parent, com)
     # Add shapes from PSOs.
     vals = []
     for pso in psos:
         shapes0 = ShapeList(pso.get_shape())
         for shape0 in shapes0:
             name = shape0.name
             args0, xform0 = shape0
             if name != "Box":
                 print("Can't handle that shape: %s" % name)
                 BP()
             shape = ShapeManager.make1((name, args0, xform0))
             shape.transform(pso, other=self)
             # scale = pso.get_scale(self)
             # pos = pso.get_pos(self)
             # quat = pso.get_quat(self)
             # shape.scale(scale)
             # shape.shift(pos, quat)
             val = (name, shape[0], shape[1])
             vals.append(val)
     # Set compound object's shapes tag.
     self.set_shape(vals)
Пример #9
0
def test_apply_prop_read_prop_SSO():
    sso = SSO("foo")
    other = SSO("other")
    other.setPos(100, 200, 300)
    other.setHpr(23, 20, 100)
    other.setScale(6, 2, 9)
    prop0 = {
        "name": "testname",
        "pos": Point3(1, 2, 3),
        "quat": Quat(2**0.5, 2**0.5, 0, 0),
        "scale": Vec3(10, 9, 8),
    }
    sso.setName(prop0["name"])
    sso.setPos(prop0["pos"])
    sso.setQuat(prop0["quat"])
    sso.setScale(prop0["scale"])
    assert prop0 == sso.read_prop()
    oprop = sso.read_prop(other=other)
    sso.wrtReparentTo(other)
    assert sso.read_prop() == oprop
Пример #10
0
 def __init__(self):
     ShowBase.__init__(self)
     resize_window = ConfigVariableBool('viewer-resize-window', '#t')
     if resize_window.getValue():
         self.win_size = (800, 800)
     # Black background
     self.win.setClearColor((0.0, 0.0, 0.0, 1.0))
     # Set up lights.
     self.lights = NodePath("lights")
     # Spotlight. Casts shadows.
     slight = Spotlight("slight")
     slight.setScene(self.render)
     slight.setShadowCaster(True, 2**11, 2**11)
     # Set shadow mask, so we can exclude objects from casting shadows
     self.shadow_mask = BitMask32.bit(2)
     slight.setCameraMask(self.shadow_mask)
     slight.setColor((1.2, 1.2, 1.2, 1.))
     slight.getLens().setFov(45)
     slight.getLens().setNearFar(1, 100)
     slnp = self.lights.attachNewNode(slight)
     slnp.setPos((6, 8, 20))
     slnp.lookAt(0, 0, 0)
     self.render.setLight(slnp)
     # Ambient light.
     alight = AmbientLight("alight")
     a = 0.75
     alight.setColor((a, a, a, 1.0))
     #alight.setColor((0.8, 0.8, 0.8, 1.0))
     alnp = self.lights.attachNewNode(alight)
     self.render.setLight(alnp)
     self.lights.reparentTo(self.render)
     # Set auto shading for shadows
     use_shaders = ConfigVariableBool('viewer-use-shaders', '#t')
     if use_shaders.getValue():
         self.render.setShaderAuto()
     # Set antialiasing on
     self.render.setAntialias(AntialiasAttrib.MAuto)
     # Camera
     self.camera_rot = self.render.attachNewNode("camera_rot")
     self.cameras = self.camera_rot.attachNewNode("cameras")
     self.cameras.setPos(14, 32, 9.)
     self.look_at = self.render.attachNewNode("look_at")
     self.look_at.setPos(Point3(2, 0, 1))
     self.cameras.lookAt(self.look_at)
     self.camera.reparentTo(self.cameras)
     # Adjust the camera's lens
     lens = PerspectiveLens()
     self.camLens = lens
     self.camLens.setNearFar(0.01, 1000.0)
     setlens = ConfigVariableBool('viewer-set-cam-lens', '#t')
     if setlens:
         self.cam.node().setLens(self.camLens)
     #
     # Initialize / set variables
     self.sso = None
     self.ssos = []
     self.cache = None
     self.scene = SSO("scene")
     self.scene.reparentTo(self.render)
     # Key callbacks.
     self.accept("shift-control-escape", self.exit)
     self.accept("escape", self.exit)
     self.accept("0", self.reset_sso)
     self.accept("arrow_left", self.prev)
     self.accept("arrow_right", self.next)
     self.accept("page_down", self.prev, [100])
     self.accept("page_up", self.next, [100])
     self.accept("f1", self.toggle_debug)
     self.accept("o", self.physics_once, extraArgs=[1. / 10])
     self.accept("i", self.physics_once, extraArgs=[1. / 10000])
     # Remove existing keyboard tasks.
     self.mandatory_events = ("window-event", "async_loader_0",
                              "render-texture-targets-changed",
                              "shift-control-escape")
     # Task list: name: (key, args)
     events = {
         "physics": ("p", ),
         "repel": ("t", ),
         "bump": ("f", ),
         "rotate": ("r", 20),
         "rotate90": ("h", ),
         "ss_task": ("s", ),
         "ssa_task": ("w", ),
         "bp": ("b", )
     }
     # Add events
     for key, val in events.iteritems():
         call = [key] + list(val[1:])
         self.accept(val[0], self.toggle_task, call)
     # These are the key events that we will never ignore
     self.permanent_events = self.getAllAccepting()
     # These are the key events that we will never ignore
     self.permanent_tasks = [
         task.getName() for task in self.taskMgr.getAllTasks()
     ]
     self.start_time = -1
     self.old_elapsed = 0
Пример #11
0
def test_default():
    props = GSO.default()
    assert props["pos"] == Point3(0, 0, 0)