feat: Start on edit modal + cape button cleanup + renderer fixes

This commit is contained in:
Calum H.
2025-05-15 12:35:46 +01:00
committed by Alejandro González
parent 79f0dfd1c0
commit fd6e263e0a
9 changed files with 521 additions and 153 deletions

File diff suppressed because one or more lines are too long

View File

@@ -1,32 +1,224 @@
<script setup lang="ts">
import ModalWrapper from '@/components/ui/modal/ModalWrapper.vue'
import { computed, useTemplateRef } from 'vue'
import {
Card,
Chips,
FileInput,
SkinPreviewRenderer,
CapeButton,
CapeLikeTextButton,
Button, RadioButtons
} from '@modrinth/ui'
import {
add_and_equip_custom_skin,
type Cape,
determineModelType,
equip_skin,
type Skin,
type SkinModel
} from '@/helpers/skins.ts'
import {handleError} from '@/store/notifications'
import {computed, ref, useTemplateRef, watch} from 'vue'
import {CheckCircleIcon, InfoIcon, UploadIcon, ChevronRightIcon} from "@modrinth/assets";
const modal = useTemplateRef('modal')
const mode = ref<'new' | 'edit'>('new')
const currentSkin = ref<Skin | null>(null)
const textureBlob = ref<Uint8Array | null>(null)
const variant = ref<SkinModel>('Classic')
const selectedCape = ref<Cape | undefined>(undefined)
const previewSkin = computed(() => `https://vzge.me/full/350/ProspectorDev.png?no=ears`)
const props = defineProps<{ capes?: Cape[] }>()
const firstThreeCapes = computed(() => props.capes?.slice(0, 3) ?? [])
function show(e: MouseEvent) {
const localPreviewUrl = ref<string | null>(null)
const fileName = ref<string | null>(null)
watch(textureBlob, async (blob, prev) => {
if (prev && localPreviewUrl.value) URL.revokeObjectURL(localPreviewUrl.value)
localPreviewUrl.value = blob ? URL.createObjectURL(new Blob([blob])) : null
if (blob && variant.value === 'Unknown' && localPreviewUrl.value) {
try {
variant.value = await determineModelType(localPreviewUrl.value)
} catch (err) {
handleError(err)
}
}
})
const previewSkin = computed(() => {
if (localPreviewUrl.value) return localPreviewUrl.value
if (currentSkin.value) return currentSkin.value.texture;
return ''
})
const emit = defineEmits<{
(e: 'view-more-capes', ev: MouseEvent): void
(e: 'saved'): void
}>()
function resetState() {
mode.value = 'new'
currentSkin.value = null
textureBlob.value = null
fileName.value = null
if (localPreviewUrl.value) {
URL.revokeObjectURL(localPreviewUrl.value)
localPreviewUrl.value = null
}
variant.value = 'Classic'
selectedCape.value = undefined
}
function show(e: MouseEvent, skin?: Skin) {
mode.value = skin ? 'edit' : 'new'
currentSkin.value = skin ?? null
textureBlob.value = null
variant.value = skin?.variant ?? 'Classic'
selectedCape.value = skin?.cape_id ? props.capes?.find(c => c.id === skin.cape_id) : undefined
modal.value?.show(e)
}
function hide() {
modal.value?.hide()
resetState()
}
async function onTextureSelected(files: FileList | null) {
if (!files?.length) return
const file = files[0]
const buf = await file.arrayBuffer()
textureBlob.value = new Uint8Array(buf)
fileName.value = file.name
}
function changeVariant(newVariant: SkinModel) {
variant.value = newVariant
}
function selectCape(cape: Cape | undefined) {
selectedCape.value = cape
}
function viewMoreCapes(e: MouseEvent) {
hide()
emit('view-more-capes', e)
}
async function save() {
try {
if (mode.value === 'new') {
if (!textureBlob.value) throw new Error('Please upload a skin texture first.')
await add_and_equip_custom_skin(textureBlob.value, variant.value, selectedCape.value).catch(handleError)
} else if (currentSkin.value) {
const edited: Skin = {
...currentSkin.value,
variant: variant.value,
cape_id: selectedCape.value?.id
}
if (textureBlob.value) {
await add_and_equip_custom_skin(textureBlob.value, variant.value, selectedCape.value).catch(handleError)
} else {
await equip_skin(edited).catch(handleError)
}
}
hide()
emit('saved')
} catch (err) {
handleError(err)
}
}
defineExpose({
show,
hide,
save,
onTextureSelected,
changeVariant,
selectCape,
viewMoreCapes,
})
</script>
<template>
<ModalWrapper ref="modal">
<ModalWrapper ref="modal" @on-modal-hide="resetState">
<template #title>
<span class="text-lg font-extrabold text-contrast">Edit skin</span>
<span class="text-lg font-extrabold text-contrast">{{
mode === 'edit' ? 'Edit skin' : 'New skin'
}}</span>
</template>
<div class="grid grid-cols-[auto_1fr] gap-6">
<div class="flex">
<img :src="previewSkin" alt="" class="w-auto my-auto h-60 object-contain" />
<div class="flex flex-col md:flex-row gap-6">
<div class="max-h-[25rem] w-[16rem] min-w-[16rem] overflow-hidden relative">
<!-- Blame Three.js for forcing 1:1 canvas ratios... -->
<div class="absolute top-[-4rem] left-0 h-[32rem] w-[16rem] min-w-[16rem] flex-shrink-0 p-0 m-0">
<SkinPreviewRenderer
slim-model-src="/src/assets/models/slim_player.gltf"
wide-model-src="/src/assets/models/classic_player.gltf"
:variant="variant"
:texture-src="previewSkin"
scale="1.4"
fov="50"
class="h-full w-full"
/>
</div>
</div>
<div class="min-h-[16rem] flex flex-col gap-4 w-full">
<section>
<h2 class="text-base font-semibold mb-2">Texture</h2>
<Card class="!bg-bg p-4 relative flex flex-col items-center gap-4">
<FileInput
:max-size="8000"
accept="image/png"
:prompt="mode === 'edit'? 'Replace skin' : 'Upload a skin'"
class="btn btn-primary"
:aria-label="mode === 'edit'? 'Replace skin' : 'Upload a skin'"
@change="onTextureSelected"
>
<UploadIcon aria-hidden="true" />
</FileInput>
<div class="flex items-center gap-2 mx-auto">
<InfoIcon v-if="!fileName" aria-hidden="true" class="text-brand-blue" />
<CheckCircleIcon v-else aria-hidden="true" class="text-brand-green" />
<small class="max-w-64 truncate block" v-tooltip="fileName ?? currentSkin.texture ?? undefined">
{{ fileName || (mode === 'edit' ? currentSkin.texture : 'No skin has been uploaded yet.') }}
</small>
</div>
</Card>
</section>
<section>
<h2 class="text-base font-semibold mb-2">Arm style</h2>
<RadioButtons
v-model="variant"
:items="['Classic', 'Slim']">
<template #default="{ item }">
{{ item === 'Classic' ? 'Wide' : 'Slim' }}
</template>
</RadioButtons>
</section>
<section>
<h2 class="text-base font-semibold mb-2">Cape</h2>
<div class="flex gap-2">
<CapeButton
v-for="cape in firstThreeCapes"
:key="cape.id"
:id="cape.id"
:texture="cape.texture"
:name="cape.name || 'Cape'"
:selected="selectedCape?.id === cape.id"
@select="selectCape(cape)"
/>
<CapeLikeTextButton tooltip="View more capes" v-if="capes?.length > 3">
<template #icon>
<ChevronRightIcon />
</template>
<span>More</span>
</CapeLikeTextButton>
</div>
</section>
</div>
</div>
</ModalWrapper>

View File

@@ -1,9 +1,8 @@
<script setup lang="ts">
import ModalWrapper from '@/components/ui/modal/ModalWrapper.vue'
import { useTemplateRef, ref, computed } from 'vue'
import CapeButton from '@/components/ui/skin/CapeButton.vue'
import type { Cape } from '@/helpers/skins.ts'
import { ButtonStyled, ScrollablePanel } from '@modrinth/ui'
import { ButtonStyled, ScrollablePanel, CapeButton } from '@modrinth/ui'
import { CheckIcon, XIcon} from '@modrinth/assets'
const modal = useTemplateRef('modal')

View File

@@ -1,4 +1,5 @@
import { invoke } from '@tauri-apps/api/core'
import {handleError} from "@/store/notifications";
export interface Cape {
id: string
@@ -21,12 +22,102 @@ export interface Skin {
is_equipped: boolean
}
export const DEFAULT_MODEL_SORTING = ['Steve', 'Alex'] as string[]
export const DEFAULT_MODELS: Record<string, SkinModel> = {
Steve: 'Classic',
Alex: 'Slim',
Zuri: 'Classic',
Sunny: 'Classic',
Noor: 'Slim',
Makena: 'Slim',
Kai: 'Classic',
Efe: 'Slim',
Ari: 'Classic',
}
export function filterSavedSkins(list: Skin[]) {
const customSkins = list.filter((s) => s.source !== 'Default');
console.log(customSkins[0]);
fixUnknownSkins(customSkins).catch(handleError);
return customSkins;
}
export async function determineModelType(texture: string): Promise<'Slim' | 'Classic'> {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
if (!context) {
return reject(new Error('Failed to create canvas rendering context.'));
}
const image = new Image();
image.crossOrigin = 'anonymous';
image.src = texture;
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
const armX = 44;
const armY = 16;
const armWidth = 4;
const armHeight = 12;
const imageData = context.getImageData(armX, armY, armWidth, armHeight).data;
for (let y = 0; y < armHeight; y++) {
const alphaIndex = (3 + y * armWidth) * 4 + 3;
if (imageData[alphaIndex] !== 0) {
resolve('Classic');
return;
}
}
canvas.remove();
resolve('Slim');
};
image.onerror = () => {
canvas.remove();
reject(new Error('Failed to load the image.'));
};
});
}
export async function fixUnknownSkins(list: Skin[]) {
const unknownSkins = list.filter((s) => s.variant === "Unknown");
for (let unknownSkin of unknownSkins) {
console.log(unknownSkin.texture);
const modelType = await determineModelType(unknownSkin.texture);
unknownSkin.variant = modelType;
}
}
export function filterDefaultSkins(list: Skin[]) {
console.log(list);
return list
.filter(
(s) =>
s.source === 'Default' &&
(!s.name || s.variant === DEFAULT_MODELS[s.name]),
)
.sort((a, b) => {
const aIndex = a.name ? DEFAULT_MODEL_SORTING.indexOf(a.name) : -1
const bIndex = b.name ? DEFAULT_MODEL_SORTING.indexOf(b.name) : -1
return (aIndex === -1 ? Infinity : aIndex) - (bIndex === -1 ? Infinity : bIndex)
})
}
export async function get_available_capes(): Promise<Cape[]> {
return await invoke('plugin:minecraft-skins|get_available_capes', {})
return invoke('plugin:minecraft-skins|get_available_capes', {})
}
export async function get_available_skins(): Promise<Skin[]> {
return await invoke('plugin:minecraft-skins|get_available_skins', {})
return invoke('plugin:minecraft-skins|get_available_skins', {})
}
export async function add_and_equip_custom_skin(

View File

@@ -4,100 +4,95 @@ import { ButtonStyled, SkinPreviewRenderer } from '@modrinth/ui'
import { ref, computed, useTemplateRef } from 'vue'
import SkinButton from '@/components/ui/skin/SkinButton.vue'
import EditSkinModal from '@/components/ui/skin/EditSkinModal.vue'
import type { Cape, Skin, SkinModel } from '@/helpers/skins.ts'
import { get_available_skins, get_available_capes } from '@/helpers/skins.ts'
import { handleError } from '@/store/notifications'
import SelectCapeModal from '@/components/ui/skin/SelectCapeModal.vue'
import { get as getSettings } from "@/helpers/settings.ts";
import { handleError } from '@/store/notifications'
import {
get_available_skins,
get_available_capes,
filterSavedSkins,
filterDefaultSkins, equip_skin,
} from '@/helpers/skins.ts'
import { get as getSettings } from '@/helpers/settings.ts'
import { get as getCreds } from '@/helpers/mr_auth'
import { get_user } from '@/helpers/cache'
import type { Cape, Skin } from '@/helpers/skins.ts'
const editSkinModal = useTemplateRef('editSkinModal')
const selectCapeModal = useTemplateRef('selectCapeModal')
const settings = ref(await getSettings());
const selectedSkin = ref('its_imb11')
const previewSkin = computed(() => `https://vzge.me/processedskin/${selectedSkin.value}.png`)
const savedSkins = computed(() => skins.value.filter((skin) => skin.source !== 'Default'))
const defaultSkins = computed(() =>
skins.value
.filter(
(skin) =>
skin.source === 'Default' && (!skin.name || skin.variant === defaultModels[skin.name]),
)
.sort((a, b) => {
if (!a.name || !defaultModelSorting.includes(a.name)) {
return 1
} else if (!b.name || !defaultModelSorting.includes(b.name)) {
return -1
}
return defaultModelSorting.indexOf(a.name) - defaultModelSorting.indexOf(b.name)
}),
)
const currentCape = ref<Cape | undefined>()
const defaultModelSorting = ['Steve', 'Alex']
const defaultModels: Record<string, SkinModel> = {
Steve: 'Classic',
Alex: 'Slim',
Zuri: 'Classic',
Sunny: 'Classic',
Noor: 'Slim',
Makena: 'Slim',
Kai: 'Classic',
Efe: 'Slim',
Ari: 'Classic',
}
const settings = ref(await getSettings())
const credentials = ref()
const skins = ref<Skin[]>([])
const capes = ref<Cape[]>([])
await loadCapes()
await loadSkins()
const selectedSkin = ref<Skin | null>(null)
const previewSkin = computed(() =>
selectedSkin.value ? `https://vzge.me/processedskin/${selectedSkin.value.texture_key}.png` : ''
)
const savedSkins = computed(() => filterSavedSkins(skins.value))
const defaultSkins = computed(() => filterDefaultSkins(skins.value))
const currentCape = ref<Cape>()
await Promise.all([fetchCredentials(), loadCapes(), loadSkins()])
async function fetchCredentials() {
const creds = await getCreds().catch(handleError)
if (creds?.user_id) {
creds.user = await get_user(creds.user_id).catch(handleError)
}
credentials.value = creds
}
async function loadCapes() {
await get_available_capes()
.then((c) => {
capes.value = c
currentCape.value = capes.value.find((cape) => cape.is_equipped)
console.log(c)
})
.catch((err) => handleError(err))
capes.value = (await get_available_capes().catch(handleError)) ?? []
currentCape.value = capes.value.find((c) => c.is_equipped)
}
async function loadSkins() {
await get_available_skins()
.then((s) => {
skins.value = s
console.log(s)
})
.catch((err) => handleError(err))
skins.value = (await get_available_skins().catch(handleError)) ?? []
selectedSkin.value =
skins.value.find((s) => s.texture_key === 'its_imb11') ?? skins.value[0] ?? null
}
async function changeSkin(newSkin: Skin) {
selectedSkin.value = newSkin;
// TODO: Backend is broken! Enums aren't being serialized/deserialized correctly.
await equip_skin(selectedSkin.value).catch(handleError);
}
</script>
<template>
<EditSkinModal ref="editSkinModal" />
<SelectCapeModal ref="selectCapeModal" :capes="capes" />
<EditSkinModal ref="editSkinModal" :capes="capes"/>
<SelectCapeModal ref="selectCapeModal" :capes="capes"/>
<div class="p-6 grid grid-cols-[300px_1fr] xl:grid-cols-[3fr_5fr] gap-6">
<div class="sticky top-6 self-start">
<div class="flex justify-between gap-4">
<h1 class="m-0 text-2xl font-extrabold">Skins</h1>
<div>
<ButtonStyled>
<button @click="(e: MouseEvent) => selectCapeModal?.show(e, selectedSkin, currentCape)">
<UpdatedIcon />
Change cape
</button>
</ButtonStyled>
</div>
<h1 class="m-0 text-2xl font-bold">Skins</h1>
<ButtonStyled>
<button
@click="(e: MouseEvent) =>
selectCapeModal?.show(e, selectedSkin?.texture_key, currentCape)"
>
<UpdatedIcon />
Change cape
</button>
</ButtonStyled>
</div>
<div class="h-[80vh] flex items-center justify-center">
<SkinPreviewRenderer :model-src="'/src/assets/models/wide_player.gltf'" :nametag="settings.hide_nametag_skins_page ? undefined : selectedSkin" :texture-src="previewSkin" />
<SkinPreviewRenderer
wide-model-src="/src/assets/models/classic_player.gltf"
slim-model-src="/src/assets/models/slim_player.gltf"
:nametag="settings.hide_nametag_skins_page ? undefined : credentials?.user?.username"
:texture-src="previewSkin"
/>
</div>
</div>
<div class="flex flex-col gap-6 add-perspective">
<div class="flex flex-col gap-3">
<section class="flex flex-col gap-3">
<h2 class="text-lg font-bold m-0 text-primary">Saved skins</h2>
<div class="grid grid-cols-3 gap-2">
<button
@@ -107,31 +102,32 @@ async function loadSkins() {
<PlusIcon class="w-6 h-6" />
Add a skin
</button>
<SkinButton
v-for="skin in savedSkins"
:key="`saved-skin-${skin.texture_key}`"
editable
:skin="skin"
:selected="selectedSkin === skin.texture_key"
@select="selectedSkin = skin.texture_key"
@edit="editSkinModal?.show"
:selected="selectedSkin === skin"
@select="changeSkin(skin)"
@edit="e => editSkinModal?.show(e, skin)"
/>
</div>
</div>
<div class="flex flex-col gap-3">
</section>
<section class="flex flex-col gap-3">
<h2 class="text-lg font-bold m-0 text-primary">Default skins</h2>
<div class="grid grid-cols-3 gap-2">
<SkinButton
v-for="skin in defaultSkins"
:key="`default-skin-${skin.texture_key}`"
:skin="skin"
:selected="selectedSkin === skin.texture_key"
@select="selectedSkin = skin.texture_key"
@edit="editSkinModal?.show"
:selected="selectedSkin === skin"
@select="changeSkin(skin)"
@edit="e => editSkinModal?.show(e, skin)"
/>
</div>
</div>
</section>
</div>
</div>
</template>
<style scoped></style>

View File

@@ -1,26 +1,31 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { Cape } from '@/helpers/skins.ts'
const emit = defineEmits<{
(e: 'select'): void
}>()
const highlighted = computed(() => props.selected ?? props.cape.is_equipped)
const props = withDefaults(
defineProps<{
cape: Cape
name: string
id: string
texture: string
isEquipped?: boolean
selected?: boolean
}>(),
{
isEquipped: false,
selected: undefined,
},
)
console.log(props);
const highlighted = computed(() => props.selected ?? props.isEquipped)
</script>
<template>
<button v-tooltip="cape.name" class="block border-0 m-0 p-0 bg-transparent group cursor-pointer" :aria-label="cape.name" @click="emit('select')">
<button v-tooltip="name" class="block border-0 m-0 p-0 bg-transparent group cursor-pointer" :aria-label="name" @click="emit('select')">
<span
:class="
highlighted
@@ -30,23 +35,25 @@ const props = withDefaults(
class="block p-[3px] rounded-lg border-0 group-active:scale-95 transition-all"
>
<span
class="block cursed-cape-shit rounded-[5px]"
class="block magical-cape-transform rounded-[5px]"
:class="{ 'highlighted-inner-shadow': highlighted }"
>
<img :src="cape.texture" alt="" />
<img :src="texture" alt="" />
</span>
</span>
</button>
</template>
<style lang="scss" scoped>
.cursed-cape-shit {
.magical-cape-transform {
aspect-ratio: 10 / 16;
position: relative;
overflow: hidden;
box-sizing: content-box;
width: 60px;
min-height: 96px;
}
.cursed-cape-shit img {
.magical-cape-transform img {
position: absolute;
object-fit: cover;
image-rendering: pixelated;

View File

@@ -0,0 +1,62 @@
<script setup lang="ts">
const emit = defineEmits<{
(e: 'click'): void
}>()
const props = withDefaults(
defineProps<{
tooltip: string
highlighted?: boolean
}>(),
{
highlighted: false,
},
)
</script>
<template>
<button
v-tooltip="tooltip"
class="block border-0 m-0 p-0 bg-transparent group cursor-pointer"
:aria-label="tooltip"
@click="emit('click')"
>
<span
:class="
highlighted
? `bg-brand highlighted-outer-glow`
: `bg-button-bg opacity-75 group-hover:opacity-100`
"
class="block p-[3px] rounded-lg border-0 group-active:scale-95 transition-all"
>
<span
class="flex flex-col items-center justify-center aspect-[10/16] w-[60px] min-h-[96px] rounded-[5px] bg-black/10 relative overflow-hidden"
:class="{ 'highlighted-inner-shadow': highlighted }"
>
<div class="mb-1">
<slot name="icon"></slot>
</div>
<span class="text-xs text-white/80 group-hover:text-white">
<slot name="default"></slot>
</span>
</span>
</span>
</button>
</template>
<style lang="scss" scoped>
.highlighted-inner-shadow::before {
content: '';
position: absolute;
inset: 0;
box-shadow: inset 0 0 4px 4px rgba(0, 0, 0, 0.2);
z-index: 2;
}
@supports (background-color: color-mix(in srgb, transparent, transparent)) {
.highlighted-outer-glow {
box-shadow: 0 0 4px 2px color-mix(in srgb, var(--color-brand), transparent 70%);
}
}
</style>

View File

@@ -1,7 +1,9 @@
<template>
<div class="relative w-full h-full">
<div class="absolute bottom-[18%] left-1/2 transform -translate-x-1/2 text-primary px-3 py-1 rounded text-md pointer-events-none z-10">
Drag to rotate
<div class="absolute bottom-[18%] left-0 right-0 flex justify-center items-center mb-2 pointer-events-none z-10">
<span class="text-primary text-xs px-2 py-1 rounded-full backdrop-blur-sm">
Drag to rotate
</span>
</div>
<div v-if="nametag" class="absolute top-[10%] left-1/2 transform -translate-x-1/2 px-3 py-1 rounded-md text-[225%] pointer-events-none z-10 font-minecraft text-secondary bg-bg-raised shadow-md border">
{{ nametag }}
@@ -22,14 +24,16 @@
>
<Suspense>
<Group>
<Group ref="modelGroup" :rotation="[0, modelRotation, 0]" :position="[0, -0.05, 1.95]" :scale="[0.8, 0.8, 0.8]">
<primitive v-if="scene" ref="modelRef" :object="scene" />
<!-- Apply the scale prop to the model group -->
<Group :rotation="[0, modelRotation, 0]" :position="[0, -0.05 * scale, 1.95]" :scale="[0.8 * scale, 0.8 * scale, 0.8 * scale]">
<primitive v-if="scene" :object="scene" />
</Group>
<!-- Scale the shadow accordingly -->
<TresMesh
:position="[0, -0.095, 2]"
:position="[0, -0.095 * scale, 2]"
:rotation="[-Math.PI / 2, 0, 0]"
:scale="[0.4, 0.4, 0.4]"
:scale="[0.4 * scale, 0.4 * scale, 0.4 * scale]"
>
<TresCircleGeometry :args="[1, 32]" />
<TresMeshBasicMaterial
@@ -40,7 +44,8 @@
/>
</TresMesh>
<TresMesh :position="[0, -0.1, 2]" :rotation="[-Math.PI / 2, 0, 0]" :scale="[0.75, 0.75, 0.75]">
<!-- Scale the radial gradient effect -->
<TresMesh :position="[0, -0.1 * scale, 2]" :rotation="[-Math.PI / 2, 0, 0]" :scale="[0.75 * scale, 0.75 * scale, 0.75 * scale]">
<TresPlaneGeometry :args="[2, 2]" />
<TresMeshBasicMaterial
:map="radialTexture"
@@ -52,17 +57,15 @@
</Group>
</Suspense>
<!-- Use the fov prop for the camera -->
<TresPerspectiveCamera
ref="cameraRef"
:makeDefault="true"
:fov="40"
:fov="fov"
:position="[0, 1.5, -3.25]"
:look-at="target"
/>
<TresAmbientLight
:intensity="2"
/>
<TresAmbientLight :intensity="2" />
</TresCanvas>
</div>
</template>
@@ -71,64 +74,80 @@
import * as THREE from 'three'
import { useGLTF } from '@tresjs/cientos'
import { useTexture, TresCanvas } from '@tresjs/core'
import {ref, computed, watch} from 'vue'
import {shallowRef, ref, computed, watch, markRaw} from 'vue'
const props = withDefaults(defineProps<{
textureSrc: string
modelSrc: string
nametag?: string
antialias?: boolean
}>(), {
antialias: false,
})
const props = withDefaults(
defineProps<{
textureSrc: string
slimModelSrc: string
wideModelSrc: string
variant?: 'Slim' | 'Classic' | 'Unknown'
nametag?: string
antialias?: boolean
scale?: number
fov?: number
}>(),
{
variant: 'Classic',
antialias: false,
scale: 1,
fov: 40
}
)
const { scene } = await useGLTF(props.modelSrc)
const selectedModelSrc = computed(() =>
props.variant === 'Slim' ? props.slimModelSrc : props.wideModelSrc
)
let texture = await useTexture([props.textureSrc])
applyTextureToScene(scene, texture);
const scene = shallowRef<THREE.Object3D | null>(null)
async function loadModel(src: string) {
const { scene: loadedScene } = await useGLTF(src)
scene.value = markRaw(loadedScene)
applyTextureToScene(scene.value, texture.value)
updateModelInfo()
}
watch(selectedModelSrc, src => loadModel(src), { immediate: true })
const texture = ref<THREE.Texture>(await useTexture([props.textureSrc]))
watch(
() => props.textureSrc,
async newSrc => {
texture = await useTexture([newSrc])
applyTextureToScene(scene, texture)
texture.value = await useTexture([newSrc])
applyTextureToScene(scene.value, texture.value)
}
)
function applyTextureToScene(root: THREE.Object3D | null, tex: THREE.Texture) {
texture.colorSpace = THREE.SRGBColorSpace
texture.flipY = false
texture.magFilter = THREE.NearestFilter
texture.minFilter = THREE.NearestFilter
if (!root) return
tex.colorSpace = THREE.SRGBColorSpace
tex.flipY = false
tex.magFilter = THREE.NearestFilter
tex.minFilter = THREE.NearestFilter
root.traverse(child => {
if ((child as THREE.Mesh).isMesh) {
const mesh = child as THREE.Mesh
const setProps = (mat: THREE.Material) => {
const m = mat as THREE.MeshStandardMaterial
m.map = tex
m.metalness = 0
m.color.set(0xffffff)
m.toneMapped = false
m.roughness = 1
m.needsUpdate = true
}
if (Array.isArray(mesh.material)) mesh.material.forEach(setProps)
else setProps(mesh.material)
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]
materials.forEach((mat: THREE.MeshStandardMaterial) => {
mat.map = tex
mat.metalness = 0
mat.color.set(0xffffff)
mat.toneMapped = false
mat.roughness = 1
mat.needsUpdate = true
})
}
})
}
const modelRef = ref<THREE.Object3D | null>(null)
const modelGroup = ref<THREE.Group | null>(null)
const cameraRef = ref<THREE.PerspectiveCamera | null>(null)
const centre = ref<[number, number, number]>([0, 1, 0])
const modelHeight = ref(1.4)
if (scene) {
const bbox = new THREE.Box3().setFromObject(scene)
function updateModelInfo() {
if (!scene.value) return
const bbox = new THREE.Box3().setFromObject(scene.value)
const mid = new THREE.Vector3()
bbox.getCenter(mid)
centre.value = [mid.x, mid.y, mid.z]
@@ -142,8 +161,7 @@ const isDragging = ref(false)
const previousX = ref(0)
const onPointerDown = (event: PointerEvent) => {
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
isDragging.value = true
previousX.value = event.clientX
}
@@ -156,8 +174,8 @@ const onPointerMove = (event: PointerEvent) => {
}
const onPointerUp = (event: PointerEvent) => {
isDragging.value = false;
(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId)
isDragging.value = false
;(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId)
}
const radialTexture = createRadialTexture(512)
@@ -176,4 +194,6 @@ function createRadialTexture(size: number): THREE.CanvasTexture {
ctx.fillRect(0, 0, size, size)
return new THREE.CanvasTexture(canvas)
}
applyTextureToScene(scene.value, texture.value)
</script>