Skip to content

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

Rust

fix(brush): every pressure curve applied; OBJ imports with its materials

Josh8b5eb13d9363
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 b120748..6d765f9 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
@@ -26,6 +26,7 @@ import io.github.artcraftandroid.procraft.ui.gradientColorAt
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.ChromaticKind
import io.github.artcraftandroid.procraft.core.GlitchKind
import io.github.artcraftandroid.procraft.core.GuideInfo
@@ -984,23 +985,25 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
/** A new artwork from a photo or picture file, its size, the picture as its one layer. */
fun newFromPicture(uri: android.net.Uri) {
- viewModelScope.launch {
- // in Display P3 if the picture is, else in sRGB
- val p3 = withContext(Dispatchers.IO) { pictureIsP3(uri) }
- val image = withContext(Dispatchers.IO) { decodePicture(uri, p3) }
- if (image == null) {
- message = "This picture can't be opened."
- return@launch
- }
- val s = withContext(Dispatchers.IO) {
- CanvasSession.fromImage(image, "Untitled Artwork").also {
- if (p3) it.setNewProfile(io.github.artcraftandroid.procraft.gallery.CanvasPreset.P3)
- loadBrushes(it)
- }
+ viewModelScope.launch { pictureArtwork(uri) }
+ }
+
+ private suspend fun pictureArtwork(uri: android.net.Uri) {
+ // in Display P3 if the picture is, else in sRGB
+ val p3 = withContext(Dispatchers.IO) { pictureIsP3(uri) }
+ val image = withContext(Dispatchers.IO) { decodePicture(uri, p3) }
+ if (image == null) {
+ message = "This picture can't be opened."
+ return
+ }
+ val s = withContext(Dispatchers.IO) {
+ CanvasSession.fromImage(image, "Untitled Artwork").also {
+ if (p3) it.setNewProfile(io.github.artcraftandroid.procraft.gallery.CanvasPreset.P3)
+ loadBrushes(it)
}
- start(s, store.newFolder(galleryDir), brushesLoaded = true)
- startedNew()
}
+ start(s, store.newFolder(galleryDir), brushesLoaded = true)
+ startedNew()
}
/** The open artwork paints on a model: one finger turns it. */
@@ -1276,13 +1279,19 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
refreshThumbnails()
}
- /** A new artwork painting on the model in the file [uri] (named [name]: OBJ, USDZ or USDC). */
- private suspend fun newFromModel(uri: android.net.Uri, name: String) {
+ /**
+ * A new artwork painting on the model in the file [uri] (named [name]: OBJ, USDZ or USDC),
+ * with the files picked along with it ([picked], by name: an OBJ's material file and images).
+ */
+ private suspend fun newFromModel(uri: android.net.Uri, name: String, picked: List<Pair<android.net.Uri, String>> = emptyList()) {
val resolver = getApplication<Application>().contentResolver
val s = withContext(Dispatchers.IO) {
runCatching {
val file = resolver.openInputStream(uri)?.use { it.readBytes() } ?: return@runCatching null
- CanvasSession.openModel(file, name, null, name.substringBeforeLast('.').ifBlank { "Untitled Artwork" }, 0u)
+ val files = picked.mapNotNull { (u, n) ->
+ runCatching { resolver.openInputStream(u)?.use { ModelFile(n, it.readBytes()) } }.getOrNull()
+ }
+ CanvasSession.openModel(file, name, files, name.substringBeforeLast('.').ifBlank { "Untitled Artwork" }, 0u)
.also(::loadModelTextures).also(::loadBrushes)
}.onFailure { android.util.Log.e("ProCraft", "opening a model", it) }.getOrNull()
}
@@ -1332,37 +1341,66 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
/** A file from elsewhere into the gallery: an artwork file, or a picture as a new artwork. */
fun importFile(uri: android.net.Uri) {
- val resolver = getApplication<Application>().contentResolver
+ viewModelScope.launch { importOne(uri) }
+ }
+
+ /**
+ * Files from elsewhere into the gallery, one after another as [importFile] takes each; a
+ * model among them takes the rest as the files picked with it (an OBJ's material file and
+ * the images it maps).
+ */
+ fun importFiles(uris: List<android.net.Uri>) {
viewModelScope.launch {
- val head = withContext(Dispatchers.IO) { runCatching { resolver.openInputStream(uri)?.use { s -> ByteArray(4).also { s.read(it) } } }.getOrNull() }
- val name = withContext(Dispatchers.IO) { fileName(uri) }
- // another program's palette
- val foreign = head != null && io.github.artcraftandroid.procraft.gallery.ColourSwatches.isExchange(head) || name?.endsWith(".aco", ignoreCase = true) == true
- val zip = head != null && head[0] == 'P'.code.toByte() && head[1] == 'K'.code.toByte()
- // a zip of brushes
- val brushes = if (zip) withContext(Dispatchers.IO) { runCatching { resolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() }?.takeIf(::isBrushFile) else null
- // a zip: brushes, a palette, an artwork file of ours, or a layered package
- if (brushes != null) {
- if (!addBrushes(brushes)) message = "This file has no brushes in it."
- } else if (head != null && (foreign || zip) && importSwatches(uri)) {
- message = "Palette added."
- } else if (foreign) {
- message = "This palette can't be read."
- } else if (name != null && MODEL_EXTENSIONS.any { name.endsWith(".$it", ignoreCase = true) }) {
- newFromModel(uri, name)
- } else if (head != null && head[0] == 'P'.code.toByte() && head[1] == 'K'.code.toByte()) {
- val ok = withContext(Dispatchers.IO) {
- val dir = store.newFolder(galleryDir)
- val ours = runCatching { resolver.openInputStream(uri)?.use { io.github.artcraftandroid.procraft.gallery.ArtworkFile.read(it, dir) } }.getOrNull() == true
- (ours || importPackage(uri, dir)).also { if (!it) dir.deleteRecursively() }
+ val names = withContext(Dispatchers.IO) { uris.map(::fileName) }
+ val models = uris.indices.filter { i -> names[i]?.let(::isModelName) == true }
+ // each one opened is kept (closed, so saved) as the next comes in
+ if (models.isEmpty()) {
+ for (uri in uris) {
+ if (session != null) closeArtwork()
+ importOne(uri)
}
- if (ok) refreshGallery() else message = "This file can't be opened."
- } else {
- newFromPicture(uri)
+ return@launch
+ }
+ val picked = (uris.indices - models.toSet()).mapNotNull { i -> names[i]?.let { uris[i] to it } }
+ for (i in models) {
+ if (session != null) closeArtwork()
+ newFromModel(uris[i], names[i] ?: continue, picked)
}
}
}
+ private fun isModelName(name: String) = MODEL_EXTENSIONS.any { name.endsWith(".$it", ignoreCase = true) }
+
+ private suspend fun importOne(uri: android.net.Uri) {
+ val resolver = getApplication<Application>().contentResolver
+ val head = withContext(Dispatchers.IO) { runCatching { resolver.openInputStream(uri)?.use { s -> ByteArray(4).also { s.read(it) } } }.getOrNull() }
+ val name = withContext(Dispatchers.IO) { fileName(uri) }
+ // another program's palette
+ val foreign = head != null && io.github.artcraftandroid.procraft.gallery.ColourSwatches.isExchange(head) || name?.endsWith(".aco", ignoreCase = true) == true
+ val zip = head != null && head[0] == 'P'.code.toByte() && head[1] == 'K'.code.toByte()
+ // a zip of brushes
+ val brushes = if (zip) withContext(Dispatchers.IO) { runCatching { resolver.openInputStream(uri)?.use { it.readBytes() } }.getOrNull() }?.takeIf(::isBrushFile) else null
+ // a zip: brushes, a palette, an artwork file of ours, or a layered package
+ if (brushes != null) {
+ if (!addBrushes(brushes)) message = "This file has no brushes in it."
+ } else if (head != null && (foreign || zip) && importSwatches(uri)) {
+ message = "Palette added."
+ } else if (foreign) {
+ message = "This palette can't be read."
+ } else if (name != null && isModelName(name)) {
+ newFromModel(uri, name)
+ } else if (head != null && head[0] == 'P'.code.toByte() && head[1] == 'K'.code.toByte()) {
+ val ok = withContext(Dispatchers.IO) {
+ val dir = store.newFolder(galleryDir)
+ val ours = runCatching { resolver.openInputStream(uri)?.use { io.github.artcraftandroid.procraft.gallery.ArtworkFile.read(it, dir) } }.getOrNull() == true
+ (ours || importPackage(uri, dir)).also { if (!it) dir.deleteRecursively() }
+ }
+ if (ok) refreshGallery() else message = "This file can't be opened."
+ } else {
+ pictureArtwork(uri)
+ }
+ }
+
/**
* A layered package from [uri] made into the artwork folder [dir]: its layers, settings and
* preview (as the gallery's thumbnail until it is opened); false if it isn't one.
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt
index d79cd21..147ca81 100644
--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt
+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/GalleryScreen.kt
@@ -148,8 +148,9 @@ fun GalleryScreen(vm: CanvasViewModel) {
selected.clear()
moreOpen = false
}
- val importFile = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->
- uri?.let(vm::importFile)
+ // several at once, as a model's material file and images come with it
+ val importFile = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenMultipleDocuments()) { uris ->
+ if (uris.isNotEmpty()) vm.importFiles(uris)
}
val photo = androidx.activity.compose.rememberLauncherForActivityResult(androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia()) { uri ->
uri?.let(vm::newFromPicture)
diff --git a/apps/procraft-android/src/lib.rs b/apps/procraft-android/src/lib.rs
index b1eac8a..6ae926f 100644
--- a/apps/procraft-android/src/lib.rs
+++ b/apps/procraft-android/src/lib.rs
@@ -1153,7 +1153,8 @@ impl CanvasSession {
size: sliders.size,
opacity: sliders.opacity,
brush_diameter: st.brush(st.tool).diameter(sliders.size) * st.brush_scale(),
- can_undo: st.canvas.as_ref().is_some_and(Canvas::can_undo) || st.crop_undo.is_some(),
+ // an open shape is kept, then undone
+ can_undo: st.canvas.as_ref().is_some_and(Canvas::can_undo) || st.crop_undo.is_some() || st.shape.is_some(),
// keeping an open shape drops what could be redone
can_redo: st.shape.is_none() && (st.canvas.as_ref().is_some_and(Canvas::can_redo) || st.crop_redo_ready()),
zoom: st.view.map_or(1.0, |v| v.zoom()),
diff --git a/apps/procraft-android/src/scene3d.rs b/apps/procraft-android/src/scene3d.rs
index b8d7fbd..9d0abf7 100644
--- a/apps/procraft-android/src/scene3d.rs
+++ b/apps/procraft-android/src/scene3d.rs
@@ -99,6 +99,36 @@ pub(crate) struct ModelSource {
mtl: Option<String>,
}
+/// A file picked along with a model: an OBJ's material file, or an image its materials map.
+#[derive(Clone, Debug, uniffi::Record)]
+pub struct ModelFile {
+ pub name: String,
+ pub bytes: Vec<u8>,
+}
+
+/// What an OBJ takes from the files picked with it: the material file it names (or the only
+/// one), and the rest as the images its materials may map.
+fn companions(model: &[u8], extension: &str, files: Vec<ModelFile>) -> (Option<String>, Vec<ModelFile>) {
+ if extension != "obj" {
+ return (None, Vec::new());
+ }
+ let (libraries, images): (Vec<ModelFile>, Vec<ModelFile>) =
+ files.into_iter().partition(|f| extension_of(&f.name) == "mtl");
+ let named = String::from_utf8_lossy(model).lines().find_map(|line| {
+ let rest = line.trim_start().strip_prefix("mtllib")?;
+ rest.starts_with(char::is_whitespace).then(|| rest.trim().to_owned())
+ });
+ let only = if libraries.len() == 1 { libraries.first() } else { None };
+ let chosen = named.and_then(|n| libraries.iter().find(|f| same_file(&f.name, &n))).or(only);
+ (chosen.map(|f| String::from_utf8_lossy(&f.bytes).into_owned()), images)
+}
+
+/// Whether two paths name the same file: their last parts, ignoring case.
+fn same_file(a: &str, b: &str) -> bool {
+ let last = |p: &str| p.trim().rsplit(['/', '\\']).next().unwrap_or("").to_lowercase();
+ last(a) == last(b)
+}
+
/// The kinds of model file that open: OBJ (with its MTL), USDZ, and USD binary or text.
fn read_model(bytes: &[u8], extension: &str, mtl: Option<&str>) -> Result<Mesh, MeshError> {
match extension {
@@ -161,6 +191,8 @@ pub(crate) struct Scene {
channel: usize,
/// Each part's channel maps as last given to the view (as [`Scene::filtered`]).
channel_shown: Vec<[Option<(u64, bool)>; 2]>,
+ /// The images picked with an OBJ, until its materials' maps have been taken from them.
+ picked: Vec<ModelFile>,
/// Each part's normal and occlusion maps from the model's file (RGBA8, the texture size
/// square), shown as they are; and whether the view has them as they are now.
surface_maps: Vec<[Option<Arc<Vec<u8>>>; 2]>,
@@ -213,6 +245,7 @@ impl Scene {
channels: Vec::new(),
channel: 0,
channel_shown: Vec::new(),
+ picked: Vec::new(),
surface_maps: Vec::new(),
surface_shown: false,
stroking: false,
@@ -237,21 +270,23 @@ impl Scene {
#[uniffi::export]
impl CanvasSession {
/// Opens a model to paint on: `file` the model file named `file_name` (OBJ, USDZ or USDC, by
- /// its extension), `mtl` an OBJ's material file if there is one. Each texture set is
- /// `texture_size` pixels square (0: the default).
+ /// its extension), with the `files` picked along with it (an OBJ's material file and the
+ /// images it maps). Each texture set is `texture_size` pixels square (0: the default).
#[uniffi::constructor]
pub fn open_model(
file: Vec<u8>,
file_name: String,
- mtl: Option<String>,
+ files: Vec<ModelFile>,
name: String,
texture_size: u32,
) -> Result<Arc<CanvasSession>, MobileError> {
let extension = extension_of(&file_name);
+ let (mtl, picked) = companions(&file, &extension, files);
let mesh = read_model(&file, &extension, mtl.as_deref())
.map_err(|e| file_error("opening the model", mesh_error_text(&e)))?;
let side = if texture_size == 0 { DEFAULT_TEXTURE_SIZE } else { texture_size.clamp(64, MOST_TEXTURE_SIZE) };
- let scene = Scene::new(mesh, ModelSource { bytes: file, extension, mtl }, side, 0, Vec::new());
+ let mut scene = Scene::new(mesh, ModelSource { bytes: file, extension, mtl }, side, 0, Vec::new());
+ scene.picked = picked;
let session = CanvasSession::with_document(empty_texture(side), name, Vec::new());
session.shared.lock().scene = Some(scene);
Ok(session)
@@ -412,16 +447,21 @@ impl CanvasSession {
Some(crate::layers::ThumbnailImage { width: t.width, height: t.height, rgba: t.rgba })
}
- /// The images the model's file brings for its texture sets (a USDZ's packed images): to be
- /// decoded and given back with [`CanvasSession::set_model_texture`]. Its normal and occlusion
- /// maps come as channels 3 and 4.
+ /// The images the model brings for its texture sets (a USDZ's packed images, or those
+ /// picked with an OBJ that its materials map): to be decoded and given back with
+ /// [`CanvasSession::set_model_texture`]. Its normal and occlusion maps come as channels 3
+ /// and 4. An OBJ's picked images are given once.
pub fn model_texture_files(&self) -> Vec<ModelTextureFile> {
- let st = self.shared.lock();
- let Some(scene) = st.scene.as_ref() else { return Vec::new() };
- if scene.source.extension != "usdz" {
- return Vec::new();
- }
- let Some(zip) = procraft_engine::zip::ZipReader::new(&scene.source.bytes) else { return Vec::new() };
+ let mut st = self.shared.lock();
+ let Some(scene) = st.scene.as_mut() else { return Vec::new() };
+ let picked = std::mem::take(&mut scene.picked);
+ let zip = (scene.source.extension == "usdz")
+ .then(|| procraft_engine::zip::ZipReader::new(&scene.source.bytes))
+ .flatten();
+ let found = |path: &str| match &zip {
+ Some(zip) => packed_file(zip, path),
+ None => picked.iter().find(|f| same_file(&f.name, path)).map(|f| f.bytes.clone()),
+ };
let mut out = Vec::new();
for (set, part) in scene.mesh.parts.iter().enumerate() {
let Some(m) = scene.mesh.materials.iter().find(|m| m.name == part.material) else { continue };
@@ -433,7 +473,7 @@ impl CanvasSession {
(4, m.occlusion_map.as_deref(), m.occlusion_component),
];
for (channel, map, component) in maps {
- let Some(bytes) = map.and_then(|f| packed_file(&zip, f)) else { continue };
+ let Some(bytes) = map.and_then(found) else { continue };
out.push(ModelTextureFile {
texture_set: u32::try_from(set).unwrap_or(0),
channel,
@@ -1991,6 +2031,7 @@ impl ModelInfo {
mod tests {
use procraft_gpu::{Gpu, wgpu};
+ use super::ModelFile;
use crate::{CanvasSession, PenSample, PointerKind};
/// A cube whose every face covers the whole texture.
@@ -2047,7 +2088,7 @@ mod tests {
#[test]
fn panels_over_a_model_blur_it_under_them() {
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 64).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 64).unwrap();
if !shown(&s) {
return;
}
@@ -2079,7 +2120,7 @@ mod tests {
Ok(g) => g,
Err(e) => return eprintln!("skipped: {e}"),
};
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 256).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 256).unwrap();
let info = s.model_info().unwrap();
assert_eq!((info.texture_sets.len(), info.triangles), (1, 12));
{
@@ -2120,7 +2161,7 @@ mod tests {
#[test]
fn the_2d_texture_shows_and_paints_flat() {
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 128).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 128).unwrap();
if !shown(&s) {
return;
}
@@ -2144,7 +2185,7 @@ mod tests {
#[test]
fn the_studio_adds_moves_and_keeps_lights() {
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 64).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 64).unwrap();
// two white lights to begin with; four at most
assert_eq!(s.model_lights().len(), 2);
assert!(s.model_lights().iter().all(|l| l.saturation == 0.0));
@@ -2199,7 +2240,7 @@ mod tests {
#[test]
fn the_turntable_pulls_back_half_way_and_exports_as_gif_and_png() {
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 64).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 64).unwrap();
if !shown(&s) {
return;
}
@@ -2227,7 +2268,7 @@ mod tests {
#[test]
fn roughness_and_metalness_are_painted_in_their_own_layers() {
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 64).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 64).unwrap();
if !shown(&s) {
return;
}
@@ -2289,9 +2330,33 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ #[test]
+ fn an_obj_takes_its_material_file_and_images_from_the_files_picked_with_it() {
+ let obj = format!("mtllib Cube Parts.mtl\nusemtl body\n{CUBE}");
+ let file = |name: &str, bytes: &[u8]| ModelFile { name: name.into(), bytes: bytes.to_vec() };
+ let mtl = b"newmtl body\nKd 1 0 0\nmap_Kd -bm 1 textures/Body.png\nmap_Pr rough.png\n";
+ let files = vec![
+ file("other.mtl", b"newmtl body\nKd 0 0 1\n"),
+ file("cube parts.MTL", mtl),
+ file("body.png", b"colour"),
+ file("rough.png", b"rough"),
+ file("unused.png", b"unused"),
+ ];
+ let s = CanvasSession::open_model(obj.clone().into(), "cube.obj".into(), files, "Cube".into(), 64).unwrap();
+ // the one it names, whatever the case; its maps found by their names alone
+ let found: Vec<(u32, Vec<u8>)> = s.model_texture_files().into_iter().map(|f| (f.channel, f.bytes)).collect();
+ assert_eq!(found, [(0, b"colour".to_vec()), (1, b"rough".to_vec())]);
+ // given once
+ assert!(s.model_texture_files().is_empty());
+ // without the one it names, the only one picked
+ let only = vec![file("whatever.mtl", mtl), file("rough.png", b"rough")];
+ let s = CanvasSession::open_model(obj.into(), "cube.obj".into(), only, "Cube".into(), 64).unwrap();
+ assert_eq!(s.model_texture_files().len(), 1);
+ }
+
#[test]
fn a_packaged_models_textures_come_in_as_its_base_layers() {
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 64).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 64).unwrap();
assert_eq!(s.layers().first().map(|l| l.name.clone()).as_deref(), Some("Base Layer"));
assert!(s.model_texture_files().is_empty());
if !shown(&s) {
@@ -2304,7 +2369,7 @@ mod tests {
// opened again, its textures come back as their images' files: the colour, and the
// roughness and metalness from their red
let bytes = std::fs::read(&path).unwrap();
- let again = CanvasSession::open_model(bytes, "cube.usdz".into(), None, "Again".into(), 64).unwrap();
+ let again = CanvasSession::open_model(bytes, "cube.usdz".into(), Vec::new(), "Again".into(), 64).unwrap();
let files = again.model_texture_files();
let kinds: Vec<(u32, u32, i32)> = files.iter().map(|f| (f.texture_set, f.channel, f.component)).collect();
assert_eq!(kinds, [(0, 0, -1), (0, 1, 0), (0, 2, 0)]);
@@ -2324,7 +2389,7 @@ mod tests {
#[test]
fn two_fingers_bring_the_model_nearer_and_move_it() {
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 64).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 64).unwrap();
if !shown(&s) {
return;
}
@@ -2367,7 +2432,8 @@ f 1/1",
f 1/1 2/2",
1,
);
- let s = CanvasSession::open_model(two.into_bytes(), "two.obj".into(), None, "Two cubes".into(), 64).unwrap();
+ let s =
+ CanvasSession::open_model(two.into_bytes(), "two.obj".into(), Vec::new(), "Two cubes".into(), 64).unwrap();
if !shown(&s) {
return;
}
@@ -2484,7 +2550,7 @@ f 1/1 2/2",
#[test]
fn a_models_normal_and_occlusion_maps_are_kept_and_exported() {
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 64).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 64).unwrap();
// channels 3 and 4: the normal and occlusion maps, the texture size square
assert!(!s.set_model_texture(0, 3, vec![0; 8]));
assert!(!s.set_model_texture(0, 5, [128, 128, 255, 255].repeat(64 * 64)));
@@ -2523,7 +2589,7 @@ f 1/1 2/2",
let usdz = dir.join("cube.usdz");
s.export_model_usdz(usdz.to_string_lossy().into_owned()).unwrap();
let back =
- CanvasSession::open_model(std::fs::read(&usdz).unwrap(), "cube.usdz".into(), None, "Back".into(), 64)
+ CanvasSession::open_model(std::fs::read(&usdz).unwrap(), "cube.usdz".into(), Vec::new(), "Back".into(), 64)
.unwrap();
let channels: Vec<u32> = back.model_texture_files().iter().map(|f| f.channel).collect();
assert_eq!(channels, [0, 1, 2, 3, 4]);
@@ -2533,7 +2599,7 @@ f 1/1 2/2",
#[test]
fn a_model_exports_as_a_glb_for_viewers() {
let two = CUBE.replacen("f 1/1", "usemtl front\nf 1/1", 1).replacen("f 1/1 2/2", "usemtl sides\nf 1/1 2/2", 1);
- let s = CanvasSession::open_model(two.into_bytes(), "two.obj".into(), None, "Two".into(), 64).unwrap();
+ let s = CanvasSession::open_model(two.into_bytes(), "two.obj".into(), Vec::new(), "Two".into(), 64).unwrap();
if !shown(&s) {
return;
}
@@ -2563,7 +2629,7 @@ f 1/1 2/2",
#[test]
fn a_saved_model_exports_once_opened_again() {
- let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), None, "Cube".into(), 64).unwrap();
+ let s = CanvasSession::open_model(CUBE.into(), "cube.obj".into(), Vec::new(), "Cube".into(), 64).unwrap();
if !shown(&s) {
return;
}
@@ -2583,7 +2649,7 @@ f 1/1 2/2",
fn a_model_saves_with_each_texture_set_and_how_it_was_seen() {
// the cube's front, top and back in one material, its bottom and sides in another
let two = CUBE.replacen("f 1/1", "usemtl front\nf 1/1", 1).replacen("f 1/1 2/2", "usemtl sides\nf 1/1 2/2", 1);
- let s = CanvasSession::open_model(two.into_bytes(), "two.OBJ".into(), None, "Two".into(), 128).unwrap();
+ let s = CanvasSession::open_model(two.into_bytes(), "two.OBJ".into(), Vec::new(), "Two".into(), 128).unwrap();
assert_eq!(s.model_info().unwrap().texture_sets, ["front", "sides"]);
if !shown(&s) {
return;
diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rs
index bed8b37..0582805 100644
--- a/apps/procraft-android/src/tests.rs
+++ b/apps/procraft-android/src/tests.rs
@@ -875,7 +875,9 @@ fn a_held_stroke_snaps_to_a_shape_and_is_edited() {
assert_eq!(info.kind, QuickShapeKind::Ellipse);
assert_eq!(info.handles.len(), 8);
s.stroke_end(vec![]);
- // still open: shown as a circle, then a handle dragged
+ // still open, and undo is there for it
+ assert!(s.info().can_undo);
+ // shown as a circle, then a handle dragged
let circle = s.quickshape_choose(QuickShapeKind::Circle).unwrap();
assert_eq!(circle.kind, QuickShapeKind::Circle);
let moved = s.quickshape_move_handle(0, 190.0, 100.0).unwrap();
diff --git a/crates/engine/src/brush.rs b/crates/engine/src/brush.rs
index 94c5077..5bf2476 100644
--- a/crates/engine/src/brush.rs
+++ b/crates/engine/src/brush.rs
@@ -116,6 +116,8 @@ pub enum PressureUse {
Opacity = 1,
Bleed = 2,
Roundness = 3,
+ /// The stamp's own pressure, which the brush's other curves read.
+ Stamp = 4,
}
/// What else a brush may give a pressure curve of its own: the control is then scaled by the
@@ -154,6 +156,18 @@ pub enum PressureCurve {
LightnessJitter,
DarknessJitter,
SecondaryJitter,
+ /// The controls that follow the pressure straight when the brush has no curve for them
+ /// (see [`PressureCurves::through`]): flow, bleed, roundness, the wet mix's dilution,
+ /// charge, attack and pull, the smudge's pull; and the spacing jitter.
+ Flow,
+ Bleed,
+ Roundness,
+ Dilution,
+ Charge,
+ Attack,
+ WetPull,
+ SmudgePull,
+ SpacingJitter,
}
/// A brush's own [`PressureCurve`]s, those it has.
@@ -185,6 +199,11 @@ impl PressureCurves {
self.0.get(&kind).map_or(1.0, |c| c.eval(pressure))
}
+ /// `pressure` through `kind`'s curve: as it is without one.
+ pub fn through(&self, kind: PressureCurve, pressure: f32) -> f32 {
+ self.0.get(&kind).map_or(pressure, |c| c.eval(pressure))
+ }
+
pub fn iter(&self) -> impl Iterator<Item = (PressureCurve, &Curve)> {
self.0.iter().map(|(k, c)| (*k, c))
}
@@ -197,6 +216,15 @@ pub const SIZE_CURVE: f32 = 2.2;
/// range, to this power: light touches fall away fast.
pub const FLOW_POWER: f32 = 2.5;
+/// The stroke length (canvas pixels) by which an amount of 1 has run out (see [`run_out`]).
+pub const RUN_OUT_LENGTH: f32 = 33.0;
+
+/// How far `amount` has run out once a stroke has gone `length` canvas pixels, 0..1: by the cube
+/// root of the length (the fall off's fade, and a wet brush's paint running out).
+pub fn run_out(amount: f32, length: f32) -> f32 {
+ (amount * (length.max(0.0) / RUN_OUT_LENGTH).cbrt()).clamp(0.0, 1.0)
+}
+
/// A grain's own blend modes, numbered past the layers' (and as brush files number them): the
/// coverage, raised twelvefold by the depth, as a height the grain cuts into, straight or also
/// thinned over the grain's light (the renderer's `grain_combine`).
@@ -581,9 +609,16 @@ impl Brush {
/// The pressure as each of its uses takes it, through the pressure curve and their own:
/// [`PressureUse`] order.
- pub fn pressures(&self, pressure: f32) -> [f32; 4] {
+ pub fn pressures(&self, pressure: f32) -> [f32; 5] {
let p = self.pressure_curve.eval(pressure);
- [self.size_curve.eval(p), self.opacity_curve.eval(p), p, p]
+ let curves = &self.pressure_curves;
+ [
+ self.size_curve.eval(p),
+ self.opacity_curve.eval(p),
+ curves.through(PressureCurve::Bleed, p),
+ curves.through(PressureCurve::Roundness, p),
+ p,
+ ]
}
/// The (size, opacity) multipliers for the size's and the opacity's own pressures: an amount
diff --git a/crates/engine/src/brushfile.rs b/crates/engine/src/brushfile.rs
index e6ab84d..6935457 100644
--- a/crates/engine/src/brushfile.rs
+++ b/crates/engine/src/brushfile.rs
@@ -399,7 +399,7 @@ fn escape(s: &str) -> String {
}
/// Where brush files keep each [`PressureCurve`].
-pub const PRESSURE_CURVES: [(PressureCurve, &str); 27] = [
+pub const PRESSURE_CURVES: [(PressureCurve, &str); 36] = [
(PressureCurve::LateralJitter, "dynamicsPressurePlotJitterCurve"),
(PressureCurve::LinearJitter, "dynamicsPressurePlotJitterLongitudinalCurve"),
(PressureCurve::Count, "dynamicsPressureStampCountCurve"),
@@ -427,6 +427,15 @@ pub const PRESSURE_CURVES: [(PressureCurve, &str); 27] = [
(PressureCurve::LightnessJitter, "dynamicsPressureLightnessJitterCurve"),
(PressureCurve::DarknessJitter, "dynamicsPressureDarknessJitterCurve"),
(PressureCurve::SecondaryJitter, "dynamicsPressureSecondaryColorJitterCurve"),
+ (PressureCurve::Flow, "dynamicsPressureTransferModulationCurve"),
+ (PressureCurve::Bleed, "dynamicsPressureBleedCurve"),
+ (PressureCurve::Roundness, "dynamicsPressureShapeRoundnessCurve"),
+ (PressureCurve::Dilution, "dynamicsPressureDilutionCurve"),
+ (PressureCurve::Charge, "dynamicsPressureCharge"),
+ (PressureCurve::Attack, "dynamicsPressureAttackCurve"),
+ (PressureCurve::WetPull, "dynamicsPressureWetPullCurve"),
+ (PressureCurve::SmudgePull, "dynamicsPressureSmudgePullCurve"),
+ (PressureCurve::SpacingJitter, "dynamicsPressurePlotSpacingJitter"),
];
/// The key brush files keep `kind` under.
@@ -469,6 +478,23 @@ fn read_in(zip: &ZipReader<'_>, prefix: &str) -> Option<BrushFile> {
set(control, v as f32);
}
}
+ // a file from before the linear jitter had its own keys jitters along the stroke as it does
+ // across (its tilt switch and angle then follow the lateral's, see `Brush::setting`); one with
+ // its own but no tilt keys has the switch off and the angle the tilt angle
+ if f.num("plotJitterLongitudinal").is_none() {
+ if let Some(v) = f.num("plotJitter") {
+ set("jitter_linear", to_control(Kept::Curve(3.0), v));
+ }
+ } else {
+ if f.num("plotJitterLongitudinalTilt").is_none() {
+ set("jitter_linear_tilt", 0.0);
+ }
+ if f.num("plotJitterLongitudinalTiltAngle").is_none()
+ && let Some(v) = f.num("dynamicsTiltAngle")
+ {
+ set("jitter_linear_tilt_angle", v as f32);
+ }
+ }
if let Some(v) = f.num("shapeCount") {
let count = stamp_count(v);
set("count", (count - 1.0) / (crate::studio::MAX_COUNT as f32 - 1.0));
@@ -930,7 +956,7 @@ mod tests {
}
#[test]
- fn a_file_without_linear_jitter_keys_gives_it_the_laterals_curve() {
+ fn a_file_without_linear_jitter_keys_gives_it_the_laterals_jitter() {
use crate::brush::PressureCurve;
let mut b = Builder::new();
let root = b.reserve();
@@ -949,6 +975,34 @@ mod tests {
let curve = |kind| back.pressure_curves.iter().find(|(k, _)| *k == kind).map(|(_, c)| c.clone());
assert!(curve(PressureCurve::LateralJitter).is_some());
assert_eq!(curve(PressureCurve::LinearJitter), curve(PressureCurve::LateralJitter));
+ let get = |k: &str| back.settings.iter().rev().find(|(key, _)| key == k).map(|(_, v)| *v);
+ assert!(get("jitter_lateral").is_some());
+ assert_eq!(get("jitter_linear"), get("jitter_lateral"));
+ }
+
+ #[test]
+ fn a_file_with_its_own_linear_jitter_but_no_tilt_keys_has_its_tilt_off() {
+ let mut b = Builder::new();
+ let root = b.reserve();
+ let name = b.string("Newer");
+ b.fill(
+ &root,
+ &["SilicaBrush", "ValkyrieBrush", "NSObject"],
+ vec![
+ ("name", name),
+ ("plotJitterLongitudinal", Value::Real(0.2)),
+ ("plotJitterTilt", Value::Bool(true)),
+ ("plotJitterTiltAngle", Value::Real(0.6)),
+ ("dynamicsTiltAngle", Value::Real(0.3)),
+ ],
+ );
+ let mut zip = ZipWriter::new();
+ zip.add("Brush.archive", &b.finish(root));
+ let back = read(&zip.finish()).unwrap();
+ let get = |k: &str| back.settings.iter().rev().find(|(key, _)| key == k).map(|(_, v)| *v);
+ assert_eq!(get("jitter_linear_tilt"), Some(0.0));
+ assert_eq!(get("jitter_linear_tilt_angle"), Some(0.3));
+ assert_eq!(get("jitter_lateral_tilt"), Some(1.0));
}
#[test]
diff --git a/crates/engine/src/mesh.rs b/crates/engine/src/mesh.rs
index a1ab9dc..d80a4e6 100644
--- a/crates/engine/src/mesh.rs
+++ b/crates/engine/src/mesh.rs
@@ -458,8 +458,7 @@ pub fn read_mtl(mtl: &str) -> Vec<Material> {
continue;
}
let Some(m) = out.last_mut() else { continue };
- // a map's file is its last word (options such as -bm 1 come before it)
- let file = || rest.last().map(|s| (*s).to_owned());
+ let file = || map_file(&rest);
let number = || rest.first().and_then(|s| s.parse::<f32>().ok());
match key {
"Kd" => {
@@ -481,6 +480,21 @@ pub fn read_mtl(mtl: &str) -> Vec<Material> {
out
}
+/// A map line's file: what follows its options (such as `-bm 1` or `-s 1 1 1`), spaces and all.
+fn map_file(words: &[&str]) -> Option<String> {
+ let mut rest = words;
+ while let Some((option, after)) = rest.split_first().filter(|(w, _)| w.starts_with('-')) {
+ let takes = match *option {
+ "-mm" => 2,
+ // up to three numbers
+ "-o" | "-s" | "-t" => after.iter().take(3).take_while(|w| w.parse::<f32>().is_ok()).count(),
+ _ => 1,
+ };
+ rest = after.get(takes..).unwrap_or(&[]);
+ }
+ (!rest.is_empty()).then(|| rest.join(" "))
+}
+
fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
@@ -572,9 +586,11 @@ f -8/1 -4/2 -1/3 -5/4
#[test]
fn a_cube_reads_as_triangles_by_material() {
- let mesh =
- read_obj(CUBE, Some("newmtl body\nKd 1 0 0\nmap_Kd -bm 1 body color.png\nnewmtl lid\nmap_Pr rough.png\n"))
- .unwrap();
+ let mesh = read_obj(
+ CUBE,
+ Some("newmtl body\nKd 1 0 0\nmap_Kd -bm 1 -s 2 2 body color.png\nnewmtl lid\nmap_Pr rough.png\n"),
+ )
+ .unwrap();
// six quads, fanned
assert_eq!(mesh.triangles.len(), 12);
// the two bodies' runs joined, first as they first came
@@ -588,7 +604,8 @@ f -8/1 -4/2 -1/3 -5/4
assert_eq!(mesh.material_file.as_deref(), Some("cube.mtl"));
assert_eq!(mesh.materials.len(), 2);
assert_eq!(mesh.materials.first().unwrap().color, Some([1.0, 0.0, 0.0]));
- assert_eq!(mesh.materials.first().unwrap().color_map.as_deref(), Some("color.png"));
+ // a map's file after its options, spaces kept
+ assert_eq!(mesh.materials.first().unwrap().color_map.as_deref(), Some("body color.png"));
assert_eq!(mesh.materials.get(1).unwrap().roughness_map.as_deref(), Some("rough.png"));
assert_eq!(mesh.bounds(), Some(([0.0; 3], [1.0; 3])));
// corners sharing position and texture coordinate kept once
diff --git a/crates/engine/src/stroke.rs b/crates/engine/src/stroke.rs
index eb80dd4..6986b32 100644
--- a/crates/engine/src/stroke.rs
+++ b/crates/engine/src/stroke.rs
@@ -2,7 +2,9 @@
//! response, spacing, the shape's placement (rotation, scatter, count, jitter, roundness) and
//! taper.
-use crate::brush::{Brush, CLASSIC_TAPER_SPAN, FLOW_POWER, PressureCurve, Rendering, TAPER_TIME_MS, Taper, Tilt};
+use crate::brush::{
+ Brush, CLASSIC_TAPER_SPAN, FLOW_POWER, PressureCurve, Rendering, TAPER_TIME_MS, Taper, Tilt, run_out,
+};
use crate::curve::Curve;
use crate::geom::{IRect, Vec2};
use crate::input::{Pointer, Sample};
@@ -50,9 +52,10 @@ pub struct Stamp {
/// How much of the brush's wet-mix attack this stamp has: the pressure (as opacity follows
/// it), as far as the attack's tilt switch lets it, 0..1.
pub attack: f32,
- /// The wet mix's grade, blur, blur jitter and wetness jitter as this stamp's pressure scales
- /// them (the brush's own pressure curves; 1 each without them).
- pub wet: [f32; 4],
+ /// The wet mix as this stamp's pressure scales it, by the brush's own pressure curves: its
+ /// grade, blur, blur jitter, wetness jitter and charge (1 each without a curve), its
+ /// dilution, wet pull and smudge pull (the pressure as it is without one).
+ pub wet: [f32; 8],
}
impl Stamp {
@@ -76,7 +79,7 @@ impl Stamp {
taper: 1.0,
transfer: 1.0,
attack: 1.0,
- wet: [1.0; 4],
+ wet: [1.0; 8],
}
}
@@ -136,9 +139,9 @@ struct Placed {
gradation: f32,
transfer: f32,
attack: f32,
- wet: [f32; 4],
- /// The pressure as the size, opacity, bleed and roundness took it.
- pressed: [f32; 4],
+ wet: [f32; 8],
+ /// The pressure as the size, opacity, bleed and roundness took it (and the stamp's own).
+ pressed: [f32; 5],
/// How much of the stamp's roundness is the drawn shape's, which the pressure squeezes (the
/// rest is what leaning adds).
drawn_share: f32,
@@ -148,8 +151,9 @@ struct Placed {
struct PathPoint {
pos: Vec2,
pressure: f32,
- /// The pressure as size, opacity, bleed and roundness each follow it (see `soften`).
- soft: [f32; 4],
+ /// The pressure as size, opacity, bleed, roundness and the stamp's other controls each
+ /// follow it (see `soften`).
+ soft: [f32; 5],
tilt: f32,
azimuth: f32,
/// How fast the input moves, 0..1 of [`FAST`].
@@ -161,7 +165,7 @@ impl PathPoint {
PathPoint {
pos: self.pos.lerp(to.pos, t),
pressure: self.pressure + (to.pressure - self.pressure) * t,
- soft: [0, 1, 2, 3].map(|k| {
+ soft: [0, 1, 2, 3, 4].map(|k| {
let (a, b) = (self.soft.get(k).copied().unwrap_or(1.0), to.soft.get(k).copied().unwrap_or(1.0));
a + (b - a) * t
}),
@@ -187,6 +191,10 @@ const MOST_AVERAGED: usize = 32;
/// expression, how much of the way back to the pen it comes.
const MOTION_FILTER_MOST: f32 = 0.9;
const EXPRESSION_MOST: f32 = 0.5;
+/// Brush files keep the spacing jitter and the speed's spacing at ten times the studio's
+/// controls: the share of a gap they widen it by.
+const SPACING_FILE_SCALE: f32 = 10.0;
+
/// The most a stamp's height may be of its width (a roundness jitter can make it taller than
/// wide).
pub const MOST_ROUNDNESS: f32 = 20.0;
@@ -194,8 +202,6 @@ pub const MOST_ROUNDNESS: f32 = 20.0;
/// The lateral and linear jitter as brush files keep them: the control to the power 2.2, times
/// this; each moves a stamp up to that many times half its diagonal (plus a pixel).
const JITTER_FILE_SCALE: f32 = 3.0;
-/// A fall off of 1 fades a stroke out over this many diameters.
-const FALLOFF_SPAN: f32 = 30.0;
/// The brush's controls the builder reads beyond its own fields (see `studio`), read once.
#[derive(Clone, Copy, Debug, Default)]
@@ -228,7 +234,7 @@ struct Extras {
/// Light pressure lowering (or, negative, raising) each stamp's flow, −1..1.
pressure_flow: f32,
/// How slowly size, opacity, bleed and roundness follow the pressure when the pen moves fast.
- pressure_response: [f32; 4],
+ pressure_response: [f32; 5],
/// Light pressure, and leaning, letting more of a moving grain through (bleed), 0..1.
pressure_bleed: f32,
tilt_bleed: f32,
@@ -324,11 +330,13 @@ impl Extras {
grain_movement: unit("grain_movement"),
grain_offset_jitter: b.setting("grain_offset_jitter") >= 0.5,
pressure_flow: both("pressure_flow"),
+ // the stamp's own pressure follows as the roundness does
pressure_response: [
"pressure_size_response",
"pressure_opacity_response",
"pressure_bleed_response",
"pressure_roundness_response",
+ "pressure_roundness_response",
]
.map(unit),
// the control's place to the power 2.2
@@ -439,7 +447,7 @@ pub struct StrokeBuilder {
/// Whether the speed has been measured (the first move is taken as it is).
speed_known: bool,
/// The pressure as each use follows it, at the last sample; and how many samples so far.
- soft: Option<[f32; 4]>,
+ soft: Option<[f32; 5]>,
segments: u32,
/// A sample stroke drawn for show: no speed, and the pressure taken as it comes.
steady: bool,
@@ -447,7 +455,9 @@ pub struct StrokeBuilder {
exact: bool,
/// Drawn on the studio's pad, and whether the brush previews tilt there.
pad: Option<bool>,
- gap_jitter: f32,
+ /// A gap drawn that the last input segment ended before reaching: the next one goes on
+ /// with it.
+ pending_gap: Option<f32>,
/// The whole stroke's colour shift, drawn once.
stroke_shift: Tint,
/// The stroke's share of the secondary colour, picked as it starts.
@@ -600,7 +610,7 @@ impl StrokeBuilder {
steady: false,
exact: false,
pad: None,
- gap_jitter: 1.0,
+ pending_gap: None,
stroke_shift: Tint::NONE,
stroke_secondary: 0.0,
stroke_turn: 0.0,
@@ -931,10 +941,20 @@ impl StrokeBuilder {
self.direction = d.y.atan2(d.x);
self.last_seg = seg;
let mut done = 0.0f32;
+ // each input segment goes on from the plain gap where it starts
+ let mut last = self.step(from);
while self.placed.len() < MAX_STAMPS {
- let need = self.step(from.lerp(to, done / seg)) - self.carry;
+ let gap = match self.pending_gap.take() {
+ Some(gap) => gap,
+ None => {
+ last = self.gap(from.lerp(to, done / seg), last);
+ last
+ }
+ };
+ let need = gap - self.carry;
if done + need > seg {
self.carry += seg - done;
+ self.pending_gap = Some(gap);
break;
}
done += need.max(0.0);
@@ -989,13 +1009,25 @@ impl StrokeBuilder {
((1.0 - compression) + compression * across * (across + long).max(0.0).sqrt()).clamp(0.0, 1.0)
}
- /// Distance to the next stamp: the spacing's share of the stamp's square, and half a pixel
- /// more (and a little with the spacing), wider apart the faster the input, jittered per gap.
+ /// The plain distance to the next stamp: the spacing's share of the stamp's square, and half
+ /// a pixel more (and a little with the spacing).
fn step(&self, p: PathPoint) -> f32 {
let spacing = self.brush.spacing.max(0.005);
let extra = 0.5 + (spacing - SPACING_FLOOR).max(0.0) / (SPACING_SPAN / 2.0);
- let speed = 1.0 + 2.0 * self.extras.speed_spacing * p.speed;
- ((spacing * self.square_at(p) * self.extras.spacing_stride + extra) * speed * self.gap_jitter).max(0.25)
+ (spacing * self.square_at(p) * self.extras.spacing_stride + extra).max(0.25)
+ }
+
+ /// The gap to the next stamp at `p`, the one before it `last`: the two gaps' mean, widened
+ /// by the spacing jitter (a random share of it, as far as its curve lets it) and by the
+ /// input's speed. Gaps only ever widen.
+ fn gap(&mut self, p: PathPoint, last: f32) -> f32 {
+ let x = self.extras;
+ let mut widen = p.speed * x.speed_spacing * SPACING_FILE_SCALE;
+ if x.spacing_jitter > 0.0 {
+ let by = self.brush.pressure_curves.at(PressureCurve::SpacingJitter, p.soft[4].clamp(0.0, 1.0));
+ widen += by * x.spacing_jitter * SPACING_FILE_SCALE * self.random.next();
+ }
+ ((1.0 + widen.max(0.0)) * (last + self.step(p)) * 0.5).max(0.25)
}
/// Each use's pressure followed from `before` towards `now` over `frames` (of a 60 Hz display)
@@ -1003,11 +1035,11 @@ impl StrokeBuilder {
/// speed lags (to (frames / pixels, at least 0.2) to the power twice its response, each
/// sample), and every use is evened out with what it was, more so the more often the pen
/// reports (eased in over the stroke's first frames).
- fn soften(&self, now: [f32; 4], before: [f32; 4], frames: f32, moved: f32) -> [f32; 4] {
+ fn soften(&self, now: [f32; 5], before: [f32; 5], frames: f32, moved: f32) -> [f32; 5] {
let pace = if moved > 0.0 { (frames / moved).clamp(0.2, 1.0) } else { 1.0 };
let held = 2.0 / frames.max(1e-3);
let ramp = (self.segments as f32 / held).clamp(0.0, 1.0) * held;
- [0, 1, 2, 3].map(|k| {
+ [0, 1, 2, 3, 4].map(|k| {
let (n, b) = (now.get(k).copied().unwrap_or(1.0), before.get(k).copied().unwrap_or(1.0));
let response = self.extras.pressure_response.get(k).copied().unwrap_or(0.0);
let followed = b + (n - b) * pace.powf(2.0 * response);
@@ -1065,18 +1097,29 @@ impl StrokeBuilder {
let x = self.extras;
let start_span = self.start_span();
let sw = x.tilt_switches;
- if x.spacing_jitter > 0.0 {
- self.gap_jitter = (1.0 + x.spacing_jitter * (self.random.next() * 2.0 - 1.0)).max(0.05);
- }
let diameter = self.diameter_at(p);
let (_, pressure_alpha) = self.brush.factors(p.soft[0], p.soft[1]);
// leaning fades the stamp by the square root of how far it has gone
let fade = self.leaning(p, x.tilt_angles.opacity).sqrt() * self.brush.tilt.opacity;
let tilt_alpha = if fade >= 0.0 { 1.0 - fade } else { 1.0 - (fade + self.brush.tilt.opacity) };
let speed_alpha = (1.0 - x.speed_opacity * p.speed).clamp(0.0, 1.0);
- let falloff = (1.0 - distance * x.falloff / (FALLOFF_SPAN * self.diameter)).max(0.0);
- let light = 1.0 - p.soft[2].clamp(0.0, 1.0);
- let pressure_flow = (1.0 - x.pressure_flow * light).clamp(0.0, 1.0);
+ // the fall off fades the stroke out by the cube root of how far it has gone
+ let falloff = 1.0 - run_out(x.falloff, distance);
+ use PressureCurve as PC;
+ // the brush's own pressure curves for its other controls, at the stamp's pressure (a
+ // finger's is full): each control scaled by its curve, or left as it is without one
+ let pressure = p.soft[4].clamp(0.0, 1.0);
+ let curves = &self.brush.pressure_curves;
+ let by = |k: PressureCurve| curves.at(k, pressure);
+ // the flow lets through as much as its pressure amount and curve say (an amount below 0
+ // the other way)
+ let flowing = curves.through(PC::Flow, pressure);
+ let pressure_flow = if x.pressure_flow >= 0.0 {
+ 1.0 - x.pressure_flow * (1.0 - flowing)
+ } else {
+ 1.0 + x.pressure_flow * flowing
+ }
+ .clamp(0.0, 1.0);
// flow, pressure, tilt and speed together through the opacity range, eased; then what
// pressure lets through (the brush's pressure flow) and the fall off
let b = &self.brush;
@@ -1090,13 +1133,7 @@ impl StrokeBuilder {
if self.brush.rendering == Rendering::Gradual && !self.brush.mixes_wet() {
alpha = StrokeBuilder::gradual(alpha, diameter / self.step(p));
}
- use PressureCurve as PC;
let shape = self.brush.shape.clone();
- // the brush's own pressure curves for its other controls, at the stamp's pressure (a
- // finger's is full): each control scaled by its curve, or left as it is without one
- let pressure = p.soft[2].clamp(0.0, 1.0);
- let curves = &self.brush.pressure_curves;
- let by = |k: PressureCurve| curves.at(k, pressure);
let [count_by, count_jitter_by, lateral_by, linear_by, size_jitter_by, opacity_jitter_by, scatter_by] = [
PC::Count,
PC::CountJitter,
@@ -1117,7 +1154,17 @@ impl StrokeBuilder {
PC::GrainDepthJitter,
]
.map(by);
- let wet = [PC::WetGrade, PC::WetBlur, PC::WetBlurJitter, PC::WetnessJitter].map(by);
+ let along = |k: PressureCurve| curves.through(k, pressure);
+ let wet = [
+ by(PC::WetGrade),
+ by(PC::WetBlur),
+ by(PC::WetBlurJitter),
+ by(PC::WetnessJitter),
+ by(PC::Charge),
+ along(PC::Dilution),
+ along(PC::WetPull),
+ along(PC::SmudgePull),
+ ];
let color_jitter_by =
[PC::HueJitter, PC::SaturationJitter, PC::LightnessJitter, PC::DarknessJitter, PC::SecondaryJitter];
let color_has_curve = color_jitter_by.map(|k| curves.get(k).is_some());
@@ -1170,7 +1217,7 @@ impl StrokeBuilder {
Some(theta) if self.pointer.has_pressure() => Tilt::reach(p.tilt, theta),
Some(theta) => Tilt::reach(std::f32::consts::FRAC_PI_2, theta),
};
- let attack = (p.soft[1].clamp(0.0, 1.0) * attack_tilt).clamp(0.0, 1.0);
+ let attack = (p.soft[1].clamp(0.0, 1.0) * attack_tilt * curves.through(PC::Attack, pressure)).clamp(0.0, 1.0);
let [hue_by, saturation_by, lightness_by, darkness_by, secondary_by] = color_first;
let [hue_more, saturation_more, lightness_more, darkness_more, secondary_more] = color_more;
for _ in 0..count {
@@ -1245,7 +1292,7 @@ impl StrokeBuilder {
};
let mut depth = base * (1.0 - jitter) * depth_by;
depth += (1.0 - depth) * (x.tilt_bleed * self.leaning(p, x.tilt_angles.bleed)).clamp(0.0, 1.0);
- let grain_press = (1.0 - light).clamp(0.0, 1.0);
+ let grain_press = p.soft[2].clamp(0.0, 1.0);
let mut depth = depth.max(x.grain_depth_min).clamp(0.0, 1.0);
// the depth tilt: leaning takes the depth down to its least
if sw.grain_depth.is_some() {
@@ -1319,7 +1366,7 @@ impl StrokeBuilder {
let (mut grain_press, mut roundness) = (p.grain_press, p.roundness);
if self.pointer.has_pressure() && fade > 0.0 {
let kept = (1.0 - fade) + fade * (start * finish).powf(Taper::tip_power(tip));
- let [s, o, b, r] = p.pressed;
+ let [s, o, b, r, _] = p.pressed;
let (s0, o0) = self.brush.factors(s, o);
let (s1, o1) = self.brush.factors(s * kept, o * kept);
if s0 > 0.0 {
@@ -1814,6 +1861,59 @@ mod tests {
assert!((upright[0].center.x - 100.0).abs() < 0.01);
}
+ #[test]
+ fn spacing_jitter_and_speed_only_widen_the_gaps() {
+ // 600 px in 200 ms: fast input
+ let gaps = |settings: &[(&str, f32)]| {
+ let mut b = plain();
+ for &(k, v) in settings {
+ b.set_setting(k, v);
+ }
+ let samples: Vec<Sample> =
+ (0..=50).map(|i| Sample::at(Vec2::new(i as f32 * 12.0, 50.0), 1.0, i as f64 * 4.0)).collect();
+ let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus);
+ let all = s.add(&samples);
+ all.windows(2).map(|w| w[1].center.x - w[0].center.x).collect::<Vec<f32>>()
+ };
+ let mean = |g: &[f32]| g.iter().sum::<f32>() / g.len() as f32;
+ let plain_gaps = gaps(&[]);
+ let least = plain_gaps.iter().copied().fold(f32::MAX, f32::min);
+ let jittered = gaps(&[("spacing_jitter", 0.1)]);
+ assert!(jittered.iter().all(|&g| g > least - 1e-3));
+ assert!(mean(&jittered) > 1.2 * mean(&plain_gaps), "{} {}", mean(&jittered), mean(&plain_gaps));
+ let sped = gaps(&[("speed_spacing", 0.05)]);
+ assert!(mean(&sped) > 1.2 * mean(&plain_gaps), "{} {}", mean(&sped), mean(&plain_gaps));
+ }
+
+ #[test]
+ fn flow_bleed_and_roundness_follow_their_own_curves() {
+ use crate::curve::Curve;
+ let middle = |settings: &[(&str, f32)], level: Option<PressureCurve>| {
+ let mut b = Brush { pressure_size: 0.0, ..plain() };
+ for &(k, v) in settings {
+ b.set_setting(k, v);
+ }
+ // a curve that holds full pressure throughout
+ if let Some(kind) = level {
+ b.pressure_curves.set(kind, Some(Curve::new(&[Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)])));
+ }
+ let samples: Vec<Sample> =
+ (0..=30).map(|i| Sample::at(Vec2::new(i as f32 * 4.0, 50.0), 0.3, i as f64 * 4.0)).collect();
+ let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus);
+ s.add(&samples);
+ let all = s.finish();
+ all[all.len() / 2]
+ };
+ let flow = [("pressure_flow", 1.0)];
+ assert!(middle(&flow, None).alpha < 0.5 * middle(&flow, Some(PressureCurve::Flow)).alpha);
+ let bleed = [("pressure_bleed", 1.0)];
+ assert!(middle(&bleed, None).grain_press < 0.4);
+ assert!(middle(&bleed, Some(PressureCurve::Bleed)).grain_press > 0.99);
+ let round = [("pressure_roundness", 1.0)];
+ assert!(middle(&round, None).roundness < 0.4);
+ assert!(middle(&round, Some(PressureCurve::Roundness)).roundness > 0.99);
+ }
+
#[test]
fn the_wet_attack_follows_the_pressure_and_its_tilt_switch() {
let attack = |pressure: f32, tilt: f32, switch: bool, pointer: Pointer| {
@@ -1826,7 +1926,8 @@ mod tests {
StrokeBuilder::new(b, 10.0, pointer).preview(&[s])[0].attack
};
assert!((attack(1.0, 0.0, false, Pointer::Stylus) - 1.0).abs() < 1e-4);
- assert!((attack(0.4, 0.0, false, Pointer::Stylus) - 0.4).abs() < 0.05);
+ // the pressure counts twice: as the opacity takes it, and through the attack's own curve
+ assert!((attack(0.4, 0.0, false, Pointer::Stylus) - 0.16).abs() < 0.03);
// switched on: an upright pen next to none, a leaning one more, a finger as a flat pen
assert!(attack(1.0, 0.0, true, Pointer::Stylus) < 0.01);
let flat = Tilt::reach(crate::brush::FLAT_TILT, 0.0);
@@ -1921,9 +2022,13 @@ mod tests {
assert!(base.iter().all(|s| (s.center.y - 50.0).abs() < 1e-3));
// spacing jitter changes how many stamps there are
assert_ne!(with("spacing_jitter", 1.0).len(), base.len());
- // fall off fades the far end
+ // fall off fades the far end: by 33 px a fall off of 1 has faded it out, a half by 264
let faded = with("falloff", 1.0);
- assert!(faded.last().unwrap().alpha < faded[0].alpha * 0.5);
+ assert!(faded.last().unwrap().alpha < 1e-6 && faded[0].alpha > 0.5);
+ let half = with("falloff", 0.5);
+ let near = |x: f32| half.iter().min_by(|a, b| (a.center.x - x).abs().total_cmp(&(b.center.x - x).abs()));
+ let (start, by_33) = (near(0.0).map_or(0.0, |s| s.alpha), near(33.0).map_or(0.0, |s| s.alpha));
+ assert!((by_33 / start - 0.5).abs() < 0.05, "{start} {by_33}");
// fast input (600 px in 200 ms: 50 px a frame) thins the stroke with speed size
let fast = |b: Brush| {
let mut s = StrokeBuilder::new(b, 10.0, Pointer::Stylus);
diff --git a/crates/gpu/src/canvas.rs b/crates/gpu/src/canvas.rs
index da58cc8..8b1d9d6 100644
--- a/crates/gpu/src/canvas.rs
+++ b/crates/gpu/src/canvas.rs
@@ -9,7 +9,7 @@ use std::num::NonZeroU64;
use std::sync::mpsc;
use procraft_engine::animation::{self, FrameLook};
-use procraft_engine::brush::{BRUSH_BEHIND, Brush, GRAIN_LINEAR_HEIGHT, GrainMode, Rendering, Source};
+use procraft_engine::brush::{BRUSH_BEHIND, Brush, GRAIN_LINEAR_HEIGHT, GrainMode, Rendering, Source, run_out};
use procraft_engine::document::{BlendMode, Document, Layer, LayerId, LayerKind};
use procraft_engine::geom::{Affine, IRect};
use procraft_engine::stroke::{MOST_ROUNDNESS, Stamp};
@@ -112,6 +112,9 @@ pub struct StrokeStyle {
pub load: f32,
/// Wet mix: water in the paint, 0..1: it goes on thinner.
pub dilution: f32,
+ /// The brush's fall off, 0..1: the paint it mixes in runs out along the stroke as its stamps
+ /// fade.
+ pub falloff: f32,
/// Wet mix: how hard the paint goes on over what is there (less of it pulled in), its grain
/// (the mix uneven from pixel to pixel), how blurred what it pulls in is, and how much the
/// pull varies from stamp to stamp; each 0..1.
@@ -171,6 +174,7 @@ impl StrokeStyle {
wet_pull: None,
load: 0.0,
dilution: 0.0,
+ falloff: 0.0,
attack: 0.0,
grade: 0.0,
blur: 0.0,
@@ -222,6 +226,7 @@ impl StrokeStyle {
wet_pull: wet.then(|| brush.setting("wet_pull").clamp(0.0, 1.0)),
load: if wet { brush.setting("wet_charge").clamp(0.0, 1.0) } else { 0.0 },
dilution: if wet { brush.setting("wet_dilution").clamp(0.0, 1.0) } else { 0.0 },
+ falloff: brush.setting("falloff").clamp(0.0, 1.0),
attack: if wet { brush.setting("wet_attack").clamp(0.0, 1.0) } else { 0.0 },
// the grade goes both ways; drawn yet only as how uneven the mix is
grade: if wet { brush.setting("wet_grade").abs().clamp(0.0, 1.0) } else { 0.0 },
@@ -653,23 +658,26 @@ fn unit_hash(n: u32) -> f32 {
/// Resolution of what a smudge brush carries, cells on a side.
const SMUDGE_GRID: u32 = 32;
const SMUDGE_UNIFORM_SIZE: u64 = std::mem::size_of::<SmudgeUniform>() as u64;
-/// Wet mix: the stroke's length (canvas pixels) over which paint loaded at nothing runs out, by the
-/// cube root of the length (see [`wet_mixture`]).
-const CHARGE_LENGTH: f32 = 33.0;
/// A wet stamp's (mixture, final mixture, pull) once the stroke has gone `length` canvas pixels:
-/// the paint the brush mixes into what it carries is what its dilution leaves (by 2.4) and its
-/// charge (running out by the cube root of the length), at least its attack (the stamp's
+/// the paint the brush mixes into what it carries is what its dilution leaves (by 2.4, and as
+/// far as the fall off has not run it out) and its charge (running out by the cube root of the
+/// length), at least its attack (the stamp's
/// `attack` share of it: its pressure), times `jitter`; it
/// lays down what it carries by the mixture, a share of it by the grade; the pull is the wet
-/// pull's eighth root (a pull of 0.9 keeps 0.99 a stamp).
-fn wet_mixture(style: &StrokeStyle, length: f32, jitter: f32, attack: f32) -> (f32, f32, f32) {
- let charge = if style.load > 0.0 {
- 1.0 - ((1.0 - style.load) * (length.max(0.0) / CHARGE_LENGTH).cbrt()).clamp(0.0, 1.0)
- } else {
- 0.0
- };
- let diluted = (1.0 - style.dilution.clamp(0.0, 1.0)).powf(2.4);
+/// pull's eighth root (a pull of 0.9 keeps 0.99 a stamp). The stamp's pressure scales the
+/// dilution and the charge by `dilution_by` and `charge_by` (their curves).
+fn wet_mixture(
+ style: &StrokeStyle,
+ length: f32,
+ jitter: f32,
+ attack: f32,
+ dilution_by: f32,
+ charge_by: f32,
+) -> (f32, f32, f32) {
+ let charge = if style.load > 0.0 { 1.0 - run_out(1.0 - style.load, length) } else { 0.0 } * charge_by;
+ let diluted =
+ (1.0 - run_out(style.falloff, length)) * (1.0 - style.dilution.clamp(0.0, 1.0) * dilution_by).powf(2.4);
let attack = style.attack.clamp(0.0, 1.0) * attack.clamp(0.0, 1.0);
let mixture = ((diluted + charge).max(attack) * jitter).clamp(0.0, 1.0);
let pull = style.wet_pull.unwrap_or(0.0).clamp(0.0, 1.0).powf(0.125);
@@ -775,7 +783,7 @@ enum Op {
Stamps {
instances: Vec<StampInstance>,
/// Each stamp's wet-mix scaling (see [`Stamp::wet`]), for the wet paint drawn in place.
- wet: Vec<[f32; 4]>,
+ wet: Vec<[f32; 8]>,
style: StrokeStyle,
clear: bool,
layer: LayerId,
@@ -1577,7 +1585,7 @@ impl Canvas {
let capped = self.pipelines.stamp_capped.is_some();
let drawn: Vec<&Stamp> =
stamps.iter().filter(|s| s.center.is_finite() && s.radius.is_finite() && s.alpha.is_finite()).collect();
- let wet: Vec<[f32; 4]> =
+ let wet: Vec<[f32; 8]> =
drawn.iter().map(|s| s.wet.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 1.0 })).collect();
let instances: Vec<StampInstance> = drawn
.iter()
@@ -2739,7 +2747,7 @@ impl Canvas {
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
params: &mut UniformData,
- (instances, wet): (&[StampInstance], &[[f32; 4]]),
+ (instances, wet): (&[StampInstance], &[[f32; 8]]),
style: &StrokeStyle,
target: LayerId,
restart: bool,
@@ -2904,15 +2912,19 @@ impl Canvas {
}
smudge.last = Some(s.center);
// the grade, blur and jitters as far as this stamp's pressure takes them
- let [grade_by, blur_by, blur_jitter_by, wet_jitter_by] = wet.get(k).copied().unwrap_or([1.0; 4]);
+ let [grade_by, blur_by, blur_jitter_by, wet_jitter_by, charge_by, dilution_by, wet_pull_by, smudge_pull_by] =
+ wet.get(k).copied().unwrap_or([1.0; 8]);
let stamp_style = StrokeStyle { grade: style.grade * grade_by, ..*style };
// the mixture varies from stamp to stamp by the wetness jitter
let jitter = 1.0 - style.wet_jitter * wet_jitter_by * unit_hash(smudge.stamps);
smudge.stamps = smudge.stamps.saturating_add(1);
+ // the pull as far as the stamp's pressure takes it (the wet pull's or the smudge's)
let (mixture, final_mixture, wet_pull) = if wet_paint {
- wet_mixture(&stamp_style, smudge.length, jitter, s.more[3])
+ let (mixture, laid, pull) =
+ wet_mixture(&stamp_style, smudge.length, jitter, s.more[3], dilution_by, charge_by);
+ (mixture, laid, pull * wet_pull_by)
} else {
- (0.0, 1.0, style.pull.clamp(0.0, 1.0))
+ (0.0, 1.0, style.pull.clamp(0.0, 1.0) * smudge_pull_by)
};
let moving = style.grain_mode == GrainMode::Moving;
let offset = params.push(&SmudgeUniform {
@@ -5308,3 +5320,41 @@ pub fn read_texture(gpu: &Gpu, texture: &wgpu::Texture, width: u32, height: u32)
buffer.unmap();
Ok(out)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_stamps_pressure_scales_the_wet_mixes_dilution_and_charge() {
+ let style = StrokeStyle {
+ dilution: 0.5,
+ load: 0.5,
+ wet_pull: Some(0.5),
+ ..StrokeStyle::new(StrokeTool::Paint, [0.0; 3], 1.0)
+ };
+ // no dilution at no pressure: the paint goes on whole
+ assert_eq!(wet_mixture(&style, 0.0, 1.0, 0.0, 0.0, 1.0).0, 1.0);
+ // diluted by half: what it leaves, by 2.4, with no charge
+ let (mixed, ..) = wet_mixture(&style, 33.0, 1.0, 0.0, 1.0, 0.0);
+ assert!((mixed - 0.5f32.powf(2.4)).abs() < 1e-5);
+ // and the charge, half run out by 33 px, as far as its curve lets it
+ let (charged, ..) = wet_mixture(&style, 33.0, 1.0, 0.0, 1.0, 1.0);
+ assert!((charged - (0.5f32.powf(2.4) + 0.5)).abs() < 1e-5);
+ }
+
+ #[test]
+ fn the_fall_off_runs_the_wet_mixes_paint_out_along_the_stroke() {
+ let style = StrokeStyle {
+ dilution: 0.5,
+ falloff: 0.5,
+ wet_pull: Some(0.5),
+ ..StrokeStyle::new(StrokeTool::Paint, [0.0; 3], 1.0)
+ };
+ let diluted = 0.5f32.powf(2.4);
+ // whole where the stroke starts, half gone by 33 px, all gone by 264
+ assert!((wet_mixture(&style, 0.0, 1.0, 0.0, 1.0, 1.0).0 - diluted).abs() < 1e-5);
+ assert!((wet_mixture(&style, 33.0, 1.0, 0.0, 1.0, 1.0).0 - diluted * 0.5).abs() < 1e-5);
+ assert!(wet_mixture(&style, 264.0, 1.0, 0.0, 1.0, 1.0).0.abs() < 1e-5);
+ }
+}