sketchucation logo sketchucation
    • Login
    Oops, your profile's looking a bit empty! To help us tailor your experience, please fill in key details like your SketchUp version, skill level, operating system, and more. Update and save your info on your profile page today!
    πŸ«› Lightbeans Update | Metallic and Roughness auto-applied in SketchUp 2025+ Download

    Looking to make a script, but dunno how.

    Scheduled Pinned Locked Moved Developers' Forum
    34 Posts 7 Posters 1.6k Views 7 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • A Offline
      agamemnus
      last edited by

      The first script is almost done. I have a few problems --

      1. I could not find a way to convert groups to components so I changed them to unique components and then changed the definition of THOSE to the randomly selected base component. Isn't there a more efficient way?

      2. I can't seem to convert the target groups to components fast enough -- I used 'if (current_entity.typename == "Group") // current_entity.to_component // end', but that only applies at the end of the script so I have to run it twice.. dunno how to make it convert instantly. Tried shoving "Sketchup.active_model.commit_operation" after and then converting the unique components to base components but it won't budge.

      3. When I do "@target_entities = target_entities", and I already had a non-empty @target_entities, am I leaking?

      4. (mini-gripe) The rand function is glitchy. Sometimes it gives several (3-4) repeats in a 90-size or so list, which has an incredibly low chance of occurring.

      
      require 'sketchup.rb'
      
      module Convert_objects_randomly
      
       @base_entities = []
       @target_entities = []
      
       def Convert_objects_randomly.choosebase
        @base_entities = Sketchup.active_model.selection.to_a
        if @base_entities.empty?
         results = UI.messagebox "Please select base groups and/or components first."
         Sketchup.send_action "selectSelectionTool;"
         return
        end
       end
      
      
       def Convert_objects_randomly.choosetarget
        target_entities = Sketchup.active_model.selection.to_a
        if @base_entities.empty?
         results = UI.messagebox "Please select base groups and/or components first."
         Sketchup.send_action "selectSelectionTool;"
         return
        end
      
        if target_entities.empty?
         if @target_entities.empty?
         results = UI.messagebox "Please select target groups and/or components first."
         Sketchup.send_action "selectSelectionTool;"
         return
         end
         target_entities = @target_entities
        end
      
        target_entities.each do |current_entity|
         if (current_entity.typename == "Group")
          current_entity.to_component
         end
        end
      
        Sketchup.active_model.commit_operation
         
        target_entities.each do |current_entity|
         if (current_entity.typename == "Group") or (current_entity.typename == "ComponentInstance")
          current_entity.make_unique
          current_entity.definition = @base_entities[rand(@base_entities.length)].definition
         end 
        end
      
        @target_entities = target_entities
        Sketchup.active_model.commit_operation
      
       end
      
      end #Convert_objects_randomly module
      
      
      Convert_objects_randomly_menu = UI.menu("Plugins").add_submenu("Convert Objects Randomly")
      Convert_objects_randomly_menu.add_item("Select base objects") {Convert_objects_randomly.choosebase}
      Convert_objects_randomly_menu.add_item("Convert selected to random base objects") {Convert_objects_randomly.choosetarget}
      
      
      file_loaded(__FILE__)
      
      
      1 Reply Last reply Reply Quote 0
      • A Offline
        agamemnus
        last edited by

        Thanks. I couldn't do it with "@module base_entities = '' "-- that gave me an error. I used " @base_entities = '' ". And looks like I need that " @base_entities ='' " or else something weird happens (maybe undefineds everywhere?) and the if statement for base_entities did not work. (it does now, of course)

        So now I have to figure out how to iterate through target_entities and convert each to a random base_entities ..

        There isn't a native function I could use?

        Edit: Figured it out mostly... See post 1 below.

        1 Reply Last reply Reply Quote 0
        • Chris FullmerC Offline
          Chris Fullmer
          last edited by

          #1 groups have the .to_component method that will turn them into a component. But it makes each group a unique component, because there is no built in way to determine if a group is an identical copy of another group. There is some work arounds that can be done on certain groups that are exact copies of another group, but generally speaking, groups can't be turned easily into a single component and instances.

          #2 - I'll have to look at later

          #3 - The @target_entities will hold its value until SketchUp is closed, after it is given a value once. So you should clear it after your script is run each time. Add a @taget_entities = [] to the end of your script. That is my gess as to what is happening.

          #4 - Yeah, that happens. Adam Billyard once took some time to explain about how random functions work in programming. It was eye opening....or rather, my eyes popped out from all the terms he used that didn't make any sense to me. But essentially random is a tricky thing to nail perfectly I guess.

          Sounds like its coming along well!

          Chris

          Lately you've been tan, suspicious for the winter.
          All my Plugins I've written

          1 Reply Last reply Reply Quote 0
          • A Offline
            agamemnus
            last edited by

            @chris fullmer said:

            #3 - The @target_entities will hold its value until SketchUp is closed, after it is given a value once. So you should clear it after your script is run each time. Add a @taget_entities = [] to the end of your script. That is my gess as to what is happening.

            Well, I know that it holds its value -- that was a way to re-randomize if the user wanted to without selecting those same groups again. But, if I set @target_entities to something else and it (@target_entities) is already set to something, that won't cause a leak, right? (the array it was previously set to will be cleared from memory?)

            1 Reply Last reply Reply Quote 0
            • Chris FullmerC Offline
              Chris Fullmer
              last edited by

              Ahh, correct. If you set it to seomthing new, then it clears its old value.

              Lately you've been tan, suspicious for the winter.
              All my Plugins I've written

              1 Reply Last reply Reply Quote 0
              • thomthomT Offline
                thomthom
                last edited by

                Ruby uses garbage collection - so it keeps track of all the junk we throw about and sweeps it all away! πŸ˜„

                Thomas Thomassen β€” SketchUp Monkey & Coding addict
                List of my plugins and link to the CookieWare fund

                1 Reply Last reply Reply Quote 0
                • C Offline
                  cjthompson
                  last edited by

                  @agamemnus said:

                  1. I can't seem to convert the target groups to components fast enough -- I used 'if (current_entity.typename == "Group") // current_entity.to_component // end', but that only applies at the end of the script so I have to run it twice.. dunno how to make it convert instantly. Tried shoving "Sketchup.active_model.commit_operation" after and then converting the unique components to base components but it won't budge.

                  the reason why is because .to_component creates a new entity.
                  Try current_entity = current_entity.to_component.

                  1 Reply Last reply Reply Quote 0
                  • thomthomT Offline
                    thomthom
                    last edited by

                    Also .typename is very slow.
                    Instead of current_entity.typename == "Group" use current_entity.is_a?(Sketchup::Group).
                    http://forums.sketchucation.com/viewtopic.php?f=180&t=19576&start=0#p162235

                    Thomas Thomassen β€” SketchUp Monkey & Coding addict
                    List of my plugins and link to the CookieWare fund

                    1 Reply Last reply Reply Quote 0
                    • A Offline
                      agamemnus
                      last edited by

                      Thanks guys. Got myself two more issues now, though. 😞

                      1. The code refuses to convert lines to groups!! (I have "current_entity = current_entity.add_group")
                      2. Is there any way to make a yes/no dropdown, and if not how do I change the size (width) of the inputbox text?
                      
                      require 'sketchup.rb'
                      
                      module Convert_objects_randomly
                      
                       @base_entities = []
                       @target_entities = []
                       @convert_only_groupsinstances = true
                      
                       def Convert_objects_randomly.choosebase
                        @base_entities = Sketchup.active_model.selection.to_a
                        if @base_entities.empty?
                         results = UI.messagebox "Please select base groups and/or components first."
                         Sketchup.send_action "selectSelectionTool;"
                         return
                        end
                       end
                      
                      
                       def Convert_objects_randomly.choosetarget
                        target_entities = Sketchup.active_model.selection.to_a
                        if @base_entities.empty?
                         results = UI.messagebox "Please select base groups and/or components first."
                         Sketchup.send_action "selectSelectionTool;"
                         return
                        end
                      
                        if target_entities.empty?
                         if @target_entities.empty?
                         results = UI.messagebox "Please select target groups and/or components first."
                         Sketchup.send_action "selectSelectionTool;"
                         return
                         end
                         target_entities = @target_entities
                        end
                         
                        target_entities.each do |current_entity|
                         if current_entity.is_a?(Sketchup;;Group)
                          current_entity = current_entity.to_component
                          current_entity.definition = @base_entities[rand(@base_entities.length)].definition
                         elsif current_entity.is_a?(Sketchup;;ComponentInstance)
                          current_entity = current_entity.make_unique
                          current_entity.definition = @base_entities[rand(@base_entities.length)].definition
                         else
                          current_entity = current_entity.add_group
                          current_entity = current_entity.to_component
                          current_entity.definition = @base_entities[rand(@base_entities.length)].definition
                         end 
                        end
                      
                        @target_entities = target_entities
                        Sketchup.active_model.commit_operation
                      
                       end
                      
                       def Convert_objects_randomly.settings
                        if (@convert_only_groupsinstances == true)
                         default = "yes"
                        else
                         default = "no"
                        end
                        settings_query1 = inputbox(["Convert only groups/components to base objects?"],[default],"Convert Objects Randomly Settings")
                        if (settings_query1[0] == "yes")
                         @convert_only_groupsinstances = true
                        else
                         @convert_only_groupsinstances = false
                        end
                       end
                      
                      end #Convert_objects_randomly module
                      
                      
                      Convert_objects_randomly_menu = UI.menu("Plugins").add_submenu("Convert Objects Randomly")
                      Convert_objects_randomly_menu.add_item("Select base objects") {Convert_objects_randomly.choosebase}
                      Convert_objects_randomly_menu.add_item("Convert selected to random base objects") {Convert_objects_randomly.choosetarget}
                      Convert_objects_randomly_menu.add_item("Settings") {Convert_objects_randomly.settings}
                      
                      file_loaded(__FILE__)
                      
                      
                      1 Reply Last reply Reply Quote 0
                      • thomthomT Offline
                        thomthom
                        last edited by

                        @agamemnus said:

                        1. The code refuses to convert lines to groups!! (I have "current_entity = current_entity.add_group")

                        Check the API on that method. It only belongs to Entities collections. Not single Entity
                        http://code.google.com/intl/nb/apis/sketchup/docs/ourdoc/entities.html

                        @agamemnus said:

                        1. Is there any way to make a yes/no dropdown

                        Check the second example in the manual:
                        http://code.google.com/intl/nb/apis/sketchup/docs/ourdoc/ui.html#inputbox

                        Thomas Thomassen β€” SketchUp Monkey & Coding addict
                        List of my plugins and link to the CookieWare fund

                        1 Reply Last reply Reply Quote 0
                        • M Offline
                          MartinRinehart
                          last edited by

                          @agamemnus said:

                          Ok, thanks. How do I convert an entity to an entities collection?

                          You don't. Use an entities collection returned by the entities method:

                          
                          Sketchup.active_model.entities
                          myGroup.entities
                          someComponent.entities
                          
                          

                          Author, Edges to Rubies - The Complete SketchUp Tutorial at http://www.MartinRinehart.com/models/tutorial.

                          1 Reply Last reply Reply Quote 0
                          • A Offline
                            agamemnus
                            last edited by

                            @thomthom said:

                            @agamemnus said:

                            1. The code refuses to convert lines to groups!! (I have "current_entity = current_entity.add_group")

                            Check the API on that method. It only belongs to Entities collections. Not single Entity
                            http://code.google.com/intl/nb/apis/sketchup/docs/ourdoc/entities.html

                            @agamemnus said:

                            1. Is there any way to make a yes/no dropdown

                            Check the second example in the manual:
                            http://code.google.com/intl/nb/apis/sketchup/docs/ourdoc/ui.html#inputbox

                            Ok, thanks. How do I convert an entity to an entities collection?

                            Edit: The textbox width is still really long, even with the dropdown now...

                            1 Reply Last reply Reply Quote 0
                            • A Offline
                              agamemnus
                              last edited by

                              @martinrinehart said:

                              @agamemnus said:

                              Ok, thanks. How do I convert an entity to an entities collection?

                              You don't. Use an entities collection returned by the entities method:

                              
                              > Sketchup.active_model.entities
                              > myGroup.entities
                              > someComponent.entities
                              > 
                              

                              But I can't... it's not a group or component. It's a line.... tried "current_entity = current_entity.entities", no go.

                              1 Reply Last reply Reply Quote 0
                              • TIGT Offline
                                TIG Moderator
                                last edited by

                                You can't convert any raw geometry to a Group.
                                But...

                                my_group=model.active_entities.add_group(my_line)
                                
                                

                                might work if the line has no face etc, then

                                my_instance=my_group.to_component
                                my_definition=my_instance.definition
                                
                                

                                Otherwise clone the line into a group and leave the original alone with

                                my_group=model.active_entities.add_group()
                                my_group.entities.add_line(my_line.start.position,my_line.end.position)
                                
                                

                                which recreates the line inside the new group...

                                TIG

                                1 Reply Last reply Reply Quote 0
                                • A Offline
                                  agamemnus
                                  last edited by

                                  Ugh. Maybe it's just better to use Chris's unsorted geometry->groups script first. πŸ˜„

                                  1 Reply Last reply Reply Quote 0
                                  • A Offline
                                    agamemnus
                                    last edited by

                                    Okay, script 1 is finished. It could use some expansion though, possibly. (eg: (1) convert areas instead of just lines, groups, and components [hard] and (2) don't make identical unique components as options [very doable, but might not be worth it]) The only real problems now are cosmetic:

                                    1. I am not sure that "Convert objects randomly" is a very good name for the script. I can't think of anything else that is both short and also semi-self-explanatory, though.

                                    2. The dropdown in the "options" is too big! I don't know how to set its width.

                                    Code:

                                    
                                    # ----------------------------------
                                    # ==================================
                                    # ----------------------------------
                                    #
                                    # "Convert objects randomly" script
                                    # Released into the public domain by Agamemnus.
                                    # Version 1; November 10, 2009
                                    # Contact the author; sketchup at flyingsoft dot phatcode dot net
                                    #
                                    # Purpose;
                                    #
                                    #     Easily converts a set of objects (target) into another set (base) randomly,
                                    # distributed amongst members of the base set.
                                    #
                                    # Use;
                                    # 1)  Select a set of objects -- currently only components and/or groups work.
                                    # 1b) Pick "Select base objects" in "Plugins">"Convert Objects Randomly".
                                    # 2)  Select a target set of objects -- currently only components, groups, or lines.
                                    # 2b) Pick "Convert selected to random base objects" in "Plugins">"Convert Objects Randomly".
                                    # 2c) Done! You may pick "Convert selected to random base objects" again if you wish --
                                    #     your previous base and target object sets apply if you did not fundamentally change
                                    #     (explode, convert to group, etc-- geometry editing is fine) the target components.
                                    #
                                    # 3) Set "Plugins">"Convert Objects Randomly">"Settings">"Convert lines to base objects?" to "YES"
                                    #    if you want ungrouped lines in the target set to be affected. Set "NO" otherwise.
                                    #    The default is "YES".
                                    # 
                                    # Behavior of result objects in version 1;
                                    # If the picked "base" object is a group, the target object is converted into a unique component.
                                    # If the picked "base" object is a component, the target object is converted into a component
                                    # instance of that component type.
                                    #
                                    # 
                                    # ==Miscellaneous Notes;==
                                    # 1.) Much thanks to the Sketchup forum regulars in helping with problems in this script.
                                    #
                                    # 2.) Looking for Work ;(
                                    # ...in the fields of;
                                    # economic analysis
                                    # business strategy
                                    # marketing
                                    # UI design
                                    # web based programming
                                    # 2D visual art
                                    # 3D visual art.
                                    # general programming.
                                    # M.A. in International Economics and Finance at Brandeis IBS, BA in economics at Brandeis IBS and Brandeis University.
                                    # 16 years of experience in amateur programming in BASIC-based languages (Basic, Freebasic, VB, etc.)
                                    # Several years of experience in PHP and Javascript. Experience in C-LISP, Matlab, and "some"
                                    # experience in Ruby (eh!) and C.
                                    # Work environment must at a _minimum_ contain penguins performing tricks, live.
                                    #
                                    # ----------------------------------
                                    # ==================================
                                    # ----------------------------------
                                    
                                    require 'sketchup.rb'
                                    
                                    module Convert_objects_randomly
                                    
                                     @base_entities = []
                                     @target_entities = []
                                     @convert_lines = true
                                    
                                     def Convert_objects_randomly.choosebase
                                      @base_entities = Sketchup.active_model.selection.to_a
                                      if @base_entities.empty?
                                       results = UI.messagebox "Please select base groups and/or components first."
                                       Sketchup.send_action "selectSelectionTool;"
                                       return
                                      end
                                     end
                                    
                                    
                                     def Convert_objects_randomly.choosetarget
                                      target_entities = Sketchup.active_model.selection.to_a
                                      if @base_entities.empty?
                                       results = UI.messagebox "Please select base groups and/or components first."
                                       Sketchup.send_action "selectSelectionTool;"
                                       return
                                      end
                                    
                                      if target_entities.empty?
                                       if @target_entities.empty?
                                       results = UI.messagebox "Please select target groups and/or components first."
                                       Sketchup.send_action "selectSelectionTool;"
                                       return
                                       end
                                       target_entities = @target_entities
                                      end
                                       
                                      target_entities.each do |current_entity|
                                       if current_entity.is_a?(Sketchup;;Group)
                                        current_entity = current_entity.to_component
                                        current_entity.definition = @base_entities[rand(@base_entities.length)].definition
                                       elsif current_entity.is_a?(Sketchup;;ComponentInstance)
                                        current_entity = current_entity.make_unique
                                        current_entity.definition = @base_entities[rand(@base_entities.length)].definition
                                       elsif (@convert_lines == true)
                                        current_entity = Sketchup.active_model.active_entities.add_group(current_entity)
                                        current_entity = current_entity.to_component
                                        current_entity.definition = @base_entities[rand(@base_entities.length)].definition
                                       end 
                                      end
                                    
                                      @target_entities = target_entities
                                      Sketchup.active_model.commit_operation
                                    
                                     end
                                    
                                     def Convert_objects_randomly.settings
                                      if (@convert_lines == true)
                                       default = "yes"
                                      else
                                       default = "no"
                                      end
                                      settings_query1 = inputbox(["Convert lines to base objects? "],[default], ["yes|no"], "Convert Objects Randomly Settings")
                                      if (settings_query1[0] == "yes")
                                       @convert_lines = true
                                      else
                                       @convert_lines = false
                                      end
                                     end
                                    
                                    end #Convert_objects_randomly module
                                    
                                    
                                    Convert_objects_randomly_menu = UI.menu("Plugins").add_submenu("Convert Objects Randomly")
                                    Convert_objects_randomly_menu.add_item("Select base objects") {Convert_objects_randomly.choosebase}
                                    Convert_objects_randomly_menu.add_item("Convert selected to random base objects") {Convert_objects_randomly.choosetarget}
                                    Convert_objects_randomly_menu.add_item("Settings") {Convert_objects_randomly.settings}
                                    
                                    
                                    1 Reply Last reply Reply Quote 0
                                    • A Offline
                                      agamemnus
                                      last edited by

                                      Here is a file with both scripts (random color and object), and another file that shows the result of using SketchyPhysics 3, these two scripts, and Chris Fullmer's "Scale and Rotate Multiple" and "Loose Geometry to Groups" scripts. (Gems are from the 3D Warehouse)

                                      So now ... what if I wanted to make the result groups instead of component instances? So far the script is only converting everything to unique component instances and changing the definition. Ideally I want to just change the geometry of the groups without making unique component instances. So, assuming I could do one of these, which one is more efficient (faster), and can I even do any of these (and how) --?

                                      1. Convert "target" objects to component instances based on "base" objects, then convert "target" objects back to groups and delete the components.

                                      2. Convert "target" objects straight to groups based on "base" objects.

                                      (If anyone thinks my question is unclear I would rephrase it.. I needs answers! πŸ˜„ )


                                      convert_objects_randomly.rb


                                      rock test.skp

                                      1 Reply Last reply Reply Quote 0
                                      • Chris FullmerC Offline
                                        Chris Fullmer
                                        last edited by

                                        A few things. I'm getting errors when I try to run the script. I have not looked at all the code, so I'm not sure what I'm doing wrong yet. But, I'll try to look it over tonight.

                                        I'm also not entirely sure what your questions are about groups and components and component instances. Maybe it will make more sense when I get the script to run all the way through. I'll try to get back to this in a few hours,

                                        Chris

                                        Lately you've been tan, suspicious for the winter.
                                        All my Plugins I've written

                                        1 Reply Last reply Reply Quote 0
                                        • A Offline
                                          agamemnus
                                          last edited by

                                          @chris fullmer said:

                                          A few things. I'm getting errors when I try to run the script. I have not looked at all the code, so I'm not sure what I'm doing wrong yet. But, I'll try to look it over tonight.

                                          I'm also not entirely sure what your questions are about groups and components and component instances. Maybe it will make more sense when I get the script to run all the way through. I'll try to get back to this in a few hours,

                                          Chris

                                          I don't know why you are getting errors. I am not getting any errors. I did not use any globals AFAIK, so that can't be it. No idea.

                                          I'll try to rehash the question. I'm trying to convert the "target" objects into "base" objects but so far the only way to do that is to convert the "targets", if they are groups or lines, to new/unique component instances and then change the definition of that instance. Instead, I would like to either change the unique component instances back into groups (and delete the component definition), or to simply change the objects right away into groups, depending on whether any of these methods are possible and which one is faster. (see "Convert_objects_randomly.choosetarget_changeobjects")

                                          1 Reply Last reply Reply Quote 0
                                          • Chris FullmerC Offline
                                            Chris Fullmer
                                            last edited by

                                            I am getting

                                            Error: #<NoMethodError: undefined method `definition' for #Sketchup::Group:0xa0636b0>

                                            I am guessing you have a plugin installed that created the Group.definition method. Probably somethin by Thom or TIG? let me know what it is and I'll intall it.

                                            Chris

                                            Lately you've been tan, suspicious for the winter.
                                            All my Plugins I've written

                                            1 Reply Last reply Reply Quote 0
                                            • 1
                                            • 2
                                            • 2 / 2
                                            • First post
                                              Last post
                                            Buy SketchPlus
                                            Buy SUbD
                                            Buy WrapR
                                            Buy eBook
                                            Buy Modelur
                                            Buy Vertex Tools
                                            Buy SketchCuisine
                                            Buy FormFonts

                                            Advertisement