Spaces:
Running

mg696 commited on
Commit
dd4d1bf
·
verified ·
1 Parent(s): 29875a0

v49: floor renderOrder=-1, stage/dome renderOrder=0, char renderOrder=10+ to fix floor/curtain transparency"

Browse files
Files changed (1) hide show
  1. app.js +7 -4
app.js CHANGED
@@ -1,6 +1,6 @@
1
  import*as THREE from'three';import{MMDLoader}from'three/examples/jsm/loaders/MMDLoader';import{TGALoader}from'three/examples/jsm/loaders/TGALoader';import{MMDAnimationHelper}from'three/examples/jsm/animation/MMDAnimationHelper';import{OrbitControls}from'three/examples/jsm/controls/OrbitControls';
2
  const debugLogEl=document.getElementById('debug-log'),debugPanel=document.getElementById('debug-panel'),debugToggle=document.getElementById('debug-toggle');let debugVisible=false;debugToggle.addEventListener('click',e=>{e.preventDefault();e.stopPropagation();debugVisible=!debugVisible;if(debugVisible){debugPanel.removeAttribute('hidden');debugPanel.classList.add('visible')}else{debugPanel.classList.remove('visible');debugPanel.setAttribute('hidden','')}});debugToggle.addEventListener('touchend',e=>{e.preventDefault();debugToggle.click()});document.getElementById('debug-clear-btn').addEventListener('click',()=>{debugLogEl.innerHTML=''});document.getElementById('debug-copy-btn').addEventListener('click',()=>{const btn=document.getElementById('debug-copy-btn');navigator.clipboard.writeText(debugLogEl.innerText).then(()=>{btn.textContent='✅ Copied!';setTimeout(()=>btn.textContent='📋 Copy All',1500)}).catch(()=>{const ta=document.createElement('textarea');ta.value=debugLogEl.innerText;document.body.appendChild(ta);ta.select();document.execCommand('copy');document.body.removeChild(ta);btn.textContent='✅ Copied!';setTimeout(()=>btn.textContent='📋 Copy All',1500)})});
3
- const APP_VER='v48';let _dbgH=false;function _t(){const d=new Date();return`${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`}function _ds(){const d=new Date();return`${d.getFullYear()}/${String(d.getMonth()+1).padStart(2,'0')}/${String(d.getDate()).padStart(2,'0')}`}
4
  function dbg(msg,level='log'){if(!_dbgH){_dbgH=true;const h=document.createElement('div');h.className='info';h.textContent=`[MMD_pmx_Player_${APP_VER}_${_ds()}]`;debugLogEl.appendChild(h)}const cls=level==='warn'?'warn':level==='error'?'error':level==='info'?'info':'';const line=document.createElement('div');if(cls)line.className=cls;line.textContent=`[${_t()}] ${msg}`;debugLogEl.appendChild(line);debugLogEl.scrollTop=debugLogEl.scrollHeight;if(level==='error')console.error(msg);else if(level==='warn')console.warn(msg);else console.log(msg)}
5
  const FALLBACK_PIXEL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";function generateToonDataURL(tR,tG,tB,bR,bG,bB){const c=document.createElement('canvas');c.width=1;c.height=256;const x=c.getContext('2d');const g=x.createLinearGradient(0,0,0,256);g.addColorStop(0,`rgb(${tR},${tG},${tB})`);g.addColorStop(1,`rgb(${bR},${bG},${bB})`);x.fillStyle=g;x.fillRect(0,0,1,256);return c.toDataURL('image/png')}const BUILTIN_TOONS={};const TOON_DEFS=[[255,255,255,180,180,180],[255,220,220,160,120,120],[255,240,210,160,140,100],[255,255,230,160,160,110],[220,255,220,110,160,110],[220,255,255,110,160,160],[210,220,255,100,110,160],[255,220,255,160,110,160],[245,245,245,150,150,150],[230,230,230,100,100,100]];for(let i=0;i<10;i++){const n=String(i+1).padStart(2,'0');const d=TOON_DEFS[i];BUILTIN_TOONS[`toon${n}.bmp`]=generateToonDataURL(d[0],d[1],d[2],d[3],d[4],d[5])}
6
  if(window.CharsetEncoder){window.CharsetEncoder.install();const orig=window.CharsetEncoder.decode;window.CharsetEncoder.decode=function(data,enc){try{return orig(data,enc||'shift_jis')}catch(e){try{return new TextDecoder('shift_jis').decode(data)}catch(e2){return new TextDecoder('utf-8').decode(data)}}}}
@@ -8,15 +8,18 @@ let scene,camera,renderer,controls,clock,mesh,mesh2,helper,stageMeshes=[],domeMe
8
  function normalizePath(path){let p=path.replace(/\\/g,'/').normalize('NFC');try{p=decodeURIComponent(p)}catch(e){}return p.replace(/^\.\//,'').replace(/%20/g,' ').toLowerCase()}
9
  function saveInitialBonePose(m){if(!m||!m.skeleton)return;m.userData._ib=m.skeleton.bones.map(b=>({n:b.name,p:b.position.clone(),q:b.quaternion.clone(),s:b.scale.clone()}));dbg(`[BoneSave] ${m.skeleton.bones.length}ボーン保存`,"info")}
10
  function restoreInitialBonePose(m){if(!m||!m.userData._ib)return;const saved=m.userData._ib;const bm={};m.skeleton.bones.forEach(b=>{bm[b.name]=b});for(const d of saved){const bone=bm[d.n];if(!bone)continue;bone.position.copy(d.p);bone.quaternion.copy(d.q);bone.scale.copy(d.s)}m.skeleton.bones.forEach(b=>b.updateMatrix());m.skeleton.update();m.updateMatrixWorld(true);dbg(`[BoneRestore] ${saved.length}ボーン復元`,"info")}
11
- async function init(){try{if(typeof Ammo==='function')await Ammo().then(()=>{ammoInitialized=true;dbg("Ammo.js初期化完了","info")})}catch(e){dbg("Ammo.js失敗:"+e.message,"error")}scene=new THREE.Scene();scene.background=new THREE.Color(0x220022);clock=new THREE.Clock();camera=new THREE.PerspectiveCamera(45,innerWidth/innerHeight,1,20000);camera.position.set(0,20,100);renderer=new THREE.WebGLRenderer({antialias:true,alpha:true,preserveDrawingBuffer:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setSize(innerWidth,innerHeight);renderer.outputColorSpace=THREE.SRGBColorSpace;document.getElementById('container').appendChild(renderer.domElement);controls=new OrbitControls(camera,renderer.domElement);controls.target.set(0,10,0);controls.enableDamping=true;controls.dampingFactor=0.1;gridHelper=new THREE.GridHelper(200,20,0xff1493,0x444444);scene.add(gridHelper);const fg=new THREE.PlaneGeometry(200,200);const fm=new THREE.MeshPhongMaterial({color:0x888888,transparent:true,opacity:0.5,side:THREE.DoubleSide});floorMesh=new THREE.Mesh(fg,fm);floorMesh.rotation.x=-Math.PI/2;floorMesh.receiveShadow=true;floorMesh.visible=false;scene.add(floorMesh);ambLight=new THREE.AmbientLight(0xffffff,0.8);scene.add(ambLight);mainLight=new THREE.DirectionalLight(0xffffff,1.2);mainLight.position.set(5,20,10);mainLight.castShadow=true;mainLight.shadow.mapSize.set(2048,2048);mainLight.shadow.camera.near=0.5;mainLight.shadow.camera.far=200;mainLight.shadow.camera.left=-50;mainLight.shadow.camera.right=50;mainLight.shadow.camera.top=50;mainLight.shadow.camera.bottom=-50;scene.add(mainLight);subLight=new THREE.DirectionalLight(0xffffff,0.4);subLight.position.set(-5,10,-5);scene.add(subLight);
 
 
 
12
  ['mesh','mesh2','stage','dome'].forEach(type=>{const mgr=new THREE.LoadingManager();mgr.addHandler(/\.tga$/i,new TGALoader(mgr));mgr.setURLModifier(url=>{let c=url.split(/[?#]/)[0];if(c.startsWith('blob:')||c.startsWith('data:'))return c;const n=normalizePath(c);let sp=n;if(sp.includes('virtual_path/'))sp=sp.split('virtual_path/').pop();const fn=sp.split('/').pop();const f=modelData[type].fileMap;if(BUILTIN_TOONS[fn]&&!f[fn])return BUILTIN_TOONS[fn];if(f[sp])return f[sp];if(f[fn])return f[fn];for(const k in f)if(k.endsWith('/'+fn)||k===fn)return f[k];const bn=fn.replace(/\.[^.]+$/,'');for(const ext of['.png','.jpg','.jpeg','.tga','.bmp','.gif']){const an=bn+ext;if(f[an])return f[an];for(const k in f)if(k.endsWith('/'+an))return f[k]}if(bn.length>=3)for(const k in f){if(k.split('/').pop().replace(/\.[^.]+$/,'')===bn)return f[k]}if(/\.(png|jpg|jpeg|tga|bmp|gif|dds|spa|sph)$/i.test(fn))return FALLBACK_PIXEL;return url});mgr.onError=url=>dbg(`[Load]エラー:${url}`,"error");modelData[type].loader=new MMDLoader(mgr);modelData[type].manager=mgr});
13
  helper=new MMDAnimationHelper({afterglow:2.0,resetPhysicsOnLoop:true});setupEventListeners();animate();dbg("初期化完了","info");dbg(`[Device]${navigator.userAgent.slice(0,80)}`,"info");dbg(`[Screen]${screen.width}x${screen.height} win=${innerWidth}x${innerHeight} dpr=${devicePixelRatio}`,"info");
14
  window.__mainLight=mainLight;window.__subLight=subLight;window.__ambLight=ambLight;window.__appReady=true;window.__processFiles=processFiles;window.__findFileInMap=findFileInMap;window.__loadPmx=loadPmx;window.__showLoading=showLoading;window.__updateStatus=updateStatus;window.__dbg=dbg;
15
  }
16
  async function processFiles(files,t){for(let i=0;i<files.length;i++){const file=files[i];const name=file.name.toLowerCase().normalize('NFC');if(name.endsWith('.zip'))await processZip(file,t);else{const url=URL.createObjectURL(file);const n=normalizePath(file.name);const fn=n.split('/').pop();modelData[t].fileMap[n]=url;modelData[t].fileMap[fn]=url}}}
17
  async function processZip(zipFile,t){try{const zip=await JSZip.loadAsync(zipFile,{decodeFileName:b=>{try{return new TextDecoder("utf-8",{fatal:true}).decode(b).normalize('NFC')}catch(e){try{return new TextDecoder("shift_jis").decode(b).normalize('NFC')}catch(e2){return new TextDecoder("utf-8",{fatal:false}).decode(b).normalize('NFC')}}}});const entries=Object.keys(zip.files).filter(k=>!zip.files[k].dir);let pmxDir='';for(const p of entries)if(/\.(pmx|pmd)$/i.test(p)){const n=p.replace(/\\/g,'/').normalize('NFC');const pts=n.split('/');pts.pop();pmxDir=pts.length?pts.join('/')+'/':'';break}const f=modelData[t].fileMap;let count=0;for(const rp of entries){const u8=await zip.files[rp].async("uint8array");const ext=rp.split('.').pop().toLowerCase();const mm={'png':'image/png','jpg':'image/jpeg','jpeg':'image/jpeg','gif':'image/gif','bmp':'image/bmp','tga':'image/x-tga'};const blob=new Blob([u8],{type:mm[ext]||'application/octet-stream'});const url=URL.createObjectURL(blob);const nf=normalizePath(rp);const fn=nf.split('/').pop();f[nf]=url;f[fn]=url;if(pmxDir){const pd=pmxDir.toLowerCase().normalize('NFC');if(nf.startsWith(pd)){const rel=nf.substring(pd.length);if(rel&&rel!==fn)f[rel]=url}}count++}dbg(`[ZIP]${zipFile.name}:${count}ファイル(PMXdir:${pmxDir||'root'})`,"info")}catch(e){dbg(`[ZIP]展開失敗:${e.message}`,"error")}}
18
- // ★v48: fixMMDMaterials - 全キャラマテリアルdepthWrite:true統一 + cloth alphaTest:0.15
19
- function fixMMDMaterials(target,loadType){let mc=0,fc=0;target.traverse(child=>{if(!child.isMesh)return;child.frustumCulled=false;const mats=Array.isArray(child.material)?child.material:[child.material];mats.forEach((m)=>{mc++;const ml=(m.name||'').toLowerCase();const ha=m.map&&m.map.format===THREE.RGBAFormat&&!/\.(jpg|jpeg)$/i.test(m.map?.name||'');const it=m.opacity<1;if(loadType==='stage'||loadType==='dome'){m.side=THREE.DoubleSide;m.needsUpdate=true;return}if(/eyehighlight|highlight/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++}else if(/eyelash/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.1;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++}else if((/eyeline/i.test(ml)||/brow/i.test(ml))&&ha){m.transparent=true;m.alphaTest=0.1;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++}else if(/_HAIR(?:_\d+)?$/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.05;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++}else if(/_CLOTH(?:_\d+)?$/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.15;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++}else if(it){m.transparent=true;m.alphaTest=0;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++}m.needsUpdate=true})});target.traverse(child=>{if(!child.isMesh)return;const mats=Array.isArray(child.material)?child.material:[child.material];const isEnv=(loadType==='stage'||loadType==='dome');const mx=mats.reduce((max,m)=>{if(m.transparent)return Math.max(max,1);return max},0);child.renderOrder=isEnv?0:(10+mx)});dbg(`[Material]${mc}個処理,${fc}個修正(${loadType})`,"info")}
20
  function setupEventListeners(){document.getElementById('file-input').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"キャラ1展開中...");await processFiles(e.target.files,'mesh');let pmx=findFileInMap('.pmx','mesh')||findFileInMap('.pmd','mesh');if(pmx){document.getElementById('pmx-label').classList.add('ready');loadPmx(pmx,'mesh')}else{showLoading(false);updateStatus("PMXが見つかりません♡")}});document.getElementById('file-input2').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"キャラ2展開中...");await processFiles(e.target.files,'mesh2');let pmx=findFileInMap('.pmx','mesh2')||findFileInMap('.pmd','mesh2');if(pmx){document.getElementById('pmx2-label').classList.add('ready');loadPmx(pmx,'mesh2')}else{showLoading(false);updateStatus("PMXが見つかりません♡")}});document.getElementById('stage-input').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"ステージ展開中...");await processFiles(e.target.files,'stage');let pmx=findFileInMap('.pmx','stage')||findFileInMap('.pmd','stage');if(pmx){document.getElementById('stage-label').classList.add('ready');loadPmx(pmx,'stage')}else{showLoading(false);updateStatus("ステージPMXがありません♡")}});
21
  document.getElementById('cam-vmd-input').addEventListener('change',async e=>{const file=e.target.files[0];if(!file)return;showLoading(true,"カメラVMD読込中...");const url=URL.createObjectURL(file);modelData.mesh.loader.loadAnimation(url,camera,clip=>{try{if(helper.camera)helper.remove(camera);helper.add(camera,{animation:clip});cameraVmdEnabled=true;helper.enabled.cameraAnimation=true;controls.enabled=false;maxDuration=Math.max(maxDuration,clip.duration);updateSeekBarLimit();document.getElementById('cam-vmd-label').classList.add('ready');document.getElementById('cam-vmd-toggle').style.display='inline-block';document.querySelectorAll('.aspect-btn').forEach(b=>b.style.display='inline-block');dbg(`[CamVMD]${file.name}(${clip.duration.toFixed(1)}s)`,"info")}catch(err){dbg(`[CamVMD]失敗:${err.message}`,"error")}showLoading(false)},null,()=>{dbg("[CamVMD]読込失敗","error");showLoading(false)})});
22
  document.getElementById('cam-vmd-toggle').addEventListener('click',()=>{cameraVmdEnabled=!cameraVmdEnabled;helper.enabled.cameraAnimation=cameraVmdEnabled;controls.enabled=!cameraVmdEnabled;const btn=document.getElementById('cam-vmd-toggle');btn.textContent=cameraVmdEnabled?'カメラVMD: ON':'カメラVMD: OFF';btn.style.color=cameraVmdEnabled?'#ff8c00':'#666';btn.style.borderColor=cameraVmdEnabled?'#ff8c00':'#666'});
 
1
  import*as THREE from'three';import{MMDLoader}from'three/examples/jsm/loaders/MMDLoader';import{TGALoader}from'three/examples/jsm/loaders/TGALoader';import{MMDAnimationHelper}from'three/examples/jsm/animation/MMDAnimationHelper';import{OrbitControls}from'three/examples/jsm/controls/OrbitControls';
2
  const debugLogEl=document.getElementById('debug-log'),debugPanel=document.getElementById('debug-panel'),debugToggle=document.getElementById('debug-toggle');let debugVisible=false;debugToggle.addEventListener('click',e=>{e.preventDefault();e.stopPropagation();debugVisible=!debugVisible;if(debugVisible){debugPanel.removeAttribute('hidden');debugPanel.classList.add('visible')}else{debugPanel.classList.remove('visible');debugPanel.setAttribute('hidden','')}});debugToggle.addEventListener('touchend',e=>{e.preventDefault();debugToggle.click()});document.getElementById('debug-clear-btn').addEventListener('click',()=>{debugLogEl.innerHTML=''});document.getElementById('debug-copy-btn').addEventListener('click',()=>{const btn=document.getElementById('debug-copy-btn');navigator.clipboard.writeText(debugLogEl.innerText).then(()=>{btn.textContent='✅ Copied!';setTimeout(()=>btn.textContent='📋 Copy All',1500)}).catch(()=>{const ta=document.createElement('textarea');ta.value=debugLogEl.innerText;document.body.appendChild(ta);ta.select();document.execCommand('copy');document.body.removeChild(ta);btn.textContent='✅ Copied!';setTimeout(()=>btn.textContent='📋 Copy All',1500)})});
3
+ const APP_VER='v49';let _dbgH=false;function _t(){const d=new Date();return`${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`}function _ds(){const d=new Date();return`${d.getFullYear()}/${String(d.getMonth()+1).padStart(2,'0')}/${String(d.getDate()).padStart(2,'0')}`}
4
  function dbg(msg,level='log'){if(!_dbgH){_dbgH=true;const h=document.createElement('div');h.className='info';h.textContent=`[MMD_pmx_Player_${APP_VER}_${_ds()}]`;debugLogEl.appendChild(h)}const cls=level==='warn'?'warn':level==='error'?'error':level==='info'?'info':'';const line=document.createElement('div');if(cls)line.className=cls;line.textContent=`[${_t()}] ${msg}`;debugLogEl.appendChild(line);debugLogEl.scrollTop=debugLogEl.scrollHeight;if(level==='error')console.error(msg);else if(level==='warn')console.warn(msg);else console.log(msg)}
5
  const FALLBACK_PIXEL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";function generateToonDataURL(tR,tG,tB,bR,bG,bB){const c=document.createElement('canvas');c.width=1;c.height=256;const x=c.getContext('2d');const g=x.createLinearGradient(0,0,0,256);g.addColorStop(0,`rgb(${tR},${tG},${tB})`);g.addColorStop(1,`rgb(${bR},${bG},${bB})`);x.fillStyle=g;x.fillRect(0,0,1,256);return c.toDataURL('image/png')}const BUILTIN_TOONS={};const TOON_DEFS=[[255,255,255,180,180,180],[255,220,220,160,120,120],[255,240,210,160,140,100],[255,255,230,160,160,110],[220,255,220,110,160,110],[220,255,255,110,160,160],[210,220,255,100,110,160],[255,220,255,160,110,160],[245,245,245,150,150,150],[230,230,230,100,100,100]];for(let i=0;i<10;i++){const n=String(i+1).padStart(2,'0');const d=TOON_DEFS[i];BUILTIN_TOONS[`toon${n}.bmp`]=generateToonDataURL(d[0],d[1],d[2],d[3],d[4],d[5])}
6
  if(window.CharsetEncoder){window.CharsetEncoder.install();const orig=window.CharsetEncoder.decode;window.CharsetEncoder.decode=function(data,enc){try{return orig(data,enc||'shift_jis')}catch(e){try{return new TextDecoder('shift_jis').decode(data)}catch(e2){return new TextDecoder('utf-8').decode(data)}}}}
 
8
  function normalizePath(path){let p=path.replace(/\\/g,'/').normalize('NFC');try{p=decodeURIComponent(p)}catch(e){}return p.replace(/^\.\//,'').replace(/%20/g,' ').toLowerCase()}
9
  function saveInitialBonePose(m){if(!m||!m.skeleton)return;m.userData._ib=m.skeleton.bones.map(b=>({n:b.name,p:b.position.clone(),q:b.quaternion.clone(),s:b.scale.clone()}));dbg(`[BoneSave] ${m.skeleton.bones.length}ボーン保存`,"info")}
10
  function restoreInitialBonePose(m){if(!m||!m.userData._ib)return;const saved=m.userData._ib;const bm={};m.skeleton.bones.forEach(b=>{bm[b.name]=b});for(const d of saved){const bone=bm[d.n];if(!bone)continue;bone.position.copy(d.p);bone.quaternion.copy(d.q);bone.scale.copy(d.s)}m.skeleton.bones.forEach(b=>b.updateMatrix());m.skeleton.update();m.updateMatrixWorld(true);dbg(`[BoneRestore] ${saved.length}ボーン復元`,"info")}
11
+ async function init(){try{if(typeof Ammo==='function')await Ammo().then(()=>{ammoInitialized=true;dbg("Ammo.js初期化完了","info")})}catch(e){dbg("Ammo.js失敗:"+e.message,"error")}scene=new THREE.Scene();scene.background=new THREE.Color(0x220022);clock=new THREE.Clock();camera=new THREE.PerspectiveCamera(45,innerWidth/innerHeight,1,20000);camera.position.set(0,20,100);renderer=new THREE.WebGLRenderer({antialias:true,alpha:true,preserveDrawingBuffer:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setSize(innerWidth,innerHeight);renderer.outputColorSpace=THREE.SRGBColorSpace;document.getElementById('container').appendChild(renderer.domElement);controls=new OrbitControls(camera,renderer.domElement);controls.target.set(0,10,0);controls.enableDamping=true;controls.dampingFactor=0.1;gridHelper=new THREE.GridHelper(200,20,0xff1493,0x444444);scene.add(gridHelper);
12
+ // ★v49: 床をdepthWrite:false + renderOrder:-1にして、キャラより先に描画&デプスバッファに書き込まない
13
+ const fg=new THREE.PlaneGeometry(200,200);const fm=new THREE.MeshPhongMaterial({color:0x888888,transparent:true,opacity:0.5,side:THREE.DoubleSide,depthWrite:false});floorMesh=new THREE.Mesh(fg,fm);floorMesh.rotation.x=-Math.PI/2;floorMesh.receiveShadow=true;floorMesh.visible=false;floorMesh.renderOrder=-1;scene.add(floorMesh);
14
+ ambLight=new THREE.AmbientLight(0xffffff,0.8);scene.add(ambLight);mainLight=new THREE.DirectionalLight(0xffffff,1.2);mainLight.position.set(5,20,10);mainLight.castShadow=true;mainLight.shadow.mapSize.set(2048,2048);mainLight.shadow.camera.near=0.5;mainLight.shadow.camera.far=200;mainLight.shadow.camera.left=-50;mainLight.shadow.camera.right=50;mainLight.shadow.camera.top=50;mainLight.shadow.camera.bottom=-50;scene.add(mainLight);subLight=new THREE.DirectionalLight(0xffffff,0.4);subLight.position.set(-5,10,-5);scene.add(subLight);
15
  ['mesh','mesh2','stage','dome'].forEach(type=>{const mgr=new THREE.LoadingManager();mgr.addHandler(/\.tga$/i,new TGALoader(mgr));mgr.setURLModifier(url=>{let c=url.split(/[?#]/)[0];if(c.startsWith('blob:')||c.startsWith('data:'))return c;const n=normalizePath(c);let sp=n;if(sp.includes('virtual_path/'))sp=sp.split('virtual_path/').pop();const fn=sp.split('/').pop();const f=modelData[type].fileMap;if(BUILTIN_TOONS[fn]&&!f[fn])return BUILTIN_TOONS[fn];if(f[sp])return f[sp];if(f[fn])return f[fn];for(const k in f)if(k.endsWith('/'+fn)||k===fn)return f[k];const bn=fn.replace(/\.[^.]+$/,'');for(const ext of['.png','.jpg','.jpeg','.tga','.bmp','.gif']){const an=bn+ext;if(f[an])return f[an];for(const k in f)if(k.endsWith('/'+an))return f[k]}if(bn.length>=3)for(const k in f){if(k.split('/').pop().replace(/\.[^.]+$/,'')===bn)return f[k]}if(/\.(png|jpg|jpeg|tga|bmp|gif|dds|spa|sph)$/i.test(fn))return FALLBACK_PIXEL;return url});mgr.onError=url=>dbg(`[Load]エラー:${url}`,"error");modelData[type].loader=new MMDLoader(mgr);modelData[type].manager=mgr});
16
  helper=new MMDAnimationHelper({afterglow:2.0,resetPhysicsOnLoop:true});setupEventListeners();animate();dbg("初期化完了","info");dbg(`[Device]${navigator.userAgent.slice(0,80)}`,"info");dbg(`[Screen]${screen.width}x${screen.height} win=${innerWidth}x${innerHeight} dpr=${devicePixelRatio}`,"info");
17
  window.__mainLight=mainLight;window.__subLight=subLight;window.__ambLight=ambLight;window.__appReady=true;window.__processFiles=processFiles;window.__findFileInMap=findFileInMap;window.__loadPmx=loadPmx;window.__showLoading=showLoading;window.__updateStatus=updateStatus;window.__dbg=dbg;
18
  }
19
  async function processFiles(files,t){for(let i=0;i<files.length;i++){const file=files[i];const name=file.name.toLowerCase().normalize('NFC');if(name.endsWith('.zip'))await processZip(file,t);else{const url=URL.createObjectURL(file);const n=normalizePath(file.name);const fn=n.split('/').pop();modelData[t].fileMap[n]=url;modelData[t].fileMap[fn]=url}}}
20
  async function processZip(zipFile,t){try{const zip=await JSZip.loadAsync(zipFile,{decodeFileName:b=>{try{return new TextDecoder("utf-8",{fatal:true}).decode(b).normalize('NFC')}catch(e){try{return new TextDecoder("shift_jis").decode(b).normalize('NFC')}catch(e2){return new TextDecoder("utf-8",{fatal:false}).decode(b).normalize('NFC')}}}});const entries=Object.keys(zip.files).filter(k=>!zip.files[k].dir);let pmxDir='';for(const p of entries)if(/\.(pmx|pmd)$/i.test(p)){const n=p.replace(/\\/g,'/').normalize('NFC');const pts=n.split('/');pts.pop();pmxDir=pts.length?pts.join('/')+'/':'';break}const f=modelData[t].fileMap;let count=0;for(const rp of entries){const u8=await zip.files[rp].async("uint8array");const ext=rp.split('.').pop().toLowerCase();const mm={'png':'image/png','jpg':'image/jpeg','jpeg':'image/jpeg','gif':'image/gif','bmp':'image/bmp','tga':'image/x-tga'};const blob=new Blob([u8],{type:mm[ext]||'application/octet-stream'});const url=URL.createObjectURL(blob);const nf=normalizePath(rp);const fn=nf.split('/').pop();f[nf]=url;f[fn]=url;if(pmxDir){const pd=pmxDir.toLowerCase().normalize('NFC');if(nf.startsWith(pd)){const rel=nf.substring(pd.length);if(rel&&rel!==fn)f[rel]=url}}count++}dbg(`[ZIP]${zipFile.name}:${count}ファイル(PMXdir:${pmxDir||'root'})`,"info")}catch(e){dbg(`[ZIP]展開失敗:${e.message}`,"error")}}
21
+ // ★v49: fixMMDMaterials - キャラ全depthWrite:true + ステージ/ドームrenderOrder=5(キャラ=10+より低い)
22
+ function fixMMDMaterials(target,loadType){let mc=0,fc=0;target.traverse(child=>{if(!child.isMesh)return;child.frustumCulled=false;const mats=Array.isArray(child.material)?child.material:[child.material];mats.forEach((m)=>{mc++;const ml=(m.name||'').toLowerCase();const ha=m.map&&m.map.format===THREE.RGBAFormat&&!/\.(jpg|jpeg)$/i.test(m.map?.name||'');const it=m.opacity<1;if(loadType==='stage'||loadType==='dome'){m.side=THREE.DoubleSide;m.needsUpdate=true;return}if(/eyehighlight|highlight/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++}else if(/eyelash/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.1;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++}else if((/eyeline/i.test(ml)||/brow/i.test(ml))&&ha){m.transparent=true;m.alphaTest=0.1;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++}else if(/_HAIR(?:_\d+)?$/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.05;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++}else if(/_CLOTH(?:_\d+)?$/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.15;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++}else if(it){m.transparent=true;m.alphaTest=0;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++}m.needsUpdate=true})});target.traverse(child=>{if(!child.isMesh)return;const isEnv=(loadType==='stage'||loadType==='dome');child.renderOrder=isEnv?5:10});dbg(`[Material]${mc}個処理,${fc}個修正(${loadType})`,"info")}
23
  function setupEventListeners(){document.getElementById('file-input').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"キャラ1展開中...");await processFiles(e.target.files,'mesh');let pmx=findFileInMap('.pmx','mesh')||findFileInMap('.pmd','mesh');if(pmx){document.getElementById('pmx-label').classList.add('ready');loadPmx(pmx,'mesh')}else{showLoading(false);updateStatus("PMXが見つかりません♡")}});document.getElementById('file-input2').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"キャラ2展開中...");await processFiles(e.target.files,'mesh2');let pmx=findFileInMap('.pmx','mesh2')||findFileInMap('.pmd','mesh2');if(pmx){document.getElementById('pmx2-label').classList.add('ready');loadPmx(pmx,'mesh2')}else{showLoading(false);updateStatus("PMXが見つかりません♡")}});document.getElementById('stage-input').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"ステージ展開中...");await processFiles(e.target.files,'stage');let pmx=findFileInMap('.pmx','stage')||findFileInMap('.pmd','stage');if(pmx){document.getElementById('stage-label').classList.add('ready');loadPmx(pmx,'stage')}else{showLoading(false);updateStatus("ステージPMXがありません♡")}});
24
  document.getElementById('cam-vmd-input').addEventListener('change',async e=>{const file=e.target.files[0];if(!file)return;showLoading(true,"カメラVMD読込中...");const url=URL.createObjectURL(file);modelData.mesh.loader.loadAnimation(url,camera,clip=>{try{if(helper.camera)helper.remove(camera);helper.add(camera,{animation:clip});cameraVmdEnabled=true;helper.enabled.cameraAnimation=true;controls.enabled=false;maxDuration=Math.max(maxDuration,clip.duration);updateSeekBarLimit();document.getElementById('cam-vmd-label').classList.add('ready');document.getElementById('cam-vmd-toggle').style.display='inline-block';document.querySelectorAll('.aspect-btn').forEach(b=>b.style.display='inline-block');dbg(`[CamVMD]${file.name}(${clip.duration.toFixed(1)}s)`,"info")}catch(err){dbg(`[CamVMD]失敗:${err.message}`,"error")}showLoading(false)},null,()=>{dbg("[CamVMD]読込失敗","error");showLoading(false)})});
25
  document.getElementById('cam-vmd-toggle').addEventListener('click',()=>{cameraVmdEnabled=!cameraVmdEnabled;helper.enabled.cameraAnimation=cameraVmdEnabled;controls.enabled=!cameraVmdEnabled;const btn=document.getElementById('cam-vmd-toggle');btn.textContent=cameraVmdEnabled?'カメラVMD: ON':'カメラVMD: OFF';btn.style.color=cameraVmdEnabled?'#ff8c00':'#666';btn.style.borderColor=cameraVmdEnabled?'#ff8c00':'#666'});