Open Sample Project starts in a Samples folder that holds the built-in sample

This commit is contained in:
vangel76 committed 2026-11-25 11:21:23 +01:00
1 parent 14f6502029
commit 9c2393655e
11 files changed
+306 -21

No files matched your search

+1 -1
View File
@@ -97,7 +97,7 @@ pub use fill_hit_test::FillHitTest;
pub use fill_mode::FillMode;
pub use log::{LogEntry, LogLevel, SessionLog};
pub use path_tool::PathState;
pub use project_cmds::sample_session;
pub use project_cmds::{SAMPLE_BAKE_RESOLUTION_PX, SAMPLE_PROJECT_NAME, SAMPLE_RESOLUTION_PX, sample_session};
pub use session::{
CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState,
ViewMode, history_label, stroke_template,
+11 -2
View File
@@ -57,9 +57,18 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "layer": l.0 }))
}
/// Name of the sample project, which is also the stem of its project file
pub const SAMPLE_PROJECT_NAME: &str = "Material Ball";
/// Texture size of the sample project the Open Sample Project menu entry offers
pub const SAMPLE_RESOLUTION_PX: u32 = 2048;
/// Bake size of the sample project the Open Sample Project menu entry offers
pub const SAMPLE_BAKE_RESOLUTION_PX: u32 = 1024;
/// A baked material ball with smart materials on both texture sets
pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result<Session> {
let mut session = Session::new_project("Material Ball", primitives::material_ball(), "builtin:material_ball", None, resolution)?;
let mut session = Session::new_project(SAMPLE_PROJECT_NAME, primitives::material_ball(), "builtin:material_ball", None, resolution)?;
for set_index in 0..session.set_count() {
let set = session.doc.project.texture_set_mut(set_index)?;
set.bake.common.resolution = BakeResolution::from_pixels(bake_resolution).ok_or_else(|| bad("project.sample", "invalid bake resolution"))?;
@@ -91,7 +100,7 @@ pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result<Session>
}
fn sample(s: &mut Session, _: &Value) -> Result<Value> {
let next = sample_session(2048, 1024)?;
let next = sample_session(SAMPLE_RESOLUTION_PX, SAMPLE_BAKE_RESOLUTION_PX)?;
s.switch_to(next);
Ok(crate::inspect::session(s))
}
+17 -1
View File
@@ -128,6 +128,8 @@ mod resource_picker;
mod resource_picker_item;
mod round_gizmo;
mod running_bake;
#[cfg(not(target_arch = "wasm32"))]
mod sample_project;
pub mod saved_search;
mod screen_color_pick;
pub mod screen_pick;
@@ -243,6 +245,12 @@ pub struct TextureCraftApp {
pub session: Session,
#[cfg(not(target_arch = "wasm32"))]
pub(crate) session_log_file: Option<session_log_file::SessionLogFile>,
/// The folder File > Open Sample Project starts in, under the data folder
#[cfg(not(target_arch = "wasm32"))]
pub samples_folder: std::path::PathBuf,
/// The sample project being written in the background
#[cfg(not(target_arch = "wasm32"))]
pub(crate) sample_preparation: Option<sample_project::SamplePreparation>,
viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds,
/// A smooth move to a saved camera in progress.
camera_glide: Option<CameraGlide>,
@@ -396,6 +404,10 @@ impl TextureCraftApp {
session,
#[cfg(not(target_arch = "wasm32"))]
session_log_file: None,
#[cfg(not(target_arch = "wasm32"))]
samples_folder: std::path::PathBuf::new(),
#[cfg(not(target_arch = "wasm32"))]
sample_preparation: None,
viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds::default(),
ui,
ui_store,
@@ -467,6 +479,7 @@ impl TextureCraftApp {
{
// The first window of the process fixes it; a new folder applies on restart
let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder));
app.samples_folder = user_dir(sample_project::SAMPLES_FOLDER);
if cc.winit_window().is_some() {
match session_log_file::SessionLogFile::start(&crate::data_dir().join("logs")) {
@@ -1088,7 +1101,10 @@ impl eframe::App for TextureCraftApp {
control::poll(self, ctx);
#[cfg(not(target_arch = "wasm32"))]
self.run_file_dialog_answers();
{
self.run_file_dialog_answers();
self.poll_sample_project();
}
web_files::poll(self);
let dropped = ctx.input(|input| input.raw.dropped_files.clone());
+118
View File
@@ -0,0 +1,118 @@
//! The sample project File > Open Sample Project offers: written once into the Samples folder.
use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, TryRecvError, channel};
use texturecraft_engine::core::PROJECT_EXT;
use texturecraft_engine::{SAMPLE_BAKE_RESOLUTION_PX, SAMPLE_PROJECT_NAME, SAMPLE_RESOLUTION_PX, sample_session};
use crate::TextureCraftApp;
use crate::file_dialogs::{Bound, FileDialog};
use crate::i18n::{tr, trf};
/// The folder under the data folder that holds the sample projects
pub(crate) const SAMPLES_FOLDER: &str = "Samples";
/// The error when the background thread ends without sending its result
const STOPPED_WITHOUT_ANSWER: &str = "the preparation stopped without an answer";
/// The background job that writes the sample project file
pub(crate) type SamplePreparation = Receiver<Result<PathBuf, String>>;
/// The sample project's file in `folder`
fn sample_file(folder: &Path) -> PathBuf {
folder.join(format!("{SAMPLE_PROJECT_NAME}.{PROJECT_EXT}"))
}
/// Makes sure `folder` exists and holds the built-in sample project, and returns the file.
/// A file that is already there is kept as it is, so a sample the user edited and saved stays.
fn ensure_sample_project(folder: &Path) -> Result<PathBuf, String> {
std::fs::create_dir_all(folder).map_err(|error| format!("{}: {error}", folder.display()))?;
let file = sample_file(folder);
if file.exists() {
return Ok(file);
}
let session = sample_session(SAMPLE_RESOLUTION_PX, SAMPLE_BAKE_RESOLUTION_PX).map_err(|error| error.to_string())?;
let bytes = session.to_project_bytes().map_err(|error| error.to_string())?;
// Baking takes a while, so look again before writing in case the file appeared meanwhile
if file.exists() {
return Ok(file);
}
texturecraft_engine::formats::write_atomic(&file, &bytes).map_err(|error| format!("{}: {error}", file.display()))?;
Ok(file)
}
impl TextureCraftApp {
/// File > Open Sample Project: the file picker, in the Samples folder. A missing sample is
/// written on a background thread first, and the picker opens when that is done.
pub(crate) fn open_sample_project(&mut self, ctx: &egui::Context) {
if self.sample_preparation.is_some() {
return;
}
let folder = self.samples_folder.clone();
if sample_file(&folder).exists() {
self.ask_for_sample_project(Some(folder));
return;
}
self.toast(tr("Preparing the sample project..."), false);
let (sender, receiver) = channel();
let ctx = ctx.clone();
std::thread::spawn(move || {
// The receiver is gone only when the app closed
let _ = sender.send(ensure_sample_project(&folder));
ctx.request_repaint();
});
self.sample_preparation = Some(receiver);
}
/// Whether the sample project is being written
pub fn sample_project_pending(&self) -> bool {
self.sample_preparation.is_some()
}
/// Takes the finished sample preparation, if any, and opens the picker. Called every frame.
pub(crate) fn poll_sample_project(&mut self) {
let Some(receiver) = &self.sample_preparation else { return };
match receiver.try_recv() {
Ok(result) => self.finish_sample_project(result),
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => self.finish_sample_project(Err(STOPPED_WITHOUT_ANSWER.to_string())),
}
}
/// Waits for the sample preparation to end and opens the picker, so tests need no timing.
pub fn wait_for_sample_project(&mut self) {
let Some(receiver) = &self.sample_preparation else { return };
let result = receiver.recv().unwrap_or_else(|_| Err(STOPPED_WITHOUT_ANSWER.to_string()));
self.finish_sample_project(result);
}
fn finish_sample_project(&mut self, result: Result<PathBuf, String>) {
self.sample_preparation = None;
match result {
Ok(_) => self.ask_for_sample_project(Some(self.samples_folder.clone())),
Err(error) => {
self.toast(trf("Could not prepare the sample project: {error}", &[("error", &error)]), true);
self.ask_for_sample_project(None);
}
}
}
fn ask_for_sample_project(&mut self, folder: Option<PathBuf>) {
let dialog = FileDialog::open().title(tr("Open Sample Project")).filter(tr("TextureCraft project"), &[PROJECT_EXT]);
let dialog = match folder {
Some(folder) => dialog.directory(folder),
None => dialog,
};
self.ask_file(dialog, Bound::App, crate::windows::open_picked);
}
}
+16 -12
View File
@@ -539,19 +539,15 @@ pub(crate) fn import_materialx(app: &mut TextureCraftApp, path: &str) -> bool {
/// File menu actions that need dialogs. Returns true when handled.
#[cfg(not(target_arch = "wasm32"))]
pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> bool {
pub fn file_action(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) -> bool {
match id {
"file.open" | "project.sample" => {
let dialog = if id == "project.sample" {
FileDialog::open().title(tr("Open Sample Project")).filter(tr("TextureCraft project"), &[texturecraft_engine::core::PROJECT_EXT])
} else {
FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS)
};
app.ask_file(dialog, Bound::App, |app, paths| {
if let Some(path) = paths.first() {
open_path(app, &path.display().to_string());
}
});
"file.open" => {
let dialog = FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS);
app.ask_file(dialog, Bound::App, open_picked);
true
}
"project.sample" => {
app.open_sample_project(ctx);
true
}
"file.save" if app.session.path.is_some() => {
@@ -631,6 +627,14 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
}
}
/// Opens the project or mesh a file dialog picked
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn open_picked(app: &mut TextureCraftApp, paths: Vec<std::path::PathBuf>) {
if let Some(path) = paths.first() {
open_path(app, &path.display().to_string());
}
}
/// Asks where to save the project and runs `cmd` with the answer. Each caller is its own dialog
/// request, so Save As and Save a Copy queue separately.
#[cfg(not(target_arch = "wasm32"))]
+13 -2
View File
@@ -165,15 +165,26 @@ fn creating_or_opening_a_project_from_the_empty_state_works() {
assert!(harness.state().ui.windows.new_project, "New project opens its dialog from the empty state");
let directory = super::temp_dir::TempDir::new("picked-sample");
let file = directory.join("sample.tcraft");
let samples_folder = directory.join("Samples");
std::fs::create_dir(&samples_folder).unwrap();
let file = samples_folder.join("Material Ball.tcraft");
let sample = Session::new_project("Chosen sample", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
std::fs::write(&file, sample.to_project_bytes().unwrap()).unwrap();
let mut harness = empty();
harness.state_mut().samples_folder = samples_folder.clone();
let picked = file.clone();
harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| texturecraft_ui_egui::file_dialogs::Answer::Paths(vec![picked.clone()]))));
let started_in = std::rc::Rc::new(std::cell::RefCell::new(None));
let recorded = started_in.clone();
harness.state_mut().file_dialogs.set_override(Some(Box::new(move |request| {
if let texturecraft_ui_egui::file_dialogs::Request::File(dialog) = request {
*recorded.borrow_mut() = dialog.directory.clone();
}
texturecraft_ui_egui::file_dialogs::Answer::Paths(vec![picked.clone()])
})));
invoke(&mut harness, "project.sample");
assert_eq!(*started_in.borrow(), Some(samples_folder), "the picker starts in the Samples folder");
assert!(harness.state().session.project_open);
assert_eq!(harness.state().session.doc.project.name, sample.doc.project.name, "the selected sample project opens");
}
+5
View File
@@ -77,7 +77,12 @@ fn a_canceled_dialog_changes_nothing() {
#[test]
fn the_sample_picker_asks_to_save_only_after_a_path_is_chosen() {
let samples = super::temp_dir::TempDir::new("sample-picker");
let mut h = harness(true);
let samples_folder = samples.join("Samples");
std::fs::create_dir(&samples_folder).unwrap();
std::fs::write(samples_folder.join("Material Ball.tcraft"), b"stand-in").unwrap();
h.state_mut().samples_folder = samples_folder;
answer(&mut h, |_| Answer::Cancelled);
invoke(&mut h, "project.sample");
assert_eq!(h.state().file_dialogs.pending(), 1);
+1
View File
@@ -77,6 +77,7 @@ mod rail;
mod reference_order;
mod rename_anchor;
mod reset_ui;
mod sample_project;
mod settings_window;
mod shelf_click;
mod shelf_drop;
+121
View File
@@ -0,0 +1,121 @@
//! File > Open Sample Project starts its file dialog in a Samples folder that holds the built-in sample.
use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use egui_kittest::Harness;
use texturecraft_engine::Session;
use texturecraft_ui_egui::file_dialogs::{Answer, Request};
use texturecraft_ui_egui::{TextureCraftApp, menus};
const SAMPLE_FILE_NAME: &str = "Material Ball.tcraft";
fn closed_app(samples_folder: &Path) -> Harness<'static, TextureCraftApp> {
let session = Session::closed().unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().samples_folder = samples_folder.to_path_buf();
harness.run_steps(4);
harness
}
/// Answers every file dialog with `pick(folder the dialog starts in)` and records that folder
fn answer_with(harness: &mut Harness<'static, TextureCraftApp>, pick: impl Fn(Option<&Path>) -> Answer + 'static) -> Rc<RefCell<Vec<Option<PathBuf>>>> {
let started_in = Rc::new(RefCell::new(Vec::new()));
let recorded = started_in.clone();
harness.state_mut().file_dialogs.set_override(Some(Box::new(move |request| {
let Request::File(dialog) = request else { return Answer::Cancelled };
recorded.borrow_mut().push(dialog.directory.clone());
pick(dialog.directory.as_deref())
})));
started_in
}
fn click_open_sample_project(harness: &mut Harness<'static, TextureCraftApp>) {
let ctx = harness.ctx.clone();
menus::invoke(harness.state_mut(), &ctx, "project.sample");
}
/// Clicks the menu entry and lets a background preparation end, so no test waits on a timer
fn open_sample_menu_entry(harness: &mut Harness<'static, TextureCraftApp>) {
click_open_sample_project(harness);
harness.state_mut().wait_for_sample_project();
harness.run_steps(3);
}
#[test]
fn the_menu_entry_writes_the_sample_and_the_dialog_starts_in_its_folder() {
let root = super::temp_dir::TempDir::new("sample-project");
let samples_folder = root.join("Samples");
let mut harness = closed_app(&samples_folder);
let started_in = answer_with(&mut harness, |folder| Answer::Paths(vec![folder.unwrap().join(SAMPLE_FILE_NAME)]));
click_open_sample_project(&mut harness);
assert!(harness.state().sample_project_pending(), "the sample is written in the background");
assert!(started_in.borrow().is_empty(), "the dialog waits for the sample");
assert!(harness.state().toasts.iter().any(|toast| !toast.error && toast.text.contains("Preparing")));
harness.state_mut().wait_for_sample_project();
harness.run_steps(3);
assert!(!harness.state().sample_project_pending());
assert!(samples_folder.join(SAMPLE_FILE_NAME).is_file(), "the sample is written on first use");
assert_eq!(*started_in.borrow(), vec![Some(samples_folder.clone())], "the dialog starts in the Samples folder");
assert!(harness.state().session.project_open, "the picked sample opens");
assert_eq!(harness.state().session.doc.project.name, "Material Ball");
let reference = texturecraft_engine::sample_session(128, 16).unwrap();
assert_eq!(harness.state().session.set_count(), reference.set_count(), "the sample keeps its texture sets");
assert!(!harness.state().session.modified, "an opened sample is a clean file");
}
#[test]
fn a_file_already_in_the_samples_folder_is_not_overwritten() {
let root = super::temp_dir::TempDir::new("sample-project-kept");
let samples_folder = root.join("Samples");
std::fs::create_dir_all(&samples_folder).unwrap();
let existing = samples_folder.join(SAMPLE_FILE_NAME);
std::fs::write(&existing, b"the user's own file").unwrap();
let mut harness = closed_app(&samples_folder);
let started_in = answer_with(&mut harness, |_| Answer::Cancelled);
click_open_sample_project(&mut harness);
assert!(!harness.state().sample_project_pending(), "nothing is written when the file is there");
harness.run_steps(3);
assert_eq!(std::fs::read(&existing).unwrap(), b"the user's own file");
assert_eq!(*started_in.borrow(), vec![Some(samples_folder)], "the dialog still starts in the Samples folder");
}
#[test]
fn a_samples_folder_that_cannot_be_made_is_reported_and_the_dialog_still_opens() {
let root = super::temp_dir::TempDir::new("sample-project-blocked");
let blocker = root.join("Samples");
std::fs::write(&blocker, b"a file where the folder should be").unwrap();
let mut harness = closed_app(&blocker);
let started_in = answer_with(&mut harness, |_| Answer::Cancelled);
open_sample_menu_entry(&mut harness);
assert!(harness.state().toasts.iter().any(|toast| toast.error), "the failure is shown");
assert_eq!(*started_in.borrow(), vec![None], "the dialog opens without a start folder");
assert!(!harness.state().session.project_open);
}
#[test]
fn a_second_click_while_the_sample_is_written_does_not_start_another_job() {
let root = super::temp_dir::TempDir::new("sample-project-twice");
let samples_folder = root.join("Samples");
let mut harness = closed_app(&samples_folder);
let started_in = answer_with(&mut harness, |_| Answer::Cancelled);
click_open_sample_project(&mut harness);
click_open_sample_project(&mut harness);
harness.state_mut().wait_for_sample_project();
harness.run_steps(3);
let preparing = harness.state().toasts.iter().filter(|toast| toast.text.contains("Preparing")).count();
assert_eq!(preparing, 1, "one job was started");
assert_eq!(started_in.borrow().len(), 1, "one dialog was asked");
}
+1 -1
View File
@@ -223,7 +223,7 @@ keeps its state in a throwaway file.
| `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) |
| `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` |
| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": "<layout>"}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) |
| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a file picker for a `.tcraft` project. The direct `project.sample` engine command still creates the generated sample for automation. |
| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a file picker for a `.tcraft` project, starting in the `Samples` folder of the data folder. The first use writes the generated sample (`Material Ball.tcraft`) there; a file that is already there is kept. The direct `project.sample` engine command still creates the generated sample for automation. |
| `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled |
| `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft_<version>_<date>_<os>_<gpuMode>.txt` name, a download on the web) |
| `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before |
+2 -2
View File
@@ -114,8 +114,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
## Files and texture sets
- **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**,
OBJ, PLY and STL, or a built-in mesh (the `project.new` command; *File › Open sample project...* opens the
material ball); UVs are generated when a mesh has none. A `.gltf`'s buffers
OBJ, PLY and STL, or a built-in mesh (the `project.new` command; *File › Open sample project...* asks for a
`.tcraft` file, starting in the `Samples` folder of the data folder, which holds the material ball); UVs are generated when a mesh has none. A `.gltf`'s buffers
and images and a loose USD layer's textures are read from its folder and kept in the project.
Reimport a changed mesh and your painted strokes stay on the surface. The
`file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers.