Struct nsi::context::Context

source ·
pub struct Context<'a>(/* private fields */);
Expand description

An ɴꜱɪ Context.

A Context is used to describe a scene to the renderer and request images to be rendered from it.

Safety

A Context may be used in multiple threads at once.

Lifetime

A Context can be used without worrying about its lifetime until you want to store it somewhere, e.g. in a struct.

The reason Context has an explicit lifetime is so that it can take References and Callbacks (closures). These must be valid until the context is dropped and this guarantee requires explicit lifetimes. When you use a context directly this is not an issue but when you want to reference it somewhere the same rules as with all references apply.

Further Reading

See the ɴꜱɪ documentation on context handling.

Implementations§

source§

impl<'a> Context<'a>

source

pub fn new(args: Option<&[Arg<'_, 'a>]>) -> Option<Context<'a>>

Creates an ɴsɪ context.

Contexts may be used in multiple threads at once.

Examples
// Create rendering context that dumps to stdout.
let ctx =
    nsi::Context::new(Some(&[nsi::string!("streamfilename", "stdout")]))
        .expect("Could not create ɴsɪ context.");
Error

If this method fails for some reason, it returns None.

source

pub fn create( &self, handle: &str, node_type: &str, args: Option<&[Arg<'_, 'a>]> )

Creates a new node.

Arguments
  • handle – A node handle. This string will uniquely identify the node in the scene.

    If the supplied handle matches an existing node, the function does nothing if all other parameters match the call which created that node. Otherwise, it emits an error. Note that handles need only be unique within a given Context. It is ok to reuse the same handle inside different Contexts.

  • node_type – The type of node to create. The crate has &str constants for all nodes that are in the official NSI specification. As this parameter is just a string you can instance other node types that a particular implementation may provide and which are not part of the official specification.

  • args – A slice of optional Arg arguments. There are no optional arguments defined as of now.

// Create a context to send the scene to.
let ctx = nsi::Context::new(None).unwrap();

// Create an infinte plane.
ctx.create("ground", nsi::PLANE, None);
source

pub fn delete(&self, handle: &str, args: Option<&[Arg<'_, 'a>]>)

This function deletes a node from the scene. All connections to and from the node are also deleted.

Note that it is not possible to delete the .root or the .global node.

Arguments
  • handle – A handle to a node previously created with create().

  • args – A slice of optional Arg arguments.

Optional Arguments
  • "recursive" (Integer) – Specifies whether deletion is recursive. By default, only the specified node is deleted. If a value of 1 is given, then nodes which connect to the specified node are recursively removed. Unless they meet one of the following conditions:

    • They also have connections which do not eventually lead to the specified node.
    • Their connection to the node to be deleted was created with a strength greater than 0.

    This allows, for example, deletion of an entire shader network in a single call.

source

pub fn set_attribute(&self, handle: &str, args: &[Arg<'_, 'a>])

This functions sets attributes on a previously node. All optional arguments of the function become attributes of the node.

On a shader, this function is used to set the implicitly defined shader arguments.

Setting an attribute using this function replaces any value previously set by set_attribute() or set_attribute_at_time().

To reset an attribute to its default value, use delete_attribute().

Arguments
  • handle – A handle to a node previously created with create().

  • args – A slice of optional Arg arguments.

source

pub fn set_attribute_at_time( &self, handle: &str, time: f64, args: &[Arg<'_, 'a>] )

This function sets time-varying attributes (i.e. motion blurred).

The time argument specifies at which time the attribute is being defined.

It is not required to set time-varying attributes in any particular order. In most uses, attributes that are motion blurred must have the same specification throughout the time range.

A notable exception is the P attribute on particles node which can be of different size for each time step because of appearing or disappearing particles. Setting an attribute using this function replaces any value previously set by set_attribute().

Arguments
  • handle – A handle to a node previously created with create().

  • time – The time at which to set the value.

  • args – A slice of optional Arg arguments.

source

pub fn delete_attribute(&self, handle: &str, name: &str)

This function deletes any attribute with a name which matches the name argument on the specified object. There is no way to delete an attribute only for a specific time value.

Deleting an attribute resets it to its default value.

For example, after deleting the transformationmatrix attribute on a transform node, the transform will be an identity. Deleting a previously set attribute on a shader node will default to whatever is declared inside the shader.

Arguments
  • handle – A handle to a node previously created with create().

  • name – The name of the attribute to be deleted/reset.

source

pub fn connect( &self, from: &str, from_attr: Option<&str>, to: &str, to_attr: &str, args: Option<&[Arg<'_, 'a>]> )

Create a connection between two elements.

It is not an error to create a connection which already exists or to remove a connection which does not exist but the nodes on which the connection is performed must exist.

Arguments
  • from – The handle of the node from which the connection is made.

  • from_attr – The name of the attribute from which the connection is made. If this is an empty string then the connection is made from the node instead of from a specific attribute of the node.

    If this is None the node itself will be connected.

  • to – The handle of the node to which the connection is made.

  • to_attr – The name of the attribute to which the connection is made. If this is an empty string then the connection is made to the node instead of to a specific attribute of the node.

Optional Arguments
  • "value" – This can be used to change the value of a node’s attribute in some contexts. Refer to guidelines on inter-object visibility for more information about the utility of this parameter.

  • "priority" (Integer) – When connecting attribute nodes, indicates in which order the nodes should be considered when evaluating the value of an attribute.

  • "strength" (Integer) – A connection with a strength greater than 0 will block the progression of a recursive delete().

source

pub fn disconnect( &self, from: &str, from_attr: Option<&str>, to: &str, to_attr: &str )

This function removes a connection between two elements.

The handle for either node may be the special value .all. This will remove all connections which match the other three arguments.

Examples
// Disconnect everything from the scene's root.
ctx.disconnect(nsi::ALL, None, ".root", "");
source

pub fn evaluate(&self, args: &[Arg<'_, 'a>])

This function includes a block of interface calls from an external source into the current scene. It blends together the concepts of a file include, commonly known as an archive, with that of procedural include which is traditionally a compiled executable. Both are the same idea expressed in a different language.

Note that for delayed procedural evaluation you should use a Procedural node.

The ɴꜱɪ adds a third option which sits in-between — Lua scripts. They are more powerful than a simple included file yet they are also easier to generate as they do not require compilation.

For example, it is realistic to export a whole new script for every frame of an animation. It could also be done for every character in a frame. This gives great flexibility in how components of a scene are put together.

The ability to load ɴꜱɪ commands from memory is also provided.

Optional Arguments
  • "type" (String) – The type of file which will generate the interface calls. This can be one of:

    • "apistream" – Read in an ɴꜱɪ stream. This requires either "filename" or "buffer"/"size" arguments to be specified too.

    • "lua" – Execute a Lua script, either from file or inline. See also how to evaluate a Lua script.

    • "dynamiclibrary" – Execute native compiled code in a loadable library. See dynamic library procedurals for an implementation example in C.

  • "filename" (String) – The name of the file which contains the interface calls to include.

  • "script" (String) – A valid Lua script to execute when "type" is set to "lua".

  • "buffer" (String) – A memory block that contain ɴꜱɪ commands to execute.

  • "backgroundload" (Integer) – If this is nonzero, the object may be loaded in a separate thread, at some later time. This requires that further interface calls not directly reference objects defined in the included file. The only guarantee is that the file will be loaded before rendering begins.

source

pub fn render_control(&self, action: Action, args: Option<&[Arg<'_, 'a>]>)

This function is the only control function of the API.

It is responsible of starting, suspending and stopping the render. It also allows for synchronizing the render with interactive calls that might have been issued.

Note that this call will block if Action::Wait is selected.

Arguments
  • action – Specifies the render Action to be performed on the scene.
Optional Arguments
  • "progressive" (Integer) – If set to 1, render the image in a progressive fashion.

  • "interactive" (Integer) – If set to 1, the renderer will accept commands to edit scene’s state while rendering. The difference with a normal render is that the render task will not exit even if rendering is finished. Interactive renders are by definition progressive.

  • "callback" (FnStatus) – A closure that will be called be when the status of the render changes.

    Example
    let status_callback = nsi::StatusCallback::new(
        |_ctx: &nsi::Context, status: nsi::RenderStatus| {
            println!("Status: {:?}", status);
          },
       );
    
    /// The renderer will abort because we didn't define an output driver.
    /// So our status_callback() above will receive RenderStatus::Aborted.
    ctx.render_control(
        nsi::Action::Start,
        Some(&[
            nsi::integer!("interactive", true as _),
            nsi::callback!("callback", status_callback),
        ]),
    );
    
    // Block until the renderer is really done.
    ctx.render_control(nsi::Action::Wait, None);

Trait Implementations§

source§

impl<'a> Clone for Context<'a>

source§

fn clone(&self) -> Context<'a>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'a> Debug for Context<'a>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<'a> From<i32> for Context<'a>

source§

fn from(context: i32) -> Context<'a>

Converts to this type from the input type.
source§

impl<'a> Hash for Context<'a>

source§

fn hash<__H>(&self, state: &mut __H)where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<'a> PartialEq for Context<'a>

source§

fn eq(&self, other: &Context<'a>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'a> Eq for Context<'a>

source§

impl<'a> Send for Context<'a>

source§

impl<'a> StructuralEq for Context<'a>

source§

impl<'a> StructuralPartialEq for Context<'a>

source§

impl<'a> Sync for Context<'a>

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Context<'a>

§

impl<'a> Unpin for Context<'a>

§

impl<'a> !UnwindSafe for Context<'a>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V