def calculatePoints(self):
        # Filter the points, first we get the undermost points, and then,
        # The point which less angle from z+ vector by y+ vector has.
        global epsilon
        vertices = [list(p.point().position()) for p in self.prim.vertices()]
        lessy = vertices[0][1]
        mayPoints = []
        for point in vertices:
            if((point[1] - epsilon) < lessy):
                mayPoints.append(point)
            if(point[1] < (lessy - epsilon)):
                lessy = point[1]
                mayPoints = [point]

        # We construct vectors from points to determine which is leftmost, so we delete 'y' component
        minAngle = 2 * math.pi + epsilon
        for point in mayPoints:
            vec = GeoMath.vecNormalize([point[0], 0, point[2]])
            angle = GeoMath.angleBetweenPointsByVec([0, 0, 1], vec, [0, 1, 0])
            if(angle < minAngle):
                minAngle = angle
                minPoint = point

        index = vertices.index(minPoint)
        previousPoint = vertices[index - 1]
        pointWhichIsRelative = minPoint
        nextPoint = vertices[(index + 1) % len(vertices)]

        self.set_previous_point(previousPoint)
        self.set_point_which_is_relative(pointWhichIsRelative)
        self.set_next_point(nextPoint)
Example #2
0
    def contain_bounding_box_3D(self, bounding_box):
        try:
            if (not self.get_prim()):
                raise Errors.CantBeNoneError(
                    'Prim cant be none',
                    'We need a prim to calculate tbn some steps after')
        except Errors.CantBeNoneError as e:
            Errors.Error.display_exception(e)
            exit()

        inside = True
        if (not self.get_rectangle_tangent_space()):
            self.convert_3D_to_2D(self.get_prim())
        this_point_relative = self.get_tbn_class().get_point_which_is_relative(
        )
        this_tbn_inverse_matrix = self.get_tbn_class().get_tbn_inverse()
        param_bounding_box_points_in_this_tangent_space = []
        for point in bounding_box.get_points_object_space():
            point_relative = GeoMath.vecSub(point, this_point_relative)
            point_tangent_space = this_tbn_inverse_matrix.mulPoint3ToMatrix3(
                point_relative)
            param_bounding_box_points_in_this_tangent_space.append(
                list(point_tangent_space))

        for point in param_bounding_box_points_in_this_tangent_space:
            logging.debug("Rectangle tangent space" +
                          str(self.get_rectangle_tangent_space()))
            inside = GeoMath.pointInPoints(point,
                                           self.get_rectangle_tangent_space())
            if (not inside):
                break
        return inside
Example #3
0
 def do(self):
     #Start pathfinding with backtracking
     logging.debug("Start method do, class PathBackTracking")
     logging.debug("Group partially destroyed: %s", str([p.prim.number() for p in self.partDes]))
     logging.debug("Group totally destroyed: %s", str([p.prim.number() for p in self.totDes]))
     global TimeExecutionFirst
     global TimeExecutionCurrent
     global MAXTIMEFORALLPATHS
     count = 1
     pathAchieved = False
     TimeExecutionFirst = time.time()
     while(not pathAchieved and count < 2):
         self.max_iterations_exceeded = False
         path = []
         pathAchieved = False
         if(count == 1):
             refPrim = self.getBestPrimReference(self.firstPrim)
             angle = GeoMath.angleBetweenPointsByPrim(GeoMath.primBoundingBox(self.lastPrim.prim).center(), GeoMath.primBoundingBox(self.firstPrim.prim).center(), refPrim.prim)
             logging.debug("Main angle, which determine direction: %s", str(angle))
             self.clockWise = angle < 0
         else:
             self.clockWise = not self.clockWise
         path.append(self.firstPrim)
         pathAchieved = self.backTracking(self.firstPrim, path)
         count += 1
     self.path = path
     logging.debug("Last prim: %s, First prim: %s", str(self.lastPrim.prim.number()), str(self.firstPrim.prim.number()))
     if(pathAchieved):
         self.goodPath = True
         logging.debug("End method do, class PathBackTracking. State: good")
     else:
         self.goodPath = False
         logging.debug("End method do, class PathBackTracking. State: No path achieved")
    def intersect_bounding_box_3D(self, bounding_box, DISPLAY=False):
        try:
            if not self.get_prim():
                raise Errors.CantBeNoneError("Prim cant be none", "We need a prim to calculate tbn some steps after")
        except Errors.CantBeNoneError as e:
            Errors.Error.display_exception(e)
            exit()

        if not self.get_points_tangent_space():
            self.create_3D_to_2D_rectangle(self.get_prim())
        this_point_relative = self.get_tbn_class().get_point_which_is_relative()
        this_tbn_inverse_matrix = self.get_tbn_class().get_tbn_inverse()
        param_bounding_box_points_in_this_tangent_space = []
        for point in bounding_box.get_rectangle_object_space():
            point_relative = GeoMath.vecSub(point, this_point_relative)
            this_tbn_inverse_matrix.printAttributes()
            point_tangent_space = this_tbn_inverse_matrix.mulPoint3ToMatrix3(point_relative)
            param_bounding_box_points_in_this_tangent_space.append(point_tangent_space)
        intersections = GeoMath.getIntersectionsBetweenEdges2D(
            GeoMath.getEdgesFromPoints(self.get_rectangle_tangent_space()),
            GeoMath.getEdgesFromPoints(param_bounding_box_points_in_this_tangent_space),
        )
        if DISPLAY:
            # TEMP: exit
            1 / 0
            exit()
            for intersection in intersections:
                this_tbn_matrix = self.get_tbn_class().get_tbn()
                point_object_space = this_tbn_matrix.mulPoint3ToMatrix3(intersection)
                point_absolute = GeoMath.vecPlus(point_object_space, this_point_relative)
                self.to_display_intersections.append(point_absolute)
            self.display_intersections()
        return intersections
Example #5
0
    def getRandomPattern(self,
                         wavelength,
                         pointI,
                         pointF,
                         normal,
                         height=None):
        logging.debug("Class Data, method getRandomPattern")

        add_noise = Add_noise()

        # Calculate height if not get
        if (not height):
            height = self.sizey / 2
        transformed_points = add_noise.apply_noise([pointI, pointF],
                                                   normal,
                                                   height,
                                                   True,
                                                   frequency='medium')
        # Now we add the heigth for each point, because the noise lies between [-sizey/2, sizey/2]
        # and we want [0, sizey]
        # So we get the direction of the noise and multiply by the heigth/2 and plus to the points
        positive_points = []
        # Calculate the sum to each point
        normal_with_module = GeoMath.vecScalarProduct(normal, height / 2)
        for point in transformed_points:
            positive_points.append(GeoMath.vecPlus(point, normal_with_module))
        logging.debug("Generated pattern finish: " + str(positive_points))

        dirWithModule = GeoMath.vecSub(pointF, pointI)
        # normal points size wavelenght
        pattern = GlassPatternDynamic(normal, positive_points,
                                      [dirWithModule[0], dirWithModule[1]],
                                      wavelength)

        return pattern
    def contain_bounding_box_3D(self, bounding_box):
        try:
            if not self.get_prim():
                raise Errors.CantBeNoneError("Prim cant be none", "We need a prim to calculate tbn some steps after")
        except Errors.CantBeNoneError as e:
            Errors.Error.display_exception(e)
            exit()

        inside = True
        if not self.get_rectangle_tangent_space():
            self.convert_3D_to_2D(self.get_prim())
        this_point_relative = self.get_tbn_class().get_point_which_is_relative()
        this_tbn_inverse_matrix = self.get_tbn_class().get_tbn_inverse()
        param_bounding_box_points_in_this_tangent_space = []
        for point in bounding_box.get_points_object_space():
            point_relative = GeoMath.vecSub(point, this_point_relative)
            point_tangent_space = this_tbn_inverse_matrix.mulPoint3ToMatrix3(point_relative)
            param_bounding_box_points_in_this_tangent_space.append(list(point_tangent_space))

        for point in param_bounding_box_points_in_this_tangent_space:
            logging.debug("Rectangle tangent space" + str(self.get_rectangle_tangent_space()))
            inside = GeoMath.pointInPoints(point, self.get_rectangle_tangent_space())
            if not inside:
                break
        return inside
 def findSomeGroupRecursively(self, prim, setNotDestroyed, setPartiallyDestroyed, setTotDestroyed):
     currentPartiallyDestroyed = list(setPartiallyDestroyed)
     '''
     h = HouInterface.HouInterface()
     h.showPoint(GeoMath.primBoundingBox(prim).center(), name='prim_' + str(prim.number()), color=[1, 0, 0])
     '''
     matchNotDes = prim in setNotDestroyed
     matchTotDes = prim in setTotDestroyed
     if(not matchNotDes):
         findInNotDestroyed = GeoMath.getConnectedPrims(prim, setNotDestroyed)
         matchNotDes = (findInNotDestroyed != [])
     if(not matchTotDes):
         findInTotDestroyed = GeoMath.getConnectedPrims(prim, setTotDestroyed)
         matchTotDes = (findInTotDestroyed != [])
     logging.debug("With prim %s, matchNotDes: %s, matchTotDes: %s", str(prim.number()), str(matchNotDes), str(matchTotDes))
     if(matchNotDes or matchTotDes):
         return matchNotDes, matchTotDes
     else:
         tempfind = []
         findInPartiallyDestroyed = GeoMath.getConnectedPrims(prim, currentPartiallyDestroyed)
         for primInPartiallyDestroyed in findInPartiallyDestroyed:
             if(primInPartiallyDestroyed not in self.path):
                 tempfind.append(primInPartiallyDestroyed)
         findInPartiallyDestroyed = list(tempfind)
         index = 0
         while(index < len(findInPartiallyDestroyed) and not matchNotDes and not matchTotDes):
             curPrim = findInPartiallyDestroyed[index]
             if(curPrim in currentPartiallyDestroyed):
                 logging.debug("with prim %s pass to %s", str(prim.number()), str(curPrim.number()))
                 currentPartiallyDestroyed.remove(curPrim)
                 matchNotDes, matchTotDes = self.findSomeGroupRecursively(curPrim, setNotDestroyed, currentPartiallyDestroyed, setTotDestroyed)
             index += 1
     return matchNotDes, matchTotDes
 def calculateDisplacement(self, curEdge, nextEdge):
     """
         Edges are correlatives and in wise direction
     """
     curEdgeNor = GeoMath.vecSub(curEdge[1], curEdge[0])
     curEdgeNor = GeoMath.vecNormalize(curEdgeNor)
     nextEdgeNor = GeoMath.vecSub(nextEdge[1], nextEdge[0])
     nextEdgeNor = GeoMath.vecNormalize(nextEdgeNor)
     return GeoMath.vecSub(curEdgeNor, nextEdgeNor)
Example #9
0
 def calculateDisplacement(self, curEdge, nextEdge):
     '''
         Edges are correlatives and in wise direction
     '''
     curEdgeNor = GeoMath.vecSub(curEdge[1], curEdge[0])
     curEdgeNor = GeoMath.vecNormalize(curEdgeNor)
     nextEdgeNor = GeoMath.vecSub(nextEdge[1], nextEdge[0])
     nextEdgeNor = GeoMath.vecNormalize(nextEdgeNor)
     return GeoMath.vecSub(curEdgeNor, nextEdgeNor)
    def goToPrimPattern(self, curPoint, nextPoint, pat, tbn, pointWhichIsRelative):
        '''
        TBN aplication
        '''
        global epsilon
        for num in range(len(pat.points)):
            pat.points[num] = tbn.mulPoint3ToMatrix3(pat.points[num])
            pat.points[num] = GeoMath.vecPlus(pointWhichIsRelative, pat.points[num])
        # Transform normal vector also
        logging.debug("Changing normal" + str(pat.getNormal()))
        transformed_normal = tbn.mulPoint3ToMatrix3(pat.getNormal())
        logging.debug("Transformed normal" + str(transformed_normal))
        normalized_normal = GeoMath.vecNormalize(transformed_normal)
        logging.debug("normalized normal" + str(normalized_normal))
        pat.setNormal(normalized_normal)
        logging.debug("normalized normal set?? " + str(pat.getNormal()))
        trans = GeoMath.vecSub(curPoint, pat.getFirstPoint())
        likelyPointF = GeoMath.vecPlus(pat.getLastPoint(), trans)
        if(GeoMath.vecModul(GeoMath.vecSub(likelyPointF, nextPoint)) > epsilon):
            trans = GeoMath.vecSub(curPoint, pat.getLastPoint())

        for num in range(len(pat.getPoints())):
            pat.points[num] = self.translatePointToPrim(pat.points[num], trans)

        if(GeoMath.vecModul(GeoMath.vecSub(likelyPointF, nextPoint)) > epsilon):
            pat.points.reverse()
Example #11
0
 def display_on(self, name = 'floor', HI = None):
     if(not HI):
         HI = HouInterface.HouInterface()
     # Get the size of the floor using its points
     bounding_box = GeoMath.boundingBox(self.get_absolute_points())
     size = bounding_box.sizevec()
     # Put the size 'y' that user wants the floor to be
     size[1] = self.extract_parm_from_user_restrictions('floor_default_size_y')
     center = GeoMath.centerOfPoints(self.get_absolute_points())
     nodeName = HI.showCube(name, size, center)
     self.associate_nodes = HI.cubes[nodeName]
    def do(self):

        angleToSum = abs(GeoMath.angleBetweenPointsByPrim(GeoMath.primBoundingBox(self.curPrim.prim).center(), \
                         GeoMath.primBoundingBox(self.nextPrim.prim).center(), self.refPrim.prim))

        heuristic = self.curPrim.F + 1
        angle = self.curPrim.sumAngle + angleToSum
        logging.debug("Heuristic for prim %s with next prim %s and ref prim %s, angle to sum: %s", str(self.curPrim.prim.number()), str(self.nextPrim.prim.number()), str(self.refPrim.prim.number()), str(angle))
        self.nextPrim.setHeuristic(heuristic, 0)
        self.nextPrim.setSumAngle(angle)
        return self.nextPrim
Example #13
0
    def pointInTexture(self, point):
        inside = None
        if(self.get_absolute_points_not_erasable()):
            inside = GeoMath.pointInPoints(point, self.get_absolute_points_not_erasable())
        elif(self.get_absolute_points()):
            inside = GeoMath.pointInPoints(point, self.get_absolute_points())

        if(inside == None):
            if(self.get_is_default_texture()):
                inside = True
        return inside
Example #14
0
 def display_on(self, name='floor', HI=None):
     if (not HI):
         HI = HouInterface.HouInterface()
     # Get the size of the floor using its points
     bounding_box = GeoMath.boundingBox(self.get_absolute_points())
     size = bounding_box.sizevec()
     # Put the size 'y' that user wants the floor to be
     size[1] = self.extract_parm_from_user_restrictions(
         'floor_default_size_y')
     center = GeoMath.centerOfPoints(self.get_absolute_points())
     nodeName = HI.showCube(name, size, center)
     self.associate_nodes = HI.cubes[nodeName]
    def pointInTexture(self, point):
        inside = None
        if (self.get_absolute_points_not_erasable()):
            inside = GeoMath.pointInPoints(
                point, self.get_absolute_points_not_erasable())
        elif (self.get_absolute_points()):
            inside = GeoMath.pointInPoints(point, self.get_absolute_points())

        if (inside == None):
            if (self.get_is_default_texture()):
                inside = True
        return inside
Example #16
0
 def getSimX(self, pattern):
     horizontal = abs(GeoMath.vecDotProduct(pattern.getNormal(), [1, 0, 0]))
     vertical = abs(GeoMath.vecDotProduct(pattern.getNormal(), [0, 1, 0]))
     oblique = abs(GeoMath.vecDotProduct(pattern.getNormal(), [1, 0, 0]))
     if (horizontal > vertical and horizontal > oblique):
         # return vertical simetry, but how this is the x and normal... it will be false
         return self.simx[1]
     if (vertical > horizontal and vertical > oblique):
         # return horizontal
         return self.simx[0]
     if (oblique > horizontal and oblique > vertical):
         # return oblique simetry
         return self.simx[2]
 def intersect_bounding_box_with_limits_2D(self, bounding_box, DISPLAY=False):
     intersection = GeoMath.getIntersectionBetweenEdgesWithoutLimits2D(
         self.get_edges_object_space(), bounding_box.get_edges_object_edges(), 1
     )
     intersection_bool = intersection or GeoMath.getEdgesBetweenEdges(
         self.get_points_object_space(), bounding_box.get_points_object_space(), 1
     )
     if DISPLAY:
         # TEMP: exit
         1 / 0
         exit()
         self.to_display_intersections.append(intersection)
     return intersection_bool
Example #18
0
 def getSimNormal(self, pattern):
     horizontal = abs(GeoMath.vecDotProduct(pattern.getNormal(), [1, 0, 0]))
     vertical = abs(GeoMath.vecDotProduct(pattern.getNormal(), [0, 1, 0]))
     oblique = abs(GeoMath.vecDotProduct(pattern.getNormal(), [1, 0, 0]))
     if (horizontal > vertical and horizontal > oblique):
         # return vertical simetry
         return self.simN[1]
     if (vertical > horizontal and vertical > oblique):
         # return horizontal simetry
         return self.simN[0]
     if (oblique > horizontal and oblique > vertical):
         # return oblique simetry
         return self.simN[2]
Example #19
0
 def getSimX(self, pattern):
     horizontal = abs(GeoMath.vecDotProduct(pattern.getNormal(), [1, 0, 0]))
     vertical = abs(GeoMath.vecDotProduct(pattern.getNormal(), [0, 1, 0]))
     oblique = abs(GeoMath.vecDotProduct(pattern.getNormal(), [1, 0, 0]))
     if (horizontal > vertical and horizontal > oblique):
         # return vertical simetry, but how this is the x and normal... it will be false
         return self.simx[1]
     if(vertical > horizontal and vertical > oblique):
         # return horizontal
         return self.simx[0]
     if(oblique > horizontal and oblique > vertical):
         # return oblique simetry
         return self.simx[2]
Example #20
0
 def getSimNormal(self, pattern):
     horizontal = abs(GeoMath.vecDotProduct(pattern.getNormal(), [1, 0, 0]))
     vertical = abs(GeoMath.vecDotProduct(pattern.getNormal(), [0, 1, 0]))
     oblique = abs(GeoMath.vecDotProduct(pattern.getNormal(), [1, 0, 0]))
     if (horizontal > vertical and horizontal > oblique):
         # return vertical simetry
         return self.simN[1]
     if(vertical > horizontal and vertical > oblique):
         # return horizontal simetry
         return self.simN[0]
     if(oblique > horizontal and oblique > vertical):
         # return oblique simetry
         return self.simN[2]
Example #21
0
    def intersections_with_crack(self, crack, path_ordered):
        reload(GeoMath)
        intersections = []
        edges_floor = GeoMath.getEdgesFromPoints(self.get_absolute_points())
        prev_intersection = None
        next_intersection = None
        #=======================================================================
        # we group the intersections in pairs, because after we'll have a different
        # destruction in the floor for each pair of intersection
        #=======================================================================

        for infoPrim in path_ordered:
            patterns = crack[infoPrim.getPrim()]
            for pattern in patterns:
                pattern_edges = GeoMath.getEdgesFromPoints(pattern.getPoints())
                may_intersect, pattern_edge_inter, floor_edge_inter = GeoMath.bolzanoIntersectionEdges2_5D(
                    pattern_edges, edges_floor)
                if (may_intersect):
                    # FIXME: HACK: we take one point of the pattern edge and put the y of the floor.
                    # We are assuming the edge is perpendicular to the floor.
                    # TEMP:
                    point_intersection = [
                        pattern_edge_inter[0][0], floor_edge_inter[0][1],
                        pattern_edge_inter[0][2]
                    ]
                    logging.debug("Intersection bef" + str(point_intersection))
                    logging.debug("fllor_edge_inter " + str(floor_edge_inter))
                    #point2DToProjectOntoXZ = [point_intersection[0], 0, point_intersection[2]]
                    #floorEdge2DToCalculateProjectionOntoXZ = [[floor_edge_inter[0][0],0 , floor_edge_inter[0][2]], [floor_edge_inter[1][0], 0, floor_edge_inter[1][2]]]

                    #point_intersection = GeoMath.getPointProjectionOnLine(floorEdge2DToCalculateProjectionOntoXZ, point2DToProjectOntoXZ)
                    #point_intersection = [point_intersection[0], floor_edge_inter[0][1], point_intersection[2]]

                    logging.debug("Intersection " + str(point_intersection))

                    if (not prev_intersection):
                        prev_intersection = point_intersection
                        break
                    elif (not GeoMath.pointEqualPoint(point_intersection,
                                                      prev_intersection)):
                        next_intersection = point_intersection
                        new_intersection = [
                            prev_intersection, next_intersection
                        ]
                        intersections.append(new_intersection)
                        prev_intersection = None
                        next_intersection = None
                        break
        return intersections
Example #22
0
 def intersect_bounding_box_with_limits_2D(self,
                                           bounding_box,
                                           DISPLAY=False):
     intersection = GeoMath.getIntersectionBetweenEdgesWithoutLimits2D(
         self.get_edges_object_space(),
         bounding_box.get_edges_object_edges(), 1)
     intersection_bool = intersection or GeoMath.getEdgesBetweenEdges(
         self.get_points_object_space(),
         bounding_box.get_points_object_space(), 1)
     if (DISPLAY):
         # TEMP: exit
         1 / 0
         exit()
         self.to_display_intersections.append(intersection)
     return intersection_bool
Example #23
0
    def mappingToPrimitive(self, prim):
        # If ttexture have not erasable points, return this points
        if(not self.get_absolute_points_not_erasable()):

            # If not, map to prim
            global primnumber
            global epsilon
            logging.debug('Start method mappingToPrimitive, class Texture')
            vertices = [list(p.point().position()) for p in prim.vertices()]
            logging.debug('Prim: ' + str(prim.number()) + ' points object space: '
                           + str(vertices))

            # Convert prim to tangent space of patterns
            tbnCalculated = CreateTBN.CreateTBN(prim)
            tbnCalculated.do()
            absolutePoints = []
            for point in self.get_delimited_proportions():
                pRotateAndScaled = tbnCalculated.get_tbn().mulPoint3ToMatrix3(point)
                pointInPrim = GeoMath.vecPlus(tbnCalculated.get_point_which_is_relative(),
                                               pRotateAndScaled)
                absolutePoints.append(pointInPrim)
                logging.debug('Point without tbn ' + str(point))
                logging.debug('Points converted ' + str(pointInPrim))
            self.set_absolute_points(absolutePoints)
        else:
            self.set_absolute_points(self.get_absolute_points_not_erasable())

        self.prim = prim
    def calculate_bounding_box_tangent_space(self):
        # Calculate bounding box in tangent space
        points_tangent_space = self.get_points_tangent_space()
        self.x_min_tangent = points_tangent_space[0][0]
        self.x_max_tangent = points_tangent_space[0][0]
        self.y_min_tangent = points_tangent_space[0][1]
        self.y_max_tangent = points_tangent_space[0][1]
        try:
            if not (
                self.x_max_tangent > 0 and self.y_max_tangent > 0 and self.x_min_tangent > 0 and self.y_min_tangent > 0
            ):
                raise Errors.NegativeValueError(
                    "Size cant be negtive",
                    "We need a positive size to do a" + " correct management of the size" + " after in other functions",
                )
        except Errors.NegativeValueError as e:
            Errors.Error.display_exception(e)
            # MAYFIX:Non negative values?
            # exit()
        for point in points_tangent_space:
            self.x_min_tangent = min(self.x_min_tangent, point[0])
            self.y_min_tangent = min(self.y_min_tangent, point[1])
            self.x_max_tangent = max(self.x_max_tangent, point[0])
            self.y_max_tangent = max(self.y_max_tangent, point[1])

        bounding_box_space_tangent_size = GeoMath.vecSub(
            [self.x_max_tangent, self.y_max_tangent, 0], [self.x_min_tangent, self.y_min_tangent, 0]
        )

        self.set_vector_size_tangent_space(bounding_box_space_tangent_size)
    def calculate_windows_size(self):
        global epsilon
        #=======================================================================
        # Get the insert node with windows
        #=======================================================================
        insert_windows = None
        for insert in self.get_inserts():
            for filter_group in insert.parm('filter').evalAsString().split():
                if(filter_group == self.extract_parm_from_user_restrictions('label_window')):
                    insert_windows = insert
                    break
        try:
            if(not insert_windows):
                logging.error('Class BuildingStructure, Label window not found at inserts')
                raise Errors.CantBeNoneError('Window cant be none',
                                             'Label window not found at inserts')
        except Errors.CantBeNoneError as e:
            Errors.Error.display_exception(e)
            exit()

        #=======================================================================
        # Get the size of the geometry of own window primitive
        #=======================================================================
        # We use the parent node because the insertnode has a cooked geometry
        # with windows inserteds.

        previous_node = insert_windows.inputs()[0]
        delete_node = previous_node.createOutputNode('delete')
        delete_node.parm('group').set(self.extract_parm_from_user_restrictions('label_window'))
        delete_node.parm('negate').set('keep')
        some_window = delete_node.geometry().prims()[0]
        window_points = [list(p.point().position()) for p in some_window.vertices()]
        window_bounding_box = GeoMath.boundingBox(window_points)
        window_size = [window_bounding_box.sizevec()[0], window_bounding_box.sizevec()[1]]
        return window_size
Example #26
0
 def contain_point_3D(self, point):
     inside = None
     if (not self.get_points_tangent_space()):
         self.create_3D_to_2D_rectangle(self.get_prim())
         inside = GeoMath.pointInPoints(point,
                                        self.get_points_tangent_space())
     return inside
Example #27
0
    def calculate_bounding_box_tangent_space(self):
        # Calculate bounding box in tangent space
        points_tangent_space = self.get_points_tangent_space()
        self.x_min_tangent = points_tangent_space[0][0]
        self.x_max_tangent = points_tangent_space[0][0]
        self.y_min_tangent = points_tangent_space[0][1]
        self.y_max_tangent = points_tangent_space[0][1]
        try:
            if (not (self.x_max_tangent > 0 and self.y_max_tangent > 0
                     and self.x_min_tangent > 0 and self.y_min_tangent > 0)):
                raise Errors.NegativeValueError(
                    'Size cant be negtive', 'We need a positive size to do a' +
                    ' correct management of the size' +
                    ' after in other functions')
        except Errors.NegativeValueError as e:
            Errors.Error.display_exception(e)
            # MAYFIX:Non negative values?
            # exit()
        for point in points_tangent_space:
            self.x_min_tangent = min(self.x_min_tangent, point[0])
            self.y_min_tangent = min(self.y_min_tangent, point[1])
            self.x_max_tangent = max(self.x_max_tangent, point[0])
            self.y_max_tangent = max(self.y_max_tangent, point[1])

        bounding_box_space_tangent_size = GeoMath.vecSub(
            [self.x_max_tangent, self.y_max_tangent, 0],
            [self.x_min_tangent, self.y_min_tangent, 0])

        self.set_vector_size_tangent_space(bounding_box_space_tangent_size)
    def mappingToPrimitive(self, prim):
        # If ttexture have not erasable points, return this points
        if (not self.get_absolute_points_not_erasable()):

            # If not, map to prim
            global primnumber
            global epsilon
            logging.debug('Start method mappingToPrimitive, class Texture')
            vertices = [list(p.point().position()) for p in prim.vertices()]
            logging.debug('Prim: ' + str(prim.number()) +
                          ' points object space: ' + str(vertices))

            # Convert prim to tangent space of patterns
            tbnCalculated = CreateTBN.CreateTBN(prim)
            tbnCalculated.do()
            absolutePoints = []
            for point in self.get_delimited_proportions():
                pRotateAndScaled = tbnCalculated.get_tbn().mulPoint3ToMatrix3(
                    point)
                pointInPrim = GeoMath.vecPlus(
                    tbnCalculated.get_point_which_is_relative(),
                    pRotateAndScaled)
                absolutePoints.append(pointInPrim)
                logging.debug('Point without tbn ' + str(point))
                logging.debug('Points converted ' + str(pointInPrim))
            self.set_absolute_points(absolutePoints)
        else:
            self.set_absolute_points(self.get_absolute_points_not_erasable())

        self.prim = prim
    def growing(self, thisPrim, previousPrim, allPrims, primsWithLine,
                volumeNode, sweepingNode):
        logging.debug(
            "Start method growing, class BoolIntersection_RegionGrowing")
        # Base case, prim matched
        if (thisPrim in primsWithLine.keys()
                and thisPrim not in self.primitivesDivided.keys()):
            # Divide prim in two prims with boolean intersection
            primDivided = PrimDivided.PrimDivided(thisPrim, previousPrim,
                                                  self.primitivesDivided,
                                                  primsWithLine, volumeNode,
                                                  sweepingNode)
            # "thisPrim" doesn't exists anymore(it was converted into two prims, contained in "primDivided"
            if (primDivided.prim):
                logging.debug("Divided prim de %s",
                              str(primDivided.prim.number()))
                self.primitivesDivided[thisPrim] = primDivided
            else:
                logging.debug("NO prim divided de %s", str(thisPrim.number()))
                logging.debug(
                    "End method growing, class BoolIntersection_RegionGrowing. State: good, no prim divided"
                )
                return
        inside = True
        # Only put in "already visited" the prims totally destroyed, the others remain in "primitivesDivided"
        if (thisPrim not in self.primitivesDivided.keys()):
            self.alreadyVisited.append(thisPrim)
            if (previousPrim in self.primitivesDivided.keys()):
                inside = self.testInsideOutside(
                    thisPrim, self.primitivesDivided[previousPrim])
        # Next recursivity
        if (inside):
            connectedPrims = GeoMath.getConnectedPrims(thisPrim, allPrims)
            logging.debug("CONNECTED PRIMS:")
            logging.debug(str([p.number() for p in connectedPrims]))
            for nextPrim in connectedPrims:
                if (nextPrim not in self.alreadyVisited
                        and nextPrim not in self.primitivesDivided.keys()):
                    logging.debug("Siguiente growing con: %s",
                                  str(nextPrim.number()), " viene de %s",
                                  str(thisPrim.number()))
                    self.growing(nextPrim, thisPrim, allPrims, primsWithLine,
                                 volumeNode, sweepingNode)
                else:
                    if (nextPrim in self.alreadyVisited):
                        logging.debug("Visitada %s", str(nextPrim.number()),
                                      " viene de %s", str(thisPrim.number()))
                    if (nextPrim in self.primitivesDivided.keys()):
                        logging.debug("Divided prim %s",
                                      str(nextPrim.number()), " viene de %s",
                                      str(thisPrim.number()))

        else:
            # It's not inside, so we have to conserve it
            self.alreadyVisited.pop()
        logging.debug(
            "End method growing, class BoolIntersection_RegionGrowing.  State: good"
        )
        return
Example #30
0
    def checkTexture(self, texture, previousTexture, genPattern, Fpoint, nextPoint):

        tex, nearestPointIntersect, minDistance = texture.findIntersectionWithNearestTexture(genPattern.getPoints())
        logging.debug("Start method checkTexture, class Crack")
        if(tex):
            logging.debug('nearestPointIntersect: ' + str(nearestPointIntersect) + 'Distance: ' + str(minDistance) + 'Texture: ' + str(tex.get_material().get_name()))
        else:
            logging.debug('nearestPointIntersect: ' + str(nearestPointIntersect) + 'Distance: ' + str(minDistance) + 'No Texture')

        # If we found some interect point we clip the pattern to this point
        if(nearestPointIntersect):
            achieved = genPattern.clipPattern(nearestPointIntersect)
            if(not achieved):
                logging.error("No clipping achieved")
                return None, previousTexture
        else:
            return None, previousTexture
        # Now we have to ensure that the next texture is correct, because possibly the intersection
        # is correct and the next texture in pattern direction is correct, but maybe the direction
        # has changed due to the clipping of the pattern and the point clipped. The direction now is
        # the direction between point clipped-intersected with next texture and the final point of
        # the crack in prim.
        # also, in the NORMAL case, maybe the pattern intersect with his texture, because are exiting
        # from it, so we have to do a point in polygon to search what texture is the next

        # Check texture, for do that get the vector direction and do it little and do a point in
        # polygon with the texture
        nextDir = GeoMath.vecSub(Fpoint, nearestPointIntersect)
        logging.debug('next dir before', str(nextDir))
        if(GeoMath.vecModul(nextDir) > 0):
            nextDir = GeoMath.vecNormalize(nextDir)
            # make it little, not more little than the epsilon used at GeoMath pointInSegmentDistance method,
            # so we use a 10x bigger than epsilon, so 0.05
            nextDir = GeoMath.vecScalarProduct(nextDir, 0.05)
            nextPoint = GeoMath.vecPlus(nextDir, nearestPointIntersect)
            nextTex = texture.findUpperTextureContainingPoint(nextPoint)
            logging.debug('Direction and texture , next point: %s, next direction', str(nextPoint), str(nextDir))
        else:
            nextTex = None
            # We get the final point, so we not have to ensure anything


        logging.debug("End method checkTexture, class Crack")
        if(nearestPointIntersect):
            self.intersectionPoints.append(nearestPointIntersect)
        return nearestPointIntersect, nextTex
    def findExtremePrims(self, startPoint, finalPoint, prims):
        startPrim = finalPrim = None
        for prim in prims:
            edge = GeoMath.getEdgeWithPointInPrim(prim, startPoint)
            if (edge):
                startPrim = prim
                logging.debug("prims start floor " + str(startPrim.number()))
                break

        for prim in prims:
            edge = GeoMath.getEdgeWithPointInPrim(prim, finalPoint)
            if (edge):
                finalPrim = prim
                logging.debug("prims final floor " + str(finalPrim.number()))
                break

        return startPrim, finalPrim
    def findExtremePrims(self, startPoint, finalPoint, prims):
        startPrim = finalPrim = None
        for prim in prims:
                edge = GeoMath.getEdgeWithPointInPrim(prim, startPoint)
                if(edge):
                    startPrim = prim
                    logging.debug("prims start floor " + str(startPrim.number()))
                    break

        for prim in prims:
            edge = GeoMath.getEdgeWithPointInPrim(prim, finalPoint)
            if(edge):
                finalPrim = prim
                logging.debug("prims final floor " + str(finalPrim.number()))
                break
                    
        return startPrim, finalPrim
Example #33
0
    def create_3D_to_2D_rectangle(self, prim):
        try:
            if (not prim):
                raise Errors.CantBeNoneError(
                    'Prim cant be none', 'We need a' +
                    ' prim to calculate tbn some' + ' steps after')
        except Errors.CantBeNoneError as e:
            Errors.Error.display_exception(e)
            exit()
        tbn_class = CreateTBN.CreateTBN(prim)
        tbn_class.do(scale=True)
        tbn_matrix = tbn_class.get_tbn()
        tbn_inverse_matrix = tbn_class.get_tbn_inverse()
        temporary_list = []
        for point in self.get_points_object_space():
            point_relative = GeoMath.vecSub(
                point, tbn_class.get_point_which_is_relative())
            point_tangent_space = tbn_inverse_matrix.mulPoint3ToMatrix3(
                point_relative)
            temporary_list.append(point_tangent_space)

        self.set_points_tangent_space(temporary_list)
        self.calculate_bounding_box_tangent_space()
        #=======================================================================
        # Tranform to object space
        #=======================================================================
        rectangle_tangent_space = self.create_rectangle('tangent')
        rectangle_object_space = []
        for point_tangent_space in rectangle_tangent_space:
            point_object_space_relative = tbn_matrix.mulPoint3ToMatrix3(
                point_tangent_space)
            point_object_space = GeoMath.vecPlus(
                point_object_space_relative,
                tbn_class.get_point_which_is_relative())
            rectangle_object_space.append(point_object_space)

        self.set_rectangle_object_space(rectangle_object_space)
        bounding_box_object_space_size = GeoMath.vecSub(
            rectangle_object_space[2], rectangle_object_space[0])
        self.set_vector_size_object_space(bounding_box_object_space_size)
        self.set_rectangle_tangent_space(rectangle_tangent_space)
        self.set_edges_object_space(
            GeoMath.getEdgesFromPoints(rectangle_object_space))
        self.set_edges_tangent_space(
            GeoMath.getEdgesFromPoints(rectangle_tangent_space))
        self.tbn_class = tbn_class
 def testInsideOutside(self, prim, primDivided):
     edgeToValidate = GeoMath.getSharedEdges(
         primDivided.pointsOutside,
         [list(po.point().position()) for po in prim.vertices()], 1)
     if (len(edgeToValidate) > 0):
         return True
     else:
         return False
    def patternPrimWithNeigborsPatternsPrims(pat, prim, groupOfPrims):
        reload(GeoMath)
        reload(BoundingBox)
        prims = groupOfPrims.keys()
        primsConected = GeoMath.getConnectedPrims(prim, prims)
        pattern_bounding_box = BoundingBox.BoundingBox2D(pat.getPoints(), prim)
        for primConected in primsConected:
            if(primConected != prim):
                gr = groupOfPrims[primConected]
                for patInGr in gr:
                    param_pattern_bounding_box = BoundingBox.BoundingBox2D(patInGr.getPoints(), prim)
                    intersections, shared_prims_edges = pattern_bounding_box.intersect_bounding_box_with_limits_3D(param_pattern_bounding_box)  # @UnusedVariable
                    if (intersections):
                        # Check if it is true that intersect
                        edges = GeoMath.getEdgesBetweenPoints(patInGr.getPoints(), pat.getPoints(), 1)

                        if(edges):
                            return False
        return True
 def intersect_bounding_box_2D(self, bounding_box, DISPLAY=False):
     intersection = GeoMath.getIntersectionsBetweenEdges2D(
         self.get_edges_object_space(), bounding_box.get_edges_object_edges(), 1
     )
     if DISPLAY:
         # TEMP: exit
         1 / 0
         exit()
         self.to_display_intersections.append(intersection)
     return intersection != []
 def isThisPrimMaybeValid(self, prim):
     # Has each edge of prim a connected prim? if not, track edges will not work!, so the prim
     # will not valid
     allGroups = []
     allGroups.extend(self.setNotDestroyed)
     allGroups.extend(self.setPartiallyDestroyed)
     allGroups.extend(self.setTotDestroyed)
     edgesHavingPrimitiveConnected = len(GeoMath.getConnectedPrimsOneForEachEdge(prim, allGroups))
     connectedWithNot = len(GeoMath.getConnectedPrims(prim, self.setNotDestroyed, 1))
     connectedWithTot = len(GeoMath.getConnectedPrims(prim, self.setTotDestroyed, 1))
     connectedWithPartially = len(GeoMath.getConnectedPrimsOneForEachEdge(prim, self.setPartiallyDestroyed))
     connectedWithPath = len(GeoMath.getConnectedPrimsOneForEachEdge(prim, self.path))
     # Prim must to acomplished that the number of connected with partially destroyed plus
     # connected with not destroyed plus connected with totally destroyed minus connecte with path
     # must to be greater than 2 primitives (at least two wanted primitives to do recursion after)
     logging.debug("Method isThisPrimMaybeValid, prim %s , with:", str(prim.number()))
     logging.debug("Connected with not: %s, connected with tot: %s, connected with partially: %s, connected with path: %s, edges having primitive: %s",
                   str(connectedWithNot), str(connectedWithTot), str(connectedWithPartially), str(connectedWithPath), str(edgesHavingPrimitiveConnected))
     return (((connectedWithPartially + connectedWithTot + connectedWithNot - connectedWithPath) >= 2) and (edgesHavingPrimitiveConnected == len(GeoMath.getEdgesFromPrim(prim))))
Example #38
0
 def intersect_bounding_box_2D(self, bounding_box, DISPLAY=False):
     intersection = GeoMath.getIntersectionsBetweenEdges2D(
         self.get_edges_object_space(),
         bounding_box.get_edges_object_edges(), 1)
     if (DISPLAY):
         # TEMP: exit
         1 / 0
         exit()
         self.to_display_intersections.append(intersection)
     return intersection != []
Example #39
0
 def applyDisplacement(self, point, displacement):
     displacement.append(0)
     m = GeoMath.Matrix(4, 4)
     m.matrix4Trans(displacement)
     point.append(1)
     pointModificated = m.mulPoint4ToMatrix4(point)
     point.pop()
     displacement.pop()
     pointModificated.pop()
     return pointModificated
    def doValidation(self, setNotDestroyed, setPartiallyDestroyed, setTotDestroyed, path):
        logging.debug("Start method doValidation. Class ValidatePath")
        '''
        We have to generate two branch for each primitive. One for one group of edges from prim, which
        all of its edges shared a group of primitives (not destroyed or tot destroyed), the other
        set of edges shared the other group of primitives (not destroyed or tot destroyed)
        
        To disjoin the two sets of edges, we take into account that each primitive is connected with
        two primitives more, that lies in set of path primitives. From one shared edge between this prim
        and one prim conected to this prim in the path set to the other edge shared to the other path prim
        we have a set of edges, and equal in the other side.
        '''
        validPrim1 = None
        validPrim2 = None
        find = False
        provePath = list(path)
        while(not (validPrim1 and validPrim2) and len(provePath) > 0):
            num = int(random.random() * len(provePath))
            prim = provePath[num]
            del provePath[num]
            '''
            h=HouInterface.HouInterface()
            h.showPoint(GeoMath.primBoundingBox(prim).center(), name='prim_'+str(prim.number()), color=[0,1,0])
            '''
            if(len(GeoMath.getEdgesFromPrim(prim)) <= 3):
                prim = self.tryToCollapseTwoTrianglesInOneQuad(prim, path)
                # NOT IMPLEMENTED YET
                logging.debug("Collapse in one quad NOT IMPLEMENTED YET")
            else:
                validPrim1, validPrim2 = self.getPrimsSharingGroupOfEdges(prim, setNotDestroyed, setPartiallyDestroyed, setTotDestroyed)
        if(not (validPrim1 and validPrim2)):
            logging.debug("Not valid path, because any prim is valid to do the validation, with groups:")
            logging.debug("Group not destroyed: %s", str([p.number() for p in setNotDestroyed]))
            logging.debug("Group partially destroyed: %s", str([p.number() for p in setPartiallyDestroyed]))
            logging.debug("Group totally destroyed: %s", str([p.number() for p in setTotDestroyed]))
            logging.debug("Path: %s", str([p.number() for p in path]))
            logging.debug("End method doValidation. Class ValidatePath. State: no valid path")
            #ONLY FOR DEBUGGING!!! IN FACT, IT MUST TO RETURN FALSE!!!!
            return True
        logging.debug("Valid primitives: %s, %s", str(validPrim1.number()), str(validPrim2.number()))
        matchNotDes1, matchTotDes1 = self.findSomeGroupRecursively(validPrim1, setNotDestroyed, setPartiallyDestroyed, setTotDestroyed)
        matchNotDes2, matchTotDes2 = self.findSomeGroupRecursively(validPrim2, setNotDestroyed, setPartiallyDestroyed, setTotDestroyed)
        if((matchNotDes1 and matchTotDes2) or (matchNotDes2 and matchTotDes1)):
            logging.debug("Valid path")
            logging.debug("End method doValidation. Class ValidatePath. State: good")
            find = True
        if (not find):
            logging.debug("Not valid path with groups:")
            logging.debug("Group not destroyed: %s", str([p.number() for p in setNotDestroyed]))
            logging.debug("Group partially destroyed: %s", str([p.number() for p in setPartiallyDestroyed]))
            logging.debug("Group totally destroyed: %s", str([p.number() for p in setTotDestroyed]))
            logging.debug("Path: %s", str([p.number() for p in path]))
            logging.debug("End method doValidation. Class ValidatePath. State: no valid path")

        return find
Example #41
0
    def rotatePattern(self, axis, angle):
        middlePoint = GeoMath.getCenterEdge(
            [self.points[0], self.points[len(self.points) - 1]])
        middlePoint.append(1)
        trans = GeoMath.Matrix(4, 4)
        trans.matrix4Trans(middlePoint)
        transIn = GeoMath.Matrix(4, 4)
        transIn.copy(trans)
        transIn.matrix4Inverse()
        for num in range(len(self.points)):
            pointRot = list(self.points[num])
            pointRot.append(1)
            pointRot = transIn.mulPoint4ToMatrix4(pointRot)
            if (axis == [1, 0, 0]):
                Rx = GeoMath.Matrix(4, 4)
                Rx.singleRotx(angle)
                pointRot = Rx.mulPoint4ToMatrix4(pointRot)
            elif (axis == [0, 1, 0]):
                Ry = GeoMath.Matrix(4, 4)
                Ry.singleRoty(angle)
                pointRot = Ry.mulPoint4ToMatrix4(pointRot)
            else:
                Rz = GeoMath.Matrix(4, 4)
                Rz.singleRotz(angle)
                pointRot = Rz.mulPoint4ToMatrix4(pointRot)

            pointRot = trans.mulPoint4ToMatrix4(pointRot)
            self.points[num] = pointRot
        # Rotate normal
        logging.debug('Normal not rotated:' + str(self.normal))
        to_rotate_normal = self.normal
        to_rotate_normal.append(0)
        if (axis == [1, 0, 0]):
            Rx = GeoMath.Matrix(4, 4)
            Rx.singleRotx(angle)
            normalRot = Rx.mulPoint4ToMatrix4(to_rotate_normal)
        elif (axis == [0, 1, 0]):
            Ry = GeoMath.Matrix(4, 4)
            Ry.singleRoty(angle)
            normalRot = Ry.mulPoint4ToMatrix4(to_rotate_normal)
        else:
            Rz = GeoMath.Matrix(4, 4)
            Rz.singleRotz(angle)
            normalRot = Rz.mulPoint4ToMatrix4(to_rotate_normal)
        normalRot.pop()
        logging.debug('Normal rotated: ' + str(normalRot))
        self.normal = normalRot
Example #42
0
    def intersections_with_crack(self, crack, path_ordered):
        reload(GeoMath)
        intersections = []
        edges_floor = GeoMath.getEdgesFromPoints(self.get_absolute_points())
        prev_intersection = None
        next_intersection = None
        #=======================================================================
        # we group the intersections in pairs, because after we'll have a different
        # destruction in the floor for each pair of intersection
        #=======================================================================

        for infoPrim in path_ordered:
            patterns = crack[infoPrim.getPrim()]
            for pattern in patterns:
                pattern_edges = GeoMath.getEdgesFromPoints(pattern.getPoints())
                may_intersect, pattern_edge_inter, floor_edge_inter = GeoMath.bolzanoIntersectionEdges2_5D(pattern_edges, edges_floor)
                if(may_intersect):
                    # FIXME: HACK: we take one point of the pattern edge and put the y of the floor.
                    # We are assuming the edge is perpendicular to the floor.
                    # TEMP:
                    point_intersection = [pattern_edge_inter[0][0], floor_edge_inter[0][1], pattern_edge_inter[0][2]]
                    logging.debug("Intersection bef" + str(point_intersection))
                    logging.debug("fllor_edge_inter " + str(floor_edge_inter))
                    #point2DToProjectOntoXZ = [point_intersection[0], 0, point_intersection[2]]
                    #floorEdge2DToCalculateProjectionOntoXZ = [[floor_edge_inter[0][0],0 , floor_edge_inter[0][2]], [floor_edge_inter[1][0], 0, floor_edge_inter[1][2]]]

                    #point_intersection = GeoMath.getPointProjectionOnLine(floorEdge2DToCalculateProjectionOntoXZ, point2DToProjectOntoXZ)
                    #point_intersection = [point_intersection[0], floor_edge_inter[0][1], point_intersection[2]]

                    logging.debug("Intersection " + str(point_intersection))
                    
                    if(not prev_intersection):
                        prev_intersection = point_intersection
                        break
                    elif(not GeoMath.pointEqualPoint(point_intersection, prev_intersection)):
                        next_intersection = point_intersection
                        new_intersection = [prev_intersection, next_intersection]
                        intersections.append(new_intersection)
                        prev_intersection = None
                        next_intersection = None
                        break
        return intersections
Example #43
0
 def findSomeGroupRecursively(self, prim, setNotDestroyed,
                              setPartiallyDestroyed, setTotDestroyed):
     currentPartiallyDestroyed = list(setPartiallyDestroyed)
     '''
     h = HouInterface.HouInterface()
     h.showPoint(GeoMath.primBoundingBox(prim).center(), name='prim_' + str(prim.number()), color=[1, 0, 0])
     '''
     matchNotDes = prim in setNotDestroyed
     matchTotDes = prim in setTotDestroyed
     if (not matchNotDes):
         findInNotDestroyed = GeoMath.getConnectedPrims(
             prim, setNotDestroyed)
         matchNotDes = (findInNotDestroyed != [])
     if (not matchTotDes):
         findInTotDestroyed = GeoMath.getConnectedPrims(
             prim, setTotDestroyed)
         matchTotDes = (findInTotDestroyed != [])
     logging.debug("With prim %s, matchNotDes: %s, matchTotDes: %s",
                   str(prim.number()), str(matchNotDes), str(matchTotDes))
     if (matchNotDes or matchTotDes):
         return matchNotDes, matchTotDes
     else:
         tempfind = []
         findInPartiallyDestroyed = GeoMath.getConnectedPrims(
             prim, currentPartiallyDestroyed)
         for primInPartiallyDestroyed in findInPartiallyDestroyed:
             if (primInPartiallyDestroyed not in self.path):
                 tempfind.append(primInPartiallyDestroyed)
         findInPartiallyDestroyed = list(tempfind)
         index = 0
         while (index < len(findInPartiallyDestroyed) and not matchNotDes
                and not matchTotDes):
             curPrim = findInPartiallyDestroyed[index]
             if (curPrim in currentPartiallyDestroyed):
                 logging.debug("with prim %s pass to %s",
                               str(prim.number()), str(curPrim.number()))
                 currentPartiallyDestroyed.remove(curPrim)
                 matchNotDes, matchTotDes = self.findSomeGroupRecursively(
                     curPrim, setNotDestroyed, currentPartiallyDestroyed,
                     setTotDestroyed)
             index += 1
     return matchNotDes, matchTotDes
Example #44
0
 def tryToCollapseTwoTrianglesInOneQuad(self, prim, path):
     index = 0
     while (index < len(path) and path[index] != prim):
         index += 1
     if (index == len(path)):
         # If error ocurred and no prim mathched
         return None
     nextPrim = (index + 1) % len(path)
     if (index != 0):
         previousPrim = len(path) - 1
     else:
         previousPrim = index - 1
     nextPrimEdges = GeoMath.getEdgesFromPrim(path[nextPrim])
     previousPrimEdges = GeoMath.getEdgesFromPrim(path[previousPrim])
     if (len(nextPrimEdges) >= 3 and len(previousPrimEdges) >= 3):
         return None
     else:
         # Case when we can to collapse two connected triangles
         # NOT IMPLEMENTED YET
         pass
Example #45
0
 def getFirstLayer(self, pointIni):
     first = self.getLayers()[0]
     texEdges = []
     texPoints = first.get_absolute_points()
     for n in range(len(texPoints) - 1):
         texEdges.append([texPoints[n], texPoints[n + 1]])
     if(GeoMath.pointInEdges(pointIni, texEdges)):
         firstLayer = first
     else:
         firstLayer = self.defaultTexture
     return firstLayer
 def tryToCollapseTwoTrianglesInOneQuad(self, prim, path):
     index = 0
     while(index < len(path) and path[index] != prim):
         index += 1
     if (index == len(path)):
         # If error ocurred and no prim mathched
         return None
     nextPrim = (index + 1) % len(path)
     if(index != 0):
         previousPrim = len(path) - 1
     else:
         previousPrim = index - 1
     nextPrimEdges = GeoMath.getEdgesFromPrim(path[nextPrim])
     previousPrimEdges = GeoMath.getEdgesFromPrim(path[previousPrim])
     if(len(nextPrimEdges) >= 3 and len(previousPrimEdges) >= 3):
         return None
     else:
         # Case when we can to collapse two connected triangles
         # NOT IMPLEMENTED YET
         pass
Example #47
0
    def findUpperTextureContainingPoint(self, point):

        if(not self.reverseListOfTextures):
            # Get ordered layers
            layers = list(self.getLayers())
            # We want to start from the upper texture, so we inverse the list
            layers.reverse()
            self.reverseListOfTextures = layers

        layerInPoint = None
        for layer in self.reverseListOfTextures:
            if(layer.pointInTexture(point)):
                if(GeoMath.pointInEdges(point, GeoMath.getEdgesFromPoints(layer.get_absolute_points()))):
                    # Warning!!! point are in the edge of a texture, so if you call this method to know
                    # the next texture be careful, it will be error
                    logging.warning('Method findUpperTextureContainingPoint, Point lie in a edge of texture')
                layerInPoint = layer
                break
        if(not layerInPoint):
            layerInPoint = self.getDefaultTexture()
        return layerInPoint
Example #48
0
 def isThisPrimMaybeValid(self, prim):
     # Has each edge of prim a connected prim? if not, track edges will not work!, so the prim
     # will not valid
     allGroups = []
     allGroups.extend(self.setNotDestroyed)
     allGroups.extend(self.setPartiallyDestroyed)
     allGroups.extend(self.setTotDestroyed)
     edgesHavingPrimitiveConnected = len(
         GeoMath.getConnectedPrimsOneForEachEdge(prim, allGroups))
     connectedWithNot = len(
         GeoMath.getConnectedPrims(prim, self.setNotDestroyed, 1))
     connectedWithTot = len(
         GeoMath.getConnectedPrims(prim, self.setTotDestroyed, 1))
     connectedWithPartially = len(
         GeoMath.getConnectedPrimsOneForEachEdge(
             prim, self.setPartiallyDestroyed))
     connectedWithPath = len(
         GeoMath.getConnectedPrimsOneForEachEdge(prim, self.path))
     # Prim must to acomplished that the number of connected with partially destroyed plus
     # connected with not destroyed plus connected with totally destroyed minus connecte with path
     # must to be greater than 2 primitives (at least two wanted primitives to do recursion after)
     logging.debug("Method isThisPrimMaybeValid, prim %s , with:",
                   str(prim.number()))
     logging.debug(
         "Connected with not: %s, connected with tot: %s, connected with partially: %s, connected with path: %s, edges having primitive: %s",
         str(connectedWithNot), str(connectedWithTot),
         str(connectedWithPartially), str(connectedWithPath),
         str(edgesHavingPrimitiveConnected))
     return (((connectedWithPartially + connectedWithTot +
               connectedWithNot - connectedWithPath) >= 2)
             and (edgesHavingPrimitiveConnected == len(
                 GeoMath.getEdgesFromPrim(prim))))
Example #49
0
    def intersect_bounding_box_3D(self, bounding_box, DISPLAY=False):
        try:
            if (not self.get_prim()):
                raise Errors.CantBeNoneError(
                    'Prim cant be none',
                    'We need a prim to calculate tbn some steps after')
        except Errors.CantBeNoneError as e:
            Errors.Error.display_exception(e)
            exit()

        if (not self.get_points_tangent_space()):
            self.create_3D_to_2D_rectangle(self.get_prim())
        this_point_relative = self.get_tbn_class().get_point_which_is_relative(
        )
        this_tbn_inverse_matrix = self.get_tbn_class().get_tbn_inverse()
        param_bounding_box_points_in_this_tangent_space = []
        for point in bounding_box.get_rectangle_object_space():
            point_relative = GeoMath.vecSub(point, this_point_relative)
            this_tbn_inverse_matrix.printAttributes()
            point_tangent_space = this_tbn_inverse_matrix.mulPoint3ToMatrix3(
                point_relative)
            param_bounding_box_points_in_this_tangent_space.append(
                point_tangent_space)
        intersections = GeoMath.getIntersectionsBetweenEdges2D(
            GeoMath.getEdgesFromPoints(self.get_rectangle_tangent_space()),
            GeoMath.getEdgesFromPoints(
                param_bounding_box_points_in_this_tangent_space))
        if (DISPLAY):
            # TEMP: exit
            1 / 0
            exit()
            for intersection in intersections:
                this_tbn_matrix = self.get_tbn_class().get_tbn()
                point_object_space = this_tbn_matrix.mulPoint3ToMatrix3(
                    intersection)
                point_absolute = GeoMath.vecPlus(point_object_space,
                                                 this_point_relative)
                self.to_display_intersections.append(point_absolute)
            self.display_intersections()
        return intersections
Example #50
0
    def patternPrimWithNeigborsPatternsPrims(pat, prim, groupOfPrims):
        reload(GeoMath)
        reload(BoundingBox)
        prims = groupOfPrims.keys()
        primsConected = GeoMath.getConnectedPrims(prim, prims)
        pattern_bounding_box = BoundingBox.BoundingBox2D(pat.getPoints(), prim)
        for primConected in primsConected:
            if (primConected != prim):
                gr = groupOfPrims[primConected]
                for patInGr in gr:
                    param_pattern_bounding_box = BoundingBox.BoundingBox2D(
                        patInGr.getPoints(), prim)
                    intersections, shared_prims_edges = pattern_bounding_box.intersect_bounding_box_with_limits_3D(
                        param_pattern_bounding_box)  # @UnusedVariable
                    if (intersections):
                        # Check if it is true that intersect
                        edges = GeoMath.getEdgesBetweenPoints(
                            patInGr.getPoints(), pat.getPoints(), 1)

                        if (edges):
                            return False
        return True
Example #51
0
 def getBestPrimReference(self, curPrim):
     listPrims = self.totDes
     index = 0
     #More little than the possible dot
     bestDot = -2
     while(index < len(listPrims) and bestDot < 0.998):
         #Both normals are good, because the projection will be the same
         dot = GeoMath.vecDotProduct(curPrim.prim.normal(), listPrims[index].prim.normal())
         if(dot > bestDot):
             bestDot = dot
             bestPrim = listPrims[index]
         index += 1
     return bestPrim
    def create_3D_to_2D_rectangle(self, prim):
        try:
            if not prim:
                raise Errors.CantBeNoneError(
                    "Prim cant be none", "We need a" + " prim to calculate tbn some" + " steps after"
                )
        except Errors.CantBeNoneError as e:
            Errors.Error.display_exception(e)
            exit()
        tbn_class = CreateTBN.CreateTBN(prim)
        tbn_class.do(scale=True)
        tbn_matrix = tbn_class.get_tbn()
        tbn_inverse_matrix = tbn_class.get_tbn_inverse()
        temporary_list = []
        for point in self.get_points_object_space():
            point_relative = GeoMath.vecSub(point, tbn_class.get_point_which_is_relative())
            point_tangent_space = tbn_inverse_matrix.mulPoint3ToMatrix3(point_relative)
            temporary_list.append(point_tangent_space)

        self.set_points_tangent_space(temporary_list)
        self.calculate_bounding_box_tangent_space()
        # =======================================================================
        # Tranform to object space
        # =======================================================================
        rectangle_tangent_space = self.create_rectangle("tangent")
        rectangle_object_space = []
        for point_tangent_space in rectangle_tangent_space:
            point_object_space_relative = tbn_matrix.mulPoint3ToMatrix3(point_tangent_space)
            point_object_space = GeoMath.vecPlus(point_object_space_relative, tbn_class.get_point_which_is_relative())
            rectangle_object_space.append(point_object_space)

        self.set_rectangle_object_space(rectangle_object_space)
        bounding_box_object_space_size = GeoMath.vecSub(rectangle_object_space[2], rectangle_object_space[0])
        self.set_vector_size_object_space(bounding_box_object_space_size)
        self.set_rectangle_tangent_space(rectangle_tangent_space)
        self.set_edges_object_space(GeoMath.getEdgesFromPoints(rectangle_object_space))
        self.set_edges_tangent_space(GeoMath.getEdgesFromPoints(rectangle_tangent_space))
        self.tbn_class = tbn_class
Example #53
0
    def getRandomPattern(self, wavelength, pointI, pointF, normal, height=None):
        logging.debug("Class Data, method getRandomPattern")

        add_noise = Add_noise()

        # Calculate height if not get
        if(not height):
            height = self.sizey / 2
        transformed_points = add_noise.apply_noise([pointI, pointF], normal, height, True, frequency='medium')
        # Now we add the heigth for each point, because the noise lies between [-sizey/2, sizey/2]
        # and we want [0, sizey]
        # So we get the direction of the noise and multiply by the heigth/2 and plus to the points
        positive_points = []
        # Calculate the sum to each point
        normal_with_module = GeoMath.vecScalarProduct(normal, height / 2)
        for point in transformed_points:
            positive_points.append(GeoMath.vecPlus(point, normal_with_module))
        logging.debug("Generated pattern finish: " + str(positive_points))

        dirWithModule = GeoMath.vecSub(pointF, pointI)
        # normal points size wavelenght
        pattern = GlassPatternDynamic(normal, positive_points, [dirWithModule[0], dirWithModule[1]], wavelength)

        return pattern
    def findBestPattern(self, curPoint, nextPoint, setClass, prim, patternCrack,
                         tbn, tbnInverse, pointWhichIsRelative, texture, texturePrim):
        logging.debug("Start method finBestPattern, class Autopattern")
        global epsilon
        global primnumber
        setPat = setClass.getPatternsWavelength(self.wavelength)
        # We have to convert vector, because the patterns are defined into positive xy plane
        goodPatterns = []
        vector = GeoMath.vecSub(nextPoint, curPoint)
        vectorRotated = tbnInverse.mulPoint3ToMatrix3(vector)
        for pat in setPat:
            goodPattern = self.getPossiblePatterns(curPoint, nextPoint, setClass,
                                                    epsilon, setPat, vector,
                                                     vectorRotated, pat)
            if(goodPattern):
                goodPatterns.append(goodPattern)

        # Validate patterns with prim
        validatedPatterns = []
        for pat in goodPatterns:
            validatedPattern = self.validateAndAdjustPatterns(
                                           curPoint, nextPoint, setClass, prim,
                                            patternCrack, tbn, pointWhichIsRelative,
                                            texture, texturePrim, pat)
            if(validatedPattern):
                validatedPatterns.append(validatedPattern)

        if(not validatedPatterns):
            # Apply the joker pattern!
            vecH, vecV = DetermineVectors.DetermineVectors.detVec(prim, GeoMath.vecSub(nextPoint, curPoint), [0, 0, 1])
            validatedPatterns.append(setClass.applyJoker(curPoint, nextPoint, vecH, vecV))
            logging.debug("End method finBestPattern, class Autopattern. State: Joker applied")
        else:
            logging.debug("End method finBestPattern, class Autopattern. State: good")

        return validatedPatterns[random.randint(0, len(validatedPatterns) - 1)]