JavaScript binding for new mesh APIs
[platform/core/uifw/dali-toolkit.git] / plugins / dali-script-v8 / src / actors / actor-wrapper.cpp
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include "actor-wrapper.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/object/type-registry.h>
23 #include <dali-toolkit/public-api/controls/control.h>
24
25 // INTERNAL INCLUDES
26 #include <actors/layer-api.h>
27 #include <actors/actor-api.h>
28 #include <actors/image-actor-api.h>
29 #include <actors/camera-actor-api.h>
30 #include <v8-utils.h>
31 #include <dali-wrapper.h>
32
33 namespace Dali
34 {
35
36 namespace V8Plugin
37 {
38
39 v8::Persistent<v8::ObjectTemplate> ActorWrapper::mActorTemplate;
40 v8::Persistent<v8::ObjectTemplate> ActorWrapper::mImageActorTemplate;
41 v8::Persistent<v8::ObjectTemplate> ActorWrapper::mCameraActorTemplate;
42 v8::Persistent<v8::ObjectTemplate> ActorWrapper::mLayerActorTemplate;
43
44 namespace
45 {
46
47
48 /**
49  * pointer to a persistent template handle
50  */
51 struct ActorTemplate
52 {
53   v8::Persistent<v8::ObjectTemplate>* actorTemplate;
54 };
55
56 /**
57  * array of templates for each type of actor
58  */
59 const ActorTemplate ActorTemplateLookup[]=
60 {
61     { &ActorWrapper::mActorTemplate },        // ACTOR
62     { &ActorWrapper::mImageActorTemplate },   // IMAGE_ACTOR
63     { &ActorWrapper::mLayerActorTemplate },   // LAYER_ACTOR
64     { &ActorWrapper::mCameraActorTemplate}    // CAMERA_ACTOR
65 };
66
67 /**
68  * Bitmask of API's that an actor can support
69  */
70 enum ActorApiBitMask
71 {
72   ACTOR_API              = 1 << 0,
73   IMAGE_ACTOR_API        = 1 << 1,
74   LAYER_API              = 1 << 2,
75   CAMERA_ACTOR_API       = 1 << 3,
76 };
77
78 /**
79  * structure used for the ActorApiLookup.
80  */
81 struct ActorApiStruct
82 {
83   const char* actorName;
84   ActorWrapper::ActorType actorType;
85   Actor (*constructor)( const v8::FunctionCallbackInfo< v8::Value >& args);
86   int supportApis;
87 };
88
89 /**
90  * Lookup table to match a actor type with a constructor and supported API's.
91  * HandleWrapper::ActorType is used to index this table
92  */
93 const ActorApiStruct ActorApiLookup[]=
94 {
95   {"Actor",      ActorWrapper::ACTOR,        ActorApi::New,       ACTOR_API },
96   {"ImageActor", ActorWrapper::IMAGE_ACTOR,  ImageActorApi::New,  ACTOR_API | IMAGE_ACTOR_API   },
97   {"Layer",      ActorWrapper::LAYER_ACTOR,  LayerApi::New,       ACTOR_API | LAYER_API                                },
98   {"CameraActor",ActorWrapper::CAMERA_ACTOR, CameraActorApi::New, ACTOR_API | CAMERA_ACTOR_API                         },
99 };
100
101 const unsigned int ActorApiLookupCount = sizeof(ActorApiLookup)/sizeof(ActorApiLookup[0]);
102
103
104
105 /**
106  * Creates an actor given a type name
107  * Uses the type registry to create an actor of the correct type
108  */
109 Actor CreateActor( const v8::FunctionCallbackInfo< v8::Value >& args,
110                         const std::string& typeName )
111 {
112   Actor actor;
113
114   ActorWrapper::ActorType actorType = ActorWrapper::GetActorType( typeName );
115
116   // if we don't currently support the actor type, then use type registry to create it
117   if( actorType == ActorWrapper::UNKNOWN_ACTOR )
118   {
119       DALI_SCRIPT_EXCEPTION( args.GetIsolate(), "Unknown actor type" );
120       return Actor();
121   }
122   else
123   {
124     // run the constructor for this type of actor so it can pull out
125     // custom parameters, e.g. new ImageActor( MyImage );
126     actor = (ActorApiLookup[actorType].constructor)( args );
127   }
128   return actor;
129 }
130
131
132
133 /**
134  * given an actor type return what api's it supports
135  */
136 int GetActorSupportedApis( ActorWrapper::ActorType type )
137 {
138   return ActorApiLookup[ type].supportApis;
139 }
140
141 /**
142  * Used for the ActorFunctionTable to map function names to functions
143  * with for a specific API
144  */
145 struct ActorFunctions
146 {
147   const char* name;               ///< function name
148   void (*function)( const v8::FunctionCallbackInfo< v8::Value >& args);
149   ActorApiBitMask api;
150 };
151
152 /**
153  * Contains a list of all functions that can be called an
154  * actor / image-actor / layer / camera-actor
155  */
156 const ActorFunctions ActorFunctionTable[]=
157 {
158     /**************************************
159     * Actor API (in order of actor.h)
160     * Any properties that have accessor functions are ignored to avoid duplication
161     **************************************/
162     // ignore. GetName()  use Actor.name
163     // ignore. SetName()  use Actor.name
164     { "GetId",             ActorApi::GetId,            ACTOR_API },
165     { "IsRoot",            ActorApi::IsRoot,           ACTOR_API },
166     { "OnStage",           ActorApi::OnStage,          ACTOR_API },
167     { "IsLayer",           ActorApi::IsLayer,          ACTOR_API },
168     { "GetLayer",          ActorApi::GetLayer,         ACTOR_API },
169     { "Add",               ActorApi::AddActor,         ACTOR_API },
170     { "Remove",            ActorApi::RemoveActor,      ACTOR_API },
171     { "IsEqualTo" ,        ActorApi::IsEqualTo,        ACTOR_API },
172     { "Unparent",          ActorApi::Unparent,         ACTOR_API },
173     { "GetChildCount",     ActorApi::GetChildCount,    ACTOR_API },
174     { "GetChildAt"   ,     ActorApi::GetChildAt,       ACTOR_API },
175     { "FindChildByName",   ActorApi::FindChildByName,  ACTOR_API },
176     { "FindChildById",     ActorApi::FindChildById,    ACTOR_API },
177     { "GetParent" ,        ActorApi::GetParent,        ACTOR_API },
178     { "GetActorType" ,     ActorApi::GetActorType,     ACTOR_API }, // custom for javascript
179
180     // ignore. SetParentOrigin() use Actor.parentOrigin
181     // ignore. GetCurrentParentOrigin()  use Actor.parentOrigin
182     // ignore. SetAnchorPoint()  use Actor.anchorPoint
183     // ignore. GetCurrentAnchorPoint()  use Actor.anchorPoint
184     // ignore. SetSize() use Actor.size
185     // ignore. GetCurrentSize() use Actor.size
186     { "GetNaturalSize",   ActorApi::GetNaturalSize,    ACTOR_API },
187     { "GetWidthForHeight",ActorApi::GetWidthForHeight, ACTOR_API },
188     { "GetHeightForWidth",ActorApi::GetHeightForWidth, ACTOR_API },
189     // ignore. SetPosition(....) use Actor.position
190     // ignore. SetX, SetY, SetZ,  use Actor.position.x, Actor.position.y, Actor.position.z
191     { "TranslateBy",         ActorApi::TranslateBy,              ACTOR_API },
192     // ignore GetCurrentPosition(). use Actor.position
193     // ignore GetCurrentWorldPosition() use Actor.worldPosition
194     // ignore SetPositionInheritanceMode() use Actor.positionInheritance
195     // ignore GetPositionInheritanceMode()  use Actor.positionInheritance
196     // ignore SetOrientation() use Actor.orientation
197     { "RotateBy",         ActorApi::RotateBy,          ACTOR_API },
198     // ignore GetCurrentOrientation() use Actor.orientation
199     // ignore SetInheritOrientation() use Actor.inheritOrientation
200     // ignore IsOrientationInherited() use Actor.inheritOrientation
201     // ignore GetCurrentWorldOrientation() use Actor.worldOrientation
202     // ignore SetScale() use Actor.scale
203     { "ScaleBy",         ActorApi::ScaleBy,            ACTOR_API },
204     // ignore GetCurrentScale() use Actor.scale
205     // ignore GetCurrentWorldScale() use Actor.worldScale
206     // ignore SetInheritScale() use Actor.inheritScale
207     // ignore IsScaleInherited() use Actor.inheritScale
208     // ignore GetCurrentWorldMatrix() use Actor.worldMatrix
209     // ignore SetVisible() use Actor.visible
210     // ignore IsVisible() use Actor.visible
211     // ignore SetOpacity() use Actor.opacity
212     // ignore GetCurrentOpacity() use Actor.opacity
213     // ignore SetColor() use Actor.color
214     // ignore GetCurrentColor() use Actor.color
215     // ignore SetColorMode() use Actor.colorMode
216     // ignore GetColorMode() use Actor.colorMode
217     // ignore GetCurrentWorldColor() use Actor.worldColor
218     // ignore SetInheritShaderEffect() use Actor.inheritShaderEffect
219     // ignore GetInheritShaderEffect() use Actor.inheritShaderEffect
220     // ignore SetDrawMode() use Actor.drawMode
221     // ignore GetDrawMode() use Actor.drawMode
222     // ignore SetSensitive() use Actor.sensitve
223     // ignore IsSensitive() use Actor.sensitive
224     { "ScreenToLocal"       , ActorApi::ScreenToLocal,         ACTOR_API},
225     // ignore SetLeaveRequired() use Actor.leaveRequired
226     // ignore GetLeaveRequired() use Actor.leaveRequired
227     { "SetKeyboardFocusable", ActorApi::SetKeyboardFocusable,  ACTOR_API }, //-- should this be a property???
228     { "IsKeyboardFocusable" , ActorApi::IsKeyboardFocusable,   ACTOR_API }, //-- should this be a property???
229
230     { "AddRenderer",          ActorApi::AddRenderer,           ACTOR_API },
231     { "GetRendererCount",     ActorApi::GetRendererCount,      ACTOR_API },
232     { "GetRendererAt" ,       ActorApi::GetRendererAt,         ACTOR_API },
233     { "RemoveRenderer" ,      ActorApi::RemoveRenderer,        ACTOR_API },
234
235     /**************************************
236      * Layer  API (in order of layer.h)
237      **************************************/
238     { "GetDepth",           LayerApi::GetDepth,                 LAYER_API  },
239     { "Raise",              LayerApi::Raise,                    LAYER_API  },
240     { "Lower",              LayerApi::Lower,                    LAYER_API  },
241     { "RaiseAbove",         LayerApi::RaiseAbove,               LAYER_API  },
242     { "RaiseBelow",         LayerApi::LowerBelow,               LAYER_API  },
243     { "RaiseToTop",         LayerApi::RaiseToTop,               LAYER_API  },
244     { "LowerToBottom",      LayerApi::ToBottom,                 LAYER_API  },
245     { "MoveAbove",          LayerApi::MoveAbove,                LAYER_API  },
246     { "MoveBelow",          LayerApi::MoveBelow,                LAYER_API  },
247     // ignore SetClipping, use layer.clippingEnable
248     // ignore IsClipping, use layer.clippingEnable
249     // ignore SetClippingBox, use layer.clippingBox
250     { "SetDepthTestDisabled", LayerApi::SetDepthTestDisabled,   LAYER_API },
251     { "IsDepthTestDisabled",  LayerApi::IsDepthTestDisabled,    LAYER_API },
252     // @todo SetSortFunction
253
254     /**************************************
255      * Image Actor API (in order of image-actor.h)
256      **************************************/
257
258     { "SetImage",           ImageActorApi::SetImage,              IMAGE_ACTOR_API },
259     { "GetImage",           ImageActorApi::GetImage,              IMAGE_ACTOR_API },
260     // ignore SetPixelArea, use imageActor.pixelArea
261     // ignore GetPixelArea, use imageActor.pixelArea
262     // ignore SetStyle, use imageActor.style
263     // ignore GetStyle, use imageActor.style
264     // ignore SetNinePatchBorder use imageActor.border
265     // ignore GetNinePatchBorder use imageActor.border
266     { "SetSortModifier",    ImageActorApi::SetSortModifier,   IMAGE_ACTOR_API  },
267     { "GetSortModifier",    ImageActorApi::GetSortModifier,   IMAGE_ACTOR_API  },
268     { "SetBlendMode",       ImageActorApi::SetBlendMode,      IMAGE_ACTOR_API  },
269     { "GetBlendMode",       ImageActorApi::GetBlendMode,      IMAGE_ACTOR_API  },
270     { "SetBlendFunc",       ImageActorApi::SetBlendFunc,      IMAGE_ACTOR_API  },
271     { "GetBlendFunc",       ImageActorApi::GetBlendFunc,      IMAGE_ACTOR_API  },
272     { "SetShaderEffect",    ImageActorApi::SetShaderEffect,   IMAGE_ACTOR_API  },
273     { "GetShaderEffect",    ImageActorApi::GetShaderEffect,   IMAGE_ACTOR_API  },
274     { "RemoveShaderEffect", ImageActorApi::RemoveShaderEffect,IMAGE_ACTOR_API  },
275     // ignore SetFadeIn use imageActor.fadeIn
276     // ignore GetFadeIn use imageActor.fadeIn
277     // ignore SetFadeInDuration use imageActor.fadeInDuration
278     // ignore GetFadeInDuration use imageActor.fadeInDuration
279     //{ "GetCurrentImageSize", ImageActorApi::GetCurrentImageSize,  IMAGE_ACTOR_API },
280
281     /**************************************
282      * Mesh Actor API (in order of mesh-actor.h)
283      **************************************/
284     // @todo a version of MeshActor::New( mesh )
285     // @todo a version of MeshActor::New( AnimatableMesh )
286     // @todo SetMaterial
287     // @todo GetMaterial
288     // @todo BindBonesToMesh
289
290     /**************************************
291      * Camera Actor API (in order of camera.h)
292      **************************************/
293     // ignore SetType use camera.type
294     // ignore GetType use camera.type
295     // ignore SetProjectionMode use camera.projectionMode
296     // ignore GetProjectionMode use camera.projectionMode
297     // ignore SetFieldOfView use camera.fieldOfView
298     // ignore GetFieldOfView use camera.fieldOfView
299     // ignore SetAspectRatio use camera.aspectRatio
300     // ignore GetAspectRatio use camera.aspectRatio
301     // ignore SetNearClippingPlane use camera.nearPlaneDistance
302     // ignore GetNearClippingPlane use camera.nearPlaneDistance
303     // ignore SetFarClippingPlane use camera.farPlaneDistance
304     // ignore GetFarClippingPlane use camera.farPlaneDistance
305     // ignore GetTargetPosition use camera.targetPosition
306     // ignore SetInvertYAxis use camera.invertYAxis
307     // ignore GetInvertYAxis use camera.invertYAxis
308     { "SetPerspectiveProjection",   CameraActorApi::SetPerspectiveProjection,   CAMERA_ACTOR_API },
309     { "SetOrthographicProjection",  CameraActorApi::SetOrthographicProjection,  CAMERA_ACTOR_API },
310
311 };
312
313 const unsigned int ActorFunctionTableCount = sizeof(ActorFunctionTable)/sizeof(ActorFunctionTable[0]);
314 } //un-named space
315
316
317 ActorWrapper::ActorWrapper( Actor actor,
318               GarbageCollectorInterface& gc )
319 : HandleWrapper( BaseWrappedObject::ACTOR , actor, gc ),
320   mActor( actor )
321
322 {
323 }
324
325 v8::Handle<v8::Object> ActorWrapper::WrapActor(v8::Isolate* isolate, Actor actor )
326 {
327   v8::EscapableHandleScope handleScope( isolate );
328
329   // Check whether the actor is a Control
330   ActorWrapper::ActorType type = Toolkit::Control::DownCast(actor) ? ACTOR : GetActorType( actor.GetTypeName() );
331   v8::Local<v8::Object> object = WrapActor( isolate, actor, type );
332
333   return handleScope.Escape( object );
334 }
335
336 Actor ActorWrapper::GetActor()
337 {
338   return mActor;
339 }
340
341 v8::Handle<v8::Object> ActorWrapper::WrapActor( v8::Isolate* isolate, Actor actor, ActorType actorType )
342 {
343   v8::EscapableHandleScope handleScope( isolate );
344   v8::Local<v8::ObjectTemplate> objectTemplate;
345
346   objectTemplate = GetActorTemplate( isolate, actorType );
347
348   // create an instance of the template
349   v8::Local<v8::Object> localObject = objectTemplate->NewInstance();
350
351   // create teh actor object
352   ActorWrapper* pointer = new ActorWrapper( actor, Dali::V8Plugin::DaliWrapper::Get().GetDaliGarbageCollector() );
353
354   // assign the JavaScript object to the wrapper.
355   // This also stores Dali object, in an internal field inside the JavaScript object.
356   pointer->SetJavascriptObject( isolate, localObject );
357
358   return handleScope.Escape( localObject );
359 }
360
361 v8::Local<v8::ObjectTemplate> ActorWrapper::GetActorTemplate( v8::Isolate* isolate, ActorWrapper::ActorType type )
362 {
363   v8::EscapableHandleScope handleScope( isolate );
364   v8::Local<v8::ObjectTemplate> objectTemplate;
365
366   if( ActorTemplateLookup[type].actorTemplate->IsEmpty() )
367   {
368     objectTemplate = MakeDaliActorTemplate( isolate, type );
369     ActorTemplateLookup[type].actorTemplate->Reset( isolate, objectTemplate );
370   }
371   else
372   {
373     // get the object template
374     objectTemplate = v8::Local<v8::ObjectTemplate>::New( isolate, *ActorTemplateLookup[type].actorTemplate );
375   }
376
377   return handleScope.Escape( objectTemplate );
378 }
379
380 v8::Handle<v8::ObjectTemplate> ActorWrapper::MakeDaliActorTemplate( v8::Isolate* isolate, ActorType actorType )
381 {
382   v8::EscapableHandleScope handleScope( isolate );
383
384   v8::Local<v8::ObjectTemplate> objTemplate = v8::ObjectTemplate::New();
385
386   objTemplate->SetInternalFieldCount( BaseWrappedObject::FIELD_COUNT );
387
388   // find out what API's this actor supports
389   int supportApis = GetActorSupportedApis( actorType );
390
391   // add our function properties
392   for( unsigned int i = 0; i < ActorFunctionTableCount; ++i )
393   {
394     const ActorFunctions property =  ActorFunctionTable[i];
395
396     // check to see if the actor supports a certain type of API
397     // e.g. ImageActor will support ACTOR_API, RENDERABLE_API and IMAGE_ACTOR_API
398     if( supportApis &  property.api )
399     {
400       std::string funcName = V8Utils::GetJavaScriptFunctionName( property.name);
401
402       objTemplate->Set( v8::String::NewFromUtf8(   isolate, funcName.c_str() ),
403                       v8::FunctionTemplate::New( isolate, property.function ) );
404     }
405   }
406
407   // property handle intercepts property getters and setters and signals
408   HandleWrapper::AddInterceptsToTemplate( isolate, objTemplate );
409
410
411   return handleScope.Escape( objTemplate );
412 }
413
414 void ActorWrapper::NewActor( const v8::FunctionCallbackInfo< v8::Value >& args)
415 {
416   v8::Isolate* isolate = args.GetIsolate();
417   v8::HandleScope handleScope( isolate );
418
419   if( !args.IsConstructCall() )
420   {
421     DALI_SCRIPT_EXCEPTION( isolate, "constructor called without 'new" );
422     return;
423   }
424
425   // find out the callee function name...e.g. ImageActor, MeshActor
426   v8::Local<v8::Function> callee = args.Callee();
427   v8::Local<v8::Value> v8String = callee->GetName();
428   std::string typeName = V8Utils::v8StringToStdString( v8String );
429
430   // create a new actor based on type, using the type registry.
431   Actor actor = CreateActor( args, typeName );
432
433   v8::Local<v8::Object> localObject = WrapActor( isolate, actor );
434
435   args.GetReturnValue().Set( localObject );
436 }
437
438 void ActorWrapper::NewControl( const v8::FunctionCallbackInfo< v8::Value >& args)
439 {
440   v8::Isolate* isolate = args.GetIsolate();
441   v8::HandleScope handleScope( isolate );
442
443   if( !args.IsConstructCall() )
444   {
445     DALI_SCRIPT_EXCEPTION( isolate, "constructor called without 'new" );
446     return;
447   }
448
449   bool found( false );
450   std::string controlName = V8Utils::GetStringParameter( PARAMETER_0, found, isolate,  args );
451
452   if( !found )
453   {
454     DALI_SCRIPT_EXCEPTION( isolate, "missing control name" );
455     return;
456   }
457   Actor control;
458   Dali::TypeInfo typeInfo = Dali::TypeRegistry::Get().GetTypeInfo( controlName );
459   if( typeInfo ) // handle, check if it has a value
460   {
461     Dali::BaseHandle handle = typeInfo.CreateInstance();
462     if( handle )
463     {
464       control = Actor::DownCast( handle );
465     }
466   }
467
468   v8::Local<v8::Object> localObject = WrapActor( isolate, control, ACTOR );
469
470   args.GetReturnValue().Set( localObject );
471 }
472
473
474 /**
475  * given an actor type name, e.g. ImageActor returns the type, e.g. ActorWrapper::IMAGE_ACTOR
476  */
477 ActorWrapper::ActorType ActorWrapper::GetActorType( const std::string& name )
478 {
479   for( unsigned int i = 0 ; i < ActorApiLookupCount ; i++ )
480   {
481     if( ActorApiLookup[i].actorName == name )
482     {
483       return ActorApiLookup[i].actorType;
484     }
485   }
486   return ActorWrapper::UNKNOWN_ACTOR;
487 }
488
489
490
491 } // namespace V8Plugin
492
493 } // namespace Dali