# encoding: UTF-8
MM = 25.4
m = Sketchup.active_model
def ents_of(e); e.is_a?(Sketchup::ComponentInstance) ? e.definition.entities : e.entities; end
def collect(ent, tr, faces)
  ents_of(ent).each do |e|
    case e
    when Sketchup::Face
      pts = e.vertices.map { |v| v.position.transform(tr) }
      n = e.normal.transform(tr); n.normalize!
      faces << [pts, n, e.area * 645.16]
    when Sketchup::Group, Sketchup::ComponentInstance
      collect(e, tr * e.transformation, faces)
    end
  end
end
def zs_at(faces, x, y)
  res = []
  faces.each do |pts, n, _|
    next if n.z.abs < 0.05
    inside = false
    j = pts.length - 1
    (0...pts.length).each do |i|
      xi = pts[i].x; yi = pts[i].y; xj = pts[j].x; yj = pts[j].y
      inside = !inside if ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
      j = i
    end
    next unless inside
    p0 = pts[0]
    d = n.x * (x - p0.x) + n.y * (y - p0.y)
    res << (p0.z - d / n.z)
  end
  res
end
out = []
g2 = m.entities.grep(Sketchup::Group).find { |g| g.definition.name == "그룹#2" }
s04 = g2.entities.grep(Sketchup::Group).find { |g| g.name == "SWD_04_t9_240x1046" }
won = m.entities.grep(Sketchup::Group).find { |g| g.name == "조립부원판_20260919" }
f4 = []; collect(s04, g2.transformation * s04.transformation, f4)
fw = []; collect(won, won.transformation, fw)
panels = m.entities.grep(Sketchup::Group).select { |g| g.name.to_s.end_with?("_6T_20260919") }
panels.each do |p|
  fp = []; collect(p, p.transformation, fp)
  tg = []; bg = []
  tops = fp.select { |_, n, _| n.z > 0.3 }
  bots = fp.select { |_, n, _| n.z < -0.3 }
  tops.each { |pts, _, _| pts.each { |q| z = zs_at(f4, q.x, q.y); tg << (z.min - q.z) * 25.4 unless z.empty? } }
  bots.each { |pts, _, _| pts.each { |q| z = zs_at(fw, q.x, q.y); bg << (q.z - z.max) * 25.4 unless z.empty? } }
  b = p.bounds
  out << "#{p.name}: solid=#{p.manifold?} bbox z #{(b.min.z*25.4).round(2)}..#{(b.max.z*25.4).round(2)} 높이 #{((b.max.z-b.min.z)*25.4).round(1)}mm"
  out << "   상틈 #{tg.empty? ? '-' : "최대 #{tg.map(&:abs).max.round(3)}mm (n=#{tg.length})"} / 하틈 #{bg.empty? ? '-' : "최대 #{bg.map(&:abs).max.round(3)}mm (n=#{bg.length})"}"
end
v = m.active_view
sel = m.selection
sel.clear
panels.each { |p| sel.add(p) }
sel.add(g2); sel.add(won)
v.camera = Sketchup::Camera.new(Geom::Point3d.new(8300/25.4, 9600/25.4, 900/25.4), Geom::Point3d.new(9020/25.4, 11400/25.4, 170/25.4), Geom::Vector3d.new(0,0,1))
v.zoom(sel.to_a)
sel.clear
path = 'E:/도진팩토리/3D스캔및티칭시스템/_자동화/inbox/_보류/_cap2.png'
out << "capture=#{v.write_image(path, 1400, 900, true)}"
puts out.join("\n")
"VFCAP"
