Advertisement
jargon

Linedancer (LD4) "UI/Font Ripper/Font Ripper.php

Jan 6th, 2025 (edited)
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.60 KB | Gaming | 0 0
  1. <?php
  2. // Linedancer (LD4) :: "UI/Font Ripper/Font Ripper.php"
  3.  
  4. use FontLib\Font;
  5.  
  6. class FontRipper
  7. {
  8.     public function __construct ( )
  9.     {
  10.         $basePath = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
  11.         $vendor_autoload = null;
  12.        
  13.         while (!empty($basePath)) {
  14.            
  15.             // Check if "vendor" exists in the current directory
  16.             if (is_file("{$basePath}/vendor/autoload.php")) {
  17.                 $vendor_autoload = "{$basePath}/vendor/autoload.php";
  18.                 break;
  19.             }
  20.        
  21.             // Move up one level
  22.             $basePath = dirname($basePath);
  23.         }
  24.        
  25.         // Early exit if no vendor directory is found
  26.         if (!is_file($vendor_autoload)) {
  27.             print_r("Missing: \"vendor/autoload.php\"\r\n");
  28.             die();
  29.         }
  30.         else
  31.         {
  32.             if (isset($_GET['debug']))
  33.                 print_r("Found: \"{$vendor_autoload}\"\r\n");
  34.         }
  35.        
  36.         // Include Composer's autoloader
  37.         /* https://github.com/dompdf/php-font-lib */
  38.    
  39.         require ($vendor_autoload);
  40.     }
  41.    
  42.     public function calculateWindingDirection($contour) {
  43.         $sum = 0;
  44.         $count = count($contour);
  45.  
  46.         for ($i = 0; $i < $count; $i++) {
  47.             $current = $contour[$i]['point'];
  48.             $next = $contour[($i + 1) % $count]['point']; // Loop to the first point
  49.             $sum += ($next[0] - $current[0]) * ($next[1] + $current[1]); // Shoelace formula
  50.         }
  51.  
  52.         return $sum < 0 ? 'clockwise': 'counterclockwise';
  53.     }
  54.  
  55.     public function extractGlyphData($ttfPath, $characters, $outputFile) {
  56.         // Open the font file
  57.         $font = Font::load($ttfPath);
  58.         $font->parse();
  59.  
  60.         // Retrieve the glyph data
  61.         $glyphData = [];
  62.         foreach (str_split($characters) as $char) {
  63.             $unicode = ord($char);
  64.             $glyphIndex = $font->getGlyphIndex($unicode);
  65.  
  66.             if ($glyphIndex === false) {
  67.                 continue; // Skip if character is not found
  68.             }
  69.  
  70.             $glyph = $font->getGlyph($glyphIndex);
  71.             $outline = $glyph->getPathData();
  72.  
  73.             // Parse contours and Bezier curves
  74.             $contours = [];
  75.             $currentContour = [];
  76.             foreach ($outline['commands'] as $cmd) {
  77.                 $type = $cmd['type'];
  78.                 if ($type === 'moveto') {
  79.                     if (!empty($currentContour)) {
  80.                         $contours[] = $currentContour;
  81.                         $currentContour = [];
  82.                     }
  83.                     $currentContour[] = ['type' => 'moveTo', 'point' => $cmd['points'][0]];
  84.                 } elseif ($type === 'lineto') {
  85.                     $currentContour[] = ['type' => 'lineTo', 'point' => $cmd['points'][0]];
  86.                 } elseif ($type === 'quadto') {
  87.                     $currentContour[] = [
  88.                         'type' => 'quadraticBezier',
  89.                         'start' => $cmd['startPoint'],
  90.                         'control' => $cmd['controlPoints'][0],
  91.                         'end' => $cmd['points'][0]
  92.                     ];
  93.                 } elseif ($type === 'cubicto') {
  94.                     $currentContour[] = [
  95.                         'type' => 'cubicBezier',
  96.                         'start' => $cmd['startPoint'],
  97.                         'control1' => $cmd['controlPoints'][0],
  98.                         'control2' => $cmd['controlPoints'][1],
  99.                         'end' => $cmd['points'][0]
  100.                     ];
  101.                 } elseif ($type === 'closepath') {
  102.                     $currentContour[] = ['type' => 'closePath'];
  103.                 }
  104.             }
  105.             if (!empty($currentContour)) {
  106.                 $contours[] = $currentContour;
  107.             }
  108.  
  109.             // Determine winding direction for each contour
  110.             $processedContours = [];
  111.             foreach ($contours as $contour) {
  112.                 $direction = $this->calculateWindingDirection($contour);
  113.                 $processedContours[] = [
  114.                     'direction' => $direction,
  115.                     'type' => $direction === 'clockwise' ? 'additive': 'subtractive',
  116.                     'segments' => $contour
  117.                 ];
  118.             }
  119.  
  120.             $glyphData[$char] = [
  121.                 'name' => $char,
  122.                 'unicode' => $unicode,
  123.                 'contours' => $processedContours
  124.             ];
  125.         }
  126.  
  127.         // Save to JSON
  128.         file_put_contents($outputFile, json_encode($glyphData, JSON_PRETTY_PRINT));
  129.         echo "Glyph data saved to $outputFile\n";
  130.     }
  131.  
  132.     public function Rip( $Font = 'impact.ttf', $Glyphs = ['A','B','C','X','Y','Z'] )
  133.     {
  134.         // Define fonts folder
  135.         $FontDir = "{$_SERVER['DOCUMENT_ROOT']}/Shared/assets/Fonts/";
  136.        
  137.         if(!is_dir($FontDir))
  138.         {
  139.             if (isset($_GET['debug']))
  140.                 print_r("Creating font directory: \"{$FontDir}\"");
  141.            
  142.             mkdir(dirname($FontDir), 0777, true);          
  143.         }
  144.            
  145.         // Define valid font extensions (lowercase)
  146.         $ValidTypes = ['ttf','otf','otc','ttc'];
  147.        
  148.         // Define font file name
  149.         $FontName = pathinfo($Font, PATHINFO_FILENAME);
  150.        
  151.         // Define font file extension
  152.         $FontType = pathinfo($Font, PATHINFO_EXTENSION);
  153.        
  154.         // If invalid font extension (early exit)
  155.         if(!in_array(strtolower($FontType),$ValidTypes))
  156.         {
  157.             if (isset($_GET['debug']))
  158.                 print_r("Bad font extension: \"{$FontType}\"");
  159.            
  160.             return;
  161.         }
  162.        
  163.         $FontNames =
  164.             array_map
  165.             (
  166.                 fn($file) =>
  167.                 pathinfo
  168.                 (
  169.                     $file,
  170.                     PATHINFO_FILENAME
  171.                 ),
  172.                 glob
  173.                 (
  174.                     rtrim
  175.                     (
  176.                         $FontDir,
  177.                         '/'
  178.                     ) . "/*.{$FontType}"
  179.                 )
  180.             );
  181.        
  182.         $Fonts = implode("\", \"",$FontNames);
  183.         $Fonts = !empty($Fonts) ? "\"{$Fonts}\"" : "";
  184.        
  185.         print_r(strtoupper($FontType)." Fonts: {$Fonts}\r\n");
  186.         print_r("Using: \"{$FontName}.{$FontType}\" In: \"{$FontDir}\"\r\n");
  187.        
  188.         if(!is_dir(dirname($FontDir)))
  189.         {
  190.             if (isset($_GET['debug']))
  191.                 print_r("Creating font directory: \"{$FontDir}\"");
  192.            
  193.             mkdir(dirname($FontDir), 0777, true);
  194.         }
  195.        
  196.         // If invalid font name (early exit)
  197.         if(!in_array($FontName,$FontNames))
  198.         {
  199.             if (isset($_GET['debug']))
  200.                 print_r("Missing: \"{$FontName}\"");
  201.            
  202.             die();
  203.         }
  204.        
  205.         $FontPath = "{$_SERVER['DOCUMENT_ROOT']}/Shared/assets/Fonts/{$FontName}.{$FontType}";
  206.        
  207.         // If invalid font path (early exit)
  208.         if(!is_dir(dirname($FontPath)))
  209.         {
  210.             if (isset($_GET['debug']))
  211.                 print_r("Creating font directory: \"".dirname($FontPath)."\"");
  212.                
  213.             if(!is_dir(dirname($FontPath)))
  214.                 mkdir(dirname($FontPath), 0777, true);
  215.         }
  216.  
  217.         // If invalid font file (early exit)
  218.         if(!is_file($FontPath))
  219.         {
  220.             if (isset($_GET['debug']))
  221.                 print_r("Missing font file: \"{$FontPath}\"");
  222.            
  223.             return;
  224.         }
  225.        
  226.         // Set brand of font
  227.         $BrandName = ucwords($FontName);
  228.        
  229.         // Specify list of glyphs to rip
  230.         $Characters = $Glyphs;
  231.  
  232.         // Cycle thru specified glyphs and rip from given font
  233.         foreach ($Characters as $GlyphName) {
  234.             $RipPath = "{$_SERVER['DOCUMENT_ROOT']}/LD4/Linedancer/scripts/json/UI/Gamepad/Labels/{$BrandName}/{$GlyphName}.json";
  235.  
  236.             // If rip destination path is missing: create it
  237.             if (!is_dir(dirname($RipPath))) {
  238.                
  239.                 if (isset($_GET['debug']))
  240.                     print_r("Creating rip directory: \"".dirname($RipPath)."\"");
  241.                
  242.                 if(!is_dir(dirname($RipPath)))
  243.                     mkdir(dirname($RipPath), 0777, true);
  244.             }
  245.  
  246.             // Extract and save glyph data
  247.             $this->extractGlyphData($FontPath, $GlyphName, $RipPath);
  248.         }
  249.        
  250.         // (exit)
  251.         return;
  252.     }
  253. }
  254.  
  255. $FontRipper = new FontRipper();
  256. $FontRipper->Rip('impact.ttf',['A','B','C','X','Y','Z']);
  257.  
  258. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement