]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/common/AbstractVTKNodeMap.java
2c37521b8367b751451d3a73c5b02cbca60977cd
[simantics/3d.git] / org.simantics.g3d.vtk / src / org / simantics / g3d / vtk / common / AbstractVTKNodeMap.java
1 /*******************************************************************************
2  * Copyright (c) 2012, 2013 Association for Decentralized Information Management in
3  * Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.g3d.vtk.common;
13
14 import java.util.ArrayDeque;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Deque;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.Stack;
25
26 import org.simantics.db.ReadGraph;
27 import org.simantics.db.Session;
28 import org.simantics.db.UndoContext;
29 import org.simantics.db.WriteGraph;
30 import org.simantics.db.common.request.ReadRequest;
31 import org.simantics.db.common.request.WriteRequest;
32 import org.simantics.db.exception.DatabaseException;
33 import org.simantics.db.layer0.util.Layer0Utils;
34 import org.simantics.db.service.UndoRedoSupport;
35 import org.simantics.g3d.ontology.G3D;
36 import org.simantics.g3d.scenegraph.RenderListener;
37 import org.simantics.g3d.scenegraph.base.INode;
38 import org.simantics.g3d.scenegraph.base.NodeListener;
39 import org.simantics.g3d.scenegraph.base.ParentNode;
40 import org.simantics.objmap.exceptions.MappingException;
41 import org.simantics.objmap.graph.IMapping;
42 import org.simantics.objmap.graph.IMappingListener;
43 import org.simantics.utils.datastructures.Callback;
44 import org.simantics.utils.datastructures.MapList;
45 import org.simantics.utils.datastructures.MapSet;
46 import org.simantics.utils.datastructures.Pair;
47 import org.simantics.utils.ui.ExceptionUtils;
48
49 import vtk.vtkProp;
50
51 public abstract class AbstractVTKNodeMap<DBObject,E extends INode> implements VTKNodeMap<DBObject,E>, IMappingListener, RenderListener, NodeListener, UndoRedoSupport.ChangeListener{
52
53         private static final boolean DEBUG = false;
54         
55         protected Session session;
56         protected IMapping<DBObject,E> mapping;
57         protected VtkView view;
58         
59         private MapList<E, vtkProp> nodeToActor = new MapList<E, vtkProp>();
60         private Map<vtkProp,E> actorToNode = new HashMap<vtkProp, E>();
61
62         protected ParentNode<E> rootNode;
63         
64         protected UndoRedoSupport undoRedoSupport;
65         protected int undoOpCount = 0;
66         protected int redoOpCount = 0;
67         protected boolean runUndo = false;
68         protected boolean runRedo = false;
69         public AbstractVTKNodeMap(Session session, IMapping<DBObject,E> mapping, VtkView view, ParentNode<E> rootNode) {
70                 this.session = session;
71                 this.mapping = mapping;
72                 this.view = view;
73                 this.rootNode = rootNode;
74                 view.addListener(this);
75                 mapping.addMappingListener(this);
76                 rootNode.addListener(this);
77                 
78                 undoRedoSupport = session.getService(UndoRedoSupport.class);
79                 undoRedoSupport.subscribe(this);
80                 try {
81                         UndoContext undoContext = undoRedoSupport.getUndoContext(session); 
82                         undoOpCount = undoContext.getAll().size();
83                         redoOpCount = undoContext.getRedoList().size();
84                 } catch(DatabaseException e) {
85                         e.printStackTrace();
86                 }
87         }
88
89         protected abstract void addActor(E node);
90         protected abstract void removeActor(E node);
91         protected abstract void updateActor(E node,Set<String> ids);
92         
93         public void repaint() {
94                 view.refresh();
95         }
96         
97         public void populate() {
98                 for (E node : rootNode.getNodes()) {
99                         receiveAdd(node, node.getParentRel(),true);
100                 }
101                 repaint();
102         }
103         
104         @Override
105         public E getNode(vtkProp prop) {
106                 return actorToNode.get(prop);
107         }
108         
109         @SuppressWarnings("unchecked")
110         @Override
111         public Collection<vtkProp> getRenderObjects(INode node) {
112                 return nodeToActor.getValues((E)node);
113         }
114         
115         protected <T extends vtkProp> void map(E node, Collection<T> props) {
116             for (vtkProp p : props) {
117                 nodeToActor.add(node, p);
118                 actorToNode.put(p, node);
119             }
120         }
121         
122         protected void removeMap(E node) {
123             Collection<vtkProp> coll = nodeToActor.getValuesUnsafe(node);
124             for (vtkProp p : coll) {
125                 actorToNode.remove(p);
126             }
127             nodeToActor.remove(node);
128         }
129         
130         @SuppressWarnings("unchecked")
131         @Override
132         public ParentNode<E> getRootNode() {
133                 return (ParentNode<E>)rootNode;
134         }
135         
136         
137         
138         @Override
139         public boolean isChangeTracking() {
140                 return changeTracking;
141         }
142         
143         @Override
144         public void setChangeTracking(boolean enabled) {
145                 changeTracking = enabled;
146         }
147         
148         private boolean changeTracking = true;
149         
150         protected Object syncMutex = new Object(); 
151         
152
153         private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
154         private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
155         private MapSet<E, String> updated = new MapSet.Hash<E, String>();
156
157         private boolean rangeModified = false;
158         
159         public boolean isRangeModified() {
160         return rangeModified;
161     }
162         
163         @Override
164         public void onChanged() {
165                 try {
166                         UndoContext undoContext = undoRedoSupport.getUndoContext(session);
167                         int ucount = undoContext.getAll().size();
168                         int rcount = undoContext.getRedoList().size();
169                         if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
170                         if (ucount < undoOpCount) {
171                                 runUndo = true;
172                         } else {
173                                 runUndo = false;
174                         }
175                         if (!runUndo && rcount > 0)
176                                 runRedo = true;
177                         else
178                                 runRedo = false;
179                         undoOpCount = ucount;
180                         redoOpCount = rcount;
181                         
182                         if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
183                 } catch (DatabaseException e) {
184                         // TODO Auto-generated catch block
185                         e.printStackTrace();
186                 }
187                 
188                 
189         }
190         
191         @SuppressWarnings("unchecked")
192         @Override
193         public void updateRenderObjectsFor(E node) {
194                 List<vtkProp> toDelete = new ArrayList<vtkProp>();
195                 view.lock();
196                 for (vtkProp prop : nodeToActor.getValues((E)node)) {
197                         if (prop.GetVTKId() != 0) {
198                                 view.getRenderer().RemoveActor(prop);
199                                 //prop.Delete();
200                                 toDelete.add(prop);
201                         }
202                         actorToNode.remove(prop);
203                 }
204                 view.unlock();
205                 nodeToActor.remove((E)node);
206                 Collection<vtkProp> coll = getActors((E)node);
207                 if (coll != null) {
208                         for (vtkProp prop : coll) {
209                                 nodeToActor.add((E)node,prop);
210                                 actorToNode.put(prop, (E)node);
211                                 toDelete.remove(prop);
212                         }
213                 }
214                 for (vtkProp p : toDelete)
215                         p.Delete();
216         }
217         
218         protected abstract  Collection<vtkProp> getActors(E node);
219         
220         @SuppressWarnings("unchecked")
221         private void receiveAdd(E node, String id, boolean db) {
222                 if (DEBUG) System.out.println("receiveAdd " + debugString(node)  + " " + id + " " + db);
223                 synchronized (syncMutex) {
224                         for (Pair<E, String> n : added) {
225                                 if (n.first.equals(node))
226                                         return;
227                         }
228                         if (changeTracking) {
229                                 mapping.rangeModified((E)node.getParent());
230                         }
231                         added.add(new Pair<E, String>(node, id));
232                         rangeModified = true;
233                 }
234                 repaint();
235         }
236         
237         @SuppressWarnings("unchecked")
238         private void receiveRemove(E node, String id, boolean db) {
239                 if (DEBUG) System.out.println("receiveRemove " + debugString(node)  + " " + id + " " + db);
240                 synchronized (syncMutex) {
241                         for (Pair<E, String> n : removed) {
242                                 if (n.first.equals(node))
243                                         return;
244                         }
245                         if (changeTracking && !db)
246                                 mapping.rangeModified((E)node.getParent());
247                         removed.add(new Pair<E, String>(node, id));
248                         rangeModified = true;
249                 }
250                 repaint();
251         }
252         
253         @SuppressWarnings("unchecked")
254         private void receiveUpdate(E node, String id, boolean db) {
255                 if (DEBUG) System.out.println("receiveUpdate " + debugString(node)  + " " + id + " " + db);
256                 synchronized (syncMutex) {
257 //          for (Pair<E, String> n : updated) {
258 //              if (n.first.equals(node))
259 //                  return;
260 //          }
261                         if (changeTracking && !db)
262                                 mapping.rangeModified(node);
263                         //updated.add(new Pair<E, String>(node, id));
264                         updated.add(node, id);
265                         rangeModified = true;
266                 }
267                 repaint();
268         }
269         
270         private boolean graphUpdates = false;
271         private Set<E> graphModified = new HashSet<E>();
272         
273         private boolean requestCommit = false;
274         private String commitMessage = null;
275         
276         @Override
277         public void commit(String message) {
278                 requestCommit = true;
279                 commitMessage = message;
280         }
281         
282         protected void doCommit() {
283                 session.asyncRequest(new WriteRequest() {
284                         
285                         @Override
286                         public void perform(WriteGraph graph) throws DatabaseException {
287                                 if (DEBUG) System.out.println("Commit " + commitMessage);
288                                 if (commitMessage != null) {
289                                         Layer0Utils.addCommentMetadata(graph, commitMessage);
290                                         graph.markUndoPoint();
291                                         commitMessage = null;
292                                 }
293                                 commit(graph);
294                         }
295                         
296                 }, new Callback<DatabaseException>() {
297                         
298                         @Override
299                         public void run(DatabaseException parameter) {
300                                 if (parameter != null)
301                                         ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter);
302                         }
303                 });
304         }
305         
306         protected void commit(WriteGraph graph) throws DatabaseException {
307                 synchronized(syncMutex) {
308                         if (DEBUG) System.out.println("Commit");
309                         graphUpdates = true;
310                         mapping.updateDomain(graph);
311                         graphUpdates = false;
312                         clearDeletes();
313                         if (DEBUG) System.out.println("Commit done");
314                 }
315         }
316         
317         
318         
319         @Override
320         public void domainModified() {
321                 if (graphUpdates)
322                         return;
323                 if (DEBUG)System.out.println("domainModified");
324                 session.asyncRequest(new ReadRequest() {
325                         
326                         @SuppressWarnings("unchecked")
327                         @Override
328                         public void run(ReadGraph graph) throws DatabaseException {
329                                 update(graph);
330                         }
331                 });
332                 
333         }
334         
335         protected void reset(ReadGraph graph) throws MappingException {
336                 if (DEBUG) System.out.println("Reset");
337                 
338                 synchronized (syncMutex) {
339                         graphUpdates = true;
340                         mapping.getRangeModified().clear();
341                         for (DBObject o : mapping.getDomain())
342                                 mapping.domainModified(o);
343                         mapping.updateRange(graph);
344                         graphModified.clear();
345                         graphUpdates = false;
346                 }
347         }
348         
349         private boolean useFullSyncWithUndo = false;
350         
351         protected void update(ReadGraph graph) throws DatabaseException {
352                 if (DEBUG) System.out.println("Graph update start");
353                 if (runUndo && useFullSyncWithUndo) {
354                         reset(graph);
355                 } else {
356                         synchronized (syncMutex) {
357                                 graphUpdates = true;
358                                 for (DBObject domainObject : mapping.getDomainModified()) {
359                                         E rangeObject = mapping.get(domainObject);
360                                         if (rangeObject != null)
361                                                 graphModified.add(rangeObject);
362                                 }
363                                 mapping.updateRange(graph);
364                                 graphModified.clear();
365                                 syncDeletes();
366                                 clearDeletes();
367                                 graphUpdates = false;
368                         }
369                 }
370                 
371                 if (mapping.isRangeModified() && !runUndo && !runRedo)
372                         commit((String)null);
373                 if (DEBUG) System.out.println("Graph update done");
374         }
375         
376         @Override
377         public void rangeModified() {
378                 //System.out.println("rangeModified");
379
380         }
381         
382         @Override
383         public void postRender() {
384                 // Commit changes if
385                 // 1. Commit has been requested
386                 // 2. There are no pending changes that should be processed in preRender() 
387                 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
388                         requestCommit = false;
389                         doCommit();
390                 }
391         }
392         
393         // Reusable containers for data synchronisation
394         List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>();  // Removed objects
395         List<Pair<E, String>> add = new ArrayList<Pair<E,String>>();  // Added objects
396         MapSet<E, String> mod = new MapSet.Hash<E, String>();         // Modified objects
397         Set<E> propagation = new HashSet<E>();                        // Objects with propagated changes 
398         Stack<E> stack = new Stack<E>();                              // Stack for handling propagation
399         Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
400         Set<E> deleteUC = new HashSet<E>();
401         
402         @Override
403         public synchronized void preRender() {
404                 updateCycle();
405         }
406         
407         
408         /**
409          * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
410          * This causes problems with Undo and Redo, which cause re-using the removed objects from mapping cache.
411          * 
412          * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).  
413          * 
414          */
415         protected void syncDeletes() {
416                 deleteUC.clear();
417                 for (Pair<E, String> n : removed) {
418                         deleteUC.add(n.first);   
419                 }
420                 for (Pair<E, String> n : added) {
421                         deleteUC.remove(n.first);   
422                 } 
423                 if (DEBUG && deleteUC.size() > 0) {
424                         System.out.println("Delete sync");
425                         for (E n : delete) {
426                                 System.out.println(debugString(n));
427                         }
428                 }
429                 delete.addAll(deleteUC);
430                 deleteUC.clear();
431         }
432
433         /**
434          * Clears deletable objects from mapping cache.
435          */
436         protected void clearDeletes() {
437                 if (DEBUG && delete.size() > 0) System.out.println("Delete");
438                 for (E n : delete) {
439                         if (DEBUG) System.out.println(debugString(n));
440                         mapping.getRange().remove(n);
441                 }
442                 delete.clear();
443         }
444         
445         protected String debugString(E n) {
446                 return n + "@" + Integer.toHexString(n.hashCode());
447         }
448         
449         protected boolean filterChange(List<Pair<E,String>> list,E n) {
450             for (int i = list.size()-1; i >= 0; i--) {
451             if (list.get(i).first == n) {
452                 list.remove(i);
453                 return true;
454             }
455         }
456             return false;
457         }
458         
459         @SuppressWarnings("unchecked")
460         protected void updateCycle() {
461                 rem.clear();
462                 add.clear();
463                 mod.clear();
464                 propagation.clear();
465                 
466                 
467                 synchronized (syncMutex) {
468                     // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
469                     Deque<E> stack = new ArrayDeque<E>();
470                 for (Pair<E, String> n : added) {
471                     stack.add(n.first);
472                 }
473                 while (!stack.isEmpty()) {
474                     E n = stack.pop();
475                     boolean conflict = filterChange(removed, n);
476                     if (conflict) {
477                         System.out.println("Prevent removing " + n);
478                         //filterChange(added, n)
479                         if (filterChange(added, n))
480                             System.out.println("Prevent adding " + n);
481                     }
482                     if (n instanceof ParentNode) {
483                         ParentNode<INode> pn = (ParentNode<INode>)n;
484                         for (INode cn : pn.getNodes()) {
485                             stack.push((E)cn);
486                         }
487                     }
488                 }
489                 
490                         rem.addAll(removed);
491                         add.addAll(added);
492                         for (E e : updated.getKeys()) {
493                                 for (String s : updated.getValues(e)) {
494                                         mod.add(e, s);
495                                 }
496                         }
497                         syncDeletes();
498                         removed.clear();
499                         added.clear();
500                         updated.clear();
501                 }
502                 
503                 
504                 
505                 for (Pair<E, String> n : rem) {
506                         stopListening(n.first);
507                         removeActor(n.first);
508                 }
509                 
510                 for (Pair<E, String> n : add) {
511                         addActor(n.first);
512                         listen(n.first);
513                 }
514                 
515                 for (E e : mod.getKeys()) {
516                         Set<String> ids = mod.getValues(e);
517                         if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
518                                 if (!propagation.contains(e))
519                                         propagation.add(e);
520                         }
521                 }
522
523                 if (propagation.size() > 0) {
524                         stack.clear();
525                         stack.addAll(propagation);
526                         propagation.clear();
527                         while (!stack.isEmpty()) {
528                                 E node = stack.pop();
529                                 if (propagation.contains(node))
530                                         continue;
531                                 propagation.add(node);
532                                 for (NodeListener l : node.getListeners()) {
533                                         if (l == this) {
534                                                 //changeTracking = false;
535                                                 //l.propertyChanged(node, G3D.URIs.hasPosition);
536                                                 //changeTracking = true;
537                                         } else {
538                                                 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
539                                         }
540                                 }
541                                 if (node instanceof ParentNode) {
542                                         stack.addAll(((ParentNode<E>)node).getNodes());
543                                 }
544                         }
545                 }
546                 
547 //      synchronized (syncMutex) {
548 //          rem.addAll(removed);
549 //          add.addAll(added);
550 //          //mod.addAll(updated);
551 //          for (E e : updated.getKeys()) {
552 //              for (String s : updated.getValues(e))
553 //                  mod.add(e, s);
554 //          }
555 //          
556 //          removed.clear();
557 //          added.clear();
558 //          updated.clear();
559 //      }
560                 
561                 for (E e : mod.getKeys()) {
562                         Set<String> ids = mod.getValues(e);
563                         updateActor(e,ids);
564                 }
565                 
566                 
567                 for (Pair<E, String> n : rem) {
568                         for (NodeListener l : nodeListeners)
569                                 l.nodeRemoved(null, n.first, n.second);
570                 }
571                 for (Pair<E, String> n : add) {
572                         for (NodeListener l : nodeListeners)
573                                 l.nodeAdded(n.first.getParent(), n.first, n.second);
574                 }
575 //      for (Pair<E, String> n : mod) {
576 //          for (NodeListener l : nodeListeners)
577 //              l.propertyChanged(n.first, n.second);
578 //      }
579                 for (E e : mod.getKeys()) {
580                         for (NodeListener l : nodeListeners)
581                                 for (String s : mod.getValues(e))
582                                         l.propertyChanged(e, s);
583                 }
584                 
585                 synchronized (syncMutex) {
586                         if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
587                                 rangeModified = false;
588                 }
589         }
590         
591         @SuppressWarnings("unchecked")
592         private void listen(INode node) {
593                 node.addListener(this);
594                 if (node instanceof ParentNode<?>) {
595                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
596                         for (INode n : parentNode.getNodes())
597                                 listen(n);
598                 }
599         }
600         
601         private void stopListening(INode node) {
602                 node.removeListener(this);
603                 if (node instanceof ParentNode<?>) {
604                         @SuppressWarnings("unchecked")
605                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
606                         for (INode n : parentNode.getNodes())
607                                 stopListening(n);
608                 }
609         }
610         
611         @SuppressWarnings("unchecked")
612         @Override
613         public void propertyChanged(INode node, String id) {
614                 //receiveUpdate((E)node, id, graphUpdates);
615                 receiveUpdate((E)node, id, graphModified.contains(node));
616                 
617         }
618         
619         @SuppressWarnings("unchecked")
620         @Override
621         public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
622                         String rel) {
623                 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
624                 //receiveAdd((E)child, rel ,graphUpdates);
625                 receiveAdd((E)child, rel ,graphModified.contains(node));
626                 
627         }
628         
629         @SuppressWarnings("unchecked")
630         @Override
631         public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
632                         String rel) {
633                 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
634                 //receiveRemove((E)child, rel, graphUpdates);
635                 receiveRemove((E)child, rel, graphModified.contains(node));
636                 
637                 //FIXME : sometimes removed structural models cause ObjMap to add their children again.
638                 //        removing the listener here prevents corruption of visual model, but better fix is needed.
639                 stopListening(child);
640         }
641         
642         @Override
643         public void delete() {
644                 if (undoRedoSupport != null)
645                         undoRedoSupport.cancel(this);
646                 
647                 changeTracking = false;
648                 view.removeListener(this);
649                 mapping.removeMappingListener(this);
650
651                 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
652                 nodes.addAll(nodeToActor.getKeys());
653                 for (E node : nodes) {
654                         node.removeListener(this);
655                         removeActor(node);
656                         node.cleanup();
657                 }
658                 for (vtkProp prop : actorToNode.keySet()) {
659                         if (prop.GetVTKId() != 0) 
660                                 prop.Delete();
661                 }
662                 actorToNode.clear();
663                 nodeToActor.clear();
664                 
665         }
666         
667         
668         private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
669         @Override
670         public void addListener(NodeListener listener) {
671                 nodeListeners.add(listener);
672                 
673         }
674         
675         @Override
676         public void removeListener(NodeListener listener) {
677                 nodeListeners.remove(listener);
678                 
679         }
680         
681         public IMapping<DBObject,E> getMapping() {
682                 return mapping;
683         }
684         
685         
686 }