Skip to content

Commit

Permalink
refactor: apply formatter (#141)
Browse files Browse the repository at this point in the history
* refactor: apply formatter

* feat: add action

* fix: change python version

* fix: fix ruff version
  • Loading branch information
lvjonok authored Mar 18, 2024
1 parent cd1013c commit a26ca34
Show file tree
Hide file tree
Showing 24 changed files with 1,342 additions and 773 deletions.
20 changes: 20 additions & 0 deletions .github/workflows/ruff.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: CI

on: push

jobs:
ruff_check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install ruff==0.3.3
# Update output format to enable automatic inline annotations.
- name: Run Ruff
run: ruff format --diff .
8 changes: 8 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.3.3
hooks:
# Run the formatter.
- id: ruff-format
types_or: [python, pyi, jupyter]
39 changes: 26 additions & 13 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@
import os, sys

# check whether we are in pyinstaller bundle and on linux
if getattr(sys, 'frozen', False) and sys.platform.startswith('linux'):
if getattr(sys, "frozen", False) and sys.platform.startswith("linux"):
app_path = os.path.dirname(sys.executable)

prev_ld_path = os.environ.get('LD_LIBRARY_PATH', '')
prev_ld_path = os.environ.get("LD_LIBRARY_PATH", "")

# shared libraries are located at lib/
shared_libs = os.path.join(app_path, 'lib')
shared_libs = os.path.join(app_path, "lib")

# add shared libraries to LD_LIBRARY_PATH
os.environ['LD_LIBRARY_PATH'] = shared_libs + ':' + prev_ld_path
print("LD_LIBRARY_PATH:", os.environ['LD_LIBRARY_PATH'])
os.environ["LD_LIBRARY_PATH"] = shared_libs + ":" + prev_ld_path
print("LD_LIBRARY_PATH:", os.environ["LD_LIBRARY_PATH"])


import logging
Expand All @@ -22,15 +22,25 @@
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication
import pathlib
from src.settings import copy_project_files, load_settings, sett, create_temporary_project_files
from src.settings import (
copy_project_files,
load_settings,
sett,
create_temporary_project_files,
)
from src.window import MainWindow
from src.model import MainModel
from src.controller import MainController
from src.interface_style_sheet import getStyleSheet
from src.entry_window import EntryWindow
from src.gui_utils import read_plane

logging.basicConfig(filename='interface.log', filemode='a+', level=logging.INFO, format='%(asctime)s %(message)s')
logging.basicConfig(
filename="interface.log",
filemode="a+",
level=logging.INFO,
format="%(asctime)s %(message)s",
)


def excepthook(exc_type, exc_value, exc_tb):
Expand All @@ -40,6 +50,7 @@ def excepthook(exc_type, exc_value, exc_tb):
logging.error(tb)
QtWidgets.QApplication.quit()


if __name__ == "__main__":
load_settings()

Expand All @@ -57,7 +68,7 @@ def open_project(project_path: str):

window = MainWindow()
window.close_signal.connect(entry_window.show)

model = MainModel()
cntrl = MainController(window, model)

Expand All @@ -66,7 +77,7 @@ def open_project(project_path: str):
if os.path.isfile(stlpath):
cntrl.load_stl(stlpath)

if hasattr(sett().slicing, 'splanes_file'):
if hasattr(sett().slicing, "splanes_file"):
# we have kinda old settings which point to separate file with planes
# load planes as it is, but remove this parameter and save settings
# TODO: we can remove this condition after one release
Expand All @@ -75,13 +86,15 @@ def open_project(project_path: str):
figpath = pathlib.Path(project_path, sett().slicing.splanes_file)
if os.path.isfile(figpath):
cntrl.load_planes_from_file(figpath)

del sett().slicing.splanes_file

cntrl.save_settings("vip")
else:
# load splanes from settings
cntrl.load_planes([read_plane(figure.description) for figure in sett().figures])
cntrl.load_planes(
[read_plane(figure.description) for figure in sett().figures]
)

window.showMaximized()
window.show()
Expand All @@ -96,7 +109,7 @@ def create_project(project_path: str):

window = MainWindow()
window.close_signal.connect(entry_window.show)

model = MainModel()
cntrl = MainController(window, model)
window.showMaximized()
Expand Down
15 changes: 0 additions & 15 deletions setup.py

This file was deleted.

93 changes: 66 additions & 27 deletions src/InteractorAroundActivePlane.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Module contains custom interactor for vtk
inspired by: https://fossies.org/linux/VTK/Examples/GUI/Python/CustomInteraction.py
"""

from typing import Tuple

import numpy as np
Expand All @@ -26,11 +27,13 @@ def RZ(rotRadian: float):
:param rotRadian: angle of rotations in radians
:return: numpy matrix of 3 by 3 size
"""
return np.array([
[np.cos(rotRadian), -np.sin(rotRadian), 0],
[np.sin(rotRadian), np.cos(rotRadian), 0],
[0, 0, 1]
])
return np.array(
[
[np.cos(rotRadian), -np.sin(rotRadian), 0],
[np.sin(rotRadian), np.cos(rotRadian), 0],
[0, 0, 1],
]
)


def Raxis(axis: Tuple[float, float, float], a: float, origin=np.array([0, 0, 0])):
Expand All @@ -45,15 +48,29 @@ def Raxis(axis: Tuple[float, float, float], a: float, origin=np.array([0, 0, 0])
oneminuscos = 1 - np.cos(a)
x, y, z = axis

return np.array([
[np.cos(a) + (x ** 2) * oneminuscos, x * y * oneminuscos - z * np.sin(a), x * z * oneminuscos + y * np.sin(a),
origin[0]],
[y * x * oneminuscos + z * np.sin(a), np.cos(a) + (y ** 2) * oneminuscos, y * z * oneminuscos - x * np.sin(a),
origin[1]],
[z * x * oneminuscos - y * np.sin(a), z * y * oneminuscos + x * np.sin(a), np.cos(a) + (z ** 2) * oneminuscos,
origin[2]],
[0, 0, 0, 1]
])
return np.array(
[
[
np.cos(a) + (x**2) * oneminuscos,
x * y * oneminuscos - z * np.sin(a),
x * z * oneminuscos + y * np.sin(a),
origin[0],
],
[
y * x * oneminuscos + z * np.sin(a),
np.cos(a) + (y**2) * oneminuscos,
y * z * oneminuscos - x * np.sin(a),
origin[1],
],
[
z * x * oneminuscos - y * np.sin(a),
z * y * oneminuscos + x * np.sin(a),
np.cos(a) + (z**2) * oneminuscos,
origin[2],
],
[0, 0, 0, 1],
]
)


class InteractionAroundActivePlane:
Expand All @@ -77,11 +94,11 @@ def __init__(self, currentInteractor, render):

self.axes = []

# real ability
# actor.SetOrigin(1, 0, 1)
# actor.SetOrientation(0, 0, 90)
# real ability
# actor.SetOrigin(1, 0, 1)
# actor.SetOrientation(0, 0, 90)

def leftBtnPress(self, obj, event, view = None):
def leftBtnPress(self, obj, event, view=None):
"""
These events are bind: "LeftButtonPressEvent" "LeftButtonReleaseEvent"
"""
Expand All @@ -91,7 +108,9 @@ def leftBtnPress(self, obj, event, view = None):
picker = self.getPicker()
actor = picker.GetActor()

if (picker.GetCellId() >= 0) and (isinstance(actor, src.gui_utils.StlActor)):
if (picker.GetCellId() >= 0) and (
isinstance(actor, src.gui_utils.StlActor)
):
triangle_id = picker.GetCellId()
normal = actor.GetTriangleNormal(triangle_id)
actor.RotateByVector(-normal)
Expand Down Expand Up @@ -127,30 +146,48 @@ def mouseMove(self, obj, event, view):
# that means if we are close to critical points, we may allow to move in opposite direction

# apply rotation around Z-axis
self.pos = Raxis((0, 0, 1), np.deg2rad(-deltaOnYaw * angleSpeed), self.focalPoint).dot(np.array(self.pos))
self.pos = Raxis(
(0, 0, 1), np.deg2rad(-deltaOnYaw * angleSpeed), self.focalPoint
).dot(np.array(self.pos))

# float in range (-1, 1) where if abs == 1 means camera view is on the z-axis
# 1 - we are facing in opposite direction than z-axis
# -1 - we are facing along direction of z-axis
viewGoesAlongZ = np.dot(np.array([0, 0, 1]), unit(self.pos[:3]))
# normalize value
maxv = 2 # normalizing range for deltaOnPitchRoll
deltaOnPitchRoll = maxv if deltaOnPitchRoll > maxv else -maxv if deltaOnPitchRoll < -maxv else deltaOnPitchRoll
deltaOnPitchRoll = (
maxv
if deltaOnPitchRoll > maxv
else -maxv
if deltaOnPitchRoll < -maxv
else deltaOnPitchRoll
)

# do not allow camera go too along with z-axis
threshold = 0.95

if abs(viewGoesAlongZ) < threshold or (viewGoesAlongZ < threshold and deltaOnPitchRoll < 0) or (
viewGoesAlongZ > threshold and deltaOnPitchRoll > 0):
self.pos = Raxis((self.pos[1], -self.pos[0], 0), np.deg2rad(-deltaOnPitchRoll / self.distanceToFocal / 2),
self.focalPoint).dot(np.array(self.pos))
if (
abs(viewGoesAlongZ) < threshold
or (viewGoesAlongZ < threshold and deltaOnPitchRoll < 0)
or (viewGoesAlongZ > threshold and deltaOnPitchRoll > 0)
):
self.pos = Raxis(
(self.pos[1], -self.pos[0], 0),
np.deg2rad(-deltaOnPitchRoll / self.distanceToFocal / 2),
self.focalPoint,
).dot(np.array(self.pos))

if self.isMoving:
# in this type we will have to move only on 2 axis
# if we move mouse up-down we will move along projection of line connecting the camera with the origin
# if we move mouse left-right we will move along perpendicular line to the previous one, also in xy plane

projVector = unit(np.array([self.pos[0] - self.focalPoint[0], self.pos[1] - self.focalPoint[1]]))
projVector = unit(
np.array(
[self.pos[0] - self.focalPoint[0], self.pos[1] - self.focalPoint[1]]
)
)
perpVector = unit(np.array([projVector[1], -projVector[0]]))

deltaOnProjection: float = xCur - xLast
Expand Down Expand Up @@ -180,7 +217,9 @@ def mouseMove(self, obj, event, view):
picker = self.getPicker()
actor = picker.GetActor()

if (picker.GetCellId() >= 0) and (isinstance(actor, src.gui_utils.StlActor)):
if (picker.GetCellId() >= 0) and (
isinstance(actor, src.gui_utils.StlActor)
):
actor.ResetColorize()
poly_data = actor.GetMapper().GetInput()
triangle_id = picker.GetCellId()
Expand Down
Loading

0 comments on commit a26ca34

Please sign in to comment.