GLModel

Source: GLModel.ts

GLModel represents a group of related atoms, their bonds, styles, and optional
trajectory frames. Obtain models from GLViewer.addModel or GLViewer.getModel.
Bonds connect atoms within one model. Style and atom changes take effect on the
next viewer.render(); model mutators generally do not return the model for chaining.


Constructor

new GLModel(): GLModel

Instance Methods

addAtomSpecs(customAtomSpecs: Array)

deprecated
GLModel.ts

add atomSpecs to validAtomSelectionSpecs

This method is deprecated and should not be used.

Parameters

  • customAtomSpecs (Array) — array of strings that can be used as atomSelectionSpecs
    this is to prevent the 'Unknown Selector x' message on the console for the strings passed.
    These messages are no longer generated as, in theory, typescript will catch problems at compile time.
    In practice, there may still be issues at run-time but we don't check for them...What we should do is use something like https://github.com/woutervh-/typescript-is to do runtime
    type checking, but it currently doesn't work with our types...

addAtoms(newatoms: Array.<AtomSpec>)

Add atoms to the current frame, remapping bonds among the supplied atoms.
Missing input indices and serials are filled in on newatoms. Atom records are
shallow-copied; existing nested properties and styles may remain shared. Bonds
to atoms outside newatoms are discarded; no bonds are inferred automatically.

Parameters

Example

CODE
var atoms = [{elem: 'C', x: 0, y: 0, z: 0, bonds: [1,2], bondOrder: [1,2]}, {elem: 'O', x: -1.5, y: 0, z: 0, bonds: [0]},{elem: 'O', x: 1.5, y: 0, z: 0, bonds: [0], bondOrder: [2]}];

        viewer.setBackgroundColor(0xffffffff);
        var m = viewer.addModel();
        m.addAtoms(atoms);
        m.setStyle({},{stick:{}});
        viewer.zoomTo();
        viewer.render();

addFrame(atoms: Array.<AtomSpec>)

Append one atom array by reference as a frame. This does not switch frames or
infer bonds; provide initialized atoms and call setFrame to select it.

Parameters

  • atoms (Array.<AtomSpec>) — atoms comprising the new frame

addMolData( data: string | ArrayBuffer, format: string, options: ParserOptionsSpec, )

Load molecular data into this model. The first load initializes frames and
selects the first nonempty frame. Later loads append atoms to the current frame
unless options.frames is true. Use options.multimodel to read multiple structures.

Parameters

  • data (string | ArrayBuffer) — atom structure file input data string, for gzipped input use ArrayBuffer
  • format (string) — input file string format (e.g 'pdb', 'sdf', 'sdf.gz', etc.)
  • options (ParserOptionsSpec) — format dependent options. Attributes depend on the input format

addPropertyLabels( prop: String, sel: AtomSelectionSpec, style: LabelSpec, )

Create labels for atoms that show the value of the passed property.

Parameters

addResLabels( sel: AtomSelectionSpec, style: LabelSpec, byframe?: boolean, ): Array.<Label>

Create labels for residues of selected atoms.
Creates one label at the arithmetic mean of the selected atom coordinates
for each group with the same chain, resn, and resi.

Parameters

  • sel (AtomSelectionSpec)
  • style (LabelSpec)
  • byframe (boolean, optional, default: false) — If true, create labels for each already loaded frame.

Returns

  • Array.<Label> — The labels created.

assignBonds()

Assign bonds based on atomic coordinates.
This currently uses a primitive distance-based algorithm that does not
consider valence constraints and will only create single bonds.

atomIsSelected(atom: AtomSpec, sel: AtomSelectionSpec): boolean

given a selection specification, return true if atom is selected.
Does not support context-aware selectors like expand/within/byres.

Parameters

Returns

  • boolean

calculateDashes()

Calculate dashed line segments along a bond, with proper centering and two-color support.

The dashes are centered along the bond using the pattern:
[halfGap]-[dash]-[gap]-[dash]-[gap]-...-[dash]-[halfGap]

For two-color bonds, the first half of dashes use colors[0], second half use colors[1].

createMolObj()

param {AtomSpec[]} atoms

drawAtomClickSphere()

Register atom shaped click handlers

drawAtomCross(atom: AtomSpec, geos: Record.<number, Geometry>)

Parameters

  • atom (AtomSpec)
  • geos (Record.<number, Geometry>)

drawAtomSphere(atom: AtomSpec, geo: Geometry)

Parameters

drawBondLines( atom: AtomSpec, atoms: Array.<AtomSpec>, geos: Record.<number, Geometry>, )

Parameters

enableContextMenu( sel: AtomSelectionSpec, contextMenuEnabled: boolean, )

enable context menu of selected atoms

Parameters

  • sel (AtomSelectionSpec) — atom selection to apply context-menu settings to
  • contextMenuEnabled (boolean) — whether contextMenu-handling is enabled for the selection

expandAtomList()

returns a list of atoms in the expanded bounding box, but not in the current one

Bounding box:

[ [ xmin, ymin, zmin ],
[ xmax, ymax, zmax ],
[ xctr, yctr, zctr ] ]

exportVRML(): string

return a VRML string representation of the model. Does not include VRML header information

Returns

  • string — VRML text without a header.

getCrystData()

Return the crystallographic metadata object, or null when none is available.
A fractional-to-Cartesian matrix is computed from cell parameters if missing.
The returned object is a live reference, not a copy.

getID(): number

Returns model id number

Returns

  • number — Model ID

getInternalState()

Return atom, frame and metadata references suitable for setInternalState,
together with model visibility and symmetry settings. This is not a deep
copy: editing the returned arrays also edits the model. Use the viewer's
getInternalState for a detached, JSON-safe scene snapshot.

getNumFrames(): number

Returns the number of frames in the model.

Returns

  • number

getRadiusFromStyle(atom: AtomSpec, style: atomstyle): number

Parameters

Returns

  • number

getSymmetries(): Array.<Matrix4>

Returns list of rotational/translational matrices if there is BIOMT data
Otherwise returns a list containing the identity matrix

Returns

getViewer(): GLViewer | undefined

Return the viewer associated with this model, if one was provided.

Returns

globj(group: Object3D, options: Object)

Manage this model's renderable object in the supplied group, rebuilding it when necessary.

Parameters

  • group (Object3D)
  • options (Object)

hide()

Don't show this model in future renderings. Keep all styles and state
so it can be efficiencly shown again.

  • @see GLModel#show

Example

CODE
$3Dmol.download("pdb:3ucr",viewer,{},function(){
        viewer.setStyle({},{stick:{}});
        viewer.getModel().hide();
        viewer.render();
        });

isHidden(): boolean

Whether this model is hidden from the viewer.

Returns

  • boolean

removeAtoms(badatoms: Array.<AtomSpec>)

Remove specified atoms from the current frame and update bond indices.
Distinct local frames remain independent, as with addAtoms(). For remote
trajectories, surviving atoms retain their original coordinate slots.

Parameters

  • badatoms (Array.<AtomSpec>) — list of atoms

removegl(group: Object3D)

Remove any renderable mol object from scene

Parameters

  • group (Object3D)

resetIntersectionShapes()

Clear picking geometry before rebuilding a frame.

selectedAtoms( sel: AtomSelectionSpec, from?: Array.<AtomSpec>, ): Array.<AtomSpec>

Return atoms matching a selection in this model.

Parameters

Returns

  • Array.<AtomSpec> — References to the selected atoms.

Example

CODE
$3Dmol.download("pdb:4wwy",viewer,{},function(){
              var atoms = viewer.selectedAtoms({chain:'A'});
              for(var i = 0, n = atoms.length; i < n; i++) {
                 atoms[i].b = 0.0;
              }
              viewer.setStyle({cartoon:{colorscheme:{prop:'b',gradient: 'roygb',min:0,max:30}}});
              viewer.render();
          });

setClickable( sel: AtomSelectionSpec, clickable: boolean, callback: function, )

Set clickable and callback of selected atoms

Parameters

  • sel (AtomSelectionSpec) — atom selection to apply clickable settings to
  • clickable (boolean) — whether click-handling is enabled for the selection
  • callback (function) — Handler with the arguments documented by AtomSpec.callback.

setColorByElement(sel: AtomSelectionSpec, colors: object)

given a mapping from element to color, set atom colors

Parameters

setColorByFunction(sel: AtomSelectionSpec, colorfun: function)

deprecated
GLModel.ts

use setStyle and colorfunc attribute

Parameters

  • sel (AtomSelectionSpec) — selection object
  • colorfun (function) — function receiving an atom and returning its color

Example

CODE
$3Dmol.download("pdb:4UAA",viewer,{},function(){
              viewer.setBackgroundColor(0xffffffff);
              var colorAsSnake = function(atom) {
                return atom.resi % 2 ? 'white': 'green'
              };

              viewer.setStyle( {}, { cartoon: {colorfunc: colorAsSnake }});

              viewer.render();
          });

setColorByProperty( sel: AtomSelectionSpec, prop: string, scheme: Gradient | string, range?: Array.<number>, )

Set base atom colors from a numeric property in the current frame.
Explicit style colors, colorschemes, or color functions can override these colors.
Missing properties leave the atom color unchanged. Call viewer.render() after updating.

Parameters

  • sel (AtomSelectionSpec) — Atoms to color.
  • prop (string) — Property name; atom.properties is checked before top-level fields.
  • scheme (Gradient | string) — Gradient object or name from builtinGradients.
  • range (Array.<number>, optional) — Minimum and maximum. Defaults to the gradient range,
    then the range of the selected atoms; supply one shared range to compare models.

Example

CODE
var model = viewer.addModel();
model.addAtoms([
  {elem: "C", x: -3, y: 0, z: 0, properties: {score: -1}},
  {elem: "C", x: 0, y: 0, z: 0, properties: {score: 0}},
  {elem: "C", x: 3, y: 0, z: 0, properties: {score: 1}}
]);
model.setStyle({}, {sphere: {radius: 1}});
model.setColorByProperty({}, "score", "rwb", [-1, 1]);
viewer.zoomTo();
viewer.render();

setCoordinates( str: string | ArrayBuffer | Array.<Array.<Array.<number>>>, format: string, ): Array.<Array.<AtomSpec>>

Replace trajectory frames with coordinates for the existing atoms and select
the first frame. Load topology first: every frame must have the same atom count
and order as the current model. Atom identity, bonds, and styles are reused;
this method does not infer a new topology from the coordinates.
Invalid or unsupported input returns an empty array without changing the existing atoms or frames.
Parsing and validation failures log a warning.

Parameters

  • str (string | ArrayBuffer | Array.<Array.<Array.<number>>>) — trajectory file data or coordinates with shape frames x atoms x 3
  • format (string) — contains the format of the file (mdcrd, inpcrd, pdb, netcdf, or array). Arrays should be TxNx3 where T is the number of timesteps and N the number of atoms.

Returns

  • Array.<Array.<AtomSpec>> — Loaded frames, or an empty array when no coordinates were loaded.

Example

CODE
let m = viewer.addModel()  //create an empty model
         m.addAtoms([{x:0,y:0,z:0,elem:'C'},{x:2,y:0,z:0,elem:'C'}]) //provide a list of dictionaries representing the atoms
         viewer.setStyle({'sphere':{}})
         m.setCoordinates([[[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]], [[0.0, 0.0, 0.0], [2.8888888359069824, 0.0, 0.0]], [[0.0, 0.0, 0.0], [3.777777671813965, 0.0, 0.0]], [[0.0, 0.0, 0.0], [4.666666507720947, 0.0, 0.0]], [[0.0, 0.0, 0.0], [5.55555534362793, 0.0, 0.0]], [[0.0, 0.0, 0.0], [6.44444465637207, 0.0, 0.0]], [[0.0, 0.0, 0.0], [7.333333492279053, 0.0, 0.0]], [[0.0, 0.0, 0.0], [8.222222328186035, 0.0, 0.0]], [[0.0, 0.0, 0.0], [9.11111068725586, 0.0, 0.0]], [[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]]],'array');
         viewer.animate({loop: "forward",reps: 1});
         viewer.zoomTo();
         viewer.zoom(0.5);
         viewer.render();

setCoordinatesFromURL(url: string, path: string): Promise

Set coordinates from remote trajectory file.
Superseded responses are ignored and their promises resolve.

Parameters

  • url (string) — contains the url where mdsrv has been hosted
  • path (string) — contains the path of the file (/filename)

Returns

  • Promise

setCrystData( a?: number, b?: number, c?: number, alpha: number, beta: number, gamma: number, )

Set crystallographic information using three angles and three lengths

Parameters

  • a (number, optional, default: 1) — Unit cell side length in angstroms.
  • b (number, optional, default: 1) — Unit cell side length in angstroms.
  • c (number, optional, default: 1) — Unit cell side length in angstroms.
  • alpha (number) — unit cell angle in degrees (default 90)
  • beta (number) — unit cell angle in degrees (default 90)
  • gamma (number) — unit cell angle in degrees (default 90)

setCrystMatrix(matrix: Matrix3)

Set the crystallographic matrix to the given matrix.

This function removes a, b, c, alpha, beta, gamma from
the crystal data.

Parameters

  • matrix (Matrix3) — unit cell matrix

setFrame(framenum: number, options: Object): Promise

Sets model's atomlist to the specified frame. Indices wrap modulo the
frame count, so -1 selects the last frame and -2 the second to last.
Fractional indices truncate toward zero; non-finite values use frame zero.
Only the latest requested remote frame is applied. Superseded responses are
ignored and their promises resolve, including when those downloads fail.

Parameters

  • framenum (number) — model's atoms are set to this index in frames list
  • options (Object) — {fast: true} replays the frame's coordinates into the existing
    geometry via syncAtomPositions() instead of rebuilding it; falls back to a rebuild when
    the replay cannot apply. Off by default. Without fast, even the current frame is
    rebuilt to reflect direct atom edits and changes to external color-function state.

Returns

  • Promise

setHoverable( sel: AtomSelectionSpec, hoverable: boolean, hover_callback: function, unhover_callback: function, )

Set hoverable and callback of selected atoms

Parameters

  • sel (AtomSelectionSpec) — atom selection to apply hoverable settings to
  • hoverable (boolean) — whether hover-handling is enabled for the selection
  • hover_callback (function) — Handler with the arguments documented by AtomSpec.hover_callback.
  • unhover_callback (function) — Handler with the arguments documented by AtomSpec.unhover_callback.

setInternalState(state)

Overwrite the internal model state with the passed state.

Parameters

  • state

setStyle( sel: AtomSelectionSpec | AtomStyleSpec | string, style?: AtomStyleSpec | string, add?: boolean, )

Set the style of selected atoms. With one argument, treat it as the style
and select all atoms. By default this replaces all representations on matching
atoms; add=true merges representation properties. Applies to every loaded
frame unless sel.frame selects one. Call viewer.render() to display changes.

Parameters

  • sel (AtomSelectionSpec | AtomStyleSpec | string) — Selection, or style when used alone.
  • style (AtomStyleSpec | string, optional) — Style object or style specification string.
  • add (boolean, optional, default: false) — Merge into the current style instead of replacing it.

Example

CODE
$3Dmol.download("pdb:4UB9",viewer,{},function(){
              viewer.setBackgroundColor(0xffffffff);

              viewer.setStyle({chain:'A'},{line:{hidden:true,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.Sinebow($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'B'},{line:{colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.Sinebow($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'C'},{cross:{hidden:true,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.Sinebow($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'D'},{cross:{colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.RWB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'E'},{cross:{radius:2.0,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.RWB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'F'},{stick:{hidden:true,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.RWB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'G'},{stick:{radius:0.8,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.ROYGB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.setStyle({chain:'H'},{stick:{singleBonds:true,colorscheme:{prop:'b',gradient: new $3Dmol.Gradient.ROYGB($3Dmol.getPropertyRange(viewer.selectedAtoms(),'b'))}}});
              viewer.render();
          });

setSymmetries(list: Array.<Matrix4>)

Sets symmetries based on specified matrices in list

Parameters

show()

Unhide a hidden model

Example

CODE
$3Dmol.download("pdb:3ucr",viewer,{},function(){
        viewer.setStyle({},{stick:{}});
        viewer.getModel().hide();
        viewer.render(  )
        viewer.getModel().show()
        viewer.render();
        });

syncAtomPositions(opts?: object)

Push the atoms' current coordinates into the existing geometry without rebuilding it.

Intended for animation: mutate model.selectedAtoms() / model.atoms x/y/z however you
like (linear interpolation between two conformations, torsion-space folding, MD frames)
and then call this to update rendered positions. Atom order, bonds, styles, colors, radii
and assembly metadata must stay fixed; this method does not validate those values.
By default, setFrame and setCoordinates
invalidate geometry for rebuilding; setFrame's fast option also uses this method.
Here only position data changes, so colors, radii, per-atom alphas and face indices
are left alone and the renderer respecifies just the affected buffers.

Covers sphere imposters, solid single-bond stick imposters (including their joint caps
and color-split half-bonds) and single-bond lines. Cartoon, cross, aromatic rings, dashed
or offset bonds, instanced and tessellated geometry require regeneration. Models with
clickable, hoverable or context-menu atoms also require regeneration to refresh picking.
Viewer-managed surfaces are not updated by this method. Requires
that the model has already been rendered once, since there is otherwise no geometry to
update.

Parameters

  • opts (object, optional)

Returns

  • true if positions were written. False means nothing was touched and the caller
    should fall back to a full rebuild: either the model has not been rendered yet,
    nothing trackable is styled, picking needs rebuilding, or the geometry contains
    something the coordinate recipes cannot update completely.

syncSpherePositions(): boolean

deprecated
GLModel.ts

Renamed to syncAtomPositions() once it grew beyond spheres.

Returns

  • boolean

syncSphereRadii(scale: function)

Rescale sphere-imposter radii in place, without rebuilding geometry.

scale is called once per sphere-styled atom and returns a multiplier on the radius that
atom was built with: 0 hides it, 1 is its natural size. Intended for entrance animations
(grow atoms in) and any effect that changes size without changing what is drawn.

This works because a sphere imposter has no radius uniform and no radius buffer of its
own -- the radius IS the billboard quad's extent, stored as the four corner offsets in the
normal array. Rewriting those corners resizes the sphere, and since only normals go dirty
the renderer respecifies one buffer instead of reallocating the group.

Parameters

  • scale (function)

Returns

  • true if radii were written, false if there is nothing to update (no prior render,
    or no sphere-imposter atoms in this model).

toCDObject(includeStyles?: boolean): Object

Convert the model into an object in the format of a ChemDoodle JSON model.

Parameters

  • includeStyles (boolean, optional, default: false) — Whether to include style information.

Returns

  • Object

vibrate( numFrames: number, amplitude: number, bothWays: boolean, arrowSpec: ArrowSpec, )

If model atoms have dx, dy, dz properties (in some xyz files), vibrate generates trajectory frames from those displacements.
Model can then be animated

Parameters

  • numFrames (number) — number of frames to be created, default to 10
  • amplitude (number) — amplitude of distortion, default to 1 (full)
  • bothWays (boolean) — if true, extend both in positive and negative directions by numFrames
  • arrowSpec (ArrowSpec) — specification for drawing animated arrows. If color isn't specified, atom color (sphere, stick, line preference) is used.

Example

CODE
$3Dmol.download("pdb:4UAA",viewer,{},function(){
        viewer.setStyle({},{stick:{}});
        viewer.vibrate(10, 1);
        viewer.animate({loop: "forward",reps: 1});

        viewer.zoomTo();
              viewer.render();
          });