cuju-render 0.1.0__py3-none-any.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 (382) hide show
  1. cuju/render/__init__.py +759 -0
  2. cuju/render/__main__.py +1065 -0
  3. cuju/render/_export/__init__.py +3 -0
  4. cuju/render/_export/feed.py +542 -0
  5. cuju/render/_export/sizes.py +157 -0
  6. cuju/render/_export/video.py +1618 -0
  7. cuju/render/_export/video_jobs.py +408 -0
  8. cuju/render/_format/__init__.py +3 -0
  9. cuju/render/_format/annotations.py +235 -0
  10. cuju/render/_format/codec.py +307 -0
  11. cuju/render/_format/keep.py +121 -0
  12. cuju/render/_format/recording.py +860 -0
  13. cuju/render/_format/writer.py +54 -0
  14. cuju/render/_guide/__init__.py +3 -0
  15. cuju/render/_guide/doctor.py +523 -0
  16. cuju/render/_guide/help.py +62 -0
  17. cuju/render/_guide/tutorial.py +254 -0
  18. cuju/render/_http/__init__.py +3 -0
  19. cuju/render/_http/commands.py +57 -0
  20. cuju/render/_http/headers.py +103 -0
  21. cuju/render/_http/launch.py +500 -0
  22. cuju/render/_http/launchers.py +408 -0
  23. cuju/render/_http/pwa.py +128 -0
  24. cuju/render/_http/server.py +2105 -0
  25. cuju/render/_http/window.py +360 -0
  26. cuju/render/_moments/__init__.py +3 -0
  27. cuju/render/_moments/captions.py +284 -0
  28. cuju/render/_moments/events.py +1123 -0
  29. cuju/render/_moments/search.py +694 -0
  30. cuju/render/_packages/__init__.py +3 -0
  31. cuju/render/_packages/glsl.py +746 -0
  32. cuju/render/_packages/loudness.py +334 -0
  33. cuju/render/_packages/pack.py +1959 -0
  34. cuju/render/_packages/presentation.py +1376 -0
  35. cuju/render/_packages/vocabulary.py +609 -0
  36. cuju/render/_playing/__init__.py +3 -0
  37. cuju/render/_playing/achievements.py +463 -0
  38. cuju/render/_playing/bench.py +609 -0
  39. cuju/render/_playing/challenges.py +1813 -0
  40. cuju/render/_playing/demo.py +323 -0
  41. cuju/render/_playing/draw.py +211 -0
  42. cuju/render/_playing/errors.py +20 -0
  43. cuju/render/_playing/game.py +645 -0
  44. cuju/render/_playing/limits.py +339 -0
  45. cuju/render/_playing/play.py +926 -0
  46. cuju/render/_playing/policy_worker.py +250 -0
  47. cuju/render/_playing/strict.py +810 -0
  48. cuju/render/_registry/__init__.py +3 -0
  49. cuju/render/_registry/clips.py +394 -0
  50. cuju/render/_registry/joints.py +108 -0
  51. cuju/render/_registry/teams.py +2058 -0
  52. cuju/render/_store/__init__.py +3 -0
  53. cuju/render/_store/home.py +70 -0
  54. cuju/render/_store/library.py +604 -0
  55. cuju/render/_store/samples.py +163 -0
  56. cuju/render/_text/__init__.py +3 -0
  57. cuju/render/_text/languages.py +637 -0
  58. cuju/render/_text/messages.py +1396 -0
  59. cuju/render/_tournaments/__init__.py +3 -0
  60. cuju/render/_tournaments/results.py +547 -0
  61. cuju/render/_tournaments/tournament.py +2742 -0
  62. cuju/render/_tournaments/tournament_cli.py +587 -0
  63. cuju/render/_tournaments/tournament_runner.py +1975 -0
  64. cuju/render/_version.py +6 -0
  65. cuju/render/_watch/__init__.py +3 -0
  66. cuju/render/_watch/grid.py +265 -0
  67. cuju/render/_watch/live.py +664 -0
  68. cuju/render/_watch/notebook.py +79 -0
  69. cuju/render/_watch/show.py +171 -0
  70. cuju/render/samples/sample-11v11.cjr +0 -0
  71. cuju/render/samples/sample-5v5.cjr +0 -0
  72. cuju/render/samples/teams/starter/main.py +33 -0
  73. cuju/render/scenarios/benchmark_full_game_11_vs_11_easy.py +46 -0
  74. cuju/render/scenarios/benchmark_full_game_11_vs_11_hard.py +46 -0
  75. cuju/render/scenarios/benchmark_full_game_11_vs_11_medium.py +46 -0
  76. cuju/render/scenarios/benchmark_full_game_5_vs_5_easy.py +34 -0
  77. cuju/render/scenarios/benchmark_full_game_5_vs_5_hard.py +34 -0
  78. cuju/render/scenarios/benchmark_full_game_5_vs_5_medium.py +34 -0
  79. cuju/render/web/assets/adboard_polygon.webp +0 -0
  80. cuju/render/web/assets/adboard_your_ad_here.webp +0 -0
  81. cuju/render/web/assets/animations/kaykit-rig-medium-combatmelee.glb +0 -0
  82. cuju/render/web/assets/animations/kaykit-rig-medium-general.glb +0 -0
  83. cuju/render/web/assets/animations/kaykit-rig-medium-movementadvanced.glb +0 -0
  84. cuju/render/web/assets/animations/kaykit-rig-medium-movementbasic.glb +0 -0
  85. cuju/render/web/assets/animations/kaykit-rig-medium-simulation.glb +0 -0
  86. cuju/render/web/assets/animations/kaykit-rig-medium-special.glb +0 -0
  87. cuju/render/web/assets/ball.glb +0 -0
  88. cuju/render/web/assets/challenges/3_vs_1_with_keeper.mp4 +0 -0
  89. cuju/render/web/assets/challenges/3_vs_1_with_keeper.webp +0 -0
  90. cuju/render/web/assets/challenges/corner.mp4 +0 -0
  91. cuju/render/web/assets/challenges/corner.webp +0 -0
  92. cuju/render/web/assets/challenges/counterattack_easy.mp4 +0 -0
  93. cuju/render/web/assets/challenges/counterattack_easy.webp +0 -0
  94. cuju/render/web/assets/challenges/counterattack_hard.mp4 +0 -0
  95. cuju/render/web/assets/challenges/counterattack_hard.webp +0 -0
  96. cuju/render/web/assets/challenges/empty_goal.mp4 +0 -0
  97. cuju/render/web/assets/challenges/empty_goal.webp +0 -0
  98. cuju/render/web/assets/challenges/empty_goal_close.mp4 +0 -0
  99. cuju/render/web/assets/challenges/empty_goal_close.webp +0 -0
  100. cuju/render/web/assets/challenges/manifest.json +375 -0
  101. cuju/render/web/assets/challenges/one_on_one.mp4 +0 -0
  102. cuju/render/web/assets/challenges/one_on_one.webp +0 -0
  103. cuju/render/web/assets/challenges/one_on_one_hard.mp4 +0 -0
  104. cuju/render/web/assets/challenges/one_on_one_hard.webp +0 -0
  105. cuju/render/web/assets/challenges/pass_and_shoot_with_keeper.mp4 +0 -0
  106. cuju/render/web/assets/challenges/pass_and_shoot_with_keeper.webp +0 -0
  107. cuju/render/web/assets/challenges/run_pass_and_shoot_with_keeper.mp4 +0 -0
  108. cuju/render/web/assets/challenges/run_pass_and_shoot_with_keeper.webp +0 -0
  109. cuju/render/web/assets/challenges/run_to_score.mp4 +0 -0
  110. cuju/render/web/assets/challenges/run_to_score.webp +0 -0
  111. cuju/render/web/assets/challenges/run_to_score_with_keeper.mp4 +0 -0
  112. cuju/render/web/assets/challenges/run_to_score_with_keeper.webp +0 -0
  113. cuju/render/web/assets/challenges/single_goal_versus_lazy.mp4 +0 -0
  114. cuju/render/web/assets/challenges/single_goal_versus_lazy.webp +0 -0
  115. cuju/render/web/assets/crowd.webp +0 -0
  116. cuju/render/web/assets/crowd_normal.webp +0 -0
  117. cuju/render/web/assets/cuju-logo-384.png +0 -0
  118. cuju/render/web/assets/cuju-logo.png +0 -0
  119. cuju/render/web/assets/cuju-logo.svg +46 -0
  120. cuju/render/web/assets/cuju-mark-light.svg +33 -0
  121. cuju/render/web/assets/cuju-mark.svg +33 -0
  122. cuju/render/web/assets/goal.glb +0 -0
  123. cuju/render/web/assets/grass.webp +0 -0
  124. cuju/render/web/assets/hair_black.png +0 -0
  125. cuju/render/web/assets/hair_blonde.png +0 -0
  126. cuju/render/web/assets/hair_brown.png +0 -0
  127. cuju/render/web/assets/hair_darkblonde.png +0 -0
  128. cuju/render/web/assets/hair_long01.glb +0 -0
  129. cuju/render/web/assets/hair_long02.glb +0 -0
  130. cuju/render/web/assets/hair_medium01.glb +0 -0
  131. cuju/render/web/assets/hair_red.png +0 -0
  132. cuju/render/web/assets/hair_short01.glb +0 -0
  133. cuju/render/web/assets/hair_short02.glb +0 -0
  134. cuju/render/web/assets/icons/cuju-192.png +0 -0
  135. cuju/render/web/assets/icons/cuju-512.png +0 -0
  136. cuju/render/web/assets/icons/cuju-maskable-512.png +0 -0
  137. cuju/render/web/assets/kit_goalkeeper.webp +0 -0
  138. cuju/render/web/assets/kit_mask.png +0 -0
  139. cuju/render/web/assets/kit_normal.webp +0 -0
  140. cuju/render/web/assets/manifest.json +601 -0
  141. cuju/render/web/assets/models/kaykit-barbarian.glb +0 -0
  142. cuju/render/web/assets/models/kaykit-barbarian.json +23 -0
  143. cuju/render/web/assets/models/kaykit-knight.glb +0 -0
  144. cuju/render/web/assets/models/kaykit-knight.json +23 -0
  145. cuju/render/web/assets/models/kaykit-mage.glb +0 -0
  146. cuju/render/web/assets/models/kaykit-mage.json +23 -0
  147. cuju/render/web/assets/models/kaykit-mannequin-medium.glb +0 -0
  148. cuju/render/web/assets/models/kaykit-mannequin-medium.json +23 -0
  149. cuju/render/web/assets/models/kaykit-ranger.glb +0 -0
  150. cuju/render/web/assets/models/kaykit-ranger.json +23 -0
  151. cuju/render/web/assets/models/kaykit-rogue-hooded.glb +0 -0
  152. cuju/render/web/assets/models/kaykit-rogue-hooded.json +23 -0
  153. cuju/render/web/assets/models/kaykit-rogue.glb +0 -0
  154. cuju/render/web/assets/models/kaykit-rogue.json +23 -0
  155. cuju/render/web/assets/models/kaykit-skeleton-mage.glb +0 -0
  156. cuju/render/web/assets/models/kaykit-skeleton-mage.json +23 -0
  157. cuju/render/web/assets/models/kaykit-skeleton-minion.glb +0 -0
  158. cuju/render/web/assets/models/kaykit-skeleton-minion.json +23 -0
  159. cuju/render/web/assets/models/kaykit-skeleton-rogue.glb +0 -0
  160. cuju/render/web/assets/models/kaykit-skeleton-rogue.json +23 -0
  161. cuju/render/web/assets/models/kaykit-skeleton-warrior.glb +0 -0
  162. cuju/render/web/assets/models/kaykit-skeleton-warrior.json +23 -0
  163. cuju/render/web/assets/pitch.webp +0 -0
  164. cuju/render/web/assets/pitch_normal.webp +0 -0
  165. cuju/render/web/assets/player.glb +0 -0
  166. cuju/render/web/assets/shoe.webp +0 -0
  167. cuju/render/web/assets/shoe_sole.png +0 -0
  168. cuju/render/web/assets/skin_01.png +0 -0
  169. cuju/render/web/assets/skin_02.png +0 -0
  170. cuju/render/web/assets/skin_03.png +0 -0
  171. cuju/render/web/assets/skin_04.png +0 -0
  172. cuju/render/web/assets/sounds/applause.ogg +0 -0
  173. cuju/render/web/assets/sounds/beach-wave-1.ogg +0 -0
  174. cuju/render/web/assets/sounds/beach-wave-2.ogg +0 -0
  175. cuju/render/web/assets/sounds/beach-wave-3.ogg +0 -0
  176. cuju/render/web/assets/sounds/beach-wave-4.ogg +0 -0
  177. cuju/render/web/assets/sounds/city-horn.ogg +0 -0
  178. cuju/render/web/assets/sounds/city-loop.ogg +0 -0
  179. cuju/render/web/assets/sounds/city-siren.ogg +0 -0
  180. cuju/render/web/assets/sounds/crowd-cheer.ogg +0 -0
  181. cuju/render/web/assets/sounds/crowd-loop.ogg +0 -0
  182. cuju/render/web/assets/sounds/crowd-ooh.ogg +0 -0
  183. cuju/render/web/assets/sounds/gulls.ogg +0 -0
  184. cuju/render/web/assets/sounds/neon-sting.ogg +0 -0
  185. cuju/render/web/assets/sounds/rain-loop.ogg +0 -0
  186. cuju/render/web/assets/sounds/sounds.json +46 -0
  187. cuju/render/web/assets/sounds/space-beep.ogg +0 -0
  188. cuju/render/web/assets/sounds/space-hum.ogg +0 -0
  189. cuju/render/web/assets/sounds/space-radio.ogg +0 -0
  190. cuju/render/web/assets/sounds/whistle-long.ogg +0 -0
  191. cuju/render/web/assets/sounds/whistle-short.ogg +0 -0
  192. cuju/render/web/assets/sounds/wind-loop.ogg +0 -0
  193. cuju/render/web/easy.css +357 -0
  194. cuju/render/web/export.html +23 -0
  195. cuju/render/web/feed.css +262 -0
  196. cuju/render/web/feed.html +28 -0
  197. cuju/render/web/flat.css +120 -0
  198. cuju/render/web/home.css +837 -0
  199. cuju/render/web/index.html +373 -0
  200. cuju/render/web/js/boot.js +50 -0
  201. cuju/render/web/js/broadcast/audio.js +2141 -0
  202. cuju/render/web/js/broadcast/celebrate.js +1238 -0
  203. cuju/render/web/js/broadcast/decisions.js +609 -0
  204. cuju/render/web/js/broadcast/hud.js +352 -0
  205. cuju/render/web/js/broadcast/show.js +3614 -0
  206. cuju/render/web/js/broadcast/transition.js +2231 -0
  207. cuju/render/web/js/broadcast/voices.js +153 -0
  208. cuju/render/web/js/capture.js +101 -0
  209. cuju/render/web/js/core/accessibility.js +90 -0
  210. cuju/render/web/js/core/api.js +429 -0
  211. cuju/render/web/js/core/comfort.js +135 -0
  212. cuju/render/web/js/core/i18n.js +705 -0
  213. cuju/render/web/js/core/icons.js +167 -0
  214. cuju/render/web/js/core/input-settings.js +156 -0
  215. cuju/render/web/js/core/keys.js +277 -0
  216. cuju/render/web/js/core/language-ui.js +125 -0
  217. cuju/render/web/js/core/menu.js +853 -0
  218. cuju/render/web/js/core/names.js +113 -0
  219. cuju/render/web/js/core/page-structure.js +110 -0
  220. cuju/render/web/js/core/scenarios.js +109 -0
  221. cuju/render/web/js/core/spoilers.js +236 -0
  222. cuju/render/web/js/core/typeahead.js +38 -0
  223. cuju/render/web/js/export/dom-picture.js +330 -0
  224. cuju/render/web/js/export/export-host.js +97 -0
  225. cuju/render/web/js/export/feed-dialog.js +191 -0
  226. cuju/render/web/js/export/feed-params.js +266 -0
  227. cuju/render/web/js/export/feed.js +363 -0
  228. cuju/render/web/js/export/mp4-mux.js +295 -0
  229. cuju/render/web/js/export/photo-core.js +313 -0
  230. cuju/render/web/js/export/photo.js +1314 -0
  231. cuju/render/web/js/export/safe-frame.js +59 -0
  232. cuju/render/web/js/export/size-fields.js +103 -0
  233. cuju/render/web/js/export/sizes.js +178 -0
  234. cuju/render/web/js/export/video-boot.js +55 -0
  235. cuju/render/web/js/export/video-browser.js +325 -0
  236. cuju/render/web/js/export/video-export.js +417 -0
  237. cuju/render/web/js/export/video-plan.js +207 -0
  238. cuju/render/web/js/export/video-range.js +185 -0
  239. cuju/render/web/js/export/webm-mux.js +198 -0
  240. cuju/render/web/js/feed-boot.js +151 -0
  241. cuju/render/web/js/feed-frame.js +101 -0
  242. cuju/render/web/js/help/doctor.js +488 -0
  243. cuju/render/web/js/help/firstrun.js +379 -0
  244. cuju/render/web/js/help/help-center.js +438 -0
  245. cuju/render/web/js/help/install-offer.js +164 -0
  246. cuju/render/web/js/help/install-state.js +104 -0
  247. cuju/render/web/js/help/lessons-core.js +207 -0
  248. cuju/render/web/js/help/lessons.js +463 -0
  249. cuju/render/web/js/help/palette.js +584 -0
  250. cuju/render/web/js/help/pwa.js +257 -0
  251. cuju/render/web/js/help/tour-core.js +241 -0
  252. cuju/render/web/js/help/tour.js +461 -0
  253. cuju/render/web/js/main.js +2513 -0
  254. cuju/render/web/js/pages/draw.js +188 -0
  255. cuju/render/web/js/pages/fieldpage.js +530 -0
  256. cuju/render/web/js/pages/home.js +521 -0
  257. cuju/render/web/js/pages/matches.js +779 -0
  258. cuju/render/web/js/pages/moments-ui.js +359 -0
  259. cuju/render/web/js/pages/queue-filters.js +63 -0
  260. cuju/render/web/js/pages/recording-groups.js +80 -0
  261. cuju/render/web/js/pages/recordings.js +1069 -0
  262. cuju/render/web/js/play/bench.js +347 -0
  263. cuju/render/web/js/play/challenges.js +1302 -0
  264. cuju/render/web/js/play/medals.js +127 -0
  265. cuju/render/web/js/play/play.js +1953 -0
  266. cuju/render/web/js/play/teasers.js +196 -0
  267. cuju/render/web/js/play/touch.js +350 -0
  268. cuju/render/web/js/play/tournament-layout.js +487 -0
  269. cuju/render/web/js/play/tournament-results.js +441 -0
  270. cuju/render/web/js/play/tournament-strict.js +560 -0
  271. cuju/render/web/js/play/tournament.js +2585 -0
  272. cuju/render/web/js/players/animate.js +972 -0
  273. cuju/render/web/js/players/clips.js +224 -0
  274. cuju/render/web/js/players/kaykit.js +162 -0
  275. cuju/render/web/js/players/kits.js +676 -0
  276. cuju/render/web/js/players/number-patch.js +82 -0
  277. cuju/render/web/js/players/players.js +2694 -0
  278. cuju/render/web/js/players/recolor.js +893 -0
  279. cuju/render/web/js/players/retarget.js +325 -0
  280. cuju/render/web/js/players/rig-numbers.js +174 -0
  281. cuju/render/web/js/presentation/animator.js +231 -0
  282. cuju/render/web/js/presentation/assign.js +85 -0
  283. cuju/render/web/js/presentation/behaviors.js +440 -0
  284. cuju/render/web/js/presentation/budget.js +209 -0
  285. cuju/render/web/js/presentation/catalog.js +1674 -0
  286. cuju/render/web/js/presentation/clocks.js +72 -0
  287. cuju/render/web/js/presentation/commands.js +301 -0
  288. cuju/render/web/js/presentation/contract.js +240 -0
  289. cuju/render/web/js/presentation/effects.js +904 -0
  290. cuju/render/web/js/presentation/flash.js +605 -0
  291. cuju/render/web/js/presentation/freeze-worklet.js +22 -0
  292. cuju/render/web/js/presentation/glsl.js +464 -0
  293. cuju/render/web/js/presentation/host.js +323 -0
  294. cuju/render/web/js/presentation/index.js +2066 -0
  295. cuju/render/web/js/presentation/loudness-worklet.js +235 -0
  296. cuju/render/web/js/presentation/loudness.js +740 -0
  297. cuju/render/web/js/presentation/moments.js +536 -0
  298. cuju/render/web/js/presentation/post.js +327 -0
  299. cuju/render/web/js/presentation/preview.js +180 -0
  300. cuju/render/web/js/presentation/protocol.js +174 -0
  301. cuju/render/web/js/presentation/reach.js +158 -0
  302. cuju/render/web/js/presentation/rigging.js +130 -0
  303. cuju/render/web/js/presentation/sandbox.js +157 -0
  304. cuju/render/web/js/presentation/shaders.js +235 -0
  305. cuju/render/web/js/presentation/stage.js +402 -0
  306. cuju/render/web/js/presentation/teamaudio.js +722 -0
  307. cuju/render/web/js/presentation/tracks.js +197 -0
  308. cuju/render/web/js/presentation/values.js +81 -0
  309. cuju/render/web/js/recording/annotation-data.js +203 -0
  310. cuju/render/web/js/recording/captions.js +491 -0
  311. cuju/render/web/js/recording/codec.js +185 -0
  312. cuju/render/web/js/recording/decode-worker.js +70 -0
  313. cuju/render/web/js/recording/decode.js +94 -0
  314. cuju/render/web/js/recording/episodes.js +46 -0
  315. cuju/render/web/js/recording/format.js +461 -0
  316. cuju/render/web/js/recording/live.js +348 -0
  317. cuju/render/web/js/recording/moments-query.js +59 -0
  318. cuju/render/web/js/recording/moments.js +149 -0
  319. cuju/render/web/js/recording/pose.js +86 -0
  320. cuju/render/web/js/recording/timeline.js +275 -0
  321. cuju/render/web/js/teams/art.js +50 -0
  322. cuju/render/web/js/teams/clip-editor.js +293 -0
  323. cuju/render/web/js/teams/editor.js +1979 -0
  324. cuju/render/web/js/teams/library.js +344 -0
  325. cuju/render/web/js/teams/painter.js +633 -0
  326. cuju/render/web/js/teams/surprise-ui.js +195 -0
  327. cuju/render/web/js/teams/surprise.js +497 -0
  328. cuju/render/web/js/teams/team-check.js +127 -0
  329. cuju/render/web/js/watch/annotations.js +270 -0
  330. cuju/render/web/js/watch/flat.js +366 -0
  331. cuju/render/web/js/watch/grid.js +436 -0
  332. cuju/render/web/js/watch/pitch2d.js +289 -0
  333. cuju/render/web/js/watch/player-tools.js +192 -0
  334. cuju/render/web/js/watch/presets.js +201 -0
  335. cuju/render/web/js/world/arenas.js +997 -0
  336. cuju/render/web/js/world/ball.js +204 -0
  337. cuju/render/web/js/world/cameras.js +982 -0
  338. cuju/render/web/js/world/crowd.js +376 -0
  339. cuju/render/web/js/world/field.js +227 -0
  340. cuju/render/web/js/world/framing.js +145 -0
  341. cuju/render/web/js/world/occlusion.js +48 -0
  342. cuju/render/web/js/world/pitch.js +703 -0
  343. cuju/render/web/js/world/scene.js +395 -0
  344. cuju/render/web/js/world/sky.js +325 -0
  345. cuju/render/web/js/world/stadium.js +1262 -0
  346. cuju/render/web/js/world/vendor-sky.js +367 -0
  347. cuju/render/web/js/world/weather.js +264 -0
  348. cuju/render/web/languages/en.json +4750 -0
  349. cuju/render/web/lessons.json +137 -0
  350. cuju/render/web/manifest.webmanifest +23 -0
  351. cuju/render/web/style.css +8399 -0
  352. cuju/render/web/sw.js +235 -0
  353. cuju/render/web/vendor/fabric/LICENSE +16 -0
  354. cuju/render/web/vendor/fabric/fabric.min.mjs +1 -0
  355. cuju/render/web/vendor/lucide/LICENSE +43 -0
  356. cuju/render/web/vendor/lucide/icons.js +141 -0
  357. cuju/render/web/vendor/three/LICENSE +21 -0
  358. cuju/render/web/vendor/three/build/three.core.js +60586 -0
  359. cuju/render/web/vendor/three/build/three.module.js +19719 -0
  360. cuju/render/web/vendor/three/examples/jsm/loaders/GLTFLoader.js +4925 -0
  361. cuju/render/web/vendor/three/examples/jsm/postprocessing/EffectComposer.js +365 -0
  362. cuju/render/web/vendor/three/examples/jsm/postprocessing/MaskPass.js +195 -0
  363. cuju/render/web/vendor/three/examples/jsm/postprocessing/OutputPass.js +148 -0
  364. cuju/render/web/vendor/three/examples/jsm/postprocessing/Pass.js +191 -0
  365. cuju/render/web/vendor/three/examples/jsm/postprocessing/RenderPass.js +193 -0
  366. cuju/render/web/vendor/three/examples/jsm/postprocessing/ShaderPass.js +135 -0
  367. cuju/render/web/vendor/three/examples/jsm/postprocessing/UnrealBloomPass.js +541 -0
  368. cuju/render/web/vendor/three/examples/jsm/shaders/CopyShader.js +52 -0
  369. cuju/render/web/vendor/three/examples/jsm/shaders/LuminosityHighPassShader.js +68 -0
  370. cuju/render/web/vendor/three/examples/jsm/shaders/OutputShader.js +103 -0
  371. cuju/render/web/vendor/three/examples/jsm/utils/BufferGeometryUtils.js +1501 -0
  372. cuju/render/web/vendor/three/examples/jsm/utils/SkeletonUtils.js +496 -0
  373. cuju_render-0.1.0.dist-info/METADATA +116 -0
  374. cuju_render-0.1.0.dist-info/RECORD +382 -0
  375. cuju_render-0.1.0.dist-info/WHEEL +4 -0
  376. cuju_render-0.1.0.dist-info/licenses/LICENSE +202 -0
  377. cuju_render-0.1.0.dist-info/licenses/LICENSES/CC-BY-4.0.txt +396 -0
  378. cuju_render-0.1.0.dist-info/licenses/LICENSES/CC0-1.0.txt +127 -0
  379. cuju_render-0.1.0.dist-info/licenses/LICENSES/ISC.txt +16 -0
  380. cuju_render-0.1.0.dist-info/licenses/LICENSES/MIT.txt +24 -0
  381. cuju_render-0.1.0.dist-info/licenses/LICENSES/Unlicense.txt +13 -0
  382. cuju_render-0.1.0.dist-info/licenses/NOTICE +35 -0
@@ -0,0 +1,1376 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """The presentation package of a team, what the page shows of it beyond its kit and roster.
5
+
6
+ A team package may carry the folder `presentation` in its `cuju-team` folder, with the manifest
7
+ `presentation.json` of the presentation contract and the files it names, models, clips, textures,
8
+ shaders, sounds and a worker module, in subfolders as the author likes. The contract, version 1.1,
9
+ is described in docs/presentation.md, and a package of 1.0 reads as it is. Everything here is
10
+ presentation alone, the engine never reads it, so a match plays bit for bit the same with or
11
+ without a package.
12
+
13
+ The manifest and every file are checked when a team is imported and again when it is exported and
14
+ served, as the other files of a team are. A part of the manifest that fails its check is left out
15
+ with a warning, and the page draws that part as it would without a package. A manifest of a newer
16
+ contract stays on disk untouched and the page draws the team in its stock look.
17
+
18
+ The names of events, reflex actions, effects, sound and features live in `_vocabulary`, apart
19
+ from this stable core, since later renderer work adds to them.
20
+
21
+ Developer mode serves the package of a team from a folder of the user's own choosing, read afresh
22
+ on every request, so an author sees each change at once. It is off unless the file
23
+ `developer.json` in the renderer's home names such a folder, and an imported archive never turns
24
+ it on.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import contextlib
30
+ import itertools
31
+ import json
32
+ import re
33
+ import struct
34
+ from pathlib import Path, PurePosixPath
35
+ from typing import Any
36
+
37
+ from cuju.errors import ArgumentError
38
+
39
+ from .._registry import teams as _teams
40
+ from .._store import home as _home
41
+ from . import glsl as _glsl
42
+ from . import vocabulary as _vocabulary
43
+
44
+ CONTRACT = '1.1'
45
+ MAJOR, MINOR = 1, 1
46
+ FOLDER = 'presentation'
47
+ MANIFEST = 'presentation.json'
48
+ DEVELOPER_FILE = 'developer.json'
49
+ SIDES_FILE = 'presentation-sides.json'
50
+ SIDES = ('left', 'right')
51
+
52
+ MAXIMUM_MANIFEST_BYTES = 256 * 1024
53
+ MAXIMUM_FILES = 256
54
+ MAXIMUM_TOTAL_BYTES = 80 * 1024 * 1024
55
+ MAXIMUM_DEPTH = 4
56
+ # The largest file of each kind, by its extension.
57
+ MAXIMUM_BYTES = {
58
+ '.glb': 30 * 1024 * 1024,
59
+ '.png': 16 * 1024 * 1024,
60
+ '.jpg': 16 * 1024 * 1024,
61
+ '.webp': 16 * 1024 * 1024,
62
+ '.ktx2': 30 * 1024 * 1024,
63
+ '.ogg': 16 * 1024 * 1024,
64
+ '.mp3': 16 * 1024 * 1024,
65
+ '.wav': 30 * 1024 * 1024,
66
+ '.js': 2 * 1024 * 1024,
67
+ '.json': 2 * 1024 * 1024,
68
+ '.glsl': 256 * 1024,
69
+ '.wasm': 8 * 1024 * 1024,
70
+ }
71
+ CONTENT_TYPES = {
72
+ '.glb': 'model/gltf-binary',
73
+ '.png': 'image/png',
74
+ '.jpg': 'image/jpeg',
75
+ '.webp': 'image/webp',
76
+ '.ktx2': 'image/ktx2',
77
+ '.ogg': 'audio/ogg',
78
+ '.mp3': 'audio/mpeg',
79
+ '.wav': 'audio/wav',
80
+ '.js': 'text/javascript',
81
+ '.json': 'application/json',
82
+ '.glsl': 'text/plain',
83
+ '.wasm': 'application/wasm',
84
+ }
85
+ # One part of a file's path inside the package, lowercase.
86
+ _PART = re.compile(r'[a-z0-9][a-z0-9_.-]{0,59}')
87
+ _ID = re.compile(r'[A-Za-z0-9_.-]{1,40}')
88
+ # The pieces of JavaScript that `module_problem` tells apart, to find imports and re-exports.
89
+ _LINE_ENDS = '\n\r\u2028\u2029'
90
+ _NUMBER = re.compile(
91
+ r'0[xXoObB][0-9a-fA-F_]*n?|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?[\d_]*)?n?'
92
+ )
93
+ _ESCAPE = re.compile(r'\\u(?:\{([0-9a-fA-F]{1,6})\}|([0-9a-fA-F]{4}))')
94
+ _PUNCTUATORS = ('>>>=', '...', '=>', '++', '--')
95
+ # The words after which a slash starts a regular expression rather than a division.
96
+ _BEFORE_REGEX = frozenset(
97
+ (
98
+ 'return',
99
+ 'typeof',
100
+ 'instanceof',
101
+ 'in',
102
+ 'of',
103
+ 'new',
104
+ 'delete',
105
+ 'void',
106
+ 'throw',
107
+ 'case',
108
+ 'do',
109
+ 'else',
110
+ 'yield',
111
+ 'await',
112
+ 'extends',
113
+ )
114
+ )
115
+ # The words of a statement whose head in parentheses a regular expression may follow.
116
+ _HEADS = frozenset(('if', 'while', 'for', 'with'))
117
+ _DOTS = (('punct', '.'), ('punct', '?.'))
118
+
119
+ DRIVERS = ('grf', 'grf+layers', 'team', 'worker')
120
+ ROOT_MOTION = ('ignore', 'cosmetic')
121
+ # The semantic roles a clip may play.
122
+ ROLES = (
123
+ 'idle.calm',
124
+ 'idle.alert',
125
+ 'move',
126
+ 'turn',
127
+ 'brake',
128
+ 'kick',
129
+ 'pass.short',
130
+ 'pass.long',
131
+ 'pass.high',
132
+ 'shot',
133
+ 'header',
134
+ 'volley',
135
+ 'slide',
136
+ 'trip',
137
+ 'catch',
138
+ 'parry',
139
+ 'dive.left',
140
+ 'dive.right',
141
+ 'throwIn',
142
+ 'restart.kickoff',
143
+ 'restart.goal_kick',
144
+ 'restart.free_kick',
145
+ 'restart.corner',
146
+ 'restart.throw_in',
147
+ 'restart.penalty',
148
+ 'trap',
149
+ 'deflect',
150
+ 'celebration',
151
+ 'reaction.win',
152
+ 'reaction.loss',
153
+ 'lineup',
154
+ 'salute',
155
+ 'lament',
156
+ 'recovery',
157
+ 'podium',
158
+ )
159
+ BEHAVIOURS = (
160
+ 'spin',
161
+ 'oscillate',
162
+ 'spring',
163
+ 'lookAt',
164
+ 'bank',
165
+ 'follow',
166
+ 'curve',
167
+ 'materialParam',
168
+ 'audioParam',
169
+ 'lightParam',
170
+ )
171
+ CHANNELS = ('x', 'y', 'z', 'rotX', 'rotY', 'rotZ', 'scale')
172
+ INPUTS = (
173
+ 'speed',
174
+ 'accel',
175
+ 'ballDistance',
176
+ 'excitement',
177
+ 'ceremony.amount',
178
+ 'ballX.attack',
179
+ 'alert',
180
+ )
181
+ CLOCKS = ('sim', 'cosmetic', 'ceremony')
182
+ QUALITIES = ('low', 'medium', 'high')
183
+ _SECTIONS = (
184
+ 'contract',
185
+ 'name',
186
+ 'requires',
187
+ 'prefers',
188
+ 'models',
189
+ 'rig',
190
+ 'clips',
191
+ 'behaviours',
192
+ 'materials',
193
+ 'effects',
194
+ 'audio',
195
+ 'reflexes',
196
+ 'worker',
197
+ 'reducedMotion',
198
+ 'quality',
199
+ 'lights',
200
+ 'post',
201
+ 'overlays',
202
+ )
203
+
204
+
205
+ def words(values: Any, last: str = 'or') -> str:
206
+ """Returns names as a list in words, such as `spin, oscillate or curve`."""
207
+ values = [str(value) for value in values]
208
+ if len(values) < 2:
209
+ return ''.join(values)
210
+ return f'{", ".join(values[:-1])} {last} {values[-1]}'
211
+
212
+
213
+ def _number(value: Any, low: float, high: float, name: str) -> float:
214
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not low <= value <= high:
215
+ raise ArgumentError(f'expected {name} from {low} to {high}, found {value!r}')
216
+ return float(value)
217
+
218
+
219
+ def _identifier(value: Any, name: str) -> str:
220
+ if not isinstance(value, str) or not _ID.fullmatch(value):
221
+ raise ArgumentError(f'expected {name} of up to 40 letters, digits, dots and underscores')
222
+ return value
223
+
224
+
225
+ def _text(value: Any, name: str, size: int = 80) -> str:
226
+ if not isinstance(value, str) or not 0 < len(value) <= size:
227
+ raise ArgumentError(f'expected {name} of 1 to {size} characters, found {value!r}')
228
+ return _teams._printable(value)
229
+
230
+
231
+ def _vector(value: Any, size: int, limit: float, name: str) -> list[float]:
232
+ if not isinstance(value, list) or len(value) != size:
233
+ raise ArgumentError(f'expected {name} as {size} numbers')
234
+ return [_number(v, -limit, limit, name) for v in value]
235
+
236
+
237
+ def _mapping(value: Any, size: int, name: str) -> dict[str, Any]:
238
+ if not isinstance(value, dict) or len(value) > size:
239
+ raise ArgumentError(f'expected {name} as a mapping of at most {size} entries')
240
+ return value
241
+
242
+
243
+ def _ignored(spec: dict[str, Any], known: set[str], what: str, warnings: list[str]) -> None:
244
+ warnings.extend(f'{what} ignores {key}' for key in sorted(set(spec) - known))
245
+
246
+
247
+ def _files(assets: dict[str, str]) -> Any:
248
+ """Returns a check that a value names a file of the package of one of the given kinds."""
249
+
250
+ def check(value: Any, name: str, suffixes: tuple[str, ...] | None = None) -> str:
251
+ if not isinstance(value, str) or value not in assets:
252
+ raise ArgumentError(f'expected {name} to name a file of the package, found {value!r}')
253
+ if suffixes and PurePosixPath(value).suffix not in suffixes:
254
+ raise ArgumentError(f'expected {name} to name a {"/".join(suffixes)} file')
255
+ return value
256
+
257
+ return check
258
+
259
+
260
+ def _selector(value: Any, name: str) -> dict[str, Any]:
261
+ spec = _mapping(value, 3, f'the selector of {name}')
262
+ out: dict[str, Any] = {}
263
+ if 'role' in spec:
264
+ if spec['role'] not in ('goalkeeper', 'outfield'):
265
+ raise ArgumentError(f'expected the role of {name} as goalkeeper or outfield')
266
+ out['role'] = spec['role']
267
+ for key in ('number', 'index'):
268
+ if key in spec:
269
+ items = spec[key] if isinstance(spec[key], list) else [spec[key]]
270
+ if not all(isinstance(i, int) and not isinstance(i, bool) for i in items):
271
+ raise ArgumentError(f'expected the {key} of {name} as integers')
272
+ out[key] = items
273
+ if set(spec) - {'role', 'number', 'index'}:
274
+ raise ArgumentError(f'expected {name} to select by role, number or index')
275
+ return out
276
+
277
+
278
+ def _models(value: Any, file: Any) -> dict[str, Any]:
279
+ spec = _mapping(value, 3, 'models')
280
+ out: dict[str, Any] = {}
281
+ for role in ('outfield', 'goalkeeper'):
282
+ if role in spec:
283
+ out[role] = file(spec[role], f'the {role} model', ('.glb',))
284
+ if 'byNumber' in spec:
285
+ numbers = _mapping(spec['byNumber'], 100, 'models by number')
286
+ out['byNumber'] = {}
287
+ for number, path in numbers.items():
288
+ if not str(number).isdigit() or not 0 <= int(number) <= 99:
289
+ raise ArgumentError(f'expected shirt numbers from 0 to 99, found {number!r}')
290
+ out['byNumber'][str(int(number))] = file(path, f'model {number}', ('.glb',))
291
+ if set(spec) - {'outfield', 'goalkeeper', 'byNumber'}:
292
+ raise ArgumentError('expected models by outfield, goalkeeper and byNumber')
293
+ return out
294
+
295
+
296
+ def _socket(name: str, spec: Any, warnings: list[str]) -> dict[str, Any]:
297
+ if not isinstance(spec, dict):
298
+ raise ArgumentError(f'expected socket {name} as a description')
299
+ item: dict[str, Any] = {
300
+ 'node': _text(spec['node'], 'a node name') if spec.get('node') else None,
301
+ 'offset': _vector(spec.get('offset', [0, 0, 0]), 3, 10, 'a socket offset'),
302
+ 'forward': _vector(spec.get('forward', [0, 0, 1]), 3, 1e3, 'a forward axis'),
303
+ 'up': _vector(spec.get('up', [0, 1, 0]), 3, 1e3, 'an up axis'),
304
+ 'rotation': _vector(spec.get('rotation', [0, 0, 0]), 3, 360, 'a socket rotation'),
305
+ }
306
+ forward, up = item['forward'], item['up']
307
+ if sum(c * c for c in forward) < 1e-12:
308
+ raise ArgumentError(f'expected socket {name} to have a forward axis')
309
+ cross = [
310
+ up[1] * forward[2] - up[2] * forward[1],
311
+ up[2] * forward[0] - up[0] * forward[2],
312
+ up[0] * forward[1] - up[1] * forward[0],
313
+ ]
314
+ if sum(c * c for c in cross) < 1e-12:
315
+ raise ArgumentError(f'expected socket {name} to have up apart from forward')
316
+ _ignored(spec, {'node', 'offset', 'forward', 'up', 'rotation'}, f'socket {name}', warnings)
317
+ return item
318
+
319
+
320
+ def _rig(value: Any, file: Any, warnings: list[str]) -> dict[str, Any]:
321
+ spec = _mapping(value, 16, 'rig')
322
+ out: dict[str, Any] = {}
323
+ driver = spec.get('driver', 'grf')
324
+ if isinstance(driver, str):
325
+ driver = {'outfield': driver, 'goalkeeper': driver}
326
+ if not isinstance(driver, dict) or not all(
327
+ role in ('outfield', 'goalkeeper') and d in DRIVERS for role, d in driver.items()
328
+ ):
329
+ raise ArgumentError(f'expected the drivers of the roles among {words(DRIVERS)}')
330
+ out['driver'] = dict(driver)
331
+ out['sockets'] = {}
332
+ for name, socket in _mapping(spec.get('sockets', {}), 64, 'sockets').items():
333
+ try:
334
+ out['sockets'][_identifier(name, 'the name of a socket')] = _socket(
335
+ name, socket, warnings
336
+ )
337
+ except ArgumentError as error:
338
+ warnings.append(f'socket {name} left out, {error}')
339
+ if 'bounds' in spec:
340
+ bounds = _mapping(spec['bounds'], 4, 'bounds')
341
+ out['bounds'] = {
342
+ 'radius': _number(bounds.get('radius'), 0.05, 5, 'the bounds radius'),
343
+ 'height': _number(bounds.get('height'), 0.2, 8, 'the bounds height'),
344
+ }
345
+ for key, high in (('top', 8), ('clearance', 2)):
346
+ if key in bounds:
347
+ out['bounds'][key] = _number(bounds[key], 0, high, f'the bounds {key}')
348
+ out['rootMotion'] = spec.get('rootMotion', 'ignore')
349
+ if out['rootMotion'] not in ROOT_MOTION:
350
+ raise ArgumentError(f'expected root motion among {words(ROOT_MOTION)}')
351
+ if 'blend' in spec:
352
+ out['blend'] = _number(spec['blend'], 0.01, 2, 'the blend time')
353
+ if 'joints' in spec:
354
+ joints = _mapping(spec['joints'], 16, 'joints')
355
+ if not all(
356
+ n in (*_teams.JOINTS, 'player') and isinstance(b, str) for n, b in joints.items()
357
+ ):
358
+ raise ArgumentError('expected joints that map GRF nodes to bone names')
359
+ out['joints'] = dict(joints)
360
+ out['attachments'] = {}
361
+ for name, item in _mapping(spec.get('attachments', {}), 32, 'attachments').items():
362
+ try:
363
+ if not isinstance(item, dict):
364
+ raise ArgumentError('expected a description')
365
+ socket = item.get('socket', 'root')
366
+ if socket != 'root' and socket not in out['sockets']:
367
+ raise ArgumentError('expected a socket of the rig')
368
+ entry = {
369
+ 'file': file(item.get('file'), f'attachment {name}', ('.glb',)),
370
+ 'socket': socket,
371
+ 'offset': _vector(item.get('offset', [0, 0, 0]), 3, 10, 'an offset'),
372
+ 'rotation': _vector(item.get('rotation', [0, 0, 0]), 3, 360, 'a rotation'),
373
+ 'scale': _number(item.get('scale', 1), 0.01, 10, 'a scale'),
374
+ 'shadows': bool(item.get('shadows', True)),
375
+ }
376
+ if 'when' in item:
377
+ entry['when'] = _selector(item['when'], f'attachment {name}')
378
+ out['attachments'][_identifier(name, 'the name of an attachment')] = entry
379
+ except ArgumentError as error:
380
+ warnings.append(f'attachment {name} left out, {error}')
381
+ if 'ik' in spec:
382
+ out['ik'] = {}
383
+ for name, item in _mapping(spec['ik'], 8, 'ik chains').items():
384
+ try:
385
+ out['ik'][_identifier(name, 'the name of a chain')] = _chain(item, out['sockets'])
386
+ except ArgumentError as error:
387
+ warnings.append(f'ik chain {name} left out, {error}')
388
+ if 'layers' in spec:
389
+ if not isinstance(spec['layers'], list) or len(spec['layers']) > 8:
390
+ raise ArgumentError('expected the layers of the rig as a list of at most 8')
391
+ out['layers'] = []
392
+ for index, item in enumerate(spec['layers'], 1):
393
+ try:
394
+ out['layers'].append(_layer(item))
395
+ except ArgumentError as error:
396
+ warnings.append(f'layer {index} left out, {error}')
397
+ known = {
398
+ 'driver',
399
+ 'sockets',
400
+ 'bounds',
401
+ 'rootMotion',
402
+ 'blend',
403
+ 'joints',
404
+ 'attachments',
405
+ 'ik',
406
+ 'layers',
407
+ }
408
+ _ignored(spec, known, 'rig', warnings)
409
+ return out
410
+
411
+
412
+ def _bones(value: Any, low: int, high: int, what: str) -> list[str]:
413
+ if not isinstance(value, list) or not low <= len(value) <= high:
414
+ raise ArgumentError(f'expected {what} as {low} to {high} bone names')
415
+ return [_text(bone, 'a bone name') for bone in value]
416
+
417
+
418
+ def _chain(item: Any, sockets: dict[str, Any]) -> dict[str, Any]:
419
+ """Checks one chain of the reach of section 7.2, solved by FABRIK toward the ball."""
420
+ if not isinstance(item, dict):
421
+ raise ArgumentError('expected a description')
422
+ out: dict[str, Any] = {
423
+ 'chain': _bones(item.get('chain'), 2, 8, 'the chain'),
424
+ 'target': 'ball',
425
+ 'window': _number(item.get('window', 0.15), 0, 0.5, 'the window'),
426
+ 'weight': _number(item.get('weight', 1), 0, 1, 'the weight'),
427
+ 'iterations': int(_number(item.get('iterations', 8), 1, 16, 'the iterations')),
428
+ }
429
+ if item.get('target', 'ball') != 'ball':
430
+ raise ArgumentError('expected the chain to reach the ball')
431
+ if 'socket' in item:
432
+ if item['socket'] not in sockets:
433
+ raise ArgumentError('expected the socket of the chain among the sockets of the rig')
434
+ out['socket'] = item['socket']
435
+ if 'roles' in item:
436
+ roles = item['roles'] if isinstance(item['roles'], list) else [item['roles']]
437
+ if not all(role in ROLES for role in roles):
438
+ raise ArgumentError('expected the roles of the chain among the clip roles')
439
+ out['roles'] = roles
440
+ if 'when' in item:
441
+ out['when'] = _selector(item['when'], 'the chain')
442
+ return out
443
+
444
+
445
+ def _layer(item: Any) -> dict[str, Any]:
446
+ """Checks one layer of the driver grf+layers, a clip over the bones of its mask."""
447
+ if not isinstance(item, dict) or not ('role' in item or 'clip' in item):
448
+ raise ArgumentError('expected a layer with a role or a clip')
449
+ out: dict[str, Any] = {'mask': _bones(item.get('mask'), 1, 32, 'the mask')}
450
+ if 'role' in item:
451
+ if item['role'] not in ROLES:
452
+ raise ArgumentError('expected the role of the layer among the clip roles')
453
+ out['role'] = item['role']
454
+ if 'clip' in item:
455
+ out['clip'] = _text(item['clip'], 'the clip of the layer')
456
+ out['weight'] = _curve(item.get('weight', 1), 'the weight of the layer')
457
+ out['rate'] = _number(item.get('rate', 1), 0.05, 8, 'the rate of the layer')
458
+ return out
459
+
460
+
461
+ def _clip(value: Any, name: str) -> dict[str, Any]:
462
+ if isinstance(value, str):
463
+ value = {'clip': value}
464
+ if not isinstance(value, dict):
465
+ raise ArgumentError(f'expected {name} as a clip name or a description of one')
466
+ out: dict[str, Any] = {'clip': _text(value.get('clip'), f'the clip of {name}')}
467
+ for key, low, high in (('speed', 0, 15), ('stride', 0.05, 50), ('rate', 0.05, 8)):
468
+ if key in value:
469
+ out[key] = _number(value[key], low, high, f'the {key} of {name}')
470
+ return out
471
+
472
+
473
+ def _clips(value: Any, warnings: list[str]) -> dict[str, Any]:
474
+ spec = _mapping(value, len(ROLES) + 16, 'clips')
475
+ out: dict[str, Any] = {}
476
+ for role, entry in spec.items():
477
+ if role not in ROLES:
478
+ warnings.append(f'clips ignore the unknown role {role}')
479
+ continue
480
+ if isinstance(entry, dict) and entry.get('space') == 'speed':
481
+ items = entry.get('clips')
482
+ if not isinstance(items, list) or not 0 < len(items) <= 8:
483
+ raise ArgumentError(f'expected one to eight clips in the speed space of {role}')
484
+ space = []
485
+ for item in items:
486
+ if isinstance(item, list) and 2 <= len(item) <= 3:
487
+ item = {
488
+ 'clip': item[0],
489
+ 'speed': item[1],
490
+ **({'stride': item[2]} if len(item) > 2 else {}),
491
+ }
492
+ space.append(_clip(item, role))
493
+ out[role] = {'space': 'speed', 'clips': sorted(space, key=lambda c: c.get('speed', 0))}
494
+ continue
495
+ entries = entry if isinstance(entry, list) else [entry]
496
+ if not 0 < len(entries) <= 8:
497
+ raise ArgumentError(f'expected one to eight clips for {role}')
498
+ out[role] = [_clip(item, role) for item in entries]
499
+ return out
500
+
501
+
502
+ def _curve(value: Any, name: str) -> Any:
503
+ """Checks a curve, a number or the keys of one input of the entity, or a sum of curves."""
504
+ if not isinstance(value, dict):
505
+ return _number(value, -1e4, 1e4, name)
506
+ if 'sum' in value:
507
+ if not isinstance(value['sum'], list) or not 0 < len(value['sum']) <= 8:
508
+ raise ArgumentError(f'expected the sum of {name} as one to eight curves')
509
+ return {'sum': [_curve(part, name) for part in value['sum']]}
510
+ source = value.get('input')
511
+ if not isinstance(source, str) or not (
512
+ source in INPUTS
513
+ or re.fullmatch(r'jointSpeed:.{1,80}', source)
514
+ or re.fullmatch(r'role:[a-z.]{1,40}', source)
515
+ ):
516
+ inputs = words([*INPUTS, 'jointSpeed', 'role'])
517
+ raise ArgumentError(f'expected an input of {name} among {inputs}')
518
+ out: dict[str, Any] = {'input': source}
519
+ if 'keys' in value:
520
+ keys = value['keys']
521
+ if not isinstance(keys, list) or not 0 < len(keys) <= 32:
522
+ raise ArgumentError(f'expected the keys of {name} as 1 to 32 points')
523
+ points = [_vector(key, 2, 1e6, f'a key of {name}') for key in keys]
524
+ if any(b[0] <= a[0] for a, b in itertools.pairwise(points)):
525
+ raise ArgumentError(f'expected the keys of {name} in rising order')
526
+ out['keys'] = points
527
+ return out
528
+
529
+
530
+ def _behaviour_name(spec: Any, index: int) -> str:
531
+ """Returns how messages name a behaviour, by its id or by its place counted from 1."""
532
+ identifier = spec.get('id') if isinstance(spec, dict) else None
533
+ return f'behaviour {identifier if isinstance(identifier, str) else index + 1}'
534
+
535
+
536
+ def behaviour(spec: Any, index: int = 0) -> dict[str, Any]:
537
+ """Checks one persistent behaviour of section 7.5 and returns it.
538
+
539
+ Args:
540
+ spec: The behaviour as the manifest or a worker gives it.
541
+ index: Its place in the list from 0, which names it in messages from 1 when it has no id.
542
+
543
+ Raises:
544
+ ArgumentError: If the behaviour is of an unknown type or holds a value out of range.
545
+ """
546
+ name = _behaviour_name(spec, index)
547
+ if not isinstance(spec, dict) or spec.get('type') not in BEHAVIOURS:
548
+ found = spec.get('type') if isinstance(spec, dict) else spec
549
+ raise ArgumentError(f'expected {name} of a type among {words(BEHAVIOURS)}, found {found!r}')
550
+ kind = spec['type']
551
+ out: dict[str, Any] = dict(spec)
552
+ out['id'] = _identifier(spec.get('id', f'{kind}{index}'), 'the id of a behaviour')
553
+ if 'weight' in spec:
554
+ out['weight'] = _curve(spec['weight'], name)
555
+ if 'when' in spec:
556
+ out['when'] = _selector(spec['when'], name)
557
+ if 'node' in spec:
558
+ out['node'] = _text(spec['node'], f'the node of {name}')
559
+ if 'attachment' in spec:
560
+ out['attachment'] = _identifier(spec['attachment'], f'the attachment of {name}')
561
+ seed = spec.get('seed', 'entity')
562
+ if seed not in ('entity', 'number', 'index') and not (
563
+ isinstance(seed, int) and not isinstance(seed, bool) and 0 <= seed < 2**31
564
+ ):
565
+ raise ArgumentError(f'expected the seed of {name} as entity, number, index or an integer')
566
+ if 'channel' in spec and spec['channel'] not in CHANNELS:
567
+ raise ArgumentError(f'expected the channel of {name} among {words(CHANNELS)}')
568
+ for key in ('rate', 'amp', 'freq', 'offset', 'goal', 'gain', 'value'):
569
+ if key in spec:
570
+ out[key] = _curve(spec[key], name)
571
+ if kind == 'spin':
572
+ if not any(key in spec for key in ('node', 'clip', 'attachment')):
573
+ raise ArgumentError(f'expected {name} to turn a node, an attachment or a clip')
574
+ if spec.get('phaseFrom', 'cosmetic') not in ('cosmetic', 'distance', 'both'):
575
+ raise ArgumentError(f'expected the phase of {name} from cosmetic, distance or both')
576
+ if 'axis' in spec:
577
+ out['axis'] = _vector(spec['axis'], 3, 1e3, f'the axis of {name}')
578
+ elif kind in ('lookAt', 'follow'):
579
+ if 'node' not in spec:
580
+ raise ArgumentError(f'expected the node of {name}')
581
+ target = spec.get('target', 'ball')
582
+ if target not in ('ball', 'subject', 'camera') and not re.fullmatch(r'p\d+', str(target)):
583
+ raise ArgumentError(f'expected {name} to follow the ball, the subject or the camera')
584
+ elif kind == 'curve':
585
+ keys = spec.get('keys')
586
+ if not isinstance(keys, list) or not 1 < len(keys) <= 64:
587
+ raise ArgumentError(f'expected the keys of {name} as 2 to 64 points')
588
+ out['keys'] = [_vector(key, 2, 1e6, f'a key of {name}') for key in keys]
589
+ if spec.get('clock', 'cosmetic') not in CLOCKS:
590
+ raise ArgumentError(f'expected the clock of {name} among {words(CLOCKS)}')
591
+ elif kind == 'materialParam' and not spec.get('uniform'):
592
+ raise ArgumentError(f'expected the uniform of {name}')
593
+ elif kind == 'audioParam' and not (spec.get('processor') and spec.get('param')):
594
+ raise ArgumentError(f'expected the processor and parameter of {name}')
595
+ elif kind == 'lightParam' and not (
596
+ spec.get('light') and spec.get('param', 'intensity') in ('intensity', 'distance')
597
+ ):
598
+ raise ArgumentError(
599
+ f'expected the light and the parameter, intensity or distance, of {name}'
600
+ )
601
+ for key in ('stiffness', 'damping', 'mass', 'limit', 'slew', 'pitchLimit', 'smoothing'):
602
+ if key in spec:
603
+ out[key] = _number(spec[key], 0, 1e4, f'the {key} of {name}')
604
+ return out
605
+
606
+
607
+ def _behaviours(value: Any, warnings: list[str]) -> list[dict[str, Any]]:
608
+ if not isinstance(value, list) or len(value) > 64:
609
+ raise ArgumentError('expected behaviours as a list of at most 64')
610
+ out = []
611
+ for index, spec in enumerate(value):
612
+ try:
613
+ out.append(behaviour(spec, index))
614
+ except ArgumentError as error:
615
+ warnings.append(f'{_behaviour_name(spec, index)} left out, {error}')
616
+ if len({item['id'] for item in out}) != len(out):
617
+ raise ArgumentError('expected behaviours of distinct ids')
618
+ return out
619
+
620
+
621
+ def _materials(value: Any, file: Any, warnings: list[str]) -> dict[str, Any]:
622
+ spec = _mapping(value, 64, 'materials')
623
+ out = {}
624
+ for name, item in spec.items():
625
+ _identifier(name, 'the name of a material')
626
+ if not isinstance(item, dict):
627
+ raise ArgumentError(f'expected material {name} as a description')
628
+ entry = dict(item)
629
+ if 'shader' in item:
630
+ entry['shader'] = file(item['shader'], f'the shader of {name}', ('.glsl',))
631
+ entry.update(_shader_entry(item, name, file))
632
+ if 'when' in item:
633
+ entry['when'] = _selector(item['when'], f'material {name}')
634
+ for key in ('baseColor', 'emissive'):
635
+ if key in item:
636
+ color = item[key]
637
+ if (
638
+ not isinstance(color, list)
639
+ or len(color) != 3
640
+ or not all(isinstance(c, int) and 0 <= c <= 255 for c in color)
641
+ ):
642
+ raise ArgumentError(f'expected the {key} of {name} as three integers')
643
+ for key, high in (
644
+ ('roughness', 1),
645
+ ('metalness', 1),
646
+ ('opacity', 1),
647
+ ('emissiveIntensity', 10),
648
+ ):
649
+ if key in item:
650
+ entry[key] = _number(item[key], 0, high, f'the {key} of {name}')
651
+ out[name] = entry
652
+ return out
653
+
654
+
655
+ _UNIFORM = re.compile(r'[a-z][A-Za-z0-9_]{0,30}')
656
+
657
+
658
+ def _uniform(key: Any, value: Any) -> Any:
659
+ if isinstance(value, dict):
660
+ if set(value) != {'seed'} or value['seed'] not in ('entity', 'number', 'index'):
661
+ raise ArgumentError(f'expected the seed of uniform {key} by entity, number or index')
662
+ return {'seed': value['seed']}
663
+ if isinstance(value, list):
664
+ if not 2 <= len(value) <= 4:
665
+ raise ArgumentError(f'expected uniform {key} of two to four numbers')
666
+ return _vector(value, len(value), 1e6, f'uniform {key}')
667
+ return _number(value, -1e6, 1e6, f'uniform {key}')
668
+
669
+
670
+ def _shader_entry(item: dict[str, Any], name: str, file: Any) -> dict[str, Any]:
671
+ """Checks the mode, uniforms, textures and options of the custom shader of a material."""
672
+ out: dict[str, Any] = {'mode': item.get('mode', 'chunks')}
673
+ if out['mode'] not in _glsl.MODES:
674
+ raise ArgumentError(f'expected the mode of the shader of {name} among {words(_glsl.MODES)}')
675
+ out['uniforms'] = {}
676
+ for key, value in _mapping(item.get('uniforms', {}), 16, f'the uniforms of {name}').items():
677
+ if not _UNIFORM.fullmatch(str(key)):
678
+ raise ArgumentError(f'expected the uniforms of {name} to start with a small letter')
679
+ out['uniforms'][key] = _uniform(key, value)
680
+ out['textures'] = {}
681
+ for key, path in _mapping(item.get('textures', {}), 4, f'the textures of {name}').items():
682
+ if not _UNIFORM.fullmatch(str(key)):
683
+ raise ArgumentError(f'expected the textures of {name} to start with a small letter')
684
+ out['textures'][key] = file(path, f'texture {key}', ('.png', '.jpg', '.webp', '.ktx2'))
685
+ for key, choices in (
686
+ ('blending', ('additive', 'normal')),
687
+ ('side', ('front', 'back', 'double')),
688
+ ):
689
+ if key in item:
690
+ if item[key] not in choices:
691
+ raise ArgumentError(f'expected the {key} of {name} among {words(choices)}')
692
+ out[key] = item[key]
693
+ for key in ('transparent', 'depthWrite'):
694
+ if key in item:
695
+ out[key] = bool(item[key])
696
+ return out
697
+
698
+
699
+ def _shaders(out: dict[str, Any], assets: dict[str, str], warnings: list[str]) -> None:
700
+ """Leaves out every part whose shader fails the static checks of `_glsl`, with a warning."""
701
+ cache: dict[tuple[str, str], list[str]] = {}
702
+
703
+ def failed(path: str, mode: str, what: str) -> bool:
704
+ if (path, mode) not in cache:
705
+ source = Path(assets.get(path, ''))
706
+ try:
707
+ cache[path, mode] = _glsl.check(source.read_text('utf-8'), mode)
708
+ except UnicodeDecodeError as error:
709
+ cache[path, mode] = [f'could not be read, {error}']
710
+ except OSError:
711
+ # A check of a manifest away from its files, as the pack tools make, leaves the
712
+ # shaders to the checks that read them.
713
+ cache[path, mode] = []
714
+ found = cache[path, mode]
715
+ warnings.extend(f'{what} left out, {path} of mode {mode} {p}' for p in found[:4])
716
+ return bool(found)
717
+
718
+ for name, item in list(out.get('materials', {}).items()):
719
+ mode = item.get('mode', 'chunks')
720
+ if item.get('shader') and failed(item['shader'], mode, f'material {name}'):
721
+ del out['materials'][name]
722
+ for name, item in list(out.get('effects', {}).items()):
723
+ if item.get('shader') and failed(item['shader'], 'material', f'effect {name}'):
724
+ del out['effects'][name]
725
+ layer = (out.get('post') or {}).get('layer')
726
+ if layer and layer.get('shader') and failed(layer['shader'], 'material', 'the layer pass'):
727
+ del out['post']
728
+ programs = _glsl.programs(out)
729
+ if programs > _glsl.BUDGET['low']:
730
+ warnings.append(f'the package compiles {programs} shader programs, low quality keeps 8')
731
+
732
+
733
+ def _quality(value: Any) -> dict[str, Any]:
734
+ spec = _mapping(value, 3, 'quality')
735
+ out = {}
736
+ for level, item in spec.items():
737
+ if level not in QUALITIES or not isinstance(item, dict):
738
+ raise ArgumentError(f'expected quality by {words(QUALITIES)}')
739
+ drop = item.get('drop', [])
740
+ if not isinstance(drop, list) or not all(isinstance(d, str) and len(d) <= 60 for d in drop):
741
+ raise ArgumentError('expected what a quality drops as a list of names')
742
+ out[level] = {'drop': list(drop)}
743
+ return out
744
+
745
+
746
+ def supported(version: Any) -> bool:
747
+ """Returns whether a contract version is one this renderer serves, 1.0 and 1.1."""
748
+ match = re.fullmatch(r'(\d+)\.(\d+)', str(version)) if isinstance(version, str) else None
749
+ return bool(match) and int(match.group(1)) == MAJOR and int(match.group(2)) <= MINOR
750
+
751
+
752
+ def check(
753
+ document: Any, assets: dict[str, str], warnings: list[str] | None = None
754
+ ) -> dict[str, Any]:
755
+ """Checks a manifest against the files of its package and returns it as the page reads it.
756
+
757
+ A section that fails its check is left out with a warning, so the page draws that part as it
758
+ would without a package.
759
+
760
+ Args:
761
+ document: The manifest as read from JSON.
762
+ assets: The files of the package, each path inside the folder to its path on disk.
763
+ warnings: A list that collects what the check left out.
764
+
765
+ Raises:
766
+ ArgumentError: If the document is no manifest or names a contract this renderer lacks.
767
+ """
768
+ warnings = warnings if warnings is not None else []
769
+ if not isinstance(document, dict):
770
+ raise ArgumentError('expected a presentation manifest, a JSON object')
771
+ version = document.get('contract')
772
+ if not isinstance(version, str) or not re.fullmatch(r'\d+\.\d+', version):
773
+ raise ArgumentError('expected contract to give the version of the manifest, such as 1.0')
774
+ if not supported(version):
775
+ raise ArgumentError(f'expected a manifest of contract {CONTRACT}, found contract {version}')
776
+ file = _files(assets)
777
+ out: dict[str, Any] = {'contract': version}
778
+ warnings.extend(f'the manifest ignores {key}' for key in sorted(set(document) - set(_SECTIONS)))
779
+
780
+ def section(key: str, read: Any) -> None:
781
+ if key not in document:
782
+ return
783
+ try:
784
+ out[key] = read(document[key])
785
+ except (ArgumentError, OSError, TypeError, ValueError, KeyError) as error:
786
+ warnings.append(f'{key} left out, {error}')
787
+
788
+ section('name', lambda value: _text(value, 'the name of the package'))
789
+ section('requires', lambda value: _vocabulary.features(value, 'requires'))
790
+ section('prefers', lambda value: _vocabulary.features(value, 'prefers'))
791
+ section('models', lambda value: _models(value, file))
792
+ section('rig', lambda value: _rig(value, file, warnings))
793
+ section('clips', lambda value: _clips(value, warnings))
794
+ section('behaviours', lambda value: _behaviours(value, warnings))
795
+ section('materials', lambda value: _materials(value, file, warnings))
796
+ section('effects', lambda value: _vocabulary.effects(value, file, warnings))
797
+ section('audio', lambda value: _vocabulary.audio(value, file, warnings))
798
+ sockets = (out.get('rig') or {}).get('sockets', {})
799
+ section('lights', lambda value: _vocabulary.lights(value, sockets, warnings))
800
+ section('post', lambda value: _vocabulary.post(value, file))
801
+ section('overlays', _vocabulary.overlays)
802
+ _shaders(out, assets, warnings)
803
+ names = {
804
+ 'cues': (out.get('audio') or {}).get('cues', {}),
805
+ 'music': (out.get('audio') or {}).get('music', {}),
806
+ 'effects': out.get('effects', {}),
807
+ 'files': set(assets),
808
+ }
809
+ section('reflexes', lambda value: _vocabulary.reflexes(value, names, warnings))
810
+ section('worker', lambda value: file(value, 'the worker', ('.js',)))
811
+ section(
812
+ 'reducedMotion',
813
+ lambda value: {
814
+ 'amplitude': _number(
815
+ _mapping(value, 4, 'reducedMotion').get('amplitude', 0.3), 0, 1, 'the amplitude'
816
+ )
817
+ },
818
+ )
819
+ section('quality', _quality)
820
+ return out
821
+
822
+
823
+ def missing(manifest: dict[str, Any]) -> list[str]:
824
+ """Returns the features a manifest requires that this renderer lacks."""
825
+ return [f for f in manifest.get('requires', []) if f not in _vocabulary.FEATURES]
826
+
827
+
828
+ def _glb(data: bytes) -> None:
829
+ """Raises `ArgumentError` for bytes that are no self-contained binary glTF 2.0 file."""
830
+ if len(data) < 20 or data[:4] != b'glTF':
831
+ raise ArgumentError('expected a binary glTF file')
832
+ version, length = struct.unpack_from('<II', data, 4)
833
+ size, kind = struct.unpack_from('<II', data, 12)
834
+ if version != 2 or length != len(data) or kind != 0x4E4F534A or 20 + size > len(data):
835
+ raise ArgumentError('expected a whole binary glTF 2.0 file')
836
+ from .._registry import clips as _clips
837
+
838
+ try:
839
+ document = json.loads(data[20 : 20 + size])
840
+ outside = _clips._uris(document)
841
+ except (ValueError, UnicodeDecodeError, RecursionError) as error:
842
+ raise ArgumentError(f'expected the JSON chunk of a glTF file, found {error}') from error
843
+ if not isinstance(document, dict):
844
+ raise ArgumentError('expected the JSON chunk of a glTF file to hold an object')
845
+ if outside:
846
+ raise ArgumentError('expected a self-contained file')
847
+ required = _teams._array(document.get('extensionsRequired'))
848
+ if any(name in _clips._UNSUPPORTED for name in required):
849
+ raise ArgumentError('expected a file without an extension that the page cannot read')
850
+
851
+
852
+ def check_path(name: str) -> str:
853
+ """Returns the path of a file inside a package, or raises `ArgumentError` for a bad one."""
854
+ parts = name.split('/') if isinstance(name, str) else []
855
+ if len(parts) > MAXIMUM_DEPTH:
856
+ raise ArgumentError(
857
+ f'expected a file in at most {MAXIMUM_DEPTH - 1} folders of the package, found '
858
+ f'{name!r} in {len(parts) - 1}'
859
+ )
860
+ if (
861
+ not parts
862
+ or not all(_PART.fullmatch(part) and '..' not in part for part in parts)
863
+ or any(_teams._device(part) for part in parts)
864
+ ):
865
+ raise ArgumentError(
866
+ 'expected a path of lowercase letters, digits, dots, dashes and underscores, found '
867
+ f'{name!r}'
868
+ )
869
+ if PurePosixPath(name).suffix not in MAXIMUM_BYTES:
870
+ raise ArgumentError(
871
+ f'expected a known kind of file, {", ".join(MAXIMUM_BYTES)}, found {name!r}'
872
+ )
873
+ return name
874
+
875
+
876
+ def _js_name(text: str, i: int) -> tuple[str, int] | None:
877
+ """Reads the name at `i` with its escapes decoded, and returns it and the offset past it."""
878
+ out = []
879
+ j = i
880
+ if text[j] == '#':
881
+ out.append('#')
882
+ j += 1
883
+ while j < len(text):
884
+ c = text[j]
885
+ if c == '\\':
886
+ match = _ESCAPE.match(text, j)
887
+ code = int(match.group(1) or match.group(2), 16) if match else 0x110000
888
+ if code > 0x10FFFF:
889
+ return None
890
+ out.append(chr(code))
891
+ j = match.end()
892
+ elif c in '$\u200c\u200d' or ('a' + c).isidentifier():
893
+ out.append(c)
894
+ j += 1
895
+ else:
896
+ break
897
+ return ''.join(out), j
898
+
899
+
900
+ def _quoted(text: str, i: int) -> int:
901
+ """Returns the offset past the string that opens at `i`, or -1 for one left open."""
902
+ quote = text[i]
903
+ j = i + 1
904
+ while j < len(text):
905
+ c = text[j]
906
+ if c == '\\':
907
+ j += 3 if text.startswith('\r\n', j + 1) else 2
908
+ elif c == quote:
909
+ return j + 1
910
+ elif c in '\n\r':
911
+ return -1
912
+ else:
913
+ j += 1
914
+ return -1
915
+
916
+
917
+ def _regex(text: str, i: int) -> int:
918
+ """Returns the offset past the regular expression that opens at `i`, or -1 for one left open."""
919
+ j = i + 1
920
+ inside = False
921
+ while j < len(text):
922
+ c = text[j]
923
+ if c in _LINE_ENDS:
924
+ return -1
925
+ if c == '\\':
926
+ if j + 1 < len(text) and text[j + 1] in _LINE_ENDS:
927
+ return -1
928
+ j += 2
929
+ continue
930
+ if c == '[':
931
+ inside = True
932
+ elif c == ']':
933
+ inside = False
934
+ elif c == '/' and not inside:
935
+ flags = _js_name(text, j + 1) if j + 1 < len(text) else None
936
+ return flags[1] if flags else j + 1
937
+ j += 1
938
+ return -1
939
+
940
+
941
+ def _template(text: str, i: int) -> tuple[int, bool]:
942
+ """Reads the text of a template from `i` to its end or to a substitution.
943
+
944
+ Returns the offset past what it read, -1 for a template left open, and whether a
945
+ substitution opens there.
946
+ """
947
+ j = i
948
+ while j < len(text):
949
+ c = text[j]
950
+ if c == '\\':
951
+ j += 2
952
+ elif c == '`':
953
+ return j + 1, False
954
+ elif text.startswith('${', j):
955
+ return j + 2, True
956
+ else:
957
+ j += 1
958
+ return -1, False
959
+
960
+
961
+ def _tokens(text: str) -> list[tuple[str, str]] | str:
962
+ """Splits a module into the tokens that `module_problem` reads, or returns what stops it.
963
+
964
+ Comments go, and strings, templates, regular expressions and numbers stay as one token of
965
+ their kind without their text, so only words and punctuators keep their value.
966
+ """
967
+ tokens: list[tuple[str, str]] = []
968
+ # Each open brace, `brace`, or open substitution of a template, `template`.
969
+ braces: list[str] = []
970
+ # Each open parenthesis, and whether it holds the head of an if, while, for or with.
971
+ parens: list[bool] = []
972
+ n = len(text)
973
+ i = 0
974
+ # Whether a line ends between the last token and the next, which ends a statement before a
975
+ # `++` or `--`.
976
+ newline = False
977
+
978
+ def add(kind: str, value: str) -> None:
979
+ nonlocal newline
980
+ if value in ('++', '--') and tokens and not newline:
981
+ last = tokens[-1]
982
+ ends = last[0] in ('number', 'string', 'template', 'regex', 'postfix') or (
983
+ last[0] == 'word' and last[1] not in _BEFORE_REGEX
984
+ )
985
+ if ends or last in (('punct', ')'), ('punct', ']')):
986
+ kind = 'postfix'
987
+ tokens.append((kind, value))
988
+ newline = False
989
+
990
+ if text.startswith('#!'):
991
+ while i < n and text[i] not in _LINE_ENDS:
992
+ i += 1
993
+
994
+ def regex_allowed() -> bool | None:
995
+ # Whether a slash here starts a regular expression, None when only a parser could say.
996
+ if not tokens:
997
+ return True
998
+ kind, value = tokens[-1]
999
+ if kind in ('number', 'string', 'template', 'regex'):
1000
+ return False
1001
+ if kind == 'word':
1002
+ return value in _BEFORE_REGEX and not (len(tokens) > 1 and tokens[-2] in _DOTS)
1003
+ if kind == 'head':
1004
+ return True
1005
+ if kind == 'postfix' or value in (')', ']'):
1006
+ return False
1007
+ if value == '}':
1008
+ return None
1009
+ return True
1010
+
1011
+ while i < n:
1012
+ c = text[i]
1013
+ if c.isspace() or c == '\ufeff':
1014
+ newline = newline or c in _LINE_ENDS
1015
+ i += 1
1016
+ elif text.startswith('//', i):
1017
+ while i < n and text[i] not in _LINE_ENDS:
1018
+ i += 1
1019
+ elif text.startswith('/*', i):
1020
+ end = text.find('*/', i + 2)
1021
+ if end < 0:
1022
+ return 'found a comment left open'
1023
+ newline = newline or any(c in _LINE_ENDS for c in text[i:end])
1024
+ i = end + 2
1025
+ elif c in '\'"':
1026
+ i = _quoted(text, i)
1027
+ if i < 0:
1028
+ return 'found a string left open'
1029
+ add('string', '')
1030
+ elif c == '`' or (c == '}' and braces and braces[-1] == 'template'):
1031
+ if c == '}':
1032
+ braces.pop()
1033
+ i, opens = _template(text, i + 1)
1034
+ if i < 0:
1035
+ return 'found a template left open'
1036
+ if opens:
1037
+ braces.append('template')
1038
+ add('punct', '${')
1039
+ else:
1040
+ add('template', '')
1041
+ elif c == '/':
1042
+ allowed = regex_allowed()
1043
+ if allowed is None:
1044
+ return (
1045
+ 'found a slash right after a closing brace, which reads two ways, put the '
1046
+ 'expression in parentheses'
1047
+ )
1048
+ if allowed:
1049
+ i = _regex(text, i)
1050
+ if i < 0:
1051
+ return 'found a regular expression left open'
1052
+ add('regex', '')
1053
+ else:
1054
+ add('punct', '/')
1055
+ i += 1
1056
+ elif c.isdigit() or (c == '.' and i + 1 < n and text[i + 1].isdigit()):
1057
+ i = _NUMBER.match(text, i).end()
1058
+ add('number', '')
1059
+ elif c in '#\\$' or c.isidentifier():
1060
+ word = _js_name(text, i)
1061
+ if word is None or word[1] == i:
1062
+ return 'found an escape that names no character'
1063
+ add('word', word[0])
1064
+ i = word[1]
1065
+ elif text.startswith('?.', i) and not (i + 2 < n and text[i + 2].isdigit()):
1066
+ add('punct', '?.')
1067
+ i += 2
1068
+ else:
1069
+ value = next((p for p in _PUNCTUATORS if text.startswith(p, i)), c)
1070
+ if value == '(':
1071
+ last = tokens[-1] if tokens else ('', '')
1072
+ before = tokens[-2] if len(tokens) > 1 else ('', '')
1073
+ head = last[0] == 'word' and (
1074
+ (last[1] in _HEADS and before not in _DOTS)
1075
+ or (last[1] == 'await' and before == ('word', 'for'))
1076
+ )
1077
+ parens.append(head)
1078
+ elif value == ')' and parens and parens.pop():
1079
+ add('head', ')')
1080
+ i += 1
1081
+ continue
1082
+ elif value == '{':
1083
+ braces.append('brace')
1084
+ elif value == '}' and braces:
1085
+ braces.pop()
1086
+ add('punct', value)
1087
+ i += len(value)
1088
+ if 'template' in braces:
1089
+ return 'found a template left open'
1090
+ return tokens
1091
+
1092
+
1093
+ def module_problem(text: str) -> str | None:
1094
+ """Returns why a module may not run as a single file module, or `None` when it may.
1095
+
1096
+ The reader walks the text as JavaScript does, past comments, strings, template literals and
1097
+ regular expressions, and refuses every `import`, static, dynamic or `import.meta`, and every
1098
+ `export` that names a module with `from`. It also refuses a comment, string, template or
1099
+ regular expression left open, and a slash right after a closing brace, whose reading only a
1100
+ parser could tell, so no import hides in what the reader takes for text.
1101
+ """
1102
+ tokens = _tokens(text)
1103
+ if isinstance(tokens, str):
1104
+ return tokens
1105
+ for k, (kind, value) in enumerate(tokens):
1106
+ if kind != 'word' or value not in ('import', 'export') or (k and tokens[k - 1] in _DOTS):
1107
+ continue
1108
+ if value == 'import':
1109
+ return 'found import'
1110
+ after = tokens[k + 1] if k + 1 < len(tokens) else None
1111
+ if after == ('punct', '*'):
1112
+ return 'found export from'
1113
+ if after == ('punct', '{'):
1114
+ close = next((m for m in range(k + 2, len(tokens)) if tokens[m][1] == '}'), None)
1115
+ if close is not None and tokens[close + 1 : close + 2] == [('word', 'from')]:
1116
+ return 'found export from'
1117
+ return None
1118
+
1119
+
1120
+ def check_file(name: str, data: bytes) -> None:
1121
+ """Raises `ArgumentError` for a file of a package of the wrong path, kind or size."""
1122
+ check_path(name)
1123
+ suffix = PurePosixPath(name).suffix
1124
+ if len(data) > MAXIMUM_BYTES[suffix]:
1125
+ raise ArgumentError(f'expected {name} of at most {MAXIMUM_BYTES[suffix]} bytes')
1126
+ if suffix == '.glb':
1127
+ _glb(data)
1128
+ elif suffix in ('.png', '.jpg', '.webp'):
1129
+ if _teams._image_suffix('art', data) != suffix:
1130
+ raise ArgumentError(f'expected {name} to hold an image of its kind')
1131
+ elif suffix == '.ktx2':
1132
+ if not data.startswith(b'\xabKTX 20\xbb\r\n\x1a\n'):
1133
+ raise ArgumentError(f'expected {name} to hold a KTX2 texture')
1134
+ elif suffix in ('.ogg', '.mp3', '.wav'):
1135
+ if _teams._sound_suffix(data) != suffix:
1136
+ raise ArgumentError(f'expected {name} to hold a sound of its kind')
1137
+ elif suffix == '.wasm':
1138
+ if not data.startswith(b'\0asm'):
1139
+ raise ArgumentError(f'expected {name} to hold WebAssembly')
1140
+ else:
1141
+ try:
1142
+ text = data.decode('utf-8')
1143
+ except UnicodeDecodeError as error:
1144
+ raise ArgumentError(f'expected {name} as UTF-8 text') from error
1145
+ if suffix == '.json':
1146
+ try:
1147
+ json.loads(text)
1148
+ except ValueError as error:
1149
+ raise ArgumentError(f'expected {name} as JSON, found {error}') from error
1150
+ problem = module_problem(text) if suffix == '.js' else None
1151
+ if problem:
1152
+ raise ArgumentError(
1153
+ f'expected {name} as a single file module without imports, {problem}'
1154
+ )
1155
+
1156
+
1157
+ def _assets(team_folder: Path, remove: bool) -> dict[str, str]:
1158
+ """Returns the sound files of a package by their paths, and deletes the others when asked."""
1159
+ folder = team_folder / FOLDER
1160
+ found: dict[str, str] = {}
1161
+ if folder.is_symlink() or (folder.exists() and not folder.is_dir()):
1162
+ if remove:
1163
+ folder.unlink()
1164
+ return found
1165
+ if not folder.is_dir():
1166
+ return found
1167
+ total = 0
1168
+ for path in sorted(folder.rglob('*')):
1169
+ if path.is_dir() and not path.is_symlink():
1170
+ continue
1171
+ name = path.relative_to(folder).as_posix()
1172
+ valid = False
1173
+ if (
1174
+ path.is_file()
1175
+ and not path.is_symlink()
1176
+ and not any(p.is_symlink() for p in path.parents if folder in p.parents)
1177
+ ):
1178
+ try:
1179
+ data = path.read_bytes()
1180
+ check_file(name, data)
1181
+ valid = len(found) < MAXIMUM_FILES and total + len(data) <= MAXIMUM_TOTAL_BYTES
1182
+ except Exception:
1183
+ # A file that fails any part of its check, however it fails, counts as failing.
1184
+ valid = False
1185
+ if valid:
1186
+ total += len(data)
1187
+ found[name] = str(path)
1188
+ elif remove:
1189
+ path.unlink(missing_ok=True)
1190
+ if remove:
1191
+ for path in sorted(folder.rglob('*'), reverse=True):
1192
+ if path.is_dir() and not any(path.iterdir()):
1193
+ path.rmdir()
1194
+ return found
1195
+
1196
+
1197
+ def _read(team_folder: Path) -> Any:
1198
+ path = team_folder / FOLDER / MANIFEST
1199
+ if not path.is_file() or path.is_symlink() or path.stat().st_size > MAXIMUM_MANIFEST_BYTES:
1200
+ raise ArgumentError('expected a presentation manifest of at most 256 KB')
1201
+ try:
1202
+ return json.loads(path.read_text(encoding='utf-8'))
1203
+ except (ValueError, UnicodeDecodeError) as error:
1204
+ raise ArgumentError(f'expected the manifest as JSON, found {error}') from error
1205
+
1206
+
1207
+ def import_folder(team_folder: Path) -> None:
1208
+ """Checks the package of an imported team as uploads are checked, and deletes what fails.
1209
+
1210
+ Files of a wrong path, kind or size and files past the limits of a package go, the manifest
1211
+ among them when it is no JSON. A manifest of a newer contract stays, untouched.
1212
+ """
1213
+ _assets(team_folder, remove=True)
1214
+
1215
+
1216
+ def left_out(root: Path) -> set[Path]:
1217
+ """Returns the files of a team's folder that an export leaves out, those failing their check.
1218
+
1219
+ Args:
1220
+ root: The submission folder of the team, with `cuju-team` inside.
1221
+ """
1222
+ team_folder = root / _teams.TEAM_FOLDER
1223
+ folder = team_folder / FOLDER
1224
+ kept = {Path(path) for path in _assets(team_folder, remove=False).values()}
1225
+ return {path for path in folder.rglob('*') if path.is_file() and path not in kept}
1226
+
1227
+
1228
+ def developer_folders() -> dict[str, Path]:
1229
+ """Returns the trusted folders of developer mode by team, empty while it is off.
1230
+
1231
+ Developer mode is on only when `developer.json` in the renderer's home holds
1232
+ `{"presentation": {"team id": "folder"}}`, each folder an absolute `cuju-team` folder of the
1233
+ author's own that holds `presentation/presentation.json`.
1234
+ """
1235
+ path = _home.home() / DEVELOPER_FILE
1236
+ try:
1237
+ document = json.loads(path.read_text(encoding='utf-8'))
1238
+ except (OSError, ValueError, UnicodeDecodeError):
1239
+ return {}
1240
+ folders = document.get('presentation') if isinstance(document, dict) else None
1241
+ out = {}
1242
+ for identifier, folder in (folders or {}).items() if isinstance(folders, dict) else []:
1243
+ if isinstance(identifier, str) and isinstance(folder, str):
1244
+ candidate = Path(folder).expanduser()
1245
+ if candidate.is_absolute() and (candidate / FOLDER / MANIFEST).is_file():
1246
+ out[identifier] = candidate
1247
+ return out
1248
+
1249
+
1250
+ def _team_folder(identifier: str) -> tuple[Path | None, bool]:
1251
+ """Returns the folder that holds a team's package and whether developer mode serves it."""
1252
+ developer = developer_folders().get(identifier)
1253
+ if developer is not None:
1254
+ return developer, True
1255
+ if identifier != _teams.BUILTIN and not _home.valid_identifier(identifier):
1256
+ return None, False
1257
+ folder = _home.folder('teams') / identifier / _teams.TEAM_FOLDER
1258
+ return (folder if folder.is_dir() else None), False
1259
+
1260
+
1261
+ def served(identifier: str) -> dict[str, Any]:
1262
+ """Returns what the page reads of a team's package, its checked manifest and its files.
1263
+
1264
+ Returns:
1265
+ A dictionary with `manifest`, the checked manifest or `None` for a team without one or
1266
+ with one this renderer cannot serve, `warnings`, `files`, the paths of the package's
1267
+ files, `developer`, whether developer mode serves it, `contract`, the version this
1268
+ renderer serves, `features`, those it implements, and `missing`, the features the
1269
+ manifest requires that it lacks.
1270
+ """
1271
+ folder, developer = _team_folder(identifier)
1272
+ out: dict[str, Any] = {
1273
+ 'manifest': None,
1274
+ 'warnings': [],
1275
+ 'files': [],
1276
+ 'developer': developer,
1277
+ 'contract': CONTRACT,
1278
+ 'features': list(_vocabulary.FEATURES),
1279
+ 'missing': [],
1280
+ }
1281
+ if folder is None or not (folder / FOLDER / MANIFEST).is_file():
1282
+ return out
1283
+ assets = _assets(folder, remove=False)
1284
+ out['files'] = sorted(name for name in assets if name != MANIFEST)
1285
+ try:
1286
+ out['manifest'] = check(_read(folder), assets, out['warnings'])
1287
+ out['missing'] = missing(out['manifest'])
1288
+ except (ArgumentError, OSError) as error:
1289
+ out['warnings'].append(f'the package is drawn without its manifest, {error}')
1290
+ return out
1291
+
1292
+
1293
+ def file_path(identifier: str, name: str) -> Path | None:
1294
+ """Returns the path of a file of a team's package, or `None` for an unknown or failing one."""
1295
+ folder, _ = _team_folder(identifier)
1296
+ try:
1297
+ check_path(name)
1298
+ except ArgumentError:
1299
+ return None
1300
+ if folder is None:
1301
+ return None
1302
+ path = folder / FOLDER / name
1303
+ with contextlib.suppress(OSError, ArgumentError):
1304
+ if path.is_file() and (folder / FOLDER).resolve() in path.resolve().parents:
1305
+ check_file(name, path.read_bytes())
1306
+ return path
1307
+ return None
1308
+
1309
+
1310
+ def content_type(identifier: str, name: str) -> str:
1311
+ """Returns the type that a file of a team's package is served with.
1312
+
1313
+ The page reads a worker as text and hands it to its sandbox, so a module of JavaScript goes
1314
+ out as plain text, which no page runs from its address. Only the sound worklet that the
1315
+ manifest names, which the page loads by its address into an audio context of the team's own,
1316
+ and every module of developer mode, which the page imports, go out as JavaScript.
1317
+ """
1318
+ suffix = PurePosixPath(name).suffix
1319
+ if suffix != '.js':
1320
+ return CONTENT_TYPES[suffix]
1321
+ folder, developer = _team_folder(identifier)
1322
+ if developer:
1323
+ return CONTENT_TYPES[suffix]
1324
+ manifest = None
1325
+ if folder is not None:
1326
+ with contextlib.suppress(ArgumentError, OSError):
1327
+ manifest = _read(folder)
1328
+ audio = manifest.get('audio') if isinstance(manifest, dict) else None
1329
+ worklet = audio.get('worklet') if isinstance(audio, dict) else None
1330
+ return CONTENT_TYPES[suffix] if worklet == name else 'text/plain; charset=utf-8'
1331
+
1332
+
1333
+ def sides() -> dict[str, str | None]:
1334
+ """Returns the registered team whose presentation each side draws, by the viewer's choice.
1335
+
1336
+ A side without a choice draws the presentation of the team that plays it. The choice serves
1337
+ matches whose header names no registered team, such as the live batches of a training run,
1338
+ section Q11 of the contract, and stays in the renderer's home until it is changed.
1339
+ """
1340
+ try:
1341
+ document = json.loads((_home.home() / SIDES_FILE).read_text(encoding='utf-8'))
1342
+ except (OSError, ValueError, UnicodeDecodeError):
1343
+ document = {}
1344
+ out: dict[str, str | None] = {}
1345
+ for side in SIDES:
1346
+ value = document.get(side) if isinstance(document, dict) else None
1347
+ out[side] = value if isinstance(value, str) and _home.valid_identifier(value) else None
1348
+ return out
1349
+
1350
+
1351
+ def assign(changes: Any) -> dict[str, str | None]:
1352
+ """Sets the registered team whose presentation a side draws, or none, and returns them all.
1353
+
1354
+ Args:
1355
+ changes: A mapping of `left` and `right` to a team identifier, or `None` for the team that
1356
+ plays the side.
1357
+
1358
+ Raises:
1359
+ ArgumentError: If a side or a team is unknown.
1360
+ """
1361
+ if not isinstance(changes, dict) or not set(changes) <= set(SIDES):
1362
+ raise ArgumentError('expected the presentation of the sides left and right')
1363
+ out = sides()
1364
+ for side, identifier in changes.items():
1365
+ if identifier is not None and (
1366
+ not isinstance(identifier, str)
1367
+ or not _home.valid_identifier(identifier)
1368
+ or not (_home.folder('teams') / identifier / _teams.TEAM_FOLDER).is_dir()
1369
+ ):
1370
+ raise ArgumentError(
1371
+ f'expected a registered team for the {side} side, found {identifier!r}'
1372
+ )
1373
+ out[side] = identifier
1374
+ path = _home.home() / SIDES_FILE
1375
+ path.write_text(json.dumps(out), encoding='utf-8')
1376
+ return out