# 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
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, s04.transformation, f4)
out = []
out << "g2.tr identity=#{g2.transformation.identity?} f4=#{f4.length}"
b = s04.bounds
out << "s04 world 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)})"
allz = f4.flat_map { |pts,_,_| pts.map { |p| p.z*25.4 } }
allx = f4.flat_map { |pts,_,_| pts.map { |p| p.x*25.4 } }
out << "collect 좌표범위 x #{allx.min.round(1)}..#{allx.max.round(1)} z #{allz.min.round(1)}..#{allz.max.round(1)}"
[9180.0, 9200.0, 9190.0, 8874.0].each do |xm|
  z = zs_at(f4, xm/MM, 11400.0/MM)
  out << "  zs_at x=#{xm} y=11400 -> #{z.map { |v| (v*25.4).round(1) }.inspect}"
end
puts out.join("\n")
"DBG1"
