Exemple #1
0
		internal static Rhino.NativeGenerator Init(ScriptableObject scope, bool @sealed)
		{
			// Generator
			// Can't use "NativeGenerator().exportAsJSClass" since we don't want
			// to define "Generator" as a constructor in the top-level scope.
			Rhino.NativeGenerator prototype = new Rhino.NativeGenerator();
			if (scope != null)
			{
				prototype.SetParentScope(scope);
				prototype.SetPrototype(GetObjectPrototype(scope));
			}
			prototype.ActivatePrototypeMap(MAX_PROTOTYPE_ID);
			if (@sealed)
			{
				prototype.SealObject();
			}
			// Need to access Generator prototype when constructing
			// Generator instances, but don't have a generator constructor
			// to use to find the prototype. Use the "associateValue"
			// approach instead.
			if (scope != null)
			{
				scope.AssociateValue(GENERATOR_TAG, prototype);
			}
			return prototype;
		}
Exemple #2
0
		public Environment(ScriptableObject scope)
		{
			SetParentScope(scope);
			object ctor = ScriptRuntime.GetTopLevelProp(scope, "Environment");
			if (ctor != null && ctor is Scriptable)
			{
				Scriptable s = (Scriptable)ctor;
				SetPrototype((Scriptable)s.Get("prototype", s));
			}
		}
Exemple #3
0
		public static void DefineClass(ScriptableObject scope)
		{
			try
			{
				ScriptableObject.DefineClass<Rhino.Tools.Shell.Environment>(scope);
			}
			catch (Exception e)
			{
				throw new Exception(e.Message);
			}
		}
Exemple #4
0
		/// <summary>Associate ClassCache object with the given top-level scope.</summary>
		/// <remarks>
		/// Associate ClassCache object with the given top-level scope.
		/// The ClassCache object can only be associated with the given scope once.
		/// </remarks>
		/// <param name="topScope">scope to associate this ClassCache object with.</param>
		/// <returns>
		/// true if no previous ClassCache objects were embedded into
		/// the scope and this ClassCache were successfully associated
		/// or false otherwise.
		/// </returns>
		/// <seealso cref="Get(Scriptable)">Get(Scriptable)</seealso>
		public virtual bool Associate(ScriptableObject topScope)
		{
			if (topScope.GetParentScope() != null)
			{
				// Can only associate cache with top level scope
				throw new ArgumentException();
			}
			if (this == topScope.AssociateValue(AKEY, this))
			{
				associatedScope = topScope;
				return true;
			}
			return false;
		}
		protected virtual void SetUp()
		{
			Context cx = Context.Enter();
			try
			{
				global = cx.InitStandardObjects();
				string[] names = new string[] { "f", "g" };
				global.DefineFunctionProperties(names, typeof(DefineFunctionPropertiesTest), ScriptableObject.DONTENUM);
			}
			finally
			{
				Context.Exit();
			}
		}
Exemple #6
0
		/// <summary>
		/// Make glue object implementing interface cl that will
		/// call the supplied JS function when called.
		/// </summary>
		/// <remarks>
		/// Make glue object implementing interface cl that will
		/// call the supplied JS function when called.
		/// Only interfaces were all methods have the same signature is supported.
		/// </remarks>
		/// <returns>
		/// The glue object or null if <tt>cl</tt> is not interface or
		/// has methods with different signatures.
		/// </returns>
		internal static object Create(Context cx, Type cl, ScriptableObject @object)
		{
			if (!cl.IsInterface)
			{
				throw new ArgumentException();
			}
			Scriptable topScope = ScriptRuntime.GetTopCallScope(cx);
			ClassCache cache = ClassCache.Get(topScope);
			Rhino.InterfaceAdapter adapter;
			adapter = (Rhino.InterfaceAdapter)cache.GetInterfaceAdapter(cl);
			ContextFactory cf = cx.GetFactory();
			if (adapter == null)
			{
				MethodInfo[] methods = cl.GetMethods();
				if (@object is Callable)
				{
					// Check if interface can be implemented by a single function.
					// We allow this if the interface has only one method or multiple 
					// methods with the same name (in which case they'd result in 
					// the same function to be invoked anyway).
					int length = methods.Length;
					if (length == 0)
					{
						throw Context.ReportRuntimeError1("msg.no.empty.interface.conversion", cl.FullName);
					}
					if (length > 1)
					{
						string methodName = methods[0].Name;
						for (int i = 1; i < length; i++)
						{
							if (!methodName.Equals(methods[i].Name))
							{
								throw Context.ReportRuntimeError1("msg.no.function.interface.conversion", cl.FullName);
							}
						}
					}
				}
				adapter = new Rhino.InterfaceAdapter(cf, cl);
				cache.CacheInterfaceAdapter(cl, adapter);
			}
			return VMBridge.instance.NewInterfaceProxy(adapter.proxyHelper, cf, adapter, @object, topScope);
		}
Exemple #7
0
        public JSTestRunner(string initSnapshotName, IDictionary<string, string> planArguments, IJSTestProvider provider)
        {
            this.ctx = Context.enter ();
            this.provider = provider;
            this.initSnapshotName = initSnapshotName;
            var tests = provider.GetTestDrivers().SelectMany(d =>
                                               d.Tests.Select (t => new { Driver = d, Name = t}));

            this.planArguments = planArguments;

            MachineInitFunc initFunc = PossiblyInitializeMachine;

            this.scope = ctx.initStandardObjects();
            foreach(var thisTest in tests)
            {
                var test = thisTest;
                TestFunc func = delegate(IMachine machine, IDictionary<string, string> arguments, ITestResultBin bin)
                {
                    return test.Driver.RunTest(test.Name, machine, bin, arguments);
                };

                scope.defineProperty(test.Name, new CallableTest(func, initFunc, planArguments, provider), ScriptableObject.READONLY + ScriptableObject.PERMANENT);
            }

            var jsArgsObject = ctx.newObject(scope);
            foreach(var arg in planArguments)
            {
                jsArgsObject.put (arg.Key, jsArgsObject, arg.Value);
            }

            foreach(var name in new[] { "args", "Args", "ARGS"})
            {
                scope.defineProperty(name, jsArgsObject, ScriptableObject.READONLY + ScriptableObject.PERMANENT);
            }

            scope.defineProperty("Debug", new DebugFunction(), ScriptableObject.READONLY + ScriptableObject.PERMANENT);

            ssFunc = new SnapshotFunction(initFunc, provider);

            scope.defineProperty("Snapshot", ssFunc, ScriptableObject.READONLY + ScriptableObject.PERMANENT);
        }
Exemple #8
0
		internal static void Init(ScriptableObject scope, bool @sealed)
		{
			// Iterator
			Rhino.NativeIterator iterator = new Rhino.NativeIterator();
			iterator.ExportAsJSClass(MAX_PROTOTYPE_ID, scope, @sealed);
			// Generator
			NativeGenerator.Init(scope, @sealed);
			// StopIteration
			NativeObject obj = new NativeIterator.StopIteration();
			obj.SetPrototype(GetObjectPrototype(scope));
			obj.SetParentScope(scope);
			if (@sealed)
			{
				obj.SealObject();
			}
			ScriptableObject.DefineProperty(scope, STOP_ITERATION, obj, ScriptableObject.DONTENUM);
			// Use "associateValue" so that generators can continue to
			// throw StopIteration even if the property of the global
			// scope is replaced or deleted.
			scope.AssociateValue(ITERATOR_TAG, obj);
		}
		public virtual void TestStrictModeError()
		{
			contextFactory = new StrictModeApiTest.MyContextFactory();
			Context cx = contextFactory.EnterContext();
			try
			{
				global = cx.InitStandardObjects();
				try
				{
					RunScript("({}.nonexistent);");
					NUnit.Framework.Assert.Fail();
				}
				catch (EvaluatorException e)
				{
					NUnit.Framework.Assert.IsTrue(e.Message.StartsWith("Reference to undefined property"));
				}
			}
			finally
			{
				Context.Exit();
			}
		}
		private static void Internal_CreateScriptableObject(ScriptableObject self){}
		private static object Evaluate(Context cx, ScriptableObject scope, string source)
		{
			return cx.EvaluateString(scope, source, "<eval>", 1, null);
		}
Exemple #12
0
    static void CreateSRP0301()
    {
        var instance = ScriptableObject.CreateInstance <SRP0301>();

        UnityEditor.AssetDatabase.CreateAsset(instance, "Assets/SRP0301.asset");
    }
Exemple #13
0
        public TChartEntity Convert(ChartJsonData chartJsonData)
        {
            var chart = ScriptableObject.CreateInstance <TChartEntity>();

            return(Convert(chartJsonData, chart));
        }
 void Start()
 {
     rotCalc = ScriptableObject.CreateInstance <RotationCalculator>();
     StartCoroutine(ModifyAngle());
 }
Exemple #15
0
 /// <summary>
 /// Show disabled reference to a scriptable object object in custom editor
 /// </summary>
 /// <typeparam name="T"></typeparam>
 public static void ShowSOReference(ScriptableObject so)
 {
     GUI.enabled = false;
     EditorGUILayout.ObjectField("Script", MonoScript.FromScriptableObject(so), typeof(ScriptableObject), false);
     GUI.enabled = true;
 }
Exemple #16
0
		public static void SetBuiltinProtoAndParent(ScriptableObject @object, Scriptable scope, TopLevel.Builtins type)
		{
			scope = ScriptableObject.GetTopLevelScope(scope);
			@object.SetParentScope(scope);
			@object.SetPrototype(TopLevel.GetBuiltinPrototype(scope, type));
		}
Exemple #17
0
    private void Awake()
    {
        // Only allow one instance at runtime.
        if (instance != null)
        {
            enabled = false;
            DestroyImmediate(this);
            return;
        }

        instance = this;

        Debug.Log("Unity v" + Application.unityVersion + ", " +
                  "Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " +
                  "OVRPlugin v" + OVRPlugin.version + ", " +
                  "SDK v" + OVRPlugin.nativeSDKVersion + ".");

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
        var supportedTypes =
            UnityEngine.Rendering.GraphicsDeviceType.Direct3D11.ToString() + ", " +
            UnityEngine.Rendering.GraphicsDeviceType.Direct3D12.ToString();

        if (!supportedTypes.Contains(SystemInfo.graphicsDeviceType.ToString()))
        {
            Debug.LogWarning("VR rendering requires one of the following device types: (" + supportedTypes + "). Your graphics device: " + SystemInfo.graphicsDeviceType.ToString());
        }
#endif

        // Detect whether this platform is a supported platform
        RuntimePlatform currPlatform = Application.platform;
        isSupportedPlatform |= currPlatform == RuntimePlatform.Android;
        //isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer;
        isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor;
        isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer;
        isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor;
        isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer;
        if (!isSupportedPlatform)
        {
            Debug.LogWarning("This platform is unsupported");
            return;
        }

#if UNITY_ANDROID && !UNITY_EDITOR
        // We want to set up our touchpad messaging system
        OVRTouchpad.Create();

        // Turn off chromatic aberration by default to save texture bandwidth.
        chromatic = false;
#endif

#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
        enableMixedReality = false;                     // we should never start the standalone game in MxR mode, unless the command-line parameter is provided
#endif

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
        bool loadMrcConfig   = LoadMixedRealityCaptureConfigurationFileFromCmd();
        bool createMrcConfig = CreateMixedRealityCaptureConfigurationFileFromCmd();

        if (loadMrcConfig || createMrcConfig)
        {
            OVRMixedRealityCaptureSettings mrcSettings = ScriptableObject.CreateInstance <OVRMixedRealityCaptureSettings>();
            mrcSettings.ReadFrom(this);
            if (loadMrcConfig)
            {
                mrcSettings.CombineWithConfigurationFile();
                mrcSettings.ApplyTo(this);
            }
            if (createMrcConfig)
            {
                mrcSettings.WriteToConfigurationFile();
            }
            ScriptableObject.Destroy(mrcSettings);
        }

        if (MixedRealityEnabledFromCmd())
        {
            enableMixedReality = true;
        }

        if (enableMixedReality)
        {
            Debug.Log("OVR: Mixed Reality mode enabled");
            if (UseDirectCompositionFromCmd())
            {
                compositionMethod = CompositionMethod.Direct;
            }
            if (UseExternalCompositionFromCmd())
            {
                compositionMethod = CompositionMethod.External;
            }
            Debug.Log("OVR: CompositionMethod : " + compositionMethod);
        }
#endif

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
        if (enableAdaptiveResolution && !OVRManager.IsAdaptiveResSupportedByEngine())
        {
            enableAdaptiveResolution = false;
            UnityEngine.Debug.LogError("Your current Unity Engine " + Application.unityVersion + " might have issues to support adaptive resolution, please disable it under OVRManager");
        }
#endif

        Initialize();

        if (resetTrackerOnLoad)
        {
            display.RecenterPose();
        }

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
        // Force OcculusionMesh on all the time, you can change the value to false if you really need it be off for some reasons,
        // be aware there are performance drops if you don't use occlusionMesh.
        OVRPlugin.occlusionMesh = true;
#endif
    }
Exemple #18
0
		/// <summary>Initialize the standard objects.</summary>
		/// <remarks>
		/// Initialize the standard objects.
		/// Creates instances of the standard objects and their constructors
		/// (Object, String, Number, Date, etc.), setting up 'scope' to act
		/// as a global object as in ECMA 15.1.<p>
		/// This method must be called to initialize a scope before scripts
		/// can be evaluated in that scope.<p>
		/// This method does not affect the Context it is called upon.
		/// </remarks>
		/// <param name="scope">
		/// the scope to initialize, or null, in which case a new
		/// object will be created to serve as the scope
		/// </param>
		/// <returns>
		/// the initialized scope. The method returns the value of the scope
		/// argument if it is not null or newly allocated scope object which
		/// is an instance
		/// <see cref="ScriptableObject">ScriptableObject</see>
		/// .
		/// </returns>
		public Scriptable InitStandardObjects(ScriptableObject scope)
		{
			return InitStandardObjects(scope, false);
		}
Exemple #19
0
        /**
         * <summary>Restores the class's data from a saved string.</summary>
         * <param name = "data">The saved string to restore from</param>
         * <param name = "subScene">If set, only data for a given subscene will be loaded. If null, only data for the active scene will be loaded</param>
         * <returns>True if the data was successfully restored</returns>
         */
        public bool LoadData(string dataString, SubScene subScene = null)
        {
            if (string.IsNullOrEmpty(dataString))
            {
                return(false);
            }

            string[] dataArray = dataString.Split(SaveSystem.colon[0]);

            // ID
            string listName = AdvGame.PrepareStringForLoading(dataArray[0]);

            resumeIndices = new int[0];

            // Resume
            string[] resumeData = dataArray[1].Split("]"[0]);
            if (resumeData.Length > 0)
            {
                List <int> resumeIndexList = new List <int>();
                for (int i = 0; i < resumeData.Length; i++)
                {
                    int resumeIndex = -1;
                    if (int.TryParse(resumeData[i], out resumeIndex) && resumeIndex >= 0)
                    {
                        resumeIndexList.Add(resumeIndex);
                    }
                }
                resumeIndices = resumeIndexList.ToArray();
            }

            // StartIndex
            int.TryParse(dataArray[2], out startIndex);

            // Skip queue
            int j = 0;

            int.TryParse(dataArray[3], out j);
            inSkipQueue = (j == 1) ? true : false;

            // IsRunning
            j = 0;
            int.TryParse(dataArray[4], out j);
            isRunning = (j == 1) ? true : false;

            // Conversation on end
            int convID = 0;

            int.TryParse(dataArray[5], out convID);
            if (convID != 0)
            {
                conversationOnEnd = Serializer.returnComponent <Conversation> (convID, (subScene != null) ? subScene.gameObject : null);
            }

            // Parameter data
            parameterData = dataArray[6];

            // ActionList
            int ID = 0;

            if (int.TryParse(listName, out ID))
            {
                // Scene
                ConstantID constantID = Serializer.returnComponent <ConstantID> (ID, (subScene != null) ? subScene.gameObject : null);
                if (constantID != null && constantID.GetComponent <ActionList>() != null)
                {
                    actionList = constantID.GetComponent <ActionList>();
                    return(true);
                }
            }
            else
            {
                // Asset file
                ActionListAsset tempAsset = ScriptableObject.CreateInstance <ActionListAsset> ();
                actionListAsset = AssetLoader.RetrieveAsset <ActionListAsset> (tempAsset, listName);
                if (actionListAsset != null && actionListAsset != tempAsset)
                {
                    return(true);
                }

                ACDebug.LogWarning("Could not restore data related to the ActionList asset '" + listName + "' - to restore it correctly, the asset must be placed in a folder named Resources.");
            }
            return(false);
        }
Exemple #20
0
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        foreach (string asset in importedAssets)
        {
            if (!filePath.Equals(asset))
            {
                continue;
            }

            using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                var book = new HSSFWorkbook(stream);

                foreach (string sheetName in sheetNames)
                {
                    var exportPath = "Assets/Resources/Data/" + sheetName + ".asset";

                    // check scriptable object
                    var data = (Entity_senpou_mst)AssetDatabase.LoadAssetAtPath(exportPath, typeof(Entity_senpou_mst));
                    if (data == null)
                    {
                        data = ScriptableObject.CreateInstance <Entity_senpou_mst>();
                        AssetDatabase.CreateAsset((ScriptableObject)data, exportPath);
                        data.hideFlags = HideFlags.NotEditable;
                    }
                    data.param.Clear();

                    // check sheet
                    var sheet = book.GetSheet(sheetName);
                    if (sheet == null)
                    {
                        Debug.LogError("[QuestData] sheet not found:" + sheetName);
                        continue;
                    }

                    // add infomation
                    for (int i = 1; i <= sheet.LastRowNum; i++)
                    {
                        IRow  row  = sheet.GetRow(i);
                        ICell cell = null;

                        var p = new Entity_senpou_mst.Param();

                        cell = row.GetCell(0); p.id = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(1); p.typ = (cell == null ? "" : cell.StringCellValue);
                        cell = row.GetCell(2); p.name = (cell == null ? "" : cell.StringCellValue);
                        cell = row.GetCell(3); p.effection = (cell == null ? "" : cell.StringCellValue);
                        cell = row.GetCell(4); p.each = (float)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(5); p.ratio = (float)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(6); p.term = (float)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(7); p.lv1 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(8); p.lv2 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(9); p.lv3 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(10); p.lv4 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(11); p.lv5 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(12); p.lv6 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(13); p.lv7 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(14); p.lv8 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(15); p.lv9 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(16); p.lv10 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(17); p.lv11 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(18); p.lv12 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(19); p.lv13 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(20); p.lv14 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(21); p.lv15 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(22); p.lv16 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(23); p.lv17 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(24); p.lv18 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(25); p.lv19 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(26); p.lv20 = (int)(cell == null ? 0 : cell.NumericCellValue);
                        cell = row.GetCell(27); p.shipFlg = (cell == null ? false : cell.BooleanCellValue);
                        cell = row.GetCell(28); p.onlySeaFlg = (cell == null ? false : cell.BooleanCellValue);
                        cell = row.GetCell(29); p.nameEng = (cell == null ? "" : cell.StringCellValue);
                        cell = row.GetCell(30); p.effectionEng = (cell == null ? "" : cell.StringCellValue);

                        data.param.Add(p);
                    }

                    // save scriptable object
                    ScriptableObject obj = AssetDatabase.LoadAssetAtPath(exportPath, typeof(ScriptableObject)) as ScriptableObject;
                    EditorUtility.SetDirty(obj);
                }
            }
        }
    }
 internal static T GetWindowDontShow <T>() where T : EditorWindow
 {
     UnityEngine.Object[] windows = Resources.FindObjectsOfTypeAll(typeof(T));
     return((windows.Length > 0) ? (T)windows[0] : ScriptableObject.CreateInstance <T>());
 }
Exemple #22
0
    // Token: 0x0600000B RID: 11 RVA: 0x000029E8 File Offset: 0x00000BE8
    public override Object LoadResource()
    {
        bool flag = this.Resource == null;

        if (flag)
        {
            GameObject          gameObject          = Resources.Load <GameObject>("WorldEntities/Eggs/BonesharkEgg");
            GameObject          gameObject2         = AssetBundleLoader.LoadedBundle.LoadAsset("Capsule 1") as GameObject;
            SkinnedMeshRenderer componentInChildren = gameObject.GetComponentInChildren <SkinnedMeshRenderer>();
            gameObject2.name = "GhostRayRedEgg";
            PrefabIdentifier prefabIdentifier = gameObject2.AddComponent <PrefabIdentifier>();
            gameObject2.AddComponent <LargeWorldEntity>().cellLevel = LargeWorldEntity.CellLevel.Near;
            prefabIdentifier.ClassId = this.Key;
            Rigidbody component = gameObject2.GetComponent <Rigidbody>();
            component.isKinematic = true;
            Pickupable  pickupable  = gameObject2.AddComponent <Pickupable>();
            CreatureEgg creatureEgg = gameObject2.AddComponent <CreatureEgg>();
            creatureEgg.daysBeforeHatching = 1.5f;
            gameObject2.AddComponent <EntityTag>().slotType = EntitySlot.Type.Small;
            WorldForces worldForces = gameObject2.AddComponent <WorldForces>();
            worldForces.handleGravity     = true;
            worldForces.underwaterGravity = 2f;
            worldForces.useRigidbody      = component;
            worldForces.aboveWaterGravity = 9.81f;
            worldForces.underwaterDrag    = 1f;
            worldForces.aboveWaterDrag    = 0.1f;
            worldForces.handleDrag        = true;
            SkyApplier   skyApplier = gameObject2.AddComponent <SkyApplier>();
            MeshRenderer component2 = gameObject2.GetComponent <MeshRenderer>();
            skyApplier.renderers = new Renderer[]
            {
                component2
            };
            skyApplier.anchorSky = Skies.Auto;
            Texture mainTexture  = component2.sharedMaterial.mainTexture;
            Texture mainTexture2 = component2.material.mainTexture;
            component2.material.shader       = componentInChildren.material.shader;
            component2.material.color        = new Color(0.75f, 0f, 0f);
            component2.sharedMaterial.shader = componentInChildren.sharedMaterial.shader;
            component2.material.SetFloat("_SpecInt", 16f);
            component2.material.SetFloat("_Shininess", 7.5f);
            component2.material.SetTexture("_SpecText", mainTexture2);
            LiveMixin liveMixin = gameObject2.AddComponent <LiveMixin>();
            liveMixin.data = ScriptableObject.CreateInstance <LiveMixinData>();
            LiveMixinData data = liveMixin.data;
            liveMixin.health      = 25f;
            data.maxHealth        = 25f;
            data.knifeable        = true;
            data.destroyOnDeath   = true;
            data.explodeOnDestroy = true;
            ResourceTracker resourceTracker = gameObject2.AddComponent <ResourceTracker>();
            resourceTracker.overrideTechType = TechType.GenericEgg;
            resourceTracker.prefabIdentifier = prefabIdentifier;
            resourceTracker.rb          = component;
            resourceTracker.pickupable  = pickupable;
            creatureEgg.overrideEggType = (TechType)6968;
            Animator animator = gameObject2.AddComponent <Animator>();
            creatureEgg.animator         = animator;
            creatureEgg.hatchingCreature = TechType.GhostRayRed;
            gameObject2.AddComponent <ScaleFixer>().scale = new Vector3(0.5f, 0.5f, 0.5f);
            this.Resource = gameObject2;
        }
        return(this.Resource);
    }
Exemple #23
0
        protected virtual TChartEntity Convert(ChartJsonData chartJsonData, TChartEntity chart)
        {
            chart.AudioSource = chartJsonData.AudioSource.Split('.')[0];
            chart.StartTime   = chartJsonData.StartTime;
            chart.Difficulty  = (TChartDifficulty)Enum.ToObject(typeof(TChartDifficulty), chartJsonData.Difficulty);

            // bpm changes
            var bpmChanges = new List <(float bpm, float position)>();

            bpmChanges.AddRange(chartJsonData.Timeline.OtherObjects.Where(o => o.type == (int)OtherObjectType.Bpm)
                                .Select(bpmChangeJsonData => (float.Parse(bpmChangeJsonData.value),
                                                              position: bpmChangeJsonData.measureIndex + bpmChangeJsonData.measurePosition.To01())));

            // speed changes
            chart.SpeedChanges = new List <SpeedChangeEntity>();
            foreach (var speedChange in chartJsonData.Timeline.OtherObjects.Where(o =>
                                                                                  o.type == (int)OtherObjectType.Speed))
            {
                chart.SpeedChanges.Add(new SpeedChangeEntity(speedChange));
            }

            // カスタムオブジェクト
            chart.OtherObjects = new List <OtherObjectEntity>();
            foreach (var jsonData in chartJsonData.Timeline.OtherObjects.Where(
                         o => o.type >= (int)OtherObjectType.Other))
            {
                chart.OtherObjects.Add(new OtherObjectEntity(jsonData));
            }

            chart.BpmChanges = new List <BpmChangeEntity>();

            var sortedBpmChanges = bpmChanges.OrderBy(bpmChange => bpmChange.position).ToList();

            // 最終 BPM を譜面の最後に配置する
            sortedBpmChanges.Add((sortedBpmChanges.Last().bpm, position: 1000f));

            // BPM の区間を計算する
            var beginTime = 0f;

            for (var i = 0; i < sortedBpmChanges.Count - 1; i++)
            {
                var begin = sortedBpmChanges[i];
                var end   = sortedBpmChanges[i + 1];

                // 1 小節の時間
                var unitTime = (60f / begin.bpm) * 4;

                var beginMeasureIndex = Mathf.FloorToInt(begin.position);
                var endMeasureIndex   = Mathf.FloorToInt(end.position);

                for (var measureIndex = beginMeasureIndex; measureIndex < endMeasureIndex; measureIndex++)
                {
                    var tempo = 1f;

                    if (chartJsonData.Timeline.Measures != null)
                    {
                        var tempoJsonData =
                            chartJsonData.Timeline.Measures.FirstOrDefault(a => a.index == measureIndex);

                        tempo = tempoJsonData == null ? 1f : tempoJsonData.beat.To01();
                    }

                    // 区間の秒数
                    var time = unitTime * tempo;

                    chart.BpmChanges.Add(new BpmChangeEntity
                    {
                        BeginPosition = measureIndex,
                        EndPosition   = measureIndex + 1,
                        BeginTime     = beginTime,
                        Duration      = time
                    });

                    beginTime += time;
                }
            }

            var noteGuidMap = new Dictionary <Guid, TNoteEntity>();

            // ノートを生成する
            chart.Notes = new List <TNoteEntity>();
            foreach (var noteJsonData in chartJsonData.Timeline.Notes)
            {
                // ノートの小節位置
                var noteMeasurePosition = noteJsonData.measureIndex + noteJsonData.measurePosition.To01();

                // 判定時間を取得する
                var judgeTime = chart.BpmChanges.Find(bpmRange => bpmRange.Between(noteMeasurePosition))
                                .GetJudgeTime(noteMeasurePosition);

                var note = ScriptableObject.CreateInstance <TNoteEntity>();
                note.Initialize(noteJsonData, judgeTime);
                note.name = $"note_{noteJsonData.guid}";

                noteGuidMap[noteJsonData.guid] = note;

                chart.Notes.Add(note);
            }

            // ノートラインを生成する
            chart.NoteLines = new List <TNoteLineEntity>();
            foreach (var noteLineJsonData in chartJsonData.Timeline.NoteLines)
            {
                var headNote = noteGuidMap[noteLineJsonData.head];
                var tailNote = noteGuidMap[noteLineJsonData.tail];

                // 横に繋がっているロングは除外する
                if (Mathf.Approximately(headNote.JudgeTime, tailNote.JudgeTime))
                {
                    continue;
                }

                var noteLine = ScriptableObject.CreateInstance <TNoteLineEntity>();
                noteLine.Initialize(noteLineJsonData, headNote, tailNote);
                chart.NoteLines.Add(noteLine);
            }

            chart.Measures = new List <MeasureEntity>();

            if (chartJsonData.Timeline.Measures != null)
            {
                // 小節を生成する
                foreach (var measureJsonData in chartJsonData.Timeline.Measures)
                {
                    try
                    {
                        // 判定時間を取得する
                        var judgeTime = chart.BpmChanges.Find(bpmRange => bpmRange.Between(measureJsonData.index))
                                        .GetJudgeTime(measureJsonData.index);

                        var measure = new MeasureEntity(measureJsonData, judgeTime);
                        chart.Measures.Add(measure);
                    }
                    catch (NullReferenceException e)
                    {
                        Debug.LogError(measureJsonData.index + " / " + e.Message);
                    }
                }
            }

            chart.Notes = chart.Notes.OrderBy(note => note.JudgeTime).ToList();

            return(chart);
        }
		protected override void DoInspectorGUI(ScriptableObject settings, ServiceItem item, System.Action onReset, GUISkin skin) {

			this.OnInspectorGUI(settings as GameDataSettings, item as GameDataServiceItem, onReset, skin);
			
		}
Exemple #25
0
		/// <summary>Initialize the standard objects.</summary>
		/// <remarks>
		/// Initialize the standard objects.
		/// Creates instances of the standard objects and their constructors
		/// (Object, String, Number, Date, etc.), setting up 'scope' to act
		/// as a global object as in ECMA 15.1.<p>
		/// This method must be called to initialize a scope before scripts
		/// can be evaluated in that scope.<p>
		/// This method does not affect the Context it is called upon.<p>
		/// This form of the method also allows for creating "sealed" standard
		/// objects. An object that is sealed cannot have properties added, changed,
		/// or removed. This is useful to create a "superglobal" that can be shared
		/// among several top-level objects. Note that sealing is not allowed in
		/// the current ECMA/ISO language specification, but is likely for
		/// the next version.
		/// </remarks>
		/// <param name="scope">
		/// the scope to initialize, or null, in which case a new
		/// object will be created to serve as the scope
		/// </param>
		/// <param name="sealed">
		/// whether or not to create sealed standard objects that
		/// cannot be modified.
		/// </param>
		/// <returns>
		/// the initialized scope. The method returns the value of the scope
		/// argument if it is not null or newly allocated scope object.
		/// </returns>
		/// <since>1.4R3</since>
		public virtual ScriptableObject InitStandardObjects(ScriptableObject scope, bool @sealed)
		{
			return ScriptRuntime.InitStandardObjects(this, scope, @sealed);
		}
        protected override JobHandle OnUpdate(JobHandle inputDependencies)
        {
            var mapEntity = this.mapQuery.GetSingletonEntity();
            var map       = this.EntityManager.GetMap(mapEntity);

            this.Job
            .WithCode(() =>
            {
                renderMapMarker.Begin();
                this.map.ClearAllTiles();

                var x = 0;
                var y = 0;

                RogueTile tile;
                for (int idx = 0; idx < map.Tiles.Length; idx++)
                {
                    tile = map.Tiles[idx];

                    if (map.RevealedTiles[idx])
                    {
                        switch (tile.Type)
                        {
                        case (TileType.Floor):
                            var floorTile = map.VisibleTiles[idx] ? this.floorTile : this.greyFloorTile;
                            this.map.SetTile(new Vector3Int(x, y, 0), floorTile);
                            break;

                        case (TileType.Wall):
                            var wallTile = map.VisibleTiles[idx] ? this.wallTile : this.greyWallTile;
                            this.map.SetTile(new Vector3Int(x, y, 0), wallTile);
                            break;
                        }
                    }

                    x += 1;

                    if (x > map.Width - 1)
                    {
                        x  = 0;
                        y += 1;
                    }
                }
                renderMapMarker.End();
            })
            .WithoutBurst()
            .Run();

            renderEntitiesMarker.Begin();
            this.entities.ClearAllTiles();

            this.Entities
            .ForEach((in Entity entity, in Position position, in Renderable renderable) =>
            {
                if (!this.tiles.TryGetValue(entity, out var tile))
                {
                    this.tiles.Add(entity, tile = ScriptableObject.CreateInstance <Tile>());
                }

                tile.sprite = this.glyphs[renderable.Glyph];
                tile.color  = renderable.Foreground;

                this.entities.SetTile(position.Value.AsVector3Int(), tile);
            })
Exemple #27
0
    public override void Tick()
    {
        if (IcaroSocket.Instance.isConnected())
        {
            List <string> messages = IcaroSocket.Instance.getMessages();
            if (messages.Count == 0)
            {
                return;
            }

            Secuence secuence = null;
            Dialog   dialog   = null;

            foreach (string s in messages)
            {
                GameEvent ge = GameEvent.CreateInstance <GameEvent>();
                ge.fromJSONObject(JSONObject.Create(s));

                // TODO Maybe this showmessage thing will be in another event manager
                if (ge.name == "show message")
                {
                    if (secuence == null && dialog == null)
                    {
                        secuence = ScriptableObject.CreateInstance <Secuence>();
                        secuence.init();
                        dialog = ScriptableObject.CreateInstance <Dialog>();
                        secuence.Root.Content = dialog;
                    }

                    dialog.addFragment();
                    Dialog.Fragment[] fragments = dialog.getFragments();
                    Dialog.Fragment   fragment  = fragments[fragments.Length - 1];
                    fragment.Name = "ChatterBotten";
                    fragment.Msg  = (string)ge.getParameter("message");
                }
                else if (ge.name == GameEvent.RECEIVE_TEXT_EVENT)
                {
                    if (ge.containsParameter("message"))
                    {
                        var msg  = (string)ge.getParameter("message");
                        var menu = GameObject.FindObjectOfType <MenuBehaviour>();
                        if (menu)
                        {
                            menu.AddLineToReceivedText(msg);
                        }
                    }
                }
                else
                {
                    Game.main.enqueueEvent(ge);
                    eventsSendedToGame.Add(ge.GetInstanceID(), ge);
                }
            }

            if (secuence != null)
            {
                GameEvent secuenceGE = new GameEvent();
                secuenceGE.Name = "start secuence";
                secuenceGE.setParameter("Secuence", secuence);
                secuenceGE.setParameter("syncronized", true);
                Game.main.enqueueEvent(secuenceGE);
                secuencesStarted.Add(secuenceGE.GetInstanceID(), secuenceGE);
            }
        }
    }
Exemple #28
0
		public static ScriptableObject InitStandardObjects(Context cx, ScriptableObject scope, bool @sealed)
		{
			if (scope == null)
			{
				scope = new NativeObject();
			}
			scope.AssociateValue(LIBRARY_SCOPE_KEY, scope);
			(new ClassCache()).Associate(scope);
			BaseFunction.Init(scope, @sealed);
			NativeObject.Init(scope, @sealed);
			Scriptable objectProto = ScriptableObject.GetObjectPrototype(scope);
			// Function.prototype.__proto__ should be Object.prototype
			Scriptable functionProto = ScriptableObject.GetClassPrototype(scope, "Function");
			functionProto.SetPrototype(objectProto);
			// Set the prototype of the object passed in if need be
			if (scope.GetPrototype() == null)
			{
				scope.SetPrototype(objectProto);
			}
			// must precede NativeGlobal since it's needed therein
			NativeError.Init(scope, @sealed);
			NativeGlobal.Init(cx, scope, @sealed);
			NativeArray.Init(scope, @sealed);
			if (cx.GetOptimizationLevel() > 0)
			{
				// When optimizing, attempt to fulfill all requests for new Array(N)
				// with a higher threshold before switching to a sparse
				// representation
				NativeArray.SetMaximumInitialCapacity(200000);
			}
			NativeString.Init(scope, @sealed);
			NativeBoolean.Init(scope, @sealed);
			NativeNumber.Init(scope, @sealed);
			NativeDate.Init(scope, @sealed);
			NativeMath.Init(scope, @sealed);
			NativeJSON.Init(scope, @sealed);
			NativeWith.Init(scope, @sealed);
			NativeCall.Init(scope, @sealed);
			NativeScript.Init(scope, @sealed);
			NativeIterator.Init(scope, @sealed);
			// Also initializes NativeGenerator
			bool withXml = cx.HasFeature(Context.FEATURE_E4X) && cx.GetE4xImplementationFactory() != null;
			// define lazy-loaded properties using their class name
			new LazilyLoadedCtor(scope, "RegExp", "org.mozilla.javascript.regexp.NativeRegExp", @sealed, true);
			new LazilyLoadedCtor(scope, "Packages", "org.mozilla.javascript.NativeJavaTopPackage", @sealed, true);
			new LazilyLoadedCtor(scope, "getClass", "org.mozilla.javascript.NativeJavaTopPackage", @sealed, true);
			new LazilyLoadedCtor(scope, "JavaAdapter", "org.mozilla.javascript.JavaAdapter", @sealed, true);
			new LazilyLoadedCtor(scope, "JavaImporter", "org.mozilla.javascript.ImporterTopLevel", @sealed, true);
			new LazilyLoadedCtor(scope, "Continuation", "org.mozilla.javascript.NativeContinuation", @sealed, true);
			foreach (string packageName in GetTopPackageNames())
			{
				new LazilyLoadedCtor(scope, packageName, "org.mozilla.javascript.NativeJavaTopPackage", @sealed, true);
			}
			if (withXml)
			{
				string xmlImpl = cx.GetE4xImplementationFactory().GetImplementationClassName();
				new LazilyLoadedCtor(scope, "XML", xmlImpl, @sealed, true);
				new LazilyLoadedCtor(scope, "XMLList", xmlImpl, @sealed, true);
				new LazilyLoadedCtor(scope, "Namespace", xmlImpl, @sealed, true);
				new LazilyLoadedCtor(scope, "QName", xmlImpl, @sealed, true);
			}
			if (scope is TopLevel)
			{
				((TopLevel)scope).CacheBuiltins();
			}
			return scope;
		}
Exemple #29
0
 // Create a standard Object-derived asset.
 public static void CreateAsset(Object asset, string pathName)
 {
     StartNameEditingIfProjectWindowExists(asset.GetInstanceID(), ScriptableObject.CreateInstance <DoCreateNewAsset>(), pathName, AssetPreview.GetMiniThumbnail(asset), null);
 }
Exemple #30
0
		public virtual void SetUp()
		{
			cx = Context.Enter();
			scope = cx.InitStandardObjects();
		}
Exemple #31
0
 // Create a folder
 public static void CreateFolder()
 {
     StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance <DoCreateFolder>(), "New Folder", EditorGUIUtility.IconContent(EditorResources.emptyFolderIconName).image as Texture2D, null);
 }
 private static SDK_BaseBoundaries GetBoundariesSDK()
 {
     if (boundariesSDK == null)
     {
         boundariesSDK = (VRTK_SDKManager.instance ? VRTK_SDKManager.instance.GetBoundariesSDK() : ScriptableObject.CreateInstance <SDK_FallbackBoundaries>());
     }
     return(boundariesSDK);
 }
Exemple #33
0
 public static void CreateScene()
 {
     StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance <DoCreateScene>(), "New Scene.unity", EditorGUIUtility.FindTexture(typeof(SceneAsset)), null);
 }
Exemple #34
0
    static void CreateIndex()
    {
        tk2dIndex newIndex = ScriptableObject.CreateInstance <tk2dIndex>();

        newIndex.version = tk2dIndex.CURRENT_VERSION;

        List <string> rebuildSpriteCollectionPaths = new List <string>();

        // check all prefabs to see if we can find any objects we are interested in
        List <string>  allPrefabPaths = new List <string>();
        Stack <string> paths          = new Stack <string>();

        paths.Push(Application.dataPath);
        while (paths.Count != 0)
        {
            string   path  = paths.Pop();
            string[] files = Directory.GetFiles(path, "*.prefab");
            foreach (var file in files)
            {
                allPrefabPaths.Add(file.Substring(Application.dataPath.Length - 6));
            }

            foreach (string subdirs in Directory.GetDirectories(path))
            {
                paths.Push(subdirs);
            }
        }

        // Check all prefabs
        int currPrefabCount = 1;

        foreach (string prefabPath in allPrefabPaths)
        {
            EditorUtility.DisplayProgressBar("Rebuilding Index", "Scanning project folder...", (float)currPrefabCount / (float)(allPrefabPaths.Count));

            GameObject iterGo = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
            if (!iterGo)
            {
                continue;
            }

            tk2dSpriteCollection     spriteCollection     = iterGo.GetComponent <tk2dSpriteCollection>();
            tk2dSpriteCollectionData spriteCollectionData = iterGo.GetComponent <tk2dSpriteCollectionData>();
            tk2dFont            font = iterGo.GetComponent <tk2dFont>();
            tk2dSpriteAnimation anim = iterGo.GetComponent <tk2dSpriteAnimation>();

            if (spriteCollection)
            {
                tk2dSpriteCollectionData thisSpriteCollectionData = spriteCollection.spriteCollection;
                if (thisSpriteCollectionData)
                {
                    if (thisSpriteCollectionData.version < 1)
                    {
                        rebuildSpriteCollectionPaths.Add(AssetDatabase.GetAssetPath(spriteCollection));
                    }
                    newIndex.AddSpriteCollectionData(thisSpriteCollectionData);
                }
            }
            else if (spriteCollectionData)
            {
                string guid    = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(spriteCollectionData));
                bool   present = false;
                foreach (var v in newIndex.GetSpriteCollectionIndex())
                {
                    if (v.spriteCollectionDataGUID == guid)
                    {
                        present = true;
                        break;
                    }
                }
                if (!present && guid != "")
                {
                    newIndex.AddSpriteCollectionData(spriteCollectionData);
                }
            }
            else if (font)
            {
                newIndex.AddOrUpdateFont(font);                 // unfortunate but necessary
            }
            else if (anim)
            {
                newIndex.AddSpriteAnimation(anim);
            }
            else
            {
                iterGo = null;
                System.GC.Collect();
            }

            tk2dEditorUtility.UnloadUnusedAssets();
            ++currPrefabCount;
        }
        EditorUtility.ClearProgressBar();

        // Create index
        AssetDatabase.CreateAsset(newIndex, indexPath);

        // unload all unused assets
        tk2dEditorUtility.UnloadUnusedAssets();

        // Rebuild invalid sprite collections
        if (rebuildSpriteCollectionPaths.Count > 0)
        {
            EditorUtility.DisplayDialog("Upgrade required",
                                        "Please wait while your sprite collection is upgraded.",
                                        "Ok");

            int count = 1;
            foreach (var scPath in rebuildSpriteCollectionPaths)
            {
                tk2dSpriteCollection sc = AssetDatabase.LoadAssetAtPath(scPath, typeof(tk2dSpriteCollection)) as tk2dSpriteCollection;
                EditorUtility.DisplayProgressBar("Rebuilding Sprite Collections", "Rebuilding Sprite Collection: " + sc.name, (float)count / (float)(rebuildSpriteCollectionPaths.Count));

                tk2dSpriteCollectionBuilder.Rebuild(sc);
                sc = null;

                tk2dEditorUtility.UnloadUnusedAssets();

                ++count;
            }

            EditorUtility.ClearProgressBar();
        }

        index = newIndex;
        tk2dSpriteGuiUtility.ResetCache();
    }
Exemple #35
0
        static private void CreateAudioMixer()
        {
            var icon = EditorGUIUtility.IconContent <AudioMixerController>().image as Texture2D;

            StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance <DoCreateAudioMixer>(), "NewAudioMixer.mixer", icon, null);
        }
Exemple #36
0
		private static void DefineReadOnlyProperty(ScriptableObject obj, string name, object value)
		{
			ScriptableObject.PutProperty(obj, name, value);
			obj.SetAttributes(name, ScriptableObject.READONLY | ScriptableObject.PERMANENT);
		}
Exemple #37
0
        void PrimarySetup()
        {
            SkillLocator component = characterPrefab.GetComponent <SkillLocator>();

            LanguageAPI.Add("EXAMPLESURVIVOR_PRIMARY_CROSSBOW_NAME", "Crossbow");
            LanguageAPI.Add("EXAMPLESURVIVOR_PRIMARY_CROSSBOW_DESCRIPTION", "Fire an arrow, dealing <style=cIsDamage>200% damage</style>.");

            // set up your primary skill def here!

            SkillDef mySkillDef = ScriptableObject.CreateInstance <SkillDef>();

            mySkillDef.activationState            = new SerializableEntityStateType(typeof(ExampleSurvivorFireArrow));
            mySkillDef.activationStateMachineName = "Weapon";
            mySkillDef.baseMaxStock                 = 1;
            mySkillDef.baseRechargeInterval         = 0f;
            mySkillDef.beginSkillCooldownOnSkillEnd = false;
            mySkillDef.canceledFromSprinting        = false;
            mySkillDef.fullRestockOnAssign          = true;
            mySkillDef.interruptPriority            = InterruptPriority.Any;
            mySkillDef.isBullets             = false;
            mySkillDef.isCombatSkill         = true;
            mySkillDef.mustKeyPress          = false;
            mySkillDef.noSprint              = true;
            mySkillDef.rechargeStock         = 1;
            mySkillDef.requiredStock         = 1;
            mySkillDef.shootDelay            = 0f;
            mySkillDef.stockToConsume        = 1;
            mySkillDef.icon                  = Assets.icon1;
            mySkillDef.skillDescriptionToken = "EXAMPLESURVIVOR_PRIMARY_CROSSBOW_DESCRIPTION";
            mySkillDef.skillName             = "EXAMPLESURVIVOR_PRIMARY_CROSSBOW_NAME";
            mySkillDef.skillNameToken        = "EXAMPLESURVIVOR_PRIMARY_CROSSBOW_NAME";

            LoadoutAPI.AddSkillDef(mySkillDef);

            component.primary = characterPrefab.AddComponent <GenericSkill>();


            SkillFamily newFamily = ScriptableObject.CreateInstance <SkillFamily>();

            newFamily.variants = new SkillFamily.Variant[1];
            LoadoutAPI.AddSkillFamily(newFamily);
            component.primary.SetFieldValue("_skillFamily", newFamily);
            SkillFamily skillFamily = component.primary.skillFamily;

            skillFamily.variants[0] = new SkillFamily.Variant
            {
                skillDef       = mySkillDef,
                unlockableName = "",
                viewableNode   = new ViewablesCatalog.Node(mySkillDef.skillNameToken, false, null)
            };



            // add this code after defining a new skilldef if you're adding an alternate skill

            /*Array.Resize(ref skillFamily.variants, skillFamily.variants.Length + 1);
             * skillFamily.variants[skillFamily.variants.Length - 1] = new SkillFamily.Variant
             * {
             *  skillDef = newSkillDef,
             *  unlockableName = "",
             *  viewableNode = new ViewablesCatalog.Node(newSkillDef.skillNameToken, false, null)
             * };*/
            Debug.LogWarning("finished PrimarySetup");
        }
Exemple #38
0
        /// <summary>
        /// Create new asset from <see cref="ScriptableObject"/> type with unique Name at
        /// selected folder in project window. Asset creation can be cancelled by pressing
        /// escape key when asset is initially being named.
        /// </summary>
        /// <typeparam Name="T">Type of scriptable object.</typeparam>
        ///
        public static void CreateAsset <T>() where T : ScriptableObject
        {
            var asset = ScriptableObject.CreateInstance <T>();

            ProjectWindowUtil.CreateAsset(asset, "New " + typeof(T).Name + ".asset");
        }
Exemple #39
0
        public void ShowContextOfCoroutine(int indexOfRoutineSlot)
        {
            var allCoroiutineIds = System.Reflection.Assembly.LoadFrom(AutomatineGUISettings.APPLICATION_DLL_PATH)
                                   .GetTypes()
                                   .Where(t => t.Name.Contains(AutomatineGUISettings.ROUTINE_CONTEXT_CLASS_NAME) && t.BaseType != null && t.BaseType.IsGenericType)
                                   .Select(t => t.GetMethods())
                                   .SelectMany(methods => methods)
                                   .Where(methodInfo => methodInfo.ReturnType == typeof(System.Collections.IEnumerator))
                                   .Select(method => method.Name)
                                   .ToList();


            var menu = new GenericMenu();

            var currentCoroutineId = routineIds[indexOfRoutineSlot];
            var coroiutineIds      = allCoroiutineIds.Where(coroutineId => coroutineId != currentCoroutineId).ToList();

            // show current coroutine
            menu.AddDisabledItem(
                new GUIContent(currentCoroutineId)
                );

            menu.AddSeparator(string.Empty);

            // set empty.
            menu.AddItem(
                new GUIContent("Add New Coroutine"),
                false,
                () => {
                if (coroutineGeneratorWindow == null)
                {
                    coroutineGeneratorWindow = ScriptableObject.CreateInstance <CoroutineGeneratorWindow>();
                }
                coroutineGeneratorWindow.existCoroutines = allCoroiutineIds;

                coroutineGeneratorWindow.enter = (string newCoroutineName) => {
                    Emit(new OnAutomatineEvent(OnAutomatineEvent.EventType.EVENT_ADDNEWCOROUTINE, tackId, indexOfRoutineSlot, newCoroutineName));
                };

                coroutineGeneratorWindow.ShowAuxWindow();
            }
                );


            // set empty.
            menu.AddItem(
                new GUIContent("Set Empty"),
                false,
                () => {
                EmitUndo("Set Coroutine");
                routineIds[indexOfRoutineSlot] = string.Empty;
                EmitSave();
            }
                );

            menu.AddSeparator(string.Empty);

            // other.
            foreach (var coroutine in coroiutineIds.Select((val, index) => new { index, val }))
            {
                var newCoroutineId = coroutine.val;

                menu.AddItem(
                    new GUIContent(newCoroutineId),
                    false,
                    () => {
                    EmitUndo("Set Coroutine");
                    routineIds[indexOfRoutineSlot] = newCoroutineId;
                    EmitSave();
                }
                    );
            }

            menu.ShowAsContext();
        }
		private static void INTERNAL_CALL_SetDirty(ScriptableObject self){}
Exemple #41
0
		protected internal override void DefineOwnProperty(Context cx, object id, ScriptableObject desc, bool checkValid)
		{
			base.DefineOwnProperty(cx, id, desc, checkValid);
			double d = ScriptRuntime.ToNumber(id);
			int index = (int)d;
			if (d != index)
			{
				return;
			}
			object value = Arg(index);
			if (value == ScriptableConstants.NOT_FOUND)
			{
				return;
			}
			if (IsAccessorDescriptor(desc))
			{
				RemoveArg(index);
				return;
			}
			object newValue = GetProperty(desc, "value");
			if (newValue == ScriptableConstants.NOT_FOUND)
			{
				return;
			}
			ReplaceArg(index, newValue);
			if (IsFalse(GetProperty(desc, "writable")))
			{
				RemoveArg(index);
			}
		}
		public override void DefineOwnProperty(Context cx, object key, ScriptableObject desc)
		{
			if (key is string)
			{
				string name = (string)key;
				int info = FindInstanceIdInfo(name);
				if (info != 0)
				{
					int id = (info & unchecked((int)(0xFFFF)));
					if (IsAccessorDescriptor(desc))
					{
						Delete(id);
					}
					else
					{
						// it will be replaced with a slot
						CheckPropertyDefinition(desc);
						ScriptableObject current = GetOwnPropertyDescriptor(cx, key);
						CheckPropertyChange(name, current, desc);
						int attr = ((int)(((uint)info) >> 16));
						object value = GetProperty(desc, "value");
						if (value != ScriptableConstants.NOT_FOUND && (attr & READONLY) == 0)
						{
							object currentValue = GetInstanceIdValue(id);
							if (!SameValue(value, currentValue))
							{
								SetInstanceIdValue(id, value);
							}
						}
						SetAttributes(name, ApplyDescriptorToAttributeBitset(attr, desc));
						return;
					}
				}
				if (prototypeValues != null)
				{
					int id = prototypeValues.FindId(name);
					if (id != 0)
					{
						if (IsAccessorDescriptor(desc))
						{
							prototypeValues.Delete(id);
						}
						else
						{
							// it will be replaced with a slot
							CheckPropertyDefinition(desc);
							ScriptableObject current = GetOwnPropertyDescriptor(cx, key);
							CheckPropertyChange(name, current, desc);
							int attr = prototypeValues.GetAttributes(id);
							object value = GetProperty(desc, "value");
							if (value != ScriptableConstants.NOT_FOUND && (attr & READONLY) == 0)
							{
								object currentValue = prototypeValues.Get(id);
								if (!SameValue(value, currentValue))
								{
									prototypeValues.Set(id, this, value);
								}
							}
							prototypeValues.SetAttributes(id, ApplyDescriptorToAttributeBitset(attr, desc));
							return;
						}
					}
				}
			}
			base.DefineOwnProperty(cx, key, desc);
		}
Exemple #43
0
    public void StartSample()
    {
        if (isSampling)
        {
            return;
        }

        if (string.IsNullOrEmpty(animName.Trim()))
        {
            ShowDialog("Animation name is empty.");
            return;
        }

        if (rootBoneTransform == null)
        {
            ShowDialog("Please set Root Bone.");
            return;
        }

        if (animClips.Count == 0)
        {
            ShowDialog("Please set Animation Clips.");
            return;
        }

        animClip = animClips[samplingClipIndex].clip;
        if (animClip == null)
        {
            isSampling = false;
            return;
        }

        int numFrames = (int)(GetClipFrameRate(animClip, samplingClipIndex) * animClip.length);

        if (numFrames == 0)
        {
            isSampling = false;
            return;
        }

        smr = GetComponentInChildren <SkinnedMeshRenderer>();
        if (smr == null)
        {
            ShowDialog("Cannot find SkinnedMeshRenderer.");
            return;
        }
        Mesh mesh = smr.sharedMesh;

        if (mesh == null)
        {
            ShowDialog("Missing Mesh");
            return;
        }

        samplingFrameIndex = 0;

        gpuSkinAnimData = animData == null?ScriptableObject.CreateInstance <GPUSkinAnimationData>() : animData;

        gpuSkinAnimData.name = animName;

        List <GPUSkinBone> bones_result = new List <GPUSkinBone>();

        CollectBones(bones_result, smr.bones, mesh.bindposes, null, rootBoneTransform, 0);
        gpuSkinAnimData.bones               = bones_result;
        gpuSkinAnimData.rootBoneIndex       = 0;
        gpuSkinAnimData.rootTransformMatrix = rootTransformMatrix;

        int numClips          = gpuSkinAnimData.clips == null ? 0 : gpuSkinAnimData.clips.Count;
        int overrideClipIndex = -1;

        for (int i = 0; i < numClips; ++i)
        {
            if (gpuSkinAnimData.clips[i].name == animClips[samplingClipIndex].name)
            {
                overrideClipIndex = i;
                break;
            }
        }

        gpuSkinClip                   = new GPUSkinClip();
        gpuSkinClip.name              = animClips[samplingClipIndex].name;
        gpuSkinClip.frameRate         = GetClipFrameRate(animClip, samplingClipIndex);
        gpuSkinClip.length            = animClip.length;
        gpuSkinClip.wrapMode          = animClips[samplingClipIndex].wrapMode;
        gpuSkinClip.frames            = new GPUSkinFrame[numFrames];
        gpuSkinClip.rootMotionEnabled = animClips[samplingClipIndex].rootMotion;

        if (gpuSkinAnimData.clips == null)
        {
            gpuSkinAnimData.clips = new List <GPUSkinClip>();
            gpuSkinAnimData.clips.Add(gpuSkinClip);
        }
        else
        {
            if (overrideClipIndex == -1)
            {
                gpuSkinAnimData.clips.Add(gpuSkinClip);
            }
            else
            {
                GPUSkinClip overridedClip = gpuSkinAnimData.clips[overrideClipIndex];
                //RestoreCustomClipData(overridedClip, gpuSkinningClip);
                gpuSkinAnimData.clips[overrideClipIndex] = gpuSkinClip;
            }
        }

        SetCurrentAnimationClip();
        PrepareRecordAnimator();

        isSampling = true;
    }
        public IEnumerator Setup()
        {
            MARSSession.TestMode = true;

            ResetScene();

            m_Module = ScriptableObject.CreateInstance <TestModule>();
            // Setup 2 parents with 1 child each
            m_Parent1 = new GameObject {
                name = "Parent 1"
            }.transform;
            var child1 = new GameObject {
                name = "Child 1"
            }.transform;

            child1.SetParent(m_Parent1);

            m_Parent2 = new GameObject {
                name = "Parent 2"
            }.transform;
            var child2 = new GameObject {
                name = "Child 2"
            }.transform;

            child2.SetParent(m_Parent2);

            // Setup MARS entities and session
            m_Parent1.gameObject.AddComponent <Proxy>();
            m_Parent2.gameObject.AddComponent <Proxy>();

            MARSSession.EnsureSessionInActiveScene();

            var moduleLoader = ModuleLoaderCore.instance;

            moduleLoader.GetModule <SimulationSceneModule>().RegisterSimulationUser(m_Module);
            moduleLoader.GetModule <SceneWatchdogModule>().ScenePoll();

            // Open simulation view and hierarchy panel in a window
            EditorWindow.GetWindow <SimulationView>();
            m_ContentHierarchyPanel = ScriptableObject.CreateInstance <ContentHierarchyPanel>();
            m_HierarchyWindow       = ScriptableObject.CreateInstance <SinglePanelWindow>();
            m_HierarchyWindow.InitWindow(m_ContentHierarchyPanel);
            m_HierarchyWindow.Show();

            // Change to synthetic type environment
            SimulationSettings.instance.EnvironmentMode = EnvironmentMode.Synthetic;

            // Load an environment
            moduleLoader.GetModule <MARSEnvironmentManager>().RefreshEnvironment();
            var querySimModule = moduleLoader.GetModule <QuerySimulationModule>();

            querySimModule.SimulateOneShot();
            while (querySimModule.simulating)
            {
                yield return(null);
            }

            GetCopies();

            // Expand root (parent of parent 1)
            m_ContentHierarchyPanel.HierarchyTreeView.SetExpanded(m_Parent1Copy.parent.gameObject.GetInstanceID(), true);

            // Expand parent 1, collapse parent 2
            m_ContentHierarchyPanel.HierarchyTreeView.SetExpanded(m_Parent1Copy.gameObject.GetInstanceID(), true);
            m_ContentHierarchyPanel.HierarchyTreeView.SetExpanded(m_Parent2Copy.gameObject.GetInstanceID(), false);

            // Select parent2, deselect everything else
            var newSelection = new List <UnityObject>();

            newSelection.Add(m_Parent2Copy.gameObject);
            m_PreviousSelection = Selection.objects;
            Selection.objects   = newSelection.ToArray();
        }
 protected T GetGenericTemplate <T>() where T : SerializableKeyValueTemplate <TK, TV>
 {
     return(ScriptableObject.CreateInstance <T>());
 }
Exemple #46
0
		public virtual void SetUp()
		{
			cx = Context.Enter();
			scope = cx.InitStandardObjects();
			cx.SetLanguageVersion(170);
		}
 private static SDK_BaseSystem GetSystemSDK()
 {
     if (systemSDK == null)
     {
         systemSDK = (VRTK_SDKManager.instance ? VRTK_SDKManager.instance.GetSystemSDK() : ScriptableObject.CreateInstance <SDK_FallbackSystem>());
     }
     return(systemSDK);
 }
Exemple #48
0
		public static void SetObjectProtoAndParent(ScriptableObject @object, Scriptable scope)
		{
			// Compared with function it always sets the scope to top scope
			scope = ScriptableObject.GetTopLevelScope(scope);
			@object.SetParentScope(scope);
			Scriptable proto = ScriptableObject.GetClassPrototype(scope, @object.GetClassName());
			@object.SetPrototype(proto);
		}
 private static SDK_BaseHeadset GetHeadsetSDK()
 {
     if (headsetSDK == null)
     {
         headsetSDK = (VRTK_SDKManager.instance ? VRTK_SDKManager.instance.GetHeadsetSDK() : ScriptableObject.CreateInstance <SDK_FallbackHeadset>());
     }
     return(headsetSDK);
 }
Exemple #50
0
			public object Run(Context cx)
			{
				this.cx = cx;
				scope = cx.InitStandardObjects(null, true);
				return Run();
			}
 private static SDK_BaseController GetControllerSDK()
 {
     if (controllerSDK == null)
     {
         controllerSDK = (VRTK_SDKManager.instance ? VRTK_SDKManager.instance.GetControllerSDK() : ScriptableObject.CreateInstance <SDK_FallbackController>());
     }
     return(controllerSDK);
 }
    private void ImportYarn(UnityEditor.AssetImporters.AssetImportContext ctx)
    {
        var    sourceText = File.ReadAllText(ctx.assetPath);
        string fileName   = System.IO.Path.GetFileNameWithoutExtension(ctx.assetPath);

        try
        {
            // Compile the source code into a compiled Yarn program (or
            // generate a parse error)
            compilationStatus = Compiler.CompileString(sourceText, fileName, out var compiledProgram, out var stringTable);

            // Create a container for storing the bytes
            var programContainer = ScriptableObject.CreateInstance <YarnProgram>();

            using (var memoryStream = new MemoryStream())
                using (var outputStream = new Google.Protobuf.CodedOutputStream(memoryStream))
                {
                    // Serialize the compiled program to memory
                    compiledProgram.WriteTo(outputStream);
                    outputStream.Flush();

                    byte[] compiledBytes = memoryStream.ToArray();

                    programContainer.compiledProgram = compiledBytes;

                    // Add this container to the imported asset; it will be
                    // what the user interacts with in Unity
                    ctx.AddObjectToAsset("Program", programContainer, YarnEditorUtility.GetYarnDocumentIconTexture());
                    ctx.SetMainObject(programContainer);

                    isSuccesfullyCompiled = true;

                    // var outPath = Path.ChangeExtension(ctx.assetPath, ".yarnc");
                    // File.WriteAllBytes(outPath, compiledBytes);
                }

            if (stringTable.Count > 0)
            {
                using (var memoryStream = new MemoryStream())
                    using (var textWriter = new StreamWriter(memoryStream)) {
                        // Generate the localised .csv file

                        // Use the invariant culture when writing the CSV
                        var configuration = new CsvHelper.Configuration.Configuration(
                            System.Globalization.CultureInfo.InvariantCulture
                            );

                        var csv = new CsvHelper.CsvWriter(
                            textWriter,   // write into this stream
                            configuration // use this configuration
                            );

                        var lines = stringTable.Select(x => new {
                            id         = x.Key,
                            text       = x.Value.text,
                            file       = x.Value.fileName,
                            node       = x.Value.nodeName,
                            lineNumber = x.Value.lineNumber
                        });

                        csv.WriteRecords(lines);

                        textWriter.Flush();

                        memoryStream.Position = 0;

                        using (var reader = new StreamReader(memoryStream)) {
                            var textAsset = new TextAsset(reader.ReadToEnd());
                            textAsset.name = $"{fileName} ({baseLanguageID})";

                            ctx.AddObjectToAsset("Strings", textAsset);

                            programContainer.baseLocalisationStringTable = textAsset;
                            baseLanguage = textAsset;
                            programContainer.localizations = localizations;
                        }

                        stringIDs = lines.Select(l => l.id).ToArray();
                    }
            }
        }
        catch (Yarn.Compiler.ParseException e)
        {
            isSuccesfullyCompiled   = false;
            compilationErrorMessage = e.Message;
            ctx.LogImportError(e.Message);
            return;
        }
    }
Exemple #53
0
        public static void CreateAsset()
        {
            ScriptableObject t = CustomAssetUtility.CreateAsset <ManagerPackage> ("New ManagerPackage");

            EditorGUIUtility.PingObject(t);
        }
        void DrawRightPanel()
        {
            EditorGUIUtility.labelWidth = k_RightPanelLabelWidth;
            EditorGUILayout.BeginVertical();
            m_RightScrollPosition = EditorGUILayout.BeginScrollView(m_RightScrollPosition, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true));

            using (new EditorGUILayout.HorizontalScope())
            {
                var titleRect = EditorGUILayout.GetControlRect(true, k_TitleTextHeight);
                EditorGUI.LabelField(titleRect, "Probe Volume Settings", m_SubtitleStyle);
                var debugButtonRect = EditorGUILayout.GetControlRect(true, k_TitleTextHeight, GUILayout.Width(k_TitleTextHeight));
                if (GUI.Button(debugButtonRect, Styles.debugButton))
                {
                    OpenProbeVolumeDebugPanel();
                }
            }

            EditorGUILayout.Space();
            SanitizeScenes();
            m_ScenesInSet.DoLayoutList();

            var set       = GetCurrentBakingSet();
            var sceneGUID = sceneData.GetFirstProbeVolumeSceneGUID(set);

            if (sceneGUID != null)
            {
                EditorGUILayout.Space();

                // Show only the profile from the first scene of the set (they all should be the same)
                if (set.profile == null)
                {
                    EditorUtility.DisplayDialog("Missing Probe Volume Profile Asset!", $"We couldn't find the asset profile associated with the Baking Set '{set.name}'.\nDo you want to create a new one?", "Yes");
                    set.profile = ScriptableObject.CreateInstance <ProbeReferenceVolumeProfile>();

                    // Delay asset creation, workaround to avoid creating assets while importing another one (SRP can be called from asset import).
                    EditorApplication.update += DelayCreateAsset;
                    void DelayCreateAsset()
                    {
                        EditorApplication.update -= DelayCreateAsset;
                        ProjectWindowUtil.CreateAsset(set.profile, set.name + ".asset");
                    }
                }
                if (m_ProbeVolumeProfileEditor == null)
                {
                    m_ProbeVolumeProfileEditor = Editor.CreateEditor(set.profile);
                }
                if (m_ProbeVolumeProfileEditor.target != set.profile)
                {
                    Editor.CreateCachedEditor(set.profile, m_ProbeVolumeProfileEditor.GetType(), ref m_ProbeVolumeProfileEditor);
                }

                EditorGUILayout.LabelField("Probe Volume Profile", EditorStyles.boldLabel);
                EditorGUI.indentLevel++;
                m_ProbeVolumeProfileEditor.OnInspectorGUI();
                EditorGUI.indentLevel--;

                var serializedSets            = m_ProbeSceneData.FindPropertyRelative("serializedBakingSets");
                var serializedSet             = serializedSets.GetArrayElementAtIndex(m_BakingSets.index);
                var probeVolumeBakingSettings = serializedSet.FindPropertyRelative("settings");
                EditorGUILayout.PropertyField(probeVolumeBakingSettings);

                // Clamp to make sure minimum we set for dilation distance is min probe distance
                set.settings.dilationSettings.dilationDistance = Mathf.Max(set.profile.minDistanceBetweenProbes, set.settings.dilationSettings.dilationDistance);

                EditorGUILayout.Space();
                EditorGUILayout.Space();
                var stateTitleRect = EditorGUILayout.GetControlRect(true, k_TitleTextHeight);
                EditorGUI.LabelField(stateTitleRect, Styles.bakingStatesTitle, m_SubtitleStyle);
                EditorGUILayout.Space();
                m_BakingStates.DoLayoutList();
            }
            else
            {
                EditorGUILayout.HelpBox("You need to assign at least one scene with probe volumes to configure the baking settings", MessageType.Error, true);
            }

            EditorGUILayout.EndScrollView();

            EditorGUILayout.Space();
            DrawBakeButton();

            EditorGUILayout.EndVertical();
        }
Exemple #55
0
		public virtual void SetUp()
		{
			cx = Context.Enter();
			cx.SetOptimizationLevel(-1);
			scope = cx.InitStandardObjects();
		}