Maxon Developers Maxon Developers
    • Documentation
      • Cinema 4D Python API
      • Cinema 4D C++ API
      • Cineware API
      • ZBrush GoZ API
      • Code Examples on Github
    • Forum
    • Downloads
    • Support
      • Support Procedures
      • Registered Developer Program
      • Plugin IDs
      • Contact Us
    • Categories
      • Overview
      • News & Information
      • Cinema 4D SDK Support
      • Cineware SDK Support
      • ZBrush 4D SDK Support
      • Bugs
      • General Talk
    • Unread
    • Recent
    • Tags
    • Users
    • Login
    1. Maxon Developers Forum
    2. HerrMay
    3. Best
    H
    • Profile
    • Following 0
    • Followers 0
    • Topics 20
    • Posts 62
    • Best 7
    • Controversial 0
    • Groups 0

    Best posts made by HerrMay

    • RE: Blank appearing dropdown cycle

      Hi @m_adam ,

      of course, stupid me. 🀦 I knew it was something simple I’m missing here. Seems I didn’t see the elephant in the room. πŸ˜„

      This works like a charm now. Thank you!

      Allow one follow up question though. If I now want to translate this code to a TagData Plugin I’m pretty sure I don’t wanna use a global variable, do I? Would it be sufficient to make that variable a member variable inside of def __init__(self) of the Tag Plugin class?

      Cheers,
      Sebastian

      posted in Cinema 4D SDK
      H
      HerrMay
    • RE: Unique Material per Object Plugin instance?

      Hi Guys,

      as I'm pretty sure I found a way to achieve what I'm after I thought I update this thread. Maybe this will help others as well. πŸ˜‰

      After taking some time to make NodeData.CopyTo() work, I ended up not getting it to work at all.

      So I thought about how I could achieve what I'm after a different way. Long story short, I ended up implementing a MessageData plugin as some kind of watchdog for a document. Since its CoreMessage runs on the main thread I can happily insert and delete materials as much as I wish to. (At least I'm hoping so 😬 😁)

      Tl; dr
      The idea behind this goes as follows. I have a timer running and in addition to that I listen for c4d.EVMSG_CHANGE and do some checking to see if the scene needs to update. In my case it's comparing the amount of a specific object against the amount of "specific" materials. If there's a difference I use that difference to delete or insert materials until there's no difference. Once there's no difference I can assign the materials to the objects and let each object control its own material.

      To distinguish between materials responsible for my plugin and the ones that aren't I make sure to put a unique plugin id inside the base container of the material I can then check for.

      Here's a code snippet of that MessageData:

      class Watchdog(c4d.plugins.MessageData):
      
          PLUGIN_ID = "Use your own unique one"
          PLUGIN_NAME = "A MessageData plugin."
          PLUGIN_INFO = 0
      
          def __init__(self):
              self._time = 1000
      
          def GetTimer(self):
              return self._time
      
          def SetTimer(self, time):
              self._time = time
      
      
          @property
          def should_execute(self):
              is_mainthread = c4d.threading.GeIsMainThread()
              check_running = (
                  bool(c4d.CheckIsRunning(c4d.CHECKISRUNNING_EDITORRENDERING)),
                  bool(c4d.CheckIsRunning(c4d.CHECKISRUNNING_EXTERNALRENDERING)),
                  bool(c4d.CheckIsRunning(c4d.CHECKISRUNNING_INTERACTIVERENDERING)),
                  bool(c4d.CheckIsRunning(c4d.CHECKISRUNNING_ANIMATIONRUNNING)),
                  bool(c4d.CheckIsRunning(c4d.CHECKISRUNNING_VIEWDRAWING))
              )
              is_running = any(item is True for item in check_running)
              return is_mainthread and not is_running
      
      
          def CoreMessage(self, mid, mdata):
      
              if not self.should_execute:
                  return False
      
              doc = c4d.documents.GetActiveDocument()
              # SceneHandler is a custom class I delegate the whole creation and comparing stuff to.
              objs, mats = ..., ...
              scene = SceneHandler(objs, mats)
      
              # Check for a change and start the timer again. But only if the scene should update. Otherwise the timer would run all the time.
              if mid == c4d.EVMSG_CHANGE:
                  if scene.should_update:
                      self.SetTimer(1000)
      
              # If we get a timer event we update the scene as long as it shouldn't update anymore. We can then stop the timer.
              if mid == c4d.MSG_TIMER:
                  if not scene.should_update:
                      self.SetTimer(0)
                  scene.update(doc)
      
              return True
      

      Maybe this will help others. Since I found a solution for my problem this thread can be marked solved.

      Cheers,
      Sebastian

      posted in Cinema 4D SDK
      H
      HerrMay
    • RE: Run a GUI Dialog AFTER C4D Launches not BEFORE?

      Hi @bentraje,

      Iβ€˜m not sure but maybe checking for c4d. C4DPL_PROGRAM_STARTED in def PluginMessage(id, data) could be of any help here.

      Something like below.

      import c4d
      import sys
      
      def PluginMessage(id, data):
          if id == c4d.C4DPL_PROGRAM_STARTED:
              # Do your messaging here. 
              return True
      
          return False
      
      

      Cheers,
      Sebastian!

      posted in Cinema 4D SDK
      H
      HerrMay
    • RE: How to Add Child Shaders to a Fusion Shader?

      Hello @ferdinand,

      when trying out your function to traverse shaders I noticed that for two materials in the scene it yields for the first material all the shaders of itself but also all the shaders of the second material. For second material it works like expected and yields only the shaders of itself.

      After fiddling around a bit with some other code of you from this post I think I ended up with a function that is yielding all the shaders from a material iteratively.

      Find the code below. Maybe this will help others. πŸ™‚

      Cheers,
      Sebastian

      def iter_shaders(node):
          """Credit belongs to Ferdinand from the Plugincafe. I added only the part with the material and First Shader checking.
      
      Yields all descendants of ``node`` in a truly iterative fashion.
      
          The passed node itself is yielded as the first node and the node graph is
          being traversed in depth first fashion.
      
          This will not fail even on the most complex scenes due to truly
          hierarchical iteration. The lookup table to do this, is here solved with
          a dictionary which yields favorable look-up times in especially larger
          scenes but results in a more convoluted code. The look-up could
          also be solved with a list and then searching in the form ``if node in
          lookupTable`` in it, resulting in cleaner code but worse runtime metrics
          due to the difference in lookup times between list and dict collections.
          """
          if not node:
              return
      
          # The lookup dictionary and a terminal node which is required due to the
          # fact that this is truly iterative, and we otherwise would leak into the
          # ancestors and siblings of the input node. The terminal node could be
          # set to a different node, for example ``node.GetUp()`` to also include
          # siblings of the passed in node.
          visisted = {}
          terminator = node
      
          while node:
      
              if isinstance(node, c4d.Material) and not node.GetFirstShader():
                 break
              
              if isinstance(node, c4d.Material) and node.GetFirstShader():
                  node = node.GetFirstShader()
              
              # C4DAtom is not natively hashable, i.e., cannot be stored as a key
              # in a dict, so we have to hash them by their unique id.
              node_uuid = node.FindUniqueID(c4d.MAXON_CREATOR_ID)
              if not node_uuid:
                  raise RuntimeError("Could not retrieve UUID for {}.".format(node))
      
              # Yield the node when it has not been encountered before.
              if not visisted.get(bytes(node_uuid)):
                  yield node
                  visisted[bytes(node_uuid)] = True
      
              # Attempt to get the first child of the node and hash it.
              child = node.GetDown()
      
              if child:
                  child_uuid = child.FindUniqueID(c4d.MAXON_CREATOR_ID)
                  if not child_uuid:
                      raise RuntimeError("Could not retrieve UUID for {}.".format(child))
      
              # Walk the graph in a depth first fashion.
              if child and not visisted.get(bytes(child_uuid)):
                  node = child
      
              elif node == terminator:
                  break
      
              elif node.GetNext():
                  node = node.GetNext()
      
              else:
                  node = node.GetUp()
      
      posted in Cinema 4D SDK
      H
      HerrMay
    • RE: Script: Connect + Delete all subdivision surface objects

      Hi @derekheisler,

      there are multiple reasons why your script isn't catching all of you SDS objects. Number one is that you only take the top level of objects into account. doc.GetObjects() does not account for nested objects that live as children under some other objects. So one solution here is to write a custom function that traverses the complete document i.e. not only the top level objects but every child, sibling, grandchild and so on.

      Number two is in Cinema there is no symbol c4d.Osubdiv. The correct symbol is c4d.Osds. ChatGPT knows and can do a lot, but not everything. πŸ˜‰

      One additional suggestion. While it can be comfortable to simply use c4d.CallCommand, for proper undo handling you should avoid it and instead use e.g. node.Remove() if you want to delete some object.

      Having said all of that, find below a script that finds all SDS objects gets a copy and of them, bakes them down and inserts the new polygon objects into your document.

      I left out the part to set back the objects position back for you to find out.

      Cheers,
      Sebastian

      import c4d
      
      def get_next(node):
          """Return the next node from a tree-like hierarchy."""
          
          if node.GetDown():
              return node.GetDown()
          
          while not node.GetNext() and node.GetUp():
              node = node.GetUp()
              
          return node.GetNext()
      
      def iter_tree(node):
          """Iterate a tree-like hierarchy yielding every object starting at *node*."""
          
          while node:
              yield node
              node = get_next(node)
              
      def iter_sds_objects(doc):
          """Iterate a tree-like hierarchy yielding every +
          SDS object starting at the first object in the document.
          """
          
          is_sds = lambda node: node.CheckType(c4d.Osds)
          node = doc.GetFirstObject()
          
          for obj in filter(is_sds, iter_tree(node)):
              yield obj
      
      
      def join_objects(op, doc):
          """Join a hierarchy of objects and return them as a single polygon."""
          
          settings = c4d.BaseContainer()
      
          res = c4d.utils.SendModelingCommand(
              command=c4d.MCOMMAND_JOIN,
              list=[op],
              mode=c4d.MODELINGCOMMANDMODE_ALL,
              bc=settings,
              doc=doc
          )
          
          if not isinstance(res, list) or not res:
              return
          
          res = res[0]
          return res.GetClone()
      
      
      # Main function
      def main():
          
          doc.StartUndo()
          
          null = c4d.BaseObject(c4d.Onull)
          
          tempdoc = c4d.documents.BaseDocument()
          tempdoc.InsertObject(null)
          
          for sds in iter_sds_objects(doc):
              clone = sds.GetClone()
              clone.InsertUnderLast(null)
              
          joined = join_objects(null, tempdoc)
          
          doc.InsertObject(joined)
          doc.AddUndo(c4d.UNDOTYPE_NEW, joined)
          
          doc.EndUndo()
          c4d.EventAdd()
      
      # Execute main()
      if __name__=='__main__':
          main()
      
      posted in Cinema 4D SDK
      H
      HerrMay
    • RE: Issue collecting all the shaders in a material

      Hi @John_Do,

      the multiple loop of some shaders can indeed come from the way the TraverseShaders function iterates the shader tree. Additionally theat function has another drawback as its iterating the tree utilizing recursion which can lead to problems on heavy scenes.

      Find below a script that uses an iterative approach of walking a shader tree. As I don't have access to Corona I could only test it for standard c4d materials.

      Cheers,
      Sebastian

      import c4d
      
      doc: c4d.documents.BaseDocument  # The active document
      
      def iter_shaders(node):
          """Credit belongs to @ferdinand from the Plugincafe. I added only the part with the material and First Shader checking.
          
          Yields all descendants of ``node`` in a truly iterative fashion.
      
          The passed node itself is yielded as the first node and the node graph is
          being traversed in depth first fashion.
      
          This will not fail even on the most complex scenes due to truly
          hierarchical iteration. The lookup table to do this, is here solved with
          a dictionary which yields favorable look-up times in especially larger
          scenes but results in a more convoluted code. The look-up could
          also be solved with a list and then searching in the form ``if node in
          lookupTable`` in it, resulting in cleaner code but worse runtime metrics
          due to the difference in lookup times between list and dict collections.
          """
          if not node:
              return
      
          # The lookup dictionary and a terminal node which is required due to the
          # fact that this is truly iterative, and we otherwise would leak into the
          # ancestors and siblings of the input node. The terminal node could be
          # set to a different node, for example ``node.GetUp()`` to also include
          # siblings of the passed in node.
          visisted = {}
          terminator = node
      
          while node:
      
              if isinstance(node, c4d.Material) and not node.GetFirstShader():
                 break
              
              if isinstance(node, c4d.Material) and node.GetFirstShader():
                  node = node.GetFirstShader()
              
              # C4DAtom is not natively hashable, i.e., cannot be stored as a key
              # in a dict, so we have to hash them by their unique id.
              node_uuid = node.FindUniqueID(c4d.MAXON_CREATOR_ID)
              if not node_uuid:
                  raise RuntimeError("Could not retrieve UUID for {}.".format(node))
      
              # Yield the node when it has not been encountered before.
              if not visisted.get(bytes(node_uuid)):
                  yield node
                  visisted[bytes(node_uuid)] = True
      
              # Attempt to get the first child of the node and hash it.
              child = node.GetDown()
      
              if child:
                  child_uuid = child.FindUniqueID(c4d.MAXON_CREATOR_ID)
                  if not child_uuid:
                      raise RuntimeError("Could not retrieve UUID for {}.".format(child))
      
              # Walk the graph in a depth first fashion.
              if child and not visisted.get(bytes(child_uuid)):
                  node = child
      
              elif node == terminator:
                  break
      
              elif node.GetNext():
                  node = node.GetNext()
      
              else:
                  node = node.GetUp()
              
      def main():
          
          materials = doc.GetActiveMaterials()
          tab = " \t"
      
          for material in materials:
          
              # Step over non Corona Physical materials or Corona Legacy materials.
              if material.GetType() not in (1056306, 1032100):
                  continue
              
              print (f"{material = }")
      
              for shader in iter_shaders(material):
                  print (f"{tab}{shader = }")
                  
              print(end="\n")
      
      if __name__ == '__main__':
          main()
      
      posted in Cinema 4D SDK
      H
      HerrMay
    • Dynamically changing custom icon of TagData Plugin

      Hi guys,

      I have a tag plugin which makes use of c4d.MSG_GETCUSTOMICON stole the code from here to dynamically change its icon based on a parameter of the tag.

      While this is all fine and dandy, I encountered the problem that this only works if I add the tag to a single object. The minute I have multiple objects selected and add my tag plugin to them, the first (or last, depending how you want to see it) always loads the wrong icon while the other objects get the correct one. See pictures below.

      Wrong behaviour:
      Not_Working.jpg

      Expected behaviour:
      Working.jpg

      My feeling is, that c4d.MSG_MENUPREPARE is the culprit here and only gets called for a single instance of the tag. Not sure though.

      To circumvent this I implemented a c4d.plugins.MessageData plugin which reacts to a c4d.SpecialEventAdd() call I send every time c4d.MSG_MENUPREPARE is called received in the tag plugin. So in essence I delegate the work to the MessageData plugin which is now responsible to set the parameter on the tag plugin instances.

      Long story short - it works. πŸ˜„
      But I wonder if this is "the right" way to do it. As it feels a little bit clunky and also somehow overkill for such a small feature. Imagine having a couple of plugins which all implement some similar feature. All of these plugins would then need a MessageData plugin which communicates with them.

      So, to finish this of. Could someone tell me if this is the intended approach or if I#m missing something here and doing things unnecessarily complicated?

      I attached the project so that its easier to follow.

      TagTest.zip

      Cheers,
      Sebastian

      posted in Cinema 4D SDK python s26 windows
      H
      HerrMay