Добавил ручки, а где же ручки, а где ваши ручки...

This commit is contained in:
moxitech 2024-10-05 22:30:20 +07:00
parent f2e9c6f38f
commit 5eef7db6a0
2 changed files with 140 additions and 238 deletions

View File

@ -1,43 +1,43 @@
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import * as THREE from 'three'; import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { FontLoader } from 'three/examples/jsm/loaders/FontLoader';
import { TextGeometry } from 'three/examples/jsm/geometries/TextGeometry';
import Drone from './model/Drone'; import Drone from './model/Drone';
import HeightPoint from './model/HeightPoint'; import HeightPoint from './model/HeightPoint';
import {RandomHeightPoint} from './helpers/generateRandomHeightPoints' import { RandomHeightPoint } from './helpers/generateRandomHeightPoints';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
// class HeightPoint {
// constructor(x, y, height) {
// this.x = x;
// this.y = y;
// this.height = height;
// }
// }
const Dashboard = () => { const Dashboard = () => {
const mountRef = useRef(null); // Указатель монтирования const mountRef = useRef(null);
const sceneRef = useRef(null); // Указатель на сцену const sceneRef = useRef(null);
const [heightData, setHeightData] = useState(RandomHeightPoint()); // Высоты const [state, setState] = useState({
const [formData, setFormData] = useState({ x: '', y: '', height: '' }); // Форма для ввода данных карты heightData: RandomHeightPoint(),
const [mouseState, setMouseState] = useState({ x: 0, y: 0, z: 0 }); // Форма для ввода данных карты drones: [],
selectedDrone: null,
baseStation: [],
selectedBaseStation: null,
formData: { x: '', y: '', height: '' },
mapSettings: { maxHeight: 20, coordX: 0, coordY: 0 },
contextMenu: { visible: false, x: 0, y: 0 },
mouseState: { x: 0, y: 0, z: 0 },
});
const mouse = new THREE.Vector2(); const mouse = new THREE.Vector2();
const [drones, setDrones] = useState([]) // Все дроны
const [selectedDrone, setSelectedDrone] = useState(null); // Состояние для выбранного дрона
const [baseStation, setBaseStation] = useState([]) // Все дроны
const [selectedBaseStation, setSelectedBaseStation] = useState(null); // Состояние для выбранного дрона
const [mapSettings, setMapSettings] = useState({
maxHeight: 20,
coordX: 0,
coordY: 0,
}); // Настройки карты
const [contextMenu, setContextMenu] = useState({ visible: false, x: 0, y: 0 }); // контекстное меню сцены
useEffect(() => { useEffect(() => {
if (!mountRef.current) return; if (!mountRef.current) return;
let width = mountRef.current.clientWidth; let width = mountRef.current.clientWidth;
let height = mountRef.current.clientHeight; let height = mountRef.current.clientHeight;
// Создаем объект сцены
// Создание сцены и камеры
const scene = new THREE.Scene(); const scene = new THREE.Scene();
// Сохраняем ссылку на сцену
sceneRef.current = scene; sceneRef.current = scene;
// Создаем камеру
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000); const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.position.set(0, 20, 30); camera.position.set(0, 20, 30);
@ -45,21 +45,21 @@ const Dashboard = () => {
renderer.setSize(width, height); renderer.setSize(width, height);
mountRef.current.appendChild(renderer.domElement); mountRef.current.appendChild(renderer.domElement);
// Плоскость для высотной карты :: TODO :: W/H/Ws/Hs change // Плоскость для высотной карты
const geometry = new THREE.PlaneGeometry(20, 20, 4, 4); const geometry = new THREE.PlaneGeometry(20, 20, 4, 4);
const vertices = geometry.attributes.position.array; const vertices = geometry.attributes.position.array;
const colors = []; const colors = [];
const color = new THREE.Color(); const color = new THREE.Color();
const minHeight = Math.min(...heightData.map((point) => point.height)); const { heightData, mapSettings } = state;
const maxHeight = Math.max(mapSettings.maxHeight, ...heightData.map((point) => point.height)); const minHeight = Math.min(...heightData.map(point => point.height));
const maxHeight = Math.max(mapSettings.maxHeight, ...heightData.map(point => point.height));
// Задание высот и цветов вершин
for (let i = 0; i < vertices.length; i += 3) { for (let i = 0; i < vertices.length; i += 3) {
const x = Math.floor(i / 3) % 5; const x = Math.floor(i / 3) % 5;
const y = Math.floor(i / (3 * 5)); const y = Math.floor(i / (3 * 5));
const heightPoint = heightData.find(point => point.x === x && point.y === y);
const heightPoint = heightData.find((point) => point.x === x && point.y === y);
const heightValue = heightPoint ? heightPoint.height : 0; const heightValue = heightPoint ? heightPoint.height : 0;
vertices[i + 2] = heightValue; vertices[i + 2] = heightValue;
@ -68,7 +68,6 @@ const Dashboard = () => {
color.setHSL(0.7 * (1 - normalizedHeight), 1, 0.5); color.setHSL(0.7 * (1 - normalizedHeight), 1, 0.5);
colors.push(color.r, color.g, color.b); colors.push(color.r, color.g, color.b);
} }
geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3)); geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
const material = new THREE.MeshBasicMaterial({ const material = new THREE.MeshBasicMaterial({
@ -81,9 +80,6 @@ const Dashboard = () => {
mesh.rotation.x = -Math.PI / 2; mesh.rotation.x = -Math.PI / 2;
scene.add(mesh); scene.add(mesh);
const axesHelper = new THREE.AxesHelper(10);
scene.add(axesHelper);
const controls = new OrbitControls(camera, renderer.domElement); const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; controls.enableDamping = true;
@ -91,248 +87,139 @@ const Dashboard = () => {
light.position.set(0, 50, 50).normalize(); light.position.set(0, 50, 50).normalize();
scene.add(light); scene.add(light);
// Обработка кликов на сцене
const handleClick = (event) => {
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
console.log('Mouse coordinates:', mouse);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(drones.map(drone => drone.getObject()), true);
console.log('Intersections:', intersects)
console.log('Drones:', drones.map(drone => [drone.getObject(), drone.getObject().position, drone.name]))
if (intersects.length > 0) {
const selected = intersects[0].object;
console.log('Clicked on:', selected); // Лог для проверки объекта
const drone = drones.find(drone => drone.getObject().children[0] === selected);
if (drone) {
if (selectedDrone) {
selectedDrone.getObject().children[0].material.color.set(0xff0000);
}
drone.getObject().children[0].material.color.set(0xff1111);
setSelectedDrone(drone);
}
} else {
if (selectedDrone) {
selectedDrone.getObject().children[0].material.color.set(0xff0000);
setSelectedDrone(null);
}
}
};
renderer.domElement.addEventListener('click', handleClick);
renderer.domElement.addEventListener('mousemove', (event) => {
let x = event.x;
let y = event.y;
setMouseState({x: x, y: y, z: 0});
})
const animate = () => { const animate = () => {
requestAnimationFrame(animate); requestAnimationFrame(animate);
controls.update(); controls.update();
renderer.render(scene, camera); renderer.render(scene, camera);
}; };
animate(); animate();
// Добавление сохранённых дронов в сцену при рендере
drones.forEach(droneData => { // События мыши
// const drone = new Drone(); const handleClick = (event) => {
// drone.setPosition(droneData.x, droneData.y, droneData.z); const { drones, selectedDrone } = state;
scene.add(droneData.getObject()); //drone.getObject() mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(drones.map(drone => drone.getObject()), true);
if (intersects.length > 0) {
const selected = intersects[0].object;
const drone = drones.find(drone => drone.getObject().children[0] === selected);
if (drone) {
if (selectedDrone) selectedDrone.getObject().children[0].material.color.set(0xff0000);
drone.getObject().children[0].material.color.set(0xff1111);
setState(prevState => ({ ...prevState, selectedDrone: drone }));
}
} else if (selectedDrone) {
selectedDrone.getObject().children[0].material.color.set(0xff0000);
setState(prevState => ({ ...prevState, selectedDrone: null }));
}
};
renderer.domElement.addEventListener('click', handleClick);
renderer.domElement.addEventListener('mousemove', (event) => {
setState(prevState => ({
...prevState,
mouseState: { x: event.clientX, y: event.clientY, z: 0 }
}));
}); });
// Обработка нажатия ПКМ
renderer.domElement.addEventListener('contextmenu', (event) => {
event.preventDefault();
setContextMenu({
visible: true,
x: event.clientX,
y: event.clientY,
});
});
// const gui = new GUI();
// gui.add( effectController, 'focalLength', 1, 135, 0.01 ).onChange( matChanger );
return () => { return () => {
if (mountRef.current) { if (mountRef.current) {
mountRef.current.removeChild(renderer.domElement); mountRef.current.removeChild(renderer.domElement);
} }
}; };
}, [drones,heightData, mapSettings]); }, [state.drones, state.heightData, state.mapSettings]);
// Добавление дрона в сцену
const handleAddDrone = () => { const handleAddDrone = () => {
if (sceneRef.current) { const { drones } = state;
const current = Date.now(); const drone = new Drone(Date.now() / 1000);
const drone = new Drone(current/1000);
// Создаем новый материал для каждого дрона
const droneMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 }); const droneMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
drone.getObject().children[0].material = droneMaterial; drone.getObject().children[0].material = droneMaterial;
drone.setPosition(Math.random() * 20 - 10, 3, Math.random() * 20 - 10); drone.setPosition(Math.random() * 20 - 10, 3, Math.random() * 20 - 10);
setDrones((prevDrones) => [...prevDrones, drone]); setState(prevState => ({
console.log(drones.map(drone => drone.getObject().children[0])); ...prevState,
drones: [...prevState.drones, drone]
}));
sceneRef.current.add(drone.getObject()); sceneRef.current.add(drone.getObject());
}
}; };
//
const handleInputChange = (event) => { const handleInputChange = (event) => {
const { name, value } = event.target; const { name, value } = event.target;
setFormData({ setState(prevState => ({
...formData, ...prevState,
[name]: value, formData: { ...prevState.formData, [name]: value }
}); }));
}; };
// Добавление элемента карты высот (высоты)
const handleAddHeight = (event) => { const handleAddHeight = (event) => {
event.preventDefault(); event.preventDefault();
const { formData, heightData } = state;
const { x, y, height } = formData; const newPoint = new HeightPoint(parseInt(formData.x), parseInt(formData.y), parseFloat(formData.height));
setState(prevState => ({
const newPoint = new HeightPoint(parseInt(x), parseInt(y), parseFloat(height)); ...prevState,
heightData: [...prevState.heightData, newPoint],
setHeightData((prevData) => [...prevData, newPoint]); formData: { x: '', y: '', height: '' }
setFormData({ x: '', y: '', height: '' }); }));
}; };
// Изменение настроек
const handleSettingsChange = (event) => { const handleSettingsChange = (event) => {
const { name, value } = event.target; const { name, value } = event.target;
setMapSettings({ setState(prevState => ({
...mapSettings, ...prevState,
[name]: value, mapSettings: { ...prevState.mapSettings, [name]: value }
}); }));
}; };
// Открытие контекстного меню
const handleContextMenuClick = (action) => { const handleContextMenuClick = (action) => {
if (action === 'add') { if (action === 'add') handleAddDrone();
handleAddDrone(); setState(prevState => ({
console.log('Добавить объект'); ...prevState,
} else if (action === 'save') { contextMenu: { ...prevState.contextMenu, visible: false }
console.log('Сохранить промежуточный результат'); }));
}
setContextMenu({ ...contextMenu, visible: false });
}; };
return ( return (
<div style={{ flex: 1 }}> <div style={{ flex: 1 }}>
<h1>Drone Network Simulator - окно разработки</h1> <h1>Drone Network Simulator</h1>
<nav class="navbar" role="navigation" aria-label="main navigation">
<div id="navbarBasicExample" class="navbar-menu">
<div class="navbar-start">
<a class="navbar-item">Объекты</a>
<a class="navbar-item">Документация</a>
<a class="navbar">
</a>
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link">Файл</a>
<div class="navbar-dropdown">
<a class="navbar-item">Сохранить локально</a>
<a class="navbar-item is-selected">Сохранить на сервере</a>
<a class="navbar-item">Настройки клиента</a>
<hr class="navbar-divider"/>
<a class="navbar-item">Debug mode</a>
</div>
</div>
</div>
<div class="navbar-end">
<div class="navbar-item">
<div class="tabs">
<ul>
<li class="is-active"><a>Моделирование</a></li>
<li><a>Симуляция</a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<div> <div>
<div> <p>x: {state.mouseState.x} y: {state.mouseState.y} z: {state.mouseState.z}</p>
<p>x: {mouseState.x} y: {mouseState.y} z: {mouseState.z}</p>
</div>
<div ref={mountRef} style={{ width: '100%', height: '500px', position: 'relative' }} /> <div ref={mountRef} style={{ width: '100%', height: '500px', position: 'relative' }} />
</div> </div>
{/* Контекстное меню */} {state.contextMenu.visible && (
{contextMenu.visible && ( <ul style={{ position: 'absolute', top: `${state.contextMenu.y}px`, left: `${state.contextMenu.x}px`, backgroundColor: 'white', padding: '10px', zIndex: 1000 }}>
<ul <li className="button" onClick={() => handleContextMenuClick('add')}>Добавить объект</li>
style={{ <li className="button" onClick={() => handleContextMenuClick('save')}>Сохранить промежуточный результат</li>
position: 'absolute', <li className="button" onClick={() => handleContextMenuClick('cancel')}>Отмена</li>
top: `${contextMenu.y}px`,
left: `${contextMenu.x}px`,
backgroundColor: 'white',
listStyle: 'none',
padding: '10px',
boxShadow: '0px 0px 5px rgba(0,0,0,0.3)',
zIndex: 1000,
}}
>
<div style={{ flex: 1, flexFlow: "column" }}>
<li className={"button"} onClick={() => handleContextMenuClick('add')}>Добавить объект</li>
<li className={"button"} onClick={() => handleContextMenuClick('save')}>Сохранить промежуточный результат</li>
<li className={"button"} onClick={() => handleContextMenuClick('cancel')}>Отмена</li>
</div>
</ul> </ul>
)} )}
<div className="columns"> <div className="columns">
{/* Форма для добавления новых высот */}
<div className='column'> <div className='column'>
<form onSubmit={handleAddHeight} style={{ marginTop: '20px' }}> <form onSubmit={handleAddHeight} style={{ marginTop: '20px' }}>
<div>
<label>Координата X:</label> <label>Координата X:</label>
<input <input className="input" type="number" name="x" value={state.formData.x} onChange={handleInputChange} />
className="input is-primary"
type="number"
name="x"
value={formData.x}
onChange={handleInputChange}
required
/>
</div>
<div>
<label>Координата Y:</label> <label>Координата Y:</label>
<input <input className="input" type="number" name="y" value={state.formData.y} onChange={handleInputChange} />
className="input is-primary"
type="number"
name="y"
value={formData.y}
onChange={handleInputChange}
required
/>
</div>
<div>
<label>Высота:</label> <label>Высота:</label>
<input <input className="input" type="number" name="height" value={state.formData.height} onChange={handleInputChange} />
className="input is-primary" <button type="submit" className="button">Добавить координаты</button>
type="number"
name="height"
value={formData.height}
onChange={handleInputChange}
required
/>
</div>
<button className='button' type="submit">Добавить точку высоты</button>
</form> </form>
</div> </div>
{/* Настройки карты */} <div className="column">
<div className='column'> <form style={{ marginTop: '20px' }}>
<div style={{ marginTop: '20px' }}> <label>Максимальная высота</label>
<h2>Настройки карты</h2> <input className="input" type="number" name="maxHeight" value={state.mapSettings.maxHeight} onChange={handleSettingsChange} />
<div> <label>Координата X</label>
<label>Максимальная высота:</label> <input className="input" type="number" name="coordX" value={state.mapSettings.coordX} onChange={handleSettingsChange} />
<input <label>Координата Y</label>
className="input" <input className="input" type="number" name="coordY" value={state.mapSettings.coordY} onChange={handleSettingsChange} />
type="number" <button type="submit" className="button">Применить</button>
name="maxHeight" </form>
value={mapSettings.maxHeight}
onChange={handleSettingsChange}
/>
</div>
</div>
</div> </div>
</div> </div>
<button className="button is-danger" onClick={handleAddDrone}>Добавить дрон</button>
</div> </div>
); );
}; };

View File

@ -27,10 +27,17 @@ func SpawnServer() error {
}) })
// GET http://localhost:8080/auth/:username/:password // GET http://localhost:8080/auth/:username/:password
app.Post("/auth/:username/:password", authorization.AuthUser) app.Post("/auth/:username/:password", authorization.AuthUser)
// GET http://localhost:8080/user/about
app.Get("/user/about", authorization.AuthUser)
// GET http://localhost:8080/user/templates
app.Get("/user/templates", authorization.AuthUser)
// GET http://localhost:8080/simulations/active // GET http://localhost:8080/simulations/active
app.Get("/simulations/active", GetActiveRooms) app.Get("/simulations/active", GetActiveRooms)
// GET http://localhost:8080/simulations/from/history // GET http://localhost:8080/simulations/from/history
app.Get("/simulations/from/history", authorization.AuthUser) // app.Get("/simulations/from/history", authorization.AuthUser)
// GET http://localhost:8080/get/server/state // GET http://localhost:8080/get/server/state
app.Get("/get/server/state", GetServerState) app.Get("/get/server/state", GetServerState)
@ -74,7 +81,15 @@ func CreateOrConnectSocket(c *websocket.Conn) {
room := Rooms[groupHash] room := Rooms[groupHash]
// Логика обработки подключения // Логика обработки подключения
fmt.Printf("[I] User connected with token or id: %s\n", userToken) fmt.Printf("[I] User connected with token or id: %s\n", userToken)
// Обрабатываем сообщение
data, err := json.Marshal(Rooms[groupHash])
if err != nil {
fmt.Printf("Error marshal json: %v\n", err)
}
err = c.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("%v", string(data))))
if err != nil {
fmt.Printf("Error writing message: %v\n", err)
}
for { for {
// Читаем сообщения от клиента // Читаем сообщения от клиента
messageType, msg, err := c.ReadMessage() messageType, msg, err := c.ReadMessage()