diff --git a/README.md b/README.md index 3441de4..95ebca6 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ The first design families are djellaba, caftan, takchita, contemporary Moroccan styling, and accessories such as babouches, fez, scarves, belts, jewelry, and eyewear. The catalog is research-first: regional and cultural references must be documented and reviewed. No single outfit is treated as representative of every Moroccan person. -See [Moroccan Wardrobe Catalog](docs/MOROCCAN_WARDROBE_CATALOG.md). +See [Moroccan Wardrobe Catalog](docs/MOROCCAN_WARDROBE_CATALOG.md) and the [Character JSON Design Schema](docs/CHARACTER_JSON_SCHEMA.md). ## Technology @@ -57,18 +57,20 @@ npm run preview - 360-degree pointer rotation, auto-rotation, and zoom. - Initial appearance and wardrobe controls. - Expression and accessory selectors. -- Validated JSON export and import for a configured look. +- Validated JSON export/import for full character profiles, including body proportions, face shape, nose, jaw, ears, hair details, and clothing construction. - Local GLB 2.0 avatar import with a 32 MB limit and rejection of external asset URLs. - Local import of one skinned garment GLB, rebound to the imported avatar by exact skeleton bone names. - Playback and selection of animation clips embedded in imported GLB avatars. - Runtime sliders for facial morph targets exposed by imported GLB models (up to 24 controls). +- Live procedural controls for body proportions, facial anatomy, hair details, and clothing fit/embroidery. +- Semantic application of supported design properties to matching GLB morph targets and conventionally named skeleton bones. - Automatic local browser persistence with no account or server storage. - Restore saved looks after reloading the studio. - Responsive Arabic RTL interface.\n- Blender export helper and GLB production-profile validation for skinned avatars and garments. ## Important limitations -The built-in preview still uses procedural geometric shapes. Users can import a self-contained GLB 2.0 avatar locally (maximum 32 MB); imported assets are not uploaded. Production human topology, finished rigged character assets, facial shape-key authoring, authored Moroccan garment meshes, multi-piece outfit composition, realistic cloth behavior, editing imported model materials from the UI, and browser E2E tests are not yet implemented. The current garment loader is a single-piece rig-binding foundation and requires a compatible garment asset. The new Blender exporter and GLB validator provide production asset tooling, not the missing art assets. See the [execution roadmap](docs/ROADMAP_EXECUTION.md). +The built-in preview still uses procedural geometric shapes. Users can import a self-contained GLB 2.0 avatar locally (maximum 32 MB); imported assets are not uploaded. Production human topology, finished rigged character assets, authored Moroccan garment meshes, multi-piece outfit composition, realistic cloth simulation, and browser E2E tests are not yet implemented. Procedural geometry is a stylized preview: some detailed proportions are only visually approximate, and imported GLB anatomy changes require compatible morph targets or conventionally named bones; unsupported GLB properties are intentionally left unchanged. The current garment loader is a single-piece rig-binding foundation and requires a compatible garment asset. The new Blender exporter and GLB validator provide production asset tooling, not the missing art assets. See the [execution roadmap](docs/ROADMAP_EXECUTION.md). ## Independence and privacy diff --git a/app.js b/app.js index ea598d3..dc6400b 100644 --- a/app.js +++ b/app.js @@ -1,5 +1,6 @@ import * as THREE from 'three'; import { DEFAULT_AVATAR_CONFIG, validateAvatarConfig } from './src/avatar-config.js'; +import { CHARACTER_CATALOG, getCharacterPreset, validateCharacterDocument, createCharacterDocument } from './src/character-library.js'; import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; import { validateGlbArrayBuffer, MAX_GLB_BYTES } from './src/avatar-asset.js'; import { buildBoneRemap } from './src/garment-rig.js'; @@ -35,8 +36,8 @@ const key=new THREE.DirectionalLight(0xffe6c4,3.2);key.position.set(-3,5,5);key. const rim=new THREE.DirectionalLight(0x9bc9b5,2.3);rim.position.set(3,3,-4);scene.add(rim); const floor=new THREE.Mesh(new THREE.CircleGeometry(2.25,64),new THREE.MeshBasicMaterial({color:0x9cb79a,transparent:true,opacity:.08}));floor.rotation.x=-Math.PI/2;floor.position.y=-1.43;scene.add(floor); const model=new THREE.Group();scene.add(model); -const state={...DEFAULT_AVATAR_CONFIG}; -const STORAGE_KEY='arcode-persona:look:v1'; +const state=JSON.parse(JSON.stringify(DEFAULT_AVATAR_CONFIG)); +const STORAGE_KEY='arcode-persona:look:v2'; const importedRoot=new THREE.Group(); scene.add(importedRoot); let importedAvatar=null; @@ -45,6 +46,8 @@ let importedMixer=null; let importedActions=[]; let activeAnimationIndex=-1; let morphBindings=new Map(); +const importedBoneBaseScales=new WeakMap(); +let importedBaseScale=1; const mat=(color,roughness=.72,metalness=0)=>new THREE.MeshStandardMaterial({color,roughness,metalness}); const skinMat=()=>mat(state.skin); const sphere=(parent,x,y,z,sx,sy,sz,material,segments=32)=>{const m=new THREE.Mesh(new THREE.SphereGeometry(1,segments,segments),material);m.position.set(x,y,z);m.scale.set(sx,sy,sz);m.castShadow=true;m.receiveShadow=true;parent.add(m);return m}; @@ -53,43 +56,56 @@ let faceParts={}; function curve(parent,points,material,r=.018){const path=new THREE.CatmullRomCurve3(points.map(p=>new THREE.Vector3(...p)));const mesh=new THREE.Mesh(new THREE.TubeGeometry(path,24,r,8,false),material);parent.add(mesh);return mesh} function build(){ while(model.children.length) {const o=model.children[0];model.remove(o);o.traverse(n=>{n.geometry?.dispose();if(n.material){for(const material of (Array.isArray(n.material)?n.material:[n.material])) material.dispose()}})} - const skin=skinMat(),hair=mat(state.hair),cloth=mat(state.cloth,.58),gold=mat('#c7a45e',.34,.68),dark=mat('#251e1a'),white=mat('#f5eee1'),eye=mat(state.eyes,.3); - const torso=new THREE.Group();model.add(torso); - // Robe / outfit silhouette + const skin=skinMat(),hair=mat(state.hair),gold=mat(state.clothing.trimColor,.34,.68),dark=mat('#251e1a'),white=mat('#f5eee1'),eye=mat(state.eyes,.3); + const body=state.body,face=state.face,hairDesign=state.hairDetails,wardrobe=state.clothing; + const fitScale={slim:.92,regular:1,loose:1.08,oversized:1.16}[wardrobe.fit]; + const clothMaterial=mat(state.cloth,.58),trim=mat(wardrobe.trimColor,.34,.62); + const torso=new THREE.Group();model.add(torso);model.scale.set(1,body.height,1); + torso.scale.set(body.shoulderWidth*fitScale,body.torsoLength,body.bodyDepth); + const robeHeight=(state.outfit==='modern'?1.13:1.48)*wardrobe.robeLength; if(state.outfit==='modern'){ - cylinder(torso,.49,.63,1.13,0,-.42,0,cloth); - sphere(torso,0,.13,0,.48,.34,.29,cloth); - cylinder(torso,.18,.2,.24,0,.28,0,skin); + cylinder(torso,.49*fitScale,.63*fitScale,robeHeight,0,-.42,0,clothMaterial); + sphere(torso,0,.13,0,.48*fitScale,.34,.29,clothMaterial); + cylinder(torso,.18,.2,.24*wardrobe.collarHeight,0,.28,0,skin); }else{ - cylinder(torso,.42,.62,1.48,0,-.48,0,cloth); - sphere(torso,0,.16,0,.47,.34,.31,cloth); - cylinder(torso,.17,.19,.22,0,.31,0,skin); - // embroidered front line and neckline - curve(torso,[[0,.2,.315],[0,-.15,.38],[0,-.65,.53],[0,-1.15,.55]],gold,.014); - curve(torso,[[-.13,.28,.27],[0,.17,.34],[.13,.28,.27]],gold,.012); - for(let y=-.05;y>-.95;y-=.18){sphere(torso,0,y,.39,.025,.025,.012,gold,12)} - if(state.outfit==='takchita'){cylinder(torso,.5,.68,1.55,0,-.48,-.015,mat('#d8c7a0',.45),48).material.transparent=true;torso.children[torso.children.length-1].material.opacity=.22} - if(state.outfit==='caftan'){curve(torso,[[-.34,.15,.23],[-.25,-.2,.33],[0,-.8,.57],[.25,-.2,.33],[.34,.15,.23]],gold,.018)} - if(state.outfit==='djellaba'){const hood=sphere(torso,0,.49,-.18,.36,.25,.22,cloth);hood.visible=state.headwear==='hood'} + const waist=.42*body.waistWidth*(wardrobe.fit==='slim'?.92:wardrobe.fit==='oversized'?1.12:1); + cylinder(torso,waist,.62*body.hipWidth*fitScale,robeHeight,0,-.48,0,clothMaterial); + sphere(torso,0,.16,0,.47*fitScale,.34,.31,clothMaterial); + cylinder(torso,.17,.19,.22*wardrobe.collarHeight,0,.31,0,skin); + curve(torso,[[0,.2,.315],[0,-.15,.38],[0,-.65,.53],[0,-1.15*wardrobe.robeLength,.55]],trim,.009+.012*wardrobe.embroidery); + curve(torso,[[-.13,.28,.27],[0,.17,.34],[.13,.28,.27]],trim,.008+.012*wardrobe.embroidery); + const stitchCount=Math.round(wardrobe.embroidery*7); + for(let i=0;i.05)sphere(head,0,.34,.39,.3*volume,.08+hairDesign.fringe*.13,.16*volume,hair); + if(hairDesign.sideburn>.05)for(const s of [-1,1])sphere(head,s*.49,-.04,.12,.055,.12+hairDesign.sideburn*.12,.08,hair); + if(hairDesign.part!=='none'){const x=hairDesign.part==='left'?.12:hairDesign.part==='right'?-.12:0;curve(head,[[x,.72,.08],[x,.68,.22],[x,.57,.36]],mat('#5b5148'),.008)} } // brows and eyes faceParts={eyes:[],mouth:null}; @@ -99,7 +115,7 @@ function build(){ faceParts.eyes.push(sphere(head,s*.235,.035,.472,.038,.045,.018,eye,20)); sphere(head,s*.235,.035,.488,.016,.02,.009,dark,16); } - sphere(head,0,-.08,.47,.07,.14,.075,skin); + sphere(head,0,-.08,.47,.055*face.noseWidth,.14*face.noseLength,.075*face.noseBridgeHeight,skin);sphere(head,0,-.15,.51,.07*face.noseWidth,.045*face.noseTip,.07,skin,20); faceParts.mouth=curve(head,[[-.14,-.29,.43],[0,-.34,.47],[.14,-.29,.43]],mat('#6b302d'),.018); if(state.expression==='neutral'){faceParts.mouth.scale.y=.45} if(state.expression==='surprised'){faceParts.mouth.scale.set(.55,1.8,1)} @@ -137,19 +153,66 @@ renderer.domElement.addEventListener('wheel',e=>{e.preventDefault();zoom=THREE.M function animate(){requestAnimationFrame(animate);const delta=clock.getDelta();const t=clock.elapsedTime;if(importedMixer)importedMixer.update(delta);if(auto&&!dragging)rotation+=.0025;model.rotation.y=rotation;model.position.y=Math.sin(t*1.5)*.025;model.rotation.z=Math.sin(t*.8)*.012;importedRoot.rotation.y=rotation;importedRoot.position.y=model.position.y;renderer.render(scene,camera)} animate(); document.getElementById('loading').classList.add('hidden'); -function update(){build();persistLook()} +function update(){build();applyImportedCharacterDesign();persistLook()} +function applyImportedCharacterDesign(){ + if(!importedAvatar)return; + const design=state; + const normalizedScale=importedBaseScale||1; + importedAvatar.scale.set(normalizedScale,normalizedScale*design.body.height,normalizedScale); + const targets={ + facewidth:design.face.width, headwidth:design.face.width, + facenarrow:2-design.face.width, headnarrow:2-design.face.width, + faceheight:design.face.height, headheight:design.face.height, + faceround:design.face.shape==='round'?1:0, facesquare:design.face.shape==='square'?1:0, + faceheart:design.face.shape==='heart'?1:0, facelong:design.face.shape==='long'?1:0, faceoval:design.face.shape==='oval'?1:0, + cheekwidth:design.face.cheekboneWidth, cheekbonewidth:design.face.cheekboneWidth, + cheeknarrow:2-design.face.cheekboneWidth, + jawwidth:design.face.jawWidth, jawwide:design.face.jawWidth, + jawnarrow:2-design.face.jawWidth, chinwidth:design.face.chinWidth, chinnarrow:2-design.face.chinWidth, + nosewidth:design.face.noseWidth, nosenarrow:2-design.face.noseWidth, + noselength:design.face.noseLength, noseshort:2-design.face.noseLength, + nosebridgeheight:design.face.noseBridgeHeight, nosetip:design.face.noseTip, earsize:design.face.earSize, + earprotrusion:design.face.earProtrusion, headscale:design.body.headScale + }; + importedAvatar.traverse(node=>{ + if(node.isMesh&&node.morphTargetDictionary&&node.morphTargetInfluences){ + for(const [name,index] of Object.entries(node.morphTargetDictionary)){ + const key=name.toLowerCase().replace(/[^a-z]/g,''); + if(Object.prototype.hasOwnProperty.call(targets,key)){ + const value=THREE.MathUtils.clamp((targets[key]-1)*2.5,0,1); + node.morphTargetInfluences[index]=value; + } + } + } + if(node.isBone){ + const name=node.name.toLowerCase().replace(/[^a-z]/g,''); + let base=importedBoneBaseScales.get(node);if(!base){base=node.scale.clone();importedBoneBaseScales.set(node,base)} + let x=1,y=1; + if(/shoulder|clavicle|upperarm/.test(name))x=design.body.shoulderWidth; + if(/spine|chest|torso/.test(name))y=design.body.torsoLength; + if(/hips|pelvis/.test(name))x=design.body.hipWidth; + if(/upperleg|thigh|upleg/.test(name))y=design.body.legLength; + if(/lowerleg|calf|shin/.test(name))y=design.body.legLength; + if(/neck/.test(name))y=design.body.neckLength; + if(/head/.test(name))x=y=design.body.headScale; + node.scale.set(base.x*x,base.y*y,base.z); + } + }); +} function persistLook(){try{localStorage.setItem(STORAGE_KEY,JSON.stringify(validateAvatarConfig(state)))}catch(error){console.warn('Unable to save persona locally:',error)}} -function restoreLook(input){try{const config=validateAvatarConfig(input);Object.assign(state,config);syncControls();update();toast('تمت استعادة الإطلالة')}catch(error){toast('ملف الإطلالة غير صالح أو غير مدعوم');console.error(error)}} +function applyAvatarConfig(input){const config=validateAvatarConfig(input);Object.assign(state,config);for(const section of ['body','face','hairDetails','clothing'])state[section]={...config[section]};return config} +function restoreLook(input){try{const characterDocument=validateCharacterDocument(input);applyAvatarConfig(characterDocument.config);syncDesignControls();const selector=globalThis.document.getElementById('characterPreset');if(selector)selector.value=characterDocument.profile?.id||'';syncControls();update();toast(characterDocument.profile?'تم استيراد ملف الشخصية':'تمت استعادة الإطلالة')}catch(error){toast('ملف الشخصية غير صالح أو غير مدعوم');console.error(error)}} function syncControls(){ const keys={skin:'skinOptions',hair:'hairOptions',cloth:'clothOptions'}; for(const [key,id] of Object.entries(keys))document.querySelectorAll(`#${id} .swatch`).forEach(b=>b.classList.toggle('selected',b.dataset.value===state[key])); document.querySelectorAll('#outfitOptions .choice').forEach(b=>b.classList.toggle('selected',b.dataset.value===state.outfit)); for(const id of ['hairStyle','expression','headwear','eyes','accessory'])document.getElementById(id).value=state[id]; } -function bindSwatches(id,key){document.querySelectorAll('#'+id+' .swatch').forEach(b=>b.addEventListener('click',()=>{document.querySelectorAll('#'+id+' .swatch').forEach(x=>x.classList.remove('selected'));b.classList.add('selected');state[key]=b.dataset.value;update()}))} +function markCharacterCustom(){const selector=document.getElementById('characterPreset');if(selector)selector.value=''} +function bindSwatches(id,key){document.querySelectorAll('#'+id+' .swatch').forEach(b=>b.addEventListener('click',()=>{markCharacterCustom();document.querySelectorAll('#'+id+' .swatch').forEach(x=>x.classList.remove('selected'));b.classList.add('selected');state[key]=b.dataset.value;update()}))} bindSwatches('skinOptions','skin');bindSwatches('hairOptions','hair');bindSwatches('clothOptions','cloth'); -[['hairStyle','hairStyle'],['expression','expression'],['headwear','headwear'],['eyes','eyes'],['accessory','accessory']].forEach(([id,key])=>document.getElementById(id).addEventListener('change',e=>{state[key]=e.target.value;update()})); -document.querySelectorAll('#outfitOptions .choice').forEach(b=>b.addEventListener('click',()=>{document.querySelectorAll('#outfitOptions .choice').forEach(x=>x.classList.remove('selected'));b.classList.add('selected');state.outfit=b.dataset.value;update()})); +[['hairStyle','hairStyle'],['expression','expression'],['headwear','headwear'],['eyes','eyes'],['accessory','accessory']].forEach(([id,key])=>document.getElementById(id).addEventListener('change',e=>{markCharacterCustom();state[key]=e.target.value;update()})); +document.querySelectorAll('#outfitOptions .choice').forEach(b=>b.addEventListener('click',()=>{markCharacterCustom();document.querySelectorAll('#outfitOptions .choice').forEach(x=>x.classList.remove('selected'));b.classList.add('selected');state.outfit=b.dataset.value;update()})); document.querySelectorAll('.tab').forEach(b=>b.addEventListener('click',()=>{document.querySelectorAll('.tab,.tab-content').forEach(x=>x.classList.remove('active'));b.classList.add('active');document.getElementById(b.dataset.tab).classList.add('active')})); document.getElementById('rotate').addEventListener('click',e=>{auto=!auto;e.currentTarget.classList.toggle('active',auto);e.currentTarget.innerHTML=auto?'⟳ دوران تلقائي':'Ⅱ إيقاف الدوران'}); document.getElementById('frontView').addEventListener('click',()=>{rotation=0;auto=false;document.getElementById('rotate').classList.remove('active')}); @@ -293,11 +356,13 @@ async function importAvatarAsset(file){ const normalizedRoot=new THREE.Group(); normalizedRoot.add(root); normalizedRoot.scale.setScalar(scale); + importedBaseScale=scale; normalizedRoot.position.copy(center).multiplyScalar(-scale); disposeImportedAvatar(); importedAvatar=normalizedRoot; importedRoot.add(normalizedRoot); buildMorphControls(root); + applyImportedCharacterDesign(); importedMixer=new THREE.AnimationMixer(root); importedActions=gltf.animations.map(clip=>importedMixer.clipAction(clip)); animationSelect.replaceChildren(new Option('اختر الحركة','')); @@ -379,12 +444,79 @@ function removeAvatarAsset(){ } function toast(msg){const el=document.getElementById('toast');el.textContent=msg;el.classList.add('show');setTimeout(()=>el.classList.remove('show'),2300)} -function reset(){Object.assign(state,DEFAULT_AVATAR_CONFIG);syncControls();rotation=0;zoom=7.6;camera.position.set(0,1.45,zoom);auto=true;document.getElementById('rotate').classList.add('active');document.getElementById('rotate').innerHTML='⟳ دوران تلقائي';update();toast('تمت إعادة الإطلالة الافتراضية')} +function reset(){applyAvatarConfig(DEFAULT_AVATAR_CONFIG);markCharacterCustom();syncControls();syncDesignControls();rotation=0;zoom=7.6;camera.position.set(0,1.45,zoom);auto=true;document.getElementById('rotate').classList.add('active');document.getElementById('rotate').innerHTML='⟳ دوران تلقائي';update();toast('تمت إعادة الإطلالة الافتراضية')} document.getElementById('resetTop').addEventListener('click',reset); -document.getElementById('randomize').addEventListener('click',()=>{const pick=a=>a[Math.floor(Math.random()*a.length)];state.skin=pick(['#b97850','#e0a77d','#8e573d','#603b30','#c98d70']);state.hair=pick(['#241b19','#57352a','#b78b53']);state.cloth=pick(['#176b60','#172b50','#873f49','#d1b16d']);state.outfit=pick(['djellaba','caftan','modern','takchita']);state.expression=pick(['smile','neutral','surprised']);update();toast('تم ابتكار إطلالة جديدة')}); -document.getElementById('saveLook').addEventListener('click',()=>{const data=validateAvatarConfig(state);const blob=new Blob([JSON.stringify(data,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download='arcode-persona-look.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);toast('تم تصدير إعدادات الشخصية')}); +document.getElementById('randomize').addEventListener('click',()=>{const pick=a=>a[Math.floor(Math.random()*a.length)];state.body.shoulderWidth=pick([.92,1,1.08]);state.face.shape=pick(['oval','round','square','heart','long']);state.face.noseWidth=pick([.9,1,1.1]);state.skin=pick(['#b97850','#e0a77d','#8e573d','#603b30','#c98d70']);state.hair=pick(['#241b19','#57352a','#b78b53']);state.cloth=pick(['#176b60','#172b50','#873f49','#d1b16d']);state.outfit=pick(['djellaba','caftan','modern','takchita']);state.expression=pick(['smile','neutral','surprised']);markCharacterCustom();syncDesignControls();update();toast('تم ابتكار إطلالة جديدة')}); +document.getElementById('saveLook').addEventListener('click',()=>{const selected=getCharacterPreset(document.getElementById('characterPreset')?.value);const data=createCharacterDocument(state,selected||{id:'custom',name:'شخصيتي المخصصة',description:'شخصية مخصصة أنشأها المستخدم.',tags:['custom']});const blob=new Blob([JSON.stringify(data,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download='arcode-persona-look.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);toast('تم تصدير إعدادات الشخصية')}); +const DESIGN_CONTROL_DEFS={ + body:[ + ['height','طول الجسم',.8,1.2,.01],['shoulderWidth','عرض الكتفين',.7,1.35,.01],['torsoLength','طول الجذع',.8,1.2,.01], + ['bodyDepth','عمق الجسم',.75,1.3,.01],['waistWidth','عرض الخصر',.7,1.35,.01],['hipWidth','عرض الوركين',.7,1.4,.01], + ['armLength','طول الذراعين',.8,1.2,.01],['legLength','طول الساقين',.8,1.2,.01],['headScale','حجم الرأس',.8,1.2,.01],['neckLength','طول الرقبة',.7,1.3,.01] + ], + face:[ + ['shape','شكل الوجه',['oval','round','square','heart','long']],['width','عرض الوجه',.75,1.25,.01],['height','ارتفاع الوجه',.8,1.2,.01], + ['cheekboneWidth','عرض عظام الخد',.75,1.3,.01],['jawWidth','عرض الفك',.7,1.3,.01],['chinWidth','عرض الذقن',.65,1.35,.01], + ['noseBridgeHeight','ارتفاع جسر الأنف',.65,1.35,.01],['noseLength','طول الأنف',.7,1.3,.01],['noseWidth','عرض الأنف',.65,1.35,.01], + ['noseTip','حجم طرف الأنف',.7,1.3,.01],['earSize','حجم الأذنين',.7,1.3,.01],['earProtrusion','بروز الأذنين',.5,1.5,.01],['earAngle','زاوية الأذنين',-25,25,1] + ], + hairDetails:[ + ['volume','حجم الشعر',.5,1.6,.01],['density','كثافة الشعر',.5,1.5,.01],['fringe','الغرة',0,1,.01], + ['part','فرق الشعر',['center','left','right','none']],['curl','درجة التجعد',0,1,.01],['sideburn','السوالف',0,1,.01],['length','طول الشعر',.5,1.8,.01] + ], + clothing:[ + ['fit','قَصّة الملابس',['slim','regular','loose','oversized']],['sleeveLength','طول الأكمام',.5,1.3,.01], + ['robeLength','طول الرداء',.7,1.3,.01],['collarHeight','ارتفاع الياقة',.5,1.5,.01],['embroidery','كثافة التطريز',0,1,.01], + ['trimColor','لون الزخرفة','color'],['belt','الحزام','boolean'],['layer','طبقات اللباس',['single','inner-outer','ceremonial']] + ] +}; +const DESIGN_LABELS={oval:'بيضاوي',round:'مستدير',square:'مربع',heart:'قلبي',long:'طويل',center:'وسط',left:'يسار',right:'يمين',none:'بدون',slim:'ضيق',regular:'عادي',loose:'واسع',oversized:'فضفاض','inner-outer':'داخلي وخارجي',ceremonial:'احتفالي',single:'طبقة واحدة'}; +function setDesignValue(section,key,value){state[section][key]=value;update()} +function buildDesignControls(){ + for(const [section,definitions] of Object.entries(DESIGN_CONTROL_DEFS)){ + const container=document.getElementById(section+'DesignControls');if(!container)continue;container.replaceChildren(); + for(const [key,label,minOrOptions,max,step] of definitions){ + const field=document.createElement('div');field.className='design-control'; + const id='design-'+section+'-'+key;const caption=document.createElement('label');caption.htmlFor=id;caption.textContent=label; + let input; + if(Array.isArray(minOrOptions)){ + input=document.createElement('select');for(const value of minOrOptions){const option=document.createElement('option');option.value=value;option.textContent=DESIGN_LABELS[value]||value;input.append(option)} + }else if(minOrOptions==='color'){ + input=document.createElement('input');input.type='color'; + }else if(minOrOptions==='boolean'){ + input=document.createElement('input');input.type='checkbox'; + }else{ + input=document.createElement('input');input.type='range';input.min=String(minOrOptions);input.max=String(max);input.step=String(step); + } + input.id=id; + const output=document.createElement('output');output.textContent=''; + const eventName=input.type==='range'?'input':'change'; + input.addEventListener(eventName,()=>{ + markCharacterCustom();const value=input.type==='checkbox'?input.checked:input.type==='range'?Number(input.value):input.value; + state[section][key]=value;if(output)output.textContent=input.type==='range'?value.toFixed(2):''; + update(); + }); + field.append(caption,input,output);container.append(field); + } + } + syncDesignControls(); +} +function syncDesignControls(){ + for(const [section,definitions] of Object.entries(DESIGN_CONTROL_DEFS)){ + for(const [key] of definitions){ + const input=document.getElementById('design-'+section+'-'+key);if(!input)continue; + const value=state[section][key]; + if(input.type==='checkbox')input.checked=value;else input.value=String(value); + const output=input.parentElement.querySelector('output');if(output)output.textContent=input.type==='range'?Number(value).toFixed(2):''; + } + } +} +buildDesignControls(); + +const characterPreset=document.getElementById('characterPreset'); +if(characterPreset){for(const item of CHARACTER_CATALOG.characters){const option=document.createElement('option');option.value=item.id;option.textContent=item.name+' — '+item.description;characterPreset.appendChild(option)}characterPreset.addEventListener('change',()=>{if(!characterPreset.value)return;try{const preset=getCharacterPreset(characterPreset.value);applyAvatarConfig(preset.config);syncControls();syncDesignControls();update();toast('تم تطبيق تصميم '+preset.name)}catch(error){console.error(error);toast('تعذر تطبيق تصميم الشخصية')}})} const importInput=document.getElementById('importLookFile'); document.getElementById('importLook').addEventListener('click',()=>importInput.click()); importInput.addEventListener('change',async()=>{const file=importInput.files?.[0];if(!file)return;if(file.size>64*1024){toast('حجم ملف الإطلالة أكبر من المسموح');importInput.value='';return}try{restoreLook(JSON.parse(await file.text()))}catch(error){toast('تعذر قراءة ملف الإطلالة');console.error(error)}finally{importInput.value=''}}); -try{const saved=localStorage.getItem(STORAGE_KEY);if(saved)restoreLook(JSON.parse(saved))}catch(error){console.warn('Saved persona look could not be restored:',error);localStorage.removeItem(STORAGE_KEY)} +try{const saved=localStorage.getItem(STORAGE_KEY)||localStorage.getItem('arcode-persona:look:v1');if(saved)restoreLook(JSON.parse(saved));localStorage.removeItem('arcode-persona:look:v1')}catch(error){console.warn('Saved persona look could not be restored:',error);localStorage.removeItem(STORAGE_KEY);localStorage.removeItem('arcode-persona:look:v1')} window.addEventListener('beforeunload',()=>{renderer.dispose();disposeImportedAvatar();scene.traverse(o=>{o.geometry?.dispose();if(o.material){for(const m of(Array.isArray(o.material)?o.material:[o.material]))m.dispose()}})}); diff --git a/data/characters.json b/data/characters.json new file mode 100644 index 0000000..27d56da --- /dev/null +++ b/data/characters.json @@ -0,0 +1,410 @@ +{ + "schemaVersion": 2, + "characters": [ + { + "id": "atlas-scholar", + "name": "باحث الأطلس", + "description": "مظهر يومي مغربي بجلابة خضراء", + "tags": [ + "moroccan", + "male-style", + "heritage" + ], + "config": { + "skin": "#b97850", + "hair": "#241b19", + "hairStyle": "short", + "cloth": "#176b60", + "outfit": "djellaba", + "headwear": "none", + "expression": "neutral", + "eyes": "#38251e", + "accessory": "none", + "schemaVersion": 2, + "body": { + "height": 1.02, + "shoulderWidth": 1.04, + "torsoLength": 1.01, + "bodyDepth": 1, + "waistWidth": 0.98, + "hipWidth": 1, + "armLength": 1, + "legLength": 1.02, + "headScale": 0.98, + "neckLength": 1 + }, + "face": { + "shape": "oval", + "width": 0.98, + "height": 1, + "cheekboneWidth": 1.02, + "jawWidth": 0.96, + "chinWidth": 0.95, + "noseBridgeHeight": 1, + "noseLength": 1, + "noseWidth": 0.96, + "noseTip": 1, + "earSize": 0.95, + "earProtrusion": 1, + "earAngle": 0 + }, + "hairDetails": { + "volume": 1, + "density": 1, + "fringe": 0.2, + "part": "left", + "curl": 0.25, + "sideburn": 0.55, + "length": 1 + }, + "clothing": { + "fit": "regular", + "sleeveLength": 1, + "robeLength": 1.05, + "collarHeight": 1.1, + "embroidery": 0.75, + "trimColor": "#c7a45e", + "belt": false, + "layer": "single" + } + } + }, + { + "id": "fes-craftsman", + "name": "صانع فاسي", + "description": "جلابة داكنة وطربوش تقليدي", + "tags": [ + "fes", + "craft", + "heritage" + ], + "config": { + "skin": "#8e573d", + "hair": "#241b19", + "hairStyle": "short", + "cloth": "#172b50", + "outfit": "djellaba", + "headwear": "fez", + "expression": "smile", + "eyes": "#38251e", + "accessory": "none", + "schemaVersion": 2, + "body": { + "height": 1.04, + "shoulderWidth": 1.08, + "torsoLength": 1, + "bodyDepth": 1.04, + "waistWidth": 1, + "hipWidth": 1.02, + "armLength": 1.02, + "legLength": 1.03, + "headScale": 0.97, + "neckLength": 0.98 + }, + "face": { + "shape": "square", + "width": 1.04, + "height": 0.98, + "cheekboneWidth": 1.04, + "jawWidth": 1.12, + "chinWidth": 1.08, + "noseBridgeHeight": 1.05, + "noseLength": 1, + "noseWidth": 1.04, + "noseTip": 1.02, + "earSize": 1, + "earProtrusion": 1, + "earAngle": 2 + }, + "hairDetails": { + "volume": 0.9, + "density": 1, + "fringe": 0.1, + "part": "none", + "curl": 0.2, + "sideburn": 0.8, + "length": 0.8 + }, + "clothing": { + "fit": "loose", + "sleeveLength": 1.04, + "robeLength": 1.08, + "collarHeight": 1.2, + "embroidery": 0.55, + "trimColor": "#c7a45e", + "belt": false, + "layer": "single" + } + } + }, + { + "id": "royal-caftan", + "name": "أناقة القفطان", + "description": "قفطان عنابي بلمسات ذهبية", + "tags": [ + "caftan", + "formal", + "heritage" + ], + "config": { + "skin": "#c98d70", + "hair": "#241b19", + "hairStyle": "long", + "cloth": "#873f49", + "outfit": "caftan", + "headwear": "none", + "expression": "smile", + "eyes": "#38251e", + "accessory": "earring", + "schemaVersion": 2, + "body": { + "height": 1, + "shoulderWidth": 0.96, + "torsoLength": 1, + "bodyDepth": 0.96, + "waistWidth": 0.92, + "hipWidth": 1, + "armLength": 1, + "legLength": 1, + "headScale": 1, + "neckLength": 1.02 + }, + "face": { + "shape": "heart", + "width": 0.98, + "height": 1, + "cheekboneWidth": 1.08, + "jawWidth": 0.86, + "chinWidth": 0.82, + "noseBridgeHeight": 0.98, + "noseLength": 0.94, + "noseWidth": 0.9, + "noseTip": 0.98, + "earSize": 0.94, + "earProtrusion": 1, + "earAngle": 0 + }, + "hairDetails": { + "volume": 1.2, + "density": 1.1, + "fringe": 0.45, + "part": "center", + "curl": 0.15, + "sideburn": 0.2, + "length": 1.25 + }, + "clothing": { + "fit": "slim", + "sleeveLength": 0.98, + "robeLength": 1, + "collarHeight": 1.25, + "embroidery": 0.95, + "trimColor": "#d8b66b", + "belt": true, + "layer": "ceremonial" + } + } + }, + { + "id": "takchita-evening", + "name": "تكشيطة المناسبات", + "description": "تكشيطة عاجية بإطلالة احتفالية", + "tags": [ + "takchita", + "formal" + ], + "config": { + "skin": "#e0a77d", + "hair": "#57352a", + "hairStyle": "long", + "cloth": "#e8dfce", + "outfit": "takchita", + "headwear": "none", + "expression": "smile", + "eyes": "#92704b", + "accessory": "earring", + "schemaVersion": 2, + "body": { + "height": 1, + "shoulderWidth": 0.98, + "torsoLength": 1.02, + "bodyDepth": 1, + "waistWidth": 0.94, + "hipWidth": 1.03, + "armLength": 1, + "legLength": 1, + "headScale": 1.02, + "neckLength": 1 + }, + "face": { + "shape": "oval", + "width": 1, + "height": 1.02, + "cheekboneWidth": 1.03, + "jawWidth": 0.9, + "chinWidth": 0.9, + "noseBridgeHeight": 1, + "noseLength": 0.96, + "noseWidth": 0.92, + "noseTip": 1, + "earSize": 0.95, + "earProtrusion": 0.95, + "earAngle": 0 + }, + "hairDetails": { + "volume": 1.25, + "density": 1.15, + "fringe": 0.55, + "part": "right", + "curl": 0.35, + "sideburn": 0.2, + "length": 1.3 + }, + "clothing": { + "fit": "regular", + "sleeveLength": 1, + "robeLength": 1.04, + "collarHeight": 1.2, + "embroidery": 1, + "trimColor": "#bfa16a", + "belt": true, + "layer": "ceremonial" + } + } + }, + { + "id": "modern-urban", + "name": "عصري حضري", + "description": "ملابس معاصرة بألوان هادئة", + "tags": [ + "modern", + "urban" + ], + "config": { + "skin": "#b97850", + "hair": "#57352a", + "hairStyle": "curly", + "cloth": "#172b50", + "outfit": "modern", + "headwear": "none", + "expression": "neutral", + "eyes": "#55718c", + "accessory": "glasses", + "schemaVersion": 2, + "body": { + "height": 1.03, + "shoulderWidth": 1.02, + "torsoLength": 1, + "bodyDepth": 1, + "waistWidth": 1, + "hipWidth": 1, + "armLength": 1.02, + "legLength": 1.03, + "headScale": 0.98, + "neckLength": 1 + }, + "face": { + "shape": "long", + "width": 0.94, + "height": 1.08, + "cheekboneWidth": 0.96, + "jawWidth": 0.94, + "chinWidth": 0.9, + "noseBridgeHeight": 1.02, + "noseLength": 1.08, + "noseWidth": 0.9, + "noseTip": 1, + "earSize": 0.95, + "earProtrusion": 1, + "earAngle": 0 + }, + "hairDetails": { + "volume": 1.15, + "density": 1, + "fringe": 0.25, + "part": "left", + "curl": 0.8, + "sideburn": 0.45, + "length": 0.85 + }, + "clothing": { + "fit": "regular", + "sleeveLength": 1, + "robeLength": 0.98, + "collarHeight": 0.9, + "embroidery": 0.25, + "trimColor": "#b7c1b5", + "belt": false, + "layer": "single" + } + } + }, + { + "id": "souss-warmth", + "name": "دفء سوس", + "description": "ألوان ترابية مستوحاة من الجنوب", + "tags": [ + "souss", + "regional-inspiration" + ], + "config": { + "skin": "#8e573d", + "hair": "#241b19", + "hairStyle": "curly", + "cloth": "#d1b16d", + "outfit": "djellaba", + "headwear": "hood", + "expression": "smile", + "eyes": "#92704b", + "accessory": "scarf", + "schemaVersion": 2, + "body": { + "height": 1.04, + "shoulderWidth": 1.06, + "torsoLength": 1.02, + "bodyDepth": 1.05, + "waistWidth": 1.04, + "hipWidth": 1.08, + "armLength": 1.02, + "legLength": 1.02, + "headScale": 1, + "neckLength": 0.96 + }, + "face": { + "shape": "round", + "width": 1.08, + "height": 0.96, + "cheekboneWidth": 1.08, + "jawWidth": 1.02, + "chinWidth": 1.05, + "noseBridgeHeight": 0.98, + "noseLength": 0.94, + "noseWidth": 1.08, + "noseTip": 1.05, + "earSize": 1.04, + "earProtrusion": 1.05, + "earAngle": 4 + }, + "hairDetails": { + "volume": 1.2, + "density": 1.15, + "fringe": 0.15, + "part": "none", + "curl": 0.9, + "sideburn": 0.7, + "length": 0.9 + }, + "clothing": { + "fit": "loose", + "sleeveLength": 1.08, + "robeLength": 1.1, + "collarHeight": 1.1, + "embroidery": 0.7, + "trimColor": "#d0ad68", + "belt": false, + "layer": "single" + } + } + } + ] +} diff --git a/docs/CHARACTER_JSON_SCHEMA.md b/docs/CHARACTER_JSON_SCHEMA.md new file mode 100644 index 0000000..c4aa9d8 --- /dev/null +++ b/docs/CHARACTER_JSON_SCHEMA.md @@ -0,0 +1,85 @@ +# Character JSON Design Schema + +ArCode Persona stores portable character designs as versioned JSON. The current design contract is **avatar config v2** and character document format v2. The validator still accepts legacy flat avatar configs (v1) and character documents with formatVersion 1; these are normalized to config v2 when loaded and re-exported. + +## Character document + +```json +{ + "format": "arcode-persona-character", + "formatVersion": 2, + "id": "custom-character", + "name": "My character", + "description": "A customizable character profile", + "tags": ["custom"], + "config": { + "schemaVersion": 2, + "skin": "#b97850", + "hair": "#241b19", + "hairStyle": "curly", + "cloth": "#176b60", + "outfit": "djellaba", + "headwear": "none", + "expression": "neutral", + "eyes": "#38251e", + "accessory": "none", + "body": { + "height": 1, "shoulderWidth": 1, "torsoLength": 1, "bodyDepth": 1, + "waistWidth": 1, "hipWidth": 1, "armLength": 1, "legLength": 1, + "headScale": 1, "neckLength": 1 + }, + "face": { + "shape": "oval", "width": 1, "height": 1, "cheekboneWidth": 1, + "jawWidth": 1, "chinWidth": 1, "noseBridgeHeight": 1, + "noseLength": 1, "noseWidth": 1, "noseTip": 1, + "earSize": 1, "earProtrusion": 1, "earAngle": 0 + }, + "hairDetails": { + "volume": 1, "density": 1, "fringe": 0.25, + "part": "center", "curl": 0.5, "sideburn": 0.5, "length": 1 + }, + "clothing": { + "fit": "regular", "sleeveLength": 1, "robeLength": 1, + "collarHeight": 1, "embroidery": 0.65, + "trimColor": "#c7a45e", "belt": false, "layer": "single" + } + } +} +``` + +## Design sections + +- **body**: overall height, shoulder/torso/waist/hip proportions, arm/leg lengths, head scale, and neck length. +- **face**: face silhouette, width/height, cheekbones, jaw/chin, nose bridge/length/width/tip, and ear size/projection/angle. +- **hairDetails**: volume, density, fringe, parting, curl amount, sideburns, and length. +- **clothing**: fit, sleeves, robe length, collar, embroidery amount/color, belt, and layer style. + +All numeric properties are finite and range-checked at import. Enumerations and colors are validated. Unknown keys are rejected instead of silently ignored. + +## Three.js application behavior + +### Procedural preview + +The built-in stylized placeholder responds directly to the design values: +- Body height and upper-body proportions scale the model and torso. +- Face silhouette, jaw/chin, cheekbones, nose, and ears modify the generated head geometry. +- Hair values change the cap, curls, fringe, part, sideburns, and long-hair strands. +- Clothing values alter robe fit/length, sleeves, collar, trim, belt, and simple outer-layer geometry. + +This is a controllable stylized preview, not production human anatomy or physically simulated cloth. Leg length is stored in JSON but is not visible on the current robe-only placeholder. + +### Imported GLB + +When an imported GLB exposes compatible targets, the runtime applies matching semantic morph-target names (case-insensitive, punctuation-insensitive), including names such as `FaceWidth`, `FaceNarrow`, `FaceRound`, `JawWidth`, `NoseWidth`, `NoseLength`, `NoseTip`, `EarSize`, and `HeadScale`. + +Body scaling is applied only where a compatible named bone exists. Recognized bone-name groups include shoulder/clavicle/upperarm, spine/chest/torso, hips/pelvis, thigh/upperleg, calf/shin/lowerleg, neck, and head. Original bone scales are retained and used as the baseline to prevent cumulative scaling. + +The GLB must contain matching morph targets or a conventionally named skeleton for the corresponding property to affect it. The runtime does not fabricate missing shape keys or bones. Clothing design values currently affect the procedural garment preview; imported garment material editing and cloth fitting remain separate work. + +## Compatibility and validation + +- Config v1 flat looks are migrated to config v2 defaults. +- Character document format versions 1 and 2 are accepted. +- New exports use character document format v2. +- Unknown properties, invalid ranges, unsupported enum values, and malformed hex colors are rejected. +- Character designs are stored locally or exported by the browser; this schema does not upload a user's design. diff --git a/docs/ROADMAP_EXECUTION.md b/docs/ROADMAP_EXECUTION.md index ded8009..3050d03 100644 --- a/docs/ROADMAP_EXECUTION.md +++ b/docs/ROADMAP_EXECUTION.md @@ -10,6 +10,8 @@ ## Phase 1 — High-quality character system - [x] Establish a local GLB 2.0 import path with size, header, version, and external-resource checks. +- [x] Define versioned body, face, hair, and clothing proportion properties in JSON. +- [x] Connect procedural geometry and compatible imported GLB morph/bone targets to design properties. - [ ] Approve stylized visual direction and character proportions. - [ ] Create production base mesh and rig. - [x] Expose imported GLB facial morph targets through runtime sliders. @@ -32,7 +34,8 @@ - [x] Import a local GLB avatar into the live preview. - [x] Add single-piece local garment import with bone-name rig rebinding. - [ ] Add multi-piece outfit composition, layering, and clipping QA. -- [ ] Preset library and outfit slots. +- [x] Add a JSON character preset library with live design controls. +- [ ] Multi-slot outfit composition and authored garment asset layers. - [ ] Color/material controls with accessible names. - [ ] Undo/redo and reset scopes. - [ ] Visual snapshot and shareable export. diff --git a/index.html b/index.html index dd883bc..339444d 100644 --- a/index.html +++ b/index.html @@ -42,6 +42,7 @@

اصنع شخصية تشبهك.

+
قوالب قابلة للتعديل والتصدير كملفات شخصية مستقلة.
@@ -56,6 +57,10 @@

اصنع شخصية تشبهك.

+
+
+
+
diff --git a/src/avatar-config.js b/src/avatar-config.js index ec8a506..cd7b269 100644 --- a/src/avatar-config.js +++ b/src/avatar-config.js @@ -1,9 +1,8 @@ /** - * Versioned, platform-neutral avatar configuration contract. - * Keep this module free of rendering dependencies so it can be reused by - * future web, mobile, and server-side adapters. + * Versioned, renderer-independent character design contract. + * Version 1 flat looks are migrated automatically to the nested version 2 model. */ -export const AVATAR_CONFIG_VERSION = 1; +export const AVATAR_CONFIG_VERSION = 2; export const AVATAR_OPTIONS = Object.freeze({ hairStyle: ['short', 'curly', 'long', 'shaved'], @@ -13,6 +12,26 @@ export const AVATAR_OPTIONS = Object.freeze({ accessory: ['none', 'glasses', 'earring', 'scarf'] }); +export const DESIGN_DEFAULTS = Object.freeze({ + body: Object.freeze({ + height: 1, shoulderWidth: 1, torsoLength: 1, bodyDepth: 1, + waistWidth: 1, hipWidth: 1, armLength: 1, legLength: 1, headScale: 1, neckLength: 1 + }), + face: Object.freeze({ + shape: 'oval', width: 1, height: 1, cheekboneWidth: 1, jawWidth: 1, + chinWidth: 1, noseBridgeHeight: 1, noseLength: 1, noseWidth: 1, + noseTip: 1, earSize: 1, earProtrusion: 1, earAngle: 0 + }), + hairDetails: Object.freeze({ + volume: 1, density: 1, fringe: 0.25, part: 'center', + curl: 0.5, sideburn: 0.5, length: 1 + }), + clothing: Object.freeze({ + fit: 'regular', sleeveLength: 1, robeLength: 1, collarHeight: 1, + embroidery: 0.65, trimColor: '#c7a45e', belt: false, layer: 'single' + }) +}); + export const DEFAULT_AVATAR_CONFIG = Object.freeze({ schemaVersion: AVATAR_CONFIG_VERSION, skin: '#b97850', @@ -23,42 +42,65 @@ export const DEFAULT_AVATAR_CONFIG = Object.freeze({ headwear: 'none', expression: 'smile', eyes: '#38251e', - accessory: 'none' + accessory: 'none', + ...DESIGN_DEFAULTS }); const HEX_COLOR = /^#[0-9a-fA-F]{6}$/; +const ENUMS = { + 'face.shape': ['oval', 'round', 'square', 'heart', 'long'], + 'hairDetails.part': ['center', 'left', 'right', 'none'], + 'clothing.fit': ['slim', 'regular', 'loose', 'oversized'], + 'clothing.layer': ['single', 'inner-outer', 'ceremonial'] +}; +const RANGES = { + 'body.height':[0.8,1.2], 'body.shoulderWidth':[0.7,1.35], 'body.torsoLength':[0.8,1.2], + 'body.bodyDepth':[0.75,1.3], 'body.waistWidth':[0.7,1.35], 'body.hipWidth':[0.7,1.4], + 'body.armLength':[0.8,1.2], 'body.legLength':[0.8,1.2], 'body.headScale':[0.8,1.2], + 'body.neckLength':[0.7,1.3], 'face.width':[0.75,1.25], 'face.height':[0.8,1.2], + 'face.cheekboneWidth':[0.75,1.3], 'face.jawWidth':[0.7,1.3], 'face.chinWidth':[0.65,1.35], + 'face.noseBridgeHeight':[0.65,1.35], 'face.noseLength':[0.7,1.3], 'face.noseWidth':[0.65,1.35], + 'face.noseTip':[0.7,1.3], 'face.earSize':[0.7,1.3], 'face.earProtrusion':[0.5,1.5], + 'face.earAngle':[-25,25], 'hairDetails.volume':[0.5,1.6], 'hairDetails.density':[0.5,1.5], + 'hairDetails.fringe':[0,1], 'hairDetails.curl':[0,1], 'hairDetails.sideburn':[0,1], + 'hairDetails.length':[0.5,1.8], 'clothing.sleeveLength':[0.5,1.3], + 'clothing.robeLength':[0.7,1.3], 'clothing.collarHeight':[0.5,1.5], + 'clothing.embroidery':[0,1] +}; -/** - * Validates a serialized avatar look. Returns a normalized copy or throws - * a descriptive TypeError. Unknown keys are rejected to keep the contract - * explicit and safe to persist. - */ -export function validateAvatarConfig(input) { - if (!input || typeof input !== 'object' || Array.isArray(input)) { - throw new TypeError('Avatar config must be an object.'); - } +function mergeDesign(source = {}) { + if (!source || typeof source !== 'object' || Array.isArray(source)) throw new TypeError('Design section must be an object.'); + return Object.fromEntries(Object.entries(DESIGN_DEFAULTS).map(([section, defaults]) => { + const supplied = Object.prototype.hasOwnProperty.call(source, section) ? source[section] : {}; + if (!supplied || typeof supplied !== 'object' || Array.isArray(supplied)) throw new TypeError(`Invalid ${section} design section.`); + for (const key of Object.keys(supplied)) if (!(key in defaults)) throw new TypeError(`Unknown design property: ${section}.${key}`); + return [section, { ...defaults, ...supplied }]; + })); +} +export function validateAvatarConfig(input) { + if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('Avatar config must be an object.'); const allowedKeys = new Set(Object.keys(DEFAULT_AVATAR_CONFIG)); - for (const key of Object.keys(input)) { - if (!allowedKeys.has(key)) throw new TypeError(`Unknown avatar property: ${key}`); - } - - const value = { ...DEFAULT_AVATAR_CONFIG, ...input }; - if (value.schemaVersion !== AVATAR_CONFIG_VERSION) { - throw new TypeError('Unsupported avatar config schema version.'); + for (const key of Object.keys(input)) if (!allowedKeys.has(key)) throw new TypeError(`Unknown avatar property: ${key}`); + const version = input.schemaVersion ?? 1; + if (version !== 1 && version !== AVATAR_CONFIG_VERSION) throw new TypeError('Unsupported avatar config schema version.'); + const value = { ...DEFAULT_AVATAR_CONFIG, ...input, schemaVersion: AVATAR_CONFIG_VERSION }; + for (const key of ['skin','hair','cloth','eyes']) { + if (typeof value[key] !== 'string' || !HEX_COLOR.test(value[key])) throw new TypeError(`Invalid color value for ${key}.`); } + for (const [key, choices] of Object.entries(AVATAR_OPTIONS)) if (!choices.includes(value[key])) throw new TypeError(`Unsupported ${key} value.`); - for (const key of ['skin', 'hair', 'cloth', 'eyes']) { - if (typeof value[key] !== 'string' || !HEX_COLOR.test(value[key])) { - throw new TypeError(`Invalid color value for ${key}.`); + const design = mergeDesign(input); + for (const [section, values] of Object.entries(design)) { + for (const [key, item] of Object.entries(values)) { + const path = `${section}.${key}`; + if (ENUMS[path] && !ENUMS[path].includes(item)) throw new TypeError(`Unsupported ${path} value.`); + if (RANGES[path] && (typeof item !== 'number' || !Number.isFinite(item) || item < RANGES[path][0] || item > RANGES[path][1])) { + throw new TypeError(`Invalid ${path} value; expected ${RANGES[path].join('..')}.`); + } + if (path === 'clothing.trimColor' && (typeof item !== 'string' || !HEX_COLOR.test(item))) throw new TypeError('Invalid clothing.trimColor value.'); + if (path === 'clothing.belt' && typeof item !== 'boolean') throw new TypeError('Invalid clothing.belt value.'); } } - - for (const [key, choices] of Object.entries(AVATAR_OPTIONS)) { - if (!choices.includes(value[key])) { - throw new TypeError(`Unsupported ${key} value.`); - } - } - - return Object.freeze(value); + return Object.freeze({ ...value, ...Object.fromEntries(Object.entries(design).map(([key, section]) => [key, Object.freeze(section)])) }); } diff --git a/src/character-library.js b/src/character-library.js new file mode 100644 index 0000000..bcee0ba --- /dev/null +++ b/src/character-library.js @@ -0,0 +1,34 @@ +import catalog from '../data/characters.json' with { type: 'json' }; +import { validateAvatarConfig } from './avatar-config.js'; + +export const CHARACTER_CATALOG = Object.freeze(catalog); + +export function getCharacterPreset(id) { + return CHARACTER_CATALOG.characters.find((item) => item.id === id) ?? null; +} + +export function validateCharacterDocument(input) { + if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('Character document must be an object.'); + if (input.format !== 'arcode-persona-character') return Object.freeze({ config: validateAvatarConfig(input), profile: null }); + if (input.formatVersion !== 1 && input.formatVersion !== 2) throw new TypeError('Unsupported character document version.'); + if (typeof input.id !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(input.id)) throw new TypeError('Invalid character id.'); + if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 80) throw new TypeError('Invalid character name.'); + if (typeof input.description !== 'string' || input.description.length > 240) throw new TypeError('Invalid character description.'); + if (!Array.isArray(input.tags) || input.tags.length > 12 || input.tags.some((tag) => typeof tag !== 'string' || tag.length > 32)) throw new TypeError('Invalid character tags.'); + return Object.freeze({ + config: validateAvatarConfig(input.config), + profile: Object.freeze({ id: input.id, name: input.name.trim(), description: input.description, tags: Object.freeze([...input.tags]) }) + }); +} + +export function createCharacterDocument(config, profile = {}) { + const safe = validateCharacterDocument({ + format: 'arcode-persona-character', formatVersion: 2, + id: profile.id ?? 'custom', name: profile.name ?? 'Custom character', + description: profile.description ?? '', tags: profile.tags ?? ['custom'], + config: validateAvatarConfig(config) + }); + return Object.freeze({ format: 'arcode-persona-character', formatVersion: 2, + id: safe.profile.id, name: safe.profile.name, description: safe.profile.description, + tags: [...safe.profile.tags], config: safe.config }); +} diff --git a/styles.css b/styles.css index ed85f2e..458e182 100644 --- a/styles.css +++ b/styles.css @@ -10,3 +10,5 @@ #toggleAvatarAnimation:disabled{opacity:.5}#importGarmentAsset,#removeGarmentAsset{font-size:10px;padding:8px 9px} .morph-presets{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0 12px}.morph-presets button{border:1px solid #405149;background:#1b2b24;color:#cbd8cc;border-radius:7px;padding:6px 9px;font:10px var(--font);cursor:pointer}.morph-presets button:hover,.morph-presets button:focus-visible{border-color:var(--green);color:#f3f1e9;outline:none} + +.design-control-group{border-top:1px solid #ffffff12;padding-top:12px;margin-top:12px}.design-controls{display:grid;grid-template-columns:1fr 1fr;gap:10px 12px}.design-control{display:grid;gap:5px;min-width:0}.design-control label{font-size:10px;color:#b9c8bb}.design-control input[type=range]{width:100%;accent-color:#a7c59b}.design-control select,.design-control input[type=color]{width:100%;min-width:0}.design-control output{font:10px Manrope;color:#9eafa3;text-align:left}.design-control input[type=color]{height:32px;padding:3px;border:1px solid #34463e;border-radius:7px;background:#101a18} diff --git a/test/avatar-config.test.js b/test/avatar-config.test.js index ec112a7..6dba733 100644 --- a/test/avatar-config.test.js +++ b/test/avatar-config.test.js @@ -1,59 +1,54 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { - AVATAR_CONFIG_VERSION, - DEFAULT_AVATAR_CONFIG, - validateAvatarConfig -} from '../src/avatar-config.js'; +import { AVATAR_CONFIG_VERSION, DEFAULT_AVATAR_CONFIG, validateAvatarConfig } from '../src/avatar-config.js'; -test('default avatar configuration is valid and versioned', () => { - const config = validateAvatarConfig(DEFAULT_AVATAR_CONFIG); - assert.equal(config.schemaVersion, AVATAR_CONFIG_VERSION); - assert.equal(config.outfit, 'djellaba'); +test('default design is versioned and includes anatomy and wardrobe sections', () => { + const config=validateAvatarConfig(DEFAULT_AVATAR_CONFIG); + assert.equal(config.schemaVersion,AVATAR_CONFIG_VERSION); + assert.equal(config.body.shoulderWidth,1); + assert.equal(config.face.shape,'oval'); + assert.equal(config.clothing.fit,'regular'); }); -test('partial saved looks inherit stable defaults', () => { - const config = validateAvatarConfig({ outfit: 'caftan', cloth: '#8a3344' }); - assert.equal(config.outfit, 'caftan'); - assert.equal(config.hairStyle, DEFAULT_AVATAR_CONFIG.hairStyle); +test('migrates legacy version 1 looks into version 2 without losing appearance',()=>{ + const config=validateAvatarConfig({schemaVersion:1,outfit:'caftan',skin:'#8a3344'}); + assert.equal(config.schemaVersion,2); + assert.equal(config.outfit,'caftan'); + assert.equal(config.body.height,1); }); -test('rejects unsupported schema versions', () => { - assert.throws(() => validateAvatarConfig({ schemaVersion: 99 }), /schema version/); +test('normalizes partial nested design sections',()=>{ + const config=validateAvatarConfig({face:{shape:'square',noseWidth:1.2},clothing:{belt:true}}); + assert.equal(config.face.shape,'square'); + assert.equal(config.face.noseWidth,1.2); + assert.equal(config.face.jawWidth,1); + assert.equal(config.clothing.belt,true); }); -test('rejects invalid colors', () => { - assert.throws(() => validateAvatarConfig({ skin: 'red' }), /Invalid color/); +test('rejects unsupported schema versions and unknown properties',()=>{ + assert.throws(()=>validateAvatarConfig({schemaVersion:99}),/schema version/); + assert.throws(()=>validateAvatarConfig({admin:true}),/Unknown avatar property/); + assert.throws(()=>validateAvatarConfig({face:{thirdEye:true}}),/Unknown design property/); + assert.throws(()=>validateAvatarConfig({face:null}),/Invalid face design section/); }); -test('rejects unknown properties rather than silently persisting them', () => { - assert.throws(() => validateAvatarConfig({ admin: true }), /Unknown avatar property/); +test('validates numeric ranges and enumerated face/hair/clothing values',()=>{ + assert.throws(()=>validateAvatarConfig({body:{height:4}}),/body.height/); + assert.throws(()=>validateAvatarConfig({face:{shape:'triangle'}}),/face.shape/); + assert.throws(()=>validateAvatarConfig({hairDetails:{part:'diagonal'}}),/hairDetails.part/); + assert.throws(()=>validateAvatarConfig({clothing:{trimColor:'gold'}}),/trimColor/); }); -test('rejects unsupported wardrobe values', () => { - assert.throws(() => validateAvatarConfig({ outfit: 'unreviewed-costume' }), /Unsupported outfit/); +test('rejects malformed colors, arrays and null',()=>{ + assert.throws(()=>validateAvatarConfig({skin:'red'}),/Invalid color/); + assert.throws(()=>validateAvatarConfig(null),/must be an object/); + assert.throws(()=>validateAvatarConfig([]),/must be an object/); }); -test('rejects arrays and null', () => { - assert.throws(() => validateAvatarConfig(null), /must be an object/); - assert.throws(() => validateAvatarConfig([]), /must be an object/); +test('does not mutate caller input and freezes normalized sections',()=>{ + const input={face:{jawWidth:1.1}}; + const config=validateAvatarConfig(input); + assert.equal(input.face.shape,undefined); + assert.equal(config.face.jawWidth,1.1); + assert.ok(Object.isFrozen(config.face)); }); - - -test('normalizes partial values without mutating the input', () => { - const input = { outfit: 'caftan' }; - const config = validateAvatarConfig(input); - assert.equal(config.outfit, 'caftan'); - assert.equal(input.hairStyle, undefined); - assert.equal(config.hairStyle, DEFAULT_AVATAR_CONFIG.hairStyle); -}); - -test('rejects malformed color strings and invalid option types', () => { - assert.throws(() => validateAvatarConfig({ hair: '#fff' }), /Invalid color/); - assert.throws(() => validateAvatarConfig({ hairStyle: null }), /Unsupported hairStyle/); -}); - -test('rejects unsupported extra configuration fields', () => { - assert.throws(() => validateAvatarConfig({ avatarUrl: 'https://example.com/a.glb' }), /Unknown avatar property/); -}); - diff --git a/test/character-library.test.js b/test/character-library.test.js new file mode 100644 index 0000000..51d9a7a --- /dev/null +++ b/test/character-library.test.js @@ -0,0 +1,42 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { CHARACTER_CATALOG, getCharacterPreset, validateCharacterDocument, createCharacterDocument } from '../src/character-library.js'; + +test('JSON character catalog contains unique valid profiles', () => { + const ids = CHARACTER_CATALOG.characters.map((item) => item.id); + assert.equal(new Set(ids).size, ids.length); + for (const item of CHARACTER_CATALOG.characters) assert.ok(validateCharacterDocument({ format:'arcode-persona-character', formatVersion:2, ...item }).config); +}); + +test('loads a known character preset by id', () => { + assert.equal(getCharacterPreset('royal-caftan').config.outfit, 'caftan'); + assert.equal(getCharacterPreset('missing'), null); +}); + +test('exports and imports a versioned character document', () => { + const preset = getCharacterPreset('atlas-scholar'); + const exported = createCharacterDocument(preset.config, preset); + const restored = validateCharacterDocument(JSON.parse(JSON.stringify(exported))); + assert.equal(restored.profile.id, 'atlas-scholar'); + assert.equal(restored.config.outfit, 'djellaba'); + assert.equal(restored.config.schemaVersion, 2); + assert.equal(restored.config.face.shape, 'oval'); +}); + +test('keeps backwards compatibility with legacy character document v1', () => { + const preset = getCharacterPreset('atlas-scholar'); + const legacy = validateCharacterDocument({ format:'arcode-persona-character', formatVersion:1, ...preset }); + assert.equal(legacy.config.schemaVersion, 2); + assert.equal(legacy.profile.id, 'atlas-scholar'); +}); + +test('keeps backwards compatibility with legacy look JSON', () => { + const restored = validateCharacterDocument({ outfit: 'caftan' }); + assert.equal(restored.profile, null); + assert.equal(restored.config.outfit, 'caftan'); +}); + +test('rejects invalid character metadata and unsupported versions', () => { + assert.throws(() => validateCharacterDocument({ format:'arcode-persona-character', formatVersion:9, id:'x', name:'X', description:'', tags:[], config:{} }), /version/); + assert.throws(() => validateCharacterDocument({ format:'arcode-persona-character', formatVersion:1, id:'bad id', name:'X', description:'', tags:[], config:{} }), /id/); +});