import os

import json

import time

from pathlib import Path

from concurrent.futures import ProcessPoolExecutor, as_completed

import numpy as np

 

# ==========================================

# 設定パラメータ

# ==========================================

GRID_RES_DEG = 0.002  # 約200mメッシュ

OUTPUT_JSON_PATH = "chubu_hokuriku_hires_3d.json"

MAX_CPU_CORES = os.cpu_count() or 4

 

EROSION_ROUNDS = 4

DROPLETS_PER_ROUND = 350_000

 

LON_MIN, LON_MAX = 135.40, 139.20

LAT_MIN, LAT_MAX = 33.65, 37.60

 

# ==========================================

# 1. 対象10県輪郭

# ==========================================

N_ISH_TOY_COAST   = [137.042, 36.858]

N_ISH_TOY_GIF     = [136.835, 36.320]

N_ISH_FUK_GIF     = [136.771, 36.155]

N_ISH_FUK_COAST   = [136.245, 36.295]

N_TOY_NII_COAST   = [137.630, 36.982]

N_TOY_GIF_NAG     = [137.605, 36.385]

N_FUK_KYOTO_SHIGA = [135.840, 35.440]

N_FUK_GIF_SHIGA   = [136.320, 35.465]

N_GIF_SHIGA_MIE   = [136.410, 35.230]

N_SHIGA_KYOTO_MIE = [136.050, 34.770]

N_GIF_AIC_MIE     = [136.665, 35.140]

N_GIF_NAG_AIC     = [137.645, 35.235]

N_NAG_AIC_SHI     = [137.670, 35.195]

N_AIC_SHI_COAST   = [137.485, 34.685]

N_NAG_YAM_SHI     = [138.180, 35.425]

N_YAM_SHI_FUJI    = [138.727, 35.361]

N_YAM_SHI_KAN     = [139.020, 35.415]

N_NAG_YAM_N       = [138.730, 35.915]

 

B_ISH_TOY   = [N_ISH_TOY_COAST, [136.95, 36.76], [136.92, 36.63], [136.88, 36.50], N_ISH_TOY_GIF]

B_ISH_GIF   = [N_ISH_TOY_GIF, [136.80, 36.23], N_ISH_FUK_GIF]

B_ISH_FUK   = [N_ISH_FUK_GIF, [136.62, 36.13], [136.42, 36.20], N_ISH_FUK_COAST]

B_TOY_GIF   = [N_ISH_TOY_GIF, [136.95, 36.34], [137.18, 36.26], [137.38, 36.29], [137.50, 36.35], N_TOY_GIF_NAG]

B_TOY_NAG   = [N_TOY_GIF_NAG, [137.62, 36.57], [137.69, 36.74], [137.67, 36.88], N_TOY_NII_COAST]

B_FUK_GIF   = [N_ISH_FUK_GIF, [136.81, 36.02], [136.74, 35.84], [136.55, 35.73], [136.38, 35.62], N_FUK_GIF_SHIGA]

B_FUK_SHIGA = [N_FUK_KYOTO_SHIGA, [135.98, 35.53], [136.18, 35.63], N_FUK_GIF_SHIGA]

B_GIF_SHIGA = [N_FUK_GIF_SHIGA, [136.39, 35.38], [136.42, 35.33], [136.39, 35.27], N_GIF_SHIGA_MIE]

B_MIE_SHIGA = [N_SHIGA_KYOTO_MIE, [136.24, 34.86], [136.40, 35.02], N_GIF_SHIGA_MIE]

B_SHIGA_W   = [N_SHIGA_KYOTO_MIE, [135.92, 34.82], [135.84, 34.93], [135.84, 35.06], [135.81, 35.24], N_FUK_KYOTO_SHIGA]

B_GIF_NAG   = [N_TOY_GIF_NAG, [137.62, 36.22], [137.55, 36.10], [137.48, 35.89], [137.56, 35.62], [137.61, 35.42], N_GIF_NAG_AIC]

B_GIF_AIC   = [N_GIF_AIC_MIE, [136.74, 35.24], [136.94, 35.38], [137.16, 35.27], [137.38, 35.33], [137.52, 35.34], N_GIF_NAG_AIC]

B_GIF_MIE   = [N_GIF_SHIGA_MIE, [136.48, 35.20], N_GIF_AIC_MIE]

B_NAG_AIC   = [N_GIF_NAG_AIC, [137.66, 35.21], N_NAG_AIC_SHI]

B_AIC_SHI   = [N_NAG_AIC_SHI, [137.71, 35.04], [137.66, 34.89], [137.58, 34.81], [137.52, 34.74], N_AIC_SHI_COAST]

B_NAG_SHI   = [N_NAG_AIC_SHI, [137.82, 35.22], [138.02, 35.26], [138.14, 35.35], N_NAG_YAM_SHI]

B_NAG_YAM   = [N_NAG_YAM_SHI, [138.24, 35.67], [138.34, 35.84], [138.52, 35.89], N_NAG_YAM_N]

B_YAM_SHI   = [N_NAG_YAM_SHI, [138.32, 35.40], [138.52, 35.32], [138.65, 35.34], N_YAM_SHI_FUJI, [138.86, 35.39], N_YAM_SHI_KAN]

B_MIE_SW    = [[136.005, 33.725], [135.91, 33.85], [135.98, 34.05], [136.11, 34.22], [136.14, 34.45], [136.05, 34.60], N_SHIGA_KYOTO_MIE]

 

TARGET_POLYGONS = [

    [N_ISH_TOY_COAST, [137.00, 36.82], [137.05, 36.77], [137.14, 36.76], [137.23, 36.77], [137.35, 36.79],

     [137.43, 36.89], [137.45, 36.92], [137.53, 36.94], N_TOY_NII_COAST]

    + list(reversed(B_TOY_NAG))[1:] + list(reversed(B_TOY_GIF))[1:] + list(reversed(B_ISH_TOY))[1:],

    [N_ISH_FUK_COAST, [136.38, 36.41], [136.50, 36.52], [136.64, 36.66], [136.75, 36.86],

     [136.74, 37.00], [136.67, 37.14], [136.71, 37.27], [136.86, 37.39], [137.06, 37.51],

     [137.33, 37.53], [137.29, 37.40], [137.16, 37.28], [137.04, 37.21], [136.94, 37.15],

     [137.02, 37.11], [136.91, 37.05], [136.98, 37.01], [137.04, 36.96], N_ISH_TOY_COAST]

    + B_ISH_TOY[1:] + B_ISH_GIF[1:] + B_ISH_FUK[1:],

    [N_ISH_FUK_COAST, [136.14, 36.24], [136.11, 36.12], [136.02, 36.02], [135.96, 35.97],

     [136.03, 35.84], [136.06, 35.72], [136.02, 35.67], [135.96, 35.75], [135.94, 35.65],

     [135.87, 35.62], [135.84, 35.53], [135.74, 35.51], [135.68, 35.56], [135.58, 35.51],

     [135.46, 35.48], [135.68, 35.41]]

    + B_FUK_SHIGA + list(reversed(B_FUK_GIF))[1:] + B_ISH_FUK[1:],

    B_NAG_YAM + [[138.94, 35.88], [139.08, 35.76], [139.14, 35.62], [139.07, 35.48], N_YAM_SHI_KAN] + list(reversed(B_YAM_SHI))[1:],

    B_TOY_NAG + [[137.88, 36.92], [138.12, 36.96], [138.42, 37.02], [138.63, 36.92], [138.57, 36.70], [138.62, 36.44], [138.68, 36.22], [138.76, 36.04], N_NAG_YAM_N]

    + list(reversed(B_NAG_YAM))[1:] + list(reversed(B_NAG_SHI))[1:] + list(reversed(B_NAG_AIC))[1:] + list(reversed(B_GIF_NAG))[1:],

    B_GIF_SHIGA + B_GIF_MIE[1:] + B_GIF_AIC[1:] + list(reversed(B_GIF_NAG))[1:] + list(reversed(B_TOY_GIF))[1:] + B_ISH_GIF[1:] + B_FUK_GIF[1:],

    [N_AIC_SHI_COAST, [137.59, 34.68], [137.82, 34.66], [138.05, 34.63], [138.22, 34.59],

     [138.24, 34.68], [138.28, 34.77], [138.33, 34.86], [138.48, 34.96], [138.54, 35.02],

     [138.51, 35.04], [138.64, 35.12], [138.80, 35.10], [138.86, 35.06], [138.77, 35.02],

     [138.80, 34.93], [138.75, 34.78], [138.79, 34.66], [138.85, 34.60], [138.95, 34.66],

     [139.04, 34.78], [139.15, 34.96], [139.11, 35.07], [139.08, 35.14], [139.01, 35.22],

     [138.98, 35.33], N_YAM_SHI_KAN]

    + list(reversed(B_YAM_SHI))[1:] + list(reversed(B_NAG_SHI))[1:] + B_AIC_SHI[1:],

    [N_GIF_AIC_MIE, [136.75, 35.06], [136.85, 35.05], [136.82, 34.92], [136.86, 34.77],

     [136.93, 34.69], [136.98, 34.73], [136.95, 34.88], [136.99, 34.87], [137.03, 34.81],

     [137.16, 34.81], [137.27, 34.81], [137.32, 34.75], [137.20, 34.69], [137.07, 34.62],

     [137.01, 34.58], [137.14, 34.60], [137.35, 34.65], N_AIC_SHI_COAST]

    + list(reversed(B_AIC_SHI))[1:] + list(reversed(B_NAG_AIC))[1:] + list(reversed(B_GIF_AIC))[1:],

    [N_GIF_AIC_MIE, [136.71, 35.03], [136.65, 34.95], [136.62, 34.85], [136.54, 34.72],

     [136.56, 34.58], [136.78, 34.50], [136.85, 34.48], [136.92, 34.37], [136.80, 34.27],

     [136.62, 34.30], [136.45, 34.25], [136.34, 34.19], [136.22, 34.07], [136.26, 34.00],

     [136.11, 33.89]]

    + B_MIE_SW + B_MIE_SHIGA[1:] + B_GIF_MIE[1:],

    B_SHIGA_W + B_FUK_SHIGA[1:] + B_GIF_SHIGA[1:] + list(reversed(B_MIE_SHIGA))[1:],

]

 

OTHER_LAND_POLYGONS = [

    [[137.63, 36.98], [139.30, 37.65], [139.30, 35.10], [139.08, 35.14], [139.01, 35.22], [138.98, 35.33], N_YAM_SHI_KAN, [139.07, 35.48], [139.14, 35.62], [139.08, 35.76], [138.94, 35.88], N_NAG_YAM_N, [138.76, 36.04], [138.68, 36.22], [138.62, 36.44], [138.57, 36.70], [138.63, 36.92], [138.42, 37.02], [138.12, 36.96], [137.88, 36.92], N_TOY_NII_COAST],

    [[135.46, 35.48], [135.20, 35.45], [135.20, 33.55], [136.005, 33.725]]

    + B_MIE_SW[1:] + B_SHIGA_W[1:] + [[135.68, 35.41], [135.46, 35.48]],

]

 

POLY_BOUNDS = []

for p in TARGET_POLYGONS:

    arr = np.array(p)

    POLY_BOUNDS.append((arr[:, 0].min() - 0.02, arr[:, 1].min() - 0.02, arr[:, 0].max() + 0.02, arr[:, 1].max() + 0.02))

 

# ==========================================

# 2. 地形コンポーネント & 精密湖沼ポリゴン

# ==========================================

PEAKS = [

    (137.758, 36.758, 2932, 0.12, 1.70), (137.753, 36.662, 2814, 0.11, 1.75),

    (137.747, 36.624, 2889, 0.11, 1.75), (137.680, 36.824, 2418, 0.12, 1.80),

    (137.617, 36.623, 2999, 0.12, 1.75), (137.619, 36.576, 3015, 0.13, 1.65),

    (137.545, 36.469, 2926, 0.12, 1.75), (137.539, 36.392, 2840, 0.11, 1.80),

    (137.603, 36.422, 2986, 0.11, 1.75), (137.605, 36.402, 2924, 0.10, 1.75),

    (137.647, 36.342, 3180, 0.11, 1.70), (137.648, 36.289, 3190, 0.13, 1.65),

    (137.727, 36.394, 2857, 0.11, 1.75), (137.713, 36.407, 2763, 0.10, 1.80),

    (137.553, 36.106, 3026, 0.14, 1.65), (137.480, 35.893, 3067, 0.14, 1.55),

    (137.804, 35.789, 2956, 0.12, 1.75), (137.817, 35.719, 2864, 0.11, 1.75),

    (137.811, 35.689, 2841, 0.11, 1.80), (137.756, 35.568, 2363, 0.12, 1.80),

    (137.596, 35.443, 2191, 0.15, 1.75), (138.237, 35.758, 2967, 0.12, 1.70),

    (138.183, 35.720, 3033, 0.12, 1.75), (138.308, 35.702, 2841, 0.11, 1.75),

    (138.239, 35.674, 3193, 0.13, 1.65), (138.228, 35.646, 3190, 0.12, 1.70),

    (138.228, 35.622, 3026, 0.11, 1.75), (138.183, 35.573, 3047, 0.12, 1.75),

    (138.182, 35.500, 3141, 0.12, 1.75), (138.157, 35.461, 3121, 0.13, 1.75),

    (138.139, 35.423, 3013, 0.12, 1.75), (138.084, 35.338, 2592, 0.13, 1.80),

    (138.161, 35.255, 2330, 0.13, 1.80), (138.370, 35.971, 2899, 0.13, 1.55),

    (138.295, 36.103, 2531, 0.12, 1.65), (138.105, 36.226, 2034, 0.13, 1.80),

    (138.197, 36.102, 1925, 0.12, 1.80), (138.523, 36.406, 2568, 0.13, 1.50),

    (138.413, 36.549, 2354, 0.13, 1.70), (138.520, 36.665, 2307, 0.18, 1.75),

    (138.140, 36.742, 2053, 0.13, 1.75), (138.132, 36.697, 1917, 0.12, 1.80),

    (138.625, 35.871, 2599, 0.15, 1.75), (138.592, 35.893, 2230, 0.13, 1.80),

    (138.729, 35.909, 2475, 0.15, 1.75), (138.845, 35.749, 2057, 0.15, 1.75),

    (138.807, 35.545, 1785, 0.12, 1.80), (138.538, 35.412, 1964, 0.13, 1.75),

    (138.807, 35.233, 1504, 0.10, 1.60), (139.021, 35.232, 1438, 0.12, 1.70),

    (138.960, 34.863, 1406, 0.14, 1.65), (138.838, 34.955,  982, 0.10, 1.75),

    (136.771, 36.155, 2702, 0.15, 1.65), (136.765, 36.106, 2399, 0.13, 1.75),

    (136.835, 36.002, 1709, 0.13, 1.80), (136.601, 35.934, 1523, 0.14, 1.75),

    (136.515, 35.762, 1617, 0.14, 1.75), (137.167, 36.038, 1529, 0.15, 1.85),

    (137.655, 35.228, 1415, 0.17, 1.85), (137.542, 35.125, 1152, 0.15, 1.90),

    (136.406, 35.418, 1377, 0.12, 1.65), (136.440, 35.220,  908, 0.12, 1.85),

    (137.365, 34.910,  789, 0.12, 1.90), (137.168, 35.258,  629, 0.11, 1.90),

    (136.815, 36.782,  637, 0.15, 1.85), (136.980, 37.330,  460, 0.20, 1.95),

    (136.109, 34.186, 1695, 0.15, 1.65), (136.419, 35.019, 1212, 0.12, 1.75),

    (136.442, 35.174, 1144, 0.11, 1.80), (136.165, 34.515, 1037, 0.14, 1.80),

    (136.290, 34.725,  842, 0.14, 1.85), (136.775, 34.455,  555, 0.11, 1.85),

    (136.020, 33.960, 1100, 0.14, 1.75),

    (135.887, 35.253, 1214, 0.08, 1.80), (135.833, 35.066,  848, 0.07, 1.85),

    (136.332, 35.533, 1317, 0.10, 1.75), (136.377, 35.280, 1084, 0.09, 1.80),

    (136.010, 34.920,  600, 0.11, 1.85),

]

 

RIDGES = [

    (137.76, 36.76, 137.64, 36.30, 2150, 0.16), (137.64, 36.30, 137.48, 35.89, 1900, 0.17),

    (137.80, 35.82, 137.75, 35.50, 1800, 0.12), (138.24, 35.76, 138.12, 35.28, 2100, 0.15),

    (136.77, 36.15, 136.52, 35.74, 1150, 0.19), (138.37, 35.97, 138.85, 35.80, 1500, 0.19),

    (137.05, 36.22, 137.45, 36.02, 1000, 0.26), (138.95, 35.05, 138.92, 34.72,  820, 0.13),

    (136.41, 35.42, 136.48, 35.65,  850, 0.16), (136.42, 35.22, 136.36, 34.85,  850, 0.14),

    (136.22, 34.60, 136.02, 33.90, 1050, 0.19),

    (135.84, 35.05, 135.91, 35.43,  820, 0.085), (135.91, 35.43, 136.30, 35.58, 720, 0.11),

]

 

PASSES = [

    (136.465, 35.345,  180, 0.07, 0.85), (137.603, 36.195, 1650, 0.06, 0.65),

    (138.015, 36.095,  950, 0.06, 0.75), (136.155, 35.745,  550, 0.06, 0.75),

    (138.865, 35.405, 1080, 0.06, 0.70), (138.625, 36.335,  950, 0.07, 0.70),

    (136.330, 34.855,  360, 0.05, 0.75),

]

 

RIVERS = [

    (137.60, 36.42, 137.63, 36.60, 1400,  800, 0.035, 0.76), (137.63, 36.60, 137.55, 36.82,  800,  150, 0.042, 0.80),

    (137.55, 36.82, 137.43, 36.91,  150,    4, 0.055, 0.86), (137.53, 36.54, 137.24, 36.75,  950,    4, 0.040, 0.78),

    (137.25, 36.14, 137.23, 36.48,  560,  220, 0.042, 0.78), (137.48, 36.28, 137.23, 36.48,  900,  220, 0.035, 0.75),

    (137.23, 36.48, 137.22, 36.76,  220,    4, 0.050, 0.84), (136.92, 36.02, 136.97, 36.45,  650,  150, 0.042, 0.78),

    (136.97, 36.45, 137.08, 36.77,  150,    4, 0.050, 0.84), (136.70, 36.22, 136.48, 36.50,  500,    4, 0.042, 0.78),

    (136.65, 35.87, 136.48, 35.98,  480,  180, 0.038, 0.76), (136.48, 35.98, 136.14, 36.22,  180,    4, 0.050, 0.84),

    (137.97, 36.24, 137.86, 36.85,  590,  340, 0.060, 0.84), (137.65, 36.25, 137.92, 36.22, 1480,  600, 0.035, 0.78),

    (138.62, 35.95, 138.48, 36.22, 1100,  680, 0.045, 0.78), (138.48, 36.22, 138.18, 36.65,  680,  340, 0.065, 0.82),

    (138.18, 36.65, 138.45, 36.96,  340,  260, 0.060, 0.82), (137.75, 35.92, 137.50, 35.49,  850,  280, 0.052, 0.82),

    (137.50, 35.49, 136.75, 35.06,  280,    3, 0.068, 0.88), (137.24, 35.81, 137.02, 35.44,  380,   60, 0.042, 0.80),

    (136.90, 35.85, 136.72, 35.15,  450,    4, 0.048, 0.82), (136.52, 35.62, 136.64, 35.22,  320,    8, 0.045, 0.80),

    (137.45, 35.22, 137.02, 34.86,  350,    4, 0.042, 0.78), (138.08, 36.04, 137.83, 35.48,  750,  400, 0.062, 0.84),

    (137.83, 35.48, 137.82, 34.67,  400,    3, 0.048, 0.86), (138.22, 35.45, 138.18, 35.15, 1100,  380, 0.038, 0.78),

    (138.18, 35.15, 138.28, 34.77,  380,    4, 0.045, 0.84), (138.34, 35.78, 138.54, 35.58,  700,  240, 0.045, 0.80),

    (138.54, 35.58, 138.64, 35.13,  240,    3, 0.052, 0.85), (138.34, 35.24, 138.40, 34.94,  400,    4, 0.038, 0.78),

    (138.92, 34.89, 138.86, 35.09,  220,    4, 0.038, 0.78), (136.22, 34.56, 136.54, 34.65,  320,    4, 0.042, 0.78),

    (136.18, 34.43, 136.56, 34.61,  450,    4, 0.042, 0.80), (136.14, 34.23, 136.72, 34.52,  600,    4, 0.045, 0.82),

    (135.90, 33.84, 136.01, 33.72,  180,    3, 0.045, 0.82),

    (136.38, 35.47, 136.22, 35.40,  350,   95, 0.035, 0.78), (136.40, 35.09, 136.13, 35.19,  450,   95, 0.038, 0.78),

    (136.28, 34.92, 135.94, 35.12,  260,   90, 0.042, 0.80), (135.91, 34.98, 135.87, 34.86,   85,   50, 0.030, 0.78),

]

 

# 各湖沼の周囲が水面と綺麗に噛み合うよう、湖岸周辺の平坦高さを調整

BASINS_PLAINS = [

    (136.85, 35.14, 0.32,  10, 0.96), (137.22, 34.93, 0.20,  28, 0.90),

    (137.38, 34.76, 0.16,  16, 0.92), (137.76, 34.74, 0.20,  10, 0.95),

    (138.34, 34.92, 0.18,  16, 0.90), (138.75, 35.14, 0.14,  12, 0.90),

    (137.20, 36.69, 0.19,  12, 0.95), (136.62, 36.54, 0.17,  12, 0.95),

    (136.22, 36.07, 0.15,  15, 0.93), (138.57, 35.63, 0.13, 260, 0.92),

    (137.97, 36.24, 0.14, 590, 0.90), (138.19, 36.65, 0.14, 355, 0.90),

    (137.25, 36.14, 0.08, 565, 0.86),

    (136.60, 34.82, 0.18,  12, 0.93), (136.72, 34.50, 0.11,  10, 0.92),

    (136.13, 34.74, 0.11, 160, 0.88),

    # 湖周囲の盆地高さ

    (136.13, 35.34, 0.18, 102, 0.95), (136.09, 35.18, 0.16, 102, 0.95), (135.94, 35.06, 0.12, 102, 0.94),  # 琵琶湖周辺

    (138.084, 36.049, 0.075, 772, 0.94),  # 諏訪湖周辺

    (137.590, 34.745, 0.095,  14, 0.95),  # 浜名湖周辺

    (138.875, 35.415, 0.055, 995, 0.92),  # 山中湖周辺

    (138.755, 35.512, 0.055, 845, 0.92),  # 河口湖周辺

    (138.610, 35.465, 0.045, 915, 0.92),  # 本栖湖周辺

    (138.220, 36.826, 0.040, 670, 0.90),  # 野尻湖周辺

]

 

def ellipse_poly(lon, lat, rx, ry, n=20):

    ang = np.linspace(0, 2 * np.pi, n, endpoint=False)

    pts = [[round(float(lon + rx * np.cos(a)), 4), round(float(lat + ry * np.sin(a)), 4)] for a in ang]

    pts.append(pts[0])

    return pts

 

# 精密な湖沼ポリゴン(琵琶湖・浜名湖・山中湖・河口湖など)

BIWAKO_POLYGON = [

    [136.17, 35.51], [136.20, 35.44], [136.26, 35.38], [136.28, 35.32],

    [136.24, 35.27], [136.17, 35.23], [136.09, 35.21], [136.11, 35.17],

    [136.04, 35.14], [135.98, 35.13], [135.95, 35.12], [135.94, 35.08],

    [135.94, 35.03], [135.91, 34.97], [135.87, 35.01], [135.88, 35.07],

    [135.93, 35.12], [135.94, 35.17], [135.98, 35.23], [136.02, 35.28],

    [136.07, 35.32], [136.04, 35.39], [136.07, 35.46], [136.13, 35.49],

    [136.17, 35.51]

]

 

HAMANAKO_POLYGON = [

    [137.60, 34.68], [137.62, 34.71], [137.64, 34.76], [137.62, 34.75],

    [137.61, 34.73], [137.59, 34.76], [137.65, 34.80], [137.63, 34.81],

    [137.58, 34.79], [137.54, 34.80], [137.56, 34.77], [137.55, 34.71],

    [137.58, 34.69], [137.60, 34.68]

]

 

YAMANAKAKO_POLYGON = [

    [138.85, 35.42], [138.87, 35.43], [138.90, 35.42], [138.91, 35.41],

    [138.89, 35.40], [138.87, 35.41], [138.85, 35.41], [138.85, 35.42]

]

 

KAWAGUCHIKO_POLYGON = [

    [138.72, 35.51], [138.74, 35.52], [138.76, 35.515], [138.78, 35.52],

    [138.79, 35.51], [138.77, 35.50], [138.74, 35.505], [138.72, 35.51]

]

 

LAKE_POLYGONS = [

    {"name": "琵琶湖", "elevation_m": 85.0,  "bed_m": 35.0,  "polygon": BIWAKO_POLYGON},

    {"name": "浜名湖", "elevation_m": 2.0,   "bed_m": -35.0, "polygon": HAMANAKO_POLYGON},

    {"name": "諏訪湖", "elevation_m": 759.0, "bed_m": 710.0, "polygon": ellipse_poly(138.084, 36.049, 0.030, 0.020)},

    {"name": "山中湖", "elevation_m": 980.0, "bed_m": 930.0, "polygon": YAMANAKAKO_POLYGON},

    {"name": "河口湖", "elevation_m": 830.0, "bed_m": 780.0, "polygon": KAWAGUCHIKO_POLYGON},

    {"name": "本栖湖", "elevation_m": 900.0, "bed_m": 850.0, "polygon": ellipse_poly(138.610, 35.465, 0.018, 0.014)},

    {"name": "野尻湖", "elevation_m": 654.0, "bed_m": 605.0, "polygon": ellipse_poly(138.220, 36.826, 0.018, 0.015)},

]


 

# ==========================================

# 3. 幾何・ノイズ関数

# ==========================================

def points_in_polygon(X, Y, poly_coords):

    inside = np.zeros(X.shape, dtype=bool)

    n = len(poly_coords)

    for i in range(n):

        j = (i - 1) % n

        xi, yi = poly_coords[i]

        xj, yj = poly_coords[j]

        cond1 = (yi > Y) != (yj > Y)

        denom = (yj - yi) if (yj != yi) else 1e-12

        x_intersect = (xj - xi) * (Y - yi) / denom + xi

        inside ^= (cond1 & (X < x_intersect))

    return inside


 

def dist_and_t_to_segment(X, Y, x1, y1, x2, y2):

    dx, dy = x2 - x1, y2 - y1

    len_sq = dx * dx + dy * dy

    t = ((X - x1) * dx + (Y - y1) * dy) / (len_sq if len_sq > 0 else 1e-12)

    t = np.clip(t, 0.0, 1.0)

    return np.hypot(X - (x1 + t * dx), Y - (y1 + t * dy)), t


 

def value_noise_deriv(X, Y, seed=0.0):

    ix, iy = np.floor(X), np.floor(Y)

    fx, fy = X - ix, Y - iy

    ux = fx * fx * fx * (fx * (fx * 6.0 - 15.0) + 10.0)

    uy = fy * fy * fy * (fy * (fy * 6.0 - 15.0) + 10.0)

    dux = 30.0 * fx * fx * (fx - 1.0) ** 2

    duy = 30.0 * fy * fy * (fy - 1.0) ** 2

 

    def rnd(gx, gy):

        v = np.sin(gx * 127.1 + gy * 311.7 + seed * 74.7) * 43758.5453123

        return v - np.floor(v)

 

    a, b, c, d = rnd(ix, iy), rnd(ix + 1.0, iy), rnd(ix, iy + 1.0), rnd(ix + 1.0, iy + 1.0)

    k0, k1, k2, k3 = a, b - a, c - a, a - b - c + d

    return k0 + k1 * ux + k2 * uy + k3 * ux * uy, (k1 + k3 * uy) * dux, (k2 + k3 * ux) * duy


 

def erosion_fbm(X, Y):

    wx = X + 0.025 * np.sin(Y * 21.0 + 0.4) * np.cos(X * 19.0)

    wy = Y + 0.025 * np.cos(X * 23.0 - 0.2) * np.sin(Y * 20.0)

    px, py = wx * 12.0, wy * 12.0

    total = np.zeros_like(X, dtype=np.float64)

    gx_acc = np.zeros_like(X, dtype=np.float64)

    gy_acc = np.zeros_like(X, dtype=np.float64)

    amp = 0.49

 

    for oct_i, ang in enumerate([0.42, 1.15, 2.08, 0.77, 2.58, 1.49, 0.23]):

        ca, sa = np.cos(ang), np.sin(ang)

        rx, ry = px * ca - py * sa, px * sa + py * ca

        n, dx, dy = value_noise_deriv(rx, ry, seed=oct_i * 13.7)

        ridge = 1.0 - np.abs(n * 2.0 - 1.0)

        sign = np.where(n * 2.0 - 1.0 >= 0.0, -2.0, 2.0)

        gx_acc += (ca * dx + sa * dy) * sign

        gy_acc += (-sa * dx + ca * dy) * sign

        total += amp * (ridge ** 1.45) / (1.0 + 0.14 * (gx_acc ** 2 + gy_acc ** 2))

        px *= 2.04

        py *= 2.04

        amp *= 0.51

    return total


 

# ==========================================

# 4. 並列ワーカー

# ==========================================

def worker_mask_chunk(task):

    r_start, r_end, lons, chunk_lats = task

    X, Y = np.meshgrid(lons, chunk_lats)

    c_minx, c_maxx = float(lons[0]), float(lons[-1])

    c_miny, c_maxy = float(chunk_lats[-1]), float(chunk_lats[0])

 

    n1, _, _ = value_noise_deriv(X * 40.0, Y * 40.0, seed=5.1)

    n2, _, _ = value_noise_deriv(X * 110.0, Y * 110.0, seed=19.3)

    Xw = X + (n1 - 0.5) * 0.013 + (n2 - 0.5) * 0.004

    Yw = Y + (n2 - 0.5) * 0.013 + (n1 - 0.5) * 0.004

 

    in_region = np.zeros(X.shape, dtype=bool)

    for poly, (bx0, by0, bx1, by1) in zip(TARGET_POLYGONS, POLY_BOUNDS):

        if c_maxx < bx0 or c_minx > bx1 or c_maxy < by0 or c_miny > by1:

            continue

        in_region |= points_in_polygon(Xw, Yw, poly)

 

    other_land = np.zeros(X.shape, dtype=bool)

    for poly in OTHER_LAND_POLYGONS:

        other_land |= points_in_polygon(Xw, Yw, poly)

 

    sea_mask = (~in_region) & (~other_land)

    return r_start, r_end, in_region, sea_mask


 

def worker_base_terrain(task):

    r_start, r_end, lons, chunk_lats, mask_chunk, coast_dist_chunk, coast_scale = task

    X, Y = np.meshgrid(lons, chunk_lats)

 

    elev = np.full(X.shape, 90.0, dtype=np.float64)

    for x1, y1, x2, y2, h, w in RIDGES:

        d, _ = dist_and_t_to_segment(X, Y, x1, y1, x2, y2)

        elev = np.maximum(elev, h * np.exp(- (d / w) ** 1.75))

 

    for px, py, h, sig, pwr in PEAKS:

        d = np.hypot(X - px, Y - py)

        elev = np.maximum(elev, h * np.exp(- (d / sig) ** pwr))

 

    d_fuji = np.hypot(X - 138.727, Y - 35.361)

    fuji_h = 3820.0 * np.exp(- (d_fuji / 0.145) ** 1.25) - 230.0 * np.exp(- (d_fuji / 0.0065) ** 2.0)

    elev = np.maximum(elev, fuji_h)

 

    for px, py, th, rad, strength in PASSES:

        d = np.hypot(X - px, Y - py)

        w = strength * np.exp(- (d / rad) ** 2.0)

        elev = np.where(elev > th, elev * (1.0 - w) + th * w, elev)

 

    for bx, by, rad, target_h, strength in BASINS_PLAINS:

        d = np.hypot(X - bx, Y - by)

        w = strength * np.exp(- (d / rad) ** 2.3)

        elev = elev * (1.0 - w) + target_h * w

 

    for x1, y1, x2, y2, bh1, bh2, r_width, strength in RIVERS:

        d, t = dist_and_t_to_segment(X, Y, x1, y1, x2, y2)

        bed_h = bh1 * (1.0 - t) + bh2 * t

        cw = strength * np.exp(- (d / r_width) ** 1.50)

        elev = np.where(elev > bed_h, elev * (1.0 - cw) + bed_h * cw, elev)

 

    erode = erosion_fbm(X, Y)

    detail_amp = np.clip(elev * 0.30, 4.0, 480.0)

    fuji_smooth = 1.0 - 0.70 * np.exp(- (d_fuji / 0.08) ** 2.0)

    elev = elev + (erode - 0.36) * detail_amp * fuji_smooth

 

    taper = np.clip(coast_dist_chunk / coast_scale, 0.05, 1.0) ** 0.72

    elev = elev * taper

    elev = np.where(mask_chunk, np.clip(elev, 1.0, 3776.0), 0.0).astype(np.float32)

    return r_start, r_end, elev


 

def worker_hydraulic_erosion(task):

    elev_norm, valid_coords, num_droplets, seed = task

    H, W = elev_norm.shape

    rng = np.random.default_rng(seed)

 

    delta = np.zeros_like(elev_norm, dtype=np.float32)

    batch_size = 8_000

    num_batches = max(1, (num_droplets + batch_size - 1) // batch_size)

    n_valid = len(valid_coords[0])

 

    inertia, min_slope, capacity_factor = 0.20, 0.002, 3.2

    erode_speed, deposit_speed, gravity, evaporate, max_steps = 0.18, 0.14, 4.0, 0.035, 55

 

    for _ in range(num_batches):

        picks = rng.integers(0, n_valid, size=batch_size)

        py = valid_coords[0][picks].astype(np.float32) + rng.uniform(0.0, 1.0, batch_size).astype(np.float32)

        px = valid_coords[1][picks].astype(np.float32) + rng.uniform(0.0, 1.0, batch_size).astype(np.float32)

 

        dir_x = np.zeros(batch_size, dtype=np.float32)

        dir_y = np.zeros(batch_size, dtype=np.float32)

        speed = np.ones(batch_size, dtype=np.float32)

        water = np.ones(batch_size, dtype=np.float32)

        sediment = np.zeros(batch_size, dtype=np.float32)

        active = (px >= 1.0) & (px < W - 2.0) & (py >= 1.0) & (py < H - 2.0)

 

        for _ in range(max_steps):

            if not np.any(active):

                break

            idx = np.where(active)[0]

            cx, cy = px[idx], py[idx]

            ix, iy = cx.astype(np.int32), cy.astype(np.int32)

            fx, fy = cx - ix, cy - iy

 

            h00, h10 = elev_norm[iy, ix], elev_norm[iy, ix + 1]

            h01, h11 = elev_norm[iy + 1, ix], elev_norm[iy + 1, ix + 1]

            h_old = (h00 * (1 - fx) + h10 * fx) * (1 - fy) + (h01 * (1 - fx) + h11 * fx) * fy

            gx = (h10 - h00) * (1 - fy) + (h11 - h01) * fy

            gy = (h01 - h00) * (1 - fx) + (h11 - h10) * fx

 

            dx_new = dir_x[idx] * inertia - gx * (1.0 - inertia)

            dy_new = dir_y[idx] * inertia - gy * (1.0 - inertia)

            norm = np.hypot(dx_new, dy_new)

            zero_mask = norm < 1e-6

            if np.any(zero_mask):

                ang = rng.uniform(0.0, 2.0 * np.pi, size=int(np.sum(zero_mask))).astype(np.float32)

                dx_new[zero_mask], dy_new[zero_mask], norm[zero_mask] = np.cos(ang), np.sin(ang), 1.0

            dx_new /= norm

            dy_new /= norm

 

            nx, ny = cx + dx_new, cy + dy_new

            in_bounds = (nx >= 1.0) & (nx < W - 2.0) & (ny >= 1.0) & (ny < H - 2.0)

            active[idx[~in_bounds]] = False

            if not np.any(in_bounds):

                break

 

            sub = idx[in_bounds]

            nx_b, ny_b = nx[in_bounds], ny[in_bounds]

            nix, niy = nx_b.astype(np.int32), ny_b.astype(np.int32)

            nfx, nfy = nx_b - nix, ny_b - niy

 

            h_new = (

                (elev_norm[niy, nix] * (1 - nfx) + elev_norm[niy, nix + 1] * nfx) * (1 - nfy) +

                (elev_norm[niy + 1, nix] * (1 - nfx) + elev_norm[niy + 1, nix + 1] * nfx) * nfy

            )

            dh = h_new - h_old[in_bounds]

            capacity = np.maximum(-dh, min_slope) * speed[sub] * water[sub] * capacity_factor

            is_deposit = (sediment[sub] > capacity) | (dh > 0.0)

 

            amount_dep = np.where(dh > 0.0, np.minimum(dh * 0.25, sediment[sub] * 0.25), (sediment[sub] - capacity) * deposit_speed)

            amount_ero = np.minimum((capacity - sediment[sub]) * erode_speed, np.maximum(-dh, 0.0))

 

            ox, oy = ix[in_bounds], iy[in_bounds]

            ofx, ofy = fx[in_bounds], fy[in_bounds]

            change = np.where(is_deposit, amount_dep, -amount_ero)

            sediment[sub] = np.where(is_deposit, sediment[sub] - amount_dep, sediment[sub] + amount_ero)

 

            np.add.at(delta, (oy, ox), change * (1 - ofx) * (1 - ofy))

            np.add.at(delta, (oy, ox + 1), change * ofx * (1 - ofy))

            np.add.at(delta, (oy + 1, ox), change * (1 - ofx) * ofy)

            np.add.at(delta, (oy + 1, ox + 1), change * ofx * ofy)

 

            px[sub], py[sub] = nx_b, ny_b

            dir_x[sub], dir_y[sub] = dx_new[in_bounds], dy_new[in_bounds]

            speed[sub] = np.sqrt(np.maximum(speed[sub] ** 2 + (-dh) * gravity, 0.05))

            water[sub] *= (1.0 - evaporate)

 

    return delta


 

# ==========================================

# 5. メイン処理

# ==========================================

def main():

    t0 = time.perf_counter()

    lons = np.arange(LON_MIN, LON_MAX + GRID_RES_DEG * 0.5, GRID_RES_DEG, dtype=np.float64)

    lats = np.arange(LAT_MAX, LAT_MIN - GRID_RES_DEG * 0.5, -GRID_RES_DEG, dtype=np.float64)

    H, W = len(lats), len(lons)

 

    print(f"使用CPUコア数: {MAX_CPU_CORES} / メッシュ: {H} x {W} = {H * W:,} 点")

    num_chunks = MAX_CPU_CORES * 4

    row_indices = np.array_split(np.arange(H), num_chunks)

 

    full_mask = np.zeros((H, W), dtype=bool)

    sea_mask = np.zeros((H, W), dtype=bool)

 

    print("Pass 1/4: 領域&詳細海岸線(10県)を全コア並列計算中...")

    tasks_p1 = [(int(idx[0]), int(idx[-1]) + 1, lons, lats[idx]) for idx in row_indices if len(idx) > 0]

    with ProcessPoolExecutor(max_workers=MAX_CPU_CORES) as pool:

        for r_s, r_e, m_c, s_c in pool.map(worker_mask_chunk, tasks_p1):

            full_mask[r_s:r_e, :] = m_c

            sea_mask[r_s:r_e, :] = s_c

 

    print("Pass 2/4: 海岸線距離マップを計算中...")

    coast_steps = max(15, int(round(0.045 / GRID_RES_DEG)))

    coast_scale = coast_steps * 0.5

    coast_dist = np.where(sea_mask, 0.0, coast_steps * 2.0).astype(np.float32)

    for _ in range(coast_steps):

        nbr = np.minimum(

            np.minimum(coast_dist[:-2, 1:-1], coast_dist[2:, 1:-1]),

            np.minimum(coast_dist[1:-1, :-2], coast_dist[1:-1, 2:])

        ) + 1.0

        coast_dist[1:-1, 1:-1] = np.minimum(coast_dist[1:-1, 1:-1], nbr)

 

    print("Pass 3/4: ベース山脈・峠・河川を全コア並列計算中...")

    elev_work = np.zeros((H, W), dtype=np.float32)

    tasks_p3 = [

        (int(idx[0]), int(idx[-1]) + 1, lons, lats[idx],

         full_mask[int(idx[0]):int(idx[-1]) + 1, :],

         coast_dist[int(idx[0]):int(idx[-1]) + 1, :], coast_scale)

        for idx in row_indices if len(idx) > 0

    ]

    with ProcessPoolExecutor(max_workers=MAX_CPU_CORES) as pool:

        for r_s, r_e, e_c in pool.map(worker_base_terrain, tasks_p3):

            elev_work[r_s:r_e, :] = e_c

 

    print(f"Pass 4/4: 水理侵食(全{EROSION_ROUNDS * DROPLETS_PER_ROUND:,}滴)を全コア並列計算中...")

    elev_norm = (elev_work / 3776.0).astype(np.float32)

    valid_coords = np.where(full_mask)

    droplets_per_core = max(12_000, DROPLETS_PER_ROUND // MAX_CPU_CORES)

 

    for rnd_i in range(EROSION_ROUNDS):

        tasks_p4 = [

            (elev_norm, valid_coords, droplets_per_core, 2000 + rnd_i * 100 + c_i)

            for c_i in range(MAX_CPU_CORES)

        ]

        total_delta = np.zeros_like(elev_norm, dtype=np.float32)

        with ProcessPoolExecutor(max_workers=MAX_CPU_CORES) as pool:

            futures = [pool.submit(worker_hydraulic_erosion, t) for t in tasks_p4]

            for fut in as_completed(futures):

                total_delta += fut.result()

 

        d = np.clip(total_delta, -0.015, 0.008)

        d_smooth = d.copy()

        d_smooth[1:-1, 1:-1] = (

            0.40 * d[1:-1, 1:-1]

            + 0.10 * (d[:-2, 1:-1] + d[2:, 1:-1] + d[1:-1, :-2] + d[1:-1, 2:])

            + 0.05 * (d[:-2, :-2] + d[:-2, 2:] + d[2:, :-2] + d[2:, 2:])

        )

        elev_norm = np.where(full_mask, np.clip(elev_norm + d_smooth, 0.0, 1.0), 0.0)

        print(f"  -> ラウンド {rnd_i + 1}/{EROSION_ROUNDS} 完了")

 

    elev_final = (elev_norm * 3776.0).astype(np.float32)

    nbr_max = np.maximum.reduce([

        elev_final[:-2, :-2], elev_final[:-2, 1:-1], elev_final[:-2, 2:],

        elev_final[1:-1, :-2],                       elev_final[1:-1, 2:],

        elev_final[2:, :-2],  elev_final[2:, 1:-1],  elev_final[2:, 2:]

    ])

    spike_mask = elev_final[1:-1, 1:-1] > (nbr_max + 110.0)

    elev_final[1:-1, 1:-1] = np.where(spike_mask, nbr_max + 25.0, elev_final[1:-1, 1:-1])

 

    # 湖底を水面より45〜50m深く設定して、斜め補間で湖面が隠れないようにする

    X_all, Y_all = np.meshgrid(lons, lats)

    for lk in LAKE_POLYGONS:

        arr = np.array(lk["polygon"])

        bx0, by0, bx1, by1 = arr[:, 0].min(), arr[:, 1].min(), arr[:, 0].max(), arr[:, 1].max()

        ix = np.where((lons >= bx0) & (lons <= bx1))[0]

        iy = np.where((lats >= by0) & (lats <= by1))[0]

        if len(ix) > 0 and len(iy) > 0:

            sub_X = X_all[iy[0]:iy[-1]+1, ix[0]:ix[-1]+1]

            sub_Y = Y_all[iy[0]:iy[-1]+1, ix[0]:ix[-1]+1]

            l_mask = points_in_polygon(sub_X, sub_Y, lk["polygon"])

            sub_m = full_mask[iy[0]:iy[-1]+1, ix[0]:ix[-1]+1]

            elev_final[iy[0]:iy[-1]+1, ix[0]:ix[-1]+1] = np.where(

                l_mask & sub_m, lk["bed_m"], elev_final[iy[0]:iy[-1]+1, ix[0]:ix[-1]+1]

            )

 

    elev_final = np.where(full_mask, np.clip(elev_final, -40.0, 3776.0), np.nan)

 

    print("JSONファイルへ書き出し中...")

    elev_list = [

        [None if np.isnan(v) else round(float(v), 1) for v in row]

        for row in elev_final

    ]

 

    output_data = {

        "metadata": {

            "description": "Hi-Res Offline 3D Terrain (10 Prefectures + Accurate Lakes)",

            "grid_res_deg": GRID_RES_DEG,

            "shape": [H, W]

        },

        "lons": [round(float(x), 5) for x in lons],

        "lats": [round(float(y), 5) for y in lats],

        "elevations_m": elev_list,

        "lake_polygons": LAKE_POLYGONS

    }

 

    with open(OUTPUT_JSON_PATH, "w", encoding="utf-8") as f:

        json.dump(output_data, f, ensure_ascii=False)

 

    elapsed = time.perf_counter() - t0

    size_mb = Path(OUTPUT_JSON_PATH).stat().st_size / (1024 * 1024)

    print(f"完了! -> {OUTPUT_JSON_PATH} ({size_mb:.2f} MB, 処理時間: {elapsed:.2f} 秒)")


 

if __name__ == "__main__":

    main()