summaryrefslogtreecommitdiffstats
path: root/Third_Party/gen_atlas
blob: dfb0e6105057ad4d108b29e9be27f0eaf43bbea5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python3

import argparse
import subprocess
import os
import json
from PIL import Image

# Define the character ranges we want to include
CHAR_RANGES = [
    (32, 126),  # Printable ASCII
    # Add more ranges here as needed, e.g.:
    # (160, 255),  # Extended Latin
]

def calculate_grid_size(char_ranges):
    """Calculate the smallest square grid that fits the highest character code"""
    max_char = max(end for _, end in char_ranges)
    grid_size = 1
    while grid_size * grid_size < max_char:
        grid_size += 1
    return grid_size

def generate_atlas(font_path, resolution, draw_grid=False):
    # Calculate grid size based on character ranges
    grid_size = calculate_grid_size(CHAR_RANGES)
    cell_size = resolution // grid_size
    
    # Convert character ranges to command-line format
    chars_str = ", ".join(f"[{start}, {end}]" for start, end in CHAR_RANGES)
    
    cmd = [
        "msdf-atlas-gen/build/bin/Debug/msdf-atlas-gen.exe",
        "-font", font_path,
        "-type", "mtsdf",
        "-format", "png",
        "-imageout", "atlas.png",
        "-json", "atlas.json",
        "-size", "32",
        "-pxrange", "2",
        "-dimensions", str(resolution), str(resolution),
        "-chars", chars_str,
        "-uniformgrid",
        "-uniformcols", str(grid_size),
        "-uniformcell", str(cell_size), str(cell_size),
        "-uniformorigin", "on",
        "-coloringstrategy", "inktrap",
        "-errorcorrection", "auto",
        "-miterlimit", "1.0",
        "-scanline"
    ]

    try:
        print("Running msdf-atlas-gen...")
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        
        # Print the output
        if result.stdout:
            print("msdf-atlas-gen output:")
            print(result.stdout)
        
        # Rearrange the atlas to include gaps for non-printable characters
        rearrange_atlas(resolution, cell_size, cell_size, draw_grid)
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error generating atlas: {e}")
        print(f"Error output: {e.stderr}")
        return False

def draw_grid_lines(image, resolution):
    """Draw red grid lines on the image"""
    draw = ImageDraw.Draw(image)
    grid_size = calculate_grid_size(CHAR_RANGES)
    
    # Draw vertical lines
    for x in range(grid_size):
        line_x = x * resolution // grid_size
        draw.line([(line_x, 0), (line_x, resolution-1)], fill=(255, 0, 0), width=1)
    
    # Draw horizontal lines
    for y in range(grid_size):
        line_y = y * resolution // grid_size
        draw.line([(0, line_y), (resolution-1, line_y)], fill=(255, 0, 0), width=1)
    
    # Draw the final borders
    draw.line([(resolution-1, 0), (resolution-1, resolution-1)], fill=(255, 0, 0), width=1)
    draw.line([(0, resolution-1), (resolution-1, resolution-1)], fill=(255, 0, 0), width=1)

def rearrange_atlas(resolution, cell_width, cell_height, draw_grid=False):
    """Rearrange the atlas to include gaps for non-printable characters"""
    original = Image.open("atlas.png")
    new_atlas = Image.new('RGBA', (resolution, resolution), (0, 0, 0, 255))
    
    grid_size = calculate_grid_size(CHAR_RANGES)
    cell_size = resolution // grid_size
    
    # Track current position in the source atlas
    source_index = 0
    
    # Process each character range
    for start, end in CHAR_RANGES:
        for ascii_code in range(start, end + 1):
            # Calculate source position (original atlas)
            source_x = (source_index % grid_size) * cell_size
            source_y = (source_index // grid_size) * cell_size
            
            # Calculate target position (new atlas)
            target_x = ((ascii_code + 1) % grid_size) * cell_size
            target_y = ((ascii_code + 1) // grid_size) * cell_size
            
            # Extract and paste the glyph
            glyph = original.crop((
                source_x,
                source_y,
                source_x + cell_size,
                source_y + cell_size
            ))
            new_atlas.paste(glyph, (target_x, target_y))
            source_index += 1
    
    # Draw the grid lines only if requested
    if draw_grid:
        draw_grid_lines(new_atlas, resolution)
    
    # Save the rearranged atlas, overwriting the original
    new_atlas.save("atlas.png")
    print("Atlas rearranged successfully!")

def main():
    parser = argparse.ArgumentParser(description='Generate a font atlas using msdf-atlas-gen')
    parser.add_argument('font_path', help='Path to the font file (.ttf/.otf)')
    parser.add_argument('resolution', type=int, help='Total atlas resolution (width=height)')
    parser.add_argument('--grid', action='store_true', help='Draw grid lines on the output atlas')
    
    args = parser.parse_args()

    # Verify font file exists
    if not os.path.isfile(args.font_path):
        print(f"Error: Font file not found at {args.font_path}")
        return

    generate_atlas(args.font_path, args.resolution, args.grid)

if __name__ == "__main__":
    main()