Compare commits

...

2 Commits

Author SHA1 Message Date
ben 7d5707bcf6 chore: add .gitignore, remove node_modules from tracking 2026-05-15 01:18:41 -07:00
ben 31d0464a60 feat: V1 prototype — Vite/React/TS tileset generator
- Scaffold: package.json, tsconfig.json, vite.config.ts, index.html
- src/lib/imageProcessor.ts: full pipeline (normalize, offset, seam repair, export, validation)
- src/components/UploadPanel.tsx: drag-and-drop, file picker, clipboard paste
- src/components/SettingsPanel.tsx: all controls per spec
- src/components/PreviewPanel.tsx: Original / Tileable / Repeated tabs
- src/components/ErrorBanner.tsx: dismissible error/warning banners
- src/App.tsx: root component wiring everything together
- src/index.css: dark premium glassmorphism theme w/ Inter font
2026-05-15 01:18:26 -07:00
14 changed files with 3785 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
# Dependencies
node_modules/
# Build output
dist/
dist-ssr/
# Vite cache
.vite/
# Editor
.DS_Store
*.local
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tileset Generator — Create Seamless Tileable Textures</title>
<meta name="description" content="Free browser-based tool to convert any image into a seamlessly tileable WebP texture. Perfect for game engines, web backgrounds, and 3D materials." />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1885
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "tileset-generator",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.7.2",
"vite": "^6.0.3"
}
}
+139
View File
@@ -0,0 +1,139 @@
import { useState, useCallback, useRef } from 'react';
import UploadPanel from './components/UploadPanel';
import SettingsPanel from './components/SettingsPanel';
import PreviewPanel from './components/PreviewPanel';
import ErrorBanner, { Banner } from './components/ErrorBanner';
import {
defaultSettings,
TilesetSettings,
generateTileableTexture,
exportAsWebP,
} from './lib/imageProcessor';
let bannerCounter = 0;
export default function App() {
const [sourceFile, setSourceFile] = useState<File | null>(null);
const [settings, setSettings] = useState<TilesetSettings>(defaultSettings);
const [resultCanvas, setResultCanvas] = useState<HTMLCanvasElement | null>(null);
const [isProcessing, setIsProcessing] = useState(false);
const [processingStep, setProcessingStep] = useState('');
const [banners, setBanners] = useState<Banner[]>([]);
const processingRef = useRef(false);
const addBanner = (type: Banner['type'], message: string) => {
const id = String(++bannerCounter);
setBanners((prev) => [...prev, { id, type, message }]);
};
const dismissBanner = (id: string) =>
setBanners((prev) => prev.filter((b) => b.id !== id));
const handleFileSelect = useCallback((file: File) => {
setSourceFile(file);
setResultCanvas(null); // Clear old result when new image loaded
}, []);
const handleGenerate = async () => {
if (!sourceFile || processingRef.current) return;
processingRef.current = true;
setIsProcessing(true);
setResultCanvas(null);
try {
const canvas = await generateTileableTexture(
sourceFile,
settings,
(step) => setProcessingStep(step),
);
setResultCanvas(canvas);
} catch (err) {
const msg = err instanceof Error ? err.message : 'An unknown error occurred.';
addBanner('error', `Processing failed: ${msg}`);
} finally {
setIsProcessing(false);
processingRef.current = false;
setProcessingStep('');
}
};
const handleExport = async () => {
if (!resultCanvas) return;
try {
await exportAsWebP(
resultCanvas,
settings.webpQuality,
settings.outputWidth,
settings.outputHeight,
);
} catch (err) {
addBanner('error', 'Export failed. Your browser may not support WebP export.');
}
};
return (
<div className="app">
{/* Header */}
<header className="app-header">
<div className="app-header-logo">
<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
<rect width="28" height="28" rx="7" fill="url(#grad)" />
<rect x="2" y="2" width="11" height="11" rx="2" fill="rgba(255,255,255,0.85)" />
<rect x="15" y="2" width="11" height="11" rx="2" fill="rgba(255,255,255,0.45)" />
<rect x="2" y="15" width="11" height="11" rx="2" fill="rgba(255,255,255,0.45)" />
<rect x="15" y="15" width="11" height="11" rx="2" fill="rgba(255,255,255,0.85)" />
<defs>
<linearGradient id="grad" x1="0" y1="0" x2="28" y2="28">
<stop stopColor="#3b82f6" />
<stop offset="1" stopColor="#8b5cf6" />
</linearGradient>
</defs>
</svg>
<div>
<h1>Tileset Generator</h1>
<div className="app-header-subtitle">Upload image Generate tileable WebP texture</div>
</div>
</div>
<div className="app-badge">V1 · Client-Side</div>
</header>
{/* Body */}
<div className="app-body">
{/* Sidebar */}
<aside className="sidebar">
{banners.length > 0 && (
<ErrorBanner banners={banners} onDismiss={dismissBanner} />
)}
<UploadPanel
onFileSelect={handleFileSelect}
onError={(msg) => addBanner('error', msg)}
onWarning={(msg) => addBanner('warning', msg)}
currentFile={sourceFile}
/>
<SettingsPanel
settings={settings}
onChange={setSettings}
onGenerate={handleGenerate}
onExport={handleExport}
canGenerate={!!sourceFile}
canExport={!!resultCanvas && !isProcessing}
isProcessing={isProcessing}
/>
</aside>
{/* Preview */}
<main className="preview-area">
<PreviewPanel
sourceFile={sourceFile}
resultCanvas={resultCanvas}
settings={settings}
isProcessing={isProcessing}
processingStep={processingStep}
/>
</main>
</div>
</div>
);
}
+56
View File
@@ -0,0 +1,56 @@
interface Banner {
id: string;
type: 'error' | 'warning' | 'info';
message: string;
}
interface Props {
banners: Banner[];
onDismiss: (id: string) => void;
}
export default function ErrorBanner({ banners, onDismiss }: Props) {
if (banners.length === 0) return null;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{banners.map((b) => (
<div key={b.id} className={`banner banner-${b.type}`} role="alert">
<BannerIcon type={b.type} />
<span>{b.message}</span>
<button
className="banner-close"
onClick={() => onDismiss(b.id)}
aria-label="Dismiss"
>
</button>
</div>
))}
</div>
);
}
function BannerIcon({ type }: { type: Banner['type'] }) {
if (type === 'error') {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
<circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
);
}
if (type === 'warning') {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" />
</svg>
);
}
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
<circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
);
}
export type { Banner };
+187
View File
@@ -0,0 +1,187 @@
import { useRef, useEffect, useState } from 'react';
import { PreviewMode, TilesetSettings } from '../lib/imageProcessor';
type Tab = 'original' | 'tile' | 'repeat';
interface Props {
sourceFile: File | null;
resultCanvas: HTMLCanvasElement | null;
settings: TilesetSettings;
isProcessing: boolean;
processingStep: string;
}
export default function PreviewPanel({
sourceFile,
resultCanvas,
settings,
isProcessing,
processingStep,
}: Props) {
const [tab, setTab] = useState<Tab>('original');
const [sourceUrl, setSourceUrl] = useState<string | null>(null);
const [resultUrl, setResultUrl] = useState<string | null>(null);
const repeatRef = useRef<HTMLDivElement>(null);
// Generate object URL for source image
useEffect(() => {
if (!sourceFile) { setSourceUrl(null); return; }
const url = URL.createObjectURL(sourceFile);
setSourceUrl(url);
return () => URL.revokeObjectURL(url);
}, [sourceFile]);
// Generate data URL for result canvas
useEffect(() => {
if (!resultCanvas) { setResultUrl(null); return; }
setResultUrl(resultCanvas.toDataURL('image/png'));
// Switch to tile tab automatically when result arrives
setTab('tile');
}, [resultCanvas]);
// Update repeated preview background
useEffect(() => {
if (!repeatRef.current || !resultUrl) return;
const gridCount = previewModeToGrid(settings.previewMode);
const tileSize = Math.floor(400 / gridCount);
repeatRef.current.style.backgroundImage = `url(${resultUrl})`;
repeatRef.current.style.backgroundSize = `${tileSize}px ${tileSize}px`;
repeatRef.current.style.backgroundRepeat = 'repeat';
repeatRef.current.style.width = `${tileSize * gridCount}px`;
repeatRef.current.style.height = `${tileSize * gridCount}px`;
}, [resultUrl, settings.previewMode]);
const hasResult = !!resultCanvas;
const hasSource = !!sourceFile;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{/* Tab bar */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10 }}>
<div className="preview-tabs">
<button
id="preview-tab-original"
className={`preview-tab ${tab === 'original' ? 'active' : ''}`}
onClick={() => setTab('original')}
>
Original
</button>
<button
id="preview-tab-tile"
className={`preview-tab ${tab === 'tile' ? 'active' : ''}`}
onClick={() => setTab('tile')}
disabled={!hasResult}
>
Tileable
</button>
<button
id="preview-tab-repeat"
className={`preview-tab ${tab === 'repeat' ? 'active' : ''}`}
onClick={() => setTab('repeat')}
disabled={!hasResult}
>
Repeated
</button>
</div>
{hasResult && (
<div className="preview-stats">
<span className="preview-stat">
<strong>{settings.outputWidth}</strong>×<strong>{settings.outputHeight}</strong> px
</span>
<span className="preview-stat">WebP <strong>{settings.webpQuality}%</strong></span>
</div>
)}
</div>
{/* Content */}
{tab === 'original' && (
<div className="preview-canvas-wrap fade-in" style={{ position: 'relative' }}>
{hasSource ? (
<img src={sourceUrl!} alt="Original uploaded image" />
) : (
<EmptyState label="Upload an image to preview it here" />
)}
</div>
)}
{tab === 'tile' && (
<div className="preview-canvas-wrap fade-in" style={{ position: 'relative' }}>
{isProcessing && (
<div className="spinner-overlay">
<div className="spinner" />
<span className="spinner-text">{processingStep}</span>
</div>
)}
{hasResult ? (
<img src={resultUrl!} alt="Generated tileable texture" />
) : (
<EmptyState label={hasSource ? 'Press Generate to process' : 'Upload an image first'} />
)}
</div>
)}
{tab === 'repeat' && (
<div className="fade-in" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
{hasResult ? (
<div style={{ position: 'relative' }}>
<div
className="preview-repeat-wrap"
ref={repeatRef}
aria-label="Repeated texture preview"
/>
<div style={{
position: 'absolute',
bottom: 8,
right: 8,
background: 'rgba(0,0,0,0.6)',
borderRadius: 4,
padding: '2px 8px',
fontSize: '0.7rem',
color: 'var(--text-secondary)',
backdropFilter: 'blur(4px)',
}}>
{previewModeLabel(settings.previewMode)} repeat
</div>
</div>
) : (
<div className="preview-canvas-wrap" style={{ width: '100%' }}>
<EmptyState label={hasSource ? 'Press Generate to preview tiling' : 'Upload an image first'} />
</div>
)}
</div>
)}
</div>
);
}
function EmptyState({ label }: { label: string }) {
return (
<div className="preview-empty">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<rect x="3" y="3" width="18" height="18" rx="2" />
<circle cx="8.5" cy="8.5" r="1.5" />
<polyline points="21 15 16 10 5 21" />
</svg>
<p className="preview-empty-text">{label}</p>
</div>
);
}
function previewModeToGrid(mode: PreviewMode): number {
switch (mode) {
case 'single': return 1;
case 'repeat-2': return 2;
case 'repeat-3': return 3;
case 'repeat-4': return 4;
}
}
function previewModeLabel(mode: PreviewMode): string {
switch (mode) {
case 'single': return '1×1';
case 'repeat-2': return '2×2';
case 'repeat-3': return '3×3';
case 'repeat-4': return '4×4';
}
}
+304
View File
@@ -0,0 +1,304 @@
import { useState } from 'react';
import {
TilesetSettings,
ResizeMode,
PreviewMode,
DetailPreservation,
} from '../lib/imageProcessor';
interface Props {
settings: TilesetSettings;
onChange: (s: TilesetSettings) => void;
onGenerate: () => void;
onExport: () => void;
canGenerate: boolean;
canExport: boolean;
isProcessing: boolean;
}
type OutputSizePreset = '512' | '1024' | '2048' | 'custom';
export default function SettingsPanel({
settings,
onChange,
onGenerate,
onExport,
canGenerate,
canExport,
isProcessing,
}: Props) {
const [sizePreset, setSizePreset] = useState<OutputSizePreset>('1024');
const set = <K extends keyof TilesetSettings>(key: K, value: TilesetSettings[K]) =>
onChange({ ...settings, [key]: value });
const handleSizePreset = (preset: OutputSizePreset) => {
setSizePreset(preset);
if (preset !== 'custom') {
const n = parseInt(preset);
onChange({ ...settings, outputWidth: n, outputHeight: n });
}
};
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{/* Output Size */}
<div className="panel">
<div className="panel-header">
<div className="panel-header-icon"><SizeIcon /></div>
<span className="panel-title">Output Size</span>
</div>
<div className="panel-body">
<div className="form-group">
<label className="form-label">Preset</label>
<div className="seg-group">
{(['512', '1024', '2048', 'custom'] as OutputSizePreset[]).map((p) => (
<button
key={p}
className={`seg-btn ${sizePreset === p ? 'active' : ''}`}
onClick={() => handleSizePreset(p)}
id={`size-preset-${p}`}
>
{p === 'custom' ? 'Custom' : `${p}²`}
</button>
))}
</div>
</div>
{sizePreset === 'custom' && (
<div className="form-group">
<label className="form-label">Dimensions (px)</label>
<div className="size-row">
<input
type="number"
id="output-width"
min={64} max={4096} step={64}
value={settings.outputWidth}
onChange={(e) => set('outputWidth', parseInt(e.target.value) || 1024)}
/>
<span className="size-row-sep">×</span>
<input
type="number"
id="output-height"
min={64} max={4096} step={64}
value={settings.outputHeight}
onChange={(e) => set('outputHeight', parseInt(e.target.value) || 1024)}
/>
</div>
</div>
)}
<div className="form-group">
<label className="form-label">Resize Mode</label>
<select
id="resize-mode"
value={settings.resizeMode}
onChange={(e) => set('resizeMode', e.target.value as ResizeMode)}
>
<option value="crop-square">Crop to Square</option>
<option value="fit">Fit Within Size</option>
<option value="stretch">Stretch to Size</option>
<option value="keep-aspect">Keep Aspect Ratio</option>
</select>
</div>
</div>
</div>
{/* Seam Settings */}
<div className="panel">
<div className="panel-header">
<div className="panel-header-icon"><SeamIcon /></div>
<span className="panel-title">Seam Repair</span>
</div>
<div className="panel-body">
<div className="form-group">
<label className="form-label">
Seam Width
<span className="form-label-value">{settings.seamWidth} px</span>
</label>
<input
type="range"
id="seam-width"
min={8} max={128} step={4}
value={settings.seamWidth}
onChange={(e) => set('seamWidth', parseInt(e.target.value))}
/>
</div>
<div className="form-group">
<label className="form-label">
Blend Strength
<span className="form-label-value">{settings.blendStrength}%</span>
</label>
<input
type="range"
id="blend-strength"
min={0} max={100} step={5}
value={settings.blendStrength}
onChange={(e) => set('blendStrength', parseInt(e.target.value))}
/>
</div>
<div className="form-group">
<label className="form-label">Detail Preservation</label>
<div className="seg-group">
{(['low', 'medium', 'high'] as DetailPreservation[]).map((d) => (
<button
key={d}
id={`detail-${d}`}
className={`seg-btn ${settings.detailPreservation === d ? 'active' : ''}`}
onClick={() => set('detailPreservation', d)}
>
{d.charAt(0).toUpperCase() + d.slice(1)}
</button>
))}
</div>
</div>
</div>
</div>
{/* Preview */}
<div className="panel">
<div className="panel-header">
<div className="panel-header-icon"><EyeIcon /></div>
<span className="panel-title">Preview</span>
</div>
<div className="panel-body">
<div className="form-group">
<label className="form-label">Repeat Grid</label>
<div className="seg-group">
{([
['single', '1×1'],
['repeat-2', '2×2'],
['repeat-3', '3×3'],
['repeat-4', '4×4'],
] as [PreviewMode, string][]).map(([mode, label]) => (
<button
key={mode}
id={`preview-mode-${mode}`}
className={`seg-btn ${settings.previewMode === mode ? 'active' : ''}`}
onClick={() => set('previewMode', mode)}
>
{label}
</button>
))}
</div>
</div>
</div>
</div>
{/* Export */}
<div className="panel">
<div className="panel-header">
<div className="panel-header-icon"><ExportIcon /></div>
<span className="panel-title">Export</span>
</div>
<div className="panel-body">
<div className="form-group">
<label className="form-label">
WebP Quality
<span className="form-label-value">{settings.webpQuality}%</span>
</label>
<input
type="range"
id="webp-quality"
min={1} max={100} step={1}
value={settings.webpQuality}
onChange={(e) => set('webpQuality', parseInt(e.target.value))}
/>
</div>
<div className="divider" />
<div className="btn-row">
<button
id="generate-btn"
className="btn btn-primary"
onClick={onGenerate}
disabled={!canGenerate || isProcessing}
>
{isProcessing ? (
<><SpinnerInline />Processing</>
) : (
<><SparkleIcon />Generate</>
)}
</button>
<button
id="export-btn"
className="btn btn-success"
onClick={onExport}
disabled={!canExport}
>
<DownloadIcon />Export .webp
</button>
</div>
</div>
</div>
</div>
);
}
// ── Inline icons ─────────────────────────────────────────────────────────────
function SizeIcon() {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="3" y="3" width="18" height="18" rx="2" /><path d="M3 9h18M9 21V9" />
</svg>
);
}
function SeamIcon() {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<line x1="12" y1="2" x2="12" y2="22" /><line x1="2" y1="12" x2="22" y2="12" />
<circle cx="12" cy="12" r="4" />
</svg>
);
}
function EyeIcon() {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" />
</svg>
);
}
function ExportIcon() {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" y1="15" x2="12" y2="3" />
</svg>
);
}
function DownloadIcon() {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" y1="15" x2="12" y2="3" />
</svg>
);
}
function SparkleIcon() {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
</svg>
);
}
function SpinnerInline() {
return (
<span style={{
display: 'inline-block',
width: 14,
height: 14,
border: '2px solid rgba(255,255,255,0.3)',
borderTopColor: '#fff',
borderRadius: '50%',
animation: 'spin 0.7s linear infinite',
}} />
);
}
+126
View File
@@ -0,0 +1,126 @@
import { useRef, useState, DragEvent, ChangeEvent, useEffect } from 'react';
import { validateFile, validateImageDimensions } from '../lib/imageProcessor';
interface Props {
onFileSelect: (file: File) => void;
onError: (msg: string) => void;
onWarning: (msg: string) => void;
currentFile: File | null;
}
export default function UploadPanel({ onFileSelect, onError, onWarning, currentFile }: Props) {
const [dragging, setDragging] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const handleFile = async (file: File) => {
const typeResult = validateFile(file);
if (!typeResult.ok) { onError(typeResult.error!); return; }
const dimResult = await validateImageDimensions(file);
if (!dimResult.ok) { onError(dimResult.error!); return; }
if (dimResult.warning) onWarning(dimResult.warning);
onFileSelect(file);
};
const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) handleFile(file);
};
const onDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
setDragging(false);
const file = e.dataTransfer.files[0];
if (file) handleFile(file);
};
const onDragOver = (e: DragEvent<HTMLDivElement>) => { e.preventDefault(); setDragging(true); };
const onDragLeave = () => setDragging(false);
// Clipboard paste listener
useEffect(() => {
const handler = (e: ClipboardEvent) => {
const item = Array.from(e.clipboardData?.items ?? []).find(
(i) => i.kind === 'file' && i.type.startsWith('image/'),
);
if (item) {
const file = item.getAsFile();
if (file) handleFile(file);
}
};
window.addEventListener('paste', handler);
return () => window.removeEventListener('paste', handler);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div className="panel">
<div className="panel-header">
<div className="panel-header-icon">
<UploadIcon />
</div>
<span className="panel-title">Image Input</span>
</div>
<div className="panel-body">
<div
className={`upload-zone ${dragging ? 'drag-over' : ''}`}
onDrop={onDrop}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onClick={() => inputRef.current?.click()}
role="button"
tabIndex={0}
aria-label="Upload image"
onKeyDown={(e) => e.key === 'Enter' && inputRef.current?.click()}
>
<input
ref={inputRef}
type="file"
accept=".png,.jpg,.jpeg,.webp,image/png,image/jpeg,image/webp"
onChange={onInputChange}
onClick={(e) => e.stopPropagation()}
id="image-file-input"
style={{ position: 'absolute', inset: 0, opacity: 0, cursor: 'pointer' }}
/>
<div className="upload-zone-icon">
<UploadIcon size={22} />
</div>
<div className="upload-zone-text">
<strong>Drop image here</strong>
<span>or click to browse · PNG, JPG, WebP</span>
</div>
{currentFile && (
<div className="upload-filename">
<CheckIcon size={12} />
{currentFile.name}
</div>
)}
</div>
<div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textAlign: 'center' }}>
Tip: you can also paste an image with <kbd style={{ background: 'rgba(255,255,255,0.08)', padding: '1px 5px', borderRadius: 3, fontSize: '0.7rem' }}>Ctrl+V</kbd>
</div>
</div>
</div>
);
}
// ── Icons ───────────────────────────────────────────────────────────────────
function UploadIcon({ size = 16 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="16 16 12 12 8 16" />
<line x1="12" y1="12" x2="12" y2="21" />
<path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3" />
</svg>
);
}
function CheckIcon({ size = 14 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
);
}
+666
View File
@@ -0,0 +1,666 @@
/* ── Reset & base ──────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--font: 'Inter', system-ui, sans-serif;
/* Palette */
--bg-base: #0b0e1a;
--bg-surface: #111827;
--bg-panel: rgba(17, 24, 39, 0.85);
--bg-card: rgba(255, 255, 255, 0.04);
--bg-hover: rgba(255, 255, 255, 0.07);
--border: rgba(255, 255, 255, 0.10);
--border-focus: rgba(99, 179, 237, 0.60);
--accent: #3b82f6;
--accent-glow: rgba(59, 130, 246, 0.35);
--accent-hover: #60a5fa;
--success: #10b981;
--warning: #f59e0b;
--danger: #ef4444;
--text-primary: #f0f4ff;
--text-secondary: #9ba3b8;
--text-muted: #5a6380;
--radius-sm: 6px;
--radius: 10px;
--radius-lg: 16px;
--radius-xl: 22px;
--shadow-sm: 0 1px 3px rgba(0,0,0,0.4);
--shadow: 0 4px 16px rgba(0,0,0,0.5);
--shadow-lg: 0 8px 32px rgba(0,0,0,0.7);
--transition: 0.18s cubic-bezier(0.4, 0, 0.2, 1);
}
html, body {
height: 100%;
font-family: var(--font);
background-color: var(--bg-base);
color: var(--text-primary);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
#root { min-height: 100vh; display: flex; flex-direction: column; }
/* ── Scrollbar ─────────────────────────────────────────────────── */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.15); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.25); }
/* ── Layout ────────────────────────────────────────────────────── */
.app {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.app-header {
padding: 18px 32px;
border-bottom: 1px solid var(--border);
background: rgba(11, 14, 26, 0.90);
backdrop-filter: blur(12px);
position: sticky;
top: 0;
z-index: 100;
display: flex;
align-items: center;
gap: 16px;
}
.app-header-logo {
display: flex;
align-items: center;
gap: 10px;
}
.app-header-logo svg { flex-shrink: 0; }
.app-header h1 {
font-size: 1.15rem;
font-weight: 700;
letter-spacing: -0.01em;
color: var(--text-primary);
white-space: nowrap;
}
.app-header-subtitle {
font-size: 0.8rem;
color: var(--text-muted);
margin-top: 1px;
}
.app-badge {
margin-left: auto;
padding: 4px 10px;
background: var(--accent-glow);
border: 1px solid var(--accent);
border-radius: 100px;
font-size: 0.7rem;
font-weight: 600;
color: var(--accent-hover);
letter-spacing: 0.05em;
text-transform: uppercase;
}
.app-body {
flex: 1;
display: grid;
grid-template-columns: 340px 1fr;
gap: 0;
overflow: hidden;
}
.sidebar {
border-right: 1px solid var(--border);
overflow-y: auto;
padding: 24px 20px;
display: flex;
flex-direction: column;
gap: 20px;
background: linear-gradient(180deg, rgba(17,24,39,0.6) 0%, rgba(11,14,26,0.4) 100%);
}
.preview-area {
overflow-y: auto;
padding: 24px 28px;
display: flex;
flex-direction: column;
gap: 24px;
}
/* ── Glass panels ──────────────────────────────────────────────── */
.panel {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
backdrop-filter: blur(8px);
overflow: hidden;
}
.panel-header {
display: flex;
align-items: center;
gap: 8px;
padding: 14px 16px;
border-bottom: 1px solid var(--border);
background: rgba(255,255,255,0.025);
}
.panel-header-icon {
width: 28px;
height: 28px;
border-radius: var(--radius-sm);
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-hover);
color: var(--accent);
flex-shrink: 0;
}
.panel-title {
font-size: 0.8rem;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--text-secondary);
}
.panel-body {
padding: 16px;
display: flex;
flex-direction: column;
gap: 14px;
}
/* ── Upload zone ───────────────────────────────────────────────── */
.upload-zone {
position: relative;
min-height: 160px;
border: 2px dashed var(--border);
border-radius: var(--radius-lg);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
cursor: pointer;
transition: border-color var(--transition), background var(--transition), transform var(--transition);
text-align: center;
padding: 20px;
overflow: hidden;
}
.upload-zone::before {
content: '';
position: absolute;
inset: 0;
background: radial-gradient(ellipse at 50% 100%, var(--accent-glow) 0%, transparent 70%);
opacity: 0;
transition: opacity var(--transition);
}
.upload-zone:hover,
.upload-zone.drag-over {
border-color: var(--accent);
background: rgba(59, 130, 246, 0.06);
}
.upload-zone:hover::before,
.upload-zone.drag-over::before {
opacity: 1;
}
.upload-zone.drag-over {
transform: scale(1.01);
}
.upload-zone-icon {
width: 48px;
height: 48px;
border-radius: 50%;
background: rgba(59, 130, 246, 0.15);
display: flex;
align-items: center;
justify-content: center;
color: var(--accent);
position: relative;
z-index: 1;
transition: background var(--transition), transform var(--transition);
}
.upload-zone:hover .upload-zone-icon {
background: rgba(59, 130, 246, 0.25);
transform: translateY(-2px);
}
.upload-zone-text {
position: relative;
z-index: 1;
}
.upload-zone-text strong {
display: block;
font-size: 0.9rem;
font-weight: 600;
color: var(--text-primary);
}
.upload-zone-text span {
font-size: 0.75rem;
color: var(--text-muted);
}
.upload-zone input[type="file"] {
position: absolute;
inset: 0;
opacity: 0;
cursor: pointer;
}
.upload-filename {
font-size: 0.75rem;
color: var(--success);
display: flex;
align-items: center;
gap: 6px;
position: relative;
z-index: 1;
font-weight: 500;
}
/* ── Form controls ─────────────────────────────────────────────── */
.form-group {
display: flex;
flex-direction: column;
gap: 6px;
}
.form-label {
font-size: 0.74rem;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--text-secondary);
display: flex;
align-items: center;
justify-content: space-between;
}
.form-label-value {
font-size: 0.78rem;
font-weight: 500;
color: var(--accent-hover);
text-transform: none;
letter-spacing: 0;
}
select, input[type="number"] {
width: 100%;
padding: 9px 12px;
background: rgba(255,255,255,0.05);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
color: var(--text-primary);
font-family: var(--font);
font-size: 0.85rem;
appearance: none;
cursor: pointer;
transition: border-color var(--transition), background var(--transition), box-shadow var(--transition);
outline: none;
}
select {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%239ba3b8' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 10px center;
padding-right: 30px;
}
select:hover, input[type="number"]:hover {
border-color: rgba(255,255,255,0.2);
background: rgba(255,255,255,0.07);
}
select:focus, input[type="number"]:focus {
border-color: var(--border-focus);
box-shadow: 0 0 0 3px rgba(99, 179, 237, 0.12);
}
/* Custom size row */
.size-row {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 8px;
}
.size-row-sep {
color: var(--text-muted);
font-size: 0.85rem;
text-align: center;
}
/* Slider */
input[type="range"] {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 4px;
background: rgba(255,255,255,0.1);
border-radius: 2px;
outline: none;
cursor: pointer;
transition: background var(--transition);
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 16px;
height: 16px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 0 3px var(--accent-glow);
cursor: pointer;
transition: transform var(--transition), box-shadow var(--transition), background var(--transition);
}
input[type="range"]:hover::-webkit-slider-thumb {
transform: scale(1.2);
background: var(--accent-hover);
box-shadow: 0 0 0 5px var(--accent-glow);
}
/* Segmented controls */
.seg-group {
display: flex;
gap: 4px;
background: rgba(0,0,0,0.3);
padding: 3px;
border-radius: var(--radius-sm);
border: 1px solid var(--border);
}
.seg-btn {
flex: 1;
padding: 6px 4px;
background: transparent;
border: none;
border-radius: 4px;
font-family: var(--font);
font-size: 0.72rem;
font-weight: 500;
color: var(--text-muted);
cursor: pointer;
transition: background var(--transition), color var(--transition);
white-space: nowrap;
}
.seg-btn:hover { color: var(--text-secondary); background: var(--bg-hover); }
.seg-btn.active {
background: var(--accent);
color: #fff;
box-shadow: 0 1px 6px var(--accent-glow);
}
/* ── Buttons ───────────────────────────────────────────────────── */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 10px 18px;
border-radius: var(--radius-sm);
font-family: var(--font);
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
border: none;
transition: background var(--transition), transform var(--transition), box-shadow var(--transition), opacity var(--transition);
outline: none;
white-space: nowrap;
}
.btn:active { transform: scale(0.97); }
.btn-primary {
background: var(--accent);
color: #fff;
box-shadow: 0 2px 12px var(--accent-glow);
}
.btn-primary:hover:not(:disabled) {
background: var(--accent-hover);
box-shadow: 0 4px 20px rgba(59,130,246,0.5);
transform: translateY(-1px);
}
.btn-secondary {
background: rgba(255,255,255,0.07);
color: var(--text-primary);
border: 1px solid var(--border);
}
.btn-secondary:hover:not(:disabled) {
background: rgba(255,255,255,0.12);
border-color: rgba(255,255,255,0.2);
}
.btn-success {
background: var(--success);
color: #fff;
box-shadow: 0 2px 12px rgba(16,185,129,0.35);
}
.btn-success:hover:not(:disabled) {
background: #34d399;
transform: translateY(-1px);
box-shadow: 0 4px 20px rgba(16,185,129,0.5);
}
.btn:disabled {
opacity: 0.38;
cursor: not-allowed;
transform: none !important;
}
.btn-row {
display: flex;
gap: 10px;
}
.btn-row .btn { flex: 1; }
/* ── Error / Warning banner ────────────────────────────────────── */
.banner {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
border-radius: var(--radius-sm);
font-size: 0.8rem;
font-weight: 500;
animation: slideDown 0.2s ease;
}
.banner-error { background: rgba(239,68,68,0.12); border: 1px solid rgba(239,68,68,0.3); color: #fca5a5; }
.banner-warning { background: rgba(245,158,11,0.12); border: 1px solid rgba(245,158,11,0.3); color: #fcd34d; }
.banner-info { background: rgba(59,130,246,0.12); border: 1px solid rgba(59,130,246,0.3); color: #93c5fd; }
.banner-close {
margin-left: auto;
background: none;
border: none;
color: inherit;
cursor: pointer;
opacity: 0.6;
font-size: 1rem;
line-height: 1;
padding: 0 2px;
}
.banner-close:hover { opacity: 1; }
/* ── Preview panel ─────────────────────────────────────────────── */
.preview-tabs {
display: flex;
gap: 2px;
padding: 4px;
background: rgba(0,0,0,0.25);
border-radius: var(--radius-sm);
width: fit-content;
}
.preview-tab {
padding: 6px 16px;
border-radius: 4px;
font-size: 0.78rem;
font-weight: 500;
cursor: pointer;
background: none;
border: none;
font-family: var(--font);
color: var(--text-muted);
transition: background var(--transition), color var(--transition);
}
.preview-tab:hover { color: var(--text-secondary); background: var(--bg-hover); }
.preview-tab.active {
background: var(--accent);
color: #fff;
}
.preview-canvas-wrap {
position: relative;
border-radius: var(--radius-lg);
overflow: hidden;
border: 1px solid var(--border);
background: repeating-conic-gradient(rgba(255,255,255,0.04) 0% 25%, transparent 0% 50%) 0 0 / 20px 20px;
min-height: 200px;
display: flex;
align-items: center;
justify-content: center;
}
.preview-canvas-wrap canvas,
.preview-canvas-wrap img {
max-width: 100%;
max-height: 520px;
display: block;
border-radius: var(--radius-sm);
}
.preview-repeat-wrap {
border-radius: var(--radius-lg);
overflow: hidden;
border: 1px solid var(--border);
min-height: 200px;
}
.preview-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
padding: 60px 20px;
color: var(--text-muted);
}
.preview-empty svg { opacity: 0.3; }
.preview-empty-text {
font-size: 0.85rem;
text-align: center;
}
/* Processing spinner */
.spinner-overlay {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: rgba(11,14,26,0.75);
backdrop-filter: blur(4px);
gap: 12px;
border-radius: inherit;
z-index: 10;
}
.spinner {
width: 36px;
height: 36px;
border: 3px solid rgba(255,255,255,0.1);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.7s linear infinite;
}
.spinner-text {
font-size: 0.8rem;
color: var(--text-secondary);
}
/* Preview stats bar */
.preview-stats {
display: flex;
align-items: center;
gap: 20px;
padding: 10px 16px;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
font-size: 0.75rem;
color: var(--text-muted);
}
.preview-stat strong {
color: var(--text-secondary);
font-weight: 600;
}
/* ── Divider ───────────────────────────────────────────────────── */
.divider {
height: 1px;
background: var(--border);
margin: 4px 0;
}
/* ── Animations ────────────────────────────────────────────────── */
@keyframes spin {
to { transform: rotate(360deg); }
}
@keyframes slideDown {
from { opacity: 0; transform: translateY(-6px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.fade-in { animation: fadeIn 0.3s ease; }
/* ── Responsive ────────────────────────────────────────────────── */
@media (max-width: 860px) {
.app-body {
grid-template-columns: 1fr;
}
.sidebar {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
+335
View File
@@ -0,0 +1,335 @@
// ── Types ──────────────────────────────────────────────────────────────────
export type ResizeMode = 'crop-square' | 'fit' | 'stretch' | 'keep-aspect';
export type PreviewMode = 'single' | 'repeat-2' | 'repeat-3' | 'repeat-4';
export type DetailPreservation = 'low' | 'medium' | 'high';
export interface TilesetSettings {
outputWidth: number;
outputHeight: number;
resizeMode: ResizeMode;
seamWidth: number;
blendStrength: number;
detailPreservation: DetailPreservation;
webpQuality: number;
previewMode: PreviewMode;
}
export const defaultSettings: TilesetSettings = {
outputWidth: 1024,
outputHeight: 1024,
resizeMode: 'crop-square',
seamWidth: 32,
blendStrength: 70,
detailPreservation: 'medium',
webpQuality: 90,
previewMode: 'repeat-3',
};
// ── Helpers ─────────────────────────────────────────────────────────────────
/** Hermite / smoothstep interpolation — same as GLSL smoothstep */
function smoothstep(edge0: number, edge1: number, x: number): number {
const t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));
return t * t * (3 - 2 * t);
}
function makeCanvas(w: number, h: number): HTMLCanvasElement {
const c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
}
// ── Step 1+2: Load & Normalize ───────────────────────────────────────────────
export async function loadAndNormalizeImage(
file: File,
settings: TilesetSettings,
): Promise<HTMLCanvasElement> {
const bitmap = await createImageBitmap(file);
return normalizeImage(bitmap, settings);
}
function normalizeImage(
bitmap: ImageBitmap,
settings: TilesetSettings,
): HTMLCanvasElement {
const { outputWidth: ow, outputHeight: oh, resizeMode } = settings;
const sw = bitmap.width;
const sh = bitmap.height;
const canvas = makeCanvas(ow, oh);
const ctx = canvas.getContext('2d')!;
if (resizeMode === 'stretch') {
ctx.drawImage(bitmap, 0, 0, ow, oh);
return canvas;
}
if (resizeMode === 'crop-square') {
// Determine side of the center-crop square
const side = Math.min(sw, sh);
const sx = (sw - side) / 2;
const sy = (sh - side) / 2;
ctx.drawImage(bitmap, sx, sy, side, side, 0, 0, ow, oh);
return canvas;
}
const srcRatio = sw / sh;
const dstRatio = ow / oh;
if (resizeMode === 'fit') {
// Letterbox / pillarbox — fill destination with scaled source, centered
let dw: number, dh: number, dx: number, dy: number;
if (srcRatio > dstRatio) {
dw = ow; dh = ow / srcRatio; dx = 0; dy = (oh - dh) / 2;
} else {
dh = oh; dw = oh * srcRatio; dx = (ow - dw) / 2; dy = 0;
}
ctx.drawImage(bitmap, 0, 0, sw, sh, dx, dy, dw, dh);
return canvas;
}
// keep-aspect — same as fit (preserves aspect within target bounds)
{
const scale = Math.min(ow / sw, oh / sh);
const dw = sw * scale;
const dh = sh * scale;
const dx = (ow - dw) / 2;
const dy = (oh - dh) / 2;
ctx.drawImage(bitmap, 0, 0, sw, sh, dx, dy, dw, dh);
return canvas;
}
}
// ── Step 3: Wrapped Offset ───────────────────────────────────────────────────
export function applyWrappedOffset(
source: HTMLCanvasElement,
offsetX: number,
offsetY: number,
): HTMLCanvasElement {
const { width: w, height: h } = source;
const out = makeCanvas(w, h);
const ctx = out.getContext('2d')!;
// Integer pixel offsets (wrap around)
const ox = Math.round(offsetX) % w;
const oy = Math.round(offsetY) % h;
// Draw source in all four wrapped quadrants
const positions = [
[ox, oy ],
[ox - w, oy ],
[ox, oy - h],
[ox - w, oy - h],
];
for (const [dx, dy] of positions) {
ctx.drawImage(source, dx, dy);
}
return out;
}
// ── Step 4: Seam Repair ──────────────────────────────────────────────────────
export function repairCenterSeams(
source: HTMLCanvasElement,
settings: Pick<TilesetSettings, 'seamWidth' | 'blendStrength' | 'detailPreservation'>,
): HTMLCanvasElement {
const { width: w, height: h } = source;
const { seamWidth, blendStrength, detailPreservation } = settings;
const out = makeCanvas(w, h);
const outCtx = out.getContext('2d')!;
// Copy source first so unmodified pixels carry over
outCtx.drawImage(source, 0, 0);
const srcCtx = source.getContext('2d')!;
const srcData = srcCtx.getImageData(0, 0, w, h);
const outData = outCtx.getImageData(0, 0, w, h);
const src = srcData.data;
const dst = outData.data;
// How much original pixel to keep (adds "detail preservation")
const detailRetain =
detailPreservation === 'high' ? 0.4 :
detailPreservation === 'medium' ? 0.2 : 0;
const blendFactor = blendStrength / 100;
const halfSeam = seamWidth / 2;
// Helper: get RGBA at (x, y) with wrapping
const getPixel = (x: number, y: number, ch: number): number => {
const px = ((x % w) + w) % w;
const py = ((y % h) + h) % h;
return src[(py * w + px) * 4 + ch];
};
// Helper: sample a soft average of neighbor pixels across the seam
const sampleNeighbors = (
x: number,
y: number,
direction: 'h' | 'v', // 'h' = horizontal seam (sample above/below), 'v' = vertical
reach: number,
ch: number,
): number => {
let total = 0;
let weight = 0;
const steps = Math.min(reach, 8); // sample up to 8 pixels away
for (let i = 1; i <= steps; i++) {
const w1 = (steps - i + 1) / steps;
const [ax, ay] = direction === 'v' ? [x + i, y] : [x, y + i];
const [bx, by] = direction === 'v' ? [x - i, y] : [x, y - i];
total += getPixel(ax, ay, ch) * w1 + getPixel(bx, by, ch) * w1;
weight += 2 * w1;
}
return weight > 0 ? total / weight : getPixel(x, y, ch);
};
const cx = Math.floor(w / 2);
const cy = Math.floor(h / 2);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const idx = (y * w + x) * 4;
const dv = Math.abs(x - cx); // distance from vertical seam
const dh = Math.abs(y - cy); // distance from horizontal seam
const inV = dv < halfSeam;
const inH = dh < halfSeam;
if (!inV && !inH) continue;
for (let ch = 0; ch < 4; ch++) {
const orig = src[idx + ch];
let blended = orig;
if (inV) {
const tV = 1 - smoothstep(0, halfSeam, dv);
const neighborV = sampleNeighbors(x, y, 'v', Math.ceil(halfSeam), ch);
const mixV = orig * (1 - tV * blendFactor) + neighborV * (tV * blendFactor);
blended = mixV;
}
if (inH) {
const tH = 1 - smoothstep(0, halfSeam, dh);
const neighborH = sampleNeighbors(x, y, 'h', Math.ceil(halfSeam), ch);
const mixH = blended * (1 - tH * blendFactor) + neighborH * (tH * blendFactor);
blended = mixH;
}
// Apply detail preservation — pull back toward original
dst[idx + ch] = Math.round(blended * (1 - detailRetain) + orig * detailRetain);
}
}
}
outCtx.putImageData(outData, 0, 0);
return out;
}
// ── Full Pipeline ────────────────────────────────────────────────────────────
export async function generateTileableTexture(
file: File,
settings: TilesetSettings,
onProgress?: (step: string) => void,
): Promise<HTMLCanvasElement> {
onProgress?.('Loading image…');
const bitmap = await createImageBitmap(file);
onProgress?.('Normalizing…');
const normalized = normalizeImage(bitmap, settings);
onProgress?.('Applying offset…');
const offsetCanvas = applyWrappedOffset(
normalized,
settings.outputWidth / 2,
settings.outputHeight / 2,
);
onProgress?.('Repairing seams…');
// Run seam repair in next microtask so the UI can update
await new Promise<void>((res) => setTimeout(res, 0));
const repaired = repairCenterSeams(offsetCanvas, settings);
onProgress?.('Done');
return repaired;
}
// ── Export ───────────────────────────────────────────────────────────────────
export function exportAsWebP(
canvas: HTMLCanvasElement,
quality: number,
width: number,
height: number,
): Promise<void> {
return new Promise((resolve, reject) => {
// Resize to export dimensions if needed
let exportCanvas = canvas;
if (canvas.width !== width || canvas.height !== height) {
exportCanvas = makeCanvas(width, height);
exportCanvas.getContext('2d')!.drawImage(canvas, 0, 0, width, height);
}
exportCanvas.toBlob(
(blob) => {
if (!blob) { reject(new Error('Canvas export failed')); return; }
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `tileset-generator-${width}x${height}.webp`;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 5000);
resolve();
},
'image/webp',
quality / 100,
);
});
}
// ── Validation ───────────────────────────────────────────────────────────────
export const SUPPORTED_TYPES = ['image/png', 'image/jpeg', 'image/webp'];
export const MAX_DIMENSION = 4096;
export const WARN_DIMENSION = 2048;
export interface ValidationResult {
ok: boolean;
error?: string;
warning?: string;
}
export function validateFile(file: File): ValidationResult {
if (!SUPPORTED_TYPES.includes(file.type)) {
return {
ok: false,
error: 'Unsupported file type. Please upload a PNG, JPG, or WebP image.',
};
}
return { ok: true };
}
export async function validateImageDimensions(file: File): Promise<ValidationResult> {
const bitmap = await createImageBitmap(file).catch(() => null);
if (!bitmap) return { ok: false, error: 'Image failed to load. It may be corrupted.' };
if (bitmap.width > MAX_DIMENSION || bitmap.height > MAX_DIMENSION) {
return {
ok: false,
error: `Image is too large (${bitmap.width}×${bitmap.height}). Maximum is ${MAX_DIMENSION}×${MAX_DIMENSION} px.`,
};
}
if (bitmap.width > WARN_DIMENSION || bitmap.height > WARN_DIMENSION) {
return {
ok: true,
warning: `This image is very large (${bitmap.width}×${bitmap.height}). The tool will resize it before processing.`,
};
}
return { ok: true };
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+6
View File
@@ -0,0 +1,6 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})