Example #1
0
 public static void Assert(bool condition, string message, Object context=null)
 {
     if (!condition)
     {
         LogError("Assert failed", message, context);
     }
 }
Example #2
0
        public static void Reset(UnityObject target_) {
            var target = new fiUnityObjectReference(target_);
            if (s_metadata.ContainsKey(target)) {
                s_metadata.Remove(target);

                for (int i = 0; i < s_providers.Length; ++i) {
                    s_providers[i].Reset(target.Target);
                }
            }
        }
        internal static bool TryReflectMethod(out MethodInfo methodInfo, out UnityReflectionException exception, UnityObject reflectionTarget, string name, Type[] parameterTypes)
        {
            #if !NETFX_CORE
            methodInfo = null;

            Type type = reflectionTarget.GetType();
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;

            if (parameterTypes != null) // Explicit matching
            {
                methodInfo = type.GetMethod(name, flags, null, parameterTypes, null);

                if (methodInfo == null)
                {
                    methodInfo = type.GetExtensionMethods()
                        .Where(extension => extension.Name == name)
                        .Where(extension => Enumerable.SequenceEqual(extension.GetParameters().Select(paramInfo => paramInfo.ParameterType), parameterTypes))
                        .FirstOrDefault();
                }

                if (methodInfo == null)
                {
                    exception = new UnityReflectionException(string.Format("No matching method found: '{0}.{1} ({2})'", type.Name, name, string.Join(", ", parameterTypes.Select(t => t.Name).ToArray())));
                    return false;
                }
            }
            else // Implicit matching
            {
                var normalMethods = type.GetMember(name, MemberTypes.Method, flags).OfType<MethodInfo>().ToList();
                var extensionMethods = type.GetExtensionMethods().Where(extension => extension.Name == name).ToList();
                var methods = new List<MethodInfo>();
                methods.AddRange(normalMethods);
                methods.AddRange(extensionMethods);

                if (methods.Count == 0)
                {
                    exception = new UnityReflectionException(string.Format("No matching method found: '{0}.{1}'", type.Name, name));
                    return false;
                }

                if (methods.Count > 1)
                {
                    exception = new UnityReflectionException(string.Format("Multiple method signatures found for '{0}.{1}'\nSpecify the parameter types explicitly.", type.FullName, name));
                    return false;
                }

                methodInfo = methods[0];
            }

            exception = null;
            return true;
            #else
            throw new Exception("Reflection is not supported in .NET Core.");
            #endif
        }
 public SubContainerPrefabBindingFinalizer(
     BindInfo bindInfo,
     GameObjectBindInfo gameObjectBindInfo,
     UnityEngine.Object prefab,
     object subIdentifier)
     : base(bindInfo)
 {
     _gameObjectBindInfo = gameObjectBindInfo;
     _prefab = prefab;
     _subIdentifier = subIdentifier;
 }
        internal static MethodInfo ReflectMethod(UnityObject reflectionTarget, string name, Type[] parameterTypes)
        {
            MethodInfo methodInfo;
            UnityReflectionException exception;

            if (!TryReflectMethod(out methodInfo, out exception, reflectionTarget, name, parameterTypes))
            {
                throw exception;
            }

            return methodInfo;
        }
        internal static MemberInfo ReflectVariable(UnityObject reflectionTarget, string name)
        {
            MemberInfo variableInfo;
            UnityReflectionException exception;

            if (!TryReflectVariable(out variableInfo, out exception, reflectionTarget, name))
            {
                throw exception;
            }

            return variableInfo;
        }
        public int StoreObjectReference(UnityObject obj)
        {
            if (SerializedObjects == null) {
                throw new InvalidOperationException("SerializedObjects cannot be null");
            }

            // We don't have to bother storing null
            if (ReferenceEquals(obj, null)) {
                return -1;
            }

            int index = SerializedObjects.Count;
            SerializedObjects.Add(obj);
            return index;
        }
Example #8
0
 public static fiGraphMetadata GetMetadataFor(UnityObject target_) {
     var target = new fiUnityObjectReference(target_);
     fiGraphMetadata metadata;
     if (s_metadata.TryGetValue(target, out metadata) == false) {
         // Make sure that we update the s_metadata instance for target before initializing all of the providers,
         // as some of the providers may recurisvely call into this method to fetch the actual fiGraphMetadata
         // instance during initialization.
         metadata = new fiGraphMetadata(target);
         s_metadata[target] = metadata;
         for (int i = 0; i < s_providers.Length; ++i) {
             s_providers[i].RestoreData(target.Target);
         }
     }
     return metadata;
 }
Example #9
0
        public bool Member(MemberInfo member, object rawTarget, UnityObject unityTarget, int id, bool ignoreComposition, out EditorMember wrappedMember)
        {
            if (member.MemberType == MemberTypes.Method)
            {
                var method = member as MethodInfo;
                var methodKey = Cache.GetMethodKey(Tuple.Create(id, method));
                var methodDrawer = MemberDrawersHandler.GetMethodDrawer(methodKey);
                methodDrawer.Initialize(method, rawTarget, unityTarget, methodKey, this);
                wrappedMember = null;
                return methodDrawer.OnGUI();
            }
            else
            {
                var cachedMember = Cache.GetMember(Tuple.Create(member, id));
                cachedMember.RawTarget = rawTarget;
                cachedMember.UnityTarget = unityTarget;
                wrappedMember = cachedMember;

                return Member(cachedMember, ignoreComposition);
            }
        }
Example #10
0
 /// <summary>
 /// Writes exception to console. Works only when Debugger is Enabled.
 /// </summary>
 /// <param name="exception">Exception to write.</param>
 /// <param name="context">Context.</param>
 public static void LogException(Exception exception, Object context = null)
 {
     if (LogLevelEnabled(LogLevel.Exception))
     {
         Debug.LogException(exception, context);
     }
 }
 public ArgMember(Func <object> getter, Action <object> setter, object target, UnityObject unityTarget, Type dataType, Attribute[] attributes, string name, string id)
     : base(null, null, unityTarget, null)
 {
     this.getter     = getter;
     this.setter     = setter;
     this.Target     = target;
     this.attributes = attributes;
     this.Name       = name;
     this.Type       = dataType;
     this.Id         = id + name;
 }
Example #12
0
 /// <summary>
 /// Asserts if obj is null. Works only when Debugger is Enabled.
 /// </summary>
 /// <param name="obj">Object to check.</param>
 /// <param name="name">Name of a object</param>
 /// <param name="context">Context for a check (usually containing class).</param>
 public static void AssertNotNull(object obj, string name, Object context)
 {
     if (Enabled && (obj == null || obj.Equals(null)))
     {
         Debug.LogError(name + " in object " + context.name + " ( " + context.GetType() + " ) is null!", context);
     }
 }
 public void RegisterPersistentListener(UnityEngine.Object ttarget, string mmethodName)
 {
   this.m_Target = ttarget;
   this.m_MethodName = mmethodName;
 }
 public static void Verbose(this ILog logger, string message, UnityEngine.Object context)
 {
     logger.Log(LogLevel.Verbose, message, context, null);
 }
 public static void VerboseFormat(this ILog logger, UnityEngine.Object context, string message, object arg0, object arg1, object arg2)
 {
     logger.Log(LogLevel.Verbose, string.Format(message, arg0, arg1, arg2), context, null);
 }
        private void ApplyListLength(UnityEngine.Object unityObject)
        {
            object listObj = GetInstanceFromPath(this.Path, unityObject);

            if (listObj == null)
            {
                // The list has been deleted on the prefab;
                // that supersedes our length change.
                return;
            }

            Type listType = listObj.GetType();

            if (listType.IsArray)
            {
                Array array = (Array)listObj;

                if (this.NewLength == array.Length)
                {
                    // If this happens, for some weird reason, then we can actually just not do anything
                    return;
                }

                // We actually need to replace all references to this array in the entire object graph!
                // Ridiculous, we know - but there's no choice...

                // Let's create a new, modified array
                Array newArray = Array.CreateInstance(listType.GetElementType(), this.NewLength);

                if (this.NewLength > array.Length)
                {
                    Array.Copy(array, 0, newArray, 0, array.Length);
                    ReplaceAllReferencesInGraph(unityObject, array, newArray);
                }
                else
                {
                    Array.Copy(array, 0, newArray, 0, newArray.Length);
                    ReplaceAllReferencesInGraph(unityObject, array, newArray);
                }
            }
            else if (typeof(IList).IsAssignableFrom(listType))
            {
                IList list               = (IList)listObj;
                Type  listElementType    = listType.ImplementsOpenGenericInterface(typeof(IList <>)) ? listType.GetArgumentsOfInheritedOpenGenericInterface(typeof(IList <>))[0] : null;
                bool  elementIsValueType = listElementType != null ? listElementType.IsValueType : false;

                int count = 0;

                while (list.Count < this.NewLength)
                {
                    if (elementIsValueType)
                    {
                        list.Add(Activator.CreateInstance(listElementType));
                    }
                    else
                    {
                        list.Add(null);
                    }

                    count++;
                }

                while (list.Count > this.NewLength)
                {
                    list.RemoveAt(list.Count - 1);
                }
            }
            else if (listType.ImplementsOpenGenericInterface(typeof(IList <>)))
            {
                Type elementType        = listType.GetArgumentsOfInheritedOpenGenericInterface(typeof(IList <>))[0];
                Type collectionType     = typeof(ICollection <>).MakeGenericType(elementType);
                bool elementIsValueType = elementType.IsValueType;

                PropertyInfo countProp = collectionType.GetProperty("Count");

                int count = (int)countProp.GetValue(listObj, null);

                if (count < this.NewLength)
                {
                    int add = this.NewLength - count;

                    MethodInfo addMethod = collectionType.GetMethod("Add");

                    for (int i = 0; i < add; i++)
                    {
                        if (elementIsValueType)
                        {
                            addMethod.Invoke(listObj, new object[] { Activator.CreateInstance(elementType) });
                        }
                        else
                        {
                            addMethod.Invoke(listObj, new object[] { null });
                        }
                        count++;
                    }
                }
                else if (count > this.NewLength)
                {
                    int remove = count - this.NewLength;

                    Type       listInterfaceType = typeof(IList <>).MakeGenericType(elementType);
                    MethodInfo removeAtMethod    = listInterfaceType.GetMethod("RemoveAt");

                    for (int i = 0; i < remove; i++)
                    {
                        removeAtMethod.Invoke(listObj, new object[] { count - (remove + 1) });
                    }
                }
            }
        }
 public static fiGraphMetadata GetMetadataFor(UnityObject target)
 {
     return GetMetadataFor(new fiUnityObjectReference(target, /*tryRestore:*/false));
 }
Example #18
0
        static public void Log(Enum_LogWriter eLogWriter, Enum_LogLevel eLogLevel, string strLog, UnityEngine.Object pObject = null)
        {
            if (CheckIsIgnore(eLogLevel, eLogWriter))
            {
                return;
            }

            ELogLevel eLogLevelConvert = _mapLogLevelConvert[eLogLevel.ToString()];

            if (eLogLevelConvert < ELogLevel.CustomLine_Warning)
            {
                UnityEngine.Debug.Log(ProcLogLine(strLog, eLogLevel, eLogWriter, true), pObject);
            }
            else if (eLogLevelConvert < ELogLevel.CustomLine_Error)
            {
                UnityEngine.Debug.LogWarning(ProcLogLine(strLog, eLogLevel, eLogWriter, true), pObject);
            }
            else
            {
                UnityEngine.Debug.LogError(ProcLogLine(strLog, eLogLevel, eLogWriter, true), pObject);
            }

            ProcWriteLog(strLog, eLogLevel, eLogWriter);
        }
Example #19
0
 public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller <TInstaller>(
     UnityEngine.Object prefab)
     where TInstaller : InstallerBase
 {
     return(ByNewPrefabInstaller(prefab, typeof(TInstaller)));
 }
Example #20
0
 public static bool IsNull(this UnityEngine.Object _o)
 {
     return(_o == null);
 }
Example #21
0
    // public so we can do passthroughs from other objects
    private static void Write(Level level, UnityEngine.Object context, string message, object[] args)
    {
        if ((level & LevelsEnabled) != level)
        {
            return;
        }

        if (args != null && args.Length > 0)
        {
            message = string.Format(message, args);
        }

        string threadId = !string.IsNullOrEmpty(System.Threading.Thread.CurrentThread.Name) ? System.Threading.Thread.CurrentThread.Name : System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();

        //"yyyy'-'MM'-'dd'T'HH':'mm':'ss,fff"
        message = string.Concat(System.DateTime.UtcNow.ToString("ss,fff"), "  [", level.ToString(), "][" + threadId + "]  ", message);

#if UNITY_EDITOR
        switch (level)
        {
        case Level.Debug:
            UnityEngine.Debug.Log("<color=cyan>" + message + "</color>", context);
            break;

        case Level.Info:
            UnityEngine.Debug.Log(message, context);
            break;

        case Level.Warning:
            UnityEngine.Debug.LogWarning("<color=yellow>" + message + "</color>", context);
            break;

        case Level.Error:
            UnityEngine.Debug.LogError(message, context);
            //Reporting.Error( message );
            break;
        }
#elif UNITY_ANDROID
        switch (level)
        {
        case Level.Debug:
            UnityEngine.Debug.Log(message);
            break;

        case Level.Info:
            UnityEngine.Debug.Log(message);
            break;

        case Level.Warning:
            UnityEngine.Debug.LogWarning(message);
            break;

        case Level.Error:
            UnityEngine.Debug.LogError(message);
            Reporting.Error(message);
            break;
        }
#elif UNITY_IPHONE
        switch (level)
        {
        case Level.Debug:
            IOSLogUtility.Write(message);
            break;

        case Level.Info:
            IOSLogUtility.Write(message);
            break;

        case Level.Warning:
            IOSLogUtility.Write(message);
            break;

        case Level.Error:
            IOSLogUtility.Write(message);
            Reporting.Error(message);
            break;
        }
#endif
    }
Example #22
0
 public static void Warning(UnityEngine.Object context, string message, params object[] args)
 {
     Write(Level.Warning, context, message, args);
 }
 public static void VerboseFormat(this ILog logger, UnityEngine.Object context, string message, params object[] args)
 {
     logger.Log(LogLevel.Verbose, string.Format(message, args), context, null);
 }
Example #24
0
 /// <summary>
 /// CustomSampler を生成してサンプリングを開始します
 /// </summary>
 public CustomSamplerScope(string name, UnityEngine.Object targetObject)
 {
     m_sampler = CustomSampler.Create(name);
     m_sampler.Begin(targetObject);
 }
Example #25
0
        static int _m_Assert_xlua_st_(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);



                int gen_param_count = LuaAPI.lua_gettop(L);

                if (gen_param_count == 1 && LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type(L, 1))
                {
                    bool _condition = LuaAPI.lua_toboolean(L, 1);

                    UnityEngine.Debug.Assert(_condition);



                    return(0);
                }
                if (gen_param_count == 2 && LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type(L, 1) && translator.Assignable <UnityEngine.Object>(L, 2))
                {
                    bool _condition             = LuaAPI.lua_toboolean(L, 1);
                    UnityEngine.Object _context = (UnityEngine.Object)translator.GetObject(L, 2, typeof(UnityEngine.Object));

                    UnityEngine.Debug.Assert(_condition, _context);



                    return(0);
                }
                if (gen_param_count == 2 && LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type(L, 1) && translator.Assignable <object>(L, 2))
                {
                    bool   _condition = LuaAPI.lua_toboolean(L, 1);
                    object _message   = translator.GetObject(L, 2, typeof(object));

                    UnityEngine.Debug.Assert(_condition, _message);



                    return(0);
                }
                if (gen_param_count == 2 && LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type(L, 1) && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING))
                {
                    bool   _condition = LuaAPI.lua_toboolean(L, 1);
                    string _message   = LuaAPI.lua_tostring(L, 2);

                    UnityEngine.Debug.Assert(_condition, _message);



                    return(0);
                }
                if (gen_param_count == 3 && LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type(L, 1) && translator.Assignable <object>(L, 2) && translator.Assignable <UnityEngine.Object>(L, 3))
                {
                    bool               _condition = LuaAPI.lua_toboolean(L, 1);
                    object             _message   = translator.GetObject(L, 2, typeof(object));
                    UnityEngine.Object _context   = (UnityEngine.Object)translator.GetObject(L, 3, typeof(UnityEngine.Object));

                    UnityEngine.Debug.Assert(_condition, _message, _context);



                    return(0);
                }
                if (gen_param_count == 3 && LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type(L, 1) && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && translator.Assignable <UnityEngine.Object>(L, 3))
                {
                    bool               _condition = LuaAPI.lua_toboolean(L, 1);
                    string             _message   = LuaAPI.lua_tostring(L, 2);
                    UnityEngine.Object _context   = (UnityEngine.Object)translator.GetObject(L, 3, typeof(UnityEngine.Object));

                    UnityEngine.Debug.Assert(_condition, _message, _context);



                    return(0);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }

            return(LuaAPI.luaL_error(L, "invalid arguments to UnityEngine.Debug.Assert!"));
        }
 public EasyRawImage(UnityEngine.Object image, Vector2 position) : base(position)
 {
     InitUiImageComponent();
     //some code...
 }
 public static void Verbose(this ILog logger, string message, UnityEngine.Object context, Exception exception)
 {
     logger.Log(LogLevel.Verbose, message, context, exception);
 }
Example #28
0
 public abstract void DrawEditor(UnityEngine.Object target, FieldInfo field, SerializedProperty property);
Example #29
0
 public abstract void DrawEditor(UnityEngine.Object target, PropertyInfo prop);
		public void UnregisterPersistentListener()
		{
			this.m_MethodName = string.Empty;
			this.m_Target = null;
		}
 public static void SetUserData <U>(this U output, UnityEngine.Object value) where U : struct, IPlayableOutput
 {
     output.GetHandle().SetUserData(value);
 }
Example #32
0
        //----- method -----

        public AssetReferenceInfo(string targetPath, Object target)
        {
            this.TargetPath   = targetPath;
            this.Target       = target;
            this.Dependencies = new List <string>();
        }
Example #33
0
 public static void LogWarning(object message, Object context = null)
 {
     Debug.LogWarning(message, context);
 }
        private void ApplyDictionaryModifications(UnityEngine.Object unityObject)
        {
            object dictionaryObj = GetInstanceFromPath(this.Path, unityObject);

            if (dictionaryObj == null)
            {
                // The dictionary has been deleted on the prefab;
                // that supersedes our dictionary modifications.
                return;
            }

            var type = dictionaryObj.GetType();

            if (!type.ImplementsOpenGenericInterface(typeof(IDictionary <,>)))
            {
                // A value change has changed the target modified value to
                // not be a dictionary - that also supersedes this modification.
                return;
            }

            var typeArgs = type.GetArgumentsOfInheritedOpenGenericInterface(typeof(IDictionary <,>));

            var iType = typeof(IDictionary <,>).MakeGenericType(typeArgs);

            //
            // First, remove keys
            //

            if (this.DictionaryKeysRemoved != null && this.DictionaryKeysRemoved.Length > 0)
            {
                MethodInfo method     = iType.GetMethod("Remove", new Type[] { typeArgs[0] });
                object[]   parameters = new object[1];

                for (int i = 0; i < this.DictionaryKeysRemoved.Length; i++)
                {
                    parameters[0] = this.DictionaryKeysRemoved[i];

                    // Ensure the key value is safe to add
                    if (object.ReferenceEquals(parameters[0], null) || !typeArgs[0].IsAssignableFrom(parameters[0].GetType()))
                    {
                        continue;
                    }

                    method.Invoke(dictionaryObj, parameters);
                }
            }

            //
            // Then, add keys
            //

            if (this.DictionaryKeysAdded != null && this.DictionaryKeysAdded.Length > 0)
            {
                MethodInfo method     = iType.GetMethod("set_Item", typeArgs);
                object[]   parameters = new object[2];

                // Get default value to set key to
                parameters[1] = typeArgs[1].IsValueType ? Activator.CreateInstance(typeArgs[1]) : null;

                for (int i = 0; i < this.DictionaryKeysAdded.Length; i++)
                {
                    parameters[0] = this.DictionaryKeysAdded[i];

                    // Ensure the key value is safe to add
                    if (object.ReferenceEquals(parameters[0], null) || !typeArgs[0].IsAssignableFrom(parameters[0].GetType()))
                    {
                        continue;
                    }

                    method.Invoke(dictionaryObj, parameters);
                }
            }
        }
Example #35
0
 public UnityEventFunction(SerializedProperty listener, UnityEngine.Object target, MethodInfo method, PersistentListenerMode mode)
 {
     this.m_Listener = listener;
     this.m_Target = target;
     this.m_Method = method;
     this.m_Mode = mode;
 }
 public void UnregisterPersistentListener()
 {
   this.m_MethodName = string.Empty;
   this.m_Target = (UnityEngine.Object) null;
 }
        internal static bool TryReflectVariable(out MemberInfo variableInfo, out UnityReflectionException exception, UnityObject reflectionTarget, string name)
        {
            #if !NETFX_CORE
            variableInfo = null;

            Type type = reflectionTarget.GetType();
            MemberTypes types = MemberTypes.Property | MemberTypes.Field;
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;

            MemberInfo[] variables = type.GetMember(name, types, flags);

            if (variables.Length == 0)
            {
                exception = new UnityReflectionException(string.Format("No matching field or property found: '{0}.{1}'", type.Name, name));
                return false;
            }

            variableInfo = variables[0]; // Safe, because there can't possibly be more than one variable of the same name
            exception = null;
            return true;
            #else
            throw new Exception("Reflection is not supported in .NET Core.");
            #endif
        }
Example #38
0
 public static extern void BeginSample(string name, UnityEngine.Object targetObject);
Example #39
0
 public AddVisualScriptToObjectAction(string assetPath, Type componentType, UnityEngine.Object instance = null)
 {
     AssetPath     = assetPath;
     Instance      = instance;
     ComponentType = componentType;
 }
Example #40
0
 public static void LogError(object message, Object context = null)
 {
     Debug.LogError(message, context);
 }
Example #41
0
 public static extern int GetRuntimeMemorySize(UnityEngine.Object o);
Example #42
0
 public static void LogWarning(string type, object message, Object context = null)
 {
     Debug.LogWarning(type + ": " + message, context);
 }
 protected override string GetObjectName(Object asset)
 {
     return(asset.name);
 }
Example #44
0
 /// <summary>
 /// Signals the persistence layer to monitor the component
 /// </summary>
 /// <param name="target"></param>
 public static void Monitor(Object target)
 {
     MonitorSignal.Emit(target);
 }
Example #45
0
        /// <summary>
        /// Given a camera and selection rect (in screen space) return a Dictionary containing the number of faces touched by the rect.
        /// </summary>
        /// <param name="camera"></param>
        /// <param name="pickerRect"></param>
        /// <param name="selection"></param>
        /// <param name="renderTextureWidth"></param>
        /// <param name="renderTextureHeight"></param>
        /// <returns></returns>
        public static Dictionary <ProBuilderMesh, HashSet <Face> > PickFacesInRect(
            Camera camera,
            Rect pickerRect,
            IList <ProBuilderMesh> selection,
            int renderTextureWidth  = -1,
            int renderTextureHeight = -1)
        {
            Dictionary <uint, SimpleTuple <ProBuilderMesh, Face> > map;
            Texture2D tex = RenderSelectionPickerTexture(camera, selection, out map, renderTextureWidth, renderTextureHeight);

            Color32[] pix = tex.GetPixels32();

            int ox          = System.Math.Max(0, Mathf.FloorToInt(pickerRect.x));
            int oy          = System.Math.Max(0, Mathf.FloorToInt((tex.height - pickerRect.y) - pickerRect.height));
            int imageWidth  = tex.width;
            int imageHeight = tex.height;
            int width       = Mathf.FloorToInt(pickerRect.width);
            int height      = Mathf.FloorToInt(pickerRect.height);

            UObject.DestroyImmediate(tex);

            Dictionary <ProBuilderMesh, HashSet <Face> > selected = new Dictionary <ProBuilderMesh, HashSet <Face> >();
            SimpleTuple <ProBuilderMesh, Face>           hit;
            HashSet <Face> faces = null;
            HashSet <uint> used  = new HashSet <uint>();

#if PB_RENDER_PICKER_TEXTURE
            List <Color> rectImg = new List <Color>();
#endif

            for (int y = oy; y < System.Math.Min(oy + height, imageHeight); y++)
            {
                for (int x = ox; x < System.Math.Min(ox + width, imageWidth); x++)
                {
#if PB_RENDER_PICKER_TEXTURE
                    rectImg.Add(pix[y * imageWidth + x]);
#endif

                    uint v = SelectionPickerRenderer.DecodeRGBA(pix[y * imageWidth + x]);

                    if (used.Add(v) && map.TryGetValue(v, out hit))
                    {
                        if (selected.TryGetValue(hit.item1, out faces))
                        {
                            faces.Add(hit.item2);
                        }
                        else
                        {
                            selected.Add(hit.item1, new HashSet <Face>()
                            {
                                hit.item2
                            });
                        }
                    }
                }
            }

#if PB_RENDER_PICKER_TEXTURE
            if (width > 0 && height > 0)
            {
//              Debug.Log("used: \n" + used.Select(x => string.Format("{0} ({1})", x, EncodeRGBA(x))).ToString("\n"));
                Texture2D img = new Texture2D(width, height);
                img.SetPixels(rectImg.ToArray());
                img.Apply();
                byte[] bytes = img.EncodeToPNG();
                System.IO.File.WriteAllBytes("Assets/rect.png", bytes);
#if UNITY_EDITOR
                UnityEditor.AssetDatabase.Refresh();
#endif
                UObject.DestroyImmediate(img);
            }
#endif

            return(selected);
        }
 /// <summary>
 /// Construct a delegate that will target the given container with the specified method.
 /// </summary>
 public BaseSerializationDelegate(UnityObject methodContainer, string methodName)
 {
     MethodContainer = methodContainer;
     MethodName = methodName;
 }
Example #47
0
        /// <summary>
        /// Selects the vertex indexes contained within a rect (rectangular selection).
        /// </summary>
        /// <param name="camera">Use this camera to evaluate whether any vertices are inside the `rect`.</param>
        /// <param name="pickerRect">Rect is in GUI space, where 0,0 is the top left of the screen, and `width = cam.pixelWidth / pointsPerPixel`.</param>
        /// <param name="selection">The collection of objects to check for selectability. ProBuilder verifies whether these objects fall inside the `rect`.</param>
        /// <param name="doDepthTest">True to include mesh elements that are hidden; false otherwise</param>
        /// <param name="renderTextureWidth">Width of the texture. If not specified, ProBuilder uses auto sizing (matches the camera's texture width).</param>
        /// <param name="renderTextureHeight">Height of the texture. If not specified, ProBuilder uses auto sizing (matches the camera's texture height).</param>
        /// <returns>A dictionary of ProBuilderMesh objects and vertex indices that are in the selection `rect`. </returns>
        public static Dictionary <ProBuilderMesh, HashSet <int> > PickVerticesInRect(
            Camera camera,
            Rect pickerRect,
            IList <ProBuilderMesh> selection,
            bool doDepthTest,
            int renderTextureWidth  = -1,
            int renderTextureHeight = -1)
        {
            Dictionary <uint, SimpleTuple <ProBuilderMesh, int> > map;
            Dictionary <ProBuilderMesh, HashSet <int> >           selected = new Dictionary <ProBuilderMesh, HashSet <int> >();

#if PB_RENDER_PICKER_TEXTURE
            List <Color> rectImg = new List <Color>();
#endif

            Texture2D tex = RenderSelectionPickerTexture(camera, selection, doDepthTest, out map, renderTextureWidth, renderTextureHeight);
            Color32[] pix = tex.GetPixels32();

            int ox          = System.Math.Max(0, Mathf.FloorToInt(pickerRect.x));
            int oy          = System.Math.Max(0, Mathf.FloorToInt((tex.height - pickerRect.y) - pickerRect.height));
            int imageWidth  = tex.width;
            int imageHeight = tex.height;
            int width       = Mathf.FloorToInt(pickerRect.width);
            int height      = Mathf.FloorToInt(pickerRect.height);

            UObject.DestroyImmediate(tex);

            SimpleTuple <ProBuilderMesh, int> hit;
            HashSet <int>  indexes = null;
            HashSet <uint> used    = new HashSet <uint>();

            for (int y = oy; y < System.Math.Min(oy + height, imageHeight); y++)
            {
                for (int x = ox; x < System.Math.Min(ox + width, imageWidth); x++)
                {
                    uint v = DecodeRGBA(pix[y * imageWidth + x]);

#if PB_RENDER_PICKER_TEXTURE
                    rectImg.Add(pix[y * imageWidth + x]);
#endif

                    if (used.Add(v) && map.TryGetValue(v, out hit))
                    {
                        if (selected.TryGetValue(hit.item1, out indexes))
                        {
                            indexes.Add(hit.item2);
                        }
                        else
                        {
                            selected.Add(hit.item1, new HashSet <int>()
                            {
                                hit.item2
                            });
                        }
                    }
                }
            }

            var coincidentSelection = new Dictionary <ProBuilderMesh, HashSet <int> >();

            // workaround for picking vertices that share a position but are not shared
            foreach (var meshSelection in selected)
            {
                var positions      = meshSelection.Key.positionsInternal;
                var sharedVertices = meshSelection.Key.sharedVerticesInternal;
                var positionHash   = new HashSet <int>(meshSelection.Value.Select(x => VectorHash.GetHashCode(positions[sharedVertices[x][0]])));
                var collected      = new HashSet <int>();

                for (int i = 0, c = sharedVertices.Length; i < c; i++)
                {
                    var hash = VectorHash.GetHashCode(positions[sharedVertices[i][0]]);
                    if (positionHash.Contains(hash))
                    {
                        collected.Add(i);
                    }
                }

                coincidentSelection.Add(meshSelection.Key, collected);
            }
            selected = coincidentSelection;

#if PB_RENDER_PICKER_TEXTURE
            if (width > 0 && height > 0)
            {
                Texture2D img = new Texture2D(width, height);
                img.SetPixels(rectImg.ToArray());
                img.Apply();
                System.IO.File.WriteAllBytes("Assets/rect_" + s_RenderTextureFormat.ToString() + ".png", img.EncodeToPNG());
#if UNITY_EDITOR
                UnityEditor.AssetDatabase.Refresh();
#endif
                UObject.DestroyImmediate(img);
            }
#endif

            return(selected);
        }
Example #48
0
 /// <summary>
 /// Writes error to console. Works only when Debugger is Enabled.
 /// </summary>
 /// <param name="message">Error to write.</param>
 /// <param name="context">Context.</param>
 public static void LogError(string message, Object context = null)
 {
     if (LogLevelEnabled(LogLevel.Error))
     {
         Debug.LogError(message, context);
     }
 }
Example #49
0
        /// <summary>
        /// Selects the <see cref="Edge" /> objects contained within a rect (rectangular selection).
        /// </summary>
        /// <param name="camera">Use this camera to evaluate whether any edge object(s) are inside the `rect`.</param>
        /// <param name="pickerRect">Rect is in GUI space, where 0,0 is the top left of the screen, and `width = cam.pixelWidth / pointsPerPixel`.</param>
        /// <param name="selection">The collection of objects to check for selectability. ProBuilder verifies whether these objects fall inside the `rect`.</param>
        /// <param name="doDepthTest">True to include mesh elements that are hidden; false otherwise</param>
        /// <param name="renderTextureWidth">Width of the texture. If not specified, ProBuilder uses auto sizing (matches the camera's texture width).</param>
        /// <param name="renderTextureHeight">Height of the texture. If not specified, ProBuilder uses auto sizing (matches the camera's texture height).</param>
        /// <returns>A dictionary of ProBuilderMesh and Edge objects that are in the selection `rect`. </returns>
        public static Dictionary <ProBuilderMesh, HashSet <Edge> > PickEdgesInRect(
            Camera camera,
            Rect pickerRect,
            IList <ProBuilderMesh> selection,
            bool doDepthTest,
            int renderTextureWidth  = -1,
            int renderTextureHeight = -1)
        {
            var selected = new Dictionary <ProBuilderMesh, HashSet <Edge> >();

#if PB_RENDER_PICKER_TEXTURE
            List <Color> rectImg = new List <Color>();
#endif

            Dictionary <uint, SimpleTuple <ProBuilderMesh, Edge> > map;
            Texture2D tex = RenderSelectionPickerTexture(camera, selection, doDepthTest, out map, renderTextureWidth, renderTextureHeight);
            Color32[] pix = tex.GetPixels32();

#if PB_RENDER_PICKER_TEXTURE
            System.IO.File.WriteAllBytes("Assets/edge_scene.png", tex.EncodeToPNG());
#endif

            int ox          = System.Math.Max(0, Mathf.FloorToInt(pickerRect.x));
            int oy          = System.Math.Max(0, Mathf.FloorToInt((tex.height - pickerRect.y) - pickerRect.height));
            int imageWidth  = tex.width;
            int imageHeight = tex.height;
            int width       = Mathf.FloorToInt(pickerRect.width);
            int height      = Mathf.FloorToInt(pickerRect.height);
            UObject.DestroyImmediate(tex);

            var pixelCount = new Dictionary <uint, uint>();

            for (int y = oy; y < System.Math.Min(oy + height, imageHeight); y++)
            {
                for (int x = ox; x < System.Math.Min(ox + width, imageWidth); x++)
                {
#if PB_RENDER_PICKER_TEXTURE
                    rectImg.Add(pix[y * imageWidth + x]);
#endif
                    uint v = DecodeRGBA(pix[y * imageWidth + x]);

                    if (v == k_PickerHashNone || v == k_PickerHashMax)
                    {
                        continue;
                    }

                    if (!pixelCount.ContainsKey(v))
                    {
                        pixelCount.Add(v, 1);
                    }
                    else
                    {
                        pixelCount[v] = pixelCount[v] + 1;
                    }
                }
            }

            foreach (var kvp in pixelCount)
            {
                SimpleTuple <ProBuilderMesh, Edge> hit;

                if (kvp.Value > k_MinEdgePixelsForValidSelection && map.TryGetValue(kvp.Key, out hit))
                {
                    HashSet <Edge> edges = null;

                    if (selected.TryGetValue(hit.item1, out edges))
                    {
                        edges.Add(hit.item2);
                    }
                    else
                    {
                        selected.Add(hit.item1, new HashSet <Edge>()
                        {
                            hit.item2
                        });
                    }
                }
            }

#if PB_RENDER_PICKER_TEXTURE
            if (width > 0 && height > 0)
            {
                Texture2D img = new Texture2D(width, height);
                img.SetPixels(rectImg.ToArray());
                img.Apply();
                System.IO.File.WriteAllBytes("Assets/edge_rect_" + s_RenderTextureFormat.ToString() + ".png", img.EncodeToPNG());
#if UNITY_EDITOR
                UnityEditor.AssetDatabase.Refresh();
#endif
                UObject.DestroyImmediate(img);
            }
#endif

            return(selected);
        }
Example #50
0
 /// <summary>
 /// Writes warning to console. Works only when Debugger is Enabled.
 /// </summary>
 /// <param name="message">Warning to write.</param>
 /// <param name="context">Context.</param>
 public static void LogWarning(string message, Object context = null)
 {
     if (LogLevelEnabled(LogLevel.Warning))
     {
         Debug.LogWarning(message, context);
     }
 }
 protected override void OnStartRunning()
 {
     _player = Object.FindObjectOfType <Player>();
 }
Example #52
0
 public bool Member(MemberInfo info, object rawTarget, UnityObject unityTarget, int id, bool ignoreComposition)
 {
     EditorMember member;
     return Member(info, rawTarget, unityTarget, id, ignoreComposition, out member);
 }
 public static string GetPath(this UnityEngine.Object obj)
 {
     return(AssetDatabase.GetAssetPath(obj.GetInstanceID()));
 }
Example #54
0
 public PrefabProvider(UnityEngine.Object prefab)
 {
     Assert.IsNotNull(prefab);
     _prefab = prefab;
 }
Example #55
0
 public override void DeleteAsset(UnityEngine.Object Asset)
 {
 }
 public int StoreObjectReference(UnityObject obj)
 {
     throw new NotSupportedException("UnityEngine.Object references are not supported " +
         "with this serialization operator (obj=" + obj + ")");
 }
 /// <summary>
 /// Gets the backing field for a public interface property that also has a proxy backing field to serialize
 /// <see cref="UnityEngine.Object"/>s that implement the interface.
 /// </summary>
 /// <returns>The current value of the <typeparamref name="T"/> backing field.</returns>
 /// <param name="interfaceBackingField">Interface backing field.</param>
 /// <param name="objectBackingField">
 /// Serialized backing field for a <see cref="UnityEngine.Object"/> that implements <typeparamref name="T"/>.
 /// </param>
 /// <typeparam name="T">The interface to which the backing field should be restricted.</typeparam>
 public static T GetInterfaceBackingField <T>(ref T interfaceBackingField, UnityEngine.Object objectBackingField)
     where T : class
 {
     return(interfaceBackingField =
                interfaceBackingField == null ? objectBackingField as T : interfaceBackingField);
 }