package com.cgvsu; import com.cgvsu.math.Matrix4f; import com.cgvsu.math.Vector3f;…
- User
package com.cgvsu;
import com.cgvsu.math.Matrix4f; import com.cgvsu.math.Vector3f; import com.cgvsu.model.Model; import com.cgvsu.objreader.ObjReader; import com.cgvsu.render_engine.Camera; import com.cgvsu.render_engine.GraphicConveyor; import com.cgvsu.render_engine.RenderEngine; import com.cgvsu.render_engine.TransformationParameters; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.image.PixelBuffer; import javafx.scene.image.PixelFormat; import javafx.scene.image.WritableImage; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.util.Duration;
import java.io.File; import java.io.IOException; import java.nio.IntBuffer; import java.nio.file.Files; import java.nio.file.Path;
public class GuiController {
final private float TRANSLATION = 0.5F; @FXML AnchorPane anchorPane; @FXML private ImageView imageView; @FXML private VBox modelsManager; @FXML private TextField textFieldScaleX; @FXML private TextField textFieldScaleY; @FXML private TextField textFieldScaleZ; @FXML private TextField textFieldRotationX; @FXML private TextField textFieldRotationY; @FXML private TextField textFieldRotationZ; @FXML private TextField textFieldTranslationX; @FXML private TextField textFieldTranslationY; @FXML private TextField textFieldTranslationZ; @FXML private VBox camerasManager; @FXML private TextField textFieldCameraPositionX; @FXML private TextField textFieldCameraPositionY; @FXML private TextField textFieldCameraPositionZ; @FXML private TextField textFieldCameraPointOfDirectionX; @FXML private TextField textFieldCameraPointOfDirectionY; @FXML private TextField textFieldCameraPointOfDirectionZ; @FXML private VBox lightingModelsManager; @FXML private CheckBox checkBoxDrawPolygonalGrid; @FXML private CheckBox checkBoxUseTexture; @FXML private CheckBox checkBoxUseLighting; @FXML private TextField textFieldLightingModelDirectionX; @FXML private TextField textFieldLightingModelDirectionY; @FXML private TextField textFieldLightingModelDirectionZ; private Model mesh = null; private int counterModels = 0; private int counterCameras = 0; private int counterLightingModels = 0; private int width; private int height; private Camera camera = new Camera( new Vector3f(0, 0, 100), new Vector3f(0, 0, 0), 1.0F, 1, 0.01F, 100); private Timeline timeline; private PixelFormat<IntBuffer> pixelFormat = PixelFormat.getIntArgbPreInstance(); private PixelBuffer<IntBuffer> pixelBuffer; private WritableImage writableImage; private IntBuffer pixelBufferData; @FXML private void initialize() { anchorPane.widthProperty().addListener((obs, oldVal, newVal) -> { width = newVal.intValue(); setupPixelBuffer(); }); anchorPane.heightProperty().addListener((obs, oldVal, newVal) -> { height = newVal.intValue(); setupPixelBuffer(); }); setupPixelBuffer(); timeline = new Timeline(); timeline.setCycleCount(Animation.INDEFINITE); KeyFrame frame = new KeyFrame(Duration.millis(15), event -> { renderFrame(); }); timeline.getKeyFrames().add(frame); timeline.play(); } private void setupPixelBuffer() { if (width <= 0 || height <= 0) return; pixelBufferData = IntBuffer.allocate(width * height); pixelBuffer = new PixelBuffer<>(width, height, pixelBufferData, pixelFormat); writableImage = new WritableImage(pixelBuffer); imageView.setImage(writableImage); } private void renderFrame() { if (mesh == null || pixelBufferData == null) return; pixelBufferData.clear(); for (int i = 0; i < width * height; i++) { pixelBufferData.put(0xFF000000); // ARGB: непрозрачный черный } pixelBufferData.rewind(); RenderEngine renderEngine = new RenderEngine(true, width,height); renderEngine.render(camera, mesh); writableImage.getPixelWriter().setPixels(0, 0, width, height, pixelFormat, pixelBufferData.array(), 0, width); } @FXML private void loadModelFromFile() { FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Model (*.obj)", "*.obj")); fileChooser.setTitle("Load Model"); File initialDirectory = new File("3DModels"); if (initialDirectory.exists()) { fileChooser.setInitialDirectory(initialDirectory); } File file = fileChooser.showOpenDialog((Stage) imageView.getScene().getWindow()); if (file == null) { return; } Path fileName = Path.of(file.getAbsolutePath()); try { String fileContent = Files.readString(fileName); mesh = ObjReader.read(fileContent); mesh.triangulate(); mesh.loadTexture("3DModels\\CaracalCube\\caracal_texture.png"); // Обработка ошибок (например, показать alert) } catch (IOException exception) { showErrorAlert("Ошибка загрузки модели", "Не удалось загрузить модель.", exception.getMessage()); } } @FXML private void saveModelFromFile() { // objWriter } @FXML public void handleCameraForward(ActionEvent actionEvent) { Vector3f currentPosition = camera.getPosition(); Vector3f newPosition = currentPosition.add(new Vector3f(0, 0, -TRANSLATION)); camera.setPosition(newPosition); } @FXML public void handleCameraBackward(ActionEvent actionEvent) { Vector3f currentPosition = camera.getPosition(); Vector3f newPosition = currentPosition.add(new Vector3f(0, 0, TRANSLATION)); camera.setPosition(newPosition); } @FXML public void handleCameraLeft(ActionEvent actionEvent) { Vector3f currentPosition = camera.getPosition(); Vector3f newPosition = currentPosition.add(new Vector3f(TRANSLATION, 0, 0)); camera.setPosition(newPosition); } @FXML public void handleCameraRight(ActionEvent actionEvent) { Vector3f currentPosition = camera.getPosition(); Vector3f newPosition = currentPosition.add(new Vector3f(-TRANSLATION, 0, 0)); camera.setPosition(newPosition); } @FXML public void handleCameraUp(ActionEvent actionEvent) { Vector3f currentPosition = camera.getPosition(); Vector3f newPosition = currentPosition.add(new Vector3f(0, TRANSLATION, 0)); camera.setPosition(newPosition); } @FXML public void handleCameraDown(ActionEvent actionEvent) { Vector3f currentPosition = camera.getPosition(); Vector3f newPosition = currentPosition.add(new Vector3f(0, -TRANSLATION, 0)); camera.setPosition(newPosition); } private TransformationParameters parseParameters() throws NumberFormatException { TransformationParameters params = new TransformationParameters(); params.setAlpha(Double.parseDouble(textFieldRotationX.getText())); params.setBeta(Double.parseDouble(textFieldRotationY.getText())); params.setGamma(Double.parseDouble(textFieldRotationZ.getText())); params.setTranslationX(Double.parseDouble(textFieldTranslationX.getText())); params.setTranslationY(Double.parseDouble(textFieldTranslationY.getText())); params.setTranslationZ(Double.parseDouble(textFieldTranslationZ.getText())); params.setScaleX(Double.parseDouble(textFieldScaleX.getText())); params.setScaleY(Double.parseDouble(textFieldScaleY.getText())); params.setScaleZ(Double.parseDouble(textFieldScaleZ.getText())); return params; } private void showErrorAlert(String title, String header, String content) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle(title); alert.setHeaderText(header); alert.setContentText(content); alert.showAndWait(); } @FXML private void recalculationOfNormals() { if (mesh != null) { TransformationParameters params; try { params = parseParameters(); } catch (NumberFormatException e) { showErrorAlert("Ошибка ввода", "Некорректные данные", "Пожалуйста, убедитесь, что все поля содержат числовые значения."); return; } Vector3f rota = new Vector3f((float) params.getAlpha(), (float) params.getBeta(), (float) params.getGamma()); Vector3f scale = new Vector3f((float) params.getScaleX(), (float) params.getScaleY(), (float) params.getScaleZ()); Vector3f trans = new Vector3f((float) params.getTranslationX(), (float) params.getTranslationY(), (float) params.getTranslationZ()); Matrix4f MAT = GraphicConveyor.scaleRotateTranslate(rota, scale, trans); mesh.getVertices().replaceAll(vector3f -> GraphicConveyor.multiplyMatrix4ByVector3(MAT, vector3f)); mesh.calculateNormals(); } } @FXML private void addNewCamera() { // для кнопки } @FXML private void addNewLightingModel() { // для кнопки } private void addModelControlButtons() { counterModels++; Button modelButton = new Button("Model " + counterModels); // здесь же наверное действие выбора активной модели (Это вроде мой блок) Button addTextureButton = new Button("Add texture"); // здесь связать кнопку с методом для добавления текстуры Button removeTextureButton = new Button("Remove texture"); // здесь связать кнопку с методом для добавления текстуры Button deleteModelButton = new Button("Delete"); // здесь связать удаление модели с кнопкой (и это вроде мой блок) HBox model = new HBox(5, modelButton, addTextureButton, removeTextureButton, deleteModelButton); modelsManager.getChildren().add(model); } private void addCameraControlButtons() { counterCameras++; Button cameraButton = new Button("Camera " + counterCameras); // здесь возможность выбирать активную камеру, чтобы для нее вводить в поле настройки Button deleteCamera = new Button("Delete"); // кнопку привязать к удалению HBox camera = new HBox(5, cameraButton, deleteCamera); camerasManager.getChildren().add(camera); } private void addLightModelControlButtons() { counterLightingModels++; Button lightModelButton = new Button("Light model " + counterLightingModels); // аналогично камере Button deleteLightButton = new Button("Delete"); // кнопку к удалению HBox lightModel = new HBox(lightModelButton, deleteLightButton); lightingModelsManager.getChildren().add(lightModel); } @FXML public void onClickCanvas() { imageView.requestFocus(); } @FXML private void returnToTheStartingPosition() { } @FXML private void moveToTheModel() { } - Assistant