├── .gitignore
├── lib
├── list.js
├── text.js
├── ex02.js
├── core.js
├── blendmode.js
├── ejoy2dgame.js
├── material.js
├── ex01.js
├── scissor.js
├── sprite_trans.js
├── ex04.js
├── ex05.js
├── ex09.js
├── main.js
├── screen.js
├── uri.js
├── string.js
├── geometry.js
├── spritepack.js
├── path.js
├── utils.js
├── texture.js
├── matrix.js
├── renderbuffer.js
├── richtext.js
├── dfont.js
├── label.js
├── http.js
└── shader.js
├── sample
├── sample.1.png
├── ex02.html
├── ex05.html
├── ex01.html
├── ex04.html
└── sample.json
├── LICENSE
├── README.md
├── simple_http_svr.go
└── tools
└── ejoy2d2json
├── main.lua
└── json.lua
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | static/.vscode
3 |
--------------------------------------------------------------------------------
/lib/list.js:
--------------------------------------------------------------------------------
1 |
2 | ejoy2d.list = function() {
3 |
4 | }
5 |
--------------------------------------------------------------------------------
/sample/sample.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sqrt2v/ejoy2d_js/HEAD/sample/sample.1.png
--------------------------------------------------------------------------------
/lib/text.js:
--------------------------------------------------------------------------------
1 |
2 | ejoy2d.text = ((function () {
3 | var context;
4 | return {
5 | init : function() {
6 | var canvas = document.getElementById("text");
7 | // make a 2D context for it
8 | var ctx = textCanvas.getContext("2d");
9 | }
10 | };
11 | })())
12 |
--------------------------------------------------------------------------------
/lib/ex02.js:
--------------------------------------------------------------------------------
1 | var ex02 =((function(){
2 |
3 | var isInited = false;
4 | var TEX_ID = 1;
5 |
6 | var vb = [
7 | 88, 0, 88, 45, 147, 45, 147, 0, // texture coord
8 | -958, -580, -958, 860, 918, 860, 918, -580, // screen coord, 16x pixel, (0,0) is the center of screen
9 | ]
10 |
11 | return {
12 | init:function() {
13 | var img = new Image();
14 | img.src = "sample.1.png";
15 | img.onload = function() {
16 | console.log(img.name, img.width, img.height);
17 | console.log("load texture succeed", typeof img);
18 | ejoy2d.texture.load_img(TEX_ID, TEXTURE_RGBA8, img);
19 | isInited = true;
20 | };
21 | img.onerror = function () {
22 | console.log("Failed to load image: sample.1.png");
23 | }
24 | },
25 | logicFrame:function()
26 | {
27 | },
28 | draw:function(){
29 | shader.clear(0xff808080);
30 | if (isInited) {
31 | ejoy2d.shader.draw(TEX_ID, vb)
32 | }
33 | }
34 | };
35 |
36 | })());
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 小V
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/lib/core.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/8/20.
3 | */
4 |
5 | ejoy2d = {};
6 |
7 | ejoy2d.extend = function(target, ex) {
8 | var prop,
9 | copy;
10 |
11 | for(prop in ex) {
12 | copy = ex[prop];
13 | if(pc.type(copy) == "object") {
14 | target[prop] = pc.extend({}, copy);
15 | } else if(pc.type(copy) == "array") {
16 | target[prop] = pc.extend([], copy);
17 | } else {
18 | target[prop] = copy;
19 | }
20 | }
21 | return target;
22 | };
23 |
24 | /**
25 | * Return true if the Object is not undefined
26 | * @param {Object} o The Object to test
27 | * @returns {Boolean} True if the Object is not undefined
28 | * @function
29 | * @name pc.isDefined
30 | */
31 | ejoy2d.isDefined= function(o) {
32 | var a;
33 | return (o !== a);
34 | };
35 |
36 | /**
37 | * Convert an array-like object into a normal array.
38 | * For example, this is useful for converting the arguments object into an array.
39 | * @param {Object} arr The array to convert
40 | * @return {Array} An array
41 | * @function
42 | * @name pc.makeArray
43 | */
44 | ejoy2d.makeArray = function (arr) {
45 | var i,
46 | ret = [],
47 | length = arr.length;
48 |
49 | for(i = 0; i < length; ++i) {
50 | ret.push(arr[i]);
51 | }
52 |
53 | return ret;
54 | };
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | > ejoy2d_js: jvascript and webGL implementation of ejoy2d
5 |
6 | General
7 | ===
8 | javascript and webGL implementation of 2d game engine [ejoy2d](https://github.com/ejoy/ejoy2d)
9 |
10 | now it implements core API of ejoy2d but some feature still missing, include:
11 |
12 | - rich text
13 | - particle
14 |
15 | Tools
16 | ===
17 | ejoy2d_js can not use the raw ejoy2d assets,because is lua file. You can use the tool provided by the the repo to convert ejoy2d lua asset to json
18 |
19 | see tools/ejoy2d2json/
20 |
21 | to run,you should have [lua](http://www.lua.org/) installed, then run:
22 |
23 | `lua main.lua input output`
24 |
25 | it will convert input.lua to output.json
26 |
27 | then you can use output.json as asset for ejoy2d_js
28 |
29 | Run example
30 | ===
31 | the repo provide an simple http server implement in go-lang for developer and debug
32 |
33 | see simple_http_svr.go
34 |
35 | to build, you need install [go-lang](https://golang.org)
36 |
37 | and you can build with (assumed the current directory is $GOPATH)
38 |
39 | `go build ejoy2d_js
40 |
41 | ./ejoy2d.js ./src/ejoy2d_js (pass the repo path to the program, to find the assets, js, html etc)`
42 |
43 | then you can open browser
44 |
45 | - localhost:9528/ex01.html
46 | - localhost:9528/ex02.html
47 | - localhost:9528/ex04.html
48 | - localhost:9528/ex05.html
49 |
50 |
51 | all samle files are located in sample fold.
52 |
53 | enjoy
54 |
55 | feel free to contact me via email
56 |
57 |
--------------------------------------------------------------------------------
/lib/blendmode.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/6/26.
3 | */
4 | var BLEND_GL_ZERO = 0;
5 | var BLEND_GL_ONE = 1;
6 | var BLEND_GL_SRC_COLOR = 0x0300;
7 | var BLEND_GL_ONE_MINUS_SRC_COLOR = 0x0301;
8 | var BLEND_GL_SRC_ALPHA = 0x0302;
9 | var BLEND_GL_ONE_MINUS_SRC_ALPHA = 0x0303;
10 | var BLEND_GL_DST_ALPHA = 0x0304;
11 | var BLEND_GL_ONE_MINUS_DST_ALPHA = 0x0305;
12 | var BLEND_GL_DST_COLOR = 0x0306;
13 | var BLEND_GL_ONE_MINUS_DST_COLOR = 0x0307;
14 | var BLEND_GL_SRC_ALPHA_SATURATE = 0x0308;
15 | ejoy2d.blendmode = {
16 | blendMode : function (gl_mode) {
17 | switch(gl_mode) {
18 | case BLEND_GL_ZERO:
19 | return BLEND_ZERO;
20 | case BLEND_GL_ONE:
21 | return BLEND_ONE;
22 | case BLEND_GL_SRC_COLOR:
23 | return BLEND_SRC_COLOR;
24 | case BLEND_GL_ONE_MINUS_SRC_COLOR:
25 | return BLEND_ONE_MINUS_SRC_COLOR;
26 | case BLEND_GL_SRC_ALPHA:
27 | return BLEND_SRC_ALPHA;
28 | case BLEND_GL_ONE_MINUS_SRC_ALPHA:
29 | return BLEND_ONE_MINUS_SRC_ALPHA;
30 | case BLEND_GL_DST_ALPHA:
31 | return BLEND_DST_ALPHA;
32 | case BLEND_GL_ONE_MINUS_DST_ALPHA:
33 | return BLEND_ONE_MINUS_DST_ALPHA;
34 | case BLEND_GL_DST_COLOR:
35 | return BLEND_DST_COLOR;
36 | case BLEND_GL_ONE_MINUS_DST_COLOR:
37 | return BLEND_ONE_MINUS_DST_COLOR;
38 | case BLEND_GL_SRC_ALPHA_SATURATE:
39 | return BLEND_SRC_ALPHA_SATURATE;
40 | }
41 | return BLEND_DISABLE;
42 | }
43 | };
44 |
--------------------------------------------------------------------------------
/simple_http_svr.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | // import "io"
4 | import (
5 | "flag"
6 | "fmt"
7 | "html/template"
8 | "io/ioutil"
9 | "log"
10 | "net/http"
11 | "os"
12 | "strings"
13 | )
14 |
15 | var resRoot string
16 |
17 | func main() {
18 | flag.Parse()
19 | resRoot = flag.Arg(0)
20 | if flag.NArg() < 1 {
21 | log.Fatal("Error! should pass res root as parameter")
22 | return
23 | }
24 | fmt.Println("--------------123")
25 | fmt.Println(resRoot)
26 | http.HandleFunc("/", handleExample)
27 | err := http.ListenAndServe(":9527", nil)
28 | if err != nil {
29 | log.Fatal("fatel: listen and serve", err)
30 | }
31 | }
32 |
33 | func handleExample(w http.ResponseWriter, r *http.Request) {
34 | r.ParseForm() //解析参数,默认是不会解析的
35 |
36 | path := r.URL.Path
37 | t := path[strings.LastIndex(path, "."):]
38 |
39 | fmt.Println("path", r.URL.Path)
40 | fmt.Println("type:", t)
41 |
42 | switch t {
43 | case ".js":
44 | handleAsset("text/javascript", resRoot+"lib/"+path, w)
45 | case ".json":
46 | handleAsset("application/json", resRoot+"sample/"+path, w)
47 | case ".png":
48 | handleAsset("image/x-png", resRoot+"sample/"+path, w)
49 | case ".html":
50 | handleHtml(resRoot+"/sample/"+path, w)
51 | default:
52 | }
53 |
54 | }
55 |
56 | func handleAsset(ct string, path string, w http.ResponseWriter) {
57 | w.Header().Set("content-type", ct)
58 |
59 | fin, err := os.Open(path)
60 |
61 | defer fin.Close()
62 |
63 | if err != nil {
64 | log.Fatal("Static resources:", err)
65 | }
66 |
67 | fd, err := ioutil.ReadAll(fin)
68 | if err != nil {
69 | log.Fatal(err)
70 | }
71 | w.Write(fd)
72 | }
73 |
74 | func handleHtml(path string, w http.ResponseWriter) {
75 | t, _ := template.ParseFiles(path)
76 | t.Execute(w, nil)
77 | }
78 |
--------------------------------------------------------------------------------
/lib/ejoy2dgame.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/6/27.
3 | */
4 |
5 | var InputType = {
6 | TOUCH_BEGIN : 0,
7 | TOUCH_END : 1,
8 | TOUCH_MOVE : 2
9 | };
10 |
11 | ejoy2d.game = function(fw) {
12 | _G.OS = "js";
13 | this.fw = fw;
14 |
15 | ejoy2d.shader.init();
16 | ejoy2d.screen.init(1024, 768, 1.0);
17 |
18 | ejoy2d.label.init();
19 | ejoy2d.label.load();
20 | this.real_time = 0.0;
21 | this.logic_time = 0.0;
22 | this.LOGIC_FRAME = 30;
23 | this.oneInvFrame = 1.0/30.0;
24 | };
25 |
26 |
27 |
28 | ejoy2d.game.prototype = {
29 | exit:function(fw) {
30 | ejoy2d.label.unload();
31 | ejoy2d.texture.exit();
32 | ejoy2d.shader.unload();
33 | },
34 |
35 | setLogicFrame:function(fram_rate){
36 | this.LOGIC_FRAME = frameRate;
37 | this.oneInvFrame = 1.0/frameRate;
38 | },
39 |
40 | update:function(dt) {
41 | // if (this.logic_time == 0.0) {
42 | // this.real_time = this.oneInvFrame;
43 | // } else {
44 | // this.real_time += dt;
45 | // }
46 | // console.log("time:", this.logic_time, this.real_time, dt);
47 | // while (this.logic_time < this.real_time) {
48 | // this.fw.logicFrame();
49 | // this.logic_time += this.oneInvFrame;
50 | // }
51 | this.fw.logicFrame();
52 | },
53 | draw:function() {
54 | this.fw.draw();
55 | ejoy2d.shader.flush();
56 | ejoy2d.label.flush();
57 | },
58 | touch:function(id, x, y, status) {
59 | this.fw.touch(status, x, y);
60 | },
61 | gesture:function(ty, x1, y1, x2, y2, s) {
62 | this.fw.gesture(ty, x1, y1, x2, y2, s);
63 | },
64 | message:function(id, state, data, n) {
65 | this.fw.message(state, data, n);
66 | },
67 | pause:function(){
68 | this.fw.pause();
69 | },
70 | resume:function(){
71 | this.fw.resume();
72 | }
73 | };
74 |
--------------------------------------------------------------------------------
/sample/ex02.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ejoy2d-js
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | Debug draw demo
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/sample/ex05.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ejoy2d-js
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | Mount sprite
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/sample/ex01.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ejoy2d-js
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | Base sprite draw
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/sample/ex04.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ejoy2d-js
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | Hit test. Click the mine sprite
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/lib/material.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/6/26.
3 | */
4 |
5 | ejoy2d.material = function(){
6 | this.texture = new Array(MAX_TEXTURE_CHANNEL);
7 | this.uniform_enable = new Array(MAX_UNIFORM);
8 | };
9 | ejoy2d.material.prototype = {
10 | init:function(RS,prog) {
11 | this.p = p;
12 | },
13 | apply:function(RS, prog) {
14 | var p = this.p;
15 | if (p != RS.program[prog])
16 | return;
17 | if (p.material == m) {
18 | return;
19 | }
20 | p.material = m;
21 | p.reset_uniform = true;
22 | for (var i=0;i< p.uniform_number;i++) {
23 | if (m.uniform_enable[i]) {
24 | var u = p.uniform[i];
25 | if (u.loc != null) {
26 | render.shader_setuniform(u.loc, u.type, this.uniform, u.offset);
27 | }
28 | }
29 | }
30 | for (var i=0;i< p.texture_number;i++) {
31 | var tex = this.texture[i];
32 | if (tex) {
33 | var glid = texture.glid(tex);
34 | if (glid) {
35 | shader.texture(glid, i);
36 | }
37 | }
38 | }
39 | },
40 |
41 | ///////////////////////////////////
42 | /////////////// API ///////////////
43 | setuniform:function(index, n, v) {
44 | var p = this.p;
45 | console.assert(index >= 0 && index < p.uniform_number);
46 | var u = p.uniform[index];
47 | if (shader.uniformsize(u.type) != n) {
48 | return true;
49 | }
50 | var offset = u.uniform;
51 | for(var i =0; i < n;++i) {
52 | this.uniform[offset +i] = v[i];
53 | }
54 | this.uniform_enable[index] = true;
55 | return false;
56 | },
57 | settexture:function(channel, texture) {
58 | if (channel >= MAX_TEXTURE_CHANNEL) {
59 | return true;
60 | }
61 | this.texture[channel] = texture;
62 | return false;
63 | }
64 | /////////// end of API ////////////////
65 | ///////////////////////////////////////
66 | };
--------------------------------------------------------------------------------
/lib/ex01.js:
--------------------------------------------------------------------------------
1 | var ex01 =((function(){
2 |
3 |
4 | var isInited = false;
5 |
6 | var obj;
7 | var turret;
8 | var obj2;
9 |
10 |
11 |
12 | var srt = {
13 | offx:512*SCREEN_SCALE,
14 | offy:384*SCREEN_SCALE,
15 | scalex : 1024 * 1.2,
16 | scaley : 1024 * 1.2,
17 | rot: 0
18 | };
19 |
20 | //var img_src = document.getElementsByName("img_src").getAttribute(src);
21 | ///console.log("-------------->>????aoaoao--->>", img_src);
22 |
23 | return {
24 | init:function() {
25 | //shader.load(geometryShaderID, geoFS, geoVS);
26 | // shader.load(BuiltinProgram.picture, spriteFS, spriteVS);
27 | //geometry.setprogram(geometryShaderID);
28 | var img = new Image();
29 | img.src = "sample.1.png";
30 | img.onload = function() {
31 | console.log(img.name, img.width, img.height);
32 | console.log("load texture succeed", typeof img);
33 | ejoy2d.texture.load_img(1, TEXTURE_RGBA8, img);
34 | ejoy2d.http.get("sample.json",function(resp) {
35 | if(resp != null) {
36 | console.log("get sample.json succeed");
37 | var sp = new ejoy2d.spritepack(resp,null);
38 | var id = sp.getIDByName("cannon");
39 | obj = new ejoy2d.sprite(sp, id);
40 | turret = obj.fetch("turret");
41 | obj.ps(-100, 0, 0.5);
42 |
43 | id = sp.getIDByName("mine");
44 | obj2 = new ejoy2d.sprite(sp, id);
45 |
46 | obj2.ps(100, 0);
47 | obj2.ps(1.2);
48 |
49 | var resource = obj2.fetch("resource")
50 | resource.setframe(10, false);
51 |
52 | var label = obj2.fetch("label");
53 | var aabb = [];
54 | obj2.aabb(srt, true, aabb);
55 | var w = Math.floor(aabb[2] - aabb[0]);
56 | var h = Math.floor(aabb[3] - aabb[1]);
57 | var aabbStr = "AABB:" + w.toString() + "x" + h.toString();
58 | label.setText(aabbStr);
59 |
60 | isInited = true;
61 | }
62 | });
63 | };
64 | img.onerror = function () {
65 | console.log("Failed to load image: sample.1.png");
66 | }
67 | },
68 | logicFrame:function()
69 | {
70 | if(isInited) {
71 | turret.setframe(turret.frame +1, false);
72 | obj2.setframe(obj2.frame +1, false);
73 | }
74 | },
75 | draw:function(){
76 | shader.clear(0xff808080);
77 | if (isInited) {
78 | obj.draw(srt);
79 | obj2.draw(srt);
80 | }
81 | }
82 | };
83 |
84 | })());
85 |
--------------------------------------------------------------------------------
/lib/scissor.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/6/22.
3 | */
4 |
5 | ejoy2d.scissor = (function(){
6 | var SCISSOR_MAX = 8;
7 | var scissor_tmp_array = new Array(4);
8 |
9 | var S = {};
10 | S.depth = 0;
11 | var box = new Array(SCISSOR_MAX);
12 | var i =0;
13 | for(i =0; i < SCISSOR_MAX; ++i) {
14 | var b = {
15 | x:0,
16 | y:0,
17 | width:0,
18 | height:0,
19 | };
20 | box[i] = b;
21 | }
22 | S.box = box;
23 |
24 |
25 | S._intersection = function(b, output) {
26 | var newx = b.x > output[0] ? b.x : output[0];
27 | var newy = b.y > output[1] ? b.y : output[1];
28 |
29 | var bx = b.x + b.width;
30 | var by = b.y + b.height;
31 | var ax = output[0] + output[2];
32 | var ay = output[1] + output[3];
33 | var neww = (bx > ax ? ax : bx) - newx;
34 | var newh = (by > ay ? ay : by) - newy;
35 |
36 | output[0] = newx;
37 | output[1] = newy;
38 | output[2] = neww;
39 | output[3] = newh;
40 | };
41 | S.push = function(x, y, w, h) {
42 | console.assert(this.depth < SCISSOR_MAX);
43 | shader.flush();
44 | if (this.depth == 0) {
45 | shader.scissortest(1);
46 | }
47 |
48 | if (this.depth >= 1) {
49 | scissor_tmp_array[0] = x;
50 | scissor_tmp_array[1] = y;
51 | scissor_tmp_array[2] = w;
52 | scissor_tmp_array[3] = h;
53 | this._intersection(this.box[this.depth-1], scissor_tmp_array);
54 | x = scissor_tmp_array[0];
55 | y = scissor_tmp_array[1];
56 | w = scissor_tmp_array[2];
57 | h = scissor_tmp_array[3];
58 | }
59 |
60 | var s = this.box[this.depth++];
61 | s.x = x;
62 | s.y = y;
63 | s.width = w;
64 | s.height = h;
65 | ejoy2d.screen.scissor(s.x, s.y, s.width, s.height);
66 | };
67 |
68 | S.pop = function() {
69 | var S = this.S;
70 | console.assert(this.depth > 0);
71 | shader.flush();
72 | --this.depth;
73 | if (this.depth == 0) {
74 | shader.scissortest(0);
75 | return;
76 | }
77 | var s = this.box[this.depth-1];
78 | ejoy2d.screen.scissor(s.x, s.y, s.width, s.height);
79 | }
80 | return S;
81 | }());
--------------------------------------------------------------------------------
/lib/sprite_trans.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/10/18.
3 | */
4 |
5 | ejoy2d.sprite_trans = function () {
6 | this.color = 0xffffffff;
7 | this.additive = 0;
8 | this.program = BuiltinProgram.default;
9 | };
10 |
11 | ejoy2d.sprite_trans.prototype = ((function() {
12 | var color_mul = function(c1,c2) {
13 | var r1 = (c1 >> 24) & 0xff;
14 | var g1 = (c1 >> 16) & 0xff;
15 | var b1 = (c1 >> 8) & 0xff;
16 | var a1 = (c1) & 0xff;
17 | var r2 = (c2 >> 24) & 0xff;
18 | var g2 = (c2 >> 16) & 0xff;
19 | var b2 = (c2 >> 8) & 0xff;
20 | var a2 = c2 & 0xff;
21 |
22 | return (r1 * r2 /255) << 24 |
23 | (g1 * g2 /255) << 16 |
24 | (b1 * b2 /255) << 8 |
25 | (a1 * a2 /255) ;
26 | };
27 |
28 | var clamp =function(c) {
29 | return ((c) > 255 ? 255 : (c));
30 | };
31 |
32 | var color_add = function(c1, c2) {
33 | var r1 = (c1 >> 16) & 0xff;
34 | var g1 = (c1 >> 8) & 0xff;
35 | var b1 = (c1) & 0xff;
36 | var r2 = (c2 >> 16) & 0xff;
37 | var g2 = (c2 >> 8) & 0xff;
38 | var b2 = (c2) & 0xff;
39 | return clamp(r1+r2) << 16 |
40 | clamp(g1+g2) << 8 |
41 | clamp(b1+b2);
42 | };
43 | var log_cnt = 0;
44 |
45 | return {
46 | copyFrom : function(a){
47 | if(a.mat)
48 | this.mat = a.mat.clone();
49 | this.color = a.color;
50 | this.additive = a.additive;
51 | this.program = a.program;
52 | },
53 | mul: function(a, b, output) {
54 | this.copyFrom(a);
55 | if (!b) {
56 | return this;
57 | }
58 | if (!this.mat) {
59 | this.mat = b.mat?b.mat.clone() : new ejoy2d.matrix();
60 | } else if (b.mat) {
61 | this.mat.mul(this.mat, b.mat);
62 | }
63 |
64 | if (this.color == 0xffffffff) {
65 | this.color = b.color;
66 | } else if (b.color != 0xffffffff) {
67 | this.color = color_mul(this.color, b.color);
68 | }
69 | if (this.additive == 0) {
70 | this.additive = b.additive;
71 | } else if (b.additive != 0) {
72 | this.additive = color_add(this.additive, b.additive);
73 | }
74 | if (this.program == BuiltinProgram.default) {
75 | this.program = b.program;
76 | }
77 | return this;
78 | }
79 | };
80 | })());
81 |
--------------------------------------------------------------------------------
/lib/ex04.js:
--------------------------------------------------------------------------------
1 | var ex04 =((function(){
2 |
3 |
4 | var isInited = false;
5 |
6 | var obj;
7 |
8 | var srt = {
9 | offx:512*SCREEN_SCALE,
10 | offy:384*SCREEN_SCALE,
11 | scalex : 1024 * 1.2,
12 | scaley : 1024 * 1.2,
13 | rot: 0
14 | };
15 |
16 | var scissor = false;
17 |
18 | return {
19 | init:function() {
20 | //shader.load(geometryShaderID, geoFS, geoVS);
21 | // shader.load(BuiltinProgram.picture, spriteFS, spriteVS);
22 | //geometry.setprogram(geometryShaderID);
23 | var img = new Image();
24 | img.src = "sample.1.png";
25 | img.onload = function() {
26 | console.log(img.name, img.width, img.height);
27 | console.log("load texture succeed", typeof img);
28 | ejoy2d.texture.load_img(1, TEXTURE_RGBA8, img);
29 | ejoy2d.http.get("sample.json",function(resp) {
30 | if(resp != null) {
31 | console.log("get sample.json succeed");
32 | var sp = new ejoy2d.spritepack(resp,null);
33 |
34 | var id = sp.getIDByName("mine");
35 | obj = new ejoy2d.sprite(sp, id);
36 |
37 | //obj.ps(100, 0);
38 | //obj.ps(1.2);
39 |
40 | var resource = obj.fetch("resource")
41 | resource.setframe(10, false);
42 | isInited = true;
43 | }
44 | });
45 | };
46 | img.onerror = function () {
47 | console.log("Failed to load image: sample.1.png");
48 | }
49 | },
50 | logicFrame:function()
51 | {
52 | if(isInited) {
53 | obj.setframe(obj.frame +1, false);
54 | }
55 | },
56 | draw:function(){
57 | shader.clear(0xff808080);
58 | if (isInited) {
59 | obj.draw(srt);
60 | }
61 | },
62 | touch:function(what, x, y) {
63 | //console.log("---->>> aoaoao touch:", what, x, y);
64 | if(what == InputType.TOUCH_END) {
65 | var touched = obj.test(x*SCREEN_SCALE, y*SCREEN_SCALE, srt);
66 | if(touched) {
67 | if(touched.name == "label") {
68 | touched.setText("Touch label");
69 | }
70 | if(touched.name == "panel") {
71 | scissor = !scissor;
72 | touched.enableScissor(scissor);
73 | var label = obj.fetch("label");
74 | label.setText(scissor?"Set Scissor":"Clear Scor");
75 | }
76 | }
77 | else
78 | {
79 | var label = obj.fetch("label");
80 | label.setText("Not Hit");
81 | }
82 |
83 | }
84 | }
85 | };
86 |
87 | })());
88 |
--------------------------------------------------------------------------------
/lib/ex05.js:
--------------------------------------------------------------------------------
1 | var ex05 =((function(){
2 |
3 | var isInited = false;
4 | var obj;
5 | var turret;
6 | var frame = 0;
7 |
8 | var srt = {
9 | offx:512*SCREEN_SCALE,
10 | offy:384*SCREEN_SCALE,
11 | scalex : 1024,
12 | scaley : 1024,
13 | rot: 0
14 | };
15 |
16 | return {
17 | init:function() {
18 | //shader.load(geometryShaderID, geoFS, geoVS);
19 | // shader.load(BuiltinProgram.picture, spriteFS, spriteVS);
20 | //geometry.setprogram(geometryShaderID);
21 | var img = new Image();
22 | img.src = "sample.1.png";
23 | img.onload = function() {
24 | console.log(img.name, img.width, img.height);
25 | console.log("load texture succeed", typeof img);
26 | ejoy2d.texture.load_img(1, TEXTURE_RGBA8, img);
27 | ejoy2d.http.get("sample.json",function(resp) {
28 | if(resp != null) {
29 | console.log("get sample.json succeed");
30 | var sp = new ejoy2d.spritepack(resp,null);
31 | var id = sp.getIDByName("cannon");
32 | obj = new ejoy2d.sprite(sp, id);
33 | turret = obj.fetch("turret");
34 |
35 | var labelData ={
36 | data :[
37 | {
38 | type : SpriteType.label,
39 | color : 0xffffffff,
40 | width : 100,
41 | height : 100,
42 | align : 0,
43 | size : 30,
44 | edge : false,
45 | auto_scale : true,
46 | }
47 | ]
48 | };
49 | var label = new ejoy2d.sprite(labelData, 0);
50 | label.setText("Hello");
51 | var idx = turret.child("anchor");
52 | console.log(idx);
53 | turret.mount(idx, label);
54 | isInited = true;
55 | }
56 | });
57 | };
58 | img.onerror = function () {
59 | console.log("Failed to load image: sample.1.png");
60 | }
61 | },
62 | logicFrame:function() {
63 | if(isInited) {
64 | turret.setframe(turret.frame +1, false);
65 | }
66 | },
67 | draw:function(){
68 | shader.clear(0xff808080);
69 | if (isInited) {
70 | obj.draw(srt);
71 | }
72 | },
73 | touch:function(what, x, y) {
74 |
75 | if(what == InputType.TOUCH_END) {
76 | frame = frame +1;
77 | console.log(frame)
78 | }
79 |
80 | }
81 | };
82 |
83 | })());
84 |
--------------------------------------------------------------------------------
/tools/ejoy2d2json/main.lua:
--------------------------------------------------------------------------------
1 | local json = require('json')
2 |
3 | local f, o = ...
4 |
5 | print('---->>> input f:', f)
6 |
7 | local data = require(f)
8 |
9 | local types = {
10 | empty =0,
11 | picture =1,
12 | animation =2,
13 | polygon = 3,
14 | label = 4,
15 | pannel = 5,
16 | anchor = 6,
17 | matrix = 7,
18 | }
19 |
20 | local rlt = {}
21 | for k,v in pairs(data) do
22 | local t = {}
23 | t[1] = assert(types[v.type])
24 | if v.type == 'matrix' then
25 | t[2] = v[1]
26 | elseif v.type == 'picture' then
27 | t[2] = v.id
28 | local p = {}
29 | t[3] = p
30 | local info = v[1]
31 | p[1] = info.tex
32 | p[2] = info.src
33 | p[3] = info.screen
34 | elseif v.type == 'animation' then
35 | t[2] = v.id
36 | -- components
37 | local cc = {}
38 | for _, cmp in ipairs(v.component) do
39 | if not cmp.name then
40 | table.insert(cc, cmp.id)
41 | else
42 | local c = {}
43 | if not cmp.id then
44 | c[1] = -1
45 | else
46 | c[1] = cmp.id
47 | end
48 | c[2] = cmp.name
49 | table.insert(cc, c)
50 | end
51 | end
52 | t[3] = cc
53 | -- frame
54 | local frames = {}
55 | for _, f in ipairs(v[1]) do
56 | local nf = {}
57 | for _, sf in ipairs(f) do
58 | if type(sf) == 'table' then
59 | local fc = {}
60 | fc[1] = sf.index
61 | fc[2] = sf.mat
62 | if sf.touch then
63 | fc[3] = sf.touch
64 | end
65 | table.insert(nf, fc)
66 | else
67 | table.insert(nf, sf)
68 | end
69 | end
70 | table.insert(frames, nf)
71 | end
72 | t[4] = frames
73 | if v.export then
74 | t[5] = v.export
75 | end
76 | elseif v.type == 'label' then
77 | print("-------aoaooaaoaoa -------->>>>", v.id)
78 | t[2] = v.id
79 | t[3] = v.color
80 | t[4] = v.width
81 | t[5] = v.height
82 | t[6] = v.align
83 | t[7] = v.size
84 | t[8] = v.noedge
85 | elseif v.type == 'pannel' then
86 | t[2] = v.id
87 | t[3] = v.width
88 | t[4] = v.height
89 | t[5] = v.scissor
90 | end
91 | rlt[k] = t
92 | end
93 |
94 | local of = io.open(o..'.json', 'w')
95 | of:write(json.encode(rlt))
96 | of:close()
97 |
98 | print('--->> done:', f)
99 |
100 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/lib/ex09.js:
--------------------------------------------------------------------------------
1 | var ex09 =((function(){
2 | var x = 0;
3 | var y = 768;
4 |
5 | var geometryShaderID = 3;
6 |
7 |
8 | var hexagon = new Array(10);
9 | for(var i =0; i < 5;++i)
10 | {
11 | var r = Math.PI * 2 * i / 6
12 | hexagon[i*2] = Math.sin(r) * 100 + 300;
13 | hexagon[i*2 +1] = Math.cos(r) * 100 + 300;
14 | }
15 |
16 | var gspr;
17 | var turret;
18 |
19 | var srt = {
20 | offx:500*SCREEN_SCALE,
21 | offy:384*SCREEN_SCALE,
22 | scalex : 1024,
23 | scaley : 1024,
24 | rot: 0
25 | };
26 |
27 | //var img_src = document.getElementsByName("img_src").getAttribute(src);
28 | ///console.log("-------------->>????aoaoao--->>", img_src);
29 |
30 | return {
31 | init:function() {
32 | //shader.load(geometryShaderID, geoFS, geoVS);
33 | // shader.load(BuiltinProgram.picture, spriteFS, spriteVS);
34 | //geometry.setprogram(geometryShaderID);
35 | var img = new Image();
36 | img.src = "sample.1.png";
37 | img.onload = function() {
38 | console.log(img.name, img.width, img.height);
39 | console.log("load texture succeed", typeof img);
40 | ejoy2d.texture.load_img(1, TEXTURE_RGBA8, img);
41 | ejoy2d.http.get("sample.json",function(resp) {
42 | if(resp != null) {
43 | console.log("get sample.json succeed");
44 | console.log(typeof resp);
45 | var sp = new ejoy2d.spritepack(resp,null);
46 | var id = sp.getIDByName("mine");
47 | gspr = new ejoy2d.sprite(sp, id);
48 | var label = gspr.fetch("label");
49 | var resource = gspr.fetch("resource")
50 | resource.setframe(10, false);
51 | gspr.setframe(11, false);
52 | label.setText("你好,webgl");
53 | // turret = gspr.fetch("turret");
54 | //this.spr.Init();
55 | }
56 | });
57 | };
58 | img.onerror = function () {
59 | console.log("Failed to load image: sample.1.png");
60 | }
61 | //ejoy2d.http.get("sample.1.png",function(resp) {
62 | // // console.log(resp);
63 | // console.log("load texture succeed");
64 | // ejoy2d.http.get("sample.json",function(resp) {
65 | // if(resp != null) {
66 | // console.log("get sample.json succeed");
67 | // console.log(typeof resp);
68 | // var sp = new ejoy2d.spritepack(resp,null);
69 | // var id = sp.getIDByName("cannon");
70 | // gspr = new ejoy2d.sprite(sp, id);
71 | // //this.spr.Init();
72 | // }
73 | // });
74 | //});
75 | },
76 | logicFrame:function()
77 | {
78 | // if(turret)
79 | // {
80 | // turret.setframe(turret.frame +1, false);
81 | // // console.log("---------<>>>", gspr.frame);
82 | // }
83 | if(gspr) {
84 | gspr.setframe(gspr.frame +1, false);
85 | // console.log("---------<>>>", gspr.frame);
86 | }
87 | },
88 | draw:function(){
89 | shader.clear(0xff808080);
90 | if (gspr)
91 | {
92 | gspr.draw(srt);
93 | }
94 | //geometry.line(0, 0, x, y, 0xffffffff);
95 | //geometry.box(100,100,200,300, 0x80ff0000);
96 | //geometry.polygon(hexagon, 0x40ffff00);
97 | }
98 | };
99 |
100 | })());
101 |
--------------------------------------------------------------------------------
/lib/main.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/6/14.
3 | */
4 |
5 |
6 | var gl;
7 | var shader;
8 | var texture;
9 | var render;
10 | var material;
11 | var renderbuffer;
12 | var ej_screen;
13 | var scissor;
14 | var geometry;
15 |
16 |
17 |
18 |
19 | var _G = {};
20 | function init(canvas,fw) {
21 | /// init gl
22 | var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
23 | for(var i =0; i < names.length; ++i) {
24 | try{
25 | gl = canvas.getContext(names[i]);
26 | gl.viewportWidth = canvas.width;
27 | gl.viewportHeight = canvas.height;
28 | } catch(e) {}
29 | if(gl) {
30 | break;
31 | }
32 | }
33 | if (!gl) {
34 | alert("Could not init WegGL,sorry :-(");
35 | return
36 | }
37 |
38 | /// inti ejoy2d
39 | shader = ejoy2d.shader;
40 | texture = ejoy2d.texture;
41 | render = ejoy2d.render;
42 | material = ejoy2d.material;
43 | renderbuffer = ejoy2d.renderbuffer;
44 | ej_screen = ejoy2d.screen;
45 | scissor = ejoy2d.scissor;
46 | geometry = ejoy2d.geometry;
47 |
48 | //render.init();
49 |
50 | fw.init();
51 | _G.game = new ejoy2d.game(fw);
52 |
53 |
54 | ////////// dealing with user input
55 | // closure
56 | var cg = _G.game;
57 | var isMouseDown = false;
58 | var bounds = canvas.getBoundingClientRect()
59 | var canvasPosX = bounds.left;
60 | var canvasPosY = bounds.top;
61 |
62 | canvas.onmousedown = function(e){
63 | var posX = e.pageX - canvasPosX;
64 | var posY = e.pageY - canvasPosY;
65 | isMouseDown = true;
66 | //console.log("------<<<<< Mouse down at", posX, posY);
67 | cg.touch(0, posX, posY, InputType.TOUCH_BEGIN);
68 |
69 | };
70 | canvas.onmouseup = function(e) {
71 | var posX = e.pageX - canvasPosX;
72 | var posY = e.pageY - canvasPosY;
73 | isMouseDown = false;
74 | cg.touch(0, posX, posY, InputType.TOUCH_END);
75 | };
76 | canvas.onmousemove = function(e) {
77 | if(isMouseDown) {
78 | var posX = e.pageX - canvasPosX;
79 | var posY = e.pageY - canvasPosY;
80 | cg.touch(0, posX, posY, InputType.TOUCH_MOVE);
81 | }
82 | };
83 | /// end of user input
84 | }
85 |
86 | function drawScene() {
87 | _G.game.draw();
88 | shader.flush()
89 | }
90 |
91 | var lastTime = 0;
92 |
93 | function update() {
94 | var timeNow = new Date().getTime();
95 | if (lastTime != 0) {
96 | var elapsed = timeNow - lastTime;
97 | _G.game.update(elapsed);
98 | }
99 | lastTime = timeNow;
100 | }
101 |
102 | function tick() {
103 | requestAnimFrame(tick);
104 | update();
105 | drawScene();
106 | }
107 |
108 |
109 | function webGLStart(fw) {
110 | var canvas = document.getElementById("main_canvas");
111 | console.log("--->> begin to init cavas:", canvas);
112 | init(canvas, fw);
113 | tick();
114 | }
115 |
--------------------------------------------------------------------------------
/lib/screen.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/6/21.
3 | */
4 |
5 | var SCREEN_SCALE = 16;
6 |
7 | ejoy2d.screen = ((function(){
8 | var trans_tmp = new Array(2);
9 | return {
10 | init_render:function(r) {
11 | // for ejoy2d compatibility, ejoy2d may call screen_init before screen_initrender
12 | /// screen_init(SCREEN.width, SCREEN.height, SCREEN.scale);
13 | },
14 | init:function(w, h, scale) {
15 | //console.log("ejoy screen_init:", w, h, scale);
16 | this.width = Math.floor(w);
17 | this.height = Math.floor(h);
18 | this.scale = scale;
19 | this.invw = 2.0 / SCREEN_SCALE / w;
20 | this.invh = -2.0 / SCREEN_SCALE / h;
21 | render.setviewport(0, 0, w * scale, h * scale );
22 | },
23 |
24 | trans:function(x, y) {
25 | trans_tmp[0] = x * this.invw;
26 | trans_tmp[1] = y * this.invh;
27 | return trans_tmp;
28 | },
29 | scissor:function(x, y, w, h) {
30 | y = this.height - y - h;
31 | if (x<0) {
32 | w += x;
33 | x = 0;
34 | } else if (x>this.width) {
35 | w=0;
36 | h=0;
37 | }
38 | if (y<0) {
39 | h += y;
40 | y = 0;
41 | } else if (y>this.height) {
42 | w=0;
43 | h=0;
44 | }
45 | if (w<=0 || h<=0) {
46 | w=0;
47 | h=0;
48 | }
49 | x *= this.scale;
50 | y *= this.scale;
51 | w *= this.scale;
52 | h *= this.scale;
53 |
54 | render.setscissor(x,y,w,h);
55 | },
56 | is_visible:function(x, y)
57 | {
58 | return x >= 0.0 && x <= 2.0 && y>=-2.0 && y<= 0.0;
59 | },
60 | is_poly_invisible:function(points, len, stride) {
61 | var i =0;
62 | // test left of x
63 | var invisible = true;
64 | for(i =0; i < len && invisible;++i)
65 | {
66 | if(points[i*stride] >= 0.0)
67 | invisible = false;
68 | }
69 | if(invisible)
70 | return true;
71 |
72 | // test right of axis x
73 | invisible = true;
74 | for(i =0; i < len && invisible;++i)
75 | {
76 | if(points[i*stride] <= 2.0)
77 | invisible = false;
78 | }
79 | if(invisible)
80 | return true;
81 |
82 | // test above of axis y
83 | invisible = true;
84 | for(i =0; i < len && invisible;++i)
85 | {
86 | if(points[i*stride +1] >= -2.0)
87 | invisible = false;
88 | }
89 | if(invisible)
90 | return true;
91 |
92 | // test below of axis y
93 | invisible = true;
94 | for(i =0; i < len && invisible;++i)
95 | {
96 | if(points[i*stride +1] <= 0.0)
97 | invisible = false;
98 | }
99 | return invisible;
100 | }
101 | };
102 | })());
103 |
--------------------------------------------------------------------------------
/lib/uri.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/8/20.
3 | */
4 |
5 | ejoy2d.URI = function (uri) {
6 | // See http://tools.ietf.org/html/rfc2396#appendix-B for details of RegExp
7 | var re = /^(([^:\/?\#]+):)?(\/\/([^\/?\#]*))?([^?\#]*)(\?([^\#]*))?(\#(.*))?/,
8 | result = uri.match(re);
9 |
10 | /**
11 | * @name pc.URI#scheme
12 | * @description The scheme. (e.g. http)
13 | */
14 | this.scheme = result[2];
15 |
16 | /**
17 | * @name pc.URI#authority
18 | * @description The authority. (e.g. www.example.com)
19 | */
20 | this.authority = result[4];
21 |
22 | /**
23 | * @name pc.URI#path
24 | * @description The path. (e.g. /users/example)
25 | */
26 | this.path = result[5];
27 |
28 | /**
29 | * @name pc.URI#query
30 | * @description The query, the section after a ?. (e.g. search=value)
31 | */
32 | this.query = result[7];
33 |
34 | /**
35 | * @name pc.URI#fragment
36 | * @description The fragment, the section after a #
37 | */
38 | this.fragment = result[9];
39 |
40 | /**
41 | * @function
42 | * @name pc.URI#toString
43 | * @description Convert URI back to string
44 | */
45 | this.toString = function () {
46 | var s = "";
47 |
48 | if (this.scheme) {
49 | s += this.scheme + ":";
50 | }
51 |
52 | if (this.authority) {
53 | s += "//" + this.authority;
54 | }
55 |
56 | s += this.path;
57 |
58 | if (this.query) {
59 | s += "?" + this.query;
60 | }
61 |
62 | if (this.fragment) {
63 | s += "#" + this.fragment;
64 | }
65 |
66 | return s;
67 | };
68 |
69 | /**
70 | * @function
71 | * @name pc.URI#getQuery
72 | * @description Returns the query parameters as an Object
73 | * @example
74 | *
75 | * var s = "http://example.com?a=1&b=2&c=3
76 | * var uri = new pc.URI(s);
77 | * var q = uri.getQuery();
78 | * console.log(q.a); // logs "1"
79 | * console.log(q.b); // logs "2"
80 | * console.log(q.c); // logs "3"
81 | *
82 | */
83 | this.getQuery = function () {
84 | var vars;
85 | var pair;
86 | var result = {};
87 |
88 | if (this.query) {
89 | vars = decodeURIComponent(this.query).split("&");
90 | vars.forEach(function (item, index, arr) {
91 | pair = item.split("=");
92 | result[pair[0]] = pair[1];
93 | }, this);
94 | }
95 |
96 | return result;
97 | };
98 |
99 | /**
100 | * @function
101 | * @name pc.URI#setQuery
102 | * @description Set the query section of the URI from a Object
103 | * @param {Object} params Key-Value pairs to encode into the query string
104 | * @example
105 | * var s = "http://example.com";
106 | * var uri = new pc.URI(s);
107 | * uri.setQuery({"a":1,"b":2});
108 | * console.log(uri.toString()); // logs "http://example.com?a=1&b=2
109 | */
110 | this.setQuery = function (params) {
111 | q = "";
112 | for (var key in params) {
113 | if (params.hasOwnProperty(key)) {
114 | if (q !== "") {
115 | q += "&";
116 | }
117 | q += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
118 | }
119 | }
120 |
121 | this.query = q;
122 | };
123 | };
--------------------------------------------------------------------------------
/lib/string.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/8/20.
3 | */
4 | /**
5 | * @name ejoy2d.string
6 | * @namespace Extended String API
7 | */
8 | ejoy2d.string = function () {
9 | return {
10 | /**
11 | * @name ejoy2d.string.ASCII_LOWERCASE
12 | * @description All lowercase letters
13 | * @type String
14 | */
15 | ASCII_LOWERCASE: "abcdefghijklmnopqrstuvwxyz",
16 |
17 | /**
18 | * @name ejoy2d.string.ASCII_UPPERCASE
19 | * @description All uppercase letters
20 | * @type String
21 | */
22 | ASCII_UPPERCASE: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
23 |
24 | /**
25 | * @name ejoy2d.string.ASCII_LETTERS
26 | * @description All ASCII letters
27 | * @type String
28 | */
29 | ASCII_LETTERS: this.ASCII_LOWERCASE + this.ASCII_UPPERCASE,
30 | /**
31 | * @function
32 | * @name ejoy2d.string.format
33 | * @description Return a string with {n} replaced with the n-th argument
34 | * @param {String} s The string to format
35 | * @param {Object} [arguments] All other arguments are substituted into the string
36 | * @returns {String} The formatted string
37 | * @example
38 | * var s = ejoy2d.string.format("Hello {0}", "world");
39 | * console.log(s); // Prints "Hello world"
40 | */
41 | format: function (s) {
42 | var i = 0,
43 | regexp,
44 | args = ejoy2d.makeArray(arguments);
45 |
46 | // drop first argument
47 | args.shift();
48 |
49 | for (i = 0; i < args.length; i++) {
50 | regexp = new RegExp('\\{' + i + '\\}', 'gi');
51 | s = s.replace(regexp, args[i]);
52 | }
53 | return s;
54 | },
55 |
56 | /**
57 | * @function
58 | * @name ejoy2d.string.startsWith
59 | * @description Check if a string s starts with another string subs
60 | * @param {String} s The string to look in
61 | * @param {String} subs The string to look for
62 | * @returns {Boolean} True if s starts with subs
63 | * @example
64 | * var s = "abc";
65 | * if (ejoy2d.string.startsWith(s, "a")) {
66 | * console.log('Starts with a');
67 | * }
68 | */
69 | startsWith: function (s, subs) {
70 | return (s.indexOf(subs) === 0);
71 | },
72 |
73 | /**
74 | * @function
75 | * @name ejoy2d.string.endsWith
76 | * @description Check if a string s ends with another string subs
77 | * @param {String} s The string to look in
78 | * @param {String} subs The string to look for
79 | * @returns {Boolean} True if s ends with subs
80 | */
81 | endsWith: function (s, subs) {
82 | return (s.lastIndexOf(subs, s.length - subs.length) !== -1);
83 | },
84 |
85 | /**
86 | * @function
87 | * @name ejoy2d.string.toBool
88 | * @description Convert a string value to a boolean. In non-strict mode (the default), 'true' is converted to true, all other values
89 | * are converted to false. In strict mode, 'true' is converted to true, 'false' is converted to false, all other values will throw
90 | * an Exception.
91 | * @param {String} s The string to convert
92 | * @param {Boolean} [strict] In strict mode an Exception is thrown if s is not an accepted string value. Defaults to false
93 | * @returns {Boolean} The converted value
94 | */
95 | toBool: function (s, strict) {
96 | if (s === 'true') {
97 | return true;
98 | }
99 |
100 | if (strict) {
101 | if (s === 'false') {
102 | return false;
103 | }
104 |
105 | throw new Error('Not a boolean string');
106 | }
107 |
108 | return false;
109 | }
110 | };
111 | } ();
112 |
113 |
--------------------------------------------------------------------------------
/lib/geometry.js:
--------------------------------------------------------------------------------
1 |
2 | ejoy2d.geometry = (function(){
3 | var PROGRAM =0;
4 | var convert_color = function(c) {
5 | var alpha = (c >> 24) & 0xff;
6 | if (alpha == 0xff) {
7 | return c;
8 | }
9 | if (alpha == 0) {
10 | return c | 0xff000000;
11 | }
12 | var red = (c >> 16) & 0xff;
13 | var green = (c >> 8) & 0xff;
14 | var blue = (c) & 0xff;
15 | red = red * alpha / 255;
16 | green = green * alpha / 255;
17 | blue = blue * alpha / 255;
18 |
19 | return alpha << 24 | red << 16 | green << 8 | blue;
20 | };
21 | return {
22 | setprogram:function(p) {
23 | PROGRAM = p;
24 | return 0;
25 | },
26 | /*
27 | float[4] endpointer x1,y1,x2,y2
28 | uint32_t color
29 | */
30 | line: function(x1,y1,x2,y2,c) {
31 | x1 = x1 * SCREEN_SCALE;
32 | y1 = y1 * SCREEN_SCALE;
33 | x2 = x2 * SCREEN_SCALE;
34 | y2 = y2 * SCREEN_SCALE;
35 | var color = convert_color(c);
36 | var vp = new Array(4*4);
37 | vp[0] = x1;
38 | vp[0 +1] = y1;
39 | vp[4 +0] = x2;
40 | vp[4 +1] = y2;
41 | if (Math.abs(x1-x2) > Math.abs(y1-y2)) {
42 | vp[8] = x2;
43 | vp[8+1]= y2+SCREEN_SCALE;
44 | vp[12] = x1;
45 | vp[12 +1] = y1+SCREEN_SCALE;
46 | } else {
47 | vp[8] = x2+SCREEN_SCALE;
48 | vp[8 +1] = y2;
49 | vp[12] = x1+SCREEN_SCALE;
50 | vp[12 +1] = y1;
51 | }
52 |
53 | for (var i=0;i<4;i++) {
54 | var base = i*4;
55 | vp[base +2] = 0;
56 | vp[base +3] = 0;
57 | var rlt = ejoy2d.screen.trans(vp[base +0], vp[base +1]);
58 | vp[base +0] = rlt[0];
59 | vp[base +1] = rlt[1];
60 | }
61 | shader.program(PROGRAM);
62 | shader.do_draw(vp, color, 0);
63 | return 0;
64 | },
65 | /*
66 | float x,y
67 | float w,h
68 | uint32_t color
69 | */
70 | box: function(x, y, w, h, c) {
71 | x = x * SCREEN_SCALE;
72 | y = y * SCREEN_SCALE;
73 | w = w * SCREEN_SCALE;
74 | h = h * SCREEN_SCALE;
75 | var color = convert_color(c);
76 | var vp = new Array(4*4);
77 | vp[0] = x;
78 | vp[0+1] = y;
79 | vp[4] = x+w;
80 | vp[4+1] = y;
81 | vp[8] = x+w;
82 | vp[8+1] = y+h;
83 | vp[12] = x;
84 | vp[12+1] = y+h;
85 | for (var i=0;i<4;i++) {
86 | var base = i*4;
87 | vp[base +2] = 0;
88 | vp[base +3] = 0;
89 | var rlt = ejoy2d.screen.trans(vp[base +0], vp[base +1]);
90 | vp[base +0] = rlt[0];
91 | vp[base +1] = rlt[1];
92 | }
93 | shader.program(PROGRAM);
94 | //console.log("----------->>> shader:", vp);
95 | shader.do_draw(vp, color, 0);
96 | },
97 | /*
98 | table float[]
99 | uint32_t color
100 | */
101 | polygon:function(vs,c) {
102 | var color = convert_color(c);
103 | var n = vs.length;
104 | var point = n/2;
105 | var vb = new Array(point*4);
106 | for (var i=0;i>>>>", i ,vs[i*2], vs[i*2 +1]);
110 | var rlt = ejoy2d.screen.trans(vx,vy);
111 | vb[i*4] = rlt[0];
112 | vb[i*4+1] = rlt[1];
113 | vb[i*4+2] = 0;
114 | vb[i*4+3] = 0;
115 | //console.log("--->>",i,vb[i*4], vb[i*4 +1], vb[i*4 +2], vb[i*4 +3]);
116 | }
117 | shader.program(PROGRAM);
118 | if (point == 4) {
119 | shader.draw(vb, color, 0);
120 | } else {
121 | shader.drawpolygon(point, vb, color);
122 | }
123 | }
124 | };
125 | })();
126 |
--------------------------------------------------------------------------------
/lib/spritepack.js:
--------------------------------------------------------------------------------
1 | var SpriteType = {
2 | empty : 0,
3 | picture : 1,
4 | animation : 2,
5 | polygon : 3,
6 | label : 4,
7 | panel : 5,
8 | anchor : 6,
9 | matrix : 7
10 | };
11 |
12 | ejoy2d.spritepack = function(json, texs) {
13 | this.tex = texs;
14 | var data = new Array();
15 | this.data = data;
16 | var namedCmp = {};
17 | this.namedCmp = namedCmp;
18 | var allMatrix = null;
19 | for(var i in json) {
20 | var v = json[i];
21 | var cmp = {};
22 | cmp.type = v[0];
23 | switch(cmp.type) {
24 | case SpriteType.label:
25 | cmp.id = v[1];
26 | cmp.color = v[2];
27 | cmp.width = v[3];
28 | cmp.height = v[4];
29 | cmp.align = v[5];
30 | cmp.size = v[6];
31 | cmp.edge = v[7];
32 | cmp.auto_scale = v[8];
33 | break;
34 | case SpriteType.panel:
35 | cmp.id = v[1];
36 | cmp.width = v[2];
37 | cmp.height = v[3];
38 | cmp.scissor = v[4];
39 | break;
40 | case SpriteType.matrix:
41 | allMatrix = v;
42 | break;
43 | case SpriteType.picture:
44 | cmp.id = v[1];
45 | var info = v[2];
46 | var rect = {};
47 | rect.texid = info[0];
48 | rect.texture_coord = [];// = info[1].slice(0);
49 | for(var ti = 0; ti < 4; ++ti) {
50 | var idx = ti*2;
51 | var tc = ejoy2d.texture.texcoord(info[0], info[1][idx], info[1][idx +1]);
52 | rect.texture_coord[idx] = tc[0];
53 | rect.texture_coord[idx +1] = tc[1];
54 | }
55 | rect.screen_coord = info[2].slice(0);
56 | cmp.rect = [];
57 | cmp.n = 1;
58 | cmp.rect.push(rect);
59 | break;
60 | case SpriteType.animation:
61 | cmp.id = v[1];
62 | var cc = v[2];
63 |
64 | if(v[4]) // exported
65 | namedCmp[v[4]] = v[1];
66 |
67 | var c = new Array();
68 | cmp.component = c;
69 | for(var idx in cc)
70 | {
71 | var cmpPart = {};
72 | if(typeof(cc[idx]) == "number") {
73 | cmpPart.id = cc[idx];
74 | } else {
75 | cmpPart.id = cc[idx][0];
76 | cmpPart.name = cc[idx][1];
77 | }
78 | c[idx] = cmpPart;
79 | }
80 | var frames = new Array();
81 | cmp.frame = frames;
82 | for(var uu in v[3]){
83 | var fd = v[3][uu]
84 | var oneFrame = new Array();
85 | for(var ii in fd ){
86 | var f = {}
87 | var f1 = fd[ii];
88 | if(typeof(f1) == "number") {
89 | f.component_id = f1;
90 | f.t = new ejoy2d.sprite_trans();
91 | } else {
92 | f.component_id = f1[0];
93 | f.t = new ejoy2d.sprite_trans();
94 | if(typeof(f1[1]) == "number")
95 | f.t.mat = new ejoy2d.matrix(allMatrix[f1[1] +1]);
96 | else
97 | f.t.mat = new ejoy2d.matrix(f1[1]);
98 | f.touchable = f1[2];
99 | }
100 | oneFrame[ii] = f;
101 | }
102 | frames[uu] = oneFrame;
103 | }
104 | var action = [];
105 | var a = {};
106 | a.start_frame =0;
107 | a.number = frames.length;
108 | action.push(a);
109 | cmp.action = action;
110 |
111 | break;
112 | }
113 | data[cmp.id] = cmp;
114 | }
115 | };
116 |
117 | ejoy2d.spritepack.prototype = {
118 | getDataByName: function (name) {
119 | return this.data[this.namedCmp[name]];
120 | },
121 | getIDByName: function (name) {
122 | return this.namedCmp[name];
123 | }
124 | };
125 |
--------------------------------------------------------------------------------
/lib/path.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by v on 2015/8/20.
3 | */
4 | ejoy2d.path = function () {
5 | return {
6 | /**
7 | * The character that separates path segments
8 | * @name ejoy2d.path.delimiter
9 | */
10 | delimiter: "/",
11 | /**
12 | * Join two sections of file path together, insert a delimiter if needed.
13 | * @param {String} one First part of path to join
14 | * @param {String} two Second part of path to join
15 | * @function
16 | * @name ejoy2d.path.join
17 | */
18 | /*
19 | join: function(one, two) {
20 | if(two[0] === ejoy2d.path.delimiter) {
21 | return two;
22 | }
23 |
24 | if(one && two && one[one.length - 1] !== ejoy2d.path.delimiter && two[0] !== ejoy2d.path.delimiter) {
25 | return one + ejoy2d.path.delimiter + two;
26 | }
27 | else {
28 | return one + two;
29 | }
30 | },
31 | */
32 | join: function () {
33 | var index;
34 | var num = arguments.length;
35 | var result = arguments[0];
36 |
37 | for(index = 0; index < num - 1; ++index) {
38 | var one = arguments[index];
39 | var two = arguments[index+1];
40 | if(!ejoy2d.isDefined(one) || !ejoy2d.isDefined(two)) {
41 | throw new Error("undefined argument to ejoy2d.path.join");
42 | }
43 | if(two[0] === ejoy2d.path.delimiter) {
44 | result = two;
45 | continue;
46 | }
47 |
48 | if(one && two && one[one.length - 1] !== ejoy2d.path.delimiter && two[0] !== ejoy2d.path.delimiter) {
49 | result += (ejoy2d.path.delimiter + two);
50 | } else {
51 | result += (two);
52 | }
53 | }
54 |
55 | return result;
56 | },
57 |
58 | /**
59 | * @function
60 | * @name ejoy2d.path.split
61 | * @description Split the pathname path into a pair [head, tail] where tail is the final part of the path
62 | * after the last delimiter and head is everything leading up to that. tail will never contain a slash
63 | */
64 | split: function (path) {
65 | var parts = path.split(ejoy2d.path.delimiter);
66 | var tail = parts.slice(parts.length-1)[0];
67 | var head = parts.slice(0,parts.length-1).join(ejoy2d.path.delimiter);
68 | return [head, tail];
69 | },
70 |
71 | /**
72 | * @function
73 | * @name ejoy2d.path.getBasename
74 | * @description Return the basename of the path. That is the second element of the pair returned by
75 | * passing path into {@link ejoy2d.path.split}.
76 | * @example
77 | * ejoy2d.path.getBasename("/path/to/file.txt"); // returns "path.txt"
78 | * ejoy2d.path.getBasename("/path/to/dir"); // returns "dir"
79 | * @returns {String} The basename
80 | */
81 | getBasename: function(path) {
82 | return ejoy2d.path.split(path)[1];
83 | },
84 |
85 | /**
86 | * Get the directory name from the path. This is everything up to the final instance of ejoy2d.path.delimiter
87 | * @param {String} path The path to get the directory from
88 | * @function
89 | * @name ejoy2d.path.getDirectory
90 | */
91 | getDirectory: function(path) {
92 | var parts = path.split(ejoy2d.path.delimiter);
93 | return parts.slice(0,parts.length-1).join(ejoy2d.path.delimiter);
94 | },
95 |
96 | getExtension: function (path) {
97 | var ext = path.split(".").pop();
98 | if (ext !== path) {
99 | return "." + ext;
100 | } else {
101 | return "";
102 | }
103 | },
104 |
105 | isRelativePath: function (s) {
106 | return s.charAt(0) !== "/" && s.match(/:\/\//) === null;
107 | },
108 |
109 | extractPath: function (s) {
110 | var path = ".",
111 | parts = s.split("/"),
112 | i = 0;
113 |
114 | if (parts.length > 1) {
115 | if (ejoy2d.path.isRelativePath(s) === false) {
116 | path = "";
117 | }
118 | for (i = 0; i < parts.length - 1; ++i) {
119 | path += "/" + parts[i];
120 | }
121 | }
122 | return path;
123 | }
124 | };
125 | } ();
--------------------------------------------------------------------------------
/lib/utils.js:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WebGLUtils = function() {
5 |
6 | /**
7 | * Creates the HTLM for a failure message
8 | * @param {string} canvasContainerId id of container of th
9 | * canvas.
10 | * @return {string} The html.
11 | */
12 | var makeFailHTML = function(msg) {
13 | return '' +
14 | '' +
15 | '' +
16 | '' +
17 | ' ' + msg + ' ' +
18 | ' ' +
19 | ' |
';
20 | };
21 |
22 | /**
23 | * Mesasge for getting a webgl browser
24 | * @type {string}
25 | */
26 | var GET_A_WEBGL_BROWSER = '' +
27 | 'This page requires a browser that supports WebGL.
' +
28 | 'Click here to upgrade your browser.';
29 |
30 | /**
31 | * Mesasge for need better hardware
32 | * @type {string}
33 | */
34 | var OTHER_PROBLEM = '' +
35 | "It doesn't appear your computer can support WebGL.
" +
36 | 'Click here for more information.';
37 |
38 | /**
39 | * Creates a webgl context. If creation fails it will
40 | * change the contents of the container of the