├── README.md ├── LICENSE └── sb3tosb2.py /README.md: -------------------------------------------------------------------------------- 1 | SB3 to SB2 Converter 2 | ============== 3 | 4 | A simple Python 3 program that converts .sb3 files to .sb2 files 5 | 6 | Requirements 7 | -------------- 8 | - Python 3 (preferably 3.6.2 or later) 9 | 10 | Installation 11 | -------------- 12 | Download and extract the ZIP file and move the sb3tosb2.py file to wherever you want. 13 | 14 | Usage 15 | -------------- 16 | 1. Run sb3tosb2.py with Python 17 | 2. Select the SB3 file to open 18 | 3. Click OK to exit. The SB2 file path will be the same as the SB3 file path except for the file extension. 19 | 20 | Usage (command line) 21 | -------------- 22 | 1. Open the terminal or command prompt and navigate to the directory of the sb3tosb2.py file. 23 | 2. Enter the following command: `python sb3tosb2.py [unordered options] sb3path [sb2path]`
Options and sb2path are not necessary. 24 | 3. If an error is given, make sure you entered a valid sb3 file. 25 | 26 | Arguments 27 | -------------- 28 | Options may or may not be separated by a space.
29 | List of options: 30 | - `-h`: Displays the program arguments and list of options 31 | - `-c`: This enables compatibility mode. Workarounds for the following blocks will be added to sprites: 32 | - glide to [ v] 33 | - costume [number v] 34 | - set drag mode [ v] 35 | - <[] contains []?> (may result in performance loss) 36 | - (item # of [] in [ v]) (may result in performance loss) 37 | - pen color blocks (including HSV and shade blocks) 38 | - timer blocks 39 | - `-j`: Automatically enables compatibility mode and adds an unlimited join workaround (may result in significant performance loss) 40 | - `-l`: Automatically enables compatibility mode and adds custom blocks to automatically limit list length to 200,000 (may result in performance loss) 41 | - `-p`: Tries to insert blocks to fill the screen when the pen size is set to a value greater than 255 42 | 43 | Known Issues 44 | -------------- 45 | - MP3 audio files cannot be converted 46 | - Compatibility mode changes variable monitor labels 47 | - Compatibility mode allows ([ v] of [ v]) to access only variables (not attributes like x position, backdrop #, etc.) 48 | - Dragging in projects converted with compatibility mode does not have the same pen behavior as in 3.0 49 | - Unlimited join does not check case when checking string equality -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /sb3tosb2.py: -------------------------------------------------------------------------------- 1 | import audioop 2 | import hashlib 3 | import io 4 | import json 5 | import sys 6 | import wave 7 | import zipfile 8 | 9 | sys.setrecursionlimit(4100) 10 | 11 | 12 | def printWarning(message): 13 | print("WARNING: " + message) 14 | 15 | 16 | def printError(message, gui): 17 | if gui: 18 | messagebox.showerror('Error', message, icon='warning') 19 | else: 20 | lines = message.split('\n') 21 | lines = [" " + line for line in lines] 22 | lines[0] = "ERROR: " + lines[0][7:] 23 | print('\n'.join(lines)) 24 | input('Press enter to exit... ') 25 | exit() 26 | 27 | 28 | def rightPad(s, l, c): 29 | assert type(s) == str and type(c) == str 30 | return s + (l * c) 31 | 32 | 33 | class BlockArgMapper: 34 | stageAttrs = { 35 | 'backdrop #', 36 | 'backdrop name', 37 | 'volume' 38 | } 39 | 40 | spriteAttrs = { 41 | 'x position', 42 | 'y position', 43 | 'direction', 44 | 'costume #', 45 | 'costume name', 46 | 'size', 47 | 'volume' 48 | } 49 | 50 | def __init__(self, obj): 51 | assert type(obj) == ProjectConverter 52 | self.converter = obj 53 | 54 | def mapArgs(self, opcode, block, blocks): 55 | assert not opcode.startswith('__') 56 | return getattr(self, opcode)(block, blocks) 57 | 58 | def varName(self, name): 59 | if type(name) == str: 60 | return ('\xa0' if self.converter.compat else '') + name 61 | else: 62 | if self.converter.compat: 63 | return ['concatenate:with:', '\xa0', name] 64 | else: 65 | return name 66 | 67 | # Motion 68 | 69 | def motion_movesteps(self, block, blocks): 70 | output = ['forward:', self.converter.inputVal('STEPS', block, blocks)] 71 | return output 72 | 73 | def motion_turnright(self, block, blocks): 74 | output = ['turnRight:', self.converter.inputVal('DEGREES', block, blocks)] 75 | return output 76 | 77 | def motion_turnleft(self, block, blocks): 78 | output = ['turnLeft:', self.converter.inputVal('DEGREES', block, blocks)] 79 | return output 80 | 81 | def motion_pointindirection(self, block, blocks): 82 | output = ['heading:', self.converter.inputVal('DIRECTION', block, blocks)] 83 | return output 84 | 85 | def motion_pointtowards(self, block, blocks): 86 | output = ['pointTowards:', self.converter.inputVal('TOWARDS', block, blocks)] 87 | return output 88 | 89 | def motion_gotoxy(self, block, blocks): 90 | output = ['gotoX:y:', self.converter.inputVal('X', block, blocks), self.converter.inputVal('Y', block, blocks)] 91 | return output 92 | 93 | def motion_goto(self, block, blocks): 94 | output = ['gotoSpriteOrMouse:', self.converter.inputVal('TO', block, blocks)] 95 | return output 96 | 97 | def motion_glidesecstoxy(self, block, blocks): 98 | output = ['glideSecs:toX:y:elapsed:from:', self.converter.inputVal('SECS', block, blocks), 99 | self.converter.inputVal('X', block, blocks), self.converter.inputVal('Y', block, blocks)] 100 | return output 101 | 102 | def motion_changexby(self, block, blocks): 103 | output = ['changeXposBy:', self.converter.inputVal('DX', block, blocks)] 104 | return output 105 | 106 | def motion_setx(self, block, blocks): 107 | output = ['xpos:', self.converter.inputVal('X', block, blocks)] 108 | return output 109 | 110 | def motion_changeyby(self, block, blocks): 111 | output = ['changeYposBy:', self.converter.inputVal('DY', block, blocks)] 112 | return output 113 | 114 | def motion_sety(self, block, blocks): 115 | output = ['ypos:', self.converter.inputVal('Y', block, blocks)] 116 | return output 117 | 118 | def motion_ifonedgebounce(self, block, blocks): 119 | return ['bounceOffEdge'] 120 | 121 | def motion_setrotationstyle(self, block, blocks): 122 | output = ['setRotationStyle', self.converter.fieldVal('STYLE', block)] 123 | return output 124 | 125 | def motion_xposition(self, block, blocks): 126 | return ['xpos'] 127 | 128 | def motion_yposition(self, block, blocks): 129 | return ['ypos'] 130 | 131 | def motion_direction(self, block, blocks): 132 | return ['heading'] 133 | 134 | def motion_scroll_right(self, block, blocks): 135 | output = ['scrollRight', self.converter.inputVal('DISTANCE', block, blocks)] 136 | return output 137 | 138 | def motion_scroll_up(self, block, blocks): 139 | output = ['scrollUp', self.converter.inputVal('DISTANCE', block, blocks)] 140 | return output 141 | 142 | def motion_align_scene(self, block, blocks): 143 | output = ['scrollAlign', self.converter.fieldVal('ALIGNMENT', block)] 144 | return output 145 | 146 | def motion_xscroll(self, block, blocks): 147 | return ['xScroll'] 148 | 149 | def motion_yscroll(self, block, blocks): 150 | return ['yScroll'] 151 | 152 | # Looks 153 | 154 | def looks_sayforsecs(self, block, blocks): 155 | output = ['say:duration:elapsed:from:', self.converter.inputVal('MESSAGE', block, blocks), 156 | self.converter.inputVal('SECS', block, blocks)] 157 | return output 158 | 159 | def looks_say(self, block, blocks): 160 | output = ['say:', self.converter.inputVal('MESSAGE', block, blocks)] 161 | return output 162 | 163 | def looks_thinkforsecs(self, block, blocks): 164 | output = ['think:duration:elapsed:from:', self.converter.inputVal('MESSAGE', block, blocks), 165 | self.converter.inputVal('SECS', block, blocks)] 166 | return output 167 | 168 | def looks_think(self, block, blocks): 169 | output = ['think:', self.converter.inputVal('MESSAGE', block, blocks)] 170 | return output 171 | 172 | def looks_show(self, block, blocks): 173 | return ['show'] 174 | 175 | def looks_hide(self, block, blocks): 176 | return ['hide'] 177 | 178 | def looks_hideallsprites(self, block, blocks): 179 | return ['hideAll'] 180 | 181 | def looks_switchcostumeto(self, block, blocks): 182 | output = ['lookLike:', self.converter.inputVal('COSTUME', block, blocks)] 183 | return output 184 | 185 | def looks_nextcostume(self, block, blocks): 186 | return ['nextCostume'] 187 | 188 | def looks_switchbackdropto(self, block, blocks): 189 | output = ['startScene', self.converter.inputVal('BACKDROP', block, blocks)] 190 | return output 191 | 192 | def looks_nextbackdrop(self, block, blocks): 193 | return ['nextScene'] 194 | 195 | def looks_changeeffectby(self, block, blocks): 196 | output = ['changeGraphicEffect:by:'] 197 | field = self.converter.fieldVal('EFFECT', block) 198 | if type(field) == str: 199 | field = str.lower(field) 200 | output.append(field) 201 | output.append(self.converter.inputVal('CHANGE', block, blocks)) 202 | return output 203 | 204 | def looks_seteffectto(self, block, blocks): 205 | output = ['setGraphicEffect:to:'] 206 | field = self.converter.fieldVal('EFFECT', block) 207 | if type(field) == str: 208 | field = str.lower(field) 209 | output.append(field) 210 | output.append(self.converter.inputVal('VALUE', block, blocks)) 211 | return output 212 | 213 | def looks_cleargraphiceffects(self, block, blocks): 214 | return ['filterReset'] 215 | 216 | def looks_changesizeby(self, block, blocks): 217 | output = ['changeSizeBy:', self.converter.inputVal('CHANGE', block, blocks)] 218 | return output 219 | 220 | def looks_setsizeto(self, block, blocks): 221 | output = ['setSizeTo:', self.converter.inputVal('SIZE', block, blocks)] 222 | return output 223 | 224 | def looks_changestretchby(self, block, blocks): 225 | output = ['changeStretchBy:', self.converter.inputVal('CHANGE', block, blocks)] 226 | return output 227 | 228 | def looks_setstretchto(self, block, blocks): 229 | output = ['setStretchTo:', self.converter.inputVal('STRETCH', block, blocks)] 230 | return output 231 | 232 | def looks_gotofrontback(self, block, blocks): 233 | field = self.converter.fieldVal('FRONT_BACK', block) 234 | if field == 'front': 235 | return ['comeToFront'] 236 | else: 237 | return ['goBackByLayers:', 1.79e+308] 238 | 239 | def looks_goforwardbackwardlayers(self, block, blocks): 240 | layers = self.converter.inputVal('NUM', block, blocks) 241 | field = self.converter.fieldVal('FORWARD_BACKWARD', block) 242 | if field == 'forward': 243 | if type(layers) == str: 244 | try: 245 | layers = float(layers) 246 | except Exception as ex: 247 | pass 248 | if type(layers) == float or type(layers) == int: 249 | layers *= -1 250 | else: 251 | layers = ['*', -1, layers] 252 | return ['goBackByLayers:', layers] 253 | 254 | def looks_costumenumbername(self, block, blocks): 255 | field = self.converter.fieldVal('NUMBER_NAME', block) 256 | if field == 'number': 257 | return ['costumeIndex'] 258 | elif field == 'name': 259 | if not self.converter.convertingMonitors: 260 | if self.converter.compat: # Can't use getAttribute:of: because it doesn't work for clones 261 | self.converter.costumeName = True 262 | return ['getLine:ofList:', ['costumeIndex'], self.converter.compatVarName('costume names')] 263 | else: 264 | self.converter.generateWarning("Incompatible block 'costume [name v]'") 265 | self.converter.compatWarning = True 266 | return ['costumeName'] 267 | 268 | def looks_backdropnumbername(self, block, blocks): 269 | field = self.converter.fieldVal('NUMBER_NAME', block) 270 | if field == 'number': 271 | return ['backgroundIndex'] 272 | elif field == 'name': 273 | return ['sceneName'] 274 | 275 | def looks_size(self, block, blocks): 276 | return ['scale'] 277 | 278 | def looks_switchbackdroptoandwait(self, block, blocks): 279 | output = ['startSceneAndWait', self.converter.inputVal('BACKDROP', block, blocks)] 280 | return output 281 | 282 | # Sound 283 | 284 | def sound_play(self, block, blocks): 285 | output = ['playSound:', self.converter.inputVal('SOUND_MENU', block, blocks)] 286 | return output 287 | 288 | def sound_playuntildone(self, block, blocks): 289 | output = ['doPlaySoundAndWait', self.converter.inputVal('SOUND_MENU', block, blocks)] 290 | return output 291 | 292 | def sound_stopallsounds(self, block, blocks): 293 | return ['stopAllSounds'] 294 | 295 | def sound_changevolumeby(self, block, blocks): 296 | output = ['changeVolumeBy:', self.converter.inputVal('VOLUME', block, blocks)] 297 | return output 298 | 299 | def sound_setvolumeto(self, block, blocks): 300 | output = ['setVolumeTo:', self.converter.inputVal('VOLUME', block, blocks)] 301 | return output 302 | 303 | def sound_volume(self, block, blocks): 304 | return ['volume'] 305 | 306 | # Music 307 | 308 | def music_playDrumForBeats(self, block, blocks): 309 | output = ['playDrum', self.converter.inputVal('DRUM', block, blocks), 310 | self.converter.inputVal('BEATS', block, blocks)] 311 | return output 312 | 313 | def music_midiPlayDrumForBeats(self, block, blocks): 314 | output = ['drum:duration:elapsed:from:', self.converter.inputVal('DRUM', block, blocks), 315 | self.converter.inputVal('BEATS', block, blocks)] 316 | return output 317 | 318 | def music_restForBeats(self, block, blocks): 319 | output = ['rest:elapsed:from:', self.converter.inputVal('BEATS', block, blocks)] 320 | return output 321 | 322 | def music_playNoteForBeats(self, block, blocks): 323 | output = ['noteOn:duration:elapsed:from:', self.converter.inputVal('NOTE', block, blocks), 324 | self.converter.inputVal('BEATS', block, blocks)] 325 | return output 326 | 327 | def music_setInstrument(self, block, blocks): 328 | output = ['instrument:', self.converter.inputVal('INSTRUMENT', block, blocks)] 329 | return output 330 | 331 | def music_midiSetInstrument(self, block, blocks): 332 | output = ['midiInstrument:', self.converter.inputVal('INSTRUMENT', block, blocks)] 333 | return output 334 | 335 | def music_changeTempo(self, block, blocks): 336 | output = ['changeTempoBy:', self.converter.inputVal('TEMPO', block, blocks)] 337 | return output 338 | 339 | def music_setTempo(self, block, blocks): 340 | output = ['setTempoTo:', self.converter.inputVal('TEMPO', block, blocks)] 341 | return output 342 | 343 | def music_getTempo(self, block, blocks): 344 | return ['tempo'] 345 | 346 | # Pen 347 | 348 | def pen_clear(self, block, blocks): 349 | return ['clearPenTrails'] 350 | 351 | def pen_stamp(self, block, blocks): 352 | return ['stampCostume'] 353 | 354 | def pen_penDown(self, block, blocks): 355 | if self.converter.compat: 356 | self.converter.penUpDown = True 357 | return ['call', 'pen down'] 358 | else: 359 | return ['putPenDown'] 360 | 361 | def pen_penUp(self, block, blocks): 362 | if self.converter.compat: 363 | self.converter.penUpDown = True 364 | return ['call', 'pen up'] 365 | else: 366 | return ['putPenUp'] 367 | 368 | def pen_setPenColorToColor(self, block, blocks): 369 | if self.converter.compat: 370 | self.converter.penColor = True 371 | output = ['call', 'set pen color to %c'] 372 | else: 373 | output = ['penColor:'] 374 | output.append(self.converter.inputVal('COLOR', block, blocks)) 375 | return output 376 | 377 | def pen_changePenHueBy(self, block, blocks): 378 | if self.converter.compat: 379 | self.converter.penColor = True 380 | output = ['call', 'change pen color by %n'] 381 | else: 382 | output = ['changePenHueBy:'] 383 | output.append(self.converter.inputVal('HUE', block, blocks)) 384 | return output 385 | 386 | def pen_setPenHueToNumber(self, block, blocks): 387 | if self.converter.compat: 388 | self.converter.penColor = True 389 | output = ['call', 'set pen color to %n'] 390 | else: 391 | output = ['setPenHueTo:'] 392 | output.append(self.converter.inputVal('HUE', block, blocks)) 393 | return output 394 | 395 | def pen_changePenShadeBy(self, block, blocks): 396 | if self.converter.compat: 397 | self.converter.penColor = True 398 | output = ['call', 'change pen shade by %n'] 399 | else: 400 | output = ['changePenShadeBy:'] 401 | output.append(self.converter.inputVal('SHADE', block, blocks)) 402 | return output 403 | 404 | def pen_setPenShadeToNumber(self, block, blocks): 405 | if self.converter.compat: 406 | self.converter.penColor = True 407 | output = ['call', 'set pen shade to %n'] 408 | else: 409 | output = ['setPenShadeTo:'] 410 | output.append(self.converter.inputVal('SHADE', block, blocks)) 411 | return output 412 | 413 | def pen_changePenColorParamBy(self, block, blocks): 414 | param = self.converter.inputVal('COLOR_PARAM', block, blocks) 415 | value = self.converter.inputVal('VALUE', block, blocks) 416 | if self.converter.compat: 417 | self.converter.penColor = True 418 | return ['call', 'change pen %s by %n', param, value] 419 | else: 420 | self.converter.compatWarning = True 421 | if param == 'color': 422 | if type(value) == str: 423 | try: 424 | value = float(value) 425 | except Exception as ex: 426 | pass 427 | if type(value) == float or type(value) == int: 428 | value *= 2 429 | else: 430 | value = ['*', 2, value] 431 | output = ['changePenHueBy:', value] 432 | return output 433 | elif param == 'brightness': 434 | if type(value) == str: 435 | try: 436 | value = float(value) 437 | except Exception as ex: 438 | pass 439 | if type(value) == float or type(value) == int: 440 | value /= 2 441 | else: 442 | value = ['/', value, 2] 443 | output = ['changePenShadeBy:', value] 444 | return output 445 | else: 446 | if type(param) == list: 447 | paramStr = '[blocks...]' 448 | else: 449 | paramStr = param 450 | self.converter.generateWarning(f"Incompatible block 'change pen [{paramStr} v] by ({value})'") 451 | return ['pen_changeColorParamBy', value, param] 452 | 453 | def pen_setPenColorParamTo(self, block, blocks): 454 | param = self.converter.inputVal('COLOR_PARAM', block, blocks) 455 | value = self.converter.inputVal('VALUE', block, blocks) 456 | if self.converter.compat: 457 | self.converter.penColor = True 458 | return ['call', 'set pen %s to %n', param, value] 459 | else: 460 | self.converter.compatWarning = True 461 | if param == 'color': 462 | if type(value) == str: 463 | try: 464 | value = float(value) 465 | except Exception as ex: 466 | pass 467 | if type(value) == float or type(value) == int: 468 | value *= 2 469 | else: 470 | value = ['*', 2, value] 471 | output = ['setPenHueTo:', value] 472 | return output 473 | elif param == 'brightness': 474 | if type(value) == str: 475 | try: 476 | value = float(value) 477 | except Exception as ex: 478 | pass 479 | if type(value) == float or type(value) == int: 480 | value /= 2 481 | else: 482 | value = ['/', value, 2] 483 | output = ['setPenShadeTo:', value] 484 | return output 485 | else: 486 | if type(param) == list: 487 | paramStr = '[blocks...]' 488 | else: 489 | paramStr = param 490 | self.converter.generateWarning(f"Incompatible block 'set pen [{paramStr} v] to ({value})'") 491 | return ['pen_setPenColorParamTo', value, param] 492 | 493 | def pen_changePenSizeBy(self, block, blocks): 494 | output = ['changePenSizeBy:', self.converter.inputVal('SIZE', block, blocks)] 495 | return output 496 | 497 | def pen_setPenSizeTo(self, block, blocks): 498 | output = ['penSize:', self.converter.inputVal('SIZE', block, blocks)] 499 | return output 500 | 501 | # Events 502 | 503 | def event_whenflagclicked(self, block, blocks): 504 | return ['whenGreenFlag'] 505 | 506 | def event_whenkeypressed(self, block, blocks): 507 | output = ['whenKeyPressed', self.converter.fieldVal('KEY_OPTION', block)] 508 | return output 509 | 510 | def event_whenthisspriteclicked(self, block, blocks): 511 | return ['whenClicked'] 512 | 513 | def event_whenstageclicked(self, block, blocks): 514 | return ['whenClicked'] 515 | 516 | def event_whenbackdropswitchesto(self, block, blocks): 517 | output = ['whenSceneStarts', self.converter.fieldVal('BACKDROP', block)] 518 | return output 519 | 520 | def event_whengreaterthan(self, block, blocks): 521 | output = ['whenSensorGreaterThan'] 522 | field = self.converter.fieldVal('WHENGREATERTHANMENU', block) 523 | if type(field) == str: 524 | field = str.lower(field) 525 | output.append(field) 526 | output.append(self.converter.inputVal('VALUE', block, blocks)) 527 | return output 528 | 529 | def event_whenbroadcastreceived(self, block, blocks): 530 | output = ['whenIReceive', self.converter.fieldVal('BROADCAST_OPTION', block)] 531 | return output 532 | 533 | def event_broadcast(self, block, blocks): 534 | output = ['broadcast:', self.converter.inputVal('BROADCAST_INPUT', block, blocks)] 535 | return output 536 | 537 | def event_broadcastandwait(self, block, blocks): 538 | output = ['doBroadcastAndWait', self.converter.inputVal('BROADCAST_INPUT', block, blocks)] 539 | return output 540 | 541 | # Control 542 | 543 | def control_wait(self, block, blocks): 544 | output = ['wait:elapsed:from:', self.converter.inputVal('DURATION', block, blocks)] 545 | return output 546 | 547 | def control_repeat(self, block, blocks): 548 | output = ['doRepeat', self.converter.inputVal('TIMES', block, blocks), 549 | self.converter.substackVal('SUBSTACK', block, blocks)] 550 | return output 551 | 552 | def control_forever(self, block, blocks): 553 | output = ['doForever', self.converter.substackVal('SUBSTACK', block, blocks)] 554 | return output 555 | 556 | def control_if(self, block, blocks): 557 | output = ['doIf', self.converter.inputVal('CONDITION', block, blocks), 558 | self.converter.substackVal('SUBSTACK', block, blocks)] 559 | return output 560 | 561 | def control_if_else(self, block, blocks): 562 | output = ['doIfElse', self.converter.inputVal('CONDITION', block, blocks), 563 | self.converter.substackVal('SUBSTACK', block, blocks), 564 | self.converter.substackVal('SUBSTACK2', block, blocks)] 565 | return output 566 | 567 | def control_wait_until(self, block, blocks): 568 | output = ['doWaitUntil', self.converter.inputVal('CONDITION', block, blocks)] 569 | return output 570 | 571 | def control_repeat_until(self, block, blocks): 572 | output = ['doUntil', self.converter.inputVal('CONDITION', block, blocks), 573 | self.converter.substackVal('SUBSTACK', block, blocks)] 574 | return output 575 | 576 | def control_while(self, block, blocks): 577 | output = ['doWhile', self.converter.inputVal('CONDITION', block, blocks), 578 | self.converter.substackVal('SUBSTACK', block, blocks)] 579 | return output 580 | 581 | def control_for_each(self, block, blocks): 582 | output = ['doForLoop', self.converter.fieldVal('VARIABLE', block), 583 | self.converter.inputVal('VALUE', block, blocks), 584 | self.converter.substackVal('SUBSTACK', block, blocks)] 585 | return output 586 | 587 | def control_stop(self, block, blocks): 588 | output = ['stopScripts', self.converter.fieldVal('STOP_OPTION', block)] 589 | return output 590 | 591 | def control_start_as_clone(self, block, blocks): 592 | return ['whenCloned'] 593 | 594 | def control_create_clone_of(self, block, blocks): 595 | output = ['createCloneOf', self.converter.inputVal('CLONE_OPTION', block, blocks)] 596 | return output 597 | 598 | def control_delete_this_clone(self, block, blocks): 599 | return ['deleteClone'] 600 | 601 | def control_get_counter(self, block, blocks): 602 | return ['COUNT'] 603 | 604 | def control_incr_counter(self, block, blocks): 605 | return ['INCR_COUNT'] 606 | 607 | def control_clear_counter(self, block, blocks): 608 | return ['CLR_COUNT'] 609 | 610 | def control_all_at_once(self, block, blocks): 611 | output = ['warpSpeed', self.converter.substackVal('SUBSTACK', block, blocks)] 612 | return output 613 | 614 | # Video Sensing 615 | 616 | def videoSensing_videoOn(self, block, blocks): 617 | output = ['senseVideoMotion', self.converter.inputVal('ATTRIBUTE', block, blocks), 618 | self.converter.inputVal('SUBJECT', block, blocks)] 619 | return output 620 | 621 | def videoSensing_whenMotionGreaterThan(self, block, blocks): 622 | output = ['whenSensorGreaterThan', 'video motion', self.converter.inputVal('REFERENCE', block, blocks)] 623 | return output 624 | 625 | def videoSensing_videoToggle(self, block, blocks): 626 | output = ['setVideoState', self.converter.inputVal('VIDEO_STATE', block, blocks)] 627 | return output 628 | 629 | def videoSensing_setVideoTransparency(self, block, blocks): 630 | output = ['setVideoTransparency', self.converter.inputVal('TRANSPARENCY', block, blocks)] 631 | return output 632 | 633 | # Sensing 634 | 635 | def sensing_touchingobject(self, block, blocks): 636 | output = ['touching:', self.converter.inputVal('TOUCHINGOBJECTMENU', block, blocks)] 637 | return output 638 | 639 | def sensing_touchingcolor(self, block, blocks): 640 | output = ['touchingColor:', self.converter.inputVal('COLOR', block, blocks)] 641 | return output 642 | 643 | def sensing_coloristouchingcolor(self, block, blocks): 644 | output = ['color:sees:', self.converter.inputVal('COLOR', block, blocks), 645 | self.converter.inputVal('COLOR2', block, blocks)] 646 | return output 647 | 648 | def sensing_distanceto(self, block, blocks): 649 | output = ['distanceTo:', self.converter.inputVal('DISTANCETOMENU', block, blocks)] 650 | return output 651 | 652 | def sensing_askandwait(self, block, blocks): 653 | output = ['doAsk', self.converter.inputVal('QUESTION', block, blocks)] 654 | return output 655 | 656 | def sensing_answer(self, block, blocks): 657 | return ['answer'] 658 | 659 | def sensing_keypressed(self, block, blocks): 660 | output = ['keyPressed:', self.converter.inputVal('KEY_OPTION', block, blocks)] 661 | return output 662 | 663 | def sensing_mousedown(self, block, blocks): 664 | return ['mousePressed'] 665 | 666 | def sensing_mousex(self, block, blocks): 667 | return ['mouseX'] 668 | 669 | def sensing_mousey(self, block, blocks): 670 | return ['mouseY'] 671 | 672 | def sensing_setdragmode(self, block, blocks): 673 | assert self.converter.compat 674 | self.converter.dragMode = True 675 | return ['call', 'set drag mode %s', self.converter.fieldVal('DRAG_MODE', block)] 676 | 677 | def sensing_loudness(self, block, blocks): 678 | return ['soundLevel'] 679 | 680 | def sensing_loud(self, block, blocks): 681 | return ['isLoud'] 682 | 683 | def sensing_timer(self, block, blocks): 684 | if self.converter.compat: 685 | self.converter.timerCompat = True 686 | return ['*', 86400, ['-', ['timestamp'], ['readVariable', 'reset time']]] 687 | else: 688 | self.converter.compatWarning = True 689 | return ['timer'] 690 | 691 | def sensing_resettimer(self, block, blocks): 692 | if self.converter.compat: 693 | self.converter.resetTimer = True 694 | self.converter.timerCompat = True 695 | return ['call', 'reset timer'] 696 | else: 697 | return ['timerReset'] 698 | 699 | def sensing_of(self, block, blocks): 700 | attr = self.converter.fieldVal('PROPERTY', block) 701 | obj = self.converter.inputVal('OBJECT', block, blocks) 702 | if obj == '_stage_': 703 | if (type(attr) == list) or (attr not in BlockArgMapper.stageAttrs): 704 | attr = self.varName(attr) 705 | elif (type(attr) == list) or (attr not in BlockArgMapper.spriteAttrs): 706 | attr = self.varName(attr) 707 | return ['getAttribute:of:', attr, obj] 708 | 709 | def sensing_current(self, block, blocks): 710 | output = ['timeAndDate'] 711 | field = self.converter.fieldVal('CURRENTMENU', block) 712 | if type(field) == str: 713 | field = str.lower(field) 714 | output.append(field) 715 | return output 716 | 717 | def sensing_dayssince2000(self, block, blocks): 718 | return ['timestamp'] 719 | 720 | def sensing_username(self, block, blocks): 721 | if not self.converter.convertingMonitors: 722 | return ['getUserName'] 723 | 724 | def sensing_userid(self, block, blocks): 725 | return ['getUserId'] 726 | 727 | # Operators 728 | 729 | def operator_add(self, block, blocks): 730 | output = ['+', self.converter.inputVal('NUM1', block, blocks), self.converter.inputVal('NUM2', block, blocks)] 731 | return output 732 | 733 | def operator_subtract(self, block, blocks): 734 | output = ['-', self.converter.inputVal('NUM1', block, blocks), self.converter.inputVal('NUM2', block, blocks)] 735 | return output 736 | 737 | def operator_multiply(self, block, blocks): 738 | output = ['*', self.converter.inputVal('NUM1', block, blocks), self.converter.inputVal('NUM2', block, blocks)] 739 | return output 740 | 741 | def operator_divide(self, block, blocks): 742 | output = ['/', self.converter.inputVal('NUM1', block, blocks), self.converter.inputVal('NUM2', block, blocks)] 743 | return output 744 | 745 | def operator_random(self, block, blocks): 746 | output = ['randomFrom:to:', self.converter.inputVal('FROM', block, blocks), 747 | self.converter.inputVal('TO', block, blocks)] 748 | return output 749 | 750 | def operator_gt(self, block, blocks): 751 | output = ['>', self.converter.inputVal('OPERAND1', block, blocks), 752 | self.converter.inputVal('OPERAND2', block, blocks)] 753 | return output 754 | 755 | def operator_lt(self, block, blocks): 756 | output = ['<', self.converter.inputVal('OPERAND1', block, blocks), 757 | self.converter.inputVal('OPERAND2', block, blocks)] 758 | return output 759 | 760 | def operator_equals(self, block, blocks): 761 | output = ['=', self.converter.inputVal('OPERAND1', block, blocks), 762 | self.converter.inputVal('OPERAND2', block, blocks)] 763 | return output 764 | 765 | def operator_and(self, block, blocks): 766 | output = ['&', self.converter.inputVal('OPERAND1', block, blocks), 767 | self.converter.inputVal('OPERAND2', block, blocks)] 768 | return output 769 | 770 | def operator_or(self, block, blocks): 771 | output = ['|', self.converter.inputVal('OPERAND1', block, blocks), 772 | self.converter.inputVal('OPERAND2', block, blocks)] 773 | return output 774 | 775 | def operator_not(self, block, blocks): 776 | output = ['not', self.converter.inputVal('OPERAND', block, blocks)] 777 | return output 778 | 779 | def operator_join(self, block, blocks): 780 | if self.converter.unlimJoin: 781 | self.converter.joinStr = True 782 | stackReporter = ['call', 'join %s %s', self.converter.inputVal('STRING1', block, blocks), 783 | self.converter.inputVal('STRING2', block, blocks)] 784 | self.converter.compatStackReporters[-1].append(stackReporter) 785 | return ['getLine:ofList:', len(self.converter.compatStackReporters[-1]), 786 | self.converter.compatVarName('results')] 787 | else: 788 | output = ['concatenate:with:', self.converter.inputVal('STRING1', block, blocks), 789 | self.converter.inputVal('STRING2', block, blocks)] 790 | return output 791 | 792 | def operator_letter_of(self, block, blocks): 793 | output = ['letter:of:', self.converter.inputVal('LETTER', block, blocks), 794 | self.converter.inputVal('STRING', block, blocks)] 795 | return output 796 | 797 | def operator_length(self, block, blocks): 798 | output = ['stringLength:', self.converter.inputVal('STRING', block, blocks)] 799 | return output 800 | 801 | def operator_contains(self, block, blocks): 802 | assert self.converter.compat 803 | self.converter.strContains = True 804 | stackReporter = ['call', '%s contains %s ?', self.converter.inputVal('STRING1', block, blocks), 805 | self.converter.inputVal('STRING2', block, blocks)] 806 | self.converter.compatStackReporters[-1].append(stackReporter) 807 | return ['getLine:ofList:', len(self.converter.compatStackReporters[-1]), 808 | self.converter.compatVarName('results')] 809 | 810 | def operator_mod(self, block, blocks): 811 | output = ['%', self.converter.inputVal('NUM1', block, blocks), self.converter.inputVal('NUM2', block, blocks)] 812 | return output 813 | 814 | def operator_round(self, block, blocks): 815 | output = ['rounded', self.converter.inputVal('NUM', block, blocks)] 816 | return output 817 | 818 | def operator_mathop(self, block, blocks): 819 | output = ['computeFunction:of:', self.converter.fieldVal('OPERATOR', block), 820 | self.converter.inputVal('NUM', block, blocks)] 821 | return output 822 | 823 | # Data 824 | 825 | def data_variable(self, block, blocks): 826 | output = ['readVariable', self.converter.fieldVal('VARIABLE', block)] 827 | return output 828 | 829 | def data_setvariableto(self, block, blocks): 830 | output = ['setVar:to:', self.converter.fieldVal('VARIABLE', block), 831 | self.converter.inputVal('VALUE', block, blocks)] 832 | return output 833 | 834 | def data_changevariableby(self, block, blocks): 835 | output = ['changeVar:by:', self.converter.fieldVal('VARIABLE', block), 836 | self.converter.inputVal('VALUE', block, blocks)] 837 | return output 838 | 839 | def data_showvariable(self, block, blocks): 840 | output = ['showVariable:', self.converter.fieldVal('VARIABLE', block)] 841 | return output 842 | 843 | def data_hidevariable(self, block, blocks): 844 | output = ['hideVariable:', self.converter.fieldVal('VARIABLE', block)] 845 | return output 846 | 847 | def data_listcontents(self, block, blocks): 848 | output = ['contentsOfList:', self.converter.fieldVal('LIST', block)] 849 | return output 850 | 851 | def data_addtolist(self, block, blocks): 852 | if self.converter.limList: 853 | self.converter.addList = True 854 | output = ['call', 'add %s to %m.list'] 855 | else: 856 | output = ['append:toList:'] 857 | output.append(self.converter.inputVal('ITEM', block, blocks)) 858 | output.append(self.converter.fieldVal('LIST', block)) 859 | return output 860 | 861 | def data_deleteoflist(self, block, blocks): 862 | output = ['deleteLine:ofList:', self.converter.inputVal('INDEX', block, blocks), 863 | self.converter.fieldVal('LIST', block)] 864 | return output 865 | 866 | def data_deletealloflist(self, block, blocks): 867 | output = ['deleteLine:ofList:', 'all', self.converter.fieldVal('LIST', block)] 868 | return output 869 | 870 | def data_insertatlist(self, block, blocks): 871 | if self.converter.limList: 872 | self.converter.insertList = True 873 | output = ['call', 'insert %s at %n of %m.list'] 874 | else: 875 | output = ['insert:at:ofList:'] 876 | output.append(self.converter.inputVal('ITEM', block, blocks)) 877 | output.append(self.converter.inputVal('INDEX', block, blocks)) 878 | output.append(self.converter.fieldVal('LIST', block)) 879 | return output 880 | 881 | def data_replaceitemoflist(self, block, blocks): 882 | output = ['setLine:ofList:to:', self.converter.inputVal('INDEX', block, blocks), 883 | self.converter.fieldVal('LIST', block), self.converter.inputVal('ITEM', block, blocks)] 884 | return output 885 | 886 | def data_itemoflist(self, block, blocks): 887 | output = ['getLine:ofList:', self.converter.inputVal('INDEX', block, blocks), 888 | self.converter.fieldVal('LIST', block)] 889 | return output 890 | 891 | def data_itemnumoflist(self, block, blocks): 892 | assert self.converter.compat 893 | self.converter.listSearch = True 894 | stackReporter = ['call', 'item # of %s in %m.list', self.converter.inputVal('ITEM', block, blocks), 895 | self.converter.fieldVal('LIST', block)] 896 | self.converter.compatStackReporters[-1].append(stackReporter) 897 | return ['getLine:ofList:', len(self.converter.compatStackReporters[-1]), 898 | self.converter.compatVarName('results')] 899 | 900 | def data_lengthoflist(self, block, blocks): 901 | output = ['lineCountOfList:', self.converter.fieldVal('LIST', block)] 902 | return output 903 | 904 | def data_listcontainsitem(self, block, blocks): 905 | output = ['list:contains:', self.converter.fieldVal('LIST', block), 906 | self.converter.inputVal('ITEM', block, blocks)] 907 | return output 908 | 909 | def data_showlist(self, block, blocks): 910 | output = ['showList:', self.converter.fieldVal('LIST', block)] 911 | return output 912 | 913 | def data_hidelist(self, block, blocks): 914 | output = ['hideList:', self.converter.fieldVal('LIST', block)] 915 | return output 916 | 917 | # Procedures 918 | 919 | def procedures_definition(self, block, blocks): 920 | block = blocks[block['inputs']['custom_block'][1]] 921 | procData = block['mutation'] 922 | output = ['procDef', self.varName(procData['proccode']), json.loads(procData['argumentnames']), 923 | json.loads(procData['argumentdefaults'])] 924 | if len(output[-1]) != len(output[-2]): 925 | output[-1] = len(output[-2]) * [''] 926 | warp = procData['warp'] 927 | output.append(warp == 'true' or (type(warp) == bool and warp)) 928 | return output 929 | 930 | def procedures_call(self, block, blocks): 931 | output = ['call', self.varName(block['mutation']['proccode'])] 932 | ids = json.loads(block['mutation']['argumentids']) 933 | for i in ids: 934 | output.append(self.converter.inputVal(i, block, blocks)) 935 | return output 936 | 937 | def argument_reporter_string_number(self, block, blocks): 938 | output = ['getParam', self.converter.fieldVal('VALUE', block), 'r'] 939 | return output 940 | 941 | def argument_reporter_boolean(self, block, blocks): 942 | output = ['getParam', self.converter.fieldVal('VALUE', block), 'b'] 943 | return output 944 | 945 | # LEGO WeDo 2.0 946 | 947 | def wedo2_motorOnFor(self, block, blocks): 948 | output = ['LEGO WeDo 2.0\u001fmotorOnFor', self.converter.inputVal('MOTOR_ID', block, blocks), 949 | self.converter.inputVal('DURATION', block, blocks)] 950 | return output 951 | 952 | def wedo2_motorOn(self, block, blocks): 953 | output = ['LEGO WeDo 2.0\u001fmotorOn', self.converter.inputVal('MOTOR_ID', block, blocks)] 954 | return output 955 | 956 | def wedo2_motorOff(self, block, blocks): 957 | output = ['LEGO WeDo 2.0\u001fmotorOff', self.converter.inputVal('MOTOR_ID', block, blocks)] 958 | return output 959 | 960 | def wedo2_startMotorPower(self, block, blocks): 961 | output = ['LEGO WeDo 2.0\u001fstartMotorPower', self.converter.inputVal('MOTOR_ID', block, blocks), 962 | self.converter.inputVal('POWER', block, blocks)] 963 | return output 964 | 965 | def wedo2_setMotorDirection(self, block, blocks): 966 | output = ['LEGO WeDo 2.0\u001fsetMotorDirection', self.converter.inputVal('MOTOR_ID', block, blocks), 967 | self.converter.inputVal('MOTOR_DIRECTION', block, blocks)] 968 | return output 969 | 970 | def wedo2_setLightHue(self, block, blocks): 971 | output = ['LEGO WeDo 2.0\u001fsetLED', self.converter.inputVal('HUE', block, blocks)] 972 | return output 973 | 974 | def wedo2_playNoteFor(self, block, blocks): 975 | output = ['LEGO WeDo 2.0\u001fplayNote', self.converter.inputVal('NOTE', block, blocks), 976 | self.converter.inputVal('DURATION', block, blocks)] 977 | return output 978 | 979 | def wedo2_whenDistance(self, block, blocks): 980 | output = ['LEGO WeDo 2.0\u001fwhenDistance', self.converter.inputVal('OP', block, blocks), 981 | self.converter.inputVal('REFERENCE', block, blocks)] 982 | return output 983 | 984 | def wedo2_whenTilted(self, block, blocks): 985 | output = ['LEGO WeDo 2.0\u001fwhenTilted', self.converter.inputVal('TILT_DIRECTION_ANY', block, blocks)] 986 | return output 987 | 988 | def wedo2_getDistance(self, block, blocks): 989 | return ['LEGO WeDo 2.0\u001fgetDistance'] 990 | 991 | def wedo2_isTilted(self, block, blocks): 992 | output = ['LEGO WeDo 2.0\u001fisTilted', self.converter.inputVal('TILT_DIRECTION_ANY', block, blocks)] 993 | return output 994 | 995 | def wedo2_getTiltAngle(self, block, blocks): 996 | output = ['LEGO WeDo 2.0\u001fgetTilt', self.converter.inputVal('TILT_DIRECTION', block, blocks)] 997 | return output 998 | 999 | 1000 | class ProjectConverter: 1001 | varModes = { 1002 | 'default': 1, 1003 | 'large': 2, 1004 | 'slider': 3 1005 | } 1006 | 1007 | rotationStyles = { 1008 | 'all around': 'normal', 1009 | 'left-right': 'leftRight', 1010 | 'don\'t rotate': 'none' 1011 | } 1012 | 1013 | monitorColors = { 1014 | 'motion': 4877524, 1015 | 'looks': 9065943, 1016 | 'sound': 12272323, 1017 | 'music': 12272323, 1018 | 'sensing': 2926050, 1019 | 'data': 15629590 1020 | } 1021 | 1022 | # Used to change variable names in hacked reporters if in compatibility mode 1023 | sb2BlocksVarFields = { 1024 | 'setVar:to:': 1, 1025 | 'changeVar:by:': 1, 1026 | 'showVariable:': 1, 1027 | 'hideVariable:': 1, 1028 | 'readVariable': 1, 1029 | 'contentsOfList:': 1, 1030 | 'append:toList:': 2, 1031 | 'deleteLine:ofList:': 2, 1032 | 'insert:at:ofList:': 3, 1033 | 'setLine:ofList:to:': 2, 1034 | 'getLine:ofList:': 2, 1035 | 'lineCountOfList:': 1, 1036 | 'list:contains:': 1, 1037 | 'showList:': 1, 1038 | 'hideList:': 1 1039 | } 1040 | 1041 | compatWarnings = { 1042 | 'sensing_setdragmode', 1043 | 'operator_contains', 1044 | 'data_itemnumoflist' 1045 | } 1046 | 1047 | @staticmethod 1048 | def hexToDec(hexNum): 1049 | try: 1050 | return int(hexNum[1:], 16) 1051 | except Exception as ex: 1052 | return hexNum 1053 | 1054 | @staticmethod 1055 | def specialNum(num): 1056 | if num == '-Infinity': 1057 | return float('-inf') 1058 | if num == 'Infinity': 1059 | return float('inf') 1060 | if num == 'NaN': 1061 | return float('nan') 1062 | return num 1063 | 1064 | def __init__(self): 1065 | self.argmapper = BlockArgMapper(self) 1066 | self.blockID = 0 1067 | self.comments = [] 1068 | self.blockComments = {} 1069 | self.compatStackReporters = [] 1070 | self.compatWarning = False 1071 | self.convertingMonitors = False 1072 | 1073 | def varName(self, name): 1074 | if type(name) == str: 1075 | return ('\xa0' if self.compat else '') + name 1076 | else: 1077 | if self.compat: 1078 | return ['concatenate:with:', '\xa0', name] 1079 | else: 1080 | return name 1081 | 1082 | def compatVarName(self, name): 1083 | return ('Stage: ' if self.targetIsStage else '') + name 1084 | 1085 | def generateWarning(self, message): 1086 | self.warnings += 1 1087 | printWarning(message) 1088 | 1089 | def setCommentBlockID(self, id): 1090 | if id in self.blockComments: 1091 | self.comments[self.blockComments[id]][5] = self.blockID 1092 | 1093 | def convertHackedReporter(self, reporter): 1094 | if self.compat: # Add underscore to variable names if in compatibility mode 1095 | block = reporter[0] 1096 | if block in ProjectConverter.sb2BlocksVarFields: 1097 | index = ProjectConverter.sb2BlocksVarFields[block] 1098 | reporter[index] = self.varName(reporter[index]) 1099 | elif block == 'getAttribute:of:': 1100 | if reporter[2] == '_stage_': 1101 | if reporter[1] not in BlockArgMapper.stageAttrs: 1102 | reporter[1] = self.varName(reporter[1]) 1103 | elif reporter[1] not in BlockArgMapper.spriteAttrs: 1104 | reporter[1] = self.varName(reporter[1]) 1105 | for value in reporter: 1106 | if type(value) == list: 1107 | self.convertHackedReporter(value) 1108 | 1109 | def convertBlock(self, block, blocks): 1110 | opcode = block['opcode'] 1111 | try: 1112 | output = self.argmapper.mapArgs(opcode, block, blocks) 1113 | output.append(tuple([block['UID']])) 1114 | return output 1115 | except Exception as ex: 1116 | if len(block['inputs']) == 0 and len(block['fields']) == 1 and block['shadow'] and not block[ 1117 | 'topLevel']: # Menu opcodes and shadows 1118 | return self.fieldVal(list(block['fields'].items())[0][0], block) 1119 | elif block['shadow'] and block['topLevel']: 1120 | # Probably an invisible block 1121 | return None 1122 | else: 1123 | self.generateWarning(f"Incompatible opcode '{opcode}'") 1124 | if opcode in ProjectConverter.compatWarnings: 1125 | self.compatWarning = True 1126 | 1127 | output = [opcode] 1128 | for i in block['inputs']: 1129 | value = self.inputVal(i, block, blocks) 1130 | output.append(value) 1131 | for f in block['fields']: 1132 | value = self.fieldVal(f, block) 1133 | output.append(value) 1134 | output.append(tuple([block['UID']])) 1135 | return output 1136 | 1137 | def inputVal(self, value, block, blocks): 1138 | 1139 | if not value in block['inputs']: 1140 | return False 1141 | 1142 | value = block['inputs'][value] 1143 | if value[1] is None: 1144 | return None 1145 | if value[0] == 1: 1146 | if type(value[1]) == str: 1147 | return self.convertBlock(blocks[value[1]], blocks) 1148 | else: 1149 | output = value[1][1] 1150 | else: 1151 | out = value[1] 1152 | if type(out) == list: 1153 | if out[0] == 12: 1154 | return ['readVariable', self.varName(out[1])] 1155 | elif out[0] == 13: 1156 | return ['contentsOfList:', self.varName(out[1])] 1157 | else: 1158 | try: 1159 | return out[1] 1160 | except Exception as ex: 1161 | return 1162 | else: 1163 | try: 1164 | return self.convertBlock(blocks[out], blocks) 1165 | except Exception as ex: 1166 | return False 1167 | 1168 | outType = value[1][0] 1169 | if outType in [4, 5, 8]: 1170 | try: 1171 | string = str(output) 1172 | output = float(output) 1173 | if output % 1 == 0 and not ('.' in string): 1174 | output = int(output) 1175 | except ValueError: 1176 | pass 1177 | elif outType in [6, 7]: 1178 | try: 1179 | output = float(output) 1180 | if output % 1 == 0: 1181 | output = int(output) 1182 | except ValueError: 1183 | pass 1184 | elif outType == 9: 1185 | output = ProjectConverter.hexToDec(output) 1186 | 1187 | return ProjectConverter.specialNum(output) 1188 | 1189 | def fieldVal(self, value, block): 1190 | 1191 | if not value in block['fields']: 1192 | return None 1193 | 1194 | output = block['fields'][value][0] 1195 | if type(output) == list: 1196 | self.convertHackedReporter(output) 1197 | if value in ['VARIABLE', 'LIST']: 1198 | output = self.varName(output) 1199 | 1200 | return output 1201 | 1202 | def convertSubstack(self, key, blocks): 1203 | self.compatStackReporters.append([]) 1204 | block = blocks[key] 1205 | script = [] 1206 | end = False 1207 | while not end: 1208 | self.compatStackReporters[-1] = [] 1209 | output = self.convertBlock(block, blocks) 1210 | sReporters = self.compatStackReporters[-1] 1211 | if len(sReporters) > 0: 1212 | script.append(['deleteLine:ofList:', 'all', self.compatVarName('results')]) 1213 | script.extend(self.compatStackReporters[-1]) 1214 | if output[0] == 'doUntil': 1215 | if type(output[2]) != list: 1216 | output[2] = [] 1217 | output[2].append(['deleteLine:ofList:', 'all', self.compatVarName('results')]) 1218 | output[2].extend(self.compatStackReporters[-1]) 1219 | script.append(output) 1220 | if block['next'] is None: 1221 | end = True 1222 | else: 1223 | block = blocks[block['next']] 1224 | del self.compatStackReporters[-1] 1225 | return script 1226 | 1227 | def substackVal(self, stack, block, blocks): 1228 | 1229 | if not stack in block['inputs']: 1230 | return None 1231 | 1232 | stack = block['inputs'][stack] 1233 | if len(stack) < 2 or stack[1] is None: 1234 | return [] 1235 | 1236 | return self.convertSubstack(stack[1], blocks) 1237 | 1238 | def addComment(self, c): 1239 | comment = [] 1240 | if c['x'] is None: 1241 | x = None 1242 | else: 1243 | x = round(c['x'] / 1.5, 6) 1244 | if x % 1 == 0: 1245 | x = int(x) 1246 | comment.append(x) 1247 | if c['y'] is None: 1248 | y = None 1249 | else: 1250 | y = round(c['y'] / 1.8, 6) 1251 | if y % 1 == 0: 1252 | y = int(y) 1253 | comment.append(y) 1254 | comment.append(c['width']) 1255 | comment.append(c['height']) 1256 | comment.append(not c['minimized']) 1257 | comment.append(-1) 1258 | comment.append(c['text']) 1259 | 1260 | if c['blockId'] is not None: 1261 | self.blockComments[c['blockId']] = len(self.comments) 1262 | 1263 | self.comments.append(comment) 1264 | 1265 | def addSound(self, s): 1266 | 1267 | scount = s['sampleCount'] 1268 | srate = s['rate'] 1269 | 1270 | if not s['assetId'] in self.soundAssets: 1271 | 1272 | md5 = s['assetId'] 1273 | self.soundAssets[s['assetId']] = [len(self.soundAssets)] 1274 | 1275 | if s['dataFormat'] == 'wav': 1276 | f = self.zfsb3.open(s['md5ext'], 'r') 1277 | wav = bytes(f.read()) 1278 | try: 1279 | wavData = wave.open(io.BytesIO(wav), 'rb') 1280 | sampData = wavData.readframes(wavData.getnframes()) 1281 | width = wavData.getsampwidth() 1282 | channels = wavData.getnchannels() 1283 | srate = wavData.getframerate() 1284 | wavData.close() 1285 | except Exception as ex: 1286 | # Original solution which works in most cases 1287 | sampData = wav[44:] 1288 | width = int.from_bytes(wav[34:36], byteorder='little') // 8 1289 | channels = int.from_bytes(wav[22:24], byteorder='little') 1290 | srate = int.from_bytes(wav[24:28], byteorder='little') 1291 | 1292 | modified = False 1293 | error = width * channels == 0 or (len(sampData) - 44) % (width * channels) != 0 1294 | 1295 | if not error: 1296 | try: 1297 | if channels == 2: # Convert to mono 1298 | sampData = audioop.tomono(sampData, width, 1, 1) 1299 | modified = True 1300 | 1301 | if srate > 22050 and srate != 44100 and not error: # Downsample 1302 | sampData = audioop.ratecv(sampData, width, 1, srate, 22050, None)[0] 1303 | srate = 22050 1304 | modified = True 1305 | except Exception as ex: 1306 | error = True 1307 | 1308 | if modified: 1309 | size = len(sampData) 1310 | scount = size // width 1311 | try: 1312 | wavFile = io.BytesIO() 1313 | wavData = wave.open(wavFile, 'wb') 1314 | wavData.setsampwidth(width) 1315 | wavData.setnchannels(1) 1316 | wavData.setframerate(srate) 1317 | wavData.setnframes(scount) 1318 | wavData.writeframes(sampData) 1319 | wavData.close() 1320 | wavFile.seek(0) 1321 | wav = wavFile.read() 1322 | except Exception as ex: 1323 | # Original solution which works in most cases 1324 | wav = wav[0:22] + (1).to_bytes(2, byteorder='little') + srate.to_bytes(4, 1325 | byteorder='little') + wav[ 1326 | 28:40] + size.to_bytes( 1327 | 4, byteorder='little') + sampData 1328 | self.soundAssets[s['assetId']].append(False) 1329 | md5 = hashlib.md5(wav).hexdigest() 1330 | elif error and not srate <= 22050 and not channels == 1: 1331 | srate = s['rate'] 1332 | self.soundAssets[s['assetId']].append(True) 1333 | else: 1334 | self.soundAssets[s['assetId']].append(False) 1335 | 1336 | self.zfsb2.writestr(f'{len(self.soundAssets) - 1}.{s["dataFormat"]}', wav) 1337 | f.close() 1338 | else: 1339 | self.soundAssets[s['assetId']].append(False) 1340 | 1341 | self.soundAssets[s['assetId']].append(scount) 1342 | self.soundAssets[s['assetId']].append(srate) 1343 | self.soundAssets[s['assetId']].append(md5) 1344 | 1345 | if s['dataFormat'] != 'wav': 1346 | self.generateWarning(f"Sound '{s['name']}' cannot be converted into WAV") 1347 | elif self.soundAssets[s['assetId']][1] == True: 1348 | self.generateWarning(f"Sound '{s['name']}' cannot be converted to mono or downsampled") 1349 | 1350 | fileData = self.soundAssets[s['assetId']] 1351 | sound = { 1352 | 'soundName': s['name'], 1353 | 'soundID': fileData[0], 1354 | 'md5': fileData[4] + '.wav', 1355 | 'sampleCount': fileData[2], 1356 | 'rate': fileData[3], 1357 | 'format': '' 1358 | } 1359 | 1360 | self.sounds.append(sound) 1361 | 1362 | def addCostume(self, c): 1363 | 1364 | if not c['assetId'] in self.costumeAssets: 1365 | if 'md5ext' in c: 1366 | md5ext = c['md5ext'] 1367 | else: 1368 | md5ext = f'{c["assetId"]}.{c["dataFormat"]}' 1369 | self.costumeAssets[c['assetId']] = [len(self.costumeAssets)] 1370 | 1371 | f = self.zfsb3.open(c['md5ext'], 'r') 1372 | img = f.read() 1373 | if c['dataFormat'] == 'svg': 1374 | img = str(img, encoding='utf-8') 1375 | 1376 | # Remove incorrect attributes added by Scratch 3.0 1377 | # The correct values are found in the style attribute 1378 | 1379 | img = img.replace('fill="undefined"', '') # Remove undefined fill 1380 | 1381 | # Remove incorrect stroke-width 1382 | if ';stroke-width:' in img: # Check if stroke-width is in style attribute (may incorrectly remove some stroke-width attributes) 1383 | left = 0 1384 | while left != -1: 1385 | left = img.find('stroke-width="', left) 1386 | if left != -1: 1387 | right = img.find('"', left + 14) + 1 1388 | img = img[0:left] + '' + img[right:] 1389 | left = right 1390 | 1391 | # Reposition bitmap images to their correct position 1392 | 1393 | if 'image' in img: 1394 | 1395 | left = 0 1396 | while left != -1: 1397 | left = img.find('', left) + 7 1437 | 1438 | innerLeft = img.find('>', left) + 1 1439 | attrs = img[left:innerLeft - 1] + ' ' 1440 | i = attrs.find('id="') # Remove id attribute 1441 | if i != -1: 1442 | j = attrs.find('"', i + 4) 1443 | attrs = attrs[0:i] + attrs[j + 1:] 1444 | attrs = attrs.replace('font-family="Sans Serif"', 'font-family="Helvetica"') 1445 | attrs = attrs.replace('font-family="Serif"', 'font-family="Donegal"') 1446 | attrs = attrs.replace('font-family="Handwriting"', 'font-family="Gloria"') 1447 | attrs = attrs.replace('font-family="Curly"', 'font-family="Mystery"') 1448 | attrs = attrs.replace('xml:space="preserve"', '') 1449 | 1450 | left = right 1451 | 1452 | # Remove tspan elements 1453 | text = '' 1454 | lineCount = 0 1455 | content = img[innerLeft:right - 7] 1456 | if 'tspan' in content: 1457 | while innerLeft != -1: 1458 | innerLeft = img.find('', innerLeft, right) + 1 1463 | innerRight = img.find('', innerLeft, right) 1464 | text += img[innerLeft:innerRight] + '\n' 1465 | innerLeft = innerRight + 7 1466 | 1467 | text = text[0:-1] 1468 | text = text + '' 1469 | else: 1470 | text += content + '' 1471 | 1472 | # Fix misplaced text 1473 | matLeft = attrs.find('matrix') 1474 | if matLeft != -1: 1475 | try: 1476 | matRight = attrs.find('"', matLeft) 1477 | matrix = attrs[matLeft:matRight].split(' ') 1478 | x = matrix[-2] 1479 | if x[-1] == ',': 1480 | x = x[0:-1] 1481 | scX = matrix[0][7:] 1482 | if scX[-1] == ',': 1483 | scX = scX[0:-1] 1484 | matrix[-2] = str(float(x) - 2.5 * float(scX)) 1485 | scY = matrix[3] 1486 | if scY[-1] == ',': 1487 | scY = scY[0:-1] 1488 | matrix[-1] = str(float(matrix[-1][0:-1]) + 2.5 * float(scY)) + ')' 1489 | matrix = ' '.join(matrix) 1490 | attrs = attrs[0:matLeft] + matrix + attrs[matRight:] 1491 | except Exception as ex: 1492 | self.generateWarning( 1493 | f"Costume '{c['name']}' may have incorrect text positioning") 1494 | else: 1495 | trLeft = attrs.find('translate') 1496 | scLeft = attrs.find('scale') 1497 | if not (trLeft == -1 or scLeft == -1): 1498 | try: 1499 | scRight = attrs.find('"', scLeft) 1500 | 1501 | i = trLeft + 10 1502 | trX = '' 1503 | while attrs[i] not in ', ': 1504 | trX += attrs[i] 1505 | i += 1 1506 | while attrs[i] in ', ': 1507 | i += 1 1508 | trY = '' 1509 | while attrs[i] not in ' )': 1510 | trY += attrs[i] 1511 | i += 1 1512 | trX = float(trX) 1513 | trY = float(trY) 1514 | 1515 | i = scLeft + 6 1516 | scX = '' 1517 | while attrs[i] not in ', ': 1518 | scX += attrs[i] 1519 | i += 1 1520 | while attrs[i] in ', ': 1521 | i += 1 1522 | scY = '' 1523 | while attrs[i] not in ' )': 1524 | scY += attrs[i] 1525 | i += 1 1526 | scX = float(scX) 1527 | scY = float(scY) 1528 | if lineCount > 1: 1529 | trY -= 40 * scY 1530 | else: 1531 | trY -= 25 * scY 1532 | matrix = f'matrix({scX} 0 0 {scY} {trX} {trY})' 1533 | attrs = attrs[0:trLeft] + matrix + attrs[scRight:] 1534 | except Exception as ex: 1535 | self.generateWarning( 1536 | f"Costume '{c['name']}' may have incorrect text positioning") 1537 | 1538 | text = attrs + '>' + text 1539 | newImg += text 1540 | left = right 1541 | else: 1542 | newImg += img[oldLeft:] 1543 | 1544 | img = newImg 1545 | 1546 | md5ext = hashlib.md5(img.encode('utf-8')).hexdigest() + '.svg' 1547 | else: 1548 | img = bytes(img) 1549 | self.zfsb2.writestr(f'{len(self.costumeAssets) - 1}.{c["dataFormat"]}', img) 1550 | f.close() 1551 | 1552 | self.costumeAssets[c['assetId']].append(md5ext) 1553 | 1554 | fileData = self.costumeAssets[c['assetId']] 1555 | costume = { 1556 | 'costumeName': c['name'], 1557 | 'baseLayerID': fileData[0], 1558 | 'baseLayerMD5': fileData[1], 1559 | 'rotationCenterX': c['rotationCenterX'], 1560 | 'rotationCenterY': c['rotationCenterY'] 1561 | } 1562 | 1563 | if ('bitmapResolution' in c) and (fileData[1][-3:] != 'svg'): 1564 | costume['bitmapResolution'] = c['bitmapResolution'] 1565 | else: 1566 | costume['bitmapResolution'] = 1 1567 | 1568 | self.costumes.append(costume) 1569 | 1570 | def getCommentBlockIDs(self, script): 1571 | if len(script) > 0: 1572 | UID = script[-1] 1573 | if type(UID) == tuple: 1574 | self.setCommentBlockID(UID[0]) 1575 | del script[-1] 1576 | if type(script[0]) == str: 1577 | self.blockID += 1 1578 | if script[0] == 'procDef': 1579 | self.blockID += 1 + len(script[2]) 1580 | else: 1581 | for block in script: 1582 | if type(block) == list: 1583 | self.getCommentBlockIDs(block) 1584 | 1585 | def convertTarget(self, target, index, maxLen): 1586 | 1587 | sprite = {} 1588 | 1589 | sprite['objName'] = target['name'] 1590 | self.targetName = sprite['objName'] 1591 | scripts = [] 1592 | variables = [] 1593 | lists = [] 1594 | self.sounds = [] 1595 | self.costumes = [] 1596 | self.comments = [] 1597 | 1598 | isStage = target['isStage'] 1599 | self.targetIsStage = isStage 1600 | 1601 | self.costumeName = False 1602 | self.dragMode = False 1603 | if not isStage: 1604 | self.dragMode = target['draggable'] 1605 | self.penUpDown = False 1606 | self.joinStr = False 1607 | self.strContains = False 1608 | self.listSearch = False 1609 | self.addList = False 1610 | self.insertList = False 1611 | self.penColor = False 1612 | self.resetTimer = False 1613 | 1614 | for s in target['sounds']: 1615 | self.addSound(s) 1616 | 1617 | for c in target['costumes']: 1618 | self.addCostume(c) 1619 | 1620 | for key, v in target['variables'].items(): 1621 | variable = { 1622 | 'name': self.varName(v[0]), 1623 | 'value': ProjectConverter.specialNum(v[1]), 1624 | 'isPersistent': len(v) >= 3 and v[2] 1625 | } 1626 | variables.append(variable) 1627 | 1628 | for key, l in target['lists'].items(): 1629 | ls = { 1630 | 'listName': self.varName(l[0]), 1631 | 'contents': [ProjectConverter.specialNum(item) for item in l[1]], 1632 | 'isPersistent': False 1633 | } 1634 | lists.append(ls) 1635 | 1636 | self.blockComments = {} 1637 | 1638 | for key, c in target['comments'].items(): 1639 | self.addComment(c) 1640 | 1641 | blocks = target['blocks'] 1642 | 1643 | for key, b in blocks.items(): 1644 | if type(b) == dict: 1645 | b['UID'] = key 1646 | 1647 | for key, b in blocks.items(): 1648 | 1649 | if type(b) == list: 1650 | 1651 | try: 1652 | x = round(b[3] / 1.5, 6) 1653 | if x % 1 == 0: 1654 | x = int(x) 1655 | y = round(b[4] / 1.8, 6) 1656 | if y % 1 == 0: 1657 | y = int(y) 1658 | except Exception as ex: 1659 | x, y = 0, 0 1660 | script = [x, y] 1661 | 1662 | if b[0] == 12: 1663 | script.append([['readVariable', self.varName(b[1])]]) 1664 | elif b[0] == 13: 1665 | script.append([['contentsOfList:', self.varName(b[1])]]) 1666 | else: 1667 | script = None 1668 | 1669 | if script is not None: 1670 | scripts.append(script) 1671 | self.scriptCount += 1 1672 | 1673 | elif b['topLevel']: 1674 | 1675 | try: 1676 | x = round(b['x'] / 1.5, 6) 1677 | if x % 1 == 0: 1678 | x = int(x) 1679 | y = round(b['y'] / 1.8, 6) 1680 | if y % 1 == 0: 1681 | y = int(y) 1682 | except Exception as ex: 1683 | x, y = 0, 0 1684 | 1685 | self.compatStackReporters = [] 1686 | substack = self.convertSubstack(key, blocks) 1687 | 1688 | if substack != [None]: 1689 | scripts.append([x, y, self.convertSubstack(key, blocks)]) 1690 | self.scriptCount += 1 1691 | 1692 | # Find where the pen size is greater than 255 and add a screen fill 1693 | 1694 | if self.penFill: 1695 | if self.compat and self.penUpDown: 1696 | penDown = ['call', 'pen down'] 1697 | penUp = ['call', 'pen up'] 1698 | else: 1699 | penDown = ['putPenDown'] 1700 | penUp = ['putPenUp'] 1701 | 1702 | def scriptAddFill(script, down, up): 1703 | if type(script) != list or len(script) < 1: 1704 | return 1705 | if type(script[0]) == str: 1706 | if script[0] in ['penSize:', 'changePenSizeBy:']: 1707 | try: 1708 | if float(script[1]) >= 255.5: 1709 | return 'bigSize' 1710 | else: 1711 | return 'smallSize' 1712 | except Exception as ex: 1713 | return 1714 | else: 1715 | # Convert subscripts in repeats, ifs, etc. 1716 | if type(script[-1]) == tuple: 1717 | if len(script) > 2: 1718 | for block in script[1:-1]: 1719 | scriptAddFill(block, down, up) 1720 | else: 1721 | if len(script) > 1: 1722 | for block in script[1:]: 1723 | scriptAddFill(block, down, up) 1724 | return script 1725 | else: 1726 | top = None 1727 | for i in range(len(script)): 1728 | value = scriptAddFill(script[i], down, up) 1729 | if value == 'bigSize': 1730 | self.bigSize = True 1731 | elif value == 'smallSize': 1732 | self.bigSize = False 1733 | top = None 1734 | elif type(value) != list or len(value) < 1: 1735 | continue 1736 | if value[0:len(down)] == down: 1737 | top = i 1738 | elif value[0:len(up)] == up and top is not None and self.bigSize: 1739 | script[top:i + 1] = [ 1740 | ['penSize:', 200], 1741 | ['gotoX:y:', -350, -100], 1742 | down, 1743 | ['xpos:', 250], 1744 | up, 1745 | ['gotoX:y:', -350, 100], 1746 | down, 1747 | ['xpos:', 250], 1748 | up, 1749 | ['penSize:', 255] 1750 | ] 1751 | top = None 1752 | elif value[0] in ['call', 'broadcast:', 'doBroadcastAndWait', 'penColor:', 'changePenHueBy:', 1753 | 'setPenHueTo:', 'changePenShadeBy:', 'setPenShadeTo:']: 1754 | top = None 1755 | 1756 | for script in scripts: 1757 | self.bigSize = False 1758 | if len(script) >= 3: 1759 | scriptAddFill(script[2], penDown, penUp) 1760 | 1761 | self.blockID = 0 1762 | for script in scripts: 1763 | self.getCommentBlockIDs(script[2]) 1764 | 1765 | # Add variables, lists, and custom blocks for compatibility mode 1766 | 1767 | if self.compat: 1768 | 1769 | if self.costumeName: 1770 | costumeNames = [] 1771 | for c in target['costumes']: 1772 | costumeNames.append(c['name']) 1773 | lists.append({ 1774 | 'listName': self.compatVarName('costume names'), 1775 | 'contents': costumeNames, 1776 | 'isPersistent': False, 1777 | 'visible': False 1778 | }) 1779 | 1780 | if self.penUpDown or self.dragMode: 1781 | pen = self.compatVarName('pen') 1782 | variables.append({ 1783 | 'name': pen, 1784 | 'value': 'up', 1785 | 'isPersistent': False 1786 | }) 1787 | 1788 | scripts.append( 1789 | [0, 1790 | 0, 1791 | [["procDef", "pen down", [], [], True], ["putPenDown"], ["setVar:to:", pen, "down"]]] 1792 | ) 1793 | scripts.append( 1794 | [0, 1795 | 0, 1796 | [["procDef", "pen up", [], [], True], ["putPenUp"], ["setVar:to:", pen, "up"]]] 1797 | ) 1798 | 1799 | self.scriptCount += 2 1800 | 1801 | if self.dragMode: 1802 | drag = self.compatVarName('drag') 1803 | variables.append({ 1804 | 'name': drag, 1805 | 'value': 'draggable' if (not isStage and target['draggable']) else 'not draggable', 1806 | 'isPersistent': False 1807 | }) 1808 | 1809 | scripts.append( 1810 | [0, 1811 | 0, 1812 | [["whenClicked"], 1813 | ["doIf", 1814 | ["=", ["readVariable", drag], "draggable"], 1815 | [["call", 1816 | "drag %n %n", 1817 | ["-", ["xpos"], ["mouseX"]], 1818 | ["-", ["ypos"], ["mouseY"]]]]]]] 1819 | ) 1820 | 1821 | scripts.append( 1822 | [0, 1823 | 0, 1824 | [["procDef", "set drag mode %s", ["drag"], ["draggable"], True], 1825 | ["setVar:to:", drag, ["getParam", "drag", "r"]]]] 1826 | ) 1827 | 1828 | scripts.append( 1829 | [0, 1830 | 0, 1831 | [["procDef", "drag %n %n", ["X", "Y"], [0, 0], False], 1832 | ['comeToFront'], 1833 | ["doIf", ["=", ["readVariable", pen], "down"], [["putPenUp"]]], 1834 | ["doUntil", 1835 | ["not", ["mousePressed"]], 1836 | [["gotoX:y:", 1837 | ["+", ["mouseX"], ["getParam", "X", "r"]], 1838 | ["+", ["mouseY"], ["getParam", "Y", "r"]]]]], 1839 | ["doIf", ["=", ["readVariable", pen], "down"], [["putPenDown"]]]]] 1840 | ) 1841 | 1842 | self.scriptCount += 3 1843 | 1844 | if self.joinStr or self.strContains or self.listSearch: 1845 | returnVar = self.compatVarName('return') 1846 | variables.append({ 1847 | 'name': returnVar, 1848 | 'value': 0, 1849 | 'isPersistent': False 1850 | }) 1851 | results = self.compatVarName('results') 1852 | lists.append({ 1853 | 'listName': results, 1854 | 'contents': [], 1855 | 'isPersistent': False, 1856 | 'x': 0, 1857 | 'y': 0, 1858 | 'width': 100, 1859 | 'height': 200, 1860 | 'visible': False 1861 | }) 1862 | 1863 | if self.joinStr or self.strContains: 1864 | i = self.compatVarName('i') 1865 | variables.append({ 1866 | 'name': i, 1867 | 'value': 0, 1868 | 'isPersistent': False 1869 | }) 1870 | 1871 | if self.joinStr: 1872 | joinList = self.compatVarName('join') 1873 | lists.append({ 1874 | 'listName': joinList, 1875 | 'contents': [], 1876 | 'isPersistent': False, 1877 | 'x': 0, 1878 | 'y': 0, 1879 | 'width': 100, 1880 | 'height': 200, 1881 | 'visible': False 1882 | }) 1883 | scripts.append( 1884 | [0, 1885 | 0, 1886 | [["procDef", "join %s %s", ["STRING1", "STRING2"], ["", ""], True], 1887 | ["doIfElse", 1888 | [">", 1889 | ["+", ["stringLength:", ["getParam", "STRING1", "r"]], 1890 | ["stringLength:", ["getParam", "STRING2", "r"]]], 1891 | 10240], 1892 | [["doIf", 1893 | ["not", ["=", ["contentsOfList:", joinList], ["getParam", "STRING1", "r"]]], 1894 | [["deleteLine:ofList:", "all", joinList], 1895 | ["setVar:to:", "i", "0"], 1896 | ["doRepeat", 1897 | ["stringLength:", ["getParam", "STRING1", "r"]], 1898 | [["changeVar:by:", "i", 1], 1899 | ["append:toList:", ["letter:of:", ["readVariable", "i"], ["getParam", "STRING1", "r"]], 1900 | joinList]]]]], 1901 | ["setVar:to:", "i", "0"], 1902 | ["doRepeat", 1903 | ["stringLength:", ["getParam", "STRING2", "r"]], 1904 | [["changeVar:by:", "i", 1], 1905 | ["append:toList:", ["letter:of:", ["readVariable", "i"], ["getParam", "STRING2", "r"]], 1906 | joinList]]], 1907 | ["append:toList:", ["contentsOfList:", joinList], "results"]], 1908 | [["append:toList:", 1909 | ["concatenate:with:", ["getParam", "STRING1", "r"], ["getParam", "STRING2", "r"]], 1910 | "results"]]]]] 1911 | ) 1912 | self.scriptCount += 1 1913 | 1914 | if self.strContains: 1915 | j = self.compatVarName('j') 1916 | variables.append({ 1917 | 'name': j, 1918 | 'value': 0, 1919 | 'isPersistent': False 1920 | }) 1921 | k = self.compatVarName('k') 1922 | variables.append({ 1923 | 'name': k, 1924 | 'value': 0, 1925 | 'isPersistent': False 1926 | }) 1927 | scripts.append( 1928 | [10, 1929 | 10, 1930 | [["procDef", "%s contains %s ?", ["STRING1", "STRING2"], ["apple", "a"], True], 1931 | ["doIfElse", 1932 | ["=", ["stringLength:", ["getParam", "STRING2", "r"]], 0], 1933 | [["append:toList:", ["=", 0, 0], results]], 1934 | [["doIfElse", 1935 | ["=", ["stringLength:", ["getParam", "STRING2", "r"]], 1], 1936 | [["setVar:to:", i, 1], 1937 | ["doRepeat", 1938 | ["stringLength:", ["getParam", "STRING1", "r"]], 1939 | [["doIf", 1940 | ["=", 1941 | ["letter:of:", ["readVariable", i], ["getParam", "STRING1", "r"]], 1942 | ["getParam", "STRING2", "r"]], 1943 | [["append:toList:", ["=", 0, 0], results], ["stopScripts", "this script"]]], 1944 | ["changeVar:by:", i, 1]]], 1945 | ["append:toList:", ["=", 1, 0], results]], 1946 | [["setVar:to:", k, ["-", ["stringLength:", ["getParam", "STRING2", "r"]], 1]], 1947 | ["setVar:to:", i, 1], 1948 | ["doRepeat", 1949 | ["+", 1950 | ["-", ["stringLength:", ["getParam", "STRING1", "r"]], 1951 | ["stringLength:", ["getParam", "STRING2", "r"]]], 1952 | 1], 1953 | [["setVar:to:", j, 0], 1954 | ["doIf", 1955 | ["=", ["readVariable", returnVar], "true"], 1956 | [["append:toList:", ["=", 0, 0], results], ["stopScripts", "this script"]]], 1957 | ["setVar:to:", returnVar, "true"], 1958 | ["doUntil", 1959 | [">", ["readVariable", j], ["readVariable", k]], 1960 | [["doIfElse", 1961 | ["=", 1962 | ["letter:of:", ["+", ["readVariable", i], ["readVariable", j]], 1963 | ["getParam", "STRING1", "r"]], 1964 | ["letter:of:", ["+", ["readVariable", j], 1], ["getParam", "STRING2", "r"]]], 1965 | [["changeVar:by:", j, 1]], 1966 | [["setVar:to:", returnVar, "false"], 1967 | ["setVar:to:", j, ["+", ["readVariable", k], 1]]]]]], 1968 | ["changeVar:by:", i, 1]]], 1969 | ["append:toList:", ["=", 1, 0], results]]]]]]] 1970 | ) 1971 | self.scriptCount += 1 1972 | 1973 | if self.listSearch: 1974 | scripts.append( 1975 | [0, 1976 | 0, 1977 | [["procDef", "item # of %s in %m.list", ["ITEM", "LIST"], ["thing", ""], True], 1978 | ["setVar:to:", returnVar, 0], 1979 | ["doIf", 1980 | ["list:contains:", ["getParam", "LIST", "r"], ["getParam", "ITEM", "r"]], 1981 | [["setVar:to:", returnVar, 0], 1982 | ["doRepeat", 1983 | ["lineCountOfList:", ["getParam", "LIST", "r"]], 1984 | [["changeVar:by:", returnVar, 1], 1985 | ["doIf", 1986 | ["=", 1987 | ["getLine:ofList:", ["readVariable", returnVar], ["getParam", "LIST", "r"]], 1988 | ["getParam", "ITEM", "r"]], 1989 | [["append:toList:", ["readVariable", returnVar], results], 1990 | ["stopScripts", "this script"]]]]]]], 1991 | ["append:toList:", 0, results]]] 1992 | ) 1993 | self.scriptCount += 1 1994 | 1995 | if self.addList: 1996 | scripts.append( 1997 | [0, 1998 | 0, 1999 | [["procDef", "add %s to %m.list", ["ITEM", "LIST"], ["thing", ""], True], 2000 | ["doIf", ["<", ["lineCountOfList:", ["getParam", "LIST", "r"]], 200000], 2001 | [["append:toList:", ["getParam", "ITEM", "r"], ["getParam", "LIST", "r"]]]]]] 2002 | ) 2003 | self.scriptCount += 1 2004 | 2005 | if self.insertList: 2006 | scripts.append( 2007 | [0, 2008 | 0, 2009 | [["procDef", "insert %s at %n of %m.list", ["ITEM", "INDEX", "LIST"], ["thing", 1, ""], True], 2010 | ["insert:at:ofList:", ["getParam", "ITEM", "r"], ["getParam", "INDEX", "r"], 2011 | ["getParam", "LIST", "r"]], 2012 | ["doIf", [">", ["lineCountOfList:", ["getParam", "LIST", "r"]], 200000], 2013 | [["deleteLine:ofList:", "last", ["getParam", "LIST", "r"]]]]]] 2014 | ) 2015 | self.scriptCount += 1 2016 | 2017 | if self.penColor: 2018 | hue = self.compatVarName('hue') 2019 | variables.append({ 2020 | 'name': hue, 2021 | 'value': 200 / 3, 2022 | 'isPersistent': False 2023 | }) 2024 | sat = self.compatVarName('sat') 2025 | variables.append({ 2026 | 'name': sat, 2027 | 'value': 100, 2028 | 'isPersistent': False 2029 | }) 2030 | val = self.compatVarName('val') 2031 | variables.append({ 2032 | 'name': val, 2033 | 'value': 100, 2034 | 'isPersistent': False 2035 | }) 2036 | alpha = self.compatVarName('alpha') 2037 | variables.append({ 2038 | 'name': alpha, 2039 | 'value': 0, 2040 | 'isPersistent': False 2041 | }) 2042 | shade = self.compatVarName('shade') 2043 | variables.append({ 2044 | 'name': shade, 2045 | 'value': 50, 2046 | 'isPersistent': False 2047 | }) 2048 | minVar = self.compatVarName('min') 2049 | variables.append({ 2050 | 'name': minVar, 2051 | 'value': 200 / 3, 2052 | 'isPersistent': False 2053 | }) 2054 | maxVar = self.compatVarName('max') 2055 | variables.append({ 2056 | 'name': maxVar, 2057 | 'value': 100, 2058 | 'isPersistent': False 2059 | }) 2060 | diff = self.compatVarName('diff') 2061 | variables.append({ 2062 | 'name': diff, 2063 | 'value': 100, 2064 | 'isPersistent': False 2065 | }) 2066 | r = self.compatVarName('r') 2067 | variables.append({ 2068 | 'name': r, 2069 | 'value': 0, 2070 | 'isPersistent': False 2071 | }) 2072 | g = self.compatVarName('g') 2073 | variables.append({ 2074 | 'name': g, 2075 | 'value': 50, 2076 | 'isPersistent': False 2077 | }) 2078 | b = self.compatVarName('b') 2079 | variables.append({ 2080 | 'name': b, 2081 | 'value': 100, 2082 | 'isPersistent': False 2083 | }) 2084 | c = self.compatVarName('c') 2085 | variables.append({ 2086 | 'name': c, 2087 | 'value': 0, 2088 | 'isPersistent': False 2089 | }) 2090 | x = self.compatVarName('x') 2091 | variables.append({ 2092 | 'name': x, 2093 | 'value': 50, 2094 | 'isPersistent': False 2095 | }) 2096 | 2097 | scripts.extend( 2098 | [[0, 2099 | 0, 2100 | [["procDef", "set pen color to %c", ["COLOR"], [255], True], 2101 | ["doIfElse", 2102 | ["=", ["*", 1, ["getParam", "COLOR", "r"]], ["getParam", "COLOR", "r"]], 2103 | [["penColor:", ["getParam", "COLOR", "r"]], 2104 | ["setVar:to:", 2105 | alpha, 2106 | ["%", ["computeFunction:of:", "floor", ["/", ["getParam", "COLOR", "r"], 16777216]], 256]], 2107 | ["doIf", 2108 | ["not", ["=", ["readVariable", alpha], 0]], 2109 | [["setVar:to:", 2110 | alpha, 2111 | ["*", 100, ["-", 1, ["/", ["readVariable", alpha], 255]]]]]], 2112 | ["call", 2113 | "store RGB as HSV %n %n %n", 2114 | ["/", 2115 | ["%", ["computeFunction:of:", "floor", ["/", ["getParam", "COLOR", "r"], 65536]], 256], 2116 | 255], 2117 | ["/", 2118 | ["%", ["computeFunction:of:", "floor", ["/", ["getParam", "COLOR", "r"], 256]], 256], 2119 | 255], 2120 | ["/", ["%", ["getParam", "COLOR", "r"], 256], 255]]], 2121 | [["doIfElse", 2122 | ["=", ["letter:of:", 1, ["getParam", "COLOR", "r"]], "#"], 2123 | [["doIfElse", 2124 | ["=", ["stringLength:", ["getParam", "COLOR", "r"]], 7], 2125 | [["call", 2126 | "set pen color to %c", 2127 | ["concatenate:with:", 2128 | "0x", 2129 | ["concatenate:with:", 2130 | ["concatenate:with:", 2131 | ["letter:of:", 2, ["getParam", "COLOR", "r"]], 2132 | ["letter:of:", 3, ["getParam", "COLOR", "r"]]], 2133 | ["concatenate:with:", 2134 | ["concatenate:with:", 2135 | ["letter:of:", 4, ["getParam", "COLOR", "r"]], 2136 | ["letter:of:", 5, ["getParam", "COLOR", "r"]]], 2137 | ["concatenate:with:", 2138 | ["letter:of:", 6, ["getParam", "COLOR", "r"]], 2139 | ["letter:of:", 7, ["getParam", "COLOR", "r"]]]]]]]], 2140 | [["doIfElse", 2141 | ["=", ["stringLength:", ["getParam", "COLOR", "r"]], 4], 2142 | [["call", 2143 | "set pen color to %c", 2144 | ["concatenate:with:", 2145 | "0x", 2146 | ["concatenate:with:", 2147 | ["concatenate:with:", 2148 | ["letter:of:", 2, ["getParam", "COLOR", "r"]], 2149 | ["letter:of:", 2, ["getParam", "COLOR", "r"]]], 2150 | ["concatenate:with:", 2151 | ["concatenate:with:", 2152 | ["letter:of:", 3, ["getParam", "COLOR", "r"]], 2153 | ["letter:of:", 3, ["getParam", "COLOR", "r"]]], 2154 | ["concatenate:with:", 2155 | ["letter:of:", 4, ["getParam", "COLOR", "r"]], 2156 | ["letter:of:", 4, ["getParam", "COLOR", "r"]]]]]]]], 2157 | [["call", "set pen color to %c", -16777216]]]]]], 2158 | [["call", "set pen color to %c", -16777216]]]]]]], 2159 | [0, 2160 | 0, 2161 | [["procDef", "change pen %s by %n", ["COLOR_PARAM", "VALUE"], ["color", 10], True], 2162 | ["doIfElse", 2163 | ["=", ["getParam", "COLOR_PARAM", "r"], "color"], 2164 | [["call", 2165 | "set pen %s to %n", 2166 | ["getParam", "COLOR_PARAM", "r"], 2167 | ["+", ["readVariable", hue], ["getParam", "VALUE", "r"]]]], 2168 | [["doIfElse", 2169 | ["=", ["getParam", "COLOR_PARAM", "r"], "saturation"], 2170 | [["call", 2171 | "set pen %s to %n", 2172 | ["getParam", "COLOR_PARAM", "r"], 2173 | ["+", ["readVariable", sat], ["getParam", "VALUE", "r"]]]], 2174 | [["doIfElse", 2175 | ["=", ["getParam", "COLOR_PARAM", "r"], "brightness"], 2176 | [["call", 2177 | "set pen %s to %n", 2178 | ["getParam", "COLOR_PARAM", "r"], 2179 | ["+", ["readVariable", val], ["getParam", "VALUE", "r"]]]], 2180 | [["doIf", 2181 | ["=", ["getParam", "COLOR_PARAM", "r"], "transparency"], 2182 | [["call", 2183 | "set pen %s to %n", 2184 | ["getParam", "COLOR_PARAM", "r"], 2185 | ["+", ["readVariable", alpha], ["getParam", "VALUE", "r"]]]]]]]]]]]]], 2186 | [0, 2187 | 0, 2188 | [["procDef", "change pen color by %n", ["HUE"], [10], True], 2189 | ["call", "change pen %s by %n", "color", ["/", ["getParam", "HUE", "r"], 2]]]], 2190 | [0, 2191 | 0, 2192 | [["procDef", "set pen color to %n", ["HUE"], [0], True], 2193 | ["call", "set pen %s to %n", "color", ["/", ["getParam", "HUE", "r"], 2]]]], 2194 | [0, 2195 | 0, 2196 | [["procDef", "change pen shade by %n", ["SHADE"], [10], True], 2197 | ["call", "set pen shade to %n", ["+", ["readVariable", shade], ["getParam", "SHADE", "r"]]]]], 2198 | [0, 2199 | 0, 2200 | [["procDef", "set pen shade to %n", ["SHADE"], [50], True], 2201 | ["setVar:to:", 2202 | shade, 2203 | ["computeFunction:of:", 2204 | "abs", 2205 | ["-", 2206 | ["getParam", "SHADE", "r"], 2207 | ["*", 200, ["rounded", ["/", ["getParam", "SHADE", "r"], 200]]]]]], 2208 | ["call", "HSV to RGB %n %n %n", ["readVariable", hue], 100, 100], 2209 | ["doIfElse", 2210 | ["<", ["readVariable", shade], 50], 2211 | [["setVar:to:", x, ["/", ["+", ["readVariable", shade], 10], 60]], 2212 | ["setVar:to:", r, ["rounded", ["*", ["readVariable", x], ["readVariable", r]]]], 2213 | ["setVar:to:", g, ["rounded", ["*", ["readVariable", x], ["readVariable", g]]]], 2214 | ["setVar:to:", b, ["rounded", ["*", ["readVariable", x], ["readVariable", b]]]]], 2215 | [["setVar:to:", x, ["/", ["-", ["readVariable", shade], 50], 60]], 2216 | ["setVar:to:", 2217 | r, 2218 | ["rounded", 2219 | ["+", 2220 | ["*", ["-", 1, ["readVariable", x]], ["readVariable", r]], 2221 | ["*", ["readVariable", x], 255]]]], 2222 | ["setVar:to:", 2223 | g, 2224 | ["rounded", 2225 | ["+", 2226 | ["*", ["-", 1, ["readVariable", x]], ["readVariable", g]], 2227 | ["*", ["readVariable", x], 255]]]], 2228 | ["setVar:to:", 2229 | b, 2230 | ["rounded", 2231 | ["+", 2232 | ["*", ["-", 1, ["readVariable", x]], ["readVariable", b]], 2233 | ["*", ["readVariable", x], 255]]]]]], 2234 | ["call", 2235 | "store RGB as HSV %n %n %n", 2236 | ["/", ["readVariable", r], 255], 2237 | ["/", ["readVariable", g], 255], 2238 | ["/", ["readVariable", b], 255]], 2239 | ["penColor:", 2240 | ["+", 2241 | ["readVariable", b], 2242 | ["*", 2243 | 256, 2244 | ["+", 2245 | ["readVariable", g], 2246 | ["*", 2247 | 256, 2248 | ["+", 2249 | ["readVariable", r], 2250 | ["*", 256, ["rounded", ["*", 2.55, ["-", 100, ["readVariable", alpha]]]]]]]]]]]]], 2251 | [0, 2252 | 0, 2253 | [["procDef", "set pen %s to %n", ["COLOR_PARAM", "VALUE"], ["color", 50], True], 2254 | ["doIfElse", 2255 | ["=", ["getParam", "COLOR_PARAM", "r"], "color"], 2256 | [["setPenHueTo:", ["*", 2, ["getParam", "VALUE", "r"]]], 2257 | ["setVar:to:", hue, ["%", ["getParam", "VALUE", "r"], 100]], 2258 | ["stopScripts", "this script"]], 2259 | [["doIfElse", 2260 | ["=", ["getParam", "COLOR_PARAM", "r"], "saturation"], 2261 | [["doIfElse", 2262 | ["<", ["getParam", "VALUE", "r"], 0], 2263 | [["setVar:to:", sat, 0]], 2264 | [["doIfElse", 2265 | [">", ["getParam", "VALUE", "r"], 100], 2266 | [["setVar:to:", sat, 100]], 2267 | [["setVar:to:", sat, ["getParam", "VALUE", "r"]]]]]]], 2268 | [["doIfElse", 2269 | ["=", ["getParam", "COLOR_PARAM", "r"], "brightness"], 2270 | [["doIfElse", 2271 | ["<", ["getParam", "VALUE", "r"], 0], 2272 | [["setVar:to:", val, 0]], 2273 | [["doIfElse", 2274 | [">", ["getParam", "VALUE", "r"], 100], 2275 | [["setVar:to:", val, 100]], 2276 | [["setVar:to:", val, ["getParam", "VALUE", "r"]]]]]]], 2277 | [["doIfElse", 2278 | ["=", ["getParam", "COLOR_PARAM", "r"], "transparency"], 2279 | [["doIfElse", 2280 | ["<", ["getParam", "VALUE", "r"], 0], 2281 | [["setVar:to:", alpha, 0]], 2282 | [["doIfElse", 2283 | [">", ["getParam", "VALUE", "r"], 100], 2284 | [["setVar:to:", alpha, 100]], 2285 | [["setVar:to:", alpha, ["getParam", "VALUE", "r"]]]]]]], 2286 | [["stopScripts", "this script"]]]]]]]]], 2287 | ["call", "HSV to RGB %n %n %n", ["readVariable", hue], ["readVariable", sat], 2288 | ["readVariable", val]], 2289 | ["penColor:", 2290 | ["+", 2291 | ["readVariable", b], 2292 | ["*", 2293 | 256, 2294 | ["+", 2295 | ["readVariable", g], 2296 | ["*", 2297 | 256, 2298 | ["+", 2299 | ["readVariable", r], 2300 | ["*", 256, ["rounded", ["*", 2.55, ["-", 100, ["readVariable", alpha]]]]]]]]]]]]], 2301 | [0, 2302 | 0, 2303 | [["procDef", "store RGB as HSV %n %n %n", ["R", "G", "B"], [0, 0, 0], True], 2304 | ["doIfElse", 2305 | ["not", 2306 | ["|", 2307 | [">", ["getParam", "R", "r"], ["getParam", "G", "r"]], 2308 | [">", ["getParam", "R", "r"], ["getParam", "B", "r"]]]], 2309 | [["setVar:to:", minVar, ["getParam", "R", "r"]]], 2310 | [["doIfElse", 2311 | ["not", 2312 | ["|", 2313 | [">", ["getParam", "G", "r"], ["getParam", "R", "r"]], 2314 | [">", ["getParam", "G", "r"], ["getParam", "B", "r"]]]], 2315 | [["setVar:to:", minVar, ["getParam", "G", "r"]]], 2316 | [["setVar:to:", minVar, ["getParam", "B", "r"]]]]]], 2317 | ["doIfElse", 2318 | ["not", 2319 | ["|", 2320 | ["<", ["getParam", "R", "r"], ["getParam", "G", "r"]], 2321 | ["<", ["getParam", "R", "r"], ["getParam", "B", "r"]]]], 2322 | [["setVar:to:", maxVar, ["getParam", "R", "r"]]], 2323 | [["doIfElse", 2324 | ["not", 2325 | ["|", 2326 | ["<", ["getParam", "G", "r"], ["getParam", "R", "r"]], 2327 | ["<", ["getParam", "G", "r"], ["getParam", "B", "r"]]]], 2328 | [["setVar:to:", maxVar, ["getParam", "G", "r"]]], 2329 | [["setVar:to:", maxVar, ["getParam", "B", "r"]]]]]], 2330 | ["setVar:to:", diff, ["-", ["readVariable", maxVar], ["readVariable", minVar]]], 2331 | ["doIfElse", 2332 | ["=", ["readVariable", diff], 0], 2333 | [["setVar:to:", hue, 0], ["setVar:to:", sat, 0]], 2334 | [["doIfElse", 2335 | ["=", ["readVariable", maxVar], ["getParam", "R", "r"]], 2336 | [["setVar:to:", 2337 | hue, 2338 | ["/", 2339 | ["%", 2340 | ["/", 2341 | ["-", ["getParam", "G", "r"], ["getParam", "B", "r"]], 2342 | ["readVariable", diff]], 2343 | 6], 2344 | 0.06]]], 2345 | [["doIfElse", 2346 | ["=", ["readVariable", maxVar], ["getParam", "G", "r"]], 2347 | [["setVar:to:", 2348 | hue, 2349 | ["/", 2350 | ["+", 2351 | ["/", 2352 | ["-", ["getParam", "B", "r"], ["getParam", "R", "r"]], 2353 | ["readVariable", diff]], 2354 | 2], 2355 | 0.06]]], 2356 | [["setVar:to:", 2357 | hue, 2358 | ["/", 2359 | ["+", 2360 | ["/", 2361 | ["-", ["getParam", "R", "r"], ["getParam", "G", "r"]], 2362 | ["readVariable", diff]], 2363 | 4], 2364 | 0.06]]]]]], 2365 | ["setVar:to:", sat, ["*", 100, ["/", ["readVariable", diff], ["readVariable", maxVar]]]]]], 2366 | ["setVar:to:", val, ["*", 100, ["readVariable", maxVar]]]]], 2367 | [0, 2368 | 0, 2369 | [["procDef", "HSV to RGB %n %n %n", ["H", "S", "V"], [0, 0, 0], True], 2370 | ["setVar:to:", 2371 | c, 2372 | ["/", ["*", ["getParam", "V", "r"], ["getParam", "S", "r"]], 10000]], 2373 | ["setVar:to:", 2374 | x, 2375 | ["*", 2376 | ["readVariable", c], 2377 | ["-", 2378 | 1, 2379 | ["computeFunction:of:", 2380 | "abs", 2381 | ["-", ["%", ["*", 0.06, ["getParam", "H", "r"]], 2], 1]]]]], 2382 | ["doIfElse", 2383 | ["<", ["getParam", "H", "r"], ["/", 100, 6]], 2384 | [["setVar:to:", r, ["readVariable", c]], 2385 | ["setVar:to:", g, ["readVariable", x]], 2386 | ["setVar:to:", b, 0]], 2387 | [["doIfElse", 2388 | ["<", ["getParam", "H", "r"], ["/", 100, 3]], 2389 | [["setVar:to:", r, ["readVariable", x]], 2390 | ["setVar:to:", g, ["readVariable", c]], 2391 | ["setVar:to:", b, 0]], 2392 | [["doIfElse", 2393 | ["<", ["getParam", "H", "r"], 50], 2394 | [["setVar:to:", r, 0], 2395 | ["setVar:to:", g, ["readVariable", c]], 2396 | ["setVar:to:", b, ["readVariable", x]]], 2397 | [["doIfElse", 2398 | ["<", ["getParam", "H", "r"], ["/", 200, 3]], 2399 | [["setVar:to:", r, 0], 2400 | ["setVar:to:", g, ["readVariable", x]], 2401 | ["setVar:to:", b, ["readVariable", c]]], 2402 | [["doIfElse", 2403 | ["<", ["getParam", "H", "r"], ["/", 250, 3]], 2404 | [["setVar:to:", r, ["readVariable", x]], 2405 | ["setVar:to:", g, 0], 2406 | ["setVar:to:", b, ["readVariable", c]]], 2407 | [["setVar:to:", r, ["readVariable", x]], 2408 | ["setVar:to:", g, 0], 2409 | ["setVar:to:", b, ["readVariable", c]]]]]]]]]]]], 2410 | ["setVar:to:", 2411 | x, 2412 | ["-", ["/", ["getParam", "V", "r"], 100], ["readVariable", c]]], 2413 | ["setVar:to:", 2414 | r, 2415 | ["rounded", ["*", 255, ["+", ["readVariable", r], ["readVariable", x]]]]], 2416 | ["setVar:to:", 2417 | g, 2418 | ["rounded", ["*", 255, ["+", ["readVariable", g], ["readVariable", x]]]]], 2419 | ["setVar:to:", 2420 | b, 2421 | ["rounded", ["*", 255, ["+", ["readVariable", b], ["readVariable", x]]]]]]]] 2422 | ) 2423 | self.scriptCount += 9 2424 | 2425 | if self.resetTimer: 2426 | scripts.append( 2427 | [0, 2428 | 0, 2429 | [["procDef", "reset timer", [], [], True], ["setVar:to:", "reset time", ["timestamp"]], 2430 | ["timerReset"]]] 2431 | ) 2432 | self.scriptCount += 1 2433 | 2434 | sprite['scripts'] = scripts 2435 | sprite['variables'] = variables 2436 | sprite['lists'] = lists 2437 | sprite['sounds'] = self.sounds 2438 | sprite['costumes'] = self.costumes 2439 | sprite['scriptComments'] = self.comments 2440 | 2441 | if isStage: 2442 | 2443 | sprite['currentCostumeIndex'] = target['currentCostume'] 2444 | sprite['tempoBPM'] = target['tempo'] 2445 | sprite['videoAlpha'] = (100 - target['videoTransparency']) / 100 2446 | sprite['penLayerMD5'] = '' 2447 | 2448 | sprite['objName'] = 'Stage' 2449 | sprite['info'] = { 2450 | 'userAgent': self.jsonData['meta']['agent'], 2451 | 'videoOn': target['videoState'] == 'on' 2452 | } 2453 | 2454 | else: 2455 | 2456 | sprite['currentCostumeIndex'] = target['currentCostume'] 2457 | sprite['scratchX'] = target['x'] 2458 | sprite['scratchY'] = target['y'] 2459 | sprite['scale'] = target['size'] / 100 2460 | sprite['direction'] = target['direction'] 2461 | sprite['rotationStyle'] = ProjectConverter.rotationStyles[target['rotationStyle']] 2462 | sprite['isDraggable'] = target['draggable'] and not self.compat 2463 | sprite['indexInLibrary'] = index 2464 | sprite['visible'] = target['visible'] 2465 | sprite['spriteInfo'] = {} 2466 | sprite['layerOrder'] = target['layerOrder'] 2467 | 2468 | print("Converted {} ({}/{})".format( 2469 | rightPad(f"'{sprite['objName']}'", maxLen - len(sprite['objName']), ' '), index + 1, 2470 | self.totalTargets)) 2471 | 2472 | return (isStage, sprite) 2473 | 2474 | def updateList(self, l, ls): 2475 | l['x'] = ls['x'] 2476 | l['y'] = ls['y'] 2477 | l['width'] = ls['width'] 2478 | l['height'] = ls['height'] 2479 | l['visible'] = ls['visible'] 2480 | 2481 | # Update list data with monitor info 2482 | 2483 | def updateListData(self, output, sprites, stageLists, lists): 2484 | 2485 | for l in output['lists']: 2486 | 2487 | if l['listName'] in stageLists: 2488 | ls = stageLists[l['listName']] 2489 | self.updateList(l, ls) 2490 | 2491 | for s in sprites: 2492 | spriteName = s['objName'] 2493 | 2494 | if spriteName in lists: 2495 | for l in s['lists']: 2496 | 2497 | if l['listName'] in lists[spriteName]: 2498 | ls = lists[spriteName][l['listName']] 2499 | self.updateList(l, ls) 2500 | 2501 | def addMonitor(self, m): 2502 | 2503 | if m['opcode'] == 'data_listcontents': 2504 | 2505 | monitor = { 2506 | 'listName': self.varName(m['params']['LIST']), 2507 | 'contents': m['value'], 2508 | 'isPersistent': False, 2509 | 'x': m['x'], 2510 | 'y': m['y'], 2511 | 'width': 100 if m['width'] == 0 else m['width'], 2512 | 'height': 200 if m['height'] == 0 else m['height'], 2513 | 'visible': m['visible'] 2514 | } 2515 | 2516 | self.monitors.append(monitor) 2517 | 2518 | listData = { 2519 | 'x': m['x'], 2520 | 'y': m['y'], 2521 | 'width': monitor['width'], 2522 | 'height': monitor['height'], 2523 | 'visible': m['visible'] 2524 | } 2525 | 2526 | if m['spriteName'] is None: 2527 | self.stageLists[monitor['listName']] = listData 2528 | else: 2529 | if m['spriteName'] not in self.lists: 2530 | self.lists[m['spriteName']] = {} 2531 | self.lists[m['spriteName']][monitor['listName']] = listData 2532 | 2533 | else: 2534 | 2535 | try: 2536 | block = {'opcode': m['opcode']} 2537 | if 'params' in m: 2538 | block['fields'] = {} 2539 | for key, value in m['params'].items(): 2540 | block['fields'][key] = [value] 2541 | 2542 | monitor = self.argmapper.mapArgs(m['opcode'], block, {}) 2543 | cmd = 'getVar:' if monitor[0] == 'readVariable' else monitor[0] 2544 | if len(monitor) > 1: 2545 | param = monitor[1] 2546 | else: 2547 | param = None 2548 | 2549 | assert cmd is not None 2550 | 2551 | sMin = m['min'] if 'min' in m else m['sliderMin'] 2552 | sMax = m['max'] if 'max' in m else m['sliderMax'] 2553 | monitor = { 2554 | 'target': 'Stage' if m['spriteName'] is None else m['spriteName'], 2555 | 'cmd': cmd, 2556 | 'param': param, 2557 | 'color': ProjectConverter.monitorColors[m['opcode'].split('_')[0]], 2558 | 'label': '', # Scratch 2 will handle this 2559 | 'mode': ProjectConverter.varModes[m['mode']], 2560 | 'sliderMin': sMin, 2561 | 'sliderMax': sMax, 2562 | 'isDiscrete': sMin % 1 == 0 and sMax % 1 == 0 and not ('.' in str(sMin)) and not ('.' in str(sMax)), 2563 | 'x': m['x'], 2564 | 'y': m['y'], 2565 | 'visible': m['visible'] 2566 | } 2567 | self.monitors.append(monitor) 2568 | 2569 | except Exception as ex: 2570 | self.generateWarning(f"Stage monitor '{m['opcode']}' will not be converted") 2571 | 2572 | def convertProject(self, sb3path, sb2path, gui=False, replace=False, compatibility=False, unlimitedJoin=False, 2573 | limitedLists=False, penFillScreen=False): 2574 | 2575 | self.compatWarning = False 2576 | self.compat = compatibility 2577 | self.unlimJoin = unlimitedJoin 2578 | self.limList = limitedLists 2579 | self.penFill = penFillScreen 2580 | 2581 | self.warnings = 0 2582 | 2583 | if not sb3path[-3:] == 'sb3': 2584 | printError(f"File '{sb3path}' is not an sb3 file", gui) 2585 | 2586 | if not sb2path[-3:] == 'sb2': 2587 | self.generateWarning( 2588 | f"The converted project will be saved to '{sb2path + '.sb2'}' instead of '{sb2path}'") 2589 | sb2path += '.sb2' 2590 | 2591 | self.convertingMonitors = False 2592 | 2593 | try: 2594 | self.zfsb3 = zipfile.ZipFile(sb3path, 'r') 2595 | except Exception as ex: 2596 | printError(f"File '{sb3path}' does not exist", gui) 2597 | 2598 | print('') 2599 | try: 2600 | self.zfsb2 = zipfile.ZipFile(sb2path, 'x') 2601 | except Exception as ex: 2602 | replaceFile = False 2603 | if replace: 2604 | replaceFile = True 2605 | else: 2606 | if gui: 2607 | goAhead = messagebox.askquestion('Overwrite SB2', 2608 | f"File {sb2path} already exists.\n\nOverwrite {sb2path}?", 2609 | icon='warning' 2610 | ) 2611 | replaceFile = (goAhead == 'yes') 2612 | else: 2613 | print(f"File '{sb2path}' already exists") 2614 | replaceFile = input(f"Overwrite '{sb2path}'? (Y/N): ") 2615 | print('') 2616 | replaceFile = replaceFile[0] == 'Y' or replaceFile[0] == 'y' 2617 | if replaceFile: 2618 | import os 2619 | os.remove(sb2path) 2620 | self.zfsb2 = zipfile.ZipFile(sb2path, 'x') 2621 | else: 2622 | exit() 2623 | 2624 | f = self.zfsb3.open('project.json', 'r') 2625 | self.jsonData = json.loads(f.read()) 2626 | f.close() 2627 | 2628 | output = {} 2629 | self.costumeAssets = {} 2630 | self.soundAssets = {} 2631 | 2632 | sprites = [] 2633 | 2634 | targetsDone = 0 2635 | 2636 | self.totalTargets = len(self.jsonData['targets']) 2637 | self.scriptCount = 0 2638 | 2639 | # Convert Stage and sprites 2640 | 2641 | maxLen = 0 2642 | for target in self.jsonData['targets']: 2643 | name = 'Stage' if target['isStage'] else target['name'] 2644 | maxLen = max(maxLen, len(name)) 2645 | 2646 | self.timerCompat = False 2647 | 2648 | for target in self.jsonData['targets']: 2649 | sprite = self.convertTarget(target, targetsDone, maxLen) 2650 | if sprite[0]: 2651 | output = sprite[1] 2652 | else: 2653 | sprites.append(sprite[1]) 2654 | targetsDone += 1 2655 | 2656 | if self.timerCompat: 2657 | output['variables'].append( 2658 | { 2659 | 'name': 'reset time', 2660 | 'value': 0, 2661 | 'isPersistent': False 2662 | } 2663 | ) 2664 | gfResetTimer = [0, 2665 | 0, 2666 | [["whenGreenFlag"], 2667 | ["doIf", 2668 | [">", 2669 | ["-", ["*", 86400, ["-", ["timestamp"], ["readVariable", "reset time"]]], ["timer"]], 2670 | "0.1"], 2671 | [["setVar:to:", "reset time", ["-", ["timestamp"], ["/", ["timer"], 86400]]]]]]] 2672 | output['scripts'].append(gfResetTimer) 2673 | for sprite in sprites: 2674 | sprite['scripts'].append(gfResetTimer) 2675 | self.scriptCount += 1 + len(sprites) 2676 | 2677 | output['info']['scriptCount'] = self.scriptCount 2678 | output['info']['spriteCount'] = self.totalTargets - 1 2679 | 2680 | self.monitors = [] 2681 | 2682 | self.lists = {} 2683 | self.stageLists = {} 2684 | 2685 | # Convert monitors 2686 | 2687 | self.convertingMonitors = True 2688 | for m in self.jsonData['monitors']: 2689 | self.addMonitor(m) 2690 | 2691 | self.updateListData(output, sprites, self.stageLists, self.lists) 2692 | 2693 | # Sort sprites into their layers 2694 | 2695 | sprites.sort(key=lambda sprite: sprite['layerOrder']) 2696 | for sprite in sprites: 2697 | del sprite['layerOrder'] 2698 | 2699 | sprites.extend(self.monitors) 2700 | self.convertingMonitors = False 2701 | 2702 | output['children'] = sprites 2703 | 2704 | # Add WeDo 2.0 extension if necessary 2705 | 2706 | if 'wedo2' in self.jsonData['extensions']: 2707 | output['info']['savedExtensions'] = [{'extensionName': 'LEGO WeDo 2.0'}] 2708 | 2709 | output = json.dumps(output) 2710 | 2711 | self.zfsb2.writestr('project.json', output) 2712 | 2713 | self.zfsb3.close() 2714 | self.zfsb2.close() 2715 | 2716 | return self.warnings, self.compatWarning and not self.compat, sb2path 2717 | 2718 | 2719 | def success(sb2path, warnings, gui): 2720 | if gui: 2721 | if warnings == 0: 2722 | messagebox.showinfo("Success", "Completed with no warnings") 2723 | elif warnings == 1: 2724 | messagebox.showinfo("Success", f"Completed with 1 warning") 2725 | else: 2726 | messagebox.showinfo("Success", f"Completed with {warnings} warnings") 2727 | else: 2728 | print('') 2729 | if warnings == 0: 2730 | print(f"Saved to '{sb2path}' with no warnings") 2731 | elif warnings == 1: 2732 | print(f"Saved to '{sb2path}' with 1 warning") 2733 | else: 2734 | print(f"Saved to '{sb2path}' with {warnings} warnings") 2735 | 2736 | 2737 | if __name__ == '__main__': 2738 | 2739 | if '-h' in sys.argv: 2740 | print( 2741 | ''' 2742 | Arguments: sb3tosb2.py [unordered options] sb3path sb2path 2743 | List of Options: 2744 | -h: Show this list 2745 | -c: Enable Scratch 3.0 compatibility mode; Add workarounds for blocks that are exclusive to or work differently in 3.0 2746 | The indented options will automatically enable compatibility mode: 2747 | -j: Use an unlimited join workaround 2748 | -l: Use custom blocks to automatically limit list length to 200,000 2749 | -p: Tries to insert blocks to fill the screen when the pen size is set to a value greater than 255 2750 | ''') 2751 | exit() 2752 | 2753 | gui = False 2754 | if len(sys.argv) < 2: 2755 | gui = True 2756 | import tkinter 2757 | from tkinter import filedialog, messagebox 2758 | 2759 | root = tkinter.Tk() 2760 | root.withdraw() 2761 | sb3path = filedialog.askopenfilename(title="Open SB3 Project", filetypes=[("Scratch 3 Project", "*.sb3")]) 2762 | i = sb3path.rfind('.') 2763 | if i > -1: 2764 | sb2path = f'{sb3path[0:i]}.sb2' 2765 | else: 2766 | sb2path = f'{sb3path}.sb2' 2767 | else: 2768 | if len(sys.argv) < 3: 2769 | sb3path = sys.argv[-1] 2770 | i = sb3path.rfind('.') 2771 | if i > -1: 2772 | sb2path = f'{sb3path[0:i]}.sb2' 2773 | else: 2774 | sb2path = f'{sb3path}.sb2' 2775 | else: 2776 | sb3path = sys.argv[-2] 2777 | sb2path = sys.argv[-1] 2778 | 2779 | if gui: 2780 | if sb3path == '' or sb2path == '': 2781 | exit() 2782 | 2783 | args = [] 2784 | if len(sys.argv) > 3: 2785 | for arg in sys.argv[1:-2]: 2786 | args.append(arg) 2787 | 2788 | args = ''.join(args) 2789 | c = '-c' in args 2790 | j = '-j' in args 2791 | l = '-l' in args 2792 | p = '-p' in args 2793 | 2794 | result = ProjectConverter().convertProject(sb3path, sb2path, gui=gui, replace=False, compatibility=(c or j or l), 2795 | unlimitedJoin=j, limitedLists=l, penFillScreen=p) 2796 | warnings = result[0] 2797 | sb2path = result[2] 2798 | 2799 | if result[1]: 2800 | if gui: 2801 | retry = messagebox.askquestion('Enable Compatibility Mode', 2802 | "The converted project may not work properly unless compatibility mode is enabled.\n\nWould you like to re-convert the sb3 file with compatibility mode enabled?", 2803 | icon='warning' 2804 | ) 2805 | retry = (retry == 'yes') 2806 | else: 2807 | print('') 2808 | printWarning("The converted project may not work properly unless compatibility mode is enabled.") 2809 | retry = input(f"Would you like to re-convert '{sb3path}' with compatibility mode enabled? (Y/N): ") 2810 | retry = (retry[0] == 'Y' or retry[0] == 'y') 2811 | 2812 | if retry: 2813 | result = ProjectConverter().convertProject(sb3path, sb2path, gui=gui, replace=True, compatibility=True, 2814 | unlimitedJoin=j, limitedLists=l, penFillScreen=p) 2815 | warnings = result[0] 2816 | sb2path = result[2] 2817 | 2818 | success(sb2path, warnings, gui) 2819 | else: 2820 | success(sb2path, warnings, gui) 2821 | else: 2822 | success(sb2path, warnings, gui) 2823 | --------------------------------------------------------------------------------