Extracting the sun azimuth angle

I need some python code for extracting the azimuth angle of a scene sun light without having to open the sun panel, ideally not even selecting the light but rather using a specific existing object name such as “MySun”.
I’m trying to write a script to match the rotation of a domelight texture to match the current sun azimuth rotation.
I have some bits and pieces already but I can’t figure out how to get the sun angle from its vector data.
My python scripting skills are pretty poor … :slight_smile:
Can anyone help ?
Thanks !

@juancarreras,

if you´re after the real sun instance object of the document, this should do it:

import scriptcontext

def SunAzimuth():
    sun = scriptcontext.doc.Lights.Sun
    if not sun: return
    print "Azimuth:", sun.Azimuth
    
SunAzimuth()

c.

Thanks clement
Actually I’m not after the document sun but a vray sun which is trated by Rhino as any directional light, so maybe could be identified along the lines of:

#Find VRay sun in document
lights = rs.LightObjects()
for i in range(0, len(lights), 1):
    if (rs.LightName(lights[i])=="MySun"): sun = lights[i]

Ok, hang on for a while, i´ll have to try something…

@juancarreras,

the question is where is north in your case ? below just gets the polar coordinates from the light direction vector xy components. It starts rotation at the x axis and rotates counter-clockwise, so y-axis would be 90 degree:

import scriptcontext
import rhinoscriptsyntax as rs
from math import atan2, degrees

def DoSomething():
    
    ids = rs.ObjectsByName("MySun", select=False, include_lights=True)
    if not ids: return
    if not rs.IsDirectionalLight(ids[0]): return

    direction = rs.VectorReverse(rs.LightDirection(ids[0]))
    deg_angle = degrees(atan2(direction[1], direction[0]))
    if deg_angle < 0: deg_angle += 360
    print deg_angle

DoSomething()

does that help ?

c.

Actually the north is at 12 oclock (zero degrees) and increases clockwise so 3 oclock is 90 degress and 9 oclock would 270. Can you modify it ? Thanks

(BTW how do you quote the code in the message editor so that it displays color coded ?)

got it, simply change the direction indexes to:

atan2(direction[0], direction[1]

Thank works now. Thanks.

just type like this:

```python

then paste the python code and end like this

-
c.

Cool. Thanks so much for your help !

One more question if i may …
How can I get out of a script that is meant to loop many times though a list:

for i in range(0, len(a_list), 1):
     more code
     etc

It seems like the only way is press esc many times and hope that it stops. Not very elegant or even effective sometimes.
Thanks

@juancarreras, try this:

import scriptcontext

def DoSomething():
    for i in xrange(100000000):
        if scriptcontext.escape_test(False):
            break

    print "loop stopped at:", i

DoSomething()

c.

1 Like

Great. That worked !
Thanks again.