Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

updated preistalled brushes

sorae13228f3199c
diff --git a/src/components/BrushPreview.tsx b/src/components/BrushPreview.tsx
index f368d2e..3e24327 100644
--- a/src/components/BrushPreview.tsx
+++ b/src/components/BrushPreview.tsx
@@ -2,6 +2,7 @@ import React, { useRef, useEffect, useState } from 'react';
import { BrushSettings, BrushPresetId } from '../types/editor';
import { renderBrushStrokePreview, BrushPreviewOptions } from '../utils/brushPreview';
import { getPreloadedTipImage, preloadTipImage } from '../utils/brushStorage';
+import { DEFAULT_BRUSH_PRESET_ID } from '../utils/brushPresetManager';
interface BrushPreviewProps {
preset?: BrushPresetId;
@@ -18,7 +19,7 @@ interface BrushPreviewProps {
}
export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
- preset = 'pencil-2b',
+ preset = DEFAULT_BRUSH_PRESET_ID,
settings,
tool = 'brush',
strokeColor = '#ffffff',
@@ -102,6 +103,11 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
flow: settings?.flow,
opacity: settings?.opacity,
grain: settings?.grain,
+ paperTextureMode: settings?.paperTextureMode,
+ paperTextureScale: settings?.paperTextureScale,
+ paperTextureContrast: settings?.paperTextureContrast,
+ paperTextureBrightness: settings?.paperTextureBrightness,
+ paperTextureInverted: settings?.paperTextureInverted,
hardness: settings?.hardness,
spacing: settings?.spacing,
minSizeFactor: settings?.minSizeFactor,
@@ -109,12 +115,14 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
antiAlias: settings?.antiAlias,
pressureCurve: settings?.pressureCurve,
spray: settings?.spray,
+ dynamics: settings?.dynamics,
usePressure: settings?.usePressure,
color: strokeColor,
backgroundColor,
tool,
customTipImage: customTipImage || internalTipImage || settings?.customTipImage,
customTipAngle: customTipAngle !== undefined ? customTipAngle : settings?.customTipAngle,
+ customTipAngleDynamics: settings?.customTipAngleDynamics,
colorMixing: settings?.colorMixing,
amountOfPaint: settings?.amountOfPaint,
densityOfPaint: settings?.densityOfPaint,
diff --git a/src/components/BrushSizePalette.tsx b/src/components/BrushSizePalette.tsx
index ec2a1c8..b4cffe5 100644
--- a/src/components/BrushSizePalette.tsx
+++ b/src/components/BrushSizePalette.tsx
@@ -56,7 +56,12 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = React.memo(({
if (tool === 'eraser') {
return <Eraser className="w-3.5 h-3.5 text-rose-400 shrink-0" />;
}
- if (presetId?.startsWith('pencil')) {
+ if (
+ presetId?.startsWith('pencil') ||
+ presetId === 'mechanical-pencil' ||
+ presetId === 'charcoal-pencil' ||
+ presetId === 'standard-chalk'
+ ) {
return <Pencil className="w-3.5 h-3.5 text-amber-400 shrink-0" />;
}
if (presetId === 'square-digital') {
diff --git a/src/components/MenuBar.tsx b/src/components/MenuBar.tsx
index 9465517..fb1c3ad 100644
--- a/src/components/MenuBar.tsx
+++ b/src/components/MenuBar.tsx
@@ -104,6 +104,12 @@ export const MenuBar: React.FC<MenuBarProps> = React.memo(({ sections = DEFAULT_
activeSection && activeSubmenuId
? activeSection.items.find((it) => it.id === activeSubmenuId && !it.disabled && it.submenu?.length) ?? null
: null;
+ const activeSectionHasCheckables = Boolean(
+ activeSection?.items.some((it) => it.checked !== undefined)
+ );
+ const activeSubmenuHasCheckables = Boolean(
+ activeSubmenuParent?.submenu?.some((it) => it.checked !== undefined)
+ );
useEffect(() => {
return () => clearSubmenuTimer();
@@ -400,15 +406,13 @@ export const MenuBar: React.FC<MenuBarProps> = React.memo(({ sections = DEFAULT_
}`}
>
<span className="flex items-center gap-2 min-w-0">
- <span className="w-3.5 h-3.5 flex items-center justify-center shrink-0">
- {item.checked ? (
- <Check className="w-3 h-3 text-[var(--accent)]" />
- ) : item.icon ? (
- <span className="w-3.5 h-3.5 flex items-center justify-center opacity-75">
- {item.icon}
- </span>
- ) : null}
- </span>
+ {activeSectionHasCheckables && (
+ <span className="w-3.5 h-3.5 flex items-center justify-center shrink-0">
+ {item.checked ? (
+ <Check className="w-3 h-3 text-[var(--accent)]" />
+ ) : null}
+ </span>
+ )}
<span className="truncate">{item.label}</span>
</span>
{hasSubmenu ? (
@@ -463,15 +467,13 @@ export const MenuBar: React.FC<MenuBarProps> = React.memo(({ sections = DEFAULT_
}`}
>
<span className="flex items-center gap-2 min-w-0">
- <span className="w-3.5 h-3.5 flex items-center justify-center shrink-0">
- {subItem.checked ? (
- <Check className="w-3 h-3 text-[var(--accent)]" />
- ) : subItem.icon ? (
- <span className="w-3.5 h-3.5 flex items-center justify-center opacity-75">
- {subItem.icon}
- </span>
- ) : null}
- </span>
+ {activeSubmenuHasCheckables && (
+ <span className="w-3.5 h-3.5 flex items-center justify-center shrink-0">
+ {subItem.checked ? (
+ <Check className="w-3 h-3 text-[var(--accent)]" />
+ ) : null}
+ </span>
+ )}
<span className="truncate">{subItem.label}</span>
</span>
{subItem.shortcut && (
diff --git a/src/components/SubToolList.tsx b/src/components/SubToolList.tsx
index 0a94bab..eea6d01 100644
--- a/src/components/SubToolList.tsx
+++ b/src/components/SubToolList.tsx
@@ -1,24 +1,31 @@
import React, { useState, useRef } from 'react';
import {
Paintbrush,
+ PenTool,
Pencil,
Plus,
Trash2,
Loader2,
FolderDown,
- Palette,
- Square,
Sparkles,
+ ChevronDown,
+ ChevronRight,
} from 'lucide-react';
-import { BrushPresetId, CspBrush } from '../types/editor';
+import { BrushCategory, BrushPresetId, CspBrush } from '../types/editor';
import { parseSutFile } from '../utils/sutParser';
import {
saveCustomBrush,
deleteCustomBrush,
prepareBrushSettingsForCsp,
} from '../utils/brushStorage';
-import { BUILTIN_BRUSHES, BrushCategory } from '../utils/presetBrushes';
import {
+ BUILTIN_BRUSHES,
+ BUILTIN_BRUSH_SECTIONS,
+ BuiltinBrushDefinition,
+} from '../utils/presetBrushes';
+import {
+ DEFAULT_BRUSH_PRESET_ID,
+ NEUTRAL_BRUSH_DEFAULTS,
getEffectiveBrushSettings,
getSavedBrushSettings,
saveActivePresetId,
@@ -30,6 +37,12 @@ export interface SubToolListProps {
setCustomBrushes: React.Dispatch<React.SetStateAction<CspBrush[]>>;
}
+function renderBuiltinIcon(icon: BuiltinBrushDefinition['icon']) {
+ if (icon === 'pen') return <PenTool className="w-3 h-3 shrink-0 opacity-80" />;
+ if (icon === 'pencil') return <Pencil className="w-3 h-3 shrink-0 opacity-80" />;
+ return <Paintbrush className="w-3 h-3 shrink-0 opacity-80" />;
+}
+
export const SubToolList: React.FC<SubToolListProps> = React.memo(
({ customBrushes, setCustomBrushes }) => {
const currentTool = useToolStore((s) => s.tool);
@@ -37,26 +50,19 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(
const [isImportingSut, setIsImportingSut] = useState(false);
const [isDraggingFileOver, setIsDraggingFileOver] = useState(false);
- const [selectedCategory, setSelectedCategory] = useState<'all' | BrushCategory | 'csp'>('all');
+ const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>({});
const sutInputRef = useRef<HTMLInputElement>(null);
+ const toggleSection = (key: string) => {
+ setCollapsedSections((prev) => ({ ...prev, [key]: !prev[key] }));
+ };
+
const handleSelectBrushPreset = (presetId: BrushPresetId) => {
toolStoreActions.selectTool('brush');
saveActivePresetId(presetId);
const effective = getEffectiveBrushSettings(presetId, customBrushes);
toolStoreActions.updateBrushSettings({
- customTipDataUrl: undefined,
- customTipImage: undefined,
- customTipAngle: 0,
- customTipAngleDynamics: 'none',
- flipH: 'none',
- flipV: 'none',
- isRibbon: false,
- colorMixing: false,
- wetEdge: 0,
- grain: 0,
- spray: undefined,
- taper: undefined,
+ ...NEUTRAL_BRUSH_DEFAULTS,
...effective,
preset: presetId,
});
@@ -68,6 +74,7 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(
const prepared = await prepareBrushSettingsForCsp(brush);
const saved = getSavedBrushSettings(brush.id);
toolStoreActions.updateBrushSettings({
+ ...NEUTRAL_BRUSH_DEFAULTS,
...prepared,
...saved,
preset: brush.id,
@@ -109,52 +116,25 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(
await deleteCustomBrush(brushId);
setCustomBrushes((prev) => prev.filter((b) => b.id !== brushId));
if (activePreset === brushId) {
- handleSelectBrushPreset('pencil-2b');
+ handleSelectBrushPreset(DEFAULT_BRUSH_PRESET_ID);
}
}
};
- const visibleBuiltinBrushes = BUILTIN_BRUSHES.filter((b) => {
- if (selectedCategory === 'all') return true;
- if (selectedCategory === 'csp') return false;
- return b.category === selectedCategory;
- });
-
- const showCspBrushes = selectedCategory === 'all' || selectedCategory === 'csp';
+ const brushesByCategory = (cat: BrushCategory) =>
+ BUILTIN_BRUSHES.filter((b) => b.category === cat);
return (
<>
- {/* Category Filter Strip + Import .sut */}
- <div className="px-1.5 py-1.5 flex items-center gap-1 shrink-0">
- <select
- value={selectedCategory}
- onChange={(e) =>
- setSelectedCategory(e.target.value as 'all' | BrushCategory | 'csp')
- }
- aria-label="Brush Category"
- className="flex-1 min-w-0 h-5 bg-[#161616] text-[#e5e5e5] text-[11px] px-1.5 rounded cursor-pointer"
- >
- <option value="all" className="bg-[#202020]">
- All Brushes
- </option>
- <option value="pencil-line" className="bg-[#202020]">
- Pencil &amp; Ink
- </option>
- <option value="color-paint" className="bg-[#202020]">
- Color &amp; Paint
- </option>
- <option value="csp" className="bg-[#202020]">
- CSP Imported
- </option>
- </select>
-
+ <div className="px-1.5 py-1 flex items-center justify-end shrink-0">
<button
type="button"
onClick={() => sutInputRef.current?.click()}
title="Import CSP Brush (.sut)"
- className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"
+ className="h-5 px-1.5 rounded flex items-center gap-1 text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"
>
<Plus className="w-3 h-3" />
+ <span>Import .sut</span>
</button>
</div>
@@ -170,7 +150,7 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(
}}
/>
- {/* Compact High-Density Sub-Tool List */}
+ {/* Compact High-Density Sectioned Sub-Tool List */}
<div
onDragOver={(e) => {
if (e.dataTransfer.types.includes('Files')) {
@@ -187,7 +167,7 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(
);
for (const f of files) handleImportSut(f);
}}
- className="flex-1 overflow-y-auto px-1.5 py-0.5 space-y-0.5 relative min-h-[84px]"
+ className="flex-1 overflow-y-auto px-1.5 py-0.5 space-y-1 relative min-h-[84px]"
>
{isDraggingFileOver && (
<div className="absolute inset-1 bg-[#161616]/95 rounded flex flex-col items-center justify-center p-2 text-center z-30 pointer-events-none">
@@ -203,85 +183,108 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(
</div>
)}
- {visibleBuiltinBrushes.map((item) => {
- const isSelected =
- currentTool === 'brush' &&
- (activePreset === item.id || (!activePreset && item.id === 'pencil-2b'));
+ {BUILTIN_BRUSH_SECTIONS.map((section) => {
+ const items = brushesByCategory(section.id);
+ if (items.length === 0) return null;
+ const isCollapsed = Boolean(collapsedSections[section.id]);
return (
- <button
- key={item.id}
- type="button"
- onClick={() => handleSelectBrushPreset(item.id)}
- title={`${item.name} - ${item.desc}`}
- className={`w-full flex items-center gap-1.5 px-2 py-1 rounded text-left transition-colors cursor-pointer ${
- isSelected
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- {item.icon === 'pencil' ? (
- <Pencil className="w-3 h-3 shrink-0 opacity-80" />
- ) : item.icon === 'palette' ? (
- <Palette className="w-3 h-3 shrink-0 opacity-80" />
- ) : item.icon === 'square' ? (
- <Square className="w-3 h-3 shrink-0 opacity-80" />
- ) : (
- <Paintbrush className="w-3 h-3 shrink-0 opacity-80" />
- )}
- <span className="text-[11px] truncate leading-tight flex-1">{item.name}</span>
- </button>
+ <div key={section.id} className="space-y-0.5">
+ <button
+ type="button"
+ onClick={() => toggleSection(section.id)}
+ className="w-full flex items-center gap-1 px-1 py-0.5 text-[9px] uppercase tracking-wider text-[#6e6e6e] hover:text-[#b5b5b5] select-none cursor-pointer"
+ >
+ {isCollapsed ? (
+ <ChevronRight className="w-2.5 h-2.5 shrink-0" />
+ ) : (
+ <ChevronDown className="w-2.5 h-2.5 shrink-0" />
+ )}
+ <span>{section.label}</span>
+ </button>
+
+ {!isCollapsed &&
+ items.map((item) => {
+ const isSelected =
+ currentTool === 'brush' &&
+ (activePreset === item.id ||
+ (!activePreset && item.id === DEFAULT_BRUSH_PRESET_ID));
+
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => handleSelectBrushPreset(item.id)}
+ title={`${item.name} - ${item.desc}`}
+ className={`w-full flex items-center gap-1.5 px-2 py-1 rounded text-left transition-colors cursor-pointer ${
+ isSelected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {renderBuiltinIcon(item.icon)}
+ <span className="text-[11px] truncate leading-tight flex-1">
+ {item.name}
+ </span>
+ </button>
+ );
+ })}
+ </div>
);
})}
- {showCspBrushes &&
- customBrushes.map((brush) => {
- const isSelected = currentTool === 'brush' && activePreset === brush.id;
- return (
- <div
- key={brush.id}
- onClick={() => handleSelectCustomBrush(brush)}
- title={brush.name}
- className={`group flex items-center justify-between gap-1 px-2 py-1 rounded cursor-pointer transition-colors ${
- isSelected
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- <div className="flex items-center gap-1.5 min-w-0">
- {brush.tipDataUrl ? (
- <img
- src={brush.tipDataUrl}
- alt=""
- className="w-3 h-3 object-contain shrink-0 brightness-125"
- />
- ) : (
- <Sparkles className="w-3 h-3 shrink-0 opacity-80" />
- )}
- <span className="text-[11px] truncate leading-tight">{brush.name}</span>
- </div>
- <button
- type="button"
- onClick={(e) => handleDeleteCustomBrush(e, brush.id)}
- title="Delete brush"
- className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-red-400 shrink-0 cursor-pointer"
- >
- <Trash2 className="w-2.5 h-2.5" />
- </button>
- </div>
- );
- })}
-
- {selectedCategory === 'csp' && customBrushes.length === 0 && (
- <div className="py-4 px-2 text-center space-y-2">
- <p className="text-[10px] text-[#8a8a8a]">Drop .sut brush file</p>
+ {customBrushes.length > 0 && (
+ <div className="space-y-0.5 pt-0.5">
<button
type="button"
- onClick={() => sutInputRef.current?.click()}
- className="px-2 py-1 rounded bg-[#2c2c2c] text-[10px] text-[#e5e5e5] cursor-pointer"
+ onClick={() => toggleSection('custom')}
+ className="w-full flex items-center gap-1 px-1 py-0.5 text-[9px] uppercase tracking-wider text-[#6e6e6e] hover:text-[#b5b5b5] select-none cursor-pointer"
>
- Import .sut
+ {collapsedSections.custom ? (
+ <ChevronRight className="w-2.5 h-2.5 shrink-0" />
+ ) : (
+ <ChevronDown className="w-2.5 h-2.5 shrink-0" />
+ )}
+ <span>Imported</span>
</button>
+
+ {!collapsedSections.custom &&
+ customBrushes.map((brush) => {
+ const isSelected = currentTool === 'brush' && activePreset === brush.id;
+ return (
+ <div
+ key={brush.id}
+ onClick={() => handleSelectCustomBrush(brush)}
+ title={brush.name}
+ className={`group flex items-center justify-between gap-1 px-2 py-1 rounded cursor-pointer transition-colors ${
+ isSelected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ <div className="flex items-center gap-1.5 min-w-0">
+ {brush.tipDataUrl ? (
+ <img
+ src={brush.tipDataUrl}
+ alt=""
+ className="w-3 h-3 object-contain shrink-0 brightness-125"
+ />
+ ) : (
+ <Sparkles className="w-3 h-3 shrink-0 opacity-80" />
+ )}
+ <span className="text-[11px] truncate leading-tight">{brush.name}</span>
+ </div>
+ <button
+ type="button"
+ onClick={(e) => handleDeleteCustomBrush(e, brush.id)}
+ title="Delete brush"
+ className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-red-400 shrink-0 cursor-pointer"
+ >
+ <Trash2 className="w-2.5 h-2.5" />
+ </button>
+ </div>
+ );
+ })}
</div>
)}
</div>
diff --git a/src/components/ToolPropertyInspector.tsx b/src/components/ToolPropertyInspector.tsx
index 2afa92f..b0897c4 100644
--- a/src/components/ToolPropertyInspector.tsx
+++ b/src/components/ToolPropertyInspector.tsx
@@ -25,7 +25,11 @@ import {
import { saveCustomBrushDebounced } from '../utils/brushStorage';
import { resolveBrushTipImage } from '../utils/brushOutline';
import { BUILTIN_BRUSHES } from '../utils/presetBrushes';
-import { resetBrushSettingsToDefault, ERASER_PRESET_ID } from '../utils/brushPresetManager';
+import {
+ resetBrushSettingsToDefault,
+ ERASER_PRESET_ID,
+ DEFAULT_BRUSH_PRESET_ID,
+} from '../utils/brushPresetManager';
import { renderBrushStrokePreview } from '../utils/brushPreview';
import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/CspBrushEngine';
import { useToolStore, toolStoreActions, useUiStore, uiStoreActions } from '../stores';
@@ -144,8 +148,14 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
if (!canvas) return;
const cssWidth = Math.max(96, width - 16);
const cssHeight = 32;
- const rafId = requestAnimationFrame(() => {
+ let loadListenerCleanup: (() => void) | null = null;
+ const drawPreview = () => {
const resolvedTip = resolveBrushTipImage(brushSettings);
+ if (resolvedTip && !resolvedTip.complete) {
+ const onLoad = () => drawPreview();
+ resolvedTip.addEventListener('load', onLoad, { once: true });
+ loadListenerCleanup = () => resolvedTip.removeEventListener('load', onLoad);
+ }
renderBrushStrokePreview(
canvas,
cssWidth,
@@ -156,6 +166,11 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
flow: brushSettings.flow,
opacity: brushSettings.opacity,
grain: brushSettings.grain,
+ paperTextureMode: brushSettings.paperTextureMode,
+ paperTextureScale: brushSettings.paperTextureScale,
+ paperTextureContrast: brushSettings.paperTextureContrast,
+ paperTextureBrightness: brushSettings.paperTextureBrightness,
+ paperTextureInverted: brushSettings.paperTextureInverted,
hardness: brushSettings.hardness,
spacing: brushSettings.spacing,
minSizeFactor: brushSettings.minSizeFactor,
@@ -165,6 +180,7 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
tool: currentTool === 'eraser' ? 'eraser' : 'brush',
customTipImage: resolvedTip,
customTipAngle: brushSettings.customTipAngle,
+ customTipAngleDynamics: brushSettings.customTipAngleDynamics,
thickness: brushSettings.thickness,
thicknessVertical: brushSettings.thicknessVertical,
flipH: brushSettings.flipH,
@@ -174,6 +190,7 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
antiAlias: brushSettings.antiAlias,
pressureCurve: brushSettings.pressureCurve,
spray: brushSettings.spray,
+ dynamics: brushSettings.dynamics,
colorMixing: brushSettings.colorMixing,
amountOfPaint: brushSettings.amountOfPaint,
densityOfPaint: brushSettings.densityOfPaint,
@@ -182,11 +199,15 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
},
true
);
- });
- return () => cancelAnimationFrame(rafId);
+ };
+ const rafId = requestAnimationFrame(drawPreview);
+ return () => {
+ cancelAnimationFrame(rafId);
+ loadListenerCleanup?.();
+ };
}, [isHidden, isBrushOrEraser, width, currentTool, brushSettings]);
- const activePreset: BrushPresetId = brushSettings.preset || 'pencil-2b';
+ const activePreset: BrushPresetId = brushSettings.preset || DEFAULT_BRUSH_PRESET_ID;
const activeBuiltinBrush = BUILTIN_BRUSHES.find((b) => b.id === activePreset);
const isCustomBrushActive =
currentTool === 'brush' &&
@@ -1289,7 +1310,7 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
const def = resetBrushSettingsToDefault(
currentTool === 'eraser'
? ERASER_PRESET_ID
- : brushSettings.preset || 'pencil-2b',
+ : brushSettings.preset || DEFAULT_BRUSH_PRESET_ID,
customBrushes
);
handleUpdateBrushSettings(def);
diff --git a/src/engine/CspBrushEngine.ts b/src/engine/CspBrushEngine.ts
index f740383..f3e1678 100644
--- a/src/engine/CspBrushEngine.ts
+++ b/src/engine/CspBrushEngine.ts
@@ -375,9 +375,12 @@ export function applyCspPaperTextureAlpha(
}
g = Math.max(0, Math.min(1, g));
- //Stylus pressure pushes pigment deeper into paper valleys
- const penetration = Math.max(0, Math.min(0.85, pressure * 0.65));
- const effDensity = textureDensity * (1.0 - penetration * 0.6);
+ // Nonlinear valley-clogging physics: light-to-medium pressure catches crisp paper peaks;
+ // heavy pressure (> 0.55) compresses soft graphite/charcoal into valleys to clog the grain.
+ const p = Math.max(0, Math.min(1, pressure));
+ const heavyExcess = Math.max(0, (p - 0.52) / 0.48);
+ const penetration = Math.min(0.92, p * 0.28 + heavyExcess * heavyExcess * 0.64);
+ const effDensity = textureDensity * (1.0 - penetration * 0.85);
switch (mode) {
case 'multiply': {
@@ -389,8 +392,17 @@ export function applyCspPaperTextureAlpha(
return Math.max(0, Math.min(1, tipAlpha - sub * (1.0 - penetration * 0.5)));
}
case 'compare': {
- const thresh = (1.0 - g) * effDensity;
- return tipAlpha > thresh ? Math.min(1, (tipAlpha - thresh) / Math.max(0.08, 1.0 - thresh)) : 0;
+ // Physical dry-media height-field tooth:
+ // Pigment deposits only where paper fiber ridges reach the tip contact plane;
+ // recessed valleys cut cleanly to 0.0 (preventing multi-dab overlap from filling valleys)
+ // until heavy pressure compresses soft lead into the troughs.
+ const contactHeight = g * (0.22 + 0.78 * tipAlpha);
+ const cutoff = effDensity * 0.68;
+ const edgeLow = cutoff - 0.05;
+ const edgeHigh = cutoff + 0.16;
+ const t = Math.max(0, Math.min(1, (contactHeight - edgeLow) / Math.max(0.01, edgeHigh - edgeLow)));
+ const tooth = t * t * (3.0 - 2.0 * t);
+ return Math.max(0, Math.min(1, tipAlpha * tooth));
}
case 'overlay': {
const ov = tipAlpha < 0.5
diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.ts
index cecd306..135cb31 100644
--- a/src/hooks/drawing/useBrushStrokeSession.ts
+++ b/src/hooks/drawing/useBrushStrokeSession.ts
@@ -520,6 +520,7 @@ export function useBrushStrokeSession({
usePressure: bs.usePressure,
useVelocity: bs.useVelocity,
useTilt: Boolean(bs.useTilt),
+ tiltScale: bs.tiltScale,
sizeSensor: bs.sizeSensor,
opacitySensor: resolveEffectiveOpacitySensor(bs, isMonochrome, isEraser),
densitySensor: bs.densitySensor,
@@ -587,6 +588,7 @@ export function useBrushStrokeSession({
dualTipImage: bs.dualTipImage,
dualBrushCompositeMode: bs.dualBrushCompositeMode,
useTilt: Boolean(bs.useTilt),
+ tiltScale: bs.tiltScale,
thicknessVertical: bs.thicknessVertical,
flipH: bs.flipH,
flipV: bs.flipV,
@@ -789,7 +791,7 @@ export function useBrushStrokeSession({
(predEvents: PointerEvent[], vRect: DOMRect) => {
clearPredictedCanvas();
const bs = getBrushSettings();
- if (getTool() === 'eraser' || bs.isTransparentInk) return;
+ if (getTool() === 'eraser' || bs.isTransparentInk || bs.colorMixing) return;
const pipeline = strokePipelineRef.current;
if (pipeline.getKnotCount() < 2) return;
const pCanvas = getPredictedCanvas();
@@ -868,9 +870,12 @@ export function useBrushStrokeSession({
minSizeFactor: bs.minSizeFactor,
opacity: 1.0,
flow: strokeFlow,
+ adjustDensityByGap: bs.adjustDensityByGap,
spacing: strokeSpacing,
thickness: bs.thickness,
thicknessVertical: bs.thicknessVertical,
+ flipH: bs.flipH,
+ flipV: bs.flipV,
angle: bs.customTipAngle,
angleDynamics: bs.customTipAngleDynamics,
rotationRandomScale: bs.customTipRotationRandomScale,
@@ -878,12 +883,24 @@ export function useBrushStrokeSession({
antiAlias: predAA,
pressureCurve: bs.pressureCurve,
usePressure: bs.usePressure,
+ useTilt: Boolean(bs.useTilt),
+ tiltScale: bs.tiltScale,
+ sizeSensor: bs.sizeSensor,
+ opacitySensor: resolveEffectiveOpacitySensor(bs, isMonochrome, false),
+ densitySensor: bs.densitySensor,
subTips: bs.subTips,
subTipOrder: bs.subTipOrder,
subTipImages: bs.subTipImages,
spray: bs.spray,
wetEdge: 0,
grain: bs.grain ?? bs.textureDensity,
+ paperTextureMode: bs.paperTextureMode,
+ paperTextureBrightness: bs.paperTextureBrightness,
+ paperTextureContrast: bs.paperTextureContrast,
+ paperTextureInverted: bs.paperTextureInverted,
+ paperTextureImage: bs.paperTextureImage,
+ paperTextureScale: bs.paperTextureScale,
+ paperTextureRotate: bs.paperTextureRotate,
dualBrush: bs.dualBrush,
dualTipImage: bs.dualTipImage,
dualBrushCompositeMode: bs.dualBrushCompositeMode,
@@ -895,12 +912,25 @@ export function useBrushStrokeSession({
const predRadialOpts: RadialMixingOptions = {
useGpu: bs.useGpu !== false,
antiAlias: predAA,
+ useTilt: Boolean(bs.useTilt),
+ tiltScale: bs.tiltScale,
+ adjustDensityByGap: bs.adjustDensityByGap,
dynamics: bs.dynamics,
secondaryColor: bs.secondaryColor,
dualBrush: bs.dualBrush,
dualTipImage: bs.dualTipImage,
dualBrushCompositeMode: bs.dualBrushCompositeMode,
grain: bs.grain ?? bs.textureDensity,
+ paperTextureMode: bs.paperTextureMode,
+ paperTextureBrightness: bs.paperTextureBrightness,
+ paperTextureContrast: bs.paperTextureContrast,
+ paperTextureInverted: bs.paperTextureInverted,
+ paperTextureImage: bs.paperTextureImage,
+ paperTextureScale: bs.paperTextureScale,
+ paperTextureRotate: bs.paperTextureRotate,
+ sizeSensor: bs.sizeSensor,
+ opacitySensor: resolveEffectiveOpacitySensor(bs, isMonochrome, false),
+ densitySensor: bs.densitySensor,
};
const predGpuDabs = frameGpuDabsRef.current;
@@ -2563,6 +2593,10 @@ export function useBrushStrokeSession({
: bs;
const needsIsolatedBake = (bakeBs.opacity ?? 1.0) < 0.999 || hasWetEdge;
+ const bakeSampler =
+ bakeBs.colorMixing && !isEraser
+ ? new LayerPixelSampler(canvas || dims, currentLayerId, grid)
+ : undefined;
if (!needsIsolatedBake) {
renderCompleteStroke(
@@ -2573,7 +2607,8 @@ export function useBrushStrokeSession({
effectiveMode,
isBgEraser,
canvas || undefined,
- Boolean(activeLayer?.alphaLocked)
+ Boolean(activeLayer?.alphaLocked),
+ bakeSampler
);
} else {
rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bakeBs.opacity ?? 1.0));
@@ -2607,7 +2642,8 @@ export function useBrushStrokeSession({
effectiveMode,
isBgEraser,
canvas || undefined,
- false
+ false,
+ bakeSampler
);
bCtx.restore();
diff --git a/src/hooks/useAppMenuSections.tsx b/src/hooks/useAppMenuSections.tsx
index 457e8e1..71c5400 100644
--- a/src/hooks/useAppMenuSections.tsx
+++ b/src/hooks/useAppMenuSections.tsx
@@ -1,47 +1,4 @@
import { useMemo } from 'react';
-import {
- FilePlus,
- FolderOpen,
- Save,
- Download,
- Trash2,
- Film,
- Layers,
- Undo2,
- Redo2,
- ZoomIn,
- ZoomOut,
- RotateCcw,
- FlipHorizontal,
- FlipVertical,
- Plus,
- Info as InfoIcon,
- Copy,
- ClipboardPaste,
- ImagePlus,
- Scaling,
- Settings,
- FolderDown,
- PaintBucket,
- SlidersHorizontal,
- Compass,
- Eye,
- EyeOff,
- Magnet,
- Lock,
- Unlock,
- Box,
- Maximize2,
- Minimize2,
- Feather,
- BoxSelect,
- X,
- Smartphone,
- Archive,
- Sparkles,
- MessageSquare,
- Spline,
-} from 'lucide-react';
import {
AnimationTimeline,
CanvasDimensions,
@@ -237,20 +194,17 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'file-new',
label: 'New...',
shortcut: 'Ctrl+N',
- icon: <FilePlus className="w-3.5 h-3.5 text-sky-400" />,
onClick: () => uiStoreActions.setNewCanvasModalOpen(true),
},
{
id: 'file-open',
label: 'Open...',
shortcut: 'Ctrl+O',
- icon: <FolderOpen className="w-3.5 h-3.5 text-amber-400" />,
onClick: handleTriggerOpenFile,
},
{
id: 'file-import-sut',
label: 'Import CSP Brush (.sut)...',
- icon: <FolderDown className="w-3.5 h-3.5 text-cyan-400" />,
onClick: () => {
const input = document.createElement('input');
input.type = 'file';
@@ -290,7 +244,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'file-import-3d',
label: 'Import 3D Model (.glb, .obj)...',
- icon: <Box className="w-3.5 h-3.5 text-purple-400" />,
disabled: !hasOpenDocument,
onClick: handleTriggerImport3DFile,
},
@@ -299,7 +252,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'file-save',
label: 'Save',
shortcut: 'Ctrl+S',
- icon: <Save className="w-3.5 h-3.5 text-blue-400" />,
disabled: !hasOpenDocument,
onClick: handleSave,
},
@@ -307,28 +259,24 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'file-save-as',
label: 'Save As...',
shortcut: 'Ctrl+Shift+S',
- icon: <Save className="w-3.5 h-3.5 text-indigo-400" />,
disabled: !hasOpenDocument,
onClick: handleSaveAs,
},
{
id: 'file-export-image',
label: 'Export Image...',
- icon: <Download className="w-3.5 h-3.5 text-emerald-400" />,
disabled: !hasOpenDocument,
onClick: handleExportImage,
},
{
id: 'file-export-webtoon',
label: 'Export Webtoon Chapter Slices (.zip)...',
- icon: <Archive className="w-3.5 h-3.5 text-cyan-400" />,
disabled: !hasOpenDocument,
onClick: () => uiStoreActions.setWebtoonExportModalOpen(true),
},
{
id: 'file-timelapse-submenu',
label: 'Time-lapse',
- icon: <Film className="w-3.5 h-3.5 text-rose-400" />,
disabled: !hasOpenDocument,
submenu: [
{
@@ -348,7 +296,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'file-clear',
label: 'Clear Canvas',
- icon: <Trash2 className="w-3.5 h-3.5 text-rose-400" />,
danger: true,
disabled: !hasOpenDocument,
onClick: clearCanvas,
@@ -363,7 +310,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'edit-undo',
label: 'Undo',
shortcut: 'Ctrl+Z',
- icon: <Undo2 className="w-3.5 h-3.5" />,
disabled: !hasOpenDocument || !canUndo,
onClick: handleUndo,
},
@@ -371,7 +317,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'edit-redo',
label: 'Redo',
shortcut: 'Ctrl+Y',
- icon: <Redo2 className="w-3.5 h-3.5" />,
disabled: !hasOpenDocument || !canRedo,
onClick: redo,
},
@@ -380,7 +325,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'edit-copy',
label: 'Copy',
shortcut: 'Ctrl+C',
- icon: <Copy className="w-3.5 h-3.5 text-sky-400" />,
disabled: !hasOpenDocument || !activeLayer,
onClick: handleCopySelectedLayer,
},
@@ -388,21 +332,18 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'edit-paste',
label: 'Paste',
shortcut: 'Ctrl+V',
- icon: <ClipboardPaste className="w-3.5 h-3.5 text-amber-400" />,
disabled: !hasOpenDocument,
onClick: handlePasteSelectedLayer,
},
{
id: 'edit-paste-file',
label: 'Paste from file...',
- icon: <ImagePlus className="w-3.5 h-3.5 text-emerald-400" />,
disabled: !hasOpenDocument,
onClick: handleTriggerPasteFromFile,
},
{
id: 'edit-import-3d',
label: 'Import 3D File (.glb, .obj)...',
- icon: <Box className="w-3.5 h-3.5 text-purple-400" />,
disabled: !hasOpenDocument,
onClick: handleTriggerImport3DFile,
},
@@ -410,7 +351,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'edit-delete',
label: 'Delete',
shortcut: 'Del',
- icon: <Trash2 className="w-3.5 h-3.5 text-rose-400" />,
danger: true,
disabled: !hasOpenDocument || layers.filter((l) => l.type === 'raster').length <= 1,
onClick: handleDeleteSelectedLayer,
@@ -425,7 +365,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'edit-transform',
label: 'Free Transform',
shortcut: 'Ctrl+T',
- icon: <Scaling className="w-3.5 h-3.5 text-cyan-400" />,
disabled: !hasOpenDocument,
onClick: handleStartTransform,
},
@@ -439,14 +378,12 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'edit-fill-sel',
label: 'Fill Selection',
- icon: <PaintBucket className="w-3.5 h-3.5 text-amber-400" />,
disabled: !hasOpenDocument || !selection,
onClick: handleFillSelectionColor,
},
{
id: 'edit-tonal-correction',
label: 'Tonal Correction',
- icon: <SlidersHorizontal className="w-3.5 h-3.5 text-violet-400" />,
disabled:
!hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster',
submenu: [
@@ -518,7 +455,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'edit-resize-canvas',
label: 'Resize Canvas...',
- icon: <Scaling className="w-3.5 h-3.5 text-indigo-400" />,
disabled: !hasOpenDocument,
onClick: () => uiStoreActions.setResizeCanvasModalOpen(true),
},
@@ -527,7 +463,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'edit-settings',
label: 'Settings...',
shortcut: 'Ctrl+,',
- icon: <Settings className="w-3.5 h-3.5 text-slate-300" />,
onClick: () => uiStoreActions.setSettingsModalOpen(true),
},
],
@@ -540,7 +475,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'select-all',
label: 'Select All',
shortcut: 'Ctrl+A',
- icon: <BoxSelect className="w-3.5 h-3.5 text-sky-400" />,
disabled: !hasOpenDocument,
onClick: handleSelectAll,
},
@@ -548,7 +482,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'select-deselect',
label: 'Deselect',
shortcut: 'Ctrl+D',
- icon: <X className="w-3.5 h-3.5 text-rose-400" />,
disabled: !hasOpenDocument || !selection,
onClick: handleDeselect,
},
@@ -556,7 +489,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'select-invert',
label: 'Invert Selection',
shortcut: 'Ctrl+Shift+I',
- icon: <RotateCcw className="w-3.5 h-3.5 text-amber-400" />,
disabled: !hasOpenDocument,
onClick: handleInvertSelection,
},
@@ -564,21 +496,18 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'select-expand',
label: 'Expand (+5px)...',
- icon: <Maximize2 className="w-3.5 h-3.5 text-indigo-400" />,
disabled: !hasOpenDocument || !selection,
onClick: () => handleExpandSelection(5),
},
{
id: 'select-contract',
label: 'Contract (-5px)...',
- icon: <Minimize2 className="w-3.5 h-3.5 text-emerald-400" />,
disabled: !hasOpenDocument || !selection,
onClick: () => handleContractSelection(5),
},
{
id: 'select-feather',
label: 'Feather (5px)...',
- icon: <Feather className="w-3.5 h-3.5 text-purple-400" />,
disabled: !hasOpenDocument || !selection,
onClick: () => handleFeatherSelection(5),
},
@@ -587,7 +516,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'select-transform',
label: 'Transform Selection',
shortcut: 'Ctrl+T',
- icon: <Scaling className="w-3.5 h-3.5 text-cyan-400" />,
disabled: !hasOpenDocument || !selection,
onClick: handleStartTransform,
},
@@ -601,7 +529,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'layer-new-raster',
label: 'New Raster Layer',
shortcut: 'Ctrl+Shift+N',
- icon: <Plus className="w-3.5 h-3.5" />,
disabled: !hasOpenDocument,
onClick: () => handleAddLayer('raster'),
},
@@ -614,7 +541,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'layer-new-3d',
label: 'New 3D Reference Layer...',
- icon: <Box className="w-3.5 h-3.5 text-purple-400" />,
disabled: !hasOpenDocument,
onClick: () => uiStoreActions.set3DLayerOpen(true),
},
@@ -896,7 +822,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'ruler-add-1p',
label: 'Add 1-Point Perspective Ruler',
- icon: <Compass className="w-3.5 h-3.5 text-cyan-400" />,
disabled: !hasOpenDocument,
onClick: () => {
documentStoreActions.setPerspectiveRuler(
@@ -908,7 +833,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'ruler-add-2p',
label: 'Add 2-Point Perspective Ruler',
- icon: <Compass className="w-3.5 h-3.5 text-purple-400" />,
disabled: !hasOpenDocument,
onClick: () => {
documentStoreActions.setPerspectiveRuler(
@@ -920,7 +844,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'ruler-add-3p-birds',
label: "Add 3-Point Perspective Ruler (Bird's-Eye)",
- icon: <Compass className="w-3.5 h-3.5 text-emerald-400" />,
disabled: !hasOpenDocument,
onClick: () => {
documentStoreActions.setPerspectiveRuler(
@@ -932,7 +855,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'ruler-add-3p-worms',
label: "Add 3-Point Perspective Ruler (Worm's-Eye)",
- icon: <Compass className="w-3.5 h-3.5 text-amber-400" />,
disabled: !hasOpenDocument,
onClick: () => {
const base = createDefaultPerspectiveRuler('3-point', dimensions);
@@ -950,11 +872,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
? 'Hide Perspective Ruler'
: 'Show Perspective Ruler',
shortcut: 'Ctrl+Shift+R',
- icon: perspectiveRuler.enabled ? (
- <EyeOff className="w-3.5 h-3.5 text-sky-400" />
- ) : (
- <Eye className="w-3.5 h-3.5 text-sky-400" />
- ),
disabled: !hasOpenDocument,
onClick: () =>
documentStoreActions.setPerspectiveRuler((prev) =>
@@ -965,7 +882,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'ruler-toggle-snap',
label: perspectiveRuler.snapEnabled ? 'Disable Snapping' : 'Enable Snapping',
shortcut: 'Ctrl+Shift+P',
- icon: <Magnet className="w-3.5 h-3.5 text-emerald-400" />,
disabled: !hasOpenDocument,
onClick: () =>
documentStoreActions.setPerspectiveRuler((prev) =>
@@ -977,11 +893,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
label: perspectiveRuler.locked
? 'Unlock Handles (Edit Mode)'
: 'Lock Handles (Freeze for Inking)',
- icon: perspectiveRuler.locked ? (
- <Unlock className="w-3.5 h-3.5 text-amber-400" />
- ) : (
- <Lock className="w-3.5 h-3.5 text-amber-400" />
- ),
disabled: !hasOpenDocument,
onClick: () =>
documentStoreActions.setPerspectiveRuler((prev) =>
@@ -1058,7 +969,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'ruler-remove',
label: 'Remove Perspective Ruler from Canvas',
danger: true,
- icon: <Trash2 className="w-3.5 h-3.5 text-red-400" />,
disabled: !hasOpenDocument,
onClick: () => {
documentStoreActions.setPerspectiveRuler(null);
@@ -1075,7 +985,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'view-zoom-in',
label: 'Zoom In',
shortcut: 'Ctrl++',
- icon: <ZoomIn className="w-3.5 h-3.5" />,
disabled: !hasOpenDocument,
onClick: zoomIn,
},
@@ -1083,7 +992,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'view-zoom-out',
label: 'Zoom Out',
shortcut: 'Ctrl+-',
- icon: <ZoomOut className="w-3.5 h-3.5" />,
disabled: !hasOpenDocument,
onClick: zoomOut,
},
@@ -1098,7 +1006,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'view-reset-rotation',
label: 'Reset Rotation',
shortcut: 'Ctrl+Alt+0',
- icon: <RotateCcw className="w-3.5 h-3.5" />,
disabled: !hasOpenDocument,
onClick: resetRotation,
},
@@ -1107,7 +1014,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'view-flip-horizontal',
label: 'Flip View Horizontal',
shortcut: 'Shift+H',
- icon: <FlipHorizontal className="w-3.5 h-3.5" />,
checked: flipX,
disabled: !hasOpenDocument,
onClick: toggleFlipHorizontal,
@@ -1116,7 +1022,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'view-flip-vertical',
label: 'Flip View Vertical',
shortcut: 'Shift+V',
- icon: <FlipVertical className="w-3.5 h-3.5" />,
checked: flipY,
disabled: !hasOpenDocument,
onClick: toggleFlipVertical,
@@ -1158,7 +1063,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
label: isWebtoonMode
? 'Exit Webtoon Studio Mode'
: 'Webtoon Studio Mode (9:16 Mockup)',
- icon: <Smartphone className="w-3.5 h-3.5 text-emerald-400" />,
disabled: !hasOpenDocument,
onClick: () => uiStoreActions.toggleWebtoonMode(),
},
@@ -1217,21 +1121,18 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'manga-effects-generator',
label: 'Manga Effect Lines Generator...',
- icon: <Sparkles className="w-3.5 h-3.5 text-amber-400" />,
disabled: !hasOpenDocument,
onClick: () => uiStoreActions.setMangaEffectsModalOpen(true),
},
{
id: 'manga-balloon-tool',
label: 'Parametric Speech Balloon Tool',
- icon: <MessageSquare className="w-3.5 h-3.5 text-cyan-400" />,
disabled: !hasOpenDocument,
onClick: () => toolStoreActions.selectTool('balloon'),
},
{
id: 'manga-correct-line',
label: 'Correct Line (Vector Pinch/Width/Simplify)',
- icon: <Spline className="w-3.5 h-3.5 text-indigo-400" />,
disabled: !hasOpenDocument,
onClick: () => toolStoreActions.selectTool('vector-edit'),
},
@@ -1241,14 +1142,12 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
label: isWebtoonMode
? 'Exit Webtoon Studio Mode'
: 'Webtoon Studio Mode (9:16 Simulator)',
- icon: <Smartphone className="w-3.5 h-3.5 text-emerald-400" />,
disabled: !hasOpenDocument,
onClick: () => uiStoreActions.toggleWebtoonMode(),
},
{
id: 'manga-webtoon-export',
label: 'Export Webtoon Chapter Slices (.zip)...',
- icon: <Archive className="w-3.5 h-3.5 text-sky-400" />,
disabled: !hasOpenDocument,
onClick: () => uiStoreActions.setWebtoonExportModalOpen(true),
},
@@ -1264,7 +1163,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
? 'Hide Animation Timeline'
: 'Show Animation Timeline',
shortcut: 'Ctrl+Alt+A',
- icon: <Film className="w-3.5 h-3.5 text-emerald-400" />,
disabled: !hasOpenDocument,
onClick: () => {
if (activeAnimationTimeline) {
@@ -1278,7 +1176,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
id: 'anim-new-cel',
label: 'Add Cel to Current Frame',
shortcut: 'Alt+C',
- icon: <Plus className="w-3.5 h-3.5" />,
disabled: !hasOpenDocument || !activeAnimationTimeline,
onClick: () => {
if (activeAnimationTimeline) {
@@ -1291,7 +1188,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
label: activeAnimationTimeline?.onionSkin.enabled
? 'Disable Onion Skinning'
: 'Enable Onion Skinning',
- icon: <Layers className="w-3.5 h-3.5 text-purple-400" />,
disabled: !hasOpenDocument || !activeAnimationTimeline,
onClick: () => {
if (activeAnimationTimeline) {
@@ -1335,7 +1231,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'window-ws-reset',
label: 'Reset Workspace',
- icon: <RotateCcw className="w-3.5 h-3.5 text-amber-400" />,
onClick: () => {
workspaceStoreActions.resetWorkspace();
showToast('Workspace reset to preset defaults');
@@ -1385,7 +1280,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
{
id: 'help-about',
label: 'About Ink Studio',
- icon: <InfoIcon className="w-3.5 h-3.5 text-[#93c5fd]" />,
onClick: () => {
alert(
'Ink Studio - Professional Digital Painting & Manga Studio\n\n' +
diff --git a/src/hooks/useCollabSync.ts b/src/hooks/useCollabSync.ts
index aaeacac..a86b621 100644
--- a/src/hooks/useCollabSync.ts
+++ b/src/hooks/useCollabSync.ts
@@ -136,7 +136,7 @@ export function useCollabSync({
const isEraser = msg.tool === 'eraser';
const isBgEraser =
isEraser && (msg.layerId === 'layer-bg' || msg.layerId.startsWith('layer-bg'));
- const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
+ const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
if (isPencil) {
@@ -178,7 +178,7 @@ export function useCollabSync({
const isBgEraser =
isEraser &&
(strokeState.layerId === 'layer-bg' || strokeState.layerId.startsWith('layer-bg'));
- const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
+ const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
const pts = strokeState.points;
diff --git a/src/stores/useToolStore.ts b/src/stores/useToolStore.ts
index 2f51c24..4dc57c3 100644
--- a/src/stores/useToolStore.ts
+++ b/src/stores/useToolStore.ts
@@ -60,22 +60,23 @@ const DEFAULT_RECENT_COLORS = [
function createInitialBrushSettings(): { presetId: BrushPresetId; brushSettings: BrushSettings } {
const activePreset = getActivePresetId();
const effective = getEffectiveBrushSettings(activePreset);
+ const resolvedPreset = (effective.preset || activePreset || DEFAULT_BRUSH_PRESET_ID) as BrushPresetId;
return {
- presetId: activePreset,
+ presetId: resolvedPreset,
brushSettings: {
- preset: activePreset,
- size: effective.size ?? 3.5,
- minSizeFactor: effective.minSizeFactor ?? 0.25,
+ preset: resolvedPreset,
+ size: effective.size ?? 8,
+ minSizeFactor: effective.minSizeFactor ?? 0.04,
color: '#000000',
secondaryColor: '#ffffff',
opacity: effective.opacity ?? 1.0,
- flow: effective.flow ?? 0.74,
- spacing: effective.spacing ?? 0.08,
- grain: effective.grain ?? 0.95,
+ flow: effective.flow ?? 1.0,
+ spacing: effective.spacing ?? 0.04,
+ grain: effective.grain ?? 0,
usePressure: effective.usePressure ?? true,
smoothing: effective.smoothing ?? true,
- stabilization: effective.stabilization ?? 15,
- hardness: effective.hardness ?? 0.8,
+ stabilization: effective.stabilization ?? 20,
+ hardness: effective.hardness ?? 1.0,
...effective,
} as BrushSettings,
};
diff --git a/src/types/editor.ts b/src/types/editor.ts
index 364deff..9091834 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -30,17 +30,29 @@ export interface Point {
isCorner?: boolean;
}
+export type BrushCategory = 'pen' | 'sketch' | 'brush';
+
export type BrushPresetId =
- | 'round'
+ // Pen section
| 'g-pen'
- | 'maru-pen'
- | 'turnip-pen'
- | 'airbrush-soft'
- | 'pencil-f'
- | 'pencil-hb'
- | 'pencil-2b'
- | 'pencil-4b'
- | 'square-digital'
+ | 'real-g-pen'
+ | 'textured-pen'
+ | 'dot-pen'
+ | 'calligraphy'
+ // Sketch section
+ | 'mechanical-pencil'
+ | 'pencil-hb-2b'
+ | 'pencil-6b-8b'
+ | 'charcoal-pencil'
+ | 'standard-chalk'
+ // Brush section
+ | 'oil-painting'
+ | 'thick-oil-painting'
+ | 'chalk-painting'
+ | 'blend-brush'
+ | 'blend-chalk-brush'
+ | 'soft-round'
+ | 'noise-shader'
| string;
export interface CspEffectorCurvePoint {
@@ -817,7 +829,6 @@ export interface MenuItem {
id: string;
label: string;
shortcut?: string;
- icon?: React.ReactNode;
disabled?: boolean;
danger?: boolean;
divider?: boolean;
diff --git a/src/utils/__tests__/builtinBrushes.test.ts b/src/utils/__tests__/builtinBrushes.test.ts
new file mode 100644
index 0000000..9313ff2
--- /dev/null
+++ b/src/utils/__tests__/builtinBrushes.test.ts
@@ -0,0 +1,302 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ BUILTIN_BRUSHES,
+ BUILTIN_BRUSH_SECTIONS,
+ getBuiltinBrushConfig,
+} from '../presetBrushes';
+import { getEffectiveBrushSettings } from '../brushPresetManager';
+import { applyCspPaperTextureAlpha } from '../../engine/CspBrushEngine';
+import { PaintReservoir } from '../colorMixingEngine';
+import { drawTexturedCubicBezierSegment, TexturedBrushOptions } from '../stampEngine';
+import { Point } from '../../types/editor';
+
+function createMockCanvas(width: number = 128, height: number = 128) {
+ const pixelBuffer = new Uint8ClampedArray(width * height * 4);
+ const drawnDabs: {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ alpha: number;
+ }[] = [];
+
+ const ctx: any = {
+ canvas: { width, height },
+ globalAlpha: 1.0,
+ globalCompositeOperation: 'source-over',
+ imageSmoothingEnabled: true,
+ clearRect: () => pixelBuffer.fill(0),
+ fillRect: () => {},
+ createImageData: (w: number, h: number) => ({
+ width: w,
+ height: h,
+ data: new Uint8ClampedArray(w * h * 4),
+ }),
+ putImageData: (imgData: any) => {
+ if (imgData.data.length === pixelBuffer.length) {
+ pixelBuffer.set(imgData.data);
+ }
+ },
+ getImageData: () => ({ width, height, data: pixelBuffer }),
+ drawImage: (_src: any, dx: number, dy: number, dw?: number, dh?: number) => {
+ drawnDabs.push({
+ x: dx + (dw ? dw / 2 : 0),
+ y: dy + (dh ? dh / 2 : 0),
+ width: dw || 0,
+ height: dh || 0,
+ alpha: ctx.globalAlpha,
+ });
+ },
+ save: () => {},
+ restore: () => {},
+ translate: () => {},
+ rotate: () => {},
+ scale: () => {},
+ };
+
+ return {
+ width,
+ height,
+ getContext: (type: string) => (type === '2d' ? ctx : null),
+ toDataURL: () => `data:image/png;base64,MOCK_${width}x${height}_${pixelBuffer.reduce((a, b) => (a + b) & 0xffff, 0)}`,
+ pixelBuffer,
+ drawnDabs,
+ };
+}
+
+describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
+ beforeEach(() => {
+ (globalThis as any).document = {
+ createElement: (tag: string) => {
+ if (tag === 'canvas') return createMockCanvas();
+ return {};
+ },
+ };
+ (globalThis as any).Image = class MockImage {
+ src = '';
+ complete = true;
+ naturalWidth = 128;
+ naturalHeight = 128;
+ width = 128;
+ height = 128;
+ decode() {
+ return Promise.resolve();
+ }
+ };
+ });
+
+ it('registers all 17 brushes cleanly across Pen (5), Sketch (5), and Brush (7) sections', () => {
+ expect(BUILTIN_BRUSH_SECTIONS.map((s) => s.id)).toEqual(['pen', 'sketch', 'brush']);
+
+ const penIds = BUILTIN_BRUSHES.filter((b) => b.category === 'pen').map((b) => b.id);
+ const sketchIds = BUILTIN_BRUSHES.filter((b) => b.category === 'sketch').map((b) => b.id);
+ const brushIds = BUILTIN_BRUSHES.filter((b) => b.category === 'brush').map((b) => b.id);
+
+ expect(penIds).toEqual(['g-pen', 'real-g-pen', 'textured-pen', 'dot-pen', 'calligraphy']);
+ expect(sketchIds).toEqual([
+ 'mechanical-pencil',
+ 'pencil-hb-2b',
+ 'pencil-6b-8b',
+ 'charcoal-pencil',
+ 'standard-chalk',
+ ]);
+ expect(brushIds).toEqual([
+ 'oil-painting',
+ 'thick-oil-painting',
+ 'chalk-painting',
+ 'blend-brush',
+ 'blend-chalk-brush',
+ 'soft-round',
+ 'noise-shader',
+ ]);
+ });
+
+ it('generates deterministic non-empty procedural tip and paper PNG data URLs for every configured brush', () => {
+ for (const def of BUILTIN_BRUSHES) {
+ const cfg = getBuiltinBrushConfig(def.id);
+ expect(cfg).not.toBeNull();
+ expect(cfg?.preset).toBe(def.id);
+ if (def.tipGenerator) {
+ expect(cfg?.customTipDataUrl).toMatch(/^data:image\/png;base64,/);
+ expect(cfg?.customTipImage).toBeDefined();
+ }
+ if (def.paperTextureGenerator) {
+ expect(cfg?.paperTexture).toMatch(/^data:image\/png;base64,/);
+ expect(cfg?.paperTextureImage).toBeDefined();
+ }
+ }
+ });
+
+ it('enforces authentic Sketch pencil physics contracts across grades', () => {
+ const mech = getBuiltinBrushConfig('mechanical-pencil')!;
+ const hb2b = getBuiltinBrushConfig('pencil-hb-2b')!;
+ const b68 = getBuiltinBrushConfig('pencil-6b-8b')!;
+ const charcoal = getBuiltinBrushConfig('charcoal-pencil')!;
+
+ // Mechanical pencil: firm, thin, tilt-independent, minimal grain, crisp edge
+ expect(mech.useTilt).toBe(false);
+ expect(mech.size).toBeLessThanOrEqual(3);
+ expect(mech.grain).toBeLessThan(0.4);
+ expect(mech.hardness).toBeGreaterThanOrEqual(0.9);
+ expect(mech.paperTextureMode).toBe('compare');
+
+ // HB/2B: moderate grain, pressure opacity/flow modulation, gentle tilt
+ expect(hb2b.useTilt).toBe(true);
+ expect(hb2b.tiltScale!).toBeGreaterThan(0.5);
+ expect(hb2b.tiltScale!).toBeLessThan(1.2);
+ expect(hb2b.grain!).toBeGreaterThan(mech.grain!);
+ expect(hb2b.grain!).toBeLessThan(b68.grain!);
+ expect(hb2b.opacitySensor?.usePressure).toBe(true);
+ expect(hb2b.paperTextureMode).toBe('compare');
+
+ // 6B/8B: rich dark, strong grain that clogs under heavy pressure, wide tilt hatching edge
+ expect(b68.useTilt).toBe(true);
+ expect(b68.tiltScale!).toBeGreaterThanOrEqual(1.8);
+ expect(b68.grain!).toBeGreaterThanOrEqual(0.8);
+ expect(b68.paperTextureMode).toBe('compare');
+
+ // Charcoal: dry jagged aggressive texture, edge crumbs (halo + scatter), max tilt response
+ expect(charcoal.useTilt).toBe(true);
+ expect(charcoal.tiltScale!).toBeGreaterThanOrEqual(2.0);
+ expect(charcoal.grain!).toBeGreaterThanOrEqual(0.88);
+ expect(charcoal.dynamics?.scatter).toBeGreaterThan(0);
+ expect(charcoal.paperTextureMode).toBe('compare');
+ });
+
+ it('cuts recessed paper valleys to exact zero at light/medium pressure and clogs only under heavy pressure (compare mode)', () => {
+ const valleyHeight = 0.22; // Deep paper valley
+ const ridgeHeight = 0.82; // High cotton paper peak
+
+ // At light & medium pressure, recessed valleys MUST cut to 0.0 so multi-dab overlap never fills them in
+ const valleyLight = applyCspPaperTextureAlpha(0.9, valleyHeight, 0.86, 0.25, 'compare');
+ const valleyMed = applyCspPaperTextureAlpha(0.9, valleyHeight, 0.86, 0.50, 'compare');
+ const ridgeMed = applyCspPaperTextureAlpha(0.9, ridgeHeight, 0.86, 0.50, 'compare');
+ expect(valleyLight).toBe(0);
+ expect(valleyMed).toBe(0);
+ expect(ridgeMed).toBeGreaterThan(0.8);
+
+ // Under heavy pressure (6B/8B clogging), soft lead compresses into mid-valleys
+ const midValleyMed = applyCspPaperTextureAlpha(0.9, 0.42, 0.86, 0.45, 'compare');
+ const midValleyHeavy = applyCspPaperTextureAlpha(0.9, 0.42, 0.86, 0.96, 'compare');
+ expect(midValleyMed).toBe(0);
+ expect(midValleyHeavy).toBeGreaterThan(0.75);
+ });
+
+ it('widens & softens tilted 6B/8B strokes while keeping Mechanical Pencil completely tilt-independent', () => {
+ const mockTip: any = { naturalWidth: 128, naturalHeight: 128, width: 128, height: 128, complete: true, src: 't' };
+ const uprightPts: [Point, Point, Point, Point] = [
+ { x: 10, y: 50, pressure: 0.7, width: 8, tiltX: 0, tiltY: 0 },
+ { x: 30, y: 50, pressure: 0.7, width: 8, tiltX: 0, tiltY: 0 },
+ { x: 60, y: 50, pressure: 0.7, width: 8, tiltX: 0, tiltY: 0 },
+ { x: 90, y: 50, pressure: 0.7, width: 8, tiltX: 0, tiltY: 0 },
+ ];
+ const tiltedPts: [Point, Point, Point, Point] = uprightPts.map((p) => ({
+ ...p,
+ tiltX: 65,
+ tiltY: 0,
+ })) as [Point, Point, Point, Point];
+
+ // 1. 6B/8B widens dramatically and softens when tilted
+ const b68 = getBuiltinBrushConfig('pencil-6b-8b')!;
+ const cUp = createMockCanvas(200, 200);
+ const cTilt = createMockCanvas(200, 200);
+ const b68Opts: TexturedBrushOptions = {
+ size: b68.size!,
+ flow: b68.flow,
+ spacing: 0.2,
+ useTilt: b68.useTilt,
+ tiltScale: b68.tiltScale,
+ thickness: b68.thickness,
+ useGpu: false,
+ };
+ drawTexturedCubicBezierSegment(cUp.getContext('2d'), ...uprightPts, '#111111', mockTip, b68Opts);
+ drawTexturedCubicBezierSegment(cTilt.getContext('2d'), ...tiltedPts, '#111111', mockTip, b68Opts);
+
+ const avgUpW = cUp.drawnDabs.reduce((s, d) => s + d.width, 0) / cUp.drawnDabs.length;
+ const avgTiltW = cTilt.drawnDabs.reduce((s, d) => s + d.width, 0) / cTilt.drawnDabs.length;
+ const avgUpA = cUp.drawnDabs.reduce((s, d) => s + d.alpha, 0) / cUp.drawnDabs.length;
+ const avgTiltA = cTilt.drawnDabs.reduce((s, d) => s + d.alpha, 0) / cTilt.drawnDabs.length;
+ expect(avgTiltW).toBeGreaterThan(avgUpW * 2.5);
+ expect(avgTiltA).toBeLessThan(avgUpA);
+
+ // 2. Mechanical Pencil ignores tilt completely
+ const mech = getBuiltinBrushConfig('mechanical-pencil')!;
+ const mUp = createMockCanvas(200, 200);
+ const mTilt = createMockCanvas(200, 200);
+ const mechOpts: TexturedBrushOptions = {
+ size: mech.size!,
+ flow: mech.flow,
+ spacing: 0.2,
+ useTilt: mech.useTilt,
+ tiltScale: mech.tiltScale,
+ useGpu: false,
+ };
+ drawTexturedCubicBezierSegment(mUp.getContext('2d'), ...uprightPts, '#111111', mockTip, mechOpts);
+ drawTexturedCubicBezierSegment(mTilt.getContext('2d'), ...tiltedPts, '#111111', mockTip, mechOpts);
+
+ const mUpW = mUp.drawnDabs.reduce((s, d) => s + d.width, 0) / mUp.drawnDabs.length;
+ const mTiltW = mTilt.drawnDabs.reduce((s, d) => s + d.width, 0) / mTilt.drawnDabs.length;
+ expect(mTiltW).toBeCloseTo(mUpW, 4);
+ });
+
+ it('prevents pure Blend / Blend Chalk brushes from emitting foreground color onto blank canvas or contaminating first contact', () => {
+ const blend = getBuiltinBrushConfig('blend-brush')!;
+ const blendChalk = getBuiltinBrushConfig('blend-chalk-brush')!;
+ expect(blend.colorMixing).toBe(true);
+ expect(blend.amountOfPaint).toBe(0);
+ expect(blend.mixingMode).toBe('smear');
+ expect(blendChalk.amountOfPaint).toBe(0);
+ expect(blendChalk.mixingMode).toBe('smear');
+ expect(blendChalk.grain).toBeGreaterThan(0.4);
+
+ // Touching blank canvas with red foreground selected must output alpha === 0
+ const resBlank = new PaintReservoir('#ff0000');
+ const blankOut = resBlank.mixWithCanvas(
+ { r: 255, g: 255, b: 255, a: 0 },
+ 0,
+ 0.75,
+ 0.74,
+ 'smear',
+ 0.8,
+ 0.7,
+ 0,
+ true
+ );
+ expect(blankOut.alpha).toBe(0);
+
+ // First contact with pure blue paint on canvas must pick up pure blue, NOT mix in red foreground!
+ const resPaint = new PaintReservoir('#ff0000');
+ const firstContact = resPaint.mixWithCanvas(
+ { r: 0, g: 40, b: 220, a: 1.0 },
+ 0,
+ 0.75,
+ 0.74,
+ 'smear',
+ 0.8,
+ 0.7,
+ 0,
+ true
+ );
+ expect(firstContact.r).toBe(0);
+ expect(firstContact.g).toBe(40);
+ expect(firstContact.b).toBe(220);
+ expect(firstContact.alpha).toBeGreaterThan(0.1);
+ });
+
+ it('resets dynamics, sensors, paper grain, tilt, and colorMixing cleanly when switching presets (zero state leakage)', () => {
+ const charcoal = getEffectiveBrushSettings('charcoal-pencil');
+ expect(charcoal.dynamics?.scatter).toBeGreaterThan(0);
+ expect(charcoal.useTilt).toBe(true);
+ expect(charcoal.grain).toBeGreaterThan(0.8);
+
+ const gPen = getEffectiveBrushSettings('g-pen');
+ expect(gPen.dynamics).toBeUndefined();
+ expect(gPen.useTilt).toBe(false);
+ expect(gPen.grain).toBe(0);
+ expect(gPen.colorMixing).toBe(false);
+ expect(gPen.opacitySensor).toBeUndefined();
+ expect(gPen.densitySensor).toBeUndefined();
+ expect(gPen.customTipImage).toBeUndefined();
+ expect(gPen.paperTextureImage).toBeUndefined();
+ });
+});
diff --git a/src/utils/__tests__/cspBrushEngineV2.test.ts b/src/utils/__tests__/cspBrushEngineV2.test.ts
index 8ef6048..3fde089 100644
--- a/src/utils/__tests__/cspBrushEngineV2.test.ts
+++ b/src/utils/__tests__/cspBrushEngineV2.test.ts
@@ -162,11 +162,12 @@ describe('CSP Brush Engine V2 - Mathematics, Sensors & Post-Processing', () => {
expect(data[rimIdx + 3]).toBeGreaterThan(180);
});
- it('steps brush size presets cleanly and includes all 18 studio presets', () => {
+ it('steps brush size presets cleanly and exposes G-Pen builtin preset', () => {
expect(stepBrushSizePreset(10, 1)).toBe(12);
expect(stepBrushSizePreset(10, -1)).toBe(8);
expect(stepBrushSizePreset(0.5, -1)).toBe(0.5);
expect(stepBrushSizePreset(2000, 1)).toBe(2000);
- expect(BUILTIN_BRUSHES.length).toBeGreaterThanOrEqual(18);
+ expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('g-pen');
+ expect(BUILTIN_BRUSHES.length).toBe(17);
});
});
diff --git a/src/utils/brushPresetManager.ts b/src/utils/brushPresetManager.ts
index b967dd0..bb2c54b 100644
--- a/src/utils/brushPresetManager.ts
+++ b/src/utils/brushPresetManager.ts
@@ -12,7 +12,6 @@ import {
CspTipFlipMode,
} from '../types/editor';
import { getBuiltinBrushConfig } from './presetBrushes';
-import { PENCIL_CONFIGS, PencilGrade } from './pencilEngine';
import { getPreloadedTipImage, getCachedCustomBrushes } from './brushStorage';
export const BRUSH_SIZE_PRESETS: number[] = [
@@ -50,8 +49,17 @@ export function stepBrushSizePreset(currentSize: number, direction: -1 | 1): num
export const STORAGE_KEY_SETTINGS = 'sora_paint_brush_settings_by_id';
export const STORAGE_KEY_ACTIVE_PRESET = 'sora_paint_active_brush_preset';
export const STORAGE_KEY_BOTTOM_TAB = 'sora_paint_left_bottom_tab';
+const STORAGE_KEY_PRESET_SCHEMA = 'sora_paint_brush_preset_schema_v';
+const BUILTIN_PRESET_SCHEMA_VERSION = 2;
+const SKETCH_PRESET_IDS = [
+ 'mechanical-pencil',
+ 'pencil-hb-2b',
+ 'pencil-6b-8b',
+ 'charcoal-pencil',
+ 'standard-chalk',
+];
export const ERASER_PRESET_ID = 'tool-eraser';
-export const DEFAULT_BRUSH_PRESET_ID = 'pencil-2b';
+export const DEFAULT_BRUSH_PRESET_ID = 'g-pen';
export interface BrushPersistentSettings {
size?: number;
@@ -108,7 +116,73 @@ export interface BrushPersistentSettings {
dynamics?: BrushDynamics;
}
+export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {
+ brushDensity: undefined,
+ adjustDensityByGap: false,
+ blendTipsMode: 'darken',
+ brushCombineMode: undefined,
+ useTilt: false,
+ tiltScale: 1.0,
+ useVelocity: false,
+ velocityDynamics: false,
+ postCorrection: 0,
+ sharpCorners: true,
+ thickness: 1.0,
+ thicknessVertical: false,
+ flipH: 'none',
+ flipV: 'none',
+ antiAlias: 2,
+ grain: 0,
+ textureDensity: 0,
+ sizeSensor: undefined,
+ opacitySensor: undefined,
+ densitySensor: undefined,
+ customTipDataUrl: undefined,
+ customTipImage: undefined,
+ customTipAngle: 0,
+ customTipAngleDynamics: 'none',
+ customTipRotationRandomScale: 0,
+ isColorTip: false,
+ subTips: undefined,
+ subTipOrder: undefined,
+ subTipImages: undefined,
+ pressureCurve: undefined,
+ velocityCurve: undefined,
+ pressureCurveGamma: 1.0,
+ spray: undefined,
+ taper: undefined,
+ isRibbon: false,
+ colorMixing: false,
+ perceptualMixing: true,
+ amountOfPaint: 0.7,
+ densityOfPaint: 0.8,
+ colorStretch: 0.6,
+ mixingMode: 'blend',
+ wetEdge: 0,
+ wetEdgeRadius: undefined,
+ wetEdgeAlphaPower: undefined,
+ wetEdgeValuePower: undefined,
+ paperTexture: undefined,
+ paperTextureImage: undefined,
+ paperTextureMode: 'subtract',
+ paperTextureBrightness: 0,
+ paperTextureContrast: 0,
+ paperTextureApplyEachPlot: false,
+ paperTextureInverted: false,
+ paperTextureScale: 1.0,
+ paperTextureRotate: 0,
+ dualBrush: false,
+ dualBrushCompositeMode: 'multiply',
+ dualSize: undefined,
+ dualSpacing: undefined,
+ dualTipDataUrl: undefined,
+ dualTipImage: undefined,
+ dynamics: undefined,
+ useGpu: true,
+};
+
export const DEFAULT_ERASER_SETTINGS: Partial<BrushSettings> = {
+ ...NEUTRAL_BRUSH_DEFAULTS,
preset: ERASER_PRESET_ID,
brushName: 'Eraser',
size: 30,
@@ -133,7 +207,24 @@ export function loadAllSavedBrushSettings(): Record<string, BrushPersistentSetti
if (_memorySettingsCache) return _memorySettingsCache;
try {
const raw = typeof localStorage !== 'undefined' ? localStorage.getItem(STORAGE_KEY_SETTINGS) : null;
- _memorySettingsCache = raw ? JSON.parse(raw) : {};
+ const parsed: Record<string, BrushPersistentSettings> = raw ? JSON.parse(raw) : {};
+ if (typeof localStorage !== 'undefined') {
+ const storedVer = Number(localStorage.getItem(STORAGE_KEY_PRESET_SCHEMA) || '0');
+ if (storedVer < BUILTIN_PRESET_SCHEMA_VERSION) {
+ let mutated = false;
+ for (const id of SKETCH_PRESET_IDS) {
+ if (parsed[id]) {
+ delete parsed[id];
+ mutated = true;
+ }
+ }
+ if (mutated) {
+ localStorage.setItem(STORAGE_KEY_SETTINGS, JSON.stringify(parsed));
+ }
+ localStorage.setItem(STORAGE_KEY_PRESET_SCHEMA, String(BUILTIN_PRESET_SCHEMA_VERSION));
+ }
+ }
+ _memorySettingsCache = parsed;
} catch {
_memorySettingsCache = {};
}
@@ -283,7 +374,10 @@ export function resetBrushSettingsToDefault(
export function getActivePresetId(): string {
try {
if (typeof localStorage === 'undefined') return DEFAULT_BRUSH_PRESET_ID;
- return localStorage.getItem(STORAGE_KEY_ACTIVE_PRESET) || DEFAULT_BRUSH_PRESET_ID;
+ const saved = localStorage.getItem(STORAGE_KEY_ACTIVE_PRESET);
+ if (!saved) return DEFAULT_BRUSH_PRESET_ID;
+ if (saved.startsWith('csp-') || getBuiltinBrushConfig(saved)) return saved;
+ return DEFAULT_BRUSH_PRESET_ID;
} catch {
return DEFAULT_BRUSH_PRESET_ID;
}
@@ -341,6 +435,7 @@ export function getEffectiveBrushSettings(
}
return {
+ ...NEUTRAL_BRUSH_DEFAULTS,
preset: cspMatch.id,
brushName: cspMatch.name,
size: cspMatch.size,
@@ -419,72 +514,31 @@ export function getEffectiveBrushSettings(
const builtinCfg = getBuiltinBrushConfig(presetId as BrushPresetId);
if (builtinCfg) {
return {
+ ...NEUTRAL_BRUSH_DEFAULTS,
preset: presetId,
- customTipDataUrl: undefined,
- customTipImage: undefined,
- customTipAngle: 0,
- customTipAngleDynamics: 'none',
- thickness: 1.0,
- thicknessVertical: false,
- flipH: 'none',
- flipV: 'none',
- blendTipsMode: 'darken',
- adjustDensityByGap: false,
- antiAlias: 2,
- postCorrection: 0,
- sharpCorners: true,
- useTilt: false,
- colorMixing: false,
- perceptualMixing: true,
- wetEdge: 0,
- grain: 0,
- spray: undefined,
...builtinCfg,
...saved,
};
}
- // 4. Pencil configs fallback
- const pencilConfig = PENCIL_CONFIGS[presetId as PencilGrade];
- if (pencilConfig) {
- return {
- preset: presetId,
- brushName: pencilConfig.name,
- customTipDataUrl: undefined,
- customTipImage: undefined,
- customTipAngle: 0,
- size: pencilConfig.defaultSize,
- flow: pencilConfig.flow,
- hardness: pencilConfig.hardness,
- minSizeFactor: pencilConfig.minSizeFactor,
- grain: pencilConfig.grain,
- spacing: pencilConfig.spacing,
- usePressure: true,
- useTilt: true,
- smoothing: true,
- stabilization: 15,
- sharpCorners: true,
- useGpu: true,
- ...saved,
- };
- }
-
- // 5. Default fallback (pencil-2b)
+ // 4. Default fallback (g-pen)
+ const defaultCfg = getBuiltinBrushConfig(DEFAULT_BRUSH_PRESET_ID);
+ const defaultSaved = getSavedBrushSettings(DEFAULT_BRUSH_PRESET_ID);
return {
- preset: 'pencil-2b',
- brushName: 'Pencil (2B)',
- size: 3.5,
- minSizeFactor: 0.25,
- flow: 0.74,
- hardness: 0.8,
- grain: 0.95,
- spacing: 0.08,
+ ...NEUTRAL_BRUSH_DEFAULTS,
+ preset: DEFAULT_BRUSH_PRESET_ID,
+ brushName: 'G-Pen',
+ size: 8,
+ minSizeFactor: 0.04,
+ flow: 1.0,
+ opacity: 1.0,
+ hardness: 1.0,
+ spacing: 0.04,
+ stabilization: 20,
usePressure: true,
- useTilt: true,
smoothing: true,
- stabilization: 15,
- sharpCorners: true,
useGpu: true,
- ...saved,
+ ...defaultCfg,
+ ...defaultSaved,
};
}
diff --git a/src/utils/brushPreview.ts b/src/utils/brushPreview.ts
index 99d403e..e998337 100644
--- a/src/utils/brushPreview.ts
+++ b/src/utils/brushPreview.ts
@@ -1,7 +1,10 @@
import {
+ BrushDynamics,
BrushPresetId,
+ CspAngleDynamicsMode,
CspAntiAliasLevel,
CspBlendTipsMode,
+ CspPaperTextureMode,
CspSpraySettings,
CspTipFlipMode,
} from '../types/editor';
@@ -13,6 +16,7 @@ import {
dabHashFloat,
computeGapAdjustedAlpha,
resolveTipFlipSigns,
+ applyCspPaperTextureAlpha,
} from '../engine/CspBrushEngine';
export interface BrushPreviewOptions {
@@ -21,6 +25,11 @@ export interface BrushPreviewOptions {
flow?: number;
opacity?: number;
grain?: number;
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureScale?: number;
+ paperTextureContrast?: number;
+ paperTextureBrightness?: number;
+ paperTextureInverted?: boolean;
hardness?: number;
spacing?: number;
minSizeFactor?: number;
@@ -31,6 +40,7 @@ export interface BrushPreviewOptions {
tool?: 'brush' | 'eraser';
customTipImage?: HTMLImageElement;
customTipAngle?: number;
+ customTipAngleDynamics?: CspAngleDynamicsMode;
thickness?: number;
thicknessVertical?: boolean;
flipH?: CspTipFlipMode;
@@ -40,6 +50,7 @@ export interface BrushPreviewOptions {
antiAlias?: number;
pressureCurve?: [number, number][];
spray?: CspSpraySettings;
+ dynamics?: BrushDynamics;
colorMixing?: boolean;
amountOfPaint?: number;
densityOfPaint?: number;
@@ -102,7 +113,7 @@ export function renderBrushStrokePreview(
const ctx = canvas.getContext('2d');
if (!ctx) return;
- const preset = options.preset || (options.customTipImage ? 'custom' : 'pencil-2b');
+ const preset = options.preset || (options.customTipImage ? 'custom' : 'g-pen');
const builtinCfg =
!options.customTipImage && options.preset ? getBuiltinBrushConfig(options.preset) : null;
const tipImage = options.customTipImage || builtinCfg?.customTipImage;
@@ -119,6 +130,13 @@ export function renderBrushStrokePreview(
const thickness = options.thickness ?? builtinCfg?.thickness ?? 1.0;
const thicknessVertical = Boolean(options.thicknessVertical ?? builtinCfg?.thicknessVertical);
const customTipAngle = options.customTipAngle ?? builtinCfg?.customTipAngle ?? 0;
+ const angleDynamics = options.customTipAngleDynamics ?? builtinCfg?.customTipAngleDynamics ?? 'none';
+ const dynamics = options.dynamics ?? builtinCfg?.dynamics;
+ const paperMode = options.paperTextureMode ?? builtinCfg?.paperTextureMode ?? 'subtract';
+ const paperScale = options.paperTextureScale ?? builtinCfg?.paperTextureScale ?? 1.0;
+ const paperContrast = options.paperTextureContrast ?? builtinCfg?.paperTextureContrast ?? 0;
+ const paperBrightness = options.paperTextureBrightness ?? builtinCfg?.paperTextureBrightness ?? 0;
+ const paperInverted = Boolean(options.paperTextureInverted ?? builtinCfg?.paperTextureInverted);
const spacing = options.spacing ?? builtinCfg?.spacing ?? (isPencil ? 0.07 : 0.045);
const blendTipsMode = options.blendTipsMode ?? builtinCfg?.blendTipsMode ?? 'darken';
const adjustByGap = Boolean(options.adjustDensityByGap ?? builtinCfg?.adjustDensityByGap);
@@ -223,7 +241,7 @@ export function renderBrushStrokePreview(
offCtx.fillStyle = 'rgba(255, 255, 255, 0.18)';
offCtx.fillRect(padX - 4, centerY - amp - 4, strokeLength + 8, (amp + 4) * 2);
- const eraserMaster = getRadialDabMaster(hardness, '#000000', true, aaLevel);
+ const eraserMaster = getRadialDabMaster(hardness, '#000000', true, displayWidth, aaLevel);
const baseAngleRad = (customTipAngle * Math.PI) / 180;
const effSpacing = clamp(spacing, 0.02, 0.25);
@@ -268,13 +286,18 @@ export function renderBrushStrokePreview(
}
}
offCtx.restore();
- } else if (tipImage) {
+ } else if (tipImage && tipImage.complete !== false && (tipImage.naturalWidth || tipImage.width) > 0) {
const tip = tipImage;
const rawAspect = (tip.naturalHeight || tip.height || 1) / (tip.naturalWidth || tip.width || 1);
const baseAngleRad = (customTipAngle * Math.PI) / 180;
const master = getTintedTipMaster(tip, strokeColor);
const effSpacing = clamp(spacing, 0.02, 0.25);
const baseFlow = computeGapAdjustedAlpha(flow, effSpacing, adjustByGap);
+ const scatterAmt = clamp(dynamics?.scatter ?? 0, 0, 1.5);
+ const sizeJit = clamp(dynamics?.sizeJitter ?? 0, 0, 1);
+ const flowJit = clamp(dynamics?.flowJitter ?? 0, 0, 1);
+ const angleJit = clamp(dynamics?.angleJitter ?? 0, 0, 1);
+ const dabCount = Math.max(1, Math.min(3, Math.round(dynamics?.count ?? 1)));
offCtx.save();
let distanceAcc = 0;
@@ -282,13 +305,19 @@ export function renderBrushStrokePreview(
for (let i = 0; i < pts.length - 1; i++) {
const p1 = pts[i];
const p2 = pts[i + 1];
- const segDist = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const segDx = p2.x - p1.x;
+ const segDy = p2.y - p1.y;
+ const segDist = Math.hypot(segDx, segDy);
+ const tangentAngle = Math.atan2(segDy, segDx);
+ const nx = segDist > 1e-4 ? -segDy / segDist : 0;
+ const ny = segDist > 1e-4 ? segDx / segDist : 1;
const stepCount = Math.max(1, Math.ceil(segDist / 0.6));
for (let s = 0; s < stepCount; s++) {
const t = s / stepCount;
- const curX = p1.x + t * (p2.x - p1.x);
- const curY = p1.y + t * (p2.y - p1.y);
+ const curX = p1.x + t * segDx;
+ const curY = p1.y + t * segDy;
const curW = p1.width + t * (p2.width - p1.width);
+ const curP = p1.pressure + t * (p2.pressure - p1.pressure);
const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
const requiredStep = Math.max(0.5, curW * effSpacing);
@@ -296,27 +325,89 @@ export function renderBrushStrokePreview(
if (distanceAcc >= requiredStep) {
distanceAcc = 0;
dabIdx++;
- const baseW = Math.max(1.2, curW);
- const stampW = thicknessVertical ? baseW * thickness : baseW;
- const stampH = thicknessVertical ? baseW * rawAspect : baseW * rawAspect * thickness;
- const alpha = clamp(opacity * baseFlow * curTipAlpha, 0.03, 1.0);
- const flips = resolveTipFlipSigns(options.flipH, options.flipV, curX, curY, dabIdx);
-
- if (options.spray?.enabled) {
- const pSize = Math.max(1, options.spray.size || 2);
- const radius = baseW * 0.5;
- const count = Math.max(1, options.spray.density || 4);
- for (let sp = 0; sp < count; sp++) {
- const r = radius * Math.sqrt(dabHashFloat(curX, curY, dabIdx * 32 + sp, 91));
- const th = dabHashFloat(curX, curY, dabIdx * 32 + sp, 92) * Math.PI * 2;
+
+ for (let k = 0; k < dabCount; k++) {
+ const seq = dabIdx * 8 + k;
+ let baseW = Math.max(1.2, curW);
+ if (sizeJit > 0) {
+ baseW *= Math.max(0.2, 1.0 - dabHashFloat(curX, curY, seq, 1) * sizeJit);
+ }
+ const stampW = thicknessVertical ? baseW * thickness : baseW;
+ const stampH = thicknessVertical ? baseW * rawAspect : baseW * rawAspect * thickness;
+
+ let alpha = clamp(opacity * baseFlow * curTipAlpha, 0.03, 1.0);
+ if (flowJit > 0) {
+ alpha *= Math.max(0.1, 1.0 - dabHashFloat(curX, curY, seq, 6) * flowJit);
+ }
+ if (grain > 0.01) {
+ const gNorm = getPaperGrain((curX * 1.4) / Math.max(0.2, paperScale), (curY * 1.4) / Math.max(0.2, paperScale)) / 255.0;
+ alpha = applyCspPaperTextureAlpha(
+ alpha,
+ gNorm,
+ grain,
+ curP,
+ paperMode,
+ paperBrightness,
+ paperContrast,
+ paperInverted
+ );
+ }
+ if (alpha <= 0.005) continue;
+
+ let dabAngle = baseAngleRad;
+ if (angleDynamics === 'direction' || angleDynamics === 'direction-random') {
+ dabAngle += tangentAngle;
+ }
+ if (angleDynamics === 'random' || angleDynamics === 'direction-random' || angleJit > 0) {
+ const jScale = angleDynamics === 'random' ? 1.0 : Math.max(angleJit, 0.3);
+ dabAngle += (dabHashFloat(curX, curY, seq, 3) - 0.5) * Math.PI * 2 * jScale;
+ }
+
+ let drawX = curX;
+ let drawY = curY;
+ if (scatterAmt > 0) {
+ const off = (dabHashFloat(curX, curY, seq, 4) * 2 - 1) * baseW * scatterAmt;
+ drawX += nx * off;
+ drawY += ny * off;
+ }
+
+ const flips = resolveTipFlipSigns(options.flipH, options.flipV, seq, drawX, drawY);
+
+ if (options.spray?.enabled) {
+ const pSize = Math.max(1, options.spray.size || 2);
+ const radius = baseW * 0.5;
+ const count = Math.max(1, options.spray.density || 4);
+ for (let sp = 0; sp < count; sp++) {
+ const r = radius * Math.sqrt(dabHashFloat(drawX, drawY, seq * 32 + sp, 91));
+ const th = dabHashFloat(drawX, drawY, seq * 32 + sp, 92) * Math.PI * 2;
+ drawSingleStamp(
+ offCtx,
+ master,
+ drawX + r * Math.cos(th),
+ drawY + r * Math.sin(th),
+ pSize,
+ pSize * rawAspect,
+ dabAngle,
+ alpha,
+ false,
+ false,
+ false,
+ false,
+ flips.signX,
+ flips.signY,
+ aaLevel,
+ blendTipsMode
+ );
+ }
+ } else {
drawSingleStamp(
offCtx,
master,
- curX + r * Math.cos(th),
- curY + r * Math.sin(th),
- pSize,
- pSize * rawAspect,
- baseAngleRad,
+ drawX,
+ drawY,
+ stampW,
+ stampH,
+ dabAngle,
alpha,
false,
false,
@@ -328,25 +419,6 @@ export function renderBrushStrokePreview(
blendTipsMode
);
}
- } else {
- drawSingleStamp(
- offCtx,
- master,
- curX,
- curY,
- stampW,
- stampH,
- baseAngleRad,
- alpha,
- false,
- false,
- false,
- false,
- flips.signX,
- flips.signY,
- aaLevel,
- blendTipsMode
- );
}
}
}
@@ -404,11 +476,11 @@ export function renderBrushStrokePreview(
const effHardness = clamp(hardness, 0.0, 1.0);
const effSpacing = clamp(spacing, 0.02, 0.25);
const effFlow = computeGapAdjustedAlpha(clamp(flow, 0.01, 1.0), effSpacing, adjustByGap);
- const master = getRadialDabMaster(effHardness, strokeColor, false, aaLevel);
+ const master = getRadialDabMaster(effHardness, strokeColor, false, displayWidth, aaLevel);
const baseAngleRad = (customTipAngle * Math.PI) / 180;
if (options.wetEdge && options.wetEdge > 0.05) {
- const rimMaster = getRadialDabMaster(Math.min(1.0, effHardness + 0.12), strokeColor, false, aaLevel);
+ const rimMaster = getRadialDabMaster(Math.min(1.0, effHardness + 0.12), strokeColor, false, displayWidth, aaLevel);
let wetAcc = 0;
for (let i = 0; i < pts.length - 1; i++) {
const p1 = pts[i];
diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.ts
index cd6ea41..c6c1477 100644
--- a/src/utils/canvasUtils.ts
+++ b/src/utils/canvasUtils.ts
@@ -549,7 +549,8 @@ export function renderCompleteStroke(
colorMode: CanvasColorMode = 'color',
isBgEraser: boolean = false,
underlyingCanvas?: HTMLCanvasElement,
- alphaLocked: boolean = false
+ alphaLocked: boolean = false,
+ explicitSampler?: LayerPixelSampler
) {
if (!points || points.length === 0) return;
@@ -598,6 +599,7 @@ export function renderCompleteStroke(
usePressure: brushSettings.usePressure,
useVelocity: brushSettings.useVelocity,
useTilt,
+ tiltScale: brushSettings.tiltScale,
sizeSensor: brushSettings.sizeSensor,
opacitySensor: brushSettings.opacitySensor,
densitySensor: brushSettings.densitySensor,
@@ -629,7 +631,9 @@ export function renderCompleteStroke(
dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
useGpu: brushSettings.useGpu !== false,
underlyingCanvas: underlyingCanvas || ctx.canvas,
- sampler: brushSettings.colorMixing && underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
+ sampler: brushSettings.colorMixing
+ ? (explicitSampler || (underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined))
+ : undefined,
reservoir: brushSettings.colorMixing && !isEraser ? new PaintReservoir(strokeColor) : undefined,
isEraser: isEraser && !isBgEraser,
isBgEraser,
@@ -650,7 +654,9 @@ export function renderCompleteStroke(
colorStretch: brushSettings.colorStretch,
mixingMode: brushSettings.mixingMode,
underlyingCanvas: underlyingCanvas || ctx.canvas,
- sampler: brushSettings.colorMixing && underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
+ sampler: brushSettings.colorMixing
+ ? (explicitSampler || (underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined))
+ : undefined,
reservoir: brushSettings.colorMixing && !isEraser ? new PaintReservoir(strokeColor) : undefined,
alphaLocked,
isTransparentInk,
@@ -661,6 +667,7 @@ export function renderCompleteStroke(
dualTipImage: brushSettings.dualTipImage,
dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
useTilt,
+ tiltScale: brushSettings.tiltScale,
thicknessVertical: brushSettings.thicknessVertical,
flipH: brushSettings.flipH,
flipV: brushSettings.flipV,
diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.ts
index 7738d58..3439e64 100644
--- a/src/utils/colorMixingEngine.ts
+++ b/src/utils/colorMixingEngine.ts
@@ -714,15 +714,24 @@ export class PaintReservoir {
};
if (isPureSmudge) {
- // Pure Smudge / Smear: drags underlying pigment with zero fresh ink injection
- const pickupRate = Math.min(0.96, canvasAlpha * (0.35 + (1.0 - colorStretch) * 0.55) * pressureInfluence);
- const mixed = mixFn(currentColor, targetColor, pickupRate);
- this.r = mixed.r;
- this.g = mixed.g;
- this.b = mixed.b;
- this.a = Math.min(1.0, this.a * 0.7 + canvasAlpha * 0.3);
- this.isLoadedWithCanvasColor = true;
- this.cumulativeDistance = 0;
+ // Pure Smudge / Smear: drags underlying pigment with zero fresh foreground injection
+ if (!this.isLoadedWithCanvasColor) {
+ // First contact with painted canvas: snap reservoir cleanly to canvas pigment
+ this.r = targetColor.r;
+ this.g = targetColor.g;
+ this.b = targetColor.b;
+ this.a = canvasAlpha;
+ this.isLoadedWithCanvasColor = true;
+ this.cumulativeDistance = 0;
+ } else {
+ const pickupRate = Math.min(0.96, canvasAlpha * (0.35 + (1.0 - colorStretch) * 0.55) * pressureInfluence);
+ const mixed = mixFn(currentColor, targetColor, pickupRate);
+ this.r = mixed.r;
+ this.g = mixed.g;
+ this.b = mixed.b;
+ this.a = Math.min(1.0, this.a * 0.72 + canvasAlpha * 0.28);
+ this.cumulativeDistance = 0;
+ }
} else if (mixingMode === 'running_color') {
// Step 1: Absorb underlying canvas pigment into wet bristles (does not self-brighten on own trail)
const pickupScale = stepDist > 0 ? Math.min(1.0, Math.max(0.2, stepDist / 2.5)) : 1.0;
@@ -774,6 +783,11 @@ export class PaintReservoir {
}
} else {
// Moving into unpainted / dry area: apply Color Stretch decay
+ if (isPureSmudge && !this.isLoadedWithCanvasColor) {
+ // Pure blender on untouched transparent canvas must not emit foreground color
+ this.a = 0;
+ return { r: 0, g: 0, b: 0, alpha: 0, colorHex: '#000000' };
+ }
if (this.isLoadedWithCanvasColor && stepDist > 0) {
const stretchDistanceLimit = Math.max(24, colorStretch * 800);
const decayRate = 1.0 - Math.exp(-stepDist / stretchDistanceLimit);
@@ -820,7 +834,9 @@ export class PaintReservoir {
r: finalR,
g: finalG,
b: finalB,
- alpha: Math.max(0.005, Math.min(1.0, dabAlpha)),
+ alpha: isPureSmudge
+ ? Math.max(0, Math.min(1.0, dabAlpha))
+ : Math.max(0.005, Math.min(1.0, dabAlpha)),
colorHex: rgbToHex(finalR, finalG, finalB),
};
}
diff --git a/src/utils/pencilEngine.ts b/src/utils/pencilEngine.ts
index 5698c06..790bc3d 100644
--- a/src/utils/pencilEngine.ts
+++ b/src/utils/pencilEngine.ts
@@ -127,34 +127,57 @@ function sfc32(a: number, b: number, c: number, d: number) {
(function initPaperGrain() {
const rand = sfc32(0x9e3779b9, 0x243f6a88, 0xb7e15162, 0x8aed2a6b);
- // Generate 2D white & cellular noise seeds
- const white = new Float32Array(GRAIN_SIZE * GRAIN_SIZE);
- for (let i = 0; i < white.length; i++) {
- white[i] = rand();
- }
-
- // Multi-scale procedural synthesis
- for (let y = 0; y < GRAIN_SIZE; y++) {
- for (let x = 0; x < GRAIN_SIZE; x++) {
- // 1. High frequency micro-tooth (mineral surface)
- const n1 = white[y * GRAIN_SIZE + x];
-
- // 2. Medium frequency intertwined fibers (cellulose weave: slightly directional)
- const x2 = (x + Math.sin(y * 0.12) * 2) & GRAIN_MASK;
- const y2 = (y + Math.cos(x * 0.12) * 2) & GRAIN_MASK;
- const n2 = white[y2 * GRAIN_SIZE + x2];
+ // Build tileable periodic value-noise grids for smooth multi-octave cold-press paper synthesis
+ const makeGrid = (res: number) => {
+ const g = new Float32Array(res * res);
+ for (let i = 0; i < g.length; i++) g[i] = rand();
+ return g;
+ };
- // 3. Low frequency paper tooth clumps
- const x3 = (x >> 2) & (GRAIN_SIZE / 4 - 1);
- const y3 = (y >> 2) & (GRAIN_SIZE / 4 - 1);
- const n3 = white[y3 * GRAIN_SIZE + x3];
+ const samplePeriodic = (grid: Float32Array, res: number, fx: number, fy: number): number => {
+ const mask = res - 1;
+ const x0 = Math.floor(fx);
+ const y0 = Math.floor(fy);
+ const tx = fx - x0;
+ const ty = fy - y0;
+ // Smooth cubic Hermite interpolation eliminates grid-aligned banding & blockiness
+ const sx = tx * tx * (3 - 2 * tx);
+ const sy = ty * ty * (3 - 2 * ty);
+ const ix0 = x0 & mask;
+ const iy0 = y0 & mask;
+ const ix1 = (ix0 + 1) & mask;
+ const iy1 = (iy0 + 1) & mask;
+ const v00 = grid[iy0 * res + ix0];
+ const v10 = grid[iy0 * res + ix1];
+ const v01 = grid[iy1 * res + ix0];
+ const v11 = grid[iy1 * res + ix1];
+ const top = v00 + (v10 - v00) * sx;
+ const bot = v01 + (v11 - v01) * sx;
+ return top + (bot - top) * sy;
+ };
- // Combine octaves with weighted contrast curve
- const combined = n1 * 0.52 + n2 * 0.32 + n3 * 0.16;
+ const gCoarse = makeGrid(64); // 8px cold-press paper hills/valleys
+ const gMedium = makeGrid(128); // 4px primary cotton paper tooth
+ const gFine = makeGrid(256); // 2px interwoven cellulose fibers
+ const gMicro = makeGrid(512); // 1px mineral grit micro-tooth
- // Enhance paper tooth peak-to-valley contrast
- const curved = Math.pow(combined, 1.4);
- paperGrainTable[y * GRAIN_SIZE + x] = Math.min(255, Math.max(0, Math.round(curved * 255)));
+ for (let y = 0; y < GRAIN_SIZE; y++) {
+ const row = y * GRAIN_SIZE;
+ for (let x = 0; x < GRAIN_SIZE; x++) {
+ // Slight anisotropic weave warp for natural organic paper fibers
+ const warpX = x + Math.sin(y * 0.09817477) * 1.4;
+ const warpY = y + Math.cos(x * 0.09817477) * 1.4;
+
+ const nCoarse = samplePeriodic(gCoarse, 64, x * 0.125, y * 0.125);
+ const nMedium = samplePeriodic(gMedium, 128, warpX * 0.25, warpY * 0.25);
+ const nFine = samplePeriodic(gFine, 256, warpX * 0.5, warpY * 0.5);
+ const nMicro = gMicro[row + x];
+
+ const combined = nCoarse * 0.28 + nMedium * 0.36 + nFine * 0.24 + nMicro * 0.12;
+ // S-curve contrast shaping for crisp tooth peaks and realistic paper valleys
+ const stretched = Math.max(0, Math.min(1, (combined - 0.18) / 0.64));
+ const curved = Math.pow(stretched, 1.18);
+ paperGrainTable[row + x] = Math.min(255, Math.max(0, Math.round(curved * 255)));
}
}
})();
diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.ts
index 0ac34f0..ed103df 100644
--- a/src/utils/presetBrushes.ts
+++ b/src/utils/presetBrushes.ts
@@ -1,305 +1,84 @@
-import { BrushPresetId, BrushSettings } from '../types/editor';
-import { dabHashFloat } from '../engine/CspBrushEngine';
-
-export type BrushCategory = 'pencil-line' | 'color-paint';
+import {
+ BrushCategory,
+ BrushPresetId,
+ BrushSettings,
+ DEFAULT_BRUSH_DYNAMICS,
+} from '../types/editor';
+import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/CspBrushEngine';
+import {
+ generateRealGPenTip,
+ generateTexturedPenTip,
+ generateCalligraphyTip,
+ generateMechanicalPencilTip,
+ generateHb2bPencilTip,
+ generate6b8bPencilTip,
+ generateCharcoalTip,
+ generateChalkTip,
+ generateOilBristleTip,
+ generateThickOilTip,
+ generateChalkPaintTip,
+ generateNoiseShaderTip,
+ generateFinePaperTexture,
+ generateSketchPaperTexture,
+ generateCharcoalPaperTexture,
+ generateCanvasWeaveTexture,
+ generateNoiseGrainTexture,
+} from './proceduralBrushTips';
export interface BuiltinBrushDefinition {
id: BrushPresetId;
- name: string;
category: BrushCategory;
- categoryName: string;
+ name: string;
badge: string;
badgeBg: string;
badgeText: string;
badgeBorder: string;
desc: string;
- icon: 'pencil' | 'paintbrush' | 'palette' | 'square';
+ icon: 'pen' | 'pencil' | 'paintbrush';
settings: Partial<BrushSettings>;
tipGenerator?: () => string; // Returns Base64 PNG data URL
+ paperTextureGenerator?: () => string; // Returns seamless Base64 PNG data URL
}
-// -------------------------------------------------------------
-// Procedural High-Resolution Tip Mask Generators
-// -------------------------------------------------------------
-
-let _squareTipDataUrl: string | null = null;
-export function getSquareTipDataUrl(): string {
- if (_squareTipDataUrl) return _squareTipDataUrl;
- const canvas = document.createElement('canvas');
- canvas.width = 64;
- canvas.height = 64;
- const ctx = canvas.getContext('2d');
- if (!ctx || typeof canvas.toDataURL !== 'function') return '';
- ctx.clearRect(0, 0, 64, 64);
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(4, 4, 56, 56);
- _squareTipDataUrl = canvas.toDataURL('image/png');
- return _squareTipDataUrl;
-}
-
-let _realGPenTipDataUrl: string | null = null;
-export function getRealGPenTipDataUrl(): string {
- if (_realGPenTipDataUrl) return _realGPenTipDataUrl;
- const size = 96;
- const canvas = document.createElement('canvas');
- canvas.width = size;
- canvas.height = size;
- const ctx = canvas.getContext('2d');
- if (!ctx || typeof canvas.toDataURL !== 'function' || typeof ctx.createImageData !== 'function') {
- return '';
- }
-
- const imgData = ctx.createImageData(size, size);
- const data = imgData.data;
- const half = size * 0.5;
- const maxR = half - 3;
-
- for (let y = 0; y < size; y++) {
- const dy = y - half;
- for (let x = 0; x < size; x++) {
- const dx = x - half;
- const r = Math.hypot(dx, dy) / maxR;
- if (r > 1.08) continue;
-
- const angleIdx = Math.round(((Math.atan2(dy, dx) + Math.PI) / (Math.PI * 2)) * 96);
- const angularTooth =
- (dabHashFloat(angleIdx, 0, 1, 701) - 0.5) * 0.14 +
- (dabHashFloat(Math.floor(angleIdx * 0.5), 1, 2, 709) - 0.5) * 0.1;
- const microGrain = (dabHashFloat(x, y, 3, 719) - 0.5) * 0.12;
- const effEdge = 0.9 + angularTooth + microGrain * 0.5;
-
- let alpha = 0;
- if (r <= effEdge - 0.08) {
- alpha = 1.0;
- } else if (r < effEdge + 0.08) {
- const t = (effEdge + 0.08 - r) / 0.16;
- alpha = t * t * (3 - 2 * t);
- }
-
- if (alpha > 0.01) {
- const idx = (y * size + x) * 4;
- data[idx] = 255;
- data[idx + 1] = 255;
- data[idx + 2] = 255;
- data[idx + 3] = Math.round(alpha * 255);
- }
- }
- }
-
- ctx.putImageData(imgData, 0, 0);
- _realGPenTipDataUrl = canvas.toDataURL('image/png');
- return _realGPenTipDataUrl;
+export interface BuiltinBrushSection {
+ id: BrushCategory;
+ label: string;
}
-let _bristleTipDataUrl: string | null = null;
-export function getBristleTipDataUrl(): string {
- if (_bristleTipDataUrl) return _bristleTipDataUrl;
- const size = 96;
- const canvas = document.createElement('canvas');
- canvas.width = size;
- canvas.height = size;
- const ctx = canvas.getContext('2d');
- if (!ctx || typeof canvas.toDataURL !== 'function' || typeof ctx.createImageData !== 'function') {
- return '';
- }
-
- const imgData = ctx.createImageData(size, size);
- const data = imgData.data;
- const half = size * 0.5;
- const maxR = half - 4;
-
- // Deterministic multi-filament hog-bristle cluster
- const filaments: { cx: number; cy: number; rad: number; str: number }[] = [];
- const count = 42;
- for (let i = 0; i < count; i++) {
- const u = dabHashFloat(i, 11, i, 811);
- const v = dabHashFloat(i, 23, i, 823);
- const rr = maxR * 0.86 * Math.sqrt(u);
- const th = v * Math.PI * 2;
- filaments.push({
- cx: half + rr * Math.cos(th),
- cy: half + rr * Math.sin(th) * 0.68,
- rad: 2.2 + dabHashFloat(i, 37, i, 829) * 3.8,
- str: 0.55 + dabHashFloat(i, 41, i, 839) * 0.45,
- });
- }
-
- for (let y = 0; y < size; y++) {
- for (let x = 0; x < size; x++) {
- let acc = 0;
- for (let f = 0; f < filaments.length; f++) {
- const fil = filaments[f];
- const d = Math.hypot(x - fil.cx, y - fil.cy) / fil.rad;
- if (d < 1.0) {
- const w = (1.0 - d) * (1.0 - d) * fil.str;
- if (w > acc) acc = Math.min(1.0, acc * 0.35 + w);
- }
- }
- if (acc > 0.02) {
- const idx = (y * size + x) * 4;
- data[idx] = 255;
- data[idx + 1] = 255;
- data[idx + 2] = 255;
- data[idx + 3] = Math.min(255, Math.round(acc * 255));
- }
- }
- }
-
- ctx.putImageData(imgData, 0, 0);
- _bristleTipDataUrl = canvas.toDataURL('image/png');
- return _bristleTipDataUrl;
-}
+export const BUILTIN_BRUSH_SECTIONS: BuiltinBrushSection[] = [
+ { id: 'pen', label: 'Pen' },
+ { id: 'sketch', label: 'Sketch' },
+ { id: 'brush', label: 'Brush' },
+];
-// Preloaded images cache
const preloadedTipImages = new Map<string, HTMLImageElement>();
export function getPreloadedBuiltinTipImage(dataUrl: string): HTMLImageElement | undefined {
if (!dataUrl || typeof Image === 'undefined') return undefined;
- if (preloadedTipImages.has(dataUrl)) {
- return preloadedTipImages.get(dataUrl);
- }
+ const cached = preloadedTipImages.get(dataUrl);
+ if (cached) return cached;
const img = new Image();
img.src = dataUrl;
+ if (typeof img.decode === 'function') {
+ img.decode().catch(() => {});
+ }
preloadedTipImages.set(dataUrl, img);
return img;
}
-// Eagerly generate and preload built-in brush tip textures at startup
-if (typeof document !== 'undefined' && typeof Image !== 'undefined') {
- try {
- const square = getSquareTipDataUrl();
- if (square) getPreloadedBuiltinTipImage(square);
- const realG = getRealGPenTipDataUrl();
- if (realG) getPreloadedBuiltinTipImage(realG);
- const bristle = getBristleTipDataUrl();
- if (bristle) getPreloadedBuiltinTipImage(bristle);
- } catch {
- // Headless test environments may mock document.createElement minimally
- }
-}
-
-// -------------------------------------------------------------
-// Built-in Brushes Directory organized by Category
-// -------------------------------------------------------------
-
export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
- // ============================================================
- // CATEGORY 1: PENCIL & LINE
- // ============================================================
- {
- id: 'pencil-2b',
- name: 'Pencil (2B)',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
- badge: '2B',
- badgeBg: 'bg-amber-500/15',
- badgeText: 'text-amber-300',
- badgeBorder: 'border-amber-500/30',
- desc: 'Soft & Black Sketching',
- icon: 'pencil',
- settings: {
- size: 3.5,
- minSizeFactor: 0.25,
- flow: 0.74,
- hardness: 0.8,
- grain: 0.95,
- spacing: 0.08,
- usePressure: true,
- useTilt: true,
- smoothing: true,
- stabilization: 15,
- sharpCorners: true,
- useGpu: true,
- },
- },
- {
- id: 'pencil-4b',
- name: 'Pencil (4B)',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
- badge: '4B',
- badgeBg: 'bg-orange-500/15',
- badgeText: 'text-orange-300',
- badgeBorder: 'border-orange-500/30',
- desc: 'Extra Soft & Velvety Carbon',
- icon: 'pencil',
- settings: {
- size: 4.5,
- minSizeFactor: 0.2,
- flow: 0.88,
- hardness: 0.7,
- grain: 0.98,
- spacing: 0.08,
- usePressure: true,
- useTilt: true,
- smoothing: true,
- stabilization: 15,
- sharpCorners: true,
- useGpu: true,
- },
- },
- {
- id: 'pencil-hb',
- name: 'Pencil (HB)',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
- badge: 'HB',
- badgeBg: 'bg-emerald-500/15',
- badgeText: 'text-emerald-300',
- badgeBorder: 'border-emerald-500/30',
- desc: 'Medium Classic',
- icon: 'pencil',
- settings: {
- size: 3.0,
- minSizeFactor: 0.3,
- flow: 0.65,
- hardness: 0.82,
- grain: 0.92,
- spacing: 0.08,
- usePressure: true,
- useTilt: true,
- smoothing: true,
- stabilization: 15,
- sharpCorners: true,
- useGpu: true,
- },
- },
- {
- id: 'pencil-f',
- name: 'Pencil (F)',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
- badge: 'F',
- badgeBg: 'bg-sky-500/15',
- badgeText: 'text-sky-300',
- badgeBorder: 'border-sky-500/30',
- desc: 'Firm & Fine Lead',
- icon: 'pencil',
- settings: {
- size: 2.5,
- minSizeFactor: 0.35,
- flow: 0.55,
- hardness: 0.85,
- grain: 0.88,
- spacing: 0.08,
- usePressure: true,
- useTilt: true,
- smoothing: true,
- stabilization: 15,
- sharpCorners: true,
- useGpu: true,
- },
- },
+ // =========================================================================
+ // PEN SECTION
+ // =========================================================================
{
id: 'g-pen',
- name: 'G-Pen (Manga Ink)',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
+ category: 'pen',
+ name: 'G-Pen',
badge: 'Pen',
badgeBg: 'bg-indigo-500/15',
badgeText: 'text-indigo-300',
badgeBorder: 'border-indigo-500/30',
desc: 'Sharp Pressure Taper & Inking',
- icon: 'paintbrush',
+ icon: 'pen',
settings: {
size: 8,
minSizeFactor: 0.04,
@@ -318,409 +97,742 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
},
{
id: 'real-g-pen',
- name: 'Real G-Pen (Textured Nib)',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
- badge: 'Real G',
+ category: 'pen',
+ name: 'Real G-Pen',
+ badge: 'Pen',
badgeBg: 'bg-indigo-500/15',
- badgeText: 'text-indigo-200',
- badgeBorder: 'border-indigo-400/30',
- desc: 'Organic Analog Manga Nib & Tooth',
- icon: 'paintbrush',
- tipGenerator: getRealGPenTipDataUrl,
+ badgeText: 'text-indigo-300',
+ badgeBorder: 'border-indigo-500/30',
+ desc: 'Organic Manga Nib with Subtle Ink-on-Paper Edge Texture',
+ icon: 'pen',
+ tipGenerator: generateRealGPenTip,
settings: {
- size: 9,
- minSizeFactor: 0.03,
- flow: 1.0,
+ size: 8,
+ minSizeFactor: 0.05,
+ flow: 0.96,
opacity: 1.0,
- hardness: 1.0,
- antiAlias: 1,
+ hardness: 0.96,
+ antiAlias: 2,
spacing: 0.045,
- grain: 0.38,
- paperTextureMode: 'subtract',
- customTipAngleDynamics: 'direction',
stabilization: 18,
sharpCorners: true,
usePressure: true,
useTilt: false,
smoothing: true,
+ pressureCurve: CSP_PRESSURE_CURVE_PRESETS['g-pen'].points,
+ customTipAngleDynamics: 'random',
+ flipH: 'random',
+ flipV: 'random',
+ grain: 0.24,
+ textureDensity: 0.24,
+ paperTextureMode: 'outline',
+ paperTextureScale: 0.85,
+ paperTextureContrast: 25,
+ taper: {
+ useIn: false,
+ inLength: 0,
+ inRatio: 0,
+ useOut: true,
+ outLength: 10,
+ outRatio: 0.25,
+ endingSharpness: 0.72,
+ affectSize: true,
+ },
useGpu: true,
},
},
{
- id: 'maru-pen',
- name: 'Maru Pen (Mapping Pen)',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
- badge: 'Maru',
- badgeBg: 'bg-violet-500/15',
- badgeText: 'text-violet-300',
- badgeBorder: 'border-violet-500/30',
- desc: 'Delicate Manga Crosshatching & Hairlines',
- icon: 'paintbrush',
+ id: 'textured-pen',
+ category: 'pen',
+ name: 'Textured Pen',
+ badge: 'Pen',
+ badgeBg: 'bg-indigo-500/15',
+ badgeText: 'text-indigo-300',
+ badgeBorder: 'border-indigo-500/30',
+ desc: 'Expressive Dry-Edge Inking Pen with Paper Tooth Breakup',
+ icon: 'pen',
+ tipGenerator: generateTexturedPenTip,
settings: {
- size: 4.5,
- minSizeFactor: 0.02,
- flow: 1.0,
+ size: 9,
+ minSizeFactor: 0.08,
+ flow: 0.92,
opacity: 1.0,
- hardness: 1.0,
+ hardness: 0.92,
antiAlias: 2,
- spacing: 0.035,
- stabilization: 24,
+ spacing: 0.055,
+ stabilization: 15,
sharpCorners: true,
usePressure: true,
useTilt: false,
smoothing: true,
+ customTipAngleDynamics: 'random',
+ flipH: 'random',
+ flipV: 'random',
+ grain: 0.56,
+ textureDensity: 0.56,
+ paperTextureMode: 'subtract',
+ paperTextureScale: 1.0,
+ paperTextureContrast: 38,
+ opacitySensor: { usePressure: true, pressureMin: 0.55 },
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ sizeJitter: 0.08,
+ angleJitter: 1.0,
+ flowJitter: 0.12,
+ },
useGpu: true,
},
},
{
- id: 'turnip-pen',
- name: 'Turnip Pen (Kabura Pen)',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
- badge: 'Turnip',
- badgeBg: 'bg-teal-500/15',
- badgeText: 'text-teal-300',
- badgeBorder: 'border-teal-500/30',
- desc: 'Uniform Contours & Manga Character Lineart',
- icon: 'paintbrush',
+ id: 'dot-pen',
+ category: 'pen',
+ name: 'Dot Pen',
+ badge: 'Pen',
+ badgeBg: 'bg-indigo-500/15',
+ badgeText: 'text-indigo-300',
+ badgeBorder: 'border-indigo-500/30',
+ desc: '1-Bit Pixel Crisp Binary Pen (Zero Anti-Aliasing)',
+ icon: 'pen',
settings: {
- size: 9.0,
- minSizeFactor: 0.28,
+ size: 1,
+ minSizeFactor: 1.0,
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
- antiAlias: 2,
- spacing: 0.05,
- stabilization: 18,
+ antiAlias: 0,
+ spacing: 0.04,
+ stabilization: 0,
sharpCorners: true,
- usePressure: true,
+ usePressure: false,
useTilt: false,
- smoothing: true,
- useGpu: true,
+ smoothing: false,
+ useGpu: false,
},
},
{
- id: 'calligraphy-pen',
- name: 'Calligraphy Pen',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
- badge: 'Calli',
- badgeBg: 'bg-fuchsia-500/15',
- badgeText: 'text-fuchsia-300',
- badgeBorder: 'border-fuchsia-500/30',
- desc: '45-Degree Flat Chisel Nib',
- icon: 'paintbrush',
+ id: 'calligraphy',
+ category: 'pen',
+ name: 'Calligraphy',
+ badge: 'Pen',
+ badgeBg: 'bg-indigo-500/15',
+ badgeText: 'text-indigo-300',
+ badgeBorder: 'border-indigo-500/30',
+ desc: 'Broad-Edge Angled Chisel Nib with Thick/Thin Directional Contrast',
+ icon: 'pen',
+ tipGenerator: generateCalligraphyTip,
settings: {
- size: 14,
- minSizeFactor: 0.35,
+ size: 18,
+ minSizeFactor: 0.45,
flow: 1.0,
opacity: 1.0,
- hardness: 1.0,
- thickness: 0.22,
- customTipAngle: 45,
- customTipAngleDynamics: 'none',
+ hardness: 0.98,
antiAlias: 2,
- spacing: 0.035,
- stabilization: 22,
+ thickness: 0.18,
+ customTipAngle: -38,
+ customTipAngleDynamics: 'none',
+ spacing: 0.04,
+ stabilization: 16,
sharpCorners: true,
usePressure: true,
useTilt: false,
smoothing: true,
+ pressureCurve: CSP_PRESSURE_CURVE_PRESETS.firm.points,
useGpu: true,
},
},
+
+ // =========================================================================
+ // SKETCH SECTION
+ // =========================================================================
{
- id: 'round',
- name: 'Round Brush',
- category: 'pencil-line',
- categoryName: 'Pencil & Line',
- badge: 'Ink',
- badgeBg: 'bg-blue-500/15',
- badgeText: 'text-blue-300',
- badgeBorder: 'border-blue-500/30',
- desc: 'Smooth Digital Inking',
- icon: 'paintbrush',
+ id: 'mechanical-pencil',
+ category: 'sketch',
+ name: 'Mechanical Pencil',
+ badge: 'Sketch',
+ badgeBg: 'bg-amber-500/15',
+ badgeText: 'text-amber-300',
+ badgeBorder: 'border-amber-500/30',
+ desc: 'Firm 0.5mm Lead — Thin, Tilt-Independent, Crisp Edge & Minimal Grain',
+ icon: 'pencil',
+ tipGenerator: generateMechanicalPencilTip,
+ paperTextureGenerator: generateFinePaperTexture,
settings: {
- size: 14,
- minSizeFactor: 0.15,
- flow: 0.85,
- opacity: 1.0,
- hardness: 0.9,
- spacing: 0.08,
- stabilization: 15,
+ size: 2.8,
+ minSizeFactor: 0.72,
+ flow: 0.44,
+ opacity: 0.94,
+ hardness: 0.95,
+ antiAlias: 1,
+ spacing: 0.1,
+ stabilization: 6,
sharpCorners: true,
usePressure: true,
useTilt: false,
smoothing: true,
+ pressureCurve: CSP_PRESSURE_CURVE_PRESETS.firm.points,
+ opacitySensor: { usePressure: true, pressureMin: 0.22 },
+ densitySensor: { usePressure: true, pressureMin: 0.35 },
+ customTipAngleDynamics: 'random',
+ flipH: 'random',
+ flipV: 'random',
+ grain: 0.34,
+ textureDensity: 0.34,
+ paperTextureMode: 'compare',
+ paperTextureScale: 0.7,
+ paperTextureContrast: 22,
useGpu: true,
},
},
- // ============================================================
- // CATEGORY 2: COLOR & PAINT
- // ============================================================
{
- id: 'airbrush-soft',
- name: 'Soft Airbrush',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Air',
- badgeBg: 'bg-pink-500/15',
- badgeText: 'text-pink-300',
- badgeBorder: 'border-pink-500/30',
- desc: 'Silky Gaussian Radial Falloff & Delicate Glaze',
- icon: 'paintbrush',
+ id: 'pencil-hb-2b',
+ category: 'sketch',
+ name: 'HB / 2B Pencil',
+ badge: 'Sketch',
+ badgeBg: 'bg-amber-500/15',
+ badgeText: 'text-amber-300',
+ badgeBorder: 'border-amber-500/30',
+ desc: 'Classic Graphite — Moderate Tooth, Smooth Pressure Flow & Gentle Tilt Shading',
+ icon: 'pencil',
+ tipGenerator: generateHb2bPencilTip,
+ paperTextureGenerator: generateSketchPaperTexture,
settings: {
- size: 48,
- minSizeFactor: 0.35,
- flow: 0.28,
- opacity: 1.0,
- hardness: 0.0,
- spacing: 0.08,
- adjustDensityByGap: true,
- stabilization: 10,
+ size: 5.5,
+ minSizeFactor: 0.45,
+ flow: 0.38,
+ opacity: 0.96,
+ hardness: 0.78,
+ antiAlias: 2,
+ spacing: 0.13,
+ stabilization: 5,
+ sharpCorners: true,
usePressure: true,
- useTilt: false,
+ useTilt: true,
+ tiltScale: 0.95,
smoothing: true,
+ pressureCurve: [
+ [0, 0],
+ [0.3, 0.24],
+ [0.7, 0.7],
+ [1, 1],
+ ],
+ opacitySensor: { usePressure: true, pressureMin: 0.14 },
+ densitySensor: { usePressure: true, pressureMin: 0.25 },
+ customTipAngleDynamics: 'random',
+ flipH: 'random',
+ flipV: 'random',
+ grain: 0.64,
+ textureDensity: 0.64,
+ paperTextureMode: 'compare',
+ paperTextureScale: 0.75,
+ paperTextureContrast: 28,
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ sizeJitter: 0.06,
+ flowJitter: 0.14,
+ },
useGpu: true,
},
},
{
- id: 'spray-tone',
- name: 'Tone Spray Airbrush',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Spray',
- badgeBg: 'bg-rose-500/15',
- badgeText: 'text-rose-300',
- badgeBorder: 'border-rose-500/30',
- desc: 'Crisp Binary Manga Tone Stipple Spray',
- icon: 'paintbrush',
- tipGenerator: getSquareTipDataUrl,
+ id: 'pencil-6b-8b',
+ category: 'sketch',
+ name: '6B / 8B Pencil',
+ badge: 'Sketch',
+ badgeBg: 'bg-amber-500/15',
+ badgeText: 'text-amber-300',
+ badgeBorder: 'border-amber-500/30',
+ desc: 'Rich Soft Graphite — Strong Paper Tooth, Heavy-Pressure Clog & Broad Tilt Edge',
+ icon: 'pencil',
+ tipGenerator: generate6b8bPencilTip,
+ paperTextureGenerator: generateSketchPaperTexture,
settings: {
- size: 44,
- minSizeFactor: 0.4,
- flow: 0.95,
+ size: 9,
+ minSizeFactor: 0.36,
+ flow: 0.56,
opacity: 1.0,
- hardness: 1.0,
- antiAlias: 0,
+ hardness: 0.65,
+ antiAlias: 2,
+ thickness: 0.7,
spacing: 0.14,
- spray: {
- enabled: true,
- size: 2,
- density: 12,
- bias: 0.3,
+ stabilization: 4,
+ sharpCorners: true,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 2.1,
+ smoothing: true,
+ pressureCurve: [
+ [0, 0],
+ [0.25, 0.28],
+ [0.6, 0.74],
+ [1, 1],
+ ],
+ opacitySensor: { usePressure: true, pressureMin: 0.18 },
+ densitySensor: { usePressure: true, pressureMin: 0.3 },
+ customTipAngleDynamics: 'direction-random',
+ customTipRotationRandomScale: 0.28,
+ flipH: 'random',
+ flipV: 'random',
+ grain: 0.86,
+ textureDensity: 0.86,
+ paperTextureMode: 'compare',
+ paperTextureScale: 0.9,
+ paperTextureContrast: 38,
+ paperTextureBrightness: -4,
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ sizeJitter: 0.1,
+ flowJitter: 0.18,
},
- stabilization: 8,
+ useGpu: true,
+ },
+ },
+ {
+ id: 'charcoal-pencil',
+ category: 'sketch',
+ name: 'Charcoal Pencil',
+ badge: 'Sketch',
+ badgeBg: 'bg-amber-500/15',
+ badgeText: 'text-amber-300',
+ badgeBorder: 'border-amber-500/30',
+ desc: 'Deep Matte Dry Carbon — Jagged Edge, Aggressive Tooth, Edge Crumbs & Tilt Shading',
+ icon: 'pencil',
+ tipGenerator: generateCharcoalTip,
+ paperTextureGenerator: generateCharcoalPaperTexture,
+ settings: {
+ size: 16,
+ minSizeFactor: 0.3,
+ flow: 0.68,
+ opacity: 1.0,
+ hardness: 0.5,
+ antiAlias: 2,
+ thickness: 0.72,
+ spacing: 0.18,
+ stabilization: 3,
+ sharpCorners: false,
usePressure: true,
- useTilt: false,
+ useTilt: true,
+ tiltScale: 2.2,
smoothing: true,
+ pressureCurve: [
+ [0, 0],
+ [0.22, 0.3],
+ [0.55, 0.76],
+ [1, 1],
+ ],
+ opacitySensor: { usePressure: true, pressureMin: 0.2 },
+ densitySensor: { usePressure: true, pressureMin: 0.32 },
+ customTipAngleDynamics: 'random',
+ flipH: 'random',
+ flipV: 'random',
+ grain: 0.92,
+ textureDensity: 0.92,
+ paperTextureMode: 'compare',
+ paperTextureScale: 1.0,
+ paperTextureContrast: 48,
+ paperTextureBrightness: -6,
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ sizeJitter: 0.2,
+ angleJitter: 1.0,
+ roundnessJitter: 0.16,
+ scatter: 0.05,
+ scatterBothAxes: true,
+ count: 1,
+ flowJitter: 0.22,
+ },
useGpu: true,
},
},
{
- id: 'flat-marker',
- name: 'Flat Marker (Copic)',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Marker',
- badgeBg: 'bg-cyan-500/15',
- badgeText: 'text-cyan-300',
- badgeBorder: 'border-cyan-500/30',
- desc: 'Compare-Density Even Wash Chisel Marker',
- icon: 'square',
+ id: 'standard-chalk',
+ category: 'sketch',
+ name: 'Standard Chalk',
+ badge: 'Sketch',
+ badgeBg: 'bg-amber-500/15',
+ badgeText: 'text-amber-300',
+ badgeBorder: 'border-amber-500/30',
+ desc: 'Powdery Dry Chalk Stick — Heavy Mineral Tooth & Tilt Shading',
+ icon: 'pencil',
+ tipGenerator: generateChalkTip,
+ paperTextureGenerator: generateCharcoalPaperTexture,
settings: {
- size: 28,
- minSizeFactor: 0.65,
- flow: 0.58,
- opacity: 0.78,
- hardness: 0.92,
- thickness: 0.32,
- customTipAngle: 30,
- customTipAngleDynamics: 'none',
- blendTipsMode: 'compare',
- adjustDensityByGap: true,
- spacing: 0.04,
- stabilization: 12,
+ size: 22,
+ minSizeFactor: 0.45,
+ flow: 0.52,
+ opacity: 0.96,
+ hardness: 0.6,
+ antiAlias: 2,
+ thickness: 0.62,
+ customTipAngle: 18,
+ customTipAngleDynamics: 'direction-random',
+ customTipRotationRandomScale: 0.18,
+ flipH: 'random',
+ flipV: 'random',
+ spacing: 0.16,
+ stabilization: 4,
+ sharpCorners: false,
usePressure: true,
- useTilt: false,
+ useTilt: true,
+ tiltScale: 1.7,
smoothing: true,
+ opacitySensor: { usePressure: true, pressureMin: 0.18 },
+ grain: 0.88,
+ textureDensity: 0.88,
+ paperTextureMode: 'compare',
+ paperTextureScale: 1.05,
+ paperTextureContrast: 44,
+ paperTextureBrightness: -4,
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ sizeJitter: 0.08,
+ angleJitter: 0.15,
+ flowJitter: 0.16,
+ scatter: 0.03,
+ },
useGpu: true,
},
},
+
+ // =========================================================================
+ // BRUSH SECTION (COLORING & PAINTING)
+ // =========================================================================
{
- id: 'opaque-watercolor',
- name: 'Opaque Watercolor',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Water',
- badgeBg: 'bg-sky-500/15',
- badgeText: 'text-sky-300',
- badgeBorder: 'border-sky-500/30',
- desc: 'Creamy Perceptual OKLab Blending Brush',
- icon: 'palette',
+ id: 'oil-painting',
+ category: 'brush',
+ name: 'Oil Painting Brush',
+ badge: 'Brush',
+ badgeBg: 'bg-emerald-500/15',
+ badgeText: 'text-emerald-300',
+ badgeBorder: 'border-emerald-500/30',
+ desc: 'Natural Bristle Oil — Perceptual Pigment Mixing & Smooth Color Stretch',
+ icon: 'paintbrush',
+ tipGenerator: generateOilBristleTip,
+ paperTextureGenerator: generateCanvasWeaveTexture,
settings: {
- size: 26,
- minSizeFactor: 0.28,
- flow: 0.74,
+ size: 32,
+ minSizeFactor: 0.35,
+ flow: 0.88,
opacity: 1.0,
- hardness: 0.45,
+ hardness: 0.75,
+ antiAlias: 2,
+ thickness: 0.85,
spacing: 0.06,
+ stabilization: 8,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 0.9,
+ smoothing: true,
+ customTipAngleDynamics: 'direction',
+ flipH: 'none',
+ flipV: 'alternate',
colorMixing: true,
perceptualMixing: true,
mixingMode: 'blend',
- amountOfPaint: 0.58,
- densityOfPaint: 0.75,
+ amountOfPaint: 0.62,
+ densityOfPaint: 0.82,
colorStretch: 0.68,
- stabilization: 12,
- usePressure: true,
- useTilt: false,
- smoothing: true,
+ grain: 0.22,
+ textureDensity: 0.22,
+ paperTextureMode: 'multiply',
+ paperTextureScale: 1.2,
+ opacitySensor: { usePressure: true, pressureMin: 0.35 },
useGpu: true,
},
},
{
- id: 'transparent-watercolor',
- name: 'Transparent Watercolor',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Wash',
- badgeBg: 'bg-blue-500/15',
- badgeText: 'text-blue-200',
- badgeBorder: 'border-blue-400/30',
- desc: 'Capillary Wet-Edge Rim & Cold-Press Grain',
- icon: 'palette',
+ id: 'thick-oil-painting',
+ category: 'brush',
+ name: 'Thick Oil Painting',
+ badge: 'Brush',
+ badgeBg: 'bg-emerald-500/15',
+ badgeText: 'text-emerald-300',
+ badgeBorder: 'border-emerald-500/30',
+ desc: 'Heavy Impasto Flat Bristles — Loaded Pigment Ridges & Rich Paint Drag',
+ icon: 'paintbrush',
+ tipGenerator: generateThickOilTip,
+ paperTextureGenerator: generateCanvasWeaveTexture,
settings: {
- size: 32,
- minSizeFactor: 0.32,
- flow: 0.44,
- opacity: 0.9,
- hardness: 0.35,
- spacing: 0.06,
- blendTipsMode: 'compare',
- adjustDensityByGap: true,
- grain: 0.45,
- paperTextureMode: 'multiply',
- wetEdge: 0.65,
- wetEdgeRadius: 3.5,
- wetEdgeAlphaPower: 35,
- wetEdgeValuePower: 18,
+ size: 38,
+ minSizeFactor: 0.45,
+ flow: 0.96,
+ opacity: 1.0,
+ hardness: 0.9,
+ antiAlias: 2,
+ thickness: 0.62,
+ spacing: 0.055,
+ stabilization: 10,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.1,
+ smoothing: true,
+ customTipAngleDynamics: 'direction',
+ flipH: 'none',
+ flipV: 'none',
colorMixing: true,
perceptualMixing: true,
mixingMode: 'running_color',
- amountOfPaint: 0.45,
- densityOfPaint: 0.55,
- colorStretch: 0.72,
- stabilization: 12,
- usePressure: true,
- useTilt: false,
- smoothing: true,
+ amountOfPaint: 0.78,
+ densityOfPaint: 0.96,
+ colorStretch: 0.82,
+ grain: 0.3,
+ textureDensity: 0.3,
+ paperTextureMode: 'multiply',
+ paperTextureScale: 1.35,
+ opacitySensor: { usePressure: true, pressureMin: 0.55 },
useGpu: true,
},
},
{
- id: 'oil-paint',
- name: 'Thick Oil Paint',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Oil',
- badgeBg: 'bg-amber-500/15',
- badgeText: 'text-amber-300',
- badgeBorder: 'border-amber-500/30',
- desc: 'Directional Hog-Bristle Impasto Mixing',
- icon: 'palette',
- tipGenerator: getBristleTipDataUrl,
+ id: 'chalk-painting',
+ category: 'brush',
+ name: 'Chalk Painting',
+ badge: 'Brush',
+ badgeBg: 'bg-emerald-500/15',
+ badgeText: 'text-emerald-300',
+ badgeBorder: 'border-emerald-500/30',
+ desc: 'Painterly Textured Chalk — Blended Pigments with Dry Gritty Tooth',
+ icon: 'paintbrush',
+ tipGenerator: generateChalkPaintTip,
+ paperTextureGenerator: generateCharcoalPaperTexture,
settings: {
- size: 30,
- minSizeFactor: 0.3,
- flow: 0.92,
+ size: 34,
+ minSizeFactor: 0.32,
+ flow: 0.85,
opacity: 1.0,
- hardness: 0.95,
- spacing: 0.045,
- customTipAngleDynamics: 'direction',
- grain: 0.25,
- paperTextureMode: 'subtract',
+ hardness: 0.72,
+ antiAlias: 2,
+ thickness: 0.74,
+ spacing: 0.065,
+ stabilization: 6,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.2,
+ smoothing: true,
+ customTipAngleDynamics: 'direction-random',
+ customTipRotationRandomScale: 0.18,
+ flipH: 'random',
+ flipV: 'random',
colorMixing: true,
perceptualMixing: true,
mixingMode: 'blend',
- amountOfPaint: 0.74,
- densityOfPaint: 0.88,
- colorStretch: 0.8,
- stabilization: 12,
+ amountOfPaint: 0.65,
+ densityOfPaint: 0.86,
+ colorStretch: 0.58,
+ grain: 0.52,
+ textureDensity: 0.52,
+ paperTextureMode: 'multiply',
+ paperTextureScale: 1.25,
+ paperTextureContrast: 32,
+ opacitySensor: { usePressure: true, pressureMin: 0.25 },
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ sizeJitter: 0.06,
+ angleJitter: 0.12,
+ flowJitter: 0.1,
+ },
+ useGpu: true,
+ },
+ },
+ {
+ id: 'blend-brush',
+ category: 'brush',
+ name: 'Blend Brush',
+ badge: 'Brush',
+ badgeBg: 'bg-emerald-500/15',
+ badgeText: 'text-emerald-300',
+ badgeBorder: 'border-emerald-500/30',
+ desc: 'Pure Soft Color Blender — Smooths & Harmonizes Existing Paint',
+ icon: 'paintbrush',
+ settings: {
+ size: 36,
+ minSizeFactor: 0.45,
+ flow: 0.65,
+ opacity: 1.0,
+ hardness: 0.25,
+ antiAlias: 3,
+ spacing: 0.06,
+ stabilization: 8,
+ sharpCorners: false,
usePressure: true,
useTilt: false,
smoothing: true,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'smear',
+ amountOfPaint: 0.0,
+ densityOfPaint: 0.72,
+ colorStretch: 0.74,
+ grain: 0,
+ textureDensity: 0,
+ opacitySensor: { usePressure: true, pressureMin: 0.2 },
useGpu: true,
},
},
{
- id: 'soft-blender',
- name: 'Soft Smudge Blender',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Blend',
- badgeBg: 'bg-purple-500/15',
- badgeText: 'text-purple-300',
- badgeBorder: 'border-purple-500/30',
- desc: 'Zero-Pigment Wet Color Stretch & Blur',
- icon: 'palette',
+ id: 'blend-chalk-brush',
+ category: 'brush',
+ name: 'Blend Chalk Brush',
+ badge: 'Brush',
+ badgeBg: 'bg-emerald-500/15',
+ badgeText: 'text-emerald-300',
+ badgeBorder: 'border-emerald-500/30',
+ desc: 'Textured Chalk Blender — Smudges Pigment While Preserving Gritty Tooth',
+ icon: 'paintbrush',
+ tipGenerator: generateChalkPaintTip,
+ paperTextureGenerator: generateCharcoalPaperTexture,
settings: {
- size: 36,
- minSizeFactor: 0.5,
- flow: 0.85,
+ size: 32,
+ minSizeFactor: 0.4,
+ flow: 0.72,
opacity: 1.0,
- hardness: 0.25,
- spacing: 0.05,
+ hardness: 0.55,
+ antiAlias: 2,
+ thickness: 0.78,
+ spacing: 0.065,
+ stabilization: 6,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.0,
+ smoothing: true,
+ customTipAngleDynamics: 'random',
+ flipH: 'random',
+ flipV: 'random',
colorMixing: true,
perceptualMixing: true,
mixingMode: 'smear',
amountOfPaint: 0.0,
- densityOfPaint: 0.0,
- colorStretch: 0.86,
- stabilization: 10,
+ densityOfPaint: 0.78,
+ colorStretch: 0.68,
+ grain: 0.55,
+ textureDensity: 0.55,
+ paperTextureMode: 'multiply',
+ paperTextureScale: 1.25,
+ paperTextureContrast: 30,
+ opacitySensor: { usePressure: true, pressureMin: 0.22 },
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ angleJitter: 0.35,
+ flowJitter: 0.14,
+ },
+ useGpu: true,
+ },
+ },
+ {
+ id: 'soft-round',
+ category: 'brush',
+ name: 'Soft Round',
+ badge: 'Brush',
+ badgeBg: 'bg-emerald-500/15',
+ badgeText: 'text-emerald-300',
+ badgeBorder: 'border-emerald-500/30',
+ desc: 'Silky Airbrush Gradient — Cosine Soft Falloff & Pressure Opacity',
+ icon: 'paintbrush',
+ settings: {
+ size: 48,
+ minSizeFactor: 0.55,
+ flow: 0.35,
+ opacity: 1.0,
+ hardness: 0.0,
+ antiAlias: 3,
+ spacing: 0.06,
+ stabilization: 8,
+ sharpCorners: false,
usePressure: true,
useTilt: false,
smoothing: true,
+ adjustDensityByGap: true,
+ pressureCurve: CSP_PRESSURE_CURVE_PRESETS.soft.points,
+ opacitySensor: { usePressure: true, pressureMin: 0.08 },
useGpu: true,
},
},
{
- id: 'square-digital',
- name: 'Square Color Brush',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Square',
- badgeBg: 'bg-teal-500/15',
- badgeText: 'text-teal-300',
- badgeBorder: 'border-teal-500/30',
- desc: 'Classic Flat Digital Coloring & Hard-Surface Blocking',
- icon: 'square',
- tipGenerator: getSquareTipDataUrl,
+ id: 'noise-shader',
+ category: 'brush',
+ name: 'Textured Grain / Noise Shader',
+ badge: 'Brush',
+ badgeBg: 'bg-emerald-500/15',
+ badgeText: 'text-emerald-300',
+ badgeBorder: 'border-emerald-500/30',
+ desc: 'Stippled Film-Grain Atmospheric Shader for Organic Textured Gradients',
+ icon: 'paintbrush',
+ tipGenerator: generateNoiseShaderTip,
+ paperTextureGenerator: generateNoiseGrainTexture,
settings: {
- size: 24,
- minSizeFactor: 0.25,
- flow: 0.95,
+ size: 56,
+ minSizeFactor: 0.45,
+ flow: 0.48,
opacity: 1.0,
- hardness: 1.0,
- spacing: 0.07,
- stabilization: 12,
+ hardness: 0.15,
+ antiAlias: 2,
+ spacing: 0.11,
+ stabilization: 5,
+ sharpCorners: false,
usePressure: true,
- useTilt: false,
+ useTilt: true,
+ tiltScale: 1.1,
smoothing: true,
- customTipAngle: 0,
- customTipAngleDynamics: 'none',
- colorMixing: true,
- perceptualMixing: true,
- amountOfPaint: 0.88,
- densityOfPaint: 0.95,
- colorStretch: 0.4,
- mixingMode: 'blend',
+ adjustDensityByGap: true,
+ customTipAngleDynamics: 'random',
+ flipH: 'random',
+ flipV: 'random',
+ grain: 0.68,
+ textureDensity: 0.68,
+ paperTextureMode: 'multiply',
+ paperTextureScale: 0.85,
+ paperTextureContrast: 48,
+ opacitySensor: { usePressure: true, pressureMin: 0.08 },
+ densitySensor: { usePressure: true, pressureMin: 0.15 },
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ sizeJitter: 0.12,
+ angleJitter: 1.0,
+ flowJitter: 0.25,
+ scatter: 0.14,
+ scatterBothAxes: true,
+ count: 1,
+ },
useGpu: true,
},
},
];
+let _assetsPrewarmed = false;
+
+/**
+ * Decodes all procedural builtin tip and paper PNG images into browser memory once
+ * so the very first stroke on any preset hits already-decoded textures with zero latency.
+ */
+export function prewarmBuiltinBrushAssets(): void {
+ if (_assetsPrewarmed || typeof document === 'undefined' || typeof Image === 'undefined') return;
+ _assetsPrewarmed = true;
+ for (let i = 0; i < BUILTIN_BRUSHES.length; i++) {
+ const def = BUILTIN_BRUSHES[i];
+ if (def.tipGenerator) {
+ const url = def.tipGenerator();
+ if (url) getPreloadedBuiltinTipImage(url);
+ }
+ if (def.paperTextureGenerator) {
+ const url = def.paperTextureGenerator();
+ if (url) getPreloadedBuiltinTipImage(url);
+ }
+ }
+}
+
+// Schedule non-blocking prewarm in browser environments after initial paint
+if (typeof window !== 'undefined' && typeof document !== 'undefined') {
+ const scheduleWarm =
+ typeof (window as unknown as { requestIdleCallback?: (cb: () => void) => number }).requestIdleCallback ===
+ 'function'
+ ? (window as unknown as { requestIdleCallback: (cb: () => void) => number }).requestIdleCallback
+ : (cb: () => void) => window.setTimeout(cb, 60);
+ scheduleWarm(() => prewarmBuiltinBrushAssets());
+}
+
/**
* Returns the full brush settings for a builtin preset.
*/
@@ -730,7 +842,6 @@ export function getBuiltinBrushConfig(presetId: BrushPresetId): Partial<BrushSet
let tipDataUrl: string | undefined = undefined;
let tipImage: HTMLImageElement | undefined = undefined;
-
if (def.tipGenerator) {
tipDataUrl = def.tipGenerator();
if (tipDataUrl) {
@@ -738,11 +849,22 @@ export function getBuiltinBrushConfig(presetId: BrushPresetId): Partial<BrushSet
}
}
+ let paperTexture: string | undefined = undefined;
+ let paperTextureImage: HTMLImageElement | undefined = undefined;
+ if (def.paperTextureGenerator) {
+ paperTexture = def.paperTextureGenerator();
+ if (paperTexture) {
+ paperTextureImage = getPreloadedBuiltinTipImage(paperTexture);
+ }
+ }
+
return {
preset: def.id,
brushName: def.name,
customTipDataUrl: tipDataUrl,
customTipImage: tipImage,
+ paperTexture,
+ paperTextureImage,
...def.settings,
};
}
diff --git a/src/utils/proceduralBrushTips.ts b/src/utils/proceduralBrushTips.ts
new file mode 100644
index 0000000..0f4a7ec
--- /dev/null
+++ b/src/utils/proceduralBrushTips.ts
@@ -0,0 +1,876 @@
+/**
+ * proceduralBrushTips.ts
+ * Deterministic, zero-allocation procedural 128x128 brush tip masks and 256x256 seamless
+ * paper/canvas grain textures modeled after Clip Studio Paint & Photoshop physical media.
+ *
+ * Tips encode alpha opacity on pure white RGB so GPU/CPU tinting stays color-accurate.
+ * Paper textures encode surface elevation in luminance [0..255] with opaque alpha=255.
+ */
+
+const TIP_SIZE = 128;
+const PAPER_SIZE = 256;
+
+const generatedCache = new Map<string, string>();
+
+function createPrng(seed: number): () => number {
+ let a = (seed ^ 0x9e3779b9) | 0;
+ let b = (seed * 1664525 + 1013904223) | 0;
+ let c = (seed ^ 0xb7e15162) | 0;
+ let d = (seed ^ 0x8aed2a6b) | 0;
+ return () => {
+ a |= 0;
+ b |= 0;
+ c |= 0;
+ d |= 0;
+ const t = (((a + b) | 0) + d) | 0;
+ d = (d + 1) | 0;
+ a = b ^ (b >>> 9);
+ b = (c + (c << 3)) | 0;
+ c = (c << 21) | (c >>> 11);
+ c = (c + t) | 0;
+ return (t >>> 0) / 4294967296;
+ };
+}
+
+function makePeriodicGrid(res: number, rand: () => number): Float32Array {
+ const g = new Float32Array(res * res);
+ for (let i = 0; i < g.length; i++) g[i] = rand();
+ return g;
+}
+
+/**
+ * Tileable periodic Worley / cellular dome height field.
+ * Models physical 3D cotton paper fiber bumps: rounded peaks with sharp recessed crevices between domes.
+ */
+function makeCellularDomeField(size: number, cells: number, rand: () => number): Float32Array {
+ const ptsX = new Float32Array(cells * cells);
+ const ptsY = new Float32Array(cells * cells);
+ const ptsH = new Float32Array(cells * cells);
+ for (let cy = 0; cy < cells; cy++) {
+ for (let cx = 0; cx < cells; cx++) {
+ const idx = cy * cells + cx;
+ ptsX[idx] = cx + 0.12 + rand() * 0.76;
+ ptsY[idx] = cy + 0.12 + rand() * 0.76;
+ ptsH[idx] = 0.76 + rand() * 0.24;
+ }
+ }
+
+ const out = new Float32Array(size * size);
+ const scale = cells / size;
+ for (let y = 0; y < size; y++) {
+ const gy = y * scale;
+ const baseCy = Math.floor(gy);
+ const row = y * size;
+ for (let x = 0; x < size; x++) {
+ const gx = x * scale;
+ const baseCx = Math.floor(gx);
+ let d1 = 99;
+ let d2 = 99;
+ let bestH = 1.0;
+
+ for (let oy = -1; oy <= 1; oy++) {
+ let cy = baseCy + oy;
+ let wrapY = 0;
+ if (cy < 0) { cy += cells; wrapY = -cells; }
+ else if (cy >= cells) { cy -= cells; wrapY = cells; }
+ const cRow = cy * cells;
+
+ for (let ox = -1; ox <= 1; ox++) {
+ let cx = baseCx + ox;
+ let wrapX = 0;
+ if (cx < 0) { cx += cells; wrapX = -cells; }
+ else if (cx >= cells) { cx -= cells; wrapX = cells; }
+ const cIdx = cRow + cx;
+ const dx = gx - (ptsX[cIdx] + wrapX);
+ const dy = gy - (ptsY[cIdx] + wrapY);
+ const d = dx * dx + dy * dy;
+ if (d < d1) {
+ d2 = d1;
+ d1 = d;
+ bestH = ptsH[cIdx];
+ } else if (d < d2) {
+ d2 = d;
+ }
+ }
+ }
+
+ const f1 = Math.sqrt(d1);
+ const f2 = Math.sqrt(d2);
+ // Combine dome elevation (1 - f1) with crisp crevice depth (f2 - f1)
+ const dome = clamp01(1.0 - f1 * 1.12);
+ const crevice = clamp01((f2 - f1) * 1.85);
+ out[row + x] = clamp01((dome * 0.62 + crevice * 0.38) * bestH);
+ }
+ }
+ return out;
+}
+
+function samplePeriodic(grid: Float32Array, res: number, fx: number, fy: number): number {
+ const mask = res - 1;
+ const x0 = Math.floor(fx);
+ const y0 = Math.floor(fy);
+ const tx = fx - x0;
+ const ty = fy - y0;
+ const sx = tx * tx * (3 - 2 * tx);
+ const sy = ty * ty * (3 - 2 * ty);
+ const ix0 = x0 & mask;
+ const iy0 = y0 & mask;
+ const ix1 = (ix0 + 1) & mask;
+ const iy1 = (iy0 + 1) & mask;
+ const v00 = grid[iy0 * res + ix0];
+ const v10 = grid[iy0 * res + ix1];
+ const v01 = grid[iy1 * res + ix0];
+ const v11 = grid[iy1 * res + ix1];
+ const top = v00 + (v10 - v00) * sx;
+ const bot = v01 + (v11 - v01) * sx;
+ return top + (bot - top) * sy;
+}
+
+function clamp01(v: number): number {
+ return v <= 0 ? 0 : v >= 1 ? 1 : v;
+}
+
+function smoothstep(edge0: number, edge1: number, x: number): number {
+ const t = clamp01((x - edge0) / Math.max(1e-5, edge1 - edge0));
+ return t * t * (3 - 2 * t);
+}
+
+/**
+ * Helper: allocates an offscreen canvas, fills RGBA via callback, and returns a cached PNG data URL.
+ */
+function buildCachedPng(
+ key: string,
+ size: number,
+ fill: (data: Uint8ClampedArray, size: number) => void
+): string {
+ const hit = generatedCache.get(key);
+ if (hit !== undefined) return hit;
+
+ if (typeof document === 'undefined') return '';
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ const ctx = canvas.getContext('2d');
+ if (!ctx || typeof ctx.createImageData !== 'function') return '';
+
+ const imgData = ctx.createImageData(size, size);
+ fill(imgData.data, size);
+ ctx.putImageData(imgData, 0, 0);
+
+ const url = typeof canvas.toDataURL === 'function' ? canvas.toDataURL('image/png') : '';
+ if (url) {
+ generatedCache.set(key, url);
+ }
+ return url;
+}
+
+function writeAlphaPixel(data: Uint8ClampedArray, idx: number, alpha: number): void {
+ const a = Math.round(clamp01(alpha) * 255);
+ if (a <= 0) return;
+ data[idx] = 255;
+ data[idx + 1] = 255;
+ data[idx + 2] = 255;
+ data[idx + 3] = a;
+}
+
+// -------------------------------------------------------------
+// PEN SECTION TIPS
+// -------------------------------------------------------------
+
+/**
+ * Real G-Pen: dense manga steel-nib core with subtle organic edge feathering & ink-on-Bristol micro-roughness.
+ */
+export function generateRealGPenTip(): string {
+ return buildCachedPng('tip:real-g-pen', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x101a);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const baseR = half - 5;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const dist = Math.hypot(dx, dy);
+ const angle = Math.atan2(dy, dx);
+
+ // Subtle organic nib wobble + Bristol fiber bleed along rim
+ const angularWobble =
+ Math.sin(angle * 5 + 0.7) * 0.022 +
+ Math.cos(angle * 11 - 1.3) * 0.016 +
+ Math.sin(angle * 19 + 2.1) * 0.011;
+ const edgeNoise =
+ (samplePeriodic(nMed, 32, x * 0.25, y * 0.25) - 0.5) * 0.09 +
+ (samplePeriodic(nFine, 64, x * 0.5, y * 0.5) - 0.5) * 0.05;
+
+ const rNorm = dist / (baseR * (1.0 + angularWobble + edgeNoise));
+ if (rNorm >= 1.04) continue;
+
+ let alpha = 1.0 - smoothstep(0.84, 1.02, rNorm);
+ // Micro-tooth only at the outermost ink rim
+ if (rNorm > 0.76) {
+ const rimTooth = samplePeriodic(nFine, 64, x * 0.75, y * 0.75);
+ alpha *= 0.82 + rimTooth * 0.26;
+ }
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ });
+}
+
+/**
+ * Textured Pen: expressive dry-ink nib with pitted organic perimeter and crisp rough edges.
+ */
+export function generateTexturedPenTip(): string {
+ return buildCachedPng('tip:textured-pen', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x202b);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const baseR = half - 6;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const dist = Math.hypot(dx, dy);
+
+ const warp =
+ (samplePeriodic(nCoarse, 16, x * 0.14, y * 0.14) - 0.5) * 0.24 +
+ (samplePeriodic(nMed, 32, x * 0.32, y * 0.32) - 0.5) * 0.14;
+ const rNorm = dist / (baseR * (1.0 + warp));
+ if (rNorm >= 1.06) continue;
+
+ const core = 1.0 - smoothstep(0.72, 1.03, rNorm);
+ const fineGrain = samplePeriodic(nFine, 64, x * 0.65, y * 0.65);
+ // Pitted dry-ink rim while keeping dense center
+ const pit = rNorm > 0.58 ? smoothstep(0.24, 0.72, fineGrain + (1.0 - rNorm) * 0.85) : 1.0;
+ writeAlphaPixel(data, row + x * 4, core * pit);
+ }
+ }
+ });
+}
+
+/**
+ * Calligraphy Nib: broad flat italic chisel edge (superellipse with crisp flat sides and subtle nib ink corners).
+ */
+export function generateCalligraphyTip(): string {
+ return buildCachedPng('tip:calligraphy', TIP_SIZE, (data, size) => {
+ const half = size * 0.5;
+ const rx = half - 4;
+ const ry = half - 4;
+
+ for (let y = 0; y < size; y++) {
+ const ny = Math.abs(y - half + 0.5) / ry;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const nx = Math.abs(x - half + 0.5) / rx;
+ // Superellipse (p = 3.6) gives a crisp chisel-nib flat edge with slightly rounded ink corners
+ const d = Math.pow(Math.pow(nx, 3.6) + Math.pow(ny, 3.6), 1 / 3.6);
+ if (d >= 1.03) continue;
+ const alpha = 1.0 - smoothstep(0.91, 1.02, d);
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ });
+}
+
+// -------------------------------------------------------------
+// SKETCH SECTION TIPS (DRY-MEDIA GRANULAR GRAPHITE / CHARCOAL / CHALK)
+// -------------------------------------------------------------
+
+/**
+ * Mechanical Pencil (0.5mm): firm polymer-graphite core — crisp edge with tight micro-graphite tooth, zero airbrush blur.
+ */
+export function generateMechanicalPencilTip(): string {
+ return buildCachedPng('tip:mechanical-pencil', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x303c);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const baseR = half - 5;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const dist = Math.hypot(dx, dy);
+ const rimWarp = (samplePeriodic(nMed, 32, x * 0.35, y * 0.35) - 0.5) * 0.08;
+ const rNorm = dist / (baseR * (1.0 + rimWarp));
+ if (rNorm >= 1.03) continue;
+
+ // Crisp firm rim (not a soft Gaussian falloff)
+ const profile = 1.0 - smoothstep(0.82, 1.01, rNorm);
+ const micro = samplePeriodic(nFine, 64, x * 0.85, y * 0.85);
+ const grit = 0.78 + micro * 0.16 + rand() * 0.06;
+ // Subtle crisp graphite flecks near outer edge
+ const rimBreak = rNorm > 0.72 ? smoothstep(0.18, 0.65, micro + (1.0 - rNorm) * 1.1) : 1.0;
+ writeAlphaPixel(data, row + x * 4, profile * grit * rimBreak);
+ }
+ }
+ });
+}
+
+/**
+ * HB/2B Pencil: sharpened wood-cased graphite core — faceted dry micro-clusters, crisp toothy rim, zero blurry halo.
+ */
+export function generateHb2bPencilTip(): string {
+ return buildCachedPng('tip:pencil-hb-2b', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x404d);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const domes = makeCellularDomeField(size, 28, rand);
+ const half = size * 0.5;
+ const baseR = half - 7;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ const dRow = y * size;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const dist = Math.hypot(dx * 0.94, dy * 1.06);
+ const angle = Math.atan2(dy, dx);
+ // Subtle asymmetric wear facet of a sharpened graphite point
+ const facet = Math.sin(angle * 3 + 0.4) * 0.06 + Math.cos(angle * 5 - 1.1) * 0.04;
+ const warp = (samplePeriodic(nCoarse, 16, x * 0.18, y * 0.18) - 0.5) * 0.18;
+ const rNorm = dist / (baseR * (1.0 + facet + warp));
+ if (rNorm >= 1.04) continue;
+
+ const dome = domes[dRow + x];
+ const grain =
+ dome * 0.48 +
+ samplePeriodic(nMed, 32, x * 0.45, y * 0.45) * 0.24 +
+ samplePeriodic(nFine, 64, x * 0.9, y * 0.9) * 0.18 +
+ rand() * 0.10;
+
+ // Sharp granular threshold: solid graphite clusters in center, dry broken grains at rim
+ const env = 1.0 - smoothstep(0.62, 1.02, rNorm);
+ const cutLow = 0.14 + rNorm * 0.34;
+ const cluster = smoothstep(cutLow, cutLow + 0.24, grain);
+ writeAlphaPixel(data, row + x * 4, env * (0.20 + 0.80 * cluster));
+ }
+ }
+ });
+}
+
+/**
+ * 6B/8B Pencil: worn soft dark graphite lead — broad chiseled oval packed with chunky high-contrast graphite grains.
+ */
+export function generate6b8bPencilTip(): string {
+ return buildCachedPng('tip:pencil-6b-8b', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x505e);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const domes = makeCellularDomeField(size, 22, rand);
+ const half = size * 0.5;
+ const rx = half - 6;
+ const ry = half - 14;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ const dRow = y * size;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const warp =
+ (samplePeriodic(nCoarse, 16, x * 0.16, y * 0.16) - 0.5) * 0.24 +
+ (samplePeriodic(nMed, 32, x * 0.36, y * 0.36) - 0.5) * 0.14;
+ const nx = dx / (rx * (1.0 + warp));
+ const ny = dy / (ry * (1.0 + warp));
+ const rNorm = Math.hypot(nx, ny);
+ if (rNorm >= 1.06) continue;
+
+ const dome = domes[dRow + x];
+ const chunk =
+ dome * 0.54 +
+ samplePeriodic(nMed, 32, x * 0.42, y * 0.42) * 0.28 +
+ rand() * 0.18;
+
+ const env = 1.0 - smoothstep(0.68, 1.05, rNorm);
+ // Chunky high-contrast graphite clumps — crisp micro-voids inside, serrated tooth along edge
+ const cutLow = 0.18 + rNorm * 0.38;
+ const cluster = smoothstep(cutLow, cutLow + 0.20, chunk);
+ writeAlphaPixel(data, row + x * 4, env * cluster);
+ }
+ }
+ });
+}
+
+/**
+ * Charcoal Pencil: raw dry fractured compressed carbon core + 60 crisp detached dust crumbs in outer halo.
+ */
+export function generateCharcoalTip(): string {
+ return buildCachedPng('tip:charcoal-pencil', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x606f);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const domes = makeCellularDomeField(size, 24, rand);
+ const half = size * 0.5;
+ const coreR = half * 0.58; // Compact jagged core leaves clear outer halo for loose crumbs/dust
+
+ // 62 crisp irregular charcoal dust crumbs & flakes around the jagged core perimeter
+ const crumbs: Array<{ x: number; y: number; rx: number; ry: number; rot: number; a: number }> = [];
+ for (let i = 0; i < 62; i++) {
+ const th = rand() * Math.PI * 2;
+ const dist = coreR * (0.92 + Math.pow(rand(), 0.75) * 0.72);
+ const baseCrumbR = 0.9 + Math.pow(rand(), 1.6) * 3.1;
+ crumbs.push({
+ x: half + Math.cos(th) * dist,
+ y: half + Math.sin(th) * dist,
+ rx: baseCrumbR * (0.7 + rand() * 0.7),
+ ry: baseCrumbR * (0.7 + rand() * 0.7),
+ rot: rand() * Math.PI,
+ a: 0.45 + rand() * 0.55,
+ });
+ }
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ const dRow = y * size;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const dist = Math.hypot(dx * 0.88, dy * 1.12);
+ const angle = Math.atan2(dy, dx);
+
+ // Angular broken-stone charcoal silhouette
+ const jagged =
+ Math.sin(angle * 3 + 0.5) * 0.16 +
+ Math.cos(angle * 5 - 1.2) * 0.12 +
+ Math.sin(angle * 9 + 0.7) * 0.09 +
+ Math.cos(angle * 15 - 0.4) * 0.05;
+ const rockWarp =
+ (samplePeriodic(nCoarse, 16, x * 0.18, y * 0.18) - 0.5) * 0.36 +
+ (samplePeriodic(nMed, 32, x * 0.40, y * 0.40) - 0.5) * 0.22;
+
+ const rNorm = dist / (coreR * (1.0 + jagged + rockWarp));
+
+ let alpha = 0;
+ if (rNorm < 1.05) {
+ const dome = domes[dRow + x];
+ const fracture =
+ dome * 0.55 +
+ samplePeriodic(nMed, 32, x * 0.45, y * 0.45) * 0.28 +
+ rand() * 0.17;
+ const env = 1.0 - smoothstep(0.74, 1.03, rNorm);
+ // Hard dry fracture cutoff — razor-dry carbon islands and jagged fissures
+ const cutLow = 0.24 + rNorm * 0.36;
+ alpha = env * smoothstep(cutLow, cutLow + 0.16, fracture);
+ }
+
+ // Accumulate crisp detached carbon dust crumbs along stroke edges
+ for (let c = 0; c < crumbs.length; c++) {
+ const cr = crumbs[c];
+ const cdx = x - cr.x;
+ const cdy = y - cr.y;
+ if (Math.abs(cdx) > 5 || Math.abs(cdy) > 5) continue;
+ const cosR = Math.cos(cr.rot);
+ const sinR = Math.sin(cr.rot);
+ const lx = (cdx * cosR + cdy * sinR) / cr.rx;
+ const ly = (-cdx * sinR + cdy * cosR) / cr.ry;
+ const cd = Math.hypot(lx, ly);
+ if (cd < 1.0) {
+ const ca = (1.0 - smoothstep(0.35, 1.0, cd)) * cr.a;
+ if (ca > alpha) alpha = ca;
+ }
+ }
+
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ });
+}
+
+/**
+ * Standard Chalk: dry porous rectangular-oval mineral chalk stick with crisp powdery micro-pores.
+ */
+export function generateChalkTip(): string {
+ return buildCachedPng('tip:standard-chalk', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x7071);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const domes = makeCellularDomeField(size, 26, rand);
+ const half = size * 0.5;
+ const rx = half - 8;
+ const ry = half - 16;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ const dRow = y * size;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const warp =
+ (samplePeriodic(nCoarse, 16, x * 0.16, y * 0.16) - 0.5) * 0.24 +
+ (samplePeriodic(nMed, 32, x * 0.34, y * 0.34) - 0.5) * 0.14;
+ const nx = Math.abs(dx) / (rx * (1.0 + warp));
+ const ny = Math.abs(dy) / (ry * (1.0 + warp));
+ // Flat blocky chalk stick cross-section (superellipse p = 3.0)
+ const d = Math.pow(Math.pow(nx, 3.0) + Math.pow(ny, 3.0), 1 / 3.0);
+ if (d >= 1.06) continue;
+
+ const body = 1.0 - smoothstep(0.72, 1.04, d);
+ const powder =
+ domes[dRow + x] * 0.52 +
+ samplePeriodic(nMed, 32, x * 0.42, y * 0.42) * 0.28 +
+ rand() * 0.20;
+ const cutLow = 0.20 + d * 0.34;
+ const porous = smoothstep(cutLow, cutLow + 0.18, powder);
+ writeAlphaPixel(data, row + x * 4, body * porous);
+ }
+ }
+ });
+}
+
+// -------------------------------------------------------------
+// BRUSH SECTION TIPS (COLORING & PAINTING)
+// -------------------------------------------------------------
+
+/**
+ * Oil Painting Brush: oval natural hog-bristle bundle (~52 soft individual bristles with organic gaps).
+ */
+export function generateOilBristleTip(): string {
+ return buildCachedPng('tip:oil-painting', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x8082);
+ const half = size * 0.5;
+ const rx = half - 12;
+ const ry = half - 16;
+
+ interface Bristle {
+ x: number;
+ y: number;
+ rx: number;
+ ry: number;
+ strength: number;
+ }
+ const bristles: Bristle[] = [];
+ // Soft core fill bristles + outer perimeter strands
+ for (let i = 0; i < 54; i++) {
+ const th = rand() * Math.PI * 2;
+ const rad = Math.sqrt(rand()) * 0.92;
+ const bx = half + Math.cos(th) * rx * rad;
+ const by = half + Math.sin(th) * ry * rad;
+ const edgeFactor = 1.0 - rad * 0.35;
+ bristles.push({
+ x: bx,
+ y: by,
+ rx: (6.5 + rand() * 7.5) * edgeFactor,
+ ry: (5.0 + rand() * 6.0) * edgeFactor,
+ strength: 0.48 + rand() * 0.52,
+ });
+ }
+
+ const nFine = makePeriodicGrid(64, rand);
+ for (let y = 0; y < size; y++) {
+ const dy = (y - half + 0.5) / (half - 6);
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = (x - half + 0.5) / (half - 6);
+ const envDist = Math.hypot(dx, dy);
+ if (envDist >= 1.04) continue;
+
+ let acc = 0;
+ for (let b = 0; b < bristles.length; b++) {
+ const br = bristles[b];
+ const bdx = (x - br.x) / br.rx;
+ const bdy = (y - br.y) / br.ry;
+ const d2 = bdx * bdx + bdy * bdy;
+ if (d2 < 1.0) {
+ const fall = 1.0 - d2;
+ acc += fall * fall * br.strength;
+ }
+ }
+ // Soft creamy oil core with distinct bristle streaks near trailing/outer edges
+ const softBase = Math.pow(clamp01(1.0 - envDist), 1.3) * 0.42;
+ const streak = 0.85 + samplePeriodic(nFine, 64, x * 0.25, y * 0.65) * 0.22;
+ const alpha = clamp01((Math.min(1.0, acc * 0.82) + softBase) * streak) * (1.0 - smoothstep(0.82, 1.02, envDist));
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ });
+}
+
+/**
+ * Thick Oil Painting Brush: flat filbert impasto hog-bristle head with bold chiseled bristle ridges.
+ */
+export function generateThickOilTip(): string {
+ return buildCachedPng('tip:thick-oil', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x9093);
+ const half = size * 0.5;
+ const rx = half - 8;
+ const ry = half - 18;
+
+ // Generate coarse parallel bristle ridges running across the flat ferrule
+ const numRidges = 26;
+ const ridgeCenters = new Float32Array(numRidges);
+ const ridgeWidths = new Float32Array(numRidges);
+ const ridgePower = new Float32Array(numRidges);
+ for (let i = 0; i < numRidges; i++) {
+ const u = (i + 0.5) / numRidges;
+ ridgeCenters[i] = half - ry + u * (ry * 2) + (rand() - 0.5) * 2.2;
+ ridgeWidths[i] = 2.0 + rand() * 3.0;
+ ridgePower[i] = 0.52 + rand() * 0.48;
+ }
+
+ const nMed = makePeriodicGrid(32, rand);
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const nx = Math.abs(dx) / rx;
+ const ny = Math.abs(dy) / ry;
+ const d = Math.pow(Math.pow(nx, 3.2) + Math.pow(ny, 3.2), 1 / 3.2);
+ if (d >= 1.06) continue;
+
+ let ridgeVal = 0;
+ for (let r = 0; r < numRidges; r++) {
+ const distY = Math.abs(y - ridgeCenters[r]) / ridgeWidths[r];
+ if (distY < 1.0) {
+ const v = (1.0 - distY * distY) * ridgePower[r];
+ if (v > ridgeVal) ridgeVal = v;
+ }
+ }
+
+ const bristleEndNoise = samplePeriodic(nMed, 32, x * 0.16, y * 0.55);
+ // Slightly ragged bristle tips along leading/trailing edge (high nx)
+ const edgeMask = 1.0 - smoothstep(0.76 - bristleEndNoise * 0.18, 1.04, d);
+ const body = 0.42 + 0.58 * ridgeVal;
+ writeAlphaPixel(data, row + x * 4, clamp01(body * edgeMask * 1.15));
+ }
+ }
+ });
+}
+
+/**
+ * Chalk Painting Brush: wide sculpted painterly chalk/oil-pastel head with broken textured streaks.
+ */
+export function generateChalkPaintTip(): string {
+ return buildCachedPng('tip:chalk-painting', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xa0a4);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const rx = half - 8;
+ const ry = half - 14;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ // Directional streak noise along X for painterly drag
+ const streak = samplePeriodic(nMed, 32, x * 0.14, y * 0.44);
+ const warp = (samplePeriodic(nCoarse, 16, x * 0.15, y * 0.15) - 0.5) * 0.22;
+ const nx = Math.abs(dx) / (rx * (1.0 + warp));
+ const ny = Math.abs(dy) / (ry * (1.0 + warp));
+ const d = Math.pow(Math.pow(nx, 2.4) + Math.pow(ny, 2.4), 1 / 2.4);
+ if (d >= 1.06) continue;
+
+ const env = 1.0 - smoothstep(0.68, 1.05, d);
+ const tooth = samplePeriodic(nFine, 64, x * 0.65, y * 0.65);
+ const dry = smoothstep(0.16, 0.78, streak * 0.52 + tooth * 0.34 + rand() * 0.14 + (1.0 - d) * 0.35);
+ writeAlphaPixel(data, row + x * 4, env * (0.38 + 0.62 * dry));
+ }
+ }
+ });
+}
+
+/**
+ * Textured Grain / Noise Shader: silky Gaussian envelope modulated by organic crisp stipple noise.
+ */
+export function generateNoiseShaderTip(): string {
+ return buildCachedPng('tip:noise-shader', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xb0b5);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const radius = half - 3;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const rNorm = Math.hypot(dx, dy) / radius;
+ if (rNorm >= 1.0) continue;
+
+ // Smooth Gaussian-like radial envelope (zero hard ring)
+ const env = 0.5 * (1.0 + Math.cos(rNorm * Math.PI));
+ const softEnv = Math.pow(env, 1.25);
+
+ // Crisp stochastic film/stipple micro-dots
+ const f1 = samplePeriodic(nFine, 64, x * 0.85, y * 0.85);
+ const speck = rand();
+ const grainVal = f1 * 0.45 + speck * 0.55;
+ // Higher envelope density permits more stipple grains to fire
+ const stipple = smoothstep(0.55 - softEnv * 0.48, 0.88 - softEnv * 0.25, grainVal);
+ const alpha = softEnv * (0.18 + 0.82 * stipple);
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ });
+}
+
+// -------------------------------------------------------------
+// SEAMLESS PROCEDURAL PAPER / CANVAS TEXTURES (256x256)
+// -------------------------------------------------------------
+
+/**
+ * Fine Bristol / Drafting Paper (256x256):
+ * Tight, crisp micro-tooth (2px-3px domes) ideal for Mechanical Pencil linework.
+ */
+export function generateFinePaperTexture(): string {
+ return buildCachedPng('paper:fine-bristol', PAPER_SIZE, (data, size) => {
+ const rand = createPrng(0xc1d2);
+ const fineDomes = makeCellularDomeField(size, 96, rand);
+ const gFibers = makePeriodicGrid(128, rand);
+
+ for (let y = 0; y < size; y++) {
+ const row = y * size * 4;
+ const dRow = y * size;
+ for (let x = 0; x < size; x++) {
+ const dome = fineDomes[dRow + x];
+ const fiber = samplePeriodic(gFibers, 128, x * 0.5, y * 0.5);
+ const raw = dome * 0.58 + fiber * 0.26 + rand() * 0.16;
+ const crisp = clamp01((raw - 0.12) / 0.76);
+ const v = Math.round(crisp * 255);
+ const idx = row + x * 4;
+ data[idx] = v;
+ data[idx + 1] = v;
+ data[idx + 2] = v;
+ data[idx + 3] = 255;
+ }
+ }
+ });
+}
+
+/**
+ * Cold-Press Cotton Sketchbook Paper (256x256):
+ * Dual-scale cellular fiber domes (3.5px primary tooth + 2px micro-tooth) with crisp valley crevices.
+ * Eliminates blurry cloud artifacts on HB/2B and 6B/8B pencils.
+ */
+export function generateSketchPaperTexture(): string {
+ return buildCachedPng('paper:cold-press-sketch', PAPER_SIZE, (data, size) => {
+ const rand = createPrng(0xc2e3);
+ const primaryDomes = makeCellularDomeField(size, 64, rand); // ~4px pressed cotton bumps
+ const microDomes = makeCellularDomeField(size, 112, rand); // ~2.3px fine tooth
+ const gUndul = makePeriodicGrid(32, rand);
+
+ for (let y = 0; y < size; y++) {
+ const row = y * size * 4;
+ const dRow = y * size;
+ for (let x = 0; x < size; x++) {
+ const d1 = primaryDomes[dRow + x];
+ const d2 = microDomes[dRow + x];
+ const undul = samplePeriodic(gUndul, 32, x * 0.125, y * 0.125);
+ const raw = d1 * 0.54 + d2 * 0.28 + undul * 0.10 + rand() * 0.08;
+ // High-contrast peak-to-valley distribution so compare cutoff reveals crisp pores
+ const crisp = clamp01((raw - 0.14) / 0.72);
+ const v = Math.round(Math.pow(crisp, 1.08) * 255);
+ const idx = row + x * 4;
+ data[idx] = v;
+ data[idx + 1] = v;
+ data[idx + 2] = v;
+ data[idx + 3] = 255;
+ }
+ }
+ });
+}
+
+/**
+ * Coarse Laid Charcoal / Pastel Paper (Canson/Ingres inspired, 256x256):
+ * Coarse 5px cellular domes + crisp periodic horizontal laid ribs & vertical chain lines.
+ */
+export function generateCharcoalPaperTexture(): string {
+ return buildCachedPng('paper:charcoal-laid', PAPER_SIZE, (data, size) => {
+ const rand = createPrng(0xc0c6);
+ const coarseDomes = makeCellularDomeField(size, 48, rand); // ~5.3px rugged charcoal tooth
+ const fineDomes = makeCellularDomeField(size, 96, rand);
+
+ for (let y = 0; y < size; y++) {
+ const row = y * size * 4;
+ const dRow = y * size;
+ // Crisp Ingres laid-paper horizontal rib (period = 6.4px -> 40 cycles per 256px)
+ const laidRib = Math.sin((y / size) * Math.PI * 2 * 40) * 0.13;
+ for (let x = 0; x < size; x++) {
+ // Subtle vertical laid chain line (8 cycles per 256px)
+ const chainLine = Math.sin((x / size) * Math.PI * 2 * 8) * 0.05;
+ const d1 = coarseDomes[dRow + x];
+ const d2 = fineDomes[dRow + x];
+ const raw = d1 * 0.56 + d2 * 0.26 + rand() * 0.12 + laidRib + chainLine;
+ const highContrast = clamp01((raw - 0.15) / 0.70);
+ const v = Math.round(Math.pow(highContrast, 1.15) * 255);
+ const idx = row + x * 4;
+ data[idx] = v;
+ data[idx + 1] = v;
+ data[idx + 2] = v;
+ data[idx + 3] = 255;
+ }
+ }
+ });
+}
+
+/**
+ * Primed Linen Oil Canvas Texture:
+ * Seamless interlocking horizontal/vertical woven canvas threads with subtle organic yarn variation.
+ */
+export function generateCanvasWeaveTexture(): string {
+ return buildCachedPng('paper:linen-canvas', PAPER_SIZE, (data, size) => {
+ const rand = createPrng(0xd0d7);
+ const gYarn = makePeriodicGrid(64, rand);
+
+ for (let y = 0; y < size; y++) {
+ const row = y * size * 4;
+ const wy = Math.sin((y / size) * Math.PI * 2 * 32); // 8px thread pitch
+ for (let x = 0; x < size; x++) {
+ const wx = Math.sin((x / size) * Math.PI * 2 * 32);
+ // Alternating over/under plain linen weave
+ const phase = Math.sin(((x + y) / size) * Math.PI * 2 * 16) * 0.22;
+ const weave = (wx * 0.5 + 0.5) * 0.42 + (wy * 0.5 + 0.5) * 0.42 + phase;
+ const organic = samplePeriodic(gYarn, 64, x * 0.25, y * 0.25) * 0.26 + rand() * 0.08;
+ const val = clamp01(weave * 0.72 + organic * 0.45);
+ const v = Math.round(val * 255);
+ const idx = row + x * 4;
+ data[idx] = v;
+ data[idx + 1] = v;
+ data[idx + 2] = v;
+ data[idx + 3] = 255;
+ }
+ }
+ });
+}
+
+/**
+ * Fine Stochastic Film / Stipple Noise Texture:
+ * Seamless high-frequency noise field for Noise Shader & textured gradients.
+ */
+export function generateNoiseGrainTexture(): string {
+ return buildCachedPng('paper:stipple-noise', PAPER_SIZE, (data, size) => {
+ const rand = createPrng(0xe0e8);
+ const gMed = makePeriodicGrid(128, rand);
+
+ for (let y = 0; y < size; y++) {
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const m = samplePeriodic(gMed, 128, x * 0.5, y * 0.5);
+ const hi = rand();
+ const combined = m * 0.35 + hi * 0.65;
+ const crisp = clamp01((combined - 0.14) / 0.72);
+ const v = Math.round(crisp * 255);
+ const idx = row + x * 4;
+ data[idx] = v;
+ data[idx + 1] = v;
+ data[idx + 2] = v;
+ data[idx + 3] = 255;
+ }
+ }
+ });
+}
diff --git a/src/utils/stampEngine.ts b/src/utils/stampEngine.ts
index f2e867f..495ae0d 100644
--- a/src/utils/stampEngine.ts
+++ b/src/utils/stampEngine.ts
@@ -19,7 +19,7 @@ import {
parseColorToRgb,
rgbToHex,
} from './colorMixingEngine';
-import { getPaperGrain } from './pencilEngine';
+import { getPaperGrain, paperGrainTable, GRAIN_SIZE } from './pencilEngine';
import { GpuDab, WebGlBrushEngine } from './webglBrushEngine';
import {
evaluateFastSpline,
@@ -218,6 +218,137 @@ export function applyColorDynamics(
};
}
+// -------------------------------------------------------------
+// Hardware-Accelerated World-Locked Paper Grain Masking (CPU/Color-Mixing Parity)
+// -------------------------------------------------------------
+
+let _invertedGrainCanvas: HTMLCanvasElement | null = null;
+let _grainScratchCanvas: HTMLCanvasElement | null = null;
+let _grainScratchCtx: CanvasRenderingContext2D | null = null;
+let _grainPattern: CanvasPattern | null = null;
+let _customGrainCanvasCache = new WeakMap<HTMLImageElement, { canvas: HTMLCanvasElement; pattern: CanvasPattern | null }>();
+
+function getInvertedGrainPattern(
+ scratchCtx: CanvasRenderingContext2D,
+ paperTextureImage?: HTMLImageElement
+): CanvasPattern | null {
+ if (typeof scratchCtx.createPattern !== 'function') return null;
+
+ if (
+ paperTextureImage &&
+ paperTextureImage.complete !== false &&
+ (paperTextureImage.naturalWidth || paperTextureImage.width) > 0
+ ) {
+ const cached = _customGrainCanvasCache.get(paperTextureImage);
+ if (cached) return cached.pattern;
+ const w = paperTextureImage.naturalWidth || paperTextureImage.width;
+ const h = paperTextureImage.naturalHeight || paperTextureImage.height;
+ const c = document.createElement('canvas');
+ c.width = w;
+ c.height = h;
+ const gCtx = c.getContext('2d', { willReadFrequently: true });
+ if (gCtx && typeof gCtx.getImageData === 'function') {
+ gCtx.drawImage(paperTextureImage, 0, 0, w, h);
+ const img = gCtx.getImageData(0, 0, w, h);
+ const d = img.data;
+ for (let i = 0; i < d.length; i += 4) {
+ const lum = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
+ const inv = 255 - Math.round(lum);
+ d[i] = 255;
+ d[i + 1] = 255;
+ d[i + 2] = 255;
+ d[i + 3] = inv;
+ }
+ gCtx.putImageData(img, 0, 0);
+ const pat = scratchCtx.createPattern(c, 'repeat');
+ _customGrainCanvasCache.set(paperTextureImage, { canvas: c, pattern: pat });
+ return pat;
+ }
+ }
+
+ if (!_invertedGrainCanvas) {
+ const c = document.createElement('canvas');
+ c.width = GRAIN_SIZE;
+ c.height = GRAIN_SIZE;
+ const gCtx = c.getContext('2d');
+ if (!gCtx) return null;
+ const img = gCtx.createImageData(GRAIN_SIZE, GRAIN_SIZE);
+ const d = img.data;
+ for (let i = 0; i < paperGrainTable.length; i++) {
+ const p = i * 4;
+ d[p] = 255;
+ d[p + 1] = 255;
+ d[p + 2] = 255;
+ // Alpha = (1 - paperHeight) so destination-out removes pigment in paper valleys
+ d[p + 3] = 255 - paperGrainTable[i];
+ }
+ gCtx.putImageData(img, 0, 0);
+ _invertedGrainCanvas = c;
+ _grainPattern = scratchCtx.createPattern(c, 'repeat');
+ }
+
+ return _grainPattern;
+}
+
+/**
+ * Applies world-anchored per-pixel paper/canvas grain onto a CPU dab stamp using hardware 2D compositing.
+ * Returns a pooled canvas containing the grain-masked dab, or null if unsupported (falls back to scalar grain).
+ */
+function applyCpuPerPixelPaperGrain(
+ master: CanvasImageSource,
+ worldX: number,
+ worldY: number,
+ renderW: number,
+ renderH: number,
+ grainAmount: number,
+ pressure: number,
+ paperScale: number = 1.0,
+ paperTextureImage?: HTMLImageElement
+): HTMLCanvasElement | null {
+ if (typeof document === 'undefined' || grainAmount <= 0.005) return null;
+ if (!_grainScratchCanvas) {
+ _grainScratchCanvas = document.createElement('canvas');
+ _grainScratchCanvas.width = 128;
+ _grainScratchCanvas.height = 128;
+ _grainScratchCtx = _grainScratchCanvas.getContext('2d');
+ }
+ const sCtx = _grainScratchCtx;
+ if (!sCtx || typeof sCtx.createPattern !== 'function') return null;
+
+ const pat = getInvertedGrainPattern(sCtx, paperTextureImage);
+ if (!pat) return null;
+
+ const bufSize = 128;
+ const p = Math.max(0, Math.min(1, pressure));
+ const heavyExcess = Math.max(0, (p - 0.52) / 0.48);
+ const penetration = Math.min(0.92, p * 0.28 + heavyExcess * heavyExcess * 0.64);
+ const effDensity = Math.max(0, Math.min(0.98, grainAmount * (1.0 - penetration * 0.85)));
+ if (effDensity <= 0.005) return null;
+
+ sCtx.save();
+ sCtx.globalCompositeOperation = 'source-over';
+ sCtx.globalAlpha = 1.0;
+ sCtx.clearRect(0, 0, bufSize, bufSize);
+ sCtx.drawImage(master, 0, 0, bufSize, bufSize);
+
+ // Align world-space paper pattern onto the dab's local [0..bufSize] frame
+ const scale = Math.max(0.1, paperScale);
+ const sx = (bufSize / Math.max(1, renderW)) * scale;
+ const sy = (bufSize / Math.max(1, renderH)) * scale;
+ const offX = -((worldX - renderW * 0.5) / scale);
+ const offY = -((worldY - renderH * 0.5) / scale);
+
+ sCtx.globalCompositeOperation = 'destination-out';
+ sCtx.globalAlpha = effDensity;
+ sCtx.fillStyle = pat;
+ sCtx.scale(sx, sy);
+ sCtx.translate(offX, offY);
+ sCtx.fillRect(-offX, -offY, bufSize / sx, bufSize / sy);
+ sCtx.restore();
+
+ return _grainScratchCanvas;
+}
+
// -------------------------------------------------------------
// High-Efficiency Tinted Tip Master Buffer & Bounded LRU Pools
// -------------------------------------------------------------
@@ -768,7 +899,11 @@ export function drawTexturedDot(
const tiltX = useTilt ? (point.tiltX ?? 0) : 0;
const tiltY = useTilt ? (point.tiltY ?? 0) : 0;
const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180) * (options.tiltScale ?? 1.0);
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
+ const tiltSpread = tiltMagnitude * (options.tiltScale ?? 1.0);
+ const grainPressure = useTilt && tiltMagnitude > 0.01
+ ? effPressure * (1.0 - tiltMagnitude * 0.55)
+ : effPressure;
let angleRad = ((options.angle ?? 0) * Math.PI) / 180;
if (useTilt && tiltMagnitude > 0.05) {
@@ -793,23 +928,29 @@ export function drawTexturedDot(
dabHashFloat(point.x, point.y, 0, 42)
);
effectiveFlow *= sensorOpacity * sensorDensity;
+ if (useTilt && tiltMagnitude > 0.03) {
+ // Contact pressure spreads over larger tilted area -> softer graphite/chalk deposition
+ effectiveFlow *= 1.0 - tiltMagnitude * 0.28;
+ }
// CPU Paper Texture modulation when not rendering on GPU (GPU shader samples paper grain per pixel)
const grainAmount = options.grain ?? options.textureDensity ?? 0;
- if (!gpuDabs && grainAmount > 0.005) {
+ const hasPerPixelCpuGrain = !gpuDabs && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
+ if (!gpuDabs && grainAmount > 0.005 && !hasPerPixelCpuGrain) {
const scale = Math.max(0.1, options.paperTextureScale ?? 1.0);
const gNorm = getPaperGrain(point.x / scale, point.y / scale) / 255.0;
effectiveFlow = applyCspPaperTextureAlpha(
effectiveFlow,
gNorm,
grainAmount,
- effPressure,
+ grainPressure,
options.paperTextureMode ?? 'subtract',
options.paperTextureBrightness ?? 0,
options.paperTextureContrast ?? 0,
Boolean(options.paperTextureInverted)
);
}
+ if (effectiveFlow <= 0.002) return;
const dynamics = options.dynamics;
const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
@@ -877,11 +1018,26 @@ export function drawTexturedDot(
let dotRenderW = isVert ? curDabW * curDabThickness : curDabW;
let dotRenderH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
if (useTilt && tiltMagnitude > 0.01) {
- dotRenderW *= 1.0 + tiltMagnitude * 1.6;
- dotRenderH /= 1.0 + tiltMagnitude * 0.45;
+ dotRenderW *= 1.0 + tiltSpread * 1.85;
+ dotRenderH *= Math.max(0.55, 1.0 - tiltMagnitude * 0.25);
}
const flips = resolveTipFlipSigns(options.flipH, options.flipV, k, curDabX, curDabY);
+ if (curMaster && hasPerPixelCpuGrain) {
+ const grained = applyCpuPerPixelPaperGrain(
+ curMaster,
+ curDabX,
+ curDabY,
+ dotRenderW,
+ dotRenderH,
+ grainAmount,
+ grainPressure,
+ options.paperTextureScale ?? 1.0,
+ options.paperTextureImage
+ );
+ if (grained) curMaster = grained;
+ }
+
if (options.spray?.enabled) {
const pCount = options.spray.density;
const pSize = Math.max(1, options.spray.size);
@@ -906,7 +1062,7 @@ export function drawTexturedDot(
g: dabG,
b: dabB,
alpha: curDabAlpha,
- pressure: effPressure,
+ pressure: grainPressure,
strokeDist: 0,
flipX: flips.signX,
flipY: flips.signY,
@@ -943,7 +1099,7 @@ export function drawTexturedDot(
g: dabG,
b: dabB,
alpha: curDabAlpha,
- pressure: effPressure,
+ pressure: grainPressure,
strokeDist: 0,
flipX: flips.signX,
flipY: flips.signY,
@@ -1258,7 +1414,11 @@ export function drawTexturedCubicBezierSegment(
const tiltX = useTilt ? pt.tiltX : 0;
const tiltY = useTilt ? pt.tiltY : 0;
const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180) * (options.tiltScale ?? 1.0);
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
+ const tiltSpread = tiltMagnitude * (options.tiltScale ?? 1.0);
+ const grainPressure = useTilt && tiltMagnitude > 0.01
+ ? effPressure * (1.0 - tiltMagnitude * 0.55)
+ : effPressure;
// Multi-sensor CSP size modulation
if (options.sizeSensor) {
@@ -1316,6 +1476,10 @@ export function drawTexturedCubicBezierSegment(
dabHashFloat(pt.x, pt.y, dabSeq, 52)
);
}
+ if (useTilt && tiltMagnitude > 0.03) {
+ // Spread graphite/chalk deposition over wider tilted contact patch
+ dabAlpha *= 1.0 - tiltMagnitude * 0.28;
+ }
if (isColorMixing && reservoir) {
let sampled = { r: 255, g: 255, b: 255, a: 0 };
@@ -1344,7 +1508,7 @@ export function drawTexturedCubicBezierSegment(
dabColor = mixed.colorHex;
dabAlpha = mixed.alpha;
- if (sampler) {
+ if (sampler && mixed.alpha > 0.002) {
sampler.depositDab(
pt.x,
pt.y,
@@ -1358,14 +1522,15 @@ export function drawTexturedCubicBezierSegment(
}
// CPU paper grain parity (when rendering live on Canvas2D without GPU batch)
- if (!gpuDabs && grainAmount > 0.005) {
+ const hasPerPixelCpuGrain = !gpuDabs && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
+ if (!gpuDabs && grainAmount > 0.005 && !hasPerPixelCpuGrain) {
const scale = Math.max(0.1, options.paperTextureScale ?? 1.0);
const gNorm = getPaperGrain(pt.x / scale, pt.y / scale) / 255.0;
dabAlpha = applyCspPaperTextureAlpha(
dabAlpha,
gNorm,
grainAmount,
- effPressure,
+ grainPressure,
options.paperTextureMode ?? 'subtract',
options.paperTextureBrightness ?? 0,
options.paperTextureContrast ?? 0,
@@ -1473,14 +1638,31 @@ export function drawTexturedCubicBezierSegment(
let finalW = isVert ? curDabW * curDabThickness : curDabW;
let finalH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
if (useTilt && tiltMagnitude > 0.01) {
- finalW *= 1.0 + tiltMagnitude * 1.6;
- finalH /= 1.0 + tiltMagnitude * 0.45;
+ finalW *= 1.0 + tiltSpread * 1.85;
+ finalH *= Math.max(0.55, 1.0 - tiltMagnitude * 0.25);
}
stepRefW = finalW;
stepRefH = finalH;
+ if (curDabAlpha <= 0.002) continue;
+
const flips = resolveTipFlipSigns(options.flipH, options.flipV, seedIdx, curDabX, curDabY);
+ if (curMaster && hasPerPixelCpuGrain) {
+ const grained = applyCpuPerPixelPaperGrain(
+ curMaster,
+ curDabX,
+ curDabY,
+ finalW,
+ finalH,
+ grainAmount,
+ grainPressure,
+ options.paperTextureScale ?? 1.0,
+ options.paperTextureImage
+ );
+ if (grained) curMaster = grained;
+ }
+
if (options.spray?.enabled) {
const pCount = options.spray.density;
const pSize = Math.max(1, options.spray.size);
@@ -1505,7 +1687,7 @@ export function drawTexturedCubicBezierSegment(
g: dabG,
b: dabB,
alpha: curDabAlpha,
- pressure: effPressure,
+ pressure: grainPressure,
strokeDist,
flipX: flips.signX,
flipY: flips.signY,
@@ -1542,7 +1724,7 @@ export function drawTexturedCubicBezierSegment(
g: dabG,
b: dabB,
alpha: curDabAlpha,
- pressure: effPressure,
+ pressure: grainPressure,
strokeDist,
flipX: flips.signX,
flipY: flips.signY,
@@ -1835,7 +2017,8 @@ export function drawRadialDot(
const tiltX = useTilt ? (point.tiltX ?? 0) : 0;
const tiltY = useTilt ? (point.tiltY ?? 0) : 0;
const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180) * (mixingOptions?.tiltScale ?? 1.0);
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
+ const tiltSpread = tiltMagnitude * (mixingOptions?.tiltScale ?? 1.0);
if (mixingOptions?.sizeSensor) {
w = Math.max(
@@ -1900,7 +2083,7 @@ export function drawRadialDot(
dabColor = mixed.colorHex;
dabFlow = mixed.alpha;
- if (mixingOptions!.sampler) {
+ if (mixingOptions!.sampler && mixed.alpha > 0.002) {
mixingOptions!.sampler.depositDab(
point.x,
point.y,
@@ -1912,12 +2095,13 @@ export function drawRadialDot(
);
}
}
+ if (dabFlow <= 0.002) return;
let dotW = w;
let dotAngle = angleRad;
if (useTilt && tiltMagnitude > 0.01) {
const tiltAzimuth = Math.atan2(tiltY, tiltX);
- dotW = w * (1.0 + tiltMagnitude * 1.8);
+ dotW = w * (1.0 + tiltSpread * 1.8);
if (tiltMagnitude > 0.05) {
dotAngle = tiltAzimuth;
}
@@ -2010,7 +2194,7 @@ export function drawRadialDot(
let finalW = isVert ? curDabW * curDabThickness : curDabW;
let finalH = isVert ? curDabW : curDabW * curDabThickness;
if (useTilt && tiltMagnitude > 0.01) {
- finalW = w * (1.0 + tiltMagnitude * 1.8);
+ finalW = w * (1.0 + tiltSpread * 1.8);
finalH = (w * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
}
@@ -2121,7 +2305,8 @@ export function drawRadialCubicBezierSegment(
const tiltX = useTilt ? pt.tiltX : 0;
const tiltY = useTilt ? pt.tiltY : 0;
const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180) * (mixingOptions?.tiltScale ?? 1.0);
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
+ const tiltSpread = tiltMagnitude * (mixingOptions?.tiltScale ?? 1.0);
if (mixingOptions?.sizeSensor) {
curWidth *= evaluateCspSensor(
@@ -2211,7 +2396,7 @@ export function drawRadialCubicBezierSegment(
}
dabFlow = mixed.alpha;
- if (sampler) {
+ if (sampler && mixed.alpha > 0.002) {
sampler.depositDab(
pt.x,
pt.y,
@@ -2315,12 +2500,14 @@ export function drawRadialCubicBezierSegment(
let finalW = isVert ? curDabW * curDabThickness : curDabW;
let finalH = isVert ? curDabW : curDabW * curDabThickness;
if (useTilt && tiltMagnitude > 0.01) {
- finalW = curDabW * (1.0 + tiltMagnitude * 1.8);
+ finalW = curDabW * (1.0 + tiltSpread * 1.8);
finalH = (curDabW * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
}
stepRefW = finalW;
stepRefH = finalH;
+ if (curDabFlow <= 0.002) continue;
+
const flips = resolveTipFlipSigns(mixingOptions?.flipH, mixingOptions?.flipV, seedIdx, curDabX, curDabY);
if (gpuDabs) {
diff --git a/src/utils/webglBrushEngine.ts b/src/utils/webglBrushEngine.ts
index 536855f..d59f15c 100644
--- a/src/utils/webglBrushEngine.ts
+++ b/src/utils/webglBrushEngine.ts
@@ -257,16 +257,20 @@ void main() {
// 2. CSP 5-Mode Paper Grain / Canvas Tooth
if (u_paperGrain > 0.001) {
float g = samplePaperTooth(v_worldPos);
- float penetration = clamp(v_pressure * 0.65, 0.0, 0.85);
- float effDensity = u_paperGrain * (1.0 - penetration * 0.6);
+ float p = clamp(v_pressure, 0.0, 1.0);
+ float heavyExcess = max(0.0, (p - 0.52) / 0.48);
+ float penetration = min(0.92, p * 0.28 + heavyExcess * heavyExcess * 0.64);
+ float effDensity = u_paperGrain * (1.0 - penetration * 0.85);
if (u_paperMode == 1) {
// Multiply
tipAlpha *= (1.0 - effDensity * (1.0 - g));
} else if (u_paperMode == 2) {
- // Compare
- float thresh = (1.0 - g) * effDensity;
- tipAlpha = tipAlpha > thresh ? clamp((tipAlpha - thresh) / max(0.08, 1.0 - thresh), 0.0, 1.0) : 0.0;
+ // Compare: physical dry-media height-field tooth (true zero in recessed paper valleys)
+ float contactHeight = g * (0.22 + 0.78 * tipAlpha);
+ float cutoff = effDensity * 0.68;
+ float tooth = smoothstep(cutoff - 0.05, cutoff + 0.16, contactHeight);
+ tipAlpha *= tooth;
} else if (u_paperMode == 3) {
// Overlay
float ov = tipAlpha < 0.5 ? (2.0 * tipAlpha * g) : (1.0 - 2.0 * (1.0 - tipAlpha) * (1.0 - g));
@@ -783,6 +787,7 @@ export class WebGlBrushEngine {
*/
public getOrCreateTipTexture(image: HTMLImageElement, repeatWrap: boolean = false): WebGLTexture | null {
if (!this.gl || !image || !image.src) return null;
+ if (image.complete === false || (image.naturalWidth || image.width || 0) <= 0) return null;
const cacheKey = `${repeatWrap ? 'rep:' : 'tip:'}${image.src}`;
const cached = this.tipTexturesMap.get(cacheKey);
if (cached) return cached;
@@ -806,7 +811,16 @@ export class WebGlBrushEngine {
const wrap = repeatWrap ? gl.REPEAT : gl.CLAMP_TO_EDGE;
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ const texW = image.naturalWidth || image.width || 0;
+ const texH = image.naturalHeight || image.height || 0;
+ const isPow2 = texW > 0 && texH > 0 && (texW & (texW - 1)) === 0 && (texH & (texH - 1)) === 0;
+ if (!repeatWrap && isPow2 && typeof gl.generateMipmap === 'function') {
+ // Trilinear mipmapping keeps 128x128 pencil tips crisp and alias-free at 2px-10px sizes
+ gl.generateMipmap(gl.TEXTURE_2D);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
+ } else {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ }
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
this.tipTexturesMap.set(cacheKey, tex);