SOLVED Script Befehl

Ok Sorry I Post the next Trhead in English.
That was the Google translator!

Hi,

You should also describe where you are stuck instead of only talking about the final goal.. I've created you this script with comment. Please read them and ask question if there are things you do not understand.

To make it simple, i did not implemented the undo system. You can have a look at our manual to understand a bit better what you have to do. And ask questions 😛

Cheers,
Manuel

from typing import Optional
import c4d



def SwitchVisibilityAndCreateKeyFrame (obj) -> None:
    # Switch the visibility of the object and create a keyframe at the current time of the document.
    # If the keyframe already exist, it will update the keyframe and switch between ON and OFF.

    # DescID allow to define how parameter can be access and what data type they are made of.
    # Just like parameter, DescID can be composed of several level to access the correct data.
    # Those levels composed some sort of path to follow to retrieve the correct data.
    # Define two desscID to access the editor and render visibility of the object.
    trackIDs = []
    trackIDs.append(c4d.DescID(c4d.DescLevel(c4d.ID_BASEOBJECT_VISIBILITY_EDITOR, c4d.DTYPE_LONG,0)))
    trackIDs.append(c4d.DescID(c4d.DescLevel(c4d.ID_BASEOBJECT_VISIBILITY_RENDER, c4d.DTYPE_LONG,0)))
    for trackID in trackIDs:
        # Define the parameter value in the object itself. If it is undef we define it to off.
        # Otherwise, we switch the value.
        if obj[trackID] == c4d.OBJECT_UNDEF:
            obj[trackID] = c4d.OBJECT_OFF
        else:
            obj[trackID] = obj[trackID] ^ 1
        # With the track ID, FindCTrack can be used to retrieve if a track exist for this object.
        track = obj.FindCTrack(trackID)
        if track is None:
            #if there is no track, create it and insert it in the object.
            track = c4d.CTrack(obj, trackID)
            if track is None:
                raise RuntimeError("Cannot create the track.")
            obj.InsertTrackSorted(track)

        # Retrieve the curve from the track. For more information see our track manual
        curve = track.GetCurve()
        if curve is None:
            raise RuntimeError("Failed to retrieve the curves, Object may not have curves.")

        # Retrieve the current time of the document so the key can be added at the right place
        currentTime = doc.GetTime()
        keyDict = curve.AddKey(currentTime)

        # Checks if the key have been added
        if keyDict is None:
            raise MemoryError("Failed to create a key")

        # Retrieves the inserted key and its index
        key = keyDict["key"]
        keyIndex = keyDict["nidx"]

        # Sets the value of the key. Because in this case, the function SetGeData must be used.
        # SetValue should only be used for Float values.
        key.SetGeData(curve, obj[trackID])
        
        # Mandatory: Fill the key with default settings
        curve.SetKeyDefault(doc, keyIndex)

        # Changes it's interpolation to step.
        key.SetInterpolation(curve, c4d.CINTERPOLATION_STEP)




def main() -> None:
    # Called when the plugin is selected by the user. Similar to CommandData.Execute.
    # Retrieve the active objects
    allobj = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_CHILDREN)
    for obj in allobj:
        SwitchVisibilityAndCreateKeyFrame(obj)
    c4d.EventAdd()

if __name__=='__main__':
    main()

Kudos to Google Translator, did a pretty good job then.
If you are willing to pay a few bucks, I could also talk you through in German while sharing screen.
You could find me as MighT over on Core4D forum and DM me there. Or you can mail to job AT andreasblock DOT de.

Thank you kudos! for the nice Answer!

M_Magalhaes Thank you for your answer, I'm sorry that I expressed myself so wrongly and asked the same question again.
Have you a tip for me, how the keyframe command is for a Python Script?
Thank you very much!

I mean the adtribute palette / base / editor visibility and render visibility key frame i can't find a script command for this click function?
Thank you very much!

There is no single function to accomplish this. You will need to add a track, a curve and aa keyframe.

hi.

thanks a lot @WDP

as @a_block said, there is no one function solution for that. You need to know how to create a key for that parameter. We have an example on github how to create a track and a keyframe for the coordinates (only the Y track) of an object. If you know how to use DescID, that will be easy to adapt the example. You have our manual about DescID on our c++ documentation that will help you to understand how it works.

I would start using GetActiveObjects and iterate the retrieved objects to display the current state of the "Show in viewport" and after that, trying to add the track and the keyframe.

Cheers,
Manuel

allmost alll functions in C4D have a Script ID and there is no script command for editor visibility and rendering visibility of Renderer( Key Frame) for a Animation? I have an animation and would like to only undef objects from the keyframe for editor visibility and render visibility per Key Frame, why isn't there a script command for these two functions?
Tried the Git Hub sample that only creates new objects.
I just want a script command that lets you control the (attributes base editor visibility and render visibility / Key Frame).
Do you also have a tip for me why can I only control individual objects and not several with this script?
Thank you very much!

import c4d

def main():
    """ Toggles both the render and editor visbilty of the active object.
    """
    if op is None:
        return


    if op.GetEditorMode() == c4d.MODE_UNDEF:
        op.SetEditorMode(c4d.MODE_ON)
        op.SetRenderMode(c4d.MODE_ON)

    elif op.GetEditorMode() == c4d.MODE_OFF:
        op.SetEditorMode(c4d.MODE_UNDEF)
        op.SetRenderMode(c4d.MODE_UNDEF)

    else:
        op.SetEditorMode(c4d.MODE_OFF)
        op.SetRenderMode(c4d.MODE_OFF)

    c4d.EventAdd()


if __name__=='__main__':
    main()

@wdp That's not quite correct, the CallCommand IDs and the simple property calls will (almost) never set a key, for example, if you change the subdivision property in a cube, this will be a static change and not set any animation key either. The visibility flags behave exactly the same. Triggering the key-setting is just another functionality, which must be called separately.

If you're interested in this specific group of functions, I have a course
https://www.patreon.com/cairyn
which explains this stuff in section 14.
(Though I am also sure that the PluginCafé has the answer for free already, I remember the topic being discussed, but you may need to search for it, and perhaps study the API some more. Also, as @m_magalhaes said, there is a Maxon Github example where you can copy and paste code from.)

Once you understand the way keys are handled, you can create a function that works for any DescID (or copy it...), which is probably what you want.

As for your other question, you are calling the EditorMode functions on the op variable which is a predefined variable containing a single selection. If there are no objects selected OR there is more than one object selected, then op will be None so your call causes an error.
To handle more than one selected object at a time, you need to retrieve a list of selections by calling GetActiveObjects ( @m_magalhaes said that as well) and then go through a for loop calling the functions for every object in the list.

@wdp said in Script Befehl:

allmost alll functions in C4D have a Script ID and there is no script command for editor visibility and rendering visibility of Renderer( Key Frame) for a Animation? I have an animation and would like to only undef objects from the keyframe for editor visibility and render visibility per Key Frame, why isn't there a script command for these two functions?

You mean that the script log does not log it correctly? That could be considered as a bug, but the script log does not log everything.

I 'am not sure if you are asking to someone to do the work or want to learn how to do it?
I linked you this thread where i added some code to toggle the viewport and render setting from default to off for all the selected objects, using GetActiveObjects

Based on examples found on github you can do something like this. You would need to add the Undo step, please have a look at our manual to understand how it works

Of course, you must add the check for the render track. That can be done by creating an array of descID and with a loop you can check several tracks.

from typing import Optional
import c4d


def IsThereAKey (obj) -> None:
     # Searches object's view track
     # For that the track ID must be defined and created. DescID are composed of descLevel. See c++ manual for more information
    trackID = c4d.DescID(c4d.DescLevel(c4d.ID_BASEOBJECT_VISIBILITY_EDITOR, c4d.DTYPE_LONG, op.GetType()))
    # With the track ID, FindCTrack can be used to retrieve if a track exist for this object.
    track = obj.FindCTrack(trackID)
    if track is None:
        raise RuntimeError("Failed to retrieve the track, Object may not have a visibility track.")

    # Retrieve the curve from the track. For more information see our track manual 
    # https://developers.maxon.net/docs/Cinema4DCPPSDK/html/page_manual_ctrack.html
    curve = track.GetCurve()
    if curve is None:
        raise RuntimeError("Failed to retrieve the curves, Object may not have curves.")
    # Retrieve the document current time to see if a key exist for that frame
    time = doc.GetTime()
    # try to find a key at the current time of the document
    found = curve.FindKey(time)
    if found is None:
        raise RuntimeError("Could not find key at given BaseTime.")

    # The key information can be or the key can be deleted.
    # To delete the key, the function DelKey will be used
    
    # The index of the retrieved key
    index = found["idx"]
    # The retrieved key
    key = found["key"]
    print (index, key)
    # To delete the key, the function DelKey will be used
    curve.DelKey(index)


def main() -> None:

    allobj = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_CHILDREN)
    for obj in allobj:
        IsThereAKey(obj)
    c4d.EventAdd()

if __name__=='__main__':
    main()

Cheers,
Manuel

Thanks for the script that deletes a key frame, but do you also have a script that adds the key frame?

hi,

I already pointed you to our github repository and our example to create a track and a keyframe in this post. 22 days ago. The purpose of this forum is to answer people's question, not to develop their tool. Please read our forum guidelines. Is there anything topic you do not understand to create your script, or what part are you struggling with?

Cheers,
Manuel

Hi!
Sorry I'm new to Python and still have to learn a lot, I've tested the Github example thanks for that, but I still can't get a keyframe to control my object visibility in Stage Animation?
It would be very nice of you if you could help me again.
Thank you very much!

Hi,

You should also describe where you are stuck instead of only talking about the final goal.. I've created you this script with comment. Please read them and ask question if there are things you do not understand.

To make it simple, i did not implemented the undo system. You can have a look at our manual to understand a bit better what you have to do. And ask questions 😛

Cheers,
Manuel

from typing import Optional
import c4d



def SwitchVisibilityAndCreateKeyFrame (obj) -> None:
    # Switch the visibility of the object and create a keyframe at the current time of the document.
    # If the keyframe already exist, it will update the keyframe and switch between ON and OFF.

    # DescID allow to define how parameter can be access and what data type they are made of.
    # Just like parameter, DescID can be composed of several level to access the correct data.
    # Those levels composed some sort of path to follow to retrieve the correct data.
    # Define two desscID to access the editor and render visibility of the object.
    trackIDs = []
    trackIDs.append(c4d.DescID(c4d.DescLevel(c4d.ID_BASEOBJECT_VISIBILITY_EDITOR, c4d.DTYPE_LONG,0)))
    trackIDs.append(c4d.DescID(c4d.DescLevel(c4d.ID_BASEOBJECT_VISIBILITY_RENDER, c4d.DTYPE_LONG,0)))
    for trackID in trackIDs:
        # Define the parameter value in the object itself. If it is undef we define it to off.
        # Otherwise, we switch the value.
        if obj[trackID] == c4d.OBJECT_UNDEF:
            obj[trackID] = c4d.OBJECT_OFF
        else:
            obj[trackID] = obj[trackID] ^ 1
        # With the track ID, FindCTrack can be used to retrieve if a track exist for this object.
        track = obj.FindCTrack(trackID)
        if track is None:
            #if there is no track, create it and insert it in the object.
            track = c4d.CTrack(obj, trackID)
            if track is None:
                raise RuntimeError("Cannot create the track.")
            obj.InsertTrackSorted(track)

        # Retrieve the curve from the track. For more information see our track manual
        curve = track.GetCurve()
        if curve is None:
            raise RuntimeError("Failed to retrieve the curves, Object may not have curves.")

        # Retrieve the current time of the document so the key can be added at the right place
        currentTime = doc.GetTime()
        keyDict = curve.AddKey(currentTime)

        # Checks if the key have been added
        if keyDict is None:
            raise MemoryError("Failed to create a key")

        # Retrieves the inserted key and its index
        key = keyDict["key"]
        keyIndex = keyDict["nidx"]

        # Sets the value of the key. Because in this case, the function SetGeData must be used.
        # SetValue should only be used for Float values.
        key.SetGeData(curve, obj[trackID])
        
        # Mandatory: Fill the key with default settings
        curve.SetKeyDefault(doc, keyIndex)

        # Changes it's interpolation to step.
        key.SetInterpolation(curve, c4d.CINTERPOLATION_STEP)




def main() -> None:
    # Called when the plugin is selected by the user. Similar to CommandData.Execute.
    # Retrieve the active objects
    allobj = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_CHILDREN)
    for obj in allobj:
        SwitchVisibilityAndCreateKeyFrame(obj)
    c4d.EventAdd()

if __name__=='__main__':
    main()

Thank you very much!!

Hello @WDP,

without any further questions and other postings, we will consider this topic as solved and flag it as such by Friday, 17/06/2022.

Thank you for your understanding,
Ferdinand