Skip to content

ProCraft for Android: An Android native painting app written in Rust

Rust

feat(brush): Materials page, sphere pad, slider keypads and source library

Joshf5cb656b5db0
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.kt
index 16683bc..cd2f87b 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.kt
@@ -714,11 +714,18 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Sur
// a tap off the nodes nudges the content a pixel towards it
vm.transformMoved(s.transformNudge(e.x, e.y))
} else if (e.eventTime - tapStart <= TAP_MS) {
- // a tap on a node types its numbers: the rotation handle its angle, the others the size
- when (transformHandle) {
- TransformHandle.Rotate -> vm.transformNumeric = CanvasViewModel.TransformNumeric(true, Offset(downX, downY))
- is TransformHandle.Corner, is TransformHandle.Edge -> vm.transformNumeric = CanvasViewModel.TransformNumeric(false, Offset(downX, downY))
- else -> Unit
+ // a tap on a node types its numbers beside it: the rotation handle its angle, the others the size
+ val shown = vm.transformBox?.let { boxOnScreen(it, vm.viewMatrix, resources.displayMetrics.density) }
+ val node = when (val h = transformHandle) {
+ TransformHandle.Rotate -> shown?.rotate
+ is TransformHandle.Corner -> shown?.corners?.getOrNull(h.index.toInt())
+ is TransformHandle.Edge -> shown?.edges?.getOrNull(h.index.toInt())
+ else -> null
+ }
+ if (shown != null && node != null) {
+ val middle = shown.corners.fold(Offset.Zero) { sum, c -> sum + c } / 4f
+ val right = node.x > middle.x + 1f
+ vm.transformNumeric = CanvasViewModel.TransformNumeric(transformHandle == TransformHandle.Rotate, node, right)
}
}
Mode.NONE -> Unit
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt
index 4e24eb6..cd853a8 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt
@@ -27,6 +27,7 @@ import io.github.artcraftandroid.procraft.core.BrushInfo
import io.github.artcraftandroid.procraft.core.BrushSetInfo
import io.github.artcraftandroid.procraft.core.CanvasSession
import io.github.artcraftandroid.procraft.core.ModelFile
+import io.github.artcraftandroid.procraft.core.SourceKind
import io.github.artcraftandroid.procraft.core.ChromaticKind
import io.github.artcraftandroid.procraft.core.GlitchKind
import io.github.artcraftandroid.procraft.core.GuideInfo
@@ -746,6 +747,8 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
var padColor by mutableStateOf(PAD_WHITE)
private set
var padMenuOpen by mutableStateOf(false)
+ /** Where the pad's Drawing Pad button's middle is across the window (pixels): its menu opens under it. */
+ var padButtonCentre by mutableStateOf(0f)
val blendModeList: List<BlendModeInfo> = blendModes()
/** The modes a brush and its burnt edges blend by, as the studio lists them (the layers' and behind). */
val brushBlendModeList: List<BlendModeInfo> = brushBlendModes()
@@ -3013,16 +3016,25 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
syncPad()
}
- // the studio brush's shape and grain images
+ /** Studio control [key]'s own pressure curve (none while it has none). */
+ fun studioSliderCurve(key: String): List<Offset>? =
+ session?.studioSliderCurve(key)?.takeIf { it.size >= 4 }?.chunked(2) { Offset(it[0], it[1]) }
- /** The images the studio brush's shape and grain use (white on black), for their rows and editors. */
- var studioShapeSource by mutableStateOf<ImageBitmap?>(null)
- private set
- var studioGrainSource by mutableStateOf<ImageBitmap?>(null)
+ /** Gives studio control [key] its own pressure curve through [points], or takes it away (none). */
+ fun setStudioSliderCurve(key: String, points: List<Offset>?) {
+ session?.setStudioSliderCurve(key, points?.flatMap { listOf(it.x, it.y) } ?: emptyList())
+ refreshStudioPreview()
+ syncPad()
+ }
+
+ // the studio brush's shape, grain and material images
+
+ /** The images the studio brush's sources use (white on black), by kind, for their rows; none for the round tip, no grain or a material's amount all over. */
+ var studioSources by mutableStateOf<Map<SourceKind, ImageBitmap>>(emptyMap())
private set
- /** The shape (false) or grain (true) editor is open. */
- var sourceEditing by mutableStateOf<Boolean?>(null)
+ /** The editor open for the studio brush's source of this kind, if one is. */
+ var sourceEditing by mutableStateOf<SourceKind?>(null)
/** The shipped shape and grain images, by name, for the source library. */
val shapeLibrary by lazy { io.github.artcraftandroid.procraft.core.sourceLibrary(false).map { it.name to grayBitmap(it.pixels) } }
@@ -3030,18 +3042,13 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
private fun readStudioSources() {
val s = session ?: return
- val shape = sourceBitmap(s.studioSource(false), shape = true)
- val grain = sourceBitmap(s.studioSource(true), shape = false)
- studioShapeSource = shape?.let { small(it, SOURCE_ROW_PX) }
- studioGrainSource = grain?.let { small(it, SOURCE_ROW_PX) }
- studioShapeSourceBig = shape?.let { small(it, SOURCE_BOX_PX) }
- studioGrainSourceBig = grain?.let { small(it, SOURCE_BOX_PX) }
+ val images = SourceKind.entries.mapNotNull { k -> sourceBitmap(s.studioSource(k), shape = k == SourceKind.SHAPE)?.let { k to it } }
+ studioSources = images.associate { (k, b) -> k to small(b, SOURCE_ROW_PX) }
+ studioSourcesBig = images.associate { (k, b) -> k to small(b, SOURCE_BOX_PX) }
}
/** The same images as big as the landscape studio's square shows them. */
- var studioShapeSourceBig by mutableStateOf<ImageBitmap?>(null)
- private set
- var studioGrainSourceBig by mutableStateOf<ImageBitmap?>(null)
+ var studioSourcesBig by mutableStateOf<Map<SourceKind, ImageBitmap>>(emptyMap())
private set
/** [image] shrunk by halves to about [side] pixels across, each step averaging, so fine detail evens out. */
@@ -3059,8 +3066,8 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
return Bitmap.createBitmap(argb, n, n, Bitmap.Config.ARGB_8888).asImageBitmap()
}
- /** The image the studio brush's shape (or [grain]) uses now: square greyscale, white = paint; empty for the round tip. */
- fun studioSourcePixels(grain: Boolean): ByteArray = session?.studioSource(grain) ?: ByteArray(0)
+ /** The image the studio brush's [kind] of source uses now: square greyscale, white = paint; empty for the round tip, no grain or the amount all over. */
+ fun studioSourcePixels(kind: SourceKind): ByteArray = session?.studioSource(kind) ?: ByteArray(0)
/** [pixels] made to repeat without seams (the grain editor's Auto repeat). */
fun repeatSource(pixels: ByteArray, scale: Float, rotation: Float, overlap: Float, hardness: Float, mirror: Boolean, pyramid: Boolean): ByteArray =
@@ -3127,12 +3134,12 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
return decodeSource(uri)
}
- /** The editor's tick: the studio brush's shape (or [grain]) becomes [pixels], or shipped image [shipped]. */
- fun keepStudioSource(grain: Boolean, pixels: ByteArray, shipped: Int?) {
+ /** The editor's tick: the studio brush's [kind] of source becomes [pixels], or shipped image [shipped]. */
+ fun keepStudioSource(kind: SourceKind, pixels: ByteArray, shipped: Int?) {
val s = session ?: return
val changed = when {
- shipped != null -> s.setStudioShippedSource(grain, shipped.toUInt())
- pixels.isNotEmpty() -> s.setStudioSource(grain, pixels)
+ shipped != null -> s.setStudioShippedSource(kind, shipped.toUInt())
+ pixels.isNotEmpty() -> s.setStudioSource(kind, pixels)
else -> false
}
sourceEditing = null
@@ -3153,11 +3160,34 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
syncPad()
}
- /** The pad has drawn its first frame: it shows the brush's sample scribble. */
+ /**
+ * The pad has drawn its first frame: it shows the brush's sample scribble, flat or on the sphere
+ * (drawn again here: a sphere asked for before now had nothing to draw on).
+ */
fun padReady(p: CanvasSession) {
- if (pad === p) p.drawSampleScribble()
+ if (pad !== p) return
+ p.showSphere(padSphere)
+ p.drawSampleScribble()
}
+ /** The pad shown as a sphere with the brush's materials (the Materials page, or the 3D preview on). */
+ var padSphere = false
+ private set
+
+ fun showPadSphere(shown: Boolean) {
+ padSphere = shown
+ pad?.showSphere(shown)
+ }
+
+ /** The pad menu's 3D preview: the pad a sphere on every page, kept from one session to the next. */
+ private var pad3dState by mutableStateOf(interfacePrefs.getBoolean(PAD_3D, false))
+ var pad3d: Boolean
+ get() = pad3dState
+ set(on) {
+ pad3dState = on
+ interfacePrefs.edit().putBoolean(PAD_3D, on).apply()
+ }
+
/** The pad paints with the brush as it is now, and what is on it is drawn again that way. */
private fun syncPad() {
val p = pad ?: return
@@ -4055,6 +4085,13 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
return index
}
+ /** Takes point [index] off the channel shown (the curve keeps two at least). */
+ fun deleteCurvePoint(index: Int) {
+ val pts = curves[curveChannel]
+ if (index !in pts.indices || pts.size <= 2) return
+ setCurve(pts.filterIndexed { k, _ -> k != index })
+ }
+
private fun setCurve(points: List<Offset>) {
curves = curves.toMutableList().also { it[curveChannel] = points }
val flat = curves.map { c -> c.flatMap { listOf(it.x, it.y) } }
@@ -4620,8 +4657,11 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
if (box != null) transformBox = box
}
- /** Numeric entry open beside window point [at]: for the box's angle (the rotation handle) or its size. */
- data class TransformNumeric(val angle: Boolean, val at: Offset)
+ /**
+ * Numeric entry open beside the node at window point [at]: for the box's angle (the rotation
+ * handle) or its size; to the node's right when it is on the box's right side ([right]), else to its left.
+ */
+ data class TransformNumeric(val angle: Boolean, val at: Offset, val right: Boolean = false)
var transformNumeric by mutableStateOf<TransformNumeric?>(null)
@@ -5158,6 +5198,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
const val COLOR_MODE = "color_mode"
const val ACTIONS_TAB = "actions_tab"
const val STUDIO_TAB = "studio_tab"
+ const val PAD_3D = "pad_3d_preview"
const val RAPID_UNDO_DELAY = "rapid_undo_delay"
const val LIGHT_INTERFACE = "light_interface"
const val BRUSH_CURSOR = "brush_cursor"
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ActionsPanel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ActionsPanel.kt
index 7f636ee..8788b1c 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ActionsPanel.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ActionsPanel.kt
@@ -699,7 +699,7 @@ private fun ActionRowContent(row: ActionRow) {
* into a clear lens as it slides across, the track's colour fading under it, then settles white.
*/
@Composable
-internal fun Switch(checked: Boolean, enabled: Boolean, fixedTrack: Color = Pc.SwitchFixed, fixedKnob: Color = Pc.SwitchFixedKnob) {
+internal fun Switch(checked: Boolean, enabled: Boolean, fixedTrack: Color = Pc.SwitchFixed, fixedKnob: Color = Pc.SwitchFixedKnob, offTrack: Color = Pc.SwitchOff) {
val on = androidx.compose.animation.core.animateFloatAsState(if (checked) 1f else 0f, Motion.switchKnob(), label = "knob").value
val lens = remember { androidx.compose.animation.core.Animatable(0f) }
var flipped by remember { mutableStateOf(false) }
@@ -714,7 +714,7 @@ internal fun Switch(checked: Boolean, enabled: Boolean, fixedTrack: Color = Pc.S
lens.animateTo(0f, Motion.switchSettle())
}
val g = lens.value
- val track = if (!enabled) fixedTrack else androidx.compose.ui.graphics.lerp(Pc.SwitchOff, Pc.Accent, on)
+ val track = if (!enabled) fixedTrack else androidx.compose.ui.graphics.lerp(offTrack, Pc.Accent, on)
// not clipped to the track: the swollen knob spills over it
Box(Modifier.size(63.dp, 28.dp)) {
Box(Modifier.matchParentSize().clip(CircleShape).background(track))
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.kt
index 8b4ec37..295d7a3 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.kt
@@ -20,6 +20,8 @@ import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
@@ -308,7 +310,10 @@ private fun BalanceRow(left: String, right: String, value: Float, track: Brush,
}
}
-/** The curves panel: the chosen channel's curve over a grid (drag its points; touch elsewhere to add one), and the channels. */
+/**
+ * The curves panel: the chosen channel's curve over a grid (drag its points; touch elsewhere to add
+ * one; tap a point for Delete over it), and the channels.
+ */
@Composable
fun CurvesPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {
Row(
@@ -316,24 +321,34 @@ fun CurvesPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
val points = vm.curves[vm.curveChannel]
+ // the point whose Delete shows, and the graph's size for placing it
+ var tapped by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<Int?>(null) }
+ var graph by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(androidx.compose.ui.unit.IntSize.Zero) }
Box(
- Modifier.weight(1f).fillMaxHeight().padding(8.dp).pointerInput(vm.curveChannel) {
+ Modifier.weight(1f).fillMaxHeight().padding(8.dp).onSizeChanged { graph = it }.pointerInput(vm.curveChannel) {
awaitEachGesture {
val down = awaitFirstDown()
down.consume()
+ tapped = null
val w = size.width.toFloat()
val h = size.height.toFloat()
fun toCurve(p: Offset) = Offset((p.x / w).coerceIn(0f, 1f), (1f - p.y / h).coerceIn(0f, 1f))
val reach = 22.dp.toPx()
val current = vm.curves[vm.curveChannel]
var index = current.indexOfFirst { (Offset(it.x * w, (1f - it.y) * h) - down.position).getDistance() <= reach }
- if (index < 0) index = vm.addCurvePoint(toCurve(down.position))
+ val added = index < 0
+ if (added) index = vm.addCurvePoint(toCurve(down.position))
+ var moved = false
while (true) {
val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break
if (!c.pressed) break
+ if (!moved && (c.position - down.position).getDistance() < viewConfiguration.touchSlop) continue
+ moved = true
index = vm.moveCurvePoint(index, toCurve(c.position))
c.consume()
}
+ // a tap on a point: Delete over it
+ if (!moved && !added) tapped = index
}
}.drawBehind {
val w = size.width
@@ -348,7 +363,28 @@ fun CurvesPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {
}
for (p in points) node(Offset(p.x * w, (1f - p.y) * h), CurveNode, 1f)
},
- )
+ ) {
+ tapped?.let { i -> points.getOrNull(i) }?.let { p ->
+ // a pill 78 x 44 over the point, its bottom 14 above it
+ val at = with(androidx.compose.ui.platform.LocalDensity.current) {
+ androidx.compose.ui.unit.IntOffset(
+ (p.x * graph.width - 39.dp.toPx()).roundToInt(),
+ ((1f - p.y) * graph.height - (14 + 44).dp.toPx()).roundToInt(),
+ )
+ }
+ PcPopup(offset = at, onDismissRequest = { tapped = null }, properties = androidx.compose.ui.window.PopupProperties(focusable = true, clippingEnabled = false)) {
+ Box(
+ Modifier.size(78.dp, 44.dp).clip(CircleShape).background(CurveMenuFill).tap {
+ tapped?.let(vm::deleteCurvePoint)
+ tapped = null
+ },
+ contentAlignment = Alignment.Center,
+ ) {
+ Text("Delete", color = Color.White, fontSize = 17.sp, maxLines = 1)
+ }
+ }
+ }
+ }
Column(Modifier.width(111.dp).fillMaxHeight().clip(RoundedCornerShape(13.dp)), verticalArrangement = Arrangement.spacedBy(1.dp)) {
listOf("Gamma", "Red", "Green", "Blue").forEachIndexed { i, name ->
val chosen = vm.curveChannel == i
@@ -361,6 +397,8 @@ fun CurvesPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {
}
private val CurveNode = Color(0xFF0171EA)
+/** The Delete pill over a tapped point. */
+private val CurveMenuFill = Color(0xFF262626)
/**
* The gradient map panel: the gradient library (a tap chooses one, a tap on the chosen one edits
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.kt
index 6c34b4d..80c4e23 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.kt
@@ -270,7 +270,7 @@ fun AppRoot(vm: CanvasViewModel) {
GuideEditor(vm)
LightingStudio(vm)
BrushStudio(vm)
- PadMenu(vm)
+ PadMenu(vm, maxWidth)
}
}
}
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushStudio.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushStudio.kt
index 783340a..c651990 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushStudio.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/BrushStudio.kt
@@ -35,6 +35,7 @@ import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
@@ -57,7 +58,9 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import io.github.artcraftandroid.procraft.canvas.CanvasViewModel
import io.github.artcraftandroid.procraft.canvas.PadSurfaceView
+import io.github.artcraftandroid.procraft.core.SourceKind
import io.github.artcraftandroid.procraft.core.curveSamples
+import io.github.artcraftandroid.procraft.core.sliderExtras
import kotlin.math.pow
import kotlin.math.roundToInt
import androidx.compose.ui.unit.IntRect
@@ -70,6 +73,7 @@ import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.draw.shadow
+import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.ui.platform.LocalDensity
@@ -119,9 +123,10 @@ private val TabsWidth = 81.dp
/**
* How a slider reads; [SIZE] reads the size the control sets (the brush's most size × place^2.2) as a
* percent (Max at the control's end), [BOTH] goes both ways from 0% in its middle, -100% to Max (and
- * [FOLLOW] and [GRADE] to a name of their own), [DOUBLE] reads 100% at its middle.
+ * [FOLLOW] and [GRADE] to a name of their own), [DOUBLE] reads 100% at its middle; [METAL] and
+ * [GLOSS] name their ends as a material's metalness and roughness.
*/
-enum class Shown { PERCENT, BOTH, COUNT, TIP, MOVEMENT, ZOOM, CHARGE, ZERO, SIZE, FOLLOW, GRADE, DOUBLE, TWICE }
+enum class Shown { PERCENT, BOTH, COUNT, TIP, MOVEMENT, ZOOM, CHARGE, ZERO, SIZE, FOLLOW, GRADE, DOUBLE, TWICE, METAL, GLOSS }
/** One control in the brush studio. */
sealed class StudioControl {
@@ -138,10 +143,12 @@ sealed class StudioControl {
data object TiltAngle : StudioControl()
/** The shape's roundness and angle on an ellipse with handles. */
data object Roundness : StudioControl()
- class Source(val label: String) : StudioControl()
+ /** The brush's [kind] of source image, opening its editor. */
+ class Source(val label: String, val kind: SourceKind) : StudioControl()
/** A blend mode, kept by the engine's number for it, picked from a list. */
class Picker(val key: String, val label: String) : StudioControl()
- class Disclosure(val label: String) : StudioControl()
+ /** A card that a tap on its title opens to show [controls] inside it. */
+ class Disclosure(val label: String, val controls: List<StudioControl>) : StudioControl()
data object PreviewCard : StudioControl()
data object About : StudioControl()
}
@@ -188,7 +195,7 @@ val STUDIO_TABS: List<StudioTab> by lazy {
StudioSection("Taper properties", listOf(toggle("classic_taper", "Classic taper"))),
)),
StudioTab("Shape", PcIcons.StudioShape, 45.dp, listOf(
- StudioSection(null, listOf(StudioControl.Source("Shape Source"))),
+ StudioSection(null, listOf(StudioControl.Source("Shape Source", SourceKind.SHAPE))),
StudioSection("Input style", listOf(
StudioControl.Choice("input_style", listOf("Touch only", "Azimuth", "Azimuth and barrel roll")),
// only with the barrel roll to follow
@@ -205,7 +212,7 @@ val STUDIO_TABS: List<StudioTab> by lazy {
StudioSection("Shape filtering", listOf(StudioControl.Choice("shape_filtering", FILTERING))),
)),
StudioTab("Grain", PcIcons.StudioGrain, 45.dp, listOf(
- StudioSection(null, listOf(StudioControl.Source("Grain Source"))),
+ StudioSection(null, listOf(StudioControl.Source("Grain Source", SourceKind.GRAIN))),
StudioSection("Grain behavior", listOf(
StudioControl.Kinds("grain_behavior", listOf(PcIcons.GrainMoving to "Moving", PcIcons.GrainTexturized to "Texturized")),
slider("grain_movement", "Movement", Shown.MOVEMENT), slider("grain_scale", "Scale"), slider("grain_zoom", "Zoom", Shown.ZOOM),
@@ -276,7 +283,16 @@ val STUDIO_TABS: List<StudioTab> by lazy {
)),
)),
StudioTab("Materials", PcIcons.StudioMaterials, 29.dp, listOf(
- StudioSection("3D Materials", listOf(StudioControl.Disclosure("Metallic"), StudioControl.Disclosure("Roughness"))),
+ StudioSection("3D Materials", listOf(
+ StudioControl.Disclosure("Metallic", listOf(
+ slider("metallic_amount", "Amount", Shown.METAL), StudioControl.Source("Metallic Source", SourceKind.METALLIC),
+ slider("metallic_scale", "Scale"),
+ )),
+ StudioControl.Disclosure("Roughness", listOf(
+ slider("roughness_amount", "Amount", Shown.GLOSS), StudioControl.Source("Roughness Source", SourceKind.ROUGHNESS),
+ slider("roughness_scale", "Scale"),
+ )),
+ )),
)),
StudioTab("Preview", PcIcons.StudioPreview, 45.dp, listOf(
StudioSection("Preview render", listOf(StudioControl.PreviewCard)),
@@ -292,9 +308,10 @@ val STUDIO_TABS: List<StudioTab> by lazy {
/** Every key the studio's controls read. */
val STUDIO_KEYS: List<String> by lazy {
- STUDIO_TABS.flatMap { t -> t.sections.flatMap { s -> s.controls } }.flatMap { c ->
+ STUDIO_TABS.flatMap { t -> t.sections.flatMap { s -> s.controls } }.flatMap { c -> if (c is StudioControl.Disclosure) c.controls else listOf(c) }.flatMap { c ->
when (c) {
- is StudioControl.Slider -> listOf(c.key)
+ // a slider's own tilt switch and angle, which its keypad shows
+ is StudioControl.Slider -> sliderExtras(c.key).let { e -> listOf(c.key, e.tiltSwitch, e.tiltAngle).filter { it.isNotEmpty() } }
is StudioControl.Toggle -> listOf(c.key)
is StudioControl.Choice -> listOf(c.key)
is StudioControl.Kinds -> listOf(c.key)
@@ -464,6 +481,8 @@ private fun shownValue(v: Float, shown: Shown, most: Float = 16f): String {
Shown.MOVEMENT -> if (v <= 0f) "Stamp" else if (v >= 1f) "Rolling" else between
Shown.ZOOM -> if (v <= 0f) "Follow size" else if (v >= 1f) "Cropped" else between
Shown.CHARGE -> if (v <= 0f) "Disabled" else if (v >= 1f) "Max" else between
+ Shown.METAL -> if (v <= 0f) "Non-Metallic" else if (v >= 1f) "Metallic" else between
+ Shown.GLOSS -> if (v <= 0f) "Glossy" else if (v >= 1f) "Matte" else between
Shown.SIZE -> {
val size = most * v.coerceIn(0f, 1f).toDouble().pow(2.2).toFloat()
// Max only at the control's end: a size of more than a unit reads as its percent
@@ -565,11 +584,15 @@ private fun StudioPagesCard(vm: CanvasViewModel) {
private fun StudioPad(vm: CanvasViewModel, modifier: Modifier) {
// the pad's own colour behind its surface, so the canvas doesn't show through before the
// pad's first frame (as the studio slides up)
+ // a sphere showing the brush's materials on their page, or on every page with the 3D preview on
+ val sphere = STUDIO_TABS.getOrNull(vm.studioTab)?.name == "Materials" || vm.pad3d
+ androidx.compose.runtime.LaunchedEffect(sphere) { vm.showPadSphere(sphere) }
Box(modifier.background(PadBehind)) {
androidx.compose.ui.viewinterop.AndroidView(factory = { PadSurfaceView(it, vm) }, modifier = Modifier.fillMaxSize())
// drawn over the surface's hole until the pad has a frame of its own
if (!vm.padShown) Box(Modifier.fillMaxSize().background(PadBehind))
- Row(Modifier.offset(21.dp, 21.dp).height(43.dp).clip(CircleShape).background(StudioButton).border(1.dp, StudioButtonEdge, CircleShape)
+ Row(Modifier.offset(21.dp, 21.dp).height(43.dp).onGloballyPositioned { vm.padButtonCentre = it.boundsInWindow().center.x }
+ .clip(CircleShape).background(StudioButton).border(1.dp, StudioButtonEdge, CircleShape)
.tap { vm.padMenuOpen = !vm.padMenuOpen }.padding(start = 9.dp, end = 13.dp),
verticalAlignment = Alignment.CenterVertically) {
Icon(PcIcons.StudioPad, contentDescription = null, tint = StudioButtonInk, modifier = Modifier.size(26.dp))
@@ -619,7 +642,8 @@ private fun StudioControlView(vm: CanvasViewModel, c: StudioControl) {
when (c) {
is StudioControl.Slider -> {
val enabled = c.enabledBy?.let { (key, choice) -> vm.studio(key).roundToInt() == choice } ?: true
- StudioSlider(c.label, vm.studio(c.key), c.shown, most = if (c.shown == Shown.SIZE) vm.studio("most_size") else 16f, enabled = enabled) { vm.setStudio(c.key, it) }
+ val extras = remember(c.key) { keypadExtras(vm, c.key) }
+ StudioSlider(c.label, vm.studio(c.key), c.shown, most = if (c.shown == Shown.SIZE) vm.studio("most_size") else 16f, enabled = enabled, extras = extras) { vm.setStudio(c.key, it) }
}
// a long name runs on under the switch, which is drawn over it
is StudioControl.Toggle -> Box(Modifier.fillMaxWidth().height(47.dp).padding(start = 8.dp)) {
@@ -682,26 +706,20 @@ private fun StudioControlView(vm: CanvasViewModel, c: StudioControl) {
StudioControl.Roundness -> RoundnessGraph(vm.studio("roundness"), vm.studio("shape_angle"), onRoundness = { vm.setStudio("roundness", it) }, onAngle = { vm.setStudio("shape_angle", it) })
is StudioControl.Source -> if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE) SourceBox(vm, c) else Row(
Modifier.fillMaxWidth().height(60.dp).clip(RoundedCornerShape(12.dp)).background(StudioCard)
- .tap { vm.sourceEditing = c.label.startsWith("Grain") }.padding(start = 16.dp, end = 8.dp),
+ .tap { vm.sourceEditing = c.kind }.padding(start = 16.dp, end = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(c.label, color = StudioHeader, fontSize = 19.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.weight(1f))
- // the image it uses: the shape white on the row (the round tip a white disc), the grain as its greys
- val image = if (c.label.startsWith("Grain")) vm.studioGrainSource else vm.studioShapeSource
- Box(Modifier.size(44.dp).clip(RoundedCornerShape(10.dp)).then(if (image == null) Modifier.clip(CircleShape).background(Color.White) else Modifier)) {
+ // the image it uses: the shape white on the row (the round tip a white disc), the grain as its greys, a
+ // material's amount all over as white
+ val image = vm.studioSources[c.kind]
+ val plain = if (c.kind.material()) Modifier.background(Color.White) else Modifier.clip(CircleShape).background(Color.White)
+ Box(Modifier.size(44.dp).clip(RoundedCornerShape(10.dp)).then(if (image == null) plain else Modifier)) {
image?.let { Image(it, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }
}
}
is StudioControl.Picker -> BlendPicker(vm, c)
- is StudioControl.Disclosure -> Row(
- Modifier.fillMaxWidth().height(60.dp).clip(RoundedCornerShape(20.dp)).background(StudioMaterial).padding(start = 16.dp, end = 16.dp),
- verticalAlignment = Alignment.CenterVertically,
- ) {
- Text(c.label, color = StudioMaterialInk, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = Modifier.weight(1f))
- Box(Modifier.size(30.dp).clip(CircleShape).background(StudioBack), contentAlignment = Alignment.Center) {
- Icon(PcIcons.ChevronRight, contentDescription = null, tint = Color.White, modifier = Modifier.size(16.dp))
- }
- }
+ is StudioControl.Disclosure -> DisclosureCard(vm, c)
// the brush's stroke filling the card's height, its name over it on a patch of the card's own colour
StudioControl.PreviewCard -> Box(
Modifier.fillMaxWidth()
@@ -783,14 +801,43 @@ private fun AboutBrush(vm: CanvasViewModel) {
}
}
+/** Whether this is a material's source (white all over when it has no image). */
+private fun SourceKind.material() = this == SourceKind.METALLIC || this == SourceKind.ROUGHNESS
+
+/**
+ * A card titled [StudioControl.Disclosure.label] that a tap on its title opens, its chevron turned
+ * down, to show its controls inside it, 8 in from its sides and spaced as a page's are; the page
+ * opens with it closed.
+ */
+@Composable
+private fun DisclosureCard(vm: CanvasViewModel, c: StudioControl.Disclosure) {
+ var open by remember { mutableStateOf(false) }
+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(20.dp)).background(StudioMaterial)) {
+ Row(
+ Modifier.fillMaxWidth().height(60.dp).tap { open = !open }.padding(start = 16.dp, end = 16.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(c.label, color = StudioMaterialInk, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = Modifier.weight(1f))
+ Box(Modifier.size(30.dp).clip(CircleShape).background(StudioBack), contentAlignment = Alignment.Center) {
+ Icon(PcIcons.ChevronRight, contentDescription = null, tint = Color.White, modifier = Modifier.size(16.dp).rotate(if (open) 90f else 0f))
+ }
+ }
+ if (open) Column(Modifier.padding(start = 8.dp, end = 8.dp, top = 12.dp, bottom = 8.dp)) {
+ c.controls.forEachIndexed { i, control ->
+ c.controls.getOrNull(i - 1)?.let { Spacer(Modifier.height(gap(it, control))) }
+ StudioControlView(vm, control)
+ }
+ }
+ }
+}
+
/**
* Landscape: a source as a title with an Edit button, over a square of its image as wide as the
- * rows (the shape white on dark, the grain as its greys).
+ * rows (the shape white on dark, the grain as its greys, a material's amount all over white).
*/
@Composable
private fun SourceBox(vm: CanvasViewModel, c: StudioControl.Source) {
- val grain = c.label.startsWith("Grain")
- val open = { vm.sourceEditing = grain }
+ val open = { vm.sourceEditing = c.kind }
Column(Modifier.fillMaxWidth()) {
Box(Modifier.fillMaxWidth().padding(top = 8.5.dp).height(45.dp)) {
// where a section's title sits
@@ -802,11 +849,12 @@ private fun SourceBox(vm: CanvasViewModel, c: StudioControl.Source) {
}
}
Spacer(Modifier.height(12.5.dp))
- val image = if (grain) vm.studioGrainSourceBig else vm.studioShapeSourceBig
- Box(Modifier.fillMaxWidth().aspectRatio(1f).clip(RoundedCornerShape(22.dp)).background(StudioButton).tap { open() }) {
+ val image = vm.studioSourcesBig[c.kind]
+ val white = image == null && c.kind.material()
+ Box(Modifier.fillMaxWidth().aspectRatio(1f).clip(RoundedCornerShape(22.dp)).background(if (white) Color.White else StudioButton).tap { open() }) {
image?.let { Image(it, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }
- // the round tip: a white disc
- ?: Box(Modifier.fillMaxSize(0.7f).align(Alignment.Center).clip(CircleShape).background(Color.White))
+ // the round tip: a white disc
+ if (image == null && !white) Box(Modifier.fillMaxSize(0.7f).align(Alignment.Center).clip(CircleShape).background(Color.White))
}
}
}
@@ -822,12 +870,17 @@ private val PadMenuGroup = Color(0xFFD3D3D3)
private val PadMenuText = Color(0xFF393939)
private val PadMenuLine = Color(0xFFBDBDBD)
-/** The drawing pad's settings: preview size, the pad's colour, and clearing or resetting. */
+/**
+ * The drawing pad's settings: preview size, the pad's colour, and clearing or resetting. It opens
+ * under the Drawing Pad button, centred on it but kept 14 in from the screen's sides ([width]).
+ */
@Composable
-fun PadMenu(vm: CanvasViewModel) {
+fun PadMenu(vm: CanvasViewModel, width: Dp) {
if (!vm.studioOpen || !vm.padMenuOpen) return
+ val centre = with(androidx.compose.ui.platform.LocalDensity.current) { vm.padButtonCentre.toDp() }
+ val left = (centre - 160.dp).coerceIn(14.dp, (width - 334.dp).coerceAtLeast(14.dp))
Column(
- Modifier.offset(14.dp, 79.dp).width(320.dp).clip(RoundedCornerShape(26.dp)).background(PadMenuFill).padding(start = 10.dp, end = 10.dp, top = 17.dp, bottom = 10.dp),
+ Modifier.offset(left, 79.dp).width(320.dp).clip(RoundedCornerShape(26.dp)).background(PadMenuFill).padding(start = 10.dp, end = 10.dp, top = 17.dp, bottom = 10.dp),
) {
Text("Settings", color = PadMenuText, fontSize = 22.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 12.dp))
Spacer(Modifier.height(18.dp))
@@ -851,9 +904,12 @@ fun PadMenu(vm: CanvasViewModel) {
Text("Stylus", color = PadMenuText, fontSize = 17.sp, maxLines = 1)
}
Box(Modifier.fillMaxWidth().height(1.dp).background(PadMenuLine))
- Row(Modifier.fillMaxWidth().height(45.dp).padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
+ Row(
+ Modifier.fillMaxWidth().height(45.dp).tap { vm.pad3d = !vm.pad3d }.padding(start = 16.dp, end = 8.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
Text("3D preview", color = PadMenuText, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))
- Switch(false, enabled = true)
+ Switch(vm.pad3d, enabled = true)
}
}
Spacer(Modifier.height(10.dp))
@@ -899,14 +955,54 @@ private fun PadSizeSlider(value: Float, onChange: (Float) -> Unit) {
)
}
+/**
+ * What a slider's keypad offers besides typing: its own pressure curve ([curve], none while off) and
+ * its own tilt (its switch, if it has one, and the angle the tilt starts from, 0..1 of a quarter
+ * turn). Each setter changes the brush at once.
+ */
+class KeypadExtras(
+ val pressure: Boolean,
+ val curve: () -> List<Offset>?,
+ val setCurve: (List<Offset>?) -> Unit,
+ val tilt: Boolean,
+ val tiltOn: () -> Boolean?,
+ val setTiltOn: (Boolean) -> Unit,
+ val tiltAngle: () -> Float,
+ val setTiltAngle: (Float) -> Unit,
+)
+
+/** What studio control [key]'s keypad offers besides typing, as its brush holds it; none if nothing. */
+private fun keypadExtras(vm: CanvasViewModel, key: String): KeypadExtras? {
+ val e = sliderExtras(key)
+ if (!e.pressure && !e.tilt) return null
+ return KeypadExtras(
+ pressure = e.pressure,
+ curve = { vm.studioSliderCurve(key) },
+ setCurve = { vm.setStudioSliderCurve(key, it) },
+ tilt = e.tilt,
+ tiltOn = { e.tiltSwitch.takeIf { it.isNotEmpty() }?.let { vm.studio(it) >= 0.5f } },
+ setTiltOn = { on -> if (e.tiltSwitch.isNotEmpty()) vm.setStudio(e.tiltSwitch, if (on) 1f else 0f) },
+ tiltAngle = { vm.studio(e.tiltAngle) },
+ setTiltAngle = { vm.setStudio(e.tiltAngle, it) },
+ )
+}
+
/** A labelled slider with its value in a pill: blue up to the knob, or out from the middle both ways. */
@Composable
-internal fun StudioSlider(label: String, value: Float, shown: Shown, most: Float = 16f, enabled: Boolean = true, onChange: (Float) -> Unit) {
+internal fun StudioSlider(
+ label: String,
+ value: Float,
+ shown: Shown,
+ most: Float = 16f,
+ enabled: Boolean = true,
+ extras: KeypadExtras? = null,
+ onChange: (Float) -> Unit,
+) {
val change by rememberUpdatedState(onChange)
val current by rememberUpdatedState(value)
val both = shown == Shown.BOTH || shown == Shown.FOLLOW || shown == Shown.GRADE
// a tap on the value types it on a keypad beside it (the pill blue meanwhile)
- val typed = typedNumber(shown)
+ val typed = typedNumber(shown, most)
var typing by remember { mutableStateOf(false) }
var pill by remember { mutableStateOf(androidx.compose.ui.geometry.Rect.Zero) }
Column(Modifier.fillMaxWidth().height(55.dp)) {
@@ -917,12 +1013,12 @@ internal fun StudioSlider(label: String, value: Float, shown: Shown, most: Float
Box(
Modifier.height(28.dp).widthIn(min = 73.dp).onGloballyPositioned { pill = it.boundsInWindow() }.clip(RoundedCornerShape(14.dp))
.background(if (typing) Pc.Accent else if (enabled) StudioPill else StudioPillOff)
- .then(if (enabled && typed != null) Modifier.tap { typing = true } else Modifier)
+ .then(if (enabled) Modifier.tap { typing = true } else Modifier)
.padding(horizontal = 13.dp),
contentAlignment = Alignment.Center,
) {
Text(shownValue(value, shown, most), color = if (typing) Color.White else if (enabled) StudioLabel else StudioValueOff, fontSize = 16.sp, maxLines = 1, softWrap = false)
- if (typing && typed != null) SliderKeypad(label, pill, typed.first, typed.second, { change(it) }) { typing = false }
+ if (typing) SliderKeypad(label, pill, typed, { change(it) }, extras) { typing = false }
}
}
Box(
@@ -964,13 +1060,21 @@ internal fun StudioSlider(label: String, value: Float, shown: Shown, most: Float
}
/**
- * How a slider's value can be typed: the largest number and what a number makes of the value (a
- * percent of the slider, or of its doubled scale); none for the others.
+ * How a slider's value is typed: the largest number, whether it may be negative (a "-" key), and what
+ * a number makes of the value.
+ */
+private class Typed(val most: Int, val signed: Boolean, val toValue: (Int) -> Float)
+
+/**
+ * A slider's [Typed]: a percent of the slider (or of its doubled scale), both ways for the controls
+ * going both ways, the count itself, or for a size the percent the slider reads (of [most]).
*/
-private fun typedNumber(shown: Shown): Pair<Int, (Int) -> Float>? = when (shown) {
- Shown.PERCENT, Shown.ZERO, Shown.TIP, Shown.MOVEMENT, Shown.ZOOM, Shown.CHARGE -> 100 to { n -> n / 100f }
- Shown.DOUBLE, Shown.TWICE -> 200 to { n -> n / 200f }
- else -> null
+private fun typedNumber(shown: Shown, most: Float): Typed = when (shown) {
+ Shown.PERCENT, Shown.ZERO, Shown.TIP, Shown.MOVEMENT, Shown.ZOOM, Shown.CHARGE, Shown.METAL, Shown.GLOSS -> Typed(100, false) { n -> n / 100f }
+ Shown.DOUBLE, Shown.TWICE -> Typed(200, false) { n -> n / 200f }
+ Shown.BOTH, Shown.FOLLOW, Shown.GRADE -> Typed(100, true) { n -> n / 100f }
+ Shown.COUNT -> Typed(16, false) { n -> (n.coerceAtLeast(1) - 1) / 15f }
+ Shown.SIZE -> Typed((most * 100f).roundToInt(), false) { n -> ((n / 100f) / most.coerceAtLeast(1e-3f)).coerceIn(0f, 1f).toDouble().pow(1.0 / 2.2).toFloat() }
}
private val KeypadFill = Color(0xFFD5D5D5)
@@ -978,26 +1082,67 @@ private val KeypadKey = Color(0xFFE6E6E6)
private val KeypadInk = Color(0xFF1D1D1D)
private val KeypadWidth = 275.dp
private val KeypadHeight = 360.dp
+/**
+ * With pages to choose between, the tabs under the title push the keys down, 64 tall: the popover
+ * is 410 tall with two tabs, 386 with three (as the reference's measure).
+ */
+private fun keypadHeight(tabs: Int) = when (tabs) {
+ 1 -> KeypadHeight
+ 2 -> 410.dp
+ else -> 386.dp
+}
+private fun keypadKeyHeight(tabs: Int) = if (tabs > 1) 64.dp else 66.dp
+private val KeypadTabs = Color(0xFFC1C1C1)
+private val KeypadTabChosen = Color(0xFF0A8CFD)
+private val KeypadTabInk = Color(0xFF393939)
+private val KeypadGraph = Color(0xFFE2E2E2)
+private val KeypadGraphEdge = Color(0xFF999999)
+private val KeypadGraphGrid = Color(0xFFD0D0D0)
+private val KeypadSwitchOff = Color(0xFFC2C1C5)
+
+/** A slider keypad's pages: typing the value, the slider's own pressure curve, its own tilt. */
+private enum class KeypadPage { NUMERIC, PRESSURE, TILT }
/**
* A slider's keypad, a light popover to the right of its value ([pill], window pixels), its arrow
- * at the value: the slider's name, then 7 8 9 / 4 5 6 / 1 2 3 / 0 and backspace (81 x 66 keys).
- * Each key sets the value at once: the digits typed so far are the number (over [most], [most]);
- * backspace takes the last one off (none left: nothing).
+ * at the value: the slider's name, then 7 8 9 / 4 5 6 / 1 2 3 / 0 and backspace (81 x 66 keys),
+ * "-" 0 and backspace for a value that may be negative. Each key sets the value at once: the digits
+ * typed so far are the number (beyond the most, the most); "-" makes it negative; backspace takes
+ * the last one off (none left: nothing).
*/
@Composable
-private fun SliderKeypad(title: String, pill: androidx.compose.ui.geometry.Rect, most: Int, toValue: (Int) -> Float, onValue: (Float) -> Unit, onDismiss: () -> Unit) {
+private fun SliderKeypad(
+ title: String,
+ pill: androidx.compose.ui.geometry.Rect,
+ typed: Typed,
+ onValue: (Float) -> Unit,
+ extras: KeypadExtras?,
+ onDismiss: () -> Unit,
+) {
+ // tabs over the keys when the slider has a pressure curve or a tilt of its own
+ val pages = buildList {
+ add(KeypadPage.NUMERIC)
+ if (extras?.pressure == true) add(KeypadPage.PRESSURE)
+ if (extras?.tilt == true) add(KeypadPage.TILT)
+ }
+ var page by remember { mutableStateOf(KeypadPage.NUMERIC) }
+ val height = keypadHeight(pages.size)
var text by remember { mutableStateOf("") }
fun type(next: String) {
- val n = next.toIntOrNull()?.coerceAtMost(most) ?: 0
+ // a sign alone waits for its digits
+ if (next == "-") {
+ text = next
+ return
+ }
+ val n = next.toIntOrNull()?.coerceIn(-typed.most, typed.most) ?: 0
text = if (next.isEmpty()) "" else n.toString()
- onValue(toValue(n))
+ onValue(typed.toValue(n))
}
val density = LocalDensity.current
val screen = with(density) { androidx.compose.ui.platform.LocalView.current.rootView.height.toDp() }
val (top, arrowAt) = with(density) {
val middle = (pill.top + pill.height / 2f).toDp()
- val top = (middle - KeypadHeight / 2).coerceIn(2.dp, (screen - KeypadHeight - 2.dp).coerceAtLeast(2.dp))
+ val top = (middle - height / 2).coerceIn(2.dp, (screen - height - 2.dp).coerceAtLeast(2.dp))
top to (middle - top)
}
// the arrow's tip a little into the pill, the body 3 past its end
@@ -1007,24 +1152,119 @@ private fun SliderKeypad(title: String, pill: androidx.compose.ui.geometry.Rect,
onDismissRequest = onDismiss,
properties = androidx.compose.ui.window.PopupProperties(focusable = true, clippingEnabled = false),
) {
- Popover(KeypadWidth, arrowAt, Modifier.height(KeypadHeight), fill = KeypadFill, corner = 22.dp, side = ArrowSide.LEFT) {
- Text(title, color = KeypadInk, fontSize = 22.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 25.dp, top = 19.dp).height(51.dp))
- Column(Modifier.padding(start = 12.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
- for (row in listOf(listOf("7", "8", "9"), listOf("4", "5", "6"), listOf("1", "2", "3"))) {
- Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { for (k in row) KeypadKey(k, 81.dp) { type(text + k) } }
+ Popover(KeypadWidth, arrowAt, Modifier.height(height), fill = KeypadFill, corner = 22.dp, side = ArrowSide.LEFT) {
+ Text(title, color = KeypadInk, fontSize = 22.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 25.dp, top = 19.dp).height(if (pages.size > 1) 43.dp else 51.dp))
+ if (pages.size > 1) {
+ KeypadTabRow(pages, page) { page = it }
+ Spacer(Modifier.height(12.dp))
+ }
+ when (page) {
+ KeypadPage.NUMERIC -> Column(Modifier.padding(start = 12.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
+ val keyHeight = keypadKeyHeight(pages.size)
+ for (row in listOf(listOf("7", "8", "9"), listOf("4", "5", "6"), listOf("1", "2", "3"))) {
+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { for (k in row) KeypadKey(k, 81.dp, keyHeight) { type(text + k) } }
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ if (typed.signed) {
+ KeypadKey("-", 81.dp, keyHeight) { type(if (text.startsWith("-")) text.drop(1) else "-$text") }
+ KeypadKey("0", 81.dp, keyHeight) { type(text + "0") }
+ } else {
+ KeypadKey("0", 166.dp, keyHeight) { type(text + "0") }
+ }
+ KeypadKey("⌫", 81.dp, keyHeight) { type(text.dropLast(1)) }
+ }
}
- Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
- KeypadKey("0", 166.dp) { type(text + "0") }
- KeypadKey("⌫", 81.dp) { type(text.dropLast(1)) }
+ KeypadPage.PRESSURE -> if (extras != null) KeypadPressure(extras)
+ KeypadPage.TILT -> if (extras != null) KeypadTilt(extras)
+ }
+ }
+ }
+}
+
+/** The keypad's tabs under its title: an icon for each page, the chosen one on blue. */
+@Composable
+private fun KeypadTabRow(pages: List<KeypadPage>, chosen: KeypadPage, onChoose: (KeypadPage) -> Unit) {
+ Row(Modifier.padding(start = 12.dp).size(251.dp, 30.dp).clip(RoundedCornerShape(9.dp)).background(KeypadTabs).padding(2.dp)) {
+ for (p in pages) {
+ Box(
+ Modifier.weight(1f).fillMaxHeight().clip(RoundedCornerShape(7.dp)).background(if (p == chosen) KeypadTabChosen else Color.Transparent).tap { onChoose(p) },
+ contentAlignment = Alignment.Center,
+ ) {
+ val icon = when (p) {
+ KeypadPage.NUMERIC -> PcIcons.Keypad
+ KeypadPage.PRESSURE -> PcIcons.PenPressure
+ KeypadPage.TILT -> PcIcons.PenTilt
}
+ Icon(icon, contentDescription = p.name.lowercase().replaceFirstChar { it.uppercase() }, tint = if (p == chosen) Color.White else KeypadTabInk, modifier = Modifier.requiredSize(30.dp))
+ }
+ }
+ }
+}
+
+/** A page's name and its switch, in a row across the keypad. */
+@Composable
+private fun KeypadSwitchRow(label: String, on: Boolean, onChange: (Boolean) -> Unit) {
+ Row(Modifier.padding(start = 18.dp, end = 8.dp).fillMaxWidth().height(28.dp).tap { onChange(!on) }, verticalAlignment = Alignment.CenterVertically) {
+ Text(label, color = KeypadInk, fontSize = 17.sp, maxLines = 1, modifier = Modifier.weight(1f))
+ Switch(on, enabled = true, offTrack = KeypadSwitchOff)
+ }
+}
+
+/** The pressure page: the slider's own curve, on or off, drawn on a light grid. */
+@Composable
+private fun KeypadPressure(extras: KeypadExtras) {
+ var curve by remember { mutableStateOf(extras.curve()) }
+ Column {
+ Spacer(Modifier.height(6.dp))
+ KeypadSwitchRow("Pressure", curve != null) { on ->
+ val next = if (on) listOf(Offset(0f, 0f), Offset(1f, 1f)) else null
+ curve = next
+ extras.setCurve(next)
+ }
+ Spacer(Modifier.height(12.dp))
+ PressureCurve(
+ curve ?: emptyList(),
+ modifier = Modifier.padding(start = 18.dp).size(239.dp, 219.dp),
+ grid = KeypadGraphGrid,
+ edge = KeypadGraphEdge,
+ fill = KeypadGraph,
+ line = Pc.Accent,
+ lineWidth = 1.5.dp,
+ ) { points ->
+ if (curve != null) {
+ curve = points
+ extras.setCurve(points)
+ }
+ }
+ }
+}
+
+/** The tilt page: the slider's own tilt switch (if it has one) over the angle its tilt starts from. */
+@Composable
+private fun KeypadTilt(extras: KeypadExtras) {
+ var on by remember { mutableStateOf(extras.tiltOn()) }
+ var angle by remember { mutableStateOf(extras.tiltAngle()) }
+ Column {
+ Spacer(Modifier.height(6.dp))
+ on?.let { now ->
+ KeypadSwitchRow("Tilt", now) {
+ on = it
+ extras.setTiltOn(it)
+ }
+ }
+ Spacer(Modifier.height(8.dp))
+ Box(Modifier.padding(start = 10.dp).size(255.dp, 209.dp).background(KeypadFill).padding(5.dp)) {
+ TiltAngle(angle, LightTilt, active = on ?: true) {
+ angle = it
+ extras.setTiltAngle(it)
}
}
}
}
@Composable
-private fun KeypadKey(label: String, width: Dp, onClick: () -> Unit) {
- Box(Modifier.size(width, 66.dp).clip(RoundedCornerShape(12.dp)).background(KeypadKey).tap(onClick = onClick), contentAlignment = Alignment.Center) {
+private fun KeypadKey(label: String, width: Dp, height: Dp = 66.dp, onClick: () -> Unit) {
+ Box(Modifier.size(width, height).clip(RoundedCornerShape(12.dp)).background(KeypadKey).tap(onClick = onClick), contentAlignment = Alignment.Center) {
if (label == "⌫") {
Icon(PcIcons.Backspace, contentDescription = "Back space", tint = KeypadInk, modifier = Modifier.size(26.dp))
} else {
@@ -1119,16 +1359,27 @@ private val StudioCurveLine = Color(0xFFD5D5D5)
private val TaperBarFill = Color(0xFF363636)
/**
- * The pressure curve: a grid in quarters, the curve through its points as strokes apply it; drag a
- * point, or tap to add one.
+ * How the tilt angle's graph is coloured: its box, the quarter disc, the arc, the line, the angle's
+ * label, and its handle's middle while the tilt is off.
+ */
+internal class TiltLook(val box: Color, val quarter: Color, val arc: Color, val line: Color, val label: Color, val off: Color, val fill: Boolean = true)
+
+private val DarkTilt = TiltLook(Color(0xFF1B1B1B), Color(0xFF262626), Color(0xFF4A4A4A), Color(0xFF6E6E6E), Color(0xFF8E8E8E), Color(0xFF6E6E6E))
+/** In the keypads: the disc darker than the box round it, as the reference's. */
+private val LightTilt = TiltLook(Color(0xFFE6E6E6), Color(0xFFDADADA), Color(0xFFABABAB), Color(0xFF797979), Color(0xFFAAAAAA), Color(0xFFAAAAAA), fill = false)
+
+/**
+ * The tilt angle: a quarter disc from the bottom-left corner with a line at the angle (0 flat, 1
+ * upright) and its handle on the arc; drag anywhere to turn it.
*/
@Composable
-internal fun TiltAngle(value: Float, onChange: (Float) -> Unit) {
+internal fun TiltAngle(value: Float, look: TiltLook = DarkTilt, active: Boolean = true, onChange: (Float) -> Unit) {
val change by rememberUpdatedState(onChange)
val degrees = (value.coerceIn(0f, 1f) * 90f).roundToInt()
Box(
// not clipped: the handle sits on the box's edge, whole
- Modifier.padding(horizontal = 5.dp).fillMaxWidth().aspectRatio(271.5f / 221f).background(TiltBox, RoundedCornerShape(6.dp)),
+ if (look.fill) Modifier.padding(horizontal = 5.dp).fillMaxWidth().aspectRatio(271.5f / 221f).background(look.box, RoundedCornerShape(6.dp))
+ else Modifier.fillMaxSize().background(look.box),
) {
Canvas(
Modifier.fillMaxSize().pointerInput(Unit) {
@@ -1150,18 +1401,18 @@ internal fun TiltAngle(value: Float, onChange: (Float) -> Unit) {
val corner = Offset(0f, size.height)
val r = size.height
clipRect {
- drawCircle(TiltQuarter, r, corner)
- drawCircle(TiltArc, r, corner, style = Stroke(1.dp.toPx()))
+ drawCircle(look.quarter, r, corner)
+ drawCircle(look.arc, r, corner, style = Stroke(1.dp.toPx()))
}
val a = value.coerceIn(0f, 1f) * (Math.PI / 2)
val dir = Offset(kotlin.math.cos(a).toFloat(), -kotlin.math.sin(a).toFloat())
// the line runs on to the box's edge; the handle sits on the arc
val reach = minOf(if (dir.x > 1e-4f) size.width / dir.x else Float.MAX_VALUE, if (dir.y < -1e-4f) size.height / -dir.y else Float.MAX_VALUE)
- drawLine(TiltLine, corner, corner + dir * reach, 1.dp.toPx())
+ drawLine(look.line, corner, corner + dir * reach, 1.dp.toPx())
drawCircle(Color.White, 5.5.dp.toPx(), corner + dir * r)
- drawCircle(Pc.Accent, 3.5.dp.toPx(), corner + dir * r)
+ drawCircle(if (active) Pc.Accent else look.off, 3.5.dp.toPx(), corner + dir * r)
}
- Text("$degrees°", color = TiltLabel, fontSize = 17.sp, modifier = Modifier.align(Alignment.TopEnd).padding(top = 7.dp, end = 9.dp))
+ Text("$degrees°", color = look.label, fontSize = 17.sp, modifier = Modifier.align(Alignment.TopEnd).padding(top = 7.dp, end = 9.dp))
}
}
@@ -1240,9 +1491,6 @@ private val RoundnessCross = Color(0xFF4C4C4C)
private val RoundnessFill = Color(0xD6232323)
private val RoundnessEdge = Color(0xFF565656)
private val TiltBox = Color(0xFF1B1B1B)
-private val TiltQuarter = Color(0xFF262626)
-private val TiltArc = Color(0xFF4A4A4A)
-private val TiltLine = Color(0xFF6E6E6E)
private val TiltLabel = Color(0xFF8E8E8E)
@Composable
@@ -1262,24 +1510,35 @@ internal fun PressureCurve(
val pts by rememberUpdatedState(points)
val change by rememberUpdatedState(onChange)
val samples = remember(points) { curveSamples(points.flatMap { listOf(it.x, it.y) }, 129u) }
+ // the node whose menu shows (a tap on a node), and the box's size for placing it
+ var menu by remember { mutableStateOf<Int?>(null) }
+ var box by remember { mutableStateOf(androidx.compose.ui.unit.IntSize.Zero) }
+ Box(modifier.onSizeChanged { box = it }) {
Canvas(
- modifier.pointerInput(Unit) {
+ Modifier.fillMaxSize().pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown()
down.consume()
+ menu = null
+ // no curve (switched off): nothing to touch
+ if (pts.isEmpty()) return@awaitEachGesture
fun toCurve(p: Offset) = Offset((p.x / size.width).coerceIn(0f, 1f), (1f - p.y / size.height).coerceIn(0f, 1f))
val at = toCurve(down.position)
var list = pts.toMutableList()
var index = list.indexOfFirst { (it - at).getDistance() < 0.05f }
- if (index < 0) {
+ val added = index < 0
+ if (added) {
list.add(at)
list.sortBy { it.x }
index = list.indexOf(at)
change(list.toList())
}
+ var moved = false
while (true) {
val ev = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break
if (!ev.pressed) break
+ if (!moved && (ev.position - down.position).getDistance() < viewConfiguration.touchSlop) continue
+ moved = true
val p = toCurve(ev.position)
val lo = list.getOrNull(index - 1)?.x ?: 0f
val hi = list.getOrNull(index + 1)?.x ?: 1f
@@ -1287,6 +1546,8 @@ internal fun PressureCurve(
change(list.toList())
ev.consume()
}
+ // a tap on a node shows what can be done with it
+ if (!moved && !added) menu = index
}
},
) {
@@ -1299,6 +1560,7 @@ internal fun PressureCurve(
drawLine(grid, Offset(0f, h * k / 4f), Offset(w, h * k / 4f), 1.dp.toPx())
}
drawRoundRect(edge, cornerRadius = round, style = Stroke(1.dp.toPx()))
+ if (points.isEmpty()) return@Canvas
val sorted = points.sortedBy { it.x }
val path = Path()
val last = (samples.size - 1).coerceAtLeast(1)
@@ -1313,4 +1575,48 @@ internal fun PressureCurve(
drawCircle(Pc.Accent, handle.second.toPx(), Offset(p.x * w, (1f - p.y) * h))
}
}
+ menu?.let { i -> NodeMenu(points.sortedBy { it.x }, i, box, { menu = null }, change) }
+ }
}
+
+/**
+ * The menu over node [index] of a curve through [points] (the box [box] pixels): Delete (a node
+ * between the ends) and Reset (the curve straight again).
+ */
+@Composable
+private fun NodeMenu(points: List<Offset>, index: Int, box: androidx.compose.ui.unit.IntSize, close: () -> Unit, change: (List<Offset>) -> Unit) {
+ val at = points.getOrNull(index) ?: return
+ val end = index == 0 || index == points.lastIndex
+ val rows = if (end) listOf("Reset") else listOf("Delete", "Reset")
+ // centred over the node, its bottom 11 above it; in a window of its own, so the column's edge
+ // doesn't cut it (with room round it for its shadow)
+ val offset = with(LocalDensity.current) {
+ androidx.compose.ui.unit.IntOffset(
+ (at.x * box.width - (NodeMenuWidth / 2 + NodeMenuHalo).toPx()).roundToInt(),
+ ((1f - at.y) * box.height - (11.dp + NodeMenuRow * rows.size + NodeMenuHalo).toPx()).roundToInt(),
+ )
+ }
+ PcPopup(offset = offset, onDismissRequest = close, properties = androidx.compose.ui.window.PopupProperties(focusable = true, clippingEnabled = false)) {
+ Column(
+ Modifier.padding(NodeMenuHalo).width(NodeMenuWidth).shadow(14.dp, RoundedCornerShape(12.dp), ambientColor = Color.Black, spotColor = Color.Black)
+ .clip(RoundedCornerShape(12.dp)).background(NodeMenuFill),
+ ) {
+ for (row in rows) {
+ Box(
+ Modifier.fillMaxWidth().height(NodeMenuRow).tap {
+ close()
+ change(if (row == "Reset") listOf(Offset(0f, 0f), Offset(1f, 1f)) else points.filterIndexed { k, _ -> k != index })
+ },
+ contentAlignment = Alignment.Center,
+ ) {
+ Text(row, color = Color.White, fontSize = 17.sp, maxLines = 1)
+ }
+ }
+ }
+ }
+}
+
+private val NodeMenuFill = Color(0xFF101010)
+private val NodeMenuHalo = 16.dp
+private val NodeMenuWidth = 70.dp
+private val NodeMenuRow = 36.dp
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.kt
index c7aab0c..68fb3c4 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.kt
@@ -677,19 +677,25 @@ private fun Palettes(vm: CanvasViewModel, c: ColorPick, short: Boolean) {
}
}
-/** The ... button of a palette card and its menu: Set as active, Duplicate, Share; Delete. */
+/**
+ * The ... button of a palette card and its menu: Set as active (unless it is), Duplicate, Share;
+ * Delete.
+ */
@Composable
private fun PaletteMenu(vm: CanvasViewModel, i: Int) {
var open by remember { mutableStateOf(false) }
val context = androidx.compose.ui.platform.LocalContext.current
val scope = androidx.compose.runtime.rememberCoroutineScope()
+ // the menu's right edge 5 left of the button, its top 25 below the button's (2.5 below its middle)
+ val (gap, drop) = with(androidx.compose.ui.platform.LocalDensity.current) { 5.dp.roundToPx() to 25.dp.roundToPx() }
Box(Modifier.padding(end = 8.5.dp).size(30.dp, 44.dp).clickable { open = true }, contentAlignment = Alignment.Center) {
Icon(PcIcons.More, contentDescription = "More", tint = Pc.PanelTitle, modifier = Modifier.size(20.dp))
- // under the button, its right edge near the button's
- LibraryMenu(open, androidx.compose.ui.graphics.TransformOrigin(1f, 0f), MenuPlace { a, size -> IntOffset(a.right - size.width, a.bottom) }, onDismiss = { open = false }, overPanel = true) {
- MenuItem(PcIcons.MenuCheckCircle, "Set as active") {
- open = false
- vm.chooseDefaultPalette(i)
+ LibraryMenu(open, androidx.compose.ui.graphics.TransformOrigin(1f, 0f), MenuPlace { a, size -> IntOffset(a.left - gap - size.width, a.top + drop) }, onDismiss = { open = false }, overPanel = true) {
+ if (vm.defaultPalette != i) {
+ MenuItem(PcIcons.MenuCheckCircle, "Set as active") {
+ open = false
+ vm.chooseDefaultPalette(i)
+ }
}
MenuItem(PcIcons.MenuDuplicate, "Duplicate") {
open = false
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Icons.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Icons.kt
index 81da5a6..7f18ca2 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Icons.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Icons.kt
@@ -115,6 +115,32 @@ object PcIcons {
)
}
+ /** A keypad: two rows of three keys over a wide key and one more. */
+ val Keypad by lazy {
+ val key = { x: Float, y: Float, w: Float -> Part("M${x + 0.8f} ${y}h${w - 1.6f}a0.8 0.8 0 0 1 0.8 0.8v2.6a0.8 0.8 0 0 1-0.8 0.8h-${w - 1.6f}a0.8 0.8 0 0 1-0.8-0.8v-2.6a0.8 0.8 0 0 1 0.8-0.8z", 0f, true) }
+ val cells = (0 until 6).map { k -> key(7.5f + (k % 3) * 5.4f, 8f + (k / 3) * 5.4f, 4.2f) } +
+ listOf(key(7.5f, 18.8f, 9.6f), key(18.3f, 18.8f, 4.2f))
+ icon("keypad", *cells.toTypedArray(), viewport = 30f)
+ }
+ /** A pen's tip pressed down on a surface. */
+ val PenPressure by lazy {
+ icon(
+ "pen-pressure",
+ Part("M11.6 5.2L18.4 5.2L17 14.6L13 14.6Z", 0f, true),
+ Part("M13.3 15.8L16.7 15.8L15.35 22.2L14.65 22.2Z", 0f, true),
+ Part("M8 23.4a7 1.9 0 1 0 14 0a7 1.9 0 1 0 -14 0Z", 0f, true),
+ viewport = 30f,
+ )
+ }
+ /** A pen leaning over, its tip down to the left. */
+ val PenTilt by lazy {
+ icon(
+ "pen-tilt",
+ Part("M17.73 6.46L22.94 10.83L15.83 17.13L12.76 14.56Z", 0f, true),
+ Part("M12.22 15.67L14.82 17.85L9.68 21.89L9.14 21.44Z", 0f, true),
+ viewport = 30f,
+ )
+ }
/** Nine small squares. */
val MenuGrid by lazy {
val cells = (0 until 9).map { k ->
@@ -474,6 +500,25 @@ object PcIcons {
// the shape and grain editors' Import menu
val SourcePhoto by lazy { outline("source-photo", 1.6f, "M4 5.5h16v13H4z", "M4 16l5-5 4 4 2.5-2.5L20 17", "M15.5 9.5a1 1 0 1 0 0-.01") }
val SourceBooks by lazy { outline("source-books", 1.6f, "M4.5 4.5h3.5v15H4.5z", "M9.5 4.5H13v15H9.5z", "M14.5 5.5l3.3-1 3.7 14.2-3.3 1z") }
+ // filled, for the Import menu's rows
+ /** A picture (a landscape cut out of it) in front of another. */
+ val SourcePhotoFill by lazy {
+ icon(
+ "source-photo-fill",
+ Part("M4.5 8h12.5a1.5 1.5 0 0 1 1.5 1.5v9a1.5 1.5 0 0 1-1.5 1.5H4.5A1.5 1.5 0 0 1 3 18.5v-9A1.5 1.5 0 0 1 4.5 8zM5 18l4-4 2.8 2.8 1.7-1.7 3 2.9zM14.2 11.2a1.2 1.2 0 1 0 0.01 0z", 0f, true, evenOdd = true),
+ Part("M6.5 5.5h13a1.5 1.5 0 0 1 1.5 1.5v9.5", 1.6f, false),
+ )
+ }
+ val FolderFill by lazy { shape("folder-fill", 24f, "M4.5 5h4.3l2 2h8.7a1.5 1.5 0 0 1 1.5 1.5v9.5a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18V6.5A1.5 1.5 0 0 1 4.5 5z") }
+ /** Two books standing and one leaning. */
+ val SourceBooksFill by lazy {
+ icon(
+ "source-books-fill",
+ Part("M4.6 4.5h2.8a0.6 0.6 0 0 1 0.6 0.6v13.8a0.6 0.6 0 0 1-0.6 0.6H4.6a0.6 0.6 0 0 1-0.6-0.6V5.1a0.6 0.6 0 0 1 0.6-0.6z", 0f, true),
+ Part("M9.6 4.5h2.8a0.6 0.6 0 0 1 0.6 0.6v13.8a0.6 0.6 0 0 1-0.6 0.6H9.6a0.6 0.6 0 0 1-0.6-0.6V5.1a0.6 0.6 0 0 1 0.6-0.6z", 0f, true),
+ Part("M14.4 5.7l2.7-0.8a0.6 0.6 0 0 1 0.75 0.42l3.6 13.4a0.6 0.6 0 0 1-0.42 0.74l-2.7 0.8a0.6 0.6 0 0 1-0.74-0.42L14 6.4a0.6 0.6 0 0 1 0.4-0.7z", 0f, true),
+ )
+ }
val Clip by lazy { outline("clip", 1.7f, "M8 4v9a4 4 0 0 0 4 4h6", "M15 14l3 3-3 3") }
// the transform toolbar: its four ways (shown 30 across) and its buttons
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SelectionUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SelectionUi.kt
index 6c1f4f5..59f34d1 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SelectionUi.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SelectionUi.kt
@@ -73,9 +73,11 @@ fun SelectionToolbar(vm: CanvasViewModel, screenWidth: Dp, modifier: Modifier =
) { w ->
// a long name smaller only where the buttons are narrow
val long = if (w < SelectionButtonRoomy) 11.sp else 12.5.sp
- // selecting by colour always adds
+ // selecting by colour always adds: Add shows chosen, and only the other ways can remove
val joins = vm.selectionKind != SelectionKind.AUTOMATIC
- ToolbarButton(PcIcons.SelectAdd, "Add", active = joins && !vm.selectionRemoves, enabled = joins, width = w, iconSize = 44.dp) { vm.chooseSelectionRemoves(false) }
+ ToolbarButton(PcIcons.SelectAdd, "Add", active = !joins || !vm.selectionRemoves, width = w, iconSize = 44.dp) {
+ if (joins) vm.chooseSelectionRemoves(false)
+ }
ToolbarButton(PcIcons.SelectRemove, "Remove", active = joins && vm.selectionRemoves, enabled = joins, width = w, iconSize = 44.dp) { vm.chooseSelectionRemoves(true) }
ToolbarButton(PcIcons.Invert, "Invert", enabled = has, width = w, iconSize = 44.dp) { vm.invertSelection() }
ToolbarButton(PcIcons.SelectCopyPaste, "Copy & Paste", enabled = has || drawing, width = w, iconSize = 44.dp, labelSize = long) { vm.copySelectionToLayer() }
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SourceEditorUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SourceEditorUi.kt
index 53003a9..fc97863 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SourceEditorUi.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/SourceEditorUi.kt
@@ -27,7 +27,6 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
-import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
@@ -57,6 +56,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.PopupProperties
import io.github.artcraftandroid.procraft.canvas.CanvasViewModel
+import io.github.artcraftandroid.procraft.core.SourceKind
import kotlin.math.roundToInt
import kotlinx.coroutines.launch
@@ -69,22 +69,30 @@ private val CapsuleInk = Color(0xFFAAAAAA)
private val DoneBlue = Color(0xFF0190FF)
private val RepeatLabel = Color(0xFF808080)
private val LibraryVeil = Color(0x80000000)
-private val LibraryBar = Color(0xF21C1C1C)
+private val LibrarySheet = Color(0xFF1C1C1E)
+private val LibraryTitle = Color(0xFFC1C1C1)
+private val LibraryDim = Color(0xFF868686)
+private val LibraryEdge = Color(0xFF5A5A5A)
+private val LibrarySearchFill = Color(0xFF1B1B1B)
+private val LibrarySearchEdge = Color(0xFF363636)
+private val LibraryHint = Color(0xFF787878)
private val MenuBlue = Color(0xFF0A84FF)
/**
- * The shape or grain editor of the brush studio (the one [CanvasViewModel.sourceEditing] says):
- * the image in a 600 square, changed by Import (a photo, a file, the source library or the
- * clipboard) or turned negative by a two-finger tap; the grain editor can also make it repeat
- * without seams. Cancel leaves the brush as it was, the tick keeps the change.
+ * The brush studio's editor for the source [CanvasViewModel.sourceEditing] says (the shape, the
+ * grain, or what the brush paints metalness or roughness through): the image in a 600 square,
+ * changed by Import (a photo, a file, the source library or the clipboard) or turned negative by a
+ * two-finger tap; all but the shape's can also make it repeat without seams, and take the grains
+ * from the library. Cancel leaves the brush as it was, the tick keeps the change.
*/
@Composable
fun SourceEditor(vm: CanvasViewModel) {
- val grain = vm.sourceEditing ?: return
+ val kind = vm.sourceEditing ?: return
+ val grain = kind != SourceKind.SHAPE
val scope = rememberCoroutineScope()
- // the image as edited here (empty: the round tip), and the shipped one it is if it is one
- var image by remember(grain) { mutableStateOf(vm.studioSourcePixels(grain)) }
- var shipped by remember(grain) { mutableStateOf<Int?>(null) }
+ // the image as edited here (empty: the round tip, or white all over), and the shipped one it is if it is one
+ var image by remember(kind) { mutableStateOf(vm.studioSourcePixels(kind)) }
+ var shipped by remember(kind) { mutableStateOf<Int?>(null) }
var importing by remember { mutableStateOf(false) }
var library by remember { mutableStateOf(false) }
// Auto repeat and its settings
@@ -144,7 +152,13 @@ fun SourceEditor(vm: CanvasViewModel) {
}
}
Text(
- if (grain) "Grain Editor" else "Shape Editor", color = EditorTitle, fontSize = 22.sp, fontWeight = FontWeight.Bold,
+ when (kind) {
+ SourceKind.SHAPE -> "Shape Editor"
+ SourceKind.GRAIN -> "Grain Editor"
+ SourceKind.METALLIC -> "Metallic Editor"
+ SourceKind.ROUGHNESS -> "Roughness Editor"
+ },
+ color = EditorTitle, fontSize = 22.sp, fontWeight = FontWeight.Bold,
modifier = Modifier.offset(24.dp, if (landscape) 16.dp else 26.dp),
)
Row(
@@ -170,7 +184,7 @@ fun SourceEditor(vm: CanvasViewModel) {
Spacer(Modifier.width(13.dp))
Box(
Modifier.size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).tap {
- vm.keepStudioSource(grain, result(), shipped.takeIf { !repeating })
+ vm.keepStudioSource(kind, result(), shipped.takeIf { !repeating })
},
contentAlignment = Alignment.Center,
) {
@@ -207,25 +221,27 @@ private fun CapsuleButton(label: String, width: Int, on: Boolean = false, onClic
private fun ImportMenu(open: Boolean, onDismiss: () -> Unit, onPick: (Int) -> Unit) {
val density = androidx.compose.ui.platform.LocalDensity.current
MenuPresence(open, androidx.compose.ui.graphics.TransformOrigin(0.5f, 0f)) { look ->
+ // under Import, its arrow pointing up at it
PcPopup(
- textScale = MATCHED_POPUP_TEXT,
alignment = Alignment.TopCenter,
- offset = with(density) { androidx.compose.ui.unit.IntOffset(0, 48.dp.roundToPx()) },
+ offset = with(density) { androidx.compose.ui.unit.IntOffset(0, 47.dp.roundToPx()) },
onDismissRequest = onDismiss,
properties = PopupProperties(focusable = true),
) {
- Column(look.width(320.dp).clip(RoundedCornerShape(24.dp)).background(Pc.LightPanel).padding(start = 8.dp, end = 8.dp, bottom = 8.dp)) {
- Text("Image source", color = Pc.LightText, fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 12.dp, top = 16.dp, bottom = 12.dp))
- Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(Pc.LightRow)) {
- MenuRow(PcIcons.SourcePhoto, "Import a photo") { onPick(0) }
- Box(Modifier.padding(start = 52.dp).fillMaxWidth().height(1.dp).background(Pc.LightSeparator))
- MenuRow(PcIcons.Folder, "Import a file") { onPick(1) }
- Box(Modifier.padding(start = 52.dp).fillMaxWidth().height(1.dp).background(Pc.LightSeparator))
- MenuRow(PcIcons.SourceBooks, "Source Library") { onPick(2) }
- }
- Spacer(Modifier.height(20.dp))
- Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(Pc.LightRow)) {
- MenuRow(PcIcons.TextPaste, "Paste", iconSize = 40.dp) { onPick(3) }
+ Popover(320.dp, 160.dp, look, fill = Pc.LightPanel, corner = 24.dp, side = ArrowSide.TOP) {
+ Column(Modifier.padding(start = 8.dp, end = 8.dp, bottom = 8.dp)) {
+ Text("Image source options", color = Pc.LightText, fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 12.dp, top = 16.dp, bottom = 12.dp))
+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(Pc.LightRow)) {
+ MenuRow(PcIcons.SourcePhotoFill, "Import a photo", iconSize = 30.dp) { onPick(0) }
+ Box(Modifier.padding(start = 52.dp).fillMaxWidth().height(1.dp).background(Pc.LightSeparator))
+ MenuRow(PcIcons.FolderFill, "Import a file", iconSize = 30.dp) { onPick(1) }
+ Box(Modifier.padding(start = 52.dp).fillMaxWidth().height(1.dp).background(Pc.LightSeparator))
+ MenuRow(PcIcons.SourceBooksFill, "Source Library", iconSize = 30.dp) { onPick(2) }
+ }
+ Spacer(Modifier.height(20.dp))
+ Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(Pc.LightRow)) {
+ MenuRow(PcIcons.TextPaste, "Paste", iconSize = 40.dp) { onPick(3) }
+ }
}
}
}
@@ -317,51 +333,99 @@ private fun SimpleSlider(value: Float, onChange: (Float) -> Unit, modifier: Modi
}
/**
- * The source library: the shipped shape or grain images in 180 cells (the image 146 square, its
- * name under it) under a bar with the title, Cancel, and Shape Source and Grain Source.
+ * The source library: a sheet (580 x 575, 74 down) over the editor with its title and Cancel, Shape
+ * Source and Grain Source with a search by name, then the shipped images three across (147 square,
+ * their names under them). A pick of the other kind than the one being edited isn't taken.
*/
@Composable
private fun SourceLibrary(vm: CanvasViewModel, grain: Boolean, onPick: (Int) -> Unit, onCancel: () -> Unit) {
var showGrains by remember { mutableStateOf(grain) }
- val images: List<Pair<String, ImageBitmap?>> = if (showGrains) vm.grainLibrary else vm.shapeLibrary
- BackHandler(onBack = onCancel)
- Box(Modifier.fillMaxSize().background(LibraryVeil)) {
- LazyVerticalGrid(
- columns = GridCells.Adaptive(180.dp),
- contentPadding = PaddingValues(top = 183.dp, start = 12.dp, end = 12.dp, bottom = 24.dp),
- modifier = Modifier.fillMaxSize(),
+ var query by remember { mutableStateOf("") }
+ val all: List<Pair<String, ImageBitmap?>> = if (showGrains) vm.grainLibrary else vm.shapeLibrary
+ val shown = all.withIndex().filter { query.isBlank() || it.value.first.contains(query.trim(), ignoreCase = true) }
+ // over the whole window, the studio's pages dimmed too, the sheet in the window's middle
+ val atOrigin = remember {
+ object : androidx.compose.ui.window.PopupPositionProvider {
+ override fun calculatePosition(
+ anchorBounds: androidx.compose.ui.unit.IntRect,
+ windowSize: androidx.compose.ui.unit.IntSize,
+ layoutDirection: androidx.compose.ui.unit.LayoutDirection,
+ popupContentSize: androidx.compose.ui.unit.IntSize,
+ ) = androidx.compose.ui.unit.IntOffset.Zero
+ }
+ }
+ PcPopup(atOrigin, onDismissRequest = onCancel, properties = PopupProperties(focusable = true, clippingEnabled = false)) {
+ Box(Modifier.fillMaxSize().background(LibraryVeil).pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume() } }) {
+ Column(
+ Modifier.align(Alignment.TopCenter).offset(y = 74.dp).size(580.dp, 575.dp).clip(RoundedCornerShape(26.dp)).background(LibrarySheet)
+ .pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false) } },
) {
- itemsIndexed(images) { i, (name, image) ->
- Column(
- Modifier.size(180.dp).tap {
- // each kind takes its own: a grain picked in the shape editor is not taken
- if (showGrains == grain) onPick(i)
- },
- horizontalAlignment = Alignment.CenterHorizontally,
- ) {
- Box(Modifier.padding(top = 6.dp).size(146.dp).clip(RoundedCornerShape(8.dp)).background(Color.Black)) {
- image?.let { Image(it, contentDescription = name, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }
+ Row(Modifier.fillMaxWidth().padding(start = 19.dp, end = 19.dp, top = 69.dp).height(39.dp), verticalAlignment = Alignment.CenterVertically) {
+ Text("Source Library", color = LibraryTitle, fontSize = 32.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.weight(1f))
+ Text("Cancel", color = LibraryDim, fontSize = 17.sp, maxLines = 1, modifier = Modifier.tap(onCancel))
+ }
+ Row(Modifier.padding(start = 43.dp, top = 25.dp).height(45.dp), verticalAlignment = Alignment.CenterVertically) {
+ for ((label, isGrain) in listOf("Shape Source" to false, "Grain Source" to true)) {
+ Box(Modifier.padding(end = 11.dp).size(115.dp, 41.dp).tap { showGrains = isGrain }, contentAlignment = Alignment.Center) {
+ Text(label, color = if (showGrains == isGrain) Color.White else LibraryDim, fontSize = 17.sp, maxLines = 1)
}
- Text(name, color = Color.White, fontSize = 17.sp, maxLines = 1, modifier = Modifier.padding(top = 5.dp))
}
+ Spacer(Modifier.width(8.dp))
+ LibrarySearch(query) { query = it }
}
- }
- Column(Modifier.fillMaxWidth().height(183.dp).background(LibraryBar)) {
- Row(Modifier.fillMaxWidth().height(128.dp).padding(start = 20.dp, end = 20.dp, bottom = 20.dp), verticalAlignment = Alignment.Bottom) {
- Text("Source Library", color = Color.White, fontSize = 27.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.weight(1f))
- Text("Cancel", color = Color.White, fontSize = 18.sp, maxLines = 1, modifier = Modifier.tap(onCancel))
- }
- Row(Modifier.fillMaxWidth().height(55.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
- for ((label, isGrain) in listOf("Shape Source" to false, "Grain Source" to true)) {
- Box(
- Modifier.padding(horizontal = 6.dp).size(114.dp, 40.dp).clip(RoundedCornerShape(8.dp))
- .background(if (showGrains == isGrain) Pc.Accent else Color.Transparent).tap { showGrains = isGrain },
- contentAlignment = Alignment.Center,
+ LazyVerticalGrid(
+ columns = GridCells.Fixed(3),
+ contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 11.dp, bottom = 24.dp),
+ horizontalArrangement = Arrangement.spacedBy(53.dp),
+ verticalArrangement = Arrangement.spacedBy(18.dp),
+ modifier = Modifier.fillMaxSize(),
+ ) {
+ items(shown.size) { k ->
+ val (i, item) = shown[k]
+ val (name, image) = item
+ Column(
+ Modifier.width(147.dp).tap {
+ // each kind takes its own: a grain picked in the shape editor is not taken
+ if (showGrains == grain) onPick(i)
+ },
) {
- Text(label, color = Color.White, fontSize = 15.sp, maxLines = 1)
+ Box(Modifier.size(147.dp, 146.dp).clip(RoundedCornerShape(8.dp)).background(Color.Black).border(1.dp, LibraryEdge, RoundedCornerShape(8.dp))) {
+ image?.let { Image(it, contentDescription = name, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) }
+ }
+ Text(name, color = LibraryTitle, fontSize = 13.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 3.dp, top = 5.dp).height(21.dp))
}
}
}
}
}
+ }
+}
+
+/** The library's search: a round field with a magnifier and its hint, matching names as typed. */
+@Composable
+private fun LibrarySearch(query: String, onQuery: (String) -> Unit) {
+ Row(
+ Modifier.size(225.dp, 45.dp).clip(RoundedCornerShape(22.5.dp)).background(LibrarySearchFill).border(1.dp, LibrarySearchEdge, RoundedCornerShape(22.5.dp)),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ androidx.compose.foundation.Canvas(Modifier.padding(start = 11.dp).size(23.dp, 22.dp)) {
+ // a magnifier: a ring and its handle
+ val c = androidx.compose.ui.geometry.Offset(size.width * 0.44f, size.height * 0.44f)
+ val r = 7.dp.toPx()
+ drawCircle(LibraryHint, r, c, style = androidx.compose.ui.graphics.drawscope.Stroke(2.dp.toPx()))
+ val d = r * 0.7071f
+ drawLine(LibraryHint, c + androidx.compose.ui.geometry.Offset(d, d), c + androidx.compose.ui.geometry.Offset(d + 5.dp.toPx(), d + 5.dp.toPx()), 2.4.dp.toPx(), cap = androidx.compose.ui.graphics.StrokeCap.Round)
+ }
+ Box(Modifier.padding(start = 9.dp, end = 12.dp).weight(1f), contentAlignment = Alignment.CenterStart) {
+ if (query.isEmpty()) Text("Search Library", color = LibraryHint, fontSize = 17.sp, maxLines = 1)
+ androidx.compose.foundation.text.BasicTextField(
+ query,
+ onValueChange = onQuery,
+ singleLine = true,
+ textStyle = androidx.compose.ui.text.TextStyle(color = Color.White, fontSize = 17.sp),
+ cursorBrush = androidx.compose.ui.graphics.SolidColor(Pc.Accent),
+ modifier = Modifier.fillMaxWidth(),
+ )
+ }
+ }
}
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformNumericUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformNumericUi.kt
index c9fe713..5c53938 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformNumericUi.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/TransformNumericUi.kt
@@ -23,11 +23,14 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import io.github.artcraftandroid.procraft.canvas.CanvasViewModel
@@ -41,6 +44,8 @@ private val DigitKey = Color(0xFF414141)
private val KeyInk = Color(0xFFDADADA)
private val LinkOn = Color(0xFF1F436B)
private const val NUMERIC_WIDTH = 248
+/** How far the arrow's tip stands from the node's middle (the panel's edge 17 from it). */
+private val NUMERIC_NODE_GAP = 5.dp
/**
* Numeric entry for an open transform, from a tap on a node: "Dimensions" (the box's width and
@@ -86,13 +91,26 @@ fun TransformNumeric(vm: CanvasViewModel) {
}
apply()
}
+ // the panel's height once laid out (it shows from then on)
+ var tall by remember(open) { mutableStateOf<Dp?>(null) }
BoxWithConstraints(Modifier.fillMaxSize().pointerInput(open) { detectTapGestures { vm.transformNumeric = null } }) {
- // under the node, its arrow pointing at it, kept on the screen
+ // beside the node, on its side of the box, level with it and its arrow pointing at it, kept on the screen
val width = NUMERIC_WIDTH.dp
+ val whole = width + Pc.ArrowHeight
val at = with(density) { open.at.x.toDp() to open.at.y.toDp() }
- val left = (at.first - width / 2).coerceIn(8.dp, maxWidth - width - 8.dp)
- val top = (at.second + 14.dp).coerceIn(8.dp, (maxHeight - 420.dp).coerceAtLeast(8.dp))
- Popover(width, at.first - left, Modifier.offset(left, top).pointerInput(Unit) { detectTapGestures { } }, corner = 20.dp) {
+ val left = (if (open.right) at.first + NUMERIC_NODE_GAP else at.first - NUMERIC_NODE_GAP - whole)
+ .coerceIn(8.dp, (maxWidth - whole - 8.dp).coerceAtLeast(8.dp))
+ val height = tall ?: 0.dp
+ val top = (at.second - height / 2).coerceIn(8.dp, (maxHeight - height - 8.dp).coerceAtLeast(8.dp))
+ Popover(
+ width,
+ (at.second - top).coerceIn(28.dp, (height - 28.dp).coerceAtLeast(28.dp)),
+ Modifier.offset(left, top).alpha(if (tall == null) 0f else 1f)
+ .onSizeChanged { tall = with(density) { it.height.toDp() } }
+ .pointerInput(Unit) { detectTapGestures { } },
+ corner = 20.dp,
+ side = if (open.right) ArrowSide.LEFT else ArrowSide.RIGHT,
+ ) {
Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp)) {
Text(if (open.angle) "Rotation" else "Dimensions", color = KeyInk, fontSize = 20.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 10.dp, top = 12.dp, bottom = 12.dp))
if (open.angle) {
diff --git a/apps/procraft-android/src/brush_files.rs b/apps/procraft-android/src/brush_files.rs
index 5ce9c09..6c80708 100644
--- a/apps/procraft-android/src/brush_files.rs
+++ b/apps/procraft-android/src/brush_files.rs
@@ -2,7 +2,7 @@
//! library, and written from it. A brush's shape and grain images go with it; an image a file only
//! names (one that came with the app that made it) is stood in for by the nearest of ours.
-use procraft_engine::brush::{Author, Brush, Source, StockImage, StockImages};
+use procraft_engine::brush::{Author, Brush, MaterialSource, Source, StockImage, StockImages};
use procraft_engine::brushfile::{self, BrushFile, Pictures, Texture};
use procraft_engine::curve::Curve;
use procraft_engine::textures::{self, TEXTURE_SIZE, grain, shape};
@@ -20,6 +20,8 @@ const THUMBNAIL: (u32, u32) = (327, 100);
struct Made {
shape: Vec<u8>,
grain: Option<Vec<u8>>,
+ metallic: Option<Vec<u8>>,
+ roughness: Option<Vec<u8>>,
thumbnail: Vec<u8>,
author: Option<std::sync::Arc<[u8]>>,
signature: Option<std::sync::Arc<[u8]>>,
@@ -30,6 +32,8 @@ impl Made {
Pictures {
shape_png: &self.shape,
grain_png: self.grain.as_deref(),
+ metallic_png: self.metallic.as_deref(),
+ roughness_png: self.roughness.as_deref(),
thumbnail_png: &self.thumbnail,
author_png: self.author.as_deref(),
signature_png: self.signature.as_deref(),
@@ -54,6 +58,8 @@ impl CanvasSession {
Made {
shape: gray_png(&shape_pixels(brush)),
grain: grain_pixels(brush).map(|p| gray_png(&p)),
+ metallic: material_pixels(&brush.metallic).map(|p| gray_png(&p)),
+ roughness: material_pixels(&brush.roughness).map(|p| gray_png(&p)),
thumbnail,
author: author.and_then(|a| a.picture.clone()),
signature: author.and_then(|a| a.signature.clone()),
@@ -174,12 +180,21 @@ fn brush_from(file: &BrushFile) -> Brush {
let (image, source) = grain_for(&file.grain, file.thumbnail.as_deref());
b.grain.image = image;
b.grain.source = source;
+ for (texture, material) in [(&file.metallic, &mut b.metallic), (&file.roughness, &mut b.roughness)] {
+ let (image, source) = material_for(texture);
+ *material = MaterialSource { image, source };
+ }
// the stock images it names, to name again when it is written out
let stock = |t: &Texture| match t {
Texture::Stock { name, inverted } => Some(StockImage { name: name.clone(), inverted: *inverted }),
_ => None,
};
- b.stock = StockImages { shape: stock(&file.shape), grain: stock(&file.grain) };
+ b.stock = StockImages {
+ shape: stock(&file.shape),
+ grain: stock(&file.grain),
+ metallic: stock(&file.metallic),
+ roughness: stock(&file.roughness),
+ };
// its own preview, if it can be shown
b.thumbnail = file.thumbnail.as_deref().filter(|t| thumbnail_pixels(t).is_some()).map(Into::into);
// who made it, if the file says
@@ -364,51 +379,66 @@ pub(crate) fn grain_for(t: &Texture, preview: Option<&[u8]>) -> (Option<u32>, Op
if n.contains("blank") {
return (None, None);
}
- let table: &[(&[&str], u32)] = &[
- (&["recycled"], grain::RECYCLED),
- (&["canvas", "weave", "burlap", "cloth", "fabric"], grain::WEAVE),
- (&["linen"], grain::LINEN),
- (&["denim", "twill"], grain::TWILL),
- (&["wood"], grain::WOOD),
- (&["brick"], grain::BRICK),
- (&["concrete", "stone", "rock", "wall", "asphalt"], grain::CONCRETE),
- (&["halftone", "dot"], grain::HALFTONE),
- (&["hatch"], grain::HATCHING),
- (&["crumple", "crease", "fold"], grain::CRUMPLED),
- (&["stipple"], grain::STIPPLE),
- (&["wash", "water", "wet"], grain::WASH),
- (&["marble"], grain::MARBLE),
- (&["cell", "organic"], grain::CELLS),
- (&["scale"], grain::SCALES),
- (&["hex", "honeycomb"], grain::HEXAGONS),
- (&["leather", "skin"], grain::LEATHER),
- (&["bark"], grain::BARK),
- (&["rust"], grain::RUST),
- (&["scratch"], grain::SCRATCHES),
- // a sheet of paper: a worn, light one, or crumpled
- (&["dirty-paper", "dirty paper", "worn-paper", "worn paper"], grain::WORN),
- (&["paper"], grain::SHEET),
- (&["grunge", "dirt", "dust", "dirty"], grain::GRUNGE),
- (&["fibre", "fiber", "hair", "straw"], grain::FIBRE),
- (&["sand", "grit"], grain::SAND),
- (&["noise", "static"], grain::FINE_NOISE),
- (&["charcoal", "willow", "chalk", "pastel", "rough", "coarse", "corse"], grain::CHARCOAL),
- ];
let unknown = || match preview.and_then(preview_look) {
Some(PreviewLook::Faint) => Some(grain::SPECKLED),
// about white: as good as none
Some(PreviewLook::Even) => None,
_ => Some(grain::MOTTLED),
};
- let g = table
- .iter()
- .find(|(words, _)| words.iter().any(|w| n.contains(w)))
- .map_or_else(unknown, |(_, g)| Some(*g));
- (g, None)
+ (named_grain(&n).map_or_else(unknown, Some), None)
+ }
+ }
+}
+
+/// The source a file's metalness or roughness is painted through: its image, or our nearest grain
+/// to a stock image it names, or none (the amount all over) for one it can't show or names in
+/// words we don't know.
+pub(crate) fn material_for(t: &Texture) -> (Option<u32>, Option<Source>) {
+ match t {
+ Texture::None => (None, None),
+ Texture::Image { bytes, inverted } => (None, gray_texture(bytes, *inverted)),
+ Texture::Stock { name, .. } => {
+ let n = name.to_lowercase();
+ (if n.contains("blank") { None } else { named_grain(&n) }, None)
}
}
}
+/// Our grain nearest to a stock image named `n` (lower case), if its name says what it is.
+fn named_grain(n: &str) -> Option<u32> {
+ let table: &[(&[&str], u32)] = &[
+ (&["recycled"], grain::RECYCLED),
+ (&["canvas", "weave", "burlap", "cloth", "fabric"], grain::WEAVE),
+ (&["linen"], grain::LINEN),
+ (&["denim", "twill"], grain::TWILL),
+ (&["wood"], grain::WOOD),
+ (&["brick"], grain::BRICK),
+ (&["concrete", "stone", "rock", "wall", "asphalt"], grain::CONCRETE),
+ (&["halftone", "dot"], grain::HALFTONE),
+ (&["hatch"], grain::HATCHING),
+ (&["crumple", "crease", "fold"], grain::CRUMPLED),
+ (&["stipple"], grain::STIPPLE),
+ (&["wash", "water", "wet"], grain::WASH),
+ (&["marble"], grain::MARBLE),
+ (&["cell", "organic"], grain::CELLS),
+ (&["scale"], grain::SCALES),
+ (&["hex", "honeycomb"], grain::HEXAGONS),
+ (&["leather", "skin"], grain::LEATHER),
+ (&["bark"], grain::BARK),
+ (&["rust"], grain::RUST),
+ (&["scratch"], grain::SCRATCHES),
+ // a sheet of paper: a worn, light one, or crumpled
+ (&["dirty-paper", "dirty paper", "worn-paper", "worn paper"], grain::WORN),
+ (&["paper"], grain::SHEET),
+ (&["grunge", "dirt", "dust", "dirty"], grain::GRUNGE),
+ (&["fibre", "fiber", "hair", "straw"], grain::FIBRE),
+ (&["sand", "grit"], grain::SAND),
+ (&["noise", "static"], grain::FINE_NOISE),
+ (&["charcoal", "willow", "chalk", "pastel", "rough", "coarse", "corse"], grain::CHARCOAL),
+ ];
+ table.iter().find(|(words, _)| words.iter().any(|w| n.contains(w))).map(|(_, g)| *g)
+}
+
/// An image (PNG) as a shape or grain: grey (its alpha taken in), [`TEXTURE_SIZE`] square, white
/// for paint; none if it can't be read.
fn gray_texture(bytes: &[u8], inverted: bool) -> Option<Source> {
@@ -490,6 +520,14 @@ fn grain_pixels(b: &Brush) -> Option<Vec<u8>> {
b.grain.image.and_then(|i| textures::grains().into_iter().nth(i as usize)).map(|g| g.pixels)
}
+/// A metalness or roughness source as an image, if it has one.
+pub(crate) fn material_pixels(m: &MaterialSource) -> Option<Vec<u8>> {
+ if let Some(s) = &m.source {
+ return Some(s.pixels.to_vec());
+ }
+ m.image.and_then(|i| textures::grains().into_iter().nth(i as usize)).map(|g| g.pixels)
+}
+
/// A square grey PNG of `pixels`.
fn gray_png(pixels: &[u8]) -> Vec<u8> {
let n = TEXTURE_SIZE as u32;
diff --git a/apps/procraft-android/src/brush_library.rs b/apps/procraft-android/src/brush_library.rs
index 46475ea..2e3f0fb 100644
--- a/apps/procraft-android/src/brush_library.rs
+++ b/apps/procraft-android/src/brush_library.rs
@@ -146,6 +146,21 @@ struct SavedBrush {
shape_stock: Option<(String, bool)>,
#[serde(default, skip_serializing_if = "Option::is_none")]
grain_stock: Option<(String, bool)>,
+ /// What it paints a model's metalness and roughness through: its own images (as text), the
+ /// shipped grains where they differ from its origin's (-1: none), and the stock images its
+ /// file named.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ metallic_source: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ roughness_source: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ metallic_image: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ roughness_image: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ metallic_stock: Option<(String, bool)>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ roughness_stock: Option<(String, bool)>,
}
/// A brush's maker as kept: their name, and their picture and signature (PNG, as text).
@@ -299,6 +314,12 @@ impl State {
.map(|r| SavedReset { made: r.made, brush: Box::new(self.saved_brush(&r.brush, from)) }),
shape_stock: brush.stock.shape.as_ref().map(|s| (s.name.clone(), s.inverted)),
grain_stock: brush.stock.grain.as_ref().map(|s| (s.name.clone(), s.inverted)),
+ metallic_source: brush.metallic.source.as_ref().map(Source::to_text),
+ roughness_source: brush.roughness.source.as_ref().map(Source::to_text),
+ metallic_image: image(brush.metallic.image, base.metallic.image),
+ roughness_image: image(brush.roughness.image, base.roughness.image),
+ metallic_stock: brush.stock.metallic.as_ref().map(|s| (s.name.clone(), s.inverted)),
+ roughness_stock: brush.stock.roughness.as_ref().map(|s| (s.name.clone(), s.inverted)),
}
}
@@ -309,7 +330,12 @@ impl State {
brush.name = b.name.chars().take(256).collect();
}
// the images first: a brush's own shape sets the unit its sizes are kept in
- for (kept, image) in [(b.shape_image, &mut brush.shape.image), (b.grain_image, &mut brush.grain.image)] {
+ for (kept, image) in [
+ (b.shape_image, &mut brush.shape.image),
+ (b.grain_image, &mut brush.grain.image),
+ (b.metallic_image, &mut brush.metallic.image),
+ (b.roughness_image, &mut brush.roughness.image),
+ ] {
if let Some(k) = kept {
*image = u32::try_from(k).ok();
}
@@ -320,11 +346,22 @@ impl State {
if let Some(text) = &b.grain_source {
brush.grain.source = Source::from_text(text);
}
+ for (text, material) in [(&b.metallic_source, &mut brush.metallic), (&b.roughness_source, &mut brush.roughness)]
+ {
+ if let Some(text) = text {
+ material.source = Source::from_text(text);
+ }
+ }
// the stock images its file named, stood in for by our nearest as they are now
let stock = |kept: &Option<(String, bool)>| {
kept.as_ref().map(|(name, inverted)| StockImage { name: name.clone(), inverted: *inverted })
};
- brush.stock = StockImages { shape: stock(&b.shape_stock), grain: stock(&b.grain_stock) };
+ brush.stock = StockImages {
+ shape: stock(&b.shape_stock),
+ grain: stock(&b.grain_stock),
+ metallic: stock(&b.metallic_stock),
+ roughness: stock(&b.roughness_stock),
+ };
let png = |text: &Option<String>| text.as_deref().and_then(procraft_engine::base64::decode).map(Into::into);
brush.thumbnail = png(&b.thumbnail);
if let Some(s) = &brush.stock.shape {
@@ -335,6 +372,14 @@ impl State {
let texture = Texture::Stock { name: s.name.clone(), inverted: s.inverted };
brush.grain.image = crate::brush_files::grain_for(&texture, brush.thumbnail.as_deref()).0;
}
+ for (stock, material) in
+ [(&brush.stock.metallic, &mut brush.metallic), (&brush.stock.roughness, &mut brush.roughness)]
+ {
+ if let Some(s) = stock {
+ let texture = Texture::Stock { name: s.name.clone(), inverted: s.inverted };
+ material.image = crate::brush_files::material_for(&texture).0;
+ }
+ }
brush.set_settings(b.settings.iter().map(|(k, v)| (k.as_str(), *v)));
for (points, curve) in [
(&b.curve, &mut brush.pressure_curve),
diff --git a/apps/procraft-android/src/lib.rs b/apps/procraft-android/src/lib.rs
index 01bcea1..4f48362 100644
--- a/apps/procraft-android/src/lib.rs
+++ b/apps/procraft-android/src/lib.rs
@@ -289,6 +289,8 @@ pub(crate) struct State {
pub(crate) pad_strokes: Option<Vec<(PointerKind, Vec<PenSample>)>>,
/// The pad shows only its sample scribble: a stroke of one's own takes it away.
pub(crate) pad_sample: bool,
+ /// The pad drawn as a sphere, the flat pad's strokes set aside meanwhile.
+ pub(crate) sphere: Option<crate::studio::SpherePad>,
pub(crate) frame_interval_ms: f32,
pub(crate) error: Option<String>,
/// Window pixels per interface point.
@@ -696,6 +698,7 @@ impl CanvasSession {
frames: 0,
pad_strokes: None,
pad_sample: false,
+ sphere: None,
frame_interval_ms: 0.0,
error: None,
display_scale: 2.0,
diff --git a/apps/procraft-android/src/render.rs b/apps/procraft-android/src/render.rs
index 4906e05..0121712 100644
--- a/apps/procraft-android/src/render.rs
+++ b/apps/procraft-android/src/render.rs
@@ -111,11 +111,15 @@ pub(crate) fn run(shared: Arc<Shared>, window: NativeWindow) {
}
let to_screen = st.view.map(|v| v.to_screen());
let grid = st.surround_grid(Vec2::ZERO);
- // a model is drawn in place of the flat canvas
+ // a model is drawn in place of the flat canvas, and the drawing pad may be a sphere
if st.scene_shown() {
let convert = colours_to(st.doc.profile, screen);
st.render_scene(&view, format, size, convert);
st.frames += 1;
+ } else if st.sphere.is_some() {
+ let convert = colours_to(st.doc.profile, screen);
+ st.render_sphere(&view, format, size, convert);
+ st.frames += 1;
} else if let (Some(canvas), Some(gpu), Some(to_screen)) = (st.canvas.as_mut(), st.gpu.as_ref(), to_screen)
{
let s = st.display_scale;
diff --git a/apps/procraft-android/src/studio.rs b/apps/procraft-android/src/studio.rs
index 8e416b7..8829bdb 100644
--- a/apps/procraft-android/src/studio.rs
+++ b/apps/procraft-android/src/studio.rs
@@ -1,12 +1,16 @@
//! The brush studio: the brush the current tool uses, edited control by control while the studio
//! is open (strokes and previews use it as it is), kept or put back when it closes.
-use procraft_engine::brush::{Brush, ResetPoint, Source};
+use std::sync::Arc;
+
+use procraft_engine::brush::{Brush, MaterialSource, ResetPoint, Source, StockImage};
use procraft_engine::curve::Curve;
-use procraft_engine::geom::Vec2;
+use procraft_engine::geom::{Affine, Vec2};
+use procraft_engine::studio::{MAX_GRAIN_SCALE, SliderCurve};
use procraft_engine::textures;
+use procraft_gpu::{SphereLook, SpherePreview, wgpu};
-use crate::{CanvasSession, State};
+use crate::{CanvasSession, PenSample, PointerKind, State, ToolKind};
/// The curve through `points` (x, y pairs on the unit square) at `count` (2 to 1024) evenly
/// spaced x from 0 to 1: the curve as strokes apply it, for drawing.
@@ -52,6 +56,46 @@ pub fn repeatable_source(
textures::repeatable(&pixels, repeat)
}
+/// Which of a brush's images the studio's editors change: its shape, its grain, or what it paints a
+/// model's metalness or roughness through (tiled as the grain is, from the same library).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)]
+pub enum SourceKind {
+ Shape,
+ Grain,
+ Metallic,
+ Roughness,
+}
+
+impl SourceKind {
+ /// Whether it draws from the grain images (all but the shape).
+ fn grain_like(self) -> bool {
+ self != SourceKind::Shape
+ }
+}
+
+/// What a studio slider's keypad offers besides typing its value: its own pressure curve
+/// (`pressure`), its own tilt (`tilt`) with the control of the switch that turns it on (empty: the
+/// slider is the tilt's own amount, always on) and of the angle it starts from.
+#[derive(Clone, Debug, PartialEq, uniffi::Record)]
+pub struct SliderExtrasInfo {
+ pub pressure: bool,
+ pub tilt: bool,
+ pub tilt_switch: String,
+ pub tilt_angle: String,
+}
+
+/// The keypad extras of the slider for studio control `key`.
+#[uniffi::export]
+pub fn slider_extras(key: String) -> SliderExtrasInfo {
+ let e = procraft_engine::studio::slider_extras(&key);
+ SliderExtrasInfo {
+ pressure: e.curve.is_some(),
+ tilt: e.tilt.is_some(),
+ tilt_switch: e.tilt.and_then(|t| t.switch).unwrap_or("").to_owned(),
+ tilt_angle: e.tilt.map_or("", |t| t.angle).to_owned(),
+ }
+}
+
/// The edge of a shape or grain image, pixels.
#[uniffi::export]
pub fn source_size() -> u32 {
@@ -150,58 +194,88 @@ impl CanvasSession {
}
}
- /// The image the brush's shape (or, `grain`, its grain) uses now: its own, else the shipped
- /// one (`source_size` square greyscale, white = paint); empty for the round tip, or no grain.
- pub fn studio_source(&self, grain: bool) -> Vec<u8> {
+ /// The image the brush's `kind` of source uses now: its own, else the shipped one
+ /// (`source_size` square greyscale, white = paint); empty for the round tip, no grain, or a
+ /// material's amount all over.
+ pub fn studio_source(&self, kind: SourceKind) -> Vec<u8> {
let mut guard = self.shared.lock();
let st = &mut *guard;
let Some(brush) = st.studio_brush() else { return Vec::new() };
- let (own, shipped) =
- if grain { (&brush.grain.source, brush.grain.image) } else { (&brush.shape.source, brush.shape.image) };
+ let (own, shipped) = match kind {
+ SourceKind::Shape => (&brush.shape.source, brush.shape.image),
+ SourceKind::Grain => (&brush.grain.source, brush.grain.image),
+ SourceKind::Metallic => (&brush.metallic.source, brush.metallic.image),
+ SourceKind::Roughness => (&brush.roughness.source, brush.roughness.image),
+ };
if let Some(source) = own {
return source.pixels.to_vec();
}
- let images = if grain { textures::grains() } else { textures::shapes() };
+ let images = if kind.grain_like() { textures::grains() } else { textures::shapes() };
shipped.and_then(|i| images.into_iter().nth(i as usize)).map_or_else(Vec::new, |i| i.pixels)
}
- /// The brush's shape (or, `grain`, grain) becomes an image of the user's own (`source_size`
- /// square greyscale, white = paint). False if the pixels aren't that size.
- pub fn set_studio_source(&self, grain: bool, pixels: Vec<u8>) -> bool {
+ /// The brush's `kind` of source becomes an image of the user's own (`source_size` square
+ /// greyscale, white = paint). False if the pixels aren't that size.
+ pub fn set_studio_source(&self, kind: SourceKind, pixels: Vec<u8>) -> bool {
let Some(source) = Source::new(pixels) else { return false };
let mut st = self.shared.lock();
let Some(brush) = st.studio_change() else { return false };
// an image of the user's own: no longer the stock one its file named
- if grain {
- brush.grain.source = Some(source);
- brush.stock.grain = None;
- } else {
- brush.shape.source = Some(source);
- brush.stock.shape = None;
- }
+ let (own, _, stock) = sources(brush, kind);
+ *own = Some(source);
+ *stock = None;
true
}
- /// The brush's shape (or, `grain`, grain) becomes shipped image `index` of the source library.
- pub fn set_studio_shipped_source(&self, grain: bool, index: u32) -> bool {
- let count = if grain { textures::grains().len() } else { textures::shapes().len() };
+ /// The brush's `kind` of source becomes shipped image `index` of the source library (the
+ /// grains for all but the shape).
+ pub fn set_studio_shipped_source(&self, kind: SourceKind, index: u32) -> bool {
+ let count = if kind.grain_like() { textures::grains().len() } else { textures::shapes().len() };
if index as usize >= count {
return false;
}
let mut st = self.shared.lock();
let Some(brush) = st.studio_change() else { return false };
- if grain {
- brush.grain.source = None;
- brush.grain.image = Some(index);
- brush.stock.grain = None;
- } else {
- brush.shape.source = None;
- brush.shape.image = Some(index);
- brush.stock.shape = None;
- }
+ let (own, shipped, stock) = sources(brush, kind);
+ *own = None;
+ *shipped = Some(index);
+ *stock = None;
true
}
+ /// Studio control `key`'s own pressure curve, as x, y pairs (0..1); empty while it has none
+ /// (or for a slider that can't have one).
+ pub fn studio_slider_curve(&self, key: String) -> Vec<f32> {
+ let mut guard = self.shared.lock();
+ let st = &mut *guard;
+ let Some(brush) = st.studio_brush() else { return Vec::new() };
+ let curve = match procraft_engine::studio::slider_extras(&key).curve {
+ Some(SliderCurve::Own(kind)) => brush.pressure_curves.get(kind),
+ // the size's and opacity's own responses: on unless straight
+ Some(SliderCurve::Size) => Some(&brush.size_curve).filter(|c| **c != Curve::linear()),
+ Some(SliderCurve::Opacity) => Some(&brush.opacity_curve).filter(|c| **c != Curve::linear()),
+ None => None,
+ };
+ curve.map_or_else(Vec::new, |c| c.points().iter().flat_map(|p| [p.x, p.y]).collect())
+ }
+
+ /// Gives studio control `key` its own pressure curve through `points` (x, y pairs, 0..1), or
+ /// takes it away (`points` empty).
+ pub fn set_studio_slider_curve(&self, key: String, points: Vec<f32>) {
+ let curve = (points.len() >= 4).then(|| {
+ let pts: Vec<Vec2> = points.as_chunks::<2>().0.iter().map(|&[x, y]| Vec2::new(x, y)).collect();
+ Curve::new(&pts)
+ });
+ let mut st = self.shared.lock();
+ let Some(brush) = st.studio_change() else { return };
+ match procraft_engine::studio::slider_extras(&key).curve {
+ Some(SliderCurve::Own(kind)) => brush.pressure_curves.set(kind, curve),
+ Some(SliderCurve::Size) => brush.size_curve = curve.unwrap_or_else(Curve::linear),
+ Some(SliderCurve::Opacity) => brush.opacity_curve = curve.unwrap_or_else(Curve::linear),
+ None => {}
+ }
+ }
+
/// The pressure curve's points, as x, y pairs (0..1).
pub fn studio_curve(&self) -> Vec<f32> {
let mut guard = self.shared.lock();
@@ -328,18 +402,53 @@ impl CanvasSession {
st.pad_sample = false;
}
- /// Draws the pad's sample scribble across it, kept like a stroke until one's own replaces it.
+ /// Draws the pad's sample scribble across it (wrapped round the sphere when it is one), kept
+ /// like a stroke until one's own replaces it.
pub fn draw_sample_scribble(&self) {
{
let mut st = self.shared.lock();
let (w, h) = (st.doc.width() as f32, st.doc.height() as f32);
let scale = st.display_scale;
- st.pad_strokes = Some(vec![(crate::PointerKind::Stylus, pad_scribble(w, h, scale))]);
+ let scribble = if st.sphere.is_some() { sphere_scribble(w, h, scale) } else { pad_scribble(w, h, scale) };
+ st.pad_strokes = Some(vec![(crate::PointerKind::Stylus, scribble)]);
st.pad_sample = true;
}
self.replay_strokes();
}
+ /// Draws the pad as a sphere showing the brush's materials (`shown`), starting from its own
+ /// sample scribble each time; or flat again, with its strokes as they were.
+ pub fn show_sphere(&self, shown: bool) {
+ {
+ let mut guard = self.shared.lock();
+ let st = &mut *guard;
+ if shown == st.sphere.is_some() {
+ return;
+ }
+ st.finish_stroke();
+ if shown {
+ let flat = st.pad_strokes.as_mut().map(std::mem::take).unwrap_or_default();
+ st.sphere = Some(SpherePad { flat, flat_sample: st.pad_sample, preview: None, sources: [None, None] });
+ } else if let Some(sphere) = st.sphere.take() {
+ if let Some(kept) = st.pad_strokes.as_mut() {
+ *kept = sphere.flat;
+ }
+ st.pad_sample = sphere.flat_sample;
+ }
+ // the sphere shows what is painted over its own colour, the flat pad over the pad's
+ st.doc.background_visible = !shown;
+ if let Some(canvas) = st.canvas.as_mut() {
+ canvas.invalidate();
+ }
+ }
+ let flat_empty = !shown && self.shared.lock().pad_strokes.as_ref().is_none_or(Vec::is_empty);
+ if shown || flat_empty {
+ self.draw_sample_scribble();
+ } else {
+ self.replay_strokes();
+ }
+ }
+
/// A stroke of one's own starts on the pad: its sample scribble goes, if it is still there.
pub fn begin_own_stroke(&self) {
let sample = std::mem::replace(&mut self.shared.lock().pad_sample, false);
@@ -380,6 +489,96 @@ impl CanvasSession {
}
}
+/// Where `brush` keeps its `kind` of source: its own image, the shipped one, and the stock one its
+/// file named.
+fn sources(brush: &mut Brush, kind: SourceKind) -> (&mut Option<Source>, &mut Option<u32>, &mut Option<StockImage>) {
+ let stock = &mut brush.stock;
+ match kind {
+ SourceKind::Shape => (&mut brush.shape.source, &mut brush.shape.image, &mut stock.shape),
+ SourceKind::Grain => (&mut brush.grain.source, &mut brush.grain.image, &mut stock.grain),
+ SourceKind::Metallic => material(&mut brush.metallic, &mut stock.metallic),
+ SourceKind::Roughness => material(&mut brush.roughness, &mut stock.roughness),
+ }
+}
+
+fn material<'a>(
+ m: &'a mut MaterialSource,
+ stock: &'a mut Option<StockImage>,
+) -> (&'a mut Option<Source>, &'a mut Option<u32>, &'a mut Option<StockImage>) {
+ (&mut m.source, &mut m.image, stock)
+}
+
+/// The drawing pad while it is a sphere: the flat pad's strokes set aside (and whether they were
+/// its sample scribble), the preview once drawn, and the brush's material sources as last given
+/// to it (a key for each and its pixels).
+#[cfg_attr(not(target_os = "android"), allow(dead_code))]
+pub(crate) struct SpherePad {
+ flat: Vec<(PointerKind, Vec<PenSample>)>,
+ flat_sample: bool,
+ preview: Option<SpherePreview>,
+ sources: [Option<(u64, Arc<Vec<u8>>)>; 2],
+}
+
+/// What tells a material source's image from another's: its own image's, else the shipped one's.
+#[cfg_attr(not(target_os = "android"), allow(dead_code))]
+fn source_key(m: &MaterialSource) -> Option<u64> {
+ m.source.as_ref().map(|s| s.id).or_else(|| m.image.map(|i| (1 << 63) | u64::from(i)))
+}
+
+#[cfg_attr(not(target_os = "android"), allow(dead_code))]
+impl State {
+ /// Draws the pad as a sphere into `target` (`size`): [`SPHERE_RADIUS_PT`] round, in its
+ /// middle, showing the canvas painted with the pad's brush, its metalness and roughness.
+ pub(crate) fn render_sphere(
+ &mut self,
+ target: &wgpu::TextureView,
+ format: wgpu::TextureFormat,
+ size: (u32, u32),
+ convert: Option<[[f32; 3]; 3]>,
+ ) {
+ let (metallic, roughness, tiles, materials) = {
+ let b = self.brush(ToolKind::Paint);
+ let tile = |key: &str| (b.setting(key) * MAX_GRAIN_SCALE).max(4.0);
+ (
+ b.setting("metallic_amount"),
+ b.setting("roughness_amount"),
+ [tile("metallic_scale"), tile("roughness_scale")],
+ [b.metallic.clone(), b.roughness.clone()],
+ )
+ };
+ let to_canvas = self.view.and_then(|v| v.to_screen().inverse()).unwrap_or(Affine::IDENTITY);
+ let behind = self.doc.background;
+ let (Some(gpu), Some(canvas), Some(sphere)) = (self.gpu.as_ref(), self.canvas.as_mut(), self.sphere.as_mut())
+ else {
+ return;
+ };
+ canvas.render(gpu, &mut self.doc, None);
+ for (slot, m) in sphere.sources.iter_mut().zip(&materials) {
+ let key = source_key(m);
+ if slot.as_ref().map(|(k, _)| *k) != key {
+ *slot = key.zip(crate::brush_files::material_pixels(m)).map(|(k, p)| (k, Arc::new(p)));
+ }
+ }
+ let [metallic_source, roughness_source] =
+ sphere.sources.each_ref().map(|s| s.as_ref().map(|(k, p)| (*k, p.as_slice())));
+ let look = SphereLook {
+ metallic,
+ roughness,
+ metallic_source,
+ roughness_source,
+ metallic_tile: tiles[0],
+ roughness_tile: tiles[1],
+ behind,
+ convert,
+ };
+ let (w, h) = (size.0 as f32, size.1 as f32);
+ let Affine { a, b, c, d, e, f } = to_canvas;
+ let radius = SPHERE_RADIUS_PT * self.display_scale;
+ let preview = sphere.preview.get_or_insert_with(|| SpherePreview::new(gpu, format));
+ preview.render(gpu, target, [w / 2.0, h / 2.0], radius, canvas, [a, b, c, d, e, f], &look);
+ }
+}
+
/// The studio's About page: who made the brush ("" for ProCraft's own) with their picture and
/// signature (PNG) if it has them, and when its reset point was made (seconds since 1970).
#[derive(uniffi::Record)]
@@ -564,6 +763,32 @@ fn pad_scribble(w: f32, h: f32, scale: f32) -> Vec<crate::PenSample> {
.collect()
}
+/// The sphere's radius on the pad, points, whatever the pad's size (as the reference's, which runs
+/// a little past a landscape pad's sides).
+const SPHERE_RADIUS_PT: f32 = 240.25;
+
+/// How the sample scribble wraps round the sphere: each of its points (see [`SCRIBBLE`]) this many
+/// radians of longitude and latitude, the scribble's middle turned this far right and up from the
+/// sphere's front (as the reference's lies, drawn on the sphere's surface).
+const SPHERE_LONGITUDE: f32 = 0.003_538_5;
+const SPHERE_LATITUDE: f32 = 0.001_788_6;
+const SPHERE_TURN: f32 = 0.089_121;
+const SPHERE_TILT: f32 = -0.014_435;
+
+/// The sample scribble wrapped round the sphere on a pad `w` x `h` (canvas pixels, `scale` a
+/// point): the sphere in its middle, seen straight on.
+fn sphere_scribble(w: f32, h: f32, scale: f32) -> Vec<crate::PenSample> {
+ let radius = SPHERE_RADIUS_PT * scale;
+ pad_scribble(0.0, 0.0, 1.0)
+ .into_iter()
+ .map(|s| {
+ let lon = s.x * SPHERE_LONGITUDE + SPHERE_TURN;
+ let lat = s.y * SPHERE_LATITUDE + SPHERE_TILT;
+ crate::PenSample { x: w / 2.0 + radius * lat.cos() * lon.sin(), y: h / 2.0 + radius * lat.sin(), ..s }
+ })
+ .collect()
+}
+
/// A smooth path through `points` (centripetal Catmull-Rom, so no loops or overshoots at sharp
/// turns), `per` points to each span.
fn through(points: &[Vec2], per: usize) -> Vec<Vec2> {
diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rs
index 48a22d3..f125f54 100644
--- a/apps/procraft-android/src/tests.rs
+++ b/apps/procraft-android/src/tests.rs
@@ -723,6 +723,8 @@ fn an_imported_brush_shows_its_own_preview_until_changed() {
&Pictures {
shape_png: &shape,
grain_png: None,
+ metallic_png: None,
+ roughness_png: None,
thumbnail_png: &thumbnail,
author_png: None,
signature_png: None,
@@ -781,28 +783,89 @@ fn a_brush_keeps_its_images_and_their_sizes() {
let sizes = vec!["max_size".to_owned()];
// its own shape (sizes kept in that shape's unit), a shipped grain
s.studio_begin();
- assert!(s.set_studio_source(false, vec![200; size * size]));
- assert!(s.set_studio_shipped_source(true, 2));
+ assert!(s.set_studio_source(crate::studio::SourceKind::Shape, vec![200; size * size]));
+ assert!(s.set_studio_shipped_source(crate::studio::SourceKind::Grain, 2));
s.set_studio_setting("max_size".to_owned(), 0.6);
- let grain = s.studio_source(true);
+ let grain = s.studio_source(crate::studio::SourceKind::Grain);
s.studio_end(true);
let Some(other) = session(100, 100) else { return };
assert!(other.load_brush_library(s.saved_brush_library()));
other.studio_begin();
assert!((other.studio_settings(sizes.clone())[0] - 0.6).abs() < 1e-3);
- assert_eq!(other.studio_source(false), vec![200; size * size]);
- assert_eq!(other.studio_source(true), grain);
+ assert_eq!(other.studio_source(crate::studio::SourceKind::Shape), vec![200; size * size]);
+ assert_eq!(other.studio_source(crate::studio::SourceKind::Grain), grain);
other.studio_end(false);
// a shipped shape in place of the round tip
s.studio_begin();
s.studio_reset();
- assert!(s.set_studio_shipped_source(false, 1));
- let shape = s.studio_source(false);
+ assert!(s.set_studio_shipped_source(crate::studio::SourceKind::Shape, 1));
+ let shape = s.studio_source(crate::studio::SourceKind::Shape);
s.studio_end(true);
let Some(third) = session(100, 100) else { return };
assert!(third.load_brush_library(s.saved_brush_library()));
third.studio_begin();
- assert_eq!(third.studio_source(false), shape);
+ assert_eq!(third.studio_source(crate::studio::SourceKind::Shape), shape);
+}
+
+#[test]
+fn a_brush_keeps_what_it_paints_materials_through() {
+ use crate::studio::SourceKind::{Metallic, Roughness};
+ let Some(s) = session(100, 100) else { return };
+ let size = crate::studio::source_size() as usize;
+ let amounts = || vec!["metallic_amount".to_owned(), "roughness_amount".to_owned(), "metallic_scale".to_owned()];
+ s.studio_begin();
+ // not metallic, half rough, each source tiled at a tenth, and neither an image (the amount all over)
+ assert_eq!(s.studio_settings(amounts()), vec![0.0, 0.5, 0.1]);
+ assert!(s.studio_source(Metallic).is_empty() && s.studio_source(Roughness).is_empty());
+ assert!(s.set_studio_source(Metallic, vec![90; size * size]));
+ assert!(s.set_studio_shipped_source(Roughness, 3));
+ s.set_studio_setting("metallic_amount".to_owned(), 0.7);
+ let rough = s.studio_source(Roughness);
+ assert_eq!(rough.len(), size * size);
+ s.studio_end(true);
+ // kept with the library
+ let Some(other) = session(100, 100) else { return };
+ assert!(other.load_brush_library(s.saved_brush_library()));
+ other.studio_begin();
+ assert_eq!(other.studio_source(Metallic), vec![90; size * size]);
+ assert_eq!(other.studio_source(Roughness), rough);
+ assert!((other.studio_settings(amounts())[0] - 0.7).abs() < 1e-3);
+ other.studio_end(false);
+ // and with a brush file: both images its own, the amount as it was
+ let b = s.current_brush();
+ let set = other.import_brushes(s.brush_as_file(b.set, b.index).unwrap()).unwrap();
+ assert!(other.select_brush(set, 0));
+ other.studio_begin();
+ assert_eq!(other.studio_source(Metallic), vec![90; size * size]);
+ assert_eq!(other.studio_source(Roughness), rough);
+ assert!((other.studio_settings(amounts())[0] - 0.7).abs() < 1e-3);
+}
+
+#[test]
+fn a_studio_slider_has_its_own_pressure_curve_and_tilt() {
+ let s = CanvasSession::new(64, 64);
+ s.studio_begin();
+ // which sliders offer what
+ let scatter = crate::studio::slider_extras("scatter".into());
+ assert!(scatter.pressure && !scatter.tilt);
+ let count = crate::studio::slider_extras("count".into());
+ assert!(count.pressure && count.tilt && count.tilt_switch == "count_tilt");
+ let gradation = crate::studio::slider_extras("tilt_gradation".into());
+ assert!(!gradation.pressure && gradation.tilt && gradation.tilt_switch.is_empty());
+ // a curve given, read back, and taken away
+ assert!(s.studio_slider_curve("scatter".into()).is_empty());
+ s.set_studio_slider_curve("scatter".into(), vec![0.0, 0.0, 0.5, 0.8, 1.0, 1.0]);
+ assert_eq!(s.studio_slider_curve("scatter".into()), vec![0.0, 0.0, 0.5, 0.8, 1.0, 1.0]);
+ s.set_studio_slider_curve("scatter".into(), Vec::new());
+ assert!(s.studio_slider_curve("scatter".into()).is_empty());
+ // the size's own response: straight reads as off
+ s.set_studio_slider_curve("pressure_size".into(), vec![0.0, 0.0, 0.5, 0.2, 1.0, 1.0]);
+ assert_eq!(s.studio_slider_curve("pressure_size".into()).len(), 6);
+ s.set_studio_slider_curve("pressure_size".into(), Vec::new());
+ assert!(s.studio_slider_curve("pressure_size".into()).is_empty());
+ // a slider without a curve keeps none
+ s.set_studio_slider_curve("spacing".into(), vec![0.0, 0.0, 1.0, 1.0]);
+ assert!(s.studio_slider_curve("spacing".into()).is_empty());
}
#[test]
@@ -1601,9 +1664,9 @@ fn a_brush_paints_with_a_shape_of_the_users_own_and_keeps_it() {
let n = crate::studio::source_size() as usize;
// a filled square: square stamps where the round pen's are round
s.studio_begin();
- assert!(!s.set_studio_source(false, vec![255; 10]), "the wrong size is refused");
- assert!(s.set_studio_source(false, vec![255; n * n]));
- assert_eq!(s.studio_source(false).len(), n * n);
+ assert!(!s.set_studio_source(crate::studio::SourceKind::Shape, vec![255; 10]), "the wrong size is refused");
+ assert!(s.set_studio_source(crate::studio::SourceKind::Shape, vec![255; n * n]));
+ assert_eq!(s.studio_source(crate::studio::SourceKind::Shape).len(), n * n);
s.studio_end(true);
s.stroke_begin(PointerKind::Finger, vec![sample(50.0, 50.0, 0.0)]);
s.stroke_end(vec![]);
@@ -1617,10 +1680,10 @@ fn a_brush_paints_with_a_shape_of_the_users_own_and_keeps_it() {
let t = CanvasSession::new(64, 64);
assert!(t.load_brush_library(saved));
t.studio_begin();
- assert_eq!(t.studio_source(false), vec![255; n * n]);
+ assert_eq!(t.studio_source(crate::studio::SourceKind::Shape), vec![255; n * n]);
// a shipped shape again
- assert!(t.set_studio_shipped_source(false, 0));
- assert_ne!(t.studio_source(false), vec![255; n * n]);
+ assert!(t.set_studio_shipped_source(crate::studio::SourceKind::Shape, 0));
+ assert_ne!(t.studio_source(crate::studio::SourceKind::Shape), vec![255; n * n]);
assert_eq!(crate::studio::source_library(true).len(), procraft_engine::textures::grains().len());
}
@@ -2006,6 +2069,63 @@ fn a_pad_keeps_its_strokes_and_its_sample_gives_way() {
assert_eq!(kept(&pad), Some(vec![]));
}
+#[test]
+fn the_pad_turns_into_a_sphere_of_its_own_and_back() {
+ let Some(pad) = session(300, 300) else { return };
+ // where each kept stroke's samples are
+ let kept = |p: &CanvasSession| {
+ let k = p.shared.lock().pad_strokes.clone().unwrap_or_default();
+ k.iter().map(|(_, s)| s.iter().map(|p| (p.x, p.y)).collect::<Vec<_>>()).collect::<Vec<_>>()
+ };
+ pad.keep_strokes();
+ pad.set_background_color(0.1, 0.1, 0.1, true);
+ // half a pixel a point: the sphere 120 pixels round
+ pad.set_display_scale(0.5);
+ pad.draw_sample_scribble();
+ pad.begin_own_stroke();
+ pad.stroke_begin(PointerKind::Finger, vec![sample(10.0, 10.0, 0.0)]);
+ pad.stroke_end(vec![sample(290.0, 20.0, 32.0)]);
+ let flat = kept(&pad);
+ pad.show_sphere(true);
+ // its own sample scribble, on the sphere's face (in the pad's middle), over nothing
+ {
+ let st = pad.shared.lock();
+ assert!(st.pad_sample && !st.doc.background_visible);
+ }
+ let k = kept(&pad);
+ assert_eq!(k.len(), 1);
+ assert!(k[0].iter().all(|(x, y)| (x - 150.0).hypot(y - 150.0) < 120.0));
+ // drawn: the pad's colour round the sphere, the sphere lit inside
+ let px = {
+ let mut guard = pad.shared.lock();
+ let st = &mut *guard;
+ let format = procraft_gpu::wgpu::TextureFormat::Rgba8Unorm;
+ let gpu = st.gpu.clone().unwrap();
+ let target = gpu.device.create_texture(&procraft_gpu::wgpu::TextureDescriptor {
+ label: Some("test frame"),
+ size: procraft_gpu::wgpu::Extent3d { width: 300, height: 300, depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: procraft_gpu::wgpu::TextureDimension::D2,
+ format,
+ usage: procraft_gpu::wgpu::TextureUsages::RENDER_ATTACHMENT | procraft_gpu::wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ });
+ let view = target.create_view(&procraft_gpu::wgpu::TextureViewDescriptor::default());
+ st.render_sphere(&view, format, (300, 300), None);
+ assert_eq!(gpu.errors(), 0, "GPU validation errors");
+ procraft_gpu::read_texture(&gpu, &target, 300, 300).unwrap()
+ };
+ let at = |x: usize, y: usize| px[(y * 300 + x) * 4];
+ assert!(at(2, 2).abs_diff(26) <= 1, "{}", at(2, 2));
+ assert!(at(150, 40) > at(2, 2) + 30, "{} {}", at(150, 40), at(2, 2));
+ // flat again: its strokes as they were, over the pad's colour
+ pad.show_sphere(false);
+ assert_eq!(kept(&pad), flat);
+ let st = pad.shared.lock();
+ assert!(!st.pad_sample && st.doc.background_visible && st.sphere.is_none());
+}
+
#[test]
fn choosing_a_layer_is_an_undo_step() {
let Some(s) = session(32, 32) else { return };
@@ -2259,6 +2379,8 @@ fn a_brush_keeps_its_maker_and_a_reset_point() {
&Pictures {
shape_png: &shape,
grain_png: None,
+ metallic_png: None,
+ roughness_png: None,
thumbnail_png: &shape,
author_png: Some(&face),
signature_png: Some(b"not a png"),
@@ -2395,11 +2517,24 @@ fn stock_images_a_file_names_are_kept_and_named_again() {
let file = brushfile::write(
&Brush {
name: "Stocked".to_owned(),
- stock: StockImages { shape: named("Hard-Round.png"), grain: named("Old-Recycled-Paper.png") },
+ stock: StockImages {
+ shape: named("Hard-Round.png"),
+ grain: named("Old-Recycled-Paper.png"),
+ metallic: named("Brushed-Metal.png"),
+ roughness: None,
+ },
..Brush::round_pen()
},
"",
- &Pictures { shape_png: &png, grain_png: None, thumbnail_png: &png, author_png: None, signature_png: None },
+ &Pictures {
+ shape_png: &png,
+ grain_png: None,
+ metallic_png: None,
+ roughness_png: None,
+ thumbnail_png: &png,
+ author_png: None,
+ signature_png: None,
+ },
);
let set = s.import_brushes(file).unwrap();
{
@@ -2417,10 +2552,15 @@ fn stock_images_a_file_names_are_kept_and_named_again() {
let b = &st.library[set].brushes[0];
assert_eq!(b.stock.shape.as_ref().map(|g| (g.name.as_str(), g.inverted)), Some(("Hard-Round.png", true)));
assert_eq!(b.grain.image, Some(grain::RECYCLED));
+ // a stock metalness source we have nothing like: the amount all over, its name kept
+ assert_eq!(b.metallic, procraft_engine::brush::MaterialSource::default());
+ assert!(b.stock.metallic.is_some() && b.stock.roughness.is_none());
set as u32
};
// written out, it names them again
let out = brushfile::read(&t.brush_as_file(set, 0).unwrap()).unwrap();
assert_eq!(out.grain, Texture::Stock { name: "Old-Recycled-Paper.png".to_owned(), inverted: true });
+ assert_eq!(out.metallic, Texture::Stock { name: "Brushed-Metal.png".to_owned(), inverted: true });
+ assert_eq!(out.roughness, Texture::None);
assert_eq!(out.shape, Texture::Stock { name: "Hard-Round.png".to_owned(), inverted: true });
}
diff --git a/crates/engine/src/brush.rs b/crates/engine/src/brush.rs
index 5bf2476..87fea44 100644
--- a/crates/engine/src/brush.rs
+++ b/crates/engine/src/brush.rs
@@ -328,6 +328,16 @@ impl Default for Shape {
}
}
+/// What a brush paints a model's metalness or roughness through, tiled like a grain: white takes
+/// the brush's amount, black none of it. Neither image: the amount all over.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct MaterialSource {
+ /// A grain image (see `textures::grain`), or none.
+ pub image: Option<u32>,
+ /// An image of the user's own, in place of `image`.
+ pub source: Option<Source>,
+}
+
/// The texture inside the stroke.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Grain {
@@ -416,6 +426,9 @@ pub struct Brush {
pub touch_taper: Taper,
pub shape: Shape,
pub grain: Grain,
+ /// What it paints a model's metalness and roughness through (their amounts are studio controls).
+ pub metallic: MaterialSource,
+ pub roughness: MaterialSource,
pub tilt: Tilt,
pub rendering: Rendering,
/// Brush studio controls the engine does not draw yet, by key (see `studio`).
@@ -429,16 +442,19 @@ pub struct Brush {
pub author: Option<Author>,
/// What resetting the brush puts back: set the first time it is opened in the studio.
pub reset_point: Option<ResetPoint>,
- /// The stock images its file named for its shape and grain, which our own stand in for.
+ /// The stock images its file named for its shape, grain and materials, which our own stand in
+ /// for.
pub stock: StockImages,
}
-/// The stock images a brush's file names for its shape and grain (drawn with ours standing in),
-/// kept so that they are named again when the brush is written out.
+/// The stock images a brush's file names for its shape, grain, metalness and roughness (drawn with
+/// ours standing in), kept so that they are named again when the brush is written out.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StockImages {
pub shape: Option<StockImage>,
pub grain: Option<StockImage>,
+ pub metallic: Option<StockImage>,
+ pub roughness: Option<StockImage>,
}
/// A stock image as a brush file names it, and whether the file has it inverted.
@@ -563,6 +579,8 @@ impl Brush {
touch_taper: Taper { start: 0.1, end: 0.1, size: 0.6, opacity: 0.0 },
shape: Shape::default(),
grain: Grain::default(),
+ metallic: MaterialSource::default(),
+ roughness: MaterialSource::default(),
tilt: Tilt::default(),
rendering: Rendering::BuildUp,
extra: BTreeMap::new(),
diff --git a/crates/engine/src/brushfile.rs b/crates/engine/src/brushfile.rs
index 6935457..8e3bb92 100644
--- a/crates/engine/src/brushfile.rs
+++ b/crates/engine/src/brushfile.rs
@@ -35,6 +35,9 @@ pub struct BrushFile {
pub pressure_curves: Vec<(PressureCurve, Vec<Vec2>)>,
pub shape: Texture,
pub grain: Texture,
+ /// What it paints a model's metalness and roughness through.
+ pub metallic: Texture,
+ pub roughness: Texture,
/// Where the size and opacity sliders start when it is picked, 0..1.
pub paint_size: f32,
pub paint_opacity: f32,
@@ -268,6 +271,7 @@ const PLAIN: &[(&str, &str, Kept)] = &[
("stamp_lightness_tilt", "lightnessJitterTilt", Kept::Switch),
("stamp_lightness_tilt_angle", "lightnessJitterTiltAngle", Kept::Same),
("stamp_darkness_tilt", "darknessJitterTilt", Kept::Switch),
+ ("stamp_darkness_tilt_angle", "darknessJitterTiltAngle", Kept::Same),
("stamp_secondary_tilt", "secondaryColorJitterTilt", Kept::Switch),
("stamp_secondary_tilt_angle", "secondaryColorJitterTiltAngle", Kept::Same),
("attack_tilt", "attackTilt", Kept::Switch),
@@ -295,6 +299,14 @@ const PLAIN: &[(&str, &str, Kept)] = &[
("preview_pressure_scale", "previewPressureScale", Kept::Times(2.0)),
("preview_wet_mix", "previewWetMixEnabled", Kept::Switch),
("preview_tilt", "previewTiltEnabled", Kept::Switch),
+ // the materials it paints on a model: metalness, roughness and height, each source tiled as
+ // the grain is
+ ("metallic_amount", "metallicAmount", Kept::Same),
+ ("metallic_scale", "metallicScale", Kept::Squared16),
+ ("roughness_amount", "roughnessAmount", Kept::Same),
+ ("roughness_scale", "roughnessScale", Kept::Squared16),
+ ("height_amount", "heightAmount", Kept::Same),
+ ("height_scale", "heightScale", Kept::Squared16),
("pressure_size_response", "dynamicsPressureSizeSpeed", Kept::Same),
("pressure_opacity_response", "dynamicsPressureOpacitySpeed", Kept::Same),
("pressure_bleed_response", "dynamicsPressureBleedSpeed", Kept::Same),
@@ -603,6 +615,8 @@ fn read_in(zip: &ZipReader<'_>, prefix: &str) -> Option<BrushFile> {
pressure_curves,
shape: texture("bundledShapePath", "Shape.png", "shapeInverted"),
grain: texture("bundledGrainPath", "Grain.png", "textureInverted"),
+ metallic: texture("bundledMetallicPath", "Metallic.png", "metallicGrainInverted"),
+ roughness: texture("bundledRoughnessPath", "Roughness.png", "roughnessGrainInverted"),
paint_size: f.num("paintSize").unwrap_or(0.5) as f32,
paint_opacity: f.num("paintOpacity").unwrap_or(1.0) as f32,
notches,
@@ -622,6 +636,9 @@ pub struct Pictures<'a> {
pub shape_png: &'a [u8],
/// The grain (PNG), or none for no grain.
pub grain_png: Option<&'a [u8]>,
+ /// The metalness and roughness sources (PNG), or none for the amount all over.
+ pub metallic_png: Option<&'a [u8]>,
+ pub roughness_png: Option<&'a [u8]>,
/// The brush's preview stroke (PNG).
pub thumbnail_png: &'a [u8],
/// Its author's picture and signature (PNG), if it has them.
@@ -723,6 +740,8 @@ fn add_brush(zip: &mut ZipWriter, prefix: &str, brush: &Brush, author: &str, pic
for (stock, path, inverted) in [
(&brush.stock.shape, "bundledShapePath", "shapeInverted"),
(&brush.stock.grain, "bundledGrainPath", "textureInverted"),
+ (&brush.stock.metallic, "bundledMetallicPath", "metallicGrainInverted"),
+ (&brush.stock.roughness, "bundledRoughnessPath", "roughnessGrainInverted"),
] {
match stock {
Some(s) => {
@@ -771,8 +790,14 @@ fn add_brush(zip: &mut ZipWriter, prefix: &str, brush: &Brush, author: &str, pic
let archive = b.finish(root);
zip.add(&format!("{prefix}Brush.archive"), &archive);
zip.add(&format!("{prefix}Shape.png"), pictures.shape_png);
- if let Some(grain) = pictures.grain_png {
- zip.add(&format!("{prefix}Grain.png"), grain);
+ for (name, png) in [
+ ("Grain.png", pictures.grain_png),
+ ("Metallic.png", pictures.metallic_png),
+ ("Roughness.png", pictures.roughness_png),
+ ] {
+ if let Some(png) = png {
+ zip.add(&format!("{prefix}{name}"), png);
+ }
}
zip.add(&format!("{prefix}QuickLook/Thumbnail.png"), pictures.thumbnail_png);
for (path, png) in [(AUTHOR_PICTURE, pictures.author_png), (SIGNATURE, pictures.signature_png)] {
@@ -811,6 +836,8 @@ mod tests {
brush.set_setting("count", 4.0 / 15.0);
brush.set_setting("wet_pull", 0.6);
brush.set_setting("input_style", 1.0);
+ brush.set_setting("metallic_amount", 0.7);
+ brush.set_setting("roughness_scale", 0.3);
brush.notches.sizes[0] = vec![0.25, 0.5];
brush.size_curve = crate::curve::Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(0.42, 0.2), Vec2::new(1.0, 1.0)]);
let file = write(
@@ -819,6 +846,8 @@ mod tests {
&Pictures {
shape_png: b"shape",
grain_png: Some(b"grain"),
+ metallic_png: Some(b"metal"),
+ roughness_png: None,
thumbnail_png: b"thumb",
author_png: Some(b"face"),
signature_png: None,
@@ -831,6 +860,8 @@ mod tests {
assert_eq!(back.signature, None);
assert_eq!(back.shape, Texture::Image { bytes: b"shape".to_vec(), inverted: false });
assert_eq!(back.grain, Texture::Image { bytes: b"grain".to_vec(), inverted: false });
+ assert_eq!(back.metallic, Texture::Image { bytes: b"metal".to_vec(), inverted: false });
+ assert_eq!(back.roughness, Texture::None);
assert_eq!(back.notches.sizes[0], vec![0.25, 0.5]);
let size_curve = back.size_curve.as_ref().unwrap();
assert!((size_curve[1] - Vec2::new(0.42, 0.2)).length() < 1e-5);
@@ -854,6 +885,10 @@ mod tests {
"flow",
"pressure_size",
"grain_scale",
+ "metallic_amount",
+ "roughness_amount",
+ "roughness_scale",
+ "metallic_scale",
] {
assert!(
(again.setting(key) - brush.setting(key)).abs() < 1e-3,
@@ -873,6 +908,8 @@ mod tests {
let pictures = Pictures {
shape_png: b"s",
grain_png: None,
+ metallic_png: None,
+ roughness_png: None,
thumbnail_png: b"t",
author_png: None,
signature_png: None,
@@ -892,8 +929,15 @@ mod tests {
let mut brush = Brush::round_pen();
brush.set_setting("blend_mode", BRUSH_BEHIND as f32);
brush.set_setting("burnt_blend", BRUSH_BEHIND as f32);
- let pictures =
- Pictures { shape_png: b"s", grain_png: None, thumbnail_png: b"t", author_png: None, signature_png: None };
+ let pictures = Pictures {
+ shape_png: b"s",
+ grain_png: None,
+ metallic_png: None,
+ roughness_png: None,
+ thumbnail_png: b"t",
+ author_png: None,
+ signature_png: None,
+ };
let back = read(&write(&brush, "", &pictures)).unwrap();
for key in ["blend_mode", "burnt_blend"] {
let mode = back.settings.iter().find(|(k, _)| k == key).map(|(_, v)| *v);
@@ -923,6 +967,8 @@ mod tests {
let pictures = || Pictures {
shape_png: b"shape",
grain_png: None,
+ metallic_png: None,
+ roughness_png: None,
thumbnail_png: b"thumb",
author_png: None,
signature_png: None,
@@ -946,8 +992,15 @@ mod tests {
let bend = Curve::new(&[Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.8), Vec2::new(1.0, 1.0)]);
brush.pressure_curves.set(PressureCurve::Count, Some(bend));
brush.pressure_curves.set(PressureCurve::HueJitter, Some(Curve::linear()));
- let pictures =
- Pictures { shape_png: b"s", grain_png: None, thumbnail_png: b"t", author_png: None, signature_png: None };
+ let pictures = Pictures {
+ shape_png: b"s",
+ grain_png: None,
+ metallic_png: None,
+ roughness_png: None,
+ thumbnail_png: b"t",
+ author_png: None,
+ signature_png: None,
+ };
let back = read(&write(&brush, "", &pictures)).unwrap();
let kinds: Vec<PressureCurve> = back.pressure_curves.iter().map(|(k, _)| *k).collect();
assert_eq!(kinds, [PressureCurve::Count, PressureCurve::HueJitter]);
diff --git a/crates/engine/src/studio.rs b/crates/engine/src/studio.rs
index 534e251..2a03a33 100644
--- a/crates/engine/src/studio.rs
+++ b/crates/engine/src/studio.rs
@@ -4,7 +4,7 @@
use std::f32::consts::PI;
-use crate::brush::{BRUSH_BEHIND, Brush, FLOW_POWER, GRAIN_LINEAR_HEIGHT, GrainMode, Rendering};
+use crate::brush::{BRUSH_BEHIND, Brush, FLOW_POWER, GRAIN_LINEAR_HEIGHT, GrainMode, PressureCurve, Rendering};
use crate::document::BlendMode;
/// The most size (in brush-file units, see [`Brush::size_unit`]) the size controls can reach, for
@@ -52,6 +52,12 @@ const STARTS: &[(&str, f32)] = &[
("preview_pressure_scale", 0.5),
// the hover outline in contrasting rings
("cursor_outline", 1.0),
+ // half rough, its height halfway, each source tiled at a tenth (the file's 0.16)
+ ("roughness_amount", 0.5),
+ ("height_amount", 0.5),
+ ("metallic_scale", 0.1),
+ ("roughness_scale", 0.1),
+ ("height_scale", 0.1),
];
/// The controls drawn from the brush's own fields (the others are kept in its `extra`).
@@ -342,10 +348,139 @@ impl Brush {
}
}
+/// A studio slider's own pressure curve: one of the brush's [`PressureCurve`]s, or its size's or
+/// opacity's own response to pressure.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SliderCurve {
+ Own(PressureCurve),
+ Size,
+ Opacity,
+}
+
+/// A studio slider's own tilt: the switch that turns it on (none: the slider is the tilt's own
+/// amount) and the control holding the angle it starts from.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SliderTilt {
+ pub switch: Option<&'static str>,
+ pub angle: &'static str,
+}
+
+/// What a studio slider's keypad offers besides typing its value: its own pressure curve and its
+/// own tilt, those it has (as the reference's keypads show them).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct SliderExtras {
+ pub curve: Option<SliderCurve>,
+ pub tilt: Option<SliderTilt>,
+}
+
+/// The extras of the slider for control `key`.
+pub fn slider_extras(key: &str) -> SliderExtras {
+ use PressureCurve as P;
+ use SliderCurve::Own;
+ let tilt = |switch, angle| Some(SliderTilt { switch: Some(switch), angle });
+ let angle_only = |angle| Some(SliderTilt { switch: None, angle });
+ let (curve, tilt) = match key {
+ "spacing_jitter" => (Some(Own(P::SpacingJitter)), None),
+ "jitter_lateral" => (Some(Own(P::LateralJitter)), tilt("jitter_lateral_tilt", "jitter_lateral_tilt_angle")),
+ "jitter_linear" => (Some(Own(P::LinearJitter)), tilt("jitter_linear_tilt", "jitter_linear_tilt_angle")),
+ "scatter" => (Some(Own(P::Scatter)), None),
+ "count" => (Some(Own(P::Count)), tilt("count_tilt", "count_tilt_angle")),
+ "count_jitter" => (Some(Own(P::CountJitter)), None),
+ "pressure_roundness" => (Some(Own(P::Roundness)), None),
+ "tilt_roundness" => (None, angle_only("roundness_tilt_angle")),
+ "roundness_jitter_y" => (Some(Own(P::RoundnessJitterY)), None),
+ "roundness_jitter_x" => (Some(Own(P::RoundnessJitterX)), None),
+ "grain_movement" => (Some(Own(P::GrainMovement)), None),
+ "grain_scale" => (Some(Own(P::GrainScale)), None),
+ "grain_zoom" => (Some(Own(P::GrainZoom)), None),
+ "grain_depth" => (Some(Own(P::GrainDepth)), tilt("grain_depth_tilt", "grain_depth_tilt_angle")),
+ "grain_depth_jitter" => (Some(Own(P::GrainDepthJitter)), None),
+ "wet_dilution" => (Some(Own(P::Dilution)), None),
+ "wet_charge" => (Some(Own(P::Charge)), None),
+ "wet_attack" => (Some(Own(P::Attack)), tilt("attack_tilt", "attack_tilt_angle")),
+ "wet_pull" => (Some(Own(P::WetPull)), None),
+ "wet_grade" => (Some(Own(P::WetGrade)), None),
+ "wet_blur" => (Some(Own(P::WetBlur)), None),
+ "wet_blur_jitter" => (Some(Own(P::WetBlurJitter)), None),
+ "wet_jitter" => (Some(Own(P::WetnessJitter)), None),
+ "stamp_hue" => (Some(Own(P::HueJitter)), tilt("stamp_hue_tilt", "stamp_hue_tilt_angle")),
+ "stamp_saturation" => {
+ (Some(Own(P::SaturationJitter)), tilt("stamp_saturation_tilt", "stamp_saturation_tilt_angle"))
+ }
+ "stamp_lightness" => {
+ (Some(Own(P::LightnessJitter)), tilt("stamp_lightness_tilt", "stamp_lightness_tilt_angle"))
+ }
+ "stamp_darkness" => (Some(Own(P::DarknessJitter)), tilt("stamp_darkness_tilt", "stamp_darkness_tilt_angle")),
+ "stamp_secondary" => {
+ (Some(Own(P::SecondaryJitter)), tilt("stamp_secondary_tilt", "stamp_secondary_tilt_angle"))
+ }
+ "pressure_hue" => (Some(Own(P::Hue)), None),
+ "pressure_saturation" => (Some(Own(P::Saturation)), None),
+ "pressure_brightness" => (Some(Own(P::Brightness)), None),
+ "pressure_secondary" => (Some(Own(P::Secondary)), None),
+ "tilt_hue" => (None, angle_only("hue_tilt_angle")),
+ "tilt_saturation" => (None, angle_only("saturation_tilt_angle")),
+ "tilt_brightness" => (None, angle_only("brightness_tilt_angle")),
+ "tilt_secondary" => (None, angle_only("secondary_tilt_angle")),
+ "jitter_size" => (Some(Own(P::SizeJitter)), None),
+ "jitter_opacity" => (Some(Own(P::OpacityJitter)), None),
+ // the stylus page's pressure: size, the opacity (kept as "pressure_flow") and the flow
+ // (kept as "pressure_opacity"), bleed; its tilt the angles each starts from
+ "pressure_size" => (Some(SliderCurve::Size), None),
+ "pressure_flow" => (Some(SliderCurve::Opacity), None),
+ "pressure_opacity" => (Some(Own(P::Flow)), None),
+ "pressure_bleed" => (Some(Own(P::Bleed)), None),
+ "tilt_opacity" => (None, angle_only("opacity_tilt_angle")),
+ "tilt_gradation" => (None, angle_only("gradation_tilt_angle")),
+ "tilt_bleed" => (None, angle_only("bleed_tilt_angle")),
+ "tilt_size" => (None, angle_only("size_tilt_angle")),
+ "smudge_pull" => (Some(Own(P::SmudgePull)), None),
+ _ => (None, None),
+ };
+ SliderExtras { curve, tilt }
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn every_slider_tilt_is_a_control_the_brush_keeps() {
+ let keys = [
+ "jitter_lateral",
+ "jitter_linear",
+ "count",
+ "tilt_roundness",
+ "grain_depth",
+ "wet_attack",
+ "stamp_hue",
+ "stamp_saturation",
+ "stamp_lightness",
+ "stamp_darkness",
+ "stamp_secondary",
+ "tilt_hue",
+ "tilt_saturation",
+ "tilt_brightness",
+ "tilt_secondary",
+ "tilt_opacity",
+ "tilt_gradation",
+ "tilt_bleed",
+ "tilt_size",
+ ];
+ for k in keys {
+ let tilt = slider_extras(k).tilt.unwrap_or_else(|| panic!("{k} has no tilt"));
+ let mut b = Brush::round_pen();
+ b.set_setting(tilt.angle, 0.3);
+ assert!((b.setting(tilt.angle) - 0.3).abs() < 1e-4, "{k}");
+ if let Some(switch) = tilt.switch {
+ b.set_setting(switch, 1.0);
+ assert_eq!(b.setting(switch), 1.0, "{k}");
+ }
+ }
+ // a slider without extras has none
+ assert_eq!(slider_extras("spacing"), SliderExtras::default());
+ }
+
#[test]
fn the_linear_jitters_tilt_follows_the_laterals_unless_it_has_its_own() {
let mut b = Brush::round_pen();
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index b3526cf..1fbed8f 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -7,6 +7,7 @@
mod canvas;
mod lighting;
mod scene;
+mod sphere;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
@@ -17,6 +18,7 @@ pub use canvas::{
};
pub use lighting::Lighting;
pub use scene::{Light, MOST_LIGHTS, MeshView, Orbit, SurfaceMap};
+pub use sphere::{SphereLook, SpherePreview, preview_environment};
pub use wgpu;
#[derive(Debug, thiserror::Error)]
diff --git a/crates/gpu/src/shaders/sphere.wgsl b/crates/gpu/src/shaders/sphere.wgsl
new file mode 100644
index 0000000..a887823
--- /dev/null
+++ b/crates/gpu/src/shaders/sphere.wgsl
@@ -0,0 +1,121 @@
+// The brush studio's 3D preview: a sphere on the pad, lit as a model is by an environment (its
+// irradiance for diffuse light, a prefiltered radiance cube for reflections, with the split-sum
+// table), showing the pad's canvas where the screen sees it: what is painted there over the
+// sphere's own plain material, in its colour and with the brush's metalness and roughness (each
+// through its source, tiled across the canvas). Around the sphere, the pad's own colour.
+
+struct Sphere {
+ // the environment's irradiance as spherical harmonics (bands 0 to 2)
+ sh: array<vec4<f32>, 9>,
+ // the sphere's middle and radius (target pixels), and the radiance cube's last level
+ circle: vec4<f32>,
+ // target pixels to canvas pixels: x by the first row, y by the second (x, y, 1 weights)
+ to_canvas_x: vec4<f32>,
+ to_canvas_y: vec4<f32>,
+ // the canvas's size, and the metalness and roughness sources' tiles (canvas pixels)
+ canvas: vec4<f32>,
+ // the sphere's own colour (as stored) and roughness
+ base: vec4<f32>,
+ // the brush's metalness and roughness, and whether each goes through a source
+ brush: vec4<f32>,
+ // around the sphere (as stored)
+ behind: vec4<f32>,
+ // the textures' colours to the target's, in linear light: three rows, c0.w 1 to apply them
+ c0: vec4<f32>,
+ c1: vec4<f32>,
+ c2: vec4<f32>,
+}
+
+@group(0) @binding(0) var<uniform> s: Sphere;
+@group(0) @binding(1) var radiance: texture_cube<f32>;
+@group(0) @binding(2) var radiance_smp: sampler;
+@group(0) @binding(3) var brdf: texture_2d<f32>;
+@group(0) @binding(4) var brdf_smp: sampler;
+@group(0) @binding(5) var painted_tex: texture_2d<f32>;
+@group(0) @binding(6) var painted_smp: sampler;
+@group(0) @binding(7) var metallic_src: texture_2d<f32>;
+@group(0) @binding(8) var roughness_src: texture_2d<f32>;
+@group(0) @binding(9) var source_smp: sampler;
+
+@vertex
+fn vs_full(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
+ let x = f32(vi & 1u) * 4.0 - 1.0;
+ let y = f32(vi >> 1u) * 4.0 - 1.0;
+ return vec4<f32>(x, y, 0.0, 1.0);
+}
+
+fn irradiance(n: vec3<f32>) -> vec3<f32> {
+ let b = array<f32, 9>(
+ 0.282095,
+ 0.488603 * n.y,
+ 0.488603 * n.z,
+ 0.488603 * n.x,
+ 1.092548 * n.x * n.y,
+ 1.092548 * n.y * n.z,
+ 0.315392 * (3.0 * n.z * n.z - 1.0),
+ 1.092548 * n.x * n.z,
+ 0.546274 * (n.x * n.x - n.y * n.y),
+ );
+ var e = vec3<f32>(0.0);
+ for (var i = 0; i < 9; i++) {
+ e += s.sh[i].xyz * b[i];
+ }
+ return max(e, vec3<f32>(0.0));
+}
+
+// the stored colour into the target's colour space (another profile's primaries), clipped to it
+fn moved(rgb: vec3<f32>) -> vec3<f32> {
+ if (s.c0.w < 0.5) {
+ return rgb;
+ }
+ let lin = srgb_to_linear(rgb);
+ let m = vec3<f32>(dot(s.c0.xyz, lin), dot(s.c1.xyz, lin), dot(s.c2.xyz, lin));
+ return linear_to_srgb(clamp(m, vec3<f32>(0.0), vec3<f32>(1.0)));
+}
+
+@fragment
+fn fs_main(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
+ let behind = moved(s.behind.rgb);
+ let d = (pos.xy - s.circle.xy) / s.circle.z;
+ let dist = length(d);
+ // how much of this pixel the sphere covers: its outline smoothed over a pixel
+ let cover = clamp(0.5 - (dist - 1.0) * s.circle.z, 0.0, 1.0);
+ if (cover <= 0.0) {
+ return vec4<f32>(behind, 1.0);
+ }
+ // just outside, the outline's own normal
+ let e = d / max(dist, 1.0);
+ let n = vec3<f32>(e.x, -e.y, sqrt(max(1.0 - dot(e, e), 0.0)));
+ let v = vec3<f32>(0.0, 0.0, 1.0);
+ // the canvas under this pixel, over the sphere's own colour
+ let at = vec2<f32>(dot(s.to_canvas_x.xyz, vec3<f32>(pos.xy, 1.0)), dot(s.to_canvas_y.xyz, vec3<f32>(pos.xy, 1.0)));
+ let painted = textureSampleLevel(painted_tex, painted_smp, at / s.canvas.xy, 0.0);
+ let color = painted.rgb + s.base.rgb * (1.0 - painted.a);
+ let albedo_lin = pow(max(color, vec3<f32>(0.0)), vec3<f32>(2.2));
+ // the paint's metalness and roughness through their sources, over the sphere's own
+ let metal_through = select(1.0, textureSampleLevel(metallic_src, source_smp, at / s.canvas.z, 0.0).r, s.brush.z > 0.5);
+ let rough_through = select(1.0, textureSampleLevel(roughness_src, source_smp, at / s.canvas.w, 0.0).r, s.brush.w > 0.5);
+ let metallic = s.brush.x * metal_through * painted.a;
+ let roughness = mix(s.base.w, s.brush.y * rough_through, painted.a);
+ let r = max(roughness, 0.045);
+ let f0 = mix(vec3<f32>(0.04), albedo_lin, metallic);
+ let nv = clamp(dot(n, v), 1e-5, 1.0);
+ let reflected = textureSampleLevel(radiance, radiance_smp, reflect(-v, n), r * s.circle.w).rgb;
+ let split = textureSampleLevel(brdf, brdf_smp, vec2<f32>(nv, r), 0.0).rg;
+ let fr = f0 + (max(vec3<f32>(1.0 - r), f0) - f0) * pow(1.0 - nv, 5.0);
+ let lit = (1.0 - fr) * (1.0 - metallic) * albedo_lin * irradiance(n) + reflected * (fr * split.x + split.y);
+ let rgb = clamp(pow(max(lit, vec3<f32>(0.0)), vec3<f32>(1.0 / 2.2)), vec3<f32>(0.0), vec3<f32>(1.0));
+ return vec4<f32>(mix(behind, moved(rgb), cover), 1.0);
+}
+
+fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
+ let lo = c / 12.92;
+ let hi = pow((c + 0.055) / 1.055, vec3<f32>(2.4));
+ return select(hi, lo, c <= vec3<f32>(0.04045));
+}
+
+fn linear_to_srgb(c: vec3<f32>) -> vec3<f32> {
+ let lo = c * 12.92;
+ let hi = 1.055 * pow(c, vec3<f32>(1.0 / 2.4)) - 0.055;
+ return select(hi, lo, c <= vec3<f32>(0.0031308));
+}
diff --git a/crates/gpu/src/sphere.rs b/crates/gpu/src/sphere.rs
new file mode 100644
index 0000000..f829622
--- /dev/null
+++ b/crates/gpu/src/sphere.rs
@@ -0,0 +1,344 @@
+//! The brush studio's 3D preview: a sphere on the drawing pad showing the pad's canvas where the
+//! screen sees it (so a stroke lands under the pen), painted over the sphere's own plain material
+//! with the brush's metalness and roughness, lit by a light of its own as a model is lit.
+
+use std::f32::consts::PI;
+
+use procraft_engine::environment::Equirect;
+use procraft_engine::textures::TEXTURE_SIZE;
+
+use crate::lighting::{CUBE_LEVELS, Lighting};
+use crate::{Canvas, Gpu};
+
+/// The sphere's own colour (as stored) and roughness, under what is painted.
+const BASE: [f32; 3] = [0.4327, 0.4234, 0.4144];
+const BASE_ROUGHNESS: f32 = 0.4836;
+
+/// The light the sphere is lit by: a sky bluest above, palest at the horizon and dark and warm
+/// below, each blended to the horizon's colour by the height to a power, and a small bright key
+/// light high to the right (directions in the camera's space, y up, z toward the eye). Matched to
+/// how the reference's sphere is lit.
+const SKY_TOP: [f32; 3] = [0.0, 0.0967, 0.2962];
+const SKY_HORIZON: [f32; 3] = [0.2846, 0.3455, 0.4076];
+const SKY_BOTTOM: [f32; 3] = [0.0749, 0.0261, 0.0167];
+const SKY_TOP_POWER: f32 = 1.5915;
+const SKY_BOTTOM_POWER: f32 = 0.1;
+/// The key light's direction (its turn about the vertical from the eye, its height, radians),
+/// colour and spread (the light falls off as exp((cos - 1) / spread²)).
+const KEY_TURN: f32 = 1.1702;
+const KEY_HEIGHT: f32 = 0.7204;
+const KEY: [f32; 3] = [47.329, 48.8426, 50.0];
+const KEY_SPREAD: f32 = 0.0788;
+/// The panorama's size the light is made at (the size it was matched at).
+const SKY_WIDTH: u32 = 64;
+
+/// What the preview shows besides the canvas.
+pub struct SphereLook<'a> {
+ /// The brush's metalness and roughness (0..1).
+ pub metallic: f32,
+ pub roughness: f32,
+ /// Each through its source, if it has one: a key that changes with it and the image
+ /// (`TEXTURE_SIZE` square grey, white = the amount), tiled every so many canvas pixels.
+ pub metallic_source: Option<(u64, &'a [u8])>,
+ pub roughness_source: Option<(u64, &'a [u8])>,
+ pub metallic_tile: f32,
+ pub roughness_tile: f32,
+ /// Around the sphere (as stored, 0..1).
+ pub behind: [f32; 3],
+ /// The textures' colours to the target's (rows of a matrix in linear light), if they differ.
+ pub convert: Option<[[f32; 3]; 3]>,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+struct SphereUniform {
+ sh: [[f32; 4]; 9],
+ circle: [f32; 4],
+ to_canvas_x: [f32; 4],
+ to_canvas_y: [f32; 4],
+ canvas: [f32; 4],
+ base: [f32; 4],
+ brush: [f32; 4],
+ behind: [f32; 4],
+ c0: [f32; 4],
+ c1: [f32; 4],
+ c2: [f32; 4],
+}
+
+/// A source as a texture, with the key it was made from.
+struct SourceTexture {
+ key: u64,
+ view: wgpu::TextureView,
+}
+
+/// The preview's pipeline, its light and its sources' textures.
+pub struct SpherePreview {
+ pipeline: wgpu::RenderPipeline,
+ layout: wgpu::BindGroupLayout,
+ uniform: wgpu::Buffer,
+ lighting: Lighting,
+ cube_sampler: wgpu::Sampler,
+ table_sampler: wgpu::Sampler,
+ painted_sampler: wgpu::Sampler,
+ source_sampler: wgpu::Sampler,
+ /// The metalness and roughness sources, once given.
+ sources: [Option<SourceTexture>; 2],
+ /// White: a source that is the amount all over.
+ white: wgpu::TextureView,
+}
+
+/// The sphere's light as a panorama (see [`SKY_TOP`]).
+pub fn preview_environment() -> Equirect {
+ let (w, h) = (SKY_WIDTH, SKY_WIDTH / 2);
+ let key = [KEY_HEIGHT.cos() * KEY_TURN.sin(), KEY_HEIGHT.sin(), KEY_HEIGHT.cos() * KEY_TURN.cos()];
+ let mut pixels = Vec::with_capacity((w * h) as usize);
+ for y in 0..h {
+ let theta = (y as f32 + 0.5) / h as f32 * PI;
+ for x in 0..w {
+ let phi = ((x as f32 + 0.5) / w as f32 - 0.5) * 2.0 * PI;
+ let d = [theta.sin() * phi.sin(), theta.cos(), -theta.sin() * phi.cos()];
+ let up = d[1];
+ let (far, t) =
+ if up >= 0.0 { (SKY_TOP, up.powf(SKY_TOP_POWER)) } else { (SKY_BOTTOM, (-up).powf(SKY_BOTTOM_POWER)) };
+ let along = d[0] * key[0] + d[1] * key[1] + d[2] * key[2];
+ let blob = ((along - 1.0) / (KEY_SPREAD * KEY_SPREAD)).exp();
+ let mut c = SKY_HORIZON;
+ for ((out, far), key) in c.iter_mut().zip(far).zip(KEY) {
+ *out = (*out + (far - *out) * t).max(0.0) + key * blob;
+ }
+ pixels.push(c);
+ }
+ }
+ Equirect { width: w, height: h, pixels }
+}
+
+impl SpherePreview {
+ /// The preview, drawing into targets of `format`.
+ pub fn new(gpu: &Gpu, format: wgpu::TextureFormat) -> SpherePreview {
+ let device = &gpu.device;
+ let texture = |binding, view_dimension| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension,
+ multisampled: false,
+ },
+ count: None,
+ };
+ let sampler = |binding| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ };
+ let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("sphere preview"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ texture(1, wgpu::TextureViewDimension::Cube),
+ sampler(2),
+ texture(3, wgpu::TextureViewDimension::D2),
+ sampler(4),
+ texture(5, wgpu::TextureViewDimension::D2),
+ sampler(6),
+ texture(7, wgpu::TextureViewDimension::D2),
+ texture(8, wgpu::TextureViewDimension::D2),
+ sampler(9),
+ ],
+ });
+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("sphere preview"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("shaders/sphere.wgsl").into()),
+ });
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("sphere preview"),
+ bind_group_layouts: &[Some(&layout)],
+ immediate_size: 0,
+ });
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("sphere preview"),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &module,
+ entry_point: Some("vs_full"),
+ compilation_options: Default::default(),
+ buffers: &[],
+ },
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ fragment: Some(wgpu::FragmentState {
+ module: &module,
+ entry_point: Some("fs_main"),
+ compilation_options: Default::default(),
+ targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })],
+ }),
+ multiview_mask: None,
+ cache: None,
+ });
+ let uniform = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("sphere preview"),
+ size: std::mem::size_of::<SphereUniform>() as u64,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let linear = |label, mipmap, address_mode| {
+ device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some(label),
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ mipmap_filter: mipmap,
+ address_mode_u: address_mode,
+ address_mode_v: address_mode,
+ ..Default::default()
+ })
+ };
+ let clamp = wgpu::AddressMode::ClampToEdge;
+ SpherePreview {
+ pipeline,
+ layout,
+ uniform,
+ lighting: Lighting::new(gpu, &preview_environment()),
+ cube_sampler: linear("sphere radiance", wgpu::MipmapFilterMode::Linear, clamp),
+ table_sampler: linear("sphere brdf table", wgpu::MipmapFilterMode::Nearest, clamp),
+ painted_sampler: linear("sphere canvas", wgpu::MipmapFilterMode::Nearest, clamp),
+ source_sampler: linear("sphere sources", wgpu::MipmapFilterMode::Nearest, wgpu::AddressMode::Repeat),
+ sources: [None, None],
+ white: grey_texture(gpu, 1, &[255]),
+ }
+ }
+
+ /// Draws the sphere into `target` (`size`): its middle at `middle`, `radius` across (target
+ /// pixels), showing `canvas` (its composite as last rendered) through `to_canvas` (target
+ /// pixels to canvas pixels: a, b, c, d, e, f of x' = a x + c y + e, y' = b x + d y + f).
+ #[allow(clippy::too_many_arguments)]
+ pub fn render(
+ &mut self,
+ gpu: &Gpu,
+ target: &wgpu::TextureView,
+ middle: [f32; 2],
+ radius: f32,
+ canvas: &Canvas,
+ to_canvas: [f32; 6],
+ look: &SphereLook<'_>,
+ ) {
+ for (slot, source) in self.sources.iter_mut().zip([look.metallic_source, look.roughness_source]) {
+ match source {
+ Some((key, pixels))
+ if slot.as_ref().is_none_or(|s| s.key != key) && pixels.len() == TEXTURE_SIZE * TEXTURE_SIZE =>
+ {
+ *slot = Some(SourceTexture { key, view: grey_texture(gpu, TEXTURE_SIZE as u32, pixels) });
+ }
+ None => *slot = None,
+ _ => {}
+ }
+ }
+ let (w, h) = canvas.size();
+ let [a, b, c, d, e, f] = to_canvas;
+ let [r0, r1, r2] = look.convert.unwrap_or([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
+ let applied = if look.convert.is_some() { 1.0 } else { 0.0 };
+ let has = |s: &Option<SourceTexture>| if s.is_some() { 1.0 } else { 0.0 };
+ let [metallic_view, roughness_view] =
+ self.sources.each_ref().map(|s| s.as_ref().map_or(&self.white, |s| &s.view));
+ let uniform = SphereUniform {
+ sh: self.lighting.sh,
+ circle: [middle[0], middle[1], radius.max(1.0), (CUBE_LEVELS - 1) as f32],
+ to_canvas_x: [a, c, e, 0.0],
+ to_canvas_y: [b, d, f, 0.0],
+ canvas: [w as f32, h as f32, look.metallic_tile.max(1.0), look.roughness_tile.max(1.0)],
+ base: [BASE[0], BASE[1], BASE[2], BASE_ROUGHNESS],
+ brush: [
+ look.metallic.clamp(0.0, 1.0),
+ look.roughness.clamp(0.0, 1.0),
+ has(&self.sources[0]),
+ has(&self.sources[1]),
+ ],
+ behind: [look.behind[0], look.behind[1], look.behind[2], 1.0],
+ c0: [r0[0], r0[1], r0[2], applied],
+ c1: [r1[0], r1[1], r1[2], 0.0],
+ c2: [r2[0], r2[1], r2[2], 0.0],
+ };
+ gpu.queue.write_buffer(&self.uniform, 0, bytemuck::bytes_of(&uniform));
+ let bind = gpu.device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("sphere preview"),
+ layout: &self.layout,
+ entries: &[
+ wgpu::BindGroupEntry { binding: 0, resource: self.uniform.as_entire_binding() },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&self.lighting.cube_view),
+ },
+ wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.cube_sampler) },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(&self.lighting.table_view),
+ },
+ wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Sampler(&self.table_sampler) },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::TextureView(canvas.composite_view()),
+ },
+ wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::Sampler(&self.painted_sampler) },
+ wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(metallic_view) },
+ wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::TextureView(roughness_view) },
+ wgpu::BindGroupEntry { binding: 9, resource: wgpu::BindingResource::Sampler(&self.source_sampler) },
+ ],
+ });
+ let mut encoder =
+ gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("sphere preview") });
+ {
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("sphere preview"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ pass.set_pipeline(&self.pipeline);
+ pass.set_bind_group(0, &bind, &[]);
+ pass.draw(0..3, 0..1);
+ }
+ gpu.queue.submit([encoder.finish()]);
+ }
+}
+
+/// A `side` square grey texture of `pixels` (rows from the top).
+fn grey_texture(gpu: &Gpu, side: u32, pixels: &[u8]) -> wgpu::TextureView {
+ use wgpu::util::DeviceExt;
+ gpu.device
+ .create_texture_with_data(
+ &gpu.queue,
+ &wgpu::TextureDescriptor {
+ label: Some("sphere source"),
+ size: wgpu::Extent3d { width: side, height: side, depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::R8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ },
+ wgpu::util::TextureDataOrder::LayerMajor,
+ pixels,
+ )
+ .create_view(&wgpu::TextureViewDescriptor::default())
+}
diff --git a/crates/gpu/tests/sphere.rs b/crates/gpu/tests/sphere.rs
new file mode 100644
index 0000000..ae3ee90
--- /dev/null
+++ b/crates/gpu/tests/sphere.rs
@@ -0,0 +1,76 @@
+//! The brush studio's 3D preview: a lit sphere showing the canvas under it.
+#![allow(clippy::unwrap_used, clippy::indexing_slicing)]
+
+use procraft_engine::document::Document;
+use procraft_gpu::{Canvas, Gpu, SphereLook, SpherePreview, read_texture, wgpu};
+
+const SIDE: u32 = 64;
+
+/// The preview of a `SIDE` square canvas whose background is `background` (or none, nothing
+/// painted), the sphere filling the target, with the brush's metalness `metallic`.
+fn draw(gpu: &Gpu, background: Option<[f32; 3]>, metallic: f32) -> Vec<u8> {
+ let mut doc = Document::new(SIDE, SIDE);
+ doc.background_visible = background.is_some();
+ doc.background = background.unwrap_or([1.0; 3]);
+ let mut canvas = Canvas::new(gpu, &doc).unwrap();
+ canvas.render(gpu, &mut doc, None);
+ let target = gpu.device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("test target"),
+ size: wgpu::Extent3d { width: SIDE, height: SIDE, depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ });
+ let view = target.create_view(&wgpu::TextureViewDescriptor::default());
+ let mut preview = SpherePreview::new(gpu, wgpu::TextureFormat::Rgba8Unorm);
+ let look = SphereLook {
+ metallic,
+ roughness: 0.5,
+ metallic_source: None,
+ roughness_source: None,
+ metallic_tile: 100.0,
+ roughness_tile: 100.0,
+ behind: [0.0, 0.0, 1.0],
+ convert: None,
+ };
+ let half = SIDE as f32 / 2.0;
+ preview.render(gpu, &view, [half, half], half, &canvas, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], &look);
+ read_texture(gpu, &target, SIDE, SIDE).unwrap()
+}
+
+fn pixel(p: &[u8], x: u32, y: u32) -> [u8; 4] {
+ let i = ((y * SIDE + x) * 4) as usize;
+ [p[i], p[i + 1], p[i + 2], p[i + 3]]
+}
+
+#[test]
+fn the_sphere_shows_its_own_grey_and_the_pad_round_it() {
+ let Some(gpu) = Gpu::headless().ok() else { return };
+ let px = draw(&gpu, None, 0.0);
+ // round the sphere, the pad's colour
+ assert_eq!(pixel(&px, 0, 0), [0, 0, 255, 255]);
+ // its middle a lit grey, brighter toward its light high on the right, darker and warmer below
+ let middle = pixel(&px, SIDE / 2, SIDE / 2);
+ assert!(middle[0] > 50 && middle[0] < 90 && middle[0].abs_diff(middle[1]) < 6, "{middle:?}");
+ let (lit, below) = (pixel(&px, 45, 18), pixel(&px, 32, 54));
+ assert!(lit[0] > middle[0] + 30, "{lit:?}");
+ assert!(below[0] < middle[0] && below[0] > below[2], "{below:?}");
+ assert_eq!(gpu.errors(), 0);
+}
+
+#[test]
+fn paint_shows_in_its_colour_and_metal_reflects_the_light() {
+ let Some(gpu) = Gpu::headless().ok() else { return };
+ let plain = draw(&gpu, None, 0.0);
+ let red = draw(&gpu, Some([1.0, 0.0, 0.0]), 0.0);
+ let middle = pixel(&red, SIDE / 2, SIDE / 2);
+ assert!(middle[0] > middle[1] + 60 && middle[0] > middle[2] + 60, "{middle:?}");
+ // the same red, metallic: its own colour now only in what it reflects
+ let metal = draw(&gpu, Some([1.0, 0.0, 0.0]), 1.0);
+ assert_ne!(pixel(&metal, SIDE / 2, SIDE / 2), middle);
+ assert_ne!(pixel(&plain, SIDE / 2, SIDE / 2), middle);
+ assert_eq!(gpu.errors(), 0);
+}