From 6947f811e17b2c7d5973de5e9fe71e9f7cade6d6 Mon Sep 17 00:00:00 2001 From: Dhruv Arora Date: Tue, 30 Jul 2024 19:00:21 -0700 Subject: [PATCH 0001/1127] Added basic UI --- fission/src/Synthesis.tsx | 2 + .../ui/modals/configuring/SettingsModal.tsx | 5 ++ .../src/ui/panels/QualitySettingsPanel.tsx | 50 +++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 fission/src/ui/panels/QualitySettingsPanel.tsx diff --git a/fission/src/Synthesis.tsx b/fission/src/Synthesis.tsx index e027a5e761..efe7ec11c8 100644 --- a/fission/src/Synthesis.tsx +++ b/fission/src/Synthesis.tsx @@ -66,6 +66,7 @@ import NewInputSchemeModal from "./ui/modals/configuring/theme-editor/NewInputSc import AssignNewSchemeModal from "./ui/modals/configuring/theme-editor/AssignNewSchemeModal.tsx" import AnalyticsConsent from "./ui/components/AnalyticsConsent.tsx" import PreferencesSystem from "./systems/preferences/PreferencesSystem.ts" +import QualitySettingsPanel from "./ui/panels/QualitySettingsPanel.tsx" const worker = new Lazy(() => new WPILibWSWorker()) @@ -253,6 +254,7 @@ const initialPanels: ReactElement[] = [ , , , + , ] export default Synthesis diff --git a/fission/src/ui/modals/configuring/SettingsModal.tsx b/fission/src/ui/modals/configuring/SettingsModal.tsx index 9e2ab7e340..5e3923b584 100644 --- a/fission/src/ui/modals/configuring/SettingsModal.tsx +++ b/fission/src/ui/modals/configuring/SettingsModal.tsx @@ -1,5 +1,6 @@ import React, { useState } from "react" import { useModalControlContext } from "@/ui/ModalContext" +import { usePanelControlContext } from "@/ui/PanelContext" import Modal, { ModalPropsImpl } from "@/components/Modal" import { FaGear } from "react-icons/fa6" import Label, { LabelSize } from "@/components/Label" @@ -15,6 +16,7 @@ import { Spacer } from "@/ui/components/StyledComponents" const SettingsModal: React.FC = ({ modalId }) => { const { openModal } = useModalControlContext() + const { openPanel } = usePanelControlContext() const [qualitySettings, setQualitySettings] = useState( PreferencesSystem.getGlobalPreference("QualitySettings") @@ -67,6 +69,9 @@ const SettingsModal: React.FC = ({ modalId }) => { >
+ +
+ ) : ( + <> + )} + + ) +} + +export default TouchControls From ccfc16f1b9fc9d3dfec12dbf798f9a2b5e1729b3 Mon Sep 17 00:00:00 2001 From: Dhruv Arora Date: Thu, 15 Aug 2024 14:53:34 -0700 Subject: [PATCH 0010/1127] Changes to fix everything before fixing build errors to run on ipad --- fission/src/systems/input/InputSystem.ts | 1 + fission/src/systems/scene/Joystick.ts | 61 +++++++ fission/src/systems/scene/SceneRenderer.ts | 16 ++ fission/src/ui/components/TouchControls.tsx | 178 ++++++-------------- 4 files changed, 134 insertions(+), 122 deletions(-) create mode 100644 fission/src/systems/scene/Joystick.ts diff --git a/fission/src/systems/input/InputSystem.ts b/fission/src/systems/input/InputSystem.ts index d56aadd692..f135169cea 100644 --- a/fission/src/systems/input/InputSystem.ts +++ b/fission/src/systems/input/InputSystem.ts @@ -189,6 +189,7 @@ class InputSystem extends WorldSystem { // Called when any key is first pressed private handleKeyDown(event: KeyboardEvent) { + console.log(event.code) InputSystem._keysPressed[event.code] = true } diff --git a/fission/src/systems/scene/Joystick.ts b/fission/src/systems/scene/Joystick.ts new file mode 100644 index 0000000000..7e752d6fb3 --- /dev/null +++ b/fission/src/systems/scene/Joystick.ts @@ -0,0 +1,61 @@ +class Joystick { + private baseElement: HTMLElement + private stickElement: HTMLElement + private maxDistance: number + private dragStart: { x: number; y: number } | null = null + private stickPosition: { x: number; y: number } = { x: 0, y: 0 } + private movementCallback: (x: number, y: number) => void + + constructor( + baseElement: HTMLElement, + stickElement: HTMLElement, + maxDistance: number, + movementCallback: (x: number, y: number) => void + ) { + this.baseElement = baseElement + this.stickElement = stickElement + this.maxDistance = maxDistance + this.movementCallback = movementCallback + + this.initialize() + } + + private initialize() { + this.stickElement.addEventListener("pointerdown", this.onPointerDown.bind(this)) + document.addEventListener("pointermove", this.onPointerMove.bind(this)) + document.addEventListener("pointerup", this.onPointerUp.bind(this)) + } + + private onPointerDown(event: PointerEvent) { + this.dragStart = { x: event.clientX, y: event.clientY } + } + + private onPointerMove(event: PointerEvent) { + if (!this.dragStart) return + + const dx = event.clientX - this.dragStart.x + const dy = event.clientY - this.dragStart.y + + const distance = Math.sqrt(dx * dx + dy * dy) + const angle = Math.atan2(dy, dx) + + const limitedDistance = Math.min(this.maxDistance, distance) + + this.stickPosition.x = limitedDistance * Math.cos(angle) + this.stickPosition.y = limitedDistance * Math.sin(angle) + + this.stickElement.style.transform = `translate(${this.stickPosition.x}px, ${this.stickPosition.y}px)` + + this.movementCallback(this.stickPosition.x / this.maxDistance, this.stickPosition.y / this.maxDistance) + } + + private onPointerUp() { + this.dragStart = null + this.stickPosition = { x: 0, y: 0 } + this.stickElement.style.transform = `translate(-50%, -50%)` + + this.movementCallback(0, 0) + } +} + +export default Joystick diff --git a/fission/src/systems/scene/SceneRenderer.ts b/fission/src/systems/scene/SceneRenderer.ts index 205aa4434d..727c43bfc2 100644 --- a/fission/src/systems/scene/SceneRenderer.ts +++ b/fission/src/systems/scene/SceneRenderer.ts @@ -15,6 +15,7 @@ import Jolt from "@barclah/jolt-physics" import { PixelSpaceCoord, SceneOverlayEvent, SceneOverlayEventKey } from "@/ui/components/SceneOverlayEvents" import PreferencesSystem from "../preferences/PreferencesSystem" import { CSM } from "three/examples/jsm/csm/CSM.js" +import Joystick from "./Joystick" const CLEAR_COLOR = 0x121212 const GROUND_COLOR = 0x4066c7 @@ -118,6 +119,21 @@ class SceneRenderer extends WorldSystem { // Orbit controls this._orbitControls = new OrbitControls(this._mainCamera, this._renderer.domElement) this._orbitControls.update() + + // Add a cube to the scene + const geometry1 = new THREE.BoxGeometry() + const material1 = new THREE.MeshBasicMaterial({ color: 0x00ff00 }) + const cube = new THREE.Mesh(geometry1, material1) + this._scene.add(cube) + + // Initialize the joystick + const joystickBase = document.getElementById("joystick-base-left")! + const joystickStick = document.getElementById("joystick-stick-left")! + const joystick = new Joystick(joystickBase, joystickStick, 50, (x, y) => { + // Use the joystick input to control the cube + cube.position.x += x * 0.1 + cube.position.y -= y * 0.1 + }) } public UpdateCanvasSize() { diff --git a/fission/src/ui/components/TouchControls.tsx b/fission/src/ui/components/TouchControls.tsx index 18481406ef..68d7f9f6c9 100644 --- a/fission/src/ui/components/TouchControls.tsx +++ b/fission/src/ui/components/TouchControls.tsx @@ -1,136 +1,70 @@ -import Button from "@/ui/components/Button" -import { useRef, useState } from "react" +import { useCallback, useRef, useState } from "react" +import Label from "./Label" function TouchControls() { const inputRef = useRef(null) - const showPlace = useState(false) - const showTouchControls = useState(false) + const [showPlaceButton, setShowPlaceButton] = useState(true) + const [showJoystick, setShowJoystick] = useState(true) - return ( - <> - - {showPlace ? ( - @@ -107,6 +110,13 @@ const MainHUD: React.FC = () => { openPanel("debug") }} /> + {touchCompatibility ? ( + new TouchControlsEvent(TouchControlsEventKeys.JOYSTICK)} + /> + ) : null} {userInfo ? ( (null) - const [showPlaceButton, setShowPlaceButton] = useState(true) - const [showJoystick, setShowJoystick] = useState(true) + const [isPlaceButtonVisible, setIsPlaceButtonVisible] = useState(false) + const [isJoystickVisible, setIsJoystickVisible] = useState( + PreferencesSystem.getGlobalPreference("TouchControls") + ) + + useEffect(() => { + const handlePlaceButtonEvent = (e: Event) => { + setIsPlaceButtonVisible((e as TouchControlsEvent).value!) + } + + const handleJoystickEvent = () => { + PreferencesSystem.setGlobalPreference("TouchControls", !isJoystickVisible) + PreferencesSystem.savePreferences() + setIsJoystickVisible(!isJoystickVisible) + } - const touch = matchMedia("(hover: none)").matches + TouchControlsEvent.Listen(TouchControlsEventKeys.PLACE_BUTTON, handlePlaceButtonEvent) + TouchControlsEvent.Listen(TouchControlsEventKeys.JOYSTICK, handleJoystickEvent) - console.log(touch) // true if the device has touch capabilities + return () => { + TouchControlsEvent.RemoveListener(TouchControlsEventKeys.PLACE_BUTTON, handlePlaceButtonEvent) + TouchControlsEvent.RemoveListener(TouchControlsEventKeys.JOYSTICK, handleJoystickEvent) + } + }, [isJoystickVisible, isPlaceButtonVisible]) /** simulates an enter key press and release within a 100 millisecond succession */ const PlaceMirabufAssembly = useCallback(() => { @@ -33,30 +52,33 @@ function TouchControls() { }, []) return ( - <> - +
+
-
+
- +
) } export default TouchControls + +export const enum TouchControlsEventKeys { + PLACE_BUTTON = "PlaceButtonEvent", + JOYSTICK = "JoystickEvent", +} + +export class TouchControlsEvent extends Event { + public value: boolean | undefined + + constructor(eventKey: TouchControlsEventKeys, value?: boolean) { + super(eventKey) + + if (value) this.value = value + + window.dispatchEvent(this) + } + + public static Listen(eventKey: TouchControlsEventKeys, func: (e: Event) => void) { + window.addEventListener(eventKey, func) + } + + public static RemoveListener(eventKey: TouchControlsEventKeys, func: (e: Event) => void) { + window.removeEventListener(eventKey, func) + } +} diff --git a/fission/src/ui/panels/mirabuf/ImportMirabufPanel.tsx b/fission/src/ui/panels/mirabuf/ImportMirabufPanel.tsx index aa3f37b2f8..be383973b2 100644 --- a/fission/src/ui/panels/mirabuf/ImportMirabufPanel.tsx +++ b/fission/src/ui/panels/mirabuf/ImportMirabufPanel.tsx @@ -74,7 +74,12 @@ function GetCacheInfo(miraType: MiraType): MirabufCacheInfo[] { return Object.values(MirabufCachingService.GetCacheMap(miraType)) } -function SpawnCachedMira(info: MirabufCacheInfo, type: MiraType, progressHandle?: ProgressHandle) { +function SpawnCachedMira( + info: MirabufCacheInfo, + type: MiraType, + openPanel: (panelId: string) => void, + progressHandle?: ProgressHandle +) { if (!progressHandle) { progressHandle = new ProgressHandle(info.name ?? info.cacheKey) } @@ -85,6 +90,7 @@ function SpawnCachedMira(info: MirabufCacheInfo, type: MiraType, progressHandle? CreateMirabuf(assembly).then(x => { if (x) { World.SceneRenderer.RegisterSceneObject(x) + if (x.miraType == MiraType.ROBOT) openPanel("choose-scheme") progressHandle.Done() } else { progressHandle.Fail() @@ -183,7 +189,7 @@ const ImportMirabufPanel: React.FC = ({ panelId }) => { // Select a mirabuf assembly from the cache. const selectCache = useCallback( (info: MirabufCacheInfo, type: MiraType) => { - SpawnCachedMira(info, type) + SpawnCachedMira(info, type, openPanel) showTooltip("controls", [ { control: "WASD", description: "Drive" }, @@ -193,7 +199,7 @@ const ImportMirabufPanel: React.FC = ({ panelId }) => { closePanel(panelId) - if (type == MiraType.ROBOT) openPanel("choose-scheme") + // if (type == MiraType.ROBOT) openPanel("choose-scheme") }, [showTooltip, closePanel, panelId, openPanel] ) @@ -207,7 +213,7 @@ const ImportMirabufPanel: React.FC = ({ panelId }) => { MirabufCachingService.CacheRemote(info.src, type) .then(cacheInfo => { if (cacheInfo) { - SpawnCachedMira(cacheInfo, type, status) + SpawnCachedMira(cacheInfo, type, openPanel, status) } else { status.Fail("Failed to cache") } @@ -229,7 +235,7 @@ const ImportMirabufPanel: React.FC = ({ panelId }) => { MirabufCachingService.CacheAPS(data, type) .then(cacheInfo => { if (cacheInfo) { - SpawnCachedMira(cacheInfo, type, status) + SpawnCachedMira(cacheInfo, type, openPanel, status) } else { status.Fail("Failed to cache") } diff --git a/fission/vite.config.ts b/fission/vite.config.ts index d1120aebe9..d528a9dc1d 100644 --- a/fission/vite.config.ts +++ b/fission/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vitest/config' import * as path from 'path' import react from '@vitejs/plugin-react-swc' +import basicSsl from '@vitejs/plugin-basic-ssl' import glsl from 'vite-plugin-glsl'; const basePath = '/fission/' @@ -8,22 +9,31 @@ const serverPort = 3000 const dockerServerPort = 80 const useLocal = false +const useSsl = true + +const plugins = [ + react(), glsl({ + include: [ // Glob pattern, or array of glob patterns to import + '**/*.glsl', '**/*.wgsl', + '**/*.vert', '**/*.frag', + '**/*.vs', '**/*.fs' + ], + exclude: undefined, // Glob pattern, or array of glob patterns to ignore + warnDuplicatedImports: true, // Warn if the same chunk was imported multiple times + defaultExtension: 'glsl', // Shader suffix when no extension is specified + compress: false, // Compress output shader code + watch: true, // Recompile shader on change + root: '/' // Directory for root imports + }) +] + +if (useSsl) { + plugins.push(basicSsl()) +} // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react(), /* viteSingleFile() */ glsl({ - include: [ // Glob pattern, or array of glob patterns to import - '**/*.glsl', '**/*.wgsl', - '**/*.vert', '**/*.frag', - '**/*.vs', '**/*.fs' - ], - exclude: undefined, // Glob pattern, or array of glob patterns to ignore - warnDuplicatedImports: true, // Warn if the same chunk was imported multiple times - defaultExtension: 'glsl', // Shader suffix when no extension is specified - compress: false, // Compress output shader code - watch: true, // Recompile shader on change - root: '/' // Directory for root imports - }) ], + plugins: plugins, resolve: { alias: [ { find: '@/components', replacement: path.resolve(__dirname, 'src', 'ui', 'components') }, From f0003856a70ce202f8624a1ca03f42ba33cd0c57 Mon Sep 17 00:00:00 2001 From: Dhruv Arora Date: Tue, 20 Aug 2024 13:07:04 -0700 Subject: [PATCH 0012/1127] Quick preference system merge conflict fix to allow joysticks to be functional --- fission/src/systems/preferences/PreferenceTypes.ts | 2 ++ fission/src/systems/scene/Joystick.ts | 3 --- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/fission/src/systems/preferences/PreferenceTypes.ts b/fission/src/systems/preferences/PreferenceTypes.ts index 4b79eaacbf..e8e98db54b 100644 --- a/fission/src/systems/preferences/PreferenceTypes.ts +++ b/fission/src/systems/preferences/PreferenceTypes.ts @@ -29,6 +29,8 @@ export const DefaultGlobalPreferences: { [key: string]: unknown } = { InputSchemes: [], RenderSceneTags: true, RenderScoreboard: true, + SubsystemGravity: false, + TouchControls: false, } export type QualitySetting = "Low" | "Medium" | "High" diff --git a/fission/src/systems/scene/Joystick.ts b/fission/src/systems/scene/Joystick.ts index 6b1b6be7fe..bf2a5a005e 100644 --- a/fission/src/systems/scene/Joystick.ts +++ b/fission/src/systems/scene/Joystick.ts @@ -67,9 +67,6 @@ class Joystick { this.stickPosition.y = y } - // this.stickPosition.x = 0 - // this.stickPosition.y = 0 - this.stickElement.style.transform = `translate(${this.stickPosition.x - this.maxDistance / 2}px, ${this.stickPosition.y - this.maxDistance / 2}px)` this.movementCallback(this.stickPosition.x / this.maxDistance, this.stickPosition.y / this.maxDistance) } From 0b437c9e1dfe92f4a922a4a00cafa7ebd449f00d Mon Sep 17 00:00:00 2001 From: Dhruv Arora Date: Tue, 20 Aug 2024 19:17:02 -0700 Subject: [PATCH 0013/1127] Working joysticks with assemblies --- fission/src/mirabuf/MirabufSceneObject.ts | 2 +- fission/src/systems/input/DefaultInputs.ts | 285 ++++++++++++++---- .../src/systems/input/InputSchemeManager.ts | 3 + fission/src/systems/input/InputSystem.ts | 37 ++- fission/src/systems/scene/Joystick.ts | 39 +-- fission/src/systems/scene/SceneRenderer.ts | 16 - fission/src/ui/components/TouchControls.tsx | 30 +- 7 files changed, 305 insertions(+), 107 deletions(-) diff --git a/fission/src/mirabuf/MirabufSceneObject.ts b/fission/src/mirabuf/MirabufSceneObject.ts index 0cbbb5a169..664dd3510b 100644 --- a/fission/src/mirabuf/MirabufSceneObject.ts +++ b/fission/src/mirabuf/MirabufSceneObject.ts @@ -187,7 +187,7 @@ class MirabufSceneObject extends SceneObject { * This block of code should only be executed if the transform gizmo exists. */ if (this._transformGizmos) { - if (InputSystem.isKeyPressed("Enter")) { + if (InputSystem.isKeyPressed("ConfirmAssemblyButton") || InputSystem.isKeyPressed("Enter")) { // confirming placement of the mirabuf object this.DisableTransformControls() return diff --git a/fission/src/systems/input/DefaultInputs.ts b/fission/src/systems/input/DefaultInputs.ts index e15fe82d44..eda7a81587 100644 --- a/fission/src/systems/input/DefaultInputs.ts +++ b/fission/src/systems/input/DefaultInputs.ts @@ -1,3 +1,4 @@ +import { TouchControlsJoystick } from "@/ui/components/TouchControls" import { InputScheme } from "./InputSchemeManager" import { AxisInput, ButtonInput, EmptyModifierState } from "./InputSystem" @@ -8,6 +9,7 @@ class DefaultInputs { descriptiveName: "WASD", customized: false, usesGamepad: false, + usesTouchControls: false, inputs: [ new AxisInput("arcadeDrive", "KeyW", "KeyS"), new AxisInput("arcadeTurn", "KeyD", "KeyA"), @@ -15,36 +17,96 @@ class DefaultInputs { new ButtonInput("intake", "KeyE"), new ButtonInput("eject", "KeyQ"), - new AxisInput("joint 1", "Digit1", "Digit1", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: false, - alt: false, - shift: true, - meta: false, - }), - new AxisInput("joint 2", "Digit2", "Digit2", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: false, - alt: false, - shift: true, - meta: false, - }), - new AxisInput("joint 3", "Digit3", "Digit3", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: false, - alt: false, - shift: true, - meta: false, - }), - new AxisInput("joint 4", "Digit4", "Digit4", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: false, - alt: false, - shift: true, - meta: false, - }), - new AxisInput("joint 5", "Digit5", "Digit5", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: false, - alt: false, - shift: true, - meta: false, - }), + new AxisInput( + "joint 1", + "Digit1", + "Digit1", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: false, + alt: false, + shift: true, + meta: false, + } + ), + new AxisInput( + "joint 2", + "Digit2", + "Digit2", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: false, + alt: false, + shift: true, + meta: false, + } + ), + new AxisInput( + "joint 3", + "Digit3", + "Digit3", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: false, + alt: false, + shift: true, + meta: false, + } + ), + new AxisInput( + "joint 4", + "Digit4", + "Digit4", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: false, + alt: false, + shift: true, + meta: false, + } + ), + new AxisInput( + "joint 5", + "Digit5", + "Digit5", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: false, + alt: false, + shift: true, + meta: false, + } + ), new AxisInput("joint 6"), new AxisInput("joint 7"), new AxisInput("joint 8"), @@ -60,6 +122,7 @@ class DefaultInputs { descriptiveName: "Arrow Keys", customized: false, usesGamepad: false, + usesTouchControls: false, inputs: [ new AxisInput("arcadeDrive", "ArrowUp", "ArrowDown"), new AxisInput("arcadeTurn", "ArrowRight", "ArrowLeft"), @@ -67,36 +130,96 @@ class DefaultInputs { new ButtonInput("intake", "Semicolon"), new ButtonInput("eject", "KeyL"), - new AxisInput("joint 1", "Slash", "Slash", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: true, - alt: false, - shift: false, - meta: false, - }), - new AxisInput("joint 2", "Period", "Period", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: true, - alt: false, - shift: false, - meta: false, - }), - new AxisInput("joint 3", "Comma", "Comma", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: true, - alt: false, - shift: false, - meta: false, - }), - new AxisInput("joint 4", "KeyM", "KeyM", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: true, - alt: false, - shift: false, - meta: false, - }), - new AxisInput("joint 5", "KeyN", "KeyN", -1, false, false, -1, -1, EmptyModifierState, { - ctrl: true, - alt: false, - shift: false, - meta: false, - }), + new AxisInput( + "joint 1", + "Slash", + "Slash", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: true, + alt: false, + shift: false, + meta: false, + } + ), + new AxisInput( + "joint 2", + "Period", + "Period", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: true, + alt: false, + shift: false, + meta: false, + } + ), + new AxisInput( + "joint 3", + "Comma", + "Comma", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: true, + alt: false, + shift: false, + meta: false, + } + ), + new AxisInput( + "joint 4", + "KeyM", + "KeyM", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: true, + alt: false, + shift: false, + meta: false, + } + ), + new AxisInput( + "joint 5", + "KeyN", + "KeyN", + -1, + false, + false, + -1, + -1, + TouchControlsJoystick.NONE, + EmptyModifierState, + { + ctrl: true, + alt: false, + shift: false, + meta: false, + } + ), new AxisInput("joint 6"), new AxisInput("joint 7"), new AxisInput("joint 8"), @@ -112,6 +235,7 @@ class DefaultInputs { descriptiveName: "Full Controller", customized: false, usesGamepad: true, + usesTouchControls: false, inputs: [ new AxisInput("arcadeDrive", "", "", 1, true), new AxisInput("arcadeTurn", "", "", 2, false), @@ -139,6 +263,7 @@ class DefaultInputs { descriptiveName: "Left Stick", customized: false, usesGamepad: true, + usesTouchControls: false, inputs: [ new AxisInput("arcadeDrive", "", "", 1, true), new AxisInput("arcadeTurn", "", "", 0, false), @@ -166,6 +291,7 @@ class DefaultInputs { descriptiveName: "Right Stick", customized: false, usesGamepad: true, + usesTouchControls: false, inputs: [ new AxisInput("arcadeDrive", "", "", 3, true), new AxisInput("arcadeTurn", "", "", 2, false), @@ -187,6 +313,43 @@ class DefaultInputs { } } + public static brandon = () => { + return { + schemeName: "Brandon", + descriptiveName: "Touch Controls", + customized: false, + usesGamepad: false, + usesTouchControls: true, + inputs: [ + new AxisInput( + "arcadeDrive", + "", + "", + undefined, + undefined, + undefined, + undefined, + undefined, + TouchControlsJoystick.LEFT + ), + new AxisInput( + "arcadeTurn", + "", + "", + undefined, + undefined, + undefined, + undefined, + undefined, + TouchControlsJoystick.RIGHT + ), + + new ButtonInput("intake", "Semicolon"), + new ButtonInput("eject", "KeyL"), + ], + } + } + public static get defaultInputCopies() { return [ DefaultInputs.ernie(), @@ -194,6 +357,7 @@ class DefaultInputs { DefaultInputs.jax(), DefaultInputs.hunter(), DefaultInputs.carmela(), + DefaultInputs.brandon(), ] } @@ -203,6 +367,7 @@ class DefaultInputs { descriptiveName: "", customized: true, usesGamepad: false, + usesTouchControls: false, inputs: [ new AxisInput("arcadeDrive"), new AxisInput("arcadeTurn"), diff --git a/fission/src/systems/input/InputSchemeManager.ts b/fission/src/systems/input/InputSchemeManager.ts index 23a5ede69d..3dcf20fd9b 100644 --- a/fission/src/systems/input/InputSchemeManager.ts +++ b/fission/src/systems/input/InputSchemeManager.ts @@ -8,6 +8,7 @@ export type InputScheme = { descriptiveName: string customized: boolean usesGamepad: boolean + usesTouchControls: boolean inputs: Input[] } @@ -58,6 +59,7 @@ class InputSchemeManager { rawAxis.useGamepadButtons, rawAxis.posGamepadButton, rawAxis.negGamepadButton, + rawAxis.touchControlAxis, rawAxis.posKeyModifiers, rawAxis.negKeyModifiers ) @@ -140,6 +142,7 @@ class InputSchemeManager { descriptiveName: scheme.descriptiveName, customized: scheme.customized, usesGamepad: scheme.usesGamepad, + usesTouchControls: scheme.usesTouchControls, inputs: copiedInputs, } } diff --git a/fission/src/systems/input/InputSystem.ts b/fission/src/systems/input/InputSystem.ts index f135169cea..ca6f9da698 100644 --- a/fission/src/systems/input/InputSystem.ts +++ b/fission/src/systems/input/InputSystem.ts @@ -1,3 +1,5 @@ +import { TouchControlsJoystick } from "@/ui/components/TouchControls" +import Joystick from "../scene/Joystick" import WorldSystem from "../WorldSystem" import { InputScheme } from "./InputSchemeManager" @@ -18,7 +20,7 @@ abstract class Input { } // Returns the current value of the input. Range depends on input type - abstract getValue(useGamepad: boolean): number + abstract getValue(useGamepad: boolean, useTouchControls: boolean): number // Creates a copy to avoid modifying the default inputs by reference abstract getCopy(): Input @@ -62,6 +64,7 @@ class AxisInput extends Input { public negKeyModifiers: ModifierState public gamepadAxisNumber: number + public touchControlAxis: TouchControlsJoystick public joystickInverted: boolean public useGamepadButtons: boolean public posGamepadButton: number @@ -76,6 +79,7 @@ class AxisInput extends Input { useGamepadButtons?: boolean, posGamepadButton?: number, negGamepadButton?: number, + touchControlAxis?: TouchControlsJoystick, posKeyModifiers?: ModifierState, negKeyModifiers?: ModifierState ) { @@ -87,6 +91,7 @@ class AxisInput extends Input { this.negKeyModifiers = negKeyModifiers ?? EmptyModifierState this.gamepadAxisNumber = gamepadAxisNumber ?? -1 + this.touchControlAxis = touchControlAxis ?? TouchControlsJoystick.NONE this.joystickInverted = joystickInverted ?? false this.useGamepadButtons = useGamepadButtons ?? false @@ -96,7 +101,7 @@ class AxisInput extends Input { // For keyboard: returns 1 if positive pressed, -1 if negative pressed, or 0 if none or both are pressed // For gamepad axis: returns a range between -1 and 1 with a deadband in the middle - getValue(useGamepad: boolean): number { + getValue(useGamepad: boolean, useTouchControls: boolean): number { // Gamepad joystick axis if (useGamepad) { if (!this.useGamepadButtons) @@ -109,6 +114,10 @@ class AxisInput extends Input { ) } + if (useTouchControls) { + return InputSystem.getTouchControlsAxis(this.touchControlAxis) * (this.joystickInverted ? -1 : 1) + } + // Keyboard button axis return ( (InputSystem.isKeyPressed(this.posKeyCode, this.posKeyModifiers) ? 1 : 0) - @@ -126,6 +135,7 @@ class AxisInput extends Input { this.useGamepadButtons, this.posGamepadButton, this.negGamepadButton, + this.touchControlAxis, this.posKeyModifiers, this.negKeyModifiers ) @@ -141,6 +151,9 @@ class InputSystem extends WorldSystem { private static _gpIndex: number | null public static gamepad: Gamepad | null + private static leftJoystick: Joystick + private static rightJoystick: Joystick + // Maps a brain index to a certain input scheme public static brainIndexSchemeMap: Map = new Map() @@ -159,6 +172,15 @@ class InputSystem extends WorldSystem { this.gamepadDisconnected = this.gamepadDisconnected.bind(this) window.addEventListener("gamepaddisconnected", this.gamepadDisconnected) + InputSystem.leftJoystick = new Joystick( + document.getElementById("joystick-base-left")!, + document.getElementById("joystick-stick-left")! + ) + InputSystem.rightJoystick = new Joystick( + document.getElementById("joystick-base-right")!, + document.getElementById("joystick-stick-right")! + ) + document.addEventListener("visibilitychange", () => { if (document.hidden) this.clearKeyData() }) @@ -238,7 +260,7 @@ class InputSystem extends WorldSystem { if (targetScheme == null || targetInput == null) return 0 - return targetInput.getValue(targetScheme.usesGamepad) + return targetInput.getValue(targetScheme.usesGamepad, targetScheme.usesTouchControls) } // Returns true if two modifier states are identical @@ -276,6 +298,15 @@ class InputSystem extends WorldSystem { return button.pressed } + + // Returns a number between -1 and 1 from the touch controls + public static getTouchControlsAxis(axisNumber: TouchControlsJoystick): number { + let value: number + if (axisNumber === TouchControlsJoystick.LEFT) value = -InputSystem.leftJoystick.y + else value = InputSystem.rightJoystick.x + + return value + } } export default InputSystem diff --git a/fission/src/systems/scene/Joystick.ts b/fission/src/systems/scene/Joystick.ts index bf2a5a005e..3dc6b059d4 100644 --- a/fission/src/systems/scene/Joystick.ts +++ b/fission/src/systems/scene/Joystick.ts @@ -1,22 +1,23 @@ +import { MAX_JOYSTICK_RADIUS } from "@/ui/components/TouchControls" + class Joystick { private baseElement: HTMLElement private stickElement: HTMLElement - private maxDistance: number private stickPosition: { x: number; y: number } = { x: 0, y: 0 } - private movementCallback: (x: number, y: number) => void private baseRect: DOMRect | null = null private activePointerId: number | null = null // Track the active pointer ID - constructor( - baseElement: HTMLElement, - stickElement: HTMLElement, - maxDistance: number, - movementCallback: (x: number, y: number) => void - ) { + public get x() { + return this.stickPosition.x / MAX_JOYSTICK_RADIUS + } + + public get y() { + return this.stickPosition.y / MAX_JOYSTICK_RADIUS + } + + constructor(baseElement: HTMLElement, stickElement: HTMLElement) { this.baseElement = baseElement this.stickElement = stickElement - this.maxDistance = maxDistance - this.movementCallback = movementCallback this.initialize() } @@ -38,12 +39,11 @@ class Joystick { this.updateStickPosition(event.clientX, event.clientY) } - private onPointerUp() { + private onPointerUp(event: PointerEvent) { + if (this.activePointerId !== event.pointerId) return this.stickPosition = { x: 0, y: 0 } this.stickElement.style.transform = `translate(-50%, -50%)` this.baseRect = null - - this.movementCallback(0, 0) } private updateStickPosition(clientX: number, clientY: number) { @@ -58,17 +58,20 @@ class Joystick { const distance = Math.sqrt(x * x + y * y) // If the distance exceeds maxDistance, constrain it - if (distance > this.maxDistance) { + if (distance > MAX_JOYSTICK_RADIUS) { const angle = Math.atan2(y, x) - this.stickPosition.x = Math.cos(angle) * this.maxDistance - this.stickPosition.y = Math.sin(angle) * this.maxDistance + this.stickPosition.x = Math.cos(angle) * MAX_JOYSTICK_RADIUS + this.stickPosition.y = Math.sin(angle) * MAX_JOYSTICK_RADIUS } else { this.stickPosition.x = x this.stickPosition.y = y } - this.stickElement.style.transform = `translate(${this.stickPosition.x - this.maxDistance / 2}px, ${this.stickPosition.y - this.maxDistance / 2}px)` - this.movementCallback(this.stickPosition.x / this.maxDistance, this.stickPosition.y / this.maxDistance) + this.stickElement.style.transform = `translate(${this.stickPosition.x - MAX_JOYSTICK_RADIUS / 2}px, ${this.stickPosition.y - MAX_JOYSTICK_RADIUS / 2}px)` + } + + public GetPosition(axis: "x" | "y") { + return this.stickPosition[axis] / MAX_JOYSTICK_RADIUS } } diff --git a/fission/src/systems/scene/SceneRenderer.ts b/fission/src/systems/scene/SceneRenderer.ts index d49bfdf8ca..92b4917050 100644 --- a/fission/src/systems/scene/SceneRenderer.ts +++ b/fission/src/systems/scene/SceneRenderer.ts @@ -15,7 +15,6 @@ import Jolt from "@barclah/jolt-physics" import { PixelSpaceCoord, SceneOverlayEvent, SceneOverlayEventKey } from "@/ui/components/SceneOverlayEvents" import PreferencesSystem from "../preferences/PreferencesSystem" import { CSM } from "three/examples/jsm/csm/CSM.js" -import Joystick from "./Joystick" import { TouchControlsEvent, TouchControlsEventKeys } from "@/ui/components/TouchControls" const CLEAR_COLOR = 0x121212 @@ -131,21 +130,6 @@ class SceneRenderer extends WorldSystem { // Orbit controls this._orbitControls = new OrbitControls(this._mainCamera, this._renderer.domElement) this._orbitControls.update() - - // Add a cube to the scene - const geometry1 = new THREE.BoxGeometry() - const material1 = new THREE.MeshBasicMaterial({ color: 0x00ff00 }) - const cube = new THREE.Mesh(geometry1, material1) - this._scene.add(cube) - - // Initialize the joystick - const joystickBase = document.getElementById("joystick-base-left")! - const joystickStick = document.getElementById("joystick-stick-left")! - const joystick = new Joystick(joystickBase, joystickStick, 55, (x, y) => { - // Use the joystick input to control the cube - cube.position.x += x * 0.1 - cube.position.y -= y * 0.1 - }) } public UpdateCanvasSize() { diff --git a/fission/src/ui/components/TouchControls.tsx b/fission/src/ui/components/TouchControls.tsx index 60f6ff065d..36cc6c6afb 100644 --- a/fission/src/ui/components/TouchControls.tsx +++ b/fission/src/ui/components/TouchControls.tsx @@ -34,16 +34,16 @@ function TouchControls() { const PlaceMirabufAssembly = useCallback(() => { if (inputRef.current) { const pressEvent = new KeyboardEvent("keydown", { - key: "Enter", - code: "Enter", + key: "ConfirmAssemblyButton", + code: "ConfirmAssemblyButton", bubbles: true, }) inputRef.current.dispatchEvent(pressEvent) setTimeout(() => { const releaseEvent = new KeyboardEvent("keyup", { - key: "Enter", - code: "Enter", + key: "ConfirmAssemblyButton", + code: "ConfirmAssemblyButton", bubbles: true, }) inputRef.current?.dispatchEvent(releaseEvent) @@ -67,7 +67,7 @@ function TouchControls() { className={`fixed bottom-[5vh] left-[5vw] w-60 h-60 touch-none ${isJoystickVisible ? "" : "hidden"}`} >
-
+
@@ -93,6 +96,8 @@ function TouchControls() { export default TouchControls +export const MAX_JOYSTICK_RADIUS: number = 55 + export const enum TouchControlsEventKeys { PLACE_BUTTON = "PlaceButtonEvent", JOYSTICK = "JoystickEvent", @@ -117,3 +122,10 @@ export class TouchControlsEvent extends Event { window.removeEventListener(eventKey, func) } } + +/** Notates the left and right joysticks with their x and y axis */ +export const enum TouchControlsJoystick { + LEFT, + RIGHT, + NONE, +} From e53dc0a0debcfc1ad8f98ba65c8af17981abaa0c Mon Sep 17 00:00:00 2001 From: BrandonPacewic <92102436+BrandonPacewic@users.noreply.github.com> Date: Wed, 21 Aug 2024 10:31:42 -0700 Subject: [PATCH 0014/1127] Remove unused code --- exporter/SynthesisFusionAddin/src/Types.py | 3 + .../SynthesisFusionAddin/src/UI/Camera.py | 2 +- .../src/UI/ConfigCommand.py | 258 ++---------------- .../src/UI/Configuration/SerialCommand.py | 104 ------- .../SynthesisFusionAddin/src/UI/Handlers.py | 107 -------- 5 files changed, 21 insertions(+), 453 deletions(-) delete mode 100644 exporter/SynthesisFusionAddin/src/UI/Configuration/SerialCommand.py diff --git a/exporter/SynthesisFusionAddin/src/Types.py b/exporter/SynthesisFusionAddin/src/Types.py index 5e2d7c967f..82169e0f54 100644 --- a/exporter/SynthesisFusionAddin/src/Types.py +++ b/exporter/SynthesisFusionAddin/src/Types.py @@ -5,6 +5,8 @@ from enum import Enum, EnumType from typing import Any, TypeAlias, get_args, get_origin +import adsk.fusion + # Not 100% sure what this is for - Brandon JointParentType = Enum("JointParentType", ["ROOT", "END"]) @@ -85,6 +87,7 @@ def toKg(pounds: LBS) -> KG: PRIMITIVES = (bool, str, int, float, type(None)) +SELECTABLE_JOINT_TYPES = (adsk.fusion.JointTypes.RevoluteJointType, adsk.fusion.JointTypes.SliderJointType) def encodeNestedObjects(obj: Any) -> Any: diff --git a/exporter/SynthesisFusionAddin/src/UI/Camera.py b/exporter/SynthesisFusionAddin/src/UI/Camera.py index 53168fd24d..4b83062687 100644 --- a/exporter/SynthesisFusionAddin/src/UI/Camera.py +++ b/exporter/SynthesisFusionAddin/src/UI/Camera.py @@ -9,7 +9,7 @@ @logFailure -def captureThumbnail(size: int = 250) -> str | os.PathLike[str]: +def captureThumbnail(size: int = 250) -> str: """ ## Captures Thumbnail and saves it to a temporary path - needs to be cleared after or on startup - Size: int (Default: 200) : (width & height) diff --git a/exporter/SynthesisFusionAddin/src/UI/ConfigCommand.py b/exporter/SynthesisFusionAddin/src/UI/ConfigCommand.py index cbdd5f1881..b95d6ecbb7 100644 --- a/exporter/SynthesisFusionAddin/src/UI/ConfigCommand.py +++ b/exporter/SynthesisFusionAddin/src/UI/ConfigCommand.py @@ -2,9 +2,6 @@ links the Configuration Command seen when pressing the Synthesis button in the Addins Panel """ -import os -import pathlib -from enum import Enum from typing import Any import adsk.core @@ -15,70 +12,22 @@ from src.Logging import getLogger, logFailure from src.Parser.ExporterOptions import ExporterOptions from src.Parser.SynthesisParser.Parser import Parser -from src.Types import ExportLocation, ExportMode +from src.Types import SELECTABLE_JOINT_TYPES, ExportLocation, ExportMode from src.UI import FileDialogConfig -from src.UI.Configuration.SerialCommand import SerialCommand from src.UI.GamepieceConfigTab import GamepieceConfigTab from src.UI.GeneralConfigTab import GeneralConfigTab from src.UI.JointConfigTab import JointConfigTab -# ====================================== CONFIG COMMAND ====================================== - generalConfigTab: GeneralConfigTab jointConfigTab: JointConfigTab gamepieceConfigTab: GamepieceConfigTab logger = getLogger() -""" -INPUTS_ROOT (adsk.fusion.CommandInputs): - - Provides access to the set of all commandInput UI elements in the panel -""" -INPUTS_ROOT = None - - -# Transition: AARD-1765 -# This should be removed in the config command refactor. Seemingly impossible to type. -def GUID(arg: str | adsk.core.Base) -> str | adsk.core.Base: - """### Will return command object when given a string GUID, or the string GUID of an object (depending on arg value) - - Args: - arg str | object: Either a command input object or command input GUID - - Returns: - str | object: Either a command input object or command input GUID - """ - if type(arg) == str: - object = gm.app.activeDocument.design.findEntityByToken(arg)[0] - return object - else: # type(obj) - return arg.entityToken # type: ignore[union-attr] - - -class JointMotions(Enum): - """### Corresponds to the API JointMotions enum - - Args: - Enum (enum.Enum) - """ - - RIGID = 0 - REVOLUTE = 1 - SLIDER = 2 - CYLINDRICAL = 3 - PIN_SLOT = 4 - PLANAR = 5 - BALL = 6 +INPUTS_ROOT: adsk.core.CommandInputs class ConfigureCommandCreatedHandler(adsk.core.CommandCreatedEventHandler): - """### Start the Command Input Object and define all of the input groups to create our ParserOptions object. - - Notes: - - linked and called from (@ref HButton) and linked - - will be called from (@ref Events.py) - """ - def __init__(self, configure: Any) -> None: super().__init__() @@ -87,22 +36,16 @@ def notify(self, args: adsk.core.CommandCreatedEventArgs) -> None: exporterOptions = ExporterOptions().readFromDesign() or ExporterOptions() cmd = args.command - # Set to false so won't automatically export on switch context cmd.isAutoExecute = False cmd.isExecutedWhenPreEmpted = False - cmd.okButtonText = "Export" # replace default OK text with "export" - cmd.setDialogInitialSize(400, 350) # these aren't working for some reason... - cmd.setDialogMinimumSize(400, 350) # these aren't working for some reason... + cmd.okButtonText = "Export" + cmd.setDialogSize(800, 350) - global INPUTS_ROOT # Global CommandInputs arg + global INPUTS_ROOT INPUTS_ROOT = cmd.commandInputs - # ~~~~~~~~~~~~~~~~ HELP FILE ~~~~~~~~~~~~~~~~ - """ - Sets the small "i" icon in bottom left of the panel. - - This is an HTML file that has a script to redirect to exporter workflow tutorial. - """ - cmd.helpFile = os.path.join(".", "src", "Resources", "HTML", "info.html") + # TODO? + # cmd.helpFile = os.path.join(".", "src", "Resources", "HTML", "info.html") global generalConfigTab generalConfigTab = GeneralConfigTab(args, exporterOptions) @@ -139,10 +82,7 @@ def notify(self, args: adsk.core.CommandCreatedEventArgs) -> None: *gm.app.activeDocument.design.rootComponent.allJoints, *gm.app.activeDocument.design.rootComponent.allAsBuiltJoints, ]: - if ( - joint.jointMotion.jointType in (JointMotions.REVOLUTE.value, JointMotions.SLIDER.value) - and not joint.isSuppressed - ): + if joint.jointMotion.jointType in SELECTABLE_JOINT_TYPES and not joint.isSuppressed: jointConfigTab.addJoint(joint) # Adding saved wheels must take place after joints are added as a result of how the two types are connected. @@ -154,75 +94,6 @@ def notify(self, args: adsk.core.CommandCreatedEventArgs) -> None: if len(fusionJoints): jointConfigTab.addWheel(fusionJoints[0], wheel) - # ~~~~~~~~~~~~~~~~ JOINT SETTINGS ~~~~~~~~~~~~~~~~ - """ - Joint settings group command - """ - - # Transition: AARD-1689 - # Should possibly be implemented later? - - # jointsSettings = a_input.addGroupCommandInput( - # "joints_settings", "Joints Settings" - # ) - # jointsSettings.isExpanded = False - # jointsSettings.isEnabled = True - # jointsSettings.tooltip = "tooltip" # TODO: update tooltip - # joints_settings = jointsSettings.children - - # self.createBooleanInput( - # "kinematic_only", - # "Kinematic Only", - # joints_settings, - # checked=False, - # tooltip="tooltip", # TODO: update tooltip - # enabled=True, - # ) - - # self.createBooleanInput( - # "calculate_limits", - # "Calculate Limits", - # joints_settings, - # checked=True, - # tooltip="tooltip", # TODO: update tooltip - # enabled=True, - # ) - - # self.createBooleanInput( - # "auto_assign_ids", - # "Auto-Assign ID's", - # joints_settings, - # checked=True, - # tooltip="tooltip", # TODO: update tooltip - # enabled=True, - # ) - - # ~~~~~~~~~~~~~~~~ CONTROLLER SETTINGS ~~~~~~~~~~~~~~~~ - """ - Controller settings group command - """ - - # Transition: AARD-1689 - # Should possibly be implemented later? - - # controllerSettings = a_input.addGroupCommandInput( - # "controller_settings", "Controller Settings" - # ) - - # controllerSettings.isExpanded = False - # controllerSettings.isEnabled = True - # controllerSettings.tooltip = "tooltip" # TODO: update tooltip - # controller_settings = controllerSettings.children - - # self.createBooleanInput( # export signals checkbox - # "export_signals", - # "Export Signals", - # controller_settings, - # checked=True, - # tooltip="tooltip", - # enabled=True, - # ) - getAuth() user_info = getUserInfo() apsSettings = INPUTS_ROOT.addTabCommandInput( @@ -230,66 +101,37 @@ def notify(self, args: adsk.core.CommandCreatedEventArgs) -> None: ) apsSettings.tooltip = "Configuration settings for Autodesk Platform Services." - # clear all selections before instantiating handlers. gm.ui.activeSelections.clear() - - # ====================================== EVENT HANDLERS ====================================== - """ - Instantiating all the event handlers - """ - onExecute = ConfigureCommandExecuteHandler() cmd.execute.add(onExecute) - gm.handlers.append(onExecute) # 0 + gm.handlers.append(onExecute) onInputChanged = ConfigureCommandInputChanged(cmd) cmd.inputChanged.add(onInputChanged) - gm.handlers.append(onInputChanged) # 1 + gm.handlers.append(onInputChanged) - onExecutePreview = CommandExecutePreviewHandler(cmd) + onExecutePreview = CommandExecutePreviewHandler() cmd.executePreview.add(onExecutePreview) - gm.handlers.append(onExecutePreview) # 2 + gm.handlers.append(onExecutePreview) onSelect = MySelectHandler(cmd) cmd.select.add(onSelect) - gm.handlers.append(onSelect) # 3 + gm.handlers.append(onSelect) onPreSelect = MyPreSelectHandler(cmd) cmd.preSelect.add(onPreSelect) - gm.handlers.append(onPreSelect) # 4 + gm.handlers.append(onPreSelect) onPreSelectEnd = MyPreselectEndHandler(cmd) cmd.preSelectEnd.add(onPreSelectEnd) - gm.handlers.append(onPreSelectEnd) # 5 + gm.handlers.append(onPreSelectEnd) onDestroy = MyCommandDestroyHandler() cmd.destroy.add(onDestroy) - gm.handlers.append(onDestroy) # 8 + gm.handlers.append(onDestroy) class ConfigureCommandExecuteHandler(adsk.core.CommandEventHandler): - """### Called when Ok is pressed confirming the export - - Process Steps: - - 1. Check for process open in explorer - - 1.5. Open file dialog to allow file location save - - Not always optimal if sending over socket for parse - - 2. Check Socket bind - - 3. Check Socket recv - - if true send data about file location in temp path - - 4. Parse file and focus on unity window - - """ - - def __init__(self) -> None: - super().__init__() - self.current = SerialCommand() - @logFailure(messageBox=True) def notify(self, args: adsk.core.CommandEventArgs) -> None: exporterOptions = ExporterOptions().readFromDesign() @@ -305,14 +147,6 @@ def notify(self, args: adsk.core.CommandEventArgs) -> None: if not savepath: # save was canceled return - - # Transition: AARD-1742 - # With the addition of a 'release' build the fusion exporter will not have permissions within the sourced - # folder. Because of this we cannot use this kind of tmp path anymore. This code was already unused and - # should be removed. - # updatedPath = pathlib.Path(savepath).parent - # if updatedPath != self.current.filePath: - # self.current.filePath = str(updatedPath) else: savepath = processedFileName @@ -361,51 +195,17 @@ def notify(self, args: adsk.core.CommandEventArgs) -> None: class CommandExecutePreviewHandler(adsk.core.CommandEventHandler): - """### Gets an event that is fired when the command has completed gathering the required input and now needs to perform a preview. - - Args: - adsk (CommandEventHandler): Command event handler that a client derives from to handle events triggered by a CommandEvent. - """ - - def __init__(self, cmd: adsk.core.Command) -> None: - super().__init__() - self.cmd = cmd - @logFailure(messageBox=True) def notify(self, args: adsk.core.CommandEventArgs) -> None: - """Notify member called when a command event is triggered - - Args: - args (CommandEventArgs): command event argument - """ jointConfigTab.handlePreviewEvent(args) gamepieceConfigTab.handlePreviewEvent(args) class MySelectHandler(adsk.core.SelectionEventHandler): - """### Event fires when the user selects an entity. - ##### This is different from a preselection where an entity is shown as being available for selection as the mouse passes over the entity. This is the actual selection where the user has clicked the mouse on the entity. - - Args: SelectionEventHandler - """ - - lastInputCmd = None - def __init__(self, cmd: adsk.core.Command) -> None: super().__init__() self.cmd = cmd - # Transition: AARD-1765 - # self.allWheelPreselections = [] # all child occurrences of selections - # self.allGamepiecePreselections = [] # all child gamepiece occurrences of selections - - self.selectedOcc = None # selected occurrence (if there is one) - self.selectedJoint = None # selected joint (if there is one) - - # Transition: AARD-1765 - # self.wheelJointList = [] - self.algorithmicSelection = True - @logFailure(messageBox=True) def traverseAssembly( self, child_occurrences: adsk.fusion.OccurrenceList, jointedOcc: dict[adsk.fusion.Joint, adsk.fusion.Occurrence] @@ -543,11 +343,6 @@ def notify(self, args: adsk.core.SelectionEventArgs) -> None: class MyPreselectEndHandler(adsk.core.SelectionEventHandler): - """### Event fires when the mouse is moved away from an entity that was in a preselect state. - - Args: SelectionEventArgs - """ - def __init__(self, cmd: adsk.core.Command) -> None: super().__init__() self.cmd = cmd @@ -563,25 +358,12 @@ def notify(self, args: adsk.core.SelectionEventArgs) -> None: class ConfigureCommandInputChanged(adsk.core.InputChangedEventHandler): - """### Gets an event that is fired whenever an input value is changed. - - Button pressed, selection made, switching tabs, etc... - - Args: InputChangedEventHandler - """ - def __init__(self, cmd: adsk.core.Command) -> None: super().__init__() self.cmd = cmd - self.allWeights = [None, None] # [lbs, kg] - self.isLbs = True - self.isLbs_f = True @logFailure def reset(self) -> None: - """### Process: - - Reset the mouse icon to default - - Clear active selections - """ self.cmd.setCursor("", 0, 0) gm.ui.activeSelections.clear() @@ -597,14 +379,8 @@ def notify(self, args: adsk.core.InputChangedEventArgs) -> None: class MyCommandDestroyHandler(adsk.core.CommandEventHandler): - """### Gets the event that is fired when the command is destroyed. Globals lists are released and active selections are cleared (when exiting the panel). - - In other words, when the OK or Cancel button is pressed... - - Args: CommandEventHandler - """ - @logFailure(messageBox=True) - def notify(self, args: adsk.core.CommandEventArgs) -> None: + def notify(self, _: adsk.core.CommandEventArgs) -> None: jointConfigTab.reset() gamepieceConfigTab.reset() diff --git a/exporter/SynthesisFusionAddin/src/UI/Configuration/SerialCommand.py b/exporter/SynthesisFusionAddin/src/UI/Configuration/SerialCommand.py deleted file mode 100644 index 61c1e30108..0000000000 --- a/exporter/SynthesisFusionAddin/src/UI/Configuration/SerialCommand.py +++ /dev/null @@ -1,104 +0,0 @@ -""" SerialCommand module - -Defines what is generated by the Fusion Command. -Use to be protobuf but can only de-serialize from a filestream strangely. -This is used to store in the userdata. -""" - -import json - -from src.Types import OString - - -# Transition: AARD-1765 -# Will likely be removed later as this is no longer used. Avoiding adding typing for now. -def generateFilePath() -> str: - """Generates a temporary file path that can be used to save the file for exporting - - Example: - - "%appdata%/Roaming/Temp/HellionFiles" - - Returns: - str: file path - """ - tempPath = OString.TempPath("").getPath() # type: ignore - return str(tempPath) - - -class Struct: - """For decoding the dict values into named values""" - - def __init__(self, **entries): # type: ignore - self.__dict__.update(entries) - - -class SerialCommand: - """All of the command inputs combined""" - - def __init__(self): # type: ignore - self.general = General() - self.advanced = Advanced() - - # Transition: AARD-1742 - # With the addition of a 'release' build the fusion exporter will not have permissions within the sourced - # folder. Because of this we cannot use this kind of tmp path anymore. This code was already unused and - # should be removed. - # self.filePath = generateFilePath() - - def toJSON(self) -> str: - """Converts this class into a json object that can be written to the object data - - Returns: - str: json version of this object - """ - return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=1) - - -class General: - """General Options""" - - def __init__(self): # type: ignore - # This is the overall export decision point - self.exportMode = ExportMode.standard - self.RenderType = RenderType.basic3D - self.material = BooleanInput("material", True) - self.joints = BooleanInput("joints", False) - self.rigidGroups = BooleanInput("rigidgroup", False) - # self.wheelType = - self.simpleWheelExport = BooleanInput("simplewheelexport", False) - - -class Advanced: - """Advanced settings in the command input""" - - def __init__(self): # type: ignore - self.friction = BooleanInput("friction", True) - self.density = BooleanInput("density", True) - self.mass = BooleanInput("mass", True) - self.volume = BooleanInput("volume", True) - self.surfaceArea = BooleanInput("surfaceArea", True) - self.com = BooleanInput("com", True) - - -class BooleanInput: - """Class to store the value of a boolean input""" - - def __init__(self, name: str, default: bool): - self.name = name - self.checked = default - - -class ExportMode: - """Export Mode defines the type of export""" - - standard = 0 - VR = 1 - Simulation = 2 - - -class RenderType: - """This will modify the type of material shaders used""" - - basic3D = 0 - URP = 1 - HDRP = 2 diff --git a/exporter/SynthesisFusionAddin/src/UI/Handlers.py b/exporter/SynthesisFusionAddin/src/UI/Handlers.py index 0e60ba36f7..b3f11f516d 100644 --- a/exporter/SynthesisFusionAddin/src/UI/Handlers.py +++ b/exporter/SynthesisFusionAddin/src/UI/Handlers.py @@ -41,110 +41,3 @@ def __init__(self, button: Any) -> None: def notify(self, _: adsk.core.CommandEventArgs) -> None: self.button.exec_func() - - -""" OLD PALETTE COMMANDS -class HPaletteHTMLEventHandler(adsk.core.HTMLEventHandler): - def __init__(self, palette): - super().__init__() - self.palette = palette - - def notify(self, args) -> None: - ui = adsk.core.Application.get().userInterface - try: - htmlArgs = adsk.core.HTMLEventArgs.cast(args) - - for event in self.palette.events[0]: - if event[0] == htmlArgs.action: - # if Helper.check_solid_open() : - val = event[1](htmlArgs.data) - if val is not None: - # logging.getLogger("HellionFusion.HUI.Handlers").debug( - # f"{htmlArgs.action}: response: {val}" - # ) - htmlArgs.returnData = val - return - else: - htmlArgs.returnData = "" - except: - ui.messageBox("Failed:\n{}".format(traceback.format_exc())) - -""" - -""" These are old functions that mapped the palette commands - -class CustomDocumentSavedHandler(adsk.core.DocumentEventHandler): - def __init__(self): - super().__init__() - - def notify(self, args) -> bool: - eventArgs = adsk.core.DocumentEventArgs.cast(args) - name = Helper.getDocName() - - if name in gm.queue: - connected = Helper.checkAttribute() - if connected and (connected == "True"): - try: - # req = DesignModificationLookup(gm.app.activeDocument.design) - # if req is not None: - # sent = nm.send(req) - # logging.getLogger('HellionFusion.HUI.Handlers.DocumentSaved').debug(f'Sending update with data: {req}') - - design = gm.app.activeDocument.design - name = design.rootComponent.name.rsplit(" ", 1)[0] - version = design.rootComponent.name.rsplit(" ", 1)[1] - - # version comes back the same - this is terrible but it will do - version = int(version[1:]) - version += 1 - version = f"v{version}" - - Helper.addUnityAttribute() - req = Parser(parseOptions=ParseOptions()).parseUpdated(version) - if req is not None: - sent = nm.send(req) - else: - logging.getLogger( - "HellionFusion.HUI.Handlers.DocumentSave" - ).error( - f"Failed to Parse Update or generate request ----- \n {req}" - ) - return True - - except: - gm.ui.messageBox() - logging.getLogger("HellionFusion.HUI.Handlers.DocumentSave").error( - "Failed:\n{}".format(traceback.format_exc()) - ) - - # TODO: add item to queue here - # let the Network manager send them and control how they are sent - # if len(gm.palettes) >= 1: - # palette = gm.ui.palettes.itemById(gm.palettes[0].uid) - # if palette: - # name = Helper.getDocName() - else: - return False - - -class ConnectionPaletteHandler(adsk.core.CustomEventHandler): - def __init__(self): - super().__init__() - - def notify(self, args): - ui = adsk.core.Application.get().userInterface - try: - if ui.activeCommand != "SelectCommand": - ui.commandDefinitions.itemById("SelectCommand").execute() - - if len(gm.palettes) >= 1: - palette = ui.palettes.itemById(gm.palettes[0].uid) - if palette: - res = palette.sendInfoToHTML( - "updateConnection", nm.NetCommand.connected() - ) - except: - if ui: - ui.messageBox("Failed:\n{}".format(traceback.format_exc())) - -""" From 969747698bb902feaeb7ff44691fb52416c4f04d Mon Sep 17 00:00:00 2001 From: Dhruv Arora Date: Wed, 21 Aug 2024 15:51:27 -0700 Subject: [PATCH 0015/1127] Fixed post-merge conflicts --- .../src/ui/panels/mirabuf/ImportMirabufPanel.tsx | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/fission/src/ui/panels/mirabuf/ImportMirabufPanel.tsx b/fission/src/ui/panels/mirabuf/ImportMirabufPanel.tsx index d5b68001b6..3bf83e647a 100644 --- a/fission/src/ui/panels/mirabuf/ImportMirabufPanel.tsx +++ b/fission/src/ui/panels/mirabuf/ImportMirabufPanel.tsx @@ -200,10 +200,7 @@ const ImportMirabufPanel: React.FC = ({ panelId }) => { closePanel(panelId) - if (type == MiraType.ROBOT) { - setSelectedBrainIndexGlobal(SynthesisBrain.brainIndexMap.size) - openPanel("choose-scheme") - } + if (type == MiraType.ROBOT) setSelectedBrainIndexGlobal(SynthesisBrain.brainIndexMap.size) }, [showTooltip, closePanel, panelId, openPanel] ) @@ -226,10 +223,7 @@ const ImportMirabufPanel: React.FC = ({ panelId }) => { closePanel(panelId) - if (type == MiraType.ROBOT) { - setSelectedBrainIndexGlobal(SynthesisBrain.brainIndexMap.size) - openPanel("choose-scheme") - } + if (type == MiraType.ROBOT) setSelectedBrainIndexGlobal(SynthesisBrain.brainIndexMap.size) }, [closePanel, panelId, openPanel] ) @@ -251,10 +245,7 @@ const ImportMirabufPanel: React.FC = ({ panelId }) => { closePanel(panelId) - if (type == MiraType.ROBOT) { - setSelectedBrainIndexGlobal(SynthesisBrain.brainIndexMap.size) - openPanel("choose-scheme") - } + if (type == MiraType.ROBOT) setSelectedBrainIndexGlobal(SynthesisBrain.brainIndexMap.size) }, [closePanel, panelId, openPanel] ) From 60b879331ba565ae040e606905ae80bc925bb764 Mon Sep 17 00:00:00 2001 From: Dhruv Arora Date: Wed, 21 Aug 2024 16:08:19 -0700 Subject: [PATCH 0016/1127] Fixing build errors --- fission/package.json | 1 + fission/src/ui/components/MainHUD.tsx | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/fission/package.json b/fission/package.json index 3b5df05cdc..89c4d89422 100644 --- a/fission/package.json +++ b/fission/package.json @@ -56,6 +56,7 @@ "@types/three": "^0.160.0", "@typescript-eslint/eslint-plugin": "^7.0.2", "@typescript-eslint/parser": "^7.0.2", + "@vitejs/plugin-basic-ssl": "^1.1.0", "@vitejs/plugin-react": "^4.0.3", "@vitejs/plugin-react-swc": "^3.5.0", "autoprefixer": "^10.4.14", diff --git a/fission/src/ui/components/MainHUD.tsx b/fission/src/ui/components/MainHUD.tsx index f78bb3ba91..b37283c705 100644 --- a/fission/src/ui/components/MainHUD.tsx +++ b/fission/src/ui/components/MainHUD.tsx @@ -170,7 +170,9 @@ const MainHUD: React.FC = () => { icon={SynthesisIcons.Gamepad} onClick={() => new TouchControlsEvent(TouchControlsEventKeys.JOYSTICK)} /> - ) : <>} + ) : ( + <> + )} {userInfo ? ( Date: Wed, 21 Aug 2024 16:44:28 -0700 Subject: [PATCH 0017/1127] Fixing unit tests --- fission/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fission/package.json b/fission/package.json index 89c4d89422..0f97b9170b 100644 --- a/fission/package.json +++ b/fission/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "init": "(bun run assetpack && bun run playwright:install) || (npm run assetpack && npm run playwright:install)", - "dev": "vite --open", + "dev": "vite --open --host", "build": "tsc && vite build", "build:prod": "tsc && vite build --base=/fission/ --outDir dist/prod", "build:dev": "tsc && vite build --base=/fission-closed/ --outDir dist/dev", From d10592c298bc584c23c9c57148630b24a6a45899 Mon Sep 17 00:00:00 2001 From: Dhruv Arora Date: Wed, 21 Aug 2024 17:25:21 -0700 Subject: [PATCH 0018/1127] Fixing unit tests --- fission/src/systems/input/InputSystem.ts | 18 ++++++++++-------- fission/src/systems/scene/Joystick.ts | 2 +- fission/vite.config.ts | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/fission/src/systems/input/InputSystem.ts b/fission/src/systems/input/InputSystem.ts index 6c39f477fd..282f5c02ee 100644 --- a/fission/src/systems/input/InputSystem.ts +++ b/fission/src/systems/input/InputSystem.ts @@ -183,14 +183,16 @@ class InputSystem extends WorldSystem { this.gamepadDisconnected = this.gamepadDisconnected.bind(this) window.addEventListener("gamepaddisconnected", this.gamepadDisconnected) - InputSystem.leftJoystick = new Joystick( - document.getElementById("joystick-base-left")!, - document.getElementById("joystick-stick-left")! - ) - InputSystem.rightJoystick = new Joystick( - document.getElementById("joystick-base-right")!, - document.getElementById("joystick-stick-right")! - ) + window.onload = () => { + InputSystem.leftJoystick = new Joystick( + document.getElementById("joystick-base-left")!, + document.getElementById("joystick-stick-left")! + ) + InputSystem.rightJoystick = new Joystick( + document.getElementById("joystick-base-right")!, + document.getElementById("joystick-stick-right")! + ) + } // Initialize an event that's triggered when the user exits/enters the page document.addEventListener("visibilitychange", () => { diff --git a/fission/src/systems/scene/Joystick.ts b/fission/src/systems/scene/Joystick.ts index 3dc6b059d4..c604da34c4 100644 --- a/fission/src/systems/scene/Joystick.ts +++ b/fission/src/systems/scene/Joystick.ts @@ -41,7 +41,7 @@ class Joystick { private onPointerUp(event: PointerEvent) { if (this.activePointerId !== event.pointerId) return - this.stickPosition = { x: 0, y: 0 } + this.stickPosition = { x: 0, y: 0 } this.stickElement.style.transform = `translate(-50%, -50%)` this.baseRect = null } diff --git a/fission/vite.config.ts b/fission/vite.config.ts index ead5ab5431..428d7d0616 100644 --- a/fission/vite.config.ts +++ b/fission/vite.config.ts @@ -9,7 +9,7 @@ const serverPort = 3000 const dockerServerPort = 80 const useLocal = false -const useSsl = true +const useSsl = false const plugins = [ react(), glsl({ From 609d178682c99a9c3fa9aea51b61d006abbc2666 Mon Sep 17 00:00:00 2001 From: Dhruv Arora Date: Thu, 22 Aug 2024 11:45:41 -0700 Subject: [PATCH 0019/1127] Fixed unit test issues and fixed joysticks --- fission/src/systems/input/DefaultInputs.ts | 7 +- fission/src/systems/input/InputSystem.ts | 15 ++-- fission/src/systems/scene/Joystick.ts | 2 +- fission/src/ui/components/TouchControls.tsx | 10 ++- .../inputs/ConfigureSchemeInterface.tsx | 11 +++ .../interfaces/inputs/EditInputInterface.tsx | 70 +++++++++++++++---- fission/vite.config.ts | 2 +- 7 files changed, 89 insertions(+), 28 deletions(-) diff --git a/fission/src/systems/input/DefaultInputs.ts b/fission/src/systems/input/DefaultInputs.ts index 4aec02a676..43e015fd03 100644 --- a/fission/src/systems/input/DefaultInputs.ts +++ b/fission/src/systems/input/DefaultInputs.ts @@ -332,7 +332,7 @@ class DefaultInputs { undefined, undefined, undefined, - TouchControlsJoystick.LEFT + TouchControlsJoystick.LEFT_Y ), new AxisInput( "arcadeTurn", @@ -343,11 +343,8 @@ class DefaultInputs { undefined, undefined, undefined, - TouchControlsJoystick.RIGHT + TouchControlsJoystick.RIGHT_X ), - - new ButtonInput("intake", "Semicolon"), - new ButtonInput("eject", "KeyL"), ], } } diff --git a/fission/src/systems/input/InputSystem.ts b/fission/src/systems/input/InputSystem.ts index 282f5c02ee..e656656579 100644 --- a/fission/src/systems/input/InputSystem.ts +++ b/fission/src/systems/input/InputSystem.ts @@ -183,7 +183,7 @@ class InputSystem extends WorldSystem { this.gamepadDisconnected = this.gamepadDisconnected.bind(this) window.addEventListener("gamepaddisconnected", this.gamepadDisconnected) - window.onload = () => { + window.addEventListener("touchcontrolsloaded", () => { InputSystem.leftJoystick = new Joystick( document.getElementById("joystick-base-left")!, document.getElementById("joystick-stick-left")! @@ -192,7 +192,7 @@ class InputSystem extends WorldSystem { document.getElementById("joystick-base-right")!, document.getElementById("joystick-stick-right")! ) - } + }) // Initialize an event that's triggered when the user exits/enters the page document.addEventListener("visibilitychange", () => { @@ -345,12 +345,15 @@ class InputSystem extends WorldSystem { } // Returns a number between -1 and 1 from the touch controls - public static getTouchControlsAxis(axisNumber: TouchControlsJoystick): number { + public static getTouchControlsAxis(axisType: TouchControlsJoystick): number { let value: number - if (axisNumber === TouchControlsJoystick.LEFT) value = -InputSystem.leftJoystick.y - else value = InputSystem.rightJoystick.x - return value + if (axisType === TouchControlsJoystick.LEFT_Y) value = -InputSystem.leftJoystick.y + else if (axisType === TouchControlsJoystick.RIGHT_X) value = InputSystem.rightJoystick.x + else if (axisType === TouchControlsJoystick.RIGHT_Y) value = -InputSystem.rightJoystick.y + else value = InputSystem.leftJoystick.x + + return value! } } diff --git a/fission/src/systems/scene/Joystick.ts b/fission/src/systems/scene/Joystick.ts index c604da34c4..3dc6b059d4 100644 --- a/fission/src/systems/scene/Joystick.ts +++ b/fission/src/systems/scene/Joystick.ts @@ -41,7 +41,7 @@ class Joystick { private onPointerUp(event: PointerEvent) { if (this.activePointerId !== event.pointerId) return - this.stickPosition = { x: 0, y: 0 } + this.stickPosition = { x: 0, y: 0 } this.stickElement.style.transform = `translate(-50%, -50%)` this.baseRect = null } diff --git a/fission/src/ui/components/TouchControls.tsx b/fission/src/ui/components/TouchControls.tsx index 36cc6c6afb..efd3fbe53d 100644 --- a/fission/src/ui/components/TouchControls.tsx +++ b/fission/src/ui/components/TouchControls.tsx @@ -24,6 +24,10 @@ function TouchControls() { TouchControlsEvent.Listen(TouchControlsEventKeys.PLACE_BUTTON, handlePlaceButtonEvent) TouchControlsEvent.Listen(TouchControlsEventKeys.JOYSTICK, handleJoystickEvent) + console.log("TouchControls loaded") + const event = new Event("touchcontrolsloaded") + window.dispatchEvent(event) + return () => { TouchControlsEvent.RemoveListener(TouchControlsEventKeys.PLACE_BUTTON, handlePlaceButtonEvent) TouchControlsEvent.RemoveListener(TouchControlsEventKeys.JOYSTICK, handleJoystickEvent) @@ -125,7 +129,9 @@ export class TouchControlsEvent extends Event { /** Notates the left and right joysticks with their x and y axis */ export const enum TouchControlsJoystick { - LEFT, - RIGHT, + LEFT_X, + LEFT_Y, + RIGHT_X, + RIGHT_Y, NONE, } diff --git a/fission/src/ui/panels/configuring/assembly-config/interfaces/inputs/ConfigureSchemeInterface.tsx b/fission/src/ui/panels/configuring/assembly-config/interfaces/inputs/ConfigureSchemeInterface.tsx index 220191cab3..75885c9d47 100644 --- a/fission/src/ui/panels/configuring/assembly-config/interfaces/inputs/ConfigureSchemeInterface.tsx +++ b/fission/src/ui/panels/configuring/assembly-config/interfaces/inputs/ConfigureSchemeInterface.tsx @@ -12,6 +12,7 @@ interface ConfigSchemeProps { /** Interface to configure a specific input scheme */ const ConfigureSchemeInterface: React.FC = ({ selectedScheme }) => { const [useGamepad, setUseGamepad] = useState(selectedScheme.usesGamepad) + const [useTouchControls, setUseTouchControls] = useState(selectedScheme.usesTouchControls) const scrollRef = useRef(null) const saveEvent = useCallback(() => { @@ -58,6 +59,15 @@ const ConfigureSchemeInterface: React.FC = ({ selectedScheme }} tooltipText="Supported controllers: Xbox one, Xbox 360." /> + { + setUseTouchControls(val) + selectedScheme.usesTouchControls = val + }} + tooltipText="Enable on-screen touch controls (only for mobile devices)." + /> {/* Scroll view for inputs */} @@ -68,6 +78,7 @@ const ConfigureSchemeInterface: React.FC = ({ selectedScheme key={i.inputName} input={i} useGamepad={useGamepad} + useTouchControls={useTouchControls} onInputChanged={() => { selectedScheme.customized = true }} diff --git a/fission/src/ui/panels/configuring/assembly-config/interfaces/inputs/EditInputInterface.tsx b/fission/src/ui/panels/configuring/assembly-config/interfaces/inputs/EditInputInterface.tsx index 33ef12b7ab..19e3dea7f7 100644 --- a/fission/src/ui/panels/configuring/assembly-config/interfaces/inputs/EditInputInterface.tsx +++ b/fission/src/ui/panels/configuring/assembly-config/interfaces/inputs/EditInputInterface.tsx @@ -87,10 +87,11 @@ const transformKeyName = (keyCode: string, keyModifiers: ModifierState) => { interface EditInputProps { input: Input useGamepad: boolean + useTouchControls: boolean onInputChanged: () => void } -const EditInputInterface: React.FC = ({ input, useGamepad, onInputChanged }) => { +const EditInputInterface: React.FC = ({ input, useGamepad, useTouchControls, onInputChanged }) => { const [selectedInput, setSelectedInput] = useState("") const [chosenGamepadAxis, setChosenGamepadAxis] = useState(-1) const [chosenKey, setChosenKey] = useState("") @@ -305,18 +306,37 @@ const EditInputInterface: React.FC = ({ input, useGamepad, onInp ) } + // const TouchControlsAxisSelection = () => { + // if (!(input instanceof AxisInput)) throw new Error("Input not axis type") + + // return ( + // <> + // + // + // { + // setSelectedInput(input.inputName) + // setChosenTouchControlsAxis(touchControlsAxes.indexOf(value)) + // }} + // /> + // + // + // ) + // } + /** Show the correct selection mode based on input type and how it's configured */ const inputConfig = () => { - if (!useGamepad) { - // Keyboard button - if (input instanceof ButtonInput) { - return KeyboardButtonSelection() - } - // Keyboard Axis - else if (input instanceof AxisInput) { - return KeyboardAxisSelection() - } - } else { + if (useGamepad) { // Joystick Button if (input instanceof ButtonInput) { return JoystickButtonSelection() @@ -352,6 +372,20 @@ const EditInputInterface: React.FC = ({ input, useGamepad, onInp
) } + } else if (useTouchControls) { + // here + if (input instanceof AxisInput) { + return <> + } + } else { + // Keyboard button + if (input instanceof ButtonInput) { + return KeyboardButtonSelection() + } + // Keyboard Axis + else if (input instanceof AxisInput) { + return KeyboardAxisSelection() + } } } @@ -375,7 +409,7 @@ const EditInputInterface: React.FC = ({ input, useGamepad, onInp /** Input detection for setting inputs */ useEffect(() => { // // Assign keyboard inputs when a key is pressed - if (!useGamepad && selectedInput && chosenKey) { + if (!useGamepad && !useTouchControls && selectedInput && chosenKey) { if (selectedInput.startsWith("pos")) { if (!(input instanceof AxisInput)) return input.posKeyCode = chosenKey @@ -429,7 +463,17 @@ const EditInputInterface: React.FC = ({ input, useGamepad, onInp setChosenGamepadAxis(-1) setSelectedInput("") } - }, [chosenKey, chosenButton, chosenGamepadAxis, input, modifierState, onInputChanged, selectedInput, useGamepad]) + }, [ + chosenKey, + chosenButton, + chosenGamepadAxis, + input, + modifierState, + onInputChanged, + selectedInput, + useGamepad, + useTouchControls, + ]) return ( Date: Thu, 22 Aug 2024 12:00:01 -0700 Subject: [PATCH 0020/1127] Final changes to `ConfigCommand.py` --- .../src/Parser/ExporterOptions.py | 4 +- .../src/Resources/HTML/info.html | 4 +- exporter/SynthesisFusionAddin/src/Types.py | 2 + .../SynthesisFusionAddin/src/UI/Camera.py | 2 +- .../src/UI/ConfigCommand.py | 290 ++++-------------- .../src/UI/GamepieceConfigTab.py | 2 +- .../SynthesisFusionAddin/src/UI/Handlers.py | 12 + .../src/UI/JointConfigTab.py | 37 ++- 8 files changed, 111 insertions(+), 242 deletions(-) diff --git a/exporter/SynthesisFusionAddin/src/Parser/ExporterOptions.py b/exporter/SynthesisFusionAddin/src/Parser/ExporterOptions.py index 1eb34e9e52..39f6c276b7 100644 --- a/exporter/SynthesisFusionAddin/src/Parser/ExporterOptions.py +++ b/exporter/SynthesisFusionAddin/src/Parser/ExporterOptions.py @@ -32,7 +32,7 @@ class ExporterOptions: # Python's `os` module can return `None` when attempting to find the home directory if the # user's computer has conflicting configs of some sort. This has happened and should be accounted # for accordingly. - fileLocation: str | None = field( + fileLocation: str | os.PathLike[str] | None = field( default=(os.getenv("HOME") if platform.system() == "Windows" else os.path.expanduser("~")) ) name: str | None = field(default=None) @@ -52,7 +52,7 @@ class ExporterOptions: compressOutput: bool = field(default=True) exportAsPart: bool = field(default=False) - exportLocation: ExportLocation = field(default=ExportLocation.UPLOAD) + exportLocation: ExportLocation = field(default=ExportLocation.DOWNLOAD) hierarchy: ModelHierarchy = field(default=ModelHierarchy.FusionAssembly) visualQuality: TriangleMeshQualityOptions = field(default=TriangleMeshQualityOptions.LowQualityTriangleMesh) diff --git a/exporter/SynthesisFusionAddin/src/Resources/HTML/info.html b/exporter/SynthesisFusionAddin/src/Resources/HTML/info.html index a44b45f115..759ed2a48d 100644 --- a/exporter/SynthesisFusionAddin/src/Resources/HTML/info.html +++ b/exporter/SynthesisFusionAddin/src/Resources/HTML/info.html @@ -2,7 +2,7 @@