def __init__(self):
        self.super(MultiTouchDevice).__init__()
        self._sceneGraph = None
        self._display = None
        self._worldMat = avango.gua.make_identity_mat()
        self._transMat = avango.gua.make_identity_mat()
        self._rotMat = avango.gua.make_identity_mat()
        self._scaleMat = avango.gua.make_identity_mat()
        """ Scene transform matrix """
        self._globalMatrix = avango.gua.make_identity_mat()
        """ last cursor position """
        self._lastPos = None
        """ params to evaluate object / navigation mode """
        self._sceneName = None
        self._objectName = None
        self._objectMode = False

        self._headPosition1 = avango.gua.Vec3(0, 0, 0)
        """ params to evaluate intersection """
        self._intersection = Intersection(
        )  # ray intersection for target identification
        self._intersectionFound = False
        self._intersectionPoint = avango.gua.Vec3(0, 0, 0)
        self._intersectionObject = None
        self._lastIntersectionCounter = 0
        """ ray representation"""
        self.ray_length = 10
        self.ray_thickness = 0.0075
        self.intersection_sphere_size = 0.025
        self.highlighted_object = None
        self.hierarchy_selection_level = -1

        self.always_evaluate(True)
Example #2
0
    def my_constructor(self, SF_STATION_MAT, RAY_START_HEIGHT):

        # attributes
        ## @var activated
        # Indicates if the ground following algorithm is activated or deactivated. In the last case,
        # the input matrix is simply passed through.
        self.activated = False

        ## @var falling
        # A boolean indicating if the user is currently falling. Used for fall speed computations.
        self.falling = False

        ## @var initial_fall_velocity
        # The starting velocity when the user is falling in meters per frame. Is increased the longer the falling process goes on.
        self.initial_fall_velocity = 0.05

        ## @var height_modification_factor
        # Scaling factor used for the modification of up and down vectors.
        self.height_modification_factor = 0.15

        # fall velocity in meter per frame
        ## @var fall_velocity
        # Speed when the user is falling in meters per frame.
        self.fall_velocity = self.initial_fall_velocity

        # pick length in meter
        ## @var ground_pick_length
        # Length of the ground following ray.
        self.ground_pick_length = 100.0

        ## @var ground_pick_direction_mat
        # Direction of the ground following ray.
        self.ground_pick_direction_mat = avango.gua.make_identity_mat()

        ## @var SCENEGRAPH
        # Reference to the scenegraph to intersect the ground following ray with.
        self.SCENEGRAPH = scenegraphs[0]

        ## @var ray_start_height
        # Starting height of the ground following ray.
        self.ray_start_height = RAY_START_HEIGHT

        # initialize shoot and output matrices
        self.sf_abs_output_mat.value = self.sf_abs_input_mat.value

        self.set_pick_direction(avango.gua.Vec3(0.0, -1.0, 0.0))

        # init field connections
        self.sf_station_mat.connect_from(SF_STATION_MAT)

        # init internal class
        ## @var ground_intersection
        # Intersection class to determine the intersections of the ground following ray with the objects in the scenegraph.
        self.ground_intersection = Intersection()
        self.ground_intersection.my_constructor(self.SCENEGRAPH,
                                                self.sf_gf_start_mat,
                                                self.ground_pick_length,
                                                "gf_pick_group")
        self.mf_ground_pick_result.connect_from(
            self.ground_intersection.mf_pick_result)
Example #3
0
 def __init__(self, speed_limit: int, num_lanes: int,
              road_length_meters: float, road_name: str):
     """ The road object will contain all """
     self.road_name = road_name
     self.__begin_intersection = Intersection(self)
     self.end_intersection = Intersection()
     self.speed_limit = speed_limit
     self.num_lanes = num_lanes
     self.lanes = self._init_lanes()
     self.road_length_meters = road_length_meters
     self.capacity = None
Example #4
0
class Road:
    """ The road object contains most objects in the system and store road data. """
    def __init__(self, speed_limit: int, num_lanes: int,
                 road_length_meters: float, road_name: str):
        """ The road object will contain all """
        self.road_name = road_name
        self.__begin_intersection = Intersection(self)
        self.end_intersection = Intersection()
        self.speed_limit = speed_limit
        self.num_lanes = num_lanes
        self.lanes = self._init_lanes()
        self.road_length_meters = road_length_meters
        self.capacity = None

    def _init_lanes(self):
        lanes = []
        out = "{:4}{:4}{:4}|\n".format("|", "|", "|")
        print(out * 2, end="")
        out = "{:4}{:4}{:4}\n".format("| 1 |", " 2 |", " 3 |")
        print(out)
        for i in range(1, self.num_lanes + 1):
            is_turnlight = input("Is lane number: " + str(i) +
                                 " a turning lane? y/n: ")
            if is_turnlight == "y":
                lanes.append(Lane("turn"))
            lanes.append(Lane("straight"))
        return lanes

    def _setBeginIntersection(self, intersection: Intersection):
        self.__begin_intersection = intersection

    def setEndIntersection(self, intersection: Intersection):
        self.end_intersection = intersection
        self.end_intersection.setIntersectionName(self.road_name)

    def getBeginIntersection(self):
        return self.__begin_intersection

    def getEndIntersection(self):
        return self.end_intersection

    def getRoadName(self):
        return self.road_name

    def __str__(self):
        out = "Road name: {:<32} Speed Limit: {:<4}  Length: {:<8}".format(
            self.road_name,
            str(self.speed_limit) + "km/h",
            str(self.road_length_meters) + "m")
        return out

    def calculateCapacity(self):
        pass
Example #5
0
    def parseSgfToken(token, board_size=19):
        ''' Takes in a single SGF token and returns an Intersection object
        representing that token.
        '''
        try:
            if token == ")":
                return None
            if len(token) > 5 and token[5] not in (")", "C"):
                SgfParser.raiseInvalidSgf(token)

            if token[0] == 'B':
                stoneColor = StoneColor.BLACK
            elif token[0] == 'W':
                stoneColor = StoneColor.WHITE
            else:
                SgfParser.raiseInvalidSgf(token)

            if token[1] != '[':
                SgfParser.raiseInvalidSgf(token)

            if token[2] == ']':
                coordinate = [-1, -1]
            elif board_size <= 19 and token[2] == 't' and token[
                    3] == 't':  # Part of SGF standard
                coordinate = [-1, -1]
            else:
                coordinate = [
                    ord(token[3]) - ord('a'),
                    ord(token[2]) - ord('a')
                ]
        except IndexError:
            SgfParser.raiseInvalidSgf(token)
        return Intersection(coordinate, stoneColor)
  def my_constructor(self, SCENEGRAPH, SF_STATION_MAT, RAY_START_HEIGHT):
    
    # attributes
    ## @var activated
    # Indicates if the ground following algorithm is activated or deactivated. In the last case,
    # the input matrix is simply passed through.
    self.activated = False

    ## @var falling
    # A boolean indicating if the user is currently falling. Used for fall speed computations.
    self.falling = False

    ## @var initial_fall_velocity
    # The starting velocity when the user is falling in meters per frame. Is increased the longer the falling process goes on.
    self.initial_fall_velocity = 0.05

    ## @var height_modification_factor
    # Scaling factor used for the modification of up and down vectors.
    self.height_modification_factor = 0.1

    # fall velocity in meter per frame
    ## @var fall_velocity
    # Speed when the user is falling in meters per frame.
    self.fall_velocity = self.initial_fall_velocity

    # pick length in meter
    ## @var ground_pick_length
    # Length of the ground following ray.
    self.ground_pick_length = 100.0

    ## @var ground_pick_direction_mat
    # Direction of the ground following ray.
    self.ground_pick_direction_mat = avango.gua.make_identity_mat()

    ## @var SCENEGRAPH
    # Reference to the scenegraph to intersect the ground following ray with.
    self.SCENEGRAPH = SCENEGRAPH

    ## @var ray_start_height
    # Starting height of the ground following ray.
    self.ray_start_height = RAY_START_HEIGHT

    # initialize shoot and output matrices
    self.sf_abs_output_mat.value = self.sf_abs_input_mat.value

    self.set_pick_direction(avango.gua.Vec3(0.0, -1.0, 0.0))

    # init field connections
    self.sf_station_mat.connect_from(SF_STATION_MAT)

    # init internal class
    ## @var ground_intersection
    # Intersection class to determine the intersections of the ground following ray with the objects in the scenegraph.
    self.ground_intersection = Intersection()
    self.ground_intersection.my_constructor(SCENEGRAPH, self.sf_gf_start_mat, self.ground_pick_length, "gf_pick_group")
    self.mf_ground_pick_result.connect_from(self.ground_intersection.mf_pick_result)
Example #7
0
    def addNeighbor(self, currentWord, currentWordIsAcross, neighborWord,
                    board):

        for current_i in range(len(currentWord)):
            for neighbor_i in range(len(neighborWord)):
                if currentWord[current_i] == neighborWord[neighbor_i]:

                    # generate an intersection object
                    if currentWordIsAcross:
                        intersection = Intersection(currentWord, current_i,
                                                    neighborWord, neighbor_i)
                    else:
                        intersection = Intersection(neighborWord, neighbor_i,
                                                    currentWord, current_i)

                    # if this is a valid intersection, add it to crossword and break out of the second loop
                    if board.addIfValid(intersection, not currentWordIsAcross):
                        return True

        return False
    def generateMap(self):
        for i in range(len(self.intersectionCount)):
            # Procedurarly position intersection count:

            if (len(self.intersectionCount) == 1):
                print("Map has one intersection")

                # We will generate one intersection in the middle of the map. This is the base case
                currIntersection = Intersection(length=40,
                                                wid=40,
                                                posX=490,
                                                posY=490)

            elif (len(self.intersectionCount) == 2):
                print("Map has two intersections")

            elif (len(self.intersectionCount) == 3):
                print("Map has three intersections")

            elif (len(self.intersectionCount == 5)):
                print("Map has three intersectoins")
Example #9
0
    def collision_test(self, start_point, end_point):
        '''
        returns if path of drop collided with `self.collider_a` and `self.collider_b`

        c and d should be `tuple` or `list`:
            (x,y) or [x,y]
        '''
        start_x = int(start_point[0])
        start_y = int(start_point[1])
        end_x = int(end_point[0])
        end_y = int(end_point[1])

        start_point = (start_x, start_y)
        end_point = (end_x, end_y)
        # in case a drop gets reset from ground to top so doesnt count as a hit
        if start_point[1] < end_point[1]:
            return False

        if Intersection.closed_segment_intersect(self.collider_a,
                                                 self.collider_b, start_point,
                                                 end_point):
            self.collider_hits += 1
Example #10
0
def getOrientamentWay(idWay, soup):
    #ottengo la lista di tutti i nodi, cerco quelli più a nord e più a sud e calcolo l'angolazione
    listIntersectionID = getListIntersection(idWay, soup)
    listIntersection = []

    for i in range(len(listIntersectionID)):
        obj = Intersection(listIntersectionID[i], soup)

        listIntersection.append(obj)

    nodeNord = getNodeNord(listIntersection)
    nodeSud = getNodeSud(listIntersection)

    latNord = math.radians(float(nodeNord.lat))
    latSud = math.radians(float(nodeSud.lat))
    lonNord = math.radians(float(nodeNord.lon))
    lonSud = math.radians(float(nodeSud.lon))

    objA = (latNord, lonNord)
    objB = (latSud, lonSud)

    x = calculate_initial_compass_bearing(objA, objB)
    return x
    def __init__(self):
        self.super(MultiTouchDevice).__init__()
        self._sceneGraph = None
        self._display    = None
        self._worldMat   = avango.gua.make_identity_mat()
        self._transMat   = avango.gua.make_identity_mat()
        self._rotMat     = avango.gua.make_identity_mat()
        self._scaleMat   = avango.gua.make_identity_mat()
        
        """ Scene transform matrix """
        self._globalMatrix = avango.gua.make_identity_mat()

        """ last cursor position """
        self._lastPos = None

        """ params to evaluate object / navigation mode """
        self._sceneName = None
        self._objectName = None
        self._objectMode = False

        self._headPosition1 = avango.gua.Vec3(0,0,0)

        """ params to evaluate intersection """
        self._intersection = Intersection() # ray intersection for target identification
        self._intersectionFound = False
        self._intersectionPoint = avango.gua.Vec3(0,0,0)
        self._intersectionObject = None
        self._lastIntersectionCounter = 0

        """ ray representation"""
        self.ray_length = 10
        self.ray_thickness = 0.0075
        self.intersection_sphere_size = 0.025
        self.highlighted_object = None
        self.hierarchy_selection_level = -1
     
        self.always_evaluate(True)
class MultiTouchDevice(avango.script.Script):
    """
    Base class for multi touch devices.

    rayOrientation: orientation matrix (start position + direction) of ray 
    fingerCenterPos: the center of finger position in interval from -display-size to +display-size
    """
    _rayOrientation = avango.gua.SFMatrix4()
    _fingerCenterPos = avango.gua.SFVec3()

    def __init__(self):
        self.super(MultiTouchDevice).__init__()
        self._sceneGraph = None
        self._display = None
        self._worldMat = avango.gua.make_identity_mat()
        self._transMat = avango.gua.make_identity_mat()
        self._rotMat = avango.gua.make_identity_mat()
        self._scaleMat = avango.gua.make_identity_mat()
        """ Scene transform matrix """
        self._globalMatrix = avango.gua.make_identity_mat()
        """ last cursor position """
        self._lastPos = None
        """ params to evaluate object / navigation mode """
        self._sceneName = None
        self._objectName = None
        self._objectMode = False

        self._headPosition1 = avango.gua.Vec3(0, 0, 0)
        """ params to evaluate intersection """
        self._intersection = Intersection(
        )  # ray intersection for target identification
        self._intersectionFound = False
        self._intersectionPoint = avango.gua.Vec3(0, 0, 0)
        self._intersectionObject = None
        self._lastIntersectionCounter = 0
        """ ray representation"""
        self.ray_length = 10
        self.ray_thickness = 0.0075
        self.intersection_sphere_size = 0.025
        self.highlighted_object = None
        self.hierarchy_selection_level = -1

        self.always_evaluate(True)

    def my_constructor(self, graph, display, NET_TRANS_NODE, SCENE_MANAGER,
                       APPLICATION_MANAGER):
        """
        Initialize multi-touch device.

        @param graph: the scene graph on which to operate
        @param display: the physical display
        """

        self._sceneGraph = graph
        self._display = display
        self._sceneManager = SCENE_MANAGER
        """ original matrix of the scene """
        self._origMat = graph.Root.value.Transform.value
        """  """
        self._applicationManager = APPLICATION_MANAGER

        self._intersection.my_constructor(
            self._sceneGraph, self._rayOrientation, self.ray_length, ""
        )  # parameters: SCENEGRAPH, SF_PICK_MATRIX, PICK_LENGTH, PICKMASK
        """ parent node of ray node """
        _parent_node = self._sceneGraph["/net"]
        """
        # init scenegraph node
        ## @var ray_transform
        # Transformation node of the pointer's ray.
        """
        self.ray_transform = avango.gua.nodes.TransformNode(
            Name="ray_transform")
        _parent_node.Children.value.append(self.ray_transform)

        _loader = avango.gua.nodes.TriMeshLoader()
        """
        ## @var ray_geometry
        # Geometry node representing the ray graphically.
        """
        self.ray_geometry = _loader.create_geometry_from_file(
            "ray_geometry", "data/objects/cylinder.obj",
            "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)
        self.ray_transform.Children.value.append(self.ray_geometry)
        self.ray_geometry.GroupNames.value = ["do_not_display_group"]

        self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0,0,0) * \
                                            avango.gua.make_rot_mat(0,0,0,0) * \
                                            avango.gua.make_scale_mat(0,0,0)
        """
        @var intersection_point_geometry
        Geometry node representing the intersection point of the ray with an object in the scene.
        """
        self.intersection_point_geometry = _loader.create_geometry_from_file(
            "intersection_point_geometry", "data/objects/sphere.obj",
            "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)
        NET_TRANS_NODE.Children.value.append(self.intersection_point_geometry)
        self.intersection_point_geometry.GroupNames.value = [
            "do_not_display_group"
        ]  # set geometry invisible

        self.ray_transform.Transform.connect_from(self._rayOrientation)
        """ representation of fingercenterpos """
        self.fingercenterpos_geometry = _loader.create_geometry_from_file(
            "fingercenterpos", "data/objects/sphere.obj",
            "data/materials/Red.gmd", avango.gua.LoaderFlags.DEFAULTS)
        NET_TRANS_NODE.Children.value.append(self.fingercenterpos_geometry)
        self.fingercenterpos_geometry.GroupNames.value = [
            "do_not_display_group"
        ]
        """ hand representation """
        self.handPos_geometry = _loader.create_geometry_from_file(
            "handpos", "data/objects/cube.obj", "data/materials/Red.gmd",
            avango.gua.LoaderFlags.DEFAULTS)
        NET_TRANS_NODE.Children.value.append(self.handPos_geometry)
        self.handPos_geometry.GroupNames.value = ["do_not_display_group"]
        """ define Input display size """
        #111,5cm x 75,8
        self._inputDisplaySize = avango.gua.Vec2(1.115, 0.758)

    def getDisplay(self):
        return self._display

    def getSceneGraph(self):
        return self._sceneGraph

    def mapInputPosition(self, Pos):
        """
        Map input position to display size
        """

        point = Pos
        """ map points from interval [0, 1] to [-0.5, 0.5] """
        mappedPosX = point[0] * 1 - 0.5
        mappedPosY = point[1] * 1 - 0.5
        """ map point to display intervall ([-1/2*display-size] -> [+1/2*display-size]) """
        mappedPos = avango.gua.Vec3(mappedPosX * self._inputDisplaySize.x, 0.0,
                                    mappedPosY * self._inputDisplaySize.y)

        return mappedPos

    def setFingerCenterPos(self, fingerPos):
        self._fingerCenterPos.value = fingerPos
        """ update fingercenterpos representation """
        self.fingercenterpos_geometry.GroupNames.value = []
        self.fingercenterpos_geometry.Transform.value = avango.gua.make_trans_mat(self._fingerCenterPos.value) * \
                                                        avango.gua.make_scale_mat( 0.025, 0.025 , 0.025 )

    def visualisizeHandPosition(self, handPos):
        """ update hand representation """
        self.handPos_geometry.GroupNames.value = []
        self.handPos_geometry.Transform.value = avango.gua.make_trans_mat(handPos) * \
                                                avango.gua.make_scale_mat( 0.1, 0.005 , 0.1 )

    def setObjectMode(self, active):
        """
        Evaluate object mode.
        object mode activated only if an intersection was found

        @param active: toggle active state of object mode 
        """
        if active and self._intersectionFound:
            self._objectMode = True
            self._objectName = self._intersectionObject.Parent.value.Name.value
            return True
        else:
            self._objectMode = False
            self._objectName = None
            return False

    def addLocalTranslation(self, transMat):
        """
        Add local translation.

        @param transMat: the (relative) translation matrix
        """
        self._transMat *= transMat

    def addLocalRotation(self, rotMat):
        """
        Add local rotation.

        @param rotMat: the (relative) rotation matrix
        """
        self._rotMat *= rotMat

    def addLocalScaling(self, scaleMat):
        """
        Add local scaling.

        @param scaleMat: the (relative) scaling matrix
        """
        self._scaleMat *= scaleMat

    def intersectSceneWithFingerPos(self):
        """
        Intersect Scene with ray from head to finger position. works only for first user.

        @param transMat: the (relative) translation matrix
        """

        #TODO: decide between displays with tracking and not
        #for no tracking use this: #self._rayOrientation.value = avango.gua.make_trans_mat(self._fingerCenterPos.value.x , 0.5 , self._fingerCenterPos.value.z) * avango.gua.make_rot_mat(-90,1,0,0)

        #do this only once per gesture

        #do this only once per gesture
        if (1 < (self._frameCounter - self._lastIntersectionCounter)):
            """ ray orientation from fingerPos down """
            self._rayOrientation.value = avango.gua.make_trans_mat(
                self._fingerCenterPos.value.x, 1,
                self._fingerCenterPos.value.z) * avango.gua.make_rot_mat(
                    -90, 1, 0, 0)
            """intersection found"""
            if len(self._intersection.mf_pick_result.value) > 0:
                self._intersectionFound = True
                """first intersected object"""
                _pick_result = self._intersection.mf_pick_result.value[0]

                self._intersectionPoint = _pick_result.Position.value
                self._intersectionObject = _pick_result.Object.value
                """update intersectionObject until you insert object Mode"""
                if not self._objectMode:
                    self._lastIntersectionObject = self._intersectionObject
                """ transform point into world coordinates """
                self._intersectionPoint = self._intersectionObject.WorldTransform.value * self._intersectionPoint
                """make Vec3 from Vec4"""
                self._intersectionPoint = avango.gua.Vec3(
                    self._intersectionPoint.x, self._intersectionPoint.y,
                    self._intersectionPoint.z)

                if (self._objectMode and not self._objectName
                        == self._intersectionObject.Parent.value.Name.value):
                    #print "same object"
                    self._intersectionPoint = avango.gua.Vec3(0, 0, 0)
                """ VISUALISATION """
                """update intersection sphere"""
                self.intersection_point_geometry.Transform.value = avango.gua.make_trans_mat(self._intersectionPoint) * \
                                                                   avango.gua.make_scale_mat(self.intersection_sphere_size, self.intersection_sphere_size, self.intersection_sphere_size)
                """set sphere and ray visible"""
                #self.intersection_point_geometry.GroupNames.value = []
                #self.ray_geometry.GroupNames.value = []
                """update ray"""
                _distance = (
                    self._intersectionPoint -
                    self.ray_transform.WorldTransform.value.get_translate()
                ).length()

                self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0.0, 0.0, _distance * -0.5) * \
                                                    avango.gua.make_rot_mat(-90.0,1,0,0) * \
                                                    avango.gua.make_scale_mat(self.ray_thickness, _distance, self.ray_thickness)

            else:
                """set geometry invisible"""
                self.intersection_point_geometry.GroupNames.value = [
                    "do_not_display_group"
                ]
                self.ray_geometry.GroupNames.value = ["do_not_display_group"]
                """set to default ray length"""
                self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0.0,0.0,self.ray_length * -0.5) * \
                                                    avango.gua.make_rot_mat(-90.0,1,0,0) * \
                                                    avango.gua.make_scale_mat(self.ray_thickness, self.ray_length, self.ray_thickness)
                self._intersectionFound = False
                self._intersectionPoint = avango.gua.Vec3(0, 0, 0)

        self._lastIntersectionCounter = self._frameCounter

    def update_object_highlight(self):
        """highlight active object:"""
        if self._objectMode:
            _node = self._lastIntersectionObject

            if _node.has_field("InteractiveObject") == True:
                _object = _node.InteractiveObject.value

                if self.hierarchy_selection_level >= 0:
                    _object = _object.get_higher_hierarchical_object(
                        self.hierarchy_selection_level)

                if _object == None:
                    """ evtl. disable highlight of prior object"""
                    if self.highlighted_object != None:
                        self.highlighted_object.enable_highlight(False)

                else:
                    if _object != self.highlighted_object:  # new object hit
                        """evtl. disable highlight of prior object"""
                        if self.highlighted_object != None:
                            self.highlighted_object.enable_highlight(False)

                        self.highlighted_object = _object
                        """enable highlight of new object"""
                        self.highlighted_object.enable_highlight(True)

        else:
            """evtl. disable highlight of prior object"""
            if self.highlighted_object != None:
                self.highlighted_object.enable_highlight(False)
                self.highlighted_object = None

    def applyTransformations(self):
        """
        Apply calculated world matrix to scene graph.
        Requires the scene graph to have a transform node as root node.
        """
        """ Reguires the scnene Name of actually scene to change dynamically """
        sceneName = self._sceneManager.getActiveSceneName()
        """ to avoid errors until the scenen Name is set """
        if (None != sceneName):
            sceneNode = "/net/" + sceneName
            self._globalMatrix = self._sceneGraph[sceneNode].Transform.value
            """ object Mode """
            if self._objectMode:
                objectNode = "/net/" + sceneName + "/" + self._objectName
                scenePos = self._sceneGraph[
                    objectNode].Transform.value.get_translate()
                TransformMatrix = self._sceneGraph[objectNode].Transform.value

            else:
                scenePos = self._sceneGraph[
                    sceneNode].Transform.value.get_translate()
                TransformMatrix = self._sceneGraph[sceneNode].Transform.value
            """ distance between finger position and scene position (object position) """
            translateDistance = self._fingerCenterPos.value - scenePos
            """transform world-space to object-space"""
            translateDistance = avango.gua.make_inverse_mat(
                avango.gua.make_rot_mat(
                    TransformMatrix.get_rotate_scale_corrected())
            ) * translateDistance
            translateDistance = avango.gua.Vec3(translateDistance.x,
                                                translateDistance.y,
                                                translateDistance.z)

            #print (self._transMat)
            """ 
            TransfotmMatrix: 
                1. translate and rotate to origin, 
                2. calculate new position, 
                3. translate and rotate back 
            """
            """ object mode """
            if self._objectMode:
                TransformMatrix = avango.gua.make_trans_mat(TransformMatrix.get_translate()) * \
                                  avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected()) * \
                                  avango.gua.make_inverse_mat(avango.gua.make_rot_mat(self._globalMatrix.get_rotate_scale_corrected())) * \
                                  avango.gua.make_inverse_mat(avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected())) * \
                                  self._rotMat * \
                                  self._scaleMat * \
                                  self._transMat * \
                                  avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected()) * \
                                  avango.gua.make_rot_mat(self._globalMatrix.get_rotate_scale_corrected()) * \
                                  avango.gua.make_scale_mat(TransformMatrix.get_scale())

            else:
                TransformMatrix = avango.gua.make_trans_mat(TransformMatrix.get_translate()) * \
                                  avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected()) *\
                                  avango.gua.make_trans_mat(translateDistance * 1.0) * \
                                  avango.gua.make_trans_mat(avango.gua.Vec3(0, self._intersectionPoint.y * -1.0 , 0)) * \
                                  avango.gua.make_inverse_mat(avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected())) * \
                                  self._rotMat * \
                                  self._scaleMat * \
                                  self._transMat * \
                                  avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected()) * \
                                  avango.gua.make_trans_mat(avango.gua.Vec3(0, self._intersectionPoint.y * 1.0 , 0)) * \
                                  avango.gua.make_trans_mat(translateDistance * -1.0) * \
                                  avango.gua.make_scale_mat(TransformMatrix.get_scale())
            """ object mode """
            if self._objectMode:
                self._sceneGraph[objectNode].Transform.value = TransformMatrix

            else:
                self._sceneGraph[sceneNode].Transform.value = TransformMatrix
        """ reset all data """
        self._transMat = avango.gua.make_identity_mat()
        self._rotMat = avango.gua.make_identity_mat()
        self._scaleMat = avango.gua.make_identity_mat()
        self._globalMatrix = avango.gua.make_identity_mat()
Example #13
0
    def intersections(self, ray):
        i = Intersection.Intersections()

        for object in self.objects:
            i += object.intersects(ray)
        return i.sort()
  def my_constructor(self
                   , APPLICATION_MANAGER
                   , USER_ID
                   , VIP
                   , GLASSES_ID
                   , HEADTRACKING_TARGET_NAME
                   , PLATFORM_ID
                   , AVATAR_MATERIAL):

    # flags 
    ## @var is_vip
    # Boolean indicating if this user has vip status.
    self.is_vip = VIP

    ## @var is_active
    # Boolean indicating if this user is currently active.
    self.is_active = True

    # variables
    ## @var APPLICATION_MANAGER
    # Reference to the ApplicationManager instance from which the user is created.
    self.APPLICATION_MANAGER = APPLICATION_MANAGER

    ## @var id
    # Identification number of the user, starting from 0.
    self.id = USER_ID

    ## @var platform_id
    # ID of the platform the user is belonging to.
    self.platform_id = PLATFORM_ID

    ## @var platform
    # Instance of the platform the user is belonging to.
    self.platform = self.APPLICATION_MANAGER.navigation_list[self.platform_id].platform

    ## @var current_display
    # Display instance on which the user physically is currently looking at.
    self.current_display = self.platform.displays[0]

    ## @var transmitter_offset
    # The transmitter offset to be applied.
    self.transmitter_offset   = self.platform.transmitter_offset

    ## @var no_tracking_mat
    # The matrix to be applied when no tracking is available.
    self.no_tracking_mat      = self.platform.no_tracking_mat
    
    ## @var avatar_material
    # Material of the user's avatar.
    self.avatar_material = AVATAR_MATERIAL

    ## @var headtracking_target_name
    # Name of the headtracking station as registered in daemon.
    self.headtracking_target_name = HEADTRACKING_TARGET_NAME

    ## @var glasses_id
    # ID of the shutter glasses worn by the user. Used for frequency updates.
    self.glasses_id = GLASSES_ID

    ## @var headtracking_reader
    # Instance of a child class of TrackingReader to supply translation input.
    if HEADTRACKING_TARGET_NAME == None:
      self.headtracking_reader = TrackingDefaultReader()
      self.headtracking_reader.set_no_tracking_matrix(self.no_tracking_mat)
    else:
      self.headtracking_reader = TrackingTargetReader()
      self.headtracking_reader.my_constructor(HEADTRACKING_TARGET_NAME)
      self.headtracking_reader.set_transmitter_offset(self.transmitter_offset)
      self.headtracking_reader.set_receiver_offset(avango.gua.make_identity_mat())

    # create avatar representation
    if self.platform.avatar_type == "joseph" or self.platform.avatar_type == "None":
      self.create_avatar_representation(self.headtracking_reader.sf_avatar_head_mat, self.headtracking_reader.sf_avatar_body_mat)  
    else:
      if self.platform.avatar_type == "joseph_table":
        print_warning("Avatar type jospeh_table is deprecated. The creation of table avatars are now handled by the " + \
                       "device automatically. Use avatar type jospeh instead.")
      print_error("Error: Unknown avatar type " + self.platform.avatar_type, True)

    # toggles avatar display and activity
    self.toggle_user_activity(self.is_active, False)

    # init intersection class for proxy geometry hit test

    ## @var pick_length
    # Length of the picking ray in meters to check for screen intersections.
    self.pick_length = 5.0

    ## @var intersection_tester
    # Instance of Intersection to determine intersection points of user with screens.
    self.intersection_tester = Intersection()
    self.intersection_tester.my_constructor(self.APPLICATION_MANAGER.SCENEGRAPH
                                          , self.headtracking_reader.sf_global_mat
                                          , self.pick_length
                                          , "screen_proxy_group")
    self.mf_screen_pick_result.connect_from(self.intersection_tester.mf_pick_result)

    ## @var looking_outside_start
    # If the user is not facing a screen, the start time of this behaviour is saved to open glasses after a certain amount of time.
    self.looking_outside_start = None

    ## @var open_threshold
    # Time in seconds after which shutter glasses should open when no screen is hit by the viewing ray.
    self.open_threshold = 2.0

    ## @var timer
    # Time sensor to handle time events.
    self.timer = avango.nodes.TimeSensor()

    # set evaluation policy
    self.always_evaluate(True)
Example #15
0
import cv2, selectivesearch
import numpy as np
import Intersection as union

candidates = set()
while True:
    image = cv2.imread('image/dog.337.jpg')
    img_lbl, regions = selectivesearch.selective_search(image)

    for r in regions:
        candidates.add(r['rect'])
    for x, y, w, h in candidates:
        iou = union.get_union([71, 63, 189, 199], [x, y, x + w, y + h])
        if iou > .7:
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 233, 12), 1)
            cv2.putText(image, 'Dog', (x - 2, y - 2), 1, 1, (1, 22, 121), 1)
    cv2.imshow('', image)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()
class User(VisibilityHandler2D):

  ## @var mf_screen_pick_result
  # Intersections of the viewing ray with the screens in the setup.
  mf_screen_pick_result = avango.gua.MFPickResult()

  ## Default constructor.
  def __init__(self):
    self.super(User).__init__()

  ## Custom constructor.
  # @param WORKSPACE_INSTANCE Workspace instance in which this user is active.
  # @param USER_ID Global user ID to be applied.
  # @param VIP Boolean indicating if the user to be created is a vip.
  # @param AVATAR_VISIBILITY_TABLE A matrix containing visibility rules according to the DisplayGroups' visibility tags. 
  # @param HEADTRACKING_TARGET_NAME Name of the headtracking station as registered in daemon.
  # @param EYE_DISTANCE The eye distance of the user to be applied.
  # @param NO_TRACKING_MAT Matrix to be applied when HEADTRACKING_TARGET_NAME is None.
  def my_constructor(self
                   , WORKSPACE_INSTANCE
                   , USER_ID
                   , VIP
                   , AVATAR_VISIBILITY_TABLE
                   , HEADTRACKING_TARGET_NAME
                   , EYE_DISTANCE
                   , NO_TRACKING_MAT
                   ):

    self.table_constructor(AVATAR_VISIBILITY_TABLE)

    # flags 
    ## @var is_vip
    # Boolean indicating if this user has vip status.
    self.is_vip = VIP

    ## @var is_active
    # Boolean indicating if this user is currently active.
    self.is_active = True

    ## @var eye_distance
    # The eye distance of the user to be applied.
    self.eye_distance = EYE_DISTANCE

    # variables
    ## @var WORKSPACE_INSTANCE
    # Workspace instance at which this user is registered.
    self.WORKSPACE_INSTANCE = WORKSPACE_INSTANCE

    ## @var id
    # Identification number of the user within the workspace, starting from 0.
    self.id = USER_ID

    ## @var headtracking_target_name
    # Name of the headtracking station as registered in daemon.
    self.headtracking_target_name = HEADTRACKING_TARGET_NAME

    ## @var headtracking_reader
    # TrackingTargetReader for the user's glasses.
    if self.headtracking_target_name == None:
      self.headtracking_reader = TrackingDefaultReader()
      self.headtracking_reader.set_no_tracking_matrix(NO_TRACKING_MAT)
    else:
      self.headtracking_reader = TrackingTargetReader()
      self.headtracking_reader.my_constructor(HEADTRACKING_TARGET_NAME)
      self.headtracking_reader.set_transmitter_offset(self.WORKSPACE_INSTANCE.transmitter_offset)
      self.headtracking_reader.set_receiver_offset(avango.gua.make_identity_mat())

    ## @var user_representations
    # List of UserRepresentation instances for all display groups in the user's workspace.
    self.user_representations = []

    # toggles activity
    self.toggle_user_activity(self.is_active)

    ## @var intersection_tester
    # Instance of Intersection to determine intersection points of user with screens.
    self.intersection_tester = Intersection()
    self.intersection_tester.my_constructor(scenegraphs[0]
                                          , self.headtracking_reader.sf_abs_mat
                                          , 5.0
                                          , "screen_proxy_group"
                                          , False)
    self.mf_screen_pick_result.connect_from(self.intersection_tester.mf_pick_result)

    ## @var last_seen_display_group
    # DisplayGroup instance for which the user's viewing ray lastly hit a screen proxy geometry.
    self.last_seen_display_group = None

    self.always_evaluate(True)

  ## Evaluated every frame.
  def evaluate(self):

    # evaluate viewing ray intersections with screen proxy geometries
    for _i in range(len(self.mf_screen_pick_result.value)):

      _pick_object = self.mf_screen_pick_result.value[_i].Object.value

      # only consider own workspace geometries
      if _pick_object.Name.value.startswith("proxy_w" + str(self.WORKSPACE_INSTANCE.id)):
        _display_group_id = int(_pick_object.Name.value.split("_")[2].replace("dg", ""))
        self.last_seen_display_group = self.WORKSPACE_INSTANCE.display_groups[_display_group_id]
        break

    _track_vec = self.headtracking_reader.sf_abs_vec.value

    if _track_vec.x < -1.5 and _track_vec.x > -2.4 and \
       _track_vec.y < 1.05 and _track_vec.y > 0.95 and \
       _track_vec.z < 1.35 and _track_vec.z > 0.16:

      self.toggle_user_activity(False)

    else:

      self.toggle_user_activity(True)

  ## Changes the visibility table during runtime.
  # @param VISIBILITY_TABLE A matrix containing visibility rules according to the DisplayGroups' visibility tags. 
  def change_visiblity_table(self, VISIBILITY_TABLE):

    self.visibility_table = VISIBILITY_TABLE

    for _display_group in self.WORKSPACE_INSTANCE.display_groups:
      self.handle_correct_visibility_groups_for(_display_group)

  ## Creates a UserRepresentation instance for a given display group.
  # @param DISPLAY_GROUP Reference to the DisplayGroup instance to create the user representation for.
  # @param VIEW_TRANSFORM_NODE Transform node to be filled by one navigation of the display group.
  # @param HEAD_NODE_NAME Name of the UserRepresentation's head node in the scenegraph.
  # @param COMPLEX_SETUP If activated, the transformation policy is evaluated every frame to update head. If deactivated,
  #                      a standard mono viewing setup is assumed.
  def create_user_representation_for(self, DISPLAY_GROUP, VIEW_TRANSFORM_NODE, HEAD_NODE_NAME = "head", COMPLEX_SETUP = True):

    _user_repr = UserRepresentation()
    _user_repr.my_constructor(self, DISPLAY_GROUP, VIEW_TRANSFORM_NODE, HEAD_NODE_NAME, COMPLEX_SETUP)
    self.user_representations.append(_user_repr)
    return _user_repr

  ## Returns the UserRepresentation instance at a given DISPLAY_GROUP.
  # @param DISPLAY_GROUP The  DisplayGroup to retrieve the UserRepresentation for.
  def get_user_representation_at(self, DISPLAY_GROUP):

    for _user_repr in self.user_representations:
      if _user_repr.DISPLAY_GROUP == DISPLAY_GROUP:
        return _user_repr

  ## Switches the navigation for a display group.
  # @param DISPLAY_GROUP_ID Identification number of the display group to switch the navigation for.
  # @param NAVIGATION_ID Identification number of the navigation to be used within the display group.
  # @param WORKSPACE_USERS A list of all Users active in the workspace.
  def switch_navigation_at_display_group(self, DISPLAY_GROUP_ID, NAVIGATION_ID, WORKSPACE_USERS):
    
    if DISPLAY_GROUP_ID < len(self.user_representations):
      
      # switch navigation to desired one for DISPLAY_GROUP_ID
      _old_nav_id = self.user_representations[DISPLAY_GROUP_ID].connected_navigation_id

      self.user_representations[DISPLAY_GROUP_ID].connect_navigation_of_display_group(NAVIGATION_ID)
      _display_group_instance = self.user_representations[DISPLAY_GROUP_ID].DISPLAY_GROUP

      # trigger correct tool visibilities at display group
      for _tool in self.WORKSPACE_INSTANCE.tools:
        _tool.handle_correct_visibility_groups_for(_display_group_instance)

      # trigger correct avatar and screen visibilities
      #for _user in WORKSPACE_USERS:
      #  _user.handle_correct_visibility_groups_for(_display_group_instance)

      # trigger correct video visibilites at both navigations
      if self.WORKSPACE_INSTANCE.video_3D != None and ApplicationManager.current_avatar_mode == "VIDEO":
        _old_nav = self.WORKSPACE_INSTANCE.display_groups[DISPLAY_GROUP_ID].navigations[_old_nav_id]
        _new_nav = self.WORKSPACE_INSTANCE.display_groups[DISPLAY_GROUP_ID].navigations[NAVIGATION_ID]
        self.WORKSPACE_INSTANCE.video_3D.handle_correct_visibility_groups_for(_old_nav)
        self.WORKSPACE_INSTANCE.video_3D.handle_correct_visibility_groups_for(_new_nav)
      else:
        for _user in WORKSPACE_USERS:
          _user.handle_correct_visibility_groups_for(_display_group_instance)

    else:
      print_error("Error. Display Group ID does not exist.", False)

    
  ## Sets the user's active flag.
  # @param ACTIVE Boolean to which the active flag should be set.
  def toggle_user_activity(self, ACTIVE):

    if ACTIVE:
      self.is_active = True
    else:
      self.is_active = False

  ## Handles the correct GroupNames of all UserRepresentations at a display group.
  # @param DISPLAY_GROUP The DisplayGroup to be handled.
  def handle_correct_visibility_groups_for(self, DISPLAY_GROUP):

    # All UserRepresentation instances at DISPLAY_GROUP
    # normally, this list should just contain one user representation
    # in case of portals, however, a display group may have more than one user representation
    _user_representations_at_display_group = []

    for _user_repr in self.user_representations:
      
      if _user_repr.DISPLAY_GROUP == DISPLAY_GROUP:
        _user_representations_at_display_group.append(_user_repr)
        
    # for all found user representations in the given display group
    for _user_repr_at_display_group in _user_representations_at_display_group:

      # display group instance belonging to DISPLAY_GROUP
      _handled_display_group_instance = _user_repr_at_display_group.DISPLAY_GROUP

      _all_user_reprs_at_display_group = []

      for _user_repr in ApplicationManager.all_user_representations:
        if _user_repr.DISPLAY_GROUP == _handled_display_group_instance:
          _all_user_reprs_at_display_group.append(_user_repr)

      ## determine which group names have to be added to the user representations ##
      _user_visible_for = []

      # when video avatars are enabled, do not make josephs visible
      if ApplicationManager.current_avatar_mode == "JOSEPH":
        
        # append all names of user representations which are not on same navigation
        for _user_repr in _all_user_reprs_at_display_group:

          if _user_repr.connected_navigation_id != _user_repr_at_display_group.connected_navigation_id:
            _user_visible_for.append(_user_repr.view_transform_node.Name.value)

        # check for all user representations outside the handled display group
        for _user_repr in ApplicationManager.all_user_representations:
          if _user_repr.DISPLAY_GROUP != _handled_display_group_instance:

            # consider visibility table
            _handled_display_group_tag = _handled_display_group_instance.visibility_tag
            _user_repr_display_group_tag = _user_repr.DISPLAY_GROUP.visibility_tag
            
            try:
              _visible = self.visibility_table[_user_repr_display_group_tag][_handled_display_group_tag]
            except:
              _visible = False
            
            if _visible:
              if _user_repr.is_in_virtual_display():
                _user_visible_for.append(_user_repr.view_transform_node.Parent.value.Name.value + "_" + _user_repr.head.Name.value)
              else:
                _user_visible_for.append(_user_repr.view_transform_node.Name.value)

      # apply the obtained group names to the user representation
      if len(_user_visible_for) == 0:

        # prevent wildcard from rendering the avatar
        _user_repr_at_display_group.set_avatar_group_names(["do_not_display_group"])

      else:

        for _string in _user_visible_for:
          _user_repr_at_display_group.set_avatar_group_names(_user_visible_for)
class GroundFollowing(avango.script.Script):

  # input field
  ## @var sf_abs_input_mat
  # The input matrix to be corrected by the ground following algorithm.
  sf_abs_input_mat = avango.gua.SFMatrix4()
  sf_abs_input_mat.value = avango.gua.make_identity_mat()

  # output field
  ## @var sf_abs_output_mat
  # The corrected matrix after the ground following algorithm was applied.
  sf_abs_output_mat = avango.gua.SFMatrix4()
  sf_abs_output_mat.value = avango.gua.make_identity_mat()

  # internal fields
  ## @var sf_gf_start_mat
  # The matrix representing the position where the sent ray to the ground starts. 
  sf_gf_start_mat = avango.gua.SFMatrix4()
  sf_gf_start_mat.value = avango.gua.make_identity_mat()

  ## @var sf_station_mat
  # The matrix representing the position of the device belonging to the platform.
  sf_station_mat = avango.gua.SFMatrix4()
  sf_station_mat.value = avango.gua.make_identity_mat()

  ## @var sf_scale
  # The current scaling factor of the Navigation.
  sf_scale = avango.SFFloat()
  sf_scale.value = 1.0

  ## @var mf_ground_pick_result
  # Intersections of the ground following ray with the objects in the scene.
  mf_ground_pick_result = avango.gua.MFPickResult()

  ## Default constructor.
  def __init__(self):
    self.super(GroundFollowing).__init__()

  ## Custom constructor.
  # @param SCENEGRAPH Reference to the scenegraph of the currently displayed scene.
  # @param SF_STATION_MAT The field containing the current position of the device belonging to the platform.
  # @param RAY_START_HEIGHT A height from which the ground following ray will originate.
  def my_constructor(self, SCENEGRAPH, SF_STATION_MAT, RAY_START_HEIGHT):
    
    # attributes
    ## @var activated
    # Indicates if the ground following algorithm is activated or deactivated. In the last case,
    # the input matrix is simply passed through.
    self.activated = False

    ## @var falling
    # A boolean indicating if the user is currently falling. Used for fall speed computations.
    self.falling = False

    ## @var initial_fall_velocity
    # The starting velocity when the user is falling in meters per frame. Is increased the longer the falling process goes on.
    self.initial_fall_velocity = 0.05

    ## @var height_modification_factor
    # Scaling factor used for the modification of up and down vectors.
    self.height_modification_factor = 0.1

    # fall velocity in meter per frame
    ## @var fall_velocity
    # Speed when the user is falling in meters per frame.
    self.fall_velocity = self.initial_fall_velocity

    # pick length in meter
    ## @var ground_pick_length
    # Length of the ground following ray.
    self.ground_pick_length = 100.0

    ## @var ground_pick_direction_mat
    # Direction of the ground following ray.
    self.ground_pick_direction_mat = avango.gua.make_identity_mat()

    ## @var SCENEGRAPH
    # Reference to the scenegraph to intersect the ground following ray with.
    self.SCENEGRAPH = SCENEGRAPH

    ## @var ray_start_height
    # Starting height of the ground following ray.
    self.ray_start_height = RAY_START_HEIGHT

    # initialize shoot and output matrices
    self.sf_abs_output_mat.value = self.sf_abs_input_mat.value

    self.set_pick_direction(avango.gua.Vec3(0.0, -1.0, 0.0))

    # init field connections
    self.sf_station_mat.connect_from(SF_STATION_MAT)

    # init internal class
    ## @var ground_intersection
    # Intersection class to determine the intersections of the ground following ray with the objects in the scenegraph.
    self.ground_intersection = Intersection()
    self.ground_intersection.my_constructor(SCENEGRAPH, self.sf_gf_start_mat, self.ground_pick_length, "gf_pick_group")
    self.mf_ground_pick_result.connect_from(self.ground_intersection.mf_pick_result)


  ## Evaluated every frame.
  def evaluate(self):
    if self.activated == True:
      # platform translation in the world
      _platform_trans_vec = self.sf_abs_input_mat.value.get_translate()

      # tracked device translation on the platform
      _device_trans_vec = self.sf_station_mat.value.get_translate()

      # prepare ground following matrix
      _gf_start_pos = self.sf_station_mat.value.get_translate()
      _gf_start_pos.y = self.ray_start_height
      _gf_start_pos *= self.sf_scale.value
      _gf_start_pos = self.sf_abs_input_mat.value * _gf_start_pos
      _gf_start_pos = avango.gua.Vec3(_gf_start_pos.x, _gf_start_pos.y, _gf_start_pos.z)
      self.sf_gf_start_mat.value = avango.gua.make_trans_mat(_gf_start_pos) * self.ground_pick_direction_mat

      if len(self.mf_ground_pick_result.value) > 0: # an intersection with the ground was found

        # get first intersection target
        _pick_result = self.mf_ground_pick_result.value[0]             
        #print _pick_result.Object.value, _pick_result.Object.value.Name.value

        # compare distance to ground and ray_start_height
        _distance_to_ground = _pick_result.Distance.value * self.ground_pick_length
        _difference = _distance_to_ground - (self.ray_start_height * self.sf_scale.value)
        _difference = round(_difference, 3)

        if _difference < 0: # climb up

          # end falling when necessary
          if self.falling:
            self.falling = False
            self.fall_velocity = self.initial_fall_velocity 

          # move player up
          _up_vec = avango.gua.Vec3(0.0, _difference * -1.0 * self.height_modification_factor, 0.0)
          self.sf_abs_output_mat.value = avango.gua.make_trans_mat(_up_vec) * self.sf_abs_input_mat.value

        elif _difference > 0:
          
          if _difference > (self.ray_start_height * self.sf_scale.value): # falling

            # make player fall down faster every time
            self.falling = True
            _fall_vec = avango.gua.Vec3(0.0, -self.fall_velocity, 0.0)
            self.sf_abs_output_mat.value = avango.gua.make_trans_mat(_fall_vec) * self.sf_abs_input_mat.value
            self.fall_velocity += 0.005

          else: # climb down
            
            # end falling when necessary
            if self.falling:
              self.falling = False
              self.fall_velocity = self.initial_fall_velocity 

            # move player down
            _down_vec = avango.gua.Vec3(0.0, _difference * -1.0 * self.height_modification_factor, 0.0)
            self.sf_abs_output_mat.value = avango.gua.make_trans_mat(_down_vec) * self.sf_abs_input_mat.value

        else:
          self.sf_abs_output_mat.value = self.sf_abs_input_mat.value        # player remains on ground

      else:
        #print "None"
        self.sf_abs_output_mat.value = self.sf_abs_input_mat.value          # no intersection with ground was found
  
    else:
      self.sf_abs_output_mat.value = self.sf_abs_input_mat.value            # ground following is deactivated


  ## Sets the pick_direction attribute.
  # @param PICK_DIRECTION New pick direction.
  def set_pick_direction(self, PICK_DIRECTION):

    PICK_DIRECTION.normalize()
    
    _ref = avango.gua.Vec3(0.0,0.0,-1.0)
    _angle = math.degrees(math.acos(_ref.dot(PICK_DIRECTION)))
    _axis = _ref.cross(PICK_DIRECTION)

    self.ground_pick_direction_mat = avango.gua.make_rot_mat(_angle, _axis)


  ## Activates the ground following algorithm.
  def activate(self):
    self.activated = True
    self.ground_intersection.activate(True)

  ## Deactivates the ground following algorithm. The input matrix is just passed through after calling this method.
  def deactivate(self):
    self.activated = False
    self.ground_intersection.activate(False)
Example #18
0
class GroundFollowing(avango.script.Script):

    # input field
    ## @var sf_abs_input_mat
    # The input matrix to be corrected by the ground following algorithm.
    sf_abs_input_mat = avango.gua.SFMatrix4()
    sf_abs_input_mat.value = avango.gua.make_identity_mat()

    # output field
    ## @var sf_abs_output_mat
    # The corrected matrix after the ground following algorithm was applied.
    sf_abs_output_mat = avango.gua.SFMatrix4()
    sf_abs_output_mat.value = avango.gua.make_identity_mat()

    # internal fields
    ## @var sf_gf_start_mat
    # The matrix representing the position where the sent ray to the ground starts.
    sf_gf_start_mat = avango.gua.SFMatrix4()
    sf_gf_start_mat.value = avango.gua.make_identity_mat()

    ## @var sf_station_mat
    # The matrix representing the position of the device belonging to the platform.
    sf_station_mat = avango.gua.SFMatrix4()
    sf_station_mat.value = avango.gua.make_identity_mat()

    ## @var sf_scale
    # The current scaling factor of the Navigation.
    sf_scale = avango.SFFloat()
    sf_scale.value = 1.0

    ## @var mf_ground_pick_result
    # Intersections of the ground following ray with the objects in the scene.
    mf_ground_pick_result = avango.gua.MFPickResult()

    ## Default constructor.
    def __init__(self):
        self.super(GroundFollowing).__init__()

    ## Custom constructor.
    # @param SF_STATION_MAT The field containing the current position of the device belonging to the platform.
    # @param RAY_START_HEIGHT A height from which the ground following ray will originate.
    def my_constructor(self, SF_STATION_MAT, RAY_START_HEIGHT):

        # attributes
        ## @var activated
        # Indicates if the ground following algorithm is activated or deactivated. In the last case,
        # the input matrix is simply passed through.
        self.activated = False

        ## @var falling
        # A boolean indicating if the user is currently falling. Used for fall speed computations.
        self.falling = False

        ## @var initial_fall_velocity
        # The starting velocity when the user is falling in meters per frame. Is increased the longer the falling process goes on.
        self.initial_fall_velocity = 0.05

        ## @var height_modification_factor
        # Scaling factor used for the modification of up and down vectors.
        self.height_modification_factor = 0.15

        # fall velocity in meter per frame
        ## @var fall_velocity
        # Speed when the user is falling in meters per frame.
        self.fall_velocity = self.initial_fall_velocity

        # pick length in meter
        ## @var ground_pick_length
        # Length of the ground following ray.
        self.ground_pick_length = 100.0

        ## @var ground_pick_direction_mat
        # Direction of the ground following ray.
        self.ground_pick_direction_mat = avango.gua.make_identity_mat()

        ## @var SCENEGRAPH
        # Reference to the scenegraph to intersect the ground following ray with.
        self.SCENEGRAPH = scenegraphs[0]

        ## @var ray_start_height
        # Starting height of the ground following ray.
        self.ray_start_height = RAY_START_HEIGHT

        # initialize shoot and output matrices
        self.sf_abs_output_mat.value = self.sf_abs_input_mat.value

        self.set_pick_direction(avango.gua.Vec3(0.0, -1.0, 0.0))

        # init field connections
        self.sf_station_mat.connect_from(SF_STATION_MAT)

        # init internal class
        ## @var ground_intersection
        # Intersection class to determine the intersections of the ground following ray with the objects in the scenegraph.
        self.ground_intersection = Intersection()
        self.ground_intersection.my_constructor(self.SCENEGRAPH,
                                                self.sf_gf_start_mat,
                                                self.ground_pick_length,
                                                "gf_pick_group")
        self.mf_ground_pick_result.connect_from(
            self.ground_intersection.mf_pick_result)

    ## Evaluated every frame.
    def evaluate(self):
        if self.activated == True:
            # platform translation in the world
            _platform_trans_vec = self.sf_abs_input_mat.value.get_translate()

            # tracked device translation on the platform
            _device_trans_vec = self.sf_station_mat.value.get_translate()

            # prepare ground following matrix
            _gf_start_pos = self.sf_station_mat.value.get_translate()
            _gf_start_pos.y = self.ray_start_height
            _gf_start_pos *= self.sf_scale.value
            _gf_start_pos = self.sf_abs_input_mat.value * _gf_start_pos
            _gf_start_pos = avango.gua.Vec3(_gf_start_pos.x, _gf_start_pos.y,
                                            _gf_start_pos.z)
            self.sf_gf_start_mat.value = avango.gua.make_trans_mat(
                _gf_start_pos) * self.ground_pick_direction_mat

            if len(self.mf_ground_pick_result.value
                   ) > 0:  # an intersection with the ground was found

                # get first intersection target
                _pick_result = self.mf_ground_pick_result.value[0]
                #print _pick_result.Object.value, _pick_result.Object.value.Name.value

                # compare distance to ground and ray_start_height
                _distance_to_ground = _pick_result.Distance.value * self.ground_pick_length
                _difference = _distance_to_ground - (self.ray_start_height *
                                                     self.sf_scale.value)
                _difference = round(_difference, 3)

                if _difference < 0:  # climb up

                    # end falling when necessary
                    if self.falling:
                        self.falling = False
                        self.fall_velocity = self.initial_fall_velocity

                    # move player up
                    _up_vec = avango.gua.Vec3(
                        0.0,
                        _difference * -1.0 * self.height_modification_factor,
                        0.0)
                    self.sf_abs_output_mat.value = avango.gua.make_trans_mat(
                        _up_vec) * self.sf_abs_input_mat.value

                elif _difference > 0:

                    if _difference > (self.ray_start_height *
                                      self.sf_scale.value):  # falling

                        # make player fall down faster every time
                        self.falling = True
                        _fall_vec = avango.gua.Vec3(0.0, -self.fall_velocity,
                                                    0.0)
                        self.sf_abs_output_mat.value = avango.gua.make_trans_mat(
                            _fall_vec) * self.sf_abs_input_mat.value
                        self.fall_velocity += 0.005

                    else:  # climb down

                        # end falling when necessary
                        if self.falling:
                            self.falling = False
                            self.fall_velocity = self.initial_fall_velocity

                        # move player down
                        _down_vec = avango.gua.Vec3(
                            0.0, _difference * -1.0 *
                            self.height_modification_factor, 0.0)
                        self.sf_abs_output_mat.value = avango.gua.make_trans_mat(
                            _down_vec) * self.sf_abs_input_mat.value

                else:
                    self.sf_abs_output_mat.value = self.sf_abs_input_mat.value  # player remains on ground

            else:
                #print "None"
                self.sf_abs_output_mat.value = self.sf_abs_input_mat.value  # no intersection with ground was found

        else:
            self.sf_abs_output_mat.value = self.sf_abs_input_mat.value  # ground following is deactivated

    ## Sets the pick_direction attribute.
    # @param PICK_DIRECTION New pick direction.
    def set_pick_direction(self, PICK_DIRECTION):

        PICK_DIRECTION.normalize()

        _ref = avango.gua.Vec3(0.0, 0.0, -1.0)
        _angle = math.degrees(math.acos(_ref.dot(PICK_DIRECTION)))
        _axis = _ref.cross(PICK_DIRECTION)

        self.ground_pick_direction_mat = avango.gua.make_rot_mat(_angle, _axis)

    ## Activates the ground following algorithm.
    def activate(self):
        self.activated = True
        self.ground_intersection.activate(True)

    ## Deactivates the ground following algorithm. The input matrix is just passed through after calling this method.
    def deactivate(self):
        self.activated = False
        self.ground_intersection.activate(False)
Example #19
0
    def bruteForce(self, graph):
        # get a random word to start with
        keys = list(graph.keys())
        randomIndex0 = random.randint(0, len(keys) - 1)
        randomLetter = keys[
            randomIndex0]  # Gives us a list of words from graph[some random letter]
        wordList = graph[randomLetter]
        randomIndex1 = random.randint(0, len(wordList) - 1)
        startWord = wordList[randomIndex1]

        Q = deque(
            []
        )  # initialize a queue that will store each word that has been added to the crossword
        Q.append(startWord)
        allWords = []
        allWords.append(startWord)
        # initialize a crossword that contains that start word
        crossword = CrosswordRepresentation({startWord: None}, {})
        board = Board(crossword)

        # this outer loop continues until we have the desired number of words in our crossword
        currentWordIsAcross = True
        while len(Q) > 0:  # while Q is not empty
            currentWord = Q.popleft(
            )  # removes the first element in the Queue.

            # updates currentWordIsAcross depending on whether or not
            # the current word is in the across or down dictionary keys.
            if currentWord in board.crossword.across.keys():
                currentWordIsAcross = True
            elif currentWord in board.crossword.down.keys():
                currentWordIsAcross = False

            # loops through each letter in the current word and try's to add a word on each letter.
            for x in range(0, len(currentWord), 2):
                neighbors = graph[currentWord[
                    x]]  # list of all words that have the letter of currentWord[x] in them.
                for neighbor in neighbors:  # Searches through all the neighbors for a potentially valid word to add.
                    newWord = neighbor
                    if currentWordIsAcross and newWord not in Q and newWord not in allWords:
                        intersection = Intersection(
                            currentWord, newWord, x,
                            newWord.find(currentWord[x]))
                        # print("Current word: " + currentWord + ", list: " + str(board.crossword.across))
                        firstCell = board.crossword.across[currentWord]
                        interCell = board.getCellAt(firstCell.xCoord + x,
                                                    firstCell.yCoord)
                        if interCell is not None and board.addIfValid(
                                interCell, intersection, False):
                            Q.append(newWord)
                            allWords.append(newWord)
                            board.terminalRepresentationOfCrossword(
                            )  # prints the crossword in the terminal as it is.
                            print("--------------")
                            break  # We don't want to keep looping through all the neighbors if we found a valid one.
                    elif not currentWordIsAcross and newWord not in Q and newWord not in allWords:
                        intersection = Intersection(
                            newWord, currentWord, newWord.find(currentWord[x]),
                            x)
                        # print("Current word: "+currentWord+", list: "+str(board.crossword.down))
                        firstCell = board.crossword.down[currentWord]
                        interCell = board.getCellAt(firstCell.xCoord,
                                                    firstCell.yCoord + x)
                        if interCell is not None and board.addIfValid(
                                interCell, intersection, True):
                            Q.append(newWord)
                            allWords.append(newWord)
                            board.terminalRepresentationOfCrossword(
                            )  # prints the crossword in the terminal as it is.
                            print("--------------")
                            break
        return board
class User(VisibilityHandler2D):

    ## @var mf_screen_pick_result
    # Intersections of the viewing ray with the screens in the setup.
    mf_screen_pick_result = avango.gua.MFPickResult()

    ## Default constructor.
    def __init__(self):
        self.super(User).__init__()

    ## Custom constructor.
    # @param WORKSPACE_INSTANCE Workspace instance in which this user is active.
    # @param USER_ID Global user ID to be applied.
    # @param VIP Boolean indicating if the user to be created is a vip.
    # @param AVATAR_VISIBILITY_TABLE A matrix containing visibility rules according to the DisplayGroups' visibility tags.
    # @param HEADTRACKING_TARGET_NAME Name of the headtracking station as registered in daemon.
    # @param EYE_DISTANCE The eye distance of the user to be applied.
    # @param NO_TRACKING_MAT Matrix to be applied when HEADTRACKING_TARGET_NAME is None.
    def my_constructor(self, WORKSPACE_INSTANCE, USER_ID, VIP,
                       AVATAR_VISIBILITY_TABLE, HEADTRACKING_TARGET_NAME,
                       EYE_DISTANCE, NO_TRACKING_MAT):

        self.table_constructor(AVATAR_VISIBILITY_TABLE)

        # flags
        ## @var is_vip
        # Boolean indicating if this user has vip status.
        self.is_vip = VIP

        ## @var is_active
        # Boolean indicating if this user is currently active.
        self.is_active = True

        ## @var eye_distance
        # The eye distance of the user to be applied.
        self.eye_distance = EYE_DISTANCE

        # variables
        ## @var WORKSPACE_INSTANCE
        # Workspace instance at which this user is registered.
        self.WORKSPACE_INSTANCE = WORKSPACE_INSTANCE

        ## @var id
        # Identification number of the user within the workspace, starting from 0.
        self.id = USER_ID

        ## @var headtracking_target_name
        # Name of the headtracking station as registered in daemon.
        self.headtracking_target_name = HEADTRACKING_TARGET_NAME

        ## @var headtracking_reader
        # TrackingTargetReader for the user's glasses.
        if self.headtracking_target_name == None:
            self.headtracking_reader = TrackingDefaultReader()
            self.headtracking_reader.set_no_tracking_matrix(NO_TRACKING_MAT)
        else:
            self.headtracking_reader = TrackingTargetReader()
            self.headtracking_reader.my_constructor(HEADTRACKING_TARGET_NAME)
            self.headtracking_reader.set_transmitter_offset(
                self.WORKSPACE_INSTANCE.transmitter_offset)
            self.headtracking_reader.set_receiver_offset(
                avango.gua.make_identity_mat())

        ## @var user_representations
        # List of UserRepresentation instances for all display groups in the user's workspace.
        self.user_representations = []

        # toggles activity
        self.toggle_user_activity(self.is_active)

        ## @var intersection_tester
        # Instance of Intersection to determine intersection points of user with screens.
        self.intersection_tester = Intersection()
        self.intersection_tester.my_constructor(
            scenegraphs[0], self.headtracking_reader.sf_abs_mat, 5.0,
            "screen_proxy_group", False)
        self.mf_screen_pick_result.connect_from(
            self.intersection_tester.mf_pick_result)

        ## @var last_seen_display_group
        # DisplayGroup instance for which the user's viewing ray lastly hit a screen proxy geometry.
        self.last_seen_display_group = None

        self.always_evaluate(True)

    ## Evaluated every frame.
    def evaluate(self):

        # evaluate viewing ray intersections with screen proxy geometries
        for _i in range(len(self.mf_screen_pick_result.value)):

            _pick_object = self.mf_screen_pick_result.value[_i].Object.value

            # only consider own workspace geometries
            if _pick_object.Name.value.startswith(
                    "proxy_w" + str(self.WORKSPACE_INSTANCE.id)):
                _display_group_id = int(
                    _pick_object.Name.value.split("_")[2].replace("dg", ""))
                self.last_seen_display_group = self.WORKSPACE_INSTANCE.display_groups[
                    _display_group_id]
                break

        _track_vec = self.headtracking_reader.sf_abs_vec.value

        if _track_vec.x < -1.5 and _track_vec.x > -2.4 and \
           _track_vec.y < 1.05 and _track_vec.y > 0.95 and \
           _track_vec.z < 1.35 and _track_vec.z > 0.16:

            self.toggle_user_activity(False)

        else:

            self.toggle_user_activity(True)

    ## Changes the visibility table during runtime.
    # @param VISIBILITY_TABLE A matrix containing visibility rules according to the DisplayGroups' visibility tags.
    def change_visiblity_table(self, VISIBILITY_TABLE):

        self.visibility_table = VISIBILITY_TABLE

        for _display_group in self.WORKSPACE_INSTANCE.display_groups:
            self.handle_correct_visibility_groups_for(_display_group)

    ## Creates a UserRepresentation instance for a given display group.
    # @param DISPLAY_GROUP Reference to the DisplayGroup instance to create the user representation for.
    # @param VIEW_TRANSFORM_NODE Transform node to be filled by one navigation of the display group.
    # @param VIRTUAL_USER_REPR_DISPLAY_INDEX If this is a portal user representation, ID giving the display index within the display group. -1 otherwise.
    # @param HEAD_NODE_NAME Name of the UserRepresentation's head node in the scenegraph.
    # @param COMPLEX_SETUP If activated, the transformation policy is evaluated every frame to update head. If deactivated,
    #                      a standard mono viewing setup is assumed.
    def create_user_representation_for(self,
                                       DISPLAY_GROUP,
                                       VIEW_TRANSFORM_NODE,
                                       VIRTUAL_USER_REPR_DISPLAY_INDEX=-1,
                                       HEAD_NODE_NAME="head",
                                       COMPLEX_SETUP=True):

        _user_repr = UserRepresentation()
        _user_repr.my_constructor(self, DISPLAY_GROUP, VIEW_TRANSFORM_NODE,
                                  VIRTUAL_USER_REPR_DISPLAY_INDEX,
                                  HEAD_NODE_NAME, COMPLEX_SETUP)
        self.user_representations.append(_user_repr)
        return _user_repr

    ## Returns the UserRepresentation instance at a diven DISPLAY_GROUP_ID.
    # @param DISPLAY_GROUP_ID The id of the DisplayGroup to retrieve the UserRepresentation for.
    def get_user_representation_at(self, DISPLAY_GROUP_ID):
        return self.user_representations[DISPLAY_GROUP_ID]

    ## Switches the navigation for a display group.
    # @param DISPLAY_GROUP_ID Identification number of the display group to switch the navigation for.
    # @param NAVIGATION_ID Identification number of the navigation to be used within the display group.
    # @param WORKSPACE_USERS A list of all Users active in the workspace.
    def switch_navigation_at_display_group(self, DISPLAY_GROUP_ID,
                                           NAVIGATION_ID, WORKSPACE_USERS):

        if DISPLAY_GROUP_ID < len(self.user_representations):

            # switch navigation to desired one for DISPLAY_GROUP_ID
            _old_nav_id = self.user_representations[
                DISPLAY_GROUP_ID].connected_navigation_id

            self.user_representations[
                DISPLAY_GROUP_ID].connect_navigation_of_display_group(
                    NAVIGATION_ID)
            _display_group_instance = self.user_representations[
                DISPLAY_GROUP_ID].DISPLAY_GROUP

            # trigger correct tool visibilities at display group
            for _tool in self.WORKSPACE_INSTANCE.tools:
                _tool.handle_correct_visibility_groups_for(
                    _display_group_instance)

            # trigger correct avatar and screen visibilities
            #for _user in WORKSPACE_USERS:
            #  _user.handle_correct_visibility_groups_for(_display_group_instance)

            # trigger correct video visibilites at both navigations
            if self.WORKSPACE_INSTANCE.video_3D != None and ApplicationManager.current_avatar_mode == "VIDEO":
                _old_nav = self.WORKSPACE_INSTANCE.display_groups[
                    DISPLAY_GROUP_ID].navigations[_old_nav_id]
                _new_nav = self.WORKSPACE_INSTANCE.display_groups[
                    DISPLAY_GROUP_ID].navigations[NAVIGATION_ID]
                self.WORKSPACE_INSTANCE.video_3D.handle_correct_visibility_groups_for(
                    _old_nav)
                self.WORKSPACE_INSTANCE.video_3D.handle_correct_visibility_groups_for(
                    _new_nav)
            else:
                for _user in WORKSPACE_USERS:
                    _user.handle_correct_visibility_groups_for(
                        _display_group_instance)

        else:
            print_error("Error. Display Group ID does not exist.", False)

    ## Sets the user's active flag.
    # @param ACTIVE Boolean to which the active flag should be set.
    def toggle_user_activity(self, ACTIVE):

        if ACTIVE:
            self.is_active = True
        else:
            self.is_active = False

    ## Handles the correct GroupNames of all UserRepresentations at a display group.
    # @param DISPLAY_GROUP The DisplayGroup to be handled.
    def handle_correct_visibility_groups_for(self, DISPLAY_GROUP):

        # All UserRepresentation instances at DISPLAY_GROUP
        # normally, this list should just contain one user representation
        # in case of portals, however, a display group may have more than one user representation
        _user_representations_at_display_group = []

        for _user_repr in self.user_representations:

            if _user_repr.DISPLAY_GROUP == DISPLAY_GROUP:
                _user_representations_at_display_group.append(_user_repr)

        # for all found user representations in the given display group
        for _user_repr_at_display_group in _user_representations_at_display_group:

            # display group instance belonging to DISPLAY_GROUP
            _handled_display_group_instance = _user_repr_at_display_group.DISPLAY_GROUP

            _all_user_reprs_at_display_group = []

            for _user_repr in ApplicationManager.all_user_representations:
                if _user_repr.DISPLAY_GROUP == _handled_display_group_instance:
                    _all_user_reprs_at_display_group.append(_user_repr)

            ## determine which group names have to be added to the user representations ##
            _user_visible_for = []

            # when video avatars are enabled, do not make josephs visible
            if ApplicationManager.current_avatar_mode == "JOSEPH":

                # append all names of user representations which are not on same navigation
                for _user_repr in _all_user_reprs_at_display_group:

                    if _user_repr.connected_navigation_id != _user_repr_at_display_group.connected_navigation_id:
                        _user_visible_for.append(
                            _user_repr.view_transform_node.Name.value)

                # check for all user representations outside the handled display group
                for _user_repr in ApplicationManager.all_user_representations:
                    if _user_repr.DISPLAY_GROUP != _handled_display_group_instance:

                        # consider visibility table
                        _handled_display_group_tag = _handled_display_group_instance.visibility_tag
                        _user_repr_display_group_tag = _user_repr.DISPLAY_GROUP.visibility_tag

                        try:
                            _visible = self.visibility_table[
                                _user_repr_display_group_tag][
                                    _handled_display_group_tag]
                        except:
                            _visible = False

                        if _visible:
                            if _user_repr.view_transform_node.Name.value == "scene_matrix":
                                _user_visible_for.append(
                                    _user_repr.view_transform_node.Parent.
                                    value.Name.value + "_" +
                                    _user_repr.head.Name.value)
                            else:
                                _user_visible_for.append(
                                    _user_repr.view_transform_node.Name.value)

            # apply the obtained group names to the user representation
            if len(_user_visible_for) == 0:

                # prevent wildcard from rendering the avatar
                _user_repr_at_display_group.set_avatar_group_names(
                    ["do_not_display_group"])

            else:

                for _string in _user_visible_for:
                    _user_repr_at_display_group.set_avatar_group_names(
                        _user_visible_for)
Example #21
0
class GroundFollowing(avango.script.Script):

    # input field
    ## @var sf_abs_input_mat
    # The input matrix to be corrected by the ground following algorithm.
    sf_abs_input_mat = avango.gua.SFMatrix4()
    sf_abs_input_mat.value = avango.gua.make_identity_mat()

    # output field
    ## @var sf_abs_output_mat
    # The corrected matrix after the ground following algorithm was applied.
    sf_abs_output_mat = avango.gua.SFMatrix4()
    sf_abs_output_mat.value = avango.gua.make_identity_mat()

    # internal fields
    ## @var sf_gf_start_mat
    # The matrix representing the position where the sent ray to the ground starts.
    sf_gf_start_mat = avango.gua.SFMatrix4()
    sf_gf_start_mat.value = avango.gua.make_identity_mat()

    ## @var sf_station_mat
    # The matrix representing the position of the device belonging to the platform.
    sf_station_mat = avango.gua.SFMatrix4()
    sf_station_mat.value = avango.gua.make_identity_mat()

    ## @var mf_ground_pick_result
    # Intersections of the ground following ray with the objects in the scene.
    mf_ground_pick_result = avango.gua.MFPickResult()

    ## Default constructor.
    def __init__(self):
        self.super(GroundFollowing).__init__()

    ## Custom constructor.
    # @param SCENEGRAPH Reference to the scenegraph of the currently displayed scene.
    # @param SF_STATION_MAT The field containing the current position of the device belonging to the platform.
    # @param SETTINGS A list of a boolean and a floating number representing self.activated and self.ray_start_height
    def my_constructor(self, SCENEGRAPH, SF_STATION_MAT, SETTINGS):

        # attributes
        ## @var activated
        # Indicates if the ground following algorithm is activated or deactivated. In the last case,
        # the input matrix is simply passed through.
        self.activated = False

        ## @var falling
        # A boolean indicating if the user is currently falling. Used for fall speed computations.
        self.falling = False

        ## @var initial_fall_velocity
        # The starting velocity when the user is falling in meters per frame. Is increased the longer the falling process goes on.
        self.initial_fall_velocity = 0.05

        ## @var scale_factor
        # Scaling factor used for the modification of up and down vectors.
        self.scale_factor = 0.1

        # fall velocity in meter per frame
        ## @var fall_velocity
        # Speed when the user is falling in meters per frame.
        self.fall_velocity = self.initial_fall_velocity

        # pick length in meter
        ## @var ground_pick_length
        # Length of the ground following ray.
        self.ground_pick_length = 100.0

        ## @var ground_pick_direction
        # Direction of the ground following ray (downwards).
        self.ground_pick_direction = avango.gua.Vec3(0.0, -1.0, 0.0)

        ## @var SCENEGRAPH
        # Reference to the scenegraph to intersect the ground following ray with.
        self.SCENEGRAPH = SCENEGRAPH

        ## @var ray_start_height
        # Starting height of the ground following ray.
        self.ray_start_height = SETTINGS[1]

        # initialize shoot and output matrices
        self.sf_abs_output_mat.value = self.sf_abs_input_mat.value

        # init field connections
        self.sf_station_mat.connect_from(SF_STATION_MAT)

        # init internal class
        ## @var ground_intersection
        # Intersection class to determine the intersections of the ground following ray with the objects in the scenegraph.
        self.ground_intersection = Intersection()
        self.ground_intersection.my_constructor(SCENEGRAPH,
                                                self.sf_gf_start_mat,
                                                self.ground_pick_length,
                                                self.ground_pick_direction)
        self.mf_ground_pick_result.connect_from(
            self.ground_intersection.mf_pick_result)

        # activate or deactive ground following
        if SETTINGS[0] == True:
            self.activate()
        else:
            self.deactivate()

    ## Evaluated every frame.
    def evaluate(self):
        if self.activated:
            # prepare ground following matrix
            _platform_trans_vec = self.sf_abs_input_mat.value.get_translate()
            _device_trans_vec = self.sf_station_mat.value.get_translate()

            _gf_start_pos = self.sf_abs_input_mat.value * avango.gua.Vec3(
                self.sf_station_mat.value.get_element(0, 3),
                self.ray_start_height,
                self.sf_station_mat.value.get_element(2, 3))
            self.sf_gf_start_mat.value = avango.gua.make_trans_mat(
                _gf_start_pos.x, _gf_start_pos.y, _gf_start_pos.z)

            if len(self.mf_ground_pick_result.value
                   ) > 0:  # an intersection with the ground was found

                _pick_result = self.mf_ground_pick_result.value[
                    0]  # get first intersection target

                _distance_to_ground = _pick_result.Distance.value * self.ground_pick_length
                _difference = _distance_to_ground - self.ray_start_height
                _difference = round(_difference, 3)

                if _difference < 0:
                    # climb up
                    if self.falling:
                        self.falling = False
                        self.fall_velocity = self.initial_fall_velocity

                    _up_vec = avango.gua.Vec3(
                        0.0, _difference * -1.0 * self.scale_factor, 0.0)
                    self.sf_abs_output_mat.value = avango.gua.make_trans_mat(
                        _up_vec) * self.sf_abs_input_mat.value

                elif _difference > 0:
                    if _difference > self.ray_start_height:
                        # falling
                        self.falling = True
                        _fall_vec = avango.gua.Vec3(0.0, -self.fall_velocity,
                                                    0.0)
                        self.sf_abs_output_mat.value = avango.gua.make_trans_mat(
                            _fall_vec) * self.sf_abs_input_mat.value
                        self.fall_velocity += 0.005

                    else:
                        # climb down
                        if self.falling:
                            self.falling = False
                            self.fall_velocity = self.initial_fall_velocity

                        _down_vec = avango.gua.Vec3(
                            0.0, _difference * -1.0 * self.scale_factor, 0.0)
                        self.sf_abs_output_mat.value = avango.gua.make_trans_mat(
                            _down_vec) * self.sf_abs_input_mat.value

                else:
                    self.sf_abs_output_mat.value = self.sf_abs_input_mat.value  # player remains on ground

            else:
                self.sf_abs_output_mat.value = self.sf_abs_input_mat.value  # no intersection with ground was found

        else:
            self.sf_abs_output_mat.value = self.sf_abs_input_mat.value  # ground following is deactivated

    ## Activates the ground following algorithm.
    def activate(self):
        self.activated = True
        self.ground_intersection.activate()

    ## Deactivates the ground following algorithm. The input matrix is just passed through after calling this method.
    def deactivate(self):
        self.activated = False
        self.ground_intersection.deactivate()
class GroundFollowing(avango.script.Script):

  # input field
  ## @var sf_abs_input_mat
  # The input matrix to be corrected by the ground following algorithm.
  sf_abs_input_mat = avango.gua.SFMatrix4()
  sf_abs_input_mat.value = avango.gua.make_identity_mat()

  # output field
  ## @var sf_abs_output_mat
  # The corrected matrix after the ground following algorithm was applied.
  sf_abs_output_mat = avango.gua.SFMatrix4()
  sf_abs_output_mat.value = avango.gua.make_identity_mat()

  # internal fields
  ## @var sf_gf_start_mat
  # The matrix representing the position where the sent ray to the ground starts. 
  sf_gf_start_mat = avango.gua.SFMatrix4()
  sf_gf_start_mat.value = avango.gua.make_identity_mat()

  ## @var sf_station_mat
  # The matrix representing the position of the device belonging to the platform.
  sf_station_mat = avango.gua.SFMatrix4()
  sf_station_mat.value = avango.gua.make_identity_mat()

  ## @var mf_ground_pick_result
  # Intersections of the ground following ray with the objects in the scene.
  mf_ground_pick_result = avango.gua.MFPickResult()

  ## Default constructor.
  def __init__(self):
    self.super(GroundFollowing).__init__()

  ## Custom constructor.
  # @param SCENEGRAPH Reference to the scenegraph of the currently displayed scene.
  # @param SF_STATION_MAT The field containing the current position of the device belonging to the platform.
  # @param SETTINGS A list of a boolean and a floating number representing self.activated and self.ray_start_height 
  def my_constructor(self, SCENEGRAPH, SF_STATION_MAT, SETTINGS):
    
    # attributes
    ## @var activated
    # Indicates if the ground following algorithm is activated or deactivated. In the last case,
    # the input matrix is simply passed through.
    self.activated = False

    ## @var falling
    # A boolean indicating if the user is currently falling. Used for fall speed computations.
    self.falling = False

    ## @var initial_fall_velocity
    # The starting velocity when the user is falling in meters per frame. Is increased the longer the falling process goes on.
    self.initial_fall_velocity = 0.05

    ## @var scale_factor
    # Scaling factor used for the modification of up and down vectors.
    self.scale_factor = 0.1

    # fall velocity in meter per frame
    ## @var fall_velocity
    # Speed when the user is falling in meters per frame.
    self.fall_velocity = self.initial_fall_velocity

    # pick length in meter
    ## @var ground_pick_length
    # Length of the ground following ray.
    self.ground_pick_length = 100.0

    ## @var ground_pick_direction
    # Direction of the ground following ray (downwards).
    self.ground_pick_direction = avango.gua.Vec3(0.0, -1.0, 0.0)

    ## @var SCENEGRAPH
    # Reference to the scenegraph to intersect the ground following ray with.
    self.SCENEGRAPH = SCENEGRAPH

    ## @var ray_start_height
    # Starting height of the ground following ray.
    self.ray_start_height = SETTINGS[1]

    # initialize shoot and output matrices
    self.sf_abs_output_mat.value = self.sf_abs_input_mat.value

    # init field connections
    self.sf_station_mat.connect_from(SF_STATION_MAT)


    # init internal class
    ## @var ground_intersection
    # Intersection class to determine the intersections of the ground following ray with the objects in the scenegraph.
    self.ground_intersection = Intersection()
    self.ground_intersection.my_constructor(SCENEGRAPH, self.sf_gf_start_mat, self.ground_pick_length, self.ground_pick_direction)
    self.mf_ground_pick_result.connect_from(self.ground_intersection.mf_pick_result)

    # activate or deactive ground following
    if SETTINGS[0] == True:
      self.activate()
    else:
      self.deactivate()

  ## Evaluated every frame.
  def evaluate(self):
    if self.activated:
      # prepare ground following matrix
      _platform_trans_vec = self.sf_abs_input_mat.value.get_translate()
      _device_trans_vec = self.sf_station_mat.value.get_translate()

      _gf_start_pos = self.sf_abs_input_mat.value * avango.gua.Vec3(self.sf_station_mat.value.get_element(0,3), self.ray_start_height, self.sf_station_mat.value.get_element(2,3))
      self.sf_gf_start_mat.value = avango.gua.make_trans_mat(_gf_start_pos.x, _gf_start_pos.y, _gf_start_pos.z)  

      if len(self.mf_ground_pick_result.value) > 0:                    # an intersection with the ground was found

        _pick_result = self.mf_ground_pick_result.value[0]             # get first intersection target

        _distance_to_ground = _pick_result.Distance.value * self.ground_pick_length
        _difference = _distance_to_ground - self.ray_start_height
        _difference = round(_difference, 3)

        if _difference < 0:
          # climb up
          if self.falling:
            self.falling = False
            self.fall_velocity = self.initial_fall_velocity 

          _up_vec = avango.gua.Vec3(0.0, _difference * -1.0 * self.scale_factor, 0.0)
          self.sf_abs_output_mat.value = avango.gua.make_trans_mat(_up_vec) * self.sf_abs_input_mat.value

        elif _difference > 0:
          if _difference > self.ray_start_height:
            # falling
            self.falling = True
            _fall_vec = avango.gua.Vec3(0.0, -self.fall_velocity, 0.0)
            self.sf_abs_output_mat.value = avango.gua.make_trans_mat(_fall_vec) * self.sf_abs_input_mat.value
            self.fall_velocity += 0.005

          else:
            # climb down
            if self.falling:
              self.falling = False
              self.fall_velocity = self.initial_fall_velocity 

            _down_vec = avango.gua.Vec3(0.0, _difference * -1.0 * self.scale_factor, 0.0)
            self.sf_abs_output_mat.value = avango.gua.make_trans_mat(_down_vec) * self.sf_abs_input_mat.value

        else:
          self.sf_abs_output_mat.value = self.sf_abs_input_mat.value        # player remains on ground

      else:
        self.sf_abs_output_mat.value = self.sf_abs_input_mat.value          # no intersection with ground was found
  
    else:
      self.sf_abs_output_mat.value = self.sf_abs_input_mat.value            # ground following is deactivated

  ## Activates the ground following algorithm.
  def activate(self):
    self.activated = True
    self.ground_intersection.activate()

  ## Deactivates the ground following algorithm. The input matrix is just passed through after calling this method.
  def deactivate(self):
    self.activated = False
    self.ground_intersection.deactivate()
class MultiTouchDevice(avango.script.Script):
    """
    Base class for multi touch devices.

    rayOrientation: orientation matrix (start position + direction) of ray 
    fingerCenterPos: the center of finger position in interval from -display-size to +display-size
    """
    _rayOrientation = avango.gua.SFMatrix4()
    _fingerCenterPos = avango.gua.SFVec3()

    def __init__(self):
        self.super(MultiTouchDevice).__init__()
        self._sceneGraph = None
        self._display    = None
        self._worldMat   = avango.gua.make_identity_mat()
        self._transMat   = avango.gua.make_identity_mat()
        self._rotMat     = avango.gua.make_identity_mat()
        self._scaleMat   = avango.gua.make_identity_mat()
        
        """ Scene transform matrix """
        self._globalMatrix = avango.gua.make_identity_mat()

        """ last cursor position """
        self._lastPos = None

        """ params to evaluate object / navigation mode """
        self._sceneName = None
        self._objectName = None
        self._objectMode = False

        self._headPosition1 = avango.gua.Vec3(0,0,0)

        """ params to evaluate intersection """
        self._intersection = Intersection() # ray intersection for target identification
        self._intersectionFound = False
        self._intersectionPoint = avango.gua.Vec3(0,0,0)
        self._intersectionObject = None
        self._lastIntersectionCounter = 0

        """ ray representation"""
        self.ray_length = 10
        self.ray_thickness = 0.0075
        self.intersection_sphere_size = 0.025
        self.highlighted_object = None
        self.hierarchy_selection_level = -1
     
        self.always_evaluate(True)


    def my_constructor(self, graph, display, NET_TRANS_NODE, SCENE_MANAGER, APPLICATION_MANAGER):
        """
        Initialize multi-touch device.

        @param graph: the scene graph on which to operate
        @param display: the physical display
        """

        self._sceneGraph = graph
        self._display    = display
        self._sceneManager = SCENE_MANAGER

        """ original matrix of the scene """
        self._origMat    = graph.Root.value.Transform.value

        """  """
        self._applicationManager = APPLICATION_MANAGER

        self._intersection.my_constructor(self._sceneGraph, self._rayOrientation, self.ray_length, "") # parameters: SCENEGRAPH, SF_PICK_MATRIX, PICK_LENGTH, PICKMASK

        """ parent node of ray node """
        _parent_node = self._sceneGraph["/net"]

        """
        # init scenegraph node
        ## @var ray_transform
        # Transformation node of the pointer's ray.
        """
        self.ray_transform = avango.gua.nodes.TransformNode(Name = "ray_transform")
        _parent_node.Children.value.append(self.ray_transform)

        _loader = avango.gua.nodes.TriMeshLoader()
        
        """
        ## @var ray_geometry
        # Geometry node representing the ray graphically.
        """
        self.ray_geometry = _loader.create_geometry_from_file("ray_geometry", "data/objects/cylinder.obj", "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)
        self.ray_transform.Children.value.append(self.ray_geometry)
        self.ray_geometry.GroupNames.value = ["do_not_display_group"]

        self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0,0,0) * \
                                            avango.gua.make_rot_mat(0,0,0,0) * \
                                            avango.gua.make_scale_mat(0,0,0)
        
        """
        @var intersection_point_geometry
        Geometry node representing the intersection point of the ray with an object in the scene.
        """
        self.intersection_point_geometry = _loader.create_geometry_from_file("intersection_point_geometry", "data/objects/sphere.obj", "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)
        NET_TRANS_NODE.Children.value.append(self.intersection_point_geometry)
        self.intersection_point_geometry.GroupNames.value = ["do_not_display_group"] # set geometry invisible

        self.ray_transform.Transform.connect_from(self._rayOrientation)

        """ representation of fingercenterpos """
        self.fingercenterpos_geometry = _loader.create_geometry_from_file("fingercenterpos", "data/objects/sphere.obj", "data/materials/Red.gmd", avango.gua.LoaderFlags.DEFAULTS)
        NET_TRANS_NODE.Children.value.append(self.fingercenterpos_geometry)
        self.fingercenterpos_geometry.GroupNames.value = ["do_not_display_group"]

        """ hand representation """
        self.handPos_geometry = _loader.create_geometry_from_file("handpos", "data/objects/cube.obj", "data/materials/Red.gmd", avango.gua.LoaderFlags.DEFAULTS)
        NET_TRANS_NODE.Children.value.append(self.handPos_geometry)
        self.handPos_geometry.GroupNames.value = ["do_not_display_group"]


        """ define Input display size """
        #111,5cm x 75,8
        self._inputDisplaySize = avango.gua.Vec2(1.115,0.758)


    def getDisplay(self):
        return self._display
    

    def getSceneGraph(self):
        return self._sceneGraph


    def mapInputPosition(self, Pos):
        """
        Map input position to display size
        """

        point = Pos

        """ map points from interval [0, 1] to [-0.5, 0.5] """
        mappedPosX = point[0] * 1 - 0.5
        mappedPosY = point[1] * 1 - 0.5

        """ map point to display intervall ([-1/2*display-size] -> [+1/2*display-size]) """
        mappedPos = avango.gua.Vec3(mappedPosX * self._inputDisplaySize.x, 0.0, mappedPosY * self._inputDisplaySize.y)   

        return mappedPos        

    def setFingerCenterPos(self, fingerPos):
        self._fingerCenterPos.value = fingerPos

        """ update fingercenterpos representation """
        self.fingercenterpos_geometry.GroupNames.value = []
        self.fingercenterpos_geometry.Transform.value = avango.gua.make_trans_mat(self._fingerCenterPos.value) * \
                                                        avango.gua.make_scale_mat( 0.025, 0.025 , 0.025 )

    def visualisizeHandPosition(self, handPos):
        """ update hand representation """
        self.handPos_geometry.GroupNames.value = []
        self.handPos_geometry.Transform.value = avango.gua.make_trans_mat(handPos) * \
                                                avango.gua.make_scale_mat( 0.1, 0.005 , 0.1 )


    def setObjectMode(self, active):
        """
        Evaluate object mode.
        object mode activated only if an intersection was found

        @param active: toggle active state of object mode 
        """
        if active and self._intersectionFound:
            self._objectMode = True
            self._objectName = self._intersectionObject.Parent.value.Name.value
            return True
        else: 
            self._objectMode = False
            self._objectName = None
            return False


    def addLocalTranslation(self, transMat):
        """
        Add local translation.

        @param transMat: the (relative) translation matrix
        """
        self._transMat *= transMat


    def addLocalRotation(self, rotMat):
        """
        Add local rotation.

        @param rotMat: the (relative) rotation matrix
        """
        self._rotMat *= rotMat


    def addLocalScaling(self, scaleMat):
        """
        Add local scaling.

        @param scaleMat: the (relative) scaling matrix
        """
        self._scaleMat *= scaleMat

    def intersectSceneWithFingerPos(self):
        """
        Intersect Scene with ray from head to finger position. works only for first user.

        @param transMat: the (relative) translation matrix
        """

        #TODO: decide between displays with tracking and not
        #for no tracking use this: #self._rayOrientation.value = avango.gua.make_trans_mat(self._fingerCenterPos.value.x , 0.5 , self._fingerCenterPos.value.z) * avango.gua.make_rot_mat(-90,1,0,0)

        #do this only once per gesture
        
        #do this only once per gesture
        if (1 < (self._frameCounter - self._lastIntersectionCounter)):                 
            """ ray orientation from fingerPos down """
            self._rayOrientation.value = avango.gua.make_trans_mat(self._fingerCenterPos.value.x , 1 , self._fingerCenterPos.value.z) * avango.gua.make_rot_mat(-90,1,0,0)
            
            """intersection found"""
            if len(self._intersection.mf_pick_result.value) > 0:
                self._intersectionFound = True

                """first intersected object"""
                _pick_result = self._intersection.mf_pick_result.value[0]

                self._intersectionPoint = _pick_result.Position.value 
                self._intersectionObject = _pick_result.Object.value
                
                """update intersectionObject until you insert object Mode"""
                if not self._objectMode:
                    self._lastIntersectionObject = self._intersectionObject
                
                """ transform point into world coordinates """
                self._intersectionPoint = self._intersectionObject.WorldTransform.value * self._intersectionPoint 
                
                """make Vec3 from Vec4"""
                self._intersectionPoint = avango.gua.Vec3(self._intersectionPoint.x,self._intersectionPoint.y,self._intersectionPoint.z) 
                
                if (self._objectMode and not self._objectName == self._intersectionObject.Parent.value.Name.value):
                    #print "same object"
                    self._intersectionPoint = avango.gua.Vec3(0,0,0)

                """ VISUALISATION """
                """update intersection sphere"""
                self.intersection_point_geometry.Transform.value = avango.gua.make_trans_mat(self._intersectionPoint) * \
                                                                   avango.gua.make_scale_mat(self.intersection_sphere_size, self.intersection_sphere_size, self.intersection_sphere_size)
                """set sphere and ray visible"""                                           
                #self.intersection_point_geometry.GroupNames.value = [] 
                #self.ray_geometry.GroupNames.value = []

                """update ray"""
                _distance = (self._intersectionPoint - self.ray_transform.WorldTransform.value.get_translate()).length()

                self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0.0, 0.0, _distance * -0.5) * \
                                                    avango.gua.make_rot_mat(-90.0,1,0,0) * \
                                                    avango.gua.make_scale_mat(self.ray_thickness, _distance, self.ray_thickness)

            else:
                """set geometry invisible"""
                self.intersection_point_geometry.GroupNames.value = ["do_not_display_group"] 
                self.ray_geometry.GroupNames.value = ["do_not_display_group"]

                """set to default ray length"""
                self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0.0,0.0,self.ray_length * -0.5) * \
                                                    avango.gua.make_rot_mat(-90.0,1,0,0) * \
                                                    avango.gua.make_scale_mat(self.ray_thickness, self.ray_length, self.ray_thickness)
                self._intersectionFound = False
                self._intersectionPoint = avango.gua.Vec3(0,0,0)
        
        self._lastIntersectionCounter = self._frameCounter
        





    def update_object_highlight(self):
        """highlight active object:"""
        if self._objectMode:
            _node = self._lastIntersectionObject

            if _node.has_field("InteractiveObject") == True:
                _object = _node.InteractiveObject.value
              
                if self.hierarchy_selection_level >= 0:          
                    _object = _object.get_higher_hierarchical_object(self.hierarchy_selection_level)
              
                if _object == None:
                    """ evtl. disable highlight of prior object"""
                    if self.highlighted_object != None:
                        self.highlighted_object.enable_highlight(False)

                else:
                    if _object != self.highlighted_object: # new object hit
                    
                        """evtl. disable highlight of prior object"""
                        if self.highlighted_object != None:
                            self.highlighted_object.enable_highlight(False)

                        self.highlighted_object = _object
                        
                        """enable highlight of new object"""
                        self.highlighted_object.enable_highlight(True)

        else:
            """evtl. disable highlight of prior object"""
            if self.highlighted_object != None:
                self.highlighted_object.enable_highlight(False)
                self.highlighted_object = None


    def applyTransformations(self):
        """
        Apply calculated world matrix to scene graph.
        Requires the scene graph to have a transform node as root node.
        """

        """ Reguires the scnene Name of actually scene to change dynamically """
        sceneName = self._sceneManager.getActiveSceneName()

        """ to avoid errors until the scenen Name is set """
        if (None != sceneName):
            sceneNode = "/net/" + sceneName
            self._globalMatrix = self._sceneGraph[sceneNode].Transform.value
            
            """ object Mode """
            if self._objectMode:
                objectNode = "/net/" + sceneName + "/" + self._objectName
                scenePos = self._sceneGraph[objectNode].Transform.value.get_translate()
                TransformMatrix = self._sceneGraph[objectNode].Transform.value
            
            else: 
                scenePos = self._sceneGraph[sceneNode].Transform.value.get_translate()
                TransformMatrix = self._sceneGraph[sceneNode].Transform.value
            
            """ distance between finger position and scene position (object position) """
            translateDistance = self._fingerCenterPos.value - scenePos

            """transform world-space to object-space"""
            translateDistance = avango.gua.make_inverse_mat(avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected())) * translateDistance
            translateDistance = avango.gua.Vec3(translateDistance.x, translateDistance.y, translateDistance.z)

            #print (self._transMat)

            """ 
            TransfotmMatrix: 
                1. translate and rotate to origin, 
                2. calculate new position, 
                3. translate and rotate back 
            """

            """ object mode """
            if self._objectMode:
                TransformMatrix = avango.gua.make_trans_mat(TransformMatrix.get_translate()) * \
                                  avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected()) * \
                                  avango.gua.make_inverse_mat(avango.gua.make_rot_mat(self._globalMatrix.get_rotate_scale_corrected())) * \
                                  avango.gua.make_inverse_mat(avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected())) * \
                                  self._rotMat * \
                                  self._scaleMat * \
                                  self._transMat * \
                                  avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected()) * \
                                  avango.gua.make_rot_mat(self._globalMatrix.get_rotate_scale_corrected()) * \
                                  avango.gua.make_scale_mat(TransformMatrix.get_scale())

            else:
                TransformMatrix = avango.gua.make_trans_mat(TransformMatrix.get_translate()) * \
                                  avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected()) *\
                                  avango.gua.make_trans_mat(translateDistance * 1.0) * \
                                  avango.gua.make_trans_mat(avango.gua.Vec3(0, self._intersectionPoint.y * -1.0 , 0)) * \
                                  avango.gua.make_inverse_mat(avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected())) * \
                                  self._rotMat * \
                                  self._scaleMat * \
                                  self._transMat * \
                                  avango.gua.make_rot_mat(TransformMatrix.get_rotate_scale_corrected()) * \
                                  avango.gua.make_trans_mat(avango.gua.Vec3(0, self._intersectionPoint.y * 1.0 , 0)) * \
                                  avango.gua.make_trans_mat(translateDistance * -1.0) * \
                                  avango.gua.make_scale_mat(TransformMatrix.get_scale())


            """ object mode """
            if self._objectMode:
                self._sceneGraph[objectNode].Transform.value = TransformMatrix
            
            else:
                self._sceneGraph[sceneNode].Transform.value = TransformMatrix


        """ reset all data """ 
        self._transMat   = avango.gua.make_identity_mat()
        self._rotMat     = avango.gua.make_identity_mat()
        self._scaleMat   = avango.gua.make_identity_mat()
        self._globalMatrix = avango.gua.make_identity_mat()
Example #24
0
# Read which input to choose
selectedInput = "a"
if len(sys.argv) > 1:
    candidate = sys.argv[1]
    if len(candidate) == 1 and candidate in "abcdef":
        selectedInput = candidate
    else:
        print(f"! Invalid input {candidate}, using default")
print(f"Selected input: {selectedInput}")

# Read input
with open(f"input/{selectedInput}.in", "r") as file:
    firstLine = file.readline().strip()
    D, I, S, V, F = list(map(int, firstLine.split(" ")))

    allIntersections = [Intersection(id) for id in range(I)]
    allStreets = {}

    for s in range(S):
        street = Street.fromString(file.readline().strip())
        allStreets[street.name] = street
        allIntersections[street.start].addOutgoing(street)
        allIntersections[street.end].addIncoming(street)
        # print(street)

    for v in range(V):
        car = Car.fromString(file.readline().strip(), allStreets, D)
        # print(car)

    # for street in allStreets.values():
    #     print(street)
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
###########################################################################################

import socket  # Import socket module
import gopigo
from Intersection import *

s = socket.socket()  # Create a socket object
host = socket.gethostname()  # Get local machine name
turnList = [
    Intersection(True, False, False, False),
    Intersection(False, True, False, False),
    Intersection(True, False, False, False)
]
port = 12345  # Reserve a port for your service.
s.bind(('192.168.1.109', port))  # Bind to the port
print(host)

s.listen(5)  # Now wait for client connection.
while True:
    c, addr = s.accept()  # Establish connection with client.
    print 'Got connection from', addr
    c.send(turnList)
    c.close()
    def my_constructor(self, WORKSPACE_INSTANCE, USER_ID, VIP,
                       AVATAR_VISIBILITY_TABLE, HEADTRACKING_TARGET_NAME,
                       EYE_DISTANCE, NO_TRACKING_MAT):

        self.table_constructor(AVATAR_VISIBILITY_TABLE)

        # flags
        ## @var is_vip
        # Boolean indicating if this user has vip status.
        self.is_vip = VIP

        ## @var is_active
        # Boolean indicating if this user is currently active.
        self.is_active = True

        ## @var eye_distance
        # The eye distance of the user to be applied.
        self.eye_distance = EYE_DISTANCE

        # variables
        ## @var WORKSPACE_INSTANCE
        # Workspace instance at which this user is registered.
        self.WORKSPACE_INSTANCE = WORKSPACE_INSTANCE

        ## @var id
        # Identification number of the user within the workspace, starting from 0.
        self.id = USER_ID

        ## @var headtracking_target_name
        # Name of the headtracking station as registered in daemon.
        self.headtracking_target_name = HEADTRACKING_TARGET_NAME

        ## @var headtracking_reader
        # TrackingTargetReader for the user's glasses.
        if self.headtracking_target_name == None:
            self.headtracking_reader = TrackingDefaultReader()
            self.headtracking_reader.set_no_tracking_matrix(NO_TRACKING_MAT)
        else:
            self.headtracking_reader = TrackingTargetReader()
            self.headtracking_reader.my_constructor(HEADTRACKING_TARGET_NAME)
            self.headtracking_reader.set_transmitter_offset(
                self.WORKSPACE_INSTANCE.transmitter_offset)
            self.headtracking_reader.set_receiver_offset(
                avango.gua.make_identity_mat())

        ## @var user_representations
        # List of UserRepresentation instances for all display groups in the user's workspace.
        self.user_representations = []

        # toggles activity
        self.toggle_user_activity(self.is_active)

        ## @var intersection_tester
        # Instance of Intersection to determine intersection points of user with screens.
        self.intersection_tester = Intersection()
        self.intersection_tester.my_constructor(
            scenegraphs[0], self.headtracking_reader.sf_abs_mat, 5.0,
            "screen_proxy_group", False)
        self.mf_screen_pick_result.connect_from(
            self.intersection_tester.mf_pick_result)

        ## @var last_seen_display_group
        # DisplayGroup instance for which the user's viewing ray lastly hit a screen proxy geometry.
        self.last_seen_display_group = None

        self.always_evaluate(True)
class Ray(avango.script.Script):

  # internal fields
  ## @var sf_pointer_button0
  # Boolean field representing the first button of the pointer.
  sf_pointer_button0 = avango.SFBool()

  ## @var sf_pointer_button1
  # Boolean field representing the second button of the pointer.
  sf_pointer_button1 = avango.SFBool()

  ## @var sf_pointer_button2
  # Boolean field representing the third button of the pointer.
  sf_pointer_button2 = avango.SFBool()  

  ## @var mf_pointer_pick_result
  # Intersections of the picking ray with the objects in the scene.
  mf_pointer_pick_result = avango.gua.MFPickResult()
  sf_normals = avango.gua.SFVec3()

  ## Default constructor.
  def __init__(self):
    self.super(Ray).__init__()

  ## Custom constructor.
  # @param MANIPULATION_MANAGER Reference to the ManipulationManager instance to which this RayPointer is associated.
  # @param ID Identification number of the RayPointer, starting from 1.
  # @param SCENEGRAPH Reference to the scenegraph in which the manipulation is taking place.
  # @param NET_TRANS_NODE Reference to the nettrans node to which the scene is appended to.
  # @param PARENT_NODE Scenegraph node to which the ray is to be appended to.
  # @param TRACKING_TRANSMITTER_OFFSET Transmitter offset of the tracking system to be applied.
  # @param POINTER_TRACKING_STATION Tracking target name of the pointing device.
  # @param POINTER_DEVICE_STATION Input values name of the pointing device.
  #def my_constructor(self, MANIPULATION_MANAGER, ID, SCENEGRAPH, NET_TRANS_NODE, PARENT_NODE, TRACKING_TRANSMITTER_OFFSET, POINTER_TRACKING_STATION, POINTER_DEVICE_STATION):

  def my_constructor(self, MANIPULATION_MANAGER, ID, SCENEGRAPH, NET_TRANS_NODE, PARENT_NODE, MATRIX, POINTER_DEVICE_STATION):
    
    # references
    ## @var MANIPULATION_MANAGER
    # Reference to the ManipulationManager instance to which this RayPointer is associated.
    self.MANIPULATION_MANAGER = MANIPULATION_MANAGER
    self.net_trans_node = NET_TRANS_NODE
    self.parent_node = PARENT_NODE
    
    # parameters
    ## @var ray_length
    # Length of the pointer's ray in meters.
    self.ray_length = 10.0

    ## @var ray_thickness
    # Thickness of the pointer's ray in meters.
    self.ray_thickness = 0.0075

    ## @var intersection_sphere_size
    # Radius of the intersection sphere in meters.
    self.intersection_sphere_size = 0.025

    ## @var hierarchy_selection_level
    # Hierarchy level which is selected by this pointer.
    self.hierarchy_selection_level = 0

    # variables
    ## @var id
    # Identification number of the RayPointer, starting from 1.
    self.id = ID

    ## @var highlighted_object
    # Reference to the currently highlighted object.
    self.highlighted_object = None

    ## @var dragged_object
    # Reference to the currently dragged object.
    self.dragged_object = None

    ## @var dragging_offset
    # Offset to be applied during the dragging process.
    self.dragging_offset = None

    # init sensors
    ## @var pointer_tracking_sensor
    # Device sensor capturing the pointer's tracking position and rotation.
    #self.pointer_tracking_sensor = avango.daemon.nodes.DeviceSensor(DeviceService = avango.daemon.DeviceService())
    #self.pointer_tracking_sensor.Station.value = POINTER_TRACKING_STATION
    #self.pointer_tracking_sensor.ReceiverOffset.value = avango.gua.make_identity_mat()
    #self.pointer_tracking_sensor.TransmitterOffset.value = TRACKING_TRANSMITTER_OFFSET
    
    ## @var pointer_device_sensor
    # Device sensor capturing the pointer's button input values.
    self.pointer_device_sensor = avango.daemon.nodes.DeviceSensor(DeviceService = avango.daemon.DeviceService())
    self.pointer_device_sensor.Station.value = POINTER_DEVICE_STATION

    # init scenegraph node
    ## @var ray_transform
    # Transformation node of the pointer's ray.
    self.ray_transform = avango.gua.nodes.TransformNode(Name = "ray_transform")
    PARENT_NODE.Children.value.append(self.ray_transform)

    _loader = avango.gua.nodes.GeometryLoader()
    
    ## @var ray_geometry
    # Geometry node representing the ray graphically.
    self.ray_geometry = _loader.create_geometry_from_file("ray_geometry", "data/objects/cylinder.obj", "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)
    self.ray_transform.Children.value.append(self.ray_geometry)
    self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0.0,0.0,self.ray_length * -0.5) * \
                                            avango.gua.make_rot_mat(-90.0,1,0,0) * \
                                            avango.gua.make_scale_mat(0.005,self.ray_length,0.005)

    self.edge_geometry = _loader.create_geometry_from_file("edge_geometry", "data/objects/cylinder.obj", "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)

    NET_TRANS_NODE.Children.value.append(self.edge_geometry)
    self.edge_geometry.GroupNames.value = ["do_not_display_group"] # set geometry invisible
  
    ## @var intersection_point_geometry
    # Geometry node representing the intersection point of the ray with an object in the scene.
    self.intersection_point_geometry = _loader.create_geometry_from_file("intersection_point_geometry", "data/objects/sphere.obj", "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)
    NET_TRANS_NODE.Children.value.append(self.intersection_point_geometry)
    self.intersection_point_geometry.GroupNames.value = ["do_not_display_group"] # set geometry invisible

    ## @var dragging_trigger
    # Trigger function which is called when a dragging process is in progress.
    self.dragging_trigger = avango.script.nodes.Update(Callback = self.dragging_callback, Active = False)
      
    # init sub classes
    ## @var pointer_intersection
    # Instance of Intersection to determine hit points of the ray with the scene
    self.pointer_intersection = Intersection() # ray intersection for target identification
    self.pointer_intersection.my_constructor(SCENEGRAPH, self.ray_transform.WorldTransform, self.ray_length, "man_pick_group") # parameters: SCENEGRAPH, SF_PICK_MATRIX, PICK_LENGTH, PICKMASK

    self.line_crossing = LineCrossing() 
    self.line_crossing.my_constructor(self.sf_normals)
    self.line_crossing_trigger = False


    # init field connections
    #self.ray_transform.Transform.connect_from(self.pointer_tracking_sensor.Matrix)    
    self.ray_transform.Transform.connect_from(MATRIX)    
    self.mf_pointer_pick_result.connect_from(self.pointer_intersection.mf_pick_result)
    self.sf_pointer_button0.connect_from(self.pointer_device_sensor.Button0)
    self.sf_pointer_button1.connect_from(self.pointer_device_sensor.Button1)
    self.sf_pointer_button2.connect_from(self.pointer_device_sensor.Button2)

    #if self.pointer_tracking_sensor.Station.value == "device-mouse":
    #  self.mouse_mover = MouseMover()
    #  self.mouse_mover.my_constructor(self.pointer_tracking_sensor)
    #  self.ray_transform.Transform.connect_from(self.mouse_mover.sf_output_mat)

    self.set_hierarchy_selection_level(-1)
    self.output_mat = avango.gua.make_identity_mat()
    self.intersection_point = avango.gua.Vec3
    
  # callbacks
  ## Called whenever mf_pointer_pick_result changes.
  @field_has_changed(mf_pointer_pick_result)
  def mf_pointer_pick_result_mat_changed(self):

    self.update_ray()
    self.update_object_highlight()
    
  ## Called whenever sf_pointer_button0 changes.
  @field_has_changed(sf_pointer_button0)
  def sf_pointer_button0_changed(self):

    if self.sf_pointer_button0.value == True and self.highlighted_object != None: # dragging started
      self.output_mat = self.ray_transform.WorldTransform.value
      self.dragged_object = self.highlighted_object

      if self.dragged_object.handler != None:
        self.dragged_object.handler.add_input(self)
        #self.dragging_offset = avango.gua.make_inverse_mat(self.ray_transform.WorldTransform.value) * self.dragged_object.get_world_transform()

        self.dragging_trigger.Active.value = True # activate dragging callback

        #get intersection point
        _pick_result = self.mf_pointer_pick_result.value[0] # get first intersection target
        _point = _pick_result.Position.value # intersection point in object coordinate system
        
        _node = _pick_result.Object.value
        _point = _node.WorldTransform.value * _point # transform point into world coordinates
        _point = avango.gua.Vec3(_point.x,_point.y,_point.z) # make Vec3 from Vec4
        
      else:
        self.dragged_object = None

    elif self.sf_pointer_button0.value == False and self.dragged_object != None: # dragging stopped
      self.dragged_object.handler.remove_input(self)
      self.dragged_object = None
      
      self.dragging_trigger.Active.value = False # deactivate dragging callback

  ## Called whenever sf_pointer_button1 changes.
  @field_has_changed(sf_pointer_button1)
  def sf_pointer_button1_changed(self):
    if self.sf_pointer_button1.value == True and self.highlighted_object != None:
      self.line_crossing_trigger = True

    if self.sf_pointer_button1.value == False:
      self.line_crossing_trigger = False


    #if self.sf_pointer_button1.value == True:
    #  self.set_hierarchy_selection_level(min(self.hierarchy_selection_level + 1, 3))
      
  ## Called whenever sf_pointer_button2 changes.
  #@field_has_changed(sf_pointer_button2)
  #def sf_pointer_button2_changed(self):

    #if self.sf_pointer_button2.value == True:
    #  self.set_hierarchy_selection_level(max(self.hierarchy_selection_level - 1, -1))
        

  # functions
  ## Called when in dragging. Updates the position of the dragged object.
  def dragging_callback(self):

    #_mat = self.ray_transform.WorldTransform.value * self.dragging_offset
    self.output_mat = self.ray_transform.WorldTransform.value
    
    #self.dragged_object.set_world_transform(_mat)

  ## Change the hierarchy selection level to a given level.
  # @param HIERARCHY_LEVEL The new hierarchy selection level to be set.
  def set_hierarchy_selection_level(self, HIERARCHY_LEVEL):

    self.hierarchy_selection_level = HIERARCHY_LEVEL
    
    print "hierarchy selection level", self.hierarchy_selection_level
    
    if self.hierarchy_selection_level >= 0:
      _material = self.MANIPULATION_MANAGER.get_hierarchy_material(HIERARCHY_LEVEL)
     
      self.ray_geometry.Material.value = _material
      self.intersection_point_geometry.Material.value = _material

    else:
      self.ray_geometry.Material.value = "data/materials/White.gmd"
      self.intersection_point_geometry.Material.value = "data/materials/White.gmd"
  
  ## Updates the ray according to the intersections found.
  def update_ray(self):
    # self.parent_node.WorldTransform.value
    if len(self.mf_pointer_pick_result.value) > 0: # intersection found    
      _pick_result = self.mf_pointer_pick_result.value[0] # get first intersection target
      #print _pick_result.Normal.value 
      

      
      #print _pick_result.Object.value, _pick_result.Object.value.Name.value

      # update intersection point
      #_point = _pick_result.WorldPosition.value # intersection point in world coordinate system --> not working ???
    
      _point = _pick_result.Position.value # intersection point in object coordinate system
      
      _node = _pick_result.Object.value
      _point = _node.WorldTransform.value * _point # transform point into world coordinates
      _point = avango.gua.Vec3(_point.x,_point.y,_point.z) # make Vec3 from Vec4


      if self.line_crossing_trigger == True:
        self.sf_normals.value = _pick_result.Normal.value

        if self.line_crossing.edge != None:
          
          _axis = self.line_crossing.edge.cross(avango.gua.Vec3(0,1,0))
          _pos =  _pick_result.Position.value 
          
          self.edge_geometry.Transform.value = avango.gua.make_trans_mat(_pos) *\
                                              avango.gua.make_rot_mat(self.line_crossing._angle, _axis) *\
                                              avango.gua.make_scale_mat(0.05,1,0.05)

          self.edge_geometry.GroupNames.value = [] # set geometry visible
          self.edge_geometry.Transform.value =_node.WorldTransform.value * self.edge_geometry.Transform.value
          
          self.line_crossing_trigger= False

      self.intersection_point = _point
      self.intersection_point_geometry.Transform.value = avango.gua.make_trans_mat(_point) * \
                                                          avango.gua.make_scale_mat(self.intersection_sphere_size, self.intersection_sphere_size, self.intersection_sphere_size)
                                                          
      self.intersection_point_geometry.GroupNames.value = [] # set geometry visible
  
      # update ray length
      _distance = (_point - self.ray_transform.WorldTransform.value.get_translate()).length()
  
      self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0.0,0.0,_distance * -0.5) * \
                                          avango.gua.make_rot_mat(-90.0,1,0,0) * \
                                          avango.gua.make_scale_mat(self.ray_thickness, _distance, self.ray_thickness)
  
    else: # no intersection found
      #print "None"
      self.intersection_point_geometry.GroupNames.value = ["do_not_display_group"] # set geometry invisible
      
      # set to default ray length
      self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0.0,0.0,self.ray_length * -0.5) * \
                                          avango.gua.make_rot_mat(-90.0,1,0,0) * \
                                          avango.gua.make_scale_mat(self.ray_thickness, self.ray_length, self.ray_thickness)


  ## Updates the object to be highlighted according to the intersections found.
  def update_object_highlight(self):
  
    if len(self.mf_pointer_pick_result.value) > 0: # intersection found    
      _pick_result = self.mf_pointer_pick_result.value[0] # get first intersection target
      
      _node = _pick_result.Object.value
      
      if _node.has_field("InteractiveObject") == True:
        _object = _node.InteractiveObject.value
        
        if self.hierarchy_selection_level >= 0:          
          _object = _object.get_higher_hierarchical_object(self.hierarchy_selection_level)
        
        if _object == None:
          # evtl. disable highlight of prior object
          if self.highlighted_object != None:
            self.highlighted_object.enable_highlight(False)

        else:
          if _object != self.highlighted_object: # new object hit
          
            # evtl. disable highlight of prior object
            if self.highlighted_object != None:
              self.highlighted_object.enable_highlight(False)

            self.highlighted_object = _object
              
            # enable highlight of new object
            self.highlighted_object.enable_highlight(True)
 
    else: # no intersection found
    
      # evtl. disable highlight of prior object
      if self.highlighted_object != None:
        self.highlighted_object.enable_highlight(False)

        self.highlighted_object = None
  def my_constructor(self, MANIPULATION_MANAGER, ID, SCENEGRAPH, NET_TRANS_NODE, PARENT_NODE, MATRIX, POINTER_DEVICE_STATION):
    
    # references
    ## @var MANIPULATION_MANAGER
    # Reference to the ManipulationManager instance to which this RayPointer is associated.
    self.MANIPULATION_MANAGER = MANIPULATION_MANAGER
    self.net_trans_node = NET_TRANS_NODE
    self.parent_node = PARENT_NODE
    
    # parameters
    ## @var ray_length
    # Length of the pointer's ray in meters.
    self.ray_length = 10.0

    ## @var ray_thickness
    # Thickness of the pointer's ray in meters.
    self.ray_thickness = 0.0075

    ## @var intersection_sphere_size
    # Radius of the intersection sphere in meters.
    self.intersection_sphere_size = 0.025

    ## @var hierarchy_selection_level
    # Hierarchy level which is selected by this pointer.
    self.hierarchy_selection_level = 0

    # variables
    ## @var id
    # Identification number of the RayPointer, starting from 1.
    self.id = ID

    ## @var highlighted_object
    # Reference to the currently highlighted object.
    self.highlighted_object = None

    ## @var dragged_object
    # Reference to the currently dragged object.
    self.dragged_object = None

    ## @var dragging_offset
    # Offset to be applied during the dragging process.
    self.dragging_offset = None

    # init sensors
    ## @var pointer_tracking_sensor
    # Device sensor capturing the pointer's tracking position and rotation.
    #self.pointer_tracking_sensor = avango.daemon.nodes.DeviceSensor(DeviceService = avango.daemon.DeviceService())
    #self.pointer_tracking_sensor.Station.value = POINTER_TRACKING_STATION
    #self.pointer_tracking_sensor.ReceiverOffset.value = avango.gua.make_identity_mat()
    #self.pointer_tracking_sensor.TransmitterOffset.value = TRACKING_TRANSMITTER_OFFSET
    
    ## @var pointer_device_sensor
    # Device sensor capturing the pointer's button input values.
    self.pointer_device_sensor = avango.daemon.nodes.DeviceSensor(DeviceService = avango.daemon.DeviceService())
    self.pointer_device_sensor.Station.value = POINTER_DEVICE_STATION

    # init scenegraph node
    ## @var ray_transform
    # Transformation node of the pointer's ray.
    self.ray_transform = avango.gua.nodes.TransformNode(Name = "ray_transform")
    PARENT_NODE.Children.value.append(self.ray_transform)

    _loader = avango.gua.nodes.GeometryLoader()
    
    ## @var ray_geometry
    # Geometry node representing the ray graphically.
    self.ray_geometry = _loader.create_geometry_from_file("ray_geometry", "data/objects/cylinder.obj", "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)
    self.ray_transform.Children.value.append(self.ray_geometry)
    self.ray_geometry.Transform.value = avango.gua.make_trans_mat(0.0,0.0,self.ray_length * -0.5) * \
                                            avango.gua.make_rot_mat(-90.0,1,0,0) * \
                                            avango.gua.make_scale_mat(0.005,self.ray_length,0.005)

    self.edge_geometry = _loader.create_geometry_from_file("edge_geometry", "data/objects/cylinder.obj", "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)

    NET_TRANS_NODE.Children.value.append(self.edge_geometry)
    self.edge_geometry.GroupNames.value = ["do_not_display_group"] # set geometry invisible
  
    ## @var intersection_point_geometry
    # Geometry node representing the intersection point of the ray with an object in the scene.
    self.intersection_point_geometry = _loader.create_geometry_from_file("intersection_point_geometry", "data/objects/sphere.obj", "data/materials/White.gmd", avango.gua.LoaderFlags.DEFAULTS)
    NET_TRANS_NODE.Children.value.append(self.intersection_point_geometry)
    self.intersection_point_geometry.GroupNames.value = ["do_not_display_group"] # set geometry invisible

    ## @var dragging_trigger
    # Trigger function which is called when a dragging process is in progress.
    self.dragging_trigger = avango.script.nodes.Update(Callback = self.dragging_callback, Active = False)
      
    # init sub classes
    ## @var pointer_intersection
    # Instance of Intersection to determine hit points of the ray with the scene
    self.pointer_intersection = Intersection() # ray intersection for target identification
    self.pointer_intersection.my_constructor(SCENEGRAPH, self.ray_transform.WorldTransform, self.ray_length, "man_pick_group") # parameters: SCENEGRAPH, SF_PICK_MATRIX, PICK_LENGTH, PICKMASK

    self.line_crossing = LineCrossing() 
    self.line_crossing.my_constructor(self.sf_normals)
    self.line_crossing_trigger = False


    # init field connections
    #self.ray_transform.Transform.connect_from(self.pointer_tracking_sensor.Matrix)    
    self.ray_transform.Transform.connect_from(MATRIX)    
    self.mf_pointer_pick_result.connect_from(self.pointer_intersection.mf_pick_result)
    self.sf_pointer_button0.connect_from(self.pointer_device_sensor.Button0)
    self.sf_pointer_button1.connect_from(self.pointer_device_sensor.Button1)
    self.sf_pointer_button2.connect_from(self.pointer_device_sensor.Button2)

    #if self.pointer_tracking_sensor.Station.value == "device-mouse":
    #  self.mouse_mover = MouseMover()
    #  self.mouse_mover.my_constructor(self.pointer_tracking_sensor)
    #  self.ray_transform.Transform.connect_from(self.mouse_mover.sf_output_mat)

    self.set_hierarchy_selection_level(-1)
    self.output_mat = avango.gua.make_identity_mat()
    self.intersection_point = avango.gua.Vec3
  def my_constructor(self
                   , WORKSPACE_INSTANCE
                   , USER_ID
                   , VIP
                   , AVATAR_VISIBILITY_TABLE
                   , HEADTRACKING_TARGET_NAME
                   , EYE_DISTANCE
                   , NO_TRACKING_MAT
                   ):

    self.table_constructor(AVATAR_VISIBILITY_TABLE)

    # flags 
    ## @var is_vip
    # Boolean indicating if this user has vip status.
    self.is_vip = VIP

    ## @var is_active
    # Boolean indicating if this user is currently active.
    self.is_active = True

    ## @var eye_distance
    # The eye distance of the user to be applied.
    self.eye_distance = EYE_DISTANCE

    # variables
    ## @var WORKSPACE_INSTANCE
    # Workspace instance at which this user is registered.
    self.WORKSPACE_INSTANCE = WORKSPACE_INSTANCE

    ## @var id
    # Identification number of the user within the workspace, starting from 0.
    self.id = USER_ID

    ## @var headtracking_target_name
    # Name of the headtracking station as registered in daemon.
    self.headtracking_target_name = HEADTRACKING_TARGET_NAME

    ## @var headtracking_reader
    # TrackingTargetReader for the user's glasses.
    if self.headtracking_target_name == None:
      self.headtracking_reader = TrackingDefaultReader()
      self.headtracking_reader.set_no_tracking_matrix(NO_TRACKING_MAT)
    else:
      self.headtracking_reader = TrackingTargetReader()
      self.headtracking_reader.my_constructor(HEADTRACKING_TARGET_NAME)
      self.headtracking_reader.set_transmitter_offset(self.WORKSPACE_INSTANCE.transmitter_offset)
      self.headtracking_reader.set_receiver_offset(avango.gua.make_identity_mat())

    ## @var user_representations
    # List of UserRepresentation instances for all display groups in the user's workspace.
    self.user_representations = []

    # toggles activity
    self.toggle_user_activity(self.is_active)

    ## @var intersection_tester
    # Instance of Intersection to determine intersection points of user with screens.
    self.intersection_tester = Intersection()
    self.intersection_tester.my_constructor(scenegraphs[0]
                                          , self.headtracking_reader.sf_abs_mat
                                          , 5.0
                                          , "screen_proxy_group"
                                          , False)
    self.mf_screen_pick_result.connect_from(self.intersection_tester.mf_pick_result)

    ## @var last_seen_display_group
    # DisplayGroup instance for which the user's viewing ray lastly hit a screen proxy geometry.
    self.last_seen_display_group = None

    self.always_evaluate(True)
class User(avango.script.Script):

  ## @var mf_screen_pick_result
  # Intersections of the viewing ray with the screens in the setup.
  mf_screen_pick_result = avango.gua.MFPickResult()

  ## Default constructor.
  def __init__(self):
    self.super(User).__init__()

  ## Custom constructor.
  # @param APPLICATION_MANAGER Reference to the ApplicationManager instance from which this user is created.
  # @param USER_ID Global user ID to be applied.
  # @param VIP Boolean indicating if the user to be created is a vip.
  # @param GLASSES_ID ID of the shutter glasses worn by the user.
  # @param HEADTRACKING_TARGET_NAME Name of the headtracking station as registered in daemon.
  # @param PLATFORM_ID Platform ID to which this user should be appended to.
  # @param AVATAR_MATERIAL The material string for the user avatar to be created.
  def my_constructor(self
                   , APPLICATION_MANAGER
                   , USER_ID
                   , VIP
                   , GLASSES_ID
                   , HEADTRACKING_TARGET_NAME
                   , PLATFORM_ID
                   , AVATAR_MATERIAL):

    # flags 
    ## @var is_vip
    # Boolean indicating if this user has vip status.
    self.is_vip = VIP

    ## @var is_active
    # Boolean indicating if this user is currently active.
    self.is_active = True

    # variables
    ## @var APPLICATION_MANAGER
    # Reference to the ApplicationManager instance from which the user is created.
    self.APPLICATION_MANAGER = APPLICATION_MANAGER

    ## @var id
    # Identification number of the user, starting from 0.
    self.id = USER_ID

    ## @var platform_id
    # ID of the platform the user is belonging to.
    self.platform_id = PLATFORM_ID

    ## @var platform
    # Instance of the platform the user is belonging to.
    self.platform = self.APPLICATION_MANAGER.navigation_list[self.platform_id].platform

    ## @var current_display
    # Display instance on which the user physically is currently looking at.
    self.current_display = self.platform.displays[0]

    ## @var transmitter_offset
    # The transmitter offset to be applied.
    self.transmitter_offset   = self.platform.transmitter_offset

    ## @var no_tracking_mat
    # The matrix to be applied when no tracking is available.
    self.no_tracking_mat      = self.platform.no_tracking_mat
    
    ## @var avatar_material
    # Material of the user's avatar.
    self.avatar_material = AVATAR_MATERIAL

    ## @var headtracking_target_name
    # Name of the headtracking station as registered in daemon.
    self.headtracking_target_name = HEADTRACKING_TARGET_NAME

    ## @var glasses_id
    # ID of the shutter glasses worn by the user. Used for frequency updates.
    self.glasses_id = GLASSES_ID

    ## @var headtracking_reader
    # Instance of a child class of TrackingReader to supply translation input.
    if HEADTRACKING_TARGET_NAME == None:
      self.headtracking_reader = TrackingDefaultReader()
      self.headtracking_reader.set_no_tracking_matrix(self.no_tracking_mat)
    else:
      self.headtracking_reader = TrackingTargetReader()
      self.headtracking_reader.my_constructor(HEADTRACKING_TARGET_NAME)
      self.headtracking_reader.set_transmitter_offset(self.transmitter_offset)
      self.headtracking_reader.set_receiver_offset(avango.gua.make_identity_mat())

    # create avatar representation
    if self.platform.avatar_type == "joseph" or self.platform.avatar_type == "None":
      self.create_avatar_representation(self.headtracking_reader.sf_avatar_head_mat, self.headtracking_reader.sf_avatar_body_mat)  
    else:
      if self.platform.avatar_type == "joseph_table":
        print_warning("Avatar type jospeh_table is deprecated. The creation of table avatars are now handled by the " + \
                       "device automatically. Use avatar type jospeh instead.")
      print_error("Error: Unknown avatar type " + self.platform.avatar_type, True)

    # toggles avatar display and activity
    self.toggle_user_activity(self.is_active, False)

    # init intersection class for proxy geometry hit test

    ## @var pick_length
    # Length of the picking ray in meters to check for screen intersections.
    self.pick_length = 5.0

    ## @var intersection_tester
    # Instance of Intersection to determine intersection points of user with screens.
    self.intersection_tester = Intersection()
    self.intersection_tester.my_constructor(self.APPLICATION_MANAGER.SCENEGRAPH
                                          , self.headtracking_reader.sf_global_mat
                                          , self.pick_length
                                          , "screen_proxy_group")
    self.mf_screen_pick_result.connect_from(self.intersection_tester.mf_pick_result)

    ## @var looking_outside_start
    # If the user is not facing a screen, the start time of this behaviour is saved to open glasses after a certain amount of time.
    self.looking_outside_start = None

    ## @var open_threshold
    # Time in seconds after which shutter glasses should open when no screen is hit by the viewing ray.
    self.open_threshold = 2.0

    ## @var timer
    # Time sensor to handle time events.
    self.timer = avango.nodes.TimeSensor()

    # set evaluation policy
    self.always_evaluate(True)

  ## Evaluated every frame.
  def evaluate(self):
    
    if INTELLIGENT_SHUTTER_SWITCHING:

      if len(self.mf_screen_pick_result.value) > 0:

        _hit = self.mf_screen_pick_result.value[0].Object.value.Name.value
        _hit = _hit.replace("proxy_", "")
        _hit = _hit.split("_")

        _hit_platform = int(_hit[0])
        _intended_platform = self.APPLICATION_MANAGER.navigation_list[_hit_platform].platform
        _hit_screen = int(_hit[1])
        _intended_display = _intended_platform.displays[_hit_screen]

        if _intended_display != self.current_display:
          self.set_user_location(_hit_platform, _hit_screen, True)

      else:
        pass
      
      '''
      if len(self.mf_screen_pick_result.value) > 0:

        _hit = self.mf_screen_pick_result.value[0]
        _hit_name = _hit.Object.value.Name.value.replace("proxy_", "")
        _hit_name = _hit_name.split("_")

        _hit_platform = int(_hit_name[0])
        _hit_screen   = int(_hit_name[1])

        _intended_platform = self.APPLICATION_MANAGER.navigation_list[_hit_platform].platform
        _max_viewing_distance = _intended_platform.displays[_hit_screen].max_viewing_distance
        _distance_to_center = Tools.euclidean_distance(_hit.Object.value.Transform.value.get_translate()
                                                     , self.headtracking_reader.sf_global_mat.value.get_translate())
        _hit_distance = _hit.Distance.value * self.pick_length


        if _hit_platform != self.platform_id and \
           _hit_distance < _max_viewing_distance and \
           _distance_to_center < 1.0:

          if self.is_active == False:
            self.toggle_user_activity(True, True)

          # new intersection with other platform found in range

          self.set_user_location(_hit_platform, True)
          self.looking_outside_start = None

        elif _hit_distance > _max_viewing_distance:

          # intersection found but too far away

          if self.looking_outside_start == None:
            self.looking_outside_start = self.timer.Time.value

          if self.timer.Time.value - self.looking_outside_start > self.open_threshold:
            if self.is_active == True:
              self.toggle_user_activity(False, True)

      else:

        # no intersection found

        if self.looking_outside_start == None:
          self.looking_outside_start = self.timer.Time.value

        if self.timer.Time.value - self.looking_outside_start > self.open_threshold:
          if self.is_active == True:
            #print_message("Opening user")
            self.toggle_user_activity(False, True)
      '''
      

  ## Sets the user's active flag.
  # @param ACTIVE Boolean to which the active flag should be set.
  # @param RESEND_CONFIG Boolean indicating if the shutter configuration should be directly resent.
  def toggle_user_activity(self, ACTIVE, RESEND_CONFIG):

    if ACTIVE:
      self.is_active = True
      self.head_avatar.GroupNames.value = ['avatar_group_' + str(self.platform_id)]
      self.body_avatar.GroupNames.value = ['avatar_group_' + str(self.platform_id)]
    else:
      self.is_active = False
      self.head_avatar.GroupNames.value.append("do_not_display_group")
      self.body_avatar.GroupNames.value.append("do_not_display_group")
      self.platform_id = -1

    if RESEND_CONFIG:
      self.APPLICATION_MANAGER.slot_manager.update_slot_configuration()

  ## Changes the user's current platform.
  # @param PLATFORM_ID The new platform id to be set.
  # @param SCREEN_ID The new screen id to be set.
  # @param RESEND_CONFIG Boolean indicating if the shutter configuration should be directly resent.
  def set_user_location(self, PLATFORM_ID, SCREEN_ID, RESEND_CONFIG):

    _intended_platform = self.APPLICATION_MANAGER.navigation_list[PLATFORM_ID].platform
    _intended_display = _intended_platform.displays[SCREEN_ID]

    if self.APPLICATION_MANAGER.slot_manager.display_has_free_slot(_intended_display):

      self.remove_from_platform(self.head_avatar)
      self.remove_from_platform(self.body_avatar)

      self.platform_id = PLATFORM_ID
      self.platform = _intended_platform
      self.current_display = _intended_display

      self.transmitter_offset = self.platform.transmitter_offset
      self.no_tracking_mat = self.platform.no_tracking_mat
      self.headtracking_reader.set_transmitter_offset(self.transmitter_offset)

      self.avatar_material = self.APPLICATION_MANAGER.navigation_list[self.platform_id].trace_material

      self.head_avatar.GroupNames.value = ['avatar_group_' + str(self.platform_id)]
      self.head_avatar.Material.value = 'data/materials/' + self.avatar_material + '.gmd'
      self.body_avatar.GroupNames.value = ['avatar_group_' + str(self.platform_id)]
      self.body_avatar.Material.value = 'data/materials/' + self.avatar_material + '.gmd'

      if self.platform.avatar_type != "None":
        self.append_to_platform(self.head_avatar)
        self.append_to_platform(self.body_avatar)

      if RESEND_CONFIG:
        self.APPLICATION_MANAGER.slot_manager.update_slot_configuration()

    else:
      print_warning("Blocked")

  ## Appends a node to the children of a platform in the scenegraph.
  # @param NODE The node to be appended to the platform node.
  def append_to_platform(self, NODE):
    
    self.platform.platform_scale_transform_node.Children.value.append(NODE)

  ## Removes a node from the children of a platform in the scenegraph.
  # @param NODE The node to be removed from the platform node.
  def remove_from_platform(self, NODE):

    self.platform.platform_scale_transform_node.Children.value.remove(NODE)

  ## Creates a basic "joseph" avatar for this user.
  # @param SF_AVATAR_HEAD_MATRIX Field containing the transformation matrix for the avatar's head on the platform.
  # @param SF_AVATAR_BODY_MATRIX Field containing the transformation matrix for the avatar's body on the platform.
  def create_avatar_representation(self, SF_AVATAR_HEAD_MATRIX, SF_AVATAR_BODY_MATRIX):

    _loader = avango.gua.nodes.GeometryLoader()
    
    # create avatar head
    ## @var head_avatar
    # Scenegraph node representing the geometry and transformation of the basic avatar's head.
    self.head_avatar = _loader.create_geometry_from_file( 'head_avatar_' + str(self.id),
                                                          'data/objects/Joseph/JosephHead.obj',
                                                          'data/materials/' + self.avatar_material + '.gmd',
                                                          avango.gua.LoaderFlags.LOAD_MATERIALS)
    self.head_avatar.Transform.value = avango.gua.make_rot_mat(-90, 0, 1, 0) * avango.gua.make_scale_mat(0.4, 0.4, 0.4)
    self.head_avatar.GroupNames.value = ['avatar_group_' + str(self.platform_id)]

    # create avatar body
    ## @var body_avatar
    # Scenegraph node representing the geometry and transformation of the basic avatar's body.
    self.body_avatar = _loader.create_geometry_from_file( 'body_avatar_' + str(self.id),
                                                          'data/objects/Joseph/JosephBody.obj',
                                                          'data/materials/' + self.avatar_material + '.gmd',
                                                          avango.gua.LoaderFlags.LOAD_MATERIALS)
    self.body_avatar.GroupNames.value = ['avatar_group_' + str(self.platform_id)]
    
    self.append_to_platform(self.head_avatar)
    self.append_to_platform(self.body_avatar)

    self.head_avatar.Transform.connect_from(SF_AVATAR_HEAD_MATRIX)
    self.body_avatar.Transform.connect_from(SF_AVATAR_BODY_MATRIX)
Example #31
0
    Detection("dog.364.jpg", [66, 22, 428, 486]),
    Detection("dog.380.jpg", [46, 5, 357, 484]),
    Detection("dog.394.jpg", [111, 24, 428, 407])
]
for detection in examples:

    image = io.imread('image/' + detection.image_path)
    im, regions = selectivesearch.selective_search(image, scale=1, sigma=1)
    for r in regions:
        if r['rect'] in candidates:
            continue
        if r['size'] < 1000:
            continue
        candidates.add(r['rect'])
        for x, y, w, h in candidates:
            iou = union.get_union(detection.coordinate, [x, y, x + w, y + h])
            if counter < 160:
                if iou > .7:
                    PosImage = image[y:y + h, x:x + w]
                    resized = cv2.resize(PosImage, (128, 128),
                                         interpolation=cv2.INTER_AREA)
                    cv2.imwrite("IMAGE/positive%i.jpg" % p, resized)
                    train_data.append(resized)
                    train_label.append(1)
                    counter += 1
                    p += 1  #for image saving
            else:
                fflag = 1
            if falsecounter < 160:
                if iou < .3:
                    NegImage = image[y:y + h, x:x + w]
Example #32
0
            return False

        if Intersection.closed_segment_intersect(self.collider_a,
                                                 self.collider_b, start_point,
                                                 end_point):
            self.collider_hits += 1


if __name__ == "__main__":
    from time import sleep

    updateintervall = 0.1
    duration = 1
    speed = 1  # 14 km/h
    # speed = 3.888888888888889 # 14 km/h
    dropcounter = 3

    print()

    dropmaker = DropMakerNP(dropcounter, speed, xbound=1, ybound=1)
    c = (4000, 5000)
    d = (4000, 5000)
    Intersection.closed_segment_intersect(dropmaker.collider_a,
                                          dropmaker.collider_b, c, d)
    for time in range(duration):
        print(f'time:{time:3d}')
        # 1sec
        for _ in range(int(1 / updateintervall)):
            dropmaker.fall()
            dropmaker.showpos()
            sleep(updateintervall)