connectPaths.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -*- coding:utf-8 -*-
  2. ##
  3. # This file is part of connectSVG.
  4. #
  5. # connectSVG is free software: you can redistribute it and/or modify it
  6. # under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License,
  8. # or (at your option) any later version.
  9. #
  10. # connectSVG is distributed in the hope that it will be useful, but WITHOUT ANY
  11. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  13. # details.
  14. #
  15. # You should have received a copy of the GNU General Public License along
  16. # with connectSVG. If not, see <https://www.gnu.org/licenses/>.
  17. ##
  18. import logging
  19. log = logging.getLogger("connectsvg")
  20. TOLERANCE = 0.0000000000005
  21. def connect(path, other) :
  22. if abs(path.end - other.start) <= TOLERANCE :
  23. log.debug("Appending path %s--%s", other.start, other.end)
  24. other.start = path.end
  25. path.extend(other)
  26. return path, True
  27. elif abs(path.end - other.end) <= TOLERANCE:
  28. log.debug("Appending path %s--%s", other.start, other.end)
  29. other.end = path.end;
  30. path.extend(other.reversed())
  31. return path, True
  32. elif abs(path.start - other.start) <= TOLERANCE :
  33. log.debug("Appending path %s--%s", other.start, other.end)
  34. other.start = path.start
  35. path = path.reversed()
  36. path.extend(other)
  37. return path, True
  38. elif abs(path.start - other.end) <= TOLERANCE :
  39. log.debug("Appending path %s--%s", other.start, other.end)
  40. other.end = path.start
  41. path = path.reversed()
  42. path.extend(other.reversed())
  43. return path, True
  44. return path, False
  45. def connectPaths(paths, attributes) :
  46. log.info("Starting with %d paths", len(paths))
  47. processedPaths = []
  48. processedAttributes = []
  49. while len(paths) > 0 :
  50. path = paths.pop()
  51. attr = attributes.pop()
  52. log.debug("Processing path %s--%s", path.start, path.end)
  53. i = 0
  54. while i < len(paths) :
  55. if attr['style'] == attributes[i]['style'] :
  56. path, used = connect(path, paths[i])
  57. if used :
  58. paths.pop(i)
  59. attributes.pop(i)
  60. i = -1
  61. i += 1
  62. processedPaths.append(path)
  63. processedAttributes.append({
  64. 'style': attr['style'],
  65. 'id': 'path'+str(len(processedPaths))
  66. })
  67. log.info("Ending with %d paths", len(processedPaths))
  68. return processedPaths, processedAttributes