示例#1
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.isbw1 = False

        self.verts = []
        self.faces = []
        self.texarchive = None

        self.main_model = None

        self.timer = QtCore.QTimer()
        self.timer.setInterval(2)
        self.timer.timeout.connect(self.render_loop)
        self.timer.start()
        self._lastrendertime = 0
        self._lasttime = 0

        self.shift_is_pressed = False

        self.MOVE_FORWARD = 0
        self.MOVE_BACKWARD = 0
        self.MOVE_LEFT = 0
        self.MOVE_RIGHT = 0
        self.MOVE_UP = 0
        self.MOVE_DOWN = 0
        self.ROTATE_RIGHT = 0
        self.ROTATE_LEFT = 0

        self.offset_x = -25
        self.offset_y = -25
        self.camera_height = 25

        self.camera_horiz = pi / 4.0
        self.camera_vertical = -pi / 8.0

        self._frame_invalid = False

        self._wasdscrolling_speed = 12.5
        self._wasdscrolling_speedupfactor = 5

        self.last_move = None
        self.camera_direction = None

        self.lines = []

        self.plane = Plane(Vector3(0, 0, 0), Vector3(1, 0, 0),
                           Vector3(0, 1, 0))

        self.selector = None

        self.setMouseTracking(True)

        self.collision = []

        self.models = []

        self.current_render_index = 0

        self.rotation = 0
        self._rotation_speed = 8
示例#2
0
    def handle_arrowkey_scroll_3d(self, timedelta):
        if self.selectionbox_projected_coords is not None:
            return

        diff_x = diff_y = diff_height = 0
        #print(self.MOVE_UP, self.MOVE_DOWN, self.MOVE_LEFT, self.MOVE_RIGHT)
        speedup = 1

        forward_vec = Vector3(cos(self.camera_horiz), sin(self.camera_horiz),
                              0)
        sideways_vec = Vector3(sin(self.camera_horiz), -cos(self.camera_horiz),
                               0)

        if self.shift_is_pressed:
            speedup = self._wasdscrolling_speedupfactor

        if self.MOVE_FORWARD == 1 and self.MOVE_BACKWARD == 1:
            forward_move = forward_vec * 0
        elif self.MOVE_FORWARD == 1:
            forward_move = forward_vec * (
                1 * speedup * self._wasdscrolling_speed * timedelta)
        elif self.MOVE_BACKWARD == 1:
            forward_move = forward_vec * (
                -1 * speedup * self._wasdscrolling_speed * timedelta)
        else:
            forward_move = forward_vec * 0

        if self.MOVE_LEFT == 1 and self.MOVE_RIGHT == 1:
            sideways_move = sideways_vec * 0
        elif self.MOVE_LEFT == 1:
            sideways_move = sideways_vec * (
                -1 * speedup * self._wasdscrolling_speed * timedelta)
        elif self.MOVE_RIGHT == 1:
            sideways_move = sideways_vec * (
                1 * speedup * self._wasdscrolling_speed * timedelta)
        else:
            sideways_move = sideways_vec * 0

        if self.MOVE_UP == 1 and self.MOVE_DOWN == 1:
            diff_height = 0
        elif self.MOVE_UP == 1:
            diff_height = 1 * speedup * self._wasdscrolling_speed * timedelta
        elif self.MOVE_DOWN == 1:
            diff_height = -1 * speedup * self._wasdscrolling_speed * timedelta

        if not forward_move.is_zero() or not sideways_move.is_zero(
        ) or diff_height != 0:
            #if self.zoom_factor > 1.0:
            #    self.offset_x += diff_x * (1.0 + (self.zoom_factor - 1.0) / 2.0)
            #    self.offset_z += diff_y * (1.0 + (self.zoom_factor - 1.0) / 2.0)
            #else:
            self.offset_x += (forward_move.x + sideways_move.x)
            self.offset_z += (forward_move.y + sideways_move.y)
            self.camera_height += diff_height
            # self.update()

            self.do_redraw()
示例#3
0
    def read_parameters(self, reader: GeneratorReader):
        if reader.read_token() != "{":
            raise RuntimeError("")

        next = reader.read_token()
        if next == "":
            raise RuntimeError("Tried to read parameters but encountered EOF")

        assert next in ("{", "}")

        while next != "}":
            param_name = reader.read_string()
            if param_name == "mPos":
                self.position = Vector3(*reader.read_vector3f())
                reader.read_token()
            elif param_name == "mPosture":
                self.rotation = Vector3(*reader.read_vector3f())
                reader.read_token()
            elif param_name == "mBaseScale":
                self.scale = reader.read_float()
                reader.read_token()
            elif param_name == "mEmitRadius":
                self.unknown_params[param_name] = reader.read_float()
                reader.read_token()
            else:
                unkdata = []
                level = 0
                while level != -1:
                    subnext = reader.read_token()
                    if subnext == "":
                        raise RuntimeError(
                            "Encountered EOF while reading parameter")
                    elif subnext == "{":
                        level += 1
                    elif subnext == "}":
                        level -= 1

                    if level != -1:
                        unkdata.append(subnext)

                self.unknown_params[param_name] = unkdata

            next = reader.read_token()
            syntax_assert(next != "",
                          "Reached end of file while parsing parameters",
                          reader.current_line)
            syntax_assert(
                next in ("{", "}"),
                "Malformed file, expected {{ or }} but got {0}".format(next),
                reader.current_line)
    def __init__(self, name, version, generatorid=["", "", ""]):
        self.name = name
        self.version = version
        self.generatorid = generatorid

        self.spline = []
        self.spline_float = None
        self.spline_params = []

        self.position = Vector3(0, 0, 0)
        self.rotation = Vector3(0, 0, 0)
        self.scale = 1.0

        self.unknown_params = OrderedDict()
示例#5
0
    def move(self, editor, buttons, event):
        if editor.gizmo.was_hit[self.axis_name]:
            editor.gizmo.hidden = True

            proj = numpy.dot(editor.mvp_mat, numpy.array([
                editor.gizmo.position.x,
                -editor.gizmo.position.z,
                editor.gizmo.position.y,
                1]
            ))

            # Dehogomization
            if proj[3] != 0.0:
                proj[0] = proj[0] / proj[3]
                proj[1] = proj[1] / proj[3]
                proj[2] = proj[2] / proj[3]

            # Transform to editor coords
            w = editor.canvas_width/2.0
            h = editor.canvas_height/2.0
            point_x = proj[0] * w + w
            point_y = -proj[1] * h + h

            x, y = event.x() - point_x, event.y() - point_y
            angle = atan2(y, x)
            if self.angle_start is not None:
                delta = self.angle_start - angle
                delta *= self.flip_rot(editor.camera_direction)

                # Sometimes on the first click the delta is too high resulting in
                # a big rotation. We will limit it this way
                if abs(delta) <= 0.3:
                    editor.rotate_current.emit(Vector3(*self.do_delta(delta)))
            self.angle_start = angle
示例#6
0
    def initializeGL(self):
        self.rotation_visualizer = glGenLists(1)
        glNewList(self.rotation_visualizer, GL_COMPILE)
        glColor4f(0.0, 0.0, 1.0, 1.0)

        glBegin(GL_LINES)
        glVertex3f(0.0, 0.0, 0.0)
        glVertex3f(0.0, 40.0, 0.0)
        glEnd()
        glEndList()

        self.models.init_gl()
        self.arrow = Material(texturepath="resources/arrow.png")

        self.minimap = Minimap(Vector3(-1000.0, 0.0, -1000.0),
                               Vector3(1000.0, 0.0, 1000.0), 0,
                               "resources/arrow.png")
示例#7
0
    def move(self, editor, buttons, event):
        startx, starty = editor.mouse_coord_to_world_coord(self.first_click.x, self.first_click.y)
        currx, curry = editor.mouse_coord_to_world_coord(event.x(), event.y())
        self.first_click.x = event.x()
        self.first_click.y = event.y()



        if len(editor.selected) == 0:
            return

        pane = editor.selected[0]

        if not self.shift_pressed and editor.shift_is_pressed:
            self.shift_pressed = True
            self.accumulate_rotation = pane.p_rotation
        elif self.shift_pressed and not editor.shift_is_pressed:
            self.shift_pressed = False


        if self.element_hit in ("move_inner", "move_outer"):
            diff = Vector3(currx - startx, curry - starty, 0)

            if pane.parent is not None:
                parent_transform = editor.transforms[pane.parent]
                inverse_parent = parent_transform.inverted()

                diff = inverse_parent.multiply_return_vec3(diff)

            print(diff)
            pane.p_offset_x += diff.x
            pane.p_offset_y += -diff.y
        elif self.element_hit == "rotation":

            angle_start = atan2(starty - editor.gizmo2d.position.y, startx - editor.gizmo2d.position.x)

            x, y = editor.mouse_coord_to_world_coord(event.x(), event.y())
            angle = atan2(curry - editor.gizmo2d.position.y, currx - editor.gizmo2d.position.x)
            delta = -(angle_start - angle)
            if not editor.shift_is_pressed:
                pane.p_rotation += degrees(delta)
            else:
                self.accumulate_rotation += degrees(delta)

                pane.p_rotation = round(self.accumulate_rotation/5)*5


        """if editor.gizmo.was_hit["gizmo_x"]:
            editor.gizmo.hidden = True
            editor.gizmo.set_render_axis(AXIS_X)
            delta_x = event.x() - self.first_click.x
            self.first_click = Vector2(event.x(), event.y())
            editor.move_points.emit(delta_x*editor.zoom_factor, 0, 0)"""
        editor.main_program.pik_control.update_info()
        editor.do_redraw(force=True)
示例#8
0
    def __init__(self):
        self.dolphin = Dolphin()
        self.karts = []
        self.kart_targets = []
        self.kart_headings = []

        for i in range(8):
            self.karts.append([None, Vector3(0.0, 0.0, 0.0)])
            self.kart_targets.append(Vector3(0.0, 0.0, 0.0))
            self.kart_headings.append(Vector3(0.0, 0.0, 0.0))
        self.stay_focused_on_player = -1

        self.timer = 0.0
        self.last_angle = 0.0
        self.last_x = 0.0
        self.last_z = 0.0

        self.last_kart_x = None
        self.last_kart_z = None

        self.last_angles = []
示例#9
0
    def create_ray_from_mouseclick(self, mousex, mousey, yisup=False):
        self.camera_direction.normalize()
        height = self.canvas_height
        width = self.canvas_width

        view = self.camera_direction.copy()

        h = view.cross(Vector3(0, 0, 1))
        v = h.cross(view)

        h.normalize()
        v.normalize()

        rad = 75 * pi / 180.0
        vLength = tan(rad / 2) * 1.0
        hLength = vLength * (width / height)

        v *= vLength
        h *= hLength

        x = mousex - width / 2
        y = height - mousey - height / 2

        x /= (width / 2)
        y /= (height / 2)
        camerapos = Vector3(self.offset_x, self.offset_z, self.camera_height)

        pos = camerapos + view * 1.0 + h * x + v * y
        dir = pos - camerapos

        if yisup:
            tmp = pos.y
            pos.y = -pos.z
            pos.z = tmp

            tmp = dir.y
            dir.y = -dir.z
            dir.z = tmp

        return Line(pos, dir)
示例#10
0
    def __init__(self, corner_model):
        self.visible = False
        self._bottom_left = Vector3(0, 0, 0)
        self._top_left = Vector3(0, 0, 0)
        self._top_right = Vector3(0, 0, 0)
        self._bottom_right = Vector3(0, 0, 0)

        self._middle_left = Vector3(0, 0, 0)
        self._middle_right = Vector3(0, 0, 0)
        self._middle_top = Vector3(0, 0, 0)
        self._middle_bottom = Vector3(0, 0, 0)
        self._transform = None

        self.corner = corner_model
        self._selected_corner = None
示例#11
0
        def change_up():
            print("finally changing up")
            forward, up, left = rotation.get_vectors()
            newup = Vector3(*[float(v.text()) for v in up_edits])
            if newup.norm() == 0.0:
                newup = forward.cross(left)
            newup.normalize()
            forward = left.cross(newup)
            forward.normalize()
            left = newup.cross(forward)
            left.normalize()

            rotation.set_vectors(forward, newup, left)
            self.update_rotation(forward_edits, up_edits)
示例#12
0
    def __init__(self,
                 name,
                 version,
                 generatorid=["", "", ""],
                 modes=[1, 1, 1],
                 fid=0,
                 fmt=0):
        self.name = name
        self.version = version
        self.generatorid = generatorid
        self.modes = modes
        self.fid = fid
        self.fmt = fmt

        self.spline = []
        self.spline_float = None
        self.spline_params = []

        self.position = Vector3(0, 0, 0)
        self.rotation = Vector3(0, 0, 0)
        self.scale = 1.0

        self.unknown_params = OrderedDict()
示例#13
0
        def change_forward():
            forward, up, left = rotation.get_vectors()

            newforward = Vector3(*[float(v.text()) for v in forward_edits])
            if newforward.norm() == 0.0:
                newforward = left.cross(up)
            newforward.normalize()
            up = newforward.cross(left)
            up.normalize()
            left = up.cross(newforward)
            left.normalize()

            rotation.set_vectors(newforward, up, left)
            self.update_rotation(forward_edits, up_edits)
示例#14
0
    def check_collision_2d(self, posx, posy):
        s = self._base_scale * self._scale
        offset = Vector3(self.position.x * s, self.position.y * s,
                         self.position.z * s)

        local_x = (posx - self.position.x)
        local_y = (posy - self.position.y)
        print(local_x, local_y)
        ray = Line(Vector3(local_x / s, local_y / s, 10), Vector3(0, 0, -1))
        closest = None
        clicked = None

        for name, mesh in self._model.named_meshes.items():
            for triangle in mesh.triangles:
                result = ray.collide(triangle)
                if result is not False:
                    point, d = result

                    if closest is None or d < closest:
                        closest = d
                        clicked = name

        return clicked
示例#15
0
    def _set_corners(self, transform, pane):
        offset_x, offset_y = PaneRender.get_anchor_offset(pane)
        w, h = pane.p_size_x, pane.p_size_y

        self._bottom_left = transform.multiply_return_vec3(
            Vector3(0.0 + offset_x, 0.0 - offset_y, 1))
        self._top_left = transform.multiply_return_vec3(
            Vector3(0.0 + offset_x, -h - offset_y, 1))
        self._top_right = transform.multiply_return_vec3(
            Vector3(w + offset_x, -h - offset_y, 1))
        self._bottom_right = transform.multiply_return_vec3(
            Vector3(w + offset_x, 0 - offset_y, 1))

        #self._bottom_left = (Vector3(0.0 + offset_x, 0.0 - offset_y, 1))
        #self._top_left = (Vector3(0.0 + offset_x, -h - offset_y, 1))
        #self._top_right = (Vector3(w + offset_x, -h - offset_y, 1))
        #self._bottom_right = (Vector3(w + offset_x, 0 - offset_y, 1))

        self._middle_left = (self._bottom_left + self._top_left) * 0.5
        self._middle_right = (self._bottom_right + self._top_right) * 0.5
        self._middle_top = (self._top_right + self._top_left) * 0.5
        self._middle_bottom = (self._bottom_left + self._bottom_right) * 0.5

        self._transform = transform
示例#16
0
    def __init__(self):
        super().__init__()

        self.position = Vector3(0.0, 0.0, 0.0)
        self.hidden = True

        self.callbacks = {}

        self.was_hit = {}
        self.was_hit_at_all = False
        for meshname in id_to_meshname.values():
            self.was_hit[meshname] = False

        self.render_axis = None

        with open("resources/gizmo_collision.obj", "r") as f:
            self.collision = Model.from_obj(f, rotate=True)
示例#17
0
    def move(self, editor, buttons, event):
        if editor.gizmo.was_hit["rotation_y"]:
            editor.gizmo.hidden = True
            self.was_hidden = True
            #editor.gizmo.set_render_axis(AXIS_Z)

            x, y = editor.mouse_coord_to_world_coord(self.first_click.x, self.first_click.y)
            angle_start = atan2(-(y + editor.gizmo.position.z), x - editor.gizmo.position.x)

            x, y = editor.mouse_coord_to_world_coord(event.x(), event.y())
            angle = atan2(-(y + editor.gizmo.position.z), x - editor.gizmo.position.x)
            delta = angle_start - angle


            editor.rotate_current.emit(Vector3(0, delta, 0))

            self.first_click = Vector2(event.x(), event.y())
示例#18
0
    def render_visual(self, renderer: BolMapViewer, selected):
        p = 0
        for valid, kartpos in self.karts:
            if valid:
                glPushMatrix()
                forward = self.kart_headings[p]
                up = Vector3(0.0, 1.0, 0.0)
                right = forward.cross(up)
                #up = right.cross(forward)
                """glMultMatrixf([
                    forward.x, forward.y, forward.z, 0,

                    right.x, right.y, right.z, 0,
                    up.x, up.y, up.z, 0,
                    kartpos.x, -kartpos.z, kartpos.y, 1]
                )"""
                """glMultMatrixf([
                    forward.x, right.x, up.x, 0,
                    -forward.z, -right.z, -up.z, 0,
                    forward.y, right.y, up.y, 0,

                    kartpos.x, -kartpos.z, kartpos.y, 1]
                )"""
                horiz = atan2(self.kart_headings[p].x,
                              self.kart_headings[p].z) - pi / 2.0

                glTranslatef(kartpos.x, -kartpos.z, kartpos.y)
                glRotatef(degrees(horiz), 0.0, 0.0, 1.0)

                renderer.models.playercolors[p].render(valid in selected)
                #renderer.models.render_player_position_colored(kartpos, valid in selected, p)
                glPopMatrix()

                glBegin(GL_LINE_STRIP)
                glColor3f(0.1, 0.1, 0.1)
                glVertex3f(kartpos.x, -kartpos.z, kartpos.y)
                glVertex3f(self.kart_targets[p].x, -self.kart_targets[p].z,
                           self.kart_targets[p].y)
                glEnd()

                renderer.models.render_player_position_colored(
                    self.kart_targets[p], False, p)
            p += 1
    def just_clicked(self, editor, buttons, event):
        #print("added object in 3d")
        ray = editor.create_ray_from_mouseclick(event.x(), event.y())
        place_at = None

        if editor.collision is not None:
            place_at = editor.collision.collide_ray(ray)

        if place_at is None:
            #print("colliding with plane")
            plane = Plane.xy_aligned(Vector3(0.0, 0.0, 0.0))

            collision = ray.collide_plane(plane)
            if collision is not False:
                place_at, _ = collision

        if place_at is not None:
            #print("placed at", place_at)
            editor.create_waypoint_3d.emit(place_at.x, place_at.z, -place_at.y)
示例#20
0
    def in_corner(self, x, y, scale):
        if not self.visible:
            return None
        else:
            for corner, val in ((self._bottom_left,
                                 self.BL), (self._bottom_right, self.BR),
                                (self._top_left, self.TL), (self._top_right,
                                                            self.TR),
                                (self._middle_left,
                                 self.ML), (self._middle_right, self.MR),
                                (self._middle_top,
                                 self.MT), (self._middle_bottom, self.MB)):

                diff = (Vector3(x, y, 0) - corner)
                #print("corner:", corner, "mouse:", x, y)
                #print("Distance:", dist, "radius:", RADIUS, "scaled:", RADIUS*scale, "scale:", scale)
                if diff.x**2 + diff.y**2 < (RADIUS * scale)**2:
                    return val

        return None
示例#21
0
    def render_scaled(self, scale, is3d=True):
        glPushMatrix()
        glTranslatef(self.position.x, -self.position.z, self.position.y)

        if self.render_axis == AXIS_X:
            glColor4f(*X_COLOR)
            self._draw_line(Vector3(-99999, 0, 0), Vector3(99999, 0, 0))
        elif self.render_axis == AXIS_Y:
            glColor4f(*Y_COLOR)
            self._draw_line(Vector3(0, 0, -99999), Vector3(0, 0, 99999))
        elif self.render_axis == AXIS_Z:
            glColor4f(*Z_COLOR)
            self._draw_line(Vector3(0, -99999, 0), Vector3(0, 99999, 0))
        glClear(GL_DEPTH_BUFFER_BIT)
        glScalef(scale, scale, scale)
        if not self.hidden:
            self.render(is3d)

        glPopMatrix()
示例#22
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self._zoom_factor = 10
        self.setFocusPolicy(Qt.ClickFocus)

        self.SIZEX = 1024  #768#1024
        self.SIZEY = 1024  #768#1024

        self.canvas_width, self.canvas_height = self.width(), self.height()

        #self.setMinimumSize(QSize(self.SIZEX, self.SIZEY))
        #self.setMaximumSize(QSize(self.SIZEX, self.SIZEY))
        self.setObjectName("bw_map_screen")

        self.origin_x = self.SIZEX // 2
        self.origin_z = self.SIZEY // 2

        self.offset_x = 0
        self.offset_z = 0

        self.left_button_down = False
        self.mid_button_down = False
        self.right_button_down = False
        self.drag_last_pos = None

        self.selected = []

        #self.p = QPainter()
        #self.p2 = QPainter()
        # self.show_terrain_mode = SHOW_TERRAIN_REGULAR

        self.selectionbox_start = None
        self.selectionbox_end = None

        self.visualize_cursor = None

        self.click_mode = 0

        self.level_image = None

        self.collision = None

        self.highlighttriangle = None

        self.setMouseTracking(True)

        self.pikmin_generators = None
        self.waterboxes = []

        self.mousemode = MOUSE_MODE_NONE

        self.overlapping_wp_index = 0
        self.editorconfig = None

        #self.setContextMenuPolicy(Qt.CustomContextMenu)

        self.spawnpoint = None

        self.shift_is_pressed = False
        self.rotation_is_pressed = False
        self.last_drag_update = 0
        self.change_height_is_pressed = False
        self.last_mouse_move = None

        self.timer = QtCore.QTimer()
        self.timer.setInterval(2)
        self.timer.timeout.connect(self.render_loop)
        self.timer.start()
        self._lastrendertime = 0
        self._lasttime = 0

        self._frame_invalid = False

        self.MOVE_UP = 0
        self.MOVE_DOWN = 0
        self.MOVE_LEFT = 0
        self.MOVE_RIGHT = 0
        self.MOVE_FORWARD = 0
        self.MOVE_BACKWARD = 0
        self.SPEEDUP = 0

        self._wasdscrolling_speed = 1
        self._wasdscrolling_speedupfactor = 3

        self.main_model = None
        self.buffered_deltas = []

        # 3D Setup
        self.mode = MODE_TOPDOWN
        self.camera_horiz = pi * (1 / 2)
        self.camera_vertical = -pi * (1 / 4)
        self.camera_height = 1000
        self.last_move = None

        #self.selection_queue = []
        self.selectionqueue = SelectionQueue()

        self.selectionbox_projected_start = None
        self.selectionbox_projected_end = None

        #self.selectionbox_projected_2d = None
        self.selectionbox_projected_origin = None
        self.selectionbox_projected_up = None
        self.selectionbox_projected_right = None
        self.selectionbox_projected_coords = None
        self.last_position_update = 0
        self.move_collision_plane = Plane(Vector3(0.0, 0.0, 0.0),
                                          Vector3(1.0, 0.0, 0.0),
                                          Vector3(0.0, 1.0, 0.0))

        self.paths = Paths()
        self.usercontrol = UserControl(self)

        # Initialize some models
        with open("resources/gizmo.obj", "r") as f:
            self.gizmo = Gizmo.from_obj(f, rotate=True)

        #self.generic_object = GenericObject()
        self.models = ObjectModels()
        self.grid = Grid(10000, 10000)

        self.modelviewmatrix = None
        self.projectionmatrix = None
示例#23
0
    def get_corner_normals(corner):
        if corner == BoxManipulator.BL:
            return Vector3(-1, 0, 0), Vector3(0, -1, 0)
        elif corner == BoxManipulator.ML:
            return Vector3(-1, 0, 0), Vector3(0, 0, 0)
        elif corner == BoxManipulator.TL:
            return Vector3(-1, 0, 0), Vector3(0, 1, 0)
        elif corner == BoxManipulator.MB:
            return Vector3(0, 0, 0), Vector3(0, -1, 0)
        elif corner == BoxManipulator.MT:
            return Vector3(0, 0, 0), Vector3(0, 1, 0)
        elif corner == BoxManipulator.BR:
            return Vector3(1, 0, 0), Vector3(0, -1, 0)
        elif corner == BoxManipulator.MR:
            return Vector3(1, 0, 0), Vector3(0, 0, 0)
        elif corner == BoxManipulator.TR:
            return Vector3(1, 0, 0), Vector3(0, 1, 0)

        return None
示例#24
0
 def __init__(self, model: Model):
     self._model = model
     self.visible = False
     self.position = Vector3(0, 0, 0)
     self._scale = 1.0
     self._base_scale = 100
示例#25
0
    def mousePressEvent(self, event):
        if event.buttons() & Qt.RightButton:
            self.last_move = (event.x(), event.y())

        elif event.buttons() & Qt.MiddleButton:
            print("hi", self.current_render_index)
            self.current_render_index += 1
            #self.re_render(self.model)

        elif event.buttons() & Qt.LeftButton:
            self.current_render_index = 0
            if self.camera_direction is not None:
                self.camera_direction.normalize()

                view = self.camera_direction.copy()

                h = view.cross(Vector3(0, 0, 1))
                v = h.cross(view)

                h.normalize()
                v.normalize()

                rad = 75 * pi / 180.0
                vLength = tan(rad / 2) * 1.0
                hLength = vLength * (self.width / self.height)

                v *= vLength
                h *= hLength

                mirror_y = self.height - event.y()

                x = event.x() - self.width / 2
                y = mirror_y - self.height / 2

                x /= (self.width / 2)
                y /= (self.height / 2)
                camerapos = Vector3(self.offset_x, self.offset_y,
                                    self.camera_height)

                pos = camerapos + view * 1.0 + h * x + v * y
                dir = pos - camerapos

                #self.lines.append((pos.x+0.5, pos.y, pos.z))
                #self.lines.append((pos.x + dir.x*400, pos.y + dir.y*400, pos.z + dir.z*400))

                # Plane Intersection
                line = Line(camerapos, dir)

                nearest_coll = None
                nearest_dist = None

                for tri in self.collision:
                    collision = line.collide(tri)

                    if collision is not False:
                        point, distance = collision
                        if nearest_coll is None or distance < nearest_dist:
                            nearest_coll = point
                            nearest_dist = distance

                if nearest_coll is not None:
                    collision = nearest_coll
                    self.lines.append((collision.x + dir.x * -100,
                                       collision.y + dir.y * -100,
                                       collision.z + dir.z * -100))
                    self.lines.append((collision.x + dir.x * +100,
                                       collision.y + dir.y * +100,
                                       collision.z + dir.z * +100))
                """if not self.plane.is_parallel(dir):
                    d = ((self.plane.origin - pos).dot(self.plane.normal)) / self.plane.normal.dot(dir)
                    if d >= 0:
                        point = pos + (dir*d)
                
                        self.lines.append((point.x, point.y, point.z-2000))
                        self.lines.append((point.x, point.y, point.z+2000))"""

                self.do_redraw()
示例#26
0
    def paintGL(self):
        start = default_timer()
        #Paint the scene.
        # clear the buffer
        #gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        glClearColor(1.0, 1.0, 1.0, 0.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)  # clear the screen
        glDisable(GL_CULL_FACE)
        #glEnable(GL_BLEND)
        #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        # set yellow color for subsequent drawing rendering calls

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(75, self.width / self.height, 1.0, 12800.0)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        look_direction = Vector3(cos(self.camera_horiz),
                                 sin(self.camera_horiz),
                                 sin(self.camera_vertical))
        #look_direction.unify()
        fac = 1.01 - abs(look_direction.z)
        #print(fac, look_direction.z, look_direction)

        gluLookAt(self.offset_x, self.offset_y, self.camera_height,
                  self.offset_x + look_direction.x * fac,
                  self.offset_y + look_direction.y * fac,
                  self.camera_height + look_direction.z, 0, 0, 1)

        self.camera_direction = Vector3(look_direction.x * fac,
                                        look_direction.y * fac,
                                        look_direction.z)

        glBegin(GL_LINES)
        glColor3f(0.0, 1.0, 0.0)
        glVertex3f(0, 0, -5000)
        glVertex3f(0, 0, 5000)

        glColor3f(0.0, 0.0, 1.0)
        glVertex3f(0, -5000, 0)
        glVertex3f(0, 5000, 0)

        glColor3f(1.0, 0.0, 0.0)
        glVertex3f(-5000, 0, 0)
        glVertex3f(5000, 0, 0)

        glColor3f(0.0, 1.0, 1.0)
        i = 0
        for line in self.lines:
            if i % 2 == 0:
                glColor3f(0.0, 1.0, 1.0)
            else:
                glColor3f(1.0, 1.0, 0.0)
            i += 1
            glVertex3f(*line)
        if self.selector is not None:
            glColor3f(1.0, 0.0, 1.0)
            glVertex3f(*self.selector[0])
            glVertex3f(*self.selector[1])
        glEnd()

        glRotatef(90, 1, 0, 0)
        for model in self.models:
            model.render()

        glRotatef(self.rotation, 0, 1, 0)

        if self.main_model is None:
            return
        """for node in self.model.nodes:
            for material in node.materials:
                if material.tex1 is not None:
                    self.texarchive.load_texture(material.tex1)"""
        #print("drawing", self.main_model, type(self.main_model))
        #glCallList(self.main_model)
        #self.main_model.sort_render_order(self.camera_direction.x, self.camera_direction.y, self.camera_direction.z)
        #self.main_model.sort_render_order(self.offset_x, self.camera_height, -self.offset_y)
        if not self.isbw1:
            glUseProgram(self.shader)
            texvar = glGetUniformLocation(self.shader, "tex")
            #print(texvar, self.shader, type(self.shader))
            glUniform1i(texvar, 0)
            bumpvar = glGetUniformLocation(self.shader, "bump")
            glUniform1i(bumpvar, 1)
            lightvar = glGetUniformLocation(self.shader, "light")
        else:
            glUseProgram(self.shaderSimple)
            texvar = glGetUniformLocation(self.shaderSimple, "tex")
            # print(texvar, self.shader, type(self.shader))
            glUniform1i(texvar, 0)
            lightvar = glGetUniformLocation(self.shaderSimple, "light")

        currenttime = default_timer()

        rot = (currenttime % 9) * 40 - self.rotation
        glUniform3fv(lightvar, 1, (sin(radians(rot)), 0, cos(radians(rot))))
        self.do_redraw()
        i = 0
        for node in self.main_model.nodes:
            if node.do_skip():
                continue

            i += 1
        if self.current_render_index > i:
            self.current_render_index = 0
        if not self.isbw1:
            self.main_model.render(self.texarchive, self.shader,
                                   self.current_render_index)
        else:
            self.main_model.render(self.texarchive, self.shaderSimple,
                                   self.current_render_index)

        glUseProgram(0)
        glFinish()
示例#27
0
    def paintGL(self):
        start = default_timer()
        offset_x = self.offset_x
        offset_z = self.offset_z

        #start = default_timer()
        glClearColor(1.0, 1.0, 1.0, 0.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        width, height = self.canvas_width, self.canvas_height

        if self.mode == MODE_TOPDOWN:
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            zf = self.zoom_factor
            #glOrtho(-6000.0, 6000.0, -6000.0, 6000.0, -3000.0, 2000.0)
            camera_width = width * zf
            camera_height = height * zf

            glOrtho(-camera_width / 2 - offset_x, camera_width / 2 - offset_x,
                    -camera_height / 2 + offset_z,
                    camera_height / 2 + offset_z, -3000.0, 2000.0)

            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()
        else:
            #glEnable(GL_CULL_FACE)
            # set yellow color for subsequent drawing rendering calls

            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            gluPerspective(75, width / height, 3.0, 12800.0 * 1.5)

            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()

            look_direction = Vector3(cos(self.camera_horiz),
                                     sin(self.camera_horiz),
                                     sin(self.camera_vertical))
            # look_direction.unify()
            fac = 1.01 - abs(look_direction.z)
            # print(fac, look_direction.z, look_direction)

            gluLookAt(self.offset_x, self.offset_z, self.camera_height,
                      self.offset_x + look_direction.x * fac,
                      self.offset_z + look_direction.y * fac,
                      self.camera_height + look_direction.z, 0, 0, 1)

            self.camera_direction = Vector3(look_direction.x * fac,
                                            look_direction.y * fac,
                                            look_direction.z)

            #print(self.camera_direction)

        self.modelviewmatrix = numpy.transpose(
            numpy.reshape(glGetFloatv(GL_MODELVIEW_MATRIX), (4, 4)))
        self.projectionmatrix = numpy.transpose(
            numpy.reshape(glGetFloatv(GL_PROJECTION_MATRIX), (4, 4)))
        self.mvp_mat = numpy.dot(self.projectionmatrix, self.modelviewmatrix)
        self.modelviewmatrix_inv = numpy.linalg.inv(self.modelviewmatrix)

        campos = Vector3(self.offset_x, self.camera_height, -self.offset_z)
        self.campos = campos

        if self.mode == MODE_TOPDOWN:
            gizmo_scale = 3 * zf
        else:

            gizmo_scale = (self.gizmo.position - campos).norm() / 130.0

        self.gizmo_scale = gizmo_scale

        #print(self.gizmo.position, campos)

        while len(self.selectionqueue) > 0:
            glClearColor(1.0, 1.0, 1.0, 0.0)
            #
            click_x, click_y, clickwidth, clickheight, shiftpressed, do_gizmo = self.selectionqueue.queue_pop(
            )
            click_y = height - click_y
            hit = 0xFF

            #print("received request", do_gizmo)

            if clickwidth == 1 and clickheight == 1:
                self.gizmo.render_collision_check(gizmo_scale,
                                                  is3d=self.mode == MODE_3D)
                pixels = glReadPixels(click_x, click_y, clickwidth,
                                      clickheight, GL_RGB, GL_UNSIGNED_BYTE)
                #print(pixels)
                hit = pixels[2]
                if do_gizmo and hit != 0xFF:
                    self.gizmo.run_callback(hit)
                    self.gizmo.was_hit_at_all = True
                #if hit != 0xFF and do_:

            glClearColor(1.0, 1.0, 1.0, 0.0)

            if self.pikmin_generators is not None and hit == 0xFF and not do_gizmo:
                objects = self.pikmin_generators.generators
                glDisable(GL_TEXTURE_2D)
                for i, pikminobject in enumerate(objects):
                    self.models.render_object_coloredid(pikminobject, i)

                pixels = glReadPixels(click_x, click_y, clickwidth,
                                      clickheight, GL_RGB, GL_UNSIGNED_BYTE)
                #print(pixels, click_x, click_y, clickwidth, clickheight)
                selected = {}
                #for i in range(0, clickwidth*clickheight, 4):
                start = default_timer()
                """for x in range(0, clickwidth, 3):
                    for y in range(0, clickheight, 3):
                        i = (x + y*clickwidth)*3
                        # | (pixels[i*3+0] << 16)
                        if pixels[i + 1] != 0xFF:
                            index = (pixels[i + 1] << 8) | pixels[i + 2]
                            #print(index)
                            pikminobject = objects[index]
                            selected[pikminobject] = True
                """
                for i in range(0, clickwidth * clickheight, 13):
                    # | (pixels[i*3+0] << 16)
                    if pixels[i * 3 + 1] != 0xFF:
                        index = (pixels[i * 3 + 1] << 8) | pixels[i * 3 + 2]
                        #print(index)

                        pikminobject = objects[index]
                        selected[pikminobject] = True
                #print("select time taken", default_timer() - start)
                selected = list(selected.keys())

                #print("result:", selected)
                if not shiftpressed:
                    self.selected = selected
                    self.select_update.emit()

                elif shiftpressed:
                    for obj in selected:
                        if obj not in self.selected:
                            self.selected.append(obj)
                    self.select_update.emit()

                self.gizmo.move_to_average(self.selected)
                if len(selected) == 0:
                    #print("Select did register")
                    self.gizmo.hidden = True
                if self.mode == MODE_3D:  # In case of 3D mode we need to update scale due to changed gizmo position
                    gizmo_scale = (self.gizmo.position - campos).norm() / 130.0
                #print("total time taken", default_timer() - start)
        #print("gizmo status", self.gizmo.was_hit_at_all)
        glClearColor(1.0, 1.0, 1.0, 0.0)

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glEnable(GL_DEPTH_TEST)
        glDisable(GL_TEXTURE_2D)
        glColor4f(1.0, 1.0, 1.0, 1.0)
        if self.main_model is not None:
            glCallList(self.main_model)

        glColor4f(1.0, 1.0, 1.0, 1.0)
        self.grid.render()
        if self.mode == MODE_TOPDOWN:
            glClear(GL_DEPTH_BUFFER_BIT)
        #    glDisable(GL_DEPTH_TEST)

        glEnable(GL_ALPHA_TEST)
        glAlphaFunc(GL_GEQUAL, 0.5)

        if self.pikmin_generators is not None:
            selected = self.selected
            objects = self.pikmin_generators.generators

            for pikminobject in objects:
                self.models.render_object(pikminobject, pikminobject
                                          in selected)

        glDisable(GL_TEXTURE_2D)
        glColor4f(0.0, 1.0, 0.0, 1.0)
        rendered = {}
        for p1i, p2i in self.paths.unique_paths:
            p1 = self.paths.waypoints[p1i]
            p2 = self.paths.waypoints[p2i]

            glBegin(GL_LINES)
            glVertex3f(p1.position.x, -p1.position.z, p1.position.y + 5)
            glVertex3f(p2.position.x, -p2.position.z, p2.position.y + 5)
            glEnd()

            if p1i not in rendered:
                self.models.draw_sphere(p1.position, p1.radius / 2)
                rendered[p1i] = True
            if p2i not in rendered:
                self.models.draw_sphere(p2.position, p2.radius / 2)
                rendered[p2i] = True
        glColor4f(0.0, 1.0, 1.0, 1.0)
        """for points in self.paths.wide_paths:
            glBegin(GL_LINE_LOOP)
            for p in points:
                glVertex3f(p.x, -p.z, p.y + 5)

            glEnd()"""

        self.gizmo.render_scaled(gizmo_scale, is3d=self.mode == MODE_3D)
        glDisable(GL_DEPTH_TEST)
        if self.selectionbox_start is not None and self.selectionbox_end is not None:
            #print("drawing box")
            startx, startz = self.selectionbox_start
            endx, endz = self.selectionbox_end
            glColor4f(1.0, 0.0, 0.0, 1.0)
            glLineWidth(2.0)
            glBegin(GL_LINE_LOOP)
            glVertex3f(startx, startz, 0)
            glVertex3f(startx, endz, 0)
            glVertex3f(endx, endz, 0)
            glVertex3f(endx, startz, 0)

            glEnd()

        if self.selectionbox_projected_origin is not None and self.selectionbox_projected_coords is not None:
            #print("drawing box")
            origin = self.selectionbox_projected_origin
            point2, point3, point4 = self.selectionbox_projected_coords
            glColor4f(1.0, 0.0, 0.0, 1.0)
            glLineWidth(2.0)

            point1 = origin

            glBegin(GL_LINE_LOOP)
            glVertex3f(point1.x, point1.y, point1.z)
            glVertex3f(point2.x, point2.y, point2.z)
            glVertex3f(point3.x, point3.y, point3.z)
            glVertex3f(point4.x, point4.y, point4.z)
            glEnd()

        glEnable(GL_DEPTH_TEST)
        glFinish()
        now = default_timer() - start
示例#28
0
    def mouseMoveEvent(self, event):
        if self.last_move is not None:
            curr_x, curr_y = event.x(), event.y()
            last_x, last_y = self.last_move

            diff_x = curr_x - last_x
            diff_y = curr_y - last_y

            self.last_move = (curr_x, curr_y)

            self.camera_horiz = (self.camera_horiz - diff_x *
                                 (pi / 500)) % (2 * pi)
            self.camera_vertical = (self.camera_vertical - diff_y * (pi / 600))
            if self.camera_vertical > pi / 2.0: self.camera_vertical = pi / 2.0
            elif self.camera_vertical < -pi / 2.0:
                self.camera_vertical = -pi / 2.0

            #print(self.camera_vertical, "hello")
            self.do_redraw()

        if self.camera_direction is not None:
            self.camera_direction.normalize()

            view = self.camera_direction.copy()

            h = view.cross(Vector3(0, 0, 1))
            v = h.cross(view)

            h.normalize()
            v.normalize()

            rad = 75 * pi / 180.0
            vLength = tan(rad / 2) * 1.0
            hLength = vLength * (self.width / self.height)

            v *= vLength
            h *= hLength

            mirror_y = self.height - event.y()

            x = event.x() - self.width / 2
            y = mirror_y - self.height / 2

            x /= (self.width / 2)
            y /= (self.height / 2)
            camerapos = Vector3(self.offset_x, self.offset_y,
                                self.camera_height)
            #print(h * x)
            #print(v * y)
            #print(view)
            pos = camerapos + view * 1.0 + h * x + v * y
            dir = pos - camerapos

            # self.lines.append((pos.x+0.5, pos.y, pos.z))
            # self.lines.append((pos.x + dir.x*400, pos.y + dir.y*400, pos.z + dir.z*400))

            # Plane Intersection

            if not self.plane.is_parallel(dir):
                d = ((self.plane.origin - pos).dot(
                    self.plane.normal)) / self.plane.normal.dot(dir)
                if d >= 0:
                    point = pos + (dir * d)
                    self.selector = ((point.x, point.y, point.z - 2000),
                                     (point.x, point.y, point.z + 2000))
                    self.camera_moved.emit(point.x, point.y, point.z)
                else:
                    self.selector = None
            else:
                self.selector = None

            self.do_redraw()
示例#29
0
    def move(self, editor, buttons, event):
        if self.handle is not None:
            startx, starty = editor.mouse_coord_to_world_coord(self.first_click.x, self.first_click.y)
            currx, curry = editor.mouse_coord_to_world_coord(event.x(), event.y())
            diff = Vector3(currx-startx, curry-starty, 0)
            #transformed_diff = editor.box_manipulator.transform(diff)
            inverse = editor.box_manipulator._transform.inverted()

            vec_horizontal, vec_vertical = editor.box_manipulator.get_corner_normals(self.handle)
            # diffx *= abs(sidex)
            # diffy *= abs(sidey)

            # diffxbox = diff.x*abs(sidex)#transformed_diff.x*abs(sidex)
            # diffybox = diff.y*abs(sidey)#transformed_diff.y*abs(sidey)


            #print(diff, diffx, diffy)

            diff_box_space = inverse.multiply_return_vec3(diff)
            diff_box_change = vec_horizontal*diff_box_space.x + vec_vertical*diff_box_space.y
            #diff2 = diff_box_space
            #print(diff, diff2)
            #diff = diff2

            pane = editor.selected[0]
            vec_horizontal_abs = vec_horizontal.abs()
            vec_vertical_abs = vec_vertical.abs()

            restrictx, restricty = editor.box_manipulator.do_restrict(self.handle)
            diff_new = Vector3(diff_box_space.x*restrictx, diff_box_space.y*restricty, 0)
            diff = editor.box_manipulator._transform.multiply_return_vec3(diff_new)

            if pane.parent is not None:
                parent_transform = editor.transforms[pane.parent]
                inverse_parent = parent_transform.inverted()

                #vec_horizontal_abs = inverse_parent.multiply_return_vec3(vec_horizontal_abs)
                #vec_vertical_abs = inverse_parent.multiply_return_vec3(vec_vertical_abs)

                diff = inverse_parent.multiply_return_vec3(diff)

                print("transformed", diff)


            #vec_horizontal.x = abs(vec_horizontal.x)
            #vec_horizontal.y = abs(vec_horizontal.y)
            #vec_vertical.x = abs(vec_vertical.x)
            #vec_vertical.y = abs(vec_vertical.y)
            #alpha = radians(pane.p_rotation)
            #vec_vertical_abs.x, vec_vertical_abs.y = rotate(vec_vertical_abs, radians(pane.p_rotation))
            #vec_horizontal_abs.x, vec_horizontal_abs.y = rotate(vec_horizontal_abs, radians(pane.p_rotation))

            #diff_change = vec_horizontal_abs*diff.x + vec_vertical_abs*diff.y
            diff_change = diff

            """alpha = radians(pane.p_rotation)
            diff_change_x = diff_change.x * cos(alpha) - diff_change.y * sin(alpha)
            diff_change_y = diff_change.x * sin(alpha) + diff_change.y * cos(alpha)
            diff_change.x = diff_change_x
            diff_change.y = diff_change_y"""
            #rot = -radians(pane.p_rotation)
            #diffx = transformed_diff.x*cos(rot) - transformed_diff.y*sin(rot)
            #diffy = transformed_diff.x*sin(rot) + transformed_diff.y*cos(rot)
            #print("diff", diffx, diffy)
            #diffx = currx-startx
            #diffy = curry-starty


            #pane.resize(diff.x*abs(sidex), -diff.y*abs(sidey), diff_box_space.x*abs(sidex), -diff_box_space.y*abs(sidey), sidex, sidey)
            #print(diffx, diffy, diff_box_change)

            pane.resize(diff_change.x, -diff_change.y, diff_box_change.x, -diff_box_change.y)

            self.first_click.x = event.x()
            self.first_click.y = event.y()
            editor.main_program.pik_control.update_info()
            editor.do_redraw(force=True)
            """selectendx, selectendz = editor.mouse_coord_to_world_coord(event.x(), event.y())
示例#30
0
def draw_collision(verts, faces):
    biggest, smallest = None, None
    for x, y, z in verts:
        if biggest is None:
            biggest = smallest = y
        if y > biggest:
            biggest = y
        if y < smallest:
            smallest = y
    scaleheight = biggest - smallest
    if scaleheight == 0:
        scaleheight = 1

    print(len(COLORS))
    lightvec = Vector3(0, 1, -1)

    glBegin(GL_TRIANGLES)

    i = -1
    for v1, v2, v3 in faces:
        i += 1
        v1x, v1y, v1z = verts[v1]
        v2x, v2y, v2z = verts[v2]
        v3x, v3y, v3z = verts[v3]

        # grayscale = ((v1y+v2y+v3y)/3.0)/scaleheight
        """average_y = max(v1y, v2y,v3y) - smallest#(v1y+v2y+v3y)/3.0 - smallest
        index = int((average_y/scaleheight)*len(COLORS))
        if index < 0:
            index = 0
        if index >= len(COLORS):
            index = len(COLORS)-1
        r, g, b = COLORS[index]
        glColor3f(r/256.0,g/256.0,b/256.0)"""

        if DO_GRAYSCALE:
            average_y = (v1y + v2y + v3y) / 3.0 - smallest
            grayscale = average_y / scaleheight

            glColor3f(grayscale, grayscale, grayscale)
            glVertex3f(v1x, -v1z, v1y)
            glVertex3f(v2x, -v2z, v2y)
            glVertex3f(v3x, -v3z, v3y)

        else:
            face = Triangle(Vector3(v1x, -v1z, v1y), Vector3(v2x, -v2z, v2y),
                            Vector3(v3x, -v3z, v3y))
            if face.normal.norm() != 0:
                angle = lightvec.cos_angle(face.normal)
            else:
                angle = 0.0
            light = max(abs(angle), 0.3)

            average_y = v1y - smallest
            index = int((average_y / scaleheight) * len(COLORS))
            if index < 0:
                index = 0
            if index >= len(COLORS):
                index = len(COLORS) - 1
            r, g, b = (i * light for i in COLORS[index])
            glColor3f(r / 256.0, g / 256.0, b / 256.0)
            glVertex3f(v1x, -v1z, v1y)

            average_y = v2y - smallest
            index = int((average_y / scaleheight) * len(COLORS))
            if index < 0:
                index = 0
            if index >= len(COLORS):
                index = len(COLORS) - 1
            r, g, b = (i * light for i in COLORS[index])
            glColor3f(r / 256.0, g / 256.0, b / 256.0)
            glVertex3f(v2x, -v2z, v2y)

            average_y = v3y - smallest
            index = int((average_y / scaleheight) * len(COLORS))
            if index < 0:
                index = 0
            if index >= len(COLORS):
                index = len(COLORS) - 1
            r, g, b = (i * light for i in COLORS[index])
            glColor3f(r / 256.0, g / 256.0, b / 256.0)
            glVertex3f(v3x, -v3z, v3y)
    glEnd()