92 lines
2.4 KiB
TypeScript
92 lines
2.4 KiB
TypeScript
import { join } from 'path'
|
|
import { existsSync } from 'fs'
|
|
import { mkdir, writeFile, readFile, unlink, rm } from 'fs/promises'
|
|
import { TMP_DIR } from '@/lib/constants'
|
|
import { compressWithBlender } from '@/lib/blender'
|
|
import { compressTextureBuffer } from '@/lib/texture-compression'
|
|
import type { ParsedFile } from '@/lib/types'
|
|
|
|
interface PushFile {
|
|
path: string
|
|
contentBase64: string
|
|
}
|
|
|
|
interface PrepareGitAssetsParams {
|
|
folderName: string
|
|
destination: string
|
|
parsedFiles: ParsedFile[]
|
|
}
|
|
|
|
interface PrepareGitAssetsResult {
|
|
filesToPush: PushFile[]
|
|
modelFilename: string
|
|
textureNames: string[]
|
|
compressed: boolean
|
|
compressionError?: string
|
|
}
|
|
|
|
export async function prepareGitAssets({
|
|
folderName,
|
|
destination,
|
|
parsedFiles,
|
|
}: PrepareGitAssetsParams): Promise<PrepareGitAssetsResult> {
|
|
const filesToPush: PushFile[] = []
|
|
const textureNames: string[] = []
|
|
let modelFilename = ''
|
|
let compressed = false
|
|
let compressionError: string | undefined
|
|
|
|
for (const pf of parsedFiles) {
|
|
let content = pf.buffer
|
|
|
|
if (pf.isModel) {
|
|
modelFilename = pf.filename
|
|
|
|
const tmpFolder = join(TMP_DIR, folderName)
|
|
await mkdir(tmpFolder, { recursive: true })
|
|
const tmpFilePath = join(tmpFolder, pf.filename)
|
|
await writeFile(tmpFilePath, pf.buffer)
|
|
|
|
const stem = pf.filename.replace(/\.[^.]+$/, '')
|
|
const compressedPath = join(tmpFolder, `${stem}_compressed.glb`)
|
|
|
|
try {
|
|
const result = await compressWithBlender(tmpFilePath, compressedPath)
|
|
|
|
if (result.success && existsSync(compressedPath)) {
|
|
content = await readFile(compressedPath)
|
|
compressed = true
|
|
await unlink(compressedPath).catch(() => {})
|
|
} else {
|
|
compressionError = result.error
|
|
}
|
|
} finally {
|
|
await unlink(tmpFilePath).catch(() => {})
|
|
await rm(tmpFolder, { recursive: true, force: true }).catch(() => {})
|
|
}
|
|
} else {
|
|
textureNames.push(pf.filename)
|
|
|
|
const textureResult = await compressTextureBuffer(pf.filename, pf.buffer)
|
|
content = textureResult.buffer
|
|
|
|
if (textureResult.error && !compressionError) {
|
|
compressionError = textureResult.error
|
|
}
|
|
}
|
|
|
|
filesToPush.push({
|
|
path: `public/models/${destination}/${folderName}/${pf.filename}`,
|
|
contentBase64: content.toString('base64'),
|
|
})
|
|
}
|
|
|
|
return {
|
|
filesToPush,
|
|
modelFilename,
|
|
textureNames,
|
|
compressed,
|
|
compressionError,
|
|
}
|
|
}
|