# encoding: UTF-8
m = Sketchup.active_model
MM = 1.0/25.4
mL, xL0, zL0 = 0.1129672, 4423.8, 20.4
cL = 1.0/Math.sqrt(1+mL*mL)
uu = lambda{|x| (x-xL0)/cL}
X0, X1 = 3940.0, 4410.0
U0, U1 = uu.call(X0), uu.call(X1)
YMID = 8142.55
SPY = [8117.55, 8167.55]          # 중앙 척추 능선 50W
RIBX = [[3965.0,4005.0],[4020.0,4060.0],[4290.0,4330.0],[4350.0,4390.0]]
RIBY = [[7540.0, SPY[0]],[SPY[1], 8745.1]]   # 척추 좌우 늑골
LIPY = [[7496.2,7506.2],[8778.9,8788.9]]
ZB   = -12.0                      # 하판 하면
DR, DL = 25.0, 30.0               # 리브 깊이 / 가장자리 립 깊이

def rrect(x0,x1,y0,y1,r,seg=8)
  pts=[]
  [[x1-r,y0+r,-90.0,0.0],[x1-r,y1-r,0.0,90.0],[x0+r,y1-r,90.0,180.0],[x0+r,y0+r,180.0,270.0]].each do |cx,cy,a0,a1|
    (0..seg).each{|i| a=(a0+(a1-a0)*i/seg.to_f)*Math::PI/180.0; pts << [cx+r*Math.cos(a), cy+r*Math.sin(a)]}
  end
  pts
end
root = m.entities.grep(Sketchup::Group).find{|g| g.name=="하부마운트커버_v2_20260919"}
plan = []
plan << ["능선_척추", rrect(U0,U1,SPY[0],SPY[1],25.0), DR]
RIBX.each_with_index do |(xa,xb),i|
  RIBY.each_with_index do |(ya,yb),j|
    plan << ["능선_늑골_#{i+1}#{j==0 ? 'L' : 'R'}", rrect(uu.call(xa),uu.call(xb),ya,yb,20.0), DR]
  end
end
LIPY.each_with_index{|(ya,yb),i| plan << ["가장자리립_#{i==0 ? 'L' : 'R'}", rrect(U0,U1,ya,yb,5.0), DL]}
puts "plan=#{plan.length} groups"
begin
  m.start_operation("v2 등껍질 리브", true)
  plan.each do |nm, outer, d|
    g = root.entities.add_group; g.name = nm
    f = g.entities.add_face(outer.map{|x,y| Geom::Point3d.new(x*MM,y*MM,ZB*MM)})
    f.pushpull((f.normal.z > 0 ? -d : d)*MM)
    raise "#{nm} not solid" unless g.manifold?
  end
  m.commit_operation
  puts "  전부 solid=true"
rescue Exception => ex
  m.commit_operation rescue nil
  puts "ERR #{ex.class}: #{ex.message}"
end
b = root.bounds
puts "ROOT BBOX mm (#{(b.min.x*25.4).round(1)},#{(b.min.y*25.4).round(1)},#{(b.min.z*25.4).round(1)}) .. (#{(b.max.x*25.4).round(1)},#{(b.max.y*25.4).round(1)},#{(b.max.z*25.4).round(1)})"
puts "SUBGROUPS=#{root.entities.grep(Sketchup::Group).length} nonsolid=#{root.entities.grep(Sketchup::Group).reject{|g| g.manifold?}.map{|g| g.name}.inspect}"
# 대칭 검증
ys=[]
root.entities.grep(Sketchup::Group).each{|g| g.entities.grep(Sketchup::Face).each{|f| f.vertices.each{|v| ys << (v.position.transform(g.transformation).y*25.4).round(2)}}}
ys.uniq!
bad = ys.reject{|y| ys.any?{|o| ((2*YMID-y)-o).abs < 0.05}}
puts "SYMMETRY uniqueY=#{ys.length} mismatch=#{bad.length} #{bad[0,8].inspect}"
"V2C"
