WebGL FinalMesh API | 3D Window/Viewport

iv.window

This is 3D Viewport object, associated with canvas, it has it's own WebGL context and 3d scene. Handling of mouse is performed automatically.

Constructor

Canvas should be passed to 3d window creation function. In order to support transparency properly, canvas may need special style in css.

All parameters are in object:

canvas HTML canvas element,
color Background color packed in integer. For instance, 0xffffff is white background
callback Callback function. Same to addRefTarget.

If you want to load 3d file, add parameters described in .load method. 

var info={};
info.canvas=document.getElementById("ivwindow3d");
info.color=0xe5e5e5;
var v=new iv.window(info);

 

var view3d=new iv.window({canvas:document.getElementById("ivwindow3d"),file:"tree.iv3d",color:0x777777,path:"1/"});

 

Properties

gl [readonly] WebGL context
cfgOrbitMode 0 or 1. Defines how rotation around vertical axis is performed. We may rotate around screen space vertical axis or around world space axis. World axis is default choice.
cfgAutoSpin &1 - auto rotation on mouse up, &2 - auto rotation after short delay
cfgSpinSpeed Speed of model spinning after releasing mouse button. Value is related to default speed. 1 is default value, decrease this value to decrease speed.
cfgBkColor Background color. 0xffffff - white, 0x0 - black, etc.
cfgSelOnDown true - Select object on mouse down. false - select object on mouse up if there were no mouse movements. false is default.
clrSelection

Array of selection color and values. All items in array are from 0 to 1.

0,1,2 Highlight RGB color components for selected object.
3 Mixing factor of highlight color and normal colors.
4 Opacity of select object. 1 - is default.
5 Opacity of non selected objects 1 - is default.

 

cfgButtons

array or 3 numbers. Each item defines action for left, right and middle mouse button respectively:

0 no action
1 orbit
2 zoom via camera dolly
3 zoom via camera FOV
4 camera pan
0x100, 0x200, 0x400 rotate predefined object in x,y,z axis.

These buttons may be configured right after 3d window creation.

cfgMinDistance Minimum distance from camera to scene center. Used by zoom mode.
cfgMaxDistance Maximum distance from camera to scene center. Used by zoom mode.
cfgMinVAngle Minimum vertical camera angle in degrees. Shouldn't be less than -90. Useb by orbit mode, undefined is default. Limits work correctly only when .cfgOrbitMode is set to 1.
cfgMaxVAngle Maximum vertical camera angle in degrees. Shouldn't be more than 90.
cfgShadows true if shadows are enabled.

Camera limits:

view3d=new iv.window(info);
view3d.cfgMaxVAngle=80;view3d.cfgMinVAngle=-80;
view3d.cfgMinDistance=1;view3d.cfgMaxDistance=10;

Load 3d Space

URL to 3d data may be passed during window creation or later. 3D data may be loaded multiple times. Old space will be removed on receiving response from server. New file may be merged with existing objects.

.load(file, {})

file short file name. Fully qualified url should be divided into path and short file name.

Optional parameters:

path Path to folder with objects and textures
merge boolean. Set to true if you want to merge with current scene.
parent Parent node. Used for merging.
zoom  boolean. Perform zoom after loading. true is default for load and false for merge.
callback function, called after loading.
type Type of file. Usually just an extension. Use this parameter, if extension is different from standard ones or if you should add extra parameters to url after file name.

 

Notifications

.addRefTarget(f)

Method registers the specified function as notification callback.

f notification function

Function received one event object as argument with following properties:

code type of notification. For list of possible values see table below
wnd 3d window - source of notifications
doDef [Optional], if exist you set to false in order to stop default processing.
... There are more, notication specific values.

If the method succeeds, the return value is true.

Following notifications are available:

"selection" Selection was changed. Additional event properties:
  • event.old - array of old selected nodes.
  • event.current - array of currently selected nodes.
  • event.node - node currently selected by mouse.
"dataReady"

File was loaded. For JSON file format, this means availability of scene tree file only. Meshes may be available later. Additional properties:

  • event.space - 3d space.
  • event.file - url of loaded file.
"merged"

File was loaded and merged. Additional properties:

  • event.space - 3d space.
  • event.file - url of loaded file.
  • event.group - group with all nodes of this file.
  • event.iid - optional iid, passed to .load method.
"progress"

called during load of iv3d file. Additional properties:

  • event.loaded - number of loaded bytes.
  • event.total - totla file size.
"mousedown"

This notification is part of extended API. Additional properties:

  • event.node - node under mouse pointer.
  • event.x - x mouse coordinate.
  • event.y - y mouse coordinate.
  • event.hitInfo - information about hit test result.

set event.doDef to false in order to prevent default processing.

"mouseup" This notification is part of extended API. Additional properties:
  • event.x - x mouse coordinate.
  • event.y - y mouse coordinate.

set event.doDef to false in order to prevent default processing. 

"mousehover" Mouse hover notification. Additional properties:
  • event.x - x mouse coordinate.
  • event.y - y mouse coordinate.

There is no information about node below mouse pointer. Use hit test functionality in order to obtain node.

"camera" Notification for pan, orbit or zoom operations.
Common additional properties:
  • event.type - on of following "pan", "orbit", "dolly", "fov"
  • event.dX - x mouse delta.
  • event.dY - y mouse delta.

set event.doDef in order to prevent changes in view.

pan, orbit

You may change dX, dY in order to change behaviour of pan function.

dolly

event.scale - for orthogonal cameras. You may modify this value in order to limit min/max scale factor.

event.len - for persepctive cameras. You may modify this value in order to limit distance from camera.

fov

For perspective cameras only.

event.fov - for perspective cameras. Modify this value in order to limit min/max field of view. 

"error"

WebGL error.

event.type - type of error. Currentl valuaes are: "hardware", "compile". For compile error, compilation error log and shader text is provided.

These errors happened only in case of out of memory/vide memory problems.

Sample

view.addRefTarget(function(event)
{
  switch(event.code)
   {
    case "dataReady":
     {
     ivDataReady(event.wnd.space);
     if(event.wnd.space.anim){
        var btn=document.getElementById("ivanimate");
        if(btn)btn.style.visibility="visible";
       }
     }break;
    case "selection":ivOnSelChanged(event.node);break;
   }
});
	  

 

Viewpoint/Camera

.getView(view)

Method retrieves current viewpoint.

view optional previous view. If this parameter is provided, it will be updated with current view information.

Method returns current camera position in the following format:

from Camera location in world coordiante system
to Camera target point in world coordiante system
up Camera up point in world  coordiante system
fov Field of view - perspective camera
scale sclae - orthogonal camera

 This object may be passed to .setView method, may be converted to string and stored in database.

.setView(view,flags)

Method changes current viewpoint.

view object with following members {from:[],to:[],up:[],fov:number,scale:number}. Where from, to and up are point in world coordinate space. fov or scale are optional. scale is for orthogonal camera, fov - perspective.
view.anim - optional object with animation information. All members are optional:
id id of animation
start, end custom start and end time of animation. If not specified, data from animation will be taken. If reversed - animation will be played in opposite direction.
delayStart start delay in seconds
delayEnd end delay in seconds
 
flags

[optional] may be undefined or bit combinations of:

iv.VIEW_UNDO Create undo record in order to restore view.
iv.VIEW_TRANSITION Executes transition from current view to new one. Doesn't work for switching between ortho and perspective views.
iv.VIEW_INVALIDATE Invalidate screen.
iv.VIEW_ANIM_SET Select animation specified in view.
iv.VIEW_ANIM_PLAY Play animation.
iv.VIEW_VISIBLE Used by .zoomToFit method. When this flags is hidden objects will be excluded.

Default is 0.

.setStdView(viewId,flags)

Method sets standard view, where standard view is defined by string: “left”, “right”, ”top”, ”bottom”, “front”, “back”.

viewId One of six standard views: “left”, “right”, ”top”, ”bottom”, “front”, “back”.
flags For list of flags see .setView method.

.getStdView(viewId)

Method returns view definition for for standard view,

viewId One of six standard views: “left”, “right”, ”top”, ”bottom”, “front”, “back”.

Sample

<span onclick="view3d.zoomToFit(view3d.getStdView('front'),iv.VIEW_TRANSITION);">[VIEW All]</span>	  

.setModelView(id,flags)

Method sets predefined model view.

id index of model view. Model views are favorites in FinalMesh UI.
flags For list of flags see .setView method.

.setOrtho(ortho)

Method switches between orthogonal or perspective view mode.

ortho boolean. true for orthogonal views, false for perpsective

This method calculates scale or fov based on current view. 

.isOrtho()

Method returns true if current view is in orthogonal mode.  

.zoomToFit(view,flags)

Method fits all objects (or visible objects) into 3d window.

view object with required camera position. If null or undefined, current view will be used.
flags For list of flags see .setView method. Use iv.VIEW_VISIBLE if you want to zoom to visible objects only.

.zoomToFitBox(view,box,flags) 

Method fits area defined by bounding box into 3d window.

view object with required camera position. If null or undefined, current view will be used.
box Bounding box of area you want to zoom.
flags For list of flags see .setView method.

.getViewToBox(view,box)

Method computes iv.viewInfo object required to fit box.

view Previous view (iv.viewInfo) which should be modified in order to fir required area. May be null, in this case current view will be used.
box Bounding box of area you want to zoom. You may use node.getBoundingBox method to compute box of required tree.

Method returns iv.viewInfo object. You may use returned view with .setView method.

.setDefView(flags)

Sets default view, this is the view embedded into 3d file.

flags For list of flags see .setView method.

.invalidate(flags)

Method marks viewport as invalid and scheduled update for the next frame. This is not an immediate update. Real rendering will be executed on the next drawing cycle.

flags

[optional] may be undefined or bit combinations of:

iv.INV_VERSION Update camera, increment current camera version. Version may be used by billboards in order to update position only when required.
iv.INV_STRUCTURE Scene structure was changed. For instance, object was moved or switched on/off. Used to update shadow maps, since such changes may affect shadows.
iv.INV_MTLS Flush shaders in materials. Same as view.space.invalidateMaterials()

Default is 0.

Resizing

.setViewSize(width,height,bufWidth,bufHeight)

Method resizes canvas and associated WebGL frame buffer.

width width of canvas
height height of canvas
bufWidth  Width of video buffer. [Optional]
bufHeight Height of video buffer. [Optional]

After changes in HTML layout or when you want to change size of 3d window, you should call view.setViewSize(width,height). This function changes size of video buffer via changing width/height properties of canvas element. Size of canvas is changes via style attribute.

If bufWidth or bufHeight are not specified width or height will be used.

.updateViewSize()

Method updates internal variables after changing canvas size. This function may be used if prefer to change size of canvas on your own.

 

Animation

.playAnimation({})

Method plays whole scene animation. All parameters are optional.

{from:, to:, type: ,speed:, count: }

from start time in seconds. If not set, global start time will be used.
to end of animation in seconds. If not set, global end time will be used.
mode 0 or 1. 0 default animation. 1 – ping pong animation. Used only if count is >1
count number of cycles to play. Use negative value in order to loop animation forether.
speed speed of playback. 1 is default.

Method returns animation controller. You may use it in order to stop animation.

function ivPlayAnimation()
	  {
	  view3d.playAnimation({speed:0.1,type:1,count:2,from:1,to:0});
	  }

In order to reverse animation, swap from and to. In order to stop endless animation use .removeAnimation method.

If you want to animate only sub-tree of whole scene, use the following code:

var r=new iv.anim.node(node,info);
view.addAnimation(r);
	  

where node – node to animate, info – parametes, described few lines above.

.removeAnimation(a)

Method removes already runned animation.

a animation to remove

If the method succeeds, the return value is true.

.addAnimation(a)

Method inserts animation object into list of active animations.

a new animation

Animation object should have .animate method.

.removeAnimationType(type,finish)

Method removes animation by type.

type type of animation to remove.
finish If true, plays animtion to end. May be used by animations with valid duration property.

If the method succeeds and animtion was removed, the return value is true.

.getAnimation(type)

Method retrives active animation of specific type.

type type of animation to search.

If animation was not found, the return value is null.

Hit testing

.hitTest(x,y)

Method performs hit testing and retrieves list of nodes  below mouse pointer defined by x, y coordinates. This method is part of extended API.

x x coordinate
y x coordinate

If at least one node was detected, object with following variables will be returned returned.

nodes array of nodes.
node nearest node.
length distance to nearest node.
pnt world space hit point

Additional information about hit point, like normal, triangle are available in nodes array. Closest item is in first item.

Each item in nodes array:

normal world space normal at hit point.
top true for topmost nodes
node iv.node
length distance from camera to hit point
pnt world space hit point
lpnt local hit point, object space coordinate.
triangle triangle index

.getRay(x,y)

Method computes ray for current view and specified mouse coordinates.

x x coordinate
y x coordinate
ray optional old ray. Will be updated in case if specified.

Method returns ray as array of 6 numbers. First 3 numebrs is origin of ray, next 3 numbers - normalized direction.

 

.setLights(light)

Method computes ray for current view and specified mouse coordinates.

lights

array of lights.

null Use null in order to restore lights saved to 3d file
[] no lights
[{light0},{light1}, etc] new custom lights.

Each item is JS object, all parameters are optional.

type
0  infinite direction light,
1  point light
2  spot light
org Light origin in world coordinate system. point or spot light.
dir Normalized light direction. Infinite of spot light.
color Light color
inner Inner angle of spot cone in raidans.
outer Outer angle of spot cone in raidans.

 

var l=[
  {"color":[0.5,0.5,0.5],"dir":[-0.57735,-0.57735,-0.57735],"type":1},
  {"color":[0.8,0.8,0.9],"dir":[0.57735,0.57735,-0.57735],"type":1},
  {"color":[0.9,0.9,0.9],"dir":[-0.242536,0,0.970143],"type":1}];
view3d.setLights(l);
	  

Shadows are not supported for standard lights, please create nodes with light object.

 

.setMaterials(b)

Method sets default material on/off.

b

true for default materials and false for materials from file.

.getMaterials()

Method returns true if default material is used.

.setDoubleSided(b)

Method sets double sided rendering on/off.

b

true for double sided materials.

.getDoubleSided()

Method returns true if double sided rendering is on.

.setShadows(b)

Method sets real-time shadows on/off.

b

true for shadows.

.getShadows()

Method returns true if real-times shadows are enabled. 

.searchNode(name)

Method searches node by name in whole scene tree.

name Name of the node.

null is returned if such node was not found. If you need to search for node in subtree, use iv.node.search method.

.setRMode(name)

Method sets new render mode.

name Short name of render mode. Available render modes are:
solid Smooth shaded render mode
wire Solid color wireframes.
wireshaded Smooth shaded wireframes
solidwire Smooth shaded surface + solid color wireframes
hiddenwire Solid color visibled wireframes only.
illustration Illustration render mode. Only contour and sharp edges.
outline Only contour and sharp edges with smooth shaded sufrace.

false is returned if such mode is not found. Available render modes are: