import matplotlib.pyplot as plt

# 断面を取得し、重ね合わせた図を作成する関数
def process_sections(axis, levels, label1, label2, idx1, idx2, idx3):
    overlay_x = []
    overlay_y = []
    overlay_alpha = []

    # 各断面の点数をカウント
    section_counts = []
    for level in levels:
        section_points = points[(points[:, idx3] >= level - slice_thickness) & (points[:, idx3] <= level + slice_thickness)]
        section_counts.append(section_points.shape[0])
    # 最大・最小のデータ点数を取得（色の調整に使用）
    max_count = max(section_counts) if max(section_counts) > 0 else 1  # 0除算を防ぐ
    min_count = min(section_counts) if min(section_counts) > 0 else 1
    # 色の濃さを点数に応じて設定（点が多いほど薄く、少ないほど濃く）
    normalized_counts = [((max_count*1.1)-count) / (max_count-min_count + 1) for count in section_counts]

    for i, level in enumerate(levels):
        section_points = points[(points[:, idx3] >= level - slice_thickness) & (points[:, idx3] <= level + slice_thickness)]
        if section_points.shape[0] == 0:
            continue
        x, y = section_points[:, idx1], section_points[:, idx2]
        # 重ね合わせ用のデータを保存
        overlay_x.extend(x)
        overlay_y.extend(y)
        overlay_alpha.extend([normalized_counts[i]] * len(x))  # 各点に対応する透明度を設定

    # 重ね合わせた図を作成
    if len(overlay_x) > 0:
        fig, ax = plt.subplots(figsize=(8, 8))
        ax.scatter(overlay_x, overlay_y, s=0.5, c=overlay_alpha, cmap="gray", alpha=0.8)
        ax.set_aspect("equal")
        ax.set_xlabel(label1)
        ax.set_ylabel(label2)
        ax.set_title(f"Overlaid {axis} Sections")
        ax.grid(True)
        plt.savefig(f"output_2d_overlay_{axis}.png", dpi=300, bbox_inches="tight")
        plt.close(fig)  # 画面表示を抑制
