clipoox-render 0.4.7 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/package.json +2 -2
  2. package/scripts/render-local.mjs +2367 -1534
  3. package/shared/photocraft/LICENSE.txt +206 -0
  4. package/shared/photocraft/clipoox_photo.js +396 -0
  5. package/shared/photocraft/clipoox_photo_bg.wasm +0 -0
  6. package/web/assets/{FxEmbed-B-D-tbgP.js → FxEmbed-adbxHEBi.js} +1 -1
  7. package/web/assets/ImageStudio-CMxiT1jp.js +3 -0
  8. package/web/assets/ImageStudio-De_DCTrz.css +1 -0
  9. package/web/assets/{MotionEmbed-eB-zRpv9.js → MotionEmbed-CDUIyjk0.js} +1 -1
  10. package/web/assets/{PluginStore-D6UvvVXA.js → PluginStore-By_pdOOg.js} +2 -2
  11. package/web/assets/ShotComposer-DcwWZ-eP.css +1 -0
  12. package/web/assets/ShotComposer-XIbJ4nNm.js +287 -0
  13. package/web/assets/{TemplateEmbed-DZNaQAJ-.js → TemplateEmbed-a01nKECT.js} +1 -1
  14. package/web/assets/{TimelinePlugins-zhB9Uqav.js → TimelinePlugins-CqLMVjuh.js} +4 -4
  15. package/web/assets/TimelineShotFx-QmkyCg31.js +2 -0
  16. package/web/assets/{TransitionEmbed-r_B0toRr.js → TransitionEmbed-Cbwlxfl2.js} +1 -1
  17. package/web/assets/{Whiteboard-f6owS-ne.js → Whiteboard-ChYqIr3v.js} +1 -1
  18. package/web/assets/{aerial-DIj143Yz.js → aerial-CZeCeacv.js} +2 -2
  19. package/web/assets/{agentTools-CoNs1wCQ.js → agentTools-DW2ETnxE.js} +2 -2
  20. package/web/assets/{aiInbetween-ZFNHEXdI.js → aiInbetween-De98iM4m.js} +2 -2
  21. package/web/assets/analyzerRun-D5-g-Vxe.js +1 -0
  22. package/web/assets/{analyzerSandbox-C2rd6s8U.js → analyzerSandbox-E3CdovIk.js} +1 -1
  23. package/web/assets/{api-DJC95K48.js → api-CZoVJ9Fy.js} +87 -87
  24. package/web/assets/auraTrack-ClhHuqlf.js +1 -0
  25. package/web/assets/{breakthrough-DiHiElqL.js → breakthrough-DTpiUIZd.js} +2 -2
  26. package/web/assets/{cameraPresets-DfKERP1j.js → cameraPresets-DD0WmxiI.js} +1 -1
  27. package/web/assets/{cameraTracker-DFjnZ7tw.js → cameraTracker-Df9jWmz6.js} +2 -2
  28. package/web/assets/{captionLayout-CAuhUiW9.js → captionLayout-eiu9QPJu.js} +1 -1
  29. package/web/assets/{clientExport-DyqpYM6h.js → clientExport-BXegTdNc.js} +1 -1
  30. package/web/assets/{clientJobs-BqkjV5Ld.js → clientJobs-eB-lNyin.js} +2 -2
  31. package/web/assets/clipoox_photo_bg-BQ0aVNY0.wasm +0 -0
  32. package/web/assets/depthEstimate-CfwX-tXP.js +1 -0
  33. package/web/assets/{directorTools-CLn4xt6m.js → directorTools-ABbI8m0e.js} +1 -1
  34. package/web/assets/distortFrames-DMnZ8OYh.js +2 -0
  35. package/web/assets/distortGL-DQu0Df2c.js +18 -0
  36. package/web/assets/{domino-BDKBYrNQ.js → domino-trmDBvfH.js} +1 -1
  37. package/web/assets/{editTools-BqKU-ucA.js → editTools-DEFo9Ahv.js} +1 -1
  38. package/web/assets/{engine-B2YPWQZ2.js → engine-Y-GotDIy.js} +1 -1
  39. package/web/assets/exportGlb-BeLpJKJT.js +2 -0
  40. package/web/assets/{faceTracker-DsmLlUZ1.js → faceTracker-BeSFnLM8.js} +1 -1
  41. package/web/assets/{fightDirector-BIVLGhAP.js → fightDirector-Dfz3vu5-.js} +1 -1
  42. package/web/assets/{fightDrama-B_jDQ-cW.js → fightDrama-CNVn69s0.js} +2 -2
  43. package/web/assets/{focusTool-mWs2Eikj.js → focusTool-Dd2UDkiO.js} +1 -1
  44. package/web/assets/{frameSink-DWkHUnvV.js → frameSink-Rj02YES5.js} +3 -3
  45. package/web/assets/{glTransitionSources.generated-BJuEUz3E.js → glTransitionSources.generated-Cs8lVRqs.js} +438 -2
  46. package/web/assets/{gpuCompose-Fi0sIUI9.js → gpuCompose-DkkKH1Ab.js} +1 -1
  47. package/web/assets/gpuExport-DwrXpVGF.js +199 -0
  48. package/web/assets/{handMatte-CvFkZKTL.js → handMatte-B5sUeqKi.js} +1 -1
  49. package/web/assets/{handTracker-CF1hqh09.js → handTracker-CQV-D7va.js} +2 -2
  50. package/web/assets/i18n-ClNt3LKg.js +3 -0
  51. package/web/assets/{index-EegUntr6.js → index-D2u6mD-8.js} +1 -1
  52. package/web/assets/layer-worker-DP0N05Ua.js +5 -0
  53. package/web/assets/library-cb43ZEmy.js +1 -0
  54. package/web/assets/{lottieLayer-Dp_vGTy8.js → lottieLayer-DEw0c3to.js} +4 -4
  55. package/web/assets/main-C_XcvNyC.js +311 -0
  56. package/web/assets/{main-B_MAOvi6.css → main-DlzdW5C4.css} +1 -1
  57. package/web/assets/{mapBake-CEmw-e9Y.js → mapBake-BUWz0cSx.js} +1 -1
  58. package/web/assets/{maskTrack-CADMBJDf.js → maskTrack-GYpJyKFw.js} +1 -1
  59. package/web/assets/matteFixRun-BCVsuSxf.js +1 -0
  60. package/web/assets/{objectLocate-DWsEG8eK.js → objectLocate-CjIlo_u0.js} +1 -1
  61. package/web/assets/{objectSegmenter-oGv8YQbI.js → objectSegmenter-C4T9qgUL.js} +1 -1
  62. package/web/assets/{objectTrack.worker-B6RVfsq4.js → objectTrack.worker-BVvsDmR0.js} +1161 -770
  63. package/web/assets/{pathTracer-DxqKEvC7.js → pathTracer-DgL1_83l.js} +2 -2
  64. package/web/assets/{pendingMatte-Taa0BlLI.js → pendingMatte-DPTe6xoZ.js} +2 -2
  65. package/web/assets/peopleMatte-C1hruEM6.js +1 -0
  66. package/web/assets/{personAi-BebqXrqD.js → personAi-Cjg9KKeH.js} +2 -2
  67. package/web/assets/{personHq-Cyq9HWnW.js → personHq-CBP8v_cw.js} +2 -2
  68. package/web/assets/photo.worker-DK_ulTzR.js +1 -0
  69. package/web/assets/photoRun-lZ2BdSEk.js +2 -0
  70. package/web/assets/photoTools-DmUh69Qk.js +1 -0
  71. package/web/assets/plateCamera-DLqlXhMp.js +1 -0
  72. package/web/assets/{plateCameraMatch-1_DuZ0LV.js → plateCameraMatch-4VUlUMi-.js} +2 -2
  73. package/web/assets/{plateFollow-Ztxwpq5v.js → plateFollow-D2rjnmZA.js} +2 -2
  74. package/web/assets/plateMatte-0tTG7oeO.js +2 -0
  75. package/web/assets/{pluginAutomation-D73Az7HS.js → pluginAutomation-ClFdpcCR.js} +1 -1
  76. package/web/assets/popTools-B38V4wub.js +1 -0
  77. package/web/assets/{poseTracker-b1h08oRY.js → poseTracker-qtuytI-L.js} +1 -1
  78. package/web/assets/{productTools-CoJ_Fnfc.js → productTools-DlC5vWjx.js} +2 -2
  79. package/web/assets/remote-CpkPQOQH.js +989 -0
  80. package/web/assets/{rigTrack-B9r9wrdV.js → rigTrack-BbKqZGs7.js} +1 -1
  81. package/web/assets/{rotoMaskStore-RmW40Pcn.js → rotoMaskStore-BZBJLcCp.js} +1 -1
  82. package/web/assets/{rotoMatte-DisQplSv.js → rotoMatte-BI-vjjrv.js} +1 -1
  83. package/web/assets/rotoscope-DuNcCxQy.js +1 -0
  84. package/web/assets/{sceneTrack-DyVxpl7i.js → sceneTrack-CO4fTjft.js} +1 -1
  85. package/web/assets/sceneTrack-_n6WKKQv.js +1 -0
  86. package/web/assets/{sceneTrack.worker-DKVLLgf9.js → sceneTrack.worker-f2d-WOzw.js} +1207 -816
  87. package/web/assets/{shot-worker-DM5PUQ6g.js → shot-worker-BSmfIXHO.js} +1 -1
  88. package/web/assets/{shotFxAgent-CsW0MAiG.js → shotFxAgent-L2GG88W3.js} +1 -1
  89. package/web/assets/{skin-CXvqtCZI.js → skin-CirUiqcr.js} +1 -1
  90. package/web/assets/{spark.module-B341moK0.js → spark.module-3Q8DniuL.js} +1 -1
  91. package/web/assets/{spellDuel-KCMEFHLA.js → spellDuel-2CDLbiLQ.js} +2 -2
  92. package/web/assets/{store-xR02oY0m.js → store-D3Y663py.js} +1 -1
  93. package/web/assets/{surfaceLight-DBfJxggM.js → surfaceLight--HQj7xhO.js} +1 -1
  94. package/web/assets/{surfacePin-i-X1Dz68.js → surfacePin-BCmgw-40.js} +2 -2
  95. package/web/assets/{textAnimators-CeMuG34D.js → textAnimators-C4eMnVRD.js} +1 -1
  96. package/web/assets/{thumb-DzNl15MN.js → thumb-M9B_goj-.js} +1 -1
  97. package/web/assets/{timeline3d-D0Ws4lcp.js → timeline3d-BcW68fQr.js} +2 -2
  98. package/web/assets/{timeline3dExport-BO--SpAn.js → timeline3dExport-DgnorHLm.js} +1 -1
  99. package/web/assets/timelineComp-Ciu9JCWJ.js +1 -0
  100. package/web/assets/timelineOps-f1WsVbgS.js +526 -0
  101. package/web/assets/{timelineProps-Cm_Irino.js → timelineProps-CE1R11Hx.js} +1 -1
  102. package/web/assets/{timelineText-DjPW2-dd.js → timelineText-Cppd4KB7.js} +1 -1
  103. package/web/assets/{titleArt-BSu80bfN.js → titleArt-D0YI5xT2.js} +3 -3
  104. package/web/assets/{titleFrameBudget-BW-N1-cw.js → titleFrameBudget-h4nOQ5u9.js} +1382 -991
  105. package/web/assets/titleFrames-DnCzi_AI.js +1 -0
  106. package/web/assets/{tool-Bboi3NDg.js → tool-tp6gat1J.js} +1 -1
  107. package/web/assets/{tools-kgYkohv8.js → tools-C07G9KUM.js} +1 -1
  108. package/web/assets/{toonTools-Bxz_HSqT.js → toonTools-Cazx2CL7.js} +2 -2
  109. package/web/assets/{trackAnchor-DK9cEMCf.js → trackAnchor-DoqFDcJB.js} +1 -1
  110. package/web/assets/{userFonts-DSkZHfmh.js → userFonts-BlVEJfDk.js} +1 -1
  111. package/web/assets/{vfxAlpha-B0rNpKZN.js → vfxAlpha-Bp6VgIGN.js} +1 -1
  112. package/web/assets/vfxBackground-BFq44Srn.js +2 -0
  113. package/web/assets/{videoExport-Cu0vw-dL.js → videoExport-Cz02XKtX.js} +1 -1
  114. package/web/assets/{views-CmulxRJP.js → views-CNF3Afse.js} +1 -1
  115. package/web/assets/{weaponDuel-DuuMMfzY.js → weaponDuel-ChqBQo_b.js} +1 -1
  116. package/web/assets/{windowFrames-BP2oDn-n.js → windowFrames-dBMXwGek.js} +1 -1
  117. package/web/layer-worker.html +3 -3
  118. package/web/shot-worker.html +24 -24
  119. package/web/assets/ShotComposer-CoxtWL6A.js +0 -287
  120. package/web/assets/ShotComposer-deLi4grZ.css +0 -1
  121. package/web/assets/TimelineShotFx-muTN__gf.js +0 -2
  122. package/web/assets/analyzerRun-BswbLsRF.js +0 -1
  123. package/web/assets/auraTrack-C9diszRB.js +0 -1
  124. package/web/assets/depthEstimate-HrGq0Ffx.js +0 -1
  125. package/web/assets/distortFrames-D-DK2HlN.js +0 -2
  126. package/web/assets/distortGL-waTJhiOf.js +0 -12
  127. package/web/assets/exportGlb-Cm07JQXt.js +0 -2
  128. package/web/assets/gpuExport-Dlf6YjLs.js +0 -198
  129. package/web/assets/i18n-C9zFX25m.js +0 -3
  130. package/web/assets/layer-worker-Drj-NLVj.js +0 -5
  131. package/web/assets/library-BhH-xsMR.js +0 -1
  132. package/web/assets/main-DAk1Tv1E.js +0 -309
  133. package/web/assets/matteFixRun-BHD3Qnta.js +0 -1
  134. package/web/assets/plateCamera-D1A1iEpf.js +0 -1
  135. package/web/assets/plateMatte-CWT1ymGj.js +0 -2
  136. package/web/assets/remote-kxNNhmis.js +0 -974
  137. package/web/assets/rotoscope-Z8bn-jRs.js +0 -1
  138. package/web/assets/sceneTrack-BKknn180.js +0 -1
  139. package/web/assets/timelineComp-D8PHGHgQ.js +0 -1
  140. package/web/assets/timelineOps-CEGk2t4h.js +0 -525
  141. package/web/assets/titleFrames-BHFaInux.js +0 -1
  142. package/web/assets/vfxBackground-CBTDl1xA.js +0 -2
@@ -0,0 +1,287 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/productTools-DlC5vWjx.js","assets/titleFrameBudget-h4nOQ5u9.js","assets/remote-CpkPQOQH.js","assets/index-CKtv7gGE.js","assets/i18n-ClNt3LKg.js","assets/api-CZoVJ9Fy.js","assets/three.module-Bx43vjkH.js","assets/gltfLoader-U0Eebg7v.js","assets/store-D3Y663py.js","assets/rotoMaskStore-BZBJLcCp.js","assets/sceneTrack-CO4fTjft.js","assets/timelineOps-f1WsVbgS.js","assets/cameraTracker-Df9jWmz6.js","assets/textAnimators-C4eMnVRD.js","assets/timelineComp-Ciu9JCWJ.js","assets/rigTrack-BbKqZGs7.js","assets/clientJobs-CuuUyhEy.js","assets/exportGlb-BeLpJKJT.js","assets/aiInbetween-De98iM4m.js","assets/pathTracer-DgL1_83l.js","assets/plateFollow-D2rjnmZA.js","assets/plateCamera-DLqlXhMp.js","assets/plateMatte-0tTG7oeO.js","assets/rotoMatte-BI-vjjrv.js","assets/videoExport-Cz02XKtX.js","assets/motionBlur-uAm030t9.js","assets/id3-arvEpAg7.js","assets/output-p-Q7qous.js"])))=>i.map(i=>d[i]);
2
+ import{_ as nn}from"./titleFrameBudget-h4nOQ5u9.js";import{a1 as Va,a2 as tt,a3 as Zs,a4 as xs,a5 as Nm,a6 as Yh,a7 as Qh,a8 as ys,a9 as yt,aa as qn,b as An,ab as Zh,ac as Am,ad as _l,ae as Rr,af as Ht,ag as Jh,ah as Tm,ai as La,aj as ei,ak as Lm,al as ed,am as Em,j as t,an as Rm,ao as Oo,ap as Im,aq as Pm,ar as Fm,as as td,at as $m,au as Dm,av as Ga,aw as nd,ax as Ea,ay as sd,az as Om,aA as zl,aB as _m,aC as zm,aD as yi,aE as _s,aF as qa,aG as Js,aH as Us,aI as Bl,aJ as Kl,aK as Hl,aL as ad,aM as Bm,aN as Ra,aO as bn,I as Ce,N as Tn,R as zs,aP as vi,aQ as Wl,aR as Gl,aS as Km,aT as ql,aU as On,aV as Hm,aW as Wm,aX as Gm,aY as _o,aZ as qm,a_ as od,a$ as Ua,b0 as Ul,b1 as Um,b2 as Lo,b3 as id,b4 as Xm,b5 as Vm,b6 as Ym,b7 as Qm,b8 as Zm,b9 as Jm,ba as zo,bb as ep,bc as tp,bd as tr,be as yn,bf as nr,bg as sr,bh as np,bi as Xl,bj as sp,bk as ap,bl as op,bm as ip,bn as is,bo as Ir,bp as rp,bq as Vl,br as ti,bs as rd,bt as Xa,bu as lp,bv as ld,bw as cd,bx as ji,by as Xn,bz as ea,bA as cp,bB as hd,bC as ki,bD as Bs,bE as hp,bF as dp,bG as dd,bH as Pr,bI as up,bJ as mp,bK as Fr,bL as Yl,bM as pp,bN as fp,F as gp,bO as xp,a0 as bp,bP as yp,bQ as vp,bR as jp,bS as kp,bT as wp,bU as $r,bV as ud,bW as Mp,bX as io,bY as Sp,bZ as Cp,b_ as Np,b$ as Ap,c0 as Tp,c1 as Lp,c2 as Ep,c3 as Rp,c4 as Ip,c5 as Ql,c6 as Zl,c7 as wi,c8 as Pp,c9 as Fp,ca as $p,cb as md,cc as pd,cd as fd,ce as Bo,cf as Jl,cg as Dr,ch as Dp,ci as Op,cj as _p,ck as ec,cl as zp,cm as Wn,cn as Bp,co as Kp,cp as tc,cq as pa,cr as As,cs as Hp,ct as Wp,cu as Gp,cv as qp,cw as Rs,cx as Up,cy as Xp,cz as Vp,cA as Yp,cB as Qp,cC as gd,cD as Ko,cE as Zp,cF as nc,cG as Jp,cH as Mi,cI as sc,cJ as Si,cK as ef,cL as Ho,cM as tf,cN as nf,cO as sf,cP as fs,cQ as Wo,r as xd,cR as af,cS as of,cT as rf,cU as ac,cV as lf,cW as cf,cX as Or,cY as _r,cZ as Ia,c_ as hf,c$ as df,d0 as uf,d1 as ro,d2 as Ci,d3 as ar,d4 as bd,d5 as mf,d6 as Ni,d7 as pf,d8 as ff,d9 as gf,da as xf,db as yd,dc as vd,a as Ot,dd as bf,de as yf,df as vf,dg as jf,dh as kf,Q as wf,W as Mf,X as Sf,di as Cf,dj as Nf,dk as or,dl as Af,dm as Tf,dn as Lf,dp as Ef,dq as Rf,dr as oc,ds as ir,dt as Da,du as If,dv as Oa,dw as ic,dx as Pf,dy as Go,dz as Eo,n as Ff,dA as $f,u as Ai,dB as rc,dC as Df,dD as Of,Y as lc,dE as _f,dF as cc,dG as zf,dH as Bf,dI as Kf,dJ as Hf,dK as Ti,q as Wf,dL as Gf,dM as qf,dN as Uf,dO as Li,dP as Xf,dQ as Vf,dR as Yf,dS as Qf,dT as Zf,dU as Jf,dV as e0,dW as t0,dX as Ei,dY as n0,dZ as hc,d_ as s0,d$ as a0,e0 as dc,e1 as o0,e2 as i0,e3 as Ri,e4 as uc,e5 as mc,e6 as Ii,e7 as r0,e8 as l0,e9 as c0,ea as h0,eb as Pi,ec as d0,ed as u0,ee as m0,ef as p0,eg as f0,eh as g0,ei as x0,ej as b0,ek as y0,el as v0,em as j0,en as k0,eo as w0,ep as M0,eq as S0,er as C0,es as N0,et as A0,eu as T0,ev as L0,ew as E0,ex as R0,ey as I0,ez as P0,eA as F0,eB as $0,eC as D0,eD as O0,eE as pc,eF as _0,eG as z0,eH as fc,eI as gc,eJ as B0}from"./remote-CpkPQOQH.js";import{u as rt,t as a,g as aa}from"./i18n-ClNt3LKg.js";import{r as I}from"./index-CKtv7gGE.js";import{Mesh as dt,SkinnedMesh as zr,Box3 as _t,Vector3 as ae,Matrix4 as Nt,Group as dn,Uint16BufferAttribute as jd,Float32BufferAttribute as zt,BufferGeometry as At,BufferAttribute as Rt,MathUtils as gn,DirectionalLight as ni,WebGLRenderer as Br,SRGBColorSpace as si,AgXToneMapping as kd,PCFSoftShadowMap as K0,Scene as Kr,PMREMGenerator as wd,HemisphereLight as Md,PlaneGeometry as ai,ShadowMaterial as H0,PerspectiveCamera as Hr,InstancedMesh as Xs,DataTexture as W0,RGBAFormat as G0,RepeatWrapping as Sd,LinearFilter as xc,CanvasTexture as Wr,NoColorSpace as Cd,LinearMipmapLinearFilter as Nd,InstancedBufferAttribute as rr,DynamicDrawUsage as oa,MeshStandardMaterial as os,ShaderMaterial as Ya,Color as Ve,DoubleSide as ks,AdditiveBlending as Gr,LinearSRGBColorSpace as vs,CapsuleGeometry as Ad,ConeGeometry as q0,CylinderGeometry as ws,TorusGeometry as qr,SphereGeometry as Un,BoxGeometry as Qa,MeshPhysicalMaterial as $s,Vector2 as ca,LatheGeometry as Td,FrontSide as Za,Quaternion as qe,Vector4 as Is,InstancedInterleavedBuffer as Ld,InterleavedBufferAttribute as $n,InstancedBufferGeometry as U0,OneMinusSrcAlphaFactor as X0,OneFactor as V0,AddEquation as Y0,CustomBlending as Q0,NormalBlending as Z0,DetachedBindMode as J0,OctahedronGeometry as lr,MeshBasicMaterial as bs,Line as Fi,LineBasicMaterial as bc,PointLight as eg,Euler as cr,Bone as _a,Uint8BufferAttribute as js,ShaderChunk as tg,Sphere as ng,LOD as sg,Skeleton as $i,Object3D as ag,NearestFilter as og,ACESFilmicToneMapping as ig,CircleGeometry as rg,Raycaster as yc}from"./three.module-Bx43vjkH.js";import{bw as lg,u as Vs,bx as vc,by as cg,bz as hg,bA as dg,bB as ug,bC as mg,bD as pg,bE as fg,bF as gg,bG as xg,bH as bg,aq as yg,bI as vg,bJ as jc,_ as jg,a as kg}from"./api-CZoVJ9Fy.js";import{R as Ed}from"./RoomEnvironment-Dmv_G5ka.js";import{i as kc,p as wc,g as wg,e as Mg}from"./tool-tp6gat1J.js";import{rowProps as Sg,rowKeyed as Cg,readProp as Ng,writeProp as Ag,keyAllAt as Tg,copyKeys as Lg,pasteKeys as Eg,easeKeys as Rg,nudgeKeys as Mc}from"./timelineProps-CE1R11Hx.js";import{b as Ig,c as Pg,A as Fg,d as Sc,a as $g,t as Dg}from"./thumb-M9B_goj-.js";import{f as Og,p as _g}from"./shotFxAgent-L2GG88W3.js";import{a as Rd}from"./gltfLoader-U0Eebg7v.js";import{p as zg,C as Bg,a as Kg,b as Hg,c as Cc}from"./cameraPresets-DD0WmxiI.js";import{m as Wg}from"./rigTrack-BbKqZGs7.js";import{D as Gg,s as qg}from"./weaponDuel-ChqBQo_b.js";import{u as ht}from"./store-D3Y663py.js";import{r as Nc,a as Ug,b as Xg,o as Vg,w as Yg,c as Qg,d as Zg,e as Di,f as Jg,g as ex,p as tx,h as nx}from"./skin-CirUiqcr.js";import{renderRigViews as sx}from"./views-CNF3Afse.js";import{M as fa}from"./motionBlur-uAm030t9.js";import{x as ax}from"./timelineOps-f1WsVbgS.js";import{fitLibraryFingers as Ac}from"./library-cb43ZEmy.js";import"./rotoMaskStore-BZBJLcCp.js";import"./sceneTrack-CO4fTjft.js";import"./cameraTracker-Df9jWmz6.js";import"./textAnimators-C4eMnVRD.js";import"./timelineComp-Ciu9JCWJ.js";import"./clientJobs-CuuUyhEy.js";function ox(e,n,s){const o=[e[0]*n[0]+e[4]*n[1]+e[8]*n[2]+e[12],e[1]*n[0]+e[5]*n[1]+e[9]*n[2]+e[13],e[2]*n[0]+e[6]*n[1]+e[10]*n[2]+e[14]],i=[0,1,2].map(r=>Math.abs(e[r]*s[0])+Math.abs(e[4+r]*s[1])+Math.abs(e[8+r]*s[2]));return{c:o,h:i,min:o.map((r,l)=>r-i[l]),max:o.map((r,l)=>r+i[l])}}function ix(e,{cell:n=1}={}){const s=e.length,o=Array.from({length:s},()=>[]),i=Array.from({length:s},()=>[]),r=e.reduce((k,w)=>Math.min(k,w.min[1]),1/0),l=e.reduce((k,w)=>Math.max(k,w.max[1]),-1/0),h=Math.max(.03,n*.2),u=Math.max(.02,n*.06),m=e.map(k=>k.min[1]<=r+h);for(let k=0;k<s;k++){const w=e[k],S=(w.min[1]+w.max[1])/2,E=(w.max[1]-w.min[1])/2;for(let j=k+1;j<s;j++){const M=e[j],T=[0,1,2].map(C=>Math.min(w.max[C],M.max[C])-Math.max(w.min[C],M.min[C]));if(T[0]<-u||T[2]<-u||T[1]<-h)continue;const N=(M.min[1]+M.max[1])/2,R=(M.max[1]-M.min[1])/2,A=N-S;if(Math.abs(A)>.3*(E+R)){const C=A>0?M:w,O=B=>T[B]/Math.max(.001,C.max[B]-C.min[B]);if(O(0)<.45||O(2)<.45)continue;A>0?o[k].push(j):o[j].push(k)}else i[k].push(j),i[j].push(k)}}const d=new Uint8Array(s).fill(1);let f=hr({ups:o,side:i,ground:m},d,null);const p=Math.max(.05,n*.25);for(let k=0;k<3;k++){let w=!1;for(let S=0;S<s;S++){if(Number.isFinite(f[S]))continue;const E=e[S],j=(E.min[1]+E.max[1])/2,M=(E.max[1]-E.min[1])/2;for(let T=0;T<s;T++){if(T===S||i[S].includes(T)||o[S].includes(T)||o[T].includes(S))continue;const N=e[T];if(![0,1,2].every(C=>Math.min(E.max[C],N.max[C])-Math.max(E.min[C],N.min[C])>=-p))continue;const R=(N.min[1]+N.max[1])/2-j,A=(N.max[1]-N.min[1])/2;Math.abs(R)>.3*(M+A)?R>0?o[S].push(T):o[T].push(S):(i[S].push(T),i[T].push(S)),w=!0}}if(!w)break;f=hr({ups:o,side:i,ground:m},d,null)}const y=e.map(k=>[k.min[0],k.max[0],k.min[2],k.max[2]]),g=e.map(k=>[(k.min[0]+k.max[0])/2,(k.min[2]+k.max[2])/2]),v={n:s,ups:o,side:i,ground:m,need0:f,base:r,top:l,foot:y,plan:g,cell:n,tops:e.map(k=>k.max[1]),slender0:0},b=[...Array(s).keys()].filter(k=>Number.isFinite(f[k]));return v.slender0=b.length?Fd(v,b):0,v.stable0=lx(v,d,0),v}function rx(e,n){if(!e.adj){e.adj=Array.from({length:e.n},(s,o)=>[...e.ups[o],...e.side[o]]);for(let s=0;s<e.n;s++)for(const o of e.ups[s])e.adj[o].push(s)}return e.adj[n]}function Id(e,n){const s=new Int32Array(e.n).fill(-1),o=[];for(let i=0;i<e.n;i++){if(!n[i]||s[i]>=0)continue;const r=[i];s[i]=o.length;for(let l=0;l<r.length;l++)for(const h of rx(e,r[l]))n[h]&&s[h]<0&&(s[h]=o.length,r.push(h));o.push(r)}return o}function Pd(e,n){let s=1/0,o=-1/0,i=1/0,r=-1/0,l=0;for(const h of n){if(!e.ground[h])continue;l++;const u=e.foot[h];s=Math.min(s,u[0]),o=Math.max(o,u[1]),i=Math.min(i,u[2]),r=Math.max(r,u[3])}return{x0:s,x1:o,z0:i,z1:r,ng:l}}function Fd(e,n){const s=Pd(e,n),o=(e.cell??1)*.25;return s.ng?(n.reduce((r,l)=>Math.max(r,e.tops[l]),-1/0)-e.base)/Math.max(.001,Math.min(s.x1-s.x0,s.z1-s.z0)+2*o):0}function $d(e,n,s,o){const i=Pd(e,n),r=i.ng;if(!r||n.length-r<2)return!0;let l=0,h=0;for(const m of n)l+=e.plan[m][0],h+=e.plan[m][1];l/=n.length,h/=n.length;const u=(e.cell??1)*.5*(1+s);return l<i.x0-u||l>i.x1+u||h<i.z0-u||h>i.z1+u||e.tops&&Fd(e,n)>Math.max(4,2*(e.slender0??0))*(1+.25*s)?!1:r/n.length>=o*(.3/(1+s))}function Dd(e){let n=0,s=0;for(let o=0;o<e.n;o++)Number.isFinite(e.need0[o])&&(s++,e.ground[o]&&n++);return s?n/s:0}function lx(e,n,s){const o=Dd(e);return Id(e,n).every(i=>$d(e,i,s,o))}function hr(e,n,s){const o=n.length,i=new Float64Array(o).fill(1/0),r=[];for(let l=0;l<o;l++)n[l]&&e.ground[l]&&(i[l]=0,r.push(l));for(let l=0;l<r.length;l++){const h=r[l],u=i[h],m=u+1;for(const d of e.ups[h])n[d]&&i[d]>0&&(i[d]=0,r.push(d));for(const d of e.side[h])n[d]&&i[d]>m&&(!s||m<=s[d])&&(i[d]=m,r.push(d))}return i}const cx=e=>e>=.8?0:e>=.4?1:2;function hx(e,n,{slack:s=0,seed:o=1,centres:i}={}){const r=e.n,l=new Array(r).fill(null),h=new Uint8Array(r).fill(1);if(!r)return l;const u=Float64Array.from(e.need0,v=>v+s),m=Math.max(.1,e.top-e.base),d=Va(o|0,7717,5),f=[],p=e.stable0!==!1&&!!e.foot,y=p?Dd(e):0;for(let v=0;v<r;v++)Number.isFinite(n[v])&&f.push({t:n[v],i:v});f.sort((v,b)=>v.t-b.t||v.i-b.i);let g=0;for(;g<f.length;){const v=f[g].t,b=[];for(;g<f.length&&f[g].t<=v+1e-9;){const S=f[g++];h[S.i]&&(h[S.i]=0,b.push(S.i))}if(!b.length)continue;const k=hr(e,h,u),w=i?tt.mul(b.reduce((S,E)=>tt.add(S,i[E]),[0,0,0]),1/b.length):null;for(let S=0;S<r;S++){if(!h[S]||!Number.isFinite(e.need0[S])||k[S]<=u[S])continue;h[S]=0;const E=i?Zs((i[S][1]-e.base)/m):.5,j=v+.05+.13*E+.07*xs(d,S,1);l[S]={t:j,from:w}}if(p){for(const S of Id(e,h))if(!$d(e,S,s,y))for(const E of S){if(e.ground[E])continue;h[E]=0;const j=i?Zs((i[E][1]-e.base)/m):.5;l[E]={t:v+.08+.15*j+.07*xs(d,E,1),from:w}}}}return l}function dx(e,n,{base:s=0,cell:o=1}={}){const i=Math.max(.05,o*.25),r=new Map,l=(d,f)=>`${d},${f}`,h=(d,f,p,y,g)=>{const v=[];for(let b=Math.floor((d-p*g)/i);b<=Math.floor((d+p*g)/i);b++)for(let k=Math.floor((f-y*g)/i);k<=Math.floor((f+y*g)/i);k++)v.push(l(b,k));return v};for(const d of n)for(const f of h(d.x,d.z,d.hx,d.hz,.85))r.set(f,Math.max(r.get(f)??s,d.y1));const u=new Map,m=Math.max(.1,o*.5);for(const d of[...e].sort((f,p)=>f.t-p.t||f.i-p.i)){const f=d.hy*.8;let p=null;for(const y of d.dirs??[[1,0,0]])for(let g=0;g<=8;g++){const v=d.x+y[0]*m*g,b=d.z+y[2]*m*g,k=h(v,b,d.hx,d.hz,.6),w=k.reduce((E,j)=>Math.max(E,r.get(j)??s),s),S=w+.45*m*g;(!p||S<p.score-1e-9)&&(p={x:v,z:b,y:Math.min(d.top,w+f),foot:k,score:S})}u.set(d.i,{x:p.x,z:p.z,y:p.y});for(const y of p.foot)r.set(y,Math.max(r.get(y)??s,p.y+f*.9))}return u}function ux(e,n,s,{gravity:o=9.8,seed:i=1,crumble:r=.6}={}){if(!e||!(s>=e.t))return null;const l=s-e.t,h=Math.max(.5,o),u=Math.max(0,e.p0[1]-e.land),m=Math.sqrt(2*u/h),d=Math.min(l,m),f=m>1e-6?d/m:1,p=Nm(u,0,h,l,.12),y=l>m?(1-Math.exp(-3*(l-m)))/3:0,g=e.p0[0]+(e.to[0]-e.p0[0])*f+e.dir[0]*.4*y,v=e.p0[2]+(e.to[1]-e.p0[2])*f+e.dir[2]*.4*y,b=Va(i|0,n,4441),k=(.25+.9*xs(b,1,1))*(.4+.6*r),w=tt.norm([e.dir[2]+(xs(b,2,1)-.5)*.3,0,-e.dir[0]+(xs(b,3,1)-.5)*.3]),S=k*Yh(0,1,f)+(l>m?.15*k*y:0);return{pos:[g,e.land+p.y,v],axis:Number.isFinite(w[0])?w:[1,0,0],angle:S,landed:l>=m}}function mx(e,n,s,{base:o=0,cell:i=1,seed:r=1,centre:l=null}={}){const h=Va(r|0,3301,7),u=[],m=n.map((f,p)=>{if(!f)return null;const y=e[p],g=f.from??y.c,v=[g[0]-y.c[0],0,g[2]-y.c[2]],b=Math.hypot(v[0],v[2]),k=xs(h,p,1)*Math.PI*2,w=(xs(h,p,2)-.5)*.9,S=b>1e-4?tt.norm([v[0]/b+Math.cos(k)*.25,0,v[2]/b+Math.sin(k)*.25]):[Math.cos(k),0,Math.sin(k)],E=l?[y.c[0]-l[0],0,y.c[2]-l[2]]:[Math.cos(k+1),0,Math.sin(k+1)],j=Math.hypot(E[0],E[2]),M=j>1e-4?[E[0]/j,0,E[2]/j]:[Math.cos(k+1),0,Math.sin(k+1)],T=(N,R)=>[N[0]*Math.cos(R)-N[2]*Math.sin(R),0,N[0]*Math.sin(R)+N[2]*Math.cos(R)];return u.push({i:p,t:f.t,x:y.c[0],z:y.c[2],hx:y.h[0],hz:y.h[2],hy:Math.min(y.h[1],Math.max(y.h[0],y.h[2])*1.2),top:y.c[1],dirs:[S,T(M,w),T(M,w+.8),T(M,w-.8)]}),{t:f.t,p0:[...y.c],dir:S,to:[y.c[0],y.c[2]],land:o,by:"fall"}}),d=s.map(f=>({x:e[f].c[0],z:e[f].c[2],hx:e[f].h[0],hz:e[f].h[2],y1:e[f].c[1]+e[f].h[1]}));for(const[f,p]of dx(u,d,{base:o,cell:i}))m[f]&&(m[f].land=p.y,m[f].to=[p.x,p.z]);return m}function px(e,{mode:n="pancake",start:s=0,duration:o=4,yaw:i=0,crumble:r=.6,seed:l=1,cell:h=1,gone:u=null,gravity:m=9.8}={}){const d=e.reduce((N,R)=>Math.min(N,R.min[1]),1/0),f=e.reduce((N,R)=>Math.max(N,R.max[1]),-1/0),p=Math.max(.3,o),y=Math.max(.1,f-d),g=.17+.13*(1-r),v=[0,2].map(N=>e.reduce((R,A)=>Math.min(R,A.min[N]),1/0)),b=[0,2].map(N=>e.reduce((R,A)=>Math.max(R,A.max[N]),-1/0)),k=[(v[0]+b[0])/2,d,(v[1]+b[1])/2],w=i*Math.PI/180,S=[Math.sin(w),0,Math.cos(w)],E=e.reduce((N,R)=>Math.max(N,...[0,1].flatMap(A=>[0,1].map(C=>(A?R.max[0]:R.min[0])*S[0]+(C?R.max[2]:R.min[2])*S[2]))),-1/0)-(k[0]*S[0]+k[2]*S[2]),j=[k[0]+S[0]*E,d,k[2]+S[2]*E],M=[S[2],0,-S[0]],T={mode:gx.has(n)?n:"pancake",t0:s,D:p,base:d,top:f,H:y,c:g,centre:k,pivot:j,dir:S,axis:M,ext:E,seed:l|0,crumble:r,cell:h};if(T.mode==="pancake"){const N=.008333333333333333,R=Math.max(.5,m),A=Math.max(.3,h),C=Math.max(.3,h*1.5),O=e.map($=>`${Math.floor($.c[0]/C)},${Math.floor($.c[2]/C)}`),B=new Map;e.forEach(($,W)=>{const z=O[W];B.has(z)||B.set(z,[]),B.get(z).push(W)});const D=new Map;for(const[$,W]of B){const z=[f];let Y=f,J=0;for(let V=1;Y>d&&V<7200;V++){const H=s+V*N,G=Zs((H-s)/p),_=y*1.6*Math.pow(Math.max(G,.02),.6)/p;J=W.some(Q=>e[Q].c[1]<=Y&&e[Q].c[1]>=Y-A&&!(u&&u[Q]<=H))?Math.max(_,J+R*.6*N):J+R*N,Y=Math.max(d,Y-J*N),z.push(Y)}D.set($,z)}T.fronts=D,T.colOf=O,T.dt=N,T.starts=e.map(($,W)=>{const z=D.get(O[W]),Y=z.findIndex(J=>J<$.c[1]);return s+(Y<0?z.length:Y)*N})}else T.starts=e.map(()=>s);return T}const fx=(e,n,s)=>{const o=e.fronts.get(e.colOf[n]),i=(s-e.t0)/e.dt;if(i<=0)return e.top;const r=Math.floor(i);return r>=o.length-1?o[o.length-1]:o[r]+(o[r+1]-o[r])*(i-r)},gx=new Set(["pancake","topple","base"]),xx=(e,n,s)=>{const o=Math.cos(s),i=Math.sin(s),r=tt.dot(n,e),l=tt.cross(n,e);return[e[0]*o+l[0]*i+n[0]*r*(1-o),e[1]*o+l[1]*i+n[1]*r*(1-o),e[2]*o+l[2]*i+n[2]*r*(1-o)]};function Tc(e,n,s,o){if(!e||!(o>=e.starts[s]))return null;const i=Va(e.seed,s,6067),r=g=>xs(i,g,1),l=Zs((o-e.t0)/e.D),h=e.crumble,u=e.base+Math.min(n.h[1],Math.max(n.h[0],n.h[2]))*.55,m=tt.norm([n.c[0]-e.centre[0]+(r(1)-.5)*.6,0,n.c[2]-e.centre[2]+(r(2)-.5)*.6]),d=tt.norm([r(3)-.5,(r(4)-.5)*.4,r(5)-.5]);if(e.mode==="topple"){const g=Math.PI/2*l*l,v=tt.sub(n.c,e.pivot),b=tt.add(e.pivot,xx(v,e.axis,g)),k=Math.max(0,o-(e.t0+e.D)),w=(1-Math.exp(-2.5*k))/2.5,S=Yh(.55,1,l),E=h*e.cell*(.4+1.2*r(6)),j=tt.add(tt.mul(e.dir,(.8+2.2*r(7))*h*w*2),tt.mul(m,E*S*.5+h*w*r(8))),M=tt.add(b,j);return M[1]=Math.max(u,M[1]),{pos:M,axis:e.axis,angle:g,extra:{axis:d,angle:h*(S*.6+w*2)*(.3+r(9))}}}let f,p;if(e.mode==="base"){const g=e.base+e.H*Math.pow(l,1.3),v=n.c[1];v>=g?(f=v-(g-e.base)*(1-e.c),p=0):(f=e.base+(v-e.base)*e.c,p=Zs((g-v)/Math.max(.2,e.cell*2)))}else{const g=fx(e,s,o),v=n.c[1];f=g>=v?v:g+(v-g)*e.c;const b=e.base+(v-e.base)*e.c;p=v-b>1e-6?Zs((v-f)/(v-b)):1}f=Math.max(u,f);const y=(.15+1.1*h)*e.cell*(.5+r(10))*p;return{pos:[n.c[0]+m[0]*y,f,n.c[2]+m[2]*y],axis:d,angle:p*(.15+1.1*h)*(.3+r(11))}}function bx(e,{blasts:n=[],collapses:s=[],falls:o=[]}={}){const i=new Array(e).fill(null),r=(l,h)=>{(!i[l]||h.t<i[l].t-1e-9||Math.abs(h.t-i[l].t)<=1e-9&&Lc[h.kind]<Lc[i[l].kind])&&(i[l]=h)};for(const l of n)for(let h=0;h<e;h++){const u=l.hits[h];u&&r(h,{kind:"hit",e:l.e,t:u.t})}for(let l=0;l<e;l++)o[l]&&r(l,{kind:"fall",e:-1,t:o[l].t});for(const l of s)for(let h=0;h<e;h++)r(h,{kind:"collapse",e:l.e,t:l.plan.starts[h]});return i}const Lc={hit:0,fall:1,collapse:2};function yx(e,n){const s=new Float64Array(e).fill(1/0);for(const o of n)for(let i=0;i<e;i++){const r=o.hits[i];r&&r.t<s[i]&&(s[i]=r.t)}return s}function vx(e){const n=Math.floor(e.length/3);if(n<4)return null;const s=j=>[e[j*3],e[j*3+1],e[j*3+2]];let o=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(let j=0;j<n;j++)for(let M=0;M<3;M++)o[M]=Math.min(o[M],e[j*3+M]),i[M]=Math.max(i[M],e[j*3+M]);const r=Math.max(1e-9,...i.map((j,M)=>j-o[M])),l=r*1e-7;let h=0;for(let j=1;j<n;j++)e[j*3]<e[h*3]&&(h=j);let u=-1,m=0;for(let j=0;j<n;j++){const M=tt.dist(s(j),s(h));M>m+l&&(m=M,u=j)}if(u<0)return null;let d=-1,f=0;const p=tt.sub(s(u),s(h));for(let j=0;j<n;j++){const M=tt.len(tt.cross(p,tt.sub(s(j),s(h))));M>f+l*r&&(f=M,d=j)}if(d<0)return null;const y=tt.cross(p,tt.sub(s(d),s(h)));let g=-1,v=0;for(let j=0;j<n;j++){const M=Math.abs(tt.dot(y,tt.sub(s(j),s(h))));M>v+l*r*r&&(v=M,g=j)}if(g<0||v<l*r*r*10)return null;const b=[],k=(j,M,T)=>{const N=tt.cross(tt.sub(s(M),s(j)),tt.sub(s(T),s(j))),R=tt.len(N)||1,A=tt.mul(N,1/R);return{v:[j,M,T],n:A,d:tt.dot(A,s(j)),alive:!0}},w=tt.mul(tt.add(tt.add(s(h),s(u)),tt.add(s(d),s(g))),.25);for(const[j,M,T]of[[h,u,d],[h,u,g],[h,d,g],[u,d,g]]){let N=k(j,M,T);tt.dot(N.n,w)-N.d>0&&(N=k(j,T,M)),b.push(N)}const S=new Set([h,u,d,g]);for(let j=0;j<n;j++){if(S.has(j))continue;const M=s(j),T=[];for(const R of b)R.alive&&tt.dot(R.n,M)-R.d>l&&T.push(R);if(!T.length)continue;const N=new Map;for(const R of T){R.alive=!1;for(let A=0;A<3;A++){const C=R.v[A],O=R.v[(A+1)%3],B=`${O},${C}`;N.has(B)?N.delete(B):N.set(`${C},${O}`,[C,O])}}for(const[R,A]of N.values())b.push(k(R,A,j))}const E=[];for(const j of b)j.alive&&E.push(...j.v);return E.length?E:null}function jx(e,n,s,o=48){const i=Math.floor(e.length/3),r=Math.max(1,Math.ceil(i/o)),l=[],h=tt.norm(n),u=tt.len(n)>1e-6?s:0;for(let m=0;m<i;m+=r){const d=[e[m*3],e[m*3+1],e[m*3+2]];l.push(...d,d[0]+h[0]*u,d[1]+h[1]*u,d[2]+h[2]*u)}return l}const Ks=e=>Array.isArray(e)&&e.length===3&&e.every(n=>typeof n=="number"&&Number.isFinite(n)&&Math.abs(n)<=1e6),Sn=e=>{throw new Error(e)};function kx(e,n){(!e||typeof e.message!="string"||e.message.length>4e3||!Array.isArray(e.tracks)||e.tracks.length>100||e.additions!=null&&(!Array.isArray(e.additions)||e.additions.length>1))&&Sn("Đề xuất AI không hợp lệ."),(!Number.isFinite(e.duration)||e.duration<n.duration||e.duration>1e7)&&Sn("Thời lượng đề xuất không hợp lệ.");for(const o of e.additions||[])(!o||o.kind!=="box"||typeof o.id!="string"||!/^agent-block-[a-zA-Z0-9_-]{1,96}$/.test(o.id)||n.items.some(i=>i.id===o.id)||!Ks(o.position)||!Ks(o.scale)||o.scale.some(i=>i<.1||i>100)||typeof o.name!="string"||o.name.length>80)&&Sn("Khối Agent không hợp lệ.");const s=new Set;for(const o of e.tracks){s.has(o.subjectId)&&Sn("AI trả về track trùng lặp."),s.add(o.subjectId);const i=n.items.find(l=>l.id===o.subjectId);if(o.subjectId!=="camera"&&(!i||i.locked)&&Sn("Đối tượng không tồn tại hoặc đã khóa."),(!Array.isArray(o.keys)||!o.keys.length||o.keys.length>200)&&Sn("Số key không hợp lệ."),o.replaceRange!=null){const l=o.replaceRange;(!Number.isFinite(l.start)||!Number.isFinite(l.end)||l.start<0||l.end<=l.start||l.end>e.duration||o.keys[0].seconds!==l.start||o.keys.at(-1).seconds!==l.end)&&Sn("Đoạn sửa phải có key ở cả hai đầu."),o.keys.some(h=>h.seconds<l.start||h.seconds>l.end)&&Sn("Key nằm ngoài đoạn sửa.")}let r=-1;for(const l of o.keys)(!Number.isFinite(l.seconds)||l.seconds<0||l.seconds>e.duration||l.seconds<=r||!Ks(l.position))&&Sn("Thời điểm hoặc vị trí key không hợp lệ."),r=l.seconds,o.subjectId==="camera"?(!Ks(l.target)||!Number.isFinite(l.lens)||l.lens<14||l.lens>200||!Number.isFinite(l.roll)||Math.abs(l.roll)>36e3||l.position.every((h,u)=>Math.abs(h-l.target[u])<1e-8))&&Sn("Thông số camera không hợp lệ."):(!Ks(l.rotation)||!Ks(l.scale)||l.scale.some(h=>h<.01||h>1e3))&&Sn("Góc xoay hoặc kích thước không hợp lệ."),l.pose!==void 0&&!["Ngồi","Đứng"].includes(l.pose)&&Sn("Tư thế key không hợp lệ.")}return e}function Ec(e,n,s,o={},i=[]){const r=e.shots.find(h=>h.id===e.activeShot),l=Qh(r,s);return{placement:{camera:r.position,colliders:i.slice(0,400).map(h=>({id:h.id,itemId:h.itemId,name:h.name,kind:h.kind,min:h.min.map(u=>Math.round(u*1e3)/1e3),max:h.max.map(u=>Math.round(u*1e3)/1e3)}))},shotId:r.id,duration:r.duration,playheadSeconds:s*r.duration,selectedId:n||"camera",camera:{position:l.position,target:l.target,lens:l.lens,roll:l.roll,motion:r.motion,keys:r.cameraKeys?.map(h=>({...h,seconds:h.time*r.duration}))||[]},items:e.items.map(h=>{const u=ys(h,r,s),m=o[h.id],d=[...r.objectKeys?.[h.id]||[]].sort((y,g)=>y.time-g.time),f=d.slice(1).map((y,g)=>{const v=d[g],b=(y.time-v.time)*r.duration,k=Math.hypot(...y.position.map((w,S)=>w-v.position[S]));return{start:v.time*r.duration,end:y.time*r.duration,distance:k,speed:b>0?k/b:null}}),p=Object.entries(o).filter(([y])=>y!==h.id).map(([y,g])=>{const v=m?u.position[0]-m.min[0]:.5,b=m?m.max[0]-u.position[0]:.5,k=m?u.position[2]-m.min[2]:.5,w=m?m.max[2]-u.position[2]:.5,S=(g.min[0]+g.max[0])/2,E=(g.min[2]+g.max[2])/2,j=[[g.min[0]-b-.3,u.position[1],E],[g.max[0]+v+.3,u.position[1],E],[S,u.position[1],g.min[2]-w-.3],[S,u.position[1],g.max[2]+k+.3]];return{targetId:y,worldAxisPoints:j,nearest:j.reduce((M,T)=>Math.hypot(T[0]-u.position[0],T[2]-u.position[2])<Math.hypot(M[0]-u.position[0],M[2]-u.position[2])?T:M)}});return{motionProfile:m?.motionProfile||null,segments:f,bounds:m||null,approachPoints:p.slice(0,6),baseTransform:{position:h.position,rotation:h.rotation,scale:h.scale},...h.kind==="person"?{pose:{hipL:h.pose.hipL,hipR:h.pose.hipR,kneeL:h.pose.kneeL,kneeR:h.pose.kneeR,lean:h.pose.lean},...h.figure?{figure:h.figure}:{}}:{},...h.kind==="set"&&h.set?{set:{id:h.set.id}}:{},id:h.id,name:h.name,kind:h.kind,locked:h.locked,hidden:h.hidden,position:u.position,rotation:u.rotation,scale:u.scale,keys:r.objectKeys?.[h.id]?.map(y=>({...y,seconds:y.time*r.duration}))||[]}})}}function Oi(e,n){const s=e.shots.find(l=>l.id===e.activeShot);kx(n,{duration:s.duration,items:e.items});const o=s.duration/n.duration,i={...s,duration:n.duration,objectKeys:Object.fromEntries(Object.entries(s.objectKeys||{}).map(([l,h])=>[l,h.map(u=>({...u,time:u.time*o}))])),cameraKeys:s.cameraKeys?.map(l=>({...l,time:l.time*o})),...s.focus?.keys?{focus:{...s.focus,keys:s.focus.keys.map(l=>({...l,time:Math.min(1,l.time*o)}))}}:{}};for(const l of n.tracks){const h=u=>!l.replaceRange||u.time*n.duration<l.replaceRange.start-1e-7||u.time*n.duration>l.replaceRange.end+1e-7;if(l.subjectId==="camera"){const u=l.keys.map(f=>({id:yt(),time:f.seconds/n.duration,position:f.position,target:f.target,lens:f.lens,roll:f.roll}));i.cameraKeys=[...(i.cameraKeys||[]).filter(f=>h(f)&&!u.some(p=>Math.abs(p.time-f.time)<1e-7)),...u].sort((f,p)=>f.time-p.time);const m=i.cameraKeys[0],d=i.cameraKeys.at(-1);Object.assign(i,{motion:"path",position:m.position,target:m.target,lens:m.lens,roll:m.roll,endPosition:d.position,endTarget:d.target,endLens:d.lens,pathSmooth:s.motion==="path"?s.pathSmooth:void 0})}else{const u=l.keys.map(m=>({id:yt(),time:m.seconds/n.duration,position:m.position,rotation:m.rotation,scale:m.scale,...m.stance?{stance:m.stance}:{},...m.pose&&qn[m.pose]?{pose:{...qn[m.pose]}}:{}}));i.objectKeys[l.subjectId]=[...(i.objectKeys[l.subjectId]||[]).filter(m=>h(m)&&!u.some(d=>Math.abs(d.time-m.time)<1e-7)),...u].sort((m,d)=>m.time-d.time)}}const r=(n.additions||[]).map((l,h)=>({...An("box",e.items.length+h),id:l.id,name:l.name,position:l.position,scale:l.scale,color:"#849095"}));return{...e,items:[...e.items,...r],shots:e.shots.map(l=>l.id===s.id?i:l)}}const za=Object.freeze({oval:{vi:"Trái xoan",en:"Oval",width:1,length:1,eyes:1},round:{vi:"Tròn",en:"Round",width:1.1,length:.94,eyes:1.08},long:{vi:"Dài",en:"Long",width:.92,length:1.1,eyes:.95},square:{vi:"Vuông",en:"Square",width:1.12,length:1.02,eyes:.92},child:{vi:"Trẻ con",en:"Child",width:1.05,length:.96,eyes:1.3}}),Es=Object.freeze({width:[.85,1.2],length:[.85,1.2],eyes:[.7,1.4]}),Rc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),wx=/^#[0-9a-fA-F]{6}$/,hs=(e,n)=>{throw Object.assign(new Error(`${e}: ${n}`),{status:400})};function Ro(e={}){Rc(e)||hs("character","object");for(const u of Object.keys(e))["preset","figure","look","face","color"].includes(u)||hs("character",`unknown field "${u}"`);const n=e.preset!=null?Zh(String(e.preset)):null;e.preset!=null&&!n&&hs("character.preset","unknown character preset");const s={height:1.75,face:"simple",...n?.figure??{},...e.figure!=null?Am(e.figure,"character.figure"):{}},o=_l({...n?.look??{},...e.look!=null?_l(e.look,"character.look"):{}},"character.look");e.color!==void 0&&!(typeof e.color=="string"&&wx.test(e.color))&&hs("character.color","#rrggbb");const i=(e.color??s.skin??n?.color??Rr[2]).toLowerCase();s.skin||(s.skin=i);const r=e.face??{};Rc(r)||hs("character.face","object");for(const u of Object.keys(r))["preset","width","length","eyes"].includes(u)||hs("character.face",`unknown field "${u}"`);r.preset!==void 0&&!za[r.preset]&&hs("character.face.preset",Object.keys(za).join("|"));const l=za[r.preset??"oval"],h={preset:r.preset??"oval"};for(const[u,[m,d]]of Object.entries(Es)){const f=r[u]===void 0?l[u]:r[u];(typeof f!="number"||!Number.isFinite(f))&&hs(`character.face.${u}`,`number ${m}..${d}`),h[u]=+Math.min(d,Math.max(m,f)).toFixed(3)}return{...n?{preset:n.id}:{},figure:s,look:o,color:i,face:h}}function Mx(e){const n=JSON.stringify(e);let s=2166136261;for(let o=0;o<n.length;o++)s^=n.charCodeAt(o),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}const Sx=e=>`gen:character:${Mx(e)}`,dr={torso:"torso",head:"head",eyes:"head",eyeL:"head",eyeR:"head"};for(const e of["L","R"])Object.assign(dr,{[`arm${e}`]:`arm${e}`,[`fore${e}`]:`fore${e}`,[`wrist${e}`]:`wrist${e}`,[`hand${e}`]:`wrist${e}`,[`thigh${e}`]:`thigh${e}`,[`shin${e}`]:`shin${e}`,[`foot${e}`]:`foot${e}`});function Cx(){return{...Object.fromEntries(Object.entries(qn.Đứng).map(([n,s])=>[n,typeof s=="number"&&!/^(grip|thumb|index)/.test(n)?0:s])),lean:0,spineTwist:0,head:0,headPitch:0,headRoll:0}}function Nx(e){const n=Ht({height:1.8,head:1,build:1,...e.figure}),s=Jh(Cx(),e.color,n,e.look);s.scale.setScalar(n.height/Tm(n));const o=s.getObjectByName("head"),i=s.getObjectByName("eyes");o&&o.scale.set(o.scale.x*e.face.width,o.scale.y*e.face.length,o.scale.z*(e.face.width+1)/2),i&&i.scale.setScalar(e.face.eyes),s.updateMatrixWorld(!0);const r=M=>{for(let T=M;T;T=T.parent)if(dr[T.name])return dr[T.name];return"torso"},l=M=>s.getObjectByName(M).getWorldPosition(new ae),h=[];s.traverse(M=>{if(!(M instanceof dt)||!M.visible||!M.geometry.getAttribute("position"))return;let T=!1;for(let R=M;R;R=R.parent)R.visible||(T=!0);if(T)return;if(M instanceof zr){h.push(Tx(M));return}const N=M.geometry.clone();N.morphAttributes={};for(const R of Object.keys(N.attributes))R!=="position"&&R!=="normal"&&R!=="uv"&&N.deleteAttribute(R);N.applyMatrix4(M.matrixWorld),h.push({geo:N,material:M.material,joint:r(M),name:M.name||r(M)})});const u=new _t,m=new Map;for(const M of h){if(M.geo.computeBoundingBox(),u.union(M.geo.boundingBox),M.weights){const N=M.geo.getAttribute("position"),R=new ae;for(let A=0;A<N.count;A++){const C=La[M.weights.index[A*4]][0],O=m.get(C)??new _t;O.expandByPoint(R.fromBufferAttribute(N,A)),m.set(C,O)}continue}const T=m.get(M.joint)??new _t;T.union(M.geo.boundingBox),m.set(M.joint,T)}const d={};for(const[M]of La)s.getObjectByName(M)&&(d[M]=l(M));d.headTop=new ae(d.head.x,m.get("head").max.y,d.head.z);for(const M of["L","R"]){const T=m.get(`wrist${M}`)??new _t().setFromCenterAndSize(d[`wrist${M}`],new ae(.05,.2,.05));d[`handTip${M}`]=new ae(d[`wrist${M}`].x,T.min.y,d[`wrist${M}`].z);const N=m.get(`foot${M}`)??new _t().setFromCenterAndSize(d[`foot${M}`],new ae(.1,.1,.25));d[`toe${M}`]=new ae(d[`foot${M}`].x,N.min.y,N.max.z)}const f=u.getSize(new ae),p=2/Math.max(f.x,f.y,f.z),y=u.getCenter(new ae),g=new Nt().makeScale(p,p,p).multiply(new Nt().makeTranslation(-y.x,-u.min.y,-y.z)),v=M=>Math.round(M*1e4)/1e4,b=La.map(([M,T])=>({name:M,parent:T,pos:d[M].clone().applyMatrix4(g).toArray().map(v)})),k=ei({kind:"humanoid",source:"template",joints:b,seed:1}),w=new Map(k.joints.map((M,T)=>[M.name,T])),S=Lm(k),E=new dn;let j=0;for(const M of h){M.geo.applyMatrix4(g);const T=M.geo.getAttribute("position").count,N=w.get(M.joint)??0,R=new Uint16Array(T*4),A=new Float32Array(T*4);if(M.weights)for(let O=0;O<T*4;O++)R[O]=w.get(La[M.weights.index[O]][0])??0,A[O]=M.weights.weight[O];else for(let O=0;O<T;O++)R[O*4]=N,A[O*4]=1;M.geo.setAttribute("skinIndex",new jd(R,4)),M.geo.setAttribute("skinWeight",new zt(A,4)),M.geo.userData.rigWeights=S,M.geo.computeBoundingBox(),M.geo.computeBoundingSphere();const C=new dt(M.geo,M.material);C.name=M.name,C.castShadow=!0,C.receiveShadow=!0,E.add(C),j+=T}return E.userData.normalizedHeight=f.y*p,{root:E,rig:k,normalizedHeight:f.y*p,height:+f.y.toFixed(4),vertices:j}}const Od=new Map(La.map(([e],n)=>[e,n]));function Ax(e){if(Od.has(e))return[[e,1]];const n=/^(arm|fore|wrist|thigh|shin|foot)Half([LR])$/.exec(e);if(n){const o={arm:"torso",fore:"arm",wrist:"fore",thigh:"torso",shin:"thigh",foot:"shin"},i=o[n[1]];return[[n[1]+n[2],.5],[i==="torso"?"torso":i+n[2],.5]]}if(e==="headHalf")return[["head",.5],["torso",.5]];const s=/^(thumb|index|middle|ring|pinky)\d([LR])$/.exec(e);return s?[[`wrist${s[2]}`,1]]:/^(jaw|lid|eye|hair)/.test(e)?[["head",1]]:[["torso",1]]}function Tx(e){const n=e.geometry,s=n.getAttribute("position").count,o=new Float32Array(s*3),i=new ae,r=n.getAttribute("skinIndex"),l=n.getAttribute("skinWeight"),h=e.skeleton.bones.map(f=>f.name),u=new Uint16Array(s*4),m=new Float32Array(s*4);e.skeleton.update();for(let f=0;f<s;f++){i.fromBufferAttribute(n.getAttribute("position"),f),e.applyBoneTransform(f,i),i.applyMatrix4(e.matrixWorld),o[f*3]=i.x,o[f*3+1]=i.y,o[f*3+2]=i.z;const p=new Map;for(let v=0;v<4;v++){const b=l.getComponent(f,v);if(b)for(const[k,w]of Ax(h[r.getComponent(f,v)]??"torso")){const S=Od.get(k)??0;p.set(S,(p.get(S)??0)+b*w)}}const y=[...p].sort((v,b)=>b[1]-v[1]).slice(0,4),g=y.reduce((v,b)=>v+b[1],0)||1;y.forEach(([v,b],k)=>{u[f*4+k]=v,m[f*4+k]=b/g})}const d=new At;return d.setAttribute("position",new Rt(o,3)),n.getAttribute("color")&&d.setAttribute("color",n.getAttribute("color").clone()),d.setIndex(n.getIndex()?Array.from(n.getIndex().array):null),d.computeVertexNormals(),{geo:d,material:e.material,joint:"torso",name:e.name||"skin",weights:{index:u,weight:m}}}const Gs=new Map;function _d(e){const n=JSON.stringify(e);let s=Gs.get(n);if(!s)for(s=Nx(e),Gs.set(n,s);Gs.size>16;)Gs.delete(Gs.keys().next().value);return s}function zd(){Gs.clear()}const Ic=e=>Array.isArray(e)&&e.length===3&&e.every(n=>Number.isFinite(Number(n)))?e.map(Number):null;function _i(e,n){const s=e.getStage(),o=String(n.name||"Nhân vật").trim().slice(0,60)||"Nhân vật",i=s.items.find(f=>f.name===o&&f.kind==="model"&&f.gen?.kind==="character");let r;try{const f=i?.gen?.kind==="character"?i.gen.spec:void 0,p=Object.fromEntries(["figure","look","face","color"].filter(g=>n[g]!=null).map(g=>[g,n[g]])),y=n.face;r=Ro(n.preset!=null||!f?{...n.preset!=null?{preset:n.preset}:{},...p}:{figure:{...f.figure,...n.figure||{}},look:{...f.look,...n.look||{}},face:y?.preset?y:{...f.face,...y||{}},color:n.color??f.color})}catch(f){return{ok:!1,error:f.message}}const l=_d(r),h=l.height,u={model:{gcsUri:Sx(r),name:`${o}.character`,height:h},gen:{kind:"character",spec:r},rig:l.rig,color:r.color,...Ic(n.position)?{position:Ic(n.position)}:{},...n.yaw_deg!=null?{rotation:[0,Number(n.yaw_deg)||0,0]}:{}};let m=i?.id;if(i)e.setStage(f=>({...f,items:f.items.map(p=>p.id===i.id?{...p,...u}:p)}));else{const f=ed(s,{kind:"model",name:o,...u});m=f.id,e.setStage(p=>({...p,items:[...p.items,f]}))}const d=l.rig.joints.filter(f=>!Em(l.rig.joints,f)).map(f=>f.name);return{ok:!0,name:o,id:m,rebuilt:!!i,height_m:h,vertices:l.vertices,rig:"humanoid",bones:d,...r.preset?{preset:r.preset}:{},face:r.face,hint:"already rigged with the humanoid skeleton: set_pose, play_motion, hold_prop, set_gaze, resolve_hits and set_bone_rotation work on it; same name = rebuild with new parameters"}}const Lx=[{key:"height",vi:"Chiều cao (m)",lo:1,hi:2.1,step:.01},{key:"weight",vi:"Cân nặng (gầy → mập)",lo:-1,hi:1,step:.05},{key:"muscle",vi:"Cơ bắp",lo:0,hi:1,step:.05},{key:"posture",vi:"Dáng (thẳng → còng)",lo:0,hi:1,step:.05},{key:"shoulders",vi:"Vai",lo:.6,hi:1.6,step:.02},{key:"hips",vi:"Hông",lo:.6,hi:1.6,step:.02},{key:"sex",vi:"Giới tính (nam ↔ nữ)",lo:0,hi:1,step:.05},{key:"age",vi:"Tuổi",lo:3,hi:90,step:1}],Ex=[{key:"width",vi:"Mặt rộng",lo:Es.width[0],hi:Es.width[1],step:.01},{key:"length",vi:"Mặt dài",lo:Es.length[0],hi:Es.length[1],step:.01},{key:"eyes",vi:"Mắt to",lo:Es.eyes[0],hi:Es.eyes[1],step:.01}];function Rx({host:e,item:n,ground:s,onSelect:o,setError:i}){const r=rt(),l=w=>r==="en"?w.en:w.vi,[h,u]=I.useState(()=>Ro({preset:"office-f"})),m=(n?.gen?.kind==="character"?n.gen.spec:null)??h,d=I.useRef(void 0),f=w=>{let S;try{S=Ro({figure:{...m.figure,...w.figure||{}},look:w.look??m.look,face:{...m.face,...w.face||{}},color:w.color??m.color})}catch(E){i(E.message);return}if(!n){u(S);return}window.clearTimeout(d.current),d.current=window.setTimeout(()=>{const E=_i(e,{name:n.name,figure:S.figure,look:S.look,face:S.face,color:S.color});E.ok||i(String(E.error))},250)},p=w=>{if(!Zh(w))return;if(!n){u(Ro({preset:w}));return}const E=_i(e,{name:n.name,preset:w});E.ok||i(String(E.error))},y=()=>{const w=_i(e,{name:Ix(e,a("Nhân vật")),figure:m.figure,look:m.look,face:m.face,color:m.color,position:s()});w.ok&&w.id?o(w.id):i(String(w.error))},g=m.figure,v=(w,S,E)=>t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a(w.vi)}),t.jsx("input",{type:"range","aria-label":a(w.vi),min:w.lo,max:w.hi,step:w.step,value:S,onChange:j=>E(+j.target.value)}),t.jsx("input",{type:"number","aria-label":`${a(w.vi)} (${a("số")})`,min:w.lo,max:w.hi,step:w.step,value:S,onChange:j=>{const M=+j.target.value;Number.isFinite(M)&&E(Math.min(w.hi,Math.max(w.lo,M)))}})]},w.key),b=m.look,k=(w,S,E,j)=>{const M=b[w];return t.jsxs("div",{className:"shot-char-piece",children:[t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a(j)}),t.jsxs("select",{"aria-label":a(j),value:M?String(M[E]):"",onChange:T=>{const N=T.target.value,R={...m.look};N?R[w]={...M||{color:w==="hair"?"#2a211b":"#4a6fa5"},[E]:N}:delete R[w],f({look:R})},children:[t.jsx("option",{value:"",children:a("Không")}),Object.entries(S).map(([T,N])=>t.jsx("option",{value:T,children:l(N)},T))]})]}),M&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Màu {0}",[a(j).toLowerCase()])}),t.jsx("input",{type:"color","aria-label":a("Màu {0}",[a(j).toLowerCase()]),value:M.color,onChange:T=>f({look:{...m.look,[w]:{...M,color:T.target.value}}})})]})]},w)};return t.jsxs("div",{className:"shot-model-edit shot-char",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsxs("strong",{children:["🧍 ",n?n.name:a("Nhân vật mới")]}),t.jsx("small",{className:"muted",children:n?a("Đang sửa: thay đổi dựng lại ngay, đã gắn xương người."):a("Lưới 3D tạo từ tham số, gắn sẵn xương người: tạo dáng, chuyển động, cầm đồ ngay.")})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Mẫu nhân vật")}),t.jsxs("select",{"aria-label":a("Mẫu nhân vật"),value:m.preset??"",onChange:w=>p(w.target.value),children:[t.jsx("option",{value:"",children:a("Tự chỉnh")}),Rm.map(w=>t.jsx("option",{value:w.id,children:l(w.name)},w.id))]})]}),t.jsx("h4",{children:a("Dáng người")}),Lx.map(w=>v(w,Number(g[w.key]??(w.key==="height"?1.75:w.key==="shoulders"||w.key==="hips"?1:w.key==="sex"?+Oo(g).fem.toFixed(2):w.key==="age"?Oo(g).age:0)),S=>f({figure:{[w.key]:S}}))),t.jsx("div",{className:"shot-char-skins",role:"group","aria-label":a("Màu da"),children:Rr.map(w=>t.jsx("button",{type:"button","aria-label":w,"aria-pressed":m.color===w,className:m.color===w?"on":"",style:{background:w},onClick:()=>f({color:w,figure:{skin:w}})},w))}),t.jsx("h4",{children:a("Khuôn mặt")}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Kiểu mặt")}),t.jsx("select",{"aria-label":a("Kiểu mặt"),value:m.face.preset,onChange:w=>{const S=za[w.target.value];f({face:{preset:w.target.value,width:S.width,length:S.length,eyes:S.eyes}})},children:Object.entries(za).map(([w,S])=>t.jsx("option",{value:w,children:l(S)},w))})]}),Ex.map(w=>v(w,m.face[w.key],S=>f({face:{[w.key]:S}}))),t.jsx("h4",{children:a("Tóc & trang phục")}),k("hair",Im,"style","Tóc"),k("top",Pm,"type","Áo"),k("bottom",Fm,"type","Quần / váy"),!n&&t.jsx("button",{className:"pill-btn primary",onClick:y,children:a("+ Tạo nhân vật (đã gắn xương)")}),n&&t.jsx("small",{className:"muted",children:a("Mở tab Rigging để xoay xương, hoặc dùng thư viện chuyển động như với ma-nơ-canh.")})]})}function Ix(e,n){const s=e.getStage();let o=n,i=2;for(;s.items.some(r=>r.name===o);)o=`${n} ${i++}`;return o}let Cn=null,Gn,ps,Pc=null,Ys;const Fc=new Map,zi=new Map;let $c=Promise.resolve(),Dc=0;const Oc=160,_c=120;function Px(){if(Cn)return Cn;Cn=new Br({antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),Cn.outputColorSpace=si,Cn.toneMapping=kd,Cn.toneMappingExposure=1.15,Cn.shadowMap.enabled=!0,Cn.shadowMap.type=K0,Cn.setClearColor(0,0),Cn.setSize(Oc,_c,!1),Gn=new Kr;const e=new wd(Cn);Pc=e.fromScene(new Ed,.04).texture,e.dispose(),Gn.environment=Pc,Gn.environmentIntensity=.7,Gn.add(new Md("#e8eeff","#5d5a55",.9));const n=new ni("#fff4e4",2.4);return n.castShadow=!0,n.shadow.mapSize.set(512,512),n.shadow.bias=-4e-4,Gn.add(n,n.target),Ys=new dt(new ai(1,1),new H0({opacity:.32})),Ys.rotation.x=-Math.PI/2,Ys.receiveShadow=!0,Gn.add(Ys),ps=new Hr(28,Oc/_c,.05,2e3),Cn}function Fx(e){const n=new _t,s=new Nt;return e.updateMatrixWorld(!0),e.traverse(o=>{if(o instanceof Xs){const i=o.geometry.boundingBox??(o.geometry.computeBoundingBox(),o.geometry.boundingBox);for(let r=0;r<o.count;r++)o.getMatrixAt(r,s),n.union(i.clone().applyMatrix4(s).applyMatrix4(o.matrixWorld))}else o instanceof dt&&n.union(new _t().setFromObject(o))}),n}function $x(e){const n=Px(),s=$m(Dm(e).recipe);Gn.add(s);try{const o=Fx(s);if(o.isEmpty())throw new Error(`empty model ${e}`);const i=o.getSize(new ae),r=o.getCenter(new ae),l=Math.max(.05,i.length()/2),h=gn.degToRad(ps.fov)/2,u=l/Math.sin(h)*.98,m=new ae(.62,.42,1).normalize();ps.position.copy(r).addScaledVector(m,u),ps.near=u/100,ps.far=u*4,ps.updateProjectionMatrix(),ps.lookAt(r),Ys.position.set(r.x,o.min.y+.001,r.z),Ys.scale.setScalar(l*6);const d=Gn.children.find(p=>p instanceof ni);d.position.copy(r).add(new ae(-.6,1.4,.9).multiplyScalar(l*3)),d.target.position.copy(r);const f=d.shadow.camera;return f.left=f.bottom=-l*1.6,f.right=f.top=l*1.6,f.near=l*.1,f.far=l*8,f.updateProjectionMatrix(),n.render(Gn,ps),n.domElement.toDataURL("image/png")}finally{Gn.remove(s),s.traverse(o=>{if(o instanceof dt){o.geometry.dispose();for(const i of[o.material].flat())i.dispose()}})}}function Dx(e){const n=Fc.get(e);if(n)return Promise.resolve(n);const s=zi.get(e);if(s)return s;if(!td(e))return Promise.reject(new Error(`unknown model kit ${e}`));const o=globalThis.__CLIPOOX_THUMB_LIMIT;if(typeof o=="number"&&Dc>=o)return Promise.reject(new Error("thumbnail limit"));Dc++;const i=$c.then(()=>new Promise((r,l)=>setTimeout(()=>{try{const h=$x(e);Fc.set(e,h),r(h)}catch(h){l(h)}},16))).finally(()=>zi.delete(e));return $c=i.catch(()=>{}),zi.set(e,i),i}const Pa="claude-opus-5-5",zc=e=>`${Math.round(e/1e3).toLocaleString("vi-VN")}k đ`;function lo({quote:e,error:n}){return n?t.jsx("small",{className:"shot-hq-quote",role:"alert",children:n}):e?!Number.isFinite(e.credits?.low)||!Number.isFinite(e.credits?.high)||!e.vnd?null:t.jsx("small",{className:"shot-hq-quote",children:a("Ước tính {0}–{1} credit (≈ {2}–{3}) cho một model mới · tối đa {4} credit mỗi lượt, tính theo token dùng thật",[e.credits.low.toFixed(1),e.credits.high.toFixed(1),zc(e.vnd.low),zc(e.vnd.high),Ga])}):t.jsx("small",{className:"shot-hq-quote",children:a("Đang ước tính chi phí…")})}const Bc=[["real","Chân thật","photoreal, real materials"],["stylized","Stylized","stylized, clean shapes, saturated colours"],["lowpoly","Low-poly","low-poly, faceted (flat:true), few segments"]];function Ox({host:e,item:n,onSelect:s,setError:o}){rt();const i=nd(),[r,l]=I.useState(""),[h,u]=I.useState(""),[m,d]=I.useState("real"),[f,p]=I.useState(null),[y,g]=I.useState(null),[v,b]=I.useState(null),[k,w]=I.useState(""),[S,E]=I.useState(""),[j,M]=I.useState(!1),T=I.useRef(void 0),N=kc(n)&&n.gen?.kind==="code"?n.gen:null,R=["thinking","acting","rendering"].includes(i.phase),A=i.purpose==="model"&&(i.log.length>0||R),C=[...e.getStage().items].reverse().find(V=>kc(V));I.useEffect(()=>{g(null),b(null),w("")},[n?.id]);const O=async V=>{w("");try{g(await lg(Pa,V)),b(V)}catch(H){w(H.message)}},B=async V=>{if(!V){p(null);return}if(V.size>28e4||!["image/jpeg","image/png"].includes(V.type)){o(a("Ảnh tham chiếu phải là JPG/PNG ≤ 280 KB."));return}const H=await new Promise((G,_)=>{const ee=new FileReader;ee.onload=()=>G(String(ee.result)),ee.onerror=()=>_(ee.error),ee.readAsDataURL(V)});p({name:V.name,data:H})},D=()=>{const V=r.trim();if(!V||R)return;const H=Bc.find(_=>_[0]===m),G=`${V}
3
+ Style: ${H[2]}.${h.trim()?` Real size: ${h.trim()}.`:""}${f?" Match the attached reference photo.":""}`;i.start(G,f?.data||null,Pa,"model",{quality:"high"}),g(null),b(null)},$=()=>{const V=S.trim();if(!V||!N||R)return;const H=`Edit the code model named "${n.name}" (read_model_code, then code_model with the same name; keep everything not mentioned): ${V}`;i.purpose==="model"&&(i.phase==="done"||i.phase==="capped")&&!!i.missionId&&i.model===Pa&&i.quality==="high"?i.followUp(H):i.start(H,null,Pa,"model",{quality:"high"}),E(""),g(null),b(null)},W=(V,H)=>{if(!N||!n)return;const G={...N.code.params,[V]:H};e.setStage(_=>({..._,items:_.items.map(ee=>ee.id===n.id&&ee.gen?.kind==="code"?{...ee,gen:{...ee.gen,code:{...ee.gen.code,params:G}}}:ee)})),window.clearTimeout(T.current),T.current=window.setTimeout(()=>{wc(e,{name:n.name,params:G,views:!1}).then(_=>{_.ok||o(String(_.error))})},250)},z=async()=>{if(!(!N||!n)){M(!0);try{const V=await wc(e,{name:n.name,seed:N.code.seed%2147483e3+1,views:!1});V.ok||o(String(V.error))}finally{M(!1)}}},Y=async()=>{if(!(!N||!n)){M(!0);try{const V=await wg(N.code),H=URL.createObjectURL(V),G=document.createElement("a");G.href=H,G.download=`${n.name.replace(/[^\p{L}\p{N}_-]+/gu,"_")||"model"}.glb`,G.click(),window.setTimeout(()=>URL.revokeObjectURL(H),4e3)}catch(V){o(V.message)}finally{M(!1)}}},J=A&&t.jsxs("div",{className:"shot-hq-progress",role:"log",children:[t.jsxs("div",{className:"shot-mission-status",children:[t.jsx("b",{className:"shot-hq-badge",children:a("Chất lượng cao · Opus")}),R?a("Đang dựng…"):i.phase==="capped"?a("Đã dùng hết {0} credit của lượt này",[Ga]):i.phase==="done"?a("Xong"):i.phase==="error"?a("Lỗi"):i.phase==="cancelled"?a("Đã dừng"):""," · ",a("bước")," ",i.step," · ",i.spent.toFixed(2),i.budget!=null?` / ${i.budget}`:""," cr"]}),i.log.slice(-6).map((V,H)=>t.jsx("div",{className:"shot-mission-line",children:V},H)),i.phase==="capped"&&t.jsx("div",{className:"shot-mission-done",role:"status",children:a('Lượt này đã dùng hết {0} credit nên Agent dừng lại; model đang có vẫn giữ nguyên. Gõ yêu cầu ở ô "Sửa bằng lời" để làm tiếp (thêm {0} credit).',[Ga])}),i.error&&t.jsx("p",{role:"alert",children:i.error}),R&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>i.stop(),children:a("Dừng")}),!R&&!N&&C&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(C.id),children:a("Chỉnh model vừa dựng: {0}",[C.name])})]});return N&&n?t.jsxs("div",{className:"shot-hq-panel",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsx("strong",{children:n.name}),t.jsx("small",{className:"muted",children:a("Model dựng bằng code · Opus")})]}),N.prompt&&t.jsx("small",{className:"muted shot-hq-prompt",children:N.prompt}),(N.schema||[]).length>0?t.jsx("div",{className:"shot-model-params",children:(N.schema||[]).map(V=>t.jsx(_x,{p:V,value:N.code.params[V.key]??V.default,onChange:H=>W(V.key,H)},V.key))}):t.jsx("small",{className:"muted",children:a("Model này không có thanh trượt tham số.")}),t.jsx("small",{className:"muted",children:a("Kéo thanh trượt để dựng lại ngay trên máy: không gọi AI, 0 credit.")}),t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:j,onClick:()=>void z(),children:a("Biến thể khác (0 credit)")}),t.jsx("button",{type:"button",className:"pill-btn thin",disabled:j,onClick:()=>void Y(),children:a("Tải .glb")})]}),t.jsxs("label",{className:"shot-hq-field",children:[t.jsx("span",{children:a("Sửa bằng lời (AI · Opus)")}),t.jsx("textarea",{rows:3,maxLength:1500,value:S,disabled:R,placeholder:a("Ví dụ: cổ chai dài hơn, thêm nắp nhôm, nhãn màu xanh lá"),onChange:V=>{E(V.target.value),v!=="edit"&&g(null)}})]}),v==="edit"&&y?t.jsx(lo,{quote:y}):k?t.jsx(lo,{quote:null,error:k}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:R||!S.trim(),onClick:()=>void O("edit"),children:a("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:R||!S.trim()||v!=="edit",title:v!=="edit"?a("Xem ước tính chi phí trước"):"",onClick:$,children:a("Sửa (≈ {0}–{1} cr)",[y?.credits.low.toFixed(1)??"?",y?.credits.high.toFixed(1)??"?"])})]}),J,t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(null),children:a("+ Dựng model mới")})]}):t.jsxs("div",{className:"shot-hq-panel",children:[t.jsxs("label",{className:"shot-hq-field",children:[t.jsx("span",{children:a("Mô tả model")}),t.jsx("textarea",{rows:4,maxLength:3e3,value:r,disabled:R,placeholder:a("Ví dụ: chai nước hoa thuỷ tinh 50 ml, thân vuông bo góc, nắp vàng xước, nước màu hồng nhạt"),onChange:V=>l(V.target.value)})]}),t.jsxs("div",{className:"shot-hq-row",children:[t.jsxs("label",{className:"shot-hq-field small",children:[t.jsx("span",{children:a("Kích thước thật (tuỳ chọn)")}),t.jsx("input",{value:h,maxLength:80,disabled:R,placeholder:a("vd: cao 12 cm"),onChange:V=>u(V.target.value)})]}),t.jsxs("label",{className:"shot-hq-field small",children:[t.jsx("span",{children:a("Phong cách")}),t.jsx("select",{value:m,disabled:R,onChange:V=>d(V.target.value),children:Bc.map(([V,H])=>t.jsx("option",{value:V,children:a(H)},V))})]})]}),t.jsxs("div",{className:"shot-hq-row",children:[t.jsxs("label",{className:"shot-mission-ref",children:[t.jsx("input",{type:"file",accept:"image/jpeg,image/png",hidden:!0,disabled:R,onChange:V=>{B(V.target.files?.[0]),V.target.value=""}}),t.jsx("span",{children:f?`🖼 ${f.name}`:a("+ Ảnh tham chiếu (tuỳ chọn)")})]}),f&&!R&&t.jsx("button",{type:"button",onClick:()=>p(null),children:"×"})]}),v==="build"&&y?t.jsx(lo,{quote:y}):k?t.jsx(lo,{quote:null,error:k}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:R||!r.trim(),onClick:()=>void O("build"),children:a("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:R||!r.trim()||v!=="build",title:v!=="build"?a("Xem ước tính chi phí trước"):"",onClick:D,children:a("Dựng (≈ {0}–{1} cr)",[y?.credits.low.toFixed(1)??"?",y?.credits.high.toFixed(1)??"?"])})]}),J]})}function _x({p:e,value:n,onChange:s}){return e.type==="num"?t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"range",min:e.min,max:e.max,step:e.step,value:Number(n),onChange:o=>s(Number(o.target.value))}),t.jsx("output",{children:Number(n).toFixed(e.step<1?Math.min(3,Math.max(0,-Math.floor(Math.log10(e.step)))):0)})]}):e.type==="bool"?t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"checkbox",checked:!!n,onChange:o=>s(o.target.checked)})]}):e.type==="choice"?t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("select",{value:String(n),onChange:o=>s(o.target.value),children:e.options.map(o=>t.jsx("option",{value:o,children:o},o))})]}):t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"color",value:String(n),onChange:o=>s(o.target.value)}),t.jsx("output",{children:String(n)})]})}function zx({host:e,item:n,ground:s,onSelect:o,setError:i}){rt();const[r,l]=I.useState("Sản phẩm"),[h,u]=I.useState(""),[m,d]=I.useState(null),[f,p]=I.useState(null),[y,g]=I.useState([]),[v,b]=I.useState(""),[k,w]=I.useState(null),S=async(A,C)=>{if(A){if(!/^image\/(png|jpeg|webp)$/.test(A.type)){i(a("Ảnh phải là PNG, JPG hoặc WEBP."));return}b(a("Đang tải ảnh lên…"));try{const O=await Vs(A,void 0,"image");C({name:A.name,url:O.url})}catch(O){i(O.message)}finally{b("")}}},E=A=>Number(String(A).replace(",","."))/100,j=async()=>{if(!m){i(a("Chọn ảnh chính diện của sản phẩm."));return}if(!(E(h)>0)){i(a("Nhập chiều cao thật của sản phẩm (cm)."));return}b(a("Đang dựng sản phẩm…")),w(null);try{const{modelProduct:A}=await nn(async()=>{const{modelProduct:O}=await import("./productTools-DlC5vWjx.js");return{modelProduct:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),C=await A({image:m.url,...f?{back_image:f.url}:{},height_m:E(h),name:r.trim()||"Sản phẩm",position:s(),labels:y.filter(O=>O.url&&E(O.height)>0).map(O=>({image:O.url,bottom_m:E(O.bottom)||0,height_m:E(O.height),center_deg:Number(O.side),finish:O.finish}))},e);C.ok?C.id&&o(String(C.id)):i(String(C.error))}finally{b("")}},M=async()=>{if(n){b(a("Đang xuất GLB…"));try{const{saveGlb:A}=await nn(async()=>{const{saveGlb:O}=await import("./productTools-DlC5vWjx.js");return{saveGlb:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),C=await A({name:n.name},e);C.ok?w({file:String(C.file),url:String(C.url)}):i(String(C.error))}finally{b("")}}},T=async()=>{if(n?.set){b(a("Đang xuất GLB…"));try{const{recipeGlb:A}=await nn(async()=>{const{recipeGlb:W}=await import("./exportGlb-BeLpJKJT.js");return{recipeGlb:W}},__vite__mapDeps([17,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),{loadSetOf:C}=await nn(async()=>{const{loadSetOf:W}=await import("./remote-CpkPQOQH.js").then(z=>z.fO);return{loadSetOf:W}},__vite__mapDeps([2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16])),O=e.engine()?.setRecipe(n.set.id)??await C(e)(n.set.id),B=await A(O),D=document.createElement("a"),$=URL.createObjectURL(B);D.href=$,D.download=`${n.name}.glb`,D.click(),setTimeout(()=>URL.revokeObjectURL($),5e3)}catch(A){i(A.message)}finally{b("")}}},N=(A,C,O)=>t.jsxs("label",{className:"shot-product-pick",children:[t.jsx("span",{children:A}),t.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",onChange:B=>void S(B.target.files?.[0],O)}),C?t.jsx("img",{src:C.url,alt:""}):t.jsx("em",{children:a("Chưa chọn")})]}),R=(A,C)=>g(O=>O.map(B=>B.key===A?{...B,...C}:B));return t.jsxs("div",{className:"shot-product",children:[t.jsx("p",{className:"shot-product-hint",children:a("Ảnh sản phẩm chụp thẳng, nền trơn (hoặc PNG trong suốt) cho dáng và màu; file thiết kế nhãn cho bao bì sắc nét, đúng kích thước.")}),t.jsxs("label",{className:"shot-product-row",children:[t.jsx("span",{children:a("Tên")}),t.jsx("input",{value:r,onChange:A=>l(A.target.value)})]}),t.jsxs("label",{className:"shot-product-row",children:[t.jsx("span",{children:a("Chiều cao thật (cm)")}),t.jsx("input",{inputMode:"decimal",value:h,placeholder:"29",onChange:A=>u(A.target.value)})]}),N(a("Ảnh chính diện"),m,d),N(a("Ảnh mặt sau (không bắt buộc)"),f,p),t.jsxs("div",{className:"shot-product-labels",children:[t.jsx("b",{children:a("File thiết kế nhãn / bao bì")}),y.map(A=>t.jsxs("div",{className:"shot-product-label",children:[A.url?t.jsx("img",{src:A.url,alt:""}):t.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",onChange:C=>void S(C.target.files?.[0],O=>O&&R(A.key,{url:O.url,name:O.name}))}),t.jsxs("label",{children:[a("Đáy nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:A.bottom,onChange:C=>R(A.key,{bottom:C.target.value})})]}),t.jsxs("label",{children:[a("Cao nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:A.height,onChange:C=>R(A.key,{height:C.target.value})})]}),t.jsxs("label",{children:[a("Mặt"),t.jsxs("select",{value:A.side,onChange:C=>R(A.key,{side:C.target.value}),children:[t.jsx("option",{value:"0",children:a("Trước")}),t.jsx("option",{value:"180",children:a("Sau")})]})]}),t.jsxs("label",{children:[a("Bề mặt"),t.jsxs("select",{value:A.finish,onChange:C=>R(A.key,{finish:C.target.value}),children:[t.jsx("option",{value:"matte",children:a("Giấy mờ")}),t.jsx("option",{value:"gloss",children:a("Bóng")}),t.jsx("option",{value:"foil",children:a("Nhũ kim loại")})]})]}),t.jsx("button",{type:"button",onClick:()=>g(C=>C.filter(O=>O.key!==A.key)),children:"✕"})]},A.key)),t.jsxs("button",{type:"button",onClick:()=>g(A=>[...A,{key:Date.now(),name:"",url:"",bottom:"",height:"",side:"0",finish:"matte"}]),children:["+ ",a("Thêm nhãn")]})]}),t.jsx("button",{type:"button",className:"shot-product-build",disabled:!!v,onClick:()=>void j(),children:a("Dựng sản phẩm")}),n?.set&&t.jsxs("div",{className:"shot-product-export",children:[t.jsx("button",{type:"button",disabled:!!v,onClick:()=>void M(),children:a("Lưu GLB vào Tài sản của tôi")}),t.jsx("button",{type:"button",disabled:!!v,onClick:()=>void T(),children:a("Tải .glb")}),k&&t.jsxs("span",{children:[a("Đã lưu")," ",k.file]})]}),v&&t.jsx("p",{className:"shot-product-busy",children:v})]})}function Bd(){return t.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M12 2.8 20 7.4v9.2L12 21.2 4 16.6V7.4z"}),t.jsx("path",{d:"m4 7.4 8 4.6 8-4.6M12 12v9.2"}),t.jsx("circle",{cx:"12",cy:"12",r:"1.3",fill:"currentColor"})]})}const Kc={oak:["Gỗ sồi","Oak"],walnut:["Gỗ óc chó","Walnut"],painted_wood:["Gỗ sơn","Painted wood"],concrete:["Bê tông","Concrete"],polished_concrete:["Bê tông mài","Polished concrete"],plaster:["Tường sơn","Plaster"],brick_red:["Gạch đỏ","Red brick"],brick_white:["Gạch sơn trắng","White brick"],tile_small:["Gạch nhỏ","Small tiles"],tile_medium:["Gạch 30 cm","Medium tiles"],tile_large:["Gạch 60 cm","Large tiles"],marble:["Đá cẩm thạch","Marble"],terrazzo:["Đá mài","Terrazzo"],linen:["Vải lanh","Linen"],velvet:["Nhung","Velvet"],leather:["Da","Leather"],carpet:["Thảm","Carpet"],glass_clear:["Kính trong","Clear glass"],glass_frosted:["Kính mờ","Frosted glass"],brushed_steel:["Inox xước","Brushed steel"],chrome:["Crôm","Chrome"],gold:["Vàng / đồng","Gold / brass"],plastic_matte:["Nhựa mờ","Matte plastic"],plastic_glossy:["Nhựa bóng","Glossy plastic"],rubber:["Cao su","Rubber"],asphalt:["Nhựa đường","Asphalt"],paving:["Gạch lát vỉa hè","Paving"],grass:["Cỏ","Grass"],soil:["Đất","Soil"],sand:["Cát","Sand"],water:["Nước","Water"],roof_tiles:["Ngói","Roof tiles"],ceramic:["Gốm sứ","Ceramic"],paper:["Giấy / bìa","Paper / cardboard"]},Bx=[.01,.05,.1,.25,.5],Kx={box:["hộp","box"],cylinder:["trụ","cylinder"],cone:["nón","cone"],sphere:["cầu","sphere"],stairs:["bậc thang","stairs"],lathe:["khối tiện","lathe"],extrude:["khối đùn","extrusion"],slab:["tấm bo tròn","rounded plate"],svg:["hình SVG đùn","SVG extrusion"]};function Hx(e){const{stage:n,selected:s}=e,o=n.items.find(m=>m.id===s&&m.kind==="set"&&m.set),i=n.items.find(m=>m.id===s&&m.kind==="model"&&m.gen?.kind==="character"),r=n.items.find(m=>m.id===s&&m.kind==="model"&&m.gen?.kind==="code"),[l,h]=I.useState(r?"ai":i?"character":o?.set?.kit?.id===Ea?"hand":"library");I.useEffect(()=>{o?.set?.kit&&h(o.set.kit.id===Ea?"hand":"library")},[o?.id,o?.set?.kit?.id]),I.useEffect(()=>{i&&h("character")},[i?.id]),I.useEffect(()=>{r&&h("ai")},[r?.id]);const u={getStage:e.getStage,setStage:e.change,engine:()=>e.engine};return t.jsxs("div",{className:"shot-panel-body shot-modeling",role:"region","aria-label":a("Dựng model"),children:[t.jsx("div",{className:"shot-model-tabs",role:"tablist",children:["library","hand",...sd()||i?["character"]:[],"product"].map(m=>t.jsx("button",{role:"tab","aria-selected":l===m,className:l===m?"on":"",onClick:()=>h(m),children:m==="library"?a("Thư viện model"):m==="hand"?a("Dựng tay"):m==="character"?a("Nhân vật"):a("Sản phẩm từ ảnh")},m))}),t.jsxs("button",{type:"button",className:`shot-model-ai-tab${l==="ai"?" on":""}`,"aria-pressed":l==="ai",onClick:()=>h("ai"),children:["✦ ",a("AI chất lượng cao")]}),l==="library"?t.jsx(Wx,{...e,host:u,item:o?.set?.kit&&o.set.kit.id!==Ea?o:void 0}):l==="hand"?t.jsx(Qx,{...e,item:o?.set?.kit?.id===Ea?o:void 0}):l==="character"?t.jsx(Rx,{host:u,item:i,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):l==="product"?t.jsx(zx,{host:u,item:o,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):t.jsx(Ox,{host:u,item:r,ground:e.ground,onSelect:e.onSelect,setError:e.setError}),o&&l!=="character"&&l!=="ai"&&l!=="product"&&t.jsx(Ux,{item:o,change:e.change})]})}function Wx({host:e,item:n,ground:s,onSelect:o,setError:i}){const r=rt(),l=C=>r==="en"?C.en:C.vi,[h,u]=I.useState("all"),[m,d]=I.useState(""),[f,p]=I.useState(null),[y,g]=I.useState({}),[v,b]=I.useState(!1),k=n?.set?.kit,w=td(k?.id??f??""),[S,E]=I.useState({});I.useEffect(()=>E({}),[k?.params]);const j=k?{...k.params,...S}:y,M=I.useRef(void 0),T=(C,O)=>{if(!w)return;const B={...j,[C]:O};if(!k){g(B);return}E(D=>({...D,[C]:O})),window.clearTimeout(M.current),M.current=window.setTimeout(()=>{Bl(e,{kit:w.id,params:B,name:n.name}).then(D=>{D.ok||i(String(D.error))})},280)},N=async()=>{if(w){b(!0);try{const C=await Bl(e,{kit:w.id,params:y,name:Hd(e.getStage(),l(w)),position:s()});C.ok?o(String(C.id)):i(String(C.error))}catch(C){i(C.message)}finally{b(!1)}}},R=I.useMemo(()=>Om(m,h),[m,h]),A=async()=>{if(n?.set){b(!0);try{const{recipeGlb:C}=await nn(async()=>{const{recipeGlb:z}=await import("./exportGlb-BeLpJKJT.js");return{recipeGlb:z}},__vite__mapDeps([17,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),{loadSetOf:O}=await nn(async()=>{const{loadSetOf:z}=await import("./remote-CpkPQOQH.js").then(Y=>Y.fO);return{loadSetOf:z}},__vite__mapDeps([2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16])),B=e.engine()?.setRecipe(n.set.id)??await O(e)(n.set.id),D=await C(B),$=document.createElement("a"),W=URL.createObjectURL(D);$.href=W,$.download=`${n.name}.glb`,$.click(),setTimeout(()=>URL.revokeObjectURL(W),5e3)}catch(C){i(C.message)}finally{b(!1)}}};return w?t.jsxs("div",{className:"shot-model-edit",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsxs("button",{className:"pill-btn thin",onClick:()=>{k&&o(null),p(null)},children:["← ",a("Thư viện")]}),t.jsx(Hc,{id:w.id,alt:l(w),small:!0}),t.jsx("strong",{children:l(w)}),k&&t.jsx("small",{className:"muted",children:a("Đang sửa: {0}",[n.name])})]}),t.jsx("div",{className:"shot-model-params",children:w.params.map(C=>t.jsx(Gx,{spec:C,value:j[C.key]??zl(w.id)[C.key],locale:r,onChange:O=>T(C.key,O)},C.key))}),w.desc&&t.jsx("small",{className:"muted shot-model-desc",children:l(w.desc)}),!k&&t.jsx("button",{className:"pill-btn primary",disabled:v,onClick:()=>void N(),children:v?a("Đang dựng model…"):a("Thêm vào cảnh")}),k&&t.jsx("button",{className:"pill-btn thin",disabled:v,onClick:()=>void A(),children:v?a("Đang xuất GLB…"):a("Xuất GLB")}),t.jsx("small",{className:"muted",children:k?a("Thay đổi được dựng lại ngay trên cảnh. Kích thước tính bằng mét thật."):a("Model đặt ở giữa khung nhìn, mặt trước hướng +Z. Kích thước tính bằng mét thật.")})]}):t.jsxs("div",{className:"shot-model-lib",children:[t.jsx("input",{type:"search",className:"shot-model-search","aria-label":a("Tìm model"),placeholder:a("Tìm: nhà phố, sofa, ô tô…"),value:m,onChange:C=>d(C.target.value)}),t.jsx("div",{className:"shot-model-groups",role:"group","aria-label":a("Nhóm model"),children:[{id:"all",vi:"Tất cả",en:"All"},..._m].map(C=>t.jsx("button",{className:`pill-btn thin${h===C.id?" on":""}`,"aria-pressed":h===C.id,onClick:()=>u(C.id),children:l(C)},C.id))}),t.jsxs("div",{className:"shot-model-grid",children:[R.map(C=>t.jsxs("button",{className:"shot-model-card","aria-label":`${a("Chọn model")} ${l(C)}`,onClick:()=>{p(C.id),g(zl(C.id))},children:[t.jsx(Hc,{id:C.id,alt:""}),t.jsx("strong",{children:l(C)}),t.jsxs("small",{children:[C.params.length," ",a("tham số")]})]},C.id)),!R.length&&t.jsx("p",{className:"muted",children:a("Không có model nào khớp.")})]})]})}function Hc({id:e,alt:n,small:s}){const[o,i]=I.useState(null),[r,l]=I.useState(!1),h=I.useRef(null);I.useEffect(()=>{if(r||!h.current||typeof IntersectionObserver>"u"){r||l(!0);return}const m=new IntersectionObserver(d=>{d.some(f=>f.isIntersecting)&&(l(!0),m.disconnect())},{rootMargin:"160px"});return m.observe(h.current),()=>m.disconnect()},[r]),I.useEffect(()=>{if(!r)return;let m=!0;return i(null),Dx(e).then(d=>{m&&i(d)}).catch(()=>{}),()=>{m=!1}},[r,e]);const u=`shot-model-thumb${s?" small":""}`;return o?t.jsx("img",{className:u,src:o,alt:n,draggable:!1,"data-kit":e}):t.jsx("span",{ref:h,className:`${u} loading`,role:n?"img":void 0,"aria-label":n||void 0,"aria-hidden":n?void 0:!0,children:t.jsx(Bd,{})})}function Gx({spec:e,value:n,locale:s,onChange:o}){const i=s==="en"?e.en:e.vi;if(e.type==="num"||e.type==="int"){const r=Number(n);return t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("input",{type:"range","aria-label":i,min:e.min,max:e.max,step:e.step,value:r,onChange:l=>o(+l.target.value)}),t.jsx("input",{type:"number","aria-label":`${i} (${a("số")})`,min:e.min,max:e.max,step:e.step,value:r,onChange:l=>{const h=+l.target.value;Number.isFinite(h)&&o(Math.min(e.max,Math.max(e.min,h)))}})]})}if(e.type==="choice"&&e.swatches){const r=e.swatches;return t.jsxs("div",{className:"shot-model-param shot-model-palettes",role:"radiogroup","aria-label":i,children:[t.jsx("span",{children:i}),e.options.map(l=>t.jsxs("button",{type:"button",role:"radio","aria-checked":n===l.id,"aria-label":s==="en"?l.en:l.vi,className:n===l.id?"on":"",onClick:()=>o(l.id),children:[t.jsx("i",{children:(r[l.id]??[]).map((h,u)=>t.jsx("b",{style:{background:h}},u))}),t.jsx("small",{children:s==="en"?l.en:l.vi})]},l.id))]})}return e.type==="choice"?t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("select",{"aria-label":i,value:String(n),onChange:r=>o(r.target.value),children:e.options.map(r=>t.jsx("option",{value:r.id,children:s==="en"?r.en:r.vi},r.id))})]}):e.type==="material"?t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("select",{"aria-label":i,value:String(n),onChange:r=>o(r.target.value),children:e.allowed.map(r=>t.jsx("option",{value:r,children:qx(r,s)},r))})]}):e.type==="toggle"?t.jsxs("label",{className:"shot-model-param shot-model-toggle",children:[t.jsx("span",{children:i}),t.jsx("input",{type:"checkbox","aria-label":i,checked:n===!0,onChange:r=>o(r.target.checked)})]}):e.type==="text"?t.jsxs("label",{className:"shot-model-param shot-model-text",children:[t.jsx("span",{children:i}),t.jsx("textarea",{"aria-label":i,rows:2,maxLength:e.max,value:String(n),onChange:r=>o(r.target.value)})]}):t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("input",{type:"color","aria-label":i,value:String(n),onChange:r=>o(r.target.value)})]})}const qx=(e,n)=>Kc[e]?Kc[e][n==="en"?1:0]:e;function Kd({value:e,onChange:n,label:s,none:o}){const i=rt();return t.jsxs("select",{"aria-label":s,value:e,onChange:r=>n(r.target.value),children:[o&&t.jsx("option",{value:"",children:o}),ad.map(r=>t.jsx("optgroup",{label:i==="en"?r.en:r.vi,children:Bm.filter(l=>l.cat===r.id).map(l=>t.jsx("option",{value:l.id,children:Ra(l,i==="en"?"en":"vi")},l.id))},r.id))]})}function Ux({item:e,change:n}){const s=e.materials?.[Js]?.preset??"";return t.jsxs("label",{className:"shot-model-param shot-model-whole",children:[t.jsx("span",{children:a("Vật liệu cả model")}),t.jsx(Kd,{label:a("Vật liệu cả model"),value:s,none:a("Theo từng khối"),onChange:o=>n(i=>Us(i,e.id,Js,o?{preset:o}:null))})]})}function Hd(e,n){let s=n,o=2;for(;e.items.some(i=>i.name===s);)s=`${n} ${o++}`;return s}const Wc={box:()=>({shape:"box",name:"Hộp",size:[1,1,1],position:[0,0,0],rotation:[0,0,0],look:{preset:"painted_wood"}}),cylinder:()=>({shape:"cylinder",name:"Trụ",size:[.5,1,.5],position:[0,0,0],rotation:[0,0,0],look:{preset:"concrete"}}),cone:()=>({shape:"cone",name:"Nón",size:[.8,1,.8],position:[0,0,0],rotation:[0,0,0],look:{preset:"plastic_matte"}}),sphere:()=>({shape:"sphere",name:"Cầu",size:[.8,.8,.8],position:[0,0,0],rotation:[0,0,0],look:{preset:"plastic_matte"}}),stairs:()=>({shape:"stairs",name:"Bậc thang",size:[1.2,1.5,2.5],steps:9,position:[0,0,0],rotation:[0,0,0],look:{preset:"concrete"}}),wall_door:()=>({shape:"extrude",name:"Tường có cửa",outline:[[-2,0],[2,0],[2,3],[-2,3]],holes:[[[-.45,0],[.45,0],[.45,2.1],[-.45,2.1]]],depth:.2,position:[0,0,0],rotation:[0,0,0],look:{preset:"painted_wood"}}),wall_window:()=>({shape:"extrude",name:"Tường có cửa sổ",outline:[[-2,0],[2,0],[2,3],[-2,3]],holes:[[[-.7,.9],[.7,.9],[.7,2.2],[-.7,2.2]]],depth:.2,position:[0,0,0],rotation:[0,0,0],look:{preset:"painted_wood"}}),cut_box:()=>({shape:"box",name:"Khoét",size:[.5,.5,2],position:[0,.25,0],rotation:[0,0,0],op:"subtract"}),cut_cylinder:()=>({shape:"cylinder",name:"Lỗ tròn",size:[.4,2,.4],position:[0,-.5,0],rotation:[0,0,0],op:"subtract"}),arch:()=>({shape:"extrude",name:"Cổng vòm",outline:[[-1.5,0],[1.5,0],[1.5,3.2],[-1.5,3.2]],holes:[[[-.8,0],[.8,0],[.8,1.8],...Array.from({length:9},(e,n)=>{const s=(n+1)*Math.PI/10;return[+(.8*Math.cos(s)).toFixed(3),+(1.8+.8*Math.sin(s)).toFixed(3)]}),[-.8,1.8]]],depth:.4,position:[0,0,0],rotation:[0,0,0],look:{preset:"brick_white"}})},Xx=[["box","Hộp"],["cylinder","Trụ"],["cone","Nón"],["sphere","Cầu"],["stairs","Bậc thang"],["wall_door","Tường có cửa"],["wall_window","Tường có cửa sổ"],["arch","Cổng vòm"],["cut_box","Khoét hộp"],["cut_cylinder","Khoét lỗ tròn"]],Vx={union:"Hợp (gộp vào)",subtract:"Trừ (khoét)",intersect:"Giao (giữ phần chung)"},Yx={union:"gộp vào",subtract:"khoét",intersect:"giao với"};function Qx({stage:e,change:n,engine:s,onSelect:o,ground:i,setError:r,item:l}){const h=rt(),[u,m]=I.useState(null),[d,f]=I.useState(0),[p,y]=I.useState(.05),g=l?.set?.id;I.useEffect(()=>{f(0),m(g?s?.setRecipe(g)??null:null)},[g,s]);const v=I.useRef(void 0),b=(A,C=l)=>{if(!C?.set)return;let O;try{O=Kl(A)}catch(D){r(D.message);return}m(O),s?.cacheSet(C.set.id,O);const B=Hl(O);n(D=>({...D,items:D.items.map($=>$.id===C.id?{...$,set:{...$.set,parts:O.parts.length,min:B.min,max:B.max}}:$)})),window.clearTimeout(v.current),v.current=window.setTimeout(()=>{vc(C.set.id,C.name,O).catch(D=>r(D.message))},400)},k=async()=>{const A=crypto.randomUUID(),C=Hd(e,a("Model tự dựng")),O=Kl({v:1,parts:[Wc.box()]});try{await vc(A,C,O)}catch($){r($.message);return}s?.cacheSet(A,O);const B=Hl(O),D=ed(e,{kind:"set",name:C,color:"#9aa3a8",position:i(),set:{id:A,name:C,parts:1,min:B.min,max:B.max,kit:{id:Ea,params:{}}}});n($=>({...$,items:[...$.items,D]})),o(D.id)};if(!l||!u)return t.jsxs("div",{className:"shot-model-hand-empty",children:[t.jsx("p",{className:"muted",children:a("Tự dựng model từ khối cơ bản: hộp, trụ, nón, cầu, bậc thang, tường có cửa, cổng vòm. Mọi kích thước tính bằng mét.")}),t.jsx("button",{className:"pill-btn primary",onClick:()=>void k(),children:a("+ Tạo model mới")}),l&&!u&&t.jsx("p",{className:"muted",children:a("Đang tải model…")})]});const w=u.parts,S=w[Math.min(d,w.length-1)],E=A=>+(Math.round(A/p)*p).toFixed(3),j=A=>b({...u,parts:w.map((C,O)=>O===d?{...C,...A}:C)}),M=A=>{const C=Wc[A]();b({...u,parts:[...w,C]}),f(w.length)},T=(A,C,O,B=-500)=>t.jsxs("div",{className:"shot-model-vec",children:[t.jsx("span",{children:A}),["X","Y","Z"].map((D,$)=>t.jsx("input",{type:"number",step:p,"aria-label":`${A} ${D}`,value:C[$],onChange:W=>{const z=+W.target.value;if(!Number.isFinite(z))return;const Y=[...C];Y[$]=Math.max(B,E(z)),O(Y)}},D))]}),N=A=>{const C=(A.outline||[]).map(B=>B[0]),O=(A.outline||[]).map(B=>B[1]);return[+(Math.max(...C)-Math.min(...C)).toFixed(3),+(Math.max(...O)-Math.min(...O)).toFixed(3),A.depth||.2]},R=(A,C)=>{const[O,B]=N(A),D=C[0]/(O||1),$=C[1]/(B||1),W=z=>z.map(([Y,J])=>[+(Y*D).toFixed(3),+(J*$).toFixed(3)]);return{outline:W(A.outline||[]),holes:A.holes?.map(W),depth:Math.max(.005,C[2])}};return t.jsxs("div",{className:"shot-model-hand",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsxs("strong",{children:["✎ ",l.name]}),t.jsxs("small",{className:"muted",children:[w.length," ",a("khối")]}),t.jsxs("label",{className:"shot-model-snap",children:[a("Bước lưới"),t.jsx("select",{"aria-label":a("Bước lưới"),value:p,onChange:A=>y(+A.target.value),children:Bx.map(A=>t.jsx("option",{value:A,children:A<.1?`${A*100} cm`:`${A} m`},A))})]})]}),t.jsx("div",{className:"shot-model-add",role:"group","aria-label":a("Thêm khối"),children:Xx.map(([A,C])=>t.jsxs("button",{className:"pill-btn thin",onClick:()=>M(A),children:["+ ",a(C)]},A))}),t.jsx("ul",{className:"shot-model-parts","aria-label":a("Các khối"),children:w.map((A,C)=>t.jsx("li",{children:t.jsxs("button",{className:C===d?"on":"",onClick:()=>f(C),children:[A.name||A.shape," ",t.jsx("small",{children:Kx[A.shape]?.[h==="en"?1:0]??A.shape})]})},C))}),S&&t.jsxs("div",{className:"shot-model-part",children:[t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Tên khối")}),t.jsx("input",{"aria-label":a("Tên khối"),maxLength:40,value:S.name||"",onChange:A=>j({name:A.target.value.slice(0,40)})})]}),S.shape==="extrude"?T(a("Rộng / cao / dày (m)"),N(S),A=>j(R(S,A)),.005):T(a("Kích thước (m)"),S.size||[1,1,1],A=>j({size:A.map(C=>Math.max(.005,C))}),.005),T(a("Vị trí (m)"),S.position,A=>j({position:A})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Xoay quanh trục đứng (°)")}),t.jsx("input",{type:"number","aria-label":a("Xoay quanh trục đứng (°)"),step:15,value:S.rotation[1],onChange:A=>{const C=+A.target.value;Number.isFinite(C)&&j({rotation:[S.rotation[0],Math.max(-360,Math.min(360,C)),S.rotation[2]]})}})]}),S.shape==="stairs"&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Số bậc")}),t.jsx("input",{type:"number","aria-label":a("Số bậc"),min:2,max:80,value:S.steps||10,onChange:A=>j({steps:Math.max(2,Math.min(80,Math.round(+A.target.value)||2))})})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Phép khối")}),t.jsxs("select",{"aria-label":a("Phép khối"),value:S.op||"",onChange:A=>{const C=A.target.value||void 0;j(C?{op:C}:{op:void 0,target:void 0})},children:[t.jsx("option",{value:"",children:a("Khối thường")}),zm.map(A=>t.jsx("option",{value:A,children:a(Vx[A])},A))]})]}),S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Tác động lên")}),t.jsxs("select",{"aria-label":a("Tác động lên"),value:S.target||"",onChange:A=>j({target:A.target.value||void 0}),children:[t.jsx("option",{value:"",children:a("Khối liền trước")}),w.slice(0,d).filter(A=>!A.op&&A.name&&!A.repeat&&!A.mirror).map((A,C)=>t.jsx("option",{value:A.name,children:A.name},C))]})]}),S.op&&t.jsx("small",{className:"muted",children:yi(w,d)>=0?a("Khối này không hiện; nó {0} “{1}”.",[a(Yx[S.op]),w[yi(w,d)].name||w[yi(w,d)].shape]):a("Cần một khối thường phía trước để tác động.")}),!S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Vật liệu")}),t.jsx(Kd,{label:a("Vật liệu"),value:_s(S)?.preset??"painted_wood",onChange:A=>j({look:{preset:A,..._s(S)?.params?.color?{params:{color:_s(S).params.color}}:{}},material:void 0,color:void 0,roughness:void 0,metalness:void 0})})]}),!S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Màu")}),t.jsx("input",{type:"color","aria-label":a("Màu khối"),value:_s(S)?.params?.color||qa(_s(S)?.preset??"")?.colors[0]||"#cccccc",onChange:A=>{const C=_s(S)??{preset:"painted_wood"};j({look:{...C,params:{...C.params||{},color:A.target.value}},material:void 0,color:void 0,roughness:void 0,metalness:void 0})}})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Bo cạnh (m)")}),t.jsx("input",{type:"number","aria-label":a("Bo cạnh (m)"),min:0,max:.5,step:.005,value:S.bevel??0,onChange:A=>j({bevel:Math.max(0,Math.min(.5,+A.target.value||0))})})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Nhân bản (số bản)")}),t.jsx("input",{type:"number","aria-label":a("Nhân bản (số bản)"),min:1,max:200,value:S.repeat?.count??1,onChange:A=>{const C=Math.max(1,Math.min(200,Math.round(+A.target.value)||1));j({repeat:C>1?{count:C,offset:S.repeat?.offset??[1,0,0],yaw:S.repeat?.yaw??0}:void 0})}})]}),S.repeat&&T(a("Khoảng cách bản sao (m)"),S.repeat.offset,A=>j({repeat:{...S.repeat,offset:A}})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Đối xứng")}),t.jsxs("select",{"aria-label":a("Đối xứng"),value:S.mirror||"",onChange:A=>j({mirror:A.target.value||void 0}),children:[t.jsx("option",{value:"",children:a("Không")}),t.jsx("option",{value:"x",children:a("Trái – phải (X)")}),t.jsx("option",{value:"z",children:a("Trước – sau (Z)")}),t.jsx("option",{value:"xz",children:a("Cả hai")})]})]}),t.jsxs("div",{className:"shot-model-actions",children:[t.jsx("button",{className:"pill-btn thin",onClick:()=>{b({...u,parts:[...w,{...S,name:`${S.name||S.shape} 2`,position:[E(S.position[0]+.5),S.position[1],S.position[2]]}]}),f(w.length)},children:a("Nhân đôi khối")}),t.jsx("button",{className:"pill-btn thin",disabled:w.length<2,onClick:()=>{b({...u,parts:w.filter((A,C)=>C!==d)}),f(Math.max(0,d-1))},children:a("Xoá khối")})]})]})]})}function Zx({loop:e,onLoop:n,range:s,rangeOn:o,onRangeOn:i,onEnd:r,onKeyAll:l,onCopy:h,onPaste:u,canPaste:m,onEase:d,onNudge:f,stage:p,cameraActive:y,cameraHidden:g,cameraLocked:v,onToggle:b,onProp:k,shot:w,items:S,time:E,fxBars:j,onFxTiming:M,onParent:T,playing:N,selected:R,picked:A=[],onPick:C,onSeek:O,onPlay:B,onRow:D,onSelect:$,onAdd:W,onMove:z,onDelete:Y,height:J,onHeight:V}){rt();const[H,G]=I.useState(1),[_,ee]=I.useState(220),Q=J??_,ve=P=>{ee(P),V?.(P)},[ye,q]=I.useState(null),[pe,ue]=I.useState({}),[U,re]=I.useState(!0),ce=I.useRef(void 0),Ee=I.useRef(null),[je,le]=I.useState(null),Le=(P,te)=>A.some(Z=>Z.row===P&&Z.id===te),Ae=(P,te,Z)=>{if(P.button!==0||!Ee.current)return;P.preventDefault(),ce.current?.();const ie=Ee.current,me=ie.parentElement,Fe=ie.getBoundingClientRect(),be=P.clientX-Fe.left,lt=P.clientY-Fe.top,wt=P.pointerId,Zt=P.shiftKey,Xe=()=>{const ut=ie.getBoundingClientRect();return[ut.left+be,ut.top+lt]};ie.setPointerCapture(wt);let ct=!1;const bt=(ut,Lt)=>{const[Gt,un]=Xe(),an=Math.min(Gt,ut),xt=Math.max(Gt,ut),mn=Math.min(un,Lt),It=Math.max(un,Lt),qt=Zt?[...A]:[];return ie.querySelectorAll(".shot-time-key:not([disabled]),.shot-prop-key[data-key]").forEach(pn=>{const Vn=pn.getBoundingClientRect(),vn=Vn.left+Vn.width/2,jn=Vn.top+Vn.height/2;vn>=an&&vn<=xt&&jn>=mn&&jn<=It&&!qt.some(oe=>oe.row===pn.dataset.row&&oe.id===pn.dataset.key)&&qt.push({row:pn.dataset.row,id:pn.dataset.key})}),qt};let Mt=[P.clientX,P.clientY],gt=0;const st=()=>{const[ut,Lt]=Xe(),[Gt,un]=Mt,an=ie.getBoundingClientRect();le({x:Math.min(ut,Gt)-an.left,y:Math.min(Lt,un)-an.top,w:Math.abs(Gt-ut),h:Math.abs(un-Lt)}),C?.(bt(Gt,un))},sn=()=>{if(gt=0,!ct||!me)return;const ut=me.getBoundingClientRect(),Lt=Mt[1],Gt=Lt<ut.top+28?-Math.ceil((ut.top+28-Lt)/3):Lt>ut.bottom-16?Math.ceil((Lt-ut.bottom+16)/3):0;if(!Gt)return;const un=me.scrollTop;me.scrollTop+=Gt,me.scrollTop!==un&&(st(),gt=requestAnimationFrame(sn))},Ie=ut=>{if(ut.pointerId!==wt)return;const[Lt,Gt]=Xe();!ct&&Math.hypot(ut.clientX-Lt,ut.clientY-Gt)<4||(ct=!0,Mt=[ut.clientX,ut.clientY],st(),gt||(gt=requestAnimationFrame(sn)))},ot=()=>{gt&&cancelAnimationFrame(gt),gt=0,ie.removeEventListener("pointermove",Ie),ie.removeEventListener("pointerup",Jt),ie.removeEventListener("pointercancel",ot),ie.hasPointerCapture(wt)&&ie.releasePointerCapture(wt),le(null)},Jt=ut=>{if(ot(),ct)C?.(bt(ut.clientX,ut.clientY));else{D(te);const Lt=Z.getBoundingClientRect();O(Math.max(0,Math.min(1,(ut.clientX-Lt.left)/Lt.width)))}};ce.current=ot,ie.addEventListener("pointermove",Ie),ie.addEventListener("pointerup",Jt),ie.addEventListener("pointercancel",ot)};I.useEffect(()=>()=>ce.current?.(),[]);const[we,he]=I.useState(null),ke=(P,te,Z,ie)=>{const me=j?.[te];if(P.button!==0||!me||!M)return;P.preventDefault(),P.stopPropagation(),ce.current?.();const Fe=P.currentTarget,be=P.pointerId,lt=P.clientX,wt=ie.getBoundingClientRect().width,Zt=w.duration,Xe=.2;Fe.setPointerCapture(be);let ct={id:te,start:me.start,duration:me.duration};const bt=sn=>Math.round(sn*20)/20,Mt=sn=>{if(sn.pointerId!==be)return;const Ie=(sn.clientX-lt)/wt*Zt;if(Z==="move")ct={id:te,start:bt(Math.max(0,Math.min(Zt-Xe,me.start+Ie))),duration:me.duration};else if(Z==="start"){const ot=me.start+me.duration,Jt=bt(Math.max(0,Math.min(ot-Xe,me.start+Ie)));ct={id:te,start:Jt,duration:+(ot-Jt).toFixed(2)}}else ct={id:te,start:me.start,duration:bt(Math.max(Xe,me.duration+Ie))};he(ct)},gt=()=>{Fe.removeEventListener("pointermove",Mt),Fe.removeEventListener("pointerup",st),Fe.removeEventListener("pointercancel",gt),Fe.hasPointerCapture(be)&&Fe.releasePointerCapture(be),he(null)},st=()=>{gt(),(ct.start!==me.start||ct.duration!==me.duration)&&M(te,{start:ct.start,duration:ct.duration})};ce.current=gt,Fe.addEventListener("pointermove",Mt),Fe.addEventListener("pointerup",st),Fe.addEventListener("pointercancel",gt)},Pe=[{id:"camera",kind:"camera",name:"📷 Camera",locked:!!v,hidden:!!g,keys:w.motion==="path"?w.cameraKeys||[]:[]},...S.map(P=>({id:P.id,kind:P.kind==="fx"?"fx":P.kind==="person"?"person":"object",name:P.kind==="fx"?`✦ ${P.name}`:P.name,locked:P.locked,hidden:P.hidden,keys:w.objectKeys?.[P.id]||[],fx:P.kind==="fx",parent:P.fx?.attach?.to??""}))],Te=S.filter(P=>P.kind!=="fx"&&!P.hidden),Be=(R?Pe.filter(P=>P.id===R.row):Pe).flatMap(P=>P.keys.map(te=>te.time)).sort((P,te)=>P-te),ze=P=>{const te=P>0?Be.find(Z=>Z>E+1e-4):[...Be].reverse().find(Z=>Z<E-1e-4);te!==void 0&&O(te)},Ke=(P,te)=>{if(P.button!==0)return;P.preventDefault(),P.stopPropagation(),ce.current?.();const Z=P.pointerId;te.setPointerCapture(Z);const ie=lt=>{const wt=te.getBoundingClientRect(),Zt=Math.max(0,Math.min(1,(lt.clientX-wt.left)/wt.width)),Xe=bn(w);O(Math.min(1,Math.round(Zt*w.duration*Xe)/Xe/w.duration))},me=lt=>{lt.pointerId===Z&&ie(lt)},Fe=()=>{te.removeEventListener("pointermove",me),te.removeEventListener("pointerup",be),te.removeEventListener("pointercancel",Fe),te.removeEventListener("lostpointercapture",Fe),te.hasPointerCapture(Z)&&te.releasePointerCapture(Z)},be=lt=>{ie(lt),Fe()};ce.current=Fe,te.addEventListener("pointermove",me),te.addEventListener("pointerup",be),te.addEventListener("pointercancel",Fe),te.addEventListener("lostpointercapture",Fe),ie(P)},Je=(P,te,Z,ie)=>{P.preventDefault(),P.stopPropagation(),$(te,Z);const me=ie.getBoundingClientRect();let Fe;const be=Zt=>{if(Fe=Math.max(0,Math.min(1,(Zt.clientX-me.left)/me.width)),U){const Xe=bn(w);Fe=Math.min(1,Math.round(Fe*w.duration*Xe)/Xe/w.duration);const ct=Pe.flatMap(bt=>bt.keys.filter(Mt=>!(bt.id===te&&Mt.id===Z)).map(Mt=>Mt.time)).find(bt=>Math.abs(bt-Fe)*me.width<6);ct!==void 0&&(Fe=ct)}q({row:te,id:Z,time:Fe})},lt=()=>{window.removeEventListener("mousemove",be),window.removeEventListener("mouseup",wt),q(null)},wt=()=>{lt(),Fe!==void 0&&z(te,Z,Fe)};ce.current?.(),ce.current=lt,window.addEventListener("mousemove",be),window.addEventListener("mouseup",wt)};return t.jsxs("section",{className:"shot-timeline","aria-label":a("Timeline keyframe"),style:{height:Q},children:[t.jsx("div",{className:"shot-timeline-tools",children:(()=>{const P=bn(w),te=w.duration,Z=E*te,ie=be=>{const lt=Math.floor(be/60),wt=be-lt*60;return`${String(lt).padStart(2,"0")}:${wt.toFixed(2).padStart(5,"0")}`},me=be=>{O(Math.max(0,Math.min(1,(Math.round(Z*P)+be)/P/te)))},Fe=A.length?!1:!R||Pe.find(be=>be.id===R.row)?.locked;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-tc",children:[t.jsxs("span",{children:[ie(Z)," / ",ie(te)]}),t.jsx("small",{children:a("Khung {0} / {1} · {2} fps",[Math.round(Z*P),Math.round(te*P),P])})]}),t.jsxs("div",{className:"shot-transport",role:"group","aria-label":a("Điều khiển phát"),children:[t.jsx("button",{className:"shot-tp-btn",onClick:()=>O(0),"aria-label":a("Về đầu"),title:a("Về đầu")+" (Home)",children:t.jsx(Ce.skipStart,{})}),t.jsx("button",{className:"shot-tp-btn",onClick:()=>me(-1),disabled:Z<=1e-6,"aria-label":a("Lùi 1 khung hình"),title:a("Lùi 1 khung hình")+" (,)",children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"19",height:"19","aria-hidden":!0,fill:"currentColor",children:[t.jsx("path",{d:"M15 6v12L7 12z"}),t.jsx("rect",{x:"17",y:"6",width:"2",height:"12",rx:"1"})]})}),t.jsx("button",{className:"shot-tp-play",onClick:B,"aria-label":N?a("Tạm dừng"):a("Phát"),title:(N?a("Tạm dừng"):a("Phát"))+" (Space)",children:N?t.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":!0,fill:"currentColor",children:[t.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",rx:"1"}),t.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",rx:"1"})]}):t.jsx("svg",{viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":!0,fill:"currentColor",children:t.jsx("path",{d:"M8 5.5v13l11-6.5z"})})}),t.jsx("button",{className:"shot-tp-btn",onClick:()=>me(1),disabled:Z>=te-1e-6,"aria-label":a("Tới 1 khung hình"),title:a("Tới 1 khung hình")+" (.)",children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"19",height:"19","aria-hidden":!0,fill:"currentColor",children:[t.jsx("path",{d:"M9 6v12l8-6z"}),t.jsx("rect",{x:"5",y:"6",width:"2",height:"12",rx:"1"})]})}),t.jsx("button",{className:`shot-tp-btn${e?" on":""}`,"data-tool":"loop",onClick:n,disabled:!n,"aria-pressed":!!e,"aria-label":a("Phát lặp"),title:a("Phát lặp")+" (L)",children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"16",height:"16","aria-hidden":!0,fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M20 12a8 8 0 1 1-2.6-5.9"}),t.jsx("path",{d:"M20 4v4.5h-4.5"})]})})]}),t.jsxs("div",{className:"shot-tl-right",children:[t.jsx("button",{className:"shot-tp-del",disabled:Fe,onClick:Y,"aria-label":A.length>1?a("Xoá {0} key",[A.length]):a("Xoá key"),title:A.length>1?a("Xoá {0} key",[A.length]):a("Xoá key"),children:t.jsx("svg",{viewBox:"0 0 24 24",width:"15",height:"15","aria-hidden":!0,fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"})})}),t.jsxs("label",{children:[a("Zoom")," ",t.jsx("input",{"aria-label":a("Zoom timeline"),type:"range",min:1,max:8,step:.5,value:H,onChange:be=>G(+be.target.value)})]}),t.jsxs("label",{children:[a("Cao")," ",t.jsx("input",{"aria-label":a("Chiều cao timeline"),type:"range",min:140,max:360,step:20,value:Q,onChange:be=>ve(+be.target.value)})]})]})]})})()}),t.jsx("div",{className:"shot-edit-bar",role:"toolbar","aria-label":a("Công cụ keyframe"),children:(()=>{const P=A.length?A:R?[R]:[],te=P.length>0,Z=R?.row,ie=(Xe,ct)=>ct?`${a(Xe)} (${ct})`:a(Xe),me=(Xe,ct,bt,Mt,gt={})=>t.jsx("button",{type:"button",className:`shot-edit-btn${gt.on?" on":""}`,"data-tool":Xe,"aria-label":a(bt),"aria-pressed":gt.on===void 0?void 0:gt.on,title:ie(bt,gt.key),disabled:gt.disabled||!Mt,onClick:Mt,children:ct},Xe),Fe=Xe=>t.jsx("i",{className:"shot-edit-sep","aria-hidden":!0},Xe),be=Xe=>t.jsx("svg",{viewBox:"0 0 20 20",width:"18",height:"18","aria-hidden":!0,fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:Xe}),lt=(Xe,ct,bt)=>me("ease-"+Xe,be(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M3 17h14M3 3v14"}),t.jsx("path",{d:bt})]})),ct,()=>d?.(Xe),{disabled:!te||!d}),wt=()=>{G(1),requestAnimationFrame(()=>{const Xe=Ee.current?.parentElement;Xe&&(Xe.scrollLeft=0)})},Zt=()=>{const Xe=Pe.flatMap(gt=>gt.keys.filter(st=>P.some(sn=>sn.row===gt.id&&sn.id===st.id)).map(st=>st.time)),ct=Math.min(...Xe),bt=Math.max(...Xe),Mt=Math.min(8,Math.max(1,.8/Math.max(.02,bt-ct)));G(Mt),requestAnimationFrame(()=>{const gt=Ee.current?.parentElement;gt&&(gt.scrollLeft=Math.max(0,(ct-.05/Mt)*gt.clientWidth*Mt))})};return t.jsxs(t.Fragment,{children:[me("add",zs.key,"Thêm key trên hàng đang chọn",Z?()=>W(Z):void 0,{key:"K",disabled:!Z}),me("key-all",be(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"m7 4 4 5.5L7 15 3 9.5z"}),t.jsx("path",{d:"m13 4 4 5.5-4 5.5"})]})),"Key tất cả: camera và mọi hàng chưa khoá",l,{key:"⇧K"}),me("key-prev",be(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"m11 5-5 5 5 5"}),t.jsx("path",{d:"m15 7 3 3-3 3-3-3z"})]})),"Key trước",Be.some(Xe=>Xe<E-1e-4)?()=>ze(-1):void 0),me("key-next",be(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"m9 5 5 5-5 5"}),t.jsx("path",{d:"m5 7 3 3-3 3-3-3z"})]})),"Key sau",Be.some(Xe=>Xe>E+1e-4)?()=>ze(1):void 0),Fe("s1"),me("copy",zs.copy,"Copy các key đang chọn",te?h:void 0,{key:"⌘C",disabled:!te}),me("paste",zs.paste,"Dán key tại playhead (giữ khoảng cách)",u,{key:"⌘V",disabled:!m}),Fe("s2"),lt("linear","Easing: Tuyến tính","M3 17 17 3"),lt("in","Easing: Vào chậm (ease in)","M3 17C10 17 14 12 17 3"),lt("snap","Easing: Ra chậm (ease out)","M3 17C6 8 10 3 17 3"),lt("smooth","Easing: Vào và ra chậm (ease in-out)","M3 17C10 17 10 3 17 3"),lt("hold","Easing: Giữ nguyên (hold)","M3 17h7V3h7"),Fe("s3"),me("nudge-back",be(t.jsx("path",{d:"m12 5-5 5 5 5M16 4v12"})),"Dịch key lùi 1 khung hình",te?()=>f?.(-1):void 0,{key:"Alt+,",disabled:!te}),me("nudge-fwd",be(t.jsx("path",{d:"m8 5 5 5-5 5M4 4v12"})),"Dịch key tới 1 khung hình",te?()=>f?.(1):void 0,{key:"Alt+.",disabled:!te}),Fe("s4"),me("range",be(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M5 4v12M15 4v12"}),t.jsx("path",{d:"M5 10h10",strokeDasharray:"2 2"})]})),s?"Chỉ phát trong vùng I–O":"Chỉ phát trong vùng (đặt I và O trước)",s?i:void 0,{key:"I / O",on:!!o,disabled:!s}),me("snap",zs.magnet,"Bám khung hình và key khác khi kéo key",()=>re(Xe=>!Xe),{on:U}),Fe("s5"),me("zoom-fit",zs.fit,"Thu phóng vừa cả shot",wt),me("zoom-sel",zs.zoomIn,"Thu phóng vào các key đang chọn",te?Zt:void 0,{disabled:!te}),me("end",be(t.jsx("path",{d:"m6 5 5 5-5 5M15 4v12"})),"Về cuối",r,{key:"End"})]})})()}),t.jsx("div",{className:"shot-timeline-scroll",children:t.jsxs("div",{className:"shot-timeline-content",ref:Ee,style:{width:`${H*100}%`},children:[je&&t.jsx("div",{className:"shot-marquee",style:{left:je.x,top:je.y,width:je.w,height:je.h}}),t.jsxs("div",{className:"shot-time-row shot-ruler-row",children:[t.jsx("div",{className:"shot-track-name",children:a("Đối tượng")}),t.jsxs("div",{className:"shot-time-ruler",onPointerDown:P=>Ke(P,P.currentTarget),children:[(w.lockUntil??0)>0&&t.jsx("div",{className:"shot-lock-band",role:"img",style:{width:`${Math.min(1,w.lockUntil/w.duration)*100}%`},"aria-label":a("Đã khoá 0–{0}s cho Agent",[String(Math.round(Math.min(w.lockUntil,w.duration)*100)/100)]),title:a("Agent không sửa phần này"),children:t.jsx("span",{children:"🔒"})}),s&&t.jsx("div",{className:`shot-range${o?" on":""}`,style:{left:`${s.in*100}%`,width:`${Math.max(0,s.out-s.in)*100}%`},"aria-hidden":!0}),t.jsx("button",{className:"shot-playhead-handle",role:"slider","aria-label":a("Vị trí phát timeline"),"aria-valuemin":0,"aria-valuemax":w.duration,"aria-valuenow":Number((E*w.duration).toFixed(2)),style:{left:`${E*100}%`},onKeyDown:P=>{const te=P.shiftKey?1:.1,Z=1/bn(w);["ArrowLeft","ArrowRight","Home","End",",","."].includes(P.key)&&(P.preventDefault(),O(P.key==="Home"?0:P.key==="End"?1:P.key===","||P.key==="."?Math.max(0,Math.min(1,Math.round(E*w.duration/Z+(P.key==="."?1:-1))*Z/w.duration)):Math.max(0,Math.min(1,E+(P.key==="ArrowRight"?te:-te)/w.duration))))}}),Array.from({length:11},(P,te)=>t.jsxs("span",{style:{left:`${te*10}%`},children:[Number((w.duration*te/10).toFixed(2)),a("s")]},te))]})]}),Pe.map(P=>{const te=p&&pe[P.id]?Sg(p,P.id):[];return t.jsxs(I.Fragment,{children:[t.jsxs("div",{className:`shot-time-row${P.id==="camera"&&y?" camera-active":""}${P.hidden?" is-hidden":""}${P.locked?" is-locked":""}`,children:[t.jsxs("div",{className:"shot-track-name",children:[b&&t.jsx("button",{className:`shot-row-eye${P.hidden?" off":""}`,"aria-pressed":!P.hidden,"aria-label":P.hidden?a("Hiện {0}",[P.name]):a("Ẩn {0}",[P.name]),title:P.id==="camera"?P.hidden?a("Hiện camera trong khung nhìn"):a("Ẩn camera khỏi khung nhìn (không ảnh hưởng ảnh xuất)"):P.hidden?a("Hiện trong cảnh và khi xuất"):a("Ẩn khỏi cảnh và khi xuất"),onClick:()=>b(P.id,"hidden"),children:P.hidden?"◌":"◉"}),p&&t.jsx("button",{className:`shot-row-keys${P.keys.length?" keyed":""}${pe[P.id]?" open":""}`,"aria-expanded":!!pe[P.id],"aria-label":a("Thuộc tính {0}",[P.name]),title:a("Mở / đóng các thuộc tính keyframe"),onClick:()=>ue(Z=>({...Z,[P.id]:!Z[P.id]})),children:"◆"}),b&&t.jsx("button",{className:`shot-row-lock${P.locked?" on":""}`,"aria-pressed":P.locked,"aria-label":P.locked?a("Mở khoá {0}",[P.name]):a("Khoá {0}",[P.name]),title:P.locked?a("Mở khoá: cho chọn và kéo"):a("Khoá: không chọn, không kéo, không sửa key"),onClick:()=>b(P.id,"locked"),children:P.locked?"🔒":"🔓"}),t.jsx("button",{className:"shot-row-name",title:P.name,onClick:()=>{P.locked||D(P.id)},children:P.name}),"fx"in P&&P.fx&&T&&t.jsxs("select",{className:"shot-track-parent","aria-label":a("Parent của {0}",[P.name]),title:a("Parent: hiệu ứng đi theo đối tượng này"),disabled:P.locked,value:P.parent,onChange:Z=>T(P.id,Z.target.value),children:[t.jsx("option",{value:"",children:a("Tự do")}),Te.map(Z=>t.jsxs("option",{value:Z.id,children:["🔗 ",Z.name]},Z.id))]}),t.jsx("button",{"aria-label":a("Thêm key {0}",[P.name]),disabled:P.locked,onClick:()=>W(P.id),children:"+◆"})]}),t.jsxs("div",{className:"shot-key-track","data-row":P.id,onPointerDown:Z=>{Z.target.closest(".shot-time-key")||Ae(Z,P.id,Z.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${E*100}%`}}),(w.clipSpans?.[P.id]||[]).map(Z=>t.jsx("div",{className:"shot-clip-block","data-clip-block":Z.clip,style:{left:`${Z.start/w.duration*100}%`,width:`${Math.max(.5,(Math.min(w.duration,Z.end)-Z.start)/w.duration*100)}%`},title:`${Z.label} · ${Z.start.toFixed(1)}–${Z.end.toFixed(1)}s`,children:t.jsx("span",{children:Z.label})},Z.id)),(w.motionEdits?.[P.id]||[]).map(Z=>t.jsx("div",{className:`shot-edit-mark${Z.off?" off":""}`,"data-edit-mark":!0,style:{left:`${Math.max(0,Z.start-(Z.scope==="span"?0:Z.fade))/w.duration*100}%`,width:`${((Z.scope==="after"?w.duration:Z.end+(Z.scope==="span"?0:Z.fade))-Math.max(0,Z.start-(Z.scope==="span"?0:Z.fade)))/w.duration*100}%`},title:`${Z.label||a("Chỉnh")} · ${(Number(Z.start)||0).toFixed(1)}s`},Z.id)),j?.[P.id]&&(()=>{const Z=we?.id===P.id?we:j[P.id],ie=!!M&&!P.locked,me=Fe=>Fe.currentTarget.closest(".shot-key-track");return t.jsx("div",{className:`shot-fx-bar${P.hidden||P.locked?" dim":""}${ie?" editable":""}${we?.id===P.id?" dragging":""}`,"data-fx-bar":P.id,title:a("Hiệu ứng: {0}s → {1}s · kéo để dời, kéo mép để đổi độ dài",[Z.start.toFixed(2),(Z.start+Z.duration).toFixed(2)]),style:{left:`${Math.min(100,Z.start/w.duration*100)}%`,width:`${Math.max(.6,Math.min(100-Z.start/w.duration*100,Z.duration/w.duration*100))}%`},onPointerDown:ie?Fe=>ke(Fe,P.id,"move",me(Fe)):void 0,children:ie&&t.jsxs(t.Fragment,{children:[t.jsx("i",{className:"shot-fx-edge start","aria-hidden":!0,onPointerDown:Fe=>ke(Fe,P.id,"start",me(Fe))}),t.jsx("i",{className:"shot-fx-edge end","aria-hidden":!0,onPointerDown:Fe=>ke(Fe,P.id,"end",me(Fe))})]})})})(),!j?.[P.id]&&P.kind!=="fx"&&t.jsx("div",{className:`shot-dur-bar kind-${P.kind}${P.hidden||P.locked?" dim":""}`,"data-dur":P.id,title:P.kind==="camera"?a("Camera chạy suốt shot: 0s → {0}s",[w.duration]):a("Có mặt suốt shot: 0s → {0}s",[w.duration]),style:{left:"0%",width:"100%"}}),P.keys.map((Z,ie)=>t.jsx("button",{"aria-label":`Key ${ie+1} ${P.name}`,title:a("{0}s · kéo để đổi thời điểm",[(Z.time*w.duration).toFixed(2)]),disabled:P.locked,"data-row":P.id,"data-key":Z.id,className:`shot-time-key ${"pose"in Z&&Z.pose?"pose":""} ${R?.row===P.id&&R.id===Z.id||Le(P.id,Z.id)?"active":""}`,style:{left:`${(ye?.id===Z.id&&ye.row===P.id?ye.time:Z.time)*100}%`},onClick:me=>{me.detail===0&&$(P.id,Z.id)},onMouseDown:me=>{if(me.shiftKey||me.metaKey||me.ctrlKey){me.preventDefault(),me.stopPropagation();const Fe=Le(P.id,Z.id),be=A.length?A:R?[R]:[];C?.(Fe?be.filter(lt=>!(lt.row===P.id&&lt.id===Z.id)):[...be,{row:P.id,id:Z.id}]);return}Je(me,P.id,Z.id,me.currentTarget.parentElement)},children:"◆"},Z.id))]})]}),te.map(Z=>{const ie=Cg(w,P.id);return t.jsxs("div",{className:"shot-time-row shot-prop-row","data-prop":`${P.id}:${Z.id}`,children:[t.jsxs("div",{className:"shot-track-name",children:[t.jsx("span",{className:`shot-stopwatch${ie?" keyed":""}`,role:"img","aria-label":ie?a("Đã có key"):a("Chưa có key"),title:ie?a("Thuộc tính đã có key: sửa số sẽ ghi key tại playhead"):a("Chưa có key: sửa số đổi giá trị cố định"),children:"⏱"}),t.jsxs("label",{className:"shot-prop-label",children:[a(Z.label),t.jsx(Tn,{"aria-label":`${a(Z.label)} · ${P.name}`,className:"shot-prop-number",step:Z.step,min:Z.min,max:Z.max,precision:3,disabled:P.locked,value:Ng(p,P.id,Z.id,E),onCommit:me=>k?.(P.id,Z.id,me)})]}),t.jsx("button",{className:"shot-prop-add","aria-label":`${a("Thêm key")} ${a(Z.label)} · ${P.name}`,title:a("Thêm key tại playhead"),disabled:P.locked,onClick:()=>W(P.id),children:"◆"})]}),t.jsxs("div",{className:"shot-key-track shot-prop-track",onPointerDown:me=>{P.locked||Ae(me,P.id,me.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${E*100}%`}}),P.keys.map(me=>t.jsx("i",{"data-row":P.locked?void 0:P.id,"data-key":P.locked?void 0:me.id,className:`shot-prop-key${Le(P.id,me.id)||R?.row===P.id&&R.id===me.id?" active":""}`,style:{left:`${me.time*100}%`}},me.id))]})]},Z.id)})]},P.id)})]})})]})}let ds=null;function Jx(){return ds||(ds=new Wr(Pg()),ds.colorSpace=Cd,ds.anisotropy=4,ds.generateMipmaps=!0,ds.minFilter=Nd,ds)}const Gc=new Map;function eb(e){let n=Gc.get(e);return n||(n=new Wr(Ig(e)),n.colorSpace=Cd,n.anisotropy=8,n.generateMipmaps=!0,n.minFilter=Nd,Gc.set(e,n)),n}let Jn=null;function tb(){if(Jn)return Jn;const e=128,n=new Uint8Array(e*e*4),s=r=>{const l=new Float32Array(r*r);let h=1013904223+r;for(let u=0;u<l.length;u++)h=Math.imul(h,1664525)+1013904223>>>0,l[u]=h/4294967296;return l},o=[4,8,16,32].map(r=>({g:r,v:s(r)})),i=r=>r*r*(3-2*r);for(let r=0;r<e;r++)for(let l=0;l<e;l++){let h=0,u=.5,m=0;for(const{g:p,v:y}of o){const g=l/e*p,v=r/e*p,b=Math.floor(g),k=Math.floor(v),w=i(g-b),S=i(v-k),E=(T,N)=>y[N%p*p+T%p],j=E(b,k)+(E(b+1,k)-E(b,k))*w,M=E(b,k+1)+(E(b+1,k+1)-E(b,k+1))*w;h+=(j+(M-j)*S)*u,m+=u,u*=.5}const d=(r*e+l)*4,f=Math.round(h/m*255);n[d]=n[d+1]=n[d+2]=f,n[d+3]=255}return Jn=new W0(n,e,e,G0),Jn.wrapS=Jn.wrapT=Sd,Jn.magFilter=xc,Jn.minFilter=xc,Jn.needsUpdate=!0,Jn}const nb=Symbol.for("clipoox.shot.fxSoftDepth"),sb=e=>e[nb]??null,Ur={uOcclude:{value:0}},qc={day:.22,golden:.16,overcast:.2,night:.03},Ba={blade:.78,width:.034,thick:.0075,grip:.19};function Uc(e,n){return[[-e,0],[-e*.62,n*.82],[-e*.26,n],[-e*.15,n*.38],[e*.15,n*.38],[e*.26,n],[e*.62,n*.82],[e,0],[e*.62,-n*.82],[e*.26,-n],[e*.15,-n*.38],[-e*.15,-n*.38],[-e*.26,-n],[-e*.62,-n*.82]]}function Xc(e=0){const{blade:n,width:s,thick:o}=Ba,i=[[0,.86,1],[.06,1,1],[.7,.96,.9],[.84,.74,.72],[.94,.4,.5],[1,.02,.15]],r=Uc(1,1).length,l=[],h=[];i.forEach(([m,d,f])=>{for(const[p,y]of Uc(s*d+e,o*f+e*.5))l.push(p,m*n,y)});for(let m=0;m<i.length-1;m++)for(let d=0;d<r;d++){const f=m*r+d,p=m*r+(d+1)%r,y=(m+1)*r+d,g=(m+1)*r+(d+1)%r;h.push(f,y,p,p,y,g)}const u=new At;return u.setAttribute("position",new zt(l,3)),u.setIndex(h),u.computeVertexNormals(),u}function ab(){const e=[],n=new Ad(.0105,.15,4,10);n.rotateZ(Math.PI/2),n.scale(1,1,1.5),e.push(n);for(const i of[-1,1]){const r=new q0(.0125,.03,10);r.rotateZ(-i*Math.PI/2),r.translate(i*.086,.012,0),e.push(r)}const s=new ws(.016,.02,.026,14);s.translate(0,-.016,0),e.push(s);const o=Wd(e);return e.forEach(i=>i.dispose()),o}function ob(){const e=[],n=new ws(.0125,.0125,Ba.grip,12);n.translate(0,-.03-Ba.grip/2,0),e.push(n);for(let i=0;i<5;i++){const r=new qr(.0132,.0028,6,14);r.rotateX(Math.PI/2),r.translate(0,-.05-i*.034,0),e.push(r)}const s=new Un(.0235,14,10);s.translate(0,-.03-Ba.grip-.012,0),e.push(s);const o=Wd(e);return e.forEach(i=>i.dispose()),o}function Wd(e){const n=[],s=[],o=[],i=[];let r=0;for(const h of e){const u=h.getAttribute("position"),m=h.getAttribute("normal"),d=h.getAttribute("uv");for(let f=0;f<u.count;f++)n.push(u.getX(f),u.getY(f),u.getZ(f)),s.push(m.getX(f),m.getY(f),m.getZ(f)),o.push(d?d.getX(f):0,d?d.getY(f):0);if(h.index)for(let f=0;f<h.index.count;f++)i.push(r+h.index.getX(f));else for(let f=0;f<u.count;f++)i.push(r+f);r+=u.count}const l=new At;return l.setAttribute("position",new zt(n,3)),l.setAttribute("normal",new zt(s,3)),l.setAttribute("uv",new zt(o,2)),l.setIndex(i),l}const ib=`
4
+ attribute float iGlow; varying float vGlow; varying vec3 vN; varying vec3 vV; varying float vY;
5
+ void main(){
6
+ mat4 im = mat4(1.0);
7
+ #ifdef USE_INSTANCING
8
+ im = instanceMatrix;
9
+ #endif
10
+ vec4 wp = modelMatrix * im * vec4(position, 1.0);
11
+ vN = normalize(mat3(modelMatrix) * mat3(im) * normal); vV = normalize(cameraPosition - wp.xyz); vGlow = iGlow; vY = position.y;
12
+ gl_Position = projectionMatrix * viewMatrix * wp;
13
+ }`,rb=`
14
+ uniform vec3 uColor; uniform vec3 uCore; uniform float uGain; varying float vGlow; varying vec3 vN; varying vec3 vV; varying float vY;
15
+ void main(){
16
+ float f = 1.0 - abs(dot(normalize(vN), normalize(vV)));
17
+ float rim = pow(f, 1.6);
18
+ float ridge = smoothstep(0.55, 1.0, f);
19
+ float along = 0.65 + 0.35 * smoothstep(0.0, 0.8, vY / ${Ba.blade.toFixed(2)});
20
+ vec3 col = mix(uColor, uCore, ridge) * (0.35 + 1.6 * rim) * along;
21
+ gl_FragColor = vec4(col * uGain * vGlow, (0.25 + 0.75 * rim) * vGlow);
22
+ #include <tonemapping_fragment>
23
+ #include <colorspace_fragment>
24
+ }`;function lb(e){const n=new dn,s=new rr(new Float32Array(e*16),16);s.setUsage(oa);const o=new os({color:"#cfd8e2",metalness:1,roughness:.22,envMapIntensity:1.6,emissive:"#7f93a8",emissiveIntensity:.16}),i=new os({color:"#c9a24b",metalness:1,roughness:.32,envMapIntensity:1.3}),r=new os({color:"#2a1913",metalness:.1,roughness:.78}),l=[Xc(),ab(),ob()],h=[new Xs(l[0],o,e),new Xs(l[1],i,e),new Xs(l[2],r,e)];for(const p of h)p.instanceMatrix=s,p.castShadow=!0,p.frustumCulled=!1,p.count=0,n.add(p);const u=Xc(.0042),m=new rr(new Float32Array(e),1);m.setUsage(oa),u.setAttribute("iGlow",m);const d=new Ya({vertexShader:ib,fragmentShader:rb,transparent:!0,depthWrite:!1,blending:Gr,side:ks,uniforms:{uColor:{value:new Ve(.3,.8,1)},uCore:{value:new Ve(1,1,1)},uGain:{value:1.05}}}),f=new Xs(u,d,e);return f.instanceMatrix=s,f.frustumCulled=!1,f.count=0,f.renderOrder=4,f.isLine=!0,n.add(f),{group:n,meshes:h,glow:f,glowAttr:m,matrix:s,setColor:p=>{d.uniforms.uColor.value.setRGB(p[0],p[1],p[2],vs),d.uniforms.uCore.value.setRGB(1,.97,.9,vs)},dispose:()=>{l.forEach(p=>p.dispose()),u.dispose(),o.dispose(),i.dispose(),r.dispose(),d.dispose()}}}function cb(){const e=[[0,.62],[.05,.6],[.12,.52],[.17,.35],[.19,.1],[.19,-.2],[.15,-.4],[.09,-.52],[.05,-.55],[0,-.55]].map(([o,i])=>new ca(o,i)),s=[new Td(e,20)];for(let o=0;o<4;o++){const i=new Qa(.012,.22,.2);i.translate(0,-.46,.17),i.rotateY(o*Math.PI/2),s.push(i)}return oi(s)}function hb(){const e=new Un(.5,14,10);e.scale(1,1.2,1);const n=new ws(.16,.2,.18,10);n.translate(0,.64,0);const s=new Qa(.06,.34,.14);return s.translate(.2,.55,0),oi([e,n,s])}function oi(e){const n=[],s=[],o=[];let i=0;for(const l of e){const h=l.getAttribute("position"),u=l.getAttribute("normal");for(let m=0;m<h.count;m++)n.push(h.getX(m),h.getY(m),h.getZ(m)),s.push(u.getX(m),u.getY(m),u.getZ(m));if(l.index)for(let m=0;m<l.index.count;m++)o.push(i+l.index.getX(m));else for(let m=0;m<h.count;m++)o.push(i+m);i+=h.count,l.dispose()}const r=new At;return r.setAttribute("position",new zt(n,3)),r.setAttribute("normal",new zt(s,3)),r.setIndex(o),r}function Gd(e,n,s){const o=n.clone().sub(e),i=o.length(),r=new Ad(s,Math.max(.001,i),4,10);return r.applyQuaternion(new qe().setFromUnitVectors(new ae(0,1,0),o.normalize())),r.translate((e.x+n.x)/2,(e.y+n.y)/2,(e.z+n.z)/2),r}function Bi(e,n,s,o,i){const r=[],l=n.clone().normalize(),h=new ae().crossVectors(l,new ae(0,0,1)).normalize();let u=e.clone();return s.forEach((m,d)=>{l.applyAxisAngle(h,-i);const f=u.clone().addScaledVector(l,m);r.push(Gd(u,f,o*(1-.12*d))),u=f}),r}function db(e){const n=(u,m,d)=>new ae(u,m,d),s=[],o=new Un(.5,16,12);o.scale(.44,e?.42:.5,e?.3:.16),o.translate(0,.27,0),s.push(o);const i=new ws(e?.12:.15,e?.11:.17,e?.14:.2,14);i.scale(1,1,.7),i.translate(0,e?.02:-.04,0),s.push(i);const r=[-.15,-.05,.05,.15],l=[[.15,.1,.08],[.17,.12,.09],[.16,.11,.09],[.12,.08,.07]];r.forEach((u,m)=>{if(e){const d=new Un(.068,10,8);d.translate(u,.5,.05),s.push(d),s.push(...Bi(n(u,.5,.06),n(0,.2,1),[.11,.09],.056,1.15))}else s.push(...Bi(n(u,.5,0),n(u*.25,1,0),l[m],.044,.16))}),e?s.push(Gd(n(.2,.22,.08),n(-.02,.36,.17),.055)):s.push(...Bi(n(.19,.2,.03),n(.75,.75,.25),[.15,.12],.052,.12));const h=oi(s);return h.computeVertexNormals(),h}function ub(){const e=[],n=new At,s=.07,o=.012,i=(g,v)=>[[-s*v,g,0],[0,g,o*v],[s*v,g,0],[0,g,-o*v]],r=i(0,1),l=i(.42,.9),h=[.012,.62,0],u=[],m=[];for(const g of[...r,...l,h])u.push(g[0],g[1],g[2]);for(let g=0;g<4;g++){const v=g,b=(g+1)%4;m.push(v,b,4+b,v,4+b,4+v,4+v,4+b,8)}n.setAttribute("position",new zt(u,3)),n.setIndex(m);const d=n.toNonIndexed();d.computeVertexNormals(),d.translate(0,.06,0),e.push(d);const f=new Qa(.2,.025,.04);f.translate(0,.05,0),e.push(f);const p=new ws(.03,.034,.3,10);p.translate(0,-.11,0),e.push(p);const y=new qr(.035,.012,6,12);return y.translate(0,-.29,0),e.push(y),oi(e.map(g=>(g.index,g)))}function mb(){const e=[[0,.5],[.5,.12],[.5,-.22],[0,-.5]].map(([s,o])=>new ca(s,o)),n=new Td(e,6);return n.computeVertexNormals(),n}function pb(e,n){const s=e==="bomb"?cb():e==="grenade"?hb():e==="crystal"?mb():e==="hand"||e==="fist"?db(e==="fist"):e==="knife"?ub():new Qa(1,1,1),o=e==="hand"||e==="fist"?fb():e==="crystal"?new $s({color:"#ffffff",metalness:0,roughness:.04,transparent:!0,opacity:.82,flatShading:!0,envMapIntensity:2,emissive:"#cfefff",emissiveIntensity:.55,clearcoat:1}):e==="glass"?new $s({color:"#ffffff",metalness:0,roughness:.06,transparent:!0,opacity:.55,envMapIntensity:1.6,emissive:"#7fc8e8",emissiveIntensity:.12}):new os({color:"#ffffff",metalness:e==="debris"?.1:e==="knife"?.85:.6,roughness:e==="debris"?.85:e==="knife"?.28:.4,emissive:"#000000",emissiveIntensity:0}),i=new Xs(s,o,n);return i.instanceColor=new rr(new Float32Array(n*3),3),i.instanceMatrix.setUsage(oa),i.instanceColor.setUsage(oa),i.castShadow=e!=="hand"&&e!=="fist",i.frustumCulled=!1,i.count=0,(e==="hand"||e==="fist")&&(i.renderOrder=2),{mesh:i,dispose:()=>{s.dispose(),o.dispose()}}}function fb(){const e=new os({color:"#ffffff",metalness:0,roughness:.45,transparent:!0,opacity:.78,depthWrite:!1,side:Za});return e.onBeforeCompile=n=>{n.fragmentShader=n.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissivemap_fragment>
25
+ #if defined( USE_INSTANCING_COLOR ) || defined( USE_COLOR )
26
+ float rim = pow(1.0 - abs(dot(normalize(vViewPosition), normal)), 2.2);
27
+ totalEmissiveRadiance += vColor.rgb * (0.55 + 1.6 * rim);
28
+ #endif`)},e.customProgramCacheKey=()=>"spirit-hand",e}const gb=`
29
+ uniform float uT; uniform float uSp; uniform vec4 uWv[4]; uniform vec4 uQ; uniform vec2 uHalf; uniform vec4 uCrest; uniform vec4 uShape; uniform float uAmp; uniform float uAlpha;
30
+ uniform vec3 uDeep; uniform vec3 uTint;
31
+ varying float vFoam; varying float vEdge; varying float vH;
32
+ #ifdef WAVE
33
+ float prof(float z){ float zz = z - uCrest.x; float H = uCrest.y; float F = max(uCrest.z, 0.1); float B = max(uCrest.w, 0.1);
34
+ if (zz < 0.0) { float u = clamp(-zz / B, 0.0, 1.0); return mix(H, uShape.x, pow(u, 0.55)); }
35
+ float u = clamp(zz / F, 0.0, 1.0); return H * (1.0 - pow(u, 1.35)); }
36
+ float taper(float x){ return 1.0 - smoothstep(0.65, 1.0, abs(x) / max(uShape.w, 0.1)); }
37
+ void waveEval(vec3 p, out vec3 disp, out vec3 nrm, out float foam, out float edge, out float hn){
38
+ // the crest line wobbles and its height varies along the width, so the wall is not a straight extrusion
39
+ float wob = 0.16 * uCrest.y * sin(p.x * 0.31 + 1.3) + 0.08 * uCrest.y * sin(p.x * 0.83 + 0.4);
40
+ float hv = 1.0 + 0.16 * sin(p.x * 0.23 + 2.0) + 0.1 * sin(p.x * 0.61);
41
+ float tx = taper(p.x); float zq = p.z - wob; float e = 0.25;
42
+ float h = prof(zq) * tx * hv;
43
+ float hz = (prof(zq + e) - prof(zq - e)) / (2.0 * e) * tx * hv; float hx = prof(zq) * hv * (taper(p.x + e) - taper(p.x - e)) / (2.0 * e);
44
+ float over = smoothstep(0.55 * uCrest.y, uCrest.y, h); float dz = uShape.y * over * over * uCrest.z * 0.55;
45
+ disp = vec3(0.0, h + 0.03, dz); nrm = normalize(vec3(-hx, 1.0, -hz));
46
+ float rel = h / max(uCrest.y * hv, 0.01);
47
+ float tall = 1.0 - smoothstep(2.0, 8.0, uCrest.z / max(uCrest.y, 0.2));
48
+ float streak = 0.6 + 0.4 * sin(p.x * 3.7 + p.z * 0.9 + uT * 1.3) * sin(p.x * 1.3 - p.z * 2.1);
49
+ float top = smoothstep(0.72, 1.0, rel) * tall;
50
+ float lip = smoothstep(0.35, 0.7, rel) * (1.0 - smoothstep(0.7, 0.95, rel)) * tall * streak * 0.5;
51
+ float wash = uShape.z * smoothstep(0.0, 0.4, h) * (1.0 - smoothstep(0.4, 1.8, h)) * (0.5 + 0.5 * streak);
52
+ foam = clamp(top * 0.95 + lip + wash * 0.6, 0.0, 1.0);
53
+ edge = smoothstep(0.015, 0.14, h); hn = rel * 2.0 - 1.0;
54
+ }
55
+ #else
56
+ void waveEval(vec3 p, out vec3 disp, out vec3 nrm, out float foam, out float edge, out float hn){
57
+ vec2 q = p.xz; disp = vec3(0.0); nrm = vec3(0.0, 1.0, 0.0); float jac = 0.0, norm = 0.0;
58
+ for (int i = 0; i < 4; i++) {
59
+ vec2 d = uWv[i].xy; float k = uWv[i].z, a = uWv[i].w, w = sqrt(9.81 * k) * uSp, ph = k * dot(d, q) - w * uT, c = cos(ph), s = sin(ph), qq = uQ[i];
60
+ disp.xz += qq * a * d * c; disp.y += a * s; nrm.xz -= d * k * a * c; nrm.y -= qq * k * a * s; jac += qq * k * a * s; norm += qq * k * a;
61
+ }
62
+ nrm = normalize(nrm); float jn = jac / max(norm, 0.001); foam = smoothstep(0.0, 0.5, jn) * (0.55 + 0.45 * sin(p.x * 2.7 + p.z * 1.9 - uT * 0.8) * sin(p.z * 3.3 - p.x * 1.1 + uT * 0.6)) * uShape.z;
63
+ edge = 1.0 - smoothstep(0.78, 1.0, max(abs(p.x) / uHalf.x, abs(p.z) / uHalf.y)); hn = disp.y / max(uAmp, 0.01);
64
+ }
65
+ #endif
66
+ `,xb=`vec3 wDisp; vec3 wNrm; float wFoam; float wEdge; float wH; waveEval(position, wDisp, wNrm, wFoam, wEdge, wH);
67
+ vec3 objectNormal = wNrm; vFoam = wFoam; vEdge = wEdge; vH = wH;
68
+ #ifdef USE_TANGENT
69
+ vec3 objectTangent = vec3(tangent.xyz);
70
+ #endif`;function bb(e,n){const s=e.geom,o=new ai(s.w,s.d,s.sx,s.sz);o.rotateX(-Math.PI/2);const i={uT:{value:0},uSp:{value:1},uWv:{value:[0,0,0,0].map(()=>new Is)},uQ:{value:new Is},uHalf:{value:new ca(1,1)},uCrest:{value:new Is},uShape:{value:new Is},uAmp:{value:1},uAlpha:{value:1},uDeep:{value:new Ve},uTint:{value:new Ve}},r=new $s({color:"#ffffff",roughness:.07,metalness:0,ior:1.33,envMapIntensity:1.35,transparent:!0,side:e.mode==="wave"?ks:Za});r.onBeforeCompile=d=>{Object.assign(d.uniforms,i),d.vertexShader=(e.mode==="wave"?`#define WAVE
71
+ `:"")+d.vertexShader.replace("#include <common>",`#include <common>
72
+ `+gb).replace("#include <beginnormal_vertex>",xb).replace("#include <begin_vertex>","vec3 transformed = position + wDisp;"),d.fragmentShader=d.fragmentShader.replace("#include <common>",`#include <common>
73
+ uniform float uAlpha; uniform vec3 uDeep; uniform vec3 uTint; varying float vFoam; varying float vEdge; varying float vH;`).replace("#include <color_fragment>",`#include <color_fragment>
74
+ diffuseColor.rgb = mix(uDeep, uTint, clamp(vH * 0.5 + 0.5, 0.0, 1.0)); diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.92, 0.96, 1.0), vFoam * 0.9); diffuseColor.a *= vEdge * uAlpha;`).replace("#include <roughnessmap_fragment>",`#include <roughnessmap_fragment>
75
+ roughnessFactor = mix(roughnessFactor, 0.78, vFoam);`)},r.customProgramCacheKey=()=>"fxwater-"+e.mode;const l=new dt(o,r);l.frustumCulled=!1,l.renderOrder=n,l.receiveShadow=!0,l.visible=!1,l.isLine=!0;const h=[0,.28,-.42,.66],u=[1,.56,.33,.19],m=[1,.5,.28,.14];return{object:l,update(d,f){const p=e.eval(d,f);if(!p)return l.visible=!1,0;l.visible=!0,l.position.set(...p.pos),l.rotation.y=p.yaw;const y=p.u,g=i;if(g.uT.value=y.t,g.uAlpha.value=p.alpha,g.uDeep.value.setRGB(p.color[0],p.color[1],p.color[2],vs),g.uTint.value.setRGB(p.tint[0],p.tint[1],p.tint[2],vs),e.mode==="ocean"){const v=y.half,b=y.amp,k=y.dir,w=y.wl;g.uSp.value=y.speed,g.uAmp.value=b,g.uHalf.value.set(v[0],v[1]),g.uShape.value.set(0,0,y.foam,0);const S=[0,0,0,0];for(let E=0;E<4;E++){const j=k+h[E],M=Math.PI*2/(w*u[E]),T=b*m[E]*.6;g.uWv.value[E].set(Math.sin(j),Math.cos(j),M,T),S[E]=Math.min(.9,y.choppy/Math.max(.001,M*T*4))}g.uQ.value.set(S[0],S[1],S[2],S[3])}else{const v=y.half;g.uCrest.value.set(y.zc,y.H,y.F,y.B),g.uShape.value.set(y.flood,y.curl,y.foam,v[0])}return 1},setShare(){},hide(){l.visible=!1},dispose(){o.dispose(),r.dispose()}}}const co=new ae,Xr=e=>{e.isLine=!0},yb=`
76
+ attribute vec3 iPos; attribute vec2 iSize; attribute float iRot; attribute vec4 iColor; attribute vec3 iDir; attribute float iSprite;
77
+ uniform float uFacing; uniform float uGrid; uniform float uWhole; varying vec2 vUv; varying vec4 vColor; varying vec2 vCell; varying float vLife; varying float vSeed; varying float vViewZ;
78
+ varying float vBlurK; varying float vKind;
79
+ void main(){
80
+ vec2 c = position.xy; float cs = cos(iRot), sn = sin(iRot);
81
+ vec2 r = vec2(c.x * cs - c.y * sn, c.x * sn + c.y * cs);
82
+ vec3 world; vBlurK = 1.0;
83
+ if (uFacing < 0.5) {
84
+ vec3 right = vec3(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]);
85
+ vec3 up = vec3(viewMatrix[0][1], viewMatrix[1][1], viewMatrix[2][1]);
86
+ world = iPos + right * (r.x * iSize.x) + up * (r.y * iSize.y);
87
+ // motion blur: emitters tag iDir with the particle's travel over the shutter (MOTION_TAG, shared/shotFxSim.js); a sprite that moves
88
+ // more than half its size in that time is smeared along its screen motion, its light spread over the smear (energy kept)
89
+ if (iDir.y > ${Wl/2}.0) {
90
+ vec3 mv = iDir - vec3(0.0, ${Wl}.0, 0.0); vec2 v2 = vec2(dot(mv, right), dot(mv, up)); float L = length(v2), sz = max(iSize.x, iSize.y);
91
+ if (L > 0.5 * sz) {
92
+ vec2 ax = v2 / L, bx = vec2(-ax.y, ax.x);
93
+ world = iPos + (right * ax.x + up * ax.y) * (c.y * (sz + L)) + (right * bx.x + up * bx.y) * (c.x * sz);
94
+ vBlurK = sz / (sz + L);
95
+ }
96
+ }
97
+ } else if (uFacing < 1.5) {
98
+ world = iPos + vec3(r.x * iSize.x, 0.0, r.y * iSize.y);
99
+ } else if (uFacing < 2.5) {
100
+ vec3 n = normalize(iDir); vec3 ref = abs(n.y) > 0.95 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);
101
+ vec3 t = normalize(cross(ref, n)); vec3 b = cross(n, t);
102
+ world = iPos + t * (r.x * iSize.x) + b * (r.y * iSize.y);
103
+ } else {
104
+ vec3 d = normalize(iDir); vec3 toCam = normalize(cameraPosition - iPos); vec3 side = cross(d, toCam);
105
+ side = length(side) < 1e-4 ? vec3(0.0, 1.0, 0.0) : normalize(side);
106
+ world = iPos + d * (c.y * iSize.y) + side * (c.x * iSize.x);
107
+ }
108
+ vUv = c + 0.5; vColor = iColor;
109
+ // the sprite slot's fraction is the particle's age (0-1) when the layer has a material (shared/shotFxSim.js E.age)
110
+ float sp = floor(iSprite + 1e-4); vLife = clamp(iSprite - sp, 0.0, 1.0);
111
+ float col = mod(sp, uGrid), row = floor(sp / uGrid);
112
+ // smoke and flame sprites get a living texture in the fragment shader (billows / licks)
113
+ vKind = uWhole > 0.5 ? 0.0 : abs(sp - ${Gl.smoke}.0) < 0.5 ? 1.0 : abs(sp - ${Gl.flame}.0) < 0.5 ? 2.0 : 0.0;
114
+ vCell = vec2(col / uGrid, 1.0 - (row + 1.0) / uGrid);
115
+ vSeed = fract(dot(iPos, vec3(0.131, 0.071, 0.113)) + iRot * 0.159);
116
+ vec4 mv = viewMatrix * vec4(world, 1.0); vViewZ = -mv.z;
117
+ gl_Position = projectionMatrix * mv;
118
+ }`,vb=`
119
+ uniform sampler2D uMap; uniform float uGrid; uniform float uWhole; varying vec2 vUv; varying vec4 vColor; varying vec2 vCell; varying float vLife; varying float vSeed; varying float vViewZ;
120
+ varying float vBlurK; varying float vKind;
121
+ uniform float uOcclude; uniform float uRampOn; uniform vec3 uRamp[4]; uniform float uDissolve; uniform float uNoiseK; uniform sampler2D uNoise;
122
+ uniform float uSoftOn; uniform sampler2D uDepth; uniform vec2 uDepthSize; uniform float uNear; uniform float uFar; uniform float uSoftDist;
123
+ vec3 ramp(float h){ h = clamp(h, 0.0, 1.0) * 3.0; return h < 1.0 ? mix(uRamp[0], uRamp[1], h) : h < 2.0 ? mix(uRamp[1], uRamp[2], h - 1.0) : mix(uRamp[2], uRamp[3], h - 2.0); }
124
+ void main(){
125
+ vec2 su = vUv;
126
+ if (vKind > 1.5) {
127
+ // flame: two noise octaves rising through the sprite bend it sideways (more toward the tip), so every tongue licks differently
128
+ float n1 = texture2D(uNoise, vec2(vUv.x * 0.8 + vSeed * 5.3, vUv.y * 0.6 - vLife * 1.4 - vSeed * 2.1)).r, n2 = texture2D(uNoise, vec2(vUv.x * 1.7 - vSeed * 3.1, vUv.y * 1.3 - vLife * 2.3)).r;
129
+ su = clamp(vec2(vUv.x + ((n1 - 0.5) * 0.3 + (n2 - 0.5) * 0.12) * (0.25 + vUv.y), vUv.y + (n2 - 0.5) * 0.08), 0.004, 0.996);
130
+ }
131
+ vec2 uv = uWhole > 0.5 ? vUv : vCell + su / uGrid;
132
+ vec4 tex = texture2D(uMap, uv);
133
+ float a = vColor.a * tex.a * vBlurK; vec3 rgb = vColor.rgb * tex.rgb;
134
+ if (vKind > 0.5 && vKind < 1.5) {
135
+ // smoke: the puff's edge erodes into billows that turn over as it ages, and its body is lit unevenly (lighter lobes, darker folds)
136
+ float b1 = texture2D(uNoise, vUv * 0.75 + vec2(vSeed * 6.1, vSeed * 2.9 + vLife * 0.22)).r, b2 = texture2D(uNoise, vUv * 1.6 + vec2(-vSeed * 4.3 + vLife * 0.15, vSeed * 3.7)).r;
137
+ float bil = b1 * 0.65 + b2 * 0.35;
138
+ a *= smoothstep(0.18, 0.62, bil * 0.75 + tex.a * 0.55);
139
+ rgb *= 0.72 + 0.5 * (bil - 0.5) + 0.28 * smoothstep(0.35, 0.8, vUv.y);
140
+ }
141
+ if (uDissolve > 0.0 || uRampOn > 0.5) {
142
+ float n = texture2D(uNoise, vUv * uNoiseK + vec2(vSeed * 7.13, vSeed * 3.71)).r;
143
+ if (uRampOn > 0.5) {
144
+ float peak = max(max(vColor.r, vColor.g), vColor.b);
145
+ rgb = ramp(tex.a * (0.6 + 0.55 * n) * (1.0 - 0.8 * vLife) * 1.25) * peak;
146
+ }
147
+ if (uDissolve > 0.0) {
148
+ float e = n * 0.7 + tex.a * 0.3, cut = vLife * vLife * 0.95, m = smoothstep(cut, cut + 0.08, e);
149
+ float rim = m * (1.0 - smoothstep(cut + 0.02, cut + 0.14, e)) * step(0.02, cut);
150
+ a *= mix(1.0, m * 1.2, uDissolve);
151
+ rgb += rgb * rim * 1.6 * uDissolve;
152
+ }
153
+ }
154
+ if (uSoftOn > 0.5) {
155
+ float d = texture2D(uDepth, gl_FragCoord.xy / uDepthSize).x;
156
+ float sceneZ = -(uNear * uFar) / ((uFar - uNear) * d - uFar);
157
+ a *= clamp((sceneZ - vViewZ) / uSoftDist, 0.0, 1.0);
158
+ }
159
+ if (a < 0.002) discard;
160
+ gl_FragColor = vec4(rgb, a);
161
+ #include <tonemapping_fragment>
162
+ #include <colorspace_fragment>
163
+ #ifdef GLOW
164
+ gl_FragColor = vec4(gl_FragColor.rgb * a * (1.0 + 1.5 * uOcclude), a * uOcclude);
165
+ #endif
166
+ }`;function qd(){const e=new U0,n=new ai(1,1);return e.setAttribute("position",n.getAttribute("position")),e.setAttribute("uv",n.getAttribute("uv")),e.setIndex(n.getIndex()),e}const ur={cam:0,flat:1,plane:2},Ud=e=>e?{blending:Q0,blendEquation:Y0,blendSrc:V0,blendDst:X0,defines:{GLOW:1}}:{blending:Z0};function jb(e,n,s){const o=sb(n),i=e.uniforms,r=s,l=i.uFacing.value;if(!o||!r.isPerspectiveCamera||l===ur.flat||l===ur.plane){i.uSoftOn.value=0;return}i.uSoftOn.value=1,i.uDepth.value=o.texture,i.uDepthSize.value.set(o.width,o.height),i.uNear.value=r.near,i.uFar.value=r.far}const kb=200,ii=(e,n)=>n?e+kb:e;function Xd(e,n){const s=qd(),o=new Ld(new Float32Array(e.max*vi),vi,1);o.setUsage(oa),s.setAttribute("iPos",new $n(o,3,0)),s.setAttribute("iSize",new $n(o,2,3)),s.setAttribute("iRot",new $n(o,1,5)),s.setAttribute("iColor",new $n(o,4,6)),s.setAttribute("iDir",new $n(o,3,10)),s.setAttribute("iSprite",new $n(o,1,13)),s.instanceCount=0;const i=e.tex!=="atlas",r=e.mat,l=r?.ramp&&r.ramp.length>=2?r.ramp:null,h=[0,1,2,3].map(v=>l?new ae(...l[Math.min(l.length-1,Math.round(v*(l.length-1)/3))]):new ae),u=new Ya({vertexShader:yb,fragmentShader:vb,transparent:!0,depthWrite:!1,side:ks,...Ud(e.blend==="add"),uniforms:{uMap:{value:i?eb(e.tex):Jx()},uGrid:{value:i?1:Fg},uWhole:{value:i?1:0},uFacing:{value:e.facing??ur.cam},uOcclude:Ur.uOcclude,uRampOn:{value:l?1:0},uRamp:{value:h},uDissolve:{value:Math.max(0,Math.min(1,r?.dissolve??0))},uNoiseK:{value:r?.noise??.9},uNoise:{value:tb()},uSoftOn:{value:0},uDepth:{value:null},uDepthSize:{value:new ca(1,1)},uNear:{value:.1},uFar:{value:1e3},uSoftDist:{value:.35}}});e.blend!=="add"&&(u.polygonOffset=!1);const m=new dt(s,u);m.frustumCulled=!1,m.renderOrder=ii(n,e.blend==="add"),Xr(m);let d=0,f=1;const p=()=>{s.instanceCount=Math.floor(d*f+(d>0&&d*f<1?1:0)),m.visible=s.instanceCount>0},y=e.sort?new Float32Array(e.max*vi):null,g=[0,0,0];return m.onBeforeRender=(v,b,k)=>{jb(u,v,k),!(!y||d<2)&&(k.getWorldPosition(co),g[0]=co.x,g[1]=co.y,g[2]=co.z,Km(o.array,d,g,y),o.needsUpdate=!0)},{object:m,update(v,b){return d=e.eval(v,b,o.array),o.needsUpdate=d>0,p(),d},setShare(v){f=v,p()},hide(){d=0,m.visible=!1},dispose(){s.dispose(),u.dispose()}}}const wb=`
167
+ attribute vec3 iA; attribute vec3 iB; attribute vec2 iW; attribute vec4 iCA; attribute vec4 iCB;
168
+ uniform float uExt; varying vec2 vUv; varying vec4 vColor; varying float vAlong;
169
+ void main(){
170
+ float x = position.x + 0.5; vec3 d = iB - iA; float len = length(d); vec3 dn = d / max(len, 1e-5);
171
+ vec3 p = mix(iA, iB, x); vec3 toCam = cameraPosition - p; vec3 side = cross(dn, toCam);
172
+ side = length(side) < 1e-6 ? vec3(0.0, 1.0, 0.0) : normalize(side);
173
+ float w = mix(iW.x, iW.y, x);
174
+ vec3 world = p + dn * ((x - 0.5) * 2.0 * w * uExt) + side * (position.y * 2.0 * w);
175
+ vUv = vec2(x, position.y * 2.0); vColor = mix(iCA, iCB, x); vAlong = (x - 0.5) * 2.0 * (1.0 + uExt * 0.0);
176
+ gl_Position = projectionMatrix * viewMatrix * vec4(world, 1.0);
177
+ }`,Mb=`
178
+ uniform float uSoft; uniform float uExt; uniform float uOcclude; varying vec2 vUv; varying vec4 vColor; varying float vAlong;
179
+ void main(){
180
+ float across = abs(vUv.y);
181
+ float prof = pow(max(0.0, 1.0 - across), mix(1.7, 2.6, uSoft));
182
+ float core = pow(max(0.0, 1.0 - across), 5.0);
183
+ float a = vColor.a * (0.35 * prof + 0.65 * core + 0.25 * prof);
184
+ if (a < 0.002) discard;
185
+ gl_FragColor = vec4(vColor.rgb * (0.55 + 0.9 * core), a);
186
+ #include <tonemapping_fragment>
187
+ #include <colorspace_fragment>
188
+ #ifdef GLOW
189
+ gl_FragColor = vec4(gl_FragColor.rgb * a * (1.0 + 1.5 * uOcclude), a * uOcclude);
190
+ #endif
191
+ }`;function Vd(e,n){const s=qd(),o=new Ld(new Float32Array(e.max*ql),ql,1);o.setUsage(oa),s.setAttribute("iA",new $n(o,3,0)),s.setAttribute("iB",new $n(o,3,3)),s.setAttribute("iW",new $n(o,2,6)),s.setAttribute("iCA",new $n(o,4,8)),s.setAttribute("iCB",new $n(o,4,12)),s.instanceCount=0;const i=new Ya({vertexShader:wb,fragmentShader:Mb,transparent:!0,depthWrite:!1,side:ks,...Ud(e.blend!=="alpha"),uniforms:{uExt:{value:e.soft!==void 0?.5:.15},uSoft:{value:e.soft??0},uOcclude:Ur.uOcclude}}),r=new dt(s,i);r.frustumCulled=!1,r.renderOrder=ii(n,e.blend!=="alpha"),Xr(r);let l=0,h=1;const u=()=>{s.instanceCount=Math.floor(l*(h<1?Math.max(h,.7):1)),r.visible=s.instanceCount>0};return{object:r,update(m,d){return l=e.eval(m,d,o.array),o.needsUpdate=l>0,u(),l},setShare(m){h=m,u()},hide(){l=0,r.visible=!1},dispose(){s.dispose(),i.dispose()}}}function Sb(e,n){const s=lb(e.max);s.setColor(n);let o=0;const i=()=>{for(const r of s.meshes)r.count=o;s.glow.count=o,s.group.visible=o>0};return{object:s.group,update(r,l){return o=e.eval(r,l,s.matrix.array,s.glowAttr.array),s.matrix.needsUpdate=o>0,s.glowAttr.needsUpdate=o>0,i(),o},setShare(){},hide(){o=0,i()},dispose(){s.dispose()}}}function Yd(e){const n=pb(e.geo,e.max);let s=0,o=1;const i=()=>{n.mesh.count=e.thin?Math.floor(s*o):s,n.mesh.visible=n.mesh.count>0};return{object:n.mesh,update(r,l){return s=e.eval(r,l,n.mesh.instanceMatrix.array,n.mesh.instanceColor.array),n.mesh.instanceMatrix.needsUpdate=s>0,n.mesh.instanceColor.needsUpdate=s>0,i(),s},setShare(r){o=r,i()},hide(){s=0,i()},dispose(){n.dispose()}}}const Cb=`
192
+ uniform vec2 uR; varying vec3 vObj; varying vec3 vN; varying vec3 vV; varying float vY; varying float vAng;
193
+ void main(){
194
+ vec3 p = position;
195
+ #ifdef COLUMN
196
+ float y = position.y; float rr = mix(uR.x, uR.y, y); p = vec3(position.x * rr, y, position.z * rr);
197
+ vN = normalize(mat3(modelMatrix) * vec3(position.x, 0.0, position.z)); vAng = atan(position.z, position.x);
198
+ #else
199
+ vN = normalize(mat3(modelMatrix) * normal); vAng = 0.0;
200
+ #endif
201
+ vObj = normalize(position); vY = position.y;
202
+ vec4 wp = modelMatrix * vec4(p, 1.0); vV = normalize(cameraPosition - wp.xyz);
203
+ gl_Position = projectionMatrix * viewMatrix * wp;
204
+ }`,Nb=`
205
+ uniform vec3 uColor; uniform float uAlpha; uniform float uScroll; uniform float uStreaks; uniform float uOpen; uniform vec4 uHit[3]; uniform float uHex;
206
+ varying vec3 vObj; varying vec3 vN; varying vec3 vV; varying float vY; varying float vAng;
207
+ float hexDist(vec2 p){ p = abs(p); return max(dot(p, normalize(vec2(1.0, 1.73))), p.x); }
208
+ float hexLine(vec2 uv){
209
+ vec2 r = vec2(1.0, 1.73); vec2 h = r * 0.5; vec2 a = mod(uv, r) - h; vec2 b = mod(uv - h, r) - h;
210
+ vec2 gv = dot(a, a) < dot(b, b) ? a : b; float d = 0.5 - hexDist(gv); return 1.0 - smoothstep(0.015, 0.075, d);
211
+ }
212
+ void main(){
213
+ float ndv = abs(dot(normalize(vN), normalize(vV)));
214
+ #ifdef COLUMN
215
+ float edge = pow(ndv, 0.8);
216
+ float st = 0.5 + 0.5 * sin(vAng * uStreaks + uScroll * 3.0 + vY * 5.0);
217
+ float st2 = 0.5 + 0.5 * sin(vAng * (uStreaks * 1.7 + 1.0) - uScroll * 2.0 + vY * 9.0);
218
+ float streak = clamp(0.3 + 0.9 * pow(st * st2 * 1.7, 1.2), 0.0, 1.0);
219
+ float vert = smoothstep(0.0, 0.08, vY) * pow(max(0.0, 1.0 - vY), 0.9);
220
+ float a = uAlpha * edge * streak * mix(vert, smoothstep(0.0, 0.2, vY) * (1.0 - smoothstep(0.62, 1.0, vY)), uOpen);
221
+ gl_FragColor = vec4(uColor * (0.7 + 0.8 * streak), a);
222
+ #else
223
+ vec3 n = normalize(vObj);
224
+ float fres = pow(1.0 - ndv, 2.4);
225
+ float line = hexLine(vec2(atan(n.z, n.x) * 6.0, n.y * 9.5)) * uHex;
226
+ float ripple = 0.0; float flash = 0.0;
227
+ for (int i = 0; i < 3; i++) {
228
+ vec4 h = uHit[i];
229
+ if (h.w >= 0.0) {
230
+ float ang = acos(clamp(dot(n, normalize(h.xyz)), -1.0, 1.0)); float front = h.w * 2.6;
231
+ float ring = exp(-pow((ang - front) * 4.0, 2.0)) + 0.5 * exp(-pow((ang - front * 0.55) * 5.0, 2.0)); ripple += ring * exp(-h.w * 1.3); flash += exp(-ang * 5.0) * exp(-h.w * 5.0);
232
+ }
233
+ }
234
+ float base = 0.07 + 0.7 * fres;
235
+ float a = uAlpha * (base + line * (0.22 + fres * 0.7) + ripple * (0.9 + line * 1.8) + flash * 1.3);
236
+ gl_FragColor = vec4(uColor * (0.8 + 1.4 * ripple + 1.2 * flash + 0.6 * line), a);
237
+ #endif
238
+ #include <tonemapping_fragment>
239
+ #include <colorspace_fragment>
240
+ }`,Ab=new ae(0,1,0);function Qd(e,n){const s=e.shape==="column",o=s?Math.max(1,e.multi??1):1,i=s?new ws(1,1,1,56,1,!0).translate(0,.5,0):new Un(1,56,36),r=new dn,l=[];for(let m=0;m<o;m++){const d=new Ya({vertexShader:Cb,fragmentShader:Nb,transparent:!0,depthWrite:!1,side:ks,blending:Gr,defines:s?{COLUMN:1}:{},uniforms:{uColor:{value:new Ve},uAlpha:{value:0},uScroll:{value:0},uStreaks:{value:8},uOpen:{value:0},uR:{value:new ca(1,1)},uHex:{value:1},uHit:{value:[new Is(0,0,1,-1),new Is(0,0,1,-1),new Is(0,0,1,-1)]}}}),f=new dt(i,d);f.frustumCulled=!1,f.renderOrder=ii(n,!0),f.visible=!1,Xr(f),l.push(f),r.add(f)}const h=new qe,u=new ae;return{object:r,update(m,d){const f=e.eval(m,d),p=f?Array.isArray(f)?f:[f]:[];return l.forEach((y,g)=>{const v=p[g];if(!v||v.alpha<=.002){y.visible=!1;return}y.visible=!0,y.position.set(...v.pos),y.scale.set(...v.scale),u.set(...v.dir).normalize(),h.setFromUnitVectors(Ab,u),y.quaternion.copy(h);const b=y.material.uniforms;b.uColor.value.setRGB(v.color[0]*v.color[3],v.color[1]*v.color[3],v.color[2]*v.color[3],vs),b.uAlpha.value=v.alpha,b.uScroll.value=v.scroll??0,b.uStreaks.value=v.streaks??8,b.uOpen.value=v.open?1:0,b.uHex.value=v.hex??1;const k=v.taper??0;b.uR.value.set(k<0?1+k:1,k>0?1-k:1),v.hits&&v.hits.forEach((w,S)=>b.uHit.value[S].set(w[0],w[1],w[2],w[3]))}),p.length},setShare(){},hide(){l.forEach(m=>{m.visible=!1})},dispose(){i.dispose(),l.forEach(m=>m.material.dispose())}}}const Tb=`
241
+ #include <common>
242
+ #include <skinning_pars_vertex>
243
+ uniform float uScale;
244
+ varying vec3 vN; varying vec3 vV; varying vec3 vW;
245
+ void main(){
246
+ #include <beginnormal_vertex>
247
+ #include <skinbase_vertex>
248
+ #include <skinnormal_vertex>
249
+ #include <begin_vertex>
250
+ #include <skinning_vertex>
251
+ vec4 wp = modelMatrix * vec4(transformed, 1.0);
252
+ vW = wp.xyz; vN = normalize(mat3(modelMatrix) * objectNormal); vV = normalize(cameraPosition - wp.xyz);
253
+ gl_Position = projectionMatrix * viewMatrix * wp;
254
+ }`,Lb=`
255
+ uniform vec3 uColor; uniform vec3 uCore; uniform float uAlpha; uniform float uTime; uniform float uBase; uniform float uHeight; uniform float uReveal;
256
+ uniform float uCut; uniform float uStars; uniform float uScale; uniform float uFlow;
257
+ varying vec3 vN; varying vec3 vV; varying vec3 vW;
258
+ float hash3(vec3 p){ p = fract(p * 0.3183099 + 0.1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }
259
+ float stars(vec3 p){
260
+ vec3 c = floor(p), f = fract(p) - 0.5; float h = hash3(c);
261
+ vec3 o = vec3(hash3(c + 1.7), hash3(c + 3.1), hash3(c + 5.3)) - 0.5;
262
+ float d = length(f - o * 0.7), tw = 0.55 + 0.45 * sin(uTime * (2.0 + 4.0 * h) + h * 40.0);
263
+ return step(0.72, h) * smoothstep(0.09, 0.0, d) * tw;
264
+ }
265
+ void main(){
266
+ float y = (vW.y - uBase) / max(0.01, uHeight);
267
+ float ndv = abs(dot(normalize(vN), normalize(vV)));
268
+ float rim = pow(1.0 - ndv, 2.2);
269
+ float flow = 0.5 + 0.5 * sin(vW.y / uScale * 9.0 - uTime * 3.0 + sin(vW.x / uScale * 5.0 + uTime) * 1.5);
270
+ vec3 sp = vW / uScale * 7.0;
271
+ float st = (stars(sp) + 0.6 * stars(sp * 1.9 + 11.0)) * uStars;
272
+ float front = uReveal > 0.999 ? 1e3 : uReveal * 1.15 - 0.05;
273
+ float shown = smoothstep(front, front - 0.08, y);
274
+ float edge = 0.45 * exp(-pow((y - front) * 30.0, 2.0)) * step(uReveal, 0.999);
275
+ float cut = smoothstep(uCut - 0.12, uCut + 0.06, y);
276
+ float body = (0.1 + 1.25 * rim + 0.16 * flow * uFlow) * shown;
277
+ vec3 col = uColor * body + uCore * (st * shown * 2.2 + edge * 2.5);
278
+ float a = uAlpha * cut * clamp(body + st * shown + edge, 0.0, 1.6);
279
+ if (a < 0.003) discard;
280
+ gl_FragColor = vec4(col, a);
281
+ #include <tonemapping_fragment>
282
+ #include <colorspace_fragment>
283
+ }`;function Zd(e,n){const s=[];e.traverse(i=>{i.isMesh&&i.visible&&!i.userData.fxMarker&&s.push(i)});const o=s.filter(i=>i.isSkinnedMesh);n.makeEmpty();for(const i of o.length?o:s)n.expandByObject(i,!0);return n}let Eb=null;const Rb=()=>Eb??=Object.assign(Jh(qn["Thiền định"],"#d8dde6",void 0),{name:"fx-ghost-stand-in"}),Ib=e=>{e.isLine=!0};function Pb(e,n,s){const o=new dn;o.name="fx-ghost";const i=new Ya({vertexShader:Tb,fragmentShader:Lb,transparent:!0,depthWrite:!1,blending:Gr,side:Za,uniforms:{uColor:{value:new Ve},uCore:{value:new Ve},uAlpha:{value:0},uTime:{value:0},uBase:{value:0},uHeight:{value:1},uReveal:{value:1},uCut:{value:0},uStars:{value:1},uScale:{value:1},uFlow:{value:1}}});let r=[],l=null,h=-1,u=null,m=0,d=!1;const f=new Nt,p=new Nt,y=new ae,g=new ae,v=new _t,b=()=>{for(const S of r)o.remove(S.copy);r=[],l=null,h=-1},k=S=>{const E=[];return S.traverse(j=>{j.isMesh&&j.visible&&!j.userData.fxMarker&&!j.isLine&&j.layers.isEnabled(0)&&E.push(j)}),E},w=(S,E)=>{b();for(const j of E){let M;if(j.isSkinnedMesh){const T=j,N=new zr(T.geometry,i);N.bindMode=J0,N.bind(T.skeleton,T.bindMatrix),N.updateMatrixWorld=()=>{},N.updateWorldMatrix=()=>{},M=N}else M=new dt(j.geometry,i);M.matrixAutoUpdate=!1,M.matrixWorldAutoUpdate=!1,M.frustumCulled=!1,M.castShadow=!1,M.receiveShadow=!1,M.renderOrder=ii(n,!0),Ib(M),o.add(M),r.push({src:j,copy:M})}l=S,h=E.length};return{object:o,update(S,E){const j=e.eval(S,E);let M=s();if(!j||j.alpha<=.002)return o.visible=!1,0;M||(M=Rb(),M.position.set(E.origin[0],E.origin[1],E.origin[2]),M.rotation.set(0,E.yaw,0),M.scale.setScalar(E.size)),M.updateWorldMatrix(!0,!0);const T=k(M);if((l!==M||T.length!==h)&&w(M,T),!r.length||((l!==u||Math.abs(S-m)>.25||!d)&&(Zd(M,v),u=l,m=S,d=!v.isEmpty()),!d))return o.visible=!1,0;y.set((v.min.x+v.max.x)/2,v.min.y,(v.min.z+v.max.z)/2),g.set(j.offset[0],j.offset[1],j.offset[2]),f.makeTranslation(y.x+g.x,y.y+g.y,y.z+g.z).multiply(p.makeRotationY(j.turn??0)).multiply(p.makeScale(j.scale,j.scale,j.scale)).multiply(p.makeTranslation(-y.x,-y.y,-y.z));for(const{src:C,copy:O}of r)O.matrixWorld.multiplyMatrices(f,C.matrixWorld),O.isSkinnedMesh&&O.bindMatrixInverse.copy(C.matrixWorld).invert(),O.visible=C.visible;const N=y.y+g.y,R=Math.max(.2,(v.max.y-v.min.y)*j.scale),A=i.uniforms;return A.uColor.value.setRGB(j.color[0]*j.color[3],j.color[1]*j.color[3],j.color[2]*j.color[3],vs),A.uCore.value.setRGB(j.core[0],j.core[1],j.core[2],vs),A.uAlpha.value=j.alpha,A.uTime.value=S,A.uBase.value=N,A.uHeight.value=R,A.uReveal.value=j.reveal,A.uCut.value=j.cut,A.uStars.value=j.stars,A.uScale.value=j.scale,A.uFlow.value=j.flow,o.visible=!0,r.length},setShare(){},hide(){o.visible=!1},dispose(){b(),i.dispose()}}}const Fb=new Set(["box","wall","platform","floor"]),Jd=new Set(["model","proxy","box","wall","platform","floor","sphere","cylinder","set","prop"]),$b=1500,Ki=8,ga=new Map,Vc=()=>{},Db=new os({color:"#7d766b",roughness:1,metalness:0,name:"mix-rubble"});function Ob(e,n,s){const o=e.kind==="model"?`${e.model?.gcsUri}|${e.model?.height??""}`:e.kind==="proxy"?JSON.stringify(e.proxy):e.kind==="set"?e.set?.id:e.kind==="prop"?e.prop?.kind:"";return`${e.id}|${e.kind}|${o}|${e.scale.map(i=>i.toFixed(3)).join(",")}|${Math.round(n)}|${s}`}function eu(e){const n=[];return e.traverse(s=>{s instanceof dt&&!s.userData.fxMarker&&n.push(s)}),n}function _b(e,n){const s=n.clone().multiply(e.matrixWorld),o=e;if(!o.isInstancedMesh)return[s];const i=[],r=new Nt;for(let l=0;l<o.count;l++)o.getMatrixAt(l,r),i.push(s.clone().multiply(r));return i}const mr=e=>Array.isArray(e.material)?e.material:[e.material];function zb(e,n,s,o){const i=jx(e,s,o),r=vx(i);if(!r)return null;const l=i.length/3,h=i.reduce((p,y,g)=>g%3===0?p+i[g]:p,0)/l,u=i.reduce((p,y,g)=>g%3===1?p+i[g]:p,0)/l,m=i.reduce((p,y,g)=>g%3===2?p+i[g]:p,0)/l,d=new Float32Array(r.length*3);r.forEach((p,y)=>{d[y*3]=h+(i[p*3]-h)*.97,d[y*3+1]=u+(i[p*3+1]-u)*.97,d[y*3+2]=m+(i[p*3+2]-m)*.97});const f=new At;return f.setAttribute("position",new Rt(d,3)),f.computeVertexNormals(),f.computeBoundingSphere(),f}function Bb(e,n,s,o){const i=Ob(n,s,o),r=ga.get(i);if(r)return r;const l=performance.now(),h=n.scale.map(g=>Math.max(.001,Math.abs(g))),u=[];let m=1,d=0,f=0;const p=Fb.has(n.kind);if(p){const g=Xm(h,s,o);m=Math.cbrt(h[0]*h[1]*h[2]/Math.max(1,g.length));for(const v of g){const b=v.s.map((S,E)=>S/h[E]),k=v.c.map((S,E)=>S/h[E]),w=new Qa(b[0],b[1],b[2]).translate(k[0],k[1],k[2]);w.clearGroups(),w.addGroup(0,w.index.count,0),u.push({geo:w,core:null,c:k,h:b.map(S=>S/2)})}d=1,f=g.length*12}else{e.updateMatrixWorld(!0);const g=e.matrixWorld.clone().invert(),v=[],b=[];for(const D of eu(e)){let $=D.geometry;$.getAttribute("position")&&!$.getAttribute("normal")&&($=$.clone(),$.computeVertexNormals());const W=$.getAttribute("position"),z=$.getAttribute("normal"),Y=$.getAttribute("uv"),J=$.index;if(!W){d+=mr(D).length;continue}const V=(G,_)=>{const ee=new Float32Array(G.count*_);for(let Q=0;Q<G.count;Q++)ee[Q*_]=G.getX(Q),ee[Q*_+1]=G.getY(Q),_>2&&(ee[Q*_+2]=G.getZ(Q));return ee},H=Vm({pos:V(W,3),nor:z?V(z,3):null,uv:Y?V(Y,2):null,index:J?J.array:null,groups:Array.isArray(D.material)&&$.groups.length?$.groups:null},_b(D,g).map(G=>G.elements),d);v.push(H.verts),b.push(H.slots),d+=mr(D).length}let k=new Float32Array(v.reduce((D,$)=>D+$.length,0)),w=0;for(const D of v)k.set(D,w),w+=D.length;let S=new Int32Array(b.reduce((D,$)=>D+$.length,0));w=0;for(const D of b)S.set(D,w),w+=D.length;if(f=S.length,!f)return{key:i,cells:[],cell:1,slots:d,ms:0,tris:0,solid:p};const E=[1/0,1/0,1/0],j=[-1/0,-1/0,-1/0];for(let D=0;D<k.length;D+=Ki)for(let $=0;$<3;$++){const W=k[D+$]*h[$];W<E[$]&&(E[$]=W),W>j[$]&&(j[$]=W)}const M=[0,1,2].map(D=>Math.max(.05,j[D]-E[D]));m=Math.cbrt(M[0]*M[1]*M[2]/Math.max(1,s));const T=Ym(k,Ki,S,m*.7,ep,h);k=T.verts,S=T.slots,f=T.tris;const N=new Float32Array(f*3);for(let D=0;D<f;D++)for(let $=0;$<3;$++)N[D*3+$]=(k[D*24+$]+k[D*24+8+$]+k[D*24+16+$])/3*h[$];const R=Qm(E,j.map((D,$)=>Math.max(D,E[$]+.05)),s,o),A=Zm(N,R),C=[0,1,2].map(D=>(E[D]+j[D])/2/h[D]),O=(h[0]+h[1]+h[2])/3,B=Array.from({length:R.count},()=>[]);for(let D=0;D<f;D++)B[A[D]].push(D);for(const D of B){if(!D.length)continue;D.sort((Q,ve)=>S[Q]-S[ve]||Q-ve);const $=new Float32Array(D.length*9),W=new Float32Array(D.length*9),z=new Float32Array(D.length*6),Y=[1/0,1/0,1/0],J=[-1/0,-1/0,-1/0],V=new At;let H=0,G=S[D[0]];D.forEach((Q,ve)=>{S[Q]!==G&&(V.addGroup(H*3,(ve-H)*3,G),H=ve,G=S[Q]);for(let ye=0;ye<3;ye++){const q=(Q*3+ye)*Ki,pe=(ve*3+ye)*3;for(let ue=0;ue<3;ue++){const U=k[q+ue];$[pe+ue]=U,W[pe+ue]=k[q+3+ue],U<Y[ue]&&(Y[ue]=U),U>J[ue]&&(J[ue]=U)}z[(ve*3+ye)*2]=k[q+6],z[(ve*3+ye)*2+1]=k[q+7]}}),V.addGroup(H*3,(D.length-H)*3,G),V.setAttribute("position",new Rt($,3)),V.setAttribute("normal",new Rt(W,3)),V.setAttribute("uv",new Rt(z,2)),V.computeBoundingSphere();const _=[0,1,2].map(Q=>(Y[Q]+J[Q])/2),ee=zb($,_,[C[0]-_[0],C[1]-_[1],C[2]-_[2]],m*.22/O);u.push({geo:V,core:ee,c:_,h:[0,1,2].map(Q=>Math.max(.01,(J[Q]-Y[Q])/2))})}}const y={key:i,cells:u,cell:Math.max(.05,m),slots:d,ms:performance.now()-l,tris:f,solid:p};for(ga.set(i,y);ga.size>6;){const[g,v]=ga.entries().next().value;ga.delete(g),v.cells.forEach(b=>{b.geo.dispose(),b.core?.dispose()})}return y}function Kb(e,n){return e.k==="particles"?Xd(e,10+n):e.k==="segments"?Vd(e,10+n):e.k==="props"?Yd(e):e.k==="shell"?Qd(e,10+n):null}const es=(e,n)=>typeof e=="number"&&Number.isFinite(e)?e:n,xa=e=>id.has(String(e.fx?.params?.recipe));function Hb(e,n,s,o){const i=e.fx?.attach,r=i&&n?.items.find(l=>l.id===i.to);return i&&r?Jm(ys(r,s,o),zo(e,s,o).position,i):[...ys(e,s,o).position]}class Wb{constructor(n){this.host=n,this.group.name="mix-fx"}group=new dn;effs=new Map;groups=new Map;stage=null;share=1;m=new Nt;r=new Nt;v=new ae;rev=0;marker(n){const s=n.fx?.params??{},o=Number(s.radius??1.5),i=Number(s.falloff??0),r=new dn,l=new dt(new lr(xa(n)?.3:.18),new bs({color:n.color,depthTest:!1,transparent:!0,opacity:.9}));if(l.renderOrder=999,!xa(n)){const h=new dt(new Un(o,28,18),new bs({color:n.color,wireframe:!0,transparent:!0,opacity:.5,depthTest:!1})),u=new dt(new Un(o+i,24,14),new bs({color:n.color,transparent:!0,opacity:.07,depthWrite:!1,depthTest:!1,side:ks}));h.raycast=Vc,u.raycast=Vc,h.renderOrder=u.renderOrder=999,h.userData.mixSphere=!0,r.add(u,h)}return r.add(l),r.traverse(h=>h.layers.set(1)),r.userData.fxMarker=!0,r}sync(n,s){this.stage=n;const o=new Set(s.map(r=>r.id));for(const[r,l]of this.effs)o.has(r)||(this.dropBursts(l.bursts),this.effs.delete(r));for(const r of this.groups.values())this.unbind(r),this.dropBursts(r.bursts);this.groups.clear();const i=new Map;for(const r of s){const h=this.effs.get(r.id)??{item:r,hits:[],samples:[],plan:null,burstKey:"",bursts:[]};h.item=r,this.effs.set(r.id,h);const u=n.items.find(d=>d.id===r.fx?.target?.to&&d.id!==r.id&&Jd.has(d.kind)&&!d.hidden);if(!u){this.dropBursts(h.bursts),h.burstKey="";continue}const m=i.get(u.id)??{target:u,effs:[]};m.effs.push(h),i.set(u.id,m)}for(const[r,{target:l,effs:h}]of i){const u=this.host.object(r);if(!u)continue;const m=h[0].item.fx,d=Number(m.params.chunks),f=m.seed,p=Bb(u,l,d,f),y=h.slice(1).some(k=>Math.round(Number(k.item.fx.params.chunks))!==Math.round(d)||k.item.fx.seed!==f),g=eu(u),v=g.flatMap(mr),b={id:r,target:l,root:u,frac:p,effs:h,note:y?h[0].item.id:null,meshes:[],cores:[],originals:g,planFor:null,planKey:"",matrices:[],rest:0,boxes:[],graph:null,graphKey:"",entries:[],falls:[],burstKey:"",bursts:[]};b.meshes=p.cells.map((k,w)=>{const S=new dt(k.geo,v.length?v:[new os({color:l.color})]);return S.matrixAutoUpdate=!1,S.castShadow=!0,S.receiveShadow=!0,S.name=`chunk ${w}`,S.visible=!1,S.userData.mixTarget=r,this.group.add(S),S}),b.cores=p.cells.map((k,w)=>{if(!k.core)return null;const S=new dt(k.core,Db);return S.matrixAutoUpdate=!1,S.castShadow=!0,S.receiveShadow=!0,S.name=`chunk core ${w}`,S.visible=!1,S.userData.mixTarget=r,this.group.add(S),S}),this.groups.set(r,b)}for(const r of this.effs.values())[...this.groups.values()].some(l=>l.effs.includes(r))||(this.dropBursts(r.bursts),r.burstKey="")}unbind(n){for(const s of n.meshes)this.group.remove(s);for(const s of n.cores)s&&this.group.remove(s);for(const s of n.originals)s.visible=!0;n.meshes=[],n.cores=[],n.originals=[]}dropBursts(n){for(const s of n)for(const o of s.layers)o.dispose(),this.group.remove(o.object);n.length=0}ensure(n,s){if(n.planFor===s)return;n.planFor=s;const o=n.target,i=bn(s),r=Math.max(.1,s.duration),l=Math.max(1/i,r/$b),h=n.effs.map(N=>On(N.item,s)),u=n.effs.map(N=>{const R=N.item.fx?.attach,A=R&&this.stage?.items.find(C=>C.id===R.to);return A?[A.position,A.rotation,A.scale,s.objectKeys?.[A.id]]:null}),m=JSON.stringify([n.effs.map(N=>[N.item.fx,N.item.position,N.item.scale,s.objectKeys?.[N.item.id]]),u,h,o.position,o.rotation,o.scale,s.objectKeys?.[o.id],r,l,n.frac.key]);if(m===n.planKey)return;n.planKey=m,this.rev++;const d=n.frac.cells,f=d.length,p=n.effs[0].item.fx,y=p.params,g=[];for(let N=0;;N++){const R=Math.min(r,N*l);if(g.push(R),R>=r)break}const v=g.map(N=>{const R=ys(o,s,N/r);return Hm(R.position,R.rotation,R.scale)});n.matrices=v.map(N=>new Nt().fromArray(N));const b=y.support!=="off",k=[];n.effs.forEach((N,R)=>{const A=N.item.fx.params,C=h[R];N.plan=null,N.hits=[],N.samples=[],!(C.off||xa(N.item))&&(N.samples=g.map((O,B)=>({t:O,c:Hb(N.item,this.stage,s,O/r),r:Number(A.radius)*Math.max(.05,Math.abs(N.item.fx?.attach?N.item.scale[0]:ys(N.item,s,O/r).scale[0])),m:v[B]})),N.hits=Wm(d,N.samples,{falloff:Number(A.falloff),start:C.start,end:C.start+C.duration,collapse:b?0:Number(A.collapse),cell:n.frac.cell,seed:N.item.fx.seed}),k.push({e:R,hits:N.hits}))});const w=Math.min(...h.filter(N=>!N.off).map(N=>N.start),r);n.rest=Gm(g.map(N=>({t:N})),w),n.boxes=d.map(N=>ox(v[n.rest],N.c,N.h));const S=(()=>{const N=[0,2].map(A=>Math.min(...n.boxes.map(C=>C.min[A]))),R=[0,2].map(A=>Math.max(...n.boxes.map(C=>C.max[A])));return[(N[0]+R[0])/2,0,(N[1]+R[1])/2]})(),E=n.effs.some((N,R)=>!h[R].off&&xa(N.item));n.falls=new Array(f).fill(null);const j=yx(f,k);if(b&&k.length){const N=`${n.frac.key}|${n.rest}|${v[n.rest].map(C=>C.toFixed(4)).join(",")}`;(n.graphKey!==N||!n.graph)&&(n.graph=ix(n.boxes,{cell:n.frac.cell}),n.graphKey=N);const R=hx(n.graph,j,{slack:cx(es(y.collapse,.85)),seed:p.seed,centres:n.boxes.map(C=>C.c)}),A=E?[]:[...Array(f).keys()].filter(C=>!Number.isFinite(j[C])&&!R[C]);n.falls=mx(n.boxes,R,A,{base:n.graph.base,cell:n.frac.cell,seed:p.seed,centre:S})}const M=Float64Array.from(j,(N,R)=>Math.min(N,n.falls[R]?.t??1/0)),T=[];n.effs.forEach((N,R)=>{const A=N.item.fx.params,C=h[R];C.off||!xa(N.item)||(N.plan=px(n.boxes,{mode:String(A.mode),start:C.start,duration:C.duration,yaw:es(A.yaw,0),crumble:es(A.crumble,.6),seed:N.item.fx.seed,cell:n.frac.cell,gone:M,gravity:es(A.gravity,9.8)}),T.push({e:R,plan:N.plan}))}),n.entries=bx(f,{blasts:k,collapses:T,falls:n.falls}),this.ensureBursts(n,s)}makeBurst(n,s,o,i,r,l,h,u,m,d,f={}){if(!_o[n.preset])return null;const p=n.fill?Math.max(n.duration,d.duration-o):n.duration,y={preset:n.preset,intensity:Math.min(3,u),seed:Va(i|0,l,r+7)%1e9,duration:p,loop:!1,params:{...qm(n.preset),...n.params,...f}},g=[],v=[];for(const[b,k]of od(y,{color:h,size:m}).entries()){if(k.k==="light"){v.push(k);continue}const w=Kb(k,b);w&&(w.hide(),w.setShare(this.share),g.push(w),this.group.add(w.object))}return{t:o,at:s,dur:p,tail:_o[n.preset].tail??0,layers:g,lights:v,size:m}}ensureBursts(n,s){const o=Math.min(4,Math.max(.6,n.frac.cell*1.3));for(const d of n.effs){const f=d.item.fx,p=f.params,y=Ua[p.recipe]??Ua.collapse,g=Number(p.debris);On(d.item,s);let v=[];if(d.plan){const k=d.plan,w=[Math.max(...n.boxes.map(E=>E.max[0]))-Math.min(...n.boxes.map(E=>E.min[0])),Math.max(...n.boxes.map(E=>E.max[2]))-Math.min(...n.boxes.map(E=>E.min[2]))];v=[{t:k.t0,at:[k.centre[0],k.base,k.centre[2]],base:!0}];const S=g<=.01?0:Math.max(1,Math.round(y.maxBursts*Math.min(1,.35+g*.55)));for(let E=0;E<S;E++){const j=E/Math.max(1,S)*Math.PI*2+.6;v.push({t:k.t0+k.D*(.3+.6*(E/Math.max(1,S))),at:[k.centre[0]+Math.cos(j)*w[0]*.45,k.base,k.centre[2]+Math.sin(j)*w[1]*.45]})}}else{const k=g<=.01?0:Math.max(1,Math.round(y.maxBursts*Math.min(1,.35+g*.55)));v=Ul(d.hits,k)}const b=JSON.stringify([v.map(k=>[+k.t.toFixed(3),...k.at.map(w=>+w.toFixed(2))]),p.recipe,p.dust,g,d.item.color,f.seed,s.duration,o,f.intensity,n.boxes.length]);b!==d.burstKey&&(this.dropBursts(d.bursts),d.burstKey=b,v.forEach((k,w)=>y.bursts.forEach((S,E)=>{const j=S.at==="base";if(j!==!!k.base)return;const M=j?[0,1,2].map(R=>Math.max(...n.boxes.map(A=>A.max[R]))-Math.min(...n.boxes.map(A=>A.min[R]))):null,T=M?{width:Math.max(2,M[0]*1.6),height:Math.max(2,M[1]),depth:Math.max(2,M[2]*1.6),dust:es(p.dust,1),spread:d.plan?.D??3}:{},N=this.makeBurst(S,k.at,k.t,f.seed,E,w,d.item.color,(.55+.6*g)*f.intensity,j?1:o,s,T);N&&d.bursts.push(N)})))}const i=n.effs[0].item,l=n.falls.map((d,f)=>d?{f:d,i:f}:null).filter(Boolean).map(({f:d,i:f})=>({t:d.t+Math.sqrt(2*Math.max(0,d.p0[1]-d.land)/Math.max(.5,Number(i.fx.params.gravity))),at:[d.to[0],d.land,d.to[1]],i:f})).sort((d,f)=>d.t-f.t||d.i-f.i),h=Math.min(3,l.length),u=[];for(let d=0;d<h;d++){const f=l.slice(Math.floor(d*l.length/h),Math.floor((d+1)*l.length/h));f.length&&u.push({t:f[0].t,at:Gb(f.map(p=>p.at))})}const m=JSON.stringify([u.map(d=>[+d.t.toFixed(3),...d.at.map(f=>+f.toFixed(2))]),i.color,i.fx.seed,s.duration,o]);m!==n.burstKey&&(this.dropBursts(n.bursts),n.burstKey=m,u.forEach((d,f)=>{const p=this.makeBurst({preset:"va_cham",params:{kind:"dust"},duration:1.4},[d.at[0],Math.max(0,d.at[1]),d.at[2]],d.t,i.fx.seed,3,f+50,"#b59a7a",1,o*1.4,s);p&&n.bursts.push(p)}))}impacts(n){const s=[],o=Math.max(.1,n.duration),i=(r,l)=>{const h=r/o;l>.01&&h>=0&&h<=1&&s.push({time:+h.toFixed(4),strength:Math.min(1,l)})};for(const r of this.groups.values()){this.ensure(r,n);for(const u of r.effs){const m=es(u.item.fx.params.shake,.5);if(!(m<=.01))if(u.plan){const d=u.plan;i(d.t0+.05,m*.45),i(d.t0+d.D*.4,m),i(d.t0+d.D*.75,m*.85),i(d.t0+d.D,m*(d.mode==="topple"?1:.6))}else Ul(u.hits,3).forEach((d,f)=>i(d.t,m*(f===0?1:.6)))}const l=es(r.effs[0].item.fx.params.shake,.5),h=r.falls.reduce((u,m)=>m&&m.t<u?m.t:u,1/0);Number.isFinite(h)&&l>.01&&i(h+.35,l*.45)}return s.sort((r,l)=>r.time-l.time||l.strength-r.strength)}update(n,s){const o=[],i=r=>{for(const l of r){const h=s-l.t;if(h<0||h>l.dur+l.tail){l.layers.forEach(m=>m.hide());continue}const u=Lo(l.at,0,l.size);u.target=l.at,u.light=1,u.volume=null;for(const m of l.layers)m.update(h,u);for(const m of l.lights){const d=m.eval(h,u);d&&d.intensity>.01&&o.push({pos:d.pos,color:d.color,intensity:d.intensity})}}};for(const r of this.groups.values()){if(!r.effs.some(d=>!On(d.item,n).off)||!r.frac.cells.length){for(const d of r.originals)d.visible=!0;for(const d of r.meshes)d.visible=!1;for(const d of r.cores)d&&(d.visible=!1);for(const d of r.effs)d.bursts.forEach(f=>f.layers.forEach(p=>p.hide()));r.bursts.forEach(d=>d.layers.forEach(f=>f.hide()));continue}this.ensure(r,n);for(const d of r.originals)d.visible=!1;r.root.updateWorldMatrix(!0,!1);const h=r.root.matrixWorld,u=r.effs[0].item.fx.params,m={gravity:es(u.gravity,9.8),seed:r.effs[0].item.fx.seed,crumble:es(u.crumble,.6)};r.meshes.forEach((d,f)=>{const p=r.entries[f],y=r.cores[f];let g=null,v=null,b=r.rest;if(p?.kind==="hit"){const k=r.effs[p.e],w=k.hits[f],S=k.item.fx.params;g=Um(w,f,s,{strength:Number(S.strength),lift:Number(S.lift),gravity:Number(S.gravity),spin:Number(S.spin),seed:k.item.fx.seed}),v=w.p0,b=w.s}else if(p?.kind==="fall"){const k=r.falls[f];g=ux(k,f,s,m),v=k.p0}else p?.kind==="collapse"&&(g=Tc(r.effs[p.e].plan,r.boxes[f],f,s),v=r.boxes[f].c);d.visible=!0,!g||!v?(d.matrix.copy(h),y&&(y.visible=!1)):(this.m.copy(r.matrices[b]),this.m.premultiply(this.r.makeTranslation(-v[0],-v[1],-v[2])),this.m.premultiply(this.r.makeRotationAxis(this.v.set(g.axis[0],g.axis[1],g.axis[2]),g.angle)),g.extra&&this.m.premultiply(this.r.makeRotationAxis(this.v.set(g.extra.axis[0],g.extra.axis[1],g.extra.axis[2]).normalize(),g.extra.angle)),this.m.premultiply(this.r.makeTranslation(g.pos[0],g.pos[1],g.pos[2])),d.matrix.copy(this.m),y&&(y.visible=!0,y.matrix.copy(this.m),y.matrixWorldNeedsUpdate=!0)),d.matrixWorldNeedsUpdate=!0});for(const d of r.effs)i(d.bursts);i(r.bursts)}return o}setShare(n){this.share=n;for(const s of this.effs.values())for(const o of s.bursts)o.layers.forEach(i=>i.setShare(n));for(const s of this.groups.values())for(const o of s.bursts)o.layers.forEach(i=>i.setShare(n))}pick(n){const s=this.group.children.filter(i=>i.visible&&i.userData.mixTarget);if(!s.length)return null;this.group.updateMatrixWorld(!0);const o=n.intersectObjects(s,!1)[0];return o?{id:String(o.object.userData.mixTarget),distance:o.distance}:null}groupOf(n){for(const s of this.groups.values())if(s.effs.some(o=>o.item.id===n))return s;return null}stats(n){return[...this.effs.values()].map(s=>{const o=this.groupOf(s.item.id),i=o?o.effs.indexOf(s):-1,r=o?o.entries.filter((l,h)=>l&&n>=l.t&&(l.kind!=="collapse"||Tc(o.effs[l.e].plan,o.boxes[h],h,n))).length:0;return{id:s.item.id,target:o?.id??null,chunks:o?.frac.cells.length??0,tris:o?.frac.tris??0,ms:Math.round(o?.frac.ms??0),broken:r,hit:s.hits.filter(Boolean).length,bursts:s.bursts.length,falling:o?o.entries.filter(l=>l?.kind==="fall").length:0,own:o?o.entries.filter(l=>l&&l.e===i).length:0,cores:o?o.cores.filter(Boolean).length:0,first:s.hits.reduce((l,h)=>h&&(l===null||h.t<l)?h.t:l,null),lead:o?.effs[0].item.id??null,overridden:!!o&&i>0&&o.note!==null}})}chunkCentres(n){const s=this.groupOf(n);return s?s.meshes.map((o,i)=>{const r=s.frac.cells[i].c,l=new ae(r[0],r[1],r[2]).applyMatrix4(o.matrix);return[l.x,l.y,l.z]}):[]}visibleCounts(n){const s=this.groupOf(n);return s?{chunks:s.meshes.filter(o=>o.visible).length,cells:s.frac.cells.length,originals:s.originals.filter(o=>o.visible).length,meshes:this.group.children.filter(o=>o.userData.mixTarget===s.id&&o.isMesh&&!o.name.includes("core")&&o.visible).length}:null}dispose(){for(const n of this.groups.values())this.unbind(n),this.dropBursts(n.bursts);for(const n of this.effs.values())this.dropBursts(n.bursts);this.groups.clear(),this.effs.clear(),this.group.parent?.remove(this.group)}}function Gb(e){const n=e.reduce((s,o)=>[s[0]+o[0],s[1]+o[1],s[2]+o[2]],[0,0,0]);return[n[0]/e.length,n[1]/e.length,n[2]/e.length]}const qb=Math.PI/180,Ub=yn.maxLights,Xb={day:1,golden:.8,overcast:.85,night:.22};class Vb{constructor(n,s){this.host=s,this.group.name="fx",this.mix=new Wb(s),n.add(this.group,this.pathGroup,this.mix.group)}group=new dn;insts=new Map;lights=[];share=1;heat=[];light={fill:0,color:[1,1,1],pos:null,sources:[]};stage;only=null;pathGroup=new dn;mix;syncPath(n,s){this.pathGroup.traverse(h=>{(h instanceof dt||h instanceof Fi)&&(h.geometry.dispose(),h.material.dispose())}),this.pathGroup.clear();const o=s&&n.items.find(h=>h.id===s.itemId),i=o?.fx?.path;if(!s||!i||i.length<2)return;const r=tp(i),l=new Fi(new At().setFromPoints(Array.from({length:48},(h,u)=>new ae(...r.at(u/47)))),new bc({color:"#b8df78",depthTest:!1,transparent:!0,opacity:.9}));l.renderOrder=998,l.layers.set(1),this.pathGroup.add(l),i.forEach((h,u)=>{const m=new dt(new Un(.1,14,10),new bs({color:u===s.selected?"#ffad52":u===0?"#7fe9ff":"#b8df78",depthTest:!1}));m.position.set(...h),m.userData.fxPoint=u,m.renderOrder=999,m.layers.set(1),this.pathGroup.add(m)})}pathHandles(){return this.pathGroup.children.filter(n=>n.userData.fxPoint!==void 0)}setFilter(n){this.only=n}get active(){return this.insts.size>0}marker(n){if(n.fx?.preset===tr)return this.mix.marker(n);const s=new dn,o=new dt(new lr(.13),new bs({color:n.color,wireframe:!0,depthTest:!1,transparent:!0,opacity:.9})),i=new dt(new lr(.06),new bs({color:n.color,depthTest:!1,transparent:!0,opacity:.85})),r=new Fi(new At().setFromPoints([new ae(0,0,0),new ae(0,-.4,0)]),new bc({color:n.color,depthTest:!1,transparent:!0,opacity:.45}));return o.renderOrder=i.renderOrder=r.renderOrder=999,s.add(o,i,r),s.traverse(l=>l.layers.set(1)),s.userData.fxMarker=!0,s.position.y=0,s}sync(n){this.stage=n;const s=new Map;let o=0,i=0;for(const r of n.items){if(r.kind!=="fx"||!r.fx||r.hidden)continue;if(++i>yn.maxItems)break;const l=nr(r.fx);if(!l.fx)continue;const h=sr(l.fx);h>yn.maxParticlesPerItem||o+h>yn.maxTotalParticles||(o+=h,s.set(r.id,r))}for(const[r,l]of this.insts)s.has(r)||this.drop(r,l);for(const[r,l]of s){const h=this.sizeOf(l,n),u=JSON.stringify([l.fx,l.color,h]),m=this.insts.get(r);if(m?.key===u){m.item=l;continue}m&&this.drop(r,m),this.insts.set(r,this.build(l,h,u))}this.mix.sync(n,[...s.values()].filter(r=>r.fx?.preset===tr)),this.ensureLights()}sizeOf(n,s){const o=Math.max(.1,n.scale[0]),i=n.fx?.attach&&s.items.find(r=>r.id===n.fx.attach.to);return o*(i?this.host.figureScale(i)*Math.max(.1,i.scale[1]):1)}build(n,s,o){const i=nr(n.fx).fx,r=od(i,{color:n.color,size:s}),l=new dn;l.name=`fx:${n.name}`;const h=[],u=[],m=[],d=r.length?Qb(n.color):[.3,.8,1];return r.forEach((f,p)=>{if(f.k==="light"){u.push(f);return}if(f.k==="heat"){m.push(f);return}const y=f.k==="particles"?Xd(f,10+p):f.k==="segments"?Vd(f,10+p):f.k==="swords"?Sb(f,d):f.k==="props"?Yd(f):f.k==="water"?bb(f,5+p):f.k==="ghost"?Pb(f,10+p,()=>n.fx?.attach?this.host.object(n.fx.attach.to):void 0):Qd(f,10+p);y.hide(),y.setShare(this.share),h.push(y),l.add(y.object)}),l.visible=!1,this.group.add(l),{item:n,key:o,layers:h,defs:r,tail:np(i.preset),group:l,lights:u,heats:m,budget:sr(i),share:this.share}}drop(n,s){s.layers.forEach(o=>o.dispose()),this.group.remove(s.group),this.insts.delete(n)}ensureLights(){if(this.insts.size&&!this.lights.length)for(let n=0;n<Ub;n++){const s=new eg(16777215,0,0,2);s.visible=!0,this.lights.push(s),this.group.add(s)}if(!this.insts.size&&this.lights.length){for(const n of this.lights)this.group.remove(n),n.dispose();this.lights=[]}}frameOf(n,s,o,i,r=0){const l=n.fx?.attach,h=l&&this.host.object(l.to);if(!l||!h)return Lo([o.position.x,o.position.y,o.position.z],o.rotation.y,s);h.updateWorldMatrix(!0,!1);const u=zo(n,i??{},r),m=u.yaw*qb,d=(l.follow==="position"?0:h.rotation.y)+m,f=new ae(...u.position);let p;if(l.hand&&l.tip){const y=this.stage?.items.find(v=>v.hold?.by===l.to&&v.hold.hand===l.hand&&v.prop&&!v.hidden),g=Xl(h,l.hand);if(y?.prop&&y.hold&&g.frame){const v=sp(g.frame,y.prop.kind,y.hold.angle??0,y.hold.tilt,g.fist),b=v.tip.clone().sub(v.grip);return Lo([v.tip.x,v.tip.y,v.tip.z],Math.atan2(b.x,b.z),s)}}if(l.hand){o.userData.fxOffsetYaw=d,o.userData.fxOffsetScale=1;const y=Xl(h,l.hand);p=y.frame?y.frame.localToWorld(y.fist.clone()):h.getWorldPosition(new ae).add(new ae(l.hand==="R"?-.3:.3,1,.3)),p.add(f.applyAxisAngle(new ae(0,1,0),d))}else{const y=h.getWorldPosition(new ae),g=l.part?h.getObjectByName("head")?.getWorldPosition(new ae):void 0,v=g&&l.part==="head"?g:g?y.clone().lerp(g,.74):y;o.userData.fxOffsetYaw=l.follow==="position"?0:h.rotation.y,o.userData.fxOffsetScale=h.scale.x||1,p=v.add(f.multiply(h.scale).applyAxisAngle(new ae(0,1,0),l.follow==="position"?0:h.rotation.y))}return Lo([p.x,p.y,p.z],d,s)}hidden=new Set;hideTargets(n){const s=n.fx?.target,o=s&&this.host.object(s.to);if(!s||!o)return[];if(!s.name)return[o];const i=s.name.toLowerCase(),r=[];return o.traverse(l=>{l instanceof dt&&l.name.toLowerCase().includes(i)&&r.push(l)}),r}volumeOf(n){const s=n.fx?.target,o=s&&this.host.object(s.to),i=s&&this.stage?.items.find(m=>m.id===s.to);if(!s||!o||!i)return null;o.updateWorldMatrix(!0,!0);const r=m=>[m.r,m.g,m.b];if(s.name){const m=s.name.toLowerCase(),d=new _t;let f=null;if(o.traverse(g=>{if(g instanceof dt&&g.name.toLowerCase().includes(m)){d.expandByObject(g);const v=Array.isArray(g.material)?g.material[0]:g.material;!f&&v.color&&(f=r(v.color))}}),d.isEmpty())return null;const p=d.getSize(new ae),y=d.getCenter(new ae);return p.x>=p.z?{size:[p.x,p.y,p.z],base:[y.x,d.min.y,y.z],yaw:0,color:f??r(new Ve(i.color))}:{size:[p.z,p.y,p.x],base:[y.x,d.min.y,y.z],yaw:Math.PI/2,color:f??r(new Ve(i.color))}}if(i.kind==="proxy"&&i.proxy){const m=i.proxy.dims,d=o.scale,f=o.getWorldPosition(new ae);return{size:[m[0]*d.x,m[1]*d.y,m[2]*d.z],base:[f.x,f.y,f.z],yaw:o.rotation.y,color:r(new Ve(i.color))}}const l=new _t().setFromObject(o);if(l.isEmpty())return null;const h=l.getSize(new ae),u=l.getCenter(new ae);return{size:[h.x,h.y,h.z],base:[u.x,l.min.y,u.z],yaw:0,color:r(new Ve(i.color))}}targetOf(n){const s=n.fx?.target,o=s&&this.host.object(s.to);if(!s||!o)return null;o.updateWorldMatrix(!0,!0);const i=o.getWorldPosition(new ae),r=this.stage?.items.find(m=>m.id===s.to)?.kind==="person";if(s.part==="feet")return[i.x,i.y,i.z];const l=r?o.getObjectByName("head")?.getWorldPosition(new ae):null;if(s.part==="head"&&l)return[l.x,l.y+.1,l.z];if(r&&l){const m=i.clone().lerp(l,.74);return[m.x,m.y,m.z]}const h=new _t().setFromObject(o);if(h.isEmpty())return[i.x,i.y+1,i.z];const u=h.getCenter(new ae);return[u.x,u.y,u.z]}headOf(n){const s=n.fx?.attach,o=s&&this.host.object(s.to);if(!o)return null;let i=o.getObjectByName("head");if(i||o.traverse(l=>{!i&&/head/i.test(l.name)&&!/top|end|scale|ref|_end|nub/i.test(l.name)&&(i=l)}),i){const l=i.getWorldPosition(new ae);return[l.x,l.y,l.z]}const r=new _t().setFromObject(o);return r.isEmpty()?null:[(r.min.x+r.max.x)/2,r.max.y-(r.max.y-r.min.y)*.08,(r.min.z+r.max.z)/2]}feetBox=new _t;feetOf(n){const s=n.fx?.attach,o=s&&this.host.object(s.to);if(!o)return null;const i=Zd(o,this.feetBox);return i.isEmpty()?null:[(i.min.x+i.max.x)/2,i.min.y,(i.min.z+i.max.z)/2]}offsetAfterDrag(n,s,o,i){const r=this.stage?.items.find(p=>p.id===n),l=this.host.object(n);if(!r?.fx?.attach||!l?.userData.fxAttached)return null;const h=zo(r,s,o),u=l.userData.fxOffsetYaw??0,m=l.userData.fxOffsetScale??1,d=new ae(l.position.x-i.position[0],l.position.y-i.position[1],l.position.z-i.position[2]).applyAxisAngle(new ae(0,1,0),-u).divideScalar(m),f=p=>+p.toFixed(3);return{position:[f(h.position[0]+d.x),f(h.position[1]+d.y),f(h.position[2]+d.z)],rotation:[0,f(h.yaw+gn.radToDeg(l.rotation.y-i.yaw)),0]}}impacts(n,s){const o=ap(n.items,s),i=this.mix.impacts(s);return i.length?[...o,...i]:o}get impactsRev(){return this.mix.rev}pickChunk(n){return this.mix.pick(n)}mixStats(n){return this.mix.stats(n)}update(n,s,o){if(!this.stage)return;const i=[],r=new Set;this.heat=[],Ur.uOcclude.value=qc[this.stage.lighting?.time??"day"]??qc.day;for(const l of this.insts.values()){const h=this.host.object(l.item.id);h&&h.traverse(k=>{k.userData.fxMarker&&(k.visible=o)});const u=On(l.item,n),m=h?op(u,s,l.tail):null,d=_o[l.item.fx.preset]?.hides===!0;if(d&&!u.off&&s>=u.start)for(const k of this.hideTargets(l.item))r.add(k);if(m===null||!h||this.only&&!this.only(l.item)){l.group.visible=!1,l.layers.forEach(k=>k.hide());continue}l.group.visible=!0;const f=this.sizeOf(l.item,this.stage),p=this.frameOf(l.item,f,h,n,n.duration>0?s/n.duration:0);p.target=this.targetOf(l.item),p.head=this.headOf(l.item);const y=l.defs.some(k=>k.k==="ghost");p.feet=y?this.feetOf(l.item):null;const g=y&&l.item.fx?.attach&&!l.item.fx.attach.hand&&!l.item.fx.attach.part?this.host.object(l.item.fx.attach.to):void 0;p.shift=g?(()=>{const k=g.getWorldPosition(new ae);return[p.origin[0]-k.x,p.origin[1]-k.y,p.origin[2]-k.z]})():null,p.volume=d?this.volumeOf(l.item):null,p.light=Xb[this.stage.lighting?.time??"day"]??1,o&&h.children[0]?.userData.fxMarker;for(const k of l.layers)k.update(m,p);for(const k of l.lights){const w=k.eval(m,p);w&&(w.intensity>.01||(w.fill??0)>.01)&&i.push({pos:w.pos,color:w.color,intensity:w.intensity,fill:w.fill??Yc(w.intensity)})}for(const k of l.heats){const w=k.eval(m,p);w&&w.amount>.01&&this.heat.push(w)}const v=h.children.find(k=>k.userData.fxMarker),b=l.item.fx?.attach;h.userData.fxAttached=!!b&&!(b.hand&&b.tip),b&&!h.userData.fxDragging&&(h.position.set(...p.origin),h.rotation.set(0,p.yaw,0),h.updateMatrixWorld(!0)),v&&v.position.set(0,0,0)}for(const l of this.hidden)r.has(l)||(l.visible=!0);for(const l of r)l.visible=!1;this.hidden=r,i.push(...this.mix.update(n,s).map(l=>({...l,fill:Yc(l.intensity)}))),i.sort((l,h)=>h.intensity-l.intensity),this.light=Yb(i),this.lights.forEach((l,h)=>{const u=i[h];u?(l.position.set(...u.pos),l.color.setRGB(u.color[0],u.color[1],u.color[2],vs),l.intensity=u.intensity):l.intensity=0})}setQuality(n){const s=n==="draft"?ip:1;if(s!==this.share){this.share=s;for(const o of this.insts.values())o.layers.forEach(i=>i.setShare(s));this.mix.setShare(s)}}dispose(){for(const[n,s]of[...this.insts])this.drop(n,s);this.mix.dispose();for(const n of this.lights)n.dispose();this.lights=[],this.pathGroup.clear(),this.group.parent?.remove(this.group,this.pathGroup)}stats(){return[...this.insts.values()].map(n=>({id:n.item.id,name:n.item.name,visible:n.group.visible,budget:n.budget}))}}const Yc=e=>Math.max(0,e-24)/220;function Yb(e){let n=0,s=0,o=[1,1,1],i=null;for(const l of e)n+=l.fill,l.fill>s&&(s=l.fill,o=l.color,i=l.pos);const r=e.filter(l=>l.intensity>.5).slice(0,4).map(l=>({pos:l.pos,color:l.color,intensity:l.intensity}));return{fill:Math.min(2,n),color:o,pos:i,sources:r}}function Qb(e){const n=new Ve(e);return[n.r,n.g,n.b]}is.fxFactory=(e,n)=>new Vb(e,n);is.fxPrompt=e=>Og(e.items,e.shots.find(n=>n.id===e.activeShot)??e.shots[0]);is.codeModel=e=>e.gen?.kind!=="code"?Promise.reject(new Error("not a code model")):Mg(e.gen.code);const tu={corner:[.01836,-.09969,.15467],upper:[0,-.09717,.1634],lower:[0,-.11192,.15558],cheek:[.03455,-.07455,.11851],browIn:[.01285,-.00904,.14251],browMid:[.02998,-.00104,.13851],browOut:[.04568,-.00704,.12451],nostril:[.011,-.07855,.1674],lidLow:[.02855,-.04704,.13651],chin:[0,-.14492,.14958]},Ct=!0,ft=(e,n=e,s=e)=>[e,n,s];function nu(e){const n=g=>[Math.abs(g[0]),g[1],g[2]],s=n(e.corner),o=n(e.cheek),i=n(e.browIn),r=n(e.browMid),l=n(e.browOut),h=n(e.nostril),u=n(e.lidLow),m=e.upper,d=e.lower,f=e.chin,p=[(h[0]+s[0])/2+.008,(h[1]+s[1])/2,(h[2]+s[2])/2-.006],y=[r[0],r[1]+.022,r[2]-.006];return{smile:[[s,ft(.024,.022,.018),[.0042,.005,-.0028],Ct],[p,ft(.014,.016,.014),[.0014,.0026,.0014],Ct],[o,ft(.022,.018,.02),[.001,.0034,.002],Ct],[u,ft(.012,.008,.01),[0,.0012,4e-4],Ct],[m,ft(.014,.006,.01),[0,.0011,-4e-4]],[d,ft(.014,.006,.01),[0,-5e-4,-6e-4]]],angry:[[i,ft(.014,.011,.012),[-.0024,-.0032,.0012],Ct],[r,ft(.014,.011,.012),[-8e-4,-.0018,6e-4],Ct],[h,ft(.008),[.0011,7e-4,0],Ct],[s,ft(.013,.011,.012),[-8e-4,-.0014,0],Ct],[m,ft(.011,.006,.009),[0,-5e-4,3e-4]],[d,ft(.011,.006,.009),[0,7e-4,4e-4]],[f,ft(.016,.012,.012),[0,.001,6e-4]]],surprise:[[i,ft(.016,.013,.014),[0,.0042,4e-4],Ct],[r,ft(.017,.014,.014),[0,.005,3e-4],Ct],[l,ft(.015,.013,.013),[0,.0036,0],Ct],[y,ft(.03,.016,.02),[0,.0014,0],Ct],[s,ft(.012,.01,.011),[-.0013,-5e-4,2e-4],Ct]],sad:[[i,ft(.013,.011,.012),[5e-4,.0036,5e-4],Ct],[l,ft(.013,.011,.012),[0,-.0018,0],Ct],[s,ft(.016,.016,.014),[-6e-4,-.0046,-6e-4],Ct],[d,ft(.011,.006,.009),[0,.0011,9e-4]],[f,ft(.016,.012,.012),[0,.0014,8e-4]]],pain:[[i,ft(.013,.011,.012),[-.002,-9e-4,9e-4],Ct],[r,ft(.014,.011,.012),[0,-.0022,5e-4],Ct],[o,ft(.02,.016,.018),[7e-4,.0032,.0014],Ct],[s,ft(.018,.016,.014),[.0044,-.0012,-.0024],Ct],[m,ft(.012,.006,.009),[0,.0019,3e-4]],[h,ft(.009),[9e-4,.0013,0],Ct],[u,ft(.011,.008,.01),[0,.0014,5e-4],Ct]]}}let su=nu(tu);function Zb(e){su=nu(e??tu)}const Jb=e=>e>=1?0:(1-e)**4*(1+4*e);function ey(e,n,s,o,i,r=1){for(const[l,h,u,m]of su[e])for(const d of m?[1,-1]:[1]){const f=Math.hypot((n-l[0]*d)/h[0],(s-l[1])/h[1],(o-l[2])/h[2]);if(f>=1)continue;const p=Jb(f)*r;i[0]+=u[0]*d*p,i[1]+=u[1]*p,i[2]+=u[2]*p}}function au(e,n,s){const o=e.length/3,i=[];for(const r of Ir){const l=new Float32Array(o*3),h=[0,0,0];for(let u=0;u<o;u++){const m=s?s(u):1;m<=0||(h[0]=h[1]=h[2]=0,ey(r,e[u*3]-n[0],e[u*3+1]-n[1],e[u*3+2]-n[2],h,m),l[u*3]=h[0],l[u*3+1]=h[1],l[u*3+2]=h[2])}i.push(l)}return i}let ta=null,ba=null;const pr=new Set;function ty(e){const n=new Uint8Array(e,0,8);if(String.fromCharCode(...n.slice(0,4))!=="HQB1")throw new Error("HQ character asset: bad magic");const s=new DataView(e).getUint32(4,!0),o=JSON.parse(new TextDecoder().decode(new Uint8Array(e,8,s)));if(o.version!==Vl)throw new Error(`HQ character asset: version ${o.version}, expected ${Vl}`);const i=8+s+((8+s)%4?4-(8+s)%4:0),r=p=>new Float32Array(e,i+p.at,p.n),l=p=>new Uint8Array(e,i+p.at,p.n),h=p=>new Uint16Array(e,i+p.at,p.n),u=p=>new Uint32Array(e,i+p.at,p.n),m=p=>new Int16Array(e,i+p.at,p.n),d=o.lods.map(p=>({vertices:p.vertices,triangles:p.triangles,position:r(p.position),index:p.index32?u(p.index):h(p.index),skinIndex:l(p.skinIndex),skinWeight:l(p.skinWeight),region:l(p.region),morphs:p.morphs.map(y=>({data:m(y),scale:y.scale}))})),f=new Map;for(const p of o.hair)f.set(p.id,{id:p.id,kind:p.kind,position:r(p.position),index:h(p.index),skinIndex:l(p.skinIndex),skinWeight:l(p.skinWeight),flow:r(p.flow),bones:p.chains.bones,chains:p.chains.chains});return{version:o.version,license:o.license,bones:o.bones,regions:o.regions,morphs:o.morphs,lods:d,hair:f,bind:o.bind,face:o.face,sources:o.sources??[],bytes:e.byteLength}}function ny(e){ta=ty(e),Zb(ta.face.landmarks);for(const n of[...pr])n();return ta}const Vr=()=>ta;function sy(e){return ta?Promise.resolve(ta):ba||(ba=fetch(`/${rp}`).then(s=>{if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.arrayBuffer()}).then(ny).catch(s=>{throw ba=null,s}),ba)}function ou(e){return pr.add(e),()=>{pr.delete(e)}}const Ts=gn.degToRad,Qc=new qe,ay=new qe;new cr;function oy(e){const n=cd(e),s=Math.min(1,Math.max(0,(e.blink||0)/100));let o=0,i=0,r=0;for(const l of Ir)o+=ji[l].lidU*n[l],i+=ji[l].lidD*n[l],r+=ji[l].jaw*n[l];return o=o-(e.eyePitch||0)*.45,o=o+(46-o)*s,i=i+(4-i)*s,{lidU:Math.max(-14,Math.min(46,o)),lidD:Math.max(-6,Math.min(14,i)),jaw:Math.max(0,Math.min(22,r))}}function Yr(e,n,s={}){const o=new dn,i=new Map;for(const h of ti(e,n,s)){const u=new _a;u.name=h.name,(h.parent?i.get(h.parent):o).add(u),i.set(h.name,u)}const r=new _a;r.name="pelvis",i.get("torso").add(r),i.set("pelvis",r);for(const[h,,u]of rd){const m=new _a;m.name=h,i.get(u).parent.add(m),i.set(h,m)}const l={root:o,body:i.get("torso"),bones:i};return qo(l,e,n,s),l}function qo(e,n,s,o={}){const{bones:i}=e;for(const u of ti(n,s,o)){const m=i.get(u.name);m.position.set(u.p[0],u.p[1],u.p[2]),m.rotation.set(Ts(u.r[0]),Ts(u.r[1]),Ts(u.r[2]),u.order),m.scale.setScalar(u.s)}const r=o.bind?{lidU:0,lidD:0,jaw:0}:oy(s);for(const u of["L","R"])i.get(`lidU${u}`).rotation.set(Ts(r.lidU),0,0),i.get(`lidD${u}`).rotation.set(Ts(-r.lidD),0,0);i.get("jaw").rotation.set(Ts(r.jaw),0,0);const l=o.bind?0:(s.lean||0)+Xa(n).torsoLean,h=i.get("pelvis");h.position.set(0,lp,0),h.rotation.set(Ts(-ld*l),0,0),h.scale.setScalar(1);for(const[u,m,d]of rd){const f=i.get(d),p=i.get(u);p.position.copy(f.position),Qc.copy(m==="pelvis"?h.quaternion:ay.identity()),p.quaternion.copy(Qc).slerp(f.quaternion,.5),p.scale.setScalar(1+(f.scale.x-1)*.5)}}const ya=new Map,iu=e=>(e.userData.shared=!0,e.userData.realDispose=e.dispose.bind(e),e.dispose=()=>{},e);function iy(e,n){return e.morphs.map(s=>{const o=n[s.param]??s.from,i=(o-s.from)/(s.to-s.from);return i>0?Math.min(i,1.6):0})}function rs(e){const n=e.bind.head;return[n[0]+ea[0],n[1]+ea[1],n[2]+ea[2]]}function ry(e){const n=e.face.stats,s=.079/n.half,o=.13/(n.crown-n.eye),i=.202/(n.front-n.back);return new Nt().makeTranslation(0,n.eye-.026/o,n.back+.117/i).multiply(new Nt().makeScale(1/s,1/o,1/i))}function ly(e,n,s=0){const o=e.lods[s],i=Float32Array.from(o.position);iy(e,n).forEach((h,u)=>{if(!h)return;const m=o.morphs[u],d=h*m.scale;for(let f=0;f<i.length;f++)i[f]+=m.data[f]*d}),n.fem>.3&&cy(e,o,i,Math.min(1,(n.fem-.3)/.4),s);const l=ru(n.fem);if(l>0){const h=cu(e,o),u=[0,0,0];for(let m=0;m<o.vertices;m++){const d=h(m);d&&(lu(e,i[m*3],i[m*3+1],i[m*3+2],l*d,u),i[m*3]+=u[0],i[m*3+1]+=u[1],i[m*3+2]+=u[2])}}return i}const ru=e=>Math.min(1,Math.max(0,(e-.3)/.4));function lu(e,n,s,o,i,r){if(r[0]=r[1]=r[2]=0,!i)return r;const l=rs(e),h=e.face.landmarks,u=n-l[0],m=s-l[1],d=o-l[2],f=(w,S,E)=>{const j=Math.min(1,Math.max(0,(E-w)/(S-w)));return j*j*(3-2*j)},p=h.mouthY,y=(h.upper[2]+h.lower[2])/2,g=Math.exp(-((u/.03)**2+((m-p)/.02)**2))*f(y-.035,y-.012,d);r[0]-=u*.1*g,r[1]-=(m-p)*.55*g,r[2]-=.009*g;const v=h.nostril[1]+.004,b=Math.exp(-((u/.024)**2+((m-v)/.022)**2))*f(h.cheek[2]-.005,h.nostril[2]-.02,d);r[0]-=u*.22*b,r[2]-=.003*b;const k=f(h.cheek[1]+.025,h.chin[1],m)*(1-f(h.chin[1]-.01,h.chin[1]-.045,m))*f(-.05,.05,d);return r[0]-=u*.16*k,r[0]*=i,r[1]*=i,r[2]*=i,r}function cy(e,n,s,o,i){const r=s.length/3,l=e.bind.torso,h=e.bones.indexOf("torso"),u=(H,G,_)=>{const ee=Math.min(1,Math.max(0,(_-H)/(G-H)));return ee*ee*(3-2*ee)},m=new Float32Array(r);for(let H=0;H<r;H++){let G=0;for(let ve=0;ve<4;ve++)n.skinIndex[H*4+ve]===h&&(G+=n.skinWeight[H*4+ve]/255);if(G<=0)continue;const _=s[H*3],ee=s[H*3+1]-l[1],Q=s[H*3+2]-l[2];m[H]=o*Math.min(1,G*1.5)*u(.1,.18,ee)*(1-u(.4,.48,ee))*u(0,.05,Q)*(1-u(.15,.21,Math.abs(_)))}const d=new Int32Array(r),f=new Map;for(let H=0;H<r;H++){const G=`${Math.round(s[H*3]*1e4)}|${Math.round(s[H*3+1]*1e4)}|${Math.round(s[H*3+2]*1e4)}`,_=f.get(G);_===void 0?(f.set(G,H),d[H]=H):(d[H]=_,m[_]=Math.max(m[_],m[H]))}for(let H=0;H<r;H++)m[H]=m[d[H]];const p=Array.from({length:r},()=>[]);for(let H=0;H<n.index.length;H+=3)for(let G=0;G<3;G++){const _=d[n.index[H+G]],ee=d[n.index[H+(G+1)%3]];_!==ee&&(m[_]||m[ee])&&(p[_].push(ee),p[ee].push(_))}let y=0,g=0,v=-1;for(let H=0;H<r;H++)m[H]>.5&&Math.abs(s[H*3])>.03&&s[H*3+2]>v&&(v=s[H*3+2],y=Math.abs(s[H*3]),g=s[H*3+1]);const b=H=>m[H]>0&&((Math.abs(s[H*3])-y)/.1)**2+((s[H*3+1]-g)/.11)**2<1,k=[],w=new Uint8Array(r),S=new Set;for(let H=0;H<r;H++)d[H]===H&&p[H].length&&b(H)&&(k.push(H),w[H]=1);for(const H of k)for(const G of p[H])w[G]||S.add(G);const E=[...S],j=Array.from({length:4},()=>[0,0,0,0,0]);for(const H of E){const G=s[H*3+1]-l[1],_=[1,G,G*G,-(s[H*3]**2)],ee=s[H*3+2];for(let Q=0;Q<4;Q++){for(let ve=0;ve<4;ve++)j[Q][ve]+=_[Q]*_[ve];j[Q][4]+=_[Q]*ee}}for(let H=0;H<4;H++)j[H][H]+=1e-6;for(let H=0;H<4;H++)for(let G=H+1;G<4;G++){const _=j[G][H]/j[H][H];for(let ee=H;ee<5;ee++)j[G][ee]-=_*j[H][ee]}const M=[0,0,0,0];for(let H=3;H>=0;H--){let G=j[H][4];for(let _=H+1;_<4;_++)G-=j[H][_]*M[_];M[H]=G/j[H][H]}const T=Math.max(0,M[3]),N=new Float32Array(r);for(let H=0;H<r;H++)N[H]=s[H*3+2]+T*s[H*3]**2;for(let H=0;H<(i===0?1500:400);H++)for(const G of k){let _=0;for(const ee of p[G])_+=N[ee];N[G]=_/p[G].length}for(let H=0;H<r;H++)N[H]=N[d[H]]-T*s[H*3]**2;let R=0,A=0,C=0,O=0;for(const H of k){const G=s[H*3+2]-N[H];if(G<=0||m[H]<.6)continue;O=Math.max(O,G);const _=G*G*G;R+=Math.abs(s[H*3])*_,A+=s[H*3+1]*_,C+=_}if(!C||O<.004)return;const B=.5*(R/C),D=A/C+.012,$=O*.6,W=.07+.3*O,z=W*.9,Y=W*1.2,J=(H,G)=>{const _=G-D,ee=H-B,Q=_/(_<0?z:Y),ve=(ee/W)**2+Q**2;if(ve>=1)return 0;const ye=Q>0?Q/Math.sqrt(ve+1e-9):0;return $*(1-ve)**(.7+1.5*ye*ye)},V=(H,G,_)=>{const ee=Math.max(0,_-Math.abs(H-G))/_;return Math.max(H,G)+ee*ee*_*.25*Math.min(1,Math.min(H,G)/(.3*$))};for(let H=0;H<r;H++){const G=m[H];if(!G)continue;const _=s[H*3],ee=s[H*3+1],Q=V(J(_,ee),J(-_,ee),.03);s[H*3+2]+=(N[H]+Q-s[H*3+2])*G}}function cu(e,n){const s=["head","jaw","headHalf"].map(o=>e.bones.indexOf(o));return o=>{let i=0;for(let r=0;r<4;r++)s.includes(n.skinIndex[o*4+r])&&(i+=n.skinWeight[o*4+r]/255);return Math.min(1,i*1.15)}}function Ms(e,n,s=0){const o=`${s}|${Xn(n)}`;let i=ya.get(o);if(i)return i;ya.size>48&&(ya.forEach(u=>u.userData.realDispose()),ya.clear());const r=e.lods[s];i=new At;const l=ly(e,n,s);i.setAttribute("position",new Rt(l,3)),i.setIndex(new Rt(r.index,1)),i.setAttribute("skinIndex",new js(r.skinIndex,4)),i.setAttribute("skinWeight",new js(r.skinWeight,4,!0)),i.computeVertexNormals();const h=cu(e,r);return i.morphAttributes.position=au(l,rs(e),h).map(u=>new Rt(u,3)),i.morphTargetsRelative=!0,i.userData.region=r.region,i.userData.lod=s,i.computeBoundingBox(),i.computeBoundingSphere(),iu(i),ya.set(o,i),i}const va=new Map;function hy(e,n,s,o){const i=Ms(e,n,s),r=`${s}|${Xn(n)}|${o.skin}|${o.buzz??""}|${o.stubble??""}`;let l=va.get(r);if(l)return l;va.size>64&&(va.forEach(T=>T.userData.realDispose()),va.clear()),l=new At;for(const T of Object.keys(i.attributes))l.setAttribute(T,i.getAttribute(T));l.setIndex(i.getIndex()),l.morphAttributes=i.morphAttributes,l.morphTargetsRelative=!0,l.boundingBox=i.boundingBox,l.boundingSphere=i.boundingSphere,l.userData={...i.userData};const h=i.userData.region,u=i.getAttribute("position"),m=u.count,d=new Float32Array(m*3),f=new Ve(o.skin),p=rs(e),y=o.buzz?new Ve(o.buzz):null,g=o.stubble?new Ve(o.stubble):null,v=e.regions,b=e.face.landmarks,k=v.indexOf("lips"),w=v.indexOf("tip"),S=v.indexOf("ear"),E=v.indexOf("nose"),j=v.indexOf("scalp"),M=v.indexOf("stubble");for(let T=0;T<m;T++){let N=1,R=1,A=1;const C=h[T],O=u.getX(T)-p[0],B=u.getY(T)-p[1],D=u.getZ(T)-p[2];if(C===k){const W=Math.max(0,1-Math.abs(B-b.mouthY)/.0022)*Math.max(0,1-Math.abs(O)/(Math.abs(b.corner[0])+.004));N=.9-.4*W,R=.62-.3*W,A=.62-.3*W}(C===S||C===E)&&(N=1,R=.94,A=.92);const $=Math.max(0,1-((Math.abs(O)-Math.abs(b.cheek[0]))**2+(B-b.cheek[1])**2+(D-b.cheek[2])**2)/6e-4);$>0&&(R*=1-.05*$,A*=1-.05*$),C===w&&(N*=1.06),y&&C===j&&(N=N*(1-.85)+y.r/Math.max(.02,f.r)*.85,R=R*(1-.85)+y.g/Math.max(.02,f.g)*.85,A=A*(1-.85)+y.b/Math.max(.02,f.b)*.85),g&&C===M&&(N=N*(1-.4)+g.r/Math.max(.02,f.r)*.4,R=R*(1-.4)+g.g/Math.max(.02,f.g)*.4,A=A*(1-.4)+g.b/Math.max(.02,f.b)*.4),d[T*3]=N,d[T*3+1]=R,d[T*3+2]=A}return l.setAttribute("color",new Rt(d,3)),iu(l),va.set(r,l),l}const Zc=new Map,dy=(e,n)=>{let s=Zc.get(e);return s||(s=n(),s.userData.shared=!0,s.dispose=()=>{},Zc.set(e,s)),s},uy=cp.eyeR;function my(e){return dy(`eye|${e}`,()=>{const n=[0,.09,.16,.2,.27,.36,.44,.5,.53,.58,.75,1,1.35,1.75,2.2,2.7,Math.PI],s=28,o=[],i=[],r=[],l=new Ve(e),h=l.clone().multiplyScalar(.45),u=new Ve("#e9e4dc"),m=new Ve("#0c0a09"),d=l.clone().multiplyScalar(.25);n.forEach((p,y)=>{const g=p<.5?.0011*Math.cos(p/.5*Math.PI/2):0,v=uy+g,b=p<.17?m:p<.42?l.clone().lerp(h,Math.max(0,(.42-p)/.25)*.6):p<.5?d:p<.55?d.clone().lerp(u,.6):u.clone().lerp(new Ve("#e8cfc6"),Math.max(0,p-1.2)/2);for(let k=0;k<=s;k++){const w=k/s*Math.PI*2;o.push(v*Math.sin(p)*Math.cos(w),v*Math.sin(p)*Math.sin(w),v*Math.cos(p)),i.push(b.r,b.g,b.b)}if(y)for(let k=0;k<s;k++){const w=(y-1)*(s+1)+k,S=w+s+1;r.push(w,S,w+1,w+1,S,S+1)}});const f=new At;return f.setAttribute("position",new zt(o,3)),f.setAttribute("color",new zt(i,3)),f.setIndex(r),f.computeVertexNormals(),f})}const Jc=new Map,Ja=(e,n)=>{let s=Jc.get(e);return s||(s=n(),s.userData.shared=!0,s.dispose=()=>{},Jc.set(e,s)),s},eh="reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );",py=`float hqWrap = saturate( ( dot( geometryNormal, directLight.direction ) + 0.5 ) / 1.5 );
284
+ reflectedLight.directDiffuse += ( irradiance + directLight.color * max( 0.0, hqWrap - dotNL ) * vec3( 0.9, 0.36, 0.24 ) ) * BRDF_Lambert( material.diffuseContribution );`;function fy(e){return e.onBeforeCompile=n=>{const s=tg.lights_physical_pars_fragment;s.includes(eh)&&(n.fragmentShader=n.fragmentShader.replace("#include <lights_physical_pars_fragment>",s.replace(eh,py)))},e.customProgramCacheKey=()=>"hq-skin-sss-v1",e}function gy(e,n=!0){return Ja(`skin|${e}|${n}`,()=>{const s=new Ve(e),o=fy(new $s({color:s,roughness:.52,metalness:0,sheen:.35,sheenRoughness:.45,sheenColor:s.clone().lerp(new Ve("#ffd9c8"),.5),specularIntensity:.55,vertexColors:n}));return o.name="skin",o})}function xy(e){return Ja(`hair|${e}`,()=>{const n=new Ve(e),s=new $s({color:n,roughness:.42,metalness:0,sheen:.55,sheenRoughness:.35,sheenColor:n.clone().lerp(new Ve("#ffffff"),.35),anisotropy:.75,specularIntensity:.7,side:ks});return s.name="hair",s})}function by(e){return Ja(`facial|${e}`,()=>{const n=new Ve(e),s=new $s({color:"#ffffff",vertexColors:!0,alphaHash:!0,roughness:.7,metalness:0,sheen:.25,sheenRoughness:.6,sheenColor:n.clone().lerp(new Ve("#ffffff"),.2),anisotropy:.5,specularIntensity:.3});return s.name="beard",s})}function yy(){return Ja("eye",()=>{const e=new $s({vertexColors:!0,roughness:.18,clearcoat:1,clearcoatRoughness:.04});return e.name="eyes",e})}function Hi(e,n,s=.6,o=Za){return Ja(`plain|${e}|${n}|${s}|${o}`,()=>{const i=new os({color:n,roughness:s,side:o});return i.name=e,i})}const th=[],nh=new Nt,fr=new ae,ja=new ae,sh=new ae;function vy(e,n=5,s=.16){let o=e.userData.samples;if(o)return o;const i=e.getAttribute("position"),r=[];for(let l=0;l<i.count;l++)(l%n===0||i.getY(l)<s)&&r.push(l);return o=Uint32Array.from(r),e.userData.samples=o,o}function ia(e,n,s,o=!1){const i=e.geometry,r=e.skeleton,l=o?Array.from({length:i.getAttribute("position").count},(d,f)=>f):vy(i),h=i.getAttribute("position"),u=i.getAttribute("skinIndex"),m=i.getAttribute("skinWeight");nh.copy((s??e).matrixWorld).invert();for(let d=0;d<r.bones.length;d++)(th[d]??=new Nt).multiplyMatrices(r.bones[d].matrixWorld,r.boneInverses[d]).premultiply(nh);for(const d of l){fr.fromBufferAttribute(h,d),ja.set(0,0,0);for(let f=0;f<4;f++){const p=m.getComponent(d,f);p&&(sh.copy(fr).applyMatrix4(th[u.getComponent(d,f)]),ja.addScaledVector(sh,p))}n(ja.x,ja.y,ja.z,d)}}function jy(e){return e.computeBoundingBox=function(){const n=(this.boundingBox??=new _t).makeEmpty();ia(this,(s,o,i)=>{n.expandByPoint(fr.set(s,o,i))}),n.expandByScalar(.004)},e.computeBoundingSphere=function(){this.boundingBox||this.computeBoundingBox(),this.boundingBox.getBoundingSphere(this.boundingSphere??=new ng)},e}const cn=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)};function ky(e,n){const s=e.face.landmarks,o=e.regions,i=o.indexOf("lips"),r=o.indexOf("stubble"),l=Math.abs(s.corner[0])+.007,h=s.upper[1]+.0025,u=s.nostril[1]-.004,m=(p,y,g,v)=>{const b=Math.abs(p),k=cn(.35,1,b/l),w=u-.009*k,S=h-.0045*k-.004*k*k,E=cn(0,.0022,y-S)*cn(0,.0028,w-y)*cn(0,.004,l-b)*cn(.11,.13,g);return v===i?E*cn(.8,1,b/l):E},d=(p,y,g,v)=>{const b=Math.abs(p),k=.019-.006*cn(s.lower[1]-.01,s.lower[1]-.003,y),w=cn(0,.003,s.lower[1]-.0045-y)*cn(0,.006,y-(s.chin[1]-.016))*cn(0,.004,k-b)*cn(.1,.125,g);return v===i?0:w},f=(p,y,g,v)=>(v===i?0:v===r?1:0)||m(p,y,g,v);return n==="goatee"?{zone:d,th:p=>.0042*Math.pow(p,.6)}:n==="beard"?{zone:f,th:(p,y,g)=>(.0032+.002*cn(s.mouthY,s.chin[1],g))*Math.pow(p,.7)}:{zone:m,th:(p,y)=>(.0032+.001*(1-cn(0,.02,Math.abs(y))))*Math.pow(p,.55)}}const ho=new Map;function wy(e,n,s,o){const i=`${Xn(n)}|${s}|${o}`;let r=ho.get(i);if(r)return r;const l=Ms(e,n,0),h=l.getAttribute("position"),u=l.getAttribute("normal"),m=l.getIndex(),d=rs(e),f=l.userData.region,p=h.count,{zone:y,th:g}=ky(e,s),v=new Float32Array(p);for(let Y=0;Y<p;Y++){const J=h.getX(Y)-d[0],V=h.getY(Y)-d[1],H=h.getZ(Y)-d[2];V>.02||V<-.2||H<0||(v[Y]=y(J,V,H,f[Y]))}const b=Array.from({length:p},()=>[]);for(let Y=0;Y<m.count;Y+=3){const J=m.getX(Y),V=m.getX(Y+1),H=m.getX(Y+2);(v[J]||v[V]||v[H])&&(b[J].push(V,H),b[V].push(J,H),b[H].push(J,V))}for(let Y=0;Y<2;Y++){const J=Float32Array.from(v);for(let V=0;V<p;V++){if(!b[V].length)continue;let H=0;for(const G of b[V])H+=J[G];J[V]>0&&(v[V]=Math.min(J[V],.5*J[V]+.5*(H/b[V].length)))}}const k=new Int32Array(p).fill(-1),w=[],S=[],E=Y=>(k[Y]<0&&(k[Y]=S.length,S.push(Y)),k[Y]);for(let Y=0;Y<m.count;Y+=3){const J=m.getX(Y),V=m.getX(Y+1),H=m.getX(Y+2);Math.max(v[J],v[V],v[H])<.04||w.push(E(J),E(V),E(H))}if(!w.length)return null;const j=S.length,M=new Float32Array(j*3),T=new Float32Array(j*4),N=new Float32Array(j*4),R=new Uint8Array(j*4),A=new Uint8Array(j*4),C=l.getAttribute("skinIndex"),O=l.getAttribute("skinWeight"),B=new Ve(o),D=B.clone().lerp(new Ve("#8a6a4e"),.22),$=B.clone().multiplyScalar(.7),W=l.morphAttributes.position||[],z=W.map(()=>new Float32Array(j*3));return S.forEach((Y,J)=>{const V=h.getX(Y)-d[0],H=h.getY(Y)-d[1],G=v[Y],_=g(G,V,H)+3e-4;M[J*3]=h.getX(Y)+u.getX(Y)*_,M[J*3+1]=h.getY(Y)+u.getY(Y)*_,M[J*3+2]=h.getZ(Y)+u.getZ(Y)*_;const ee=.5+.5*Math.sin(V*2300+Math.sin(H*900)*2.2)*Math.sin(V*870-H*610),Q=$.clone().lerp(D,Math.pow(ee,2.5)*.85);T[J*4]=Q.r,T[J*4+1]=Q.g,T[J*4+2]=Q.b,T[J*4+3]=cn(.04,.55,G);const ve=Math.sign(V)*.55,ye=Math.hypot(ve,1,.25);N[J*4]=ve/ye,N[J*4+1]=-1/ye,N[J*4+2]=.25/ye,N[J*4+3]=1;for(let q=0;q<4;q++)R[J*4+q]=C.getComponent(Y,q),A[J*4+q]=Math.round(O.getComponent(Y,q)*(O.normalized?255:1));z.forEach((q,pe)=>{const ue=W[pe];q[J*3]=ue.getX(Y),q[J*3+1]=ue.getY(Y),q[J*3+2]=ue.getZ(Y)})}),r=new At,r.setAttribute("position",new Rt(M,3)),r.setAttribute("color",new Rt(T,4)),r.setAttribute("tangent",new Rt(N,4)),r.setAttribute("skinIndex",new js(R,4)),r.setAttribute("skinWeight",new js(A,4,!0)),r.setIndex(w),r.computeVertexNormals(),r.morphAttributes.position=z.map(Y=>new Rt(Y,3)),r.morphTargetsRelative=!0,r.userData.shared=!0,r.userData.facialHair={type:s,triangles:w.length/3,maxLift:Math.max(...S.map((Y,J)=>Math.hypot(M[J*3]-h.getX(Y),M[J*3+1]-h.getY(Y),M[J*3+2]-h.getZ(Y))))},r.dispose=()=>{},ho.size>32&&ho.clear(),ho.set(i,r),r}const My=hd,Bn=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)},Dn=Math.PI*2;function Sy(e){const n=e.face.stats,s=e.face.landmarks,o=n.eye+.02;return{cy:o,cz:(n.front+n.back)/2,ax:n.half*1.04,ay:n.crown-o,az:(n.front-n.back)/2,eye:n.eye,brow:Math.max(s.browIn[1],s.browMid[1],s.browOut[1]),crown:n.crown}}const Qs=(e,n,s)=>Math.atan2(n,s-e.cz),Uo=(e,n,s,o)=>Math.hypot(n/e.ax,(s-e.cy)/e.ay,(o-e.cz)/e.az);function Fs(e,n,s,o){const i=(o-e.cy)/(n*e.ay),r=n*Math.sqrt(Math.max(0,1-i*i));return[e.ax*r*Math.sin(s),o,e.cz+e.az*r*Math.cos(s)]}const Hs=(e,n)=>s=>n+(e-n)*(.5+.5*Math.cos(s)),ah=new WeakMap;function Io(e){let n=ah.get(e);if(n)return n;const s=e.lods[0],o=rs(e),i=["head","jaw","lidUL","lidUR","lidDL","lidDR"].map(h=>e.bones.indexOf(h)),r=[];for(let h=0;h<s.vertices;h++){let u=0;for(let m=0;m<4;m++)i.includes(s.skinIndex[h*4+m])&&(u+=s.skinWeight[h*4+m]/255);u>=.5&&r.push(s.position[h*3]-o[0],s.position[h*3+1]-o[1],s.position[h*3+2]-o[2])}const l=new Map;for(const[h,u]of e.hair)u.kind==="hair"&&l.set(h,u.position.map((m,d)=>m-o[d%3]));return n={skin:Float32Array.from(r),hair:l},ah.set(e,n),n}const oh=new WeakMap;function Cy(e,n){let s=oh.get(e);if(s)return s;const o=e.lods[0],i=rs(e),r=["torso","pelvis","headHalf"].map(f=>e.bones.indexOf(f)),l=48,h=-.36,u=.01,m=30,d=new Float32Array(l*m);for(let f=0;f<o.vertices;f++){if(!r.includes(o.skinIndex[f*4]))continue;const p=o.position[f*3]-i[0],y=o.position[f*3+1]-i[1],g=o.position[f*3+2]-i[2],v=Math.round((y-h)/u);if(v<0||v>=m)continue;const b=(Math.round(Math.atan2(p,g-n)/Dn*l)%l+l)%l;d[v*l+b]=Math.max(d[v*l+b],Math.hypot(p,g-n))}for(let f=0;f<3;f++){const p=d.slice();for(let y=0;y<m;y++)for(let g=0;g<l;g++)d[y*l+g]=Math.max(p[y*l+g],p[y*l+(g+1)%l],p[y*l+(g+l-1)%l])}for(let f=m-2;f>=0;f--)for(let p=0;p<l;p++)d[f*l+p]=Math.max(d[f*l+p],d[(f+1)*l+p]);for(let f=0;f<4;f++){const p=d.slice();for(let y=0;y<m;y++)for(let g=0;g<l;g++)d[y*l+g]=.5*p[y*l+g]+.25*(p[y*l+(g+1)%l]+p[y*l+(g+l-1)%l])}return s=(f,p)=>{const y=(f/Dn*l+l*4)%l,g=Math.floor(y),v=y-g,b=Math.min(m-1,Math.max(0,Math.round((p-h)/u)));return d[b*l+g]*(1-v)+d[b*l+(g+1)%l]*v},oh.set(e,s),s}function Ls(e,n,s,o,i=.004,r=.0025){const l=Io(e),h=(n.ax+n.az)/2;let u=1;for(let d=0;d<l.skin.length;d+=3){const f=l.skin[d],p=l.skin[d+1],y=l.skin[d+2];p>s(Qs(n,f,y))-.004&&(u=Math.max(u,Uo(n,f,p,y)+i/h))}const m=o?l.hair.get(o):void 0;if(m)for(let d=0;d<m.length;d+=3){const f=m[d],p=m[d+1],y=m[d+2],g=s(Qs(n,f,y));p>g-.006&&p<g+.012&&(u=Math.max(u,Uo(n,f,p,y)+r/h))}return u}function gs(e,n,s,o,i=!1){const r=[],l=[],h=s?e:e+1;for(const p of[0,1])for(let y=0;y<=n;y++)for(let g=0;g<h;g++)r.push(...o(g/e,y/n,p));const u=(p,y,g)=>p*h*(n+1)+g*h+(s?y%e:y),m=(p,y,g)=>i?l.push(p,g,y):l.push(p,y,g);for(let p=0;p<n;p++)for(let y=0;y<e;y++){const g=T=>[u(T,y,p),u(T,y+1,p),u(T,y+1,p+1),u(T,y,p+1)],[v,b,k,w]=g(0),[S,E,j,M]=g(1);m(v,b,k),m(v,k,w),m(S,j,E),m(S,M,j)}const d=(p,y)=>{const g=u(0,...p),v=u(0,...y),b=u(1,...p),k=u(1,...y);m(g,b,k),m(g,k,v)};for(let p=0;p<e;p++)d([p,0],[p+1,0]),d([p+1,n],[p,n]);if(!s)for(let p=0;p<n;p++)d([e,p],[e,p+1]),d([0,p+1],[0,p]);const f=new At;return f.setAttribute("position",new zt(r,3)),f.setIndex(l),f}function ts(e){const n=[],s=[];for(const i of e){const r=n.length/3,l=i.getAttribute("position");for(let u=0;u<l.count;u++)n.push(l.getX(u),l.getY(u),l.getZ(u));const h=i.getIndex();for(let u=0;u<h.count;u++)s.push(h.getX(u)+r);i.dispose()}const o=new At;return o.setAttribute("position",new zt(n,3)),o.setIndex(s),o.computeVertexNormals(),o}function ih(e,n,s,o,i,r){const l=(e.ax+e.az)/2;return gs(96,20,!0,(h,u,m)=>{const d=h*Dn,f=m?n:n+s/l,p=o(d),y=e.cy+f*e.ay,g=Math.asin(Math.max(-1,Math.min(1,(p-e.cy)/(f*e.ay)))),v=g+(Math.PI/2-g)*u,b=Fs(e,f,d,Math.min(y,e.cy+f*e.ay*Math.sin(v)));if(r){const k=r(d,u);b[0]*=k,b[2]=e.cz+(b[2]-e.cz)*k}return!m&&i&&(b[1]+=i(b)),b})}function ka(e,n,s,o,i,r,l,h,u=!1){const m=(e.ax+e.az)/2,d=n+.6*h/m;return gs(u?72:40,8,u,(f,p,y)=>{const g=o+(i-o)*f,v=s(g),b=Fs(e,d,g,v),k=Math.sin(g)/e.ax,w=Math.cos(g)/e.az,S=Math.hypot(k,w),E=-.003+(r(g)+.003)*p;return[b[0]+k/S*E,v-l(g,Math.max(0,E))-(y?h:0),b[2]+w/S*E]},!0)}function uo(e,n,s,o,i,r,l={}){const h=(e.ax+e.az)/2,u=22,m=14;return gs(64,u,!0,(d,f,p)=>{const y=d*Dn,g=s(y),v=Fs(e,n+(p?0:r/h),y,g),b=v[0],k=v[2]-e.cz;if(f*u<=m){const M=f*u/m,T=i(M)*(l.pleats?.(y,M)??1);return[b*T,g+(o-(p?r:0)-g)*M,e.cz+k*T]}const w=1-(f*u-m)/(u-m),S=i(1)*w*(l.pleats?.(y,1)??1),E=b*S,j=k*S;return[E,o-(p?r:0)-(l.dent?.(E,j)??0)*(1-w*w),e.cz+j]})}function Wi(e,n,s,o,i,r,l=.0015){const h=(e.ax+e.az)/2;return gs(64,2,!0,(u,m,d)=>{const f=u*Dn,p=s(f),y=Fs(e,n+(d?0:l/h),f,p),g=o+(i-o)*m,v=r(g);return[y[0]*v,p+g,e.cz+(y[2]-e.cz)*v]})}function Ny(e,n,s=[14,10]){const o=new Un(1,s[0],s[1]);return o.scale(...e),o.translate(...n),o.deleteAttribute("uv"),o.deleteAttribute("normal"),o}function Ay(e){const n=e.brow;return{cap:Hs(n+.02,e.eye+.008),helmet:Hs(n+.024,e.eye+.016),police:Hs(n+.022,e.eye+.012),fedora:Hs(n+.026,e.eye+.02),chef:Hs(n+.024,e.eye+.018),ancient:Hs(n+.028,e.eye+.022)}}function Ty(e,n,s){const o=Sy(e),i=Ay(o),r=(o.ax+o.az)/2,l=h=>(u,m,d)=>m>h(Qs(o,u,d))-.003;switch(n){case"cap":{const h=i.cap,u=Ls(e,o,h,void 0),m=Math.min(Ls(e,o,h,s),u+.02),d=.0035,f=(g,v)=>1-.045*Math.pow(1-Math.abs(Math.sin(3*g)),14)*Math.sin(Math.PI*Math.min(1,v*1.25))+.1*Math.pow(Math.max(0,Math.cos(g)),2)*Math.sin(Math.PI*Math.min(1,v*1.4))*(1-v),p=ka(o,m+.02,h,-.8,.8,g=>.075*Math.pow(Math.max(0,1-(g/.8)**2),.4),(g,v)=>.12*v*v+.05*(g/.8)**2*Bn(0,.05,v),.004),y=o.cy+(m+d/r)*o.ay;return{main:ts([ih(o,m,d,h,void 0,f),p]),trim:Ny([.008,.004,.008],[0,y+.0015,o.cz]),cut:(g,v,b)=>{const k=Qs(o,g,b);return v>h(k)-.003-.035*Math.max(0,Math.cos(k))}}}case"helmet":{const h=i.helmet,u=Ls(e,o,h,s,.02,.012),m=.005,d=p=>.007*Math.exp(-((p[0]/.014)**2))*Bn(o.cy,o.cy+o.ay*.6,p[1]),f=ka(o,u+m/r,h,0,Dn,p=>.018+.028*Math.max(0,Math.cos(p))**2,(p,y)=>.25*y*y,.004,!0);return{main:ts([ih(o,u,m,h,d),f]),cut:l(h)}}case"police":{const h=i.police,u=Ls(e,o,h,s,.005),m=Math.max(h(0),h(Math.PI))+.068,d=uo(o,u,h,m,p=>1+.17*Bn(.4,1,p),.003),f=ka(o,u+.004/r,h,-1.05,1.05,p=>.05*Math.pow(Math.max(0,1-(p/1.05)**2),.6),(p,y)=>.3*y,.003);return{main:ts([d,f]),trim:Wi(o,u+.002/r,h,.004,.02,()=>1),cut:l(h)}}case"fedora":{const h=i.fedora,u=Ls(e,o,h,s,.005),m=Math.max(h(0),h(Math.PI))+.09,d=uo(o,u,h,m,p=>1-.07*p,.003,{dent:p=>.016*Math.exp(-((p/.022)**2)),pleats:(p,y)=>1-.05*Bn(.6,1,y)*Math.max(0,Math.cos(p))**4}),f=ka(o,u+.003/r,h,0,Dn,p=>.055+.008*Math.cos(p)**2,(p,y)=>.18*y*y*Math.cos(p)**2-.3*y*y*Math.sin(p)**2,.003,!0);return{main:ts([d,f]),trim:Wi(o,u+.0035/r,h,.002,.022,p=>1-.07*(p/.09)),cut:l(h)}}case"chef":{const h=i.chef,u=Ls(e,o,h,s,.005),m=Math.max(h(0),h(Math.PI))+.17;return{main:uo(o,u,h,m,f=>f<.42?1.01:1.01+.3*Math.sin(Math.min(1,(f-.42)/.4)*Math.PI/2)-.12*Bn(.85,1,f),.003,{pleats:(f,p)=>1+.03*Bn(.42,.6,p)*Math.sin(f*16)}),cut:l(h)}}case"ancient":{const h=i.ancient,u=Ls(e,o,h,s,.006),m=Math.max(h(0),h(Math.PI))+.085,d=uo(o,u,h,m,g=>1+.04*g,.003,{dent:(g,v)=>-.012*Math.exp(-((g/.05)**2+((v-o.cz)/.06)**2))}),f=h(Math.PI)+.055,p=o.cz-o.az*u*.7,y=[-1,1].map(g=>{const v=new ws(1,1,1,20);return v.rotateX(Math.PI/2),v.scale(.055,.017,.003),v.rotateZ(g*.22),v.translate(g*(o.ax*u+.045),f,p),v.deleteAttribute("uv"),v.deleteAttribute("normal"),v});return{main:ts([d,...y]),trim:Wi(o,u+.0035/r,h,.002,.018,()=>1),cut:l(h)}}case"nonla":{const m=Io(e),d=[m.skin,m.hair.get(s??"")??new Float32Array];let f=-1/0;for(const g of d)for(let v=0;v<g.length;v+=3)f=Math.max(f,g[v+1]+Math.hypot(g[v],g[v+2]-o.cz)*.15/.235+.008);const p=gs(56,10,!0,(g,v,b)=>{const k=g*Dn,w=.235*v,S=f-.15*v-(b?.003:0);return[w*Math.sin(k),S,o.cz+w*Math.cos(k)]},!0),y=new qr(.235,.0035,6,56);return y.rotateX(Math.PI/2),y.translate(0,f-.15-.0015,o.cz),y.deleteAttribute("uv"),y.deleteAttribute("normal"),{main:ts([p]),trim:ts([y]),cut:null}}case"moto":{const h={...o,cy:o.eye-.004,ay:o.crown-o.eye+.004,ax:o.ax*1.1},u=g=>Bn(1.25,1.05,Math.abs(g)),m=g=>-.118+.012*Math.cos(g)**2+(o.brow+.016+.118)*u(g),d=Io(e);let f=1;for(let g=0;g<d.skin.length;g+=3){const v=d.skin[g],b=d.skin[g+1],k=d.skin[g+2];b>m(Qs(h,v,k))-.01&&(f=Math.max(f,Uo(h,v,b,k)+.025/r))}const p=gs(96,18,!0,(g,v,b)=>{const k=g*Dn-Math.PI,w=b?f:f+.006/r,S=m(k),E=Math.asin(Math.max(-1,Math.min(1,(S-h.cy)/(w*h.ay)))),j=E+(Math.PI/2-E)*v;return Fs(h,w,k,h.cy+w*h.ay*Math.sin(j))}),y=ka(h,f+.006/r,m,-.8,.8,g=>.035*Math.pow(Math.max(0,1-(g/.8)**2),.6),(g,v)=>.2*v,.004);return{main:ts([p,y]),cut:"hide"}}case"hijab":{const h={...o,cy:o.eye-.035,ay:o.crown-o.eye+.035,ax:o.ax*1.12,az:o.az*1.04},u=e.face.landmarks,m=u.chin[1],d=S=>Bn(1,.82,Math.abs(S)),f=S=>m-.012+(o.brow+.03-m+.012)*d(S)-.05*Bn(1.4,2.6,Math.abs(S)),p=Io(e);let y=1;for(let S=0;S<p.skin.length;S+=3){const E=p.skin[S],j=p.skin[S+1],M=p.skin[S+2],T=Qs(h,E,M);j>f(T)-.004&&d(T)<.98&&(y=Math.max(y,Uo(h,E,j,M)+.008/r))}const g=gs(96,18,!0,(S,E,j)=>{const M=S*Dn-Math.PI,T=j?y:y+.003/r,N=f(M),R=Math.asin(Math.max(-1,Math.min(1,(N-h.cy)/(T*h.ay)))),A=R+(Math.PI/2-R)*E;return Fs(h,T,M,h.cy+T*h.ay*Math.sin(A))}),v=S=>Math.min(m+.004,f(S)+.02),b=-.27,k=Cy(e,o.cz),w=gs(72,12,!0,(S,E,j)=>{const M=S*Dn-Math.PI,T=v(M),N=Fs(h,y+.004/r,M,T),R=T+(b-T)*E,A=Math.hypot(N[0],N[2]-o.cz),C=Math.max(A*(1+.5*E*E),(k(M,R)+.012)*Bn(0,.4,E))-(j?.003:0);return[Math.sin(M)*C,R,o.cz+Math.cos(M)*C]});return{main:ts([g,w]),cut:"hide"}}}return null}const wa=new Map;function hu(e,n,s){const o=`${e.bytes}|${n}|${s??""}`;if(!wa.has(o)){wa.size>48&&wa.clear();const i=Ty(e,n,s);for(const r of[i?.main,i?.trim])r&&(r.computeVertexNormals(),r.userData.shared=!0,r.dispose=()=>{});wa.set(o,i)}return wa.get(o)}function Ly(e,n,s){return hu(e,n,s)?.cut??null}const rh=(e,n)=>"#"+new Ve(e).lerp(new Ve(n>0?"#ffffff":"#000000"),Math.abs(n)).getHexString(),Ey=e=>{const n=new Ve(e);return n.r*.3+n.g*.59+n.b*.11>.5?rh(e,-.55):rh(e,.65)},mo={cap:e=>`fab:cotton:${e}`,police:e=>`fab:wool:${e}`,fedora:e=>`fab:wool:${e}`,chef:e=>`fab:cotton:${e}`,ancient:e=>`fab:silk:${e}`,nonla:e=>`fab:linen:${e}`,hijab:e=>`fab:cotton:${e}`,helmet:e=>`sol:${e}:0.35:0`,moto:e=>`sol:${e}:0.25:0`};function Ry(e,n,s){const o=hu(e,n.type,s);if(!o)return[];const i=[{geometry:o.main,mat:(mo[n.type]??mo.cap)(n.color),slot:"hat"}],r=n.type==="cap"?n.color:n.color2??(n.type==="police"?"#d8b64a":Ey(n.color));return o.trim&&i.push({geometry:o.trim,mat:n.type==="police"||n.type==="ancient"?`sol:${r}:0.35:0.6`:(mo[n.type]??mo.cap)(r),slot:"hat"}),i}const po=new Map,Gi=new Map;function Iy(e,n){let s=Gi.get(n.id);if(s!==void 0)return s;const o=e.morphs.findIndex(p=>p.name==="femFace"),i=e.lods[0];if(o<0)return Gi.set(n.id,null),null;const r=i.morphs[o],l=i.position,h=n.position,u=h.length/3,m=[1/0,1/0,1/0],d=[-1/0,-1/0,-1/0];for(let p=0;p<u;p++)for(let y=0;y<3;y++)m[y]=Math.min(m[y],h[p*3+y]),d[y]=Math.max(d[y],h[p*3+y]);const f=[];for(let p=0;p<i.vertices;p++)[0,1,2].every(y=>l[p*3+y]>m[y]-.015&&l[p*3+y]<d[y]+.015)&&f.push(p);s=new Float32Array(u*3);for(let p=0;p<u;p++){let y=-1,g=1/0;for(const v of f){const b=(l[v*3]-h[p*3])**2+(l[v*3+1]-h[p*3+1])**2+(l[v*3+2]-h[p*3+2])**2;b<g&&(g=b,y=v)}if(y>=0)for(let v=0;v<3;v++)s[p*3+v]=r.data[y*3+v]*r.scale}return Gi.set(n.id,s),s}function Py(e,n){const s=rs(e),o=Float32Array.from(n),i=(l,h,u,m)=>{const d=l<h?(l-h+m)/m:l>u?(u+m-l)/m:1;return d<=0?0:d>=1?1:d*d*(3-2*d)};let r=!1;for(let l=0;l<o.length;l+=3){const h=o[l]-s[0],u=Math.abs(h);if(u<.05)continue;const m=i(o[l+1]-s[1],-.072,-.016,.015)*i(o[l+2]-s[2],.025,.075,.02),d=.091+(u-.072)*.3;m>0&&u<d&&(o[l]=s[0]+Math.sign(h)*(u+(d-u)*m),r=!0)}return r?o:null}function Fy(e,n,s,o,i=0){const r=i>0&&(n.kind==="brows"||n.kind==="teeth"||n.kind==="lashes")?Iy(e,n):null,l=r?Math.round(i*100)/100:0,h=`${n.id}|${o}|${l}`;let u=po.get(h);if(u)return u;po.size>96&&po.clear();const m=r?n.position.map((b,k)=>b+r[k]*l):n.position,d=r?ru(l):0;if(d>0){const b=[0,0,0];for(let k=0;k<m.length;k+=3)lu(e,m[k],m[k+1],m[k+2],d,b),m[k]+=b[0],m[k+1]+=b[1],m[k+2]+=b[2]}const f=n.kind==="hair"?Py(e,n.position):null;u=new At,u.setAttribute("position",new Rt(f??m,3)),u.setAttribute("skinIndex",new js(n.skinIndex,4)),u.setAttribute("skinWeight",new js(n.skinWeight,4,!0));const p=n.position.length/3,y=new Float32Array(p*4);for(let b=0;b<p;b++)y[b*4]=n.flow[b*3],y[b*4+1]=n.flow[b*3+1],y[b*4+2]=n.flow[b*3+2],y[b*4+3]=1;u.setAttribute("tangent",new Rt(y,4));const g=rs(e);let v=n.index;if(typeof s=="function"){const b=[],k=w=>s(m[w*3]-g[0],m[w*3+1]-g[1],m[w*3+2]-g[2]);for(let w=0;w<n.index.length;w+=3)k(n.index[w])&&k(n.index[w+1])&&k(n.index[w+2])||b.push(n.index[w],n.index[w+1],n.index[w+2]);v=b}return u.setIndex(Array.from(v)),u.computeVertexNormals(),(n.kind==="beard"||n.kind==="brows")&&(u.morphAttributes.position=au(m,g).map(b=>new Rt(b,3)),u.morphTargetsRelative=!0),u.userData.shared=!0,u.dispose=()=>{},po.set(h,u),u}function $y(e,n,s,o){const i=[],r=s.hat?Ly(e,s.hat.type,s.hair?.style):null,l=s.hat?`hat:${s.hat.type}`:"",h=s.hair?.color??"#2a211b",u=(f,p,y,g)=>{const v=e.hair.get(f);if(!v||g==="hide")return;const b=n.bones.get("head"),k=new Map,w=v.chains.length?{kind:"hair",anchor:"head",chains:[]}:null;for(const[S,E]of v.chains.entries()){let j=b,M=[-ea[0],-ea[1],-ea[2]];const T=[],N=[];E.forEach((R,A)=>{const C=new _a;C.name=R.name,C.position.set(R.at[0]-M[0],R.at[1]-M[1],R.at[2]-M[2]),j.add(C),n.bones.set(R.name,C),T.push(C);const O=rs(e);k.set(R.name,new Nt().makeTranslation(-(O[0]+R.at[0]),-(O[1]+R.at[1]),-(O[2]+R.at[2])));const B=E[A+1];N.push(B?new ae(B.at[0]-R.at[0],B.at[1]-R.at[1],B.at[2]-R.at[2]):N[A-1]?.clone()??new ae(0,-.08,0)),j=C,M=R.at}),w.chains.push({bones:T,rest:N,kind:"hair",stiffness:f==="long"?.55:.4,collide:!0,side:S})}i.push({geometry:Fy(e,v,g,g?l:"",o.fem),material:typeof p=="string"?xy(p):p,slot:y,bones:v.bones,inverses:k,chains:w,near:v.kind==="lashes"||v.kind==="teeth"||v.kind==="brows"})},m=s.hair?.style;if(m&&m!=="none"&&m!=="buzz"&&u(m,h,"hair",r),u("brows",Dy(s.hair&&s.hair.style!=="none"?h:s.beard?.color??"#2a211b",o.skin),"hair",null),s.beard&&s.beard.type!=="none"){const f=wy(e,o,s.beard.type,s.beard.color);f&&i.push({geometry:f,material:by(s.beard.color),slot:"beard",bones:[...My],inverses:new Map,chains:null,near:!1})}u("lashes",Hi("lashes","#17110d",.75,ks),"lashes",null);const d=Hi("teeth","#e6dfd2",.3);return u("teeth-upper",d,"teeth",null),u("teeth-lower",d,"teeth",null),u("tongue",Hi("tongue","#a5525a",.45),"mouth",null),i}function Dy(e,n="#c9956f"){const s=new Ve(e);return"#"+(s.getHSL({h:0,s:0,l:0}).l>.7?s.multiplyScalar(.75):s.lerp(new Ve(n),.1)).getHexString()}const Qt=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)},Ma=-.1,Xo={tshirt:{sleeve:.42,hem:-.11,neck:"crew",th:.0055},shirt:{sleeve:1.93,hem:-.13,neck:"collar",th:.0065},polo:{sleeve:.45,hem:-.11,neck:"collar",th:.006},blazer:{sleeve:1.9,hem:-.2,neck:"deepv",th:.013},hoodie:{sleeve:1.95,hem:-.13,neck:"high",th:.013},chef:{sleeve:1.9,hem:-.17,neck:"high",th:.011},doctor:{sleeve:1.9,hem:.02,neck:"v",th:.01,loose:{top:.02,length:.5,flare:1.12,open:34,folds:.004,chains:10}},police:{sleeve:1.92,hem:-.13,neck:"collar",th:.008},worker:{sleeve:-.06,hem:-.12,neck:"v",th:.011,stripes:!0},nurse:{sleeve:.45,hem:-.13,neck:"v",th:.007},sports:{sleeve:.36,hem:-.1,neck:"crew",th:.005},tank:{sleeve:-.08,hem:-.1,neck:"scoop",th:.0045},robe:{sleeve:1.97,hem:.06,neck:"v",th:.012,loose:{top:.2,length:1.06,flare:1.2,folds:.006,chains:14}},tunic:{sleeve:1.9,hem:.02,neck:"high",th:.011,loose:{top:.02,length:.48,flare:1.2,folds:.005,chains:12}},dress:{sleeve:.3,hem:.06,neck:"scoop",th:.005,loose:{top:.06,length:.55,flare:1.3,folds:.006,chains:12}},wedding:{sleeve:-.08,hem:.08,neck:"scoop",th:.006,loose:{top:.08,length:1.02,flare:1.9,folds:.012,chains:16}},armor:{sleeve:.32,hem:-.14,neck:"high",th:.02},hero:{sleeve:1.97,hem:-.15,neck:"high",th:.0035},aodai:{sleeve:1.97,hem:-.03,neck:"high",th:.005,loose:{top:.08,length:.9,flare:1.08,panels:"aodai",folds:.003,chains:14}}},Nn={trousers:{waist:.06,leg:1.99,th:.0075},jeans:{waist:.02,leg:1.99,th:.0065},shorts:{waist:.05,leg:.52,th:.007},ancient:{waist:.08,leg:1.97,th:.014},miniskirt:{waist:.05,leg:.24,th:.005,loose:{top:.05,length:.32,flare:1.18,folds:.004,chains:16}},"skirt-mid":{waist:.07,leg:.4,th:.005,loose:{top:.07,length:.56,flare:1.28,folds:.006,chains:16}},"skirt-long":{waist:.07,leg:.45,th:.005,loose:{top:.07,length:.95,flare:1.4,folds:.008,chains:18}}},Vo={coat:{sleeve:1.95,hem:.03,neck:"deepv",th:.018,loose:{top:.03,length:.6,flare:1.2,open:26,folds:.006,chains:12}},raincoat:{sleeve:1.95,hem:.03,neck:"high",th:.016,loose:{top:.03,length:.7,flare:1.25,open:18,folds:.006,chains:12}}},Oy=e=>!!e.top||!!(e.outer&&Vo[e.outer.type]),_y=e=>!!e.bottom||!!(e.top&&Xo[e.top.type]?.loose&&Xo[e.top.type].loose.length>.4)||!!(e.outer&&Vo[e.outer.type]?.loose),zy=e=>e.fabric??up[e.type]??"cotton",nt={torso:0,arm:1,hand:2,leg:3,foot:4,head:5},fo=new Map;function Qr(e,n,s){const o=e.lods[n],i=`${n}|${Xn(s)}`;let r=fo.get(i);if(r)return r;fo.size>48&&fo.clear();const l=dd(ti({...s,head:1,posture:0},Pr,{bind:!0})),h=new Proxy(e.bind,{get:(f,p)=>l.get(p)?.t??f[p]}),u=o.vertices,m=Ms(e,s,n).getAttribute("position").array;r={cat:new Uint8Array(u),yt:new Float32Array(u),armT:new Float32Array(u),legT:new Float32Array(u),x:new Float32Array(u),z:new Float32Array(u),footY:new Float32Array(u),sole:0};const d=(f,p,y)=>{const g=[y[0]-p[0],y[1]-p[1],y[2]-p[2]],v=g[0]**2+g[1]**2+g[2]**2;return((f[0]-p[0])*g[0]+(f[1]-p[1])*g[1]+(f[2]-p[2])*g[2])/v};for(let f=0;f<u;f++){const p=[m[f*3],m[f*3+1],m[f*3+2]],y=p[0]<0?"L":"R",g=e.bones[o.skinIndex[f*4]];r.cat[f]=/^(arm|fore)/.test(g)?nt.arm:/^(wrist|thumb|index|middle|ring|pinky)/.test(g)?nt.hand:/^(thigh|shin)/.test(g)?nt.leg:/^foot/.test(g)?nt.foot:/^(head|jaw|lid)/.test(g)?nt.head:nt.torso,r.yt[f]=p[1]-h.torso[1],r.x[f]=p[0],r.z[f]=p[2];const v=h[`arm${y}`],b=h[`fore${y}`],k=h[`wrist${y}`];let w=d(p,v,b);w>1&&(w=1+d(p,b,k),w>2&&(w=2+Math.hypot(p[0]-k[0],p[1]-k[1],p[2]-k[2])/.19)),r.armT[f]=w;const S=h[`thigh${y}`],E=h[`shin${y}`],j=h[`foot${y}`];let M=d(p,S,E);M>1&&(M=1+d(p,E,j)),r.legT[f]=M,r.footY[f]=p[1]-j[1],r.cat[f]===nt.foot&&(r.sole=Math.max(r.sole,-r.footY[f]))}return fo.set(i,r),r}function By(e,n,s){const o=Qt(-.015,.05,s),i=Math.abs(n);switch(e){case"crew":return .565-.045*o*Math.max(0,1-(i/.07)**2);case"collar":return .6-.065*o*Math.max(0,1-i/.035);case"v":return .565-.13*o*Math.max(0,1-i/.08);case"deepv":return .57-.24*o*Math.max(0,1-i/.1);case"scoop":return .53-.1*o*Math.max(0,1-(i/.11)**2);case"high":return .62-.02*o}}function lh(e,n,s=.134){return o=>{const i=e.cat[o];if(i===nt.head||i===nt.foot)return-1;if(i===nt.arm||i===nt.hand)return n.sleeve<0?Math.min(-.01,s-Math.abs(e.x[o])):(n.sleeve-e.armT[o])*.29;let r=Math.min(e.yt[o]-n.hem,By(n.neck,e.x[o],e.z[o])-e.yt[o]);return n.sleeve<0&&(r=Math.min(r,s-Math.abs(e.x[o])+2.5*Math.max(0,.3-e.yt[o]))),r}}function Ky(e,n){return s=>{const o=e.cat[s];if(o===nt.head||o===nt.arm||o===nt.hand)return-1;const i=n.waist-e.yt[s];return o===nt.torso?i:Math.min(i,(n.leg-e.legT[s])*.43)}}const Sa=new Map;function Hy(e,n,s,o){const{out:i,nv:r,idx:l}=o,h=new Map,u=new Map;for(let O=0;O<l.length;O+=3)for(let B=0;B<3;B++){const D=l[O+B],$=l[O+(B+1)%3],W=Math.min(D,$)*r+Math.max(D,$);h.set(W,(h.get(W)??0)+1),u.set(W,[D,$])}const m=new Map;for(const[O,B]of h)if(B===1){const[D,$]=u.get(O);m.set($,D)}let d=1+s.hem,f=null;const p=new Set;for(const O of m.keys()){if(p.has(O))continue;const B=[];let D=O;for(;!p.has(D)&&m.has(D);)p.add(D),B.push(D),D=m.get(D);if(B.length<12)continue;const $=B.map(z=>i[z*3+1]),W=B.map(z=>i[z*3]);if(Math.max(...$.map(z=>Math.abs(z-d)))<.05&&Math.min(...W)<-.05&&Math.max(...W)>.05){f=B;break}}if(!f)return null;d=Math.min(...f.map(O=>i[O*3+1]));for(const O of f)i[O*3+1]=d;const y=120,g=.01,v=Math.ceil(s.length/g)+2,b=new Float32Array(y*v);for(let O=0;O<s.cat.length;O++){const B=s.cat[O];if(B===nt.arm||B===nt.hand||B===nt.head)continue;const D=n[O*3+1],$=Math.round((d-D)/g);if($<0||$>=v)continue;const W=n[O*3],z=n[O*3+2],Y=(Math.round(Math.atan2(W,z)/(Math.PI*2)*y)%y+y)%y;b[$*y+Y]=Math.max(b[$*y+Y],Math.hypot(W,z))}for(let O=0;O<v;O++)for(let B=0;B<4;B++){const D=b.slice(O*y,(O+1)*y);for(let $=0;$<y;$++)b[O*y+$]=Math.max(D[$],(D[($+1)%y]+D[($+y-1)%y])/2*.998)}{const O=b.slice(),B=(D,$)=>D<0||D>=v?0:O[D*y+($+y)%y];for(let D=0;D<v;D++)for(let $=0;$<y;$++){let W=0;for(let z=-1;z<=1;z++)for(let Y=-1;Y<=1;Y++)W=Math.max(W,B(D+z,$+Y));b[D*y+$]=W}}const k=(O,B)=>{const D=(O/(Math.PI*2)*y+y*4)%y,$=Math.floor(D),W=D-$,z=Math.min(v-1,Math.max(0,Math.round(B/g)));return b[z*y+$]*(1-W)+b[z*y+($+1)%y]*W},w=e.bones.indexOf("pelvis"),S=e.bones.indexOf("thighHalfL"),E=e.bones.indexOf("thighHalfR"),j=e.bones.indexOf("thighL"),M=e.bones.indexOf("thighR"),T=f.length,N=Math.max(3,Math.round(s.length/.012)),R=[...i],A=f.map(O=>Math.hypot(i[O*3],i[O*3+2]));let C=f.slice();for(let O=1;O<=N;O++){const B=s.length*O/N,D=[];for(let W=0;W<T;W++){const z=f[W],Y=Math.atan2(i[z*3],i[z*3+2]);D.push(Math.max(A[W]-s.tuck*(s.length/N),k(Y,B)+o.th[z]+.004+.01*Math.min(1,B/.012)))}for(let W=0;W<3;W++){const z=D.slice();for(let Y=0;Y<T;Y++)D[Y]=Math.max(z[Y],(z[(Y+1)%T]+z[(Y+T-1)%T])/2)}const $=[];for(let W=0;W<T;W++){const z=f[W],Y=Math.atan2(i[z*3],i[z*3+2]),J=D[W]*(1+s.flare*B),V=R.length/3;R.push(Math.sin(Y)*J,d-B,Math.cos(Y)*J),o.base.push(Math.sin(Y)*(J-o.th[z]),d-B,Math.cos(Y)*(J-o.th[z])),o.nrm.push(Math.sin(Y),0,Math.cos(Y)),o.th.push(o.th[z]);const H=Math.min(1,B/.03),G=i[z*3],_=Qt(.015,.07,Math.abs(G)),ee=.45*_,Q=(Math.cos(Y)>0?.55:.3)*Qt(.1,.7,Math.abs(Math.cos(Y))),ve=Qt(-.04,.04,G),ye=new Map;for(let U=0;U<4;U++){const re=o.sw[z*4+U];re&&ye.set(o.si[z*4+U],(ye.get(o.si[z*4+U])??0)+re*(1-H))}ye.set(w,(ye.get(w)??0)+H*(1-ee-Q));const q=G<0?S:E;if(ye.set(q,(ye.get(q)??0)+H*ee),Q>0)for(const[U,re]of[[j,1-ve],[M,ve]])re>0&&ye.set(U,(ye.get(U)??0)+H*Q*re);const pe=[...ye].sort((U,re)=>re[1]-U[1]).slice(0,4);let ue=0;for(const[,U]of pe)ue+=U;for(let U=0;U<4;U++)o.si.push(pe[U]?.[0]??0),o.sw.push(pe[U]?pe[U][1]/ue:0);o.col.length&&o.col.push(o.col[z*3],o.col[z*3+1],o.col[z*3+2]),$.push(V),A[W]=D[W]}for(let W=0;W<T;W++){const z=C[W],Y=C[(W+1)%T],J=$[W],V=$[(W+1)%T];l.push(z,Y,V,z,V,J)}C=$}return{out:Float32Array.from(R),nv:R.length/3}}function Wy(e,n,s,o,i,r,l={}){const h=`${s}|${Xn(n)}|${o}`;let u=Sa.get(h);if(u)return u;Sa.size>96&&(Sa.forEach(U=>U.geometry.userData.realDispose?.()),Sa.clear());const m=e.lods[s],d=Ms(e,n,s),f=d.getAttribute("position").array,p=d.getAttribute("normal").array,y=m.vertices,g=new Float32Array(y),v=new Uint8Array(y);for(let U=0;U<y;U++){let re=i(U);Math.abs(re)<.0012&&(re=re>=0?.0012:-.0012),g[U]=re,re>.028&&(v[U]=1)}const b=[],k=[],w=[],S=[],E=[],j=[],M=[],T=new Int32Array(y).fill(-1),N=new Map,R=U=>{const re=new Map;for(let ce=0;ce<4;ce++){const Ee=m.skinWeight[U*4+ce];Ee&&re.set(m.skinIndex[U*4+ce],Ee/255)}return re},A=(U,re,ce,Ee,je)=>{const le=k.length/3;k.push(U[0],U[1],U[2]),b.push(re[0],re[1],re[2]),w.push(Ee);const Le=[...ce].sort((we,he)=>he[1]-we[1]).slice(0,4);let Ae=0;for(const[,we]of Le)Ae+=we;for(let we=0;we<4;we++)S.push(Le[we]?.[0]??0),E.push(Le[we]?Le[we][1]/Ae:0);return je&&j.push(...je),le},C=U=>(T[U]<0&&(T[U]=A([f[U*3],f[U*3+1],f[U*3+2]],[p[U*3],p[U*3+1],p[U*3+2]],R(U),r(U),l.colors?.(U))),T[U]),O=(U,re)=>{const ce=U<re?U*y+re:re*y+U;let Ee=N.get(ce);if(Ee!==void 0)return Ee;const je=g[U]/(g[U]-g[re]),le=(Pe,Te)=>Pe[U*3+Te]+(Pe[re*3+Te]-Pe[U*3+Te])*je,Le=R(U),Ae=R(re),we=new Map;for(const[Pe,Te]of Le)we.set(Pe,Te*(1-je));for(const[Pe,Te]of Ae)we.set(Pe,(we.get(Pe)??0)+Te*je);const he=l.colors?.(U),ke=l.colors?.(re);return Ee=A([le(f,0),le(f,1),le(f,2)],[le(p,0),le(p,1),le(p,2)],we,r(U)*(1-je)+r(re)*je,he&&ke?[he[0]*(1-je)+ke[0]*je,he[1]*(1-je)+ke[1]*je,he[2]*(1-je)+ke[2]*je]:void 0),N.set(ce,Ee),Ee},B=m.index;for(let U=0;U<B.length;U+=3){const re=[B[U],B[U+1],B[U+2]],ce=re.map(we=>g[we]>0),Ee=ce.filter(Boolean).length;if(!Ee)continue;if(Ee===3){M.push(C(re[0]),C(re[1]),C(re[2]));continue}let je=0;Ee===1?je=ce.indexOf(!0):je=ce.indexOf(!1);const le=re[je],Le=re[(je+1)%3],Ae=re[(je+2)%3];if(Ee===1)M.push(C(le),O(le,Le),O(le,Ae));else{const we=O(le,Le),he=O(le,Ae);M.push(we,C(Le),C(Ae),we,C(Ae),he)}}let D=k.length/3;const $=Array.from({length:D},()=>[]);for(let U=0;U<M.length;U+=3)for(let re=0;re<3;re++){const ce=M[U+re],Ee=M[U+(re+1)%3];$[ce].push(Ee),$[Ee].push(ce)}if(l.smoothBase){const U=l.smoothBaseAbove,re=l.smoothBaseLift,ce=we=>U==null?1:Qt(U,U+.1,k[we*3+1])*Qt(.15,.45,b[we*3+2]),Ee=Float64Array.from({length:D},(we,he)=>ce(he)),je=Float64Array.from({length:D},(we,he)=>re==null?0:1-Qt(re,re+.1,k[he*3+1])),le=we=>{const he=Float64Array.from(k);for(let ke=0;ke<D;ke++){if(!$[ke].length||!Ee[ke])continue;let Pe=0,Te=0,Be=0;for(const ie of $[ke])Pe+=k[ie*3],Te+=k[ie*3+1],Be+=k[ie*3+2];const ze=1/$[ke].length,Ke=we*Ee[ke];let Je=(Pe*ze-k[ke*3])*Ke,P=(Te*ze-k[ke*3+1])*Ke,te=(Be*ze-k[ke*3+2])*Ke;const Z=Je*b[ke*3]+P*b[ke*3+1]+te*b[ke*3+2];Z<0&&je[ke]&&(Je-=b[ke*3]*Z*je[ke],P-=b[ke*3+1]*Z*je[ke],te-=b[ke*3+2]*Z*je[ke]),he[ke*3]=k[ke*3]+Je,he[ke*3+1]=k[ke*3+1]+P,he[ke*3+2]=k[ke*3+2]+te}for(let ke=0;ke<he.length;ke++)k[ke]=he[ke]};for(let we=0;we<l.smoothBase;we++)le(.5);const Le=new At;Le.setAttribute("position",new zt(k,3)),Le.setIndex(M),Le.computeVertexNormals();const Ae=Le.getAttribute("normal");for(let we=0;we<D;we++)b[we*3]=Ae.getX(we),b[we*3+1]=Ae.getY(we),b[we*3+2]=Ae.getZ(we);Le.dispose()}let W=new Float32Array(D*3);for(let U=0;U<D;U++)for(let re=0;re<3;re++)W[U*3+re]=k[U*3+re]+b[U*3+re]*w[U];const z=l.smooth??4,Y=new Map;for(let U=0;U<M.length;U+=3)for(let re=0;re<3;re++){const ce=M[U+re],Ee=M[U+(re+1)%3],je=Math.min(ce,Ee)*D+Math.max(ce,Ee);Y.set(je,(Y.get(je)??0)+1)}const J=Array.from({length:D},()=>[]);for(const[U,re]of Y)if(re===1){const ce=Math.floor(U/D),Ee=U%D;J[ce].push(Ee),J[Ee].push(ce)}for(let U=0;U<z+8;U++){const re=Float32Array.from(W);for(let ce=0;ce<D;ce++){const Ee=J[ce].length?J[ce]:$[ce];if(!Ee.length||U>=z&&!J[ce].length)continue;let je=0,le=0,Le=0;for(const we of Ee)je+=W[we*3],le+=W[we*3+1],Le+=W[we*3+2];const Ae=1/Ee.length;re[ce*3]=W[ce*3]*.5+je*Ae*.5,re[ce*3+1]=W[ce*3+1]*.5+le*Ae*.5,re[ce*3+2]=W[ce*3+2]*.5+Le*Ae*.5}for(let ce=0;ce<D;ce++){const Ee=re[ce*3]-k[ce*3],je=re[ce*3+1]-k[ce*3+1],le=re[ce*3+2]-k[ce*3+2],Le=Ee*b[ce*3]+je*b[ce*3+1]+le*b[ce*3+2],Ae=w[ce]*.85;if(Le<Ae)for(let we=0;we<3;we++)re[ce*3+we]+=b[ce*3+we]*(Ae-Le)}W.set(re)}if(l.band){const U=Hy(e,f,l.band,{out:W,base:k,nrm:b,th:w,si:S,sw:E,col:j,idx:M,nv:D});U&&(W=U.out,D=U.nv)}if(l.sole)for(let U=0;U<D;U++){const re=W[U*3+1];if(re<l.sole.y+.02){const ce=Qt(l.sole.y+.02,l.sole.y-.005,re);W[U*3+1]=re-l.sole.th*ce,W[U*3+1]<l.sole.y-l.sole.th&&(W[U*3+1]=l.sole.y-l.sole.th)}}const V=new Map;for(let U=0;U<M.length;U+=3)for(let re=0;re<3;re++){const ce=M[U+re],Ee=M[U+(re+1)%3],je=Math.min(ce,Ee)*D+Math.max(ce,Ee);V.has(je)?V.delete(je):V.set(je,[ce,Ee])}const H=[],G=new Map,_=U=>{let re=G.get(U);return re===void 0&&(re=D+H.length/3,H.push(k[U*3]+b[U*3]*w[U]*.12,k[U*3+1]+b[U*3+1]*w[U]*.12,k[U*3+2]+b[U*3+2]*w[U]*.12),G.set(U,re)),re};for(const[U,re]of V.values()){const ce=_(U),Ee=_(re);M.push(re,U,ce,re,ce,Ee)}const ee=D+H.length/3,Q=[...G.keys()],ve=new Float32Array(ee*3);ve.set(W),ve.set(H,D*3);const ye=new Uint8Array(ee*4),q=new Float32Array(ee*4),pe=j.length?new Float32Array(ee*3):null;ye.set(S),q.set(E),pe?.set(j),Q.forEach((U,re)=>{for(let ce=0;ce<4;ce++)ye[(D+re)*4+ce]=S[U*4+ce],q[(D+re)*4+ce]=E[U*4+ce];if(pe)for(let ce=0;ce<3;ce++)pe[(D+re)*3+ce]=j[U*3+ce]});const ue=new At;return ue.setAttribute("position",new Rt(ve,3)),ue.setAttribute("skinIndex",new js(ye,4)),ue.setAttribute("skinWeight",new Rt(q,4)),pe&&ue.setAttribute("color",new Rt(pe,3)),ue.setIndex(M),ue.computeVertexNormals(),ue.userData.shared=!0,ue.userData.realDispose=ue.dispose.bind(ue),ue.dispose=()=>{},u={geometry:ue,covered:v},Sa.set(h,u),u}const Ka=8;function du(e,n,s=Ka){const o=Math.hypot(e[0],e[1],e[2])||1,i=e[0]/o,r=e[1]/o,l=e[2]/o;let h=1-i*i,u=-i*r,m=-i*l;const d=Math.hypot(h,u,m);d<1e-4?(h=-l*i,u=-l*r,m=1-l*l):(h/=d,u/=d,m/=d);const f=r*m-l*u,p=l*h-i*m,y=i*u-r*h,g=Math.atan2(n[0]*f+n[1]*p+n[2]*y,n[0]*h+n[1]*u+n[2]*m);return(Math.round(g/(Math.PI*2)*s)%s+s)%s}const go=new Map;function Gy(e,n){const s=Xn(n);let o=go.get(s);if(o)return o;const i=Qr(e,0,n),r=Ms(e,n,0).getAttribute("position").array,l=dd(ti({...n,head:1,posture:0},Pr,{bind:!0})),h=12,u=Ka;o={L:{thigh:new Float32Array(h*u),shin:new Float32Array(h*u)},R:{thigh:new Float32Array(h*u),shin:new Float32Array(h*u)}};for(const m of["L","R"])for(const[d,f,p]of[["thigh",`thigh${m}`,`shin${m}`],["shin",`shin${m}`,`foot${m}`]]){const y=l.get(f).t,g=l.get(p).t,v=[g[0]-y[0],g[1]-y[1],g[2]-y[2]],b=v[0]**2+v[1]**2+v[2]**2,k=o[m][d];for(let S=0;S<i.cat.length;S++){const E=d==="thigh"&&i.cat[S]===nt.torso&&r[S*3+1]<y[1]+.02&&r[S*3+2]<y[2]+.02;if(i.cat[S]!==nt.leg&&!E||Math.sign(r[S*3])!==(m==="L"?-1:1))continue;const j=[r[S*3]-y[0],r[S*3+1]-y[1],r[S*3+2]-y[2]],M=(j[0]*v[0]+j[1]*v[1]+j[2]*v[2])/b,T=E?Math.max(0,M):M;if(T<0||T>(E?.35:1)||E&&M<-.12)continue;const N=[j[0]-v[0]*T,j[1]-v[1]*T,j[2]-v[2]*T],R=Math.hypot(N[0],N[1],N[2]);if(R>(d==="thigh"&&T<.4&&N[2]<0?.18:.12))continue;const A=Math.min(h-1,Math.floor(T*h)),C=du(v,N,u);k[A*u+C]=Math.max(k[A*u+C],R)}const w=k.slice();for(let S=0;S<h;S++)for(let E=0;E<u;E++){let j=0;for(const M of[S-1,S,S+1])for(const T of[E-1,E,E+1])M<0||M>=h||(j=Math.max(j,w[M*u+(T+u)%u]));k[S*u+E]=j}for(let S=0;S<h;S++)for(let E=0;E<u;E++)k[S*u+E]||(k[S*u+E]=S?k[(S-1)*u+E]:.06)}return go.size>48&&go.clear(),go.set(s,o),o}const ch=new Map;function qy(e,n,s,o,i,r){const l=`${s}|${Xn(n)}|${JSON.stringify(o)}|${i}|${r}`;let h=ch.get(l);if(h)return h;const u=Ms(e,n,s),m=u.getAttribute("position"),d=Qr(e,s,n),f=e.bind,p=r==="cape",y=p?"torso":"pelvis",g=f.torso[1]+o.top,v=72,b=new Float32Array(v);for(let V=0;V<m.count;V++){if(d.cat[V]!==nt.torso&&d.cat[V]!==nt.leg&&!(p&&d.cat[V]===nt.arm&&d.armT[V]<.15)||Math.abs(m.getY(V)-g)>.025)continue;const H=m.getX(V),G=m.getZ(V),_=Math.atan2(H,G),ee=(Math.round(_/(Math.PI*2)*v)%v+v)%v;b[ee]=Math.max(b[ee],Math.hypot(H,G))}const k=o.panels==="apron"?.34:.2,w=new Float32Array(v);for(let V=0;V<m.count;V++){if(d.cat[V]!==nt.torso&&!(k>.2&&d.cat[V]===nt.leg))continue;const H=g-m.getY(V);if(H<0||H>k)continue;const G=m.getX(V),_=m.getZ(V),ee=Math.atan2(G,_),Q=(Math.round(ee/(Math.PI*2)*v)%v+v)%v;w[Q]=Math.max(w[Q],Math.hypot(G,_))}for(let V=0;V<3;V++){const H=Float32Array.from(b),G=Float32Array.from(w);for(let _=0;_<v;_++)b[_]=Math.max(H[_],(H[(_+v-1)%v]+H[(_+1)%v])/2),w[_]=Math.max(G[_],(G[(_+v-1)%v]+G[(_+1)%v])/2)}const S=V=>{const H=(V/(Math.PI*2)*v+v*4)%v,G=Math.floor(H),_=H-G;return w[G%v]*(1-_)+w[(G+1)%v]*_+.014+i*.006},E=V=>{const H=(V/(Math.PI*2)*v+v*4)%v,G=Math.floor(H),_=H-G;return b[G%v]*(1-_)+b[(G+1)%v]*_+.008+i*.006},j=(()=>{if(!p)return()=>0;const V=Math.ceil((o.length+.1)/.02),H=new Float32Array(V);for(let G=0;G<m.count;G++){if(d.cat[G]!==nt.torso&&d.cat[G]!==nt.leg)continue;const _=Math.floor((g-m.getY(G))/.02),ee=m.getZ(G);_<0||_>=V||ee>=0||Math.abs(m.getX(G))>.16||(H[_]=Math.max(H[_],-ee))}for(let G=1;G<V;G++)H[G]=Math.max(H[G],H[G-1]);return G=>{const _=g-G,ee=Math.max(0,Math.min(V-1,Math.floor(_/.02)));return H[ee]+.012+(o.clear??0)*Math.min(1,Math.max(0,(_-.35)/Math.max(.1,o.length-.35)))}})(),M=V=>p?.07*Math.sin(V)**2:0,T=V=>r==="cape"?E(V):Math.max(E(V),S(V)),N=V=>Math.max(T(V)*1.04,E(V)*o.flare),R=p?[[Math.PI*.55,Math.PI*1.45]]:o.panels==="aodai"?[[-.95,.95],[Math.PI-1.3,Math.PI+1.3]]:o.panels==="apron"?[[-1.1,1.1]]:o.open?[[o.open*Math.PI/180,Math.PI*2-o.open*Math.PI/180]]:[[0,Math.PI*2]],A=!p&&!o.panels&&!o.open,C=[],O=[],B=[],D=[],$=[],W=[],z=4,Y=Math.max(16,Math.round(o.length/.022));p?f.torso[1]:f.torso[1]-.07;for(const[V,H]of R){const G=H-V,_=Math.max(2,Math.round((o.chains??12)*G/(Math.PI*2))+(A?0:1)),ee=Math.max(8,Math.round(56*G/(Math.PI*2))),Q=$.length;for(let ye=0;ye<_;ye++){const q=A?V+G*ye/_:V+G*ye/(_-1),pe=E(q),ue=[Math.sin(q)*pe,g-M(q),Math.cos(q)*pe],U=(p?pe*o.flare:N(q))+(p?.03:0),re=[Math.sin(q)*U,g-o.length,Math.cos(q)*U];p&&(re[2]=Math.min(re[2],-.12-.02*Math.abs(Math.sin(q)),Math.cos(q)*j(re[1])));const ce=[(re[0]-ue[0])/z,(re[1]-ue[1])/z,(re[2]-ue[2])/z];$.push({at:ue,dirs:Array.from({length:z},()=>ce),seg:ye})}const ve=C.length/3;W.push({base:ve,width:ee+1,rows:Y+1,wrap:A});for(let ye=0;ye<=Y;ye++){const q=ye/Y;for(let pe=0;pe<=ee;pe++){const ue=V+G*pe/ee,U=E(ue),re=(o.folds??0)*Math.sin(ue*(p?14:22))*q,ce=T(ue),Ee=p?0:Math.min(1,o.length*q/k),je=U+(ce-U)*Math.sin(Math.min(1,Ee)*Math.PI/2);let le=(p?U+(U*o.flare+.03-U)*q:q*o.length<=k?je:ce+(N(ue)-ce)*((o.length*q-k)/Math.max(1e-6,o.length-k)))+re,Le=Math.cos(ue)*le;p&&(Le=Math.min(Le,Math.cos(ue)*U+(-.12-Math.cos(ue)*U)*q,Math.cos(ue)*j(g-o.length*q))),C.push(Math.sin(ue)*le,g-M(ue)*(1-q)-o.length*q,Le);const Ae=A?(ue-V)/G*_:(ue-V)/G*(_-1);let we=Math.floor(Ae),he=Ae-we;A?we%=_:we>=_-1&&(we=_-2,he=1);const ke=A?(we+1)%_:we+1,Pe=q*z,Te=Math.min(z-1,Math.floor(Pe)),Be=Math.min(1,Pe-Te),ze=Math.min(z-1,Te+1),Ke=[[(Q+we)*z+Te,(1-he)*(ze===Te?1:1-Be)],[(Q+ke)*z+Te,he*(ze===Te?1:1-Be)]];for(ze!==Te&&Ke.push([(Q+we)*z+ze,(1-he)*Be],[(Q+ke)*z+ze,he*Be]);Ke.length<4;)Ke.push([0,0]);for(const[Je,P]of Ke)B.push(Je),D.push(P)}}for(let ye=0;ye<Y;ye++)for(let q=0;q<ee;q++){const pe=ve+ye*(ee+1)+q,ue=pe+ee+1;O.push(pe,ue,pe+1,pe+1,ue,ue+1)}}const J=new At;return J.setAttribute("position",new zt(C,3)),J.setAttribute("skinIndex",new jd(B,4)),J.setAttribute("skinWeight",new zt(D,4)),J.setIndex(O),J.computeVertexNormals(),J.userData.shared=!0,J.userData.rings=W,J.dispose=()=>{},h={geometry:J,roots:$,anchor:y},ch.set(l,h),h}function Uy(e,n,s){const o=e.bones.get(n.anchor),i=[],r=new Map,l=[],h=n.anchor==="torso"?new ae(0,1,0):new ae(0,.93,0);return n.roots.forEach((u,m)=>{let d=o,f=new ae(...u.at);const p=[],y=[];u.dirs.forEach((g,v)=>{const b=new _a;b.name=`${s}${m}_${v}`;const k=v===0?f.clone().sub(h):new ae(...u.dirs[v-1]);b.position.copy(k),d.add(b),e.bones.set(b.name,b),r.set(b.name,new Nt().makeTranslation(-f.x,-f.y,-f.z)),i.push(b.name),p.push(b),y.push(new ae(...g)),d=b,f=f.clone().add(new ae(...g))}),l.push({bones:p,rest:y,kind:"cloth",stiffness:.5,collide:!0,side:m})}),{bones:i,inverses:r,set:{kind:"cloth",anchor:n.anchor,chains:l}}}const xo=new Map;function bo(e,n,s,o,i,r,l){const h=e.pos.length/3,u=o?n:n+1;for(const f of[0,1])for(let p=0;p<=s;p++)for(let y=0;y<u;y++){const g=i(y/n,p/s,f),[v,b]=l(y/n,p/s);e.pos.push(...g),e.col.push(...r(y/n,p/s,f,g[1]));for(let k=0;k<4;k++)e.si.push(v[k]??0),e.sw.push(b[k]??0)}const m=(f,p,y)=>h+f*u*(s+1)+y*u+(o?p%n:p);for(let f=0;f<s;f++)for(let p=0;p<n;p++){const y=M=>[m(M,p,f),m(M,p+1,f),m(M,p+1,f+1),m(M,p,f+1)],[g,v,b,k]=y(0),[w,S,E,j]=y(1);e.idx.push(g,v,b,g,b,k,w,E,S,w,j,E)}const d=(f,p)=>{const y=m(0,...f),g=m(0,...p),v=m(1,...f),b=m(1,...p);e.idx.push(y,v,b,y,b,g)};for(let f=0;f<n;f++)d([f,0],[f+1,0]),d([f+1,s],[f,s]);if(!o)for(let f=0;f<s;f++)d([n,f],[n,f+1]),d([0,f+1],[0,f])}function Xy(e,n,s,o,i,r,l,h,u=0){const m=`${s}|${Xn(n)}|${i}|${l}|${h}|${u}`;let d=xo.get(m);if(d)return d;const f=Ms(e,n,s),p=f.getAttribute("position").array,y=o.cat.length,g=new Uint8Array(y),v={pos:[],idx:[],si:[],sw:[],col:[]},b=new Ve(l),k=B=>{const D=new Ve(B);return[D.r/Math.max(.02,b.r),D.g/Math.max(.02,b.g),D.b/Math.max(.02,b.b)]},w=b.r*.3+b.g*.59+b.b*.11,S=k(h),E=k(w>.55?"#8d8f94":"#d9d9d4"),j=k(w>.45?"#2b2c30":"#efefea"),M=k(b.clone().multiplyScalar(.45)),T=i==="boots"?.036:i==="heels"?.022:i==="sandals"?0:i==="sneakers"?.032:.026,N=40,R=12,A=i==="sneakers"?.0045:.003,C=i==="sneakers"?.12:.45;for(const B of["L","R"]){const D=e.bind[`foot${B}`],$=e.bones.indexOf(`foot${B}`),W=e.bones.indexOf(`shin${B}`),z=[],Y=[];for(let he=0;he<y;he++)o.cat[he]===nt.foot&&Math.sign(p[he*3])===(B==="L"?-1:1)&&(Y.push(he),o.footY[he]<-.012&&z.push(he));if(!z.length)continue;let J=1/0,V=-1/0;for(const he of z)J=Math.min(J,p[he*3+2]),V=Math.max(V,p[he*3+2]);J-=.006,V+=i==="heels"||i==="dress"?.02:i==="sandals"?.008:.014;const H=14,G=new Float64Array(H),_=new Float64Array(H),ee=new Float64Array(H);for(let he=0;he<H;he++){const ke=J+(V-J)*(he/H),Pe=J+(V-J)*((he+1)/H);let Te=1/0,Be=-1/0,ze=-1/0;for(const Ke of Y){const Je=p[Ke*3+2];Je<ke-.01||Je>Pe+.01||o.footY[Ke]>.035||(Te=Math.min(Te,p[Ke*3]),Be=Math.max(Be,p[Ke*3]),ze=Math.max(ze,p[Ke*3+1]))}Te===1/0?(G[he]=he?G[he-1]:D[0],_[he]=he?_[he-1]:.04,ee[he]=he?ee[he-1]:D[1]-.03):(G[he]=(Te+Be)/2,_[he]=(Be-Te)/2,ee[he]=ze)}const Q=(he,ke)=>{const Pe=Math.min(H-1,Math.max(0,ke*H-.5)),Te=Math.floor(Pe),Be=Math.min(H-1,Te+1),ze=Pe-Te;return he[Te]*(1-ze)+he[Be]*ze},ve=D[1]-o.sole-r,ye=ve+r,q=B==="L"?1:-1,pe=he=>{const ke=Math.sqrt(Math.max(0,1-((.17-Math.min(he,.17))/.17)**2)),Pe=Math.max(0,(he-.62)/.38),Te=Math.max(Q(_,he),.028)+.006;return{w:Te*ke*Math.sqrt(Math.max(0,1-Math.pow(Pe,2.4))),x0:Q(G,he)+q*Te*.28*Math.pow(Pe,1.5),spring:.008*Qt(.7,1,he)**2,z:J+(V-J)*he}},ue=D[1]-(i==="sneakers"?.012:i==="boots"?-.04:i==="heels"?.04:.018),U=i==="heels"?.6:i==="boots"?0:i==="sneakers"?.44:.5,re=i==="sneakers"||i==="boots"?.74:.66,ce=he=>{const ke=Math.max(Math.min(D[1]+(i==="boots"?.02:i==="sneakers"?.004:-.006),Q(ee,he)+.009),ye+T)-ye;return Math.max(.004,ke*Math.sqrt(Math.max(0,1-Math.pow(Math.max(0,(he-re)/(1-re)),2))))},Ee=Math.min(ue,Q(ee,U)+(i==="heels"?-.004:.006)),je=he=>he>=U?1/0:he<.28?ue:ue+(Ee-ue)*Qt(.28,U,he),le=he=>Math.max(ce(he),Number.isFinite(je(he))?je(he)-ye+.025*(1-Qt(U-.06,U,he)):0),Le=(he,ke,Pe)=>{const Te=pe(he),Be=Math.cos(ke),ze=Math.max(0,Math.sin(ke)),Ke=Math.sign(Be)*Math.pow(Math.abs(Be),.8);return[Te.x0+(Te.w+Pe)*Ke*(1-.16*ze),ye+Te.spring-r*C+(le(he)+r*C+Pe)*Math.pow(ze,.85),Te.z]},Ae=he=>{const ke=je(he);if(!Number.isFinite(ke))return Math.PI/2;const Pe=(ke-ye-pe(he).spring+r*C)/(le(he)+r*C);return Pe>=1?Math.PI/2:Math.asin(Math.max(.05,Math.pow(Math.max(0,Pe),1/.85)))},we=()=>[[$],[1]];for(const he of Y){const ke=Math.min(1,Math.max(0,(p[he*3+2]-J)/(V-J))),Pe=p[he*3+1];i==="sandals"?Pe<ye+.004&&(g[he]=1):i==="heels"?(ke>=U-.03||Pe<je(ke)-.005)&&(g[he]=1):g[he]=1}if(bo(v,N,16,!1,(he,ke,Pe)=>{const Te=pe(he),Be=i==="heels"?.001:i==="sneakers"?.006:.0035,ze=ke*Math.PI*2,Ke=Math.cos(ze),Je=Math.sin(ze),P=Pe?.6:1;return[Te.x0+(Te.w*1.03+Be)*P*Math.sign(Ke)*Math.pow(Math.abs(Ke),.35),ve+Te.spring+r*.5+r*.5*P*Math.sign(Je)*Math.pow(Math.abs(Je),.35),Te.z]},(he,ke,Pe,Te)=>i==="sneakers"&&Te>ve+r*.62&&Te<ve+r*.8?E:S,we),i==="sandals"){for(const[he,ke]of[[.6,.66],[.38,.44]])bo(v,6,16,!1,(Pe,Te,Be)=>{const ze=he+(ke-he)*Pe,Ke=pe(ze),Je=Math.PI*Te,P=Math.cos(Je),te=Math.sin(Je),Z=Be?.002:.0045,ie=Math.max(.006,Q(ee,ze)+.004-ye);return[Ke.x0+(Ke.w+Z-.004)*Math.sign(P)*Math.pow(Math.abs(P),.7),ye+Ke.spring-.001+(ie+Z)*Math.pow(te,.8),Ke.z]},()=>[1,1,1],we);continue}for(const he of[1,-1])bo(v,N,R,!1,(ke,Pe,Te)=>{const Be=Ae(ke),ze=he>0?Be*Pe:Math.PI-Be*Pe;return Le(ke,ze,Te?0:A)},(ke,Pe,Te)=>Te?ke<U+.05?M:[1,1,1]:i==="sneakers"&&ke>.44&&ke<.68&&Pe>.82&&Math.sin(ke*Math.PI*42)>.2?j:[1,1,1],we);if(i==="boots"){const he=Be=>{for(let ze=.015;;ze*=1.5){let Ke=1/0,Je=-1/0,P=1/0,te=-1/0,Z=0;for(let ie=0;ie<y;ie++)o.cat[ie]!==nt.leg&&o.cat[ie]!==nt.foot||Math.sign(p[ie*3])!==(B==="L"?-1:1)||Math.abs(p[ie*3+1]-Be)>ze||(Z++,Ke=Math.min(Ke,p[ie*3]),Je=Math.max(Je,p[ie*3]),P=Math.min(P,p[ie*3+2]),te=Math.max(te,p[ie*3+2]));if(Z>=24||ze>.1)return{cx:(Ke+Je)/2,cz:(P+te)/2,rx:(Je-Ke)/2,rz:(te-P)/2}}},ke=D[1]+.005,Pe=D[1]+.2,Te=Array.from({length:9},(Be,ze)=>{const Ke=ke+(Pe-ke)*(ze/8);return{y:Ke,...he(Ke)}});for(let Be=7;Be>=0;Be--)Te[Be].rx=Math.max(Te[Be].rx,Te[Be+1].rx*.9),Te[Be].rz=Math.max(Te[Be].rz,Te[Be+1].rz*.9);bo(v,32,8,!0,(Be,ze,Ke)=>{const Je=Te[Math.round(ze*8)],P=Be*Math.PI*2,te=u+(Ke?.004:.0075);return[Je.cx+(Je.rx+te)*Math.sin(P),Je.y,Je.cz+(Je.rz+te)*Math.cos(P)]},()=>[1,1,1],(Be,ze)=>{const Ke=Qt(D[1]-.01,D[1]+.05,Te[Math.round(ze*8)].y);return[[$,W],[1-Ke,Ke]]})}}const O=new At;return O.setAttribute("position",new zt(v.pos,3)),O.setAttribute("skinIndex",new js(v.si,4)),O.setAttribute("skinWeight",new zt(v.sw,4)),O.setAttribute("color",new zt(v.col,3)),O.setIndex(v.idx),O.computeVertexNormals(),O.userData.shared=!0,O.userData.realDispose=O.dispose.bind(O),O.dispose=()=>{},d={geometry:O,hide:g},xo.size>48&&xo.clear(),xo.set(m,d),d}const Vy=new Nt().makeTranslation(0,-.008,-.0155).multiply(new Nt().makeScale(.66,1,.75));function Yy(e,n,s,o,i,r={}){const l=[],h=Qr(e,i,s),u=[],m=[],d=(S,E,j,M,T,N={},R)=>{const A=Wy(e,s,i,S,E,R??(()=>j),N);A.geometry.getIndex()?.count&&(l.push({geometry:A.geometry,material:M,slot:T,skinned:!0}),u.push(A.covered),m.push(S))},f=S=>Bs(`fab:${zy(S)}:${S.color}`),p=(S,E,j,M,T="skirt")=>{if(r.fittedOnly)return;const N=qy(e,s,i,S,E,T),R=Uy(n,N,`${M}${T}`);l.push({geometry:N.geometry,material:j,slot:M,skinned:!0,bones:R.bones,inverses:R.inverses,chains:R.set,drape:T!=="cape"})},y=o.top?Xo[o.top.type]??Xo.tshirt:null,g=!!y&&!!o.bottom&&(["shirt","police","polo"].includes(o.top.type)&&["trousers","jeans","shorts","ancient"].includes(o.bottom.type)||!!Nn[o.bottom.type]?.loose&&!y.loose),v=y&&g?{...y,hem:(Nn[o.bottom.type]?.waist??.05)-.05}:y,b=S=>h.cat[S]===nt.torso?.003:0;if(o.bottom){const S=Nn[o.bottom.type]??Nn.trousers,E=g?v.th+.005:0,j=o.shoes?.type==="boots"&&S.leg>1.6;d(`bottom|${o.bottom.type}|${g}|${j}`,Ky(h,j?{...S,leg:1.6}:S),S.th,f(o.bottom),"bottom",{},M=>(o.bottom.type==="ancient"?S.th*(.6+.6*Qt(.6,1.8,h.legT[M])):S.th)+(E?E*Qt(-.2,-.05,h.yt[M]):0)),S.loose&&p(S.loose,0,f(o.bottom),"bottom")}if(o.top){const S=v,E=!S.loose&&S.hem<Ma,j=E?{...S,hem:Ma}:S,M=o.top.color2,T=o.bottom&&!g?(Nn[o.bottom.type]?.th??.007)+.002:0,N=j.stripes?C=>{const O=h.yt[C],D=(Math.abs(O-.12)<.018||Math.abs(O-.26)<.018)&&h.cat[C]===nt.torso?new Ve(M??"#e6e6e0"):new Ve(o.top.color),$=new Ve(o.top.color);return[D.r/Math.max(.02,$.r),D.g/Math.max(.02,$.g),D.b/Math.max(.02,$.b)]}:void 0,R=N?dh(f(o.top)):f(o.top),A=Math.max(1+j.hem+.1,T?1+(Nn[o.bottom.type]?.waist??.06)+.08:0);d(`top|${o.top.type}|${M??""}|${g}|${T}|${A.toFixed(3)}`,lh(h,j,.67*Xa(s).shoulderX),j.th,R,"top",{colors:N,smooth:6,...j.th>=.01?{smoothBase:6,smoothBaseLift:A}:{},...E&&Ma-S.hem>.015?{band:{hem:Ma,length:Ma-S.hem,flare:.25,tuck:.3,cat:h.cat}}:{}},C=>j.th+b(C)+(T&&h.yt[C]<.12?T*Qt(.12,.04,h.yt[C]):0)+(j.neck==="collar"||j.neck==="high"?.005*Qt(.5,.58,h.yt[C]):0)),j.loose&&p(j.loose,1,f(o.top),"top")}if(o.outer){const S=o.outer.type;if(Vo[S]){const E=Vo[S],j=Math.max(1+E.hem+.1,o.bottom&&Nn[o.bottom.type]?1+Nn[o.bottom.type].waist+.08:0);d(`outer|${S}|${j.toFixed(3)}`,lh(h,E,.67*Xa(s).shoulderX),E.th,f(o.outer),"outer",{smooth:6,smoothBase:6,smoothBaseLift:j},M=>E.th+(h.cat[M]===nt.torso?.006:0)),E.loose&&p(E.loose,2,f(o.outer),"outer")}else if(S==="cape"){const E=[v?.loose,o.bottom?Nn[o.bottom.type]?.loose:void 0].reduce((j,M)=>M?Math.max(j,.025+(M.flare-1)*.16):j,0);p({top:.47,length:1.05,flare:1.15,folds:.012,chains:10,...E?{clear:Math.round(E*1e3)/1e3}:{}},2,f(o.outer),"outer","cape")}else S==="apron"&&p({top:.12,length:.55,flare:1.04,panels:"apron",folds:.002,chains:5},2,f(o.outer),"outer")}if(o.shoes&&o.shoes.type!=="barefoot"){const S=o.shoes.type,E=S==="sneakers"?.027:S==="boots"?.022:S==="sandals"?.014:S==="heels"?.008:.014,j=S==="sneakers"?"#f4f4f0":S==="sandals"?ki(o.shoes.color,-.25):S==="boots"||S==="dress"||S==="heels"?ki(o.shoes.color,-.55):ki(o.shoes.color,-.3),M=o.shoes.fabric??(S==="sneakers"||S==="cloth"?"cotton":"leather"),T=dh(Bs(M==="leather"?`sol:${o.shoes.color}:0.36:0`:`fab:${M}:${o.shoes.color}`));S!=="sandals"&&S!=="heels"&&S!=="boots"&&d(`socks|${S}`,A=>h.cat[A]===nt.leg?(h.legT[A]-1.8)*.43:h.cat[A]===nt.foot?Math.min((h.legT[A]-1.8)*.43,(h.footY[A]+.045)*.6,(e.bind.footL[2]+.02-h.z[A])*.6):-1,.0018,Bs(`fab:cotton:${S==="sneakers"?"#e9e9e4":"#2a2a2d"}`),"shoes",{smooth:3});const N=S==="boots"&&o.bottom?Nn[o.bottom.type]?.th??.007:0,R=Xy(e,s,i,h,S,E,o.shoes.color,j,N);if(l.push({geometry:R.geometry,material:T,slot:"shoes",skinned:!0}),u.push(R.hide),m.push(`last|${S}`),S==="heels"&&!r.fittedOnly)for(const A of["L","R"]){const C=new ws(.011,.0055,.072,12);C.scale(1,1,1.15),C.rotateX(-22*Math.PI/180),C.translate(0,-.086,-.092),l.push({geometry:C,material:Bs(`sol:${o.shoes.color}:0.4:0`),slot:"shoes",skinned:!1,bone:`foot${A}`})}}if(o.hat&&!r.fittedOnly)for(const S of Ry(e,o.hat,o.hair?.style))l.push({geometry:S.geometry,material:Bs(S.mat),slot:S.slot,skinned:!1,bone:"head"});if(o.accessories?.length&&!r.fittedOnly){const S=hp({shoulders:s.shoulders,hips:s.hips,chest:s.chest,waist:s.waist,weight:s.weight,muscle:s.muscle,face:"simple"},"#888888");for(const E of dp(S,{accessories:o.accessories})){const j=E.geo.clone();E.group==="head"&&j.applyMatrix4(ry(e).multiply(Vy)),l.push({geometry:j,material:Bs(E.mat),slot:"accessory",skinned:!1,bone:E.group})}}const k=[v?.loose,o.bottom?Nn[o.bottom.type]?.loose:void 0].find(S=>S&&S.length>=.45&&!S.panels&&!S.open);if(k&&!r.fittedOnly&&(!o.bottom||Nn[o.bottom.type]?.loose)){const S=new Uint8Array(h.cat.length);for(let E=0;E<S.length;E++)(h.cat[E]===nt.torso&&h.yt[E]<k.top-.02||h.cat[E]===nt.leg&&h.legT[E]<.3)&&(S[E]=1);u.push(S),m.push(`seat|${k.top}`)}let w=null;if(u.length){w=new Uint8Array(h.cat.length);for(const S of u)for(let E=0;E<S.length;E++)S[E]&&(w[E]=1)}return{parts:l,hide:w,hideKey:m.join("§")}}const hh=new Map;function dh(e){let n=hh.get(e);return n||(n=e.clone(),n.vertexColors=!0,n.onBeforeCompile=e.onBeforeCompile,n.customProgramCacheKey=e.customProgramCacheKey,n.userData.shared=!0,n.dispose=()=>{},hh.set(e,n)),n}const Ha=new qe,uh=new qe,mh=new qe,Qy=new Nt,uu=new Nt,Ps=new ae,as=new ae,en=new ae,Pn=new ae,Wt=new ae,yo=new ae,hn=new ae,na=new ae,xn=Array.from({length:14},()=>({a:new ae,b:new ae,r:0,rb:0,lap:!1})),vo=[0,0,0],jo=[0,0,0],mu=(e,n,s,o,i)=>{const r=e.length/Ka,l=Math.min(r-1,Math.max(0,n*r-.5)),h=Math.floor(l),u=l-h,m=Math.min(r-1,h+1);vo[0]=s.b.x-s.a.x,vo[1]=s.b.y-s.a.y,vo[2]=s.b.z-s.a.z,jo[0]=o.x-i.x,jo[1]=o.y-i.y,jo[2]=o.z-i.z;const d=du(vo,jo);return e[h*Ka+d]*(1-u)+e[m*Ka+d]*u};function ra(e,n,s,o){const i=e.bones.get(n);return s.set(...o??[0,0,0]).applyMatrix4(i.matrixWorld).applyMatrix4(uu),s}const Yt=7;function pu(e){uu.copy(e.root.matrixWorld).invert();let n=0;const s=(o,i,r,l,h,u=r)=>{const m=xn[n++];ra(e,o,m.a,l),ra(e,i,m.b,h),m.r=r,m.rb=u,m.lap=!1};s("torso","torso",.155,[0,-.06,-.01],[0,.36,-.02]),s("head","head",.105,[0,0,-.01],[0,.06,-.015]),s("armL","armR",.07);for(const o of["L","R"])s(`fore${o}`,`hand${o}`,.045),s(`hand${o}`,`hand${o}`,.048,[0,0,.005],[0,-.13,.01]);if(n!==Yt)throw new Error("HQ dynamics: leg capsules must start at LEGS");for(const o of["L","R"])s(`thigh${o}`,`shin${o}`,.088,void 0,void 0,.064),s(`shin${o}`,`foot${o}`,.062,void 0,void 0,.05),s(`foot${o}`,`foot${o}`,.058,[0,-.03,-.02],[0,-.04,.2]);for(const[o,i]of[[3,4],[5,6]]){const r=xn[i];na.addVectors(r.a,r.b).multiplyScalar(.5);for(const l of[Yt,Yt+3]){Zr(xn[l],na,hn),as.subVectors(na,hn);const h=as.length();h<.16&&as.y>.6*h&&(xn[o].lap=xn[i].lap=!0)}}return n}function Zr(e,n,s){Ps.subVectors(e.b,e.a);const o=Ps.lengthSq(),i=o>1e-10?Math.max(0,Math.min(1,as.subVectors(n,e.a).dot(Ps)/o)):0;return s.copy(e.a).addScaledVector(Ps,i),i}function ph(e,n,s){const o=Zr(n,e,hn),i=e.distanceTo(hn),r=(n.prof?mu(n.prof,o,n,e,hn):n.r+(n.rb-n.r)*o)+s;i<r&&i>1e-6&&e.sub(hn).multiplyScalar(r/i).add(hn)}const fh=.68,Zy=(e,n,s)=>{const o=n.x-s.x,i=n.z-s.z,r=Math.hypot(o,i);if(r<1e-6)return e.r;const l=o/r,h=i/r;return e.r/Math.sqrt(l*l+h*h/(fh*fh))};function gr(e,n,s,o=!1){for(let i=0;i<n;i++){const r=xn[i];if(o&&(i<2||r.lap))continue;const l=Zr(r,e,hn),h=e.distanceTo(hn),u=(r.prof?mu(r.prof,l,r,e,hn):i===0?Zy(r,e,hn):r.r+(r.rb-r.r)*l)+s;h>=u||(h<1e-6?e.y-=u:e.sub(hn).multiplyScalar(u/h).add(hn))}}function Jy(e,n,s,o){e.root.updateMatrixWorld(!0);const i=pu(e);xn[Yt].prof=s.L.thigh,xn[Yt+1].prof=s.L.shin,xn[Yt+3].prof=s.R.thigh,xn[Yt+4].prof=s.R.shin;for(let r=0;r<n.length;r+=3){Wt.set(n[r],n[r+1],n[r+2]);for(let l=0;l<5;l++)gr(Wt,i,.007,!0);for(const l of[Yt,Yt+1,Yt+3,Yt+4])ph(Wt,xn[l],.007);n[r]=Wt.x,n[r+1]=Wt.y,n[r+2]=Wt.z}if(o?.some(r=>r.wrap)){for(const r of o)r.wrap&&ev(n,r);for(let r=0;r<n.length;r+=3){Wt.set(n[r],n[r+1],n[r+2]);for(let l=0;l<2;l++)for(const h of[Yt,Yt+1,Yt+3,Yt+4])ph(Wt,xn[h],.007);n[r]=Wt.x,n[r+1]=Wt.y,n[r+2]=Wt.z}}for(const r of[0,1,3,4])xn[Yt+r].prof=void 0}function ev(e,n){const s=n.width-1,o=new Float64Array(s),i=new Float64Array(s),r=new Float64Array(s),l=new Float64Array(s),h=new Float64Array(s);for(let u=0;u<n.rows;u++){const m=n.base+u*n.width;let d=0,f=0;for(let S=0;S<s;S++)o[S]=e[(m+S)*3],i[S]=e[(m+S)*3+2],d+=o[S],f+=i[S];d/=s,f/=s;const p=Array.from({length:s},(S,E)=>E).sort((S,E)=>o[S]-o[E]||i[S]-i[E]),y=(S,E,j)=>(o[E]-o[S])*(i[j]-i[S])-(i[E]-i[S])*(o[j]-o[S]),g=[],v=[];for(const S of p){for(;g.length>=2&&y(g[g.length-2],g[g.length-1],S)<=0;)g.pop();g.push(S)}for(let S=p.length-1;S>=0;S--){const E=p[S];for(;v.length>=2&&y(v[v.length-2],v[v.length-1],E)<=0;)v.pop();v.push(E)}const b=[...g.slice(0,-1),...v.slice(0,-1)];for(let S=0;S<s;S++){const E=o[S]-d,j=i[S]-f,M=Math.hypot(E,j);if(l[S]=Math.atan2(E,j),r[S]=M,M<1e-6)continue;const T=E/M,N=j/M;let R=M;for(let A=0;A<b.length;A++){const C=b[A],O=b[(A+1)%b.length],B=o[O]-o[C],D=i[O]-i[C],$=T*D-N*B;if(Math.abs($)<1e-9)continue;const W=o[C]-d,z=i[C]-f,Y=(W*D-z*B)/$,J=(W*N-z*T)/$;Y>0&&J>=-1e-6&&J<=1+1e-6&&(R=Math.max(R,Y))}r[S]=R}for(let S=0;S<s;S++){let E=0;for(let j=-2;j<=2;j++)E+=r[(S+j+s)%s];h[S]=Math.max(r[S],E/5)}for(let S=0;S<s;S++){const E=(m+S)*3;e[E]=d+Math.sin(l[S])*h[S],e[E+2]=f+Math.cos(l[S])*h[S]}const k=(m+s)*3,w=m*3;e[k]=e[w],e[k+1]=e[w+1],e[k+2]=e[w+2]}}const Ca=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)},Hn=new ae,Yo=new ae,gh=new ae,xr={L:new ae,R:new ae},Po={L:new ae,R:new ae},br={L:1,R:1},xh=e=>n=>Hn.subVectors(n,xr[e]).dot(Po[e])/br[e],bh={L:new qe,R:new qe,alongL:xh("L"),alongR:xh("R")};function tv(e,n){e.bones.get("torso").getWorldQuaternion(Ha).premultiply(n),gh.set(0,-1,0).applyQuaternion(Ha);for(const s of["L","R"])ra(e,`thigh${s}`,xr[s]),ra(e,`shin${s}`,Yo),br[s]=Math.max(1e-6,Po[s].subVectors(Yo,xr[s]).length()),Po[s].divideScalar(br[s]),bh[s].setFromUnitVectors(gh,Po[s]);return bh}function nv(e,n,s,o){if(!e.length)return;const i=pu(n),r=o?.vel??[0,0,0],l=o?.acc??[0,0,0],h=o?.time??0,u=o?.air??0,m=Math.hypot(r[0],r[1],r[2]);n.root.updateMatrixWorld(!0);const d=new qe;n.root.getWorldQuaternion(d);const f=d.clone().invert(),p=tv(n,f);for(const y of e)y.chains.forEach((g,v)=>{const b=g.kind==="cloth",k=(b?.085:.05)*(1+.8*u),w=b?.012:.008,S=new ae(-r[0]*k-l[0]*w,-r[1]*k*.6-l[1]*w,-r[2]*k-l[2]*w),E=Math.min(1,m/3)*(b?.12:.06);g.bones.forEach((j,M)=>{const T=j.parent;T.updateWorldMatrix(!0,!1),T.getWorldQuaternion(uh).premultiply(f);let N=j;for(let O=0;O<=M;O++)N=N.parent;N.getWorldQuaternion(Ha).premultiply(f),yo.copy(g.rest[M]).normalize();const R=g.rest[M].length()*T.getWorldScale(hn).x*j.scale.x/n.root.getWorldScale(as).x;en.copy(yo).applyQuaternion(Ha);const A=g.stiffness*(M===0?1.4:1);if(en.multiplyScalar(A).add(Ps.set(0,-(1-Math.min(.95,A)),0)).add(S),E){const O=h*(b?5.3:3.7)+v*1.7+M*.9;en.x+=Math.sin(O)*E,en.z+=Math.cos(O*.8)*E*.5}if(en.normalize(),Qy.copy(j.matrixWorld),ra(n,j.name,Pn),b&&y.anchor==="pelvis"){const O=g.bones[0].position,B=Math.atan2(O.x,O.z),D=Ca(.06,-.06,O.x),$=D*p.alongL(Pn)+(1-D)*p.alongR(Pn),W=(.6+.3*(M/g.bones.length))*(.3+.7*Ca(-.5,.4,Math.cos(B)))*(1-Ca(.82,1.02,$)),z=Ca(.85,1.05,$)*Ca(.2,.7,Math.cos(B));if(z>0)for(const Y of["L","R"]){const J=Y==="L"?D:1-D;J<=0||(ra(n,`foot${Y}`,Yo,[0,-.02,.24]),Hn.subVectors(Yo,Pn),Hn.lengthSq()>1e-8&&Hn.y<0&&en.lerp(Hn.normalize(),z*J).normalize())}W>0&&(Hn.copy(yo).applyQuaternion(Ha),Ps.copy(Hn).applyQuaternion(p.L).multiplyScalar(D),as.copy(Hn).applyQuaternion(p.R).multiplyScalar(1-D),Hn.copy(Ps).add(as).normalize(),en.lerp(Hn,W).normalize())}Wt.copy(Pn).addScaledVector(en,R);const C=b&&y.anchor==="pelvis";if(g.collide)for(let O=0;O<6;O++)na.copy(Pn).addScaledVector(en,R*.5),gr(na,i,b?.014:.008,C),en.subVectors(na,Pn).normalize(),Wt.copy(Pn).addScaledVector(en,R),gr(Wt,i,b?.014:.008,C),en.subVectors(Wt,Pn).normalize(),Wt.copy(Pn).addScaledVector(en,R);en.subVectors(Wt,Pn).normalize(),as.copy(en).applyQuaternion(uh.clone().invert()),mh.setFromUnitVectors(yo,as),j.quaternion.copy(mh),j.updateMatrixWorld(!0)})})}const sv=6.5,Na=new Map;function av(e){const n=Xn(e);let s=Na.get(n);if(!s){const i=Yr({...e,head:1,posture:0},Pr,{bind:!0});i.root.updateMatrixWorld(!0),s=[...i.bones.values()].map(l=>l.matrixWorld.clone().invert());const r=[...i.bones.keys()];s.names=r,Na.set(n,s),Na.size>64&&Na.delete(Na.keys().next().value)}const o=s.names;return new Map(o.map((i,r)=>[i,s[r]]))}function fu(e){const n=new Ve(e),s={h:0,s:0,l:0};return n.getHSL(s),s.h>=.01&&s.h<=.14&&s.s>=.15&&s.s<=.75&&s.l>=.12&&s.l<=.93}function ov(e,n,s){const o=mp(e),i=!e||!Object.keys(o).length,r=fu(n)?"#6d7a86":n;if(i){const l="#"+new Ve(r).multiplyScalar(.45).getHexString();return{hair:{style:s.fem>.5?"bob":"short",color:"#2a211b"},top:{type:"tshirt",color:r},bottom:{type:"trousers",color:l},shoes:{type:"sneakers",color:"#2a2a2c"}}}return Oy(o)||(o.top={type:"tank",color:"#e8e4dc"}),_y(o)||(o.bottom={type:"shorts",color:"#3a3f47"}),o}function iv(e,n){return e?.skin??(fu(n)?n:Rr[2])}const ko=(e,n)=>(e.name=n,e.castShadow=!0,e.receiveShadow=!0,e);function rv(e,n,s,o,i={}){const r=Vr();if(!r)throw new Error("HQ character asset not loaded");const l=iv(s,n),h=Oo({...s??{},skin:l},l),u=i.bare?{}:ov(o,n,h),m=u.shoes?.type==="heels",d=Yr(h,e,{heels:m}),f=av(h),p=(R,A)=>new $i(R.map(C=>d.bones.get(C)),R.map(C=>f.get(C).clone())),y=[],g=[],v=i.lod===void 0?[0,1]:[i.lod],b=new sg,k=v.map(()=>new dn);k.forEach((R,A)=>{R.name=`lod${v[A]}`,b.addLevel(R,A===0?0:sv),A&&(R.visible=!1)}),b.name="hqLod",d.root.add(b);const w=(R,A,C,O,B=d.root,D=!0)=>{const $=new zr(R,A);return $.bind(O,new Nt),ko($,C),jy($),$.userData.grounds=D,y.push($),B.add($),$},S=p(hd),E=u.hat?null:u.hair?.style,j={skin:l,buzz:E==="buzz"?u.hair.color:null,stubble:u.beard?.type==="beard"?u.beard.color:null},M=hv(l);for(const R of["L","R"])d.bones.get(`eye${R}`).add(ko(new dt(my(M),yy()),"eyes"));const T=[];for(const R of $y(r,d,u,h)){const A=new $i(R.bones.map(O=>d.bones.get(O)),R.bones.map(O=>(R.inverses.get(O)??f.get(O)).clone())),C=R.near&&v[0]===0&&v.length>1?k[0]:d.root;w(R.geometry,R.material,R.slot,A,C,!1),R.chains&&T.push(R.chains)}v.forEach((R,A)=>{const C=Yy(r,d,h,u,R,{fittedOnly:A>0}),O=w(hy(r,h,R,j),gy(l),"skin",S,k[A],A===0);C.hide&&(O.geometry=cv(O.geometry,C.hide,C.hideKey));for(const B of C.parts){if(B.skinned){const D=B.bones?new $i(B.bones.map(W=>d.bones.get(W)),B.bones.map(W=>(B.inverses?.get(W)??f.get(W)).clone())):S,$=w(B.geometry,B.material,B.slot,D,B.bones?d.root:k[A],A===0);if(B.drape){const W=new At,z=B.geometry.getAttribute("position").count;W.setAttribute("position",new Rt(new Float32Array(z*3),3)),W.setIndex(B.geometry.getIndex());const Y=ko(new dt(W,B.material),B.slot);Y.userData.drape=!0,$.visible=!1,$.userData.grounds=!1,d.root.add(Y),g.push({src:$,mesh:Y})}}else{const D=ko(new dt(B.geometry,B.material),B.slot);(d.bones.get(B.bone)??d.root).add(D)}B.chains&&T.push(B.chains)}});const N={rig:d,b:h,look:u,meshes:y,chains:T,heels:m,drapes:g,legs:Gy(r,h)};return d.root.userData.hq={repose:(R,A)=>yh(N,R,A??null),built:N,torso:lv(r,h,u)},d.root.userData.hqLook=u,yh(N,e,i.motion??null,!0),d.root}function yh(e,n,s,o=!1){const{rig:i,b:r}=e;o||qo(i,r,n,{heels:e.heels});const l=cd(n);for(const u of e.meshes)u.morphTargetInfluences&&Ir.forEach((m,d)=>{u.morphTargetInfluences[d]=l[m]});i.body.position.y=1,i.root.updateMatrixWorld(!0),nv(e.chains,i,n,s);let h=1/0;for(const u of e.meshes)u.userData.grounds!==!1&&ia(u,(m,d)=>{d<h&&(h=d)},i.root);i.body.position.y=1-(Number.isFinite(h)?h:0),i.root.updateMatrixWorld(!0);for(const u of e.meshes)u.boundingBox=null,u.boundingSphere=null;for(const u of e.drapes){const m=u.mesh.geometry.getAttribute("position"),d=m.array;ia(u.src,(f,p,y,g)=>{d[g*3]=f,d[g*3+1]=p,d[g*3+2]=y},i.root,!0),Jy(i,d,e.legs,u.src.geometry.userData.rings),m.needsUpdate=!0,u.mesh.geometry.computeVertexNormals(),u.mesh.geometry.computeBoundingSphere(),u.mesh.geometry.computeBoundingBox()}}const wo=new Map;function lv(e,n,s){const o=(s.top?.012:0)+(s.outer?.016:0),i=`${Xn(n)}|${o}`;let r=wo.get(i);if(r)return r;const l=e.lods.length-1,h=e.lods[l],u=Ms(e,n,l).getAttribute("position"),m=new Set(["torso","pelvis"].map(v=>e.bones.indexOf(v)));let d=0,f=1/0,p=-1/0;const y=.02,g=.3;for(let v=0;v<h.vertices;v++){if(!m.has(h.skinIndex[v*4]))continue;const b=u.getY(v)-1;b<y||b>g||(d=Math.max(d,Math.abs(u.getX(v))),f=Math.min(f,u.getZ(v)),p=Math.max(p,u.getZ(v)))}return r=Number.isFinite(f)?{rx:d+o,rz:(p-f)/2+o,cz:(f+p)/2,y0:y,y1:g}:{rx:.16,rz:.12,cz:0,y0:y,y1:g},wo.size>64&&wo.clear(),wo.set(i,r),r}const Mo=new Map;function cv(e,n,s){const o=`${e.uuid}|${s}`;let i=Mo.get(o);if(i)return i;Mo.size>64&&Mo.clear();const r=e.getIndex(),l=[];for(let h=0;h<r.count;h+=3){const u=r.getX(h),m=r.getX(h+1),d=r.getX(h+2);n[u]&&n[m]&&n[d]||l.push(u,m,d)}i=new At;for(const h of Object.keys(e.attributes))i.setAttribute(h,e.getAttribute(h));return i.morphAttributes=e.morphAttributes,i.morphTargetsRelative=e.morphTargetsRelative,i.setIndex(l),i.userData={...e.userData,samples:void 0},i.userData.shared=!0,i.dispose=()=>{},Mo.set(o,i),i}function hv(e){const n=new Ve(e).getHSL({h:0,s:0,l:0}).l;return n>.78?"#4a6a8a":n>.62?"#5a3f2a":"#3a2618"}const yr="shot-hq-characters";function Jr(){try{return globalThis.localStorage?.getItem(yr)!=="off"}catch{return!0}}function dv(e){try{e?globalThis.localStorage?.removeItem(yr):globalThis.localStorage?.setItem(yr,"off")}catch{}for(const n of[...vr])n()}const vr=new Set;function gu(e){return vr.add(e),()=>{vr.delete(e)}}const uv=()=>Jr()&&!!Vr();Fr.active=uv;Fr.build=rv;Fr.samples=ia;is.hq={enabled:Jr,ready:()=>!!Vr(),load:()=>sy(),onSetting:gu,onAsset:ou};ou(zd);gu(zd);const xu=["Thumb","Index","Middle","Ring","Pinky"],bu={l:"Left",r:"Right",left:"Left",right:"Right"};function mv(e){const n=String(e||"");let s=/^mixamorig\d*[_:]?([A-Za-z]+\d?)$/.exec(n);return s?jr.has(s[1])?s[1]:null:(s=/^Bip\d+[ _](.+)$/i.exec(n),s?pv(s[1].split(/[ _]+/)):(s=/^J_Bip_([CLR])_(\w+)$/i.exec(n),s?fv(s[1].toUpperCase(),s[2]):(s=/^(pelvis|spine_0[1-5]|neck_01|head|clavicle|upperarm|lowerarm|hand|thigh|calf|foot|ball|(thumb|index|middle|ring|pinky)_0([1-3]))(?:_([lr]))?$/i.exec(n),s?gv(s[1].toLowerCase(),s[4]?.toLowerCase()):(s=/^DEF-(shoulder|upper_arm|forearm|hand|thigh|shin|foot|toe|thumb[._]?0([1-3])|f_(index|middle|ring|pinky)[._]?0([1-3]))[._]?([LR])$/.exec(n),s?xv(s):jr.has(n)?n:null))))}function pv(e){const[n,s]=e,o={Pelvis:"Hips",Spine:"Spine",Spine1:"Spine1",Spine2:"Spine2",Neck:"Neck",Head:"Head"};if(e.length===1)return o[n]??null;const i=bu[String(n).toLowerCase()];if(!i||e.length!==2)return null;const r={Clavicle:"Shoulder",UpperArm:"Arm",Forearm:"ForeArm",Hand:"Hand",Thigh:"UpLeg",Calf:"Leg",Foot:"Foot",Toe0:"ToeBase"}[s];if(r)return i+r;const l=/^Finger([0-4])([12])?$/.exec(s);return l?`${i}Hand${xu[+l[1]]}${l[2]?+l[2]+1:1}`:null}function fv(e,n){if(e==="C")return{Hips:"Hips",Spine:"Spine",Chest:"Spine1",UpperChest:"Spine2",Neck:"Neck",Head:"Head"}[n]??null;const s=e==="L"?"Left":"Right",o={Shoulder:"Shoulder",UpperArm:"Arm",LowerArm:"ForeArm",Hand:"Hand",UpperLeg:"UpLeg",LowerLeg:"Leg",Foot:"Foot",ToeBase:"ToeBase"}[n];if(o)return s+o;const i=/^(Thumb|Index|Middle|Ring|Little)([1-3])$/.exec(n);return i?`${s}Hand${i[1]==="Little"?"Pinky":i[1]}${i[2]}`:null}function gv(e,n){const s={pelvis:"Hips",spine_01:"Spine",spine_02:"Spine1",spine_03:"Spine2",neck_01:"Neck",head:"Head"};if(s[e])return n?null:s[e];if(/^spine_0[45]$/.test(e))return null;const o=n?bu[n]:null;if(!o)return null;const i={clavicle:"Shoulder",upperarm:"Arm",lowerarm:"ForeArm",hand:"Hand",thigh:"UpLeg",calf:"Leg",foot:"Foot",ball:"ToeBase"}[e];if(i)return o+i;const r=/^(thumb|index|middle|ring|pinky)_0([1-3])$/.exec(e);return r?`${o}Hand${r[1][0].toUpperCase()}${r[1].slice(1)}${r[2]}`:null}function xv(e){const n=e[5]==="L"?"Left":"Right";return e[2]?`${n}HandThumb${e[2]}`:e[3]?`${n}Hand${e[3][0].toUpperCase()}${e[3].slice(1)}${e[4]}`:n+{shoulder:"Shoulder",upper_arm:"Arm",forearm:"ForeArm",hand:"Hand",thigh:"UpLeg",shin:"Leg",foot:"Foot",toe:"ToeBase"}[e[1]]}function bv(e){const n=new Map;for(const i of e){const r=/^DEF-spine(?:[._]?0*(\d+))?$/.exec(i);r&&n.set(r[1]?+r[1]:0,i)}if(!n.has(0))return[];const s=Math.max(...n.keys()),o=[[n.get(0),"Hips"]];for(const[i,r]of[[1,"Spine"],[2,"Spine1"],[3,"Spine2"]])n.has(i)&&i<s&&o.push([n.get(i),r]);return s>=5&&n.has(4)&&o.push([n.get(4),"Neck"]),s>=4&&o.push([n.get(s),"Head"]),o}const el=["Hips","Spine","Spine2","Neck","Head"];for(const e of["Left","Right"])el.push(...["Shoulder","Arm","ForeArm","Hand","UpLeg","Leg","Foot"].map(n=>e+n));const yv=Object.freeze(el.slice()),jr=new Set([...el,"Spine1","LeftToeBase","RightToeBase",...["Left","Right"].flatMap(e=>xu.flatMap(n=>[1,2,3].map(s=>`${e}Hand${n}${s}`)))]);function vv(e){const n=new Map,s=new Set;let o=0;for(const[r,l]of bv(e||[]))n.set(r,l),s.add(l);for(const r of e||[]){if(n.has(r))continue;const l=mv(r);!l||s.has(l)||(n.set(r,l),s.add(l),(/^mixamorig/.test(r)||jr.has(r))&&o++)}if(!s.has("Spine2")&&s.has("Spine1"))for(const[r,l]of n)l==="Spine1"&&(n.set(r,"Spine2"),s.delete("Spine1"),s.add("Spine2"));const i=yv.filter(r=>!s.has(r));return{ok:i.length===0,exact:i.length===0&&o===n.size,rename:n,missing:i,bones:n.size}}const jv={fingers:.85,palm:.2,across:.07},vh={x:"shot/bot/xbot.glb",y:"shot/bot/ybot.glb"},la={};let Aa=null;const kr=new Set,kv=()=>!!la.x&&!!la.y;function wv(e){return kr.add(e),()=>{kr.delete(e)}}function Mv(e){if(Aa)return Aa;const n="/";return Aa=(async()=>{const{createGltfLoader:s}=await nn(async()=>{const{createGltfLoader:l}=await import("./gltfLoader-U0Eebg7v.js").then(h=>h.g);return{createGltfLoader:l}},__vite__mapDeps([7,6])),o=s(),[i,r]=await Promise.all([o.loadAsync(`${n}${vh.x}`),o.loadAsync(`${n}${vh.y}`)]);la.x=jh(r.scene),la.y=jh(i.scene);for(const l of[...kr])l()})().catch(s=>{throw Aa=null,s}),Aa}function jh(e){e.updateMatrixWorld(!0);const n=new _t().setFromObject(e),s=e.getObjectByName("mixamorigHips"),o=new ae;return s?.getWorldPosition(o),{scene:e,height:n.max.y-n.min.y,hipsY:o.y-n.min.y}}const Sv=[["head","Head"],["arm","Arm"],["fore","ForeArm"],["wrist","Hand"],["thigh","UpLeg"],["shin","Leg"],["foot","Foot"]],Cv={thumb:"HandThumb",index:"HandIndex",middle:"HandMiddle",ring:"HandRing",pinky:"HandPinky"},Qo=[["Hips",1-ld,.3],["Spine",.73,.55],["Spine1",.87,.8],["Spine2",1,1]],Nv=.45,Av=24,So=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Tv=/hair|bang|fringe|pony|braid|plait|ahoge|tress|bun|tail|ribbon|tassel|earring|hat|ear_?ring/i,Lv=/skirt|hem|coat|cape|cloak|robe|ribbon|tassel|sash|apron|scarf|cloth|flap|necktie|belt|frill|veil|mantle/i,Ev=/twist|eye|tooth|teeth|tongue|jaw|mouth|lip|brow|lid|cheek|nose|mask|weapon|sword|gun|ik|pole|target|end$|_end|helper/i,Rv=e=>new Ve(e).lerp(new Ve("#d8dbe0"),.55),Iv=e=>new Ve(e).offsetHSL(0,.05,-.12);function Pv(e,n,s,o="x"){const i=la[o]??la.x;if(!i)throw new Error("bot asset not loaded");return ju(Rd(i.scene),i.height,e,n,s,!1)}function yu(e){const n=[],s=new Set;let o=!1;e.traverse(r=>{r.isSkinnedMesh&&(o=!0),r.isBone&&!s.has(r.name)&&(s.add(r.name),n.push(r.name))});const i=vv(n);return{...i,ok:i.ok&&o,skinned:o,total:n.length}}function Fv(e,n,s,o){const i=yu(e);if(!i.ok)throw new Error(i.skinned?`bộ xương thiếu: ${i.missing.join(", ")}`:"model không có lưới gắn xương");const r=new Set;e.traverse(v=>r.add(v)),e.traverse(v=>{if(v.isSkinnedMesh){for(const b of v.skeleton.bones)if(b&&!r.has(b)){let k=b;for(;k.parent;)k=k.parent;r.has(k)||(e.add(k),k.traverse(w=>r.add(w)))}}});const l=new dn,h=Rd(e);l.add(h);const u=new Set;h.traverse(v=>{const b=v.isBone?i.rename.get(v.name):void 0;b&&!u.has(v)&&(v.name=`mixamorig${b}`,u.add(v))}),h.traverse(v=>{v.isBone&&!u.has(v)&&/^mixamorig/.test(v.name)&&(v.name=`x_${v.name}`)}),l.updateMatrixWorld(!0);const m=v=>l.getObjectByName(`mixamorig${v}`)?.getWorldPosition(new ae);let d=0;for(const v of["Left","Right"]){const b=m(`${v}Foot`),k=m(`${v}ToeBase`);b&&k&&(d+=k.z-b.z)}d<0&&(h.rotation.y=Math.PI),l.updateMatrixWorld(!0);const f=l.getObjectByName("mixamorigHips");if(f){const v=new Set;for(let k=f.parent;k;k=k.parent)v.add(k);const b=[];l.traverse(k=>{if(!k.isBone||k===f||v.has(k))return;let w=k.parent;for(;w&&w!==f&&!v.has(w);)w=w.parent;w!==f&&k.parent&&v.has(k.parent)&&b.push(k)});for(const k of b)f.attach(k);l.updateMatrixWorld(!0)}const p=new _t().setFromObject(l),y=Math.max(.001,p.max.y-p.min.y);h.position.y-=p.min.y;const g=ju(l,y,n,s,{height:o},!0);return g.userData.botExact=i.exact,g.userData.nativeBones=i.bones,g}const vu=e=>{const n=Qo[0][1],s=Qo.find(([o])=>o===e)?.[1]??0;return e==="Hips"?0:Math.max(0,(s-n)/(1-n))},$v=12;function Dv(e,n){const s=n.get("mixamorigHips"),o=n.get("mixamorigNeck"),i=Qo.map(([b])=>({bone:n.get(`mixamorig${b}`),share:vu(b)})).filter(b=>!!b.bone),r=n.get("mixamorigSpine2");if(!s||!o||!r||i.length<2)return{deg:0,chest:null};e.updateMatrixWorld(!0);const l=b=>b.getWorldPosition(new ae).z,h=i.map(b=>b.bone.quaternion.clone()),u=new ae(1,0,0),m=new qe,d=new qe,f=new qe,p=b=>{i.forEach((w,S)=>{w.bone.quaternion.copy(h[S])}),e.updateMatrixWorld(!0);const k=i.map(w=>w.bone.getWorldQuaternion(new qe));i.forEach((w,S)=>{w.bone.parent.updateWorldMatrix(!0,!1),w.bone.parent.getWorldQuaternion(m),f.setFromAxisAngle(u,gn.degToRad(b*w.share)),d.copy(f).multiply(k[S]),w.bone.quaternion.copy(m.invert().multiply(d)),w.bone.updateMatrixWorld(!0)})},y=o.getWorldPosition(new ae).sub(s.getWorldPosition(new ae)).length();let g=0;for(let b=0;b<6;b++){p(g);const k=l(s)-l(o);if(Math.abs(k)<.001)break;g=Math.min($v,Math.max(0,g+gn.radToDeg(Math.atan2(k,y))))}g<1&&(g=0),p(g);const v=r.getWorldPosition(new ae);return i.forEach((b,k)=>b.bone.quaternion.copy(h[k])),e.updateMatrixWorld(!0),{deg:Math.round(g*10)/10,chest:g?v:null}}function ju(e,n,s,o,i,r){const l=Ht(i),h=Oo({...i??{}},o),u=new dn;u.name="bot";const m=Yr(h,{},{bind:!0});m.root.name="driver",m.root.traverse(oe=>{oe.visible=!0}),u.add(m.root),m.root.updateMatrixWorld(!0),e.name="skin";const d=l.height/n;e.scale.setScalar(d),u.add(e),e.updateMatrixWorld(!0),e.traverse(oe=>{if(!(oe instanceof dt)||(oe.castShadow=!0,oe.receiveShadow=!0,oe.frustumCulled=!1,r))return;const Se=/joint/i.test(oe.name);oe.material=new os({color:Se?Iv(o):Rv(o),roughness:Se?.5:.42,metalness:Se?.15:.08})});const f=new Map;e.traverse(oe=>{oe.isBone&&!f.has(oe.name)&&f.set(oe.name,oe)});const p=f.get("mixamorigHips"),y=Dv(e,f);u.userData.uprightDeg=y.deg;const g={};for(const[oe,Se]of f)oe.startsWith("mixamorig")&&(g[oe.slice(9)]={q:Se.getWorldQuaternion(new qe).toArray(),p:Se.getWorldPosition(new ae).toArray()});u.userData.botRest=g;const v=[],b=[],k=new ae,w=new ae,S=new qe,E=oe=>oe.getWorldQuaternion(new qe),j=(oe,Se)=>{oe.getWorldPosition(k);let $e=null,Re=1e-6;for(const He of oe.children){He.getWorldPosition(w);const Ze=w.clone().sub(k);Ze.lengthSq()>Re&&(Re=Ze.lengthSq(),$e=Ze)}return $e?$e.normalize():Se.clone()},M=oe=>Math.sign(oe.getWorldPosition(new ae).x||0),T=(oe,Se,$e,Re=!1)=>{const He=m.bones.get(oe);if(!He){b.push(`driver ${oe}`);return}const Ze=M(He),Ye=[...f.values()].filter(it=>it.name===`mixamorig${Se}`||it.name===`mixamorigLeft${Se}`||it.name===`mixamorigRight${Se}`),Ge=Ye.length===1?Ye[0]:Ye.find(it=>Math.sign(it.getWorldPosition(new ae).x||0)===Ze);if(!Ge){b.push(`bone ${Se} for ${oe} (${Ye.length} cands, want ${Ze})`);return}const Qe=Re?$e:j(Ge,$e),at=Re?$e:j(He,$e),mt=new qe().setFromUnitVectors(Qe,at);v.push({bone:Ge,driver:He,cal:mt,restInv:E(He).invert(),mRest:E(Ge)})},N=new ae(0,1,0),R=new ae(0,-1,0),A=new ae(0,0,1);T("torso","Spine2",N,!0);for(const[oe,Se]of Sv){if(oe==="head"){T("head",Se,N,!0);continue}const $e=oe==="thigh"||oe==="shin"||oe==="foot";for(const Re of["L","R"])T(`${oe}${Re}`,Se,oe==="foot"?A:R,$e)}for(const oe of["L","R"]){const Se=v.find(Re=>Re.driver.name===`wrist${oe}`),$e=v.find(Re=>Re.driver.name===`fore${oe}`);Se&&$e&&Se.cal.copy($e.cal)}for(const oe of["L","R"])for(const[Se,$e]of Object.entries(Cv))for(let Re=1;Re<=3;Re++)T(`${Se}${Re}${oe}`,`${$e}${Re}`,R);const C=oe=>f.get(`mixamorig${oe}`),O=m.bones.get("torso"),B=m.bones.get("head"),D=E(O),$=D.clone().invert(),W=E(B).invert(),z=C("Spine2"),Y=(y.chest??z.getWorldPosition(new ae)).clone().applyMatrix4(O.matrixWorld.clone().invert()),J=Qo.filter(([oe])=>C(oe)).map(([oe,Se,$e])=>({bone:C(oe),lean:Se,twist:$e,up:vu(oe),mRest:E(C(oe)),pos:C(oe).position.clone()})),V=C("Neck"),H=E(V),G=["Left","Right"].map(oe=>{const Se=f.get(`mixamorig${oe}Shoulder`),$e=f.get(`mixamorig${oe}Arm`),Re=Math.sign(Se.getWorldPosition(new ae).x||0),He=["L","R"].map(Ze=>({S:Ze,a:m.bones.get(`arm${Ze}`),f:m.bones.get(`fore${Ze}`)})).find(Ze=>Math.sign(Ze.a.getWorldPosition(new ae).x||0)===Re);return{bone:Se,arm:$e,sx:Re,drv:He,mRest:E(Se),armPos:$e.position.clone(),follow:new qe}}).filter(oe=>oe.bone&&oe.arm&&oe.drv),_=kh(m),ee=p.getWorldPosition(new ae),Q=p.position.clone(),ve=new Map;for(const oe of f.values())ve.set(oe,oe.parent);const ye=new Map;for(const oe of v)ye.set(oe.bone,oe);const q=[];p.traverse(oe=>{oe.isBone&&q.push(oe)});const pe=[];if(r){const oe=new Set([...f.values()].filter(He=>/^mixamorig/.test(He.name))),Se=f.get("mixamorigHead"),$e=f.get("mixamorigNeck"),Re=new Map;for(const He of q){if(oe.has(He)||Ev.test(He.name))continue;const Ze=He.children.find(it=>it.isBone);if(!Ze||Ze.position.lengthSq()<1e-10)continue;let Ye=He.parent,Ge=!1;for(;Ye&&!oe.has(Ye);)Ye=Ye.parent;(Ye===Se||Ye===$e)&&(Ge=!0);const Qe=Re.get(He.parent);if(!(Ge?Tv.test(He.name)||Qe!==void 0:Lv.test(He.name)||Qe!==void 0))continue;const mt=Qe===void 0?0:Qe+1;Re.set(He,mt),pe.push({bone:He,rest:He.quaternion.clone(),tip:Ze.position.clone(),hair:Ge,depth:mt})}}const ue={pos:new ae,time:-1},U=new ae,re=new ae,ce=new qe,Ee=new qe,je=new qe,le=new qe,Le=new ae,Ae=new ae,we=new ae,he=new ae;function ke(oe){if(!pe.length)return;for(const Ge of pe)Ge.bone.quaternion.copy(Ge.rest);e.updateMatrixWorld(!0);const Se=f.get("mixamorigHead"),$e=oe?.time??-1;Se?.getWorldPosition(we),re.set(0,0,0),Se&&$e>=0&&ue.time>=0&&$e>ue.time&&$e-ue.time<.2&&re.subVectors(we,ue.pos).divideScalar($e-ue.time),ue.pos.copy(we),ue.time=$e,u.getWorldQuaternion(ce);const Re=oe?.vel??[0,0,0],He=oe?.acc??[0,0,0],Ze=oe?.air??0,Ye=Math.hypot(Re[0],Re[1],Re[2]);for(const Ge of pe){const Qe=(Ge.hair?.07:.1)*(1+.6*Ze),at=Ge.hair?.012:.016,mt=Ge.hair?.09:.05;U.set(-Re[0]*Qe-He[0]*at,-Re[1]*Qe*.6-He[1]*at,-Re[2]*Qe-He[2]*at).applyQuaternion(ce).addScaledVector(re,-mt),U.length()>1.6&&U.setLength(1.6);const it=Ge.bone,Bt=it.parent;Bt.updateWorldMatrix(!0,!1),it.updateWorldMatrix(!1,!1),it.getWorldPosition(we),he.copy(Ge.tip).applyMatrix4(it.matrixWorld),Le.subVectors(he,we);const De=Le.length();if(De<1e-6)continue;Le.divideScalar(De);const Pt=.55+.25*Math.min(3,Ge.depth),Tt=Math.min(1,Ye/3)*(Ge.hair?.07:.12),on=Math.max(0,$e)*(Ge.hair?3.7:5.3)+Ge.depth*.9+it.id*.37;Ae.copy(Le).add(he.set(0,Ge.hair?-.22:-.3,0)).addScaledVector(U,Pt),Tt&&(Ae.x+=Math.sin(on)*Tt,Ae.z+=Math.cos(on*.8)*Tt*.5),Ae.normalize();const fn=u.getWorldPosition(he).y+.02;if(we.y+Ae.y*De<fn){Ae.y=Math.min(1,(fn-we.y)/De);const Kt=Math.hypot(Ae.x,Ae.z),kn=Math.sqrt(Math.max(0,1-Ae.y*Ae.y));Kt>1e-6?(Ae.x*=kn/Kt,Ae.z*=kn/Kt):Ae.x=kn,Ae.normalize()}const Et=Ge.depth===0?.96:.35,Ln=Le.angleTo(Ae);Ln>Et&&Ae.lerp(Le,1-Et/Ln).normalize(),Ee.setFromUnitVectors(Le,Ae),Bt.getWorldQuaternion(je),it.getWorldQuaternion(le),it.quaternion.copy(je.invert().multiply(Ee).multiply(le)),it.updateMatrixWorld(!0)}}const Pe=new Map,Te=new qe,Be=new qe,ze=new qe,Ke=[];e.traverse(oe=>{oe.isSkinnedMesh&&Ke.push(oe)});let Je=0;const P=()=>{e.updateMatrixWorld(!0);let oe=1/0;for(const Se of Ke)ia(Se,($e,Re)=>{Re<oe&&(oe=Re)},u);Number.isFinite(oe)&&(Je-=oe,m.body.position.y=1+Je)};let te=s;const Z=[];function ie(oe,Se,$e){te=oe;for(const Re of pe)Re.bone.quaternion.copy(Re.rest);qo(m,h,oe),m.body.position.y=1+Je,m.root.updateMatrixWorld(!0),bt(),P(),bt();for(const Re of Z)Re.userData.active=!!(Se&&Se.w>0);Se&&Se.w>0&&ct(Se),ke($e)}const me=new qe,Fe=new qe,be=new qe,lt=new qe,wt=new ae,Zt=new qe;function Xe(oe,Se,$e,Re,He){const Ze=Math.max(0,Math.min(oe.n-1,$e*oe.rate)),Ye=Math.floor(Ze),Ge=Math.min(oe.n-1,Ye+1),Qe=Ze-Ye,at=oe.bones.length,mt=(Ye*at+Se)*4,it=(Ge*at+Se)*4;return me.set(oe.q[mt],oe.q[mt+1],oe.q[mt+2],oe.q[mt+3]),Fe.set(oe.q[it],oe.q[it+1],oe.q[it+2],oe.q[it+3]),He.copy(me).slerp(Fe,Qe).normalize(),Re&&(wt.set(0,0,1).applyQuaternion(He),lt.setFromAxisAngle(N,-Math.atan2(wt.x,wt.z)),He.premultiply(lt)),He}function ct(oe){const Se=Yl(oe.id);if(!Se)return;const $e=Se.bones.length,Re=Math.min(1,oe.w),He=oe.from?Yl(oe.from.id):void 0,Ze=He?new Map(He.bones.map((Qe,at)=>[Qe,at])):null;for(let Qe=0;Qe<$e;Qe++){const at=f.get(Se.bones[Qe]);if(!at)continue;Xe(Se,Qe,oe.t,at===p,be);const mt=Ze?.get(Se.bones[Qe]);He&&mt!==void 0&&oe.from.k>0&&be.slerp(Xe(He,mt,oe.from.t,at===p,Zt),Math.min(1,oe.from.k)).normalize(),Re>=1?at.quaternion.copy(be):at.quaternion.slerp(be,Re)}e.updateMatrixWorld(!0);let Ye=1/0;for(const Qe of Ke)ia(Qe,(at,mt)=>{mt<Ye&&(Ye=mt)},u);const Ge=oe.po;if(Number.isFinite(Ye)&&Math.abs(Ye)>1e-4||Ge){const Qe=p.getWorldPosition(new ae);Number.isFinite(Ye)&&(Qe.y-=Ye*u.getWorldScale(new ae).y),Ge&&(Qe.x-=Ge[0]*Re,Qe.z-=Ge[1]*Re),p.position.copy(p.parent.worldToLocal(Qe)),e.updateMatrixWorld(!0)}}function bt(){m.root.updateMatrixWorld(!0);const oe=kh(m),Se=ee.clone().add(oe.sub(_));p.parent.updateWorldMatrix(!0,!1),p.position.copy(p.parent.worldToLocal(Se)),Q.y=Q.y,Pe.clear();const $e=an(te);for(const Re of J.slice(1))Re.bone.position.copy(Re.pos);for(const Re of q){const He=ve.get(Re);Pe.has(He)?Te.copy(Pe.get(He)):He.getWorldQuaternion(Te);const Ze=ye.get(Re),Ye=$e.get(Re);Ye?(ze.copy(Te).invert(),Re.quaternion.copy(ze).multiply(Ye)):Ze&&(Ze.driver.getWorldQuaternion(S),Be.copy(S).multiply(Ze.restInv).multiply(Ze.cal).multiply(Ze.mRest),ze.copy(Te).invert(),Re.quaternion.copy(ze).multiply(Be)),Pe.set(Re,Te.clone().multiply(Re.quaternion))}e.updateMatrixWorld(!0),vn()}const Mt=new qe,gt=new qe,st=new qe,sn=new qe,Ie=new qe,ot=new qe,Jt=new ae(1,0,0),ut=new ae(0,1,0),Lt=new ae(0,0,1),Gt=new qe,un=Xa(h);function an(oe){const Se=new Map,$e=gn.degToRad,Re=So(oe.lean),He=So(oe.spineTwist),Ze=So(oe.sideBend),Ye=So(oe.tumble)+un.torsoLean;O.parent.getWorldQuaternion(Gt);const Ge=(De,Pt)=>Gt.clone().multiply(Mt.setFromAxisAngle(Jt,$e(Ye+De*Re))).multiply(gt.setFromAxisAngle(ut,$e(Pt*He))).multiply(st.setFromAxisAngle(Lt,$e(De*Ze))).multiply($),Qe=De=>sn.setFromAxisAngle(Jt,$e(De*y.deg));for(const De of J)(De.lean<1||De.twist<1||y.deg)&&Se.set(De.bone,Ge(De.lean,De.twist).multiply(Qe(De.up)).multiply(De.mRest));const at=O.getWorldQuaternion(Ie).multiply($).clone(),mt=B.getWorldQuaternion(ot).multiply(W).clone();Se.set(V,at.clone().slerp(mt,Nv).multiply(H));const it=new ae(0,-1,0).applyQuaternion(at),Bt=new ae(0,0,1).applyQuaternion(at);for(const De of G){const Pt=De.drv.f.getWorldPosition(new ae).sub(De.drv.a.getWorldPosition(new ae)).normalize(),Tt=gn.radToDeg(Pt.angleTo(it)),on=gn.clamp((Tt-80)/90,0,1);De.follow.copy(at).multiply(De.mRest);const fn=new qe().setFromAxisAngle(Bt,$e(De.sx*Av*on*on*(3-2*on)));Se.set(De.bone,fn.multiply(De.follow))}return Se}const xt=new ae,mn=new ae,It=new Nt,qt=new ae,pn=new ae,Vn=new qe;function vn(){mn.copy(Y).applyMatrix4(O.matrixWorld);const oe=mn.sub(z.getWorldPosition(xt)).multiplyScalar(1/3);for(const Se of J.slice(1)){Se.bone.parent.updateWorldMatrix(!0,!1);const $e=Se.bone.getWorldPosition(new ae).add(oe);Se.bone.position.copy(Se.bone.parent.worldToLocal($e)),Se.bone.updateMatrixWorld(!0)}for(const Se of G){Se.bone.matrixWorld.decompose(qt,Vn,pn);const $e=Se.armPos.clone().applyMatrix4(It.compose(qt,Se.follow,pn));Se.arm.position.copy(Se.bone.worldToLocal($e)),Se.arm.updateMatrixWorld(!0)}}ie(s),u.updateMatrixWorld(!0);for(const oe of["L","R"]){const Se=v.find(kn=>kn.driver.name===`wrist${oe}`);if(!Se)continue;const $e=kn=>f.get(`${Se.bone.name}${kn}`)?.getWorldPosition(new ae),Re=Se.bone.getWorldPosition(new ae),He=$e("Index1"),Ze=$e("Middle1"),Ye=$e("Pinky1"),Ge=$e("Thumb1");if(!He||!Ze||!Ye||!Ge)continue;const Qe=He.clone().sub(Ye).normalize(),at=Ze.clone().sub(Re);at.addScaledVector(Qe,-at.dot(Qe)).normalize();let mt=new ae().crossVectors(at,Qe);mt.dot(Ge.clone().sub(Re))<0&&mt.negate();const it=new ae().setFromMatrixScale(Se.driver.matrixWorld),Bt=Ze.distanceTo(Re),De=jv,Pt=Re.clone().addScaledVector(at,De.fingers*Bt).addScaledVector(mt,De.palm*Bt).addScaledVector(Qe,De.across*Bt),Tt=Qe,on=at,fn=new ae().crossVectors(on,Tt).normalize(),Et=new Nt().makeBasis(fn,on,Tt).setPosition(Pt).scale(it),Ln=Se.bone.matrixWorld.clone().invert().multiply(Et),Kt=new ag;Kt.name=`rigHold${oe}`,Kt.userData.rigHold=oe,Kt.userData.active=!1,Z.push(Kt),Ln.decompose(Kt.position,Kt.quaternion,Kt.scale),Se.bone.add(Kt)}const jn=(oe,Se,$e,Re)=>{for(const _e of q){const ge=oe.get(_e.name);ge&&_e.quaternion.copy(ge)}Se&&p.position.copy(Se),e.rotation.y=0,e.updateMatrixWorld(!0);const He=p.getWorldPosition(new ae),Ze=(()=>{const _e=p.getWorldQuaternion(new qe),ge=new ae(0,0,1).applyQuaternion(_e);if(!Re?.steadyYaw)return Math.atan2(ge.x,ge.z);const Ut=new ae(1,0,0).applyQuaternion(_e);return Math.atan2(ge.x-Ut.z,ge.z+Ut.x)})();e.rotation.y=-Ze,e.updateMatrixWorld(!0),qo(m,h,{},{bind:!0}),m.root.updateMatrixWorld(!0);const Ye=new qe,Ge=new qe,Qe=new qe,at=new qe().setFromAxisAngle(new ae(1,0,0),gn.degToRad(-y.deg));for(const _e of v)_e.bone.getWorldQuaternion(Ye),_e.driver===O&&y.deg&&Ye.multiply(_e.mRest.clone().invert()).multiply(at).multiply(_e.mRest),Ge.copy(Ye).multiply(_e.mRest.clone().invert()).multiply(_e.cal.clone().invert()).multiply(_e.restInv.clone().invert()),_e.driver.parent.getWorldQuaternion(Qe),_e.driver.quaternion.copy(Qe.invert()).multiply(Ge),_e.driver.updateMatrixWorld(!0);const mt=Xa(h),it=gn.radToDeg,Bt=new cr,De={},Pt=_e=>((_e+180)%360+360)%360-180,Tt=(_e,ge,Ut=[])=>{const En=m.bones.get(_e);Bt.setFromQuaternion(En.quaternion,ge);const wn=[it(Bt.x),it(Bt.y),it(Bt.z)],Ne=Dt=>{const St=Ut[Dt];if(!(!$e||!St||$e[St[0]]===void 0))return $e[St[0]]*St[1]},rn=ge[1]==="X"?0:ge[1]==="Y"?1:2,_n=wn.map((Dt,St)=>Pt(St===rn?180-Dt:Dt+180)),Yn=Dt=>Dt.reduce((St,Ft,Qn)=>{const Me=Ne(Qn);return St+(Me===void 0?0:Math.abs(Pt(Ft-Me)))+.05*Math.abs(Ft)},0);let Xt=Yn(_n)<Yn(wn)?_n:wn;if($e&&Math.abs(Xt[rn])>70){const Dt=[0,1,2].filter(Ds=>Ds!==rn),[St,Ft]=Dt,Qn=(ge==="XYZ"?-1:1)*Math.sign(Xt[rn]),Me=Ne(St),ha=Ne(Ft);if(Me!==void 0&&ha!==void 0){const Ds=(Pt(Me-Xt[St])*Qn+Pt(ha-Xt[Ft]))/2,zn=[...Xt];zn[St]=Pt(Xt[St]+Qn*Ds),zn[Ft]=Pt(Xt[Ft]+Ds);const et=new cr(gn.degToRad(zn[0]),gn.degToRad(zn[1]),gn.degToRad(zn[2]),ge),eo=new qe().setFromEuler(et);2*Math.acos(Math.min(1,Math.abs(eo.dot(En.quaternion))))*57.3<4&&(Xt=zn)}}return Xt},[on,fn,Et]=Tt("torso","XYZ",[["lean",1],["spineTwist",1],["sideBend",1]]);De.lean=on-mt.torsoLean,De.spineTwist=fn,De.sideBend=Et;const[Ln,Kt,kn]=Tt("head","YXZ",[["headPitch",1],["head",1],["headRoll",1]]);De.headPitch=Ln-mt.headPitch,De.head=Kt,De.headRoll=kn;for(const _e of["L","R"]){const ge=_e==="L",Ut=ge?1:-1,[En,wn,Ne]=Tt(`arm${_e}`,"XZY",[[`shoulder${_e}`,1],[`armTwist${_e}`,ge?1:-1],[`shoulderOut${_e}`,ge?-1:1]]);De[`shoulder${_e}`]=En,De[`armTwist${_e}`]=ge?wn:-wn,De[`shoulderOut${_e}`]=ge?-Ne:Ne,De[`elbow${_e}`]=-Tt(`fore${_e}`,"XYZ")[0];const[rn,_n,Yn]=Tt(`wrist${_e}`,"YXZ",[[`wrist${_e}`,1],[`wristTwist${_e}`,-Ut],[`wristSide${_e}`,-Ut]]);De[`wrist${_e}`]=rn,De[`wristTwist${_e}`]=-_n*Ut,De[`wristSide${_e}`]=-Yn*Ut;const[Xt,Dt,St]=Tt(`thigh${_e}`,"XZY",[[`hip${_e}`,1],[`hipTwist${_e}`,ge?1:-1],[`hipOut${_e}`,ge?-1:1]]);De[`hip${_e}`]=Xt,De[`hipTwist${_e}`]=ge?Dt:-Dt,De[`hipOut${_e}`]=ge?-St:St,De[`knee${_e}`]=Tt(`shin${_e}`,"XYZ")[0],De[`ankle${_e}`]=Tt(`foot${_e}`,"XYZ")[0];const Ft=Qn=>Math.abs(Tt(`${Qn}2${_e}`,"XYZ")[2]);De[`grip${_e}`]=Math.max(0,Math.min(100,(Ft("index")+Ft("middle")+Ft("ring"))/3/100*100)),De[`thumb${_e}`]=Math.max(0,Math.min(100,Ft("thumb")/60*100))}return e.rotation.y=0,{pose:De,hips:He,yaw:it(Ze)}};return u.userData.bot={repose:ie,poseFrom:jn},u.userData.dynamicBones=pe.length,u.userData.botMisses=b,u.userData.botLinks=v.map(oe=>`${oe.driver.name}→${oe.bone.name.replace("mixamorig","")} cal ${Math.round(2*Math.acos(Math.min(1,Math.abs(oe.cal.w)))*57.3)}°`),u}function kh(e){const n=e.bones.get("thighL").getWorldPosition(new ae),s=e.bones.get("thighR").getWorldPosition(new ae);return n.add(s).multiplyScalar(.5)}is.bot={ready:kv,load:()=>Mv(),onAsset:wv,build:Pv,native:Fv,nativeOf:yu};function Ov(e,n,s={}){const o=n.items.find(h=>h.id===s.selected&&h.kind!=="fx"&&!h.hidden)??null,i=Math.max(0,+(s.start??0).toFixed(2)),r=_g(e,{items:n.items,selected:o,ground:s.ground??[0,0,0],reach:s.reach,anchor:s.anchor?(h,u)=>s.anchor(h.id,u,i):null}),l={...fp(e,s.seed??Math.floor(Math.random()*1e9)+1),start:i,...r.attach?{attach:r.attach}:{},...r.path?{path:r.path}:{},...r.target?{target:r.target}:{}};return{...An("fx",n.items.length),name:e.name,color:e.color,position:r.position,rotation:r.rotation,fx:l}}function _v(e,n,s){const o=n.fx,i=e.shots.find(u=>u.id===e.activeShot)??e.shots[0],r=Math.min(o.start,Math.max(0,i.duration-.2)),l=s?.fill?Math.max(Math.min(s.duration,3),i.duration-r):o.duration,h={start:+r.toFixed(2),duration:+Math.min(60,l).toFixed(2),...o.loop?{loop:!0}:{}};return{...e,items:[...e.items,{...n,fx:{...o,start:h.start,duration:h.duration}}],shots:e.shots.map(u=>u.id===i.id?{...u,fxTiming:{...u.fxTiming,[n.id]:h}}:u)}}function ku(e,n,s={}){const o=Ov(n,e,s),i=e.items.filter(u=>u.kind==="fx"&&u.fx?.preset===n.preset).length,r={...o,name:`${s.label??n.name} ${i+1}`},l=pp(e.items,r.fx);if(!l.ok)return{error:"limit",detail:l.errors.join("; ")};const h=_v(e,r,n);return{stage:h,item:h.items[h.items.length-1]}}let wr=0;const Mr=new Set;function wu(e=!1){return gp("fx",e).then(n=>{xp(n.filter(s=>s.kind==="fx"&&s.preset).map(s=>bp(s))),wr++,Mr.forEach(s=>s())},()=>{})}function zv(){const[e,n]=I.useState(wr);return I.useEffect(()=>{const s=()=>n(wr);return Mr.add(s),wu(),()=>{Mr.delete(s)}},[]),{entries:yp(),version:e}}const wh=new Map;function Mu(e){let n=wh.get(e.id);return n||(n=jp(e,24),wh.set(e.id,n)),n}const Su=(e,n)=>e[Math.max(0,Math.min(e.length-1,Math.round(n*24)))];function Bv(e){const n=e.keys.find(s=>s.strike);return n?n.t:e.duration/2}const Mh=(e,n)=>[e[0]-n[0],e[1]-n[1],e[2]-n[2]],qi=(e,n)=>[e[1]*n[2]-e[2]*n[1],e[2]*n[0]-e[0]*n[2],e[0]*n[1]-e[1]*n[0]],Ui=(e,n)=>e[0]*n[0]+e[1]*n[1]+e[2]*n[2],Sh=e=>{const n=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/n,e[1]/n,e[2]/n]};function Kv(e,n,s){const o=Sh(Mh(e.target,e.position)),i=Sh(qi(o,[0,1,0])),r=qi(i,o),l=Math.cos(e.roll*Math.PI/180),h=Math.sin(e.roll*Math.PI/180),u=[i[0]*l+r[0]*h,i[1]*l+r[1]*h,i[2]*l+r[2]*h],m=qi(u,o),d=e.lens/36*n;return f=>{const p=Mh(f,e.position),y=Ui(p,o);return y<.05?null:[n/2+Ui(p,u)/y*d,s/2-Ui(p,m)/y*d]}}const Hv=[["pelvis","chest"],["chest","neck"],["shoulderL","shoulderR"],["shoulderL","elbowL"],["elbowL","handL"],["shoulderR","elbowR"],["elbowR","handR"],["hipL","hipR"],["hipL","kneeL"],["kneeL","ankleL"],["ankleL","toeL"],["hipR","kneeR"],["kneeR","ankleR"],["ankleR","toeR"]],Ch={spear:{tip:1.42,blade:1.18,butt:.82},sword:{tip:.95,blade:.13,butt:.1},katana:{tip:.98,blade:.18,butt:.13},staff:{tip:1.1,blade:1.1,butt:.5}};function Cu(e,n,s,o="spear"){const i=Wg(e.pose),r=Math.cos(s*Math.PI/180),l=Math.sin(s*Math.PI/180),h=g=>[n[0]+g[0]*r+g[2]*l,n[1]+g[1],n[2]-g[0]*l+g[2]*r],u={};for(const g of Object.keys(i))g!=="lift"&&(u[g]=h(i[g]));const m=kp(e.pose),d=[0,1-i.lift,0],f=g=>h([d[0]+g[0],d[1]+g[1],d[2]+g[2]]),p=Ch[o]??Ch.spear,y=g=>f(m.front.map((v,b)=>v+m.dir[b]*g));return{pts:u,tip:y(p.tip),butt:y(-p.butt),blade:y(p.blade)}}function Nu(e,n,s,o,i,r=0){const l=Kv(o,n,s),h=e.createLinearGradient(0,0,0,s);h.addColorStop(0,"#1a2532"),h.addColorStop(1,"#0b1018"),e.fillStyle=h,e.fillRect(0,0,n,s),e.lineWidth=1,e.strokeStyle="rgba(140,170,200,.16)";const u=Math.round(i[0]?.pts.pelvis[0]??0),m=Math.round(i[0]?.pts.pelvis[2]??0);for(let d=-8;d<=8;d++)for(const[f,p]of[[[u+d,0,m-8],[u+d,0,m+8]],[[u-8,0,m+d],[u+8,0,m+d]]]){const y=l(f),g=l(p);!y||!g||(e.beginPath(),e.moveTo(y[0],y[1]),e.lineTo(g[0],g[1]),e.stroke())}for(const d of i){const f=(g,v,b,k)=>{const w=l(g),S=l(v);!w||!S||(e.strokeStyle=b,e.lineWidth=k,e.beginPath(),e.moveTo(w[0],w[1]),e.lineTo(S[0],S[1]),e.stroke())},p=(()=>{const g=l(d.pts.pelvis),v=l(d.pts.neck);return g&&v?Math.max(1,Math.hypot(g[0]-v[0],g[1]-v[1])/16):1})();e.lineCap="round";for(const[g,v]of Hv)f(d.pts[g],d.pts[v],"#dfe6ee",2.2*p);const y=l(d.pts.head);y&&(e.fillStyle="#dfe6ee",e.beginPath(),e.arc(y[0],y[1],3.6*p,0,Math.PI*2),e.fill()),f(d.butt,d.blade,"#c79a5a",1.6*p),f(d.blade,d.tip,"#a8ff3c",2.4*p)}r>0&&(e.fillStyle=`rgba(168,255,60,${.22*r})`,e.fillRect(0,0,n,s))}function Wv(e,n,s,o,i,r="spear"){const l=Mu(n),h=Su(l,s),u=[h.dx??0,h.dy??0,h.dz??0],m=h.turn??0,d=l[l.length-1].dz??0,f=[0,.85,d/2],p={position:[4.4,1.25,f[2]+1.4],target:f,lens:30,roll:0};Nu(e,o,i,p,[Cu(h,u,m,r)])}const Gv=["spear-thrust","spear-double-thrust","spear-spin"].map(e=>vp.find(n=>n.id===e)).filter(Boolean),sa=(()=>{let e=0,n=0;const s=Gv.map(i=>{const r=Mu(i),l={clip:i,s:r,at:e,z:n};return e+=i.duration,n+=r[r.length-1].dz??0,l}),o=s.flatMap(i=>i.clip.keys.filter(r=>r.strike).map(r=>i.at+r.t));return{parts:s,duration:e,beats:o}})(),qv=sa.duration;function Nh(e){const n=[...sa.parts].reverse().find(o=>e>=o.at)??sa.parts[0],s=Su(n.s,e-n.at);return{k:s,root:[s.dx??0,s.dy??0,n.z+(s.dz??0)],yaw:s.turn??0}}function Uv(e,n,s,o,i){const r={start:0,end:sa.duration,yaw:0,height:1.8,beats:sa.beats,centre:m=>{const d=Nh(m);return[d.root[0],0,d.root[2]]}},l=zg(n,s,r),h=Nh(s),u=sa.beats.reduce((m,d)=>Math.max(m,s>=d&&s-d<.12?1-(s-d)/.12:0),0);Nu(e,o,i,l,[Cu(h.k,h.root,h.yaw)],n.beats?u:0)}const Zo=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/đ/g,"d").toLowerCase();function Au({draw:e,rest:n,loop:s,hot:o}){const i=I.useRef(null);return I.useEffect(()=>{const r=i.current,l=r?.getContext("2d");if(!r||!l)return;if(!o){e(l,n,r.width,r.height);return}let h=0;const u=performance.now(),m=()=>{e(l,(performance.now()-u)/1e3%s,r.width,r.height),h=requestAnimationFrame(m)};return h=requestAnimationFrame(m),()=>cancelAnimationFrame(h)},[e,n,s,o]),t.jsx("canvas",{ref:i,width:192,height:108,"aria-hidden":"true"})}function Xv({stage:e,selected:n,playhead:s,change:o,setError:i,query:r}){const l=rt(),h=l==="en",[u,m]=I.useState(null),[d,f]=I.useState("all"),p=Zo(r.trim()),y=Bg.filter(b=>p?Zo(`${b.name} ${b.nameEn} ${b.desc??""} ${b.id}`).includes(p):d==="all"||b.cat===d),g=Kg(e,n),v=b=>{if(!g){i(a("Thêm một nhân vật hoặc vật thể vào cảnh để camera bám theo."));return}const k=Cc(e,{preset:b,subject:g.id,start:s});if(!k.ok){i(k.error.startsWith("not enough")?a("Không còn đủ thời lượng shot sau playhead cho chuyển động camera."):k.error);return}i(""),o(w=>{const S=Cc(w,{preset:b,subject:g.id,start:s});return S.ok?S.stage:w})};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-fx-cats shot-lib-subcats",role:"tablist","aria-label":a("Nhóm camera"),children:[{id:"all",name:"Tất cả",nameEn:"All"},...Hg].map(b=>t.jsx("button",{type:"button",role:"tab","aria-selected":d===b.id,className:d===b.id&&!p?"active":"",onClick:()=>f(b.id),children:h?b.nameEn:a(b.name)},b.id))}),t.jsx("p",{className:"shot-fx-hint",children:g?a("Camera bám theo “{0}” từ playhead đến hết shot. Chọn đối tượng khác trước để đổi chủ thể.",[g.name]):a("Thêm một nhân vật vào cảnh để camera bám theo.")}),t.jsxs("div",{className:"shot-fx-grid",children:[y.map(b=>t.jsxs("button",{type:"button",className:"shot-fx-card shot-lib-card","data-camera":b.id,title:h?b.descEn:b.desc,onMouseEnter:()=>m(b.id),onMouseLeave:()=>m(null),onFocus:()=>m(b.id),onBlur:()=>m(null),onClick:()=>v(b),children:[t.jsx(Au,{draw:(k,w,S,E)=>Uv(k,b,w,S,E),rest:1.2,loop:qv,hot:u===b.id}),t.jsx("span",{children:h?b.nameEn:b.name})]},b.id)),!y.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có camera nào khớp.")})]})]})}function Vv({stage:e,selected:n,onPlay:s,setError:o,query:i}){const r=rt(),l=r==="en",[h,u]=I.useState(null),[m,d]=I.useState("all"),f=Zo(i.trim()),p=wp.filter(({clip:b,pack:k})=>f?Zo(`${b.label} ${b.labelEn} ${b.id} ${k.label} ${k.labelEn} ${k.id==="spear"?"thuong giao":k.id==="katana"?"kiem guom":"con gay truong"}`).includes(f):m==="all"||k.id===m),y=n?e.items.find(b=>b.id===n):null,g=y&&$r(y)?y:e.items.find(b=>b.kind==="person"&&!b.hidden)??null,v=b=>{const k=Mp(b.id);if(!g||!k){o(a("Thêm một nhân vật vào cảnh (hoặc chọn nhân vật) để áp combo vũ khí."));return}o(""),s(g.id,k)};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-fx-cats shot-lib-subcats",role:"tablist","aria-label":a("Loại vũ khí"),children:[{id:"all",label:"Tất cả",labelEn:"All"},...ud].map(b=>t.jsx("button",{type:"button",role:"tab","data-weapon-pack":b.id,"aria-selected":m===b.id,className:m===b.id&&!f?"active":"",onClick:()=>d(b.id),children:l?b.labelEn:a(b.label)},b.id))}),t.jsx("p",{className:"shot-fx-hint",children:g?a("Áp lên “{0}” từ playhead — tự đặt vũ khí vào tay, hai tay bám cán.",[g.name]):a("Thêm một nhân vật vào cảnh để áp combo vũ khí.")}),t.jsxs("div",{className:"shot-fx-grid",children:[p.map(({clip:b,pack:k})=>t.jsxs("button",{type:"button",className:"shot-fx-card shot-lib-card","data-combo":b.id,title:`${l?b.labelEn:b.label} · ${b.duration}s`,onMouseEnter:()=>u(b.id),onMouseLeave:()=>u(null),onFocus:()=>u(b.id),onBlur:()=>u(null),onClick:()=>v(b),children:[t.jsx(Au,{draw:(w,S,E,j)=>Wv(w,b,S,E,j,k.prop.prop),rest:Bv(b),loop:b.duration+.4,hot:h===b.id}),t.jsx("span",{children:l?b.labelEn:b.label})]},b.id)),!p.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có combo nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:a("Mẹo: nối nhiều combo liên tiếp (dời playhead), rồi chọn camera “Punch-in theo nhịp đòn” hoặc “Đạo diễn hành động” — camera tự bắt nhịp các đòn.")})]})}const Yv=[.5,.3,.15],Qv=[["sakuga","Sakuga · khung tối rồi chớp trắng 2 khung"],["anime","Anime · khung âm bản rồi tách màu"],["manga","Manga · mực đen trắng + vệt tốc độ"],["flash","Chớp trắng"],["invert","Đảo màu"],["rgb","Tách màu RGB"],["radial","Nhoè toả tâm"]],Zv=e=>{const{trail:n,...s}=e;return s};function Jv({stage:e,playhead:n,change:s,setError:o}){rt();const[i,r]=I.useState("medium"),[l,h]=I.useState(.3),u=e.shots.find(j=>j.id===e.activeShot)??e.shots[0],m=u.duration,d=io(u.timing,m),f=Sp(e).map(j=>j.time),p=j=>s(M=>({...M,shots:M.shots.map(T=>{if(T.id!==M.activeShot)return T;const N=j(io(T.timing,T.duration)),{timing:R,...A}=T;return N?{...A,timing:N}:A})})),y=()=>e.items.filter(j=>$r(j)).flatMap(j=>Ip([...u.objectKeys?.[j.id]||[]].sort((M,T)=>M.time-T.time).map(M=>({t:M.time*m,y:M.position[1],air:!!M.air})))),g=e.items.filter(j=>j.kind==="prop"&&j.hold&&j.prop&&Cp[j.prop.kind]),v=g.length>0&&g.every(j=>j.trail),b=(j,M={})=>s(T=>({...T,items:T.items.map(N=>g.some(R=>R.id===N.id)?j?{...N,trail:{...N.trail||{},...M}}:Zv(N):N)})),k=g[0]?.trail?.style??"ribbon",w=Np({duration:m,timing:d??void 0}),S=Ap(u.impactFrame),E=j=>s(M=>({...M,shots:M.shots.map(T=>{if(T.id!==M.activeShot)return T;const{impactFrame:N,...R}=T;return j?{...R,impactFrame:j}:R})}));return t.jsxs("div",{className:"shot-timing",children:[t.jsx("p",{className:"shot-fx-hint",children:a("Hit-stop khựng hình đúng lúc trúng đòn, slow-mo làm chậm khoảnh khắc đẹp nhất. Chỉ đổi cách phát và xuất video — key chuyển động giữ nguyên.")}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Nhịp anime (sakuga)")}),t.jsx("p",{className:"shot-fx-hint",children:a("Nhịp đòn đo từ các cảnh đánh nhau anime vẽ tay: đỡ khựng 1 khung, trúng thân 3, trúng đầu 6, đòn kết 12; lặng một nhịp trước đòn kết rồi bùng nổ, dư chấn chậm lại; máy rung kiểu vẽ tay; khung tối rồi chớp trắng.")}),t.jsx("button",{type:"button","data-timing":"sakuga",disabled:!f.length&&!u.impacts?.length,onClick:()=>{const j=Tp(u,Lp(e),{keepLook:!1});if(!j){o(a("Chưa có đòn đánh nào trong shot (áp một combo vũ khí hoặc động tác võ trước)."));return}o(""),s(M=>({...M,shots:M.shots.map(T=>T.id===M.activeShot?{...T,timing:j.shot.timing,impacts:j.shot.impacts,impactFrame:j.shot.impactFrame}:T)}))},children:a("Áp nhịp anime ({0} đòn)",[u.impacts?.length||f.length])})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Hit-stop")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Độ khựng")}),t.jsxs("select",{"aria-label":a("Độ khựng"),value:i,onChange:j=>r(j.target.value),children:[t.jsx("option",{value:"light",children:a("Nhẹ")}),t.jsx("option",{value:"medium",children:a("Vừa")}),t.jsx("option",{value:"heavy",children:a("Mạnh")})]})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-timing":"hitstops",disabled:!f.length,title:f.length?void 0:a("Chưa có đòn đánh nào trong shot (áp một combo vũ khí hoặc động tác võ trước)."),onClick:()=>{o(""),p(j=>Ql(j,f,Zl[i],m))},children:a("Khựng mọi đòn ({0})",[f.length])}),t.jsx("button",{type:"button",onClick:()=>p(j=>Ql(j,[n],Zl[i],m)),children:a("Khựng tại playhead")})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Slow-mo")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Tốc độ")}),t.jsx("select",{"aria-label":a("Tốc độ slow-mo"),value:l,onChange:j=>h(+j.target.value),children:Yv.map(j=>t.jsxs("option",{value:j,children:[Math.round(j*100),"%"]},j))})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-timing":"apex",onClick:()=>{const j=y();if(!j.length){o(a("Không thấy cú nhảy nào trong shot."));return}o(""),p(M=>j.reduce((T,N)=>wi(T,N,.3,l,m),M))},children:a("Chậm ở đỉnh cú nhảy")}),t.jsx("button",{type:"button","data-timing":"slow-playhead",onClick:()=>p(j=>wi(j,n,.35,l,m)),children:a("Chậm quanh playhead")}),f.length>0&&t.jsx("button",{type:"button",onClick:()=>p(j=>wi(j,f[f.length-1],.3,l,m)),children:a("Chậm đòn kết")})]})]}),d&&t.jsxs("div",{className:"shot-list shot-timing-list",children:[d.holds.map(j=>t.jsxs("div",{children:[t.jsxs("span",{children:["⏸ ",a("Khựng {0}s · {1}s",[j.at.toFixed(2),j.hold.toFixed(2)])]}),t.jsx("button",{type:"button","aria-label":a("Bỏ khựng {0}s",[j.at.toFixed(2)]),onClick:()=>p(M=>io({holds:(M?.holds||[]).filter(T=>T.at!==j.at),slows:M?.slows||[]},m)),children:t.jsx(Ce.trash,{})})]},`h${j.at}`)),d.slows.map(j=>t.jsxs("div",{children:[t.jsxs("span",{children:["🐢 ",a("Chậm {0}–{1}s · {2}%",[j.start.toFixed(2),j.end.toFixed(2),Math.round(j.speed*100)])]}),t.jsx("button",{type:"button","aria-label":a("Bỏ slow-mo {0}s",[j.start.toFixed(2)]),onClick:()=>p(M=>io({holds:M?.holds||[],slows:(M?.slows||[]).filter(T=>T.start!==j.start)},m)),children:t.jsx(Ce.trash,{})})]},`s${j.start}`))]}),t.jsx("p",{className:"shot-fx-hint","data-testid":"timing-length",children:d?a("Video dài {0}s (shot {1}s).",[w.toFixed(2),m.toFixed(2)]):a("Chưa có hit-stop hay slow-mo.")}),d&&t.jsx("button",{type:"button",onClick:()=>p(()=>null),children:a("Xoá nhịp đòn")}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Khung va chạm")}),t.jsx("p",{className:"shot-fx-hint",children:a("Mỗi lần khựng hình chớp một khung va chạm kiểu anime / game, hướng về chỗ hai nhân vật.")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Kiểu")}),t.jsxs("select",{"aria-label":a("Kiểu khung va chạm"),"data-timing":"impact-style",value:S?.style??"",onChange:j=>E(j.target.value?{style:j.target.value,strength:S?.strength??1}:null),children:[t.jsx("option",{value:"",children:a("Không")}),Qv.map(([j,M])=>t.jsx("option",{value:j,children:a(M)},j))]})]}),S&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Độ mạnh")}),t.jsx("input",{type:"range","aria-label":a("Độ mạnh khung va chạm"),min:.1,max:1,step:.05,value:S.strength,onChange:j=>E({...S,strength:+j.target.value})})]}),S&&!d?.holds.length&&t.jsx("p",{className:"shot-fx-hint",children:a("Thêm hit-stop để khung va chạm hiện ra.")})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Vệt chém")}),g.length?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Vệt chém trên vũ khí đang cầm ({0})",[g.length])}),t.jsx("input",{type:"checkbox","aria-label":a("Vệt chém"),checked:v,onChange:j=>b(j.target.checked)})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Kiểu vệt")}),t.jsxs("select",{"aria-label":a("Kiểu vệt chém"),"data-timing":"trail-style",value:k,onChange:j=>b(!0,{style:j.target.value}),children:[t.jsx("option",{value:"ribbon",children:a("Dải sáng")}),t.jsx("option",{value:"smear",children:a("Smear trắng (anime)")})]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Màu vệt")}),t.jsx("input",{type:"color","aria-label":a("Màu vệt chém"),value:g[0].trail?.color||(k==="smear"?Ep.color:Rp.color),onChange:j=>b(!0,{color:j.target.value})})]})]}):t.jsx("p",{className:"shot-fx-hint",children:a("Chưa có vũ khí nào đang cầm (thương, kiếm, côn, gậy, dao).")})]})]})}const e1={blocked:"đỡ",miss:"né",body:"trúng"};function t1({stage:e,playhead:n,change:s,setError:o}){const i=rt(),r=i==="en",l=e.items.filter(A=>$r(A)&&!A.hidden),[h,u]=I.useState(""),[m,d]=I.useState(""),[f,p]=I.useState(["katana","katana"]),[y,g]=I.useState(4),[v,b]=I.useState(1),[k,w]=I.useState(!0),[S,E]=I.useState(""),j=l.find(A=>A.id===h)??l[0],M=l.find(A=>A.id===m&&A.id!==j?.id)??l.find(A=>A.id!==j?.id),T=()=>s(A=>{const C=A.items.find(B=>B.id===j?.id),O=C?[C.position[0],0,C.position[2]+2]:[0,0,2];return{...A,items:[...A.items,{...An("person",A.items.length),name:a("Đối thủ"),position:O,rotation:[0,180,0]}]}}),N=A=>{if(!j||!M){o(a("Cần hai nhân vật trong cảnh để dàn cảnh đấu."));return}const C=qg(e,{a:j.id,b:M.id,packs:f,exchanges:y,seed:A,start:n},()=>crypto.randomUUID());if(!C.ok){o(C.error);return}let O=C.stage;if(k)try{O=Pp(O,{fighters:[j.name,M.name],start:n,end:C.end+.4}).stage}catch{}o(""),b(A),E(C.plan.map(B=>`${B.time.toFixed(1)}s ${B.attackerName} → ${r?B.result:a(e1[B.result])}`).join(" · ")),s(()=>O)},R=(A,C)=>p(O=>A===0?[C,O[1]]:[O[0],C]);return t.jsxs("fieldset",{className:"shot-duel",children:[t.jsx("legend",{children:a("Đấu 2 người")}),l.length<2?t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"shot-fx-hint",children:a("Cần hai nhân vật trong cảnh để dàn cảnh đấu.")}),t.jsx("button",{type:"button","data-duel":"add-opponent",onClick:T,children:a("Thêm đối thủ")})]}):t.jsxs(t.Fragment,{children:[[0,1].map(A=>t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("select",{"aria-label":A===0?a("Người tấn công trước"):a("Đối thủ"),value:(A===0?j:M)?.id??"",onChange:C=>(A===0?u:d)(C.target.value),children:l.filter(C=>A===0||C.id!==j?.id).map(C=>t.jsx("option",{value:C.id,children:C.name},C.id))}),t.jsx("select",{"aria-label":a("Vũ khí"),"data-duel-weapon":A,value:f[A],onChange:C=>R(A,C.target.value),children:[...ud.filter(C=>C.id in Gg),{id:"fist",label:"Tay không",labelEn:"Unarmed"}].map(C=>t.jsx("option",{value:C.id,children:r?C.labelEn:a(C.label)},C.id))})]},A)),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Số pha đấu")}),t.jsx("input",{type:"number","aria-label":a("Số pha đấu"),min:1,max:10,value:y,onChange:A=>g(Math.max(1,Math.min(10,Number(A.target.value)||4)))})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Camera đấu (giữ cả hai trong khung)")}),t.jsx("input",{type:"checkbox","aria-label":a("Camera đấu"),checked:k,onChange:A=>w(A.target.checked)})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-duel":"stage",onClick:()=>N(v),children:a("Dàn cảnh đấu từ playhead")}),t.jsx("button",{type:"button","data-duel":"reroll",onClick:()=>N(v+1),children:a("Phương án khác")})]}),t.jsx("p",{className:"shot-fx-hint",children:S||a("Đòn tấn công gặp đỡ / né / trúng đúng khung chạm, tự thêm hit-stop và tia lửa. Thay toàn bộ chuyển động của hai người từ playhead.")})]})]})}const Sr="application/x-clipoox-fx",Cr=(e,n)=>e.lib?n==="en"&&e.nameEn?e.nameEn:e.name:a(e.name),n1=(e,n)=>e.lib?n==="en"&&e.descEn?e.descEn:e.desc:a(e.desc);function s1({entry:e,hot:n}){const s=I.useRef(null);return I.useEffect(()=>{const o=s.current;if(!o)return;const i=o.getContext("2d");if(!i)return;const r=o.width,l=o.height;if(!n){Sc(i,e,$g(e),r,l);return}let h=0;const u=performance.now(),m=Dg(e),d=()=>{Sc(i,e,(performance.now()-u)/1e3%m,r,l),h=requestAnimationFrame(d)};return h=requestAnimationFrame(d),()=>cancelAnimationFrame(h)},[e,n]),t.jsx("canvas",{ref:s,width:192,height:108,"aria-hidden":"true"})}function Ws({label:e,value:n,onChange:s,min:o,max:i,step:r=.1}){return t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a(e)}),t.jsx(Tn,{"aria-label":a(e),precision:2,value:n,min:o,max:i,step:r,onCommit:s})]})}const Ah=[["chest","ngực"],["head","đầu"],["feet","chân"],["hand_right","tay phải"],["hand_left","tay trái"]];function a1({stage:e,selected:n,playhead:s,change:o,onSelect:i,ground:r,anchor:l,setError:h,onEdit:u,onPlayClip:m}){const d=rt(),f=zv(),[p,y]=I.useState(""),[g,v]=I.useState("tu-tien"),[b,k]=I.useState(null),w=e.shots.find(T=>T.id===e.activeShot)??e.shots[0],S=I.useMemo(()=>g==="camera"||g==="weapon"||g==="timing"?[]:Fp(p,p.trim()?void 0:g),[p,g,f.version]),E=e.items.filter(T=>T.kind==="fx"&&T.fx),j=E.find(T=>T.id===n)??null,M=T=>{const N=ku(e,T,{selected:n,ground:r(),start:s,label:Cr(T,d),anchor:l});if("error"in N){h(a("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[yn.maxItems]));return}h(""),o(()=>N.stage),i(N.item.id)};return t.jsxs("div",{className:"shot-fx",children:[j&&u&&t.jsxs("button",{type:"button",className:"shot-fx-edit-jump",onClick:u,children:["✎ ",a("Sửa {0}",[j.name])]}),t.jsx("div",{className:"shot-fx-search",children:t.jsx("input",{type:"search","aria-label":a("Tìm hiệu ứng"),placeholder:a("Tìm hiệu ứng… (vd: kiem, set, aura)"),value:p,onChange:T=>y(T.target.value)})}),t.jsxs("div",{className:"shot-fx-cats",role:"tablist","aria-label":a("Nhóm hiệu ứng"),children:[$p.map(T=>t.jsxs("button",{type:"button",role:"tab","aria-selected":g===T.id&&!p.trim(),disabled:!T.ready,className:g===T.id&&!p.trim()?"active":"",title:T.ready?a(T.name):a("Sắp có"),onClick:()=>{v(T.id),y("")},children:[a(T.name),!T.ready&&t.jsx("small",{children:a("sắp có")})]},T.id)),t.jsxs("button",{type:"button",role:"tab","aria-selected":g==="camera",className:`shot-lib-tab${g==="camera"?" active":""}`,onClick:()=>v("camera"),children:["🎥 ",a("Camera")]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":g==="weapon",className:`shot-lib-tab${g==="weapon"?" active":""}`,onClick:()=>v("weapon"),children:["⚔ ",a("Combo vũ khí")]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":g==="timing",className:`shot-lib-tab${g==="timing"?" active":""}`,onClick:()=>v("timing"),children:["⏱ ",a("Nhịp đòn")]})]}),g==="camera"&&t.jsx(Xv,{stage:e,selected:n,playhead:s,change:o,setError:h,query:p}),g==="weapon"&&!p&&t.jsx(t1,{stage:e,playhead:s,change:o,setError:h}),g==="weapon"&&(m?t.jsx(Vv,{stage:e,selected:n,onPlay:m,setError:h,query:p}):null),g==="timing"&&t.jsx(Jv,{stage:e,playhead:s,change:o,setError:h}),g!=="camera"&&g!=="weapon"&&g!=="timing"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-fx-grid",children:[S.map(T=>t.jsxs("button",{type:"button",className:`shot-fx-card${T.lib?" lib":""}`,"data-fx":T.id,draggable:!0,title:n1(T,d),onMouseEnter:()=>k(T.id),onMouseLeave:()=>k(null),onFocus:()=>k(T.id),onBlur:()=>k(null),onDragStart:N=>{N.dataTransfer.setData(Sr,T.id),N.dataTransfer.effectAllowed="copy"},onClick:()=>M(T),children:[t.jsx(s1,{entry:T,hot:b===T.id}),t.jsx("span",{children:Cr(T,d)}),T.lib&&t.jsx("small",{className:"shot-fx-lib",children:a("Thư viện Clipoox")})]},T.id)),!S.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có hiệu ứng nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:a("Bấm hoặc kéo thẻ vào khung 3D. Chọn nhân vật trước để hiệu ứng bám vào tay / chân và nhắm vào nhân vật khác.")})]}),t.jsxs("h3",{children:[a("Hiệu ứng trong cảnh")," ",t.jsxs("small",{className:"shot-total",children:["· ",E.length,"/",yn.maxItems]})]}),t.jsxs("div",{className:"shot-list shot-fx-list",children:[E.map(T=>{const N=On(T,w);return t.jsxs("div",{className:n===T.id?"active":"",children:[t.jsxs("button",{title:a("Sửa {0}",[T.name]),onClick:()=>{i(T.id),u?.()},children:["✦ ",T.name,t.jsxs("small",{className:"shot-list-meta",children:[" · ",N.off?a("không phát trong shot này"):`${N.start.toFixed(1)}s → ${(N.start+N.duration).toFixed(1)}s`]})]}),t.jsx("button",{title:T.hidden?a("Hiện"):a("Ẩn"),onClick:()=>o(R=>({...R,items:R.items.map(A=>A.id===T.id?{...A,hidden:!A.hidden}:A)})),children:T.hidden?"○":"●"}),t.jsx("button",{className:"shot-delete-item","aria-label":a("Xóa {0}",[T.name]),title:a("Xóa {0}",[T.name]),onClick:()=>{o(R=>({...R,items:R.items.filter(A=>A.id!==T.id),shots:R.shots.map(A=>A.fxTiming?.[T.id]?{...A,fxTiming:Object.fromEntries(Object.entries(A.fxTiming).filter(([C])=>C!==T.id))}:A)})),n===T.id&&i(null)},children:t.jsx(Ce.trash,{})})]},T.id)}),!E.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Chưa có hiệu ứng. Chọn một thẻ ở trên.")})]})]})}function o1({stage:e,selected:n,playhead:s,change:o,onSelect:i,ground:r,engine:l}){rt();const h=e.shots.find(d=>d.id===e.activeShot)??e.shots[0],u=e.items.filter(d=>d.kind==="fx"&&d.fx),m=u.find(d=>d.id===n)??null;return t.jsxs("div",{className:"shot-fx shot-fx-edit",children:[u.length>1&&t.jsxs("select",{"aria-label":a("Hiệu ứng đang sửa"),value:m?.id??"",onChange:d=>i(d.target.value||null),children:[!m&&t.jsx("option",{value:"",children:a("Chọn hiệu ứng…")}),u.map(d=>t.jsxs("option",{value:d.id,children:["✦ ",d.name]},d.id))]}),m?t.jsx(i1,{item:m,stage:e,shot:h,playhead:s,change:o,ground:r,engine:l??null}):t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"shot-fx-hint",children:u.length?a("Bấm vào một hiệu ứng trên timeline (hàng ✦) hoặc chọn ở trên để sửa."):a("Chưa có hiệu ứng. Thêm ở bảng Hiệu ứng.")}),u.length===1&&t.jsxs("button",{type:"button",onClick:()=>i(u[0].id),children:["✎ ",a("Sửa {0}",[u[0].name])]})]})]})}function i1({item:e,stage:n,shot:s,playhead:o,change:i,ground:r,engine:l}){const h=rt(),[u,m]=I.useState(null),d=e.fx,f=_o[d.preset],p=md(d.cat??""),y=On(e,s),g=!!s.fxTiming?.[e.id],v=n.items.filter($=>$.id!==e.id&&$.kind!=="fx"&&!$.hidden),b=($,W={})=>i(z=>({...z,items:z.items.map(Y=>Y.id===e.id?{...Y,...W,fx:{...Y.fx,...$}}:Y)})),k=$=>i(W=>({...W,items:W.items.map(z=>z.id===e.id?{...z,...$}:z)})),w=$=>i(W=>({...W,shots:W.shots.map(z=>z.id===W.activeShot?{...z,fxTiming:{...z.fxTiming,[e.id]:Dr({...On(e,z),...$,off:!1},z.duration)}}:z)})),S=($,W)=>b({params:{...d.params,[$]:W}}),E=sr(nr(d).fx??d),j=d.path??[],M=$=>b({path:$.length>=2?$:void 0}),T=j.length;I.useEffect(()=>{if(!(!l||T<2))return l.setFxPathEditor({itemId:e.id,selected:u,select:m,move:($,W)=>i(z=>({...z,items:z.items.map(Y=>Y.id===e.id&&Y.fx?.path?{...Y,fx:{...Y.fx,path:Y.fx.path.map((J,V)=>V===$?W.map(H=>+H.toFixed(2)):J)}}:Y)}))}),()=>l.setFxPathEditor(null)},[l,e.id,T,u]);const N=d.attach?v.find($=>$.id===d.attach.to):void 0,R=s.duration>0?Math.min(1,Math.max(0,o/s.duration)):0,A=pd(e,s),C=zo(e,s,R),O=$=>{A?i(W=>Bo(W,e.id,R,$)):$.position?b({attach:{...d.attach,offset:$.position}}):$.yaw!==void 0&&k({rotation:[e.rotation[0],$.yaw,e.rotation[2]]})},B=$=>{const[W,z]=$.split("|"),Y=v.find(J=>J.id===W);return Y?Jl(Y,z).map(J=>+J.toFixed(2)):null},D=v.flatMap($=>Ah.filter(([W])=>$.kind==="person"||W==="chest"||W==="feet").map(([W,z])=>t.jsxs("option",{value:`${$.id}|${W}`,children:[$.name," · ",a(z)]},`${$.id}|${W}`)));return t.jsxs("div",{className:"shot-fx-inspector","aria-label":a("Chỉnh hiệu ứng"),children:[t.jsxs("h3",{children:[a("CHỈNH HIỆU ỨNG")," ",t.jsxs("small",{className:"shot-total",children:["· ",p?Cr(p,h):e.name]})]}),t.jsx("input",{"aria-label":a("Tên hiệu ứng"),value:e.name,onChange:$=>k({name:$.target.value})}),n.plate&&t.jsxs("label",{className:"shot-field",title:a("Lớp sau người: Timeline tách người trong video và đặt hiệu ứng ra sau (aura, vòng sáng). Lớp trước người: phủ lên cả người (tia lửa, hạt bay qua)."),children:[t.jsx("span",{className:"shot-fx-vfx-label",children:a("Lớp VFX")}),t.jsxs("select",{"aria-label":a("Lớp VFX"),value:fd(e),onChange:$=>k({vfxLayer:$.target.value}),children:[t.jsx("option",{value:"behind",children:a("Sau người")}),t.jsx("option",{value:"front",children:a("Trước người")})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Thời gian trong shot")}),g?t.jsxs(t.Fragment,{children:[t.jsx(Ws,{label:"Bắt đầu (s)",value:y.start,min:0,max:Math.max(.1,s.duration),step:.1,onChange:$=>w({start:$})}),t.jsx(Ws,{label:"Kéo dài (s)",value:y.duration,min:.2,max:yn.maxDuration,step:.1,onChange:$=>w({duration:$})}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Lặp lại")}),t.jsx("input",{type:"checkbox","aria-label":a("Lặp lại"),checked:y.loop,onChange:$=>w({loop:$.target.checked})})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",onClick:()=>w({start:+(o*s.duration).toFixed(2)}),children:a("Bắt đầu tại playhead")}),t.jsx("button",{type:"button",onClick:()=>i($=>({...$,shots:$.shots.map(W=>W.id===$.activeShot?{...W,fxTiming:Object.fromEntries(Object.entries(W.fxTiming??{}).filter(([z])=>z!==e.id))}:W)})),children:a("Bỏ khỏi shot này")})]})]}):t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>w({start:+(o*s.duration).toFixed(2),duration:d.duration}),children:a("Phát trong shot này")})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Màu")}),t.jsx("input",{type:"color","aria-label":a("Màu hiệu ứng"),value:e.color,onChange:$=>k({color:$.target.value})})]}),t.jsx(Ws,{label:"Cường độ",value:d.intensity,min:.1,max:3,step:.1,onChange:$=>b({intensity:$})}),t.jsx(Ws,{label:"Kích thước",value:e.scale[0],min:.1,max:6,step:.1,onChange:$=>k({scale:[$,$,$]})}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Seed")}),t.jsxs("span",{className:"shot-fx-seed",children:[t.jsx(Tn,{"aria-label":a("Seed"),value:d.seed,min:0,max:2147483647,step:1,onCommit:$=>b({seed:Math.round($)})}),t.jsxs("button",{type:"button","aria-label":a("Đổi seed ngẫu nhiên"),title:a("Đổi seed ngẫu nhiên"),onClick:()=>b({seed:Math.floor(Math.random()*1e9)+1}),children:[t.jsx(Ce.reset,{}),a("Xáo trộn")]})]})]}),f.params.length>0&&t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Thông số")}),f.params.map($=>$.type==="number"?t.jsx(Ws,{label:$.label??$.key,value:Number(d.params[$.key]??$.def),min:$.min,max:$.max,step:$.max-$.min>20?1:.05,onChange:W=>S($.key,W)},$.key):t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a($.label??$.key)}),t.jsx("select",{"aria-label":a($.label??$.key),value:String(d.params[$.key]??$.def),onChange:W=>S($.key,W.target.value),children:$.options.map(W=>t.jsx("option",{value:W,children:W},W))})]},$.key))]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Gắn vào")}),t.jsxs("select",{"aria-label":a("Đối tượng gắn hiệu ứng"),value:d.attach?.to??"",onChange:$=>{const W=$.target.value;b({attach:W?{to:W,...d.attach?.hand?{hand:d.attach.hand}:{},offset:d.attach?.offset}:void 0})},children:[t.jsx("option",{value:"",children:a("Tự do (theo vị trí của hiệu ứng)")}),v.map($=>t.jsx("option",{value:$.id,children:$.name},$.id))]}),d.attach&&t.jsxs(t.Fragment,{children:[N?.kind==="person"&&t.jsxs("select",{"aria-label":a("Bộ phận gắn"),value:d.attach.hand??d.attach.part??"",onChange:$=>{const W=$.target.value,{hand:z,part:Y,...J}=d.attach;b({attach:{...J,...W==="L"||W==="R"?{hand:W}:W==="chest"||W==="head"?{part:W}:{}}})},children:[t.jsx("option",{value:"",children:a("Cơ thể (chân)")}),t.jsx("option",{value:"chest",children:a("Ngực")}),t.jsx("option",{value:"head",children:a("Đầu")}),t.jsx("option",{value:"R",children:a("Tay phải")}),t.jsx("option",{value:"L",children:a("Tay trái")})]}),d.attach.hand&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Ở đầu vật đang cầm (nòng súng)")}),t.jsx("input",{type:"checkbox","aria-label":a("Ở đầu vật đang cầm (nòng súng)"),checked:d.attach.tip===!0,onChange:$=>b({attach:{...d.attach,tip:$.target.checked?!0:void 0}})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Xoay theo đối tượng")}),t.jsx("input",{type:"checkbox","aria-label":a("Xoay theo đối tượng"),checked:d.attach.follow!=="position",onChange:$=>{const{follow:W,...z}=d.attach;b({attach:{...z,...$.target.checked?{}:{follow:"position"}}})}})]}),t.jsx("p",{className:"shot-fx-hint",children:A?a("Độ lệch theo key: {0} key trong shot này. Sửa số dưới đây là ghi key tại playhead.",[s.objectKeys?.[e.id]?.length??0]):a("Bấm +◆ ở hàng hiệu ứng trên timeline để thêm key độ lệch tại playhead (sửa khi hiệu ứng bị lệch).")}),t.jsx("div",{className:"shot-fx-vec",children:["X","Y","Z"].map(($,W)=>t.jsxs("label",{children:[t.jsx("span",{children:$}),t.jsx(Tn,{"aria-label":a("Lệch {0}",[$]),precision:2,step:.1,min:-100,max:100,value:+C.position[W].toFixed(3),onCommit:z=>{const Y=[...C.position];Y[W]=z,O({position:Y})}})]},$))}),t.jsx("button",{type:"button",onClick:()=>i($=>Bo($,e.id,R)),children:a("+◆ Key độ lệch tại playhead")})]}),!d.attach&&t.jsx("div",{className:"shot-fx-vec",children:["X","Y","Z"].map(($,W)=>t.jsxs("label",{children:[t.jsx("span",{children:$}),t.jsx(Tn,{"aria-label":a("Vị trí {0}",[$]),precision:2,step:.1,min:-1e3,max:1e3,value:e.position[W],onCommit:z=>{const Y=[...e.position];Y[W]=z,k({position:Y})}})]},$))}),t.jsx(Ws,{label:"Hướng (độ)",value:d.attach?+C.yaw.toFixed(1):e.rotation[1],min:-360,max:360,step:5,onChange:$=>d.attach?O({yaw:$}):k({rotation:[e.rotation[0],$,e.rotation[2]]})})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Nhắm vào")}),t.jsxs("select",{"aria-label":a("Mục tiêu bám theo"),value:d.target?`${d.target.to}|${d.target.part}`:"",onChange:$=>{const[W,z]=$.target.value.split("|");b({target:W?{to:W,part:z,...d.target?.to===W&&d.target.name?{name:d.target.name}:{}}:void 0})},children:[t.jsx("option",{value:"",children:a("Không (theo đường bay / hướng)")}),v.flatMap($=>[...Ah.filter(([W])=>["chest","head","feet"].includes(W)).map(([W,z])=>t.jsxs("option",{value:`${$.id}|${W}`,children:[$.name," · ",a(z)]},`${$.id}|${W}`)),t.jsxs("option",{value:`${$.id}|center`,children:[$.name," · ",a("Cả khối (nhà, tường, cửa kính)")]},`${$.id}|center`)])]}),d.target&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Chỉ một phần (tên, vd: window)")}),t.jsx("input",{"aria-label":a("Tên phần của mục tiêu"),value:d.target.name??"",onChange:$=>b({target:{...d.target,name:$.target.value.trim()?$.target.value.slice(0,60):void 0}})})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Đường bay")}),j.length<2&&t.jsx("button",{type:"button",onClick:()=>{const $=Jl(N??{kind:"box",position:e.position,scale:[1,1,1]},"chest"),W=r();M([$.map(z=>+z.toFixed(2)),[+($[0]+6).toFixed(2),$[1],+(W[2]||$[2]).toFixed(2)]])},children:a("Tạo đường bay")}),j.length>=2&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Từ")}),t.jsxs("select",{"aria-label":a("Điểm xuất phát"),value:"",onChange:$=>{const W=B($.target.value);W&&M([W,...j.slice(1)])},children:[t.jsx("option",{value:"",children:a("Chọn đối tượng…")}),D]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Tới")}),t.jsxs("select",{"aria-label":a("Điểm đến"),value:"",onChange:$=>{const W=B($.target.value);W&&M([...j.slice(0,-1),W])},children:[t.jsx("option",{value:"",children:a("Chọn đối tượng…")}),D]})]}),j.map(($,W)=>t.jsxs("div",{className:`shot-fx-point ${u===W?"active":""}`,children:[t.jsx("b",{role:"button",tabIndex:0,title:a("Chọn điểm để kéo trong khung 3D"),onClick:()=>m(W),onKeyDown:z=>{z.key==="Enter"&&m(W)},children:W===0?a("Đầu"):W===j.length-1?a("Cuối"):`${W+1}`}),[0,1,2].map(z=>t.jsx(Tn,{"aria-label":a("Điểm {0} {1}",[W+1,"XYZ"[z]]),precision:2,step:.1,min:-1e3,max:1e3,value:$[z],onCommit:Y=>{const J=j.map(V=>[...V]);J[W][z]=Y,M(J)}},z)),t.jsx("button",{type:"button","aria-label":a("Xóa điểm {0}",[W+1]),disabled:j.length<=2,onClick:()=>M(j.filter((z,Y)=>Y!==W)),children:t.jsx(Ce.close,{})})]},W)),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",disabled:j.length>=yn.maxPathPoints,onClick:()=>{const $=j.at(-2),W=j.at(-1);M([...j.slice(0,-1),[+(($[0]+W[0])/2).toFixed(2),+(($[1]+W[1])/2+.8).toFixed(2),+(($[2]+W[2])/2).toFixed(2)],W])},children:a("Thêm điểm giữa")}),t.jsx("button",{type:"button",onClick:()=>b({path:void 0}),children:a("Xóa đường bay")})]})]})]}),t.jsx("small",{className:"shot-fx-budget",children:a("{0} hạt · giới hạn {1}/hiệu ứng",[E,yn.maxParticlesPerItem])})]})}const tn=e=>+e.toFixed(2),r1=[{key:"radius",step:.1},{key:"falloff",step:.1},{key:"strength",step:.5},{key:"lift",step:.05},{key:"gravity",step:.5},{key:"chunks",step:10},{key:"debris",step:.1},{key:"spin",step:.5},{key:"collapse",step:.05},{key:"shake",step:.05}],l1=[{key:"yaw",step:5},{key:"crumble",step:.05},{key:"dust",step:.1},{key:"shake",step:.05},{key:"chunks",step:10},{key:"gravity",step:.5},{key:"debris",step:.1}],c1={collapse:"🏚",explosion:"💥",shatter:"🪟",burning:"🔥",collapse_building:"🏢"},h1={pancake:"Sập tại chỗ (từng tầng)",topple:"Đổ nghiêng",base:"Sập từ chân"},Tu=e=>id.has(String(e)),Wa=e=>!!e&&e.kind==="fx"&&e.fx?.preset===tr,Lu=e=>e.items.filter(n=>Jd.has(n.kind)&&!n.hidden&&!n.hold);function Eu(e,n){const s=e.shots.find(y=>y.id===e.activeShot)??e.shots[0],o=e.items.find(y=>y.id===n.target),i=n.bounds??{min:[o.position[0]-.5,0,o.position[2]-.5],max:[o.position[0]+.5,1,o.position[2]+.5]},r=[0,1,2].map(y=>i.max[y]-i.min[y]),l=tn(Math.min(6,Math.max(.6,Math.max(...r)/5))),h=Tu(n.recipe),u=tn(Math.min(Math.max(0,n.playhead),Math.max(0,s.duration-.2))),m=tn(Math.max(.3,h?Math.min(4,s.duration-u):s.duration-u)),d=zp({target:o.id,recipe:n.recipe,seed:n.seed??Math.floor(Math.random()*1e9)+1,start:u,duration:m,params:{radius:l,...n.params}}),f=h?[tn((i.min[0]+i.max[0])/2),tn(i.max[1]+.6),tn((i.min[2]+i.max[2])/2)]:[tn(i.min[0]-l-Number(d.params.falloff)-.3),tn((i.min[1]+i.max[1])/2),tn((i.min[2]+i.max[2])/2)],p={...An("fx",e.items.length),name:n.name,color:Ua[n.recipe].color,position:f,fx:d};return{item:p,stage:{...e,items:[...e.items,p],shots:e.shots.map(y=>y.id===s.id?{...y,fxTiming:{...y.fxTiming,[p.id]:{start:u,duration:m}}}:y)}}}function Co(e,n,s,o,i=yt()){const r=e.shots.find(f=>f.id===e.activeShot)??e.shots[0],l=e.items.find(f=>f.id===n);if(!l)return e;const h=r.objectKeys?.[n]??[],u=Wn(l,r,s),m=h.find(f=>Math.abs(f.time-s)<1e-6),d={...m,id:m?.id??i,time:s,position:o??[...u.position],rotation:[...u.rotation],scale:[...u.scale]};return{...e,shots:e.shots.map(f=>f.id===r.id?{...f,objectKeys:{...f.objectKeys,[n]:[...h.filter(p=>p.id!==d.id),d].sort((p,y)=>p.time-y.time)}}:f)}}function No({label:e,value:n,onChange:s,min:o,max:i,step:r=.1}){return t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a(e)}),t.jsx(Tn,{"aria-label":a(e),precision:2,value:n,min:o,max:i,step:r,onCommit:s})]})}function d1({stage:e,selected:n,progress:s,change:o,onSelect:i,engine:r,setError:l}){rt();const h=e.shots.find(k=>k.id===e.activeShot)??e.shots[0],u=s*h.duration,m=e.items.filter(Wa),d=Lu(e),f=m.find(k=>k.id===n)??null,[p,y]=I.useState(()=>({target:"",recipe:"collapse"})),g=d.find(k=>k.id===n)??null,v=d.some(k=>k.id===p.target)?p.target:g?.id??d[0]?.id??"",b=()=>{if(!v)return;if(e.items.filter(S=>S.kind==="fx").length>=yn.maxItems){l?.(a("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[yn.maxItems]));return}const k=r?.objectBounds()[v]??null,w=Eu(e,{target:v,recipe:p.recipe,playhead:u,bounds:k,name:`${a("Mix FX")} ${m.length+1}`});o(()=>w.stage),i(w.item.id)};return t.jsxs("div",{className:"shot-fx shot-mixfx",children:[t.jsx("p",{className:"shot-fx-hint",children:a("Khối cầu vô hình đi theo các điểm bạn đặt; nó đi qua đâu, mục tiêu vỡ ở đó. Kéo khối cầu trong khung 3D, mỗi lần thả là một key tại playhead.")}),m.length>0&&t.jsx("div",{className:"shot-list shot-fx-list",children:m.map(k=>t.jsx("div",{className:k.id===f?.id?"active":"",children:t.jsxs("button",{type:"button",onClick:()=>i(k.id),children:["💥 ",k.name,t.jsxs("small",{className:"shot-list-meta",children:[" · ",e.items.find(w=>w.id===k.fx?.target?.to)?.name??a("chưa có mục tiêu")]})]})},k.id))}),!f&&t.jsxs("fieldset",{className:"shot-mixfx-new",children:[t.jsx("legend",{children:a("Tạo Mix FX")}),d.length?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Mục tiêu")}),t.jsx("select",{"aria-label":a("Mục tiêu bị phá"),value:v,onChange:k=>y(w=>({...w,target:k.target.value})),children:d.map(k=>t.jsx("option",{value:k.id,children:k.name},k.id))})]}),t.jsx(Ru,{value:p.recipe,onPick:k=>y(w=>({...w,recipe:k}))}),t.jsx("button",{type:"button",className:"shot-primary",onClick:b,children:a("Tạo khối cầu phá huỷ")})]}):t.jsx("p",{className:"shot-fx-empty",children:a("Thêm một model GLB, proxy hoặc hộp / tường / bục trước, rồi chọn nó làm mục tiêu.")})]}),f&&t.jsx(u1,{item:f,stage:e,progress:s,change:o,onSelect:i,engine:r??null},f.id)]})}function Ru({value:e,onPick:n}){return t.jsx("div",{className:"shot-mixfx-recipes",role:"group","aria-label":a("Công thức hiệu ứng"),children:Dp.map(s=>t.jsxs("button",{type:"button","data-recipe":s,className:e===s?"active":"","aria-pressed":e===s,onClick:()=>n(s),children:[t.jsx("span",{"aria-hidden":!0,children:c1[s]}),a(Ua[s].name)]},s))})}function u1({item:e,stage:n,progress:s,change:o,onSelect:i,engine:r}){const l=n.shots.find(M=>M.id===n.activeShot)??n.shots[0],h=e.fx,u=h.params,m=On(e,l),d=!!l.fxTiming?.[e.id],f=l.objectKeys?.[e.id]??[],p=Lu(n),y=n.items.find(M=>M.id===h.target?.to)??null,g=(M,T={})=>o(N=>({...N,items:N.items.map(R=>R.id===e.id?{...R,...T,fx:{...R.fx,...M}}:R)})),v=(M,T)=>g({params:{...u,[M]:T}}),b=M=>o(T=>({...T,shots:T.shots.map(N=>N.id===T.activeShot?{...N,fxTiming:{...N.fxTiming,[e.id]:Dr({...On(e,N),...M,off:!1},N.duration)}}:N)})),[k,w]=I.useState(null),S=Tu(u.recipe),E=()=>{if(!y||n.items.filter(C=>C.kind==="fx").length>=yn.maxItems)return;const M=(k?.first??m.start)+.6,T=r?.objectBounds()[y.id]??null,N=n.items.filter(Wa).length,R=Eu(n,{target:y.id,recipe:"collapse_building",playhead:Math.min(M,Math.max(0,l.duration-.3)),bounds:T,name:`${a("Sập toà nhà")} ${N+1}`,params:{chunks:Number(u.chunks)}}),A={...R.item,fx:{...R.item.fx,seed:h.seed}};o(()=>({...R.stage,items:R.stage.items.map(C=>C.id===A.id?A:C)})),i(A.id)};I.useEffect(()=>{const M=()=>w(r?.fx?.mixStats?.(s*l.duration).find(N=>N.id===e.id)??null);M();const T=window.setInterval(M,500);return()=>window.clearInterval(T)},[r,e.id,s,l.duration,n.revision]);const j=()=>{const M=y&&r?.objectBounds()[y.id];if(!M||l.duration<=0)return;const T=Number(u.radius)*e.scale[0]+Number(u.falloff)+.3,N=tn((M.min[1]+M.max[1])/2),R=tn((M.min[2]+M.max[2])/2),A=Math.min(1,m.start/l.duration),C=Math.min(1,(m.start+m.duration)/l.duration);o(O=>{const B={...O,shots:O.shots.map(D=>D.id===O.activeShot?{...D,objectKeys:{...D.objectKeys,[e.id]:[]}}:D)};return Co(Co(B,e.id,A,[tn(M.min[0]-T),N,R]),e.id,C,[tn(M.max[0]+T),N,R])})};return t.jsxs("div",{className:"shot-fx-inspector shot-mixfx-inspector","aria-label":a("Chỉnh Mix FX"),children:[t.jsxs("h3",{children:[a("MIX FX")," ",t.jsxs("small",{className:"shot-total",children:["· ",e.name]})]}),t.jsx("input",{"aria-label":a("Tên Mix FX"),value:e.name,onChange:M=>o(T=>({...T,items:T.items.map(N=>N.id===e.id?{...N,name:M.target.value}:N)}))}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Mục tiêu")}),t.jsxs("select",{"aria-label":a("Mục tiêu bị phá"),value:y?.id??"",onChange:M=>g({target:M.target.value?{to:M.target.value,part:"center"}:void 0}),children:[!y&&t.jsx("option",{value:"",children:a("Chọn đối tượng…")}),p.map(M=>t.jsx("option",{value:M.id,children:M.name},M.id))]})]}),t.jsx(Ru,{value:String(u.recipe),onPick:M=>g({params:Op(M,u)},{color:Ua[M].color})}),k?.overridden&&t.jsx("p",{className:"shot-fx-hint shot-mixfx-note","data-mix":"note",children:a("Mục tiêu này đã có Mix FX “{0}” tạo trước: các Mix FX cùng mục tiêu dùng chung số mảnh và seed của nó.",[n.items.find(M=>M.id===k.lead)?.name??""])}),S?t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Sập toà nhà")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Kiểu sập")}),t.jsx("select",{"aria-label":a("Kiểu sập"),"data-mix":"mode",value:String(u.mode??"pancake"),onChange:M=>v("mode",M.target.value),children:_p.map(M=>t.jsx("option",{value:M,children:a(h1[M])},M))})]}),l1.filter(({key:M})=>M!=="yaw"||u.mode==="topple").map(({key:M,step:T})=>{const N=ec.find(R=>R.key===M);return t.jsx(No,{label:N.label??M,value:Number(u[M]??N.def),min:N.min,max:N.max,step:T,onChange:R=>v(M,M==="chunks"?Math.round(R):R)},M)})]}):t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Khối cầu & độ ảnh hưởng")}),r1.map(({key:M,step:T})=>{const N=ec.find(R=>R.key===M);return t.jsx(No,{label:N.label??M,value:Number(u[M]??N.def),min:N.min,max:N.max,step:T,onChange:R=>v(M,M==="chunks"?Math.round(R):R)},M)}),t.jsxs("label",{className:"shot-field shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a("Mất đỡ thì rơi"),"data-mix":"support",checked:u.support!=="off",onChange:M=>v("support",M.target.checked?"on":"off")}),t.jsx("span",{children:a("Mất đỡ thì rơi")})]}),t.jsxs("button",{type:"button","data-mix":"collapse-after",disabled:!y,onClick:E,children:["🏢 ",a("Thêm sập sau nổ")]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Seed & màu")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Seed")}),t.jsxs("span",{className:"shot-fx-seed",children:[t.jsx(Tn,{"aria-label":a("Seed"),value:h.seed,min:0,max:2147483647,step:1,onCommit:M=>g({seed:Math.round(M)})}),t.jsxs("button",{type:"button","aria-label":a("Đổi seed ngẫu nhiên"),title:a("Đổi seed ngẫu nhiên"),onClick:()=>g({seed:Math.floor(Math.random()*1e9)+1}),children:[t.jsx(Ce.reset,{}),a("Xáo trộn")]})]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Màu bụi / lửa")}),t.jsx("input",{type:"color","aria-label":a("Màu bụi / lửa"),value:e.color,onChange:M=>o(T=>({...T,items:T.items.map(N=>N.id===e.id?{...N,color:M.target.value}:N)}))})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Thời gian phá trong shot")}),d?t.jsxs(t.Fragment,{children:[t.jsx(No,{label:"Bắt đầu (s)",value:m.start,min:0,max:Math.max(.1,l.duration),step:.1,onChange:M=>b({start:M})}),t.jsx(No,{label:"Kéo dài (s)",value:m.duration,min:.2,max:yn.maxDuration,step:.1,onChange:M=>b({duration:M})})]}):t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>b({start:tn(s*l.duration),duration:tn(Math.max(.2,l.duration*(1-s)))}),children:a("Phát trong shot này")})]}),!S&&t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Đường đi của khối cầu")}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsxs("button",{type:"button","data-mix":"add-key",onClick:()=>o(M=>Co(M,e.id,s)),children:["+◆ ",a("Thêm điểm tại playhead")]}),t.jsx("button",{type:"button","data-mix":"sweep",disabled:!y,onClick:j,children:a("Quét ngang qua mục tiêu")})]}),f.map((M,T)=>t.jsxs("div",{className:"shot-fx-point shot-mixfx-key","data-key":M.id,children:[t.jsxs("b",{children:[(M.time*l.duration).toFixed(1),"s"]}),[0,1,2].map(N=>t.jsx(Tn,{"aria-label":a("Điểm {0} {1}",[T+1,"XYZ"[N]]),precision:2,step:.1,min:-1e3,max:1e3,value:M.position[N],onCommit:R=>{const A=[...M.position];A[N]=R,o(C=>Co(C,e.id,M.time,A,M.id))}},N)),t.jsx("button",{type:"button","aria-label":a("Xóa điểm {0}",[T+1]),onClick:()=>o(N=>({...N,shots:N.shots.map(R=>R.id===N.activeShot?{...R,objectKeys:{...R.objectKeys,[e.id]:(R.objectKeys?.[e.id]??[]).filter(A=>A.id!==M.id)}}:R)})),children:t.jsx(Ce.close,{})})]},M.id)),!f.length&&t.jsx("p",{className:"shot-fx-hint",children:a("Chưa có điểm: khối cầu đứng yên. Dời playhead, kéo khối cầu rồi bấm “Thêm điểm tại playhead”.")})]}),k&&t.jsxs("small",{className:"shot-fx-budget","data-mix-stats":`${k.broken}/${k.chunks}`,children:[a("{0} mảnh · {1} mảnh đã vỡ tại playhead · {2} sẽ vỡ",[k.chunks,k.broken,k.hit]),k.falling?a(" · {0} mảnh mất đỡ rơi xuống",[k.falling]):""]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",className:"shot-delete-item",onClick:()=>{o(M=>({...M,items:M.items.filter(T=>T.id!==e.id),shots:M.shots.map(T=>({...T,...T.objectKeys?.[e.id]?{objectKeys:Object.fromEntries(Object.entries(T.objectKeys).filter(([N])=>N!==e.id))}:{},...T.fxTiming?.[e.id]?{fxTiming:Object.fromEntries(Object.entries(T.fxTiming).filter(([N])=>N!==e.id))}:{}}))})),i(null)},children:a("Xóa {0}",[e.name])}),t.jsx("button",{type:"button",onClick:()=>i(null),children:a("+ Mix FX khác")})]})]})}let Kn=null,qs,Fo,Nr,Th=null;const Lh=new Map,Xi=new Map;let Eh=Promise.resolve(),Rh=0;const Ih=112;function m1(){const e=document.createElement("canvas");e.width=e.height=64;const n=e.getContext("2d");for(let o=0;o<8;o++)for(let i=0;i<8;i++)n.fillStyle=(i+o)%2?"#3a4148":"#262b30",n.fillRect(i*8,o*8,8,8);const s=new Wr(e);return s.colorSpace=si,s.wrapS=s.wrapT=Sd,s.repeat.set(3,3),s.magFilter=og,s}function p1(){if(Kn)return Kn;Kn=new Br({antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),Kn.outputColorSpace=si,Kn.toneMapping=kd,Kn.toneMappingExposure=1.1,Kn.setClearColor(0,0),Kn.setSize(Ih,Ih,!1),qs=new Kr;const e=new wd(Kn);Th=e.fromScene(new Ed,.04).texture,e.dispose(),qs.environment=Th;const n=new ni("#fff4e4",2.2);n.position.set(-2,3,3),qs.add(n);const s=new dt(new ai(4,4),new bs({map:m1()}));return s.position.set(0,0,-1.4),qs.add(s),Nr=new dt(new Un(.5,48,32)),qs.add(Nr),Fo=new Hr(30,1,.1,20),Fo.position.set(0,.18,2.15),Fo.lookAt(0,0,0),Kn}function f1(e){const n=p1(),s=Bp({preset:e},Za,{studio:!0});if(!s)throw new Error(`unknown material ${e}`);Nr.material=s,n.render(qs,Fo);const o=n.domElement.toDataURL("image/png");return s.dispose(),o}function g1(e){const n=Lh.get(e);if(n)return Promise.resolve(n);const s=Xi.get(e);if(s)return s;if(!qa(e))return Promise.reject(new Error(`unknown material ${e}`));const o=globalThis.__CLIPOOX_THUMB_LIMIT;if(typeof o=="number"&&Rh>=o)return Promise.reject(new Error("thumbnail limit"));Rh++;const i=Eh.then(()=>new Promise((r,l)=>setTimeout(()=>{try{const h=f1(e);Lh.set(e,h),r(h)}catch(h){l(h)}},20))).finally(()=>Xi.delete(e));return Eh=i.catch(()=>{}),Xi.set(e,i),i}const $o="application/x-clipoox-material",Fa=e=>!!e&&e.kind!=="fx"&&e.kind!=="splat",Ta=e=>e===Js?a("Cả đối tượng"):/^part-\d+/.test(e)?a("Phần {0}",[e.slice(5)]):e;function x1({preset:e,alt:n}){const[s,o]=I.useState(null),[i,r]=I.useState(!1),l=I.useRef(null);return I.useEffect(()=>{if(i||!l.current||typeof IntersectionObserver>"u"){i||r(!0);return}const h=new IntersectionObserver(u=>{u.some(m=>m.isIntersecting)&&(r(!0),h.disconnect())},{rootMargin:"120px"});return h.observe(l.current),()=>h.disconnect()},[i]),I.useEffect(()=>{if(!i)return;let h=!0;return g1(e.id).then(u=>{h&&o(u)}).catch(()=>{}),()=>{h=!1}},[i,e.id]),s?t.jsx("img",{className:"shot-mat-swatch",src:s,alt:n,draggable:!1}):t.jsx("span",{ref:l,className:"shot-mat-swatch loading",role:"img","aria-label":n,style:{background:`radial-gradient(circle at 35% 30%, #ffffff55, ${e.colors[0]} 45%, #0008 100%)`}})}function us({label:e,value:n,range:s,step:o,onInput:i,format:r}){return t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:a(e)}),t.jsx("input",{type:"range","aria-label":a(e),min:s[0],max:s[1],step:o,value:n,onChange:l=>i(Number(l.target.value))}),t.jsx("output",{children:r?r(n):n.toFixed(2)})]})}function b1({stage:e,selected:n,change:s,engine:o,setError:i,scope:r,setScope:l}){const h=rt(),[u,m]=I.useState(""),[d,f]=I.useState(""),[p,y]=I.useState(!1),[g,v]=I.useState([]),b=e.items.find(q=>q.id===n)??null,k=Fa(b),w=I.useMemo(()=>Kp(u,u.trim()?"":d),[u,d]);I.useEffect(()=>{if(!b||!k){v([]);return}const q=()=>v(o?.materialSlots(b.id)??[]);q();const pe=setTimeout(q,400),ue=setTimeout(q,1600);return()=>{clearTimeout(pe),clearTimeout(ue)}},[o,b?.id,b?.model?.gcsUri,b?.look,b?.figure,e.revision,k]),I.useEffect(()=>()=>o?.setPartPicker(null),[o]),I.useEffect(()=>{y(!1),o?.setPartPicker(null)},[n,o]);const S=g.length>1,E=r.mode==="part"&&S&&r.slot&&g.some(q=>q.slot===r.slot)?r.slot:Js,j=b?.materials?.[E]??null,M=tc(j),[T,N]=I.useState([]),R=e.items.filter(q=>q.id!==b?.id&&Fa(q)&&!q.hidden),A=T.filter(q=>R.some(pe=>pe.id===q&&!pe.locked)),C=(q,pe=b?.id,ue=E,U=!0)=>{const re=e.items.find(Ee=>Ee.id===pe);if(!re||!Fa(re)){i(a("Chọn một đối tượng (hộp, model, nhân vật…) để áp vật liệu."));return}if(re.locked){i(a("{0} đang khoá — mở khoá ở timeline để đổi vật liệu.",[re.name]));return}i("");const ce=U?A.filter(Ee=>Ee!==re.id):[];s(Ee=>ce.reduce((je,le)=>Us(je,le,Js,q),Us(Ee,re.id,ue,q)))},O=(q,pe=b?.id,ue=E)=>C({preset:q.id},pe,ue),B=()=>C({mode:"tint",params:{color:"#ffffff"}}),[D,$]=I.useState(null),W=I.useRef(null),z=I.useRef(void 0),Y=()=>{clearTimeout(z.current);const q=W.current;W.current=null,q&&($(null),s(pe=>Us(pe,q.itemId,q.slot,q.override)))};I.useEffect(()=>()=>Y(),[]);const J=`${b?.id}|${E}|${JSON.stringify(j)}`,V=D?.key===J?D.params:null,H=q=>{if(!b||!j)return;const pe={...j.params||{},...V||{},...q},ue=pa(j)?{mode:"tint",params:{color:pe.color??"#ffffff",...pe.roughness!==void 0?{roughness:pe.roughness}:{},...pe.metalness!==void 0?{metalness:pe.metalness}:{}}}:{preset:j.preset,params:pe};$({key:J,params:pe}),o?.previewMaterials(b.id,Hp(b.materials,E,ue)),W.current={itemId:b.id,slot:E,override:ue},clearTimeout(z.current),z.current=setTimeout(Y,450)},G=j&&!pa(j)?V?tc({preset:j.preset,params:V}):M:null,_=j&&pa(j)?{...j.params,...V||{}}:null,ee=q=>{b&&(W.current=null,clearTimeout(z.current),s(pe=>Us(pe,b.id,q,null)))},Q=()=>{b&&(W.current=null,clearTimeout(z.current),s(q=>({...q,items:q.items.map(pe=>{if(pe.id!==b.id)return pe;const{materials:ue,...U}=pe;return U})})))},ve=()=>{if(!(!o||!b)){if(p){o.setPartPicker(null),y(!1);return}y(!0),o.setPartPicker((q,pe)=>{y(!1);const ue=e.items.find(U=>U.id===q);if(q!==b.id){ue&&Fa(ue)&&!ue.locked&&i(a("Phần đó thuộc {0} — chọn đối tượng ấy trước.",[ue.name]));return}i(""),l({mode:"part",slot:pe})})}},ye=Object.entries(b?.materials||{});return t.jsxs("div",{className:"shot-mat",children:[t.jsx("div",{className:"shot-mat-target",children:b?t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:b.name}),!k&&t.jsx("small",{children:a("Đối tượng này không đổi được vật liệu.")}),b.locked&&t.jsx("small",{children:a("Đang khoá")})]}):t.jsx("small",{children:a("Chọn một đối tượng trong cảnh, rồi bấm một vật liệu. Hoặc kéo vật liệu thả lên đối tượng trong khung 3D.")})}),b&&k&&S&&t.jsxs("div",{className:"shot-mat-scope",children:[t.jsxs("div",{className:"shot-seg",role:"radiogroup","aria-label":a("Áp vật liệu cho"),children:[t.jsx("button",{type:"button",role:"radio","aria-checked":r.mode==="all",className:r.mode==="all"?"active":"",onClick:()=>l({mode:"all",slot:r.slot}),children:a("Cả đối tượng")}),t.jsx("button",{type:"button",role:"radio","aria-checked":r.mode==="part",className:r.mode==="part"?"active":"",onClick:()=>l({mode:"part",slot:r.slot&&g.some(q=>q.slot===r.slot)?r.slot:g[0].slot}),children:a("Từng phần")})]}),r.mode==="part"&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-mat-parts",role:"listbox","aria-label":a("Các phần của model"),children:g.map(({slot:q})=>{const pe=b.materials?.[q],ue=pe?qa(pe.preset):null;return t.jsxs("button",{type:"button",role:"option","data-slot":q,"aria-selected":E===q,className:E===q?"active":"",onClick:()=>l({mode:"part",slot:q}),children:[Ta(q),ue?t.jsxs("small",{children:[" · ",Ra(ue,h)]}):pa(pe)?t.jsxs("small",{children:[" · ",a("Giữ texture")]}):null]},q)})}),t.jsxs("button",{type:"button",className:`shot-mat-pick${p?" active":""}`,"aria-pressed":p,onClick:ve,children:[t.jsx(Ce.focus,{})," ",p?a("Bấm vào một phần của model… (bấm lại để huỷ)"):a("Chọn phần trên khung 3D")]})]})]}),b&&k&&!b.locked&&t.jsx("div",{className:"shot-mat-tintbar",children:t.jsxs("button",{type:"button","data-mat":"tint",className:_?"active":"","aria-pressed":!!_,onClick:()=>_?ee(E):B(),title:a("Giữ texture gốc của phần này, chỉ đổi màu (và độ nhám / kim loại nếu muốn)"),children:["🎨 ",a("Giữ texture gốc, chỉ đổi màu")]})}),b&&k&&_&&t.jsxs("section",{className:"shot-mat-tweak","aria-label":a("Chỉnh vật liệu"),"data-mat":"tint-panel",children:[t.jsxs("div",{className:"shot-mat-tweak-head",children:[t.jsx("strong",{children:a("Giữ texture gốc, chỉ đổi màu")}),t.jsxs("small",{children:[" · ",Ta(E)]}),t.jsxs("button",{type:"button",className:"shot-mat-reset",onClick:()=>ee(E),title:a("Đặt lại vật liệu gốc"),children:[t.jsx(Ce.reset,{})," ",a("Đặt lại vật liệu gốc")]})]}),t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:a("Màu nhân")}),t.jsx("input",{type:"color","aria-label":a("Màu nhân"),value:_.color,onChange:q=>H({color:q.target.value})}),t.jsx("output",{children:_.color})]}),t.jsx(us,{label:"Độ nhám",value:_.roughness??.5,range:As.roughness,step:.01,onInput:q=>H({roughness:q}),format:q=>_.roughness===void 0?a("gốc"):q.toFixed(2)}),t.jsx(us,{label:"Độ kim loại",value:_.metalness??0,range:As.metalness,step:.01,onInput:q=>H({metalness:q}),format:q=>_.metalness===void 0?a("gốc"):q.toFixed(2)})]}),b&&k&&R.length>0&&t.jsxs("details",{className:"shot-mat-also",open:A.length>0,children:[t.jsx("summary",{children:a("Áp cho cả: {0} đối tượng khác",[A.length])}),t.jsx("div",{className:"shot-mat-also-list",role:"group","aria-label":a("Áp cho nhiều đối tượng"),children:R.map(q=>t.jsxs("label",{className:q.locked?"is-locked":"",children:[t.jsx("input",{type:"checkbox","data-also":q.id,disabled:q.locked,checked:A.includes(q.id),onChange:pe=>N(ue=>pe.target.checked?[...ue.filter(U=>U!==q.id),q.id]:ue.filter(U=>U!==q.id))}),q.name]},q.id))}),t.jsx("small",{className:"shot-fx-hint",children:a("Bấm một vật liệu: {0} và các đối tượng đã đánh dấu đổi cùng lúc (một bước hoàn tác).",[b.name])})]}),b&&k&&j&&G&&t.jsxs("section",{className:"shot-mat-tweak","aria-label":a("Chỉnh vật liệu"),children:[t.jsxs("div",{className:"shot-mat-tweak-head",children:[t.jsx("strong",{children:Ra(G.preset,h)}),t.jsxs("small",{children:[" · ",Ta(E)]}),t.jsxs("button",{type:"button",className:"shot-mat-reset",onClick:()=>ee(E),title:a("Đặt lại vật liệu gốc"),children:[t.jsx(Ce.reset,{})," ",a("Đặt lại vật liệu gốc")]})]}),t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:a("Màu")}),t.jsx("input",{type:"color","aria-label":a("Màu vật liệu"),value:G.color,onChange:q=>H({color:q.target.value})}),t.jsx("output",{children:G.color})]}),t.jsx(us,{label:"Độ nhám",value:G.roughness,range:As.roughness,step:.01,onInput:q=>H({roughness:q})}),t.jsx(us,{label:"Độ kim loại",value:G.metalness,range:As.metalness,step:.01,onInput:q=>H({metalness:q})}),!G.preset.mapless&&t.jsxs(t.Fragment,{children:[t.jsx(us,{label:"Cỡ vân",value:G.scale,range:[.1,5],step:.05,onInput:q=>H({scale:q}),format:q=>`×${q.toFixed(2)}`}),t.jsx(us,{label:"Xoay vân",value:G.rotation,range:As.rotation,step:1,onInput:q=>H({rotation:q}),format:q=>`${Math.round(q)}°`})]}),t.jsx(us,{label:"Phát sáng",value:G.emissive,range:As.emissive,step:.1,onInput:q=>H({emissive:q}),format:q=>q.toFixed(1)}),t.jsx(us,{label:G.preset.transmission?"Độ đục (kính)":"Độ đặc",value:G.opacity,range:As.opacity,step:.01,onInput:q=>H({opacity:q})})]}),t.jsx("div",{className:"shot-fx-search",children:t.jsx("input",{type:"search","aria-label":a("Tìm vật liệu"),placeholder:a("Tìm vật liệu… (vd: go, kinh, thep)"),value:u,onChange:q=>m(q.target.value)})}),t.jsxs("div",{className:"shot-fx-cats shot-mat-cats",role:"tablist","aria-label":a("Nhóm vật liệu"),children:[t.jsx("button",{type:"button",role:"tab","aria-selected":!d&&!u.trim(),className:!d&&!u.trim()?"active":"",onClick:()=>{f(""),m("")},children:a("Tất cả")}),ad.map(q=>t.jsx("button",{type:"button",role:"tab","aria-selected":d===q.id&&!u.trim(),className:d===q.id&&!u.trim()?"active":"",onClick:()=>{f(q.id),m("")},children:h==="en"?q.en:q.vi},q.id))]}),t.jsxs("div",{className:"shot-mat-grid",children:[w.map(q=>{const pe=Ra(q,h),ue=j?.preset===q.id;return t.jsxs("button",{type:"button",className:`shot-mat-card${ue?" active":""}`,"data-material":q.id,draggable:!0,"aria-pressed":ue,title:b&&k?a("Áp {0} cho {1}",[pe,b.name]):pe,onDragStart:U=>{U.dataTransfer.setData($o,q.id),U.dataTransfer.effectAllowed="copy"},onClick:()=>O(q),children:[t.jsx(x1,{preset:q,alt:pe}),t.jsx("span",{children:pe})]},q.id)}),!w.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có vật liệu nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:a("Bấm để áp cho đối tượng đang chọn, hoặc kéo thả lên một đối tượng trong khung 3D. Ở chế độ Từng phần, thả lên phần nào thì áp cho phần đó.")}),b&&ye.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("h3",{children:[a("Vật liệu đang dùng")," ",t.jsxs("small",{className:"shot-total",children:["· ",ye.length]})]}),t.jsx("div",{className:"shot-list shot-mat-list",children:ye.map(([q,pe])=>{const ue=qa(pe.preset);return t.jsxs("div",{className:q===E?"active":"",children:[t.jsxs("button",{type:"button",onClick:()=>l(q===Js?{mode:"all",slot:r.slot}:{mode:"part",slot:q}),children:[Ta(q),t.jsxs("small",{className:"shot-list-meta",children:[" · ",ue?Ra(ue,h):pa(pe)?a("Giữ texture · {0}",[pe.params.color]):pe.preset]})]}),t.jsx("button",{type:"button",className:"shot-delete-item","aria-label":a("Đặt lại {0}",[Ta(q)]),title:a("Đặt lại vật liệu gốc"),onClick:()=>ee(q),children:t.jsx(Ce.reset,{})})]},q)})}),t.jsxs("button",{type:"button",className:"shot-mat-reset-all",onClick:Q,children:[t.jsx(Ce.reset,{})," ",a("Đặt lại tất cả vật liệu gốc")]})]})]})}function tl({pose:e}){rt();const n=(h,u,m,d,f,p,y,g=0)=>{const v=(m+y*g*.34)*Math.PI/180,b=(m-d+y*g*.22)*Math.PI/180,k=[h+Math.sin(v)*f,u+Math.cos(v)*f];return{joint:k,end:[k[0]+Math.sin(b)*p,k[1]+Math.cos(b)*p]}},s=n(35,38,e.shoulderL,e.elbowL,21,19,-1,e.shoulderOutL),o=n(55,38,e.shoulderR,e.elbowR,21,19,1,e.shoulderOutR),i=n(40,66,e.hipL,e.kneeL,25,23,-1,e.hipOutL),r=n(50,66,e.hipR,e.kneeR,25,23,1,e.hipOutR),l=(h,u,m,d)=>t.jsxs("g",{children:[t.jsx("path",{d:`M${h} L${u} L${m}`}),t.jsx("circle",{cx:u[0],cy:u[1],r:"2.8"}),t.jsx("circle",{cx:m[0],cy:m[1],r:"3.2"})]},d);return t.jsx("svg",{className:"shot-rig-thumb",viewBox:"0 0 90 115","aria-hidden":"true",children:t.jsxs("g",{transform:`rotate(${e.lean*.25} 45 62)`,children:[l([35,38],s.joint,s.end,"la"),l([55,38],o.joint,o.end,"ra"),t.jsx("path",{className:"shot-rig-torso",d:"M34 35 Q45 29 56 35 L53 64 Q45 70 37 64Z"}),t.jsx("ellipse",{cx:"45",cy:"20",rx:"9",ry:"11",transform:`rotate(${e.head} 45 20)`}),l([40,66],i.joint,i.end,"ll"),l([50,66],r.joint,r.end,"rl")]})})}const y1=["person","prop","box","sphere","cylinder","model"],v1=[["snap","Nhịp dứt khoát (giữ dáng)"],["anticipation","Lấy đà & dư chấn"],["exaggerate","Cường điệu tư thế"],["squash","Co giãn (squash & stretch)"],["smear","Vệt nhoè khi nhanh"]];function j1({item:e,shot:n,playhead:s,patchItem:o,change:i}){rt();const r=Wp(e.toon),l=!!r?.on,h=r??{...Gp,on:!1},u=p=>o(e.id,{toon:{...h,...p}}),m=e.kind==="prop"&&e.prop?.kind==="ball",d=e.ball?.restitution??qp.restitution,f=()=>i(p=>({...p,shots:p.shots.map(y=>y.id===n.id?{...y,ball:{...y.ball,[e.id]:[...(y.ball?.[e.id]||[]).filter(g=>g.t<s*y.duration-1e-6),{t:Math.round(s*y.duration*1e3)/1e3,kind:"launch",from:[...e.position],vel:[0,0,0]}]}}:y)}));return t.jsxs("div",{className:"shot-toon","data-testid":"shot-toon",children:[t.jsx("h3",{children:a("HOẠT HÌNH / CARTOON")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a("Phong cách hoạt hình"),checked:l,onChange:p=>u({on:p.target.checked})}),t.jsx("span",{children:a("Phong cách hoạt hình")})]}),t.jsxs("label",{className:`shot-joint${l?"":" is-off"}`,children:[t.jsx("span",{className:"shot-toon-name",children:a("Mức cường điệu")}),t.jsxs("span",{children:[Math.round(h.amount*100),"%"]}),t.jsx("input",{"aria-label":a("Mức cường điệu"),type:"range",min:0,max:1,step:.05,value:h.amount,disabled:!l,onChange:p=>u({amount:+p.target.value})})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a("Hình nhảy cách (on twos)"),checked:h.twos,disabled:!l,onChange:p=>u({twos:p.target.checked})}),t.jsx("span",{children:a("Hình nhảy cách (on twos)")})]}),t.jsxs("details",{className:"shot-toon-more",children:[t.jsx("summary",{children:a("Chi tiết nguyên lý")}),t.jsx("div",{className:"shot-toon-flags",children:v1.map(([p,y])=>t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a(y),checked:h[p],disabled:!l,onChange:g=>u({[p]:g.target.checked})}),t.jsx("span",{children:a(y)})]},p))})]}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-joint",children:[t.jsx("span",{className:"shot-toon-name",children:a("Độ nảy")}),t.jsxs("span",{children:[Math.round(d*100),"%"]}),t.jsx("input",{"aria-label":a("Độ nảy"),type:"range",min:.3,max:.95,step:.01,value:d,onChange:p=>o(e.id,{ball:{...e.ball,restitution:+p.target.value}})})]}),t.jsx("button",{type:"button",onClick:f,children:a("Thả bóng nảy từ đây")})]}),t.jsx("small",{className:"shot-hint",children:a("Lấy đà trước cú bật, dư chấn khi dừng, dáng giữ dứt khoát, co giãn khi bật / tiếp đất. Tính theo thời gian nên xem trước và video xuất giống hệt; key gốc không bị đổi.")})]})}const k1=[{id:"moment",label:"Quanh khung này",hint:"Hoà vào trước và sau khung hình hiện tại"},{id:"span",label:"Cả khối động tác",hint:"Cả động tác đang phát tại playhead"},{id:"after",label:"Từ đây đến hết",hint:"Từ playhead đến cuối shot"}],ms=e=>(Number(e)||0).toFixed(1),Ph=()=>crypto.randomUUID(),w1=(e,n)=>(e||[]).find(s=>n>=s.start-.001&&n<=s.end+.001)??null;function M1({shot:e,item:n,playhead:s,change:o,engine:i,seek:r}){const l=rt(),h=l==="en",u=e.motionEdits?.[n.id]||[],m=w1(e.clipSpans?.[n.id],s),[d,f]=I.useState("moment"),[p,y]=I.useState(Rs.default),[g,v]=I.useState(!1),[b,k]=I.useState("handR"),[w,S]=I.useState(null),E=u.find(C=>C.id===w)??null,j=(C=d)=>C==="span"&&m?{scope:"span",start:m.start,end:m.end,fade:p}:C==="after"?{scope:"after",start:s,end:s,fade:p}:{scope:C==="span"?"moment":C,start:s,end:s,fade:p},M=C=>o(O=>({...O,shots:O.shots.map(B=>B.id===e.id?{...B,motionEdits:{...B.motionEdits,[n.id]:gd(B.motionEdits?.[n.id],C,B.duration)}}:B)})),T=C=>{o(O=>({...O,shots:O.shots.map(B=>B.id===e.id?{...B,motionEdits:{...B.motionEdits,[n.id]:(B.motionEdits?.[n.id]||[]).filter(D=>D.id!==C)}}:B)})),w===C&&S(null)},N=(C,O)=>{if(E){M({...E,...C});return}const B=Ph();S(B),M({id:B,...j(),label:O,...C})},R=I.useRef({reach:j,write:M,setSelId:S,setPart:k});R.current={reach:j,write:M,setSelId:S,setPart:k},I.useEffect(()=>{if(i){if(!g){i.editTool&&!i.editTool.direct&&i.setEditTool(null);return}i.setEditTool({personId:n.id,part:b,draft:(C,O)=>({id:"__drag",...R.current.reach(O==="hips"&&d==="moment"?"after":d),...C}),commit:(C,O)=>{const B=Ph(),D=R.current;D.setSelId(B),D.write({id:B,...D.reach(O==="hips"&&d==="moment"?"after":d),label:a(Ko[O]),...C})},select:C=>R.current.setPart(C)})}},[i,g,n.id,b,d,p]),I.useEffect(()=>()=>{i&&!i.editTool?.direct&&i.setEditTool(null)},[i]);const A=C=>E?.stance?.[C]??0;return t.jsxs("section",{className:"shot-motion-edit","data-motion-edit":!0,children:[t.jsxs("h3",{children:[a("SỬA CHUYỂN ĐỘNG"),t.jsx("small",{children:a("{0} chỉnh",[u.length])})]}),t.jsxs("p",{className:"shot-hint",children:[m?a("Đang ở khối “{0}” {1}–{2}s",[m.label,ms(m.start),ms(m.end)]):a("Playhead {0}s",[ms(s)])," · ",a("Chuyển động gốc giữ nguyên, tắt chỉnh là về bản gốc.")]}),t.jsx("div",{className:"shot-seg",role:"radiogroup","aria-label":a("Phạm vi chỉnh"),children:k1.map(C=>t.jsx("button",{role:"radio","aria-checked":d===C.id,className:d===C.id?"active":"",disabled:C.id==="span"&&!m,title:a(C.hint),onClick:()=>f(C.id),children:a(C.label)},C.id))}),t.jsxs("label",{className:"shot-joint",children:[a("Độ mềm (hoà vào/ra)")," ",t.jsxs("span",{children:[p.toFixed(2),"s"]}),t.jsx("input",{"aria-label":a("Độ mềm (hoà vào/ra)"),type:"range",min:Rs.min,max:1.2,step:.05,value:p,onChange:C=>y(+C.target.value)})]}),t.jsx("h4",{children:a("Kéo trên nhân vật")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:g,onChange:C=>v(C.target.checked)}),a("Hiện tay cầm để kéo tay, chân, hông")]}),g&&t.jsx("div",{className:"shot-edit-parts",children:Up.map(C=>t.jsx("button",{"data-edit-part":C,className:b===C?"active":"",onClick:()=>k(C),children:a(Ko[C])},C))}),g&&t.jsx("small",{className:"shot-hint",children:b==="hips"?a("Kéo ngang để dời vị trí, kéo xuống để hạ trọng tâm (chân vẫn bám đất)."):a("Kéo chấm sáng: khớp vai, khuỷu, hông, gối tự xoay theo (IK).")}),t.jsx("h4",{children:a("Dáng đứng mẫu")}),t.jsx("div",{className:"shot-stance-grid",children:Xp.map(C=>t.jsx("button",{"data-stance":C.id,className:E?.preset?.id===C.id?"active":"",onClick:()=>N({preset:{id:C.id,amount:E?.preset?.amount??.7}},h?C.nameEn:C.name),children:h?C.nameEn:a(C.name)},C.id))}),E?.preset&&t.jsxs("label",{className:"shot-joint",children:[a("Độ mạnh dáng mẫu")," ",t.jsxs("span",{children:[Math.round(E.preset.amount*100),"%"]}),t.jsx("input",{"aria-label":a("Độ mạnh dáng mẫu"),type:"range",min:0,max:1,step:.05,value:E.preset.amount,onChange:C=>N({preset:{...E.preset,amount:+C.target.value}},"")})]}),t.jsx("h4",{children:a("Chỉnh nhanh")}),Vp.map(C=>t.jsxs("label",{className:"shot-joint",children:[h?C.nameEn:a(C.name)," ",t.jsx("span",{children:C.max===1?`${Math.round(A(C.id)*100)}%`:`${A(C.id)}°`}),t.jsx("input",{"aria-label":h?C.nameEn:a(C.name),"data-stance-slider":C.id,type:"range",min:C.min,max:C.max,step:C.step,value:A(C.id),onChange:O=>N({stance:{...E?.stance||{},[C.id]:+O.target.value}},h?C.nameEn:C.name)})]},C.id)),t.jsxs("div",{className:"shot-edit-move",children:[[["Dời ngang (m)",0],["Dời tới / lui (m)",2]].map(([C,O])=>t.jsxs("label",{className:"shot-joint",children:[a(C)," ",t.jsx("span",{children:(E?.move?.[O]??0).toFixed(2)}),t.jsx("input",{"aria-label":a(C),type:"range",min:-2,max:2,step:.02,value:E?.move?.[O]??0,onChange:B=>{const D=[...E?.move??[0,0,0]];D[O]=+B.target.value,N({move:D},a("Vị trí"))}})]},C)),t.jsxs("label",{className:"shot-joint",children:[a("Xoay hướng")," ",t.jsxs("span",{children:[E?.turn??0,"°"]}),t.jsx("input",{"aria-label":a("Xoay hướng"),type:"range",min:-180,max:180,step:1,value:E?.turn??0,onChange:C=>N({turn:+C.target.value},a("Hướng"))})]})]}),t.jsx("h4",{children:a("Các chỉnh đã có")}),!u.length&&t.jsx("small",{className:"shot-hint",children:a("Chưa có chỉnh nào. Kéo tay cầm hoặc chọn dáng mẫu / thanh trượt để bắt đầu.")}),t.jsx("ul",{className:"shot-edit-list",children:u.map(C=>{const O=Yp(C),B=O?0:Qp(C,s);return t.jsxs("li",{className:`${C.id===w?"active":""} ${C.off?"off":""} ${O?"broken":""}`,children:[t.jsxs("button",{className:"shot-edit-pick",onClick:()=>{S(C.id===w?null:C.id),r(Number(C.start)||0)},title:O?a("Chỉnh này bị lỗi dữ liệu nên đã được bỏ qua — xoá nó và chỉnh lại"):a("Chọn chỉnh này và tua tới"),children:[t.jsxs("b",{children:[O?"⚠ ":"",C.label||a("Chỉnh")]}),t.jsx("small",{children:C.scope==="span"?`${ms(C.start)}–${ms(C.end)}s`:C.scope==="after"?a("từ {0}s",[ms(C.start)]):`${ms(C.start)}s ±${(Number(C.fade)||0).toFixed(1)}`}),t.jsx("i",{className:"shot-edit-weight",style:{width:`${Math.round(B*100)}%`},"aria-hidden":!0})]}),t.jsx("button",{title:C.off?a("Bật"):a("Tắt (xem bản gốc)"),"aria-pressed":!C.off,onClick:()=>M({...C,off:!C.off}),children:C.off?"○":"●"}),t.jsx("button",{title:a("Xoá chỉnh"),onClick:()=>T(C.id),children:"✕"})]},C.id)})}),E&&t.jsx("button",{className:"shot-edit-new",onClick:()=>S(null),children:a("+ Chỉnh mới tại {0}s",[ms(s)])})]})}const Fh=[{id:"moment",label:"Quanh khung này",hint:"Hoà vào trước và sau khung hình hiện tại"},{id:"span",label:"Cả khối động tác",hint:"Cả động tác đang phát tại playhead"},{id:"after",label:"Từ đây đến hết",hint:"Từ playhead đến cuối shot"},{id:"range",label:"Vùng key",hint:"Một lần chỉnh áp cho mọi key trong vùng đã chọn"},{id:"key",label:"Key tại khung này",hint:"Mỗi lần kéo sửa key tại playhead (tạo key nếu chưa có); giữa các key chuyển động tự nội suy (I: đặt key)"}],S1=[{id:"free",icon:"✋",label:"✋ Kéo tự do",hint:"Kéo tay cầm theo mặt màn hình (phím F)"},{id:"move",icon:"✥",label:"✥ Di chuyển",hint:"Bấm một tay cầm rồi kéo mũi tên: chỉ đi theo một hướng (phím G)"},{id:"rotate",icon:"⟳",label:"⟳ Xoay",hint:"Bấm một tay cầm rồi kéo vòng xoay: khuỷu tay xoay cả cánh tay, đầu gối xoay cả chân (phím R)"}],C1=(e,n)=>(e||[]).find(s=>n>=s.start-.001&&n<=s.end+.001)??null,N1=(e,n)=>!!(e.objectKeys?.[n]?.length||e.clipSpans?.[n]?.length);function A1({engine:e,stage:n,shot:s,item:o,playhead:i,change:r,onDone:l}){rt();const h=C1(s.clipSpans?.[o.id],i),[u,m]=I.useState(()=>N1(s,o.id)?"moment":"after"),[d,f]=I.useState("free"),[p,y]=I.useState(()=>Math.max(0,+(i-1).toFixed(2))),[g,v]=I.useState(()=>Math.min(s.duration,+(i+1).toFixed(2))),b={start:Math.max(0,Math.min(p,g)),end:Math.min(s.duration,Math.max(p,g))},[k,w]=I.useState(!1),[S,E]=I.useState(0),[j,M]=I.useState([]),[T,N]=I.useState(null),[R,A]=I.useState(null),[C,O]=I.useState(!0),[B,D]=I.useState(!0),$=P=>P==="key"?{scope:"moment",start:i,end:i,fade:Rs.default}:P==="range"&&b.end-b.start>.05?{scope:"span",start:b.start,end:b.end,fade:Rs.default}:P==="range"?{scope:"moment",start:i,end:i,fade:Rs.default}:P==="span"&&h?{scope:"span",start:h.start,end:h.end,fade:Rs.default}:{scope:P==="span"?"moment":P,start:i,end:i,fade:Rs.default},W=P=>r(te=>({...te,shots:te.shots.map(Z=>Z.id===s.id?{...Z,motionEdits:{...Z.motionEdits,[o.id]:gd(Z.motionEdits?.[o.id],P,Z.duration)}}:Z)})),z=i/Math.max(1e-6,s.duration),Y=(P,te)=>{const Z=s.objectKeys?.[o.id];r(ie=>({...ie,shots:ie.shots.map(me=>me.id===s.id?tf(me,ie.items.find(Fe=>Fe.id===o.id)??o,z,P??{},te):me)})),M(ie=>[...ie,{kind:"key",prev:Z}])},J=(P,te,Z=u)=>{if(Z==="key"&&!P.stance&&!P.track&&!P.turn&&!P.preset){Y(P.pose,P.move);return}const ie=crypto.randomUUID();W({id:ie,...$(Z),label:te,...P}),M(me=>[...me,{kind:"edit",id:ie}])},V=()=>{const P=j.at(-1);P&&(P.kind==="key"?r(te=>({...te,shots:te.shots.map(Z=>Z.id===s.id?{...Z,objectKeys:{...Z.objectKeys,[o.id]:P.prev??[]}}:Z)})):r(te=>({...te,shots:te.shots.map(Z=>Z.id===s.id?{...Z,motionEdits:{...Z.motionEdits,[o.id]:(Z.motionEdits?.[o.id]||[]).filter(ie=>ie.id!==P.id)}}:Z)})),M(te=>te.slice(0,-1)))},H=Zp(s,o.id,z),[G,_]=I.useState(.5),ee=()=>{const P=s.objectKeys?.[o.id],te=nc(s,n.items.find(Z=>Z.id===o.id)??o,z,G);te&&(r(Z=>({...Z,shots:Z.shots.map(ie=>ie.id===s.id?te:ie)})),M(Z=>[...Z,{kind:"key",prev:P}]))},Q=!!nc(s,o,z,.5),[ve,ye]=I.useState(!1),[q,pe]=I.useState(!1),[ue,U]=I.useState("");I.useEffect(()=>{let P=!0;return nn(()=>import("./api-CZoVJ9Fy.js").then(te=>te.bZ),__vite__mapDeps([5,1,4,3])).then(te=>te.shotInbetweenInfo()).then(te=>{P&&ye(te.available)}),()=>{P=!1}},[]);const re=async()=>{if(!q){pe(!0),U("");try{const P=await nn(()=>import("./aiInbetween-De98iM4m.js"),__vite__mapDeps([18,1,6,2,3,4,5,7,8,9,10,11,12,13,14,15,16])),te=s.objectKeys?.[o.id],Z=await P.aiInbetween(n,o.id,{at:z},await P.editorInbetweenDeps());r(()=>Z.stage),M(ie=>[...ie,{kind:"key",prev:te}])}catch(P){U(P.message||a("Không tạo được chuyển động nối"))}finally{pe(!1)}}},[ce,Ee]=I.useState(0),je=P=>{if(!e||!T||!T.startsWith("foot")||!P)return;const te=e.rollFootAt(i,o.id,T,P,Z=>({id:"__drag",...$(u),...Z}));te&&J(te.fields,`${a("Cuộn bàn chân")} ${P>0?"+":""}${P}°`),Ee(0)},le=P=>P==="hips"&&u==="moment"?"after":u,Le=I.useRef({reach:$,add:J,scopeOf:le,setSel:N,writeKey:Y});Le.current={reach:$,add:J,scopeOf:le,setSel:N,writeKey:Y},I.useEffect(()=>{if(e)return e.setEditTool({personId:o.id,part:null,parts:Jp,direct:!0,mode:d,lockFeet:B,draft:(P,te)=>({id:"__drag",...Le.current.reach(Le.current.scopeOf(te)),...P}),commit:(P,te)=>{const Z=Mi(te);Le.current.add(P,Z?aa()!=="en"?Z.vi:Z.en:a(Ko[te]),Le.current.scopeOf(te))},select:P=>Le.current.setSel(P),hover:P=>A(P)}),()=>{e.editTool?.direct&&e.setEditTool(null)}},[e,o.id,d,B]);const Ae=I.useRef(T);Ae.current=T,I.useEffect(()=>{Ae.current&&e?.selectPosePart(Ae.current)},[e,d]);const we=P=>{N(P),e?.selectPosePart(P)},he=()=>Le.current.writeKey(),ke=I.useRef({pick:we,sel:T,insertKey:he,breakdown:ee});ke.current={pick:we,sel:T,insertKey:he,breakdown:ee},I.useEffect(()=>{const P=te=>{const Z=te.target;if(te.metaKey||te.ctrlKey||te.altKey||Z&&(Z.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Z.tagName)))return;const ie=te.key.toLowerCase(),me=ie==="g"?"move":ie==="r"?"rotate":ie==="f"?"free":null;if(me){te.preventDefault(),te.stopImmediatePropagation(),f(me);return}if((ie==="i"||ie==="k")&&!te.shiftKey){te.preventDefault(),te.stopImmediatePropagation(),ke.current.insertKey();return}if(ie==="e"&&te.shiftKey){te.preventDefault(),te.stopImmediatePropagation(),ke.current.breakdown();return}te.key==="Tab"&&(te.preventDefault(),te.stopImmediatePropagation(),ke.current.pick(nf(Mi(ke.current.sel??"")?.id??null,te.shiftKey?-1:1).part))};return window.addEventListener("keydown",P,!0),()=>window.removeEventListener("keydown",P,!0)},[]);const Pe=aa()!=="en",Te=Mi(R??T??"");I.useEffect(()=>{if(e)return e.setFocusLock(o.id),()=>e.setFocusLock(null)},[e,o.id]);const Be=()=>ys(n.items.find(P=>P.id===o.id)??o,s,i/Math.max(1e-6,s.duration),n.items).pose,ze=(P,te)=>{const Z=sf(Be(),P,te);Z&&Object.keys(Z).length&&J({pose:Z},`${a(Ko[`hand${P}`])}: ${a(Si[te].name)}`)},Ke=T==="handL"||T==="handR"?T.slice(-1):null,Je=P=>{const te=Be(),Z=qn[P],ie={};for(const[me,Fe]of Object.entries(Z))if(typeof Fe=="number"&&Number.isFinite(Fe)){const be=Fe-(typeof te[me]=="number"?te[me]:0);Math.abs(be)>.01&&(ie[me]=Math.round(be*100)/100)}Object.keys(ie).length&&J({pose:ie},a(P))};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-pose-banner shot-pose-bar",role:"toolbar","aria-label":a("Chỉnh dáng"),children:[t.jsx("span",{className:"shot-pose-who",title:a("Kéo các tay cầm để chỉnh dáng {0}",[o.name]),children:o.name}),t.jsx("span",{className:"shot-pose-control","aria-live":"polite",style:Te?{color:`#${sc[Te.side].toString(16).padStart(6,"0")}`}:void 0,children:Te?`${Pe?Te.vi:Te.en} · ${Te.id}`:a("Chọn một tay cầm")}),t.jsx("button",{className:C?"active":"","aria-expanded":C,"aria-label":a("Bảng điều khiển"),title:a("Bảng điều khiển: bấm tên để chọn tay cầm (Tab: tay cầm kế tiếp)"),onClick:()=>O(P=>!P),children:"🧍"}),t.jsx("select",{"aria-label":a("Phạm vi chỉnh"),title:a(Fh.find(P=>P.id===u)?.hint??""),value:u,onChange:P=>m(P.target.value),children:Fh.map(P=>t.jsx("option",{value:P.id,disabled:P.id==="span"&&!h,children:a(P.label)},P.id))}),u==="range"&&t.jsxs("span",{className:"shot-pose-range",role:"group","aria-label":a("Vùng key"),children:[t.jsx("input",{type:"number","aria-label":a("Vùng key từ (giây)"),title:a("Đặt đầu vùng ở playhead"),min:0,max:s.duration,step:.1,value:p,onChange:P=>y(+P.target.value),onDoubleClick:()=>y(+i.toFixed(2))}),t.jsx("span",{"aria-hidden":!0,children:"–"}),t.jsx("input",{type:"number","aria-label":a("Vùng key đến (giây)"),title:a("Đặt cuối vùng ở playhead"),min:0,max:s.duration,step:.1,value:g,onChange:P=>v(+P.target.value),onDoubleClick:()=>v(+i.toFixed(2))}),"s"]}),t.jsx("div",{className:"shot-seg shot-pose-modes",role:"radiogroup","aria-label":a("Cách chỉnh"),children:S1.map(P=>t.jsx("button",{role:"radio","aria-checked":d===P.id,"aria-label":a(P.label),className:d===P.id?"active":"",title:`${a(P.label)} · ${a(P.hint)}`,onClick:()=>f(P.id),children:P.icon},P.id))}),Ke&&t.jsxs("select",{"aria-label":a("Kiểu bàn tay"),value:"",onChange:P=>{P.target.value&&ze(Ke,P.target.value)},children:[t.jsx("option",{value:"",children:a("Bàn tay…")}),Object.keys(Si).map(P=>t.jsx("option",{value:P,children:a(Si[P].name)},P))]}),t.jsx("button",{className:B?"active":"","aria-pressed":B,"aria-label":a("Khoá chân"),title:a("Khoá chân: kéo hông thì chân đứng yên, gối tự gập / duỗi (tắt: kéo hông dời cả người)"),onClick:()=>D(P=>!P),children:"🔒"}),t.jsx("button",{className:H?"active shot-pose-key":"shot-pose-key","aria-label":a("Đặt key"),title:a("Đặt key tư thế tại playhead (I)"),onClick:()=>Y(),children:"◆"}),t.jsx("button",{disabled:!Q,className:"shot-pose-breakdown","aria-label":a("Breakdown"),title:a("Breakdown: key chuyển tiếp giữa key trước và sau ({0}% về key sau) — Shift+E",[Math.round(G*100)]),onClick:ee,onWheel:P=>_(te=>Math.max(0,Math.min(1,+(te+(P.deltaY<0?.1:-.1)).toFixed(1)))),children:"◇"}),ve&&t.jsx("button",{disabled:!Q||q,className:q?"shot-pose-ai busy":"shot-pose-ai","aria-busy":q,"aria-label":a("AI nối tư thế"),title:ue?`${a("Không tạo được chuyển động nối")}: ${ue}`:a("AI nối tư thế: tạo chuyển động tự nhiên (bước chân, dồn trọng tâm, vung tay) giữa key trước và key sau playhead"),onClick:()=>void re(),children:q?"…":"AI ◆→◆"}),T?.startsWith("foot")&&t.jsxs("label",{className:"shot-pose-roll",title:a("Cuộn bàn chân: + nhón gót (kiễng chân), − kiễng mũi (tựa gót) — thả chuột để áp"),children:[t.jsx("span",{children:a("Cuộn")}),t.jsx("input",{type:"range","aria-label":a("Cuộn bàn chân"),min:-40,max:60,step:5,value:ce,onChange:P=>Ee(+P.target.value),onPointerUp:()=>je(ce),onKeyUp:P=>{P.key==="Enter"&&je(ce)}}),t.jsxs("b",{children:[ce>0?"+":"",ce,"°"]})]}),t.jsx("button",{className:k?"active":"","aria-expanded":k,"aria-label":a("Thư viện dáng"),title:a("Thư viện dáng"),onClick:()=>w(P=>!P),children:a("Dáng")}),t.jsx("button",{disabled:!j.length,"aria-label":a("Hoàn tác"),title:a("Bỏ lần chỉnh vừa rồi"),onClick:V,children:"↶"}),t.jsx("button",{className:"shot-primary",title:a("Xong (Esc)"),onClick:l,children:a("Xong")})]}),C&&t.jsx("div",{className:"shot-pose-picker",role:"group","aria-label":a("Bảng điều khiển"),children:ef.map(P=>{const te=`#${sc[P.side].toString(16).padStart(6,"0")}`,Z=T===P.part;return t.jsx("button",{"data-control":P.id,"aria-pressed":Z,className:`shot-pose-pick ${P.shape}${Z?" active":""}`,style:{gridColumn:P.picker[0]+1,gridRow:P.picker[1]+1,borderColor:te,...Z?{background:te}:{}},title:`${Pe?P.vi:P.en} (${P.id})`,onMouseEnter:()=>A(P.part),onMouseLeave:()=>A(null),onClick:()=>we(P.part),children:Pe?P.vi:P.en},P.id)})}),k&&t.jsxs("div",{className:"shot-pose-library",children:[t.jsx("div",{className:"shot-pose-tabs",role:"tablist",children:Ho.map((P,te)=>t.jsx("button",{role:"tab","aria-selected":S===te,className:S===te?"active":"",onClick:()=>E(te),children:a(P.name)},P.name))}),t.jsx("div",{className:"shot-rig-grid",children:Ho[S]?.presets.map(P=>t.jsxs("button",{title:a("Áp dáng {0} tại {1}s",[a(P),i.toFixed(1)]),onClick:()=>Je(P),children:[t.jsx(tl,{pose:qn[P]}),t.jsx("span",{children:a(P)})]},P))})]})]})}const $a=e=>aa()==="en"?e.labelEn:e.label,$h=e=>aa()==="en"?lf(e):cf(e),Dh={counter:"Quầy bếp / quầy",desk:"Bàn làm việc + ghế",table:"Bàn ăn + ghế",chair:"Ghế",door:"Cửa"},Oh=["Di chuyển","Giao tiếp","Tư thế","Võ","Phản ứng trúng đòn","Thể thao","Nhảy múa","Đời thường"],Vi=[...Oh.filter(e=>ac.includes(e)),...ac.filter(e=>!Oh.includes(e))];function Iu(e,n){if(!Or(e))return Ar(e);const s=e.keys(0),o=e.duration?n%e.duration:0;if(o<=s[0].t)return s[0].pose;for(let i=0;i<s.length-1;i++)if(o<=s[i+1].t)return df(s[i].pose,s[i+1].pose,(o-s[i].t)/Math.max(1e-6,s[i+1].t-s[i].t),s[i+1].ease);return s[s.length-1].pose}const Ar=e=>{if(e.thumb)return e.thumb;const n=e.keys(0);return n[Math.min(n.length-1,Math.floor(n.length/2))].pose},T1=()=>typeof window<"u"&&Number.isFinite(window.__CLIPOOX_THUMB_LIMIT)?Math.max(0,window.__CLIPOOX_THUMB_LIMIT):48,Jo=new Set;let Tr=0;const L1=performance.now();function Pu(e){if(e-_h>=80){_h=e;for(const n of Jo)n((e-L1)/1e3)}Tr=Jo.size?requestAnimationFrame(Pu):0}let _h=0;function Fu(e){return Jo.add(e),Tr||(Tr=requestAnimationFrame(Pu)),()=>{Jo.delete(e)}}function E1({clip:e,animate:n}){const[s,o]=I.useState(()=>Ar(e));return I.useEffect(()=>{if(!n){o(Ar(e));return}let i=!0;e.mocap&&!Or(e)&&_r(e.id).catch(()=>{});const r=Fu(l=>{i&&o(Iu(e,l))});return()=>{i=!1,r()}},[n,e]),t.jsx(tl,{pose:s})}function R1({person:e,clip:n}){const s=I.useRef(null),[o,i]=I.useState(!1);return I.useEffect(()=>{const r=s.current;if(!r||!n)return;let l;try{l=new Br({canvas:r,antialias:!0,alpha:!0})}catch{return}l.setPixelRatio(Math.min(2,window.devicePixelRatio||1)),l.setSize(r.clientWidth||220,r.clientHeight||280,!1),l.outputColorSpace=si,l.toneMapping=ig;const h=new Kr,u=new Hr(28,(r.clientWidth||220)/(r.clientHeight||280),.1,50);h.add(new Md("#e8eeff","#5e5a52",1.4));const m=new ni("#fff4e4",2.4);m.position.set(-2.5,3.5,3.5),h.add(m);const d=new dt(new rg(.9,40),new bs({color:"#1d242b"}));d.rotation.x=-Math.PI/2,h.add(d),u.position.set(1.9,1.35,4.6),u.lookAt(0,.9,0);let f=null,p=!0,y=null;const g=e?.color??"#8f9aa3",v=e?.kind==="person"?e.figure:void 0,b=e?.kind==="person"?e.look:void 0,k=S=>{if(!p)return;const E=Iu(n,S);if(E!==y){y=E,f&&(h.remove(f),f.traverse(M=>{M instanceof dt&&(M.geometry.dispose(),(Array.isArray(M.material)?M.material:[M.material]).forEach(T=>T.dispose()))})),f=hf(E,g,v,b);const j=new _t().setFromObject(f).getSize(new ae).y||1.8;f.scale.multiplyScalar(1.8/Math.max(1.2,j>2.4?j:1.8)),h.add(f)}l.render(h,u)};n.mocap&&!Or(n)&&(i(!0),_r(n.id).then(()=>{p&&i(!1)}).catch(()=>p&&i(!1))),k(0);const w=Fu(k);return()=>{p=!1,w(),f&&f.traverse(S=>{S instanceof dt&&(S.geometry.dispose(),(Array.isArray(S.material)?S.material:[S.material]).forEach(E=>E.dispose()))}),d.geometry.dispose(),d.material.dispose(),l.dispose()}},[n,e?.color,e]),t.jsxs("div",{className:"mocap-preview",children:[n?t.jsx("canvas",{ref:s,className:"mocap-preview-canvas","aria-label":a("Xem trước chuyển động trên nhân vật")}):t.jsx("div",{className:"mocap-preview-empty",children:a("Chọn một chuyển động để xem trước trên nhân vật")}),o&&t.jsx("small",{className:"shot-hint",children:a("Đang tải dữ liệu mocap…")})]})}const Yi=e=>e.meta?.pair;function I1({person:e,loop:n,mirror:s,onLoop:o,onMirror:i,onApply:r,onClose:l,playhead:h}){rt();const[u,m]=I.useState(""),[d,f]=I.useState(null),[p,y]=I.useState(null),[g,v]=I.useState(null),[b,k]=I.useState(()=>new Set),w=I.useRef(null),S=I.useRef(null);I.useEffect(()=>{S.current?.focus();const A=C=>{C.key==="Escape"&&(C.stopPropagation(),l())};return window.addEventListener("keydown",A,!0),()=>window.removeEventListener("keydown",A,!0)},[l]);const E=I.useMemo(()=>{const A=af(u),C=B=>(!d||B.group===d)&&Wo(B.meta);if(!A)return fs.filter(C).sort((B,D)=>Vi.indexOf(B.group)-Vi.indexOf(D.group));const O=new Map(of(u,{limit:120}).map(B=>[B.id,B.score]));return fs.filter(B=>O.has(B.id)&&C(B)).sort((B,D)=>(O.get(D.id)??0)-(O.get(B.id)??0))},[u,d]);I.useEffect(()=>{const A=w.current;if(!A||typeof IntersectionObserver>"u")return;const C=new IntersectionObserver(O=>k(B=>{const D=new Set(B);for(const $ of O){const W=$.target.dataset.clip;$.isIntersecting?D.add(W):D.delete(W)}return D}),{root:A,rootMargin:"80px"});return A.querySelectorAll("[data-clip]").forEach(O=>C.observe(O)),()=>C.disconnect()},[E]);const j=I.useMemo(()=>{const A=T1();return new Set(E.filter(C=>b.has(C.id)).slice(0,A).map(C=>C.id))},[E,b]),M=fs.find(A=>A.id===p)??null,T=fs.find(A=>A.id===(g??p))??null,N=A=>[A.anchor&&A.anchor.kind!=="floor"?a(Dh[A.anchor.kind]):"",...A.props.length?[a("Đạo cụ: {0}",[A.props.map(C=>a(Ia[C.prop].label)).join(", ")])]:[]].filter(Boolean).join(" · "),R=M?.meta?.src?rf[M.meta.src.license]:null;return t.jsx("div",{className:"shot-char-overlay mocap-overlay",role:"dialog","aria-modal":"true","aria-label":a("Thư viện Mocap"),onMouseDown:A=>{A.target===A.currentTarget&&l()},children:t.jsxs("div",{className:"shot-char-panel mocap-panel",ref:S,tabIndex:-1,children:[t.jsxs("header",{children:[t.jsxs("h2",{children:[a("Thư viện Mocap")," ",t.jsx("span",{className:"shot-motion-count",children:fs.filter(A=>Wo(A.meta)).length})]}),t.jsx("span",{className:"shot-char-for",children:e?a("Áp dụng cho: {0}",[e.name]):""}),t.jsx("button",{className:"shot-char-close","aria-label":a("Đóng"),onClick:l,children:"×"})]}),t.jsxs("div",{className:"mocap-body",children:[t.jsxs("div",{className:"mocap-browse",children:[t.jsxs("div",{className:"shot-char-tools",children:[t.jsx("input",{className:"shot-motion-search mocap-search",type:"search",value:u,placeholder:a("Tìm chuyển động (đấm móc, ngã, nhảy salsa, cat hanh…)"),"aria-label":a("Tìm chuyển động"),onChange:A=>m(A.target.value)}),t.jsxs("div",{className:"shot-motion-chips mocap-chips",role:"group","aria-label":a("Nhóm chuyển động"),children:[t.jsx("button",{type:"button",className:d?"":"active","aria-pressed":!d,onClick:()=>f(null),children:a("Tất cả")}),Vi.map(A=>t.jsx("button",{type:"button","data-group":A,className:d===A?"active":"","aria-pressed":d===A,onClick:()=>f(d===A?null:A),children:$h(A)},A))]})]}),E.length===0&&t.jsx("small",{className:"shot-hint mocap-empty",children:a('Không có chuyển động khớp "{0}"',[u])}),t.jsx("div",{className:"shot-motion-grid mocap-grid",ref:w,role:"listbox","aria-label":a("Chuyển động"),children:E.map(A=>t.jsxs("button",{type:"button",role:"option","aria-selected":p===A.id,"data-clip":A.id,className:`mocap-card ${p===A.id?"picked":""}`,title:`${$a(A)} · ${A.duration.toFixed(1)}s${N(A)?` · ${N(A)}`:""}`,onClick:()=>y(A.id),onDoubleClick:()=>r(A),onPointerEnter:()=>v(A.id),onPointerLeave:()=>v(C=>C===A.id?null:C),children:[t.jsx(E1,{clip:A,animate:j.has(A.id)||g===A.id}),t.jsx("span",{className:"mocap-card-name",children:$a(A)}),t.jsxs("span",{className:"mocap-card-meta",children:[A.duration.toFixed(1),"s",A.loop?` · ${a("↻ lặp")}`:"",A.mocap?" · mocap":"",Yi(A)?` · ${a("cặp đôi")}`:""]}),A.anchor&&A.anchor.kind!=="floor"||A.props.length?t.jsx("em",{children:[A.anchor&&A.anchor.kind!=="floor"?a(Dh[A.anchor.kind]):"",A.props.length?"+"+A.props.length:""].filter(Boolean).join(" ")}):null]},A.id))})]}),t.jsxs("aside",{className:"mocap-side",children:[t.jsx(R1,{person:e,clip:T}),M?t.jsxs("div",{className:"mocap-detail",children:[t.jsx("b",{children:$a(M)}),t.jsxs("small",{children:[$h(M.group)," · ",M.duration.toFixed(1),"s",M.loop?` · ${a("↻ lặp")}`:""]}),N(M)&&t.jsx("small",{children:N(M)}),Yi(M)&&t.jsx("small",{className:"mocap-pair",children:a("Clip cặp đôi với “{0}”. Áp ở đây chỉ chạy một người; nhờ Agent để đặt cả hai (play_motion partner).",[$a(fs.find(A=>A.id===Yi(M).with)??M)])}),R&&M.meta?.src&&M.meta.src.db!=="Clipoox"&&t.jsx("small",{className:"mocap-source",children:a("Nguồn: {0} (cảnh {1}) · {2}",[R.name,M.meta.src.trial,a("miễn phí, được dùng thương mại")])})]}):t.jsx("small",{className:"shot-hint",children:a("Bấm một thẻ để chọn, bấm đúp để áp ngay.")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:n,onChange:A=>o(A.target.checked)}),a("Lặp tới hết shot (đi, chạy, đứng chờ)")]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:s,onChange:A=>i(A.target.checked)}),a("Đổi tay / chân")]}),t.jsx("button",{type:"button",className:"shot-primary mocap-apply",disabled:!M,onClick:()=>M&&r(M),children:h!=null?a("Áp từ playhead ({0}s)",[h.toFixed(1)]):a("Áp từ playhead")}),t.jsx("small",{className:"shot-hint",children:a("Chuyển động có quầy / bàn / ghế / cửa sẽ đặt nhân vật vào đúng chỗ và đưa đạo cụ vào tay.")})]})]})]})})}function P1(e){rt();const[n,s]=I.useState(!1);return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"shot-mocap-lib-open",disabled:e.disabled,onClick:()=>s(!0),title:a("Mở thư viện chuyển động: {0} chuyển động, có mocap thật",[fs.filter(o=>Wo(o.meta)).length]),children:[t.jsx(Ce.person,{})," ",a("Thư viện Mocap")," ",t.jsx("span",{className:"shot-motion-count",children:fs.filter(o=>Wo(o.meta)).length})]}),n&&xd.createPortal(t.jsx(I1,{...e,onClose:()=>s(!1),onApply:o=>{s(!1),e.onApply(o)}}),document.querySelector(".shot-workspace")||document.body)]})}function $u({disabled:e,loop:n,mirror:s,onLoop:o,onMirror:i,onPlay:r,person:l,playhead:h}){return rt(),t.jsx("div",{className:"shot-motion-lib",children:t.jsx(P1,{disabled:e,loop:n,mirror:s,onLoop:o,onMirror:i,onApply:r,person:l,playhead:h})})}const F1=24;function Lr(e,n="joint"){const s=new Set((e?.joints||[]).map(o=>o.name));for(let o=1;;o++){const i=`${n}${o}`.slice(0,F1);if(!s.has(i))return i}}function zh(e,n,s,o){const i=o||Lr(e);if(!e)return ei({kind:"manual",source:"manual",joints:[{name:i,parent:null,pos:n}],seed:1});const r=[...e.joints,{name:i,parent:s&&e.joints.some(l=>l.name===s)?s:e.joints[0].name,pos:n}];return Du(e,r)}function $1(e,n){const s=e.joints.find(r=>r.name===n);if(!s)return e;const o=e.joints.filter(r=>r.name!==n).map(r=>r.parent===n?{...r,parent:s.parent}:r);if(!o.length)return null;const i=e.bones?Object.fromEntries(Object.entries(e.bones).filter(([r])=>r!==n)):void 0;return Du({...e,...i?{bones:i}:{}},o)}function D1(e,n,s){return ei({...e,joints:e.joints.map(o=>o.name===n?{...o,pos:s}:o)})}function Du(e,n){const s=ei({...e,joints:n});return s.kind!==e.kind?{...s,source:"manual"}:s}class O1{constructor(n,s){this.engine=n,this.ev=s,this.host=n.renderer.domElement.parentElement??n.renderer.domElement,this.host.addEventListener("pointerdown",this.onDown,!0),this.host.addEventListener("pointerup",this.onUp,!0),n.rigTool=this}mode="off";itemId=null;picked=null;host;down=null;get restFor(){return this.mode==="edit"||this.mode==="place"?this.itemId:null}get posing(){return this.mode==="pose"?this.itemId:null}dispose(){this.host.removeEventListener("pointerdown",this.onDown,!0),this.host.removeEventListener("pointerup",this.onUp,!0),this.engine.rigTool===this&&(this.engine.rigTool=null);const n=this.root();n&&Nc(n),this.engine.orbit.enabled=!0}set(n,s,o){this.itemId=n,this.mode=n?s:"off",this.picked=o}root(){return this.engine.objects.children.find(n=>n.userData.id===this.itemId)?.children[0]}state(){return this.root()?.userData.rig}afterSync(){const n=this.root(),s=this.state();if(!n||(Nc(n),this.mode==="off"))return;const o=this.engine.transform;if(this.mode==="place"&&o.detach(),!s)return;Ug(s,this.picked),n.updateMatrixWorld(!0);const i=this.picked?s.rig.joints.findIndex(r=>r.name===this.picked):-1;if(i<0){this.mode!=="place"&&o.detach();return}if(this.mode==="edit"){const r=s.bones[i].children.find(l=>l.userData.rigJoint===this.picked);r&&(o.attach(r),o.setMode("translate"),o.setSpace("world"))}else this.mode==="pose"&&(o.attach(s.bones[i]),o.setMode("rotate"),o.setSpace("local"))}commit(n){const s=this.state(),o=this.root(),i=this.itemId;if(!s||!o||!i)return!1;if(n.userData.rigJoint&&this.mode==="edit"){const r=o.worldToLocal(n.getWorldPosition(new ae)).toArray().map(l=>Math.round(l*1e4)/1e4);return this.ev.setRig(i,D1(s.rig,n.userData.rigJoint,r)),!0}return n.userData.rigBone&&this.mode==="pose"&&this.ev.boneKey(i,n.userData.rigBone,Xg(s,n.userData.rigBone,this.ev.pose(i))),!0}ray(n){const s=this.engine.renderer.domElement.getBoundingClientRect(),o=new yc;return o.layers.enable(1),o.setFromCamera(new ca((n.clientX-s.left)/s.width*2-1,-(n.clientY-s.top)/s.height*2+1),this.engine.camera),o}jointHit(n){const s=this.root();if(!s)return null;s.updateMatrixWorld(!0);const o=[];return s.traverse(i=>{i.userData.rigJoint&&o.push(i)}),n.intersectObjects(o,!1)[0]?.object.userData.rigJoint??null}interiorPoint(n){const s=this.root();if(!s)return null;s.updateMatrixWorld(!0);const o=[];s.traverse(f=>{f instanceof dt&&!f.userData.rigOverlay&&o.push(f)});const i=n.intersectObjects(o,!1);if(!i.length)return null;const r=i[0],l=n.ray.direction.clone(),h=new _t().setFromObject(r.object).getSize(new ae).length()+.1,u=new yc(r.point.clone().addScaledVector(l,h),l.clone().negate(),0,h-1e-4);u.layers.mask=n.layers.mask;const m=u.intersectObjects(o,!1).at(-1),d=m?r.point.clone().add(m.point).multiplyScalar(.5):r.point.clone().addScaledVector(l,.02);return s.worldToLocal(d).toArray().map(f=>Math.round(f*1e4)/1e4)}onDown=n=>{if(this.mode==="off"||n.button!==0||this.engine.transform.axis){this.down=null;return}const s=this.mode==="place"?this.jointHit(this.ray(n)):null;this.down={x:n.clientX,y:n.clientY,link:s},s&&(this.engine.orbit.enabled=!1,n.stopPropagation())};onUp=n=>{const s=this.down;if(this.down=null,!s||this.mode==="off")return;const o=this.itemId,i=this.state(),r=Math.hypot(n.clientX-s.x,n.clientY-s.y)>4;if(s.link){if(this.engine.orbit.enabled=!0,r&&o&&i){const d=this.interiorPoint(this.ray(n));if(d){const f=Lr(i.rig);this.picked=f,this.ev.setRig(o,zh(i.rig,d,s.link,f))}}else r||(this.picked=s.link,this.ev.changed());return}if(r||this.engine.transform.axis||!o)return;const l=this.ray(n),h=this.jointHit(l);if(h){this.picked=h,this.ev.changed();return}if(this.mode!=="place")return;const u=this.interiorPoint(l);if(!u)return;const m=Lr(i?.rig);this.ev.setRig(o,zh(i?.rig,u,this.picked,m)),this.picked=m}}const Bh=[["humanoid","Người","Hai tay, hai chân — khớp với thư viện chuyển động"],["quadruped","Bốn chân","Thú bốn chân, đầu hướng +Z"],["chain","Đuôi / chuỗi","Chuỗi khớp dọc cạnh dài nhất (dây, đuôi, rắn…)"],["hinge","Bản lề","Nắp hộp, cửa: phần trên xoay quanh bản lề"],["wheels","Bánh xe","Thân xe + 4 bánh xoay riêng"]],Kh=[["edit","Chỉnh khớp","Bấm khớp rồi kéo bằng gizmo di chuyển (model về tư thế gốc)"],["place","Đặt khớp","Bấm lên model để thêm khớp con của khớp đang chọn; kéo từ một khớp thả lên model để tạo xương con"],["pose","Xoay xương","Bấm khớp rồi xoay bằng vòng xoay: ghi key tại playhead"]];function _1(e){rt();const{stage:n,shot:s,selected:o,engine:i,playhead:r}=e,l=n.items.find(_=>_.id===o&&_.kind==="model"&&_.model),h=l?.rig,[u,m]=I.useState("edit"),[d,f]=I.useState(4),[p,y]=I.useState(null),[g,v]=I.useState(!1),[b,k]=I.useState(""),[w,S]=I.useState(()=>{try{return localStorage.getItem("clipoox.rig.fingers")==="1"}catch{return!1}}),E=_=>{S(_);try{localStorage.setItem("clipoox.rig.fingers",_?"1":"0")}catch{}},[,j]=I.useReducer(_=>_+1,0),M=I.useRef(null),T=I.useRef(e);T.current=e;const N=(_,ee)=>T.current.change(Q=>({...Q,items:Q.items.map(ve=>ve.id!==_?ve:ee?{...ve,rig:ee,skeleton:void 0}:(({rig:ye,...q})=>q)(ve)),...ee?{}:{shots:Q.shots.map(ve=>({...ve,objectKeys:Object.fromEntries(Object.entries(ve.objectKeys||{}).map(([ye,q])=>[ye,ye===_?q.map(pe=>(({bones:ue,...U})=>U)(pe)):q]))}))}})),R=(_,ee,Q)=>T.current.change(ve=>{const ye=ve.shots.find(je=>je.id===ve.activeShot),q=ve.items.find(je=>je.id===_),pe=ye.objectKeys?.[_]||[],ue=T.current.playhead,U=bd(pe,ue,q.rig?.bones),re=(je,le)=>{const Le=pe.find(we=>Math.abs(we.time-je)<1e-6),Ae=Wn(q,ye,je);return{...Le,id:Le?.id||yt(),time:je,position:Ae.position,rotation:Ae.rotation,scale:Ae.scale,bones:le}};let ce=[...pe];if(!pe.some(je=>je.bones)&&ue>1e-6){const je=re(0,{...q.rig?.bones||{}});ce=[...ce.filter(le=>le.id!==je.id),je]}const Ee=re(ue,{...U,[ee]:Q});return ce=[...ce.filter(je=>je.id!==Ee.id),Ee].sort((je,le)=>je.time-le.time),{...ve,shots:ve.shots.map(je=>je.id===ve.activeShot?{...je,objectKeys:{...je.objectKeys,[_]:ce}}:je)}}),A=_=>T.current.change(ee=>({...ee,items:ee.items.map(Q=>Q.id===_&&Q.rig?{...Q,rig:(({bones:ve,...ye})=>ye)(Q.rig)}:Q),shots:ee.shots.map(Q=>Q.id!==ee.activeShot?Q:{...Q,objectKeys:{...Q.objectKeys,[_]:(Q.objectKeys?.[_]||[]).map(ve=>(({bones:ye,...q})=>q)(ve))}})}));I.useEffect(()=>{if(!i)return;const _=new O1(i,{setRig:(ee,Q)=>{N(ee,Q),j()},boneKey:(ee,Q,ve)=>{R(ee,Q,ve),j()},pose:ee=>{const Q=T.current.stage,ve=Q.shots.find(q=>q.id===Q.activeShot),ye=Q.items.find(q=>q.id===ee);return ye?ys(ye,ve,T.current.playhead).pose:null},changed:()=>{j(),T.current.resync()}});return M.current=_,()=>{_.dispose(),M.current=null,T.current.resync()}},[i]),I.useEffect(()=>{const _=M.current;if(!_)return;const ee=_.itemId===l?.id&&_.mode===u&&h?.joints.some(Q=>Q.name===_.picked)?_.picked:null;_.set(l?.id??null,l?u:"off",ee),e.resync()},[i,l?.id,u,!!h]),I.useEffect(()=>Vg(()=>j()),[]),I.useEffect(()=>{let _=!0;return cg().then(ee=>{_&&y(ee)}).catch(()=>{}),()=>{_=!1}},[]),e.keys.current={del:()=>{const _=M.current;if(!_||!l?.rig||!_.picked||u!=="edit"&&u!=="place")return!1;const ee=_.picked;return _.picked=null,N(l.id,$1(l.rig,ee)),j(),!0},esc:()=>{const _=M.current;return _?.picked?(_.picked=null,j(),e.resync(),!0):!1}};const C=()=>{const _=M.current?.root();return _?Jg(_):null},O=_=>{const ee=C();if(!l||!ee||ee.isEmpty()){e.setError(a("Model chưa tải xong."));return}k(""),M.current&&(M.current.picked=null);const Q=M.current?.root(),ve=_==="humanoid"&&Q?Zg(Q):null;let ye=mf(_,{min:ee.min.toArray(),max:ee.max.toArray()},{segments:d,...ve?{tips:ve}:{}});_==="humanoid"&&w&&Q&&(ye=Ni(ye,{positions:Di(Q).positions})),N(l.id,ye),m("edit"),j()},B=()=>{const _=C();!l?.rig||!_||(N(l.id,pf(l.rig,(_.min.x+_.max.x)/2)),j())},D=async()=>{const _=M.current?.root();if(!l||!_){e.setError(a("Model chưa tải xong."));return}v(!0),k("");try{const ee=sx(_),Q=await hg({requestId:yt(),front:ee.front,side:ee.side,name:l.name});if(!Q.humanoid||!Q.landmarks||!Q.landmarks.humanoid){k(a("AI không thấy hình người trong model này. Không bị trừ credits — hãy chọn một mẫu bên dưới (miễn phí)."));return}let ve=ff(Q.landmarks,ee.frame);w&&(ve=Ni(ve,{positions:Di(_).positions,tips:gf(Q.landmarks,ee.frame)})),M.current&&(M.current.picked=null),N(l.id,ve),m("edit"),j(),ht.getState().toast(a("Đã gắn xương tự động · {0} credits",[Q.credits]),"ok"),Q.landmarks.facing==="away"&&k(a("Model đang quay lưng về phía trước (+Z): chuyển động sẽ đi lùi. Xoay model 180° trong file gốc để chạy đúng hướng."))}catch(ee){k(ee.message||a("Gắn xương AI gặp lỗi."))}finally{v(!1)}},$=()=>{const _=M.current?.root();!l?.rig||!_||(M.current&&(M.current.picked=null),N(l.id,Ci(l.rig)?xf(l.rig):Ni(l.rig,{positions:Di(_).positions})),j())},W=_=>{const ee=ar.find(ve=>ve.id===_);if(!l||!ee)return;let Q=l.pose||{};for(const ve of["L","R"])Q=yd(Q,ve,ee);e.patchItem(l.id,{pose:Q})},z=M.current?.state(),Y=M.current?.picked??null,J=uf(h),V=n.items.filter(_=>_.kind==="model"&&_.model);if(!l)return t.jsx("div",{className:"shot-rig-panel",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("p",{className:"shot-rig-empty",children:a("Chọn một model GLB để gắn xương.")}),V.length?t.jsx("div",{className:"shot-rig-models",children:V.map(_=>t.jsxs("button",{type:"button",onClick:()=>e.onSelect(_.id),children:[_.name,_.rig||_.skeleton==="native"?` · ${a("đã có xương")}`:""]},_.id))}):t.jsx("small",{className:"shot-hint",children:a("Thêm model ở tab Dựng cảnh (Nhập GLB / Thư viện 3D), rồi quay lại đây.")})]})});const H=(s.objectKeys?.[l.id]||[]).filter(_=>_.bones),G=l.model?Yg(l.model.gcsUri):null;return t.jsx("div",{className:"shot-rig-panel",children:t.jsxs("div",{className:"shot-panel-body",children:[V.length>1&&t.jsx("div",{className:"shot-rig-switch",role:"group","aria-label":a("Model khác"),children:V.filter(_=>_.id!==l.id).map(_=>t.jsxs("button",{type:"button",onClick:()=>e.onSelect(_.id),children:[_.name,_.rig||_.skeleton==="native"?` · ${a("đã có xương")}`:""]},_.id))}),t.jsxs("div",{className:"shot-rig-target",children:[t.jsx("b",{children:l.name}),t.jsx("small",{children:h?a("{0} khớp · {1}",[h.joints.length,J?a("xương người"):a(Bh.find(_=>_[0]===h.kind)?.[1]??"Gắn tay")]):a("Chưa có xương")})]}),(()=>{const _=i?.nativeSkeleton(l.id);return!_?.ok&&l.skeleton!=="native"?null:t.jsxs("div",{className:"shot-rig-native",children:[t.jsx("h3",{children:a("XƯƠNG TRONG FILE")}),l.skeleton==="native"?t.jsxs(t.Fragment,{children:[t.jsx("small",{className:"shot-hint",children:a("Đang dùng xương gốc của file ({0} xương) — chuyển động như trong Blender.",[_?.bones??"…"])}),t.jsx("button",{type:"button",onClick:()=>{T.current.change(ee=>({...ee,items:ee.items.map(Q=>Q.id===l.id?{...Q,skeleton:void 0}:Q)})),j()},children:a("Bỏ xương gốc")})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>{M.current&&(M.current.picked=null),T.current.change(ee=>({...ee,items:ee.items.map(Q=>Q.id===l.id?{...Q,rig:void 0,skeleton:"native"}:Q)})),j()},children:a("Dùng xương có sẵn trong file")}),t.jsx("small",{className:"shot-hint",children:a("File này đã gắn xương người ({0} xương). Dùng thẳng xương và trọng số gốc thay cho xương mẫu — mượt như trong Blender, miễn phí.",[_?.bones??0])})]})]})})(),t.jsx("h3",{children:a("TỰ ĐỘNG")}),t.jsx("button",{type:"button",className:"shot-primary shot-rig-auto",disabled:g||e.busy||p?.configured===!1,onClick:()=>void D(),title:a("AI nhìn model từ trước và bên hông, đặt khớp và tính trọng số. Chỉ tính phí khi gắn thành công."),children:g?a("Đang gắn xương…"):a("✦ Tự gắn xương · ≈{0} credits",[p?p.estimate.toFixed(2):"…"])}),t.jsx("small",{className:"shot-hint shot-rig-price",children:p?a("Tối đa {0} credits · hoàn lại nếu AI không nhận ra hình người hoặc lỗi.",[p.max.toFixed(2)]):a("Cho nhân vật hình người (2 tay, 2 chân).")}),b&&t.jsx("div",{className:"shot-rig-note",role:"status",children:b}),t.jsx("h3",{children:a("MẪU CÓ SẴN · MIỄN PHÍ")}),t.jsx("div",{className:"shot-rig-templates",children:Bh.map(([_,ee,Q])=>t.jsx("button",{type:"button","data-template":_,title:a(Q),onClick:()=>O(_),children:a(ee)},_))}),t.jsxs("label",{className:"shot-rig-check",children:[t.jsx("input",{type:"checkbox",checked:w,onChange:_=>E(_.target.checked)})," ",a("Thêm xương ngón tay (mẫu Người / AI)")]}),t.jsxs("label",{className:"shot-field shot-rig-segments",children:[a("Số đốt (đuôi / chuỗi)"),t.jsx("input",{"aria-label":a("Số đốt (đuôi / chuỗi)"),type:"number",min:ro.chainMin,max:ro.chainMax,value:d,onChange:_=>f(Math.max(ro.chainMin,Math.min(ro.chainMax,Math.round(+_.target.value)||4)))})]}),t.jsx("h3",{children:a("GẮN TAY")}),t.jsx("div",{className:"shot-rig-modes",role:"group","aria-label":a("Công cụ xương"),children:Kh.map(([_,ee,Q])=>t.jsx("button",{type:"button",className:u===_?"active":"","aria-pressed":u===_,title:a(Q),onClick:()=>m(_),children:a(ee)},_))}),t.jsx("small",{className:"shot-hint",children:a(Kh.find(_=>_[0]===u)[2])}),Y&&t.jsx("div",{className:"shot-rig-picked",children:a("Khớp: {0}",[Y])}),t.jsxs("div",{className:"shot-rig-actions",children:[t.jsx("button",{type:"button",disabled:!h,onClick:B,title:a("Chép nửa trái (−X) sang phải qua tâm model, tự đặt tên .L / .R"),children:a("⇆ Đối xứng L/R")}),t.jsx("button",{type:"button",disabled:!h||!Y||u==="pose",onClick:()=>e.keys.current?.del(),children:a("Xoá khớp")}),t.jsx("button",{type:"button",disabled:!h,onClick:()=>{l.model&&Qg(l.model.gcsUri),e.resync(),j()},children:a("Tính lại trọng số")}),t.jsx("button",{type:"button",disabled:!h,onClick:()=>{M.current&&(M.current.picked=null),N(l.id,null),j()},children:a("Bỏ xương")})]}),G?t.jsxs("div",{className:"shot-rig-progress",role:"status",children:[t.jsx("span",{children:G.done?a("Đã tính xong trọng số chạy nền · {0} đỉnh",[G.vertices.toLocaleString()]):a("Đang tính trọng số chạy nền… {0}% · {1} đỉnh",[Math.round(G.progress*100),G.vertices.toLocaleString()])}),t.jsx("progress",{max:100,value:Math.round(G.progress*100),"aria-label":a("Tiến độ tính trọng số")}),!G.done&&t.jsx("small",{className:"shot-hint",children:a("Vẫn chỉnh được cảnh trong lúc chờ; xuất video sẽ đợi xong.")})]}):z&&z.info.source!=="pending"&&t.jsx("small",{className:"shot-hint shot-rig-stats",children:a("{0} đỉnh · trọng số {1} ms{2}",[z.info.vertices.toLocaleString(),z.info.ms,(z.info.via==="worker"?a(" · chạy nền"):"")+(z.info.source==="disk"?a(" (đã lưu trên máy)"):z.info.cached?a(" (bộ nhớ đệm)"):"")])}),J&&h&&t.jsxs("div",{className:"shot-rig-fingers",children:[t.jsx("span",{children:Ci(h)?a("Ngón tay: 5 ngón × 3 đốt mỗi tay"):a("Chưa có xương ngón tay")}),t.jsx("button",{type:"button",onClick:$,children:Ci(h)?a("Bỏ ngón tay"):a("Thêm ngón tay")})]}),h&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:a("TẠO DÁNG & CHUYỂN ĐỘNG")}),t.jsxs("div",{className:"shot-rig-pose-keys",children:[t.jsx("button",{type:"button",onClick:()=>m("pose"),className:u==="pose"?"active":"",children:a("Xoay xương tại {0}s",[(r*s.duration).toFixed(1)])}),t.jsx("button",{type:"button",disabled:!H.length&&!h.bones,onClick:()=>A(l.id),children:a("Đặt lại dáng xương")})]}),t.jsx("small",{className:"shot-hint",children:H.length?a("{0} key xương trên timeline.",[H.length]):a("Xoay xương ghi key ngay tại playhead (Ctrl+Z để hoàn tác).")}),J?t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"shot-rig-posekey",onClick:()=>e.addPoseKey(l.id),children:a("◇ Key tư thế tại {0}s",[(r*s.duration).toFixed(1)])}),t.jsxs("div",{className:"shot-rig-hands",role:"group","aria-label":a("Dáng tay"),children:[t.jsx("span",{children:a("Dáng tay")}),ar.map(_=>t.jsx("button",{type:"button","data-hand":_.id,onClick:()=>W(_.id),children:a(_.label)},_.id))]}),t.jsx("div",{className:"shot-rig-presets",children:Ho[0].presets.map(_=>t.jsx("button",{type:"button",onClick:()=>e.patchItem(l.id,{pose:{...qn[_]}}),children:a(_)},_))}),t.jsx($u,{disabled:e.busy,loop:e.motionLoop,mirror:e.motionMirror,onLoop:e.onMotionLoop,onMirror:e.onMotionMirror,onPlay:_=>e.onPlayClip(l.id,_),person:l,playhead:r*s.duration})]}):t.jsx("small",{className:"shot-hint",children:a("Thư viện chuyển động cần xương người (mẫu Người hoặc AI). Xương khác: tạo dáng bằng Xoay xương.")})]})]})})}const z1={viewBox:"0 0 24 24",width:15,height:15,fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},B1=()=>t.jsxs("svg",{...z1,children:[t.jsx("circle",{cx:"12",cy:"4",r:"2"}),t.jsx("path",{d:"M12 6v8M6 9l6-1 6 1M8 21l4-7 4 7"}),t.jsx("circle",{cx:"6",cy:"9",r:".9",fill:"currentColor"}),t.jsx("circle",{cx:"18",cy:"9",r:".9",fill:"currentColor"}),t.jsx("circle",{cx:"12",cy:"14",r:".9",fill:"currentColor"})]});is.rig={apply(e,n,s){n.rig&&n.model&&nx(e,n.rig,n.model.gcsUri,s?(o,i)=>s.trackRigJob(o,i):void 0)},pose(e,n,s,o,i,r){const l=e.userData.rig;l&&n.rig&&tx(l,i,bd(s.objectKeys?.[n.id],o,n.rig.bones),r)},gaze(e,n,s){const o=e.userData.rig;o&&o.rig.kind==="humanoid"&&ex(o,s)}};is.generate=e=>e.gen?.kind==="character"?_d(e.gen.spec).root:null;function K1({shot:e,engine:n,onClose:s,onBusy:o,onReady:i,timelineTarget:r,vfx:l}){rt();const[h,u]=I.useState(0),[m,d]=I.useState(e.duration),[f,p]=I.useState(720),[y,g]=I.useState(bn(e)),[v,b]=I.useState(!1),[k,w]=I.useState(0),[S,E]=I.useState(""),[j,M]=I.useState("film"),T=I.useRef(null);I.useEffect(()=>()=>T.current?.abort(),[]);const N=Number.isFinite(h)&&Number.isFinite(m)&&h>=0&&m>h&&m<=e.duration,R=async()=>{if(!n||!l)return;const C=new AbortController;T.current=C,b(!0),o(!0),w(0),E("");try{await l.run({height:f,fps:y,motionBlur:fa[j].samples,shutter:fa[j].shutter},w,C.signal),s()}catch(O){E(C.signal.aborted?"Đã huỷ xuất video.":O.message)}finally{T.current=null,b(!1),o(!1)}},A=async C=>{if(!n||!N)return;const O=new AbortController;T.current=O,b(!0),o(!0),w(0),E("");let B;try{const D={motionBlur:fa[j].samples,shutter:fa[j].shutter};if(B=await n.exportVideo({start:h,end:m,height:f,fps:y,...D,signal:O.signal,progress:w}),C==="download"){const $=URL.createObjectURL(B.blob),W=document.createElement("a");W.href=$,W.download=`${e.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-${h}-${m}.mp4`,W.click();const z=B.cleanup;setTimeout(()=>{URL.revokeObjectURL($),z()},6e4),B=void 0}else await i(B.blob,{start:h,end:m,height:f,fps:y,...D},C);s()}catch(D){E(O.signal.aborted?"Đã huỷ xuất video.":D.message)}finally{await B?.cleanup(),T.current=null,b(!1),o(!1)}};return t.jsx("div",{className:"shot-video-overlay",children:t.jsxs("section",{role:"dialog","aria-modal":"true","aria-label":a("Xuất video camera"),className:"shot-video-dialog",children:[t.jsx("h2",{children:a("Xuất video camera · MP4")}),t.jsx("p",{children:a("H.264, không âm thanh, đúng đường chạy và không có line/gizmo. 720p · 24 fps phù hợp làm video tham chiếu nhẹ.")}),t.jsxs("fieldset",{disabled:v,children:[t.jsxs("div",{className:"shot-path-vector",children:[t.jsxs("label",{children:[a("Từ giây"),t.jsx("input",{"aria-label":a("Video từ giây"),type:"number",min:0,max:e.duration,step:"0.1",value:Number.isFinite(h)?h:"",onChange:C=>u(C.target.valueAsNumber)})]}),t.jsxs("label",{children:[a("Đến giây"),t.jsx("input",{"aria-label":a("Video đến giây"),type:"number",min:0,max:e.duration,step:"0.1",value:Number.isFinite(m)?m:"",onChange:C=>d(C.target.valueAsNumber)})]})]}),t.jsxs("label",{children:[a("Chất lượng"),t.jsxs("select",{"aria-label":a("Độ phân giải video"),value:f,onChange:C=>p(+C.target.value),children:[t.jsx("option",{value:720,children:a("720p · Nhẹ")}),t.jsx("option",{value:1080,children:a("1080p · Chi tiết")})]})]}),t.jsxs("label",{children:[a("Khung hình/giây"),t.jsx("select",{"aria-label":a("FPS video"),value:y,onChange:C=>g(+C.target.value),children:vd.map(C=>t.jsx("option",{value:C,children:a("{0} fps",[C])},C))})]}),t.jsxs("label",{title:a("Mỗi khung hình là trung bình nhiều lần render trong lúc màn trập mở, như máy quay phim: chuyển động nhanh nhoè tự nhiên. Xuất lâu hơn."),children:[a("Nhoè chuyển động"),t.jsxs("select",{"aria-label":a("Nhoè chuyển động"),value:j,onChange:C=>M(C.target.value),children:[t.jsx("option",{value:"off",children:a("Tắt · xuất nhanh")}),t.jsx("option",{value:"film",children:a("Điện ảnh · màn trập 180°")}),t.jsx("option",{value:"strong",children:a("Mạnh · hành động nhanh")})]})]})]}),t.jsxs("p",{children:[N?a("{0} giây · {1} · khoảng {2} MB",[(m-h).toFixed(1),e.aspect,Math.ceil((m-h)*(f===1080?6:3)/8)]):a("Chọn khoảng thời gian hợp lệ trong shot."),N&&j!=="off"?" · "+a("xuất lâu hơn khoảng {0} lần",[fa[j].samples]):""]}),v&&t.jsxs(t.Fragment,{children:[t.jsx("progress",{max:100,value:k}),t.jsx("p",{children:k<100?a("Đang xuất từng frame… {0}%",[k]):a("Đang hoàn tất / lưu video…")}),t.jsx("button",{disabled:k===100,onClick:()=>T.current?.abort(),children:a("Huỷ xuất")})]}),S&&t.jsx("p",{role:"alert",children:a(S)}),!v&&l&&t.jsxs("div",{className:"shot-video-vfx",children:[t.jsx("p",{children:l.layers?a("VFX: {0} lớp hiệu ứng xuất riêng trên nền đen (sau người / trước người) rồi đặt lên clip {1}, hoà kiểu Cộng sáng — cả shot, không cần chọn đoạn.",[l.layers,l.target?`“${l.target}”`:a("gốc")]):a("Cảnh chưa có hiệu ứng nào để xuất.")}),t.jsx("button",{className:"shot-primary",disabled:!l.layers,onClick:()=>void R(),children:a("✦ Xuất lớp hiệu ứng về Timeline")})]}),!v&&t.jsxs("div",{className:"shot-video-actions",children:[t.jsx("button",{onClick:s,children:a("Đóng")}),t.jsx("button",{disabled:!N,onClick:()=>void A("download"),children:a("Tải MP4")}),t.jsx("button",{disabled:!N,className:r||l?void 0:"shot-primary",onClick:()=>void A("canvas"),children:a("Đưa video vào Canvas")}),r&&t.jsx("button",{disabled:!N,className:"shot-primary",title:r,onClick:()=>void A("timeline"),children:a("Đưa về Timeline")})]}),t.jsx("small",{children:a("Xuất MP4 không chạy model AI. Tải về hoặc đưa vào Canvas rồi dùng video làm tham chiếu ở bất kỳ đâu.")})]})})}const H1=(e,n)=>`${e} · VFX ${n==="behind"?a("sau người"):a("trước người")}`;async function W1(e,n,s,o,i={}){const r=n.shots.find(p=>p.id===n.activeShot),l=e.vfxLayers();if(!n.plate)throw new Error(a("Cảnh này không có video nền (mở từ một clip trên Timeline)."));if(!l.length)throw new Error(a("Cảnh chưa có hiệu ứng nào để xuất."));const h=ht.getState().canvasId,u=[],m=o.vfxAlpha??"auto",{vfxAlpha:d,...f}=o;for(const[p,y]of l.entries()){const g=m==="on"||m==="auto"&&await e.vfxOccludes(y),{blob:v,cleanup:b}=await e.exportVideo({...f,start:0,end:r.duration,vfx:y,alpha:g,signal:i.signal??new AbortController().signal,progress:k=>i.progress?.(Math.round((p*100+k)/l.length))});try{const k=H1(r.name,y),w=g?"webm":"mp4",{url:S,gcsUri:E}=await Vs(new File([v],`${r.name}-vfx-${y}.${w}`,{type:`video/${w}`}),void 0,"video"),j=Ot()?.getNode(s);if(!j||ht.getState().canvasId!==h)throw new Error(a("Canvas đã thay đổi. Video đã lưu trong Tài sản của tôi."));const M=Ot()?.addNode("video",{url:S,gcsUri:E,label:k,duration:r.duration,ratio:r.aspect,status:"succeeded",shotSourceId:s,shotId:r.id,vfxLayer:y},{x:j.position.x+380,y:j.position.y+p*260},{sourceIds:[s]});if(!M)throw new Error(a("Không tạo được video trên Canvas"));const{width:T,height:N}=bf(r.aspect,{short:o.height});u.push({layer:y,nodeId:M,url:S,gcsUri:E,duration:r.duration,label:k,...g?{alpha:!0,fps:o.fps,width:T,height:N}:{}})}finally{await b()}}return u}const G1=(e,n)=>[...e].sort((s,o)=>(s.layer==="behind"?0:1)-(o.layer==="behind"?0:1)).map(s=>({op:"addVfxLayer",materialId:s.nodeId,clipId:n,layer:s.layer}));function q1(e,n){const s=ht.getState(),o=n?s.clips.find(l=>l.id===n):void 0;if(!o||o.kind!=="video")return{passes:e,placed:!1};const i=e.map(l=>({id:l.nodeId,kind:"video",url:l.url,gcsUri:l.gcsUri,label:l.label,duration:l.duration,...l.alpha?{alpha:!0,fps:l.fps,width:l.width,height:l.height}:{}})),r=ax(s.clips,G1(e,o.id),i,s.timelineTracks,s.timelineCamera);if(r.errors.length)throw new Error(r.errors[0]);return s.setClips(()=>r.clips),s.setTimelineMedia(l=>[...l,...e.filter(h=>!l.some(u=>u.source==="canvas"&&u.id===h.nodeId)).map(h=>({id:h.nodeId,source:"canvas",kind:"video",url:h.url,gcsUri:h.gcsUri,label:h.label,duration:h.duration}))]),{passes:e,placed:!0,clipId:o.id,pendingMatte:!!r.mattes?.length}}function U1({stage:e,selected:n,time:s,disabled:o,onApply:i,getBounds:r,getColliders:l,onPreview:h,embedded:u=!1}){rt();const[m,d]=I.useState(()=>{try{return localStorage.getItem("clipoox.shot.keyModel")==="gpt-5.6-sol"?"gpt-5.6-sol":"gpt-6.1-sol"}catch{return"gpt-6.1-sol"}}),[f,p]=I.useState([]),[y,g]=I.useState(""),[v,b]=I.useState(!1),[k,w]=I.useState(""),[S,E]=I.useState(null),[j,M]=I.useState(null),[T,N]=I.useState(null),[R,A]=I.useState(!1),[C,O]=I.useState(null),B=I.useRef(null),D=[...f,{role:"user",content:y.trim()}].slice(-12),$=JSON.stringify({scene:Ec(e,n,s,r(),l?.()),messages:D,model:m});I.useEffect(()=>{if(N(null),!y.trim()||v)return;let G=!1;A(!0);const _=setTimeout(()=>{const ee=JSON.parse($);dg(ee.scene,ee.messages,ee.model).then(Q=>{G||N({signature:$,credits:Q.reservedCredits})}).catch(Q=>{G||w(Q.message)}).finally(()=>{G||A(!1)})},400);return()=>{G=!0,clearTimeout(_)}},[$,y,v]);const W=I.useRef(null),z=I.useRef(!0),Y=I.useRef(!1);I.useEffect(()=>(z.current=!0,ug().then(G=>{z.current&&E(G)}).catch(()=>{}),()=>{z.current=!1}),[]),I.useEffect(()=>{W.current&&(W.current.scrollTop=W.current.scrollHeight)},[f,v,j]);const J=j&&(j.revision!==e.revision||j.shotId!==e.activeShot),V=async(G=!1)=>{if(Y.current||o||!G&&(!y.trim()||T?.signature!==$))return;const _=G?B.current:{scene:Ec(e,n,s,r(),l?.()),messages:D,id:crypto.randomUUID(),revision:e.revision,shotId:e.activeShot,model:m};if(_){B.current=_,Y.current=!0,b(!0),w(""),M(null),p(_.messages),g("");try{const{plan:ee,model:Q,billing:ve}=await mg(_.scene,_.messages,_.id,_.model);if(!z.current)return;B.current=null,O(ve.credits),E({available:!0,model:Q}),p([..._.messages,{role:"assistant",content:ee.message}]),ee.tracks.length&&M({plan:ee,revision:_.revision,shotId:_.shotId})}catch(ee){z.current&&w(ee.message)}finally{Y.current=!1,z.current&&b(!1)}}},H=u?"div":"section";return t.jsxs(H,{className:u?"shot-agent-embedded":"shot-agent","aria-label":a("AI Agent 3D"),children:[t.jsxs("select",{"aria-label":a("Model AI"),value:m,disabled:v,onChange:G=>{d(G.target.value),B.current=null,w("");try{localStorage.setItem("clipoox.shot.keyModel",G.target.value)}catch{}},children:[t.jsx("option",{value:"gpt-5.6-sol",children:"GPT 5.6 Sol"}),t.jsx("option",{value:"gpt-6.1-sol",children:"GPT 6.1 Sol"})]}),t.jsxs("div",{className:"shot-agent-heading",children:[u?t.jsx("small",{children:a("Đề xuất key cho đối tượng đang chọn hoặc camera")}):t.jsxs(t.Fragment,{children:[t.jsx("b",{children:a("✦ AI Agent")}),t.jsx("small",{children:S?.model||"GPT 5.6 sol"})]}),t.jsx("button",{title:a("Xóa hội thoại"),disabled:v,onClick:()=>{p([]),M(null),w(""),B.current=null},children:"↺"})]}),t.jsxs("div",{className:"shot-agent-chat",ref:W,role:"log","aria-label":a("Hội thoại AI"),children:[!f.length&&t.jsx("p",{className:"shot-agent-intro",children:a("Mô tả chuyển động cho đối tượng đang chọn hoặc camera. AI đề xuất key để bạn áp dụng.")}),f.map((G,_)=>t.jsx("div",{className:`shot-agent-message ${G.role}`,children:G.content},_)),v&&t.jsx("p",{role:"status",children:a("Đang tạo đề xuất key…")}),k&&t.jsxs("p",{role:"alert",children:[k,B.current&&t.jsx("button",{disabled:v,onClick:()=>void V(!0),children:a("Thử lại")})]}),j&&t.jsxs("div",{className:"shot-agent-proposal",children:[t.jsxs("small",{children:[j.plan.tracks.length," ",a("track ·")," ",j.plan.tracks.reduce((G,_)=>G+_.keys.length,0)," ",a("key ·")," ",j.plan.duration,a("s")]}),J?t.jsx("p",{children:a("Cảnh đã thay đổi. Gửi lại yêu cầu để cập nhật đề xuất.")}):t.jsxs(t.Fragment,{children:[t.jsx("ul",{children:j.plan.tracks.map(G=>t.jsxs("li",{children:[G.subjectId==="camera"?"Camera":e.items.find(_=>_.id===G.subjectId)?.name,": ",G.replaceRange?a("Sửa đoạn {0}–{1}s",[G.replaceRange.start.toFixed(2),G.replaceRange.end.toFixed(2)]):a("Thêm/cập nhật {0}–{1}s",[G.keys[0].seconds.toFixed(2),G.keys.at(-1).seconds.toFixed(2)])]},G.subjectId))}),t.jsx("button",{disabled:o,onClick:()=>h(j.plan,G=>{G&&(M(null),p(_=>[..._,{role:"assistant",content:a("Đã giữ thay đổi sau khi xem thử. Có thể hoàn tác bằng Ctrl/Cmd + Z.")}]))}),children:a("Xem thử chuyển động")}),t.jsx("button",{className:"shot-primary",disabled:o,onClick:()=>{try{i(j.plan),M(null),p(G=>[...G,{role:"assistant",content:a("Đã áp dụng key. Bấm Play để xem; Ctrl/Cmd + Z để hoàn tác.")}])}catch(G){w(G.message)}},children:a("Áp dụng key")})]})]})]}),t.jsxs("form",{onSubmit:G=>{G.preventDefault(),V()},children:[t.jsx("textarea",{"aria-label":a("Mô tả key cho AI"),maxLength:4e3,rows:3,value:y,placeholder:a("Ví dụ: xe đi tới 3 mét trong 5 giây…"),onChange:G=>g(G.target.value)}),t.jsx("small",{children:T?.signature===$?a("Tạm giữ tối đa {0} credit; hoàn phần dư theo token thực tế.",[T.credits.toFixed(2)]):R&&y.trim()?a("Đang tính phí…"):a("Chỉ tính phí khi có đề xuất key. Hỏi làm rõ: miễn phí.")}),t.jsx("button",{className:"shot-primary",disabled:v||o||!y.trim()||T?.signature!==$||S?.available===!1,children:a("Tạo key")})]}),C!==null&&t.jsx("small",{children:a("Phí: {0} credit.",[C.toFixed(2)])}),S?.available===!1&&t.jsx("small",{children:a("Admin cần cấu hình API key để bật Agent.")})]})}const Hh=[["gpt-6.1-sol","GPT 6.1 Sol"],["gemini-4-argon","Gemini 4 Argon"],["claude-sonnet-5-5","Claude Sonnet 5.5"],["claude-opus-5-5","Claude Opus 5.5"],["qwen-3.8-flash","Qwen 3.8 Flash (tiết kiệm)"]],X1={mission:["Cô gái đi từ cửa tới bàn trong 4 giây rồi ngồi xuống, camera trung cảnh bám theo","Hai võ sĩ giao đấu: A đấm thẳng, B né rồi trúng cú đá tạt, camera cầm tay rung khi trúng đòn","Xe đỏ chạy qua hẻm núi, camera bám sau rồi vòng ra trước, 12 giây, dọc 9:16"],set:["Quán cà phê 6×8 m: quầy bar, 5 bàn tròn, cửa kính mặt tiền","Hẻm Sài Gòn ban đêm: nhà ống hai bên, dây điện, xe máy dựng dọc tường","Phòng khách căn hộ hiện đại: sofa chữ L, bàn trà, cửa sổ lớn"]},Wh=(e,n)=>{try{return localStorage.getItem(e)||n}catch{return n}},Qi=(e,n)=>{try{localStorage.setItem(e,n)}catch{}},Fn=e=>String(Math.round(e*100)/100);function V1({stage:e,disabled:n,agent:s,lock:o}){rt();const i=nd(),[r,l]=I.useState(()=>{const le=Wh("clipoox.shot.missionMode","mission");return le==="keys"||le==="set"?le:"mission"}),h=le=>[le==="set"?"clipoox.shot.setModel2":"clipoox.shot.missionModel2","gpt-6.1-sol"],u=le=>{const[Le,Ae]=h(le),we=Wh(Le,Ae);return Hh.some(([he])=>he===we)?we:Ae},[m,d]=I.useState(()=>u(r)),[f,p]=I.useState(!1),y=le=>{p(le),Qi("clipoox.shot.hq","")},g=f?Pa:m,[v,b]=I.useState(""),[k,w]=I.useState(null),[S,E]=I.useState(""),j=I.useRef(null),M=I.useRef(null),T=yf(e),N=vf(T),[R,A]=I.useState(null),[C,O]=I.useState(!1),[B,D]=I.useState(null),$=I.useRef(null);I.useEffect(()=>{if(!B)return;const le=Ae=>{$.current?.contains(Ae.target)||D(null)},Le=Ae=>{Ae.key==="Escape"&&(Ae.stopPropagation(),D(null))};return window.addEventListener("pointerdown",le),window.addEventListener("keydown",Le,!0),()=>{window.removeEventListener("pointerdown",le),window.removeEventListener("keydown",Le,!0)}},[B]);const[W,z]=I.useState(""),[Y,J]=I.useState(""),[V,H]=I.useState(null),G=["thinking","acting","rendering"].includes(i.phase);I.useEffect(()=>{j.current&&(j.current.scrollTop=j.current.scrollHeight)},[i.log.length]);const _=le=>{l(le),Qi("clipoox.shot.missionMode",le),d(u(le))},ee=le=>{d(le),Qi(h(r)[0],le)},Q=async le=>{if(E(""),!le){w(null);return}if(le.size>28e4||!["image/jpeg","image/png"].includes(le.type)){E(a("Ảnh tham chiếu phải là JPG/PNG ≤ 280 KB."));return}const Le=await new Promise((Ae,we)=>{const he=new FileReader;he.onload=()=>Ae(String(he.result)),he.onerror=()=>we(he.error),he.readAsDataURL(le)});w({name:le.name,data:Le})},ve=(i.phase==="done"||i.phase==="capped")&&!!i.missionId&&i.model===g&&i.quality==="high"===f,ye=C?jf({from:Number(W),to:Number(Y)},T.duration):null,q=(le=!1)=>{const Le=v.trim();if(!Le||G||n)return;b("");const Ae={window:ye,continueFrom:V,quality:f?"high":null};H(null),le&&ve?i.followUp(Le,Ae):i.start(Le,k?.data||null,g,r==="set"?"set":"shot",Ae)},pe=le=>{A(null),o&&Math.abs(le-N)>1e-6&&o.onChange(Math.max(0,Math.min(T.duration,le)))},ue=(le,Le=null)=>{b(le),H(Le),requestAnimationFrame(()=>{const Ae=M.current;Ae&&(Ae.focus(),Ae.setSelectionRange(le.length,le.length))})},U=le=>a("Giữ nguyên 0–{0}s, kéo dài shot thêm 5s, từ {0}s đến {1}s: ",[Fn(le),Fn(le+5)]),re=()=>{C||(z(Fn(N)),J(Fn(T.duration))),O(!C)},ce=(navigator.language||"").startsWith("vi"),Ee={thinking:a("Đang nghĩ…"),acting:a("Đang dựng trong composer…"),rendering:a("Đang render & đưa vào canvas…"),done:a("Xong"),error:a("Lỗi"),cancelled:a("Đã dừng"),capped:a("Đã dùng hết {0} credit của lượt này",[Ga]),idle:""}[i.phase],je=t.jsxs("label",{className:`shot-lock-chip shot-hq-chip${f?" on":""}`,children:[t.jsx("input",{type:"checkbox","aria-label":a("Model chất lượng cao · Opus"),checked:f,disabled:G,onChange:le=>y(le.target.checked)}),t.jsxs("span",{"aria-hidden":"true",children:["✦ ",a("Chất lượng cao")]})]});return t.jsxs("section",{className:"shot-agent shot-mission","aria-label":a("Mission Agent"),children:[t.jsxs("div",{className:"shot-agent-heading",children:[t.jsx("b",{children:a("✦ Mission")}),r!=="keys"&&t.jsx("select",{className:"shot-mission-model","aria-label":a("Model AI"),value:g,disabled:G||f,onChange:le=>ee(le.target.value),title:a("GPT 6 Astra suy luận tốt hơn, giá token cao hơn (tính theo dùng thật)"),children:Hh.map(([le,Le])=>t.jsx("option",{value:le,children:a(Le)},le))}),r!=="keys"&&i.missionId&&!G&&t.jsx("button",{title:a("Yêu cầu mới"),onClick:()=>i.reset(),children:"↺"})]}),t.jsxs("div",{className:"shot-mission-tabs",role:"tablist",children:[t.jsx("button",{role:"tab","aria-selected":r==="mission",className:r==="mission"?"active":"",disabled:G,onClick:()=>_("mission"),children:a("Dựng shot")}),t.jsx("button",{role:"tab","aria-selected":r==="set",className:r==="set"?"active":"",disabled:G,onClick:()=>_("set"),children:a("Dựng bối cảnh")}),t.jsx("button",{role:"tab","aria-selected":r==="keys",className:r==="keys"?"active":"",disabled:G,onClick:()=>_("keys"),children:a("Key đối tượng")})]}),r==="keys"?t.jsx(U1,{embedded:!0,stage:e,selected:s.selected,time:s.time,disabled:n,getBounds:s.getBounds,getColliders:s.getColliders,onPreview:s.onPreview,onApply:s.onApply}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-mission-body",children:[i.phase==="idle"&&!i.log.length&&t.jsxs("div",{className:"shot-mission-empty",children:[t.jsx("p",{className:"shot-agent-intro",children:r==="set"?a("Mô tả địa điểm (hoặc gửi ảnh tham chiếu) → Agent dựng bối cảnh 3D đúng tỉ lệ bằng khối, đặt camera và tự xem lại. Bối cảnh dùng chung cho mọi shot. Tính theo token dùng thật."):a("Một câu → Agent dựng proxy, cho xe/nhân vật chạy, camera bám, tự kiểm tra rồi render video ref vào canvas. ≈ 0.05–0.4 credit/bước.")}),t.jsx("div",{className:"shot-mission-suggest","aria-label":a("Gợi ý"),children:X1[r==="set"?"set":"mission"].map(le=>t.jsx("button",{type:"button",disabled:G||n,onClick:()=>b(a(le)),children:a(le)},le))})]}),i.log.length>0&&t.jsxs("div",{className:"shot-agent-chat shot-mission-log",ref:j,role:"log",children:[t.jsxs("div",{className:"shot-mission-status",children:[i.quality==="high"&&t.jsx("b",{className:"shot-hq-badge",children:a("Chất lượng cao · Opus")}),Ee," · ",a("bước")," ",i.step,"/",i.maxSteps," · ",i.spent.toFixed(2),i.budget!=null?` / ${i.budget}`:""," cr"]}),i.log.slice(-12).map((le,Le)=>t.jsx("div",{className:"shot-mission-line",children:le},Le)),i.sheet&&t.jsx("img",{className:"shot-mission-sheet",src:i.sheet,alt:a("Contact sheet 6 khung hình")}),i.phase==="done"&&t.jsx("div",{className:"shot-mission-facts",children:kf(e,i.facts,ce)}),i.phase==="done"&&i.purpose==="set"&&i.ready&&t.jsx("div",{className:"shot-mission-done",children:a('Bối cảnh đã có trong composer (danh sách Đối tượng). Muốn sửa tiếp: gõ bên dưới rồi bấm "Sửa / làm tiếp phiên này"; hoặc chuyển sang "Dựng shot" để thêm nhân vật và chuyển động.')}),i.phase==="done"&&i.result?.nodeId&&t.jsx("div",{className:"shot-mission-done",children:a('Video ref đã được thêm vào canvas. Bấm "← Canvas" để xem. Muốn sửa hoặc làm tiếp shot này: gõ bên dưới rồi bấm "Sửa / làm tiếp phiên này". Ưng phần đầu rồi thì khoá lại trước.')}),i.phase==="capped"&&t.jsx("div",{className:"shot-mission-done",role:"status",children:a('Lượt này đã dùng hết {0} credit nên Agent dừng lại; mọi thứ đã dựng vẫn giữ nguyên. Gõ yêu cầu bên dưới rồi bấm "Sửa / làm tiếp phiên này" để làm tiếp từ những gì đang có (thêm {0} credit).',[Ga])}),i.error&&t.jsx("p",{role:"alert",children:i.error})]})]}),r==="set"&&t.jsx("div",{className:"shot-mission-lock",children:je}),r==="mission"&&t.jsxs("div",{ref:$,className:`shot-mission-lock${N>0?" on":""}`,role:"group","aria-label":a("Khoá đoạn đã ưng"),children:[o&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:`shot-lock-chip${N>0?" on":""}`,"aria-expanded":B==="lock",title:N>0?a("Agent giữ nguyên 0–{0}s, chỉ làm tiếp từ {0}s (bạn vẫn sửa tay được).",[Fn(N)]):a("Ưng phần đầu rồi thì khoá lại: Agent làm tiếp mà không đè lên."),onClick:()=>D(B==="lock"?null:"lock"),children:["🔒 ",N>0?`0–${Fn(N)}s`:a("Khoá")]}),t.jsxs("button",{type:"button",className:`shot-lock-chip${C?ye?" on":" bad":""}`,"aria-expanded":B==="window",onClick:()=>D(B==="window"?null:"window"),children:["✂ ",C&&ye?`${Fn(ye.from)}–${Fn(ye.to)}s`:a("Chỉ sửa đoạn")]})]}),je,B==="lock"&&o&&t.jsxs("div",{className:"shot-lock-pop",children:[t.jsxs("div",{className:"shot-mission-lock-row",children:[t.jsxs("span",{className:"shot-mission-lock-label",children:[a("Khoá")," 0–"]}),t.jsx("input",{"aria-label":a("Khoá đến (giây)"),inputMode:"decimal",value:R??Fn(N),disabled:G,onFocus:le=>le.target.select(),onChange:le=>A(le.target.value),onBlur:()=>{if(R!=null){const le=Number(R.replace(",","."));Number.isFinite(le)?pe(le):A(null)}},onKeyDown:le=>{le.key==="Enter"&&(le.preventDefault(),le.target.blur()),le.key==="Escape"&&(A(null),le.target.blur())}}),t.jsx("span",{children:"s"}),t.jsx("button",{type:"button",disabled:G||o.playhead<=0,title:a("Agent sẽ không sửa gì trước vị trí playhead; bạn vẫn sửa tay được."),onClick:()=>pe(o.playhead),children:a("Khoá tới playhead")}),N>0&&t.jsx("button",{type:"button",disabled:G,onClick:()=>pe(0),children:a("Mở khoá")})]}),t.jsx("small",{children:N>0?a("Agent giữ nguyên 0–{0}s, chỉ làm tiếp từ {0}s (bạn vẫn sửa tay được).",[Fn(N)]):a("Ưng phần đầu rồi thì khoá lại: Agent làm tiếp mà không đè lên.")})]}),B==="window"&&t.jsxs("div",{className:"shot-lock-pop",children:[t.jsxs("label",{className:"shot-mission-window",children:[t.jsx("input",{type:"checkbox",checked:C,disabled:G,onChange:re}),t.jsx("span",{children:a("Chỉ sửa đoạn")}),C&&t.jsxs(t.Fragment,{children:[t.jsx("input",{"aria-label":a("Sửa từ (giây)"),inputMode:"decimal",value:W,disabled:G,onChange:le=>z(le.target.value.replace(",","."))}),t.jsx("span",{children:"–"}),t.jsx("input",{"aria-label":a("Sửa đến (giây)"),inputMode:"decimal",value:Y,disabled:G,onChange:le=>J(le.target.value.replace(",","."))}),t.jsx("span",{children:"s"})]})]}),C&&!ye&&t.jsx("small",{role:"alert",children:a("Đoạn sửa không hợp lệ (cần dài ít nhất 0,1 giây, trong thời lượng shot).")}),t.jsx("small",{children:a("Chỉ lần chạy này: Agent chỉ sửa trong đoạn đã chọn, ngoài đoạn được giữ nguyên.")})]})]}),t.jsxs("form",{className:"shot-mission-composer",onSubmit:le=>{le.preventDefault(),q(!1)},children:[t.jsx("textarea",{ref:M,"aria-label":a("Mô tả shot cho Agent"),maxLength:4e3,rows:3,value:v,disabled:G||n,placeholder:ve?a("Yêu cầu mới → bấm “Chạy Agent (mới)”. Muốn sửa hoặc làm tiếp phiên vừa xong thì gõ rồi bấm “Sửa / làm tiếp phiên này”."):r==="set"?a("Ví dụ: quán cà phê 8×12 m, cửa kính mặt tiền, quầy bar bên trái, 6 bàn tròn, cầu thang lên gác lửng ở cuối"):a("Ví dụ: xe đỏ chạy qua hẻm núi, camera bám sau rồi vòng ra trước, drift 2 vòng quanh một người, 12 giây, dọc 9:16"),onChange:le=>{b(le.target.value),le.target.value.trim()||H(null)}}),ve&&r==="mission"&&t.jsxs("div",{className:"shot-mission-chips","aria-label":a("Làm tiếp"),children:[t.jsx("button",{type:"button",disabled:n,onClick:()=>ue(a("Sửa đoạn đã làm: ")),children:a("Sửa đoạn đã làm")}),t.jsx("button",{type:"button",disabled:n,onClick:()=>ue(U(T.duration),T.duration),children:a("Làm tiếp thêm 5s")}),o&&t.jsx("button",{type:"button",disabled:n,title:a("Khoá 0–{0}s rồi viết phần tiếp theo",[Fn(T.duration)]),onClick:()=>{pe(T.duration),ue(U(T.duration),T.duration)},children:a("Khoá phần đã ưng rồi làm tiếp")})]}),t.jsxs("div",{className:"shot-mission-row",children:[t.jsxs("label",{className:"shot-mission-ref",children:[t.jsx("input",{type:"file",accept:"image/jpeg,image/png",hidden:!0,disabled:G,onChange:le=>{Q(le.target.files?.[0]),le.target.value=""}}),t.jsx("span",{children:k?`🖼 ${k.name}`:a("+ Ảnh tham chiếu (tuỳ chọn)")})]}),k&&!G&&t.jsx("button",{type:"button",onClick:()=>w(null),children:"×"}),G?t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>i.stop(),children:a("Dừng")}):t.jsxs(t.Fragment,{children:[ve&&t.jsx("button",{type:"button",className:"shot-continue",disabled:n||!v.trim(),title:a("Sửa kết quả vừa xong hoặc làm tiếp (giữ cảnh, model và lịch sử). Không bấm thì là yêu cầu mới."),onClick:()=>q(!0),children:a("↪ Sửa / làm tiếp phiên này")}),t.jsx("button",{className:"shot-primary",disabled:n||!v.trim(),title:a("Yêu cầu mới: Agent không dùng lịch sử phiên trước"),children:a("Chạy Agent (mới)")})]})]}),S&&t.jsx("small",{role:"alert",children:S})]})]})]})}const Y1=1200,Q1=4e3,Z1=8e3,J1=12e4;function ej(e,n,s,o){let i=!1,r=null,l=0,h=!1;const u=wf(),m=()=>typeof document<"u"&&document.hidden?Z1:Date.now()-l<J1?Y1:Q1,d=async p=>{l=Date.now();let y;try{y=await Mf(p.tool,p.args||{},e)}catch(b){y={ok:!1,error:String(b?.message||b).slice(0,500)}}const{_image:g,...v}=y;try{await fg(p.id,{tabId:u,ok:y.ok!==!1,result:Sf(v),...typeof g=="string"?{image:g}:{}})}catch{}p.tool==="drive_character"&&y.ok!==!1&&typeof y.start=="number"&&s?.(y.start)},f=async()=>{if(!i){if(!h){h=!0;try{const p=o?.()||void 0,{commands:y}=await pg({tabId:u,scene:n().slice(0,120),...p?{sceneId:p}:{}});for(const g of y||[]){if(i)break;await d(g)}}catch{}finally{h=!1}}i||(r=setTimeout(()=>{f()},m()))}};return f(),()=>{i=!0,r&&clearTimeout(r)}}function tj({shot:e,patch:n,progress:s,seek:o,engine:i,selected:r,select:l}){rt();const[h,u]=I.useState(!1),m=e.cameraKeys||[],d=m.find(j=>j.id===r),f=e.cameraMode==="free",p=[...m].sort((j,M)=>j.time-M.time),y=d?Cf(p,p.indexOf(d)):null,g=j=>n(or(j)),v=(j,M)=>g(m.map(T=>T.id===j?{...T,...M}:T)),b=j=>Af(e,j),k=()=>{const j=m.find(T=>Math.abs(T.time-s)<1e-6);if(j){l(j.id);return}const M=b(s);g([...m,M]),l(M.id)};I.useEffect(()=>{if(i){if(e.motion!=="path"&&!h){i.setPathEditor(void 0);return}return i.setPathEditor({selected:r,drawing:h,select:j=>{l(j);const M=m.find(T=>T.id===j);M&&o(M.time)},move:(j,M)=>v(j,{position:M}),add:j=>{const M={...b(1),position:j},T=[...m,M].map((N,R,A)=>({...N,time:A.length>1?R/(A.length-1):0}));g(T),l(M.id),o(T.at(-1)?.time||0)}}),()=>i.setPathEditor(void 0)}},[i,e.id,e.cameraKeys,e.motion,r,h]),I.useEffect(()=>{u(!1),l(null)},[e.id]);const w=j=>{const M=Tf(e,j);g(M),l(M[0].id),o(0),u(!1)},S=(j,M,T,N,R)=>t.jsxs("label",{className:"shot-path-number",children:[a(j),t.jsx(Tn,{"aria-label":a(j),step:"0.1",min:N,max:R,precision:3,value:M,onCommit:T})]}),E=(j,M,T)=>t.jsx("div",{className:"shot-path-vector",children:M.map((N,R)=>t.jsx("div",{children:S(`${a(j)} ${"XYZ"[R]}`,N,A=>T(M.map((C,O)=>R===O?A:C)))},R))});return t.jsxs("section",{className:"shot-path-editor",children:[t.jsx("h3",{children:a("ĐƯỜNG CHẠY CAMERA")}),t.jsx("p",{children:a("Chọn mẫu hoặc vẽ điểm trong cảnh. Chọn điểm để kéo trục màu và chỉnh độ cao.")}),t.jsxs("div",{className:"shot-camera-mode",role:"radiogroup","aria-label":a("Hướng camera"),children:[t.jsx("button",{role:"radio","aria-checked":!f,className:f?"":"shot-primary",onClick:()=>n({cameraMode:void 0}),children:a("Bám theo (Track)")}),t.jsx("button",{role:"radio","aria-checked":f,className:f?"shot-primary":"",onClick:()=>n({cameraMode:"free"}),children:a("Tự do (Free style)")})]}),t.jsx("p",{className:"shot-camera-mode-hint",children:f?a("Camera nhìn theo hướng đi của đường; chọn từng điểm để xoay hướng nhìn tuỳ ý."):a('Camera luôn nhìn về điểm "Nhìn tới" của từng key.')}),t.jsx("div",{className:"shot-add",children:[["circle","Vòng tròn"],["spiral","Xoắn ốc"],["line","Đường thẳng"],["curve","Uốn nhẹ"]].map(([j,M])=>t.jsxs("button",{onClick:()=>w(j),children:[{circle:t.jsx(Ce.circle,{}),spiral:t.jsx(Ce.spiral,{}),line:t.jsx(Ce.line,{}),curve:t.jsx(Ce.curve,{})}[j],a(M)]},j))}),t.jsxs("button",{className:h?"shot-primary":"",onClick:()=>{u(!h),h||(g([]),l(null),o(0),i?.view(!0))},children:[t.jsx(Ce.pen,{}),h?a("✓ Xong vẽ đường").replace("✓ ",""):a("✎ Vẽ đường mới bằng điểm").replace("✎ ","")]}),h&&t.jsx("p",{children:a("Nhấp vào cảnh để nối thêm điểm. Độ cao ban đầu theo camera; kéo trục Y để nâng/hạ. Điểm mới sẽ chia đều lại thời gian.")}),t.jsxs("div",{className:"shot-add",children:[t.jsxs("button",{onClick:k,children:[t.jsx(Ce.key,{}),a("+ Key tại thời điểm này").replace("+ ","")]}),t.jsx("button",{disabled:!m.length,onClick:()=>g(m.map((j,M)=>({...j,time:m.length>1?M/(m.length-1):0}))),children:a("Chia đều thời gian")})]}),m.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{children:[t.jsx("input",{type:"checkbox",checked:e.pathSmooth!==!1,onChange:j=>n({pathSmooth:j.target.checked})})," ",a("Đường cong mượt")]}),t.jsx("div",{className:"shot-path-keys",children:m.map((j,M)=>t.jsxs("button",{className:j.id===r?"shot-primary":"",onClick:()=>{l(j.id),o(j.time)},children:["◆ ",M+1," · ",(j.time*e.duration).toFixed(1),a("s")]},j.id))})]}),d&&t.jsxs("div",{className:"shot-path-key",children:[t.jsxs("b",{children:[a("Điểm")," ",m.indexOf(d)+1]}),t.jsx("button",{onClick:()=>l(null),children:a("Bỏ chọn điểm")}),S(a("Thời điểm key (giây)"),d.time*e.duration,j=>{const M=j/e.duration;m.some(T=>T.id!==d.id&&Math.abs(T.time-M)<1e-6)||(v(d.id,{time:M}),o(M))},0,e.duration),E("Camera",d.position,j=>v(d.id,{position:j})),!f&&E(a("Nhìn tới"),d.target,j=>v(d.id,{target:j})),f&&y&&t.jsxs("div",{className:"shot-path-aim",children:[S(a("Xoay ngang (°)"),y[0],j=>v(d.id,{aim:[j,y[1]]}),-360,360),S(a("Ngẩng / cúi (°)"),y[1],j=>v(d.id,{aim:[y[0],j]}),-85,85),t.jsx("button",{disabled:!d.aim,onClick:()=>v(d.id,{aim:void 0}),children:a("Nhìn theo hướng đi")})]}),S(a("Tiêu cự key (mm)"),d.lens,j=>v(d.id,{lens:j}),14,200),S(a("Nghiêng key (°)"),d.roll,j=>v(d.id,{roll:j})),t.jsx("button",{onClick:()=>{const j=i?.captureCamera();j&&v(d.id,{position:j.position,target:j.target,lens:j.lens,roll:j.roll,...f&&j.target&&j.position?{aim:Nf(new ae(j.target[0]-j.position[0],j.target[1]-j.position[1],j.target[2]-j.position[2]))}:{}})},children:a("Lấy góc đang quan sát cho key")}),t.jsx("button",{onClick:()=>{g(m.filter(j=>j.id!==d.id)),l(null)},children:a("Xoá key này")})]})]})}const Ou=.5,_u=60,nj=e=>Math.min(_u,Math.max(Ou,Math.round(e*100)/100));function zu(e){const n=bn(e);return{aspect:[...oc.includes(e.aspect)?[]:[a("Seedance không nhận tỷ lệ {0}; khi gửi sẽ dùng {1}.",[e.aspect,ir(e.aspect,oc)])],...Da.includes(e.aspect)?[]:[a("Ảnh thật (GPT Image) không nhận tỷ lệ {0}; sẽ dùng {1}.",[e.aspect,ir(e.aspect,Da)])]],duration:e.duration<4?[a("Seedance 2.5 cần tối thiểu 4 giây; video camera ngắn hơn vẫn xuất bình thường.")]:[],fps:n===24||n===30?[]:[a("Đa số model video chỉ xuất 24/30 fps; {0} fps chỉ áp dụng cho video camera previs.",[n])]}}const Gh=e=>{const n=If(e),s=n>=1?14:14*n,o=n>=1?14/n:14;return t.jsx("span",{className:"shot-fmt-glyph","aria-hidden":"true",style:{width:s,height:o}})};function sj({shot:e,patch:n,disabled:s}){rt();const[o,i]=I.useState(null),[r,l]=I.useState(null),h=I.useRef(null),u=bn(e),m=zu(e);I.useEffect(()=>{if(!o)return;const w=S=>{h.current?.contains(S.target)||i(null)};return document.addEventListener("pointerdown",w,!0),()=>document.removeEventListener("pointerdown",w,!0)},[o]),I.useEffect(()=>{o&&h.current?.querySelector('.shot-fmt-pop [aria-checked="true"], .shot-fmt-pop button')?.focus()},[o]);const d=w=>h.current?.querySelector(`[data-fmt="${w}"]`),f=w=>{const S=o;i(null),S&&requestAnimationFrame(()=>d(S)?.focus())},p=w=>{n(w),f()},y=w=>{if(Number.isFinite(w)){const S=nj(w);S!==e.duration&&n({duration:S})}},g=()=>{if(r!==null){const w=Number(r.replace(",","."));r.trim()!==""&&y(w),l(null)}},v=w=>{if(w.key==="Escape"&&o){w.preventDefault(),w.stopPropagation(),f();return}const S=w.target.closest(".shot-fmt-pop");if(S&&["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(w.key)){w.preventDefault();const E=[...S.querySelectorAll("button")],j=E.indexOf(w.target),M=w.key==="Home"?0:w.key==="End"?E.length-1:(j+(w.key==="ArrowDown"||w.key==="ArrowRight"?1:-1)+E.length)%E.length;E[M]?.focus()}},b=[...Lf,...Ef.includes(e.aspect)?[e.aspect]:[]],k=a("Thời lượng shot (giây). Bước 0,5 giây; ▾ để chọn nhanh 3/5/8/10/15 giây.");return t.jsxs("div",{className:"shot-fmt",ref:h,onKeyDown:v,children:[t.jsxs("small",{children:[Number(e.lens.toFixed(1)),a("mm ·")]}),t.jsxs("div",{className:"shot-fmt-item",children:[t.jsxs("button",{type:"button","data-fmt":"aspect",className:m.aspect.length?"warn":"",disabled:s,"aria-haspopup":"menu","aria-expanded":o==="aspect","aria-label":a("Tỷ lệ khung hình: {0}",[e.aspect]),title:[a("Tỷ lệ khung hình của shot"),...m.aspect].join(`
285
+ `),onClick:()=>i(o==="aspect"?null:"aspect"),children:[Gh(e.aspect),e.aspect]}),o==="aspect"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":a("Tỷ lệ khung hình"),children:[b.map(w=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e.aspect===w,className:e.aspect===w?"active":"",onClick:()=>p({aspect:w}),children:[Gh(w),w]},w)),m.aspect.map(w=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",w]},w))]})]}),t.jsx("span",{className:"shot-fmt-dot","aria-hidden":"true",children:"·"}),t.jsxs("div",{className:"shot-fmt-item shot-fmt-dur",role:"group","aria-label":a("Thời lượng shot (giây)"),title:k,children:[t.jsx("button",{type:"button",disabled:s||e.duration<=Ou,"aria-label":a("Giảm 0,5 giây"),title:a("Giảm 0,5 giây"),onClick:()=>y(e.duration-.5),children:"−"}),t.jsx("input",{"aria-label":a("Thời lượng shot (giây)"),title:k,inputMode:"decimal",disabled:s,className:m.duration.length?"warn":"",value:r??String(Number(e.duration.toFixed(2))),onFocus:w=>w.currentTarget.select(),onChange:w=>l(w.target.value),onBlur:g,onKeyDown:w=>{if(w.key==="Enter")w.preventDefault(),g(),w.currentTarget.blur();else if(w.key==="Escape")w.preventDefault(),w.stopPropagation(),l(null),w.currentTarget.blur();else if(w.key==="ArrowUp"||w.key==="ArrowDown"){w.preventDefault();const S=r!==null&&Number.isFinite(Number(r.replace(",",".")))?Number(r.replace(",",".")):e.duration;l(null),y(S+(w.key==="ArrowUp"?.5:-.5))}}}),t.jsx("span",{className:"shot-fmt-unit","aria-hidden":"true",children:a("s")}),t.jsx("button",{type:"button",disabled:s||e.duration>=_u,"aria-label":a("Tăng 0,5 giây"),title:a("Tăng 0,5 giây"),onClick:()=>y(e.duration+.5),children:"+"}),t.jsx("button",{type:"button","data-fmt":"dur",className:`shot-fmt-more${m.duration.length?" warn":""}`,disabled:s,"aria-haspopup":"menu","aria-expanded":o==="dur","aria-label":a("Chọn nhanh thời lượng"),title:[a("Chọn nhanh thời lượng"),...m.duration].join(`
286
+ `),onClick:()=>i(o==="dur"?null:"dur"),children:"▾"}),o==="dur"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":a("Chọn nhanh thời lượng"),children:[Rf.map(w=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e.duration===w,className:e.duration===w?"active":"",onClick:()=>p({duration:w}),children:[w," ",a("giây")]},w)),m.duration.map(w=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",w]},w))]})]}),t.jsx("span",{className:"shot-fmt-dot","aria-hidden":"true",children:"·"}),t.jsxs("div",{className:"shot-fmt-item",children:[t.jsxs("button",{type:"button","data-fmt":"fps",className:m.fps.length?"warn":"",disabled:s,"aria-haspopup":"menu","aria-expanded":o==="fps","aria-label":a("Tốc độ khung hình: {0} fps",[u]),title:[a("Tốc độ khung hình (fps) khi xuất video camera"),...m.fps].join(`
287
+ `),onClick:()=>i(o==="fps"?null:"fps"),children:[u,a("fps")]}),o==="fps"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":a("Tốc độ khung hình (fps)"),children:[vd.map(w=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":u===w,className:u===w?"active":"",title:w===40?a("Đa số model video chỉ xuất 24/30 fps; {0} fps chỉ áp dụng cho video camera previs.",[w]):void 0,onClick:()=>p({fps:w}),children:[w," ",a("fps")]},w)),m.fps.map(w=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",w]},w))]})]})]})}function Er(e,n,s){const o=Ot();if(!o||!e.url)return null;const i=o.nodes().find(l=>l.type==="image"&&l.data.gcsUri===e.gcsUri);if(i)return i.id;const r=o.getNode(n);return o.addNode("image",{url:e.url,gcsUri:e.gcsUri,label:e.name},r?{x:r.position.x-360,y:r.position.y+s*220}:void 0,{select:!1})}function qh(e,n){const s=e?Ot()?.getNode(e)?.data:void 0;return s?.gcsUri&&/^gs:\/\//.test(s.gcsUri)?{gcsUri:s.gcsUri,...s.url?{url:s.url}:{},name:n}:void 0}function aj(e,n,s){let o=!1;const i=e.items.map((r,l)=>{const h=r.castId?n.cast.find(m=>m.id===r.castId):void 0;if(!h)return r;const u={...r,name:h.name,color:h.color};if(r.kind==="person"&&(u.figure=h.figure?Ht(h.figure):void 0,u.look=h.look),h.reference&&(r.reference?.nodeId?Ot()?.getNode(r.reference.nodeId)?.data?.gcsUri:void 0)!==h.reference.gcsUri){const d=Er(h.reference,s,l);d&&(u.reference={nodeId:d,url:h.reference.url||"",name:h.reference.name})}return JSON.stringify(u)!==JSON.stringify(r)&&(o=!0),u});return o?{...e,items:i}:null}function oj({stage:e,nodeId:n,selected:s,disabled:o,change:i,onError:r,onSelect:l}){rt();const[h,u]=I.useState(null),[m,d]=I.useState(null),[f,p]=I.useState(""),[y,g]=I.useState(!1),v=I.useRef(null),b=e.series;I.useEffect(()=>{if(!b?.id){d(null);return}let N=!0;return gg(b.id).then(R=>{if(N&&(d(R),v.current!==R.id)){v.current=R.id;const A=aj(e,R,n);A&&i(()=>A)}}).catch(R=>r(R.message)),()=>{N=!1}},[b?.id]),I.useEffect(()=>{!b?.id&&h===null&&xg().then(N=>u(N.series)).catch(()=>u([]))},[b?.id,h]);const k=async N=>{g(!0);try{const{id:R,updatedAt:A,...C}=N;await bg(R,C),d(N)}catch(R){r(R.message)}finally{g(!1)}},w=async()=>{const N=f.trim();if(!N)return;const R={id:yt(),name:N,cast:[],locations:[],episodes:[]};await k(R),i(A=>({...A,series:{id:R.id,name:N}})),p("")},S=async()=>{if(!m||!s||!["person","model"].includes(s.kind))return;const N=s.castId&&m.cast.some(C=>C.id===s.castId)?s.castId:yt(),R=qh(s.reference?.nodeId,s.reference?.name||s.name),A={id:N,name:s.name.slice(0,60),color:/^#[0-9a-f]{6}$/i.test(s.color)?s.color:"#baca9e",...s.kind==="person"&&s.figure?{figure:Ht(s.figure)}:{},...s.kind==="person"&&s.look?{look:s.look}:{},...R?{reference:R}:{},...s.kind==="model"&&s.model?{model:{gcsUri:s.model.gcsUri,name:s.model.name,...s.model.height?{height:s.model.height}:{}}}:{}};await k({...m,cast:[...m.cast.filter(C=>C.id!==N),A]}),i(C=>({...C,items:C.items.map(O=>O.id===s.id?{...O,castId:N}:O)})),s.reference&&!R&&r(a("Ảnh nhận diện không phải ảnh đã tải lên / tạo trên Clipoox nên không lưu vào thư viện được."))},E=N=>{const R=e.items.length,A=N.model?{...An("model",R),model:N.model}:{...An("person",R),...N.figure?{figure:Ht(N.figure)}:{},...N.look?{look:N.look}:{}},C=N.reference?Er(N.reference,n,R):null,O={...A,name:N.name,color:N.color,castId:N.id,...C&&N.reference?{reference:{nodeId:C,url:N.reference.url||"",name:N.reference.name}}:{}};i(B=>({...B,items:[...B.items,O]})),l(O.id)},j=async N=>{if(!m)return;const R=e.items.find(B=>B.kind==="set"&&B.set),A=(e.styleRefs||[]).flatMap(B=>{const D=qh(B.nodeId,B.name);return D?[D]:[]}),O={id:m.locations.find(B=>B.name===N)?.id||yt(),name:N,...R?.set?{setId:R.set.id}:{},lighting:Oa(e.lighting),...A.length?{styleRefs:A}:{}};await k({...m,locations:[...m.locations.filter(B=>B.id!==O.id),O]}),i(B=>({...B,series:{...B.series,location:O.id}}))},M=N=>{const R=(N.styleRefs||[]).flatMap((A,C)=>{const O=Er(A,n,10+C);return O?[{nodeId:O,url:A.url||"",name:A.name}]:[]});i(A=>{const C=N.setId&&A.items.some(B=>B.kind==="set"&&B.set?.id===N.setId),O=N.setId&&!C?[{...An("set",A.items.length),name:N.name,set:{id:N.setId,name:N.name}},...A.items]:A.items;return{...A,items:O,...N.lighting?{lighting:Oa(N.lighting)}:{},...R.length?{styleRefs:R}:{},series:{...A.series,location:N.id}}})},T=async N=>{if(!m||!N.trim())return;const R={id:yt(),name:N.trim().slice(0,80)};await k({...m,episodes:[...m.episodes,R]}),i(A=>({...A,series:{...A.series,episode:R.id}}))};return b?t.jsxs("div",{className:"shot-series",children:[t.jsxs("div",{className:"shot-series-row",children:[t.jsx("b",{children:b.name}),t.jsx("button",{disabled:o,onClick:()=>i(N=>({...N,series:void 0})),children:a("Bỏ gắn")})]}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Tập")}),t.jsxs("select",{"aria-label":a("Tập"),value:b.episode||"",disabled:o,onChange:N=>{if(N.target.value==="+"){const R=window.prompt(a("Tên tập"),`Tập ${m.episodes.length+1}`);R&&T(R);return}i(R=>({...R,series:{...R.series,episode:N.target.value||void 0}}))},children:[t.jsx("option",{value:"",children:"—"}),m.episodes.map(N=>t.jsx("option",{value:N.id,children:N.name},N.id)),t.jsx("option",{value:"+",children:a("+ Tập mới…")})]})]}),t.jsxs("h4",{children:[a("Dàn nhân vật")," · ",m.cast.length]}),t.jsx("ul",{className:"shot-series-list",children:m.cast.map(N=>t.jsxs("li",{children:[N.reference?.url?t.jsx("img",{src:N.reference.url,alt:""}):t.jsx("span",{className:"shot-series-dot",style:{background:N.color}}),t.jsxs("span",{children:[N.name,N.figure?t.jsxs("small",{children:[" · ",N.figure.height.toFixed(2)," m"]}):null]}),t.jsx("button",{"aria-label":a("Đưa {0} vào cảnh",[N.name]),disabled:o,onClick:()=>E(N),children:"+"})]},N.id))}),t.jsx("button",{disabled:o||y||!s||!["person","model"].includes(s.kind),onClick:()=>void S(),children:s?.castId?a("Cập nhật nhân vật vào series"):a("Lưu nhân vật đang chọn vào series")}),t.jsxs("h4",{children:[a("Bối cảnh")," · ",m.locations.length]}),t.jsx("ul",{className:"shot-series-list",children:m.locations.map(N=>t.jsxs("li",{className:b.location===N.id?"active":"",children:[t.jsx("span",{className:"shot-series-dot","aria-hidden":"true",children:"⌂"}),t.jsxs("span",{children:[N.name,N.setId?t.jsxs("small",{children:[" · ",a("có set")]}):null]}),t.jsx("button",{"aria-label":a("Áp dụng bối cảnh {0}",[N.name]),disabled:o,onClick:()=>M(N),children:a("Dùng")})]},N.id))}),t.jsx("button",{disabled:o||y,onClick:()=>{const N=window.prompt(a("Tên bối cảnh"),e.items.find(R=>R.kind==="set")?.name||`Bối cảnh ${m.locations.length+1}`);N?.trim()&&j(N.trim().slice(0,60))},children:a("Lưu bối cảnh hiện tại vào series")})]})]}):t.jsxs("div",{className:"shot-series",children:[t.jsxs("select",{"aria-label":a("Chọn series"),value:"",disabled:o||!h?.length,onChange:N=>{const R=h?.find(A=>A.id===N.target.value);R&&i(A=>({...A,series:{id:R.id,name:R.name}}))},children:[t.jsx("option",{value:"",children:h===null?a("Đang tải…"):h.length?a("Gắn shot vào series…"):a("Chưa có series")}),h?.map(N=>t.jsx("option",{value:N.id,children:N.name},N.id))]}),t.jsxs("form",{className:"shot-series-row",onSubmit:N=>{N.preventDefault(),w()},children:[t.jsx("input",{"aria-label":a("Tên series mới"),placeholder:a('Tên series mới, ví dụ "Chuyện quán cà phê"'),maxLength:80,value:f,onChange:N=>p(N.target.value),disabled:o||y}),t.jsx("button",{disabled:o||y||!f.trim(),children:a("Tạo")})]}),t.jsx("small",{className:"shot-hint",children:a("Series giữ dàn nhân vật và bối cảnh dùng chung cho mọi shot, mọi canvas. Sửa nhân vật trong series thì mọi shot dùng nhân vật đó cập nhật theo.")})]})}const Uh=e=>`f/${Number(e.toFixed(1))}`,ij=e=>Go.reduce((n,s,o)=>Math.abs(Math.log(s/e))<Math.abs(Math.log(Go[n]/e))?o:n,0),rj=()=>globalThis.crypto?.randomUUID?.()??`fk-${Math.random().toString(36).slice(2)}`;function lj({shot:e,items:n,progress:s,presetFstop:o,onChange:i}){const r=e.focus,l=r?.keys||[],h=ic(r?.fstop??o),u=n.filter(b=>b.kind!=="fx"&&b.kind!=="set"),m=b=>b?n.find(k=>k.id===b)?.name??"?":"",d=b=>i(Object.keys(b).length?b:void 0),f=b=>{const k={...r||{},...b};for(const w of Object.keys(k))k[w]===void 0&&delete k[w];d(k)},p=r?.subject?n.find(b=>b.id===r.subject):void 0,y=(()=>{if(!p)return"";const b=[p.position[0],p.position[1]+(p.kind==="person"?1.6*(p.scale?.[1]||1):.4),p.position[2]],k=Math.hypot(b[0]-e.position[0],b[1]-e.position[1],b[2]-e.position[2]),w=Pf(k,e.lens,h);return`${w.near.toFixed(1)}–${Number.isFinite(w.far)?`${w.far.toFixed(1)} m`:"∞"}`})(),g=()=>{const b=Math.min(1,Math.max(0,s)),k=l.find(S=>Math.abs(S.time-b)<1e-4),w={id:k?.id??rj(),time:k?.time??b,...r?.subject?{subject:r.subject}:r?.distance!==void 0?{distance:r.distance}:{},fstop:h};d({...r||{},keys:[...l.filter(S=>S!==k),w].sort((S,E)=>S.time-E.time)})},v=b=>{const k=l.filter(E=>E.id!==b),{keys:w,...S}=r||{};d(k.length?{...S,keys:k}:S)};return t.jsxs("div",{className:"shot-focus","data-testid":"shot-focus",children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Lấy nét vào (shot này)")}),t.jsxs("select",{"aria-label":a("Lấy nét vào (shot này)"),value:r?.subject??"",onChange:b=>f({subject:b.target.value||void 0,distance:void 0}),children:[t.jsx("option",{value:"",children:a("Tự động (mục tiêu camera)")}),u.map(b=>t.jsx("option",{value:b.id,children:b.name},b.id))]})]}),t.jsxs("label",{className:"shot-joint",children:[a("Khẩu độ")," ",t.jsx("span",{children:Uh(h)}),t.jsx("input",{"aria-label":a("Khẩu độ"),type:"range",min:0,max:Go.length-1,step:1,value:ij(h),onChange:b=>f({fstop:Go[+b.target.value]})})]}),t.jsx("small",{className:"shot-hint",children:y?a("Ống kính {0} mm · vùng nét {1}",[Math.round(e.lens),y]):a("Ống kính {0} mm",[Math.round(e.lens)])}),r?.fstop!==void 0&&t.jsx("button",{type:"button",onClick:()=>f({fstop:void 0}),children:a("Theo mức xoá phông")}),t.jsx("button",{type:"button",onClick:g,children:a("Thêm điểm lấy nét tại playhead")}),l.length>0&&t.jsxs("div",{className:"shot-focus-keys",role:"list","aria-label":a("Điểm lấy nét"),children:[t.jsx("small",{className:"shot-hint",children:a("Điểm lấy nét quyết định chỗ nét theo thời gian; nét được kéo mượt giữa các điểm.")}),l.map(b=>{const k=`${(b.time*e.duration).toFixed(2)}s`;return t.jsxs("div",{role:"listitem",className:"shot-focus-key",children:[t.jsxs("span",{children:[k," · ",b.subject?m(b.subject):b.distance!==void 0?`${b.distance.toFixed(1)} m`:a("Tự động")," · ",Uh(ic(b.fstop??r?.fstop??o))]}),t.jsx("button",{type:"button","aria-label":a("Xoá điểm lấy nét {0}",[k]),title:a("Xoá điểm lấy nét {0}",[k]),onClick:()=>v(b.id),children:"×"})]},b.id)}),t.jsx("button",{type:"button",onClick:()=>{const{keys:b,...k}=r||{};d(k)},children:a("Xoá hết điểm lấy nét")})]})]})}const Xh=(e,n,s)=>Math.max(n,Math.min(s,e)),ns=e=>Math.round(e*100)/100;function cj(e,n,s=45){const o=n[0]-e[0],i=n[1]-e[1],r=n[2]-e[2],l=Math.hypot(o,r),h=Xh(Math.hypot(o,i,r),1.6,60),u=l>.05?Math.atan2(o,r):.35,m=(d,f,p,y=.25)=>{const g=u+d*Math.PI/180,v=p*Math.PI/180,b=h*f,k=Math.cos(v)*b;return[ns(e[0]+Math.sin(g)*k),ns(Math.max(y,e[1]+Math.sin(v)*b)),ns(e[2]+Math.cos(g)*k)]};return[{id:"wide",label:"Toàn cảnh",subtitle:"28mm · Thiết lập không gian",camera:m(-18,1.45,22),target:[...e],lens:28},{id:"hero_34",label:"Trung cảnh 3/4",subtitle:"45mm · Góc kể chuyện chuẩn",camera:m(36,1,14),target:[...e],lens:Xh(Math.round(s),35,55)},{id:"low_hero",label:"Góc thấp anh hùng",subtitle:"35mm · Tạo cảm giác uy lực",camera:m(-28,.82,-6,.3),target:[ns(e[0]),ns(e[1]+.15),ns(e[2])],lens:35},{id:"closeup",label:"Cận cảnh",subtitle:"70mm · Nhấn biểu cảm & chi tiết",camera:m(12,.56,8),target:[ns(e[0]),ns(e[1]+.12),ns(e[2])],lens:70},{id:"top_down",label:"Từ trên xuống",subtitle:"35mm · Toàn cục & địa hình",camera:m(0,1.38,68),target:[...e],lens:35},{id:"reverse",label:"Góc ngược vai",subtitle:"50mm · Đối thoại / kịch tính",camera:m(152,.92,12),target:[...e],lens:50}]}function hj({x:e,y:n,items:s,canPaste:o,hiddenCount:i,blenderKeys:r,renaming:l,onBlenderKeys:h,onAction:u,onRename:m,onClose:d}){const f=I.useRef(null),[p,y]=I.useState({left:e,top:n}),[g,v]=I.useState(s[0]?.name??""),b=N=>s.length>0&&s.every(N),k=s[0]?.shading,w=N=>r?N:void 0,S=s.length?[[{action:"shade-smooth",label:"Bề mặt mượt",check:"shading",checked:b(N=>N.shading==="smooth")},{action:"shade-auto",label:"Mượt tự động (30°)",check:"shading",checked:b(N=>N.shading==="auto")},{action:"shade-flat",label:"Bề mặt phẳng",check:"shading",checked:b(N=>N.shading==="flat")},...k||s.some(N=>N.shading)?[{action:"shade-reset",label:"Bề mặt như gốc",check:"shading"}]:[]],[{action:"origin-center",label:"Đặt tâm vào giữa khối",check:"origin"},{action:"origin-bottom",label:"Đặt tâm ở đáy khối",check:"origin"},...s.some(N=>N.origin)?[{action:"origin-reset",label:"Tâm như gốc",check:"origin"}]:[]],[{action:"copy",label:"Sao chép",keys:"Ctrl+C",check:"copy"},{action:"paste",label:"Dán",keys:"Ctrl+V"},{action:"duplicate",label:"Nhân bản",keys:w("Shift+D"),check:"duplicate"},{action:"duplicate-linked",label:"Nhân bản liên kết",keys:w("Alt+D"),check:"duplicate"},...s.some(N=>N.link)?[{action:"unlink",label:"Bỏ liên kết",check:"unlink"}]:[]],[{action:"mirror-x",label:"Lật theo X",check:"mirror",checked:b(N=>(N.mirror?.[0]??1)<0)},{action:"mirror-y",label:"Lật theo Y",check:"mirror",checked:b(N=>(N.mirror?.[1]??1)<0)},{action:"mirror-z",label:"Lật theo Z",check:"mirror",checked:b(N=>(N.mirror?.[2]??1)<0)},{action:"key",label:"Thêm key",keys:"K",check:"key"},{action:"physics-drop",label:"Rơi tự nhiên…",check:"physics"}],[{action:"hide",label:"Ẩn",keys:w("H"),check:"hide"},{action:"lock",label:b(N=>N.locked)?"Mở khoá":"Khoá",check:"lock"},{action:"delete",label:"Xoá",keys:w("X"),check:"delete"}],[{action:"rig",label:"AI · Auto-Rig…",check:"rig"},{action:"rig",label:"AI · Retexture",soon:!0}]]:[[{action:"paste",label:"Dán",keys:"Ctrl+V"},{action:"select-all",label:"Chọn tất cả",keys:w("A")},{action:"box-select",label:"Chọn theo vùng",keys:w("B")},{action:"unhide-all",label:"Hiện tất cả",keys:w("Alt+H")}]],E=N=>N.soon?"Sắp có":N.action==="paste"?o?null:"Chưa sao chép đối tượng nào":N.action==="unhide-all"?i?null:"Không có đối tượng nào đang ẩn":N.check?s.some(R=>!Eo(R,N.check))?null:Eo(s[0],N.check):null,j=s.length!==1?"Chọn một đối tượng để đổi tên":Eo(s[0],"rename");I.useLayoutEffect(()=>{const N=f.current;if(!N)return;const R=N.getBoundingClientRect();y({left:Math.max(4,Math.min(e,innerWidth-R.width-4)),top:Math.max(4,Math.min(n,innerHeight-R.height-4))})},[e,n,l]),I.useEffect(()=>{const N=f.current;if(!N)return;l?N.querySelector("input[type=text]")?.select():N.querySelector("[role=menuitem]:not([disabled])")?.focus();const R=A=>{N.contains(A.target)||d()};return document.addEventListener("mousedown",R,!0),()=>document.removeEventListener("mousedown",R,!0)},[l,d]);const M=N=>{if(N.key==="Escape"){N.preventDefault(),d();return}if(N.key!=="ArrowDown"&&N.key!=="ArrowUp")return;N.preventDefault();const R=[...f.current.querySelectorAll("[role=menuitem]:not([disabled]),[role=menuitemcheckbox]")],A=R.indexOf(document.activeElement);R[(A+(N.key==="ArrowDown"?1:-1)+R.length)%R.length]?.focus()},T=s.length>1?a("{0} đối tượng",[s.length]):s[0]?.name;return t.jsxs("div",{className:"shot-ctxmenu",role:"menu","aria-label":a("Menu đối tượng"),ref:f,style:p,onKeyDown:M,onContextMenu:N=>N.preventDefault(),children:[T&&t.jsx("div",{className:"shot-ctxmenu-title",children:T}),l?t.jsxs("form",{className:"shot-ctxmenu-rename",onSubmit:N=>{N.preventDefault(),g.trim()&&m(g.trim().slice(0,80))},children:[t.jsx("input",{type:"text","aria-label":a("Tên mới"),value:g,maxLength:80,onChange:N=>v(N.target.value)}),t.jsx("button",{type:"submit",children:a("Đổi tên")})]}):t.jsxs(t.Fragment,{children:[s.length>0&&t.jsxs("button",{type:"button",role:"menuitem",disabled:!!j,title:j?a(j):void 0,onClick:()=>u("rename"),children:[t.jsx("span",{children:a("Đổi tên…")}),r&&t.jsx("kbd",{children:"F2"})]}),S.map((N,R)=>t.jsx("div",{className:"shot-ctxmenu-group",role:"group",children:N.map((A,C)=>{const O=E(A);return t.jsxs("button",{type:"button",role:"menuitem",disabled:!!O,title:O?a(O):void 0,"aria-checked":A.checked===void 0?void 0:A.checked,className:A.checked?"checked":"",onClick:()=>u(A.action),children:[t.jsxs("span",{children:[A.checked?"✓ ":"",a(A.label),A.soon?t.jsxs("small",{children:[" · ",a("Sắp có")]}):null]}),A.keys&&t.jsx("kbd",{children:A.keys})]},A.action+C)})},R)),t.jsxs("button",{type:"button",className:"shot-ctxmenu-keys",role:"menuitemcheckbox","aria-checked":r,onClick:()=>h(!r),children:[t.jsxs("span",{children:[r?"☑":"☐"," ",a("Phím tắt kiểu Blender")]}),t.jsx("small",{children:"G R S · Shift+D · X · H · A · B"})]})]})]})}const dj=[{id:"above",label:"Thả từ trên cao"},{id:"here",label:"Từ vị trí hiện tại"}],uj=[{id:"bouncy",label:"Nảy nhiều"},{id:"normal",label:"Vừa"},{id:"heavy",label:"Nặng"}];function mj({count:e,start:n,left:s,busy:o,onRun:i,onClose:r}){const[l,h]=I.useState({mode:"above",bounciness:"normal",duration:3}),u=I.useRef(null);I.useEffect(()=>{u.current?.querySelector("button.active")?.focus()},[]);const m=Math.min(l.duration,s);return t.jsxs("form",{ref:u,className:"shot-ctxmenu shot-drop",role:"dialog","aria-label":a("Rơi tự nhiên"),onSubmit:d=>{d.preventDefault(),!o&&s>=.25&&i(l)},onKeyDown:d=>{d.key==="Escape"&&(d.preventDefault(),r())},children:[t.jsx("div",{className:"shot-ctxmenu-title",children:a("Rơi tự nhiên · {0} đối tượng",[e])}),t.jsx("div",{className:"shot-seg shot-seg-2",role:"group","aria-label":a("Bắt đầu rơi"),children:dj.map(d=>t.jsx("button",{type:"button",className:l.mode===d.id?"active":"","aria-pressed":l.mode===d.id,onClick:()=>h({...l,mode:d.id}),children:a(d.label)},d.id))}),t.jsx("div",{className:"shot-seg",role:"group","aria-label":a("Độ nảy"),children:uj.map(d=>t.jsx("button",{type:"button",className:l.bounciness===d.id?"active":"","aria-pressed":l.bounciness===d.id,onClick:()=>h({...l,bounciness:d.id}),children:a(d.label)},d.id))}),t.jsxs("label",{className:"shot-drop-row",children:[a("Thời lượng")," ",t.jsxs("b",{children:[l.duration,a("s")]}),t.jsx("input",{type:"range",min:1,max:6,step:.5,value:l.duration,"aria-label":a("Thời lượng rơi"),onChange:d=>h({...l,duration:+d.target.value})})]}),t.jsx("small",{className:"shot-drop-hint",children:s<.25?a("Đầu phát đang ở cuối shot — kéo về trước rồi thử lại."):a("Từ {0}s đến {1}s · ghi thành key thường, Ctrl+Z để hoàn tác",[n.toFixed(1),(n+m).toFixed(1)])}),t.jsxs("div",{className:"shot-drop-actions",children:[t.jsx("button",{type:"button",onClick:r,children:a("Huỷ")}),t.jsx("button",{type:"submit",className:"shot-primary",disabled:o||s<.25,children:o?a("Đang mô phỏng…"):a("Mô phỏng")})]})]})}is.plateUrl=e=>kg({gcsUri:e.gcsUri,url:e.url});const Zi=[["person","Nhân vật"],["box","Hộp"],["sphere","Cầu"],["cylinder","Trụ"],["wall","Tường"],["platform","Bục"],["floor","Sàn"]],Ao=[["scene","Dựng cảnh",t.jsx(Ce.scene,{},"scene")],["objects","Đối tượng",t.jsx(Ce.objects,{},"objects")],["material","Vật liệu",t.jsx(Ce.material,{},"material")],["rigging","Rigging · gắn xương",t.jsx(B1,{},"rigging")],["modeling","Dựng model",t.jsx(Bd,{},"modeling")],["camera","Camera & shot",t.jsx(Ce.camera,{},"camera")],["light","Ánh sáng cảnh",t.jsx(Ce.light,{},"light")],["shots","Danh sách shot",t.jsx(Ce.film,{},"shots")],["notes","Ghi chú 3D",t.jsx(Ce.note,{},"notes")],["series","Series",t.jsx(Ce.series,{},"series")],["fx","Hiệu ứng",t.jsx(Ce.fx,{},"fx")],["fxedit","Sửa hiệu ứng",t.jsx(Ce.pen,{},"fxedit")],["mixfx","Mix FX",t.jsx(Ce.mixfx,{},"mixfx")]],Ji={drawer:300,right:320,timeline:210},pj={person:t.jsx(Ce.person,{}),box:t.jsx(Ce.box,{}),sphere:t.jsx(Ce.sphere,{}),cylinder:t.jsx(Ce.cylinder,{}),wall:t.jsx(Ce.wall,{}),platform:t.jsx(Ce.platform,{}),floor:t.jsx(Ce.floor,{}),model:t.jsx(Ce.cube,{}),proxy:t.jsx(Ce.cube,{}),splat:t.jsx(Ce.image,{}),prop:t.jsx(Ce.key,{}),fx:t.jsx(Ce.fx,{})},Do={shoulderL:"Vai trái",shoulderR:"Vai phải",elbowL:"Khuỷu trái",elbowR:"Khuỷu phải",hipL:"Hông trái",hipR:"Hông phải",kneeL:"Gối trái",kneeR:"Gối phải",head:"Hướng đầu",lean:"Nghiêng thân",shoulderOutL:"Dang vai trái",shoulderOutR:"Dang vai phải",hipOutL:"Dang hông trái",hipOutR:"Dang hông phải",wristL:"Cổ tay trái",wristR:"Cổ tay phải",ankleL:"Cổ chân trái",ankleR:"Cổ chân phải",spineTwist:"Xoay cột sống"};function ss({label:e,value:n,onChange:s,min:o=-100,max:i=100,step:r=.1}){return rt(),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a(e)}),t.jsx(Tn,{"aria-label":a(e),precision:2,value:n,min:o,max:i,step:r,onCommit:s})]})}function To({label:e,root:n,bend:s,upper:o,lower:i,onChange:r}){rt();const l=I.useRef(null),h=_0(n,s,o,i),u=o+i,m=f=>{const p=l.current.getBoundingClientRect(),y=((f.clientX-p.left)/p.width*2-1)*u,g=((f.clientY-p.top)/p.height*2-1)*u,v=z0(y,g,o,i);r(Math.round(v.root),Math.round(v.bend))},d=f=>{f.preventDefault(),m(f);const p=g=>m(g),y=()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",y)};window.addEventListener("mousemove",p),window.addEventListener("mouseup",y)};return t.jsxs("div",{children:[t.jsx("small",{children:a(e)}),t.jsx("div",{ref:l,className:"shot-ik-pad",onMouseDown:d,children:t.jsx("i",{style:{left:`${50+h.forward/u*50}%`,top:`${50+h.down/u*50}%`}})})]})}const er={headPitch:"Cúi / ngẩng đầu",headRoll:"Nghiêng đầu",eyeYaw:"Mắt liếc trái / phải",eyePitch:"Mắt liếc lên / xuống",blink:"Nhắm mắt",gripL:"Nắm tay trái",indexL:"Ngón trỏ trái",middleL:"Ngón giữa trái",ringL:"Ngón áp út trái",pinkyL:"Ngón út trái",thumbL:"Ngón cái trái",spreadL:"Xoè ngón tay trái",wristTwistL:"Xoay cổ tay trái",wristSideL:"Nghiêng cổ tay trái",gripR:"Nắm tay phải",indexR:"Ngón trỏ phải",middleR:"Ngón giữa phải",ringR:"Ngón áp út phải",pinkyR:"Ngón út phải",thumbR:"Ngón cái phải",spreadR:"Xoè ngón tay phải",wristTwistR:"Xoay cổ tay phải",wristSideR:"Nghiêng cổ tay phải",smile:"Biểu cảm: cười",angry:"Biểu cảm: giận dữ",surprise:"Biểu cảm: ngạc nhiên",sad:"Biểu cảm: buồn",pain:"Biểu cảm: đau"},fj=(e,n)=>{if(e[n]!==void 0)return e[n];const s=n.endsWith("L")?"L":"R",o=n.slice(0,-1);return R0.includes(o)?Math.round(I0(e,s)[o]):0},gj=(e,n,s)=>yd(e,n,s);function xj(e,n){return Object.keys(Do).every(s=>(e[s]||0)===(n[s]||0))}const Vh="clipoox.shot.objectClipboard",bj=e=>e.kind==="person"||e.kind==="model"&&e.skeleton==="native";function qj({nodeId:e,headless:n=!1,background:s}){rt();const[o,i]=I.useState(null),[r,l]=I.useState(!1),h=I.useRef(!1),[u,m]=I.useState(!1),[d,f]=I.useState(null),[p,y]=I.useState(!1),g=I.useRef([]),[v,b]=I.useState(!1),[k,w]=I.useState(!1),[S,E]=I.useState(!1),[j,M]=I.useState(null),[T,N]=I.useState([]),[R,A]=I.useState(!1),[C,O]=I.useState(null),[B,D]=I.useState(!1),[$,W]=I.useState(!1),[z,Y]=I.useState(()=>{const c=Ot()?.getNode(e)?.data.shotScene;if(c)return fc(gc(c));const x=Ff();return x.items=x.items.map((L,F)=>({...L,name:`${a(Zi.find(([K])=>K===L.kind)?.[1]||"Model")} ${F+1}`})),x}),[J,V]=I.useState(z.items[0]?.id||null),[H,G]=I.useState([]),[_,ee]=I.useState("translate"),[Q,ve]=I.useState(()=>{try{const c=localStorage.getItem("clipoox.shot.panel");return Ao.some(x=>x[0]===c)?c:null}catch{return null}}),[ye,q]=I.useState(()=>{try{return localStorage.getItem("clipoox.shot.railWide")==="1"}catch{return!1}}),[pe,ue]=I.useState(()=>{try{return{...Ji,...JSON.parse(localStorage.getItem("clipoox.shot.layout")||"{}")}}catch{return Ji}}),[U,re]=I.useState(()=>{try{return localStorage.getItem("clipoox.shot.tools")!=="0"}catch{return!0}}),[ce,Ee]=I.useState(!1),[je,le]=I.useState($f),[Le,Ae]=I.useState(!1),[we,he]=I.useState("shot"),[ke,Pe]=I.useState({done:0,total:64}),[Te,Be]=I.useState(0),[ze,Ke]=I.useState(null),[Je,P]=I.useState(Jr),[te,Z]=I.useState([]),[ie,me]=I.useState(!1),[Fe,be]=I.useState(""),[lt,wt]=I.useState([]),[Zt,Xe]=I.useState(null),[ct,bt]=I.useState(!1),[Mt,gt]=I.useState(1),[st,sn]=I.useState(!1),[Ie,ot]=I.useState(0),[Jt,ut]=I.useState(null),[Lt,Gt]=I.useState({}),un=I.useRef(null),an=I.useRef(null);I.useEffect(()=>{if(!Le){an.current?.dispose(),an.current=null;return}const c=ge.current,x=un.current;if(!c||!x)return;let L=!1;return Pe({done:0,total:64}),nn(async()=>{const{ShotPathTracer:F}=await import("./pathTracer-DgL1_83l.js");return{ShotPathTracer:F}},__vite__mapDeps([19,1,6])).then(({ShotPathTracer:F})=>{if(L)return;an.current?.dispose();const K=new F(x);an.current=K,K.start(c.getPathTraceSource(),{view:we,targetSamples:64,bounces:4,onProgress:(X,se)=>{L||Pe({done:X,total:se})},onError:X=>{L||(be(`Path Trace: ${X}`),Ae(!1))}})}),()=>{L=!0,an.current?.dispose(),an.current=null}},[Le,we,Te,st]);const xt=c=>{V(c),G([])},mn=J?[J,...H.filter(c=>c!==J)]:[],It=I.useRef(mn);It.current=mn;const qt=c=>{V(c[0]??null),G(c.slice(1))},pn=(c,x=!1)=>{const L=It.current;if(!x||!c)return qt(c?[c]:x?L:[]);qt(L.includes(c)?L.filter(F=>F!==c):[c,...L])},Vn=I.useRef(pn);Vn.current=pn;const[vn,jn]=I.useState(null),[oe,Se]=I.useState(!1),$e=I.useCallback(()=>jn(null),[]),[Re,He]=I.useState(()=>{try{return localStorage.getItem("clipoox.shot.blenderKeys")!=="0"}catch{return!0}}),Ze=c=>{He(c);try{localStorage.setItem("clipoox.shot.blenderKeys",c?"1":"0")}catch{}},[Ye,Ge]=I.useState({on:!1}),Qe=I.useRef("keys"),[at,mt]=I.useState(!1),[it,Bt]=I.useState(null),[De,Pt]=I.useState(null),[Tt,on]=I.useState({mode:"all",slot:null}),fn=I.useRef(null),Et=I.useRef(Ie);Et.current=Ie,I.useEffect(()=>{Jt&&J!==Jt&&ut(null)},[J,Jt]);const Ln=I.useRef(null),Kt=I.useRef(null),kn=I.useRef(null),_e=I.useRef(null),ge=I.useRef(null),Ut=I.useRef(null),En=I.useRef(null),wn=I.useRef(null),Ne=I.useRef(z),rn=I.useRef([]),_n=I.useRef([]),Yn=ht(c=>c.saveError),Xt=ht(c=>c.saveState),Dt=Ai(c=>c.close);Ne.current=z;const St=ht(c=>c.canvasId),Ft=rc(c=>c.conflict),Qn=rc(c=>c.reloading);I.useEffect(()=>n||!St?void 0:Df(St,e,c=>{const x=fc(gc(c));rn.current=[],_n.current=[],Ne.current=x,Y(x)}),[St,e,n]),Of(n?null:St,e,()=>ht.getState().saveState!=="saved");const Me=c=>{const x=Ne.current;rn.current.push(x),rn.current.length>60&&rn.current.shift(),_n.current=[];const L={...l0(x,c(x)),revision:x.revision+1};Ne.current=L,Y(L)},ha={getStage:()=>Ne.current,setStage:Me,engine:()=>ge.current},Ds=c=>{const{item:x,fingers:L}=c0(c,Ne.current.items.length),F=it?Ne.current.items.find(X=>X.id===it&&X.kind==="person"):void 0,K=F?{...x,id:F.id,name:F.name,position:F.position,rotation:F.rotation,...F.hidden?{hidden:!0}:{}}:x;Me(X=>({...X,items:F?X.items.map(se=>se.id===F.id?K:se):[...X.items,K]})),xt(K.id),W(!1),Bt(null),L&&K.rig&&Ac(ha,K.id,K.rig)};I.useEffect(()=>{if(!st)return;const c=Ai.getState().fitFingers;if(!(!c||c.node!==e)){Ai.setState({fitFingers:null});for(const x of c.items){const L=Ne.current.items.find(F=>F.id===x);L?.rig&&Ac(ha,x,L.rig)}}},[st,e]);const zn=c=>{C&&(D(!1),ot(C.time),c&&Me(x=>Oi(x,C.plan)),C.done(c),O(null))},et=(c,x)=>{D(!1),Me(L=>eo(L,c,x))},eo=(c,x,L)=>{{const F=c.shots.find(fe=>fe.id===c.activeShot),K=c.items.find(fe=>fe.id===x),X=K.kind==="fx"?K.fx?.attach:void 0;if(X&&!(X.hand&&X.tip)&&(L.position||L.rotation)){if(pd(K,F)){const fe=Bo(c,x,Et.current,{position:L.position,yaw:L.rotation?.[1]});return L.scale?{...fe,items:fe.items.map(We=>We.id===x?{...We,scale:L.scale}:We)}:fe}return{...c,items:c.items.map(fe=>fe.id===x?{...fe,...L.scale?{scale:L.scale}:{},...L.rotation?{rotation:[fe.rotation[0],L.rotation[1],fe.rotation[2]]}:{},fx:{...fe.fx,attach:{...X,...L.position?{offset:L.position}:{}}}}:fe)}}const se=F.objectKeys?.[x]||[],xe=!!L.pose&&se.some(fe=>fe.pose);if(se.length&&(L.position||L.rotation||L.scale||xe)){const fe={...Wn(K,F,Et.current),...L},We=se,Oe=We.find(pt=>Math.abs(pt.time-Et.current)<1e-6),Ue={...Oe,id:Oe?.id||yt(),time:Et.current,position:fe.position,rotation:fe.rotation,scale:fe.scale,...xe?{pose:L.pose}:{}};return{...c,shots:c.shots.map(pt=>pt.id===c.activeShot?{...pt,objectKeys:{...pt.objectKeys,[x]:[...We.filter(kt=>kt.id!==Ue.id),Ue].sort((kt,In)=>kt.time-In.time)}}:pt)}}return K.kind==="fx"&&K.fx&&L.position&&!L.fx&&(L={...L,fx:h0(K.fx,K.position,L.position)}),{...c,items:c.items.map(fe=>fe.id===x?{...fe,...L}:fe)}}},Bu=(c,x)=>{const L={...qn[x]};if(!!!Ne.current.shots.find(X=>X.id===Ne.current.activeShot)?.objectKeys?.[c.id]?.length&&!c.hold&&ge.current){if(Pi(L)==="sit"){const X=ge.current.sitSnap(c);if(X)return et(c.id,{pose:L,...X})}else if(Pi(c.pose)==="sit"&&Pi(L)==="stand")return et(c.id,{pose:L,position:ge.current.standUp(c).position})}et(c.id,{pose:L})},nl=c=>{const x=c.filter(L=>L.fix&&!L.locked);x.length&&(D(!1),Me(L=>({...L,items:L.items.map(F=>{const K=x.find(X=>X.itemId===F.id)?.fix;return K?{...F,position:K.position,...K.rotation?{rotation:K.rotation}:{}}:F})})))},sl=c=>{D(!1),Me(x=>{const L=x.shots.find(Oe=>Oe.id===x.activeShot),F=x.items.find(Oe=>Oe.id===c),K=L.objectKeys?.[c]||[],X=Et.current,se=Wn(F,L,X),xe=(Oe,Ue)=>{const pt=Wn(F,L,Oe),kt=K.find(In=>Math.abs(In.time-Oe)<1e-6);return{...kt,id:kt?.id||yt(),time:Oe,position:pt.position,rotation:pt.rotation,scale:pt.scale,pose:structuredClone(Ue)}};let fe=[...K];if(!K.some(Oe=>Oe.pose)&&X>1e-6){const Oe=xe(0,F.pose);fe=[...fe.filter(Ue=>Ue.id!==Oe.id),Oe]}const We=xe(X,se.pose);return fe=[...fe.filter(Oe=>Oe.id!==We.id),We].sort((Oe,Ue)=>Oe.time-Ue.time),{...x,shots:x.shots.map(Oe=>Oe.id===x.activeShot?{...Oe,objectKeys:{...Oe.objectKeys,[c]:fe}}:Oe)}})},Ku=c=>{D(!1),Me(x=>{const K=(x.shots.find(X=>X.id===x.activeShot).objectKeys?.[c]||[]).map(X=>Math.abs(X.time-Et.current)<1e-6&&X.pose?(({pose:se,poseEase:xe,...fe})=>fe)(X):X);return{...x,shots:x.shots.map(X=>X.id===x.activeShot?{...X,objectKeys:{...X.objectKeys,[c]:K}}:X)}})},Hu=(c,x)=>{D(!1),Me(L=>{const X=(L.shots.find(se=>se.id===L.activeShot).objectKeys?.[c]||[]).map(se=>Math.abs(se.time-Et.current)<1e-6&&se.pose?x==="smooth"?(({poseEase:xe,...fe})=>fe)(se):{...se,poseEase:x}:se);return{...L,shots:L.shots.map(se=>se.id===L.activeShot?{...se,objectKeys:{...se.objectKeys,[c]:X}}:se)}})},al=I.useRef(null),[ls,ol]=I.useState(null),[da,Wu]=I.useState(1),[il,Gu]=I.useState(!0),[rl,ll]=I.useState(!1),qu=async c=>{if(c){be(""),ll(!0);try{if(c.size>60*1024*1024)throw new Error(a("File mocap tối đa 60 MB."));ol(await d0(c.name,await c.arrayBuffer()))}catch(x){ol(null),be(x.message)}finally{ll(!1)}}},cl=async c=>{if(De)return;D(!1),be(""),Pt({kind:c,pct:0});const x=(L,F)=>Pt({kind:c,pct:Math.round(L/F*100)});try{const L=Ne.current;if(c==="follow"){const F=L.items.find(xe=>xe.id===J&&xe.kind==="person"),K=F??L.items.find(xe=>xe.kind==="person");if(!K)throw new Error(a("Cảnh chưa có người đứng thế để bám theo."));const{followPlate:X}=await nn(async()=>{const{followPlate:xe}=await import("./plateFollow-D2rjnmZA.js");return{followPlate:xe}},__vite__mapDeps([20,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),se=await X(L,K.id,{newId:yt,progress:x});Me(()=>se.stage),ht.getState().toast(a("{0} đã bám theo người trong video: {1}/{2} khung thấy người.",[K.name,se.found,se.frames]),"ok")}else{const{trackPlateCamera:F}=await nn(async()=>{const{trackPlateCamera:X}=await import("./plateCamera-DLqlXhMp.js");return{trackPlateCamera:X}},__vite__mapDeps([21,2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16,22,23])),K=await F(L,{newId:yt,progress:x});Me(()=>K.stage),ht.getState().toast(K.mode==="travel"?a("Đã lấy camera từ video: camera đi {0} m, quay {1}°.",[K.travel,K.pan]):a("Đã lấy camera từ video: {0} key, quay {1}°.",[K.keys,K.pan]),"ok")}}catch(L){const F=L.message;be(F==="no-person-in-plate"?a("Không thấy người trong video nền."):F==="camera-not-found"?a("Không bám được camera: nền quá ít chi tiết hoặc khung hình toàn vật thể chuyển động."):F)}finally{Pt(null)}},Uu=async()=>{const{shotBlenderScript:c}=await nn(async()=>{const{shotBlenderScript:F}=await import("./plateCamera-DLqlXhMp.js");return{shotBlenderScript:F}},__vite__mapDeps([21,2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16,22,23])),x=new Blob([c(Ne.current)],{type:"text/x-python"}),L=document.createElement("a");L.href=URL.createObjectURL(x),L.download=`${(de.name||"shot").replace(/[^\w-]+/g,"_")}-camera.py`,L.click(),setTimeout(()=>URL.revokeObjectURL(L.href),4e3)},Xu=c=>{if(!ls)return;D(!1);const x=Ne.current,L=x.items.find(Oe=>Oe.id===c),F=x.shots.find(Oe=>Oe.id===x.activeShot),K=Et.current,X=ys(L,F,K),se=(1-K)*F.duration*da,xe=u0(ls,15*da,0,Math.min(ls.duration,se)).map(Oe=>({...Oe,time:Oe.time/da})),fe=.93*m0(L)*L.scale[1],We=p0(x,c,f0(xe,{position:X.position,yaw:X.rotation[1],hipHeight:fe},il),K,yt);if(!We.keys){be(a("Không còn đủ thời lượng shot sau playhead để đặt mocap."));return}Me(()=>We.stage),ht.getState().toast(a("Đã áp mocap {0}: {1} key · {2}s",[ls.name,We.keys,We.seconds]),"ok")},[ri,hl]=I.useState(!0),[li,dl]=I.useState(!1),ci=async(c,x)=>{if(D(!1),x.mocap)try{await _r(x.id)}catch(se){be(a("Không tải được dữ liệu mocap: {0}",[se.message]));return}const L=Ne.current,F=L.shots.find(se=>se.id===L.activeShot),K=Et.current,X=g0(L,c,x,{start:K,newId:yt,colliders:ge.current?.placementColliders(),camera:F.position,loop:ri,mirror:li});if(!X.ok){be(X.error.startsWith("not enough")?a("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."):X.error);return}if(!X.keys){be(a("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."));return}Me(()=>X.stage),ht.getState().toast(a('Đã áp "{0}" · {1}s',[$a(x),X.seconds])+(X.notes.length&&aa()==="vi"?` · ${X.notes[0]}`:""),"ok")},ul=(c,x,L)=>{D(!1),Me(F=>{const K=xe=>(({hold:fe,...We})=>We)(xe),X=F.items.find(xe=>xe.id===c);let se=F.items.map(xe=>xe.hold?.by===c&&xe.hold.hand===x?{...K(xe),position:[X.position[0]+(x==="R"?.4:-.4),0,X.position[2]]}:xe);if(L.startsWith("item:"))se=se.map(xe=>xe.id===L.slice(5)?{...xe,hold:{by:c,hand:x}}:xe);else if(L.startsWith("prop:")){const xe=L.slice(5);se=[...se,{...An("prop",se.length),name:Ia[xe].label,prop:{kind:xe},color:"#8a939b",hold:{by:c,hand:x}}]}return{...F,items:se}})},[Vu,ml]=I.useState(""),Yu=()=>{D(!1);let c=[];Me(L=>{const F=x0(L);return c=F.outcomes,F.stage});const x=L=>c.filter(F=>F.result===L).length;ml(c.length?a("{0} đòn · {1} trúng · {2} bị đỡ · {3} trượt",[c.length,x("head")+x("body"),x("blocked"),x("miss")])+(x("miss")?" — "+c.filter(L=>L.result==="miss").map(L=>a("{0}s thiếu {1} m",[L.time_s,L.gap_m])).join(", "):""):a('Chưa có đòn nào: đặt key tư thế kiểu "Ra đòn nhanh" giữa hai người.'))},Qu=()=>{D(!1),Me(b0),ml("")},pl=c=>{const x=Ne.current.items.find(L=>L.id===c);!x||x.locked||ie||(D(!1),Me(L=>({...L,items:L.items.filter(F=>F.id!==c),shots:L.shots.map(F=>({...F,objectKeys:Object.fromEntries(Object.entries(F.objectKeys||{}).filter(([K])=>K!==c)),...F.fxTiming?{fxTiming:Object.fromEntries(Object.entries(F.fxTiming).filter(([K])=>K!==c))}:{}}))})),j?.row===c&&M(null),N(L=>L.filter(F=>F.row!==c)),xt(L=>L===c?null:L))},fl=I.useRef(""),to=()=>{let c=fl.current;try{c=localStorage.getItem(Vh)||c}catch{}return c?y0(c):null},gl=()=>{const c=It.current;if(!c.length)return;const x=O0(Ne.current,c);fl.current=x,Qe.current="objects";try{localStorage.setItem(Vh,x)}catch{}},xl=()=>{const c=to();if(!c||ie)return;D(!1);let x=[];Me(L=>{const F=$0(L,c,yt);return x=F.ids,{...F.stage,items:F.stage.items.map(K=>x.includes(K.id)?D0(K):K)}}),qt(x)},no=c=>{const x=It.current;if(!x.length||ie)return;D(!1);let L=[];Me(F=>{const K=F0(F,x,{linked:c,newId:yt});return L=K.ids,K.stage}),L.length&&qt(L)},hi=()=>{const c=It.current.filter(x=>!Ne.current.items.find(L=>L.id===x)?.locked);!c.length||ie||(D(!1),Me(x=>P0(x,c)),j&&c.includes(j.row)&&M(null),N(x=>x.filter(L=>!c.includes(L.row))),qt(It.current.filter(x=>!c.includes(x))))},di=(c,x,L)=>{c.length&&(D(!1),Me(F=>({...F,items:F.items.map(K=>c.includes(K.id)?{...K,[x]:L}:K)})))},bl=()=>{const c=It.current;c.length&&(di(c,"hidden",!0),qt([]))},yl=()=>di(Ne.current.items.filter(c=>c.hidden).map(c=>c.id),"hidden",!1),vl=()=>qt(Ne.current.items.filter(c=>!c.hidden&&!c.locked).map(c=>c.id)),ui=c=>{const x=ge.current,L=It.current.filter(F=>!Eo(Ne.current.items.find(K=>K.id===F),"origin"));!x||!L.length||(D(!1),Me(F=>L.reduce((K,X)=>{if(c==="reset")return pc(K,X,null,!0);const se=x.builtBounds(X),xe=K.items.find(Oe=>Oe.id===X);if(!se||!xe)return K;const fe=xe.origin||[0,0,0],We=[(se.min[0]+se.max[0])/2,c==="bottom"?se.min[1]:(se.min[1]+se.max[1])/2,(se.min[2]+se.max[2])/2];return pc(K,X,We.map((Oe,Ue)=>Oe-fe[Ue]))},F)))},jl=()=>{const c=It.current;if(c.length===1)return pi(c[0]);if(!c.length)return;const x=Et.current;D(!1),Me(L=>{const F=L.shots.find(X=>X.id===L.activeShot),K={...F.objectKeys};for(const X of c){const se=L.items.find(Ue=>Ue.id===X);if(!se||se.locked||se.hold||se.kind==="fx"&&se.fx?.attach)continue;const xe=Wn(se,F,x),fe=K[X]||[],We=fe.find(Ue=>Math.abs(Ue.time-x)<1e-6),Oe={...We,id:We?.id||yt(),time:x,position:xe.position,rotation:xe.rotation,scale:xe.scale};K[X]=[...fe.filter(Ue=>Ue.id!==Oe.id),Oe].sort((Ue,pt)=>Ue.time-pt.time)}return{...L,shots:L.shots.map(X=>X.id===L.activeShot?{...X,objectKeys:K}:X)}})},mi=(c,x,L)=>{ie||C||(c&&!It.current.includes(c)&&pn(c),jn({x,y:L,scene:!c}))},kl=I.useRef(mi);kl.current=mi;const Zu=()=>{const c=Ln.current?.getBoundingClientRect();jn({x:c?c.left+c.width/2-110:200,y:c?c.top+c.height/3:200,renaming:!0})},Ju=c=>{const x=It.current;if(c==="rename"){jn(L=>L&&{...L,renaming:!0});return}switch(jn(null),c){case"shade-smooth":case"shade-auto":case"shade-flat":case"shade-reset":{const L=c==="shade-reset"?null:c.slice(6);D(!1),Me(F=>k0(F,x,L));return}case"origin-center":return ui("center");case"origin-bottom":return ui("bottom");case"origin-reset":return ui("reset");case"copy":return gl();case"paste":return xl();case"duplicate":return no(!1);case"duplicate-linked":return no(!0);case"unlink":D(!1),Me(L=>j0(L,x));return;case"mirror-x":case"mirror-y":case"mirror-z":D(!1),Me(L=>v0(L,x,c.slice(7)));return;case"key":return jl();case"physics-drop":D(!1),Se(!0);return;case"hide":return bl();case"lock":return di(x,"locked",!x.every(L=>Ne.current.items.find(F=>F.id===L)?.locked));case"delete":return hi();case"rig":{const L=x.find(F=>Ne.current.items.find(K=>K.id===F)?.kind==="model");L&&(xt(L),Zn("rigging"));return}case"select-all":return vl();case"unhide-all":return yl();case"box-select":return Ge({on:!0})}},em=async c=>{const x=Ne.current,L=x.shots.find(Ue=>Ue.id===x.activeShot),F=Et.current,K=It.current,X=await nn(()=>import("./sceneTrack-CO4fTjft.js").then(Ue=>Ue.$),__vite__mapDeps([10,1])),se=K.map(Ue=>x.items.find(pt=>pt.id===Ue)).filter(Ue=>!!Ue&&!X.dropUnavailable(Ue)&&!(Ue.kind==="prop"&&Ue.prop?.kind==="ball"&&L.ball?.[Ue.id]?.length)).slice(0,X.MAX_PHYSICS_BODIES);if(!se.length){Se(!1),be(a("Không có đối tượng nào rơi được trong vùng chọn (nhân vật, hiệu ứng, sàn, đồ đang cầm hay đã khoá thì không)."));return}const xe=F,fe=Math.min(c.duration,(1-xe)*L.duration),We=ge.current,Oe=se.map(Ue=>Ue.id);me(!0),be("");try{const Ue=We?.physicsShapes(Oe)??{},pt=(We?.placementColliders()??[]).filter($t=>!Oe.includes($t.itemId)),kt=Object.fromEntries(se.map($t=>[$t.id,(L.objectKeys?.[$t.id]||[]).filter(ln=>ln.time<xe-1e-6).sort((ln,Ns)=>ln.time-Ns.time).pop()])),In=se.map($t=>{const ln=Wn($t,L,xe);return{id:$t.id,position:ln.position,rotation:ln.rotation,shape:X.shapeKind($t),...Ue[$t.id]??X.fallbackShape($t)}}),Vt=await X.bakeDrop({bodies:In,statics:pt,mode:c.mode,bounciness:c.bounciness,duration:fe,start:xe*L.duration,shotDuration:L.duration,seed:Oe.join(","),before:kt,seam:L.lockUntil?L.lockUntil/L.duration:null}),Mn=Object.fromEntries(se.map($t=>[$t.id,Wn($t,L,xe).scale]));Me($t=>X.applyDropKeys($t,L.id,Vt.tracks,{scale:Mn,newId:yt,lifted:c.mode==="above"})),Se(!1)}catch(Ue){be(a("Không mô phỏng được: {0}",[Ue.message]))}finally{me(!1)}},tm=c=>{const x=c.code;return c.shiftKey&&!c.altKey&&x==="KeyD"?(no(!1),!0):c.altKey&&!c.shiftKey&&x==="KeyD"?(no(!0),!0):c.altKey&&!c.shiftKey&&x==="KeyH"?(yl(),!0):c.altKey&&!c.shiftKey&&x==="KeyA"?(qt([]),!0):c.altKey||c.shiftKey?!1:x==="KeyG"||x==="KeyR"||x==="KeyS"&&!r?(ee(x==="KeyG"?"translate":x==="KeyR"?"rotate":"scale"),!0):x==="KeyX"?(Q==="rigging"&&fn.current?.del()||hi(),!0):x==="KeyH"?(bl(),!0):x==="KeyA"?(vl(),!0):x==="KeyB"?(Ge({on:!0}),!0):x==="F2"&&It.current.length===1?(Zu(),!0):!1},so=(c=!1)=>{const x=c?_n.current:rn.current,L=c?rn.current:_n.current,F=x.pop();F&&(L.push(Ne.current),Ne.current=F,Y(F))};I.useEffect(()=>{wu()},[]),I.useEffect(()=>{ge.current?.setPlatePlaying(B)},[B]),I.useEffect(()=>{nn(()=>import("./videoExport-Cz02XKtX.js"),__vite__mapDeps([24,2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16,25,26,27])).catch(()=>{})},[]),I.useEffect(()=>{try{ge.current=new is(Ln.current,_e.current,(c,x)=>Vn.current(c,x),(c,x)=>et(c,x),yg,be,c=>vg(c).then(x=>x.recipe)),ge.current.onContext=(c,x,L)=>kl.current(c,x,L),ge.current.commitMany=c=>{D(!1),Me(x=>c.reduce((L,F)=>eo(L,F.id,F.patch),x))},ge.current.setCameraEditor({select:c=>{l(c&&!h.current),c&&(xt(null),i(null),ee(x=>x==="scale"?"translate":x))},commit:c=>jt(c)}),ge.current.sync(Ne.current,J),sn(!0)}catch(c){be(`Không khởi tạo được 3D: ${c.message}`)}return()=>ge.current?.dispose()},[]),I.useEffect(()=>{ge.current?.sync(C?.stage||z,C?null:J,C?[]:H)},[z,J,H,C]),I.useEffect(()=>{const c={getStage:()=>Ne.current,setStage:F=>{D(!1),Me(F)},engine:()=>ge.current,timelineClip:F=>ht.getState().clips.find(K=>K.id===F),undo:(F,K)=>{let X=0;for(let se=0;se<K;se++){const xe=Ne.current;if(so(F),Ne.current===xe)break;X++}return X},...n?{}:{exportVideo:async F=>{const K=ge.current;if(!K)throw new Error("3D chưa sẵn sàng");K.sync(Ne.current,null),me(!0),be("");try{const{blob:X,cleanup:se}=await K.exportVideo({...F,signal:new AbortController().signal,progress:()=>{}});try{return Ut.current=null,En.current=null,wn.current=null,await xi(X,F,"canvas"),{nodeId:Ut.current||void 0,url:En.current||void 0,gcsUri:wn.current||void 0}}finally{await se()}}finally{me(!1)}},exportVfx:async F=>{me(!0),be("");try{return await gi(F)}finally{me(!1)}},exportFrame:F=>cs(!0,Ne.current.shots.find(K=>K.id===Ne.current.activeShot),0,!0,F)}};if(s){jc().then(F=>lc(!!F?.allowed)).catch(()=>{}),s({ready:()=>!!ge.current,run:(F,K)=>_f(F,K,c),exportVfx:(F,K,X)=>gi(F,K,X)});return}if(B0(c,async()=>{const F=ge.current;if(!F)throw new Error("3D chưa sẵn sàng");const K=Ne.current,X=K.shots.find(se=>se.id===K.activeShot);F.sync(K,null),me(!0),be("");try{const se={start:0,end:X.duration,fps:bn(X),height:720},{blob:xe,cleanup:fe}=await F.exportVideo({...se,signal:new AbortController().signal,progress:()=>{}});try{return Ut.current=null,En.current=null,wn.current=null,await xi(xe,se,"canvas"),{nodeId:Ut.current||void 0,url:En.current||void 0,gcsUri:wn.current||void 0}}finally{await fe()}}finally{me(!1)}}),n)return()=>cc(c);n||jc().then(F=>lc(!!F?.allowed)).catch(()=>{});const x=zf(()=>Ne.current.shots.find(F=>F.id===Ne.current.activeShot)?.name||"3D Shot"),L=ej(c,()=>Ne.current.shots.find(F=>F.id===Ne.current.activeShot)?.name||"3D Shot",F=>{const K=Ne.current.shots.find(X=>X.id===Ne.current.activeShot)?.duration||1;D(!1),ot(Math.max(0,Math.min(1,F/K))),setTimeout(()=>D(!0),50)},()=>{const F=ht.getState().canvasId;return F?`shot:${F}:${e}`:null});return()=>{x(),L(),cc(c)}},[]),I.useEffect(()=>{Ot()?.updateNodeData(e,{shotScene:z})},[z,e]),I.useEffect(()=>{h.current=S,S&&l(!1)},[S]),I.useEffect(()=>ge.current?.setCameraHidden(k),[k,st]),I.useEffect(()=>ge.current?.mode(_,ce),[_,ce,r]),I.useEffect(()=>{J&&l(!1)},[J]),I.useEffect(()=>{ge.current?.setCameraSelected(r&&!J&&!C)},[r,J,C,st]),I.useEffect(()=>{ge.current&&(ge.current.cameraTip=a("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"))},[st,aa()]),I.useEffect(()=>ge.current?.setQuality(je),[je,st]),I.useEffect(()=>{if(!st||Q!=="shots"||ie||C)return;let c=!0,x,L=0;const F=()=>{const K=ge.current;!K||!c||K.shotThumbnails(Ne.current.shots).then(X=>{c&&Gt(X)}).catch(X=>{c&&++L<8?x=setTimeout(F,1500):console.warn("[shot] thumbnails failed:",X?.message)})};return x=setTimeout(F,900),()=>{c=!1,clearTimeout(x)}},[z.revision,st,Q,ie,C]),I.useEffect(()=>ge.current?.setPreviewProgress(Ie),[Ie]),I.useEffect(()=>{if(!st||C)return;const c=()=>{const F=ge.current,K=Ne.current;if(!F)return;const X=K.shots.find(xe=>xe.id===K.activeShot),se=new Set(Object.entries(X?.objectKeys||{}).filter(([,xe])=>xe.length).map(([xe])=>xe));try{Z(w0(K,{colliders:F.placementColliders(),keyed:se}))}catch{Z([])}},x=setTimeout(c,350),L=setTimeout(c,2500);return()=>{clearTimeout(x),clearTimeout(L)}},[z.revision,st,C]),I.useEffect(()=>{const c=x=>{if(C){x.key==="Escape"&&(x.preventDefault(),zn(!1)),!x.target.closest(".shot-trial-controls")&&x.key!=="Tab"&&x.stopImmediatePropagation();return}if(x.target.closest(".shot-ctxmenu")||x.target.closest(".shot-playhead-handle")&&["ArrowLeft","ArrowRight","Home","End",",","."].includes(x.key))return;const L=x.target.closest(".shot-fmt");if(!(L&&(["Enter","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End"].includes(x.key)||x.key==="Escape"&&L.querySelector(".shot-fmt-pop"))||(x.stopImmediatePropagation(),x.target.closest('input,textarea,select,[contenteditable="true"],[role="textbox"]')||ie))){if((x.metaKey||x.ctrlKey)&&x.key.toLowerCase()==="z")x.preventDefault(),so(x.shiftKey);else if((x.key==="Delete"||x.key==="Backspace")&&(j||T.length)&&x.target.closest(".shot-timeline"))x.preventDefault(),Pl();else if((x.key==="Delete"||x.key==="Backspace")&&x.target.closest?.(".shot-shotlist li"))x.preventDefault(),Cl(x.target.closest(".shot-shotlist li").dataset.shot);else if((x.key==="Delete"||x.key==="Backspace")&&Q==="rigging"&&fn.current?.del())x.preventDefault();else if((x.key==="Delete"||x.key==="Backspace")&&!R&&J&&!ge.current?.transform.object?.userData.cameraKey)x.preventDefault(),hi();else if((x.metaKey||x.ctrlKey)&&!x.altKey&&["c","v"].includes(x.key.toLowerCase())){const K=!!x.target.closest(".shot-timeline");x.key.toLowerCase()==="c"?K||Ss.length?(x.preventDefault(),El()):mn.length&&!R&&(x.preventDefault(),gl()):K||g.current.length&&(Qe.current==="keys"||!to())?g.current.length&&(x.preventDefault(),Rl()):!R&&to()&&(x.preventDefault(),xl())}else if(!R&&!x.metaKey&&!x.ctrlKey&&!x.altKey&&!x.shiftKey&&x.code==="KeyF")x.preventDefault(),ge.current?.view();else if(Re&&!R&&!x.metaKey&&!x.ctrlKey&&tm(x))x.preventDefault();else if(x.altKey&&(x.code==="Comma"||x.code==="Period"))x.preventDefault(),Il(x.code==="Period"?1:-1);else if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!R&&x.key.toLowerCase()==="k"){const K=j?.row??J??(r?"camera":null);x.shiftKey?(x.preventDefault(),Ll()):!j&&mn.length>1?(x.preventDefault(),jl()):K&&(x.preventDefault(),pi(K))}else if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!R&&["l","i","o"].includes(x.key.toLowerCase())){x.preventDefault();const K=x.key.toLowerCase();K==="l"?m(X=>!X):mm(K==="i"?"in":"out")}else if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!R&&(x.key===" "||x.key===","||x.key==="."||x.key==="Home"||x.key==="End"))if(x.preventDefault(),x.key===" ")D(K=>(!K&&Ie>=1&&ot(0),!K));else{D(!1);const K=z.shots.find(se=>se.id===z.activeShot),X=bn(K);ot(x.key==="Home"?0:x.key==="End"?1:Math.max(0,Math.min(1,(Math.round(Ie*K.duration*X)+(x.key==="."?1:-1))/X/K.duration)))}else if(r&&!R&&["w","e"].includes(x.key.toLowerCase())&&!x.metaKey&&!x.ctrlKey&&!x.altKey)x.preventDefault(),ee(x.key.toLowerCase()==="w"?"translate":"rotate");else if(x.key==="Escape"){if(Jt){ut(null);return}if(Ye.on){Ge({on:!1});return}if(vn){jn(null);return}if(Q==="rigging"&&fn.current?.esc())return;r&&!R?l(!1):R?A(!1):Q?Zn(null):Dt()}}};return window.addEventListener("keydown",c,!0),()=>window.removeEventListener("keydown",c,!0)},[Dt,ie,R,J,H,j,T,z,C,Q,r,Ie,d,Re,Ye.on,vn,Jt]);const de=(C?.stage||z).shots.find(c=>c.id===z.activeShot),wl=z.items.find(c=>c.id===J),ne=wl?Wn(wl,de,Ie):void 0;I.useEffect(()=>{ie&&D(!1)},[ie]),I.useEffect(()=>{D(!1),ot(0),i(null),M(null),N([])},[z.activeShot]);const nm=c=>{const x=md(c.dataTransfer.getData(Sr)),L=ge.current;if(!x||!L||ie)return;c.preventDefault();const F=L.pointerTarget(c.clientX,c.clientY),K=Ne.current,X=K.shots.find(xe=>xe.id===K.activeShot),se=ku(K,x,{selected:F.id??J,ground:F.ground,start:Et.current*X.duration,label:a(x.name),anchor:(xe,fe,We)=>L.partPointAt(X,We,xe,fe)});if("error"in se){be(a("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[24]));return}be(""),D(!1),Me(()=>se.stage),xt(se.item.id),Zn("fx")},sm=c=>{const x=qa(c.dataTransfer.getData($o)),L=ge.current;if(!x||!L||ie)return;c.preventDefault();const F=L.pointerSlot(c.clientX,c.clientY),K=F&&Ne.current.items.find(se=>se.id===F.id);if(!F||!K||!Fa(K)){be(a("Thả vật liệu lên một đối tượng trong cảnh."));return}if(K.locked){be(a("{0} đang khoá — mở khoá ở timeline để đổi vật liệu.",[K.name]));return}const X=Tt.mode==="part"&&L.materialSlots(K.id).length>1;be(""),D(!1),Me(se=>Us(se,K.id,X?F.slot:"*",{preset:x.id})),xt(K.id),X&&on({mode:"part",slot:F.slot})},am=Object.fromEntries(z.items.flatMap(c=>{if(c.kind!=="fx"||!c.fx)return[];const x=On(c,de);return x.off?[]:[[c.id,{start:x.start,duration:x.duration}]]})),Ml=Bf(C?.stage||z),vt=Oa(z.lighting),Sl=Kf(z.shots),Rn=c=>Me(x=>({...x,lighting:Oa({...Oa(x.lighting),...c})})),Os=z.notes||[],ua=z.styleRefs||[],om=()=>{const c=ge.current;if(c){if(at){c.setNotePlacer(null),mt(!1);return}mt(!0),c.setNotePlacer(x=>{mt(!1),Me(L=>({...L,notes:[...L.notes||[],{id:yt(),text:a("Ghi chú"),position:x}].slice(0,uc)}))})}},im=(c,x)=>Me(L=>({...L,notes:(L.notes||[]).map(F=>F.id===c?{...F,text:x.slice(0,mc)}:F)})),rm=c=>Me(x=>({...x,notes:(x.notes||[]).filter(L=>L.id!==c)})),Cl=c=>Me(x=>{if(x.shots.length<2)return x;const L=x.shots.findIndex(K=>K.id===c);if(L<0)return x;const F=x.shots.filter(K=>K.id!==c);return{...x,shots:F,activeShot:x.activeShot===c?F[Math.min(L,F.length-1)].id:x.activeShot}}),Nl=(c,x)=>Me(L=>{const F=L.shots.findIndex(se=>se.id===c),K=F+x;if(F<0||K<0||K>=L.shots.length)return L;const X=[...L.shots];return[X[F],X[K]]=[X[K],X[F]],{...L,shots:X}});I.useEffect(()=>{if(!B)return;const c=p&&d?d.in:0,x=p&&d?d.out:1;let L=0,F=performance.now(),K=Ie;(K<c||K>=x)&&(K=c);const X=Hf(de),se=Math.max(.1,de.duration),xe=X?Ti(de,c*se):0,fe=X?Ti(de,x*se):0;let We=X?Ti(de,K*se):0;const Oe=Ue=>{const pt=(Ue-F)/1e3;if(F=Ue,X){if(We+=pt,We>=fe)if(u)We=xe+(We-fe)%Math.max(1e-6,fe-xe);else{ge.current?.setOutputClock(null),ot(x),D(!1);return}ge.current?.setOutputClock(We),ot(M0(de,We).scene/se),L=requestAnimationFrame(Oe);return}if(K+=pt/se,K>=x)if(u)K=c+(K-x)%Math.max(1e-6,x-c);else{ot(x),D(!1);return}ot(K),L=requestAnimationFrame(Oe)};return L=requestAnimationFrame(Oe),()=>{cancelAnimationFrame(L),ge.current?.setOutputClock(null)}},[B,de.duration,de.timing,z.activeShot,u,p,d]);const ao=(Ot()?.nodes()||[]).filter(c=>c.type==="image"&&c.id!==e&&c.data.url),jt=c=>{D(!1),Me(x=>({...x,shots:x.shots.map(L=>L.id===x.activeShot?{...L,...c}:L)}))},Al=c=>jt(or(c)),lm=(c,x)=>{const L=(c==="camera"?de.cameraKeys:de.objectKeys?.[c])?.find(F=>F.id===x);L&&(D(!1),ot(L.time),M({row:c,id:x}),N([]),i(c==="camera"?x:null),xt(c==="camera"?null:c))},Tl=c=>{D(!1),N(c),M(c.length===1?c[0]:null),i(c.length===1&&c[0].row==="camera"?c[0].id:null)},pi=c=>{if(c==="camera"){const x=de.motion==="path"?de.cameraKeys||[]:[],L=x.find(X=>Math.abs(X.time-Ie)<1e-6),F=Qh(de,Ie),K={id:L?.id||yt(),time:Ie,position:F.position,target:F.target,lens:F.lens,roll:F.roll};Al([...x.filter(X=>X.id!==K.id),K]),i(K.id),M({row:c,id:K.id}),xt(null)}else{const x=z.items.find(se=>se.id===c);if(!x||x.locked)return;if(x.kind==="fx"&&x.fx?.attach){const se=x.fx.attach.keyed?(de.objectKeys?.[c]||[]).find(fe=>Math.abs(fe.time-Ie)<1e-6):void 0,xe=se?.id||yt();Me(fe=>Bo(fe,c,Ie,{id:xe})),i(null),xt(c),M({row:c,id:xe});return}const L=Wn(x,de,Ie),F=de.objectKeys?.[c]||[],X={id:F.find(se=>Math.abs(se.time-Ie)<1e-6)?.id||yt(),time:Ie,position:L.position,rotation:L.rotation,scale:L.scale};jt({objectKeys:{...de.objectKeys,[c]:[...F.filter(se=>se.id!==X.id),X].sort((se,xe)=>se.time-xe.time)}}),i(null),xt(c),M({row:c,id:X.id})}},cm=(c,x)=>Me(L=>{const F=L.items.find(fe=>fe.id===c);if(!F?.fx||F.locked||(F.fx.attach?.to??"")===x)return L;const K=F.fx.attach,X=x?{to:x,...K?.part?{part:K.part}:{},...K?.follow?{follow:K.follow}:{}}:void 0,se=K?.keyed?L.shots.map(fe=>fe.objectKeys?.[c]?{...fe,objectKeys:Object.fromEntries(Object.entries(fe.objectKeys).filter(([We])=>We!==c))}:fe):L.shots,xe=x?L.items.find(fe=>fe.id===x):null;return{...L,shots:se,items:L.items.map(fe=>fe.id===c?{...fe,...!x&&K?{position:[...L.items.find(We=>We.id===K.to)?.position??fe.position]}:{},...xe?{position:[...xe.position]}:{},fx:{...F.fx,attach:X}}:fe)}}),hm=(c,x)=>{if(c==="camera"){x==="hidden"?w(L=>!L):E(L=>!L);return}D(!1),Me(L=>({...L,items:L.items.map(F=>F.id===c?{...F,[x]:!F[x]}:F)})),(x==="hidden"||x==="locked")&&xt(L=>L===c&&!z.items.find(F=>F.id===c)?.[x]?null:L)},dm=(c,x,L)=>{D(!1),Me(F=>Ag(F,c,x,Ie,L))},Ss=T.length?T:j?[j]:[],Ll=()=>{D(!1),Me(c=>Tg(c,Ie))},El=()=>{g.current=Lg(Ne.current,Ss),b(g.current.length>0),Qe.current="keys"},Rl=()=>{if(!g.current.length)return;D(!1);let c=[];Me(x=>{const L=Eg(x,g.current,Ie);return c=L.pasted,L.stage}),c.length&&Tl(c)},um=c=>{Ss.length&&Me(x=>Rg(x,Ss,c))},Il=c=>{if(!Ss.length)return;const x=c/(bn(de)*de.duration);Mc(Ne.current,Ss,x).moved&&(D(!1),Me(L=>Mc(L,Ss,x).stage))},mm=c=>{const x=Ie;f(L=>c==="in"?{in:x,out:L&&L.out>x?L.out:1}:{in:L&&L.in<x?L.in:0,out:x}),y(!0)},pm=(c,x,L)=>{if(!((c==="camera"?de.cameraKeys:de.objectKeys?.[c])||[]).some(K=>K.id!==x&&Math.abs(K.time-L)<1e-6)){if(c==="camera")Al((de.cameraKeys||[]).map(K=>K.id===x?{...K,time:L}:K));else{if(z.items.find(K=>K.id===c)?.locked)return;jt({objectKeys:{...de.objectKeys,[c]:(de.objectKeys?.[c]||[]).map(K=>K.id===x?{...K,time:L}:K).sort((K,X)=>K.time-X.time)}})}ot(L)}},Pl=()=>{const c=[...T,...j&&!T.some(X=>X.row===j.row&&X.id===j.id)?[j]:[]];if(!c.length)return;const x=X=>new Set(c.filter(se=>se.row===X).map(se=>se.id)),L={...de.objectKeys};let F=!1;for(const X of new Set(c.map(se=>se.row)))if(X!=="camera"&&!z.items.find(se=>se.id===X)?.locked){const se=x(X);L[X]=(L[X]||[]).filter(xe=>!se.has(xe.id)),F=!0}const K=c.some(X=>X.row==="camera")?or((de.cameraKeys||[]).filter(X=>!x("camera").has(X.id))):{};jt({...K,...F?{objectKeys:L}:{}}),i(null),M(null),N([])},fm=c=>{D(!1),jt(S0(de,c)),c!=="path"&&ot(c==="static"?0:1)},Fl=async c=>{try{const x=await jg("model",c);wt(L=>c?[...L,...x.assets]:x.assets),Xe(x.nextCursor)}catch(x){be(x.message)}},gm=async c=>{if(c){if(be(""),!c.name.toLowerCase().endsWith(".glb")||c.size>50*1024*1024){be("Chọn file GLB tối đa 50 MB.");return}bt(!0);try{const x=new DataView(await c.slice(0,12).arrayBuffer());if(x.byteLength<12||x.getUint32(0,!0)!==1179937895||x.getUint32(4,!0)!==2)throw new Error("File không phải GLB 2.0 hợp lệ");const L=await c.arrayBuffer(),F=new DataView(L);if(F.byteLength<20||F.getUint32(8,!0)!==L.byteLength||F.getUint32(16,!0)!==1313821514)throw new Error("Cấu trúc GLB không hợp lệ");const K=F.getUint32(12,!0);if(20+K>L.byteLength)throw new Error("File GLB bị thiếu dữ liệu");const X=JSON.parse(new TextDecoder().decode(new Uint8Array(L,20,K)));if([...X.buffers||[],...X.images||[]].some(fe=>fe.uri&&!fe.uri.startsWith("data:")))throw new Error("Hãy xuất GLB với texture và dữ liệu nhúng trong file.");const{gcsUri:se}=await Vs(new File([c],c.name,{type:"model/gltf-binary"})),xe={...An("model",Ne.current.items.length),name:c.name,model:{gcsUri:se,name:c.name}};Me(fe=>({...fe,items:[...fe.items,xe]})),xt(xe.id)}catch(x){be(x.message)}finally{bt(!1)}}},$l=(c,x)=>{const L={...An("splat",Ne.current.items.length),name:c,position:[0,0,0],color:"#9aa3a8",splat:x};Me(F=>({...F,items:[...F.items,L]})),xt(L.id)},xm=async c=>{if(!c)return;be("");const x=c.name.split(".").pop()?.toLowerCase()||"";if(!C0.includes(x)||c.size>N0){be(a("Chọn file bản quét .spz, .ply, .splat, .ksplat hoặc .sog tối đa 300 MB."));return}bt(!0);try{const{gcsUri:L}=await Vs(new File([c],c.name,{type:"application/x-gaussian-splat"}));$l(c.name.replace(/\.[^.]+$/,""),{name:c.name,gcsUri:L,source:"scan",flip:!0})}catch(L){be(L.message)}finally{bt(!1)}},fi=(Ot()?.nodes()||[]).filter(c=>c.type==="world"&&typeof c.data.splatUrl=="string"),bm=c=>{const x=Array.from({length:c==="person"?Mt:1},(L,F)=>({...An(c,z.items.length+F),name:`${a(Zi.find(([K])=>K===c)?.[1]||"Model")} ${z.items.length+F+1}`}));Me(L=>({...L,items:[...L.items,...x]})),xt(x[0].id)};async function gi(c,x,L){const F=ge.current;if(!F)throw new Error("3D chưa sẵn sàng");const K=structuredClone(Ne.current);F.sync(K,null);const X=await W1(F,K,e,c,{signal:L,progress:x}),se=q1(X,K.plate?.timelineClipId);return Ut.current=X.at(-1)?.nodeId||null,En.current=X.at(-1)?.url||null,se}async function xi(c,x,L){const F=structuredClone(Ne.current),K=F.shots.find(kt=>kt.id===F.activeShot),X=ht.getState().canvasId,se=new File([c],`${K.name}-camera.mp4`,{type:"video/mp4"}),{url:xe,gcsUri:fe}=await Vs(se,void 0,"video");En.current=xe,wn.current=fe||null;const We=Ot()?.getNode(e);if(!We||ht.getState().canvasId!==X)throw new Error("Canvas đã thay đổi. Video đã lưu trong Tài sản của tôi.");const Oe=x.end-x.start,Ue=`Use the attached 3D previs video as the camera-motion and spatial-layout reference. Preserve its camera trajectory, framing, lens perspective and timing over ${Oe} seconds. Preserve the subject movements and their spatial relationships shown in the reference. Replace the previs appearance with the intended final visual style; do not copy editor helpers. The reference contains no audio. Describe the desired final appearance here.`,pt=Ot()?.addNode("video",{url:xe,gcsUri:fe,label:`${K.name} · Camera ref`,duration:Oe,ratio:K.aspect,status:"succeeded",shotSourceId:e,shotId:K.id,shotRevision:F.revision,cameraVideo:{...x},prompt:Ue},{x:We.position.x+380,y:We.position.y},{sourceIds:[e]});if(Ut.current=pt||null,L==="timeline"){if(!pt)throw new Error("Không tạo được video trên Canvas");const kt=ht.getState(),In=We.data?.timelineClipId,Vt=kt.clips.find(ln=>ln.id===In);if(!Vt)throw new Error("Clip 3D gốc không còn trên Timeline. Video đã lưu vào Canvas.");if(kt.timelineTracks[Vt.track]?.locked)throw new Error("Track đã khóa. Video đã lưu vào Canvas.");const Mn=Vt.kind==="model"?Vt:Vt.from3D?.clip,$t={id:crypto.randomUUID(),nodeId:pt,track:Vt.track,start:Vt.start,duration:Math.max(1/30,Math.min(Vt.duration,Math.floor(Oe*30)/30)),sourceDuration:Oe,inPoint:0,volume:1,url:xe,gcsUri:fe,kind:"video",label:`${Vt.label.replace(/ · 3D$/,"")} · 3D`,...Vt.zIndex!==void 0?{zIndex:Vt.zIndex}:{},...Mn?{from3D:{shotNodeId:e,clip:Mn}}:{}};kt.setClips(ln=>ln.map(Ns=>Ns.id===Vt.id?$t:Ns)),kt.setTimelineMedia(ln=>ln.some(Ns=>Ns.source==="canvas"&&Ns.id===pt)?ln:[...ln,{id:pt,source:"canvas",kind:"video",url:xe,gcsUri:fe,label:$t.label,duration:Oe}]),Ot()?.updateNodeData(e,{timelineClipId:$t.id}),Dt(),kt.setView("timeline"),kt.toast(a("Đã đưa video 3D về Timeline, thay đúng chỗ clip model"),"ok");return}ht.getState().toast(a("Đã lưu video camera vào Canvas và tài sản của bạn"),"ok")}async function cs(c,x=Ne.current.shots.find(se=>se.id===Ne.current.activeShot),L=0,F=!0,K=0,X=""){if(!ge.current)return;F&&me(!0),be("");const se=ht.getState().canvasId,xe=structuredClone(Ne.current);xe.activeShot=x.id;const fe=x,We=Ne.current.activeShot;try{We!==fe.id&&ge.current.sync(xe,J);const Oe=await ge.current.exportPng(K),Ue=`${fe.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}${X.replace(/\s+/g,"-")}.png`;if(c){const{url:pt,gcsUri:kt}=await Vs(new File([Oe],Ue,{type:"image/png"})),In=Ot()?.getNode(e);if(ht.getState().canvasId!==se)throw new Error("Canvas đã thay đổi; ảnh chưa được chèn");if(!In)throw new Error("Cảnh gốc không còn tồn tại");const Vt=Ot()?.addNode("image",{url:pt,gcsUri:kt,label:`${fe.name}${X}`,ratio:fe.aspect,prompt:Ei(xe),shotSourceId:e,shotId:fe.id,shotRevision:xe.revision,sceneVersion:xe.version,characterReferences:xe.items.filter(Mn=>Mn.kind==="person"&&Mn.reference).map(Mn=>Mn.reference),cameraMotion:{pathSmooth:fe.pathSmooth,type:fe.motion,duration:fe.duration,endPosition:fe.endPosition,endTarget:fe.endTarget,endLens:fe.endLens},cameraFrame:K},{x:In.position.x+380,y:In.position.y+L*280},{sourceIds:[e,...xe.items.flatMap(Mn=>Mn.reference?.nodeId?[Mn.reference.nodeId]:[])]});return ht.getState().toast(a("Đã đưa ảnh shot vào Canvas"),"ok"),Vt}else{const pt=URL.createObjectURL(Oe),kt=document.createElement("a");kt.href=pt,kt.download=Ue,kt.click(),setTimeout(()=>URL.revokeObjectURL(pt),1e3)}}catch(Oe){if(be(Oe.message),!F)throw Oe}finally{We!==fe.id&&ge.current.sync(Ne.current,J),F&&me(!1)}}async function ym(){if(de.motion!=="static"){me(!0),be("");try{const c=await cs(!0,de,0,!1,0," · Start"),x=await cs(!0,de,1,!1,1," · End");c&&x&&(Ot()?.updateNodeData(c,{pairedShotNodeId:x}),Ot()?.updateNodeData(x,{pairedShotNodeId:c})),ht.getState().toast(a("Đã tạo cặp Start/End cho Seedance"),"ok")}catch(c){be(c.message)}finally{ge.current?.sync(Ne.current,J),me(!1)}}}async function vm(){let c=!1;me(!0),be("");try{Da.includes(de.aspect)||ht.getState().toast(zu(de).aspect.at(-1)||"","error");const x=await cs(!0,de,0,!1,Ie," · Previs");if(!x)return;const L=[x,...Ne.current.items.flatMap(K=>K.reference?.nodeId?[K.reference.nodeId]:[]),...(Ne.current.styleRefs||[]).map(K=>K.nodeId)],F=Ot()?.getNode(e);c=!0,Dt(),ht.getState().openComposer({mode:"image",generator:"openai:gpt-image",refs:Array.from(new Set(L)),prompt:A0(Ne.current),count:1,aspectRatio:Da.includes(de.aspect)?de.aspect:ir(de.aspect,Da),resolution:"2K",quality:"high",anchor:F?{x:F.position.x+760,y:F.position.y}:null}),ht.getState().toast(a("Khung previs đã sẵn sàng để tạo ảnh thật"),"ok")}catch(x){be(x.message)}finally{c||ge.current?.sync(Ne.current,J),me(!1)}}async function jm(){if(ge.current){me(!0),be("");try{const c=await ge.current.exportPng(Ie,!0),x=URL.createObjectURL(c),L=document.createElement("a");L.href=x,L.download=`${de.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-ghi-chu.png`,L.click(),setTimeout(()=>URL.revokeObjectURL(x),1e3)}catch(c){be(c.message)}finally{me(!1)}}}async function km(){me(!0),be("");try{for(let c=0;c<Ne.current.shots.length;c++)await cs(!0,Ne.current.shots[c],c,!1);ht.getState().toast(a("Đã xuất {0} shot vào Canvas",[Ne.current.shots.length]),"ok")}catch(c){be(c.message)}finally{me(!1)}}async function wm(){if(ge.current){me(!0);try{const c=Ne.current.shots.find(K=>K.id===Ne.current.activeShot),x=await ge.current.exportDepth(Ie),L=URL.createObjectURL(x),F=document.createElement("a");F.href=L,F.download=`${c.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-depth.png`,F.click(),setTimeout(()=>URL.revokeObjectURL(L),1e3)}catch(c){be(c.message)}finally{me(!1)}}}async function Mm(){if(ge.current){me(!0);try{const c=Ne.current.shots.find(K=>K.id===Ne.current.activeShot),x=await ge.current.exportPoseMask(Ie),L=URL.createObjectURL(x),F=document.createElement("a");F.href=L,F.download=`${c.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-pose-mask.png`,F.click(),setTimeout(()=>URL.revokeObjectURL(L),1e3)}catch(c){be(c.message)}finally{me(!1)}}}const Cs=(c,x,L,F=-100)=>t.jsxs("div",{className:"shot-vector",children:[t.jsx("small",{children:a(c)}),x.map((K,X)=>t.jsx(ss,{label:`${a(c)} ${["X","Y","Z"][X]}`,value:K,min:F,onChange:se=>{const xe=[...x];xe[X]=se,L(xe)}},X))]});I.useEffect(()=>{try{localStorage.setItem("clipoox.shot.layout",JSON.stringify(pe))}catch{}},[pe]);const Zn=c=>{ve(c);try{localStorage.setItem("clipoox.shot.panel",c||"")}catch{}},Sm=c=>Zn(Q===c?null:c),Dl=c=>{q(c);try{localStorage.setItem("clipoox.shot.railWide",c?"1":"0")}catch{}},[oo,ma]=I.useState(null),Ol=c=>{const x=c.target.closest("button"),L=x?.querySelector(".lbl");if(!x||!L||getComputedStyle(L).display!=="none"){ma(null);return}const F=x.getBoundingClientRect(),K=c.currentTarget.getBoundingClientRect().right,X=x.getAttribute("aria-label")||"";ma(se=>se&&se.label===X&&se.top===F.top+F.height/2?se:{label:X,left:K+8,top:F.top+F.height/2})},Cm=()=>{ue(Ji),Dl(!1);try{localStorage.removeItem("clipoox.shot.layout")}catch{}},bi=(c,x)=>{if(c.button!==0)return;c.preventDefault();const L=c.currentTarget,F={x:c.clientX,y:c.clientY,value:pe[x]},K=c.pointerId;L.setPointerCapture(K),L.classList.add("dragging");const X=fe=>x==="timeline"?Math.max(120,Math.min(window.innerHeight*.55,fe)):x==="drawer"?Math.max(240,Math.min(window.innerWidth*.2,fe)):Math.max(260,Math.min(window.innerWidth*.22,fe)),se=fe=>{const We=x==="timeline"?F.y-fe.clientY:x==="drawer"?fe.clientX-F.x:F.x-fe.clientX;ue(Oe=>({...Oe,[x]:Math.round(X(F.value+We))}))},xe=()=>{L.removeEventListener("pointermove",se),L.removeEventListener("pointerup",xe),L.removeEventListener("pointercancel",xe),L.classList.remove("dragging")};L.addEventListener("pointermove",se),L.addEventListener("pointerup",xe),L.addEventListener("pointercancel",xe)};return t.jsxs("div",{className:"shot-workspace",role:"dialog","aria-modal":"true","aria-label":a("3D Shot Composer"),children:[oe&&t.jsx(mj,{count:mn.length,start:Ie*de.duration,left:(1-Ie)*de.duration,busy:ie,onRun:c=>{em(c)},onClose:()=>Se(!1)}),vn&&t.jsx(hj,{x:vn.x,y:vn.y,renaming:!!vn.renaming,items:vn.scene?[]:mn.map(c=>z.items.find(x=>x.id===c)).filter(Boolean),canPaste:!!to(),hiddenCount:z.items.filter(c=>c.hidden).length,blenderKeys:Re,onBlenderKeys:Ze,onAction:Ju,onRename:c=>{const x=mn[0];jn(null),x&&et(x,{name:c})},onClose:$e}),Ye.on&&(()=>{const c=Ln.current?.getBoundingClientRect(),x=Ye.from,L=Ye.to;if(!c)return null;const F=K=>{if(!x)return;const X=L&&Math.hypot(L[0]-x[0],L[1]-x[1])>3?ge.current?.objectsInRect(x[0],x[1],K.clientX,K.clientY)??[]:[];qt(K.shiftKey?[...It.current,...X.filter(se=>!It.current.includes(se))]:X),Ge({on:!1})};return t.jsxs("div",{className:"shot-boxsel",role:"presentation","aria-label":a("Kéo để chọn theo vùng"),style:{left:c.left,top:c.top,width:c.width,height:c.height},onMouseDown:K=>{K.button===0&&Ge({on:!0,from:[K.clientX,K.clientY],to:[K.clientX,K.clientY]})},onMouseMove:K=>{x&&Ge({on:!0,from:x,to:[K.clientX,K.clientY]})},onMouseUp:F,onContextMenu:K=>{K.preventDefault(),Ge({on:!1})},children:[t.jsx("span",{className:"shot-boxsel-hint",children:a("Kéo để chọn theo vùng · Shift: chọn thêm · Esc: thôi")}),x&&L&&t.jsx("i",{style:{left:Math.min(x[0],L[0])-c.left,top:Math.min(x[1],L[1])-c.top,width:Math.abs(L[0]-x[0]),height:Math.abs(L[1]-x[1])}})]})})(),R&&t.jsx(K1,{shot:de,engine:ge.current||null,onClose:()=>A(!1),onBusy:me,onReady:xi,timelineTarget:(()=>{const c=Ot()?.getNode(e)?.data?.timelineClipId;return typeof c=="string"?ht.getState().clips.find(x=>x.id===c)?.label:void 0})(),vfx:z.plate?{layers:new Set(z.items.filter(c=>c.kind==="fx"&&!c.hidden).map(fd)).size,target:ht.getState().clips.find(c=>c.id===z.plate?.timelineClipId)?.label,run:async(c,x,L)=>{const F=await gi(c,x,L),K=ht.getState();if(!F.placed){K.toast(a("Đã lưu {0} video hiệu ứng vào Canvas. Clip gốc không có trên Timeline đang mở: thêm bằng tay hoặc mở lại Timeline đó.",[F.passes.length]),"info");return}Dt(),K.setView("timeline"),K.toast(F.pendingMatte?a("Đã đặt {0} lớp hiệu ứng lên Timeline. Timeline đang tách người để đặt lớp sau người ra sau.",[F.passes.length]):a("Đã đặt {0} lớp hiệu ứng lên Timeline.",[F.passes.length]),"ok")}}:void 0}),t.jsxs("header",{children:[t.jsxs("button",{disabled:ie,onClick:Dt,children:[t.jsx(Ce.back,{}),a("← Canvas").replace("← ","")]}),t.jsxs("strong",{children:[a("3D Shot Composer"),t.jsx("em",{children:a("BETA")})]}),t.jsx("span",{className:"shot-save","data-save-state":Xt,title:Xt==="error"&&Yn?Yn:void 0,children:Xt==="saved"?a("Đã lưu"):Xt==="error"?t.jsxs(t.Fragment,{children:[a("Lỗi lưu — đã giữ bản trên máy này"),Yn&&t.jsx("small",{className:"shot-save-why",children:Yn}),t.jsx("button",{type:"button",className:"shot-save-retry",onClick:()=>ht.getState().retrySave(),children:a("Thử lại")})]}):a("Đang lưu…")}),t.jsx("button",{"aria-label":a("Hoàn tác"),title:a("Hoàn tác (⌘Z)"),disabled:!rn.current.length||ie,onClick:()=>so(),children:t.jsx(Ce.undo,{})}),t.jsx("button",{"aria-label":a("Làm lại"),title:a("Làm lại (⇧⌘Z)"),disabled:!_n.current.length||ie,onClick:()=>so(!0),children:t.jsx(Ce.redo,{})}),t.jsxs("button",{disabled:ie||!st,onClick:()=>{D(!1),cs(!1,de,0,!0,Ie)},title:a("Tải PNG"),children:[t.jsx(Ce.image,{}),t.jsx("span",{className:"lbl",children:a("Tải PNG")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:ie||!st,onClick:wm,title:a("Depth map"),children:[t.jsx(Ce.depth,{}),t.jsx("span",{className:"lbl",children:a("Depth map")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:ie||!st,onClick:Mm,title:a("Pose mask"),children:[t.jsx(Ce.mask,{}),t.jsx("span",{className:"lbl",children:a("Pose mask")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:ie||!st||z.shots.length<2,onClick:km,title:a("Xuất tất cả shot"),children:[t.jsx(Ce.layers,{}),t.jsx("span",{className:"lbl",children:a("Xuất tất cả shot")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:ie||!st||de.motion==="static",onClick:ym,title:a("Start + End"),children:[t.jsx(Ce.frames,{}),t.jsx("span",{className:"lbl",children:a("Start + End")})]}),t.jsxs("button",{disabled:ie||!st,onClick:()=>{D(!1),vm()},title:a("Biến khung xám thành ảnh thật (giữ nguyên bố cục)"),children:[t.jsx(Ce.image,{}),t.jsx("span",{className:"lbl",children:a("Ảnh thật")})]}),t.jsxs("button",{className:"shot-primary",disabled:ie||!st,onClick:()=>{D(!1),A(!0)},title:a("Xuất MP4"),children:[t.jsx(Ce.video,{}),a("Xuất MP4")]}),t.jsxs("button",{disabled:ie||!st,onClick:()=>{D(!1),cs(!0,de,0,!0,Ie)},children:[t.jsx(Ce.plus,{}),ie?a("Đang xuất…"):a("Đưa vào Canvas")]})]}),Ft&&Ft.canvasId===St&&Ft.nodeId===e&&t.jsxs("div",{className:"shot-sync-bar",role:"alert",children:[t.jsx("span",{"aria-hidden":!0,children:"⟳"}),t.jsxs("div",{className:"grow",children:[t.jsx("b",{children:Wf(Ft.by)?a("Cảnh 3D này có phiên bản mới từ trợ lý AI của bạn."):a("Cảnh 3D này có phiên bản mới.")})," ",a("Bạn cũng có thay đổi chưa lưu ở đây — chọn bản muốn giữ.")]}),t.jsx("button",{className:"primary",disabled:Qn,onClick:()=>void Gf(Ft.canvasId,Ft.nodeId).then(()=>ht.getState().toast(a("Đã tải phiên bản mới nhất của cảnh 3D."),"ok")),children:a("Tải phiên bản mới")}),t.jsx("button",{disabled:Qn,onClick:qf,children:a("Giữ bản của tôi")})]}),Fe&&t.jsx("div",{className:"shot-error",role:"alert",children:a(Fe)}),$&&t.jsx(Uf,{characters:$==="characters",onClose:()=>{W(!1),Bt(null)},onSelect:Ds}),C&&t.jsx("div",{className:"shot-trial-shield",role:"dialog","aria-label":a("Xem thử đề xuất AI"),children:t.jsxs("div",{className:"shot-trial-controls",children:[t.jsx("b",{children:a("Xem thử · chưa lưu")}),t.jsx("button",{onClick:()=>{Ie>=1&&ot(0),D(!B)},children:B?a("Tạm dừng"):a("Phát lại")}),t.jsx("input",{"aria-label":a("Thời gian xem thử"),type:"range",min:0,max:1,step:1e-4,value:Ie,onChange:c=>{D(!1),ot(+c.target.value)}}),t.jsxs("span",{children:[(Ie*de.duration).toFixed(2),a("s")]}),t.jsx("button",{onClick:()=>zn(!1),children:a("Bỏ bản xem thử")}),t.jsx("button",{className:"shot-primary",onClick:()=>zn(!0),children:a("Giữ thay đổi")})]})}),t.jsxs("div",{className:`shot-layout ${Q?"has-drawer":""} ${ye?"rail-wide":""}`,style:{"--drawer-w":`${pe.drawer}px`,"--right-w":`${pe.right}px`},children:[t.jsxs("nav",{className:"shot-rail","aria-label":a("Công cụ dựng cảnh"),onMouseOver:Ol,onFocus:Ol,onMouseLeave:()=>ma(null),onBlur:()=>ma(null),onScroll:()=>ma(null),children:[Ao.map(([c,x,L])=>t.jsxs("button",{type:"button",className:Q===c?"active":"","aria-pressed":Q===c,"aria-label":a(x),onClick:()=>Sm(c),children:[L,t.jsx("span",{className:"lbl",children:a(x)}),c==="objects"&&t.jsx("small",{className:"shot-rail-count",children:z.items.length}),c==="shots"&&z.shots.length>1&&t.jsx("small",{className:"shot-rail-count",children:z.shots.length}),c==="notes"&&Os.length>0&&t.jsx("small",{className:"shot-rail-count",children:Os.length})]},c)),t.jsx("span",{className:"shot-rail-gap"}),t.jsxs("button",{type:"button","aria-label":ye?a("Thu gọn thanh công cụ"):a("Mở rộng thanh công cụ"),onClick:()=>Dl(!ye),children:[ye?t.jsx(Ce.collapse,{}):t.jsx(Ce.expand,{}),t.jsx("span",{className:"lbl",children:a("Thu gọn")})]}),t.jsxs("button",{type:"button","aria-label":a("Khôi phục bố cục"),onClick:Cm,children:[t.jsx(Ce.reset,{}),t.jsx("span",{className:"lbl",children:a("Khôi phục bố cục")})]})]}),oo&&xd.createPortal(t.jsx("span",{className:"shot-rail-tip",role:"tooltip",style:{left:oo.left,top:oo.top},children:oo.label}),document.querySelector(".shot-workspace")||document.body),Q&&t.jsxs("aside",{className:"shot-drawer shot-inspector","aria-label":a(Ao.find(c=>c[0]===Q)[1]),children:[t.jsxs("div",{className:"shot-drawer-head",children:[t.jsxs("h3",{children:[a(Ao.find(c=>c[0]===Q)[1]),Q==="objects"?t.jsxs("small",{className:"shot-total",children:[" · ",z.items.length]}):Q==="shots"?t.jsxs("small",{className:"shot-total",children:[" · ",z.shots.length," · ",Li(Sl.at(-1)?.end||0)]}):Q==="notes"?t.jsxs("small",{className:"shot-total",children:[" · ",Os.length]}):Q==="series"&&z.series?t.jsxs("small",{className:"shot-total",children:[" · ",z.series.name]}):null]}),t.jsx("button",{type:"button",className:"shot-drawer-close","aria-label":a("Đóng bảng"),title:a("Đóng bảng (Esc)"),onClick:()=>Zn(null),children:t.jsx(Ce.close,{})})]}),t.jsxs("div",{className:"shot-drawer-body shot-inspector-scroll",tabIndex:0,children:[Q==="scene"&&t.jsx("div",{className:"shot-scene-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsxs("div",{className:"shot-add",children:[t.jsx("input",{ref:Kt,type:"file",accept:".glb",hidden:!0,onChange:c=>{gm(c.target.files?.[0]),c.target.value=""}}),t.jsxs("button",{onClick:()=>W("all"),children:[t.jsx(Ce.library,{}),a("Kho 3D chung")]}),t.jsxs("button",{onClick:()=>void Fl(),children:[t.jsx(Ce.user,{}),a("Model của tôi")]}),lt.length>0&&t.jsxs("select",{"aria-label":a("Model 3D đã lưu"),value:"",onChange:c=>{const x=lt.find(F=>F.id===c.target.value);if(!x)return;const L={...An("model",Ne.current.items.length),name:x.name,model:{gcsUri:x.gcsUri,name:x.name}};Me(F=>({...F,items:[...F.items,L]})),xt(L.id)},children:[t.jsx("option",{value:"",children:a("Chọn model đã lưu…")}),lt.map(c=>t.jsx("option",{value:c.id,children:c.name},c.id))]}),Zt&&t.jsx("button",{onClick:()=>void Fl(Zt),children:a("Thêm model đã lưu")}),t.jsxs("button",{disabled:ct,onClick:()=>Kt.current?.click(),children:[t.jsx(Ce.cube,{}),ct?a("Đang tải…"):"Model GLB"]}),t.jsx("input",{ref:kn,type:"file",accept:".spz,.ply,.splat,.ksplat,.sog",hidden:!0,onChange:c=>{xm(c.target.files?.[0]),c.target.value=""}}),t.jsxs("button",{disabled:ct,title:a("Bản quét 3D địa điểm thật từ app điện thoại (Scaniverse, Polycam, Luma…)"),onClick:()=>kn.current?.click(),children:[t.jsx(Ce.image,{}),a("Bối cảnh thật")]}),fi.length>0&&t.jsxs("select",{"aria-label":a("Dùng 3D World trên Canvas"),value:"",onChange:c=>{const x=fi.find(F=>F.id===c.target.value);if(!x)return;const L=x.data;$l(L.label||"3D World",{name:L.label||"3D World",url:L.splatUrl,source:"world",flip:!0,...L.worldId?{worldId:L.worldId}:{}})},children:[t.jsx("option",{value:"",children:a("Dùng 3D World trên Canvas…")}),fi.map(c=>t.jsx("option",{value:c.id,children:String(c.data.label||"3D World")},c.id))]}),Zi.map(([c,x])=>t.jsxs("button",{disabled:ie,onClick:()=>bm(c),children:[pj[c],a(x)]},c))]}),t.jsx(ss,{label:"Số người mỗi lần thêm",value:Mt,min:1,max:50,step:1,onChange:c=>gt(Math.floor(c))})]})}),Q==="fx"&&t.jsx(a1,{onEdit:()=>Zn("fxedit"),onPlayClip:(c,x)=>{ci(c,x)},stage:z,selected:J,playhead:Ie*de.duration,change:Me,onSelect:xt,ground:()=>ge.current?.groundAtScreenCentre()??[0,0,0],anchor:(c,x,L)=>ge.current?.partPointAt(de,L,c,x)??null,engine:ge.current,setError:be}),Q==="material"&&t.jsx(b1,{stage:z,selected:J,change:Me,engine:ge.current,setError:be,scope:Tt,setScope:on}),Q==="rigging"&&t.jsx(_1,{stage:z,shot:de,selected:J,engine:st?ge.current:null,playhead:Ie,busy:ie,change:Me,patchItem:et,onSelect:xt,resync:()=>ge.current?.sync(Ne.current,J),setError:be,addPoseKey:sl,onPlayClip:ci,motionLoop:ri,motionMirror:li,onMotionLoop:hl,onMotionMirror:dl,keys:fn}),Q==="fxedit"&&t.jsx(o1,{stage:z,selected:J,playhead:Ie*de.duration,change:Me,onSelect:xt,ground:()=>ge.current?.groundAtScreenCentre()??[0,0,0],engine:ge.current}),Q==="mixfx"&&t.jsx(d1,{stage:z,selected:J,progress:Ie,change:Me,onSelect:xt,engine:ge.current,setError:be}),Q==="modeling"&&t.jsx(Hx,{stage:z,selected:J,change:Me,getStage:()=>Ne.current,onSelect:xt,ground:()=>ge.current?.groundAtScreenCentre()??[0,0,0],engine:ge.current,setError:be}),Q==="objects"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-objects-section",children:[t.jsx("div",{className:"shot-charlib",children:t.jsxs("button",{type:"button",className:"shot-charlib-btn",onClick:()=>W("characters"),title:a("Nhân vật có xương: thêm vào cảnh là chạy mocap / chuyển động ngay"),children:[t.jsx(Ce.person,{}),t.jsx("span",{children:a("Thư viện nhân vật")})]})}),t.jsx("div",{className:"shot-list",children:z.items.map(c=>t.jsxs("div",{className:J===c.id?"active":H.includes(c.id)?"picked":"",onContextMenu:x=>{x.preventDefault(),mi(c.id,x.clientX,x.clientY)},children:[t.jsxs("button",{"aria-pressed":mn.includes(c.id),title:a("Shift/Ctrl+click: chọn thêm · chuột phải: menu"),onClick:x=>pn(c.id,x.shiftKey||x.ctrlKey||x.metaKey),children:[c.kind==="person"?"♙":c.kind==="set"?"⌂":"◇"," ",c.name,c.kind==="set"&&c.set?.parts?t.jsxs("small",{className:"shot-list-meta",children:[" · ",c.set.parts," ",a("khối")]}):null]}),t.jsx("button",{title:c.hidden?a("Hiện"):a("Ẩn"),onClick:()=>et(c.id,{hidden:!c.hidden}),children:c.hidden?"○":"●"}),t.jsx("button",{title:c.locked?a("Mở khóa"):a("Khóa"),onClick:()=>et(c.id,{locked:!c.locked}),children:c.locked?"▣":"□"}),t.jsx("button",{className:"shot-delete-item","aria-label":a("Xóa {0}",[c.name]),title:c.locked?a("Mở khóa đối tượng trước khi xóa"):a("Xóa {0} (Delete)",[c.name]),disabled:ie||c.locked,onClick:()=>pl(c.id),children:t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:t.jsx("path",{d:"M4 6h16M9 6V3h6v3M6 6l1 15h10l1-15M10 10v7m4-7v7"})})})]},c.id))})]}),ne&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:a("CHỈNH ĐỐI TƯỢNG")}),t.jsxs("fieldset",{disabled:ne.locked||ie,children:[t.jsx("input",{"aria-label":a("Tên đối tượng"),value:ne.name,onChange:c=>et(ne.id,{name:c.target.value})}),t.jsxs("label",{className:"shot-field",children:[a("Màu"),t.jsx("input",{"aria-label":a("Màu đối tượng"),type:"color",value:ne.color,onChange:c=>et(ne.id,{color:c.target.value})})]}),t.jsxs("select",{"aria-label":a("Đặt lên bề mặt"),value:"",onChange:c=>{c.target.value&&ge.current?.placeOnSurface(c.target.value)},children:[t.jsx("option",{value:"",children:a("Đặt lên bề mặt…")}),t.jsx("option",{value:"ground",children:a("Mặt đất")}),z.items.filter(c=>c.kind!=="person"&&c.id!==ne.id&&!c.hidden).map(c=>t.jsx("option",{value:c.id,children:c.name},c.id))]}),Cs(a("Vị trí"),ne.position,c=>et(ne.id,{position:c})),Cs("Xoay °",ne.rotation,c=>et(ne.id,{rotation:c}),-360),Cs(a("Tỷ lệ"),ne.scale,c=>et(ne.id,{scale:c}),.05),ne.kind==="model"&&ne.model&&t.jsxs("div",{className:"shot-model-size",children:[t.jsx(ss,{label:"Chiều cao thật (m)",value:Number((ge.current?.modelHeight(ne)??2).toFixed(2)),min:.02,max:500,step:.01,onChange:c=>et(ne.id,{model:{...ne.model,height:c}})}),t.jsx("small",{className:"shot-hint",children:ne.model.height?a("Kích thước thật"):a("Tự động: cạnh dài nhất 2 m")}),ne.model.height&&t.jsx("button",{onClick:()=>{const{height:c,...x}=ne.model;et(ne.id,{model:x})},children:a("Về tự động")})]}),ne.hold&&(()=>{const c=z.items.find(x=>x.id===ne.hold.by);return t.jsxs("div",{className:"shot-held",children:[t.jsx("small",{className:"shot-hint",children:a("Đang được {0} cầm ở {1}",[c?.name||"?",ne.hold.hand==="R"?a("tay phải"):a("tay trái")])}),t.jsx("button",{onClick:()=>c&&ul(c.id,ne.hold.hand,""),children:a("Thả xuống")})]})})(),ne.kind==="splat"&&ne.splat&&(()=>{const c=ge.current?.splatExtent(ne.splat);return t.jsxs("div",{className:"shot-splat",children:[t.jsx("h3",{children:a("BỐI CẢNH THẬT")}),t.jsxs("small",{className:"shot-hint",children:[ne.splat.source==="world"?a("3D World do AI tạo"):a("Bản quét địa điểm thật"),c?` · ${(c.max[0]-c.min[0]).toFixed(1)} × ${(c.max[2]-c.min[2]).toFixed(1)} m`:` · ${a("đang tải…")}`]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:ne.splat.flip!==!1,onChange:x=>{const L={...ne.splat,flip:x.target.checked},F=ge.current?.splatExtent(L);et(ne.id,F?{splat:{...L,bounds:{min:F.min,max:F.max},floor:F.floor},position:[ne.position[0],-F.floor*ne.scale[1],ne.position[2]]}:{splat:L})}}),a("Lật trục (file quét kiểu OpenCV)")]}),t.jsx(ss,{label:"Tỷ lệ bản quét",value:ne.scale[0],min:.05,step:.05,onChange:x=>et(ne.id,{scale:[x,x,x]})}),t.jsx("button",{disabled:!c,onClick:()=>{c&&et(ne.id,{position:[ne.position[0],-c.floor*ne.scale[1],ne.position[2]],splat:{...ne.splat,bounds:{min:c.min,max:c.max},floor:c.floor}})},children:a("Căn sàn về mặt đất")}),t.jsx("small",{className:"shot-hint",children:a('Người và camera đặt thẳng trong bối cảnh. Ảnh và video AI giữ nguyên kiến trúc, đồ đạc của bản quét. Sai hướng thì bật/tắt "Lật trục" rồi căn sàn lại.')})]})})(),y1.includes(ne.kind)&&t.jsx(j1,{item:z.items.find(c=>c.id===ne.id)??ne,shot:de,playhead:Ie,patchItem:et,change:Me}),ne.kind==="person"&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:a("NHẬN DIỆN NHÂN VẬT")}),t.jsxs("select",{"aria-label":a("Ảnh tham chiếu nhân vật"),value:ne.reference?.nodeId||"",onChange:c=>{const x=ao.find(F=>F.id===c.target.value),L=x?.data;et(ne.id,{reference:x&&L?.url?{nodeId:x.id,url:L.url,name:L.label||"Character reference"}:null})},children:[t.jsx("option",{value:"",children:a("Không dùng ảnh nhận diện")}),ao.map(c=>t.jsx("option",{value:c.id,children:String(c.data.label||"Image")},c.id))]}),ne.reference&&t.jsx("img",{className:"shot-character-ref",src:ne.reference.url,alt:ne.reference.name}),t.jsx("h3",{children:a("NHÂN VẬT")}),t.jsx("button",{type:"button",className:"shot-char-open",title:a("Thay người này bằng một nhân vật có xương trong kho (giữ vị trí và chuyển động)"),onClick:()=>{Bt(ne.id),W("characters")},children:a("Chọn nhân vật từ thư viện…")}),ne.look||ne.figure&&["legs","shoulders","hips","chest","waist","weight","muscle","posture","skin","face"].some(c=>ne.figure[c]!==void 0)?t.jsx("button",{type:"button",onClick:()=>et(ne.id,{figure:ne.figure?{height:ne.figure.height,head:ne.figure.head,build:ne.figure.build}:void 0,look:void 0,character:void 0}),children:a("Về mannequin trơn")}):null,t.jsx("h3",{children:a("VÓC DÁNG")}),t.jsx("div",{className:"shot-add shot-figure-presets",children:Xf.map(c=>{const x=Ht(ne.figure);return t.jsx("button",{className:x.height===c.figure.height&&x.head===c.figure.head&&x.build===c.figure.build?"active":"",onClick:()=>et(ne.id,{figure:{...c.figure}}),children:a(c.name)},c.name)})}),t.jsx(ss,{label:"Chiều cao (m)",value:Ht(ne.figure).height,min:.3,max:3,step:.01,onChange:c=>et(ne.id,{figure:Ht({...Ht(ne.figure),height:c})})}),t.jsxs("label",{className:"shot-joint",children:[a("Cỡ đầu")," ",t.jsxs("span",{children:[Ht(ne.figure).head.toFixed(2),"×"]}),t.jsx("input",{"aria-label":a("Cỡ đầu"),type:"range",min:.7,max:2,step:.05,value:Ht(ne.figure).head,onChange:c=>et(ne.id,{figure:Ht({...Ht(ne.figure),head:+c.target.value})})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Vai / hông")," ",t.jsxs("span",{children:[Ht(ne.figure).build.toFixed(2),"×"]}),t.jsx("input",{"aria-label":a("Vai / hông"),type:"range",min:.6,max:1.6,step:.05,value:Ht(ne.figure).build,onChange:c=>et(ne.id,{figure:Ht({...Ht(ne.figure),build:+c.target.value})})})]}),t.jsx("h3",{children:a("ĐẠO CỤ TRÊN TAY")}),t.jsxs("div",{className:"shot-props",children:[["R","L"].map(c=>{const x=z.items.find(F=>F.hold?.by===ne.id&&F.hold.hand===c),L=z.items.filter(F=>F.id!==ne.id&&!["person","splat","set","floor","wall"].includes(F.kind)&&!(F.hold&&F.hold.by!==ne.id));return t.jsxs("div",{className:"shot-prop-hand",children:[t.jsxs("label",{className:"shot-field",children:[c==="R"?a("Tay phải"):a("Tay trái"),t.jsxs("select",{"aria-label":c==="R"?a("Đạo cụ tay phải"):a("Đạo cụ tay trái"),value:x?`item:${x.id}`:"",onChange:F=>ul(ne.id,c,F.target.value),children:[t.jsx("option",{value:"",children:a("— Tay không —")}),x&&t.jsx("option",{value:`item:${x.id}`,children:x.name}),t.jsx("optgroup",{label:a("Đạo cụ dựng sẵn"),children:Vf.map(F=>t.jsx("option",{value:`prop:${F}`,children:a(Ia[F].label)},F))}),L.filter(F=>F.id!==x?.id).length>0&&t.jsx("optgroup",{label:a("Vật trong cảnh"),children:L.filter(F=>F.id!==x?.id).map(F=>t.jsx("option",{value:`item:${F.id}`,children:F.name},F.id))})]})]}),x&&t.jsxs("label",{className:"shot-joint",children:[a("Gập cổ tay")," ",t.jsxs("span",{children:[x.hold.tilt??(x.prop?Ia[x.prop.kind].tilt??0:0),"°"]}),t.jsx("input",{"aria-label":a("Gập cổ tay"),type:"range",min:-90,max:90,step:5,value:x.hold.tilt??(x.prop?Ia[x.prop.kind].tilt??0:0),onChange:F=>Me(K=>({...K,items:K.items.map(X=>X.id===x.id?{...X,hold:{...X.hold,tilt:+F.target.value}}:X)}))})]}),x&&t.jsxs("label",{className:"shot-joint",children:[a("Xoay quanh cổ tay")," ",t.jsxs("span",{children:[x.hold.angle??0,"°"]}),t.jsx("input",{"aria-label":a("Xoay đạo cụ quanh cổ tay"),type:"range",min:-180,max:180,step:5,value:x.hold.angle??0,onChange:F=>Me(K=>({...K,items:K.items.map(X=>X.id===x.id?{...X,hold:{...X.hold,angle:+F.target.value}}:X)}))})]})]},c)}),t.jsx("small",{className:"shot-hint",children:a("Đạo cụ đi theo cẳng tay qua mọi tư thế, dáng đi, cú đánh. Kiếm, gậy, dao nối dài tầm đánh khi tính trúng đòn.")})]}),t.jsx("h3",{children:a("CHUYỂN ĐỘNG NGƯỜI")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:ne.gait!=="off",onChange:c=>et(ne.id,{gait:c.target.checked?"auto":"off"})}),a("Tự bước đi / chạy khi di chuyển")]}),(()=>{const c=de.objectKeys?.[ne.id]||[],x=c.filter(F=>F.pose),L=x.find(F=>Math.abs(F.time-Ie)<1e-6);return t.jsxs("div",{className:"shot-pose-keys",children:[t.jsx("button",{className:L?"active":"",onClick:()=>sl(ne.id),children:L?a("◆ Cập nhật key tư thế · {0}s",[(Ie*de.duration).toFixed(1)]):a("◇ Key tư thế tại {0}s",[(Ie*de.duration).toFixed(1)])}),L&&t.jsx("button",{onClick:()=>Ku(ne.id),children:a("Bỏ key tư thế")}),L&&t.jsxs("label",{className:"shot-pose-ease",children:[a("Kiểu chuyển vào key")," ",t.jsx("select",{"aria-label":a("Kiểu chuyển vào key"),value:L.poseEase||"smooth",onChange:F=>Hu(ne.id,F.target.value),children:Yf.map(F=>t.jsx("option",{value:F.id,children:a(F.label)},F.id))})]}),t.jsx("small",{className:"shot-hint",children:x.length?a("{0} key tư thế · chỉnh khớp/rig tại key sẽ ghi vào key đó; giữa các key tư thế chuyển mượt.",[x.length]):a("Đặt key ở nhiều thời điểm (đứng → ngồi → giơ tay…) để tư thế chuyển động theo thời gian.")})]})})(),t.jsx(M1,{shot:de,item:ne,playhead:Ie*de.duration,change:Me,engine:ge.current,seek:c=>{D(!1),ot(Math.max(0,Math.min(1,c/de.duration)))}}),t.jsx($u,{disabled:ie,loop:ri,mirror:li,onLoop:hl,onMirror:dl,onPlay:c=>{ci(ne.id,c)},person:ne,playhead:Ie*de.duration}),t.jsxs("div",{className:"shot-mocap",children:[t.jsx("input",{ref:al,type:"file",accept:".bvh,.fbx,.glb",hidden:!0,onChange:c=>{qu(c.target.files?.[0]),c.target.value=""}}),t.jsxs("button",{disabled:rl||ie,onClick:()=>al.current?.click(),title:a("Chuyển động người thật: Mixamo (.fbx), CMU (.bvh) hoặc GLB có animation"),children:[t.jsx(Ce.person,{}),rl?a("Đang đọc…"):a("Nhập mocap (.bvh · .fbx · .glb)")]}),ls&&t.jsxs("div",{className:"shot-mocap-card",children:[t.jsx("b",{children:ls.name}),t.jsxs("small",{children:[ls.duration.toFixed(1),a("s · khung xương người ✓")]}),t.jsxs("label",{className:"shot-field",children:[a("Tốc độ"),t.jsx("select",{"aria-label":a("Tốc độ mocap"),value:da,onChange:c=>Wu(+c.target.value),children:[.5,.75,1,1.25,1.5,2].map(c=>t.jsxs("option",{value:c,children:[c,"×"]},c))})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:il,onChange:c=>Gu(c.target.checked)}),a("Di chuyển theo mocap (đi, chạy, nhảy)")]}),t.jsx("small",{className:"shot-hint",children:a("Bắt đầu tại {0}s · dùng {1}s (phần dài hơn shot bị cắt)",[(Ie*de.duration).toFixed(1),Math.min(ls.duration/da,(1-Ie)*de.duration).toFixed(1)])}),t.jsx("button",{className:"shot-primary",disabled:ie,onClick:()=>Xu(ne.id),children:a("Áp dụng cho {0}",[ne.name])})]}),Qf(z,ne.id)&&t.jsx("button",{onClick:()=>{D(!1),Me(c=>T0(c,ne.id))},children:a("Xoá mocap của {0}",[ne.name])})]}),t.jsxs("div",{className:"shot-hits",children:[t.jsx("button",{onClick:Yu,children:a("⚡ Tự tạo phản ứng trúng đòn")}),Zf(de)&&t.jsx("button",{onClick:Qu,children:a("Xoá phản ứng tự động")}),t.jsx("small",{className:"shot-hint",children:Vu||a('Đòn = key tư thế kiểu "Ra đòn nhanh". Trúng thì người kia tự bật ra; key Đỡ đòn / Né cúi / Ngả né trước cú đánh để đỡ hoặc né.')})]}),t.jsxs("h3",{children:[a("RIG PRESETS"),t.jsx("button",{className:"shot-pose-mirror",title:a("Lật tư thế trái ↔ phải"),onClick:()=>et(ne.id,{pose:Jf(ne.pose)}),children:a("⇆ Lật trái/phải")})]}),t.jsx("div",{className:"shot-rig-library",children:Ho.map(c=>t.jsxs("section",{children:[t.jsxs("header",{children:[t.jsx("span",{children:a(c.name)}),t.jsxs("small",{children:[c.presets.length," ",a("rig")]})]}),t.jsx("div",{className:"shot-rig-grid",children:c.presets.map(x=>t.jsxs("button",{className:xj(ne.pose,qn[x])?"active":"",title:a("Áp dụng rig {0}",[x]),onClick:()=>Bu(ne,x),children:[t.jsx(tl,{pose:qn[x]}),t.jsx("span",{children:a(x)})]},x))})]},a(c.name)))}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Thư viện pose cá nhân")}),t.jsxs("div",{className:"shot-pose-library",children:[z.poseLibrary.map(c=>t.jsxs("div",{children:[t.jsx("button",{onClick:()=>et(ne.id,{pose:{...c.pose}}),children:c.name}),t.jsx("button",{"aria-label":a("Xóa {0}",[c.name]),onClick:()=>Me(x=>({...x,poseLibrary:x.poseLibrary.filter(L=>L.id!==c.id)})),children:a("×")})]},c.id)),t.jsx("button",{onClick:()=>{const c=window.prompt(a("Tên pose"),`Pose ${z.poseLibrary.length+1}`)?.trim();c&&Me(x=>({...x,poseLibrary:[...x.poseLibrary,{id:yt(),name:c,pose:structuredClone(ne.pose)}]}))},children:a("+ Lưu pose hiện tại")})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:a("Kéo tay/chân IK")}),t.jsxs("div",{className:"shot-ik-grid",children:[t.jsx(To,{label:"Tay trái",root:ne.pose.shoulderL,bend:ne.pose.elbowL,upper:.29,lower:.27,onChange:(c,x)=>et(ne.id,{pose:{...ne.pose,shoulderL:c,elbowL:x}})}),t.jsx(To,{label:"Tay phải",root:ne.pose.shoulderR,bend:ne.pose.elbowR,upper:.29,lower:.27,onChange:(c,x)=>et(ne.id,{pose:{...ne.pose,shoulderR:c,elbowR:x}})}),t.jsx(To,{label:"Chân trái",root:ne.pose.hipL,bend:ne.pose.kneeL,upper:.43,lower:.4,onChange:(c,x)=>et(ne.id,{pose:{...ne.pose,hipL:c,kneeL:x}})}),t.jsx(To,{label:"Chân phải",root:ne.pose.hipR,bend:ne.pose.kneeR,upper:.43,lower:.4,onChange:(c,x)=>et(ne.id,{pose:{...ne.pose,hipR:c,kneeR:x}})})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:a("Chỉnh từng khớp")}),Object.keys(Do).map(c=>t.jsxs("label",{className:"shot-joint",children:[a(Do[c])," ",t.jsxs("span",{children:[ne.pose[c]||0,"°"]}),t.jsx("input",{"aria-label":a(Do[c]),type:"range",min:c.startsWith("knee")||c.startsWith("elbow")?0:-120,max:150,value:ne.pose[c]||0,onChange:x=>et(ne.id,{pose:{...ne.pose,[c]:+x.target.value}})})]},c))]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:a("Tay · đầu · mắt")}),t.jsx("div",{className:"shot-hand-shapes",children:["R","L"].map(c=>t.jsxs("div",{children:[t.jsx("small",{children:c==="R"?a("Tay phải"):a("Tay trái")}),t.jsx("span",{children:ar.map(x=>t.jsx("button",{type:"button",className:e0(ne.pose,c,x)?"active":"",onClick:()=>et(ne.id,{pose:gj(ne.pose,c,x)}),children:a(x.label)},x.id))})]},c))}),t.jsxs("label",{className:"shot-field",children:[a("Mắt nhìn"),t.jsxs("select",{"aria-label":a("Mắt nhìn"),value:ne.gaze||"",onChange:c=>et(ne.id,{gaze:c.target.value||void 0}),children:[t.jsx("option",{value:"",children:a("Theo tư thế")}),t.jsx("option",{value:"camera",children:a("Nhìn vào camera")}),z.items.filter(c=>c.id!==ne.id&&c.kind!=="splat"&&c.kind!=="set").map(c=>t.jsx("option",{value:c.id,children:a("Nhìn {0}",[c.name])},c.id))]})]}),Object.keys(er).map(c=>{const[x,L,F]=t0[c],K=fj(ne.pose,c);return t.jsxs("label",{className:"shot-joint",children:[a(er[c])," ",t.jsxs("span",{children:[K,F]}),t.jsx("input",{"aria-label":a(er[c]),type:"range",min:x,max:L,value:K,disabled:(c==="eyeYaw"||c==="eyePitch")&&!!ne.gaze,onChange:X=>et(ne.id,{pose:{...ne.pose,[c]:+X.target.value}})})]},c)})]})]}),t.jsx("button",{onClick:()=>{const c={...structuredClone(ne),id:yt(),name:`${ne.name} copy`,position:[ne.position[0]+1,...ne.position.slice(1)]};Me(x=>({...x,items:[...x.items,c]})),xt(c.id)},children:a("Nhân bản")}),t.jsx("button",{onClick:()=>{pl(ne.id)},children:a("Xóa đối tượng")})]})]})]}),Q==="camera"&&t.jsxs(t.Fragment,{children:[t.jsx("input",{"aria-label":a("Tên shot"),value:de.name,onChange:c=>jt({name:c.target.value})}),t.jsxs("div",{className:"shot-camera-gizmo",role:"group","aria-label":a("Chỉnh camera trong cảnh 3D"),children:[t.jsxs("button",{type:"button",className:r?"active":"","aria-pressed":r,disabled:S,title:a("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"),onClick:()=>{xt(null),i(null),l(!r),ee(c=>c==="scale"?"translate":c)},children:[t.jsx(Ce.camera,{}),a("Chọn camera")]}),r&&["translate","rotate"].map(c=>t.jsxs("button",{type:"button",className:(_==="rotate"?"rotate":"translate")===c?"active":"","aria-pressed":(_==="rotate"?"rotate":"translate")===c,title:a(c==="translate"?"Di chuyển camera (W)":"Xoay camera (E): vòng xanh dương = nghiêng"),onClick:()=>ee(c),children:[c==="translate"?t.jsx(Ce.move,{}):t.jsx(Ce.rotate,{}),a(c==="translate"?"Di chuyển":"Xoay")]},c))]}),t.jsx("textarea",{className:"shot-note","aria-label":a("Ghi chú đạo diễn cho shot"),placeholder:a("Ghi chú đạo diễn: hành động, cảm xúc, điểm nhấn… (đưa vào prompt)"),maxLength:500,rows:2,value:de.note||"",onChange:c=>jt({note:c.target.value})}),t.jsxs("div",{className:"shot-row",children:[t.jsx("select",{"aria-label":a("Tỷ lệ ảnh"),value:de.aspect,onChange:c=>jt({aspect:c.target.value}),children:["16:9","9:16","1:1","21:9","4:3","2.39:1"].map(c=>t.jsx("option",{children:c},c))}),de.motion!=="path"&&t.jsx(ss,{label:"Lens mm",value:de.lens,min:14,max:200,step:1,onChange:c=>jt({lens:c})})]}),t.jsxs("label",{className:"shot-field",children:[a("Thời lượng camera (giây)"),t.jsx(Tn,{"aria-label":a("Thời lượng camera (giây)"),min:.1,step:"0.1",value:de.duration,onCommit:c=>jt({duration:c})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Rung cầm tay")," ",t.jsxs("span",{children:[Math.round((de.handheld||0)*100),"%"]}),t.jsx("input",{"aria-label":a("Rung cầm tay"),type:"range",min:0,max:1,step:.05,value:de.handheld||0,onChange:c=>jt({handheld:+c.target.value||void 0})})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:de.impactShake!==!1,onChange:c=>{const x=c.target.checked;jt(x?{impactShake:void 0}:{impactShake:!1,impacts:void 0})}}),a("Rung camera khi trúng đòn")]}),t.jsx(tj,{shot:de,patch:jt,progress:Ie,seek:c=>{D(!1),ot(c)},engine:ge.current||null,selected:o,select:c=>{i(c),M(c?{row:"camera",id:c}:null)}}),de.motion==="path"&&t.jsx("button",{disabled:ie||!st||!de.cameraKeys?.length,onClick:async()=>{D(!1),me(!0),be("");try{for(const[c,x]of(de.cameraKeys||[]).entries())await cs(!0,de,c,!1,x.time,` · Key ${c+1} · ${(x.time*de.duration).toFixed(1)}s`)}catch(c){be(c.message)}finally{me(!1)}},children:a("Xuất các key thành ảnh tham chiếu")}),t.jsx("h3",{children:a("CHUYỂN ĐỘNG NHANH")}),t.jsxs("select",{"aria-label":a("Chuyển động camera"),value:de.motion,onChange:c=>fm(c.target.value),children:[t.jsx("option",{value:"path",disabled:!de.cameraKeys?.length,children:a("Đường chạy keyframe")}),t.jsx("option",{value:"static",children:a("Đứng yên")}),t.jsx("option",{value:"dolly-in",children:a("Dolly in")}),t.jsx("option",{value:"dolly-out",children:a("Dolly out")}),t.jsx("option",{value:"truck-left",children:a("Truck trái")}),t.jsx("option",{value:"truck-right",children:a("Truck phải")}),t.jsx("option",{value:"crane-up",children:a("Crane lên")}),t.jsx("option",{value:"crane-down",children:a("Crane xuống")}),t.jsx("option",{value:"orbit-left",children:a("Orbit trái")}),t.jsx("option",{value:"orbit-right",children:a("Orbit phải")}),t.jsx("option",{value:"custom",children:a("Tùy chỉnh")})]}),de.motion!=="static"&&de.motion!=="path"&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-joint",children:[a("Xem chuyển động")," ",t.jsxs("span",{children:[Math.round(Ie*100),"%"]}),t.jsx("input",{"aria-label":a("Tiến trình camera"),type:"range",min:0,max:100,value:Ie*100,onChange:c=>ot(+c.target.value/100)})]}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Camera kết thúc")}),Cs(a("Vị trí cuối"),de.endPosition,c=>jt({endPosition:c,motion:"custom"})),Cs(a("Điểm nhìn cuối"),de.endTarget,c=>jt({endTarget:c,motion:"custom"})),t.jsx(ss,{label:"Lens cuối mm",value:de.endLens,min:14,max:200,step:1,onChange:c=>jt({endLens:c,motion:"custom"})})]})]}),t.jsxs("fieldset",{disabled:de.motion==="path",style:{display:de.motion==="path"?"none":void 0},children:[t.jsx("button",{onClick:()=>jt(ge.current?.captureCamera()||{}),children:a("Dùng góc quan sát làm camera")}),t.jsx("div",{className:"shot-add",children:["Toàn","Trung","Cận","Thấp","Cao","Qua vai"].map((c,x)=>t.jsx("button",{onClick:()=>{const L=ne?.position||[0,0,0];jt({position:[[3,2,6],[0,1.5,3],[0,1.7,1.2],[1,.3,3],[2,5,3],[.5,1.7,-1.5]][x].map((K,X)=>K+L[X]),target:[L[0],L[1]+(x===2?1.65:1.2),L[2]],roll:0})},children:a(c)},c))}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Thông số camera")}),Cs(a("Vị trí máy"),de.position,c=>jt({position:c})),Cs(a("Điểm nhìn"),de.target,c=>jt({target:c})),t.jsx(ss,{label:"Nghiêng máy °",value:de.roll,min:-180,max:180,step:1,onChange:c=>jt({roll:c})}),t.jsx("button",{disabled:z.shots.length<2,onClick:()=>Me(c=>{const x=c.shots.filter(L=>L.id!==c.activeShot);return{...c,shots:x,activeShot:x[0].id}}),children:a("Xóa camera này")})]})]}),de.motion==="path"&&t.jsx("button",{disabled:z.shots.length<2,onClick:()=>Me(c=>{const x=c.shots.filter(L=>L.id!==c.activeShot);return{...c,shots:x,activeShot:x[0].id}}),children:a("Xóa camera đường chạy")}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Prompt bố cục")}),t.jsx("textarea",{"aria-label":a("Prompt bố cục"),readOnly:!0,value:Ei(z),rows:8}),t.jsx("button",{onClick:()=>navigator.clipboard.writeText(Ei(z)).then(()=>ht.getState().toast(a("Đã copy prompt"),"ok")).catch(()=>be("Không truy cập được clipboard; hãy chọn và copy nội dung.")),children:a("Copy prompt")})]})]}),Q==="light"&&t.jsx("div",{className:"shot-light-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("select",{"aria-label":a("Thời điểm trong ngày"),value:vt.time,onChange:c=>{const x=c.target.value;Rn({time:x,elevation:hc[x].elevation})},children:n0.map(c=>t.jsx("option",{value:c,children:a(hc[c].label)},c))}),t.jsxs("label",{className:"shot-joint",children:[a("Hướng mặt trời")," ",t.jsxs("span",{children:[Math.round(vt.azimuth),"°"]}),t.jsx("input",{"aria-label":a("Hướng mặt trời"),type:"range",min:0,max:359,value:Math.round(vt.azimuth),onChange:c=>Rn({azimuth:+c.target.value})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Độ cao mặt trời")," ",t.jsxs("span",{children:[Math.round(vt.elevation),"°"]}),t.jsx("input",{"aria-label":a("Độ cao mặt trời"),type:"range",min:1,max:89,value:Math.round(vt.elevation),onChange:c=>Rn({elevation:+c.target.value})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Môi trường phản xạ")}),t.jsx("select",{"aria-label":a("Môi trường phản xạ"),value:vt.env??"auto",onChange:c=>Rn({env:c.target.value}),children:s0.map(c=>t.jsx("option",{value:c.id,children:a(c.label)},c.id))})]}),t.jsxs("label",{className:"shot-joint",children:[a("Xoay môi trường")," ",t.jsxs("span",{children:[Math.round(vt.envRotation??0),"°"]}),t.jsx("input",{"aria-label":a("Xoay môi trường"),type:"range",min:0,max:359,value:Math.round(vt.envRotation??0),onChange:c=>Rn({envRotation:+c.target.value})})]}),a0(vt)==="sky"&&t.jsxs("label",{className:"shot-joint",children:[a("Mây trên trời")," ",t.jsxs("span",{children:[Math.round(dc(vt)*100),"%"]}),t.jsx("input",{"aria-label":a("Mây trên trời"),type:"range",min:0,max:100,value:Math.round(dc(vt)*100),onChange:c=>Rn({clouds:+c.target.value/100})})]}),vt.time!=="interior"&&t.jsxs("label",{className:"shot-joint",title:a("Tia sáng từ mặt trời (đêm: mặt trăng) xuyên qua vật chắn — thấy ở chất lượng Cao và khi xuất video"),children:[a("Tia nắng mặt trời")," ",t.jsxs("span",{children:[Math.round((vt.sunRays??0)*100),"%"]}),t.jsx("input",{"aria-label":a("Tia nắng mặt trời"),type:"range",min:0,max:100,value:Math.round((vt.sunRays??0)*100),onChange:c=>Rn({sunRays:+c.target.value/100})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Ánh sáng viền (Rim)")," ",t.jsxs("span",{children:[Math.round((vt.rim??1)*100),"%"]}),t.jsx("input",{"aria-label":a("Ánh sáng viền (Rim)"),type:"range",min:0,max:200,value:Math.round((vt.rim??1)*100),onChange:c=>Rn({rim:+c.target.value/100})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Xóa phông ống kính (DOF)")}),t.jsx("select",{"aria-label":a("Xóa phông ống kính (DOF)"),value:vt.dof??"off",onChange:c=>Rn({dof:c.target.value}),children:o0.map(c=>t.jsx("option",{value:c.id,children:a(c.label)},c.id))})]}),vt.dof&&t.jsxs("label",{className:"shot-joint",children:[a("Khoảng nét")," ",t.jsx("span",{children:vt.focusDistance?`${vt.focusDistance.toFixed(1)}m`:a("Tự động")}),t.jsx("input",{"aria-label":a("Khoảng nét"),type:"range",min:.5,max:40,step:.5,value:vt.focusDistance??Math.max(.5,Math.min(40,Math.hypot(de.position[0]-de.target[0],de.position[1]-de.target[1],de.position[2]-de.target[2]))),onChange:c=>Rn({focusDistance:+c.target.value})})]}),vt.dof&&vt.focusDistance!==void 0&&t.jsx("button",{type:"button",onClick:()=>Rn({focusDistance:void 0}),children:a("Lấy nét tự động theo mục tiêu")}),t.jsx("small",{className:"shot-hint",children:a("Dùng chung cho mọi shot của cảnh, để hướng sáng không lệch giữa các góc máy.")}),vt.dof&&t.jsx(lj,{shot:de,items:z.items,progress:Ie,presetFstop:i0(vt.dof)??2.8,onChange:c=>jt({focus:c})}),t.jsxs("label",{className:"shot-field shot-render-style",children:[t.jsx("span",{children:a("Kiểu hình")}),t.jsxs("select",{"aria-label":a("Kiểu hình"),value:z.style?"clay":"natural",onChange:c=>{const x=c.target.value==="clay";Me(L=>{const{style:F,...K}=L;return x?{...K,style:L0({...E0,...F||{},style:"clay"})}:K})},children:[t.jsx("option",{value:"natural",children:a("Tự nhiên")}),t.jsx("option",{value:"clay",children:a("Đất sét · phim tài liệu 3D")})]})]}),z.style&&t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:z.style.accents==="vivid",onChange:c=>{const x=c.target.checked?"vivid":"none";Me(L=>L.style?{...L,style:{...L.style,accents:x}}:L)}}),a("Giữ màu nổi bật trên người (đồng phục đỏ, sọc vàng…)")]}),z.style&&t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:z.style.faceted,onChange:c=>{const x=c.target.checked;Me(L=>L.style?{...L,style:{...L.style,faceted:x}}:L)}}),a("Mặt góc cạnh (low-poly)")]}),z.style&&t.jsx("small",{className:"shot-hint",children:a("Người và nhân vật thành tượng đất sét xám, bối cảnh và xe cộ giữ màu — kiểu phim tài liệu tội phạm 3D.")}),t.jsxs("label",{className:"shot-field shot-style-refs",children:[t.jsxs("span",{children:[a("Ảnh phong cách bối cảnh")," · ",ua.length,"/",Ri]}),t.jsxs("select",{"aria-label":a("Thêm ảnh phong cách bối cảnh"),value:"",disabled:ua.length>=Ri,onChange:c=>{const x=ao.find(F=>F.id===c.target.value),L=x?.data;x&&L?.url&&Me(F=>({...F,styleRefs:[...(F.styleRefs||[]).filter(K=>K.nodeId!==x.id),{nodeId:x.id,url:L.url,name:L.label||"Location look"}].slice(0,Ri)}))},children:[t.jsx("option",{value:"",children:a("+ Chọn ảnh trên canvas…")}),ao.filter(c=>!ua.some(x=>x.nodeId===c.id)).map(c=>t.jsx("option",{value:c.id,children:String(c.data.label||"Image")},c.id))]})]}),ua.length>0&&t.jsx("div",{className:"shot-style-strip",children:ua.map(c=>t.jsxs("span",{children:[t.jsx("img",{src:c.url,alt:c.name}),t.jsx("button",{"aria-label":a("Bỏ {0}",[c.name]),onClick:()=>Me(x=>({...x,styleRefs:(x.styleRefs||[]).filter(L=>L.nodeId!==c.nodeId)})),children:"×"})]},c.nodeId))}),t.jsx("small",{className:"shot-hint",children:a("Khoá chất liệu, màu và đồ đạc của bối cảnh cho mọi shot khi tạo ảnh thật và video.")})]})}),Q==="shots"&&t.jsx("div",{className:"shot-shots-section",children:t.jsx("ol",{className:"shot-shotlist",children:z.shots.map((c,x)=>{const L=Sl[x];return t.jsxs("li",{"data-shot":c.id,className:c.id===z.activeShot?"active":"",children:[t.jsxs("button",{className:"shot-shotlist-pick","aria-label":a("Chọn {0}",[c.name]),"aria-current":c.id===z.activeShot,disabled:!!C,onClick:()=>Me(F=>({...F,activeShot:c.id})),children:[Lt[c.id]?t.jsx("img",{src:Lt[c.id],alt:""}):t.jsx("span",{className:"shot-thumb-empty","aria-hidden":"true"}),t.jsxs("span",{className:"shot-shotlist-meta",children:[t.jsx("b",{children:c.name}),t.jsxs("small",{children:[Li(L.start),"–",Li(L.end)," · ",Number(c.lens.toFixed(1)),"mm"]}),c.note?.trim()&&t.jsx("small",{className:"shot-shotlist-note",children:c.note.trim()})]})]}),t.jsxs("span",{className:"shot-shotlist-order",children:[t.jsx("button",{"aria-label":a("Đưa {0} lên",[c.name]),disabled:x===0||!!C,onClick:()=>Nl(c.id,-1),children:"↑"}),t.jsx("button",{"aria-label":a("Đưa {0} xuống",[c.name]),disabled:x===z.shots.length-1||!!C,onClick:()=>Nl(c.id,1),children:"↓"})]}),t.jsx("button",{className:"shot-shotlist-delete","aria-label":a("Xóa {0}",[c.name]),title:z.shots.length<2?a("Cảnh cần ít nhất một shot"):a("Xóa {0} (hoàn tác bằng ⌘Z)",[c.name]),disabled:z.shots.length<2||!!C,onClick:()=>Cl(c.id),children:t.jsx(Ce.trash,{})})]},c.id)})})}),Q==="notes"&&t.jsx("div",{className:"shot-notes-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("button",{className:at?"active":"","aria-pressed":at,disabled:!st||Os.length>=uc,onClick:om,children:at?a("Bấm vào cảnh để ghim… (bấm lại để huỷ)"):a("+ Ghim ghi chú vào cảnh")}),t.jsx("ol",{className:"shot-note-list",children:Os.map((c,x)=>t.jsxs("li",{children:[t.jsx("span",{children:x+1}),t.jsx("input",{"aria-label":a("Ghi chú {0}",[x+1]),value:c.text,maxLength:mc,onChange:L=>im(c.id,L.target.value)}),t.jsx("button",{"aria-label":a("Xoá ghi chú {0}",[x+1]),onClick:()=>rm(c.id),children:"×"})]},c.id))}),Os.length>0&&t.jsx("button",{disabled:ie||!st,onClick:()=>void jm(),children:a("Tải PNG có ghi chú")}),t.jsx("small",{className:"shot-hint",children:a("Ghi chú gắn vào vị trí trong không gian 3D nên đúng chỗ ở mọi góc máy; chỉ hiện trong khung dựng, được đưa vào prompt và bản PNG có ghi chú.")})]})}),Q==="series"&&t.jsx("div",{className:"shot-series-section",children:t.jsx("div",{className:"shot-panel-body",children:t.jsx(oj,{stage:z,nodeId:e,selected:z.items.find(c=>c.id===J)||null,disabled:ie||!!C,change:Me,onError:be,onSelect:xt})})})]}),t.jsx("div",{className:"shot-resize shot-resize-x",role:"separator","aria-orientation":"vertical","aria-label":a("Kéo để đổi độ rộng bảng công cụ"),onPointerDown:c=>bi(c,"drawer")})]}),t.jsxs("main",{className:"shot-center",children:[t.jsxs("div",{className:"shot-monitor",children:[t.jsxs("div",{className:`shot-topbar ${U?"":"collapsed"}`,children:[t.jsxs("div",{className:"shot-shot-switcher",children:[t.jsx("select",{"aria-label":a("Chọn shot"),value:de.id,onChange:c=>Me(x=>({...x,activeShot:c.target.value})),children:z.shots.map(c=>t.jsx("option",{value:c.id,children:c.name},c.id))}),t.jsxs("button",{onClick:()=>{const c={...structuredClone(de),id:yt(),name:`Shot ${z.shots.length+1}`};Me(x=>({...x,shots:[...x.shots,c],activeShot:c.id}))},children:[t.jsx(Ce.save,{}),t.jsx("span",{className:"lbl",children:a("+ Lưu góc mới").replace("+ ","")})]}),t.jsx(sj,{shot:de,patch:jt,disabled:ie||!!C})]}),t.jsxs("div",{className:"shot-viewtools",hidden:!U,children:[_==="scale"&&ne&&!ne.locked&&t.jsx(ss,{label:"Tỷ lệ đồng đều",value:ne.scale[0],min:.05,step:ce?.1:.05,onChange:c=>et(ne.id,{scale:ne.scale.map(x=>x*c/ne.scale[0])})}),t.jsxs("span",{className:"shot-tools-hint",children:[_==="scale"?a("Kéo ô vuông trên trục để đổi kích thước."):"",ce?a(" Bước: 1 m · 15° · tỷ lệ 0,1"):""]}),["translate","rotate","scale"].map((c,x)=>t.jsxs("button",{className:c===_?"active":"",title:a(["Di chuyển","Xoay","Kích thước"][x]),onClick:()=>ee(c),children:[[t.jsx(Ce.move,{},"m"),t.jsx(Ce.rotate,{},"r"),t.jsx(Ce.scale,{},"s")][x],t.jsx("span",{className:"lbl",children:a(["Di chuyển","Xoay","Kích thước"][x])})]},c)),t.jsxs("button",{className:ce?"active":"",title:ce?a("Bám lưới: Bật"):a("Bám lưới: Tắt"),onClick:()=>Ee(!ce),children:[t.jsx(Ce.snap,{}),t.jsx("span",{className:"lbl",children:ce?a("Bám lưới: Bật"):a("Bám lưới: Tắt")})]}),t.jsxs("button",{className:je==="high"?"active":"","aria-pressed":je==="high",title:je==="high"?a("Chất lượng cao: bóng mềm, AO, bloom. Bấm để chuyển sang Nháp (nhanh hơn). Xuất video/ảnh luôn dùng Chất lượng cao."):a("Nháp: nhanh, cho máy yếu. Bấm để bật Chất lượng cao. Xuất video/ảnh luôn dùng Chất lượng cao."),onClick:()=>le(je==="high"?"draft":"high"),children:[t.jsx(Ce.cinema,{}),t.jsx("span",{className:"lbl",children:je==="high"?a("Chất lượng cao"):a("Nháp")})]}),t.jsxs("button",{className:Le?"active":"","aria-pressed":Le,title:a("Path Trace (GPU Ray Tracing): ánh sáng nảy GI, bóng mềm & phản chiếu vật lý như Blender Cycles ngay trên trình duyệt"),onClick:()=>{D(!1),Ke(null),Ae(c=>!c)},children:[t.jsx(Ce.spark,{}),t.jsx("span",{className:"lbl",children:a("Path Trace")})]}),t.jsxs("button",{className:ze?"active":"","aria-pressed":!!ze,title:a("Chụp nhanh lưới 6 góc máy điện ảnh từ cảnh hiện tại để chọn góc đẹp nhất chỉ bằng 1 bấm"),onClick:()=>{if(ze){Ke(null);return}const c=ge.current;if(!c)return;D(!1),Ae(!1);const x=cj(de.target,de.position,de.lens);Ke(c.renderAngleSheet(x,360,202))},children:[t.jsx(Ce.camera,{}),t.jsx("span",{className:"lbl",children:a("6 góc máy")})]}),sd()&&t.jsxs("button",{className:Je?"active":"","aria-pressed":Je,title:Je?a("Nhân vật người thật vẽ chất lượng cao (thân mượt, mặt, tóc, quần áo). Bấm để vẽ nhẹ hơn cho máy yếu. Người thường là mannequin; chọn nhân vật trong thư viện để thành người thật."):a("Máy yếu: nhân vật người thật vẽ bản nhẹ. Bấm để bật chất lượng cao."),onClick:()=>{const c=!Je;dv(c),P(c)},children:[t.jsx(Ce.person,{}),t.jsx("span",{className:"lbl",children:Je?a("Người thật"):a("Mannequin")})]}),t.jsxs("button",{title:a("Từ trên xuống"),onClick:()=>ge.current?.view(!0),children:[t.jsx(Ce.top,{}),t.jsx("span",{className:"lbl",children:a("Từ trên xuống")})]}),t.jsxs("button",{title:a("Tập trung (F)"),"aria-keyshortcuts":"F",onClick:()=>ge.current?.view(),children:[t.jsx(Ce.focus,{}),t.jsx("span",{className:"lbl",children:a("Tập trung")})]})]}),t.jsx("button",{className:"shot-tools-toggle","aria-expanded":U,title:U?a("Thu gọn công cụ"):a("Mở công cụ"),onClick:()=>{const c=!U;re(c);try{localStorage.setItem("clipoox.shot.tools",c?"1":"0")}catch{}},children:U?t.jsx(Ce.chevUp,{}):t.jsx(Ce.chevDown,{})})]}),t.jsxs("div",{className:"shot-viewport",ref:Ln,onDragOver:c=>{(c.dataTransfer.types.includes(Sr)||c.dataTransfer.types.includes($o))&&(c.preventDefault(),c.dataTransfer.dropEffect="copy")},onDrop:c=>{c.dataTransfer.types.includes($o)?sm(c):nm(c)},children:[Le&&t.jsxs("div",{className:"shot-pt-overlay",children:[t.jsx("canvas",{ref:un,className:"shot-pt-canvas"}),t.jsxs("div",{className:"shot-pt-hud",children:[t.jsx("span",{className:"shot-pt-status",children:ke.done>=ke.total?a("Path Trace · Xong ({0} mẫu)",[ke.total]):a("Path Trace · {0}/{1} mẫu",[ke.done,ke.total])}),t.jsx("button",{type:"button",onClick:()=>he(c=>c==="shot"?"viewport":"shot"),children:we==="shot"?a("Camera Shot"):a("Góc quan sát")}),t.jsx("button",{type:"button",onClick:()=>Be(c=>c+1),children:a("Vẽ lại")}),t.jsx("button",{type:"button",onClick:()=>{const c=an.current?.captureDataUrl();if(!c)return;const x=document.createElement("a");x.href=c,x.download=`clipoox-pathtrace-${Date.now()}.png`,x.click()},children:a("Lưu PNG")}),t.jsx("button",{type:"button",onClick:()=>Ae(!1),children:a("Đóng")})]})]}),ze&&t.jsxs("div",{className:"shot-angles-overlay",onPointerDown:c=>c.stopPropagation(),children:[t.jsxs("div",{className:"shot-angles-head",children:[t.jsx("b",{children:a("Chọn nhanh 6 góc máy điện ảnh")}),t.jsx("button",{type:"button",onClick:()=>Ke(null),children:a("Đóng")})]}),t.jsx("div",{className:"shot-angles-grid",children:ze.map(c=>t.jsxs("button",{type:"button",className:"shot-angle-card",onClick:()=>{Me(x=>({...x,shots:x.shots.map(L=>L.id===x.activeShot?{...L,position:[...c.camera],target:[...c.target],lens:c.lens}:L)})),Ke(null)},children:[t.jsx("img",{src:c.dataUrl,alt:c.label}),t.jsxs("div",{className:"shot-angle-meta",children:[t.jsx("strong",{children:a(c.label)}),t.jsx("span",{children:a(c.subtitle)})]})]},c.id))})]})]}),t.jsx("span",{className:"shot-viewlabel",children:a("GÓC QUAN SÁT · không đổi camera xuất ảnh")}),ne&&bj(ne)&&!C&&(Jt===ne.id?t.jsx(A1,{engine:st?ge.current:null,stage:z,shot:de,item:ne,playhead:Ie*de.duration,change:Me,onDone:()=>ut(null)}):t.jsxs("button",{type:"button",className:"shot-pose-chip",title:a("Kéo trực tiếp các khớp trên nhân vật (đầu, ngực, khuỷu, tay, hông, gối, chân)"),onClick:()=>{D(!1),ut(ne.id)},children:[t.jsx(Ce.person,{}),a("Chỉnh dáng")]})),ne&&Q!==(Wa(ne)?"mixfx":ne.kind==="fx"?"fxedit":"objects")&&t.jsxs("button",{type:"button",className:"shot-edit-chip",onClick:()=>Zn(Wa(ne)?"mixfx":ne.kind==="fx"?"fxedit":"objects"),children:[t.jsx(Ce.pen,{}),a("Chỉnh {0}",[ne.name])]})]}),t.jsx("div",{className:"shot-resize shot-resize-y",role:"separator","aria-orientation":"horizontal","aria-label":a("Kéo để đổi chiều cao timeline"),onPointerDown:c=>bi(c,"timeline")}),t.jsx(Zx,{loop:u,onLoop:()=>m(c=>!c),range:d,rangeOn:p,onRangeOn:()=>y(c=>!c),onEnd:()=>{D(!1),ot(1)},onKeyAll:Ll,onCopy:El,onPaste:Rl,canPaste:v,onEase:um,onNudge:Il,stage:z,cameraActive:r,cameraHidden:k,cameraLocked:S,onToggle:hm,onProp:dm,height:pe.timeline,onHeight:c=>ue(x=>({...x,timeline:c})),shot:de,items:z.items,fxBars:am,onParent:cm,onFxTiming:(c,x)=>Me(L=>({...L,shots:L.shots.map(F=>F.id===L.activeShot?{...F,fxTiming:{...F.fxTiming,[c]:Dr({...On(L.items.find(K=>K.id===c),F),...x,off:!1},F.duration)}}:F)})),time:Ie,playing:B,selected:j,picked:T,onPick:Tl,onSeek:c=>{D(!1),ot(c)},onPlay:()=>{!B&&Ie>=1&&ot(0),D(!B)},onRow:c=>{i(null),M(null),N([]),xt(c==="camera"?null:c),l(c==="camera"&&!S);{const x=z.items.find(L=>L.id===c);Wa(x)?Zn("mixfx"):x?.kind==="fx"&&Zn("fxedit")}},onSelect:lm,onAdd:pi,onMove:pm,onDelete:Pl})]}),t.jsxs("aside",{className:"shot-right",children:[t.jsx("div",{className:"shot-resize shot-resize-x shot-resize-left",role:"separator","aria-orientation":"vertical","aria-label":a("Kéo để đổi độ rộng cột xem trước"),onPointerDown:c=>bi(c,"right")}),t.jsxs("section",{className:"shot-preview-pinned",children:[t.jsx("h3",{children:a("KHUNG CAMERA")}),t.jsx("div",{className:"shot-preview",style:{aspectRatio:Ii(de.aspect).join(" / "),width:`min(100%, ${30*Ii(de.aspect)[0]/Ii(de.aspect)[1]}dvh)`},ref:_e}),t.jsxs("div",{className:"shot-camera-player",children:[t.jsx("button",{"aria-label":B?a("Tạm dừng camera"):a("Phát camera"),onClick:()=>{!B&&Ie>=1&&ot(0),D(!B)},children:a(B?"Ⅱ Pause":"▶ Play")}),t.jsx("button",{"aria-label":a("Về đầu"),onClick:()=>{D(!1),ot(0)},children:"↤"}),t.jsxs("span",{children:[(Ie*de.duration).toFixed(1)," / ",de.duration,a("s")]}),t.jsx("input",{"aria-label":a("Thời gian camera"),type:"range",min:0,max:1,step:1e-4,value:Ie,onChange:c=>{D(!1),ot(+c.target.value)}})]}),z.plate&&t.jsxs("div",{className:"shot-plate-row",title:a("Video quay thật phía sau camera: chỉ để canh hiệu ứng. Khi xuất VFX, hiệu ứng ra riêng trên nền đen."),children:[t.jsxs("span",{children:["🎬 ",z.plate.label]}),t.jsxs("label",{children:[t.jsx("input",{type:"checkbox","aria-label":a("Hiện video nền"),checked:!z.plate.hidden,onChange:c=>{const x=c.target.checked;Me(L=>L.plate?{...L,plate:{...L.plate,hidden:!x}}:L)}}),a("Hiện video nền")]})]}),z.plate&&t.jsxs("div",{className:"shot-plate-tools",children:[t.jsx("button",{type:"button",className:"pill-btn",disabled:!!De||ie,title:a("Người đứng thế đi theo người trong video (vị trí, khoảng cách, hướng, tay chân): hiệu ứng gắn vào nó sẽ bám theo người thật."),onClick:()=>void cl("follow"),children:De?.kind==="follow"?a("Đang đọc người… {0}%",[De.pct]):a("🧍 Bám theo người")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!De||ie,title:a("Camera của cảnh xoay / lia / zoom giống camera đã quay video."),onClick:()=>void cl("camera"),children:De?.kind==="camera"?a("Đang track camera… {0}%",[De.pct]):a("🎥 Lấy camera từ video")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!De,title:a("Tải camera của shot thành script Python cho Blender, để dựng hiệu ứng khớp với video."),onClick:()=>void Uu(),children:a("⬇ Camera cho Blender")})]}),te.length>0&&t.jsxs("div",{className:"shot-placement",role:"status","aria-label":a("Cảnh báo vị trí nhân vật"),children:[t.jsx("ul",{children:te.map(c=>t.jsxs("li",{children:[t.jsxs("span",{children:["⚠ ",c.type==="floating"?a("{0} lơ lửng {1} m so với mặt đỡ",[c.name,String(c.amount)]):c.type==="sinking"?a("{0} chìm {1} m dưới mặt đỡ",[c.name,String(c.amount)]):c.type==="no_seat"?c.seat?a("{0} ngồi lơ lửng — có thể ngồi lên “{1}”",[c.name,c.seat]):a("{0} ngồi mà không có chỗ ngồi gần",[c.name]):a("{0} đang xuyên vào {1}",[c.name,(c.with||[]).join(", ")])]}),c.fix&&!c.locked&&t.jsx("button",{onClick:()=>nl([c]),children:c.type==="intersect"?a("Đẩy ra chỗ trống"):c.type==="no_seat"?a("Ngồi lên ghế gần nhất"):a("Đặt xuống mặt đỡ")})]},c.itemId+c.type))}),te.filter(c=>c.fix&&!c.locked).length>1&&t.jsx("button",{className:"shot-placement-all",onClick:()=>nl(te),children:a("Sửa tất cả ({0})",[String(te.filter(c=>c.fix&&!c.locked).length)])})]}),Ml.length>0&&t.jsx("ul",{className:"shot-warnings",role:"status","aria-label":a("Cảnh báo liền mạch"),children:Ml.map(c=>t.jsxs("li",{children:["⚠ ",a(c)]},c))})]}),t.jsx("section",{className:"shot-agent-card",children:t.jsx(V1,{stage:z,disabled:ie||R||!!C,lock:{playhead:Math.round(Ie*de.duration*bn(de))/bn(de),onChange:c=>jt({lockUntil:r0(c,de.duration)||void 0})},agent:{selected:J,time:Ie,getBounds:()=>ge.current?.objectBounds()||{},getColliders:()=>ge.current?.placementColliders()||[],onPreview:(c,x)=>{D(!1);const L=Oi(Ne.current,c);O({stage:L,plan:c,time:Ie,done:x}),ot(Math.min(...c.tracks.map(F=>F.keys[0].seconds))/c.duration),D(!0)},onApply:c=>{D(!1),Me(x=>Oi(x,c)),ot(0),i(null),M(null)}}})})]})]})]})}export{qj as default};