NativeObjectManager.java 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /*
  2. * Copyright (c) 2009-2012 jMonkeyEngine
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are
  7. * met:
  8. *
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. *
  12. * * Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. *
  16. * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
  17. * may be used to endorse or promote products derived from this software
  18. * without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  22. * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  24. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  25. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  28. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  30. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. package com.jme3.util;
  33. import com.jme3.renderer.Renderer;
  34. import java.lang.ref.PhantomReference;
  35. import java.lang.ref.ReferenceQueue;
  36. import java.lang.ref.WeakReference;
  37. import java.util.ArrayDeque;
  38. import java.util.ArrayList;
  39. import java.util.HashMap;
  40. import java.util.logging.Level;
  41. import java.util.logging.Logger;
  42. /**
  43. * GLObjectManager tracks all GLObjects used by the Renderer. Using a
  44. * <code>ReferenceQueue</code> the <code>GLObjectManager</code> can delete
  45. * unused objects from GPU when their counterparts on the CPU are no longer used.
  46. *
  47. * On restart, the renderer may request the objects to be reset, thus allowing
  48. * the GLObjects to re-initialize with the new display context.
  49. */
  50. public class NativeObjectManager {
  51. private static final Logger logger = Logger.getLogger(NativeObjectManager.class.getName());
  52. /**
  53. * Set to <code>true</code> to enable deletion of native buffers together with GL objects
  54. * when requested. Note that usage of object after deletion could cause undefined results
  55. * or native crashes, therefore by default this is set to <code>false</code>.
  56. */
  57. public static boolean UNSAFE = false;
  58. /**
  59. * The maximum number of objects that should be removed per frame.
  60. * If the limit is reached, no more objects will be removed for that frame.
  61. */
  62. private static final int MAX_REMOVES_PER_FRAME = 100;
  63. /**
  64. * Reference queue for {@link NativeObjectRef native object references}.
  65. */
  66. private ReferenceQueue<Object> refQueue = new ReferenceQueue<Object>();
  67. /**
  68. * List of currently active GLObjects.
  69. */
  70. private HashMap<Long, NativeObjectRef> refMap = new HashMap<Long, NativeObjectRef>();
  71. /**
  72. * List of real objects requested by user for deletion.
  73. */
  74. private ArrayDeque<NativeObject> userDeletionQueue = new ArrayDeque<NativeObject>();
  75. private static class NativeObjectRef extends PhantomReference<Object> {
  76. private NativeObject objClone;
  77. private WeakReference<NativeObject> realObj;
  78. public NativeObjectRef(ReferenceQueue<Object> refQueue, NativeObject obj){
  79. super(obj.handleRef, refQueue);
  80. assert obj.handleRef != null;
  81. this.realObj = new WeakReference<NativeObject>(obj);
  82. this.objClone = obj.createDestructableClone();
  83. assert objClone.getId() == obj.getId();
  84. }
  85. }
  86. /**
  87. * (Internal use only) Register a <code>NativeObject</code> with the manager.
  88. */
  89. public void registerObject(NativeObject obj) {
  90. if (obj.getId() <= 0) {
  91. throw new IllegalArgumentException("object id must be greater than zero");
  92. }
  93. NativeObjectRef ref = new NativeObjectRef(refQueue, obj);
  94. refMap.put(obj.getUniqueId(), ref);
  95. obj.setNativeObjectManager(this);
  96. if (logger.isLoggable(Level.FINEST)) {
  97. logger.log(Level.FINEST, "Registered: {0}", new String[]{obj.toString()});
  98. }
  99. }
  100. private void deleteNativeObject(Object rendererObject, NativeObject obj, NativeObjectRef ref,
  101. boolean deleteGL, boolean deleteBufs) {
  102. assert rendererObject != null;
  103. // "obj" is considered the real object (with buffers and everything else)
  104. // if "ref" is null.
  105. NativeObject realObj = ref != null ?
  106. ref.realObj.get() :
  107. obj;
  108. assert realObj == null || obj.getId() == realObj.getId();
  109. if (deleteGL) {
  110. if (obj.getId() <= 0) {
  111. logger.log(Level.WARNING, "Object already deleted: {0}", obj.getClass().getSimpleName() + "/" + obj.getId());
  112. } else {
  113. // Unregister it from cleanup list.
  114. NativeObjectRef ref2 = refMap.remove(obj.getUniqueId());
  115. if (ref2 == null) {
  116. throw new IllegalArgumentException("This NativeObject is not " +
  117. "registered in this NativeObjectManager");
  118. }
  119. assert ref == null || ref == ref2;
  120. int id = obj.getId();
  121. // Delete object from the GL driver
  122. obj.deleteObject(rendererObject);
  123. assert obj.getId() == NativeObject.INVALID_ID;
  124. if (logger.isLoggable(Level.FINEST)) {
  125. logger.log(Level.FINEST, "Deleted: {0}", obj.getClass().getSimpleName() + "/" + id);
  126. }
  127. if (realObj != null){
  128. // Note: make sure to reset them as well
  129. // They may get used in a new renderer in the future
  130. realObj.resetObject();
  131. }
  132. }
  133. }
  134. if (deleteBufs && UNSAFE && realObj != null) {
  135. // Only the real object has native buffers.
  136. // The destructable clone has nothing and cannot be used in this case.
  137. realObj.deleteNativeBuffersInternal();
  138. }
  139. }
  140. /**
  141. * (Internal use only) Deletes unused NativeObjects.
  142. * Will delete at most {@link #MAX_REMOVES_PER_FRAME} objects.
  143. *
  144. * @param rendererObject The renderer object.
  145. * For graphics objects, {@link Renderer} is used, for audio, {#link AudioRenderer} is used.
  146. */
  147. public void deleteUnused(Object rendererObject){
  148. int removed = 0;
  149. while (removed < MAX_REMOVES_PER_FRAME && !userDeletionQueue.isEmpty()) {
  150. // Remove user requested objects.
  151. NativeObject obj = userDeletionQueue.pop();
  152. deleteNativeObject(rendererObject, obj, null, true, true);
  153. removed++;
  154. }
  155. while (removed < MAX_REMOVES_PER_FRAME) {
  156. // Remove objects reclaimed by GC.
  157. NativeObjectRef ref = (NativeObjectRef) refQueue.poll();
  158. if (ref == null) {
  159. break;
  160. }
  161. deleteNativeObject(rendererObject, ref.objClone, ref, true, false);
  162. removed++;
  163. }
  164. if (removed >= 1) {
  165. logger.log(Level.FINE, "NativeObjectManager: {0} native objects were removed from native", removed);
  166. }
  167. }
  168. /**
  169. * (Internal use only) Deletes all objects.
  170. * Must only be called when display is destroyed.
  171. */
  172. public void deleteAllObjects(Object rendererObject){
  173. deleteUnused(rendererObject);
  174. ArrayList<NativeObjectRef> refMapCopy = new ArrayList<NativeObjectRef>(refMap.values());
  175. for (NativeObjectRef ref : refMapCopy) {
  176. deleteNativeObject(rendererObject, ref.objClone, ref, true, false);
  177. }
  178. assert refMap.size() == 0;
  179. }
  180. /**
  181. * Marks the given <code>NativeObject</code> as unused,
  182. * to be deleted on the next frame.
  183. * Usage of this object after deletion will cause an exception.
  184. * Note that native buffers are only reclaimed if
  185. * {@link #UNSAFE} is set to <code>true</code>.
  186. *
  187. * @param obj The object to mark as unused.
  188. */
  189. void enqueueUnusedObject(NativeObject obj) {
  190. userDeletionQueue.push(obj);
  191. }
  192. /**
  193. * (Internal use only) Resets all {@link NativeObject}s.
  194. * This is typically called when the context is restarted.
  195. */
  196. public void resetObjects(){
  197. for (NativeObjectRef ref : refMap.values()) {
  198. // Must use the real object here, for this to be effective.
  199. NativeObject realObj = ref.realObj.get();
  200. if (realObj == null) {
  201. continue;
  202. }
  203. realObj.resetObject();
  204. if (logger.isLoggable(Level.FINEST)) {
  205. logger.log(Level.FINEST, "Reset: {0}", realObj);
  206. }
  207. }
  208. refMap.clear();
  209. }
  210. // public void printObjects(){
  211. // System.out.println(" ------------------- ");
  212. // System.out.println(" GL Object count: "+ objectList.size());
  213. // for (GLObject obj : objectList){
  214. // System.out.println(obj);
  215. // }
  216. // }
  217. }