Browse Source

getJSComponent fails if called immediately after createChildPrefab #991

bitonator 9 years ago
parent
commit
826f7d2249

+ 0 - 561
JSComponent.cpp

@@ -1,561 +0,0 @@
-//
-// Copyright (c) 2008-2014 the Urho3D project.
-// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-//
-
-#include <Atomic/IO/Log.h>
-#include <Atomic/IO/FileSystem.h>
-#include <Atomic/Core/Context.h>
-#include <Atomic/Resource/ResourceCache.h>
-
-#ifdef ATOMIC_PHYSICS
-#include <Atomic/Physics/PhysicsEvents.h>
-#include <Atomic/Physics/PhysicsWorld.h>
-#endif
-#include <Atomic/Scene/Scene.h>
-#include <Atomic/Scene/SceneEvents.h>
-
-#include "JSVM.h"
-#include "JSComponentFile.h"
-#include "JSComponent.h"
-
-namespace Atomic
-{
-
-extern const char* LOGIC_CATEGORY;
-
-class JSComponentFactory : public ObjectFactory
-{
-    ATOMIC_REFCOUNTED(JSComponentFactory)
-
-public:
-    /// Construct.
-    JSComponentFactory(Context* context) :
-        ObjectFactory(context)
-    {
-        typeInfo_ = JSComponent::GetTypeInfoStatic();
-    }
-
-    /// Create an object of the specific type.
-    SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY)
-    {
-
-        // if in editor, just create the JSComponent
-        if (context_->GetEditorContext())
-        {
-            return SharedPtr<Object>(new JSComponent(context_));
-        }
-
-        // At runtime, a XML JSComponent may refer to a "scriptClass"
-        // component which is new'd in JS and creates the component itself
-        // we peek ahead here to see if we have a JSComponentFile and if it is a script class
-
-        String componentRef;
-
-        if (source != XMLElement::EMPTY)
-        {
-            XMLElement attrElem = source.GetChild("attribute");
-
-            while (attrElem)
-            {
-                if (attrElem.GetAttribute("name") == "ComponentFile")
-                {
-                    componentRef = attrElem.GetAttribute("value");
-                    break;
-                }
-
-                attrElem = attrElem.GetNext("attribute");
-            }
-        }
-
-        SharedPtr<Object> ptr;
-
-        if (componentRef.Length())
-        {
-            Vector<String> split = componentRef.Split(';');
-
-            if (split.Size() == 2)
-            {
-                ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
-                JSComponentFile* componentFile = cache->GetResource<JSComponentFile>(split[1]);
-                if (componentFile)
-                    ptr = componentFile->CreateJSComponent();
-                else
-                {
-                    ATOMIC_LOGERRORF("Unable to load component file %s", split[1].CString());
-                }
-            }
-
-        }
-
-        if (ptr.Null())
-        {
-            ptr = new JSComponent(context_);
-        }
-
-        return ptr;
-
-    }
-};
-
-
-JSComponent::JSComponent(Context* context) :
-    ScriptComponent(context),
-    updateEventMask_(USE_UPDATE | USE_POSTUPDATE | USE_FIXEDUPDATE | USE_FIXEDPOSTUPDATE),
-    currentEventMask_(0),
-    instanceInitialized_(false),
-    started_(false),
-    destroyed_(false),
-    scriptClassInstance_(false),
-    delayedStartCalled_(false),
-    loading_(false)
-{
-    vm_ = JSVM::GetJSVM(NULL);
-}
-
-JSComponent::~JSComponent()
-{
-
-}
-
-void JSComponent::RegisterObject(Context* context)
-{
-    context->RegisterFactory( new JSComponentFactory(context), LOGIC_CATEGORY);
-    ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("ComponentFile", GetComponentFileAttr, SetComponentFileAttr, ResourceRef, ResourceRef(JSComponentFile::GetTypeStatic()), AM_DEFAULT);
-    ATOMIC_COPY_BASE_ATTRIBUTES(ScriptComponent);
-}
-
-void JSComponent::OnSetEnabled()
-{
-    UpdateEventSubscription();
-}
-
-void JSComponent::SetUpdateEventMask(unsigned char mask)
-{
-    if (updateEventMask_ != mask)
-    {
-        updateEventMask_ = mask;
-        UpdateEventSubscription();
-    }
-}
-
-void JSComponent::ApplyAttributes()
-{
-}
-
-bool JSComponent::IsInstanceInitialized() {
-	return instanceInitialized_;
-}
-
-void JSComponent::InitInstance(bool hasArgs, int argIdx)
-{
-    if (context_->GetEditorContext() || componentFile_.Null())
-        return;
-
-    duk_context* ctx = vm_->GetJSContext();
-
-    duk_idx_t top = duk_get_top(ctx);
-
-    // apply fields
-
-    const FieldMap& fields = componentFile_->GetFields();
-
-    if (fields.Size())
-    {
-        // push self
-        js_push_class_object_instance(ctx, this, "JSComponent");
-
-        FieldMap::ConstIterator itr = fields.Begin();
-        while (itr != fields.End())
-        {
-            if (fieldValues_.Contains(itr->first_))
-            {
-                Variant& v = fieldValues_[itr->first_];
-
-                if (v.GetType() == itr->second_)
-                {
-                    js_push_variant(ctx, v);
-                    duk_put_prop_string(ctx, -2, itr->first_.CString());
-                }
-            }
-            else
-            {
-                Variant v;
-                componentFile_->GetDefaultFieldValue(itr->first_, v);
-                js_push_variant(ctx,  v);
-                duk_put_prop_string(ctx, -2, itr->first_.CString());
-            }
-
-            itr++;
-        }
-
-        // pop self
-        duk_pop(ctx);
-    }
-
-    // apply args if any
-    if (hasArgs)
-    {
-        // push self
-        js_push_class_object_instance(ctx, this, "JSComponent");
-
-        duk_enum(ctx, argIdx, DUK_ENUM_OWN_PROPERTIES_ONLY);
-
-        while (duk_next(ctx, -1, 1)) {
-
-            duk_put_prop(ctx, -4);
-
-        }
-
-        // pop self and enum object
-        duk_pop_2(ctx);
-
-    }
-
-    if (!componentFile_->GetScriptClass())
-    {
-
-        componentFile_->PushModule();
-
-        if (!duk_is_object(ctx, -1))
-        {
-            duk_set_top(ctx, top);
-            return;
-        }
-
-        // Check for "default" constructor which is used by TypeScript and ES2015
-        duk_get_prop_string(ctx, -1, "default");
-
-        if (!duk_is_function(ctx, -1))
-        {
-            duk_pop(ctx);
-
-            // If "default" doesn't exist, look for component
-            duk_get_prop_string(ctx, -1, "component");
-
-            if (!duk_is_function(ctx, -1))
-            {
-                duk_set_top(ctx, top);
-                return;
-            }
-        }
-
-        // call with self
-        js_push_class_object_instance(ctx, this, "JSComponent");
-
-        if (duk_pcall(ctx, 1) != 0)
-        {
-            vm_->SendJSErrorEvent();
-            duk_set_top(ctx, top);
-            return;
-        }
-
-    }
-
-    duk_set_top(ctx, top);
-
-    instanceInitialized_ = true;
-
-}
-
-void JSComponent::CallScriptMethod(const String& name, bool passValue, float value)
-{
-    if (destroyed_ || !node_ || !node_->GetScene())
-        return;
-
-    void* heapptr = JSGetHeapPtr();
-
-    if (!heapptr)
-        return;
-
-    duk_context* ctx = vm_->GetJSContext();
-
-    duk_idx_t top = duk_get_top(ctx);
-
-    duk_push_heapptr(ctx, heapptr);
-
-    duk_get_prop_string(ctx, -1, name.CString());
-
-    if (!duk_is_function(ctx, -1))
-    {
-        duk_set_top(ctx, top);
-        return;
-    }
-
-    // push this
-    if (scriptClassInstance_)
-        duk_push_heapptr(ctx, heapptr);
-
-    if (passValue)
-        duk_push_number(ctx, value);
-
-    int status = scriptClassInstance_ ? duk_pcall_method(ctx, passValue ? 1 : 0) : duk_pcall(ctx, passValue ? 1 : 0);
-
-    if (status != 0)
-    {
-        vm_->SendJSErrorEvent();
-        duk_set_top(ctx, top);
-        return;
-    }
-
-    duk_set_top(ctx, top);
-}
-
-void JSComponent::Start()
-{
-    static String name = "start";
-    CallScriptMethod(name);
-}
-
-void JSComponent::DelayedStart()
-{
-    static String name = "delayedStart";
-    CallScriptMethod(name);
-}
-
-void JSComponent::Update(float timeStep)
-{
-    if (!instanceInitialized_)
-        InitInstance();
-
-    if (!started_)
-    {
-        started_ = true;
-        Start();
-    }
-
-    static String name = "update";
-    CallScriptMethod(name, true, timeStep);
-}
-
-void JSComponent::PostUpdate(float timeStep)
-{
-    static String name = "postUpdate";
-    CallScriptMethod(name, true, timeStep);
-}
-
-void JSComponent::FixedUpdate(float timeStep)
-{
-    static String name = "fixedUpdate";
-    CallScriptMethod(name, true, timeStep);
-}
-
-void JSComponent::FixedPostUpdate(float timeStep)
-{
-    static String name = "fixedPostUpdate";
-    CallScriptMethod(name, true, timeStep);
-}
-
-void JSComponent::OnNodeSet(Node* node)
-{
-    if (node)
-    {
-    }
-    else
-    {
-        Stop();
-    }
-}
-
-void JSComponent::OnSceneSet(Scene* scene)
-{
-    if (scene)
-        UpdateEventSubscription();
-    else
-    {
-        UnsubscribeFromEvent(E_SCENEUPDATE);
-        UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
-#ifdef ATOMIC_PHYSICS
-        UnsubscribeFromEvent(E_PHYSICSPRESTEP);
-        UnsubscribeFromEvent(E_PHYSICSPOSTSTEP);
-#endif
-        currentEventMask_ = 0;
-    }
-}
-
-void JSComponent::UpdateEventSubscription()
-{
-    Scene* scene = GetScene();
-    if (!scene)
-        return;
-
-    bool enabled = IsEnabledEffective();
-
-    bool needUpdate = enabled && ((updateEventMask_ & USE_UPDATE) || !delayedStartCalled_);
-    if (needUpdate && !(currentEventMask_ & USE_UPDATE))
-    {
-        SubscribeToEvent(scene, E_SCENEUPDATE, ATOMIC_HANDLER(JSComponent, HandleSceneUpdate));
-        currentEventMask_ |= USE_UPDATE;
-    }
-    else if (!needUpdate && (currentEventMask_ & USE_UPDATE))
-    {
-        UnsubscribeFromEvent(scene, E_SCENEUPDATE);
-        currentEventMask_ &= ~USE_UPDATE;
-    }
-
-    bool needPostUpdate = enabled && (updateEventMask_ & USE_POSTUPDATE);
-    if (needPostUpdate && !(currentEventMask_ & USE_POSTUPDATE))
-    {
-        SubscribeToEvent(scene, E_SCENEPOSTUPDATE, ATOMIC_HANDLER(JSComponent, HandleScenePostUpdate));
-        currentEventMask_ |= USE_POSTUPDATE;
-    }
-    else if (!needPostUpdate && (currentEventMask_ & USE_POSTUPDATE))
-    {
-        UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
-        currentEventMask_ &= ~USE_POSTUPDATE;
-    }
-
-#ifdef ATOMIC_PHYSICS
-    PhysicsWorld* world = scene->GetComponent<PhysicsWorld>();
-    if (!world)
-        return;
-
-    bool needFixedUpdate = enabled && (updateEventMask_ & USE_FIXEDUPDATE);
-    if (needFixedUpdate && !(currentEventMask_ & USE_FIXEDUPDATE))
-    {
-        SubscribeToEvent(world, E_PHYSICSPRESTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPreStep));
-        currentEventMask_ |= USE_FIXEDUPDATE;
-    }
-    else if (!needFixedUpdate && (currentEventMask_ & USE_FIXEDUPDATE))
-    {
-        UnsubscribeFromEvent(world, E_PHYSICSPRESTEP);
-        currentEventMask_ &= ~USE_FIXEDUPDATE;
-    }
-
-    bool needFixedPostUpdate = enabled && (updateEventMask_ & USE_FIXEDPOSTUPDATE);
-    if (needFixedPostUpdate && !(currentEventMask_ & USE_FIXEDPOSTUPDATE))
-    {
-        SubscribeToEvent(world, E_PHYSICSPOSTSTEP, ATOMIC_HANDLER(JSComponent, HandlePhysicsPostStep));
-        currentEventMask_ |= USE_FIXEDPOSTUPDATE;
-    }
-    else if (!needFixedPostUpdate && (currentEventMask_ & USE_FIXEDPOSTUPDATE))
-    {
-        UnsubscribeFromEvent(world, E_PHYSICSPOSTSTEP);
-        currentEventMask_ &= ~USE_FIXEDPOSTUPDATE;
-    }
-#endif
-}
-
-void JSComponent::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
-{
-    using namespace SceneUpdate;
-
-    assert(!destroyed_);
-
-    // Execute user-defined delayed start function before first update
-    if (!delayedStartCalled_)
-    {
-        DelayedStart();
-        delayedStartCalled_ = true;
-
-        // If did not need actual update events, unsubscribe now
-        if (!(updateEventMask_ & USE_UPDATE))
-        {
-            UnsubscribeFromEvent(GetScene(), E_SCENEUPDATE);
-            currentEventMask_ &= ~USE_UPDATE;
-            return;
-        }
-    }
-
-    // Then execute user-defined update function
-    Update(eventData[P_TIMESTEP].GetFloat());
-}
-
-void JSComponent::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
-{
-    using namespace ScenePostUpdate;
-
-    // Execute user-defined post-update function
-    PostUpdate(eventData[P_TIMESTEP].GetFloat());
-}
-
-#ifdef ATOMIC_PHYSICS
-void JSComponent::HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData)
-{
-    using namespace PhysicsPreStep;
-
-    // Execute user-defined fixed update function
-    FixedUpdate(eventData[P_TIMESTEP].GetFloat());
-}
-
-void JSComponent::HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData)
-{
-    using namespace PhysicsPostStep;
-
-    // Execute user-defined fixed post-update function
-    FixedPostUpdate(eventData[P_TIMESTEP].GetFloat());
-}
-#endif
-
-bool JSComponent::Load(Deserializer& source, bool setInstanceDefault)
-{
-    loading_ = true;
-    bool success = Component::Load(source, setInstanceDefault);
-    loading_ = false;
-
-    return success;
-}
-
-bool JSComponent::LoadXML(const XMLElement& source, bool setInstanceDefault)
-{
-    loading_ = true;
-    bool success = Component::LoadXML(source, setInstanceDefault);
-    loading_ = false;
-
-    return success;
-}
-
-bool JSComponent::MatchScriptName(const String& path)
-{
-    if (componentFile_.Null())
-        return false;
-
-    String _path = path;
-    _path.Replace(".js", "", false);
-
-    const String& name = componentFile_->GetName();
-
-    if (_path == name)
-        return true;
-
-    String pathName, fileName, ext;
-    SplitPath(name, pathName, fileName, ext);
-
-    if (fileName == _path)
-        return true;
-
-
-    return false;
-
-}
-
-ResourceRef JSComponent::GetComponentFileAttr() const
-{
-    return GetResourceRef(componentFile_, JSComponentFile::GetTypeStatic());
-}
-
-void JSComponent::SetComponentFileAttr(const ResourceRef& value)
-{
-    ResourceCache* cache = GetSubsystem<ResourceCache>();
-    SetComponentFile(cache->GetResource<JSComponentFile>(value.name_));
-}
-
-}

+ 0 - 152
JSComponent.h

@@ -1,152 +0,0 @@
-//
-// Copyright (c) 2008-2014 the Urho3D project.
-// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-//
-
-#pragma once
-
-#include <Atomic/Script/ScriptComponent.h>
-
-#include "JSComponentFile.h"
-
-namespace Atomic
-{
-
-class JSVM;
-
-/// JavaScript component
-class ATOMIC_API JSComponent : public ScriptComponent
-{
-    friend class JSComponentFactory;
-    friend class JSComponentFile;
-
-    ATOMIC_OBJECT(JSComponent, ScriptComponent);
-
-    enum EventFlags
-    {
-        USE_UPDATE = 0x1,
-        USE_POSTUPDATE = 0x2,
-        USE_FIXEDUPDATE = 0x4,
-        USE_FIXEDPOSTUPDATE = 0x8
-    };
-
-public:
-
-    /// Construct.
-    JSComponent(Context* context);
-    /// Destruct.
-    virtual ~JSComponent();
-
-    /// Register object factory.
-    static void RegisterObject(Context* context);
-
-    bool Load(Deserializer& source, bool setInstanceDefault);
-    bool LoadXML(const XMLElement& source, bool setInstanceDefault);
-    void ApplyAttributes();
-
-    /// Match script name
-    bool MatchScriptName(const String& path);
-
-    /// Handle enabled/disabled state change. Changes update event subscription.
-    virtual void OnSetEnabled();
-
-    /// Set what update events should be subscribed to. Use this for optimization: by default all are in use. Note that this is not an attribute and is not saved or network-serialized, therefore it should always be called eg. in the subclass constructor.
-    void SetUpdateEventMask(unsigned char mask);
-
-    /// Return what update events are subscribed to.
-    unsigned char GetUpdateEventMask() const { return updateEventMask_; }
-    /// Return whether the DelayedStart() function has been called.
-    bool IsDelayedStartCalled() const { return delayedStartCalled_; }
-
-    void SetDestroyed() { destroyed_ = true; }
-
-    bool IsInstanceInitialized();	
-    void InitInstance(bool hasArgs = false, int argIdx = 0);
-
-    /// Get script attribute
-    ResourceRef GetComponentFileAttr() const;
-    ScriptComponentFile* GetComponentFile() { return componentFile_; }
-
-    /// Set script attribute.
-    void SetComponentFile(JSComponentFile* cfile) { componentFile_ = cfile; }
-    void SetComponentFileAttr(const ResourceRef& value);
-
-    // a JSComponentFile only holds one class, so no classname to look up in it
-    const String& GetComponentClassName() const { return String::EMPTY; }
-
-
-protected:
-    /// Handle scene node being assigned at creation.
-    virtual void OnNodeSet(Node* node);
-    /// Handle scene being assigned.
-    virtual void OnSceneSet(Scene* scene);
-
-private:
-    /// Subscribe/unsubscribe to update events based on current enabled state and update event mask.
-    void UpdateEventSubscription();
-    /// Handle scene update event.
-    void HandleSceneUpdate(StringHash eventType, VariantMap& eventData);
-    /// Handle scene post-update event.
-    void HandleScenePostUpdate(StringHash eventType, VariantMap& eventData);
-#ifdef ATOMIC_PHYSICS
-    /// Handle physics pre-step event.
-    void HandlePhysicsPreStep(StringHash eventType, VariantMap& eventData);
-    /// Handle physics post-step event.
-    void HandlePhysicsPostStep(StringHash eventType, VariantMap& eventData);
-#endif
-
-    void CallScriptMethod(const String& name, bool passValue = false, float value = 0.0f);
-
-    /// Called when the component is added to a scene node. Other components may not yet exist.
-    virtual void Start();
-    /// Called before the first update. At this point all other components of the node should exist. Will also be called if update events are not wanted; in that case the event is immediately unsubscribed afterward.
-    virtual void DelayedStart();
-    /// Called when the component is detached from a scene node, usually on destruction. Note that you will no longer have access to the node and scene at that point.
-    virtual void Stop() {}
-    /// Called on scene update, variable timestep.
-    virtual void Update(float timeStep);
-    /// Called on scene post-update, variable timestep.
-    virtual void PostUpdate(float timeStep);
-    /// Called on physics update, fixed timestep.
-    virtual void FixedUpdate(float timeStep);
-    /// Called on physics post-update, fixed timestep.
-    virtual void FixedPostUpdate(float timeStep);
-
-    /// Requested event subscription mask.
-    unsigned char updateEventMask_;
-    /// Current event subscription mask.
-    unsigned char currentEventMask_;
-
-    bool instanceInitialized_;
-    bool started_;
-    bool destroyed_;
-    bool scriptClassInstance_;
-
-    /// Flag for delayed start.
-    bool delayedStartCalled_;
-
-    bool loading_;
-    WeakPtr<JSVM> vm_;
-    SharedPtr<JSComponentFile> componentFile_;
-
-};
-
-}

+ 0 - 360
JSScene.cpp

@@ -1,360 +0,0 @@
-//
-// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-//
-
-#include <Atomic/Resource/ResourceCache.h>
-#include <Atomic/Resource/XMLFile.h>
-#include <Atomic/IO/File.h>
-#include <Atomic/Scene/Node.h>
-#include <Atomic/Scene/Scene.h>
-#include <Atomic/Scene/PrefabComponent.h>
-#include <Atomic/Graphics/Camera.h>
-
-#ifdef ATOMIC_3D
-#include <Atomic/Physics/RigidBody.h>
-#endif
-
-#include "JSScene.h"
-#include "JSComponent.h"
-#include "JSVM.h"
-
-namespace Atomic
-{
-
-void jsapi_init_scene_serializable(JSVM* vm);
-
-static int Node_CreateJSComponent(duk_context* ctx)
-{
-    String path = duk_require_string(ctx, 0);
-
-    bool hasArgs = false;
-    int argIdx = -1;
-    if (duk_get_top(ctx) > 1 && duk_is_object(ctx, 1))
-    {
-        hasArgs = true;
-        argIdx = 1;
-    }
-
-    duk_push_this(ctx);
-    Node* node = js_to_class_instance<Node>(ctx, -1, 0);
-
-    ResourceCache* cache = node->GetContext()->GetSubsystem<ResourceCache>();
-    JSComponentFile* file = cache->GetResource<JSComponentFile>(path);
-
-    if (!file)
-    {
-        ATOMIC_LOGERRORF("Unable to load component file %s", path.CString());
-        duk_push_undefined(ctx);
-        return 1;
-    }
-
-    SharedPtr<JSComponent> jsc = file->CreateJSComponent();
-
-    node->AddComponent(jsc, jsc->GetID(), LOCAL);
-
-    jsc->InitInstance(hasArgs, argIdx);
-
-    js_push_class_object_instance(ctx, jsc, "JSComponent");
-    return 1;
-}
-
-static int Node_GetJSComponent(duk_context* ctx)
-{
-    String path = duk_require_string(ctx, 0);
-
-    bool recursive = false;
-    if (duk_get_top(ctx) == 2)
-        if (duk_get_boolean(ctx, 1))
-            recursive = true;
-
-    duk_push_this(ctx);
-    Node* node = js_to_class_instance<Node>(ctx, -1, 0);
-
-    PODVector<JSComponent*> components;
-    node->GetComponents<JSComponent>(components, recursive);
-
-    for (unsigned i = 0; i < components.Size(); i++)
-    {
-        JSComponent* component = components[i];
-        if (component->MatchScriptName(path)) {
-			if(!component->IsInstanceInitialized())
-				component->InitInstance();
-
-            js_push_class_object_instance(ctx, component, "Component");
-            return 1;
-
-        }
-
-    }
-    duk_push_null(ctx);
-    return 1;
-}
-
-static int Node_GetChildrenWithComponent(duk_context* ctx)
-{
-    StringHash type = duk_to_string(ctx, 0);
-
-    bool recursive = false;
-    if (duk_get_top(ctx) == 2)
-        if (duk_get_boolean(ctx, 1))
-            recursive = true;
-
-    duk_push_this(ctx);
-    Node* node = js_to_class_instance<Node>(ctx, -1, 0);
-
-    PODVector<Node*> dest;
-    node->GetChildrenWithComponent(dest, type, recursive);
-
-    duk_push_array(ctx);
-
-    for (unsigned i = 0; i < dest.Size(); i++)
-    {
-        js_push_class_object_instance(ctx, dest[i], "Node");
-        duk_put_prop_index(ctx, -2, i);
-    }
-
-    return 1;
-}
-
-static int Node_GetChildrenWithName(duk_context* ctx)
-{
-    StringHash nameHash = duk_to_string(ctx, 0);
-
-    bool recursive = false;
-    if (duk_get_top(ctx) == 2)
-        if (duk_get_boolean(ctx, 1))
-            recursive = true;
-
-    duk_push_this(ctx);
-    Node* node = js_to_class_instance<Node>(ctx, -1, 0);
-
-    PODVector<Node*> dest;
-    node->GetChildrenWithName(dest, nameHash, recursive);
-
-    duk_push_array(ctx);
-
-    for (unsigned i = 0; i < dest.Size(); i++)
-    {
-        js_push_class_object_instance(ctx, dest[i], "Node");
-        duk_put_prop_index(ctx, -2, i);
-    }
-
-    return 1;
-}
-
-static int Node_GetComponents(duk_context* ctx)
-{
-    bool recursive = false;
-    StringHash typeHash = Component::GetTypeStatic();
-
-
-    if (duk_get_top(ctx) > 0)
-    {
-        if (duk_is_string(ctx, 0) && strlen(duk_get_string(ctx, 0)))
-            typeHash = duk_get_string(ctx, 0);
-    }
-
-    if (duk_get_top(ctx) > 1)
-        recursive = duk_require_boolean(ctx, 1) ? true : false;
-
-
-    duk_push_this(ctx);
-    Node* node = js_to_class_instance<Node>(ctx, -1, 0);
-
-    PODVector<Component*> dest;
-    node->GetComponents(dest, typeHash, recursive);
-
-    duk_push_array(ctx);
-
-    int count = 0;
-    for (unsigned i = 0; i < dest.Size(); i++)
-    {
-        if (js_push_class_object_instance(ctx, dest[i], dest[i]->GetTypeName().CString()))
-        {
-            duk_put_prop_index(ctx, -2, count++);
-        }
-    }
-
-    return 1;
-}
-
-static int Node_GetChildAtIndex(duk_context* ctx)
-{
-    duk_push_this(ctx);
-    Node* node = js_to_class_instance<Node>(ctx, -1, 0);
-
-    unsigned idx = (unsigned) duk_to_number(ctx, 0);
-
-    if (node->GetNumChildren() <= idx)
-    {
-        duk_push_null(ctx);
-        return 1;
-    }
-
-    Node* child = node->GetChild(idx);
-    js_push_class_object_instance(ctx, child, "Node");
-
-    return 1;
-}
-
-static int Node_SaveXML(duk_context* ctx)
-{
-    File* file = js_to_class_instance<File>(ctx, 0, 0);
-
-    duk_push_this(ctx);
-    Node* node = js_to_class_instance<Node>(ctx, -1, 0);
-
-    duk_push_boolean(ctx, node->SaveXML(*file) ? 1 : 0);
-
-    return 1;
-}
-
-static int Node_LoadPrefab(duk_context* ctx)
-{
-    const char* prefabName = duk_require_string(ctx, 0);
-
-    duk_push_this(ctx);
-    Node* node = js_to_class_instance<Node>(ctx, -1, 0);
-
-    PrefabComponent* prefabComponent = node->CreateComponent<PrefabComponent>();
-    prefabComponent->SetPrefabGUID(prefabName);
-
-    duk_push_boolean(ctx, 1);
-    return 1;
-
-}
-
-static int Node_CreateChildPrefab(duk_context* ctx)
-{
-    const char* childName = duk_require_string(ctx, 0);
-    const char* prefabName = duk_require_string(ctx, 1);
-
-    duk_push_this(ctx);
-    Node* parent = js_to_class_instance<Node>(ctx, -1, 0);
-
-    Node* node = parent->CreateChild();
-
-    PrefabComponent* prefabComponent = node->CreateComponent<PrefabComponent>();
-    prefabComponent->SetPrefabGUID(prefabName);
-
-    // override what node name is in prefab
-    node->SetName(childName);
-
-    js_push_class_object_instance(ctx, node, "Node");
-
-    return 1;
-
-}
-
-
-static int Scene_LoadXML(duk_context* ctx)
-{
-    JSVM* vm = JSVM::GetJSVM(ctx);
-
-    String filename = duk_to_string(ctx, 0);
-
-    ResourceCache* cache = vm->GetSubsystem<ResourceCache>();
-
-    SharedPtr<File> file = cache->GetFile(filename);
-
-    if (!file->IsOpen())
-    {
-        duk_push_false(ctx);
-        return 1;
-    }
-
-    duk_push_this(ctx);
-    Scene* scene = js_to_class_instance<Scene>(ctx, -1, 0);
-
-    bool success = scene->LoadXML(*file);
-
-    if (success)
-        duk_push_true(ctx);
-    else
-        duk_push_false(ctx);
-
-
-    return 1;
-
-}
-
-static int Scene_GetMainCamera(duk_context* ctx)
-{
-    duk_push_this(ctx);
-    Scene* scene = js_to_class_instance<Scene>(ctx, -1, 0);
-
-    PODVector<Node*> cameraNodes;
-    Camera* camera = 0;
-    scene->GetChildrenWithComponent(cameraNodes, Camera::GetTypeStatic(), true);
-    if (cameraNodes.Size())
-    {
-        camera = cameraNodes[0]->GetComponent<Camera>();
-    }
-
-    if (!camera)
-    {
-        duk_push_null(ctx);
-        return 1;
-    }
-
-    js_push_class_object_instance(ctx, camera, "Camera");
-
-    return 1;
-
-}
-
-void jsapi_init_scene(JSVM* vm)
-{
-    duk_context* ctx = vm->GetJSContext();
-
-    jsapi_init_scene_serializable(vm);
-
-    js_class_get_prototype(ctx, "Atomic", "Node");
-    duk_push_c_function(ctx, Node_GetChildrenWithComponent, DUK_VARARGS);
-    duk_put_prop_string(ctx, -2, "getChildrenWithComponent");
-    duk_push_c_function(ctx, Node_GetChildrenWithName, DUK_VARARGS);
-    duk_put_prop_string(ctx, -2, "getChildrenWithName");
-    duk_push_c_function(ctx, Node_GetComponents, DUK_VARARGS);
-    duk_put_prop_string(ctx, -2, "getComponents");
-    duk_push_c_function(ctx, Node_CreateJSComponent, DUK_VARARGS);
-    duk_put_prop_string(ctx, -2, "createJSComponent");
-    duk_push_c_function(ctx, Node_GetJSComponent, 1);
-    duk_put_prop_string(ctx, -2, "getJSComponent");
-    duk_push_c_function(ctx, Node_GetChildAtIndex, 1);
-    duk_put_prop_string(ctx, -2, "getChildAtIndex");
-    duk_push_c_function(ctx, Node_SaveXML, 1);
-    duk_put_prop_string(ctx, -2, "saveXML");
-    duk_push_c_function(ctx, Node_LoadPrefab, 1);
-    duk_put_prop_string(ctx, -2, "loadPrefab");
-    duk_push_c_function(ctx, Node_CreateChildPrefab, 2);
-    duk_put_prop_string(ctx, -2, "createChildPrefab");
-    duk_pop(ctx);
-
-    js_class_get_prototype(ctx, "Atomic", "Scene");
-    duk_push_c_function(ctx, Scene_LoadXML, 1);
-    duk_put_prop_string(ctx, -2, "loadXML");
-    duk_push_c_function(ctx, Scene_GetMainCamera, 0);
-    duk_put_prop_string(ctx, -2, "getMainCamera");
-    duk_pop(ctx);
-
-}
-
-}

+ 4 - 0
Source/AtomicJS/Javascript/JSComponent.cpp

@@ -161,6 +161,10 @@ void JSComponent::ApplyAttributes()
 {
 {
 }
 }
 
 
+bool JSComponent::IsInstanceInitialized() {
+	return instanceInitialized_;
+}
+
 void JSComponent::InitInstance(bool hasArgs, int argIdx)
 void JSComponent::InitInstance(bool hasArgs, int argIdx)
 {
 {
     if (context_->GetEditorContext() || componentFile_.Null())
     if (context_->GetEditorContext() || componentFile_.Null())

+ 1 - 0
Source/AtomicJS/Javascript/JSComponent.h

@@ -78,6 +78,7 @@ public:
 
 
     void SetDestroyed() { destroyed_ = true; }
     void SetDestroyed() { destroyed_ = true; }
 
 
+    bool IsInstanceInitialized();	
     void InitInstance(bool hasArgs = false, int argIdx = 0);
     void InitInstance(bool hasArgs = false, int argIdx = 0);
 
 
     /// Get script attribute
     /// Get script attribute

+ 2 - 0
Source/AtomicJS/Javascript/JSScene.cpp

@@ -95,6 +95,8 @@ static int Node_GetJSComponent(duk_context* ctx)
     {
     {
         JSComponent* component = components[i];
         JSComponent* component = components[i];
         if (component->MatchScriptName(path)) {
         if (component->MatchScriptName(path)) {
+			if(!component->IsInstanceInitialized())
+				component->InitInstance();
 
 
             js_push_class_object_instance(ctx, component, "Component");
             js_push_class_object_instance(ctx, component, "Component");
             return 1;
             return 1;