-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSciView.kt
More file actions
2155 lines (1933 loc) · 76.2 KB
/
SciView.kt
File metadata and controls
2155 lines (1933 loc) · 76.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2024 sciview developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package sc.iview
import bdv.BigDataViewer
import bdv.cache.CacheControl
import bdv.tools.brightness.ConverterSetup
import bdv.util.AxisOrder
import bdv.util.RandomAccessibleIntervalSource
import bdv.util.RandomAccessibleIntervalSource4D
import bdv.util.volatiles.VolatileView
import bdv.viewer.Source
import bdv.viewer.SourceAndConverter
import bvv.core.VolumeViewerOptions
import dev.dirs.ProjectDirectories
import graphics.scenery.*
import graphics.scenery.Scene.RaycastResult
import graphics.scenery.attribute.material.Material
import graphics.scenery.backends.Renderer
import graphics.scenery.backends.vulkan.VulkanRenderer
import graphics.scenery.controls.InputHandler
import graphics.scenery.controls.OpenVRHMD
import graphics.scenery.controls.TrackerInput
import graphics.scenery.primitives.*
import graphics.scenery.proteins.Protein
import graphics.scenery.proteins.RibbonDiagram
import graphics.scenery.utils.LogbackUtils
import graphics.scenery.utils.SceneryPanel
import graphics.scenery.utils.Statistics
import graphics.scenery.volumes.Colormap
import graphics.scenery.volumes.RAIVolume
import graphics.scenery.volumes.TransferFunction
import graphics.scenery.volumes.Volume
import graphics.scenery.volumes.Volume.Companion.fromXML
import graphics.scenery.volumes.Volume.Companion.setupId
import graphics.scenery.volumes.Volume.VolumeDataSource.RAISource
import io.scif.SCIFIOService
import net.imagej.Dataset
import net.imagej.ImageJService
import net.imagej.axis.CalibratedAxis
import net.imagej.axis.DefaultAxisType
import net.imagej.axis.DefaultLinearAxis
import net.imagej.interval.CalibratedRealInterval
import net.imagej.lut.LUTService
import net.imagej.mesh.Mesh
import net.imagej.mesh.io.ply.PLYMeshIO
import net.imagej.mesh.io.stl.STLMeshIO
import net.imagej.units.UnitService
import net.imglib2.*
import net.imglib2.display.ColorTable
import net.imglib2.img.Img
import net.imglib2.img.array.ArrayImgs
import net.imglib2.realtransform.AffineTransform3D
import net.imglib2.type.numeric.ARGBType
import net.imglib2.type.numeric.RealType
import net.imglib2.type.numeric.integer.UnsignedByteType
import net.imglib2.view.Views
import org.joml.Quaternionf
import org.joml.Vector2f
import org.joml.Vector3f
import org.scijava.Context
import org.scijava.`object`.ObjectService
import org.scijava.display.Display
import org.scijava.event.EventHandler
import org.scijava.event.EventService
import org.scijava.io.IOService
import org.scijava.log.LogLevel
import org.scijava.log.LogService
import org.scijava.menu.MenuService
import org.scijava.plugin.Parameter
import org.scijava.service.SciJavaService
import org.scijava.thread.ThreadService
import org.scijava.util.ColorRGB
import org.scijava.util.Colors
import sc.iview.commands.edit.InspectorInteractiveCommand
import sc.iview.event.NodeActivatedEvent
import sc.iview.event.NodeAddedEvent
import sc.iview.event.NodeChangedEvent
import sc.iview.event.NodeRemovedEvent
import sc.iview.process.MeshConverter
import sc.iview.ui.CustomPropertyUI
import sc.iview.ui.MainWindow
import sc.iview.ui.SwingMainWindow
import sc.iview.ui.TaskManager
import java.awt.event.WindowListener
import java.io.File
import java.io.IOException
import java.net.JarURLConnection
import java.net.URL
import java.nio.ByteBuffer
import java.nio.FloatBuffer
import java.nio.file.Path
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.function.Consumer
import java.util.function.Function
import java.util.function.Predicate
import java.util.stream.Collectors
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.concurrent.thread
import javax.swing.JOptionPane
import kotlin.math.cos
import kotlin.math.sin
/**
* Main SciView class.
*
* @author Kyle Harrington
*/
// we suppress unused warnings here because @Parameter-annotated fields
// get updated automatically by SciJava.
class SciView : SceneryBase, CalibratedRealInterval<CalibratedAxis> {
val sceneryPanel = arrayOf<SceneryPanel?>(null)
/*
* Return the default floor object
*//*
* Set the default floor object
*/
/**
* The floor that orients the user in the scene
*/
var floor: Node? = null
protected var vrActive = false
/**
* The primary camera/observer in the scene
*/
var camera: Camera? = null
set(value) {
field = value
setActiveObserver(field)
}
lateinit var controls: Controls
val targetArcball: AnimatedCenteringBeforeArcBallControl
get() = controls.targetArcball
val currentScene: Scene
get() = scene
/**
* Geometry/Image information of scene
*/
private lateinit var axes: Array<CalibratedAxis>
@Parameter
private lateinit var log: LogService
@Parameter
private lateinit var menus: MenuService
@Parameter
private lateinit var io: IOService
@Parameter
internal lateinit var eventService: EventService
@Parameter
private lateinit var lutService: LUTService
@Parameter
private lateinit var threadService: ThreadService
@Parameter
private lateinit var objectService: ObjectService
@Parameter
private lateinit var unitService: UnitService
private lateinit var imageToVolumeMap: HashMap<Any, Volume>
/**
* Queue keeps track of the currently running animations
*/
private var animations: Queue<Future<*>>? = null
/**
* Animation pause tracking
*/
private var animating = false
/**
* Track whether the scene changed and needs an update in the next tick
*/
public var needSceneUpdate: Boolean = false
/**
* This tracks the actively selected Node in the scene
*/
var activeNode: Node? = null
private set
/**
* The SciJava Display that contains SciView
*/
var display: Display<*>? = null
/**
* List of available LUTs for caching
*/
private var availableLUTs = LinkedHashMap<String, URL>()
/**
* Return the current SceneryJPanel. This is necessary for custom context menus
* @return panel the current SceneryJPanel
*/
var lights: ArrayList<PointLight>? = null
private set
private val notAbstractNode: Predicate<in Node> = Predicate { node: Node -> !(node is Camera || node is Light || node === floor) }
var isClosed = false
internal set
private val notAbstractBranchingFunction = Function { node: Node -> node.children.stream().filter(notAbstractNode).collect(Collectors.toList()) }
val taskManager = TaskManager()
// If true, then when a new node is added to the scene, the camera will refocus on this node by default
var centerOnNewNodes = false
// If true, then when a new node is added the thread will block until the node is added to the scene. This is required for
// centerOnNewNodes
var blockOnNewNodes = false
private var headlight: PointLight? = null
lateinit var mainWindow: MainWindow
constructor(context: Context) : super("SciView", 1280, 720, false, context) {
context.inject(this)
}
constructor(applicationName: String?, windowWidth: Int, windowHeight: Int) : super(applicationName!!, windowWidth, windowHeight, false)
/**
* Toggle video recording with scenery's video recording mechanism
* Note: this video recording may skip frames because it is asynchronous
*/
fun toggleRecordVideo() {
toggleRecordVideo("sciview_" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss")), false)
}
/**
* Toggle video recording with scenery's video recording mechanism
* Note: this video recording may skip frames because it is asynchronous
*
* @param filename destination for saving video
* @param overwrite should the file be replaced, otherwise a unique incrementing counter will be appended
*/
fun toggleRecordVideo(filename: String?, overwrite: Boolean) {
if (renderer is VulkanRenderer)
(renderer as VulkanRenderer).recordMovie(filename!!, overwrite)
else
log.info("This renderer does not support video recording.")
}
/**
* See [Controls.stashControls].
*/
fun stashControls() {
controls.stashControls()
}
/**
* See [Controls.restoreControls] and [Controls.stashControls].
*/
fun restoreControls() {
controls.restoreControls()
}
internal fun setRenderer(newRenderer: Renderer) {
renderer = newRenderer
}
/**
* Reset the scene to initial conditions
*/
fun reset() {
// Initialize the 3D axes
axes = arrayOf(
DefaultLinearAxis(DefaultAxisType("X", true), "um", 1.0),
DefaultLinearAxis(DefaultAxisType("Y", true), "um", 1.0),
DefaultLinearAxis(DefaultAxisType("Z", true), "um", 1.0)
)
// Remove everything except camera
val toRemove = getSceneNodes { n: Node? -> n !is Camera }
for (n in toRemove) {
// activePublish is true to update the inspector's tree view
// it used to be false for fear of slowdowns when resetting a large scene
deleteNode(n, true)
}
imageToVolumeMap = HashMap<Any, Volume>()
// Setup camera
if (camera == null) {
camera = DetachedHeadCamera()
(camera as DetachedHeadCamera).position = Vector3f(0.0f, 1.65f, 0.0f)
scene.addChild(camera as DetachedHeadCamera)
}
camera!!.spatial().position = Vector3f(0.0f, 1.65f, 5.0f)
camera!!.perspectiveCamera(50.0f, windowWidth, windowHeight, 0.1f, 1000.0f)
// Setup lights
val tetrahedron = arrayOfNulls<Vector3f>(4)
tetrahedron[0] = Vector3f(1.0f, 0f, -1.0f / Math.sqrt(2.0).toFloat())
tetrahedron[1] = Vector3f(-1.0f, 0f, -1.0f / Math.sqrt(2.0).toFloat())
tetrahedron[2] = Vector3f(0.0f, 1.0f, 1.0f / Math.sqrt(2.0).toFloat())
tetrahedron[3] = Vector3f(0.0f, -1.0f, 1.0f / Math.sqrt(2.0).toFloat())
lights = ArrayList()
for (i in 0..3) { // TODO allow # initial lights to be customizable?
val light = PointLight(150.0f)
light.spatial().position = tetrahedron[i]!!.mul(25.0f)
light.emissionColor = Vector3f(1.0f, 1.0f, 1.0f)
light.intensity = 1.0f
lights!!.add(light)
//camera.addChild( light );
scene.addChild(light)
}
// Make a headlight for the camera
headlight = PointLight(150.0f)
headlight!!.spatial().position = Vector3f(0f, 0f, -1f).mul(25.0f)
headlight!!.emissionColor = Vector3f(1.0f, 1.0f, 1.0f)
headlight!!.intensity = 0.5f
headlight!!.name = "headlight"
val lightSphere = Icosphere(1.0f, 2)
headlight!!.addChild(lightSphere)
lightSphere.material().diffuse = headlight!!.emissionColor
lightSphere.material().specular = headlight!!.emissionColor
lightSphere.material().ambient = headlight!!.emissionColor
lightSphere.material().wireframe = true
lightSphere.visible = false
//lights.add( light );
camera!!.nearPlaneDistance = 0.01f
camera!!.farPlaneDistance = 1000.0f
camera!!.addChild(headlight!!)
floor = InfinitePlane() //new Box( new Vector3f( 500f, 0.2f, 500f ) );
(floor as InfinitePlane).type = InfinitePlane.Type.Grid
(floor as Node).name = "Floor"
scene.addChild(floor as Node)
}
/**
* Initialization of SWING and scenery. Also triggers an initial population of lights/camera in the scene
*/
override fun init() {
val logLevel = System.getProperty("scenery.LogLevel", "info")
log.level = LogLevel.value(logLevel)
LogbackUtils.setLogLevel(null, logLevel)
System.getProperties().stringPropertyNames().forEach(Consumer { name: String ->
if (name.startsWith("scenery.LogLevel")) {
LogbackUtils.setLogLevel("", System.getProperty(name, "info"))
}
})
animations = LinkedList()
mainWindow = SwingMainWindow(this)
controls = Controls(this)
imageToVolumeMap = HashMap<Any, Volume>()
// Create a hook for running after each frame is rendered
renderer?.runAfterRendering?.add { this.updateAferRendering() }
}
/**
* A method that is run after the scene is rendered
*/
private fun updateAferRendering() {
if(needSceneUpdate) {
mainWindow.rebuildSceneTree()
if (activeNode == null){
(mainWindow as SwingMainWindow).nodePropertyEditor.updateProperties(null)
}
needSceneUpdate = false
}
}
fun toggleSidebar(): Boolean {
return mainWindow.toggleSidebar()
}
private fun initializeInterpreter() {
mainWindow.initializeInterpreter()
}
/*
* Completely close the SciView window + cleanup
*/
fun closeWindow() {
mainWindow.close()
dispose()
}
/*
* Return true if the scene has been initialized
*/
val isInitialized: Boolean
get() = sceneInitialized()
/**
* Place the scene into the center of camera view, and zoom in/out such
* that the whole scene is in the view (everything would be visible if it
* would not be potentially occluded).
*/
fun fitCameraToScene() {
centerOnNode(scene)
//TODO: smooth zoom in/out VLADO vlado Vlado
}
/**
* Place the scene into the center of camera view.
*/
fun centerOnScene() {
centerOnNode(scene)
}
/*
* Get the InputHandler that is managing mouse, input, VR controls, etc.
*/
val sceneryInputHandler: InputHandler?
get() = inputHandler
/*
* Return a bounding box around a subgraph of the scenegraph
*/
fun getSubgraphBoundingBox(n: Node): OrientedBoundingBox? {
val predicate = Function<Node, List<Node>> { node: Node -> node.children }
return getSubgraphBoundingBox(n, predicate)
}
/*
* Return a bounding box around a subgraph of the scenegraph
*/
fun getSubgraphBoundingBox(n: Node, branchFunction: Function<Node, List<Node>>): OrientedBoundingBox? {
if (n.boundingBox == null && n.children.size != 0) {
return n.getMaximumBoundingBox().asWorld()
}
val branches = branchFunction.apply(n)
if (branches.isEmpty()) {
return if (n.boundingBox == null) null else n.boundingBox!!.asWorld()
}
var bb = n.getMaximumBoundingBox()
for (c in branches) {
val cBB = getSubgraphBoundingBox(c, branchFunction)
if (cBB != null) bb = bb.expand(bb, cBB)
}
return bb
}
/**
* Place the active node into the center of camera view.
*/
fun centerOnActiveNode() {
if (activeNode == null) return
centerOnNode(activeNode)
}
/**
* Place the specified node into the center of camera view.
*/
fun centerOnNode(currentNode: Node?) {
if (currentNode == null) {
log.info("Cannot center on null node.")
return
}
//center the on the same spot as ArcBall does
centerOnPosition(currentNode.getMaximumBoundingBox().getBoundingSphere().origin)
}
/**
* Center the camera on the specified Node
*/
fun centerOnPosition(currentPos: Vector3f?) {
controls.centerOnPosition(currentPos)
}
/**
* Activate the node, and center the view on it.
* @param n
* @return the currently active node
*/
fun setActiveCenteredNode(n: Node?): Node? {
//activate...
val ret = setActiveNode(n)
//...and center it
ret?.let { centerOnNode(it) }
return ret
}
//a couple of shortcut methods to readout controls params
fun getFPSSpeedSlow(): Float {
return controls.getFPSSpeedSlow()
}
fun getFPSSpeedFast(): Float {
return controls.getFPSSpeedFast()
}
fun getFPSSpeedVeryFast(): Float {
return controls.getFPSSpeedVeryFast()
}
fun getMouseSpeed(): Float {
return controls.getMouseSpeed()
}
fun getMouseScrollSpeed(): Float {
return controls.getMouseScrollSpeed()
}
//a couple of setters with scene sensible boundary checks
fun setFPSSpeedSlow(slowSpeed: Float) {
controls.setFPSSpeedSlow(slowSpeed)
}
fun setFPSSpeedFast(fastSpeed: Float) {
controls.setFPSSpeedFast(fastSpeed)
}
fun setFPSSpeedVeryFast(veryFastSpeed: Float) {
controls.setFPSSpeedVeryFast(veryFastSpeed)
}
fun setFPSSpeed(newBaseSpeed: Float) {
controls.setFPSSpeed(newBaseSpeed)
}
fun setMouseSpeed(newSpeed: Float) {
controls.setMouseSpeed(newSpeed)
}
fun setMouseScrollSpeed(newSpeed: Float) {
controls.setMouseScrollSpeed(newSpeed)
}
fun setObjectSelectionMode() {
controls.setObjectSelectionMode()
}
/*
* Set the action used during object selection
*/
fun setObjectSelectionMode(selectAction: Function3<RaycastResult, Int, Int, Unit>?) {
controls.setObjectSelectionMode(selectAction)
}
fun showContextNodeChooser(x: Int, y: Int) {
mainWindow.showContextNodeChooser(x,y)
}
/*
* Initial configuration of the scenery InputHandler
* This is automatically called and should not be used directly
*/
override fun inputSetup() {
log.debug("Running InputSetup")
controls.inputSetup()
}
/**
* Add a box at the specified position with specified size, color, and normals on the inside/outside
* @param position position to put the box
* @param size size of the box
* @param color color of the box
* @param inside are normals inside the box?
* @return the Node corresponding to the box
*/
@JvmOverloads
fun addBox(position: Vector3f = Vector3f(0.0f, 0.0f, 0.0f), size: Vector3f = Vector3f(1.0f, 1.0f, 1.0f), color: ColorRGB = DEFAULT_COLOR,
inside: Boolean = false, block: Box.() -> Unit = {}): Box {
val box = Box(size, inside)
box.spatial().position = position
box.material {
ambient = Vector3f(1.0f, 0.0f, 0.0f)
diffuse = Utils.convertToVector3f(color)
specular = Vector3f(1.0f, 1.0f, 1.0f)
}
box.name = generateUniqueName("Box")
return addNode(box, block = block)
}
/**
* Return a Unique name (in terms of the scene) given a [candidateName].
* @param candidateName a candidate name
* @return a unique name based on [candidateName]
*/
fun generateUniqueName(candidateName: String): String {
var uniqueName = candidateName
var counter = 1
val names = allSceneNodes.map { el -> el.name }
while (names.contains(uniqueName)) {
uniqueName = "$candidateName $counter"
counter++
}
return uniqueName
}
/**
* Add a unit sphere at a given [position] with given [radius] and [color].
* @return the Node corresponding to the sphere
*/
@JvmOverloads
fun addSphere(position: Vector3f = Vector3f(0.0f, 0.0f, 0.0f), radius: Float = 1f, color: ColorRGB = DEFAULT_COLOR, block: Sphere.() -> Unit = {}): Sphere {
val sphere = Sphere(radius, 20)
sphere.spatial().position = position
sphere.material {
ambient = Vector3f(1.0f, 0.0f, 0.0f)
diffuse = Utils.convertToVector3f(color)
specular = Vector3f(1.0f, 1.0f, 1.0f)
}
sphere.name = generateUniqueName("Sphere")
return addNode(sphere, block = block)
}
/**
* Add a Cylinder at the given position with radius, height, and number of faces/segments
* @param position position of the cylinder
* @param radius radius of the cylinder
* @param height height of the cylinder
* @param num_segments number of segments to represent the cylinder
* @return the Node corresponding to the cylinder
*/
fun addCylinder(position: Vector3f, radius: Float, height: Float, color: ColorRGB = DEFAULT_COLOR, num_segments: Int, block: Cylinder.() -> Unit = {}): Cylinder {
val cyl = Cylinder(radius, height, num_segments)
cyl.spatial().position = position
cyl.material {
ambient = Vector3f(1.0f, 0.0f, 0.0f)
diffuse = Utils.convertToVector3f(color)
specular = Vector3f(1.0f, 1.0f, 1.0f)
cullingMode = Material.CullingMode.None
}
cyl.name = generateUniqueName("Cylinder")
return addNode(cyl, block = block)
}
/**
* Add a Cone at the given position with radius, height, and number of faces/segments
* @param position position to put the cone
* @param radius radius of the cone
* @param height height of the cone
* @param num_segments number of segments used to represent cone
* @return the Node corresponding to the cone
*/
fun addCone(position: Vector3f, radius: Float, height: Float, color: ColorRGB = DEFAULT_COLOR, num_segments: Int, block: Cone.() -> Unit = {}): Cone {
val cone = Cone(radius, height, num_segments, Vector3f(0.0f, 0.0f, 1.0f))
cone.spatial().position = position
cone.material {
ambient = Vector3f(1.0f, 0.0f, 0.0f)
diffuse = Utils.convertToVector3f(color)
specular = Vector3f(1.0f, 1.0f, 1.0f)
cullingMode = Material.CullingMode.None
}
cone.name = generateUniqueName("Cone")
return addNode(cone, block = block)
}
/**
* Add a line from start to stop with the given color
* @param start start position of line
* @param stop stop position of line
* @param color color of line
* @return the Node corresponding to the line
*/
@JvmOverloads
fun addLine(start: Vector3f = Vector3f(0.0f, 0.0f, 0.0f), stop: Vector3f = Vector3f(1.0f, 1.0f, 1.0f), color: ColorRGB = DEFAULT_COLOR, block: Line.() -> Unit = {}): Line {
return addLine(arrayOf(start, stop), color, 0.1, block)
}
/**
* Add a multi-segment line that goes through the supplied points with a single color and edge width
* @param points points along line including first and terminal points
* @param color color of line
* @param edgeWidth width of line segments
* @return the Node corresponding to the line
*/
@JvmOverloads
fun addLine(points: Array<Vector3f>, color: ColorRGB, edgeWidth: Double, block: Line.() -> Unit = {}): Line {
val line = Line(points.size)
for (pt in points) {
line.addPoint(pt)
}
line.edgeWidth = edgeWidth.toFloat()
line.material {
ambient = Vector3f(1.0f, 1.0f, 1.0f)
diffuse = Utils.convertToVector3f(color)
specular = Vector3f(1.0f, 1.0f, 1.0f)
}
line.spatial().position = points[0]
line.name = generateUniqueName("Line")
return addNode(line, block = block)
}
/**
* Add a PointLight source at the origin
* @return a Node corresponding to the PointLight
*/
@JvmOverloads
fun addPointLight(block: PointLight.() -> Unit = {}): PointLight {
val light = PointLight(5.0f)
light.material {
ambient = Vector3f(1.0f, 0.0f, 0.0f)
diffuse = Vector3f(0.0f, 1.0f, 0.0f)
specular = Vector3f(1.0f, 1.0f, 1.0f)
}
light.spatial().position = Vector3f(0.0f, 0.0f, 0.0f)
lights!!.add(light)
light.name = generateUniqueName("Point Light")
return addNode(light, block = block)
}
/**
* Position all lights that were initialized by default around the scene in a circle at Y=0
*/
fun surroundLighting() {
val bb = getSubgraphBoundingBox(scene, notAbstractBranchingFunction)
val (c, r) = bb!!.getBoundingSphere()
// Choose a good y-position, then place lights around the cross-section through this plane
val y = 0f
for (k in lights!!.indices) {
val light = lights!![k]
val x = (c.x() + r * cos(if (k == 0) 0.0 else Math.PI * 2 * (k.toFloat() / lights!!.size.toFloat()))).toFloat()
val z = (c.y() + r * sin(if (k == 0) 0.0 else Math.PI * 2 * (k.toFloat() / lights!!.size.toFloat()))).toFloat()
light.lightRadius = 2 * r
light.spatial().position = Vector3f(x, y, z)
}
}
@Throws(IOException::class)
fun openDirTiff(source: Path, onlyFirst: Int? = null)
{
val v = Volume.fromPath(source, hub, onlyFirst)
v.name = "volume"
v.spatial().position = Vector3f(-3.0f, 10.0f, 0.0f)
v.colormap = Colormap.get("jet")
v.spatial().scale = Vector3f(15.0f, 15.0f,45.0f)
v.transferFunction = TransferFunction.ramp(0.05f, 0.8f)
v.metadata["animating"] = true
v.converterSetups.firstOrNull()?.setDisplayRange(0.0, 1500.0)
v.visible = true
v.spatial().wantsComposeModel = true
v.spatial().updateWorld(true)
addNode(v)
}
/**
* Open a file specified by the source path. The file can be anything that SciView knows about: mesh, volume, point cloud
* @param source string of a data source
* @throws IOException
*/
@Suppress("UNCHECKED_CAST")
@Throws(IOException::class)
fun open(source: String) {
val name = source.split("/").last()//
//
// NB: For now, we assume all elements will be RealLocalizable.
// Highly likely to be the case, barring antagonistic importers.
// is RandomAccessibleInterval<*> -> {
// val t = data.randomAccess().get()
// addVolume(data, source, floatArrayOf(1.0f, 1.0f, 1.0f))
// }
when {
source.endsWith(".xml", ignoreCase = true) -> {
val openedNode = fromXML(source, hub, VolumeViewerOptions())
openedNode.name = generateUniqueName(name)
addNode(openedNode)
return
}
source.endsWith(".pdb", ignoreCase = true) -> {
val protein = Protein.fromFile(source)
val ribbon = RibbonDiagram(protein)
ribbon.spatial().position = Vector3f(0f, 0f, 0f)
ribbon.name = generateUniqueName(name)
addNode(ribbon)
return
}
source.endsWith(".stl", ignoreCase = true) -> {
val stlReader = STLMeshIO()
addMesh(stlReader.open(source), name=name)
return
}
source.endsWith(".ply", ignoreCase = true) -> {
val plyReader = PLYMeshIO()
addMesh(plyReader.open(source), name=name)
return
}
else -> {
val data = io.open(source)
when(data) {
is Mesh -> addMesh(data, name = name)
is PointCloud -> addPointCloud(data, name)
is graphics.scenery.Mesh -> addMesh(data, name = name)
is Dataset -> addVolume(data)
is List<*> -> {
require(data.isNotEmpty()) { "Data source '$source' appears empty." }
val element = data[0]
if(element is RealLocalizable) {
// NB: For now, we assume all elements will be RealLocalizable.
// Highly likely to be the case, barring antagonistic importers.
val points = data as List<RealLocalizable>
addPointCloud(points, name)
} else {
val type = if(element == null) "<null>" else element.javaClass.name
throw IllegalArgumentException(
"Data source '" + source + //
"' contains elements of unknown type '" + type + "'"
)
}
}
else -> {
val type = if(data == null) "<null>" else data.javaClass.name
throw IllegalArgumentException(
"Data source '" + source + //
"' contains data of unknown type '" + type + "'"
)
}
}
}
}
}
/**
* Add the given points to the scene as a PointCloud with a given name
* @param points points to use in a PointCloud
* @param name name of the PointCloud
* @return
*/
@JvmOverloads
fun addPointCloud(points: Collection<RealLocalizable>,
name: String? = "PointCloud",
pointSize : Float = 1.0f,
block: PointCloud.() -> Unit = {}): PointCloud {
val flatVerts = FloatArray(points.size * 3)
var k = 0
for (point in points) {
flatVerts[k * 3] = point.getFloatPosition(0)
flatVerts[k * 3 + 1] = point.getFloatPosition(1)
flatVerts[k * 3 + 2] = point.getFloatPosition(2)
k++
}
val pointCloud = PointCloud(pointSize, name!!)
val vBuffer: FloatBuffer = BufferUtils.allocateFloat(flatVerts.size * 4)
val nBuffer: FloatBuffer = BufferUtils.allocateFloat(0)
vBuffer.put(flatVerts)
vBuffer.flip()
pointCloud.geometry().vertices = vBuffer
pointCloud.geometry().normals = nBuffer
pointCloud.geometry().indices = BufferUtils.allocateInt(0)
pointCloud.spatial().position = Vector3f(0f, 0f, 0f)
pointCloud.setupPointCloud()
return addNode(pointCloud, block = block)
}
/**
* Add a PointCloud to the scene
* @param pointCloud existing PointCloud to add to scene
* @return a Node corresponding to the PointCloud
*/
@JvmOverloads
fun addPointCloud(pointCloud: PointCloud,
name: String = "Point Cloud",
block: PointCloud.() -> Unit = {}): PointCloud {
pointCloud.setupPointCloud()
pointCloud.spatial().position = Vector3f(0f, 0f, 0f)
pointCloud.name = generateUniqueName(name)
return addNode(pointCloud, block = block)
}
/**
* Add Node n to the scene and set it as the active node/publish it to the event service if activePublish is true.
* @param n node to add to scene
* @param activePublish flag to specify whether the node becomes active *and* is published in the inspector/services
* @param block an optional code that will be executed as a part of adding the node
* @param parent optional name of the parent node, default is the scene root
* @return a Node corresponding to the Node
*/
@JvmOverloads
fun <N: Node?> addNode(n: N, activePublish: Boolean = true, block: N.() -> Unit = {}, parent: Node = scene): N {
n?.let {
it.block()
// Ensure name is unique
if(n.name.isEmpty()) {
n.name = generateUniqueName(n.name)
}
parent.addChild(it)
objectService.addObject(n)
if (blockOnNewNodes) {
Utils.blockWhile({ this.find(n.name) == null }, 20)
//System.out.println("find(name) " + find(n.getName()) );
}
if (activePublish) {
eventService.publish(NodeAddedEvent(n))
setActiveNode(n)
// Set new node as centered
if (centerOnNewNodes) {
centerOnNode(n)
}
}
}
return n
}
/**
* Add Node n to the scene and set it as the active node/publish it to the event service if activePublish is true.
* This is technically only a shortcut method (to the same named method) that has left out the 'block' parameter.
* @param n node to add to scene
* @param activePublish flag to specify whether the node becomes active *and* is published in the inspector/services
* @param parent name of the parent node
* @return a Node corresponding to the Node
*/
@JvmOverloads
fun <N: Node?> addNode(n: N, activePublish: Boolean = true, parent: Node): N {
return addNode(n, activePublish, {}, parent)
}
/**
* Make a node known to the services.
* Used for nodes that are not created/added by a SciView controlled process e.g. [BoundingGrid].
*
* @param n node to add to publish
*/
fun <N: Node> publishNode(n: N): N {
n.let {
objectService.addObject(n)
eventService.publish(NodeAddedEvent(n))
(mainWindow as SwingMainWindow).nodePropertyEditor.updateProperties(n, rebuild = true)
}
return n
}
/**
* Add a scenery Mesh to the scene
* @param scMesh scenery mesh to add to scene
* @param name the name of the mesh
* @return a Node corresponding to the mesh
*/
fun addMesh(scMesh: graphics.scenery.Mesh, name: String ="Mesh"): graphics.scenery.Mesh {
scMesh.ifMaterial {
ambient = Vector3f(1.0f, 0.0f, 0.0f)
diffuse = Vector3f(0.0f, 1.0f, 0.0f)
specular = Vector3f(1.0f, 1.0f, 1.0f)
}
scMesh.spatial().position = Vector3f(0.0f, 0.0f, 0.0f)
scMesh.name = generateUniqueName(name)
objectService.addObject(scMesh)
return addNode(scMesh)
}
/**
* Add a scenery Mesh to the scene
* @param scMesh scenery mesh to add to scene
* @return a Node corresponding to the mesh
*/
fun addMesh(scMesh: graphics.scenery.Mesh): graphics.scenery.Mesh {
return addMesh(scMesh, "Mesh")
}
/**
* Add an ImageJ mesh to the scene