# encoding: UTF-8
# vf4 — 6TB 필러 검증: 상면 정점마다 SWD_04 하면과의 z차, 하면 정점의 z, 벽두께(단면 폭)
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
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" }
f4 = []; collect(s04, g2.transformation * s04.transformation, f4)
out = []
g2.entities.grep(Sketchup::Group).select { |g| g.name.to_s.include?("_6TB_") }.each do |g|
  fs = []
  collect(g, g2.transformation * g.transformation, fs)
  tops = fs.select { |_, n, _| n.z > 0.3 }
  bots = fs.select { |_, n, _| n.z < -0.3 }
  gaps = []
  tops.each do |pts, _, _|
    pts.each do |p|
      zz = zs_at(f4, p.x, p.y)
      next if zz.empty?
      cand = zz.select { |z| z >= p.z - 0.5 / MM }
      next if cand.empty?
      gaps << (cand.min - p.z) * 25.4
    end
  end
  botz = bots.flat_map { |pts, _, _| pts.map { |p| p.z * 25.4 } }
  # 벽두께: 상면 면적 / 상면 최장변 근사 -> 대신 각 상면의 짧은변
  tw = tops.map do |pts, _, a|
    per = 0.0
    pts.each_with_index { |p, k| per += p.distance(pts[(k + 1) % pts.length]) }
    (4.0 * a / (per * 25.4)).round(2)
  end
  zr = fs.flat_map { |pts, _, _| pts.map { |p| p.z * 25.4 } }
  out << "#{g.name}: 상틈 #{gaps.empty? ? '-' : "최대 #{gaps.max.round(3)} / 평균 #{(gaps.inject(:+) / gaps.length).round(3)}"}mm, 하면 z #{botz.min.round(2)}..#{botz.max.round(2)} (기준 106.5), 높이 #{(zr.max - zr.min).round(1)}mm, 벽두께추정 #{tw.inspect}, solid=#{g.manifold?}"
end
puts out.join("\n")
"VF4"
