Slide 1

Slide 1 text

🀌 Filippo Scognamiglio πŸ₯– Renaud Mathieu Building a Joystick using Compose Multiplatform Android Makers by droidcon 2024 ❀

Slide 2

Slide 2 text

@renaud_mathieu @[email protected] renaudmathieu.com @Swordfish90 @[email protected] swordfish90.github.io

Slide 3

Slide 3 text

Prologue

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

Introduction

Slide 8

Slide 8 text

Overview Touch and input in Compose Pointer Input Focus Interactions Jetpack Compose

Slide 9

Slide 9 text

Pointer Input Components Gesture Modifiers Gesture Recognizers Pointer Events

Slide 10

Slide 10 text

Jolanda Verhoef

Slide 11

Slide 11 text

Understand gestures pointerInput fun Modifier.pointerInput( key1: Any?, block: suspend PointerInputScope.() -> Unit ): Modifier = this then SuspendPointerInputElement( key1 = key1, pointerInputHandler = block )

Slide 12

Slide 12 text

Understand gestures detectDragGestures suspend fun PointerInputScope.detectDragGestures( onDragStart: (Offset) -> Unit = { }, onDragEnd: () -> Unit = { }, onDragCancel: () -> Unit = { }, onDrag: (change: PointerInputChange, dragAmount: Offset) -> Unit ): Unit

Slide 13

Slide 13 text

Part 1. The bad idea 😒

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

Joystick NavKey, NavState @Composable pointerInput(x,y)

Slide 18

Slide 18 text

Joystick NavKey, NavState @Composable pointerInput(x,y)

Slide 19

Slide 19 text

Joystick NavKey, NavState @Composable pointerInput(x,y)

Slide 20

Slide 20 text

Joystick NavKey, NavState @Composable pointerInput(x,y) enum class NavState { RELEASED, PRESSED } enum class NavKey { UNKNOWN, ARROW_LEFT, ARROW_UP, ARROW_RIGHT, ARROW_DOWN, ARROW_UPPER_LEFT, ARROW_LOWER_LEFT, ARROW_UPPER_RIGHT, ARROW_LOWER_RIGHT }

Slide 21

Slide 21 text

Joystick @Composable @Composable fun JoyStick( modifier: Modifier = Modifier, size: Dp = 200.dp, dotSize: Dp = 110.dp, onValueChanged: (NavKey, NavState) -> Unit )

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

UP UPPER_RIGHT DOWN RIGHT LOWER_RIGHT LEFT UPPER_LEFT LOWER_LEFT

Slide 26

Slide 26 text

UP UPPER_RIGHT DOWN RIGHT LOWER_RIGHT LEFT UPPER_LEFT LOWER_LEFT

Slide 27

Slide 27 text

UP UPPER_RIGHT DOWN RIGHT LOWER_RIGHT LEFT UPPER_LEFT LOWER_LEFT

Slide 28

Slide 28 text

UP UPPER_RIGHT DOWN RIGHT LOWER_RIGHT LEFT UPPER_LEFT LOWER_LEFT

Slide 29

Slide 29 text

UP UPPER_RIGHT DOWN RIGHT LOWER_RIGHT LEFT UPPER_LEFT LOWER_LEFT

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

Part 2. The Better Idea πŸ€”

Slide 32

Slide 32 text

🧰 Tools A. Calculate the angle B. Find the direction from the angle C. Apply the offset to the dot

Slide 33

Slide 33 text

x,y 0,0 Calculate the angle

Slide 34

Slide 34 text

x,y 0,0 Ο‘ Calculate the angle

Slide 35

Slide 35 text

x,y 0,0 Ο‘ A B C Calculate the angle

Slide 36

Slide 36 text

x,y 0,0 Ο‘ A B C tan(Ο‘) = BC / AC tan(Ο‘) = y / x Ο‘ = atan(y / x) Calculate the angle

Slide 37

Slide 37 text

theta = getTheta(x, y) private fun getTheta(x: Float, y: Float) = when { x < 0 -& y -= 0 -> (PI).toFloat() + atan(y / x) x < 0 -& y < 0 -> -(PI).toFloat() + atan(y / x) else -> atan(y / x) }

Slide 38

Slide 38 text

Find the direction from the angle

Slide 39

Slide 39 text

Find the direction from the angle

Slide 40

Slide 40 text

Find the direction from the angle private fun getDirectionFromAngle(theta: Float): NavKey = when { theta -= 0 -& theta -= PI.div(6) -> { NavKey.ARROW_RIGHT } theta -= PI.div(6) -& theta -= PI.div(3) -> { NavKey.ARROW_LOWER_RIGHT } …

Slide 41

Slide 41 text

Calculate the offset of the dot Calculate the radius then the offset β€’ Polar to Cartesian

Slide 42

Slide 42 text

Calculate the offset of the dot Calculate the radius then the offset β€’ Polar to Cartesian private fun polarToCartesian( radius: Float, theta: Float ): Pair = Pair(radius * cos(theta), radius * sin(theta))

Slide 43

Slide 43 text

Box( modifier = Modifier .paint( painter = painterResource("joystick_background.xml"), alignment = Alignment.Center ) ) { Image( painter = painterResource("joystick_dot.xml"), contentDescription = "JoyStickDot" ) }

Slide 44

Slide 44 text

val localDensity = LocalDensity.current val centerX = with(localDensity) { ((size - dotSize) / 2).toPx() } val centerY = with(localDensity) { ((size - dotSize) / 2).toPx() } Image( painter = painterResource("joystick_dot.xml"), contentDescription = "JoyStickDot", modifier = Modifier .offset { IntOffset( centerX.roundToInt(), centerY.roundToInt() ) } .size(dotSize) )

Slide 45

Slide 45 text

val localDensity = LocalDensity.current val centerX = with(localDensity) { ((size - dotSize) / 2).toPx() } val centerY = with(localDensity) { ((size - dotSize) / 2).toPx() } Image( painter = painterResource("joystick_dot.xml"), contentDescription = "JoyStickDot", modifier = Modifier .offset { IntOffset( centerX.roundToInt(), centerY.roundToInt() ) } .size(dotSize) )

Slide 46

Slide 46 text

var navKey by remember { mutableStateOf(NavKey.UNKNOWN) } var navState by remember { mutableStateOf(NavState.RELEASED) }

Slide 47

Slide 47 text

.pointerInput(Unit) { detectDragGestures( onDragStart = { navState = NavState.PRESSED }, onDragEnd = { }, onDrag = { pointerInputChange: PointerInputChange, offset: Offset -> } ) }

Slide 48

Slide 48 text

.pointerInput(Unit) { detectDragGestures( onDrag = { pointerInputChange: PointerInputChange, offset: Offset -> if (navState -= NavState.PRESSED) { -/ Nothing is pressed return@detectDragGestures } pointerInputChange.consume() val x = offsetX + offset.x - centerX val y = offsetY + offset.y - centerY theta = getTheta(x, y) val fourDimensionDirection: NavKey = getFourDimensionFromAngle(theta) if (navKey -= fourDimensionDirection) {

Slide 49

Slide 49 text

theta = getTheta(x, y) val fourDimensionDirection: NavKey = getFourDimensionFromAngle(theta) if (navKey -= fourDimensionDirection) { if (navKey -= NavKey.UNKNOWN) { onValueChanged(navKey, NavState.RELEASED) } navKey = fourDimensionDirection -/ vibrate() if (navKey -= NavKey.UNKNOWN) { onValueChanged(navKey, NavState.PRESSED) } } } ) }

Slide 50

Slide 50 text

The dot does not move 😢

Slide 51

Slide 51 text

radius = sqrt((x.pow(2)) + (y.pow(2))) offsetX += offset.x offsetY += offset.y val t = polarToCartesian(radius, theta) positionX = t.first positionY = t.second

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

val maxRadius = with(localDensity) { 30.dp.toPx() } if (radius > maxRadius) { polarToCartesian(maxRadius, theta) } else { polarToCartesian(radius, theta) }.apply { positionX = first positionY = second }

Slide 54

Slide 54 text

Image( painter = painterResource("joystick_dot.xml"), contentDescription = "JoyStickDot", modifier = Modifier .offset { IntOffset( (positionX + centerX).roundToInt(), (positionY + centerY).roundToInt() ) }

Slide 55

Slide 55 text

Drag End ?

Slide 56

Slide 56 text

onDragEnd = { -/ Reset everybody offsetX = centerX offsetY = centerY radius = 0f theta = 0f positionX = 0f positionY = 0f -/ Release everybody navState = NavState.RELEASED if (navKey -= NavKey.UNKNOWN) { releaseAllNavKeys() navKey = NavKey.UNKNOWN } }

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

Part 3. The Best Idea 🀩

Slide 59

Slide 59 text

Handling multiple controls Expected touch behaviour change depending on the different controls

Slide 60

Slide 60 text

Single gamepad state data class InputState( internal val digitalKeys: PersistentSet = persistentSetOf(), internal val directions: PersistentMap = persistentMapOf(), ) { fun setDigitalKey(keyId: Int, value: Boolean): InputState { … } fun getDigitalKey(digitalId: Int): Boolean { return digitalKeys.contains(digitalId) } fun setDirection(directionId: Int, offset: Offset): InputState { … } fun getDirection(directionId: Int, default: Offset = Offset.Unspecified): Offset { return directions.getOrElse(directionId) { default } } }

Slide 61

Slide 61 text

Single input handling ● All inputs are received a single compose function ● Each Control compose function is associated to a Handler ● The handler receives the pointer event if: β—‹ It’s tracking the pointer β—‹ The pointer is currently in its trigger area ● Each handler updates the state and may request to track a pointer id data class Pointer(val pointerId: Long, val position: Offset) data class Result(val inputState: InputState, val dragGestureStart: Pointer? = null) fun handle(pointers: List, inputState: InputState, dragGestureStart: Pointer?): Result

Slide 62

Slide 62 text

Finding the right Handler val gamepadPosition: MutableState val trackedPointers = scope.getTrackedIds() val handlersAssociations: Map = event.changes .asSequence() .filter { it.pressed } .map { Pointer(it.id.value, it.position + gamepadPosition.value) } .groupBy { pointer /> if (pointer.pointerId in trackedPointers) { scope.getHandlerTracking(pointer.pointerId) } else { scope.getHandlerAtPosition(pointer.position) } }

Slide 63

Slide 63 text

Updating the state scope.inputState.value = scope.getAllHandlers().fold(scope.inputState.value) { state, handler /> val pointers = handlersAssociations.getOrElse(handler) { emptyList() } val relativePointers = pointers .map { Pointer(it.pointerId, it.position.relativeTo(handler.rect)) } val (updatedState, updatedTracked) = handler.handle(relativePointers, state, scope.getStartDragGestureForHandler(handler)) scope.setStartGestureForHandler(handler, updatedTracked) updatedState }

Slide 64

Slide 64 text

Writing layouts - Scope class JamPadScope { internal val inputState = mutableStateOf(InputState()) private val handlers = mutableMapOf() --. internal fun registerHandler(handler: Handler) { --. } }

Slide 65

Slide 65 text

Writing Layouts - Controls fun JamPadScope.ControlAnalog(--.){ BoxWithConstraints( modifier = modifier.onGloballyPositioned { registerHandler(AnalogHandler(id, it.boundsInRoot())) }, ) { ... } }

Slide 66

Slide 66 text

Joystick Refined

Slide 67

Slide 67 text

Analog Handling override fun handle(pointers: List, inputState: InputState, startDragGesture: Pointer?): Result { val currentDragGesture = pointers.firstOrNull { it.pointerId -= startDragGesture-.pointerId } return when { pointers.isEmpty() -> { Result(inputState.setDirection(id, Offset.Unspecified), null) } startDragGesture -= null -& currentDragGesture -= null -> { val deltaPosition = (currentDragGesture.position - startDragGesture.position) val offsetValue = deltaPosition.coerceIn(Offset(-1f, -1f), Offset(1f, 1f)) Result(inputState.setDirection(id, offsetValue), startDragGesture) } else -> { val firstPointer = pointers.first() Result(inputState.setDirection(id, Offset.Zero), firstPointer) } } }

Slide 68

Slide 68 text

The Analog Control @Composable fun JamPadScope.ControlAnalog( modifier: Modifier = Modifier, id: Int, background: @Composable () -> Unit = { DefaultControlBackground() }, foreground: @Composable (Boolean) -> Unit = { DefaultButtonForeground(pressed = it, scale = 1f) }, ) { val position = inputState.value.getDirection(id, Offset.Zero) BoxWithConstraints( modifier = modifier .aspectRatio(1f) .onGloballyPositioned { registerHandler(AnalogPointerHandler(id, it.boundsInRoot())) }, contentAlignment = Alignment.Center, ) { Box(modifier = Modifier.fillMaxSize(0.75f)) { background() } Box(modifier = Modifier .fillMaxSize(0.50f) .offset(maxWidth * position.x * 0.25f, maxHeight * position.y * 0.25f), ) { foreground(inputState.value.getDirection(id) -= Offset.Unspecified) } } }

Slide 69

Slide 69 text

Cross Handling enum class State(val position: Offset) { UP(Offset(0f, 1f)), DOWN(Offset(0f, -1f)), LEFT(Offset(-1f, 0f)), RIGHT(Offset(1f, 0f)), UP_LEFT(Offset(-1f, 1f)), UP_RIGHT(Offset(1f, 1f)), DOWN_LEFT(Offset(-1f, -1f)), DOWN_RIGHT(Offset(1f, -1f)), }

Slide 70

Slide 70 text

override fun handle( pointers: List, inputState: InputState, startDragGesture: Pointer?, ): Result { val currentDragGesture = pointers.firstOrNull { it.pointerId -= startDragGesture-.pointerId } return when { pointers.isEmpty() -> { Result( inputState.setDirection(id, Offset.Unspecified), null ) } currentDragGesture -= null -> { Result( inputState.setDirection(id, findCloserState(currentDragGesture)), startDragGesture ) } else -> { val firstPointer = pointers.first() Result( inputState.setDirection(id, findCloserState(firstPointer)), firstPointer ) } } }

Slide 71

Slide 71 text

The Cross Control @Composable fun JamPadScope.ControlCross( modifier: Modifier = Modifier, id: Int, background: @Composable () -> Unit = { DefaultControlBackground() }, foreground: @Composable (Offset) -> Unit = { DefaultCrossForeground(direction = it) }, ) { Box( modifier = modifier .aspectRatio(1f) .onGloballyPositioned { registerHandler(CrossPointerHandler(id, it.boundsInRoot())) }, ) { background() foreground(inputState.value.getDirection(id)) } }

Slide 72

Slide 72 text

Face buttons Face buttons have many faces:

Slide 73

Slide 73 text

Face buttons We need to allow customization Depending on the number of buttons we lay them down in a circle. For each pointer in the circle we compute the closest button.

Slide 74

Slide 74 text

Face buttons fun computeSizeOfItemsOnCircumference(itemsCount: Int): Float { val angle = sin(Constants.PI / maxOf(itemsCount, 2)) return (angle / (1 + angle)) }

Slide 75

Slide 75 text

Composite buttons Some games require you to press two Face Buttons and the same time. We simulate this with composite buttons.

Slide 76

Slide 76 text

Haptics Feeling a button press is very important because the brain needs to register the input happens. We can use Kotlin Multiplatform actual expect mechanism to implement the Android and iOS variants. When the input state changes we try can emit a press or release feedback.

Slide 77

Slide 77 text

Haptics enum class HapticEffect { PRESS, RELEASE, } interface HapticGenerator { fun generate(type: HapticEffect) } @Composable expect fun rememberHapticGenerator(): HapticGenerator

Slide 78

Slide 78 text

iOS Haptics object IosHapticGenerator : HapticGenerator { private val impactFeedbackGenerator = UIImpactFeedbackGenerator() override fun generate(type: HapticEffect) { when (type) { HapticEffect.PRESS -> impactFeedbackGenerator.impactOccurredWithIntensity(0.5) HapticEffect.RELEASE -> impactFeedbackGenerator.impactOccurredWithIntensity(0.3) } } }

Slide 79

Slide 79 text

Android Haptics class AndroidHapticGenerator(applicationContext: Context) : HapticGenerator { … override fun generate(type: HapticEffect) { val effect = when (type) { HapticEffect.PRESS -> strongEffect HapticEffect.RELEASE -> weakEffect } vibrator.vibrate(effect) }

Slide 80

Slide 80 text

A minimal gamepad JamPad( modifier = Modifier.fillMaxSize().aspectRatio(2f), onInputStateUpdated = { … } ) { // Inside JamPad scope… Row(modifier = Modifier.fillMaxSize()) { ControlCross( modifier = Modifier.weight(1f), id = 0 ) ControlFaceButtons( modifier = Modifier.weight(1f), ids = listOf(1, 2, 3) ) } }

Slide 81

Slide 81 text

Introducing JamPadCompose A Virtual Gamepad Library for Kotlin Multiplatform https://github.com/piepacker/JamPadCompose ● The library is still in its early stages of development ● Contributions and feedback are highly welcome to improve the library and expand its capabilities.

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

Epilogue

Slide 84

Slide 84 text

No content

Slide 85

Slide 85 text

No content

Slide 86

Slide 86 text

Thank you πŸ™ Special thanks to @renaud_mathieu @[email protected] renaudmathieu.com @fil @fil fil.com