phg-vis 7.2.1__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. phg_vis-7.2.1.data/purelib/phg/__init__.py +441 -0
  2. phg_vis-7.2.1.data/purelib/phg/ai_bridge.py +222 -0
  3. phg_vis-7.2.1.data/purelib/phg/backend.py +403 -0
  4. phg_vis-7.2.1.data/purelib/phg/docs/PHG_SYNTAX_SPEC.md +303 -0
  5. phg_vis-7.2.1.data/purelib/phg/frame_bool.py +286 -0
  6. phg_vis-7.2.1.data/purelib/phg/gcu_api.py +1100 -0
  7. phg_vis-7.2.1.data/purelib/phg/phg_to_shader.py +433 -0
  8. phg_vis-7.2.1.data/purelib/phg/pipe_string_phg.py +439 -0
  9. phg_vis-7.2.1.data/purelib/phg/router_engine/README.md +95 -0
  10. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/FreeImage.dll +0 -0
  11. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/GCU.dll +0 -0
  12. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/Iex-3_2.dll +0 -0
  13. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/IlmThread-3_2.dll +0 -0
  14. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/Imath-3_1.dll +0 -0
  15. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/Manifold.dll +0 -0
  16. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/OpenEXR-3_2.dll +0 -0
  17. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/OpenEXRCore-3_2.dll +0 -0
  18. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/RWWlkx.dll +0 -0
  19. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/ToKtx.dll +0 -0
  20. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/ToolSets.dll +0 -0
  21. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/co.dll +0 -0
  22. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/deflate.dll +0 -0
  23. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/freeglut.dll +0 -0
  24. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/jpeg62.dll +0 -0
  25. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/jsoncpp.dll +0 -0
  26. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/ktx.dll +0 -0
  27. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/lcms2.dll +0 -0
  28. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/liblzma.dll +0 -0
  29. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/libpng16.dll +0 -0
  30. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/libsharpyuv.dll +0 -0
  31. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/libwebp.dll +0 -0
  32. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/libwebpdecoder.dll +0 -0
  33. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/libwebpmux.dll +0 -0
  34. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/lua.dll +0 -0
  35. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/lz4.dll +0 -0
  36. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/nwcreate_20.dll +0 -0
  37. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/openjp2.dll +0 -0
  38. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/raw.dll +0 -0
  39. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/sqlite3.dll +0 -0
  40. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/tiff.dll +0 -0
  41. phg_vis-7.2.1.data/purelib/phg/router_engine/bin/zlib1.dll +0 -0
  42. phg_vis-7.2.1.data/purelib/phg/router_engine/data/ROUTERs.json +7281 -0
  43. phg_vis-7.2.1.data/purelib/phg/router_engine/data/auto-pipe-test.phg +41737 -0
  44. phg_vis-7.2.1.data/purelib/phg/router_engine/data/full_scene_raw_grid_unit015.grid +0 -0
  45. phg_vis-7.2.1.data/purelib/phg/router_engine/data/real_scene_business_router_results.json +8728 -0
  46. phg_vis-7.2.1.data/purelib/phg/router_engine/data/recommended_thresholds.json +94 -0
  47. phg_vis-7.2.1.data/purelib/phg/router_engine/data/test.json +3742 -0
  48. phg_vis-7.2.1.data/purelib/phg/router_engine/data/thresholds_astar_guidance_mild.json +9 -0
  49. phg_vis-7.2.1.data/purelib/phg/router_engine/data/thresholds_astar_guidance_off.json +5 -0
  50. phg_vis-7.2.1.data/purelib/phg/router_engine/pyproject.toml +20 -0
  51. phg_vis-7.2.1.data/purelib/phg/router_engine/scripts/benchmark_cooperative_reservations.py +120 -0
  52. phg_vis-7.2.1.data/purelib/phg/router_engine/scripts/build_grid_from_phg.ps1 +20 -0
  53. phg_vis-7.2.1.data/purelib/phg/router_engine/scripts/experiment_batch_pipe_string_optimizer.py +583 -0
  54. phg_vis-7.2.1.data/purelib/phg/router_engine/scripts/experiment_nozzle_guided_retry.py +232 -0
  55. phg_vis-7.2.1.data/purelib/phg/router_engine/scripts/experiment_pipe_string_retry.py +246 -0
  56. phg_vis-7.2.1.data/purelib/phg/router_engine/scripts/run_real_scene.ps1 +19 -0
  57. phg_vis-7.2.1.data/purelib/phg/router_engine/src/auto_pipe_engine/__init__.py +39 -0
  58. phg_vis-7.2.1.data/purelib/phg/router_engine/src/auto_pipe_engine/cli.py +112 -0
  59. phg_vis-7.2.1.data/purelib/phg/router_engine/src/auto_pipe_engine/free_energy.py +129 -0
  60. phg_vis-7.2.1.data/purelib/phg/router_engine/src/auto_pipe_engine/grid_builder.py +480 -0
  61. phg_vis-7.2.1.data/purelib/phg/router_engine/src/auto_pipe_engine/interface.py +299 -0
  62. phg_vis-7.2.1.data/purelib/phg/router_engine/src/auto_pipe_engine/standalone_runner.py +757 -0
  63. phg_vis-7.2.1.data/purelib/phg/router_engine/src/auto_pipe_engine/support/phg_pipe_rack_occupancy.py +234 -0
  64. phg_vis-7.2.1.data/purelib/phg/router_engine/src/auto_pipe_engine/support/route_routers_json_120.py +473 -0
  65. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/business_optimization/__init__.py +3 -0
  66. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/business_optimization/free_energy_constraints.py +139 -0
  67. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/business_optimization/free_energy_spec.py +131 -0
  68. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/doctor/__init__.py +9 -0
  69. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/doctor/pipe_intersection_doctor.py +2261 -0
  70. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/doctor/socket_guide_doctor.py +185 -0
  71. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/__init__.py +28 -0
  72. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/api.py +21 -0
  73. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/api_impl.py +395 -0
  74. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/batch/__init__.py +19 -0
  75. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/batch/batch_router_engine.py +926 -0
  76. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/cooperative/__init__.py +17 -0
  77. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/cooperative/cooperative_astar.py +515 -0
  78. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/core/__init__.py +41 -0
  79. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/core/astar_path_kernel.py +821 -0
  80. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/core/path_postprocess.py +390 -0
  81. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/core/pipe_path_solver.py +298 -0
  82. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/core/router_engine.py +1095 -0
  83. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/grid/__init__.py +6 -0
  84. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/grid/dynamic_route_grid.py +366 -0
  85. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/grid/grid_static_collision.py +220 -0
  86. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/optimization/__init__.py +29 -0
  87. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/optimization/free_energy.py +476 -0
  88. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/validation/__init__.py +5 -0
  89. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_router/validation/audit_port_pose_reasonableness.py +201 -0
  90. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_string_solver/README.md +64 -0
  91. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_string_solver/__init__.py +28 -0
  92. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_string_solver/encoding.py +60 -0
  93. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_string_solver/free_energy.py +25 -0
  94. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_string_solver/isomers.py +70 -0
  95. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_string_solver/model.py +121 -0
  96. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_string_solver/solver.py +116 -0
  97. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_string_solver/v2_post_optimizer.py +298 -0
  98. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/pipe_string_solver/validation.py +29 -0
  99. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/short_router/__init__.py +7 -0
  100. phg_vis-7.2.1.data/purelib/phg/router_engine/vendor/short_router/semantic_short_router.py +269 -0
  101. phg_vis-7.2.1.data/purelib/phg/semantic_engine/__init__.py +10 -0
  102. phg_vis-7.2.1.data/purelib/phg/semantic_engine/engine.py +2891 -0
  103. phg_vis-7.2.1.data/purelib/phg/semantic_engine/qgraph_business_regulations.py +381 -0
  104. phg_vis-7.2.1.data/purelib/phg/semantic_engine/qgraph_recovery.py +383 -0
  105. phg_vis-7.2.1.data/purelib/phg/semantic_engine/semantic_constraints.py +588 -0
  106. phg_vis-7.2.1.data/purelib/phg/semantic_recovery.py +92 -0
  107. phg_vis-7.2.1.data/purelib/phg/shader_render.py +439 -0
  108. phg_vis-7.2.1.data/purelib/phg/vis/FZQTJW.TTF +0 -0
  109. phg_vis-7.2.1.data/purelib/phg/vis/GCU.dll +0 -0
  110. phg_vis-7.2.1.data/purelib/phg/vis/config.ini +4 -0
  111. phg_vis-7.2.1.data/purelib/phg/vis/dragpad.exe +0 -0
  112. phg_vis-7.2.1.data/purelib/phg/vis/dragpad_config.ini +6 -0
  113. phg_vis-7.2.1.data/purelib/phg/vis/freeglut.dll +0 -0
  114. phg_vis-7.2.1.data/purelib/phg/vis/imgui/login.lua +46 -0
  115. phg_vis-7.2.1.data/purelib/phg/vis/imgui/main.lua +44 -0
  116. phg_vis-7.2.1.data/purelib/phg/vis/imgui.ini +19 -0
  117. phg_vis-7.2.1.data/purelib/phg/vis/lua.dll +0 -0
  118. phg_vis-7.2.1.data/purelib/phg/vis/nl_service.py +267 -0
  119. phg_vis-7.2.1.data/purelib/phg/vis/shader/fragment_shader.glsl +314 -0
  120. phg_vis-7.2.1.data/purelib/phg/vis/shader/vertex_shader.glsl +9 -0
  121. phg_vis-7.2.1.data/purelib/phg/vis/sqlite3.dll +0 -0
  122. phg_vis-7.2.1.data/purelib/phg/vis/vis.exe +0 -0
  123. phg_vis-7.2.1.data/purelib/phg/vis/vis.ini +17 -0
  124. phg_vis-7.2.1.data/purelib/phg/vis/zlib1.dll +0 -0
  125. phg_vis-7.2.1.data/purelib/phg/visphg.py +81 -0
  126. phg_vis-7.2.1.data/purelib/phg/web_three.py +172 -0
  127. phg_vis-7.2.1.dist-info/METADATA +720 -0
  128. phg_vis-7.2.1.dist-info/RECORD +132 -0
  129. phg_vis-7.2.1.dist-info/WHEEL +5 -0
  130. phg_vis-7.2.1.dist-info/entry_points.txt +2 -0
  131. phg_vis-7.2.1.dist-info/licenses/LICENSE +9 -0
  132. phg_vis-7.2.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,441 @@
1
+ """
2
+ PHG - Python Hypergraphics Library
3
+ ===================================
4
+
5
+ A powerful graphics library for procedural 3D visualization using PHG scripts.
6
+
7
+ Main Features:
8
+ - PHG script visualization via vis.exe
9
+ - Shader-based rendering with GLSL conversion
10
+ - Pipe system visualization with world/local coordinate systems
11
+ - PHG semantic recovery with pipe-first AUTO_PIPE topology extraction
12
+ - Multiple pipe visualization support
13
+ - Real-time, deterministic video, and image rendering capabilities
14
+ - GPU material and post-effect presentation through VIS commands
15
+
16
+ Version: 7.2.1
17
+ Author: PanGuoJun
18
+ License: MIT
19
+ """
20
+
21
+ import os
22
+ import tempfile
23
+
24
+ from .backend import ensure_vis_server, render_png, render_png_bytes, resolve_vis_runtime_dir, send_phg
25
+ from .visphg import vis, image
26
+ from .phg_to_shader import PHGToShaderConverter, phg_to_shader
27
+ from .pipe_string_phg import (
28
+ world_to_local_pipe_str,
29
+ local_pipe_to_phg,
30
+ world_pipe_to_phg,
31
+ world_pipestr_vis,
32
+ local_pipestr_vis,
33
+ multiple_pipes_vis
34
+ )
35
+ from .ai_bridge import (
36
+ compile_ai_phg,
37
+ vis_ai,
38
+ image_ai,
39
+ export_ai_obj,
40
+ web_view_ai,
41
+ )
42
+ from .web_three import write_three_view_html, serve_three_view
43
+ from .frame_bool import (
44
+ FrameBoolMesh,
45
+ add_grid_faces_expected,
46
+ build_sphere_minus_cylinder_mesh,
47
+ make_frame_bool_phg,
48
+ )
49
+
50
+ def _shader_symbols():
51
+ from .shader_render import ShaderRenderer as _ShaderRenderer, render_shader as _render_shader
52
+
53
+ return _ShaderRenderer, _render_shader
54
+
55
+
56
+ class PHGShaderRenderer:
57
+ """Lazy wrapper that avoids importing pygame/OpenGL on plain `import phg`."""
58
+
59
+ def __init__(self, width=800, height=600, title="PHG Renderer"):
60
+ ShaderRenderer, _ = _shader_symbols()
61
+ self._renderer = ShaderRenderer(width, height, title)
62
+
63
+ def __getattr__(self, name):
64
+ return getattr(self._renderer, name)
65
+
66
+ def render_phg(self, phg_script: str, duration=0, interactive=True):
67
+ converter = PHGToShaderConverter()
68
+ shader_code = converter.generate_shader_code(phg_script)
69
+
70
+ if not shader_code:
71
+ print("Error: PHG conversion failed")
72
+ return False
73
+
74
+ return self._renderer.render_shader(shader_code, duration, interactive)
75
+
76
+ # Convenience functions
77
+ def render_phg(phg_script: str, width=800, height=600, duration=0, title="PHG Renderer"):
78
+ """
79
+ Directly render PHG script
80
+
81
+ Parameters:
82
+ phg_script: PHG script code
83
+ width: Window width
84
+ height: Window height
85
+ duration: Render duration
86
+ title: Window title
87
+ """
88
+ renderer = PHGShaderRenderer(width, height, title)
89
+ success = renderer.render_phg(phg_script, duration)
90
+ renderer.close()
91
+ return success
92
+
93
+
94
+ def render_shader(*args, **kwargs):
95
+ _, _render_shader = _shader_symbols()
96
+ return _render_shader(*args, **kwargs)
97
+
98
+ def convert_phg_to_shader(phg_script: str) -> str:
99
+ """
100
+ Convert PHG script to GLSL shader code
101
+
102
+ Parameters:
103
+ phg_script: PHG script
104
+
105
+ Returns:
106
+ shader_code: GLSL shader code
107
+ """
108
+ return phg_to_shader(phg_script)
109
+
110
+ def visualize_pipe_variants(pipe_variants, start_position=None, colors=None, coordinate_system='world'):
111
+ """
112
+ Visualize multiple pipe variants for comparison
113
+
114
+ Parameters:
115
+ pipe_variants: List of pipe strings or configuration dictionaries
116
+ start_position: Starting coordinate (optional)
117
+ colors: List of colors for each pipe variant
118
+ coordinate_system: 'world' or 'local' coordinate system
119
+
120
+ Returns:
121
+ PHG script string
122
+ """
123
+ from coordinate_system import vec3, quat, coord3
124
+
125
+ # Handle start position
126
+ if start_position is None:
127
+ start_c = coord3(vec3(0, 0, 0), quat(1, 0, 0, 0))
128
+ else:
129
+ start_c = start_position
130
+
131
+ # Handle different input formats
132
+ if isinstance(pipe_variants[0], str):
133
+ # Simple list of pipe strings
134
+ if colors is None:
135
+ # Generate distinct colors for each variant
136
+ import colorsys
137
+ colors = []
138
+ for i in range(len(pipe_variants)):
139
+ hue = i / len(pipe_variants)
140
+ rgb = colorsys.hsv_to_rgb(hue, 0.8, 0.9)
141
+ colors.append(tuple(int(c * 255) for c in rgb))
142
+
143
+ if coordinate_system == 'world':
144
+ return world_pipestr_vis(pipe_variants, start_c, colors)
145
+ else:
146
+ return local_pipestr_vis(pipe_variants, start_c, colors)
147
+
148
+ else:
149
+ # List of configuration dictionaries
150
+ pipe_configs = []
151
+ for i, variant in enumerate(pipe_variants):
152
+ if isinstance(variant, str):
153
+ config = {
154
+ 'pipe_str': variant,
155
+ 'start_c': start_c,
156
+ 'color': colors[i] if colors else None,
157
+ 'radius': 0.3
158
+ }
159
+ else:
160
+ config = variant
161
+ if 'start_c' not in config:
162
+ config['start_c'] = start_c
163
+
164
+ pipe_configs.append(config)
165
+
166
+ return multiple_pipes_vis(pipe_configs, coordinate_system)
167
+
168
+ def create_pipe_comparison_grid(pipe_strings, grid_size=(2, 2), start_position=None,
169
+ base_color=(0, 55, 255), coordinate_system='world'):
170
+ """
171
+ Create a grid layout for comparing multiple pipe paths
172
+
173
+ Parameters:
174
+ pipe_strings: List of pipe strings to compare
175
+ grid_size: (rows, cols) for grid layout
176
+ start_position: Base starting position
177
+ base_color: Base color for pipes
178
+ coordinate_system: 'world' or 'local'
179
+
180
+ Returns:
181
+ PHG script string
182
+ """
183
+ from coordinate_system import vec3, quat, coord3
184
+
185
+ if start_position is None:
186
+ start_position = coord3(vec3(0, 0, 0), quat(1, 0, 0, 0))
187
+
188
+ rows, cols = grid_size
189
+ spacing = 5.0 # Space between pipes in grid
190
+
191
+ pipe_configs = []
192
+
193
+ for i, pipe_str in enumerate(pipe_strings):
194
+ if i >= rows * cols:
195
+ break
196
+
197
+ row = i // cols
198
+ col = i % cols
199
+
200
+ # Calculate position in grid
201
+ x_offset = col * spacing
202
+ z_offset = row * spacing
203
+
204
+ # Create individual start position for this pipe
205
+ individual_start = coord3(
206
+ vec3(
207
+ start_position.o.x + x_offset,
208
+ start_position.o.y,
209
+ start_position.o.z + z_offset
210
+ ),
211
+ start_position.Q()
212
+ )
213
+
214
+ # Generate color variation
215
+ color_variation = (
216
+ min(255, base_color[0] + (i * 30) % 100),
217
+ min(255, base_color[1] + (i * 50) % 100),
218
+ min(255, base_color[2] + (i * 70) % 100)
219
+ )
220
+
221
+ pipe_configs.append({
222
+ 'pipe_str': pipe_str,
223
+ 'start_c': individual_start,
224
+ 'color': color_variation,
225
+ 'radius': 0.25 + (i * 0.05) # Vary radius slightly
226
+ })
227
+
228
+ return multiple_pipes_vis(pipe_configs, coordinate_system)
229
+
230
+ def generate_pipe_variants_from_rules(base_pipe, num_variants=5, apply_rules=None):
231
+ """
232
+ Generate pipe variants using transformation rules
233
+
234
+ Parameters:
235
+ base_pipe: Base pipe string
236
+ num_variants: Number of variants to generate
237
+ apply_rules: List of rules to apply ('swap', 'insert', 'cancel')
238
+
239
+ Returns:
240
+ List of pipe variant strings
241
+ """
242
+ if apply_rules is None:
243
+ apply_rules = ['swap', 'insert', 'cancel']
244
+
245
+ variants = [base_pipe]
246
+
247
+ # Import the pipe transformer if available
248
+ try:
249
+ from .pipe_string_phg import PipeStringTransformer
250
+ transformer = PipeStringTransformer()
251
+
252
+ for _ in range(num_variants - 1):
253
+ current_pipe = base_pipe
254
+
255
+ # Apply random transformations
256
+ import random
257
+ for _ in range(random.randint(1, 3)):
258
+ rule = random.choice(apply_rules)
259
+
260
+ if rule == 'swap' and len(current_pipe) >= 2:
261
+ i, j = random.sample(range(len(current_pipe)), 2)
262
+ current_pipe = transformer.swap_positions(current_pipe, i, j)
263
+
264
+ elif rule == 'insert':
265
+ position = random.randint(0, len(current_pipe))
266
+ direction = random.choice(list(transformer.CANCEL_PAIRS.keys()))
267
+ current_pipe = transformer.insert_cancel_pair(current_pipe, position, direction)
268
+
269
+ elif rule == 'cancel':
270
+ current_pipe = transformer.cancel_adjacent_pairs(current_pipe)
271
+
272
+ # Simplify and add if valid
273
+ simplified = transformer.simplify_path(current_pipe)
274
+ if simplified not in variants:
275
+ variants.append(simplified)
276
+
277
+ except ImportError:
278
+ # Fallback: simple variant generation
279
+ import random
280
+ for i in range(num_variants - 1):
281
+ # Simple character shuffling
282
+ pipe_list = list(base_pipe)
283
+ random.shuffle(pipe_list)
284
+ variant = ''.join(pipe_list)
285
+ if variant not in variants:
286
+ variants.append(variant)
287
+
288
+ return variants[:num_variants]
289
+
290
+ # Enhanced pipe visualization with transformation support
291
+ def visualize_pipe_with_transformations(pipe_string, start_position=None,
292
+ transformations=None, show_variants=3):
293
+ """
294
+ Visualize a pipe string along with its transformed variants
295
+
296
+ Parameters:
297
+ pipe_string: Base pipe string
298
+ start_position: Starting coordinate
299
+ transformations: List of transformation rules to apply
300
+ show_variants: Number of variants to show
301
+
302
+ Returns:
303
+ PHG script string
304
+ """
305
+ # Generate variants
306
+ variants = generate_pipe_variants_from_rules(
307
+ pipe_string,
308
+ num_variants=show_variants + 1, # +1 for original
309
+ apply_rules=transformations
310
+ )
311
+
312
+ # Create comparison visualization
313
+ return visualize_pipe_variants(variants, start_position)
314
+
315
+
316
+ def web_view(script: str, out_html: str = "phg_view.html", out_obj: str = None,
317
+ ai_root: str = None, title: str = "PHG Web Viewer") -> str:
318
+ """
319
+ Export OBJ via AI parser and write a three.js HTML viewer.
320
+ """
321
+ return web_view_ai(script, out_html=out_html, out_obj=out_obj, ai_root=ai_root, title=title)
322
+
323
+
324
+ def web_serve(script: str, host: str = "127.0.0.1", port: int = 8766,
325
+ ai_root: str = None, title: str = "PHG Web Viewer") -> str:
326
+ """
327
+ Export OBJ via AI parser, write HTML, and serve with a local HTTP server.
328
+ """
329
+ temp_dir = tempfile.mkdtemp(prefix="phg_web_")
330
+ out_obj = os.path.join(temp_dir, "scene.obj")
331
+ out_html = os.path.join(temp_dir, "viewer.html")
332
+ web_view_ai(script, out_html=out_html, out_obj=out_obj, ai_root=ai_root, title=title)
333
+ return serve_three_view(out_obj, html_path=out_html, host=host, port=port, title=title)
334
+
335
+
336
+ def visualize(script: str, mode: str = "vis", ai: bool = False, **kwargs):
337
+ """
338
+ Unified visualization entrypoint.
339
+ mode: vis | image | shader | web
340
+ ai: use AI parser (DGE++) to normalize/expand before visualization
341
+ """
342
+ mode = (mode or "vis").lower()
343
+ ai_root = kwargs.pop("ai_root", None)
344
+
345
+ if mode in ("vis", "native", "exe"):
346
+ return vis_ai(script, ai_root=ai_root) if ai else vis(script)
347
+
348
+ if mode in ("image", "img", "png"):
349
+ filename = kwargs.pop("filename", "shot.png")
350
+ return image_ai(script, filename=filename, ai_root=ai_root) if ai else image(script, filename=filename)
351
+
352
+ if mode in ("shader", "ray", "rt"):
353
+ phg_script = compile_ai_phg(script, ai_root=ai_root, include_setup=True) if ai else script
354
+ return render_phg(phg_script, **kwargs)
355
+
356
+ if mode in ("web", "three"):
357
+ out_html = kwargs.pop("out_html", "phg_view.html")
358
+ out_obj = kwargs.pop("out_obj", None)
359
+ title = kwargs.pop("title", "PHG Web Viewer")
360
+ return web_view_ai(script, out_html=out_html, out_obj=out_obj, ai_root=ai_root, title=title)
361
+
362
+ raise ValueError(f"Unknown mode: {mode}")
363
+
364
+
365
+ def __getattr__(name):
366
+ if name == "ShaderRenderer":
367
+ ShaderRenderer, _ = _shader_symbols()
368
+ return ShaderRenderer
369
+ if name in {"SemanticRecoveryResult", "recover_phg_semantics", "recover_phg_semantic_text"}:
370
+ from . import semantic_recovery as _semantic_recovery
371
+ return getattr(_semantic_recovery, name)
372
+ raise AttributeError(name)
373
+
374
+ __all__ = [
375
+ # Core visualization functions
376
+ 'vis',
377
+ 'image',
378
+ 'visualize',
379
+ 'send_phg',
380
+ 'render_png',
381
+ 'render_png_bytes',
382
+ 'ensure_vis_server',
383
+ 'resolve_vis_runtime_dir',
384
+
385
+ # Shader rendering
386
+ 'ShaderRenderer',
387
+ 'render_shader',
388
+ 'render_phg',
389
+ 'PHGShaderRenderer',
390
+
391
+ # PHG conversion
392
+ 'PHGToShaderConverter',
393
+ 'phg_to_shader',
394
+ 'convert_phg_to_shader',
395
+ 'compile_ai_phg',
396
+ 'vis_ai',
397
+ 'image_ai',
398
+ 'export_ai_obj',
399
+ 'web_view',
400
+ 'web_view_ai',
401
+ 'web_serve',
402
+ 'write_three_view_html',
403
+ 'serve_three_view',
404
+ 'SemanticRecoveryResult',
405
+ 'recover_phg_semantics',
406
+ 'recover_phg_semantic_text',
407
+
408
+ # Frame/coord Boolean modeling
409
+ 'FrameBoolMesh',
410
+ 'add_grid_faces_expected',
411
+ 'build_sphere_minus_cylinder_mesh',
412
+ 'make_frame_bool_phg',
413
+
414
+ # Pipe visualization
415
+ 'world_pipe_to_phg',
416
+ 'local_pipe_to_phg',
417
+ 'world_pipestr_vis',
418
+ 'local_pipestr_vis',
419
+ 'multiple_pipes_vis',
420
+
421
+ # Enhanced pipe visualization
422
+ 'visualize_pipe_variants',
423
+ 'create_pipe_comparison_grid',
424
+ 'generate_pipe_variants_from_rules',
425
+ 'visualize_pipe_with_transformations',
426
+ ]
427
+
428
+ __version__ = "7.2.1"
429
+ __author__ = "PanGuoJun"
430
+ __description__ = "Python Hypergraphics Library"
431
+
432
+ if os.environ.get("PHG_VERBOSE"):
433
+ print(f"PHG {__version__} - {__description__}")
434
+ print("[OK] Visualization module loaded")
435
+ print("[OK] Shader converter loaded")
436
+ print("[OK] Pipe visualization loaded")
437
+ print("[OK] Multiple pipe visualization support loaded")
438
+ print("[OK] Pipe transformation utilities loaded")
439
+
440
+
441
+
@@ -0,0 +1,222 @@
1
+ """
2
+ AI bridge for PHG (DGE++ parser -> normalized PHG -> vis.exe / web).
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import importlib
8
+ import importlib.util
9
+ import json
10
+ import os
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ from typing import Any, Dict, Iterable, List, Optional
15
+
16
+ from .visphg import vis as _vis, image as _image
17
+ from .web_three import write_three_view_html
18
+
19
+ DEFAULT_AI_ROOT = None
20
+ _AI_MODULE = None
21
+ _AI_MODULE_ROOT = None
22
+
23
+
24
+ def resolve_ai_root(ai_root: Optional[str] = None) -> str:
25
+ root = ai_root or os.environ.get("PHG_AI_ROOT") or DEFAULT_AI_ROOT
26
+ if not root:
27
+ raise FileNotFoundError(
28
+ "AI PHG root is not configured. Set PHG_AI_ROOT or pass ai_root explicitly."
29
+ )
30
+ if not os.path.isdir(root):
31
+ raise FileNotFoundError(
32
+ f"AI PHG root not found: {root}. "
33
+ "Set PHG_AI_ROOT or pass ai_root explicitly."
34
+ )
35
+ return root
36
+
37
+
38
+ def _run_ai_cli(args: List[str], ai_root: Optional[str] = None, timeout: int = 120) -> subprocess.CompletedProcess:
39
+ root = resolve_ai_root(ai_root)
40
+ cmd = [sys.executable, "-m", "phg"] + args
41
+ return subprocess.run(
42
+ cmd,
43
+ cwd=root,
44
+ capture_output=True,
45
+ text=True,
46
+ timeout=timeout,
47
+ check=False,
48
+ )
49
+
50
+
51
+ def _load_ai_module(ai_root: Optional[str] = None):
52
+ global _AI_MODULE, _AI_MODULE_ROOT
53
+ root = resolve_ai_root(ai_root)
54
+ if _AI_MODULE is not None and _AI_MODULE_ROOT == root:
55
+ return _AI_MODULE
56
+
57
+ pkg_dir = os.path.join(root, "phg")
58
+ init_path = os.path.join(pkg_dir, "__init__.py")
59
+ if not os.path.isfile(init_path):
60
+ raise FileNotFoundError(f"AI PHG package not found: {init_path}")
61
+
62
+ spec = importlib.util.spec_from_file_location(
63
+ "phg_ai",
64
+ init_path,
65
+ submodule_search_locations=[pkg_dir],
66
+ )
67
+ if spec is None or spec.loader is None:
68
+ raise ImportError("Failed to load AI PHG package")
69
+
70
+ module = importlib.util.module_from_spec(spec)
71
+ sys.modules["phg_ai"] = module
72
+ spec.loader.exec_module(module)
73
+ _AI_MODULE = module
74
+ _AI_MODULE_ROOT = root
75
+ return module
76
+
77
+
78
+ def _write_temp_phg(script: str) -> str:
79
+ fd, path = tempfile.mkstemp(suffix=".phg")
80
+ os.close(fd)
81
+ with open(path, "w", encoding="utf-8") as f:
82
+ f.write(script)
83
+ return path
84
+
85
+
86
+ def dump_scene(script: str, ai_root: Optional[str] = None) -> Dict[str, Any]:
87
+ """
88
+ Use AI PHG (DGE++) to parse script and dump scene JSON.
89
+ """
90
+ phg_path = _write_temp_phg(script)
91
+ fd, json_path = tempfile.mkstemp(suffix=".json")
92
+ os.close(fd)
93
+ try:
94
+ try:
95
+ ai = _load_ai_module(ai_root)
96
+ engine_mod = importlib.import_module("phg_ai.engine")
97
+ engine = engine_mod.Engine()
98
+ engine.run(script)
99
+ if "setup" not in engine.calls:
100
+ engine.setup()
101
+ if "draw" not in engine.calls:
102
+ engine.draw()
103
+ return engine._scene_to_dict(engine.scene.root)
104
+ except Exception:
105
+ proc = _run_ai_cli(["dump", phg_path, "--out", json_path], ai_root=ai_root)
106
+ if proc.returncode != 0:
107
+ raise RuntimeError(proc.stderr.strip() or proc.stdout.strip() or "AI dump failed")
108
+ with open(json_path, "r", encoding="utf-8") as f:
109
+ return json.load(f)
110
+ finally:
111
+ for p in (phg_path, json_path):
112
+ try:
113
+ os.remove(p)
114
+ except OSError:
115
+ pass
116
+
117
+
118
+ def _format_value(value: Any) -> str:
119
+ if value is None:
120
+ return ""
121
+ if isinstance(value, bool):
122
+ return "1" if value else "0"
123
+ if isinstance(value, (int, float)):
124
+ return str(value)
125
+ if isinstance(value, (list, tuple)):
126
+ return ",".join(str(v) for v in value)
127
+ return str(value)
128
+
129
+
130
+ def _emit_props(props: Dict[str, Any], indent: str) -> List[str]:
131
+ lines = []
132
+ for key, value in props.items():
133
+ val = _format_value(value)
134
+ if val == "":
135
+ lines.append(f"{indent}{key};")
136
+ else:
137
+ lines.append(f"{indent}{key}:{val};")
138
+ return lines
139
+
140
+
141
+ def _emit_node(node: Dict[str, Any], indent: str = " ") -> List[str]:
142
+ name = node.get("name", "node")
143
+ props = node.get("props", {}) or {}
144
+ children = node.get("children", []) or []
145
+
146
+ lines = [f"{indent}{name}{{"]
147
+ lines.extend(_emit_props(props, indent + " "))
148
+ for child in children:
149
+ lines.extend(_emit_node(child, indent + " "))
150
+ lines.append(f"{indent}}}")
151
+ return lines
152
+
153
+
154
+ def scene_to_phg(scene: Dict[str, Any], include_setup: bool = True) -> str:
155
+ """
156
+ Convert AI scene JSON (dump) to normalized PHG script.
157
+ """
158
+ root_props = scene.get("props", {}) or {}
159
+ root_children = scene.get("children", []) or []
160
+
161
+ lines = ["{"]
162
+ if root_props:
163
+ # Preserve root-level props by creating a synthetic node.
164
+ root_node = {
165
+ "name": scene.get("name", "root"),
166
+ "props": root_props,
167
+ "children": root_children,
168
+ }
169
+ lines.extend(_emit_node(root_node, indent=" "))
170
+ else:
171
+ for child in root_children:
172
+ lines.extend(_emit_node(child, indent=" "))
173
+ lines.append("}")
174
+ if include_setup:
175
+ lines.append("setup_draw();")
176
+ return "\n".join(lines)
177
+
178
+
179
+ def compile_ai_phg(script: str, ai_root: Optional[str] = None, include_setup: bool = True) -> str:
180
+ scene = dump_scene(script, ai_root=ai_root)
181
+ return scene_to_phg(scene, include_setup=include_setup)
182
+
183
+
184
+ def vis_ai(script: str, ai_root: Optional[str] = None) -> None:
185
+ phg_script = compile_ai_phg(script, ai_root=ai_root, include_setup=True)
186
+ _vis(phg_script)
187
+
188
+
189
+ def image_ai(script: str, filename: str = "shot.png", ai_root: Optional[str] = None) -> None:
190
+ phg_script = compile_ai_phg(script, ai_root=ai_root, include_setup=True)
191
+ _image(phg_script, filename=filename)
192
+
193
+
194
+ def export_ai_obj(script: str, out_obj: str, ai_root: Optional[str] = None) -> str:
195
+ try:
196
+ ai = _load_ai_module(ai_root)
197
+ engine_mod = importlib.import_module("phg_ai.engine")
198
+ engine = engine_mod.Engine()
199
+ engine.run(script)
200
+ if "setup" not in engine.calls:
201
+ engine.setup()
202
+ if "draw" not in engine.calls:
203
+ engine.draw()
204
+ engine.export_obj(out_obj)
205
+ finally:
206
+ pass
207
+ return out_obj
208
+
209
+
210
+ def web_view_ai(
211
+ script: str,
212
+ out_html: str,
213
+ out_obj: Optional[str] = None,
214
+ ai_root: Optional[str] = None,
215
+ title: str = "PHG Web Viewer",
216
+ ) -> str:
217
+ if out_obj is None:
218
+ base, _ = os.path.splitext(out_html)
219
+ out_obj = base + ".obj"
220
+ export_ai_obj(script, out_obj, ai_root=ai_root)
221
+ write_three_view_html(out_obj, out_html, title=title)
222
+ return out_html