def setPosition(self): if self.parent == pixel2d: frame_width = app.get_show_base().win.getXSize() frame_height = app.get_show_base().win.getYSize() else: size = self.parent["frameSize"] if size is not None: frame_width = size[1] - size[0] frame_height = size[3] - size[2] else: frame_width = 0 frame_height = 0 x0, y0 = 0, 0 x, y = self["position"] if self["orginH"] is "left": x0 = 0 elif self["orginH"] is "center": x0 = frame_width / 2 elif self["orginH"] is "right": x0 = frame_width if self["orginV"] is "top": y0 = 0 elif self["orginV"] is "middle": y0 = -frame_height / 2 elif self["orginV"] is "bottom": y0 = -frame_height self.setPos(x0 + x, 0, y0 - y)
def setPosition(self): win_width = app.get_show_base().win.getXSize() win_height = app.get_show_base().win.getYSize() h1, h2 = self["position"] if self["orginV"] is "top": self.setPos(0, 0, -h1) elif self["orginV"] is "middle": self.setPos(0, 0, -win_height / 2 - h1) elif self["orginV"] is "bottom": self.setPos(0, 0, -win_height - h1) height = h2 - h1 self["frameSize"] = (0, win_width, 0, -height)
def focus_task(self, task): panda3d = app.get_show_base() btn = panda3d.mouseWatcherNode if btn.isButtonDown("mouse1"): mouse_data = panda3d.win.getPointer(0) mouse_x, mouse_y = mouse_data.getX(), mouse_data.getY() frame_size = self["frameSize"] if frame_size is None: frame_size = self.getBounds() else: frame_size = list(frame_size) pos = self.getPos(pixel2d) x0 = pos[0] + frame_size[0] x1 = pos[0] + frame_size[1] y0 = -pos[2] - frame_size[2] y1 = -pos[2] - frame_size[3] x_left = min(x0, x1) x_right = max(x0, x1) y_top = min(y0, y1) y_bottom = max(y0, y1) overmouse_x = (x_left <= mouse_x <= x_right) overmouse_y = (y_top <= mouse_y <= y_bottom) if not overmouse_x or not overmouse_y: print("over task") task_manager.remove(task) self["focus"] = False return task.cont
def draw_get_font( font_name: str = None, font_size: int = None ) -> (Type[DynamicTextFont], Type[ImageFont.FreeTypeFont]): """ Devuelve la fuente activa, o la fuente especificada como parámetro """ fonts = DRAW_DATA.get("fonts") if font_name is None: font_name = fonts.get("_active") if font_size is None: font_size = fonts.get("_size") if font_name not in fonts: loader = app.get_show_base().loader font_panda3d = loader.loadFont("data/fonts/{}.ttf".format(font_name)) font_panda3d.setPixelSize(30) font_pil = ImageFont.truetype("data/fonts/{}.ttf".format(font_name), font_size) fonts[font_name] = { "panda3d": font_panda3d, "pil{}".format(font_size): font_pil } else: font = fonts.get(font_name) font_panda3d = font.get("panda3d") font_pil = font.get("pil{}".format(font_size)) fonts.update({"_active": font_name}) return font_panda3d, font_pil
def change_cursor(cursor_file): winprops = WindowProperties() filename = Filename.binaryFilename(cursor_file) print("filename", filename.exists()) winprops.setCursorFilename(filename) base = app.get_show_base() base.win.requestProperties(winprops)
def get_mouse_3d_coords_task(): # Obtenemos la ubicación absoluta de la camara y su dirección base = app.get_show_base() if base.mouseWatcherNode.has_mouse(): camera_vect = base.camera.getQuat(base.render).getForward() camera_pos = base.camera.get_pos(base.render) """ Para determinar la posición origen del rayo se mueve un objeto cursor enparentado a la camara, estableciendo su posición realtiva a esta en funcion de la ubicacion del mouse """ width = base.win.getXSize() height = base.win.getYSize() mouse_data = base.win.getPointer(0) mouse_pos = mouse_data.getX(), mouse_data.getY() cursor_x = (mouse_pos[0] - width / 2) / 100 cursor_y = (height / 2 - mouse_pos[1]) / 100 app.cursor.set_pos(cursor_x, 2, cursor_y) cursor_pos = app.cursor.get_pos(base.render) """ El siguiente código calcula la intersección entre el plano de trabajo y la recta de acción del mouse from https://stackoverflow.com/a/39424162 """ epsilon = 1e-6 # Define plane plane_normal = np.array(app.work_plane_vect) plane_point = np.array(app.work_plane_point) # Any point on the plane # Define ray ray_direction = np.array(camera_vect) ray_point = np.array(cursor_pos) # Any point along the ray ndotu = plane_normal.dot(ray_direction) if abs(ndotu) < epsilon: # No se encuentra intersección app.work_plane_mouse = [None, None, None] else: # Se encuentra intersección w = ray_point - plane_point si = -plane_normal.dot(w) / ndotu psi = w + si * ray_direction + plane_point app.work_plane_mouse = psi return app.work_plane_mouse
def set_cursor(cursor: str): """ change the current filename cursor from the default cursor directory """ global cursor_dir cursor_filename = cursor_dir + cursor winprops = WindowProperties() winprops.setCursorFilename(cursor_filename) base = app.get_show_base() base.win.requestProperties(winprops)
def get_parent_size(self): if self.parent == pixel2d: parent_width = app.get_show_base().win.getXSize() parent_height = app.get_show_base().win.getYSize() else: if self.parent_gui is not None: size = self.parent_gui["frameSize"] if size is None: print("size is None", self.parent_gui) if hasattr(self.parent_gui, "getCanvas"): size = self.parent_gui["canvasSize"] parent_width = size[1] - size[0] parent_height = size[3] - size[2] else: parent_width = 0 parent_height = 0 return parent_width, parent_height
def __init__(self): draw.draw_set_font() app.main_ui = self base = app.get_show_base() base.setBackgroundColor(1, 1, 1) self.layout = interface.Layout() self.option_bar = OptionBar() self.prop_editor = interface.PropertiesEditor(self.layout) self.status_bar = interface.StatusBar(self.layout) interface.ConsoleUI(self.layout)
def draw_cicle(x, y, r, col=None, parent=None): base = app.get_show_base() loader = Loader(base) model = loader.loadModel("data/geom/circle.egg") col = draw_get_color(col, color_format="rgba") if parent is None: parent = builtins.pixel2d model.reparentTo(parent) model.setPos(x, 0, -y) model.setScale(r, 1, r) # model.setColorScale(1, 0, 0, 1) model.setColor(col) return model
def __init__(self): self.panda3d = app.get_show_base() self.options_frame = WideFrame(position=[0, 150], colorString="C_NEPHRITIS") app.add_gui_region("options_frame", self.options_frame) workspace = SimpleFrame(position=[0, 0], sizeHint=[1, 1], alpha=0, padding=[250, 0, 25, 150]) self.tab_btn = [] self.tab_frames = [] self.active_tab = 0 # frame2 = WideFrame(position=[25, 100], colorString="C_WHITE", parent=self.options_frame) self.create_tab_buttons() self.set_active_tab(0)
def draw_line_3d(x1, y1, z1, x2, y2, z2, w=1, color=None, parent=None, dynamic=False): """ Dibuja un segmento de linea, teniendo como origen de cordenadas la esquina superior izquierda de la pantalla """ line = LineSegs() line.setThickness(w) color = draw_get_color(color, color_format="rgba") line.setColor((1, 1, 1, 1)) line.moveTo(x1, y1, z1) line.drawTo(x2, y2, z2) node = line.create(dynamic=dynamic) print("draw_line_3d_1", node) base = app.get_show_base() if parent is None: parent = base.render np = NodePath(node) print("draw_line_3d_2", np) np.reparentTo(parent) np.setColorScale(color) np.setLightOff() np.setPythonTag('line', line) np.setPythonTag('defcolor', color) if dynamic: return np, line else: return np
def start_analysis(): print("----------------------------------------------------") print("start_analysis()") # Accede a la interfaz de kivy para obtener la información de panda3d panda3d = app.get_show_base() # Obtenemos el registro del modelo model_reg = app.model_reg areas = [] inercias = [] node_list = [] # Recorremos la lista de barras e imprimimos en consola las posiciones de inicio y fin de cada barra print("model_reg", model_reg) Barras = [] for bar in model_reg.get_bars(): #print("Barra {}".format(i)) print(bar) start = bar.start.position[0], bar.start.position[1] end = bar.end.position[0], bar.end.position[1] if bar.start not in node_list: node_list.append(bar.start) if bar.end not in node_list: node_list.append(bar.end) elastic_modulus = bar.material.elastic_modulus inertia_x = bar.section.inertia_x() area = bar.section.area() inercias.append(inertia_x) areas.append(area) Barras.append(calculo.Viga(elastic_modulus, inertia_x, area, start, end)) b = len(Barras) puntos = np.ones((b * 2, 2)) m = 0 for i in range(0, b): puntos[m, 0] = Barras[i].a[0] puntos[m, 1] = Barras[i].a[1] puntos[m + 1, 0] = Barras[i].b[0] puntos[m + 1, 1] = Barras[i].b[1] m = m + 2 # Lista "PUNTOS" es un valor cpor cada punto y el numero de adentro define su posibilidad de desplazamientos PUNTOS = [] point: Node for point in node_list: restrictions = point.get_restrictions2d() new_point = calculo.Puntos(0) new_point.P = list(map(lambda x: not x, restrictions)) PUNTOS.append(new_point) Rest = calculo.resticciones(PUNTOS) Con = np.zeros((b * 2, 1)) Con[0] = 0 Con[1] = 1 for i in range(2, b * 2): for n in range(0, i): if puntos[i, 0] == puntos[n, 0] and puntos[i, 1] == puntos[n, 1]: Con[i] = Con[n] if Con[i] == 0: Con[i] = max(Con) + 1 print("Con=", Con) # se Crea una matriz que contenga en forma ordenada el orden de puntos y las barras que llegan a los mismos # es deci la barra esta representada por renglones. el renglon uno representa a la barra uno # la barra uno va del punto que se encuentra en la primera columna al punto de la segunda columna matrizconectividad = np.ones((b, 2)) d = 0 for i in range(0, b): matrizconectividad[i, 0] = Con[d] matrizconectividad[i, 1] = Con[d + 1] d = d + 2 print("Vector de puntos=", matrizconectividad) MC = calculo.Matrizconectividad(matrizconectividad) print("matriz conectividad=", MC) # Matriz de conectividad de baras (fila 1=barra 1, pos 1: Punto a, pos 2: Punto B) MG = calculo.MatrizGlobalEnsambalda(Barras, matrizconectividad)
def regen(): print("regen") # Accede a la interfaz de kivy para obtener la información de panda3d panda3d = app.get_show_base() # Obtenemos el registro del modelo model_register = app.model_reg print(model_register) print(model_register.get("Node", dict()).items()) print("-----t----") # Recorre todos los nodos del modelo y coloca una esfera en el punto correspondiente entities_dict = model_register.get("Node", dict()) for entity_id in entities_dict: node = entities_dict[entity_id] # Si no hay una geometría asignada, la carga y la asgina a la entidad ux, uz, ry = node.get_restrictions2d() if node.geom is None: node.geom = [None] if ry is False: if "node_box" in str(node.geom[0]): node.geom[0].removeNode() node.geom[0] = None if node.geom[0] is None: node.geom[0] = panda3d.loader.loadModel("data/geom/node") else: if "node_box" not in str(node.geom[0]): node.geom[0].removeNode() node.geom[0] = None if node.geom[0] is None: node.geom[0] = panda3d.loader.loadModel("data/geom/node_box") geom1 = node.geom[0] geom1.setTag('entity_type', type(node).__name__) geom1.setTag('entity_id', node.entity_id) x, y, z = node.position geom1.setPos(x, y, z) geom1.reparentTo(panda3d.render) geom2 = None if ux + uz == 0 and len(node.geom) is 2: geom2 = node.geom.pop() geom2.removeNode() geom2 = None if ux + uz == 1: if len(node.geom) is 1: geom2 = panda3d.loader.loadModel("data/geom/support_roller_x") node.geom.append(geom2) else: geom2 = node.geom[1] if "support_roller_x" not in str(geom2): geom2.removeNode() node.geom[1] = panda3d.loader.loadModel( "data/geom/support_roller_x") geom2 = node.geom[1] if uz is True: geom1.setR(0) else: geom1.setR(90) if ux is True and uz is True: geom1.setR(0) if len(node.geom) is 1: geom2 = panda3d.loader.loadModel("data/geom/support_pinned_x") node.geom.append(geom2) else: geom2 = node.geom[1] if "support_pinned_x" not in str(geom2): geom2.removeNode() node.geom[1] = panda3d.loader.loadModel( "data/geom/support_pinned_x") geom2 = node.geom[1] if geom2 is not None: geom2.setTag('entity_type', type(node).__name__) geom2.setTag('entity_id', node.entity_id) geom2.reparentTo(geom1) geom2.setPos(0, 0, -0.2) geom2.setScale(0.20, 0.20, 0.20) entities_dict = model_register.get("Bar", dict()) for entity_id in entities_dict: bar = entities_dict[entity_id] # Si no hay una geometría asignada, la carga y la asgina a la entidad if bar.geom is None: bar.geom = [] bar.geom.append(panda3d.loader.loadModel("data/geom/beam")) else: geom = bar.geom[0] if "data/geom/beam" not in str(geom): geom.removeNode() bar.geom[0] = panda3d.loader.loadModel("data/geom/beam") geom = bar.geom[0] geom.setTag('entity_type', type(bar).__name__) geom.setTag('entity_id', bar.entity_id) # Ubica un cubo de 1x1x1 [m] en la posición inicial de la barra x0, y0, z0 = bar.start.position x1, y1, z1 = bar.end.position geom.setPos(x0, y0, z0) # Escalamos el cubo de forma que adquiera el largo de la barra, y las dimensiones de la sección b, h = bar.section.size x = x1 - x0 y = y1 - y0 z = z1 - z0 vector = [x, y, z] norm = np.linalg.norm(vector) geom.setScale(b, norm, h) geom.lookAt(bar.end.geom[0]) geom.reparentTo(panda3d.render) if wireframe is True: geom.hide() geom.setScale(0.1, norm, 0.1) if len(bar.geom) is 1: line = draw.draw_line_3d(x0, y0, z0, x1, y1, z1, 3, "C_BLUE") line.setDepthOffset(1) bar.geom.append(line) else: line = bar.geom[1] if line is not None: line.removeNode() line = draw.draw_line_3d(x0, y0, z0, x1, y1, z1, 3, "C_BLUE") line.setDepthOffset(1) bar.geom[1] = line print("!!!!!!!!!!!!!!!!!!!!!!line") print(line) #line.setLight(panda3d.plight_node) else: if len(bar.geom) > 1: line = bar.geom[1] if line is not None: line.removeNode() bar.geom[1] = None
def set_window_icon(file: str): winprops = WindowProperties() winprops.setIconFilename(file) base = app.get_show_base() base.win.requestProperties(winprops)
def bar_task(task): # Establece coredata como variable global global coredata # Accede a la instancia base de la aplicación panda3d = app.get_show_base() watcher = panda3d.mouseWatcherNode box_input = app.console_input if coredata["start"] is not None and coredata["end"] is not None: # Una vez que se tiene un inicio y un fin creamos los nodos y la barra en el modelo x0, y0, z0 = coredata["start"] x1, y1, z1 = coredata["end"] if coredata["last_node"] is None: start_node = Node(x0, y0, z0) else: start_node = coredata["last_node"] if coredata["end_node"] is None: end_node = Node(x1, y1, z1) else: end_node = coredata["end_node"] section = Section(0.2, 0.3) Bar(start_node, end_node, section) coredata["last_node"] = end_node # Se crea una nueva linea para dibujar coredata["start"] = coredata["end"] coredata["line"].setVertex(0, x1, y1, z1) coredata["end"] = None #execute("regen") if app.mouse_on_workspace: if watcher.isButtonDown("mouse1"): if coredata["start"] is None and not coredata["press"]: # Almacena el valor de inicio del segmento de linea selection = app.main_ui.status_bar.entity_info if isinstance(selection, Node): coredata["start"] = selection.position coredata["last_node"] = selection else: coredata["start"] = app.work_plane_mouse coredata["press"] = True print("start") #print(coredata) create_line_seg(panda3d) elif coredata["end"] is None and not coredata["press"]: # Almacena el valor final del segmento de linea selection = app.main_ui.status_bar.entity_info if isinstance(selection, Node) and selection is not coredata["last_node"]: coredata["end"] = selection.position coredata["end_node"] = selection else: coredata["end"] = app.work_plane_mouse #coredata["end"] = app.work_plane_mouse coredata["press"] = True print("end") #print(coredata) else: if coredata["press"]: # Resetea una variable que permite detectar el momento en que se empieza a presionar el mouse coredata["press"] = False if coredata["start"] is not None and coredata["line"] is not None: # Actualiza la posición final de la línea a la ubicación del cursor, dejando fijo el origen line = coredata["line"] x0, y0, z0 = coredata["start"] x1, y1, z1 = app.work_plane_mouse bar_vect = np.array([x1 - x0, y1 - y0, z1 - z0]) bar_len = np.linalg.norm(bar_vect) if box_input["focus"] is True: print("focused") input_len = box_input.get() if input_len is not "": try: input_len = float(input_len) except Exception as ex: input_len = 0 else: input_len = 0 if input_len is None: input_len = 0 if bar_len is 0: bar_len = 1 bar_vect = input_len * (bar_vect / bar_len) x1, y1, z1 = coredata["start"] + bar_vect else: # Mostrar la longitud de la barra en pantalla box_input.enterText("{}".format(round(bar_len, 2))) line.setVertex(1, x1, y1, z1) if watcher.has_mouse() and (watcher.isButtonDown("escape") or watcher.isButtonDown("mouse3")): # Detiene la creación de la linea y resetea las variables box_input.enterText("") coredata["start"] = None coredata["end"] = None coredata["press"] = False if coredata["line_node"] is not None: print(coredata["line_node"]) coredata["line_node"].removeNode() man = TaskManager() man.remove("create_bar") del man return task.cont