branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>luther168/MavenSSM<file_sep>/WebModule/src/main/java/cn/luo/web/entity/sbss/response/GetTaskListResponse.java package cn.luo.web.entity.sbss.response; import cn.luo.web.entity.sbss.Task; import java.util.List; /** * @author Luo * @version V1.0 * @description description * @createTime 2018/1/27 19:38 * @note */ public class GetTaskListResponse extends SBSSResponse { private List<Task> mapList; public List<Task> getMapList() { return mapList; } public void setMapList(List<Task> mapList) { this.mapList = mapList; } } <file_sep>/WebModule/src/main/java/cn/luo/web/entity/sbss/AddressItem.java package cn.luo.web.entity.sbss; /** * Created by gsp on 2017-08-05. */ public class AddressItem { private int id; private String address; private String address_src; private String qx;//区县 private String jd;//街道 private String pcs;//派出所 private String jw; private String wg; private String jlx; private String mp; private String dz; private float x; private float y; private String edit_type; private String xz; private String czqk; public void setComplete(int complete) { this.complete = complete; } public int isComplete() { return complete; } private int complete=-1; // public AddressItem(String address) { // this.address = address; // } public AddressItem(String address,String src) { this.address = address; this.address_src=src; } public AddressItem(String address,String src,int id) { this.address = address; this.address_src=src; this.id=id; } public AddressItem(String address,String src,String editType) { this.address = address; this.address_src=src; this.edit_type=editType; } public AddressItem() { } public void setId(int id) { this.id = id; } public String getAddress() { return address; } public String getAddressSrc() { return address_src; } @Override public String toString(){ if(this.mp==null){ return address; }else { return mp; } } public void setAddress(String address) { this.address = address; } public void setAddressSrc(String addressSrc) { this.address_src = addressSrc; } public void setAddress_src(String address_src) { this.address_src = address_src; } public void setQx(String qx) { this.qx = qx; } public void setJd(String jd) { this.jd = jd; } public void setPcs(String pcs) { this.pcs = pcs; } public void setJw(String jw) { this.jw = jw; } public void setWg(String wg) { this.wg = wg; } public void setJlx(String jlx) { this.jlx = jlx; } public void setMp(String mp) { this.mp = mp; } public void setDz(String dz) { this.dz = dz; } public void setX(float x) { this.x = x; } public void setY(float y) { this.y = y; } public void setEdit_type(String edit_type) { this.edit_type = edit_type; } public int getId(){ return id; } public String getQx() { return qx; } public String getJd() { return jd; } public String getPcs() { return pcs; } public String getJw() { return jw; } public String getWg() { return wg; } public String getJlx() { return jlx; } public String getMp() { return mp; } public String getDz() { return dz; } public float getX() { return x; } public float getY() { return y; } public String getEdit_type(){ return edit_type; } public String getXz() { return xz; } public void setXz(String xz) { this.xz = xz; } public String getCzqk() { return czqk; } public void setCzqk(String czqk) { this.czqk = czqk; } } <file_sep>/WebModule/src/main/java/cn/luo/web/entity/sbss/response/LoginResponse.java package cn.luo.web.entity.sbss.response; import java.io.Serializable; /** * AUTHOR: Luo * VERSION: V1.0 * DESCRIPTION: description * CREATE TIME: 2018/1/20 17:40 * NOTE: */ public class LoginResponse extends SBSSResponse implements Serializable { private String token; private String sswg; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getSswg() { return sswg; } public void setSswg(String sswg) { this.sswg = sswg; } } <file_sep>/WebModule/src/main/java/cn/luo/web/entity/sbss/response/GetEventListResponse.java package cn.luo.web.entity.sbss.response; import cn.luo.web.entity.sbss.DataEvent; import java.util.List; /** * @author Luo * @version V1.0 * @description description * @createTime 2018/1/27 19:38 * @note */ public class GetEventListResponse extends SBSSResponse { private List<DataEvent> eventList; public List<DataEvent> getEventList() { return eventList; } public void setEventList(List<DataEvent> eventList) { this.eventList = eventList; } } <file_sep>/WebModule/src/main/java/cn/luo/web/entity/sbss/DataEvent.java package cn.luo.web.entity.sbss; /** * @author Luo * @version V1.0 * @description description * @createTime 2018/1/25 20:38 * @note */ public class DataEvent extends BaseEntity { public final static int SAVE_LOCAL = 0; // is_upload=0 public final static int SOLVED_LOCAL = 1; // is_upload=1,solved=1 public final static int REPORT = 2; // is_upload=1,solved=0 public static final int UNSOLVED = 0; public static final int SOLVED = 1; private String fssj; private String sjmc; private String sjms; private String sjrs; private String gjc; private String sjlx; private String fsxc; private String wgy; private String sswg; private String tp; private String solved; private String id; private String sfqy; public String getFssj() { return fssj; } public void setFssj(String fssj) { this.fssj = fssj; } public String getSjmc() { return sjmc; } public void setSjmc(String sjmc) { this.sjmc = sjmc; } public String getSjms() { return sjms; } public void setSjms(String sjms) { this.sjms = sjms; } public String getSjrs() { return sjrs; } public void setSjrs(String sjrs) { this.sjrs = sjrs; } public String getGjc() { return gjc; } public void setGjc(String gjc) { this.gjc = gjc; } public String getSjlx() { return sjlx; } public void setSjlx(String sjlx) { this.sjlx = sjlx; } public String getFsxc() { return fsxc; } public void setFsxc(String fsxc) { this.fsxc = fsxc; } public String getWgy() { return wgy; } public void setWgy(String wgy) { this.wgy = wgy; } public String getSswg() { return sswg; } public void setSswg(String sswg) { this.sswg = sswg; } public String getTp() { return tp; } public void setTp(String tp) { this.tp = tp; } public String getSolved() { return solved; } public void setSolved(String solved) { this.solved = solved; } public void setId(String id) { this.id = id; } public String getId() { return id; } public String getSfqy() { return sfqy; } public void setSfqy(String sfqy) { this.sfqy = sfqy; } } <file_sep>/ModelModule/src/main/java/cn/luo/mybatis/provider/MySQLProvider.java package cn.luo.mybatis.provider; import cn.luo.mybatis.base.BaseProvider; import cn.luo.utils.StringUtils; import javax.naming.InvalidNameException; public class MySQLProvider implements BaseProvider { @Override public String selectAll(String tableName) throws InvalidNameException { return select(null, tableName, null, 0, 0); } @Override public String select(String selectStr, String tableName, String whereStr, int limit, int offset) throws InvalidNameException { StringBuilder builder = new StringBuilder(); builder.append("SELECT "); if (StringUtils.stringIsEmpty(selectStr)) { builder.append("*"); } else { builder.append(selectStr); } builder.append(" FROM "); if (StringUtils.stringIsEmpty(tableName)) { throw new InvalidNameException("The table name '" + tableName + "' is not invalid"); } else { builder.append(tableName); } if (!StringUtils.stringIsEmpty(whereStr)) { builder.append(" WHERE "); builder.append(whereStr); } if (limit > 0) { builder.append(" LIMIT "); if (offset > 0) { builder.append(offset).append(","); } builder.append(limit); } return builder.toString(); } } <file_sep>/WebModule/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <artifactId>MavenSSM</artifactId> <groupId>cn.luo</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>WebModule</artifactId> <packaging>war</packaging> <name>WebApp Maven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>cn.luo</groupId> <artifactId>ModelModule</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- junit test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <!-- log --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </dependency> <!-- database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> </dependency> <!-- DAO framework:mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </dependency> <!-- servlet --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <!-- spring --> <!-- spring core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <!-- spring DAO --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <!-- spring web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <!-- spring test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <!-- aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> </dependency> <!-- common utils --> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <!-- apache common--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc --> <dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency> <dependency> <groupId>cn.luo</groupId> <artifactId>CoreModel</artifactId> <version>1.0-SNAPSHOT</version> <scope>compile</scope> </dependency> </dependencies> <build> <finalName>WebApp</finalName> <plugins> <!-- 指定编译JDK版本 --> <plugin> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> </plugin> </plugins> </build> </project> <file_sep>/WebModule/src/main/java/cn/luo/web/entity/sbss/response/GetAddressListResponse.java package cn.luo.web.entity.sbss.response; import cn.luo.web.entity.sbss.AddressItem; import java.util.List; /** * @author Luo * @version V1.0 * @description description * @createTime 2018/1/27 19:38 * @note */ public class GetAddressListResponse extends SBSSResponse { private List<AddressItem> addressList; public List<AddressItem> getAddressList() { return addressList; } public void setAddressList(List<AddressItem> addressList) { this.addressList = addressList; } } <file_sep>/WebModule/src/main/java/cn/luo/web/utils/LogUtils.java package cn.luo.web.utils; public class LogUtils { private static final String DEFAULT_TAG = LogUtils.class.getSimpleName(); public static void d(Object o) { String log = o == null ? "null" : o.toString(); System.out.println(DEFAULT_TAG + " " + log); } } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.luo</groupId> <artifactId>MavenSSM</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>ModelModule</module> <module>UIModule</module> <module>WebModule</module> <module>CommonModule</module> <module>AdminModule</module> </modules> <name>MavenSSM Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- base setting --> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!--lib setting--> <aspectj.version>1.8.7</aspectj.version> <c3p0.version>0.9.1.1</c3p0.version> <commons-dbcp2.version>2.1</commons-dbcp2.version> <commons-lang3.version>3.4</commons-lang3.version> <druid.version>1.1.5</druid.version> <fastjson.version>1.2.47</fastjson.version> <jackson.version>2.9.3</jackson.version> <javax.servlet-api.version>3.1.0</javax.servlet-api.version> <jstl.version>1.2</jstl.version> <junit.version>4.12</junit.version> <log4j.version>1.2.17</log4j.version> <mybatis.version>3.4.1</mybatis.version> <mybatis-spring.version>1.3.0</mybatis-spring.version> <mysql-connector-java.version>5.1.39</mysql-connector-java.version> <slf4j-api.version>1.7.25</slf4j-api.version> <slf4j-log4j12.version>1.7.21</slf4j-log4j12.version> <spring.version>5.0.2.RELEASE</spring.version> <sqlite-jdbc.version>3.8.11.2</sqlite-jdbc.version> <taglibs.standard.version>1.1.2</taglibs.standard.version> </properties> <dependencyManagement> <dependencies> <!-- junit test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- log --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j-api.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j-log4j12.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-java.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> <version>${sqlite-jdbc.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>${commons-dbcp2.version}</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0.version}</version> </dependency> <!-- DAO framework:mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- servlet --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibs.standard.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet-api.version}</version> </dependency> <!-- spring --> <!-- spring core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- spring DAO --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!-- spring web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- spring test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version> </dependency> <!-- common utils --> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- apache common--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <pluginManagement> <plugins> <!-- 指定编译JDK版本 --> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <executions> <execution> <id>default-compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> </executions> <configuration> <source>${java.version}</source> <target>${java.version}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </pluginManagement> </build> </project> <file_sep>/ModelModule/src/main/java/cn/luo/mybatis/base/BaseMapper.java package cn.luo.mybatis.base; import java.util.List; import java.util.Map; public interface BaseMapper { List<Map<String, Object>> select(String selectStr, String tableName, String whereStr, int limit, int offset); List<Map<String,Object>> selectAll(String tableName); } <file_sep>/UIModule/src/main/java/cn/luo/form/MainForm.java package cn.luo.form; import cn.luo.mybatis.DBHelper; import javax.swing.*; public class MainForm { private JPanel panelRoot; public static void main(String[] args) { JFrame frame = new JFrame("MainForm"); frame.setContentPane(new MainForm().panelRoot); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); DBHelper.getInstance().select("UserInfo"); } }
56c6f46ab68f8e4b8d85f1c8bb397a9bf91f5d99
[ "Java", "Maven POM" ]
12
Java
luther168/MavenSSM
33ed4c6e6938c108430c6314687951bcede8081f
19dd1b2a67669fe4485e3a37d69012fa24748ff0
refs/heads/main
<file_sep># The following script passes two arguments. The first is for the specified date - 0310, 0312, and 0315. The second is for the specified time. The analysis results in easily finding the roulette dealer # at a specified time. awk -F" " '{print$1,$2,$3,$6,$7}' losses_Dealer_Schedules_DateAdd | grep $1 | grep $2 | grep $3 # Print columns date, time, ante / post meridiem (AM/PM), Dealer's First Name, Last Name. # Print contents containing date, time, and ante / post meridiem. <file_sep># A script using awk, pipes, and grep. # awk calls on the time, AM/PM, Roulette First Name and Last Name Columns. # Pipe | transitions the awk results into the next grep command. # grep passes arugment by times matching player anomolies at 05:00:00 AM, 08:00:00 AM, 02:00:00 PM, 08:00:00 PM, & 11:00:00 PM. awk -F" " '{print$1,$2,$5,$6}' losses_Dealer_Schedules| grep $1 | grep $2 >> Dealers_working_during_losses
11d7453c991994b048ef2d428342033e3b780de3
[ "Shell" ]
2
Shell
hessianhobs/ucsdcybersecuritytrilogybootcamp
e25ecf7cdbb269ecb65c085f3d73f512c38c9728
974aa0f21887f51ea60cb1cb5755241b74511fb3
refs/heads/master
<repo_name>semen-gen/WorkBook<file_sep>/src/task11/Main11.java package task11; public class Main11 { public static void main(String[] args) { simple(121); } public static void simple(int x) { boolean simpleInt = true; if (x > 0) { for (int i = 2; i <= Math.sqrt(x); i++) { if (!(x == 1 || x == 2) && x != i && x % i == 0) { simpleInt = false; i = (int) Math.sqrt(x); // используется вместо break } } } else { simpleInt = false; } if (simpleInt) { System.out.println("Простое"); } else { System.out.println("Не простое"); } } } <file_sep>/src/task17/Main17.java package task17; import java.util.Arrays; public class Main17 { public static void main(String[] args) { printButterfly(5); } public static void printButterfly(int length) { int[][] arr = new int[length][length]; int absDelta; for (int i = 0, e = length - 1; i < length; i++, e--) { absDelta = (length - (Math.abs(e - i) + 1)) / 2; for (int l = 0; l < length; l++) { arr[i][l] = l >= absDelta && l <= length - absDelta - 1 ? 1 : 0; } } for (int[] el : arr) { System.out.println(Arrays.toString(el)); } } }<file_sep>/src/task4/Main4.java package task4; public class Main4 { public static void main(String[] args) { System.out.println(isCloseHole(3, 4, 5)); } /** * Прямоугольное отверстие со сторонами a и b полностью закрыть кругом с радиусом r * * @param a одна сторона отверстия * @param b вторая сторона отверстия * @param r радиус крышки * @return */ public static boolean isCloseHole(int a, int b, int r) { return r >= Math.sqrt(a * a + b * b) / 2; } } <file_sep>/src/task7/Main7.java package task7; public class Main7 { public static void main(String[] args) { whichHouseFit(20, 50, 30, 80, 90, 50); } public static void whichHouseFit(int a, int b, int c, int d, int e, int f) { boolean house1, house2; house1 = house2 = false; if ((a <= e && b <= f) || (b <= e && a <= f)) { house1 = true; System.out.println("Первый дом поместится"); } if ((c <= e && d <= f) || (d <= e && c <= f)) { house2 = true; System.out.println("Второй дом поместится"); } if (!(house1 && house2)) { System.out.println("Оба дома не поместились"); } } }
660abd57445eca44048fdce875f8ea04ea7353a3
[ "Java" ]
4
Java
semen-gen/WorkBook
18b985ec734c522dca6011a95d735bd8f372eb22
372c93138c4bd1a0ded0be7f4ada531af5e598db
refs/heads/master
<repo_name>melletL/pokedex-express<file_sep>/index.js const express = require('express'); const jsonfile = require('jsonfile'); const file = 'pokedex.json' /** * =================================== * Configurations and set up * =================================== */ // Init express app const app = express(); /** * =================================== * Routes * =================================== */ app.get('/:name', (request, response) => { // send response with some data (a string) let path = request.params.name; let counter = 0; jsonfile.readFile(file, (err, obj) => { for (let i=0; i<151; i++){ if (obj['pokemon'][i]['name'].toLowerCase() === path) { console.log("found it! " + obj['pokemon'][i]['name'].toLowerCase()) response.send(path + " is " + obj['pokemon'][i]['weight']); // } else if (obj['pokemon'][i]['name'].toLowerCase() !== path) { // response.status(404).send("Could not find information about "+ path + "- Is that a new pokemon? Gotta catch em' all!"); } } }) }) /** * =================================== * Listen to requests on port 3000 * =================================== */ app.listen(3000, () => console.log('~~~ Tuning in to the waves of port 3000 ~~~'));
137187b9739de8a118716cb4ea2043ba032a7080
[ "JavaScript" ]
1
JavaScript
melletL/pokedex-express
fe134d374e2d56ce0392bdd42223b3f9233fa456
8dbe8ca8029f3dbc292ec5a1fa315aa83c559b64
refs/heads/main
<file_sep># wp-custom-node-importer Importer for wordpress from XLS files
214ae0482dcea0b6a50a3382784651339573beba
[ "Markdown" ]
1
Markdown
webislife/wp-custom-node-importer
44e75bec57af2ca0b477530ad9ae1246664e903f
78f8f09e853ddc5d593a99104f1b77c95a6e018d
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <center> <?php include "/include/include.php"; $typelist=array(1=>"数码",2=>"服装",3=>"车"); ?> <br><br> <h3>浏览商品信息</h3><br> <table border="1" width="800"> <tr> <th>商品编号</th> <th>商品名称</th> <th>商品图片</th> <th>单价</th> <th>库存量</th> <th>添加时间</th> <th>操作</th> </tr> <?php //从数据库中读取信息并输出到浏览器中 //1.连接数据库 require "/include/conn.php"; //2.执行查询 $sql="select * from goods"; $result=mysql_query($sql); //解析结果集 while($row=mysql_fetch_array($result)){ echo "<tr>"; echo "<td>{$row['id']}</td>"; echo "<td>{$row['name']}</td>"; echo "<td><img src='{$row['pic']}' width='70' height='70'></td>"; echo "<td>{$row['price']}</td>"; echo "<td>{$row['total']}</td>"; echo "<td>".@date("Y-m-d H:i:s",$row['addtime'])."</td>"; echo "<td><a href='action.php?action=del&id={$row['id']}&pic={$row['pic']}'>删除</a> <a href='update.php?id={$row['id']}'>修改</a> <a href='{$row['pic']}'>查看</a> <a href='download.php?name={$row['pic']}'>下载</a> <a href='addCart.php?id={$row['id']}'>放入购物车</a> </td>"; echo "</tr>"; } ?> </table> </body> </center> </html> <file_sep><?php //修改购物车中的信息 //1、启动会话 session_start(); //2、获取要修改的信息 $id=$_GET['id']; $num=$_GET['num']; //3、修改商品信息的数量 $_SESSION["shoplist"][$id]["num"]+=$num; //控制商品数量过小 if($_SESSION["shoplist"][$id]["num"]<1){ $_SESSION["shoplist"][$id]["num"]=1; } //4、跳转到我的购物车页面 header("location:myCart.php"); ?> <file_sep><?php //删除购物车中session的信息 //1、在要使用session的页面开始出使用session_start();函数启动会话 session_start();//会话启动,下面可以使用session //判断是删除一个商品还是清空整个购物车。 //因为mycart.php中传过来的是id号,所以如果有id号就是删除一个商品,否则,清空整个购物车 if($_GET['id']){ //从session中删除指定的商品的信息 unset($_SESSION["shoplist"][$_GET['id']]); }else{ //删除购物车中session的信息,一定不要清空session,要清空session里面的信息 unset($_SESSION["shoplist"]); } //跳转到浏览购物车界面 header("location:myCart.php"); ?> <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <center> <?php include "/include/include.php"; //导入导航栏 $typelist=array(1=>"数码",2=>"服装",3=>"车"); ?> <br> <h3>发布商品信息</h3><br> <form action="action.php?action=add" method="post" enctype="multipart/form-data"> <table border="0" width="300" > <tr> <td align="right" width="50">名称:</td> <td><input type="text" name="name"></td> </tr> <tr> <td align="right">类型:</td> <td> <select name="typeid"> <?php foreach($typelist as $key=>$val){ echo "<option value='{$key}'>{$val}</option>"; } ?> </select> </td> </tr> <tr> <td align="right">单价:</td> <td><input type="text" name="price"></td> </tr> <tr> <td align="right">库存:</td> <td><input type="text" name="total"></td> </tr> <tr> <td align="right">图片:</td> <td><input type="file" name="pic"></td> </tr> <tr> <td align="right" valign="top">描述:</td> <td><textarea name="note" rows="10" cols="30"></textarea></td> </tr> <tr > <td colspan="2" align="center"> <input type="submit" name="submit" value="添加" >&nbsp;&nbsp; <input type="reset" name="reset" value="重置"> </td> </tr> </table> </body> </form> </center> </html> <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>修改商品信息</title> </head> <body> <!-- 修改页面和添加页面相同 --> <center> <?php include "/include/include.php"; $typelist=array(1=>"数码",2=>"服装",3=>"车"); //获取要修改的信息 //1.连接数据库 require "/include/conn.php"; //2.获取要修改的商品信息 $id=$_GET["id"]; $sql = "select * from goods where id=$id"; $result=mysql_query($sql); //3.判断是否获取到了要编辑的信息,并解析要修改的信息 $row=mysql_fetch_array($result); ?> <br><br> <h3>编辑商品信息</h3><br> <form action="action.php?action=update" method="post" enctype="multipart/form-data"> <!-- 因为获取的编辑的信息中没有编辑id号,所以点击修改的时候, 提交到执行页面的时候也不会把id号传过去,所以要加一个隐藏域,获取修改的id号 --> <input type="hidden" name="id" value="<?php echo $row['id']; ?>"> <table border="0" > <tr> <td align="right" width="50">名称:</td> <td><input type="text" name="name" value="<?php echo $row['name']; ?>"></td> </tr> <tr> <td align="right">类型:</td> <td> <select name="typeid"> <?php foreach($typelist as $key=>$val){ $sd = ($row['typeid']==$key)?"selected":"";//是否是当前的类型 echo "<option value='{$key}'{$sd}>{$val}</option>"; } ?> </select></td> </tr> <tr> <td align="right">单价:</td> <td><input type="text" name="price" value="<?php echo $row['price']; ?>"</td> </tr> <tr> <td align="right">库存:</td> <td><input type="text" name="total" value="<?php echo $row['total']; ?>"</td> </tr> <tr> <td align="right">图片:</td> <td><input type="file" name="pic" ></td> </tr> <tr> <td align="right" valign="top">描述:</td> <td><textarea name="note" rows="10" cols="30"><?php echo $row['note']; ?></textarea></td> </tr> <tr > <td colspan="2" align="center"> <input type="submit" name="submit" value="修改" > <input type="reset" name="reset" value="重置"></td> </tr> <tr > <td align="right" valign="top">&nbsp;</td> <td><img src="<?php echo $row['pic']; ?>" width="100" height="100"></td> </tr> </table> </body> </form> </center> </html> <file_sep><?php $con=mysql_connect("localhost","root","root"); mysql_select_db("goods"); mysql_query("set names utf8"); ?><file_sep><?php //执行商品的增删改的操作 //一、导入配置文件和函数库文件(没写文件上传和缩放的函数) //二、连接mysql,选择数据库 include "/include/conn.php"; //三、获取action参数的值,并做对应的操作 switch($_GET["action"]){ case "add": //添加 //1、获取添加信息 extract($_POST); $addtime=time(); //2、验证(省略) //3、执行文件(图片)上传 $uploads_dir='./upload'; //var_dump($_FILES); $tmp_name=@$_FILES['pic']['tmp_name']; @$filename=date("YmdHis").rand(1,1000).".jpg"; move_uploaded_file($tmp_name,"$uploads_dir/$filename"); //4、执行图片缩放 //5、拼装sql语句并执行添加(单价设置的是六位数,保留两位小数,所以,若超过位数,自动转成9999.99) $sql="insert into goods(name,typeid, price,pic,total,note,addtime) values('$name', '$typeid', '$price','$uploads_dir/$filename', '$total', '$note','$addtime')"; mysql_query($sql); header("location:index.php"); //6、判断并输出结果 if(mysql_insert_id($link)>0){ echo "商品发布成功"; }else{ echo "商品发布失败"; } break; case "del": //删除 //1、获取要删除的id号,并执行删除语句 $sql="delete from goods where id={$_GET['id']}"; mysql_query($sql); //2、执行图片删除(图片存放目录里的图片被删除) if(mysql_affected_rows($con)>0){//判断是否有图片,有的话,执行删除 unlink($_GET['pic']);//图片的路径。 } //3、跳转页面 header("location:index.php"); break; case "update"; //修改 //1、获取要修改的信息 extract($_POST); $id=$_POST['id']; //2、数据验证 if(empty($name)){ die("商品名称必须有值"); } //3、判断有无图片上传 //4、有图片上传执行缩放 //5、执行修改 $sql="update goods set name='$name',typeid='$typeid', price='$price',total='$total',note='$note' where id='$id'"; echo $sql; mysql_query("set names utf8"); mysql_query($sql); //6、判断是否修改成功 //echo "<a href='index.php'>浏览</a>"; header("location:index.php"); break; } ?><file_sep><?php //在要使用session的页面开始出使用session_start();函数启动会话 session_start();//会话启动,下面可以使用session ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <center> <?php include "/include/include.php"; $typelist=array(1=>"数码",2=>"服装",3=>"车"); ?> <br><br> <h3>添加商品到购物车</h3><br> <?php //从数据库中读取要购买的信息并添加到购物车中 //1.连接数据库 require "/include/conn.php"; //2.执行查询(获取要购买的信息 ) $id=$_GET["id"]; $sql="select * from goods where id='$id'"; $result=mysql_query($sql,$con); //3、判断是否没有找到要购买的信息,若有就读取出购买的信息 if(empty($result) || mysql_num_rows($result)==0){ die("没有找到购买的信息"); }else{ $shop= mysql_fetch_array($result); } $shop["num"]=1;//添加一个数量的字段 //4、准备放入购物车中(若已经存在的商品实现树龄累加) //var_dump($shop); //$_SESSION['shooplist']=$shop;//只能放一个商品 if(isset($_SESSION['shoplist'][$shop['id']])){ //若存在,数量++ $_SESSION['shoplist'][$shop['id']]["num"]++;//[]定义成数组,可以放很多商品 }else{ //若不存在,作为新购买的商品添加到购物车中 $_SESSION['shoplist'][$shop['id']]=$shop; } ?> </table> </body> </center> </html> <file_sep><?php //在要使用session的页面开始出使用session_start();函数启动会话 session_start();//会话启动,下面可以使用session ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <center> <?php include "/include/include.php"; $typelist=array(1=>"数码",2=>"服装",3=>"车"); ?> <br><br> <h3>浏览我的购物车</h3><br> <table border="1" width="600"> <tr> <th>商品id号</th> <th>商品名称</th> <th>商品图片</th> <th>单价</th> <th>数量</th> <th>小计</th> <th>操作</th> </tr> <?php //echo "<pre>"; // var_dump($_SESSION); //echo "</pre>"; $sum=0;//定义总金额的变量 //若不判断会报两个提示 if(isset($_SESSION["shoplist"]))//Notice: Undefined index: shoplist in D:\phpstudy\WWW\goods\myCart.php on line 32 //Warning: Invalid argument supplied for foreach() in D:\phpstudy\WWW\goods\myCart.php on line 32 foreach($_SESSION["shoplist"] as $v){ echo "<tr>"; echo "<td>{$v['id']}</td>"; echo "<td>{$v['name']}</td>"; echo "<td><img src='{$v['pic']}' width='80'></td>"; echo "<td>{$v['price']}</td>"; echo @"<td align='center'> <button onclick='window.location=\"updateCart.php?id={$v['id']}&num=-1\"'>-</button> {$v['num']} <button onclick='window.location=\"updateCart.php?id={$v['id']}&num=+1\"'>+</button> </td>"; echo "<td>".$v["price"]*$v["num"]."</td>"; echo "<td><a href='cleanCart.php?id={$v['id']}'>删除</a></td>"; echo "</tr>"; $sum+=$v["price"]*$v["num"]; //累计金额 } ?> <tr> <th>总结金额:</th> <th colspan="5" align="right"><?php echo $sum; ?></th> <td>&nbsp;</td> </tr> </table> </body> </center> </html>
f7e25d70e3a8f375deb84494a924c64f378f7849
[ "PHP" ]
9
PHP
huihuihuizhi/goods
fb2553b6086622f0f9b5089f33f968382eafe8d6
8e41516d6a4c0fbf64bd9a2f89087d72c18ba608
refs/heads/master
<repo_name>jbertran/apsProject<file_sep>/README.md # apsProject Project for the APS course, M1S2 at UPMC: an interpreter of a mini-Pascal language. <file_sep>/prolog_gen.h #ifndef __prolog__ #define __prolog__ #include "ast.h" void print_program(FILE* f, Program* prog); #endif <file_sep>/ast.h #ifndef __TYPES__H_ #define __TYPES__H_ typedef enum _typeNode { T_PROG, T_CMDS, T_DEC, T_STAT, T_EXPR, T_TYPE } TypeNode; typedef enum _typeDec { T_CONST, T_VAR } TypeDec; typedef enum _typeStat { T_SET, T_IF, T_WHILE, T_ECHO } TypeStat; typedef enum _typeExpr { T_E_BOOL, T_NUM, T_IDENT, T_UNOP, T_BINOP } TypeExpr; typedef enum _operators { T_NOT, T_AND, T_OR, T_EQ, T_LT, T_ADD, T_SUB, T_MUL, T_DIV, T_MOD } Operators; typedef enum _types { T_VOID, T_BOOL, T_INT } PrimitiveType; typedef enum _bool { T_TRUE, T_FALSE } Bool; struct _prog; typedef struct _ast AST; typedef PrimitiveType* Type; typedef struct _unop { Operators op; AST * arg; } UnOp; typedef struct _binop { Operators op; AST * arg1; AST * arg2; } BinOp; typedef struct _expr { TypeExpr type; union { UnOp * unop; BinOp * binop; Bool bool; int num; char* ident; } contents; } Expr; typedef struct _stat { TypeStat type; char* ident; // NULL unless it's a SET AST* expr; AST* prog1; // NULL if it's a SET AST* prog2; // NULL if it's a SET or a WHILE } Stat; typedef struct _dec { TypeDec type; char* ident; AST* decType; AST* expr; // NULL if it's a VAR } Dec; typedef struct _cmds { AST* statDec; AST* next; // Can be NULL. } Cmds; typedef struct _block { AST* cmds; } Block; /* ------------------------------------------ *\ MAIN STRUCT \* ------------------------------------------ */ typedef struct _ast { TypeNode type; union { Block* asBlock; Cmds* asCmds; Dec* asDec; Stat* asStat; Expr* asExpr; Type asType; } content; } AST; typedef struct _program { AST * cmds; } Program; AST* make_block (AST* block); AST* make_cmds (AST* statDec, AST* next); AST* make_var (char* ident, AST* type); AST* make_cst(char* ident, AST* type, AST* expr); AST* make_set(char* ident, AST* expr); AST* make_cond(AST* cond, AST* cons, AST* alt); AST* make_loop(AST* cond, AST* body); AST* make_echo(AST* expr); AST* make_type (PrimitiveType t); AST* make_bool_expr (Bool b); AST* make_integer_expr (int n); AST* make_ident_expr (char* ident); AST* make_unary_expr (Operators op, AST* expr); AST* make_binary_expr (Operators op, AST* expr1, AST* expr2); Program* make_program (AST* cmds); #endif <file_sep>/rapport.md % APS - Evaluateur de mini-Pascal % <NAME> # Résumé ## Utilisation Des fichiers de test syntaxiquement corrects et bien typés sont disponibles dans le souds-dossier `refs`. ### Compilation * Parser : * `$ make parser` * Lexer : * `$ make lexer` * Génération de code Prolog * `$ make type` * Evaluation du programme * `$ make eval` ### Utilisation * La génération du code Prolog se fait par défaut dans `tmptypes.pl` (modifiable en \#define dans eval.c). * Génération du code: `$ ./type <fichier.aps>` * Typage: * `$ swipl typechecker.pl` * Copier le code prolog généré dans le REPL Prolog * Prolog renvoie faux si le programme est mal typé. * Pour faire abstraction des problèmes d'interopérabilité entre C et Prolog, on suppose à l'évaluation que le programme est bien typé. L'évaluation fournit des messages d'erreurs généralement suffisamment verbeux dans le cas contraire. L'évaluation affiche les valeurs contenues dans l'environnement à chaque sortie de bloc (que ce soit pour retourner dans le bloc pour un while, ou réellement en sortie), puisque l'afficher en sortie de programme reverrait un environnement vide à cause du traitement de la portée des variables. * `$ ./aps <fichier.aps>` construit l'AST, et évalue le code contenu dans `fichier.aps`. ### Debug Chaque fichier de traitement de génération et traitement de l'AST contient un switch de debug pour obtenir un affichage verbeux des étapes du traitement, à éventuellement \#define en début du `.c` pour activer cet affichage. # Arbre de syntaxe abstrait Pour simplifier le parser, éviter d'avoir une union de types énorme dans celui-ci et réduire le nombre de tokens à typer différemment dans l'en-tête, tous les noeuds de l'AST sont de type AST, une union entre les différents types concrets de noeuds -- expression, déclaration, etc... Le désavantage de la couche d'indirection supplémentaire est contrebalancé par la facilité de modification du contenu de la structure à l'écriture. # Typage ## Génération du code Prolog Le code Prolog est généré par écriture dans un fichier avec la seule fonction rendue visible par `prolog_gen.h`, qui propose de fournir un file handle dans lequel écrire le code Prolog correspondant au `Programme *` passé en argument. On aurait éventuellement pu récupérer à partir du parser le nombre exact de caractères nécessaires à l'écriture du programme de typage Prolog pour se passer de fichier et ainsi gérer directement le typage en C (avec un appel à `pipe` pour ouvrir une instance de SWIPL dans laquelle on lirait le résultat du typage par exemple), mais ceci nécessite de coder en dur un nombre important de correspondances entre les noeuds de l'AST et le code Prolog généré. En théorie, pour être cohérent avec la logique du typage de _tous_ les noeuds de l'AST en `AST`, on devrait utiliser un `switch` sur le type interne du noeud dans une fonction générale de gestion de l'AST pour aiguiller l'opération à faire. En pratique, ceci rend le code difficile à lire, et on préfère donc aiguiller manuellement sur fonctions de gestion des types internes, ce qui est gérable vu le faible nombre de types internes. Cette remarque est également valable pour le code de l'évaluateur. ## Typage du programme Le typeur lui-même ne contient que 2 règles différentes: * type(instruction, environnement, type) * typeNamed(instruction, environnement, nouvel environnement, type) L'environnement est ici représenté sous la forme d'une liste de triplets tr(nomVar, const, type). Le suivi de trois valeurs dans l'environnement au lieu de deux nous permet de détecter au typage les tentatives d'accès en écriture à des variables constantes. # Evaluation L'évaluateur suppose le programme correctement typé après la passe de parsing et de typage prolog. On vérifie quand même que les types concordent lors de l'évaluation, notamment avec l'opérateur `default` des `switch` qui permet de repérer quand une valeur d'énumération ne concorde pas avec les valeurs attendues. Ceci nous prémunit aussi contre les malformations de l'AST, sans coût supplémentaire. Les erreurs de confusion entre variable et constante ainsi que les tentatives d'accès en lecture à une variable non définie sont également signalées par l'évaluateur, qui les traite comme des erreurs fatales. ## Valeurs Par soucis de séparation des étapes, toutes les énumérations qu'on peut retrouver à la fois dans la génération de l'AST (ast.x) et dans l'évaluation du programme -- par exemple l'énumération des types primitifs -- sont séparées, avec une énumération côté AST (T\_X) et une côté évaluateur (EVAL\_X). Par soucis de clarté de relecture, même si il est possible de gérer toutes nos valeurs primitives (entiers et booléens) avec des `int` C, on préfère boxer nos types. Ceci améliore aussi la facilité d'ajout de nouveaux types primitifs, puisqu'il suffit alors de les rajouter dans la structure de boxing et dans les `switch` traitant les types primitifs dans l'évaluateur. <file_sep>/aps.c #include <stdio.h> #include <stdlib.h> #include "prolog_gen.h" #include "aps.tab.h" #include "ast.h" #include "aps.h" #include "eval.h" int main(int argc, char* argv[]) { FILE *fp; if (argc > 1) { // Open program if (! (fp = fopen(argv[1], "r"))) { fprintf(stderr, "Error, can't open %s\n", argv[1]); exit(1); } // AST! Program* prog = ast_from_program(fp); // Eval! fprintf(stdout, "Evaluating..\n"); eval_program(prog); } else { fprintf(stderr, "Error, no file specified\n"); exit(1); } return 0; } <file_sep>/typeur.c #include "aps.h" #include "prolog_gen.h" #include <stdio.h> #include <stdlib.h> #define PL_PATH "tmptypes.pl" int main(int argc, char* argv[]) { FILE* fp; // Open program if (! (fp = fopen(argv[1], "r"))) { fprintf(stderr, "Error, can't open %s\n", argv[1]); exit(1); } // AST! Program* prog = ast_from_program(fp); // Typing! FILE* typefp; if (! (typefp = fopen(PL_PATH, "w"))) { fprintf(stderr, "Error, can't write prolog typing file %s\n", PL_PATH); exit(EXIT_FAILURE); } fprintf(stdout, "Printing to type file..\n"); print_program(typefp, prog); fprintf(stdout, "Done\n"); fclose(typefp); return 0; } <file_sep>/tests.c #include <stdio.h> #include <stdlib.h> #include "prolog_gen.h" #include "aps.tab.h" #include "ast.h" #include "aps.h" #include "eval.h" #define PL_PATH "tmptypes.pl" int main(int argc, char* argv[]) { FILE *fp; if (argc > 1) { // Open program if (! (fp = fopen(argv[1], "r"))) { fprintf(stderr, "Error, can't open %s\n", argv[1]); exit(1); } // AST! Program* prog = ast_from_program(fp); // Typing! FILE* typefp; if (! (typefp = fopen(PL_PATH, "w"))) { fprintf(stderr, "Error, can't write prolog typing file %s\n", PL_PATH); exit(EXIT_FAILURE); } fprintf(stdout, "Printing to type file..\n"); print_program(typefp, prog); fprintf(stdout, "Done\n"); fclose(typefp); fprintf(stdout, "Evaluating..\n"); eval_program(prog); } else { fprintf(stderr, "Error, no file specified\n"); exit(1); } return 0; } <file_sep>/Makefile CC=gcc CFLAGS=-Wall -g all: eval type parser: aps.y bison -d aps.y lexer: aps.l flex aps.l type: lexer parser prolog_gen.c typeur.c ast.c eval.c $(CC) $(CFLAGS) -o type typeur.c prolog_gen.c ast.c aps.tab.c lex.yy.c -lfl eval: lexer parser prolog_gen.c aps.c ast.c eval.c $(CC) $(CFLAGS) -o eval aps.c eval.c ast.c aps.tab.c lex.yy.c -lfl clean: rm -f *tab.* lex.yy.c eval type *~ *.o tests <file_sep>/prolog_gen.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include "ast.h" #include "prolog_gen.h" #ifdef DEBUG_PLG #define debug_plg(str) {fprintf(stderr, "%s\n", str); fflush(stderr);} #else #define debug_plg(str) ; #endif // Forward decs void print_block(FILE* f, AST* block); void print_cmds(FILE* f, AST* cmds); void print_seq(FILE* f, Cmds* cmds); void print_dec(FILE* f, AST* dec); void print_stat(FILE* f, AST* stat); void print_expr(FILE* f, AST* expr); void print_type(FILE* f, AST* type); void print_program(FILE* f, Program* prog) { debug_plg("Program"); fprintf(f, "type(prog("); print_block(f, prog->cmds); fprintf(f, "), [], void)."); } void print_block(FILE* f, AST* block) { debug_plg("Block"); fprintf(f, "["); print_cmds(f, block->content.asBlock->cmds); fprintf(f, "]"); } void print_cmds(FILE* f, AST* cmds) { debug_plg("Cmds"); print_seq(f, cmds->content.asCmds); } void print_seq(FILE* f, Cmds* cmds) { debug_plg("Seq"); while(cmds) { AST* statdec = cmds->statDec; switch (statdec->type) { case T_STAT: if (cmds->next) { print_stat(f, statdec); fprintf(f, ","); } else print_stat(f, statdec); break; case T_DEC: if (cmds->next) { print_dec(f, statdec); fprintf(f, ","); } else print_dec(f, statdec); break; default: fprintf(stderr, "Sequence error - invalid instruction\n"); exit(EXIT_FAILURE); } if (!cmds->next) break; cmds = cmds->next->content.asCmds; } } void print_dec(FILE* f, AST* dec) { debug_plg("Dec"); Dec* decl = dec->content.asDec; switch (decl->type) { case T_CONST: fprintf(f, "const(%s,", decl->ident); print_type(f, decl->decType); fprintf(f, ","); print_expr(f, decl->expr); fprintf(f, ")"); break; case T_VAR: fprintf(f, "var(%s,", decl->ident); print_type(f, decl->decType); fprintf(f, ")"); break; default: fprintf(stderr, "Unknown declaration type!\n"); exit(EXIT_FAILURE); } } void print_stat(FILE* f, AST* st) { debug_plg("Stat"); Stat* stat = st->content.asStat; switch (stat->type) { case T_SET: fprintf(f, "set(%s,", stat->ident); print_expr(f, stat->expr); fprintf(f, ")"); break; case T_IF: fprintf(f, "if("); print_expr(f, stat->expr); fprintf(f, ","); print_block(f, stat->prog1); fprintf(f, ","); print_block(f, stat->prog2); fprintf(f, ")"); break; case T_WHILE: fprintf(f, "while("); print_expr(f, stat->expr); fprintf(f, ","); print_block(f, stat->prog1); fprintf(f, ")"); break; case T_ECHO: fprintf(f, "echo("); print_expr(f, stat->expr); fprintf(f, ")"); break; default: fprintf(stderr, "Unknown statement type!\n"); exit(EXIT_FAILURE); } } void print_expr(FILE* f, AST* exp) { debug_plg("Expr"); Expr* expr = exp->content.asExpr; switch (expr->type) { case T_E_BOOL: if (expr->contents.bool == T_TRUE) fprintf(f, "true"); else fprintf(f, "false"); break; case T_NUM: fprintf(f, "%d", expr->contents.num); break; case T_IDENT: fprintf(f, "%s", expr->contents.ident); break; case T_UNOP: { UnOp* un = expr->contents.unop; switch (un->op) { case T_NOT: fprintf(f, "not("); break; default: fprintf(stderr, "Unknown operand!\n"); exit(EXIT_FAILURE); } print_expr(f, un->arg); fprintf(f, ")"); break; } case T_BINOP: { BinOp* bin = expr->contents.binop; switch (bin->op) { case T_AND: fprintf(f, "and("); break; case T_OR: fprintf(f, "or("); break; case T_EQ: fprintf(f, "eq("); break; case T_LT: fprintf(f, "lt("); break; case T_ADD: fprintf(f, "add("); break; case T_SUB: fprintf(f, "sub("); break; case T_MUL: fprintf(f, "mul("); break; case T_DIV: fprintf(f, "div("); break; case T_MOD: fprintf(f, "mod("); break; default: fprintf(stderr, "Unknown operand!\n"); exit(EXIT_FAILURE); } print_expr(f, bin->arg1); fprintf(f, ","); print_expr(f, bin->arg2); fprintf(f, ")"); } break; default: fprintf(stderr, "Unknown expression type!\n"); exit(EXIT_FAILURE); } } void print_type(FILE* f, AST* type) { debug_plg("Type"); switch (*(type->content.asType)) { case T_VOID: fprintf(f, "void"); break; case T_BOOL: fprintf(f, "bool"); break; case T_INT: fprintf(f, "int"); } }
b98373e7aea640b57be7198af371d9e8499612dd
[ "Markdown", "C", "Makefile" ]
9
Markdown
jbertran/apsProject
8c59e03cedcb820b6d83e0a3928ee030d8b2efd9
eb456644fb44b851095a9ede9a494c28f4282c3a
refs/heads/master
<file_sep>''' Contains all the utility funcs. ''' import os import re import sys import imghdr def delete_layout(layout, delete_container=True): if layout is None: return for i in reversed(range(layout.count())): item = layout.itemAt(i).widget() layout.removeItem(layout.itemAt(i)) if item is not None: item.setParent(None) else: delete_layout(layout.itemAt(i).layout(), delete_container=True) if delete_container: layout.deleteLater() del layout def ident(x): return x def natural_sort(file_list, get_filename=ident): def natural_string_compare(a, b): str1 = get_filename(a) str2 = get_filename(b) str_chunks1 = [int(x) if (x is not None and x.isdigit()) else x for x in re.split('(\d+)|[-_\.\/]', str1.lower())] str_chunks2 = [int(x) if (x is not None and x.isdigit()) else x for x in re.split('(\d+)|[-_\.\/]', str2.lower())] return cmp(str_chunks1, str_chunks2) return sorted(file_list, cmp=natural_string_compare) def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) def is_supported_file(fname): if os.path.isfile(fname): if imghdr.what(fname) in ('tiff', 'jpeg', 'png', 'gif'): return True if fname.lower().endswith('.pdf'): return True return False <file_sep>hiddenimports = ['keyring.credentials', 'keyring.backends.file', 'keyring.backends.Gnome', 'keyring.backends.Google', 'keyring.backends.keyczar', 'keyring.backends.kwallet', 'keyring.backends.multi', 'keyring.backends.OS_X', 'keyring.backends.pyfs', 'keyring.backends.SecretService', 'keyring.backends.Windows', 'keyring.util', 'keyring.util.escape', 'keyring.util.XDG', 'keyring.util.platform_', 'keyring.util.properties'] <file_sep>''' Contains all the GUI and backend code to initiate new uploads to Captricity. ''' import os import glob from captools.api import Client from PySide import QtCore, QtGui from utils import delete_layout, natural_sort, is_supported_file class NewUploadWindow(QtGui.QWidget): MENU_WINDOW = 0 LIST_WINDOW = 1 CREATE_WINDOW = 2 CONFIRM_WINDOW = 3 DEFAULT_BATCH_NAME = 'New Batch' def __init__(self, cap_client, main_window, parent=None): self.cap_client = cap_client self.main_window = main_window self.upload_manager = None self.menu_layout = QtGui.QVBoxLayout() self.menu_widget = QtGui.QWidget() self.menu_widget.setLayout(self.menu_layout) self.list_layout = QtGui.QVBoxLayout() self.list_widget = QtGui.QWidget() self.list_widget.setLayout(self.list_layout) self.confirm_layout = QtGui.QVBoxLayout() self.confirm_widget = QtGui.QWidget() self.confirm_widget.setLayout(self.confirm_layout) self.create_layout = QtGui.QVBoxLayout() self.create_widget = QtGui.QWidget() self.create_widget.setLayout(self.create_layout) self.layout_ = QtGui.QStackedLayout() self.layout_.addWidget(self.menu_widget) self.layout_.addWidget(self.list_widget) self.layout_.addWidget(self.create_widget) self.layout_.addWidget(self.confirm_widget) super(NewUploadWindow, self).__init__(parent) self.setLayout(self.layout_) self.load_menu_window() self.new_batch_name = NewUploadWindow.DEFAULT_BATCH_NAME def upload_to_batch(self): batch_getter = lambda: self.cap_client.read_batches('?status=setup') self.load_list_window(batch_getter, self.batch_upload_callback_func_generator) def create_batch(self): new_batch = self.cap_client.create_batches({'name': self.new_batch_name}) self.batch_upload_callback_func_generator(new_batch)() def cancel(self): self.close() self.main_window.close_new_upload() def batch_upload_callback_func_generator(self, batch): def callback(): directory = str(QtGui.QFileDialog.getExistingDirectory(None, 'Select directory to upload')) if directory: self.upload_manager = UploadToBatch(self.main_window.cap_client, self.main_window.pool, batch['id'], directory) self.load_confirm_window(self.upload_manager) return callback def upload(self): # Trigger upload self.close() self.main_window.add_upload_tracker(self.upload_manager) def load_menu_window(self): delete_layout(self.menu_layout, delete_container=False) self.layout_.setCurrentIndex(NewUploadWindow.MENU_WINDOW) self.load_prev_window = self.cancel self.load_current_window = self.load_menu_window self.close() self.resize(350, 250) upload_to_batch = QtGui.QPushButton('Upload to Batch', self) self.connect(upload_to_batch, QtCore.SIGNAL('clicked()'), self.upload_to_batch) cancel = QtGui.QPushButton('Cancel', self) self.connect(cancel, QtCore.SIGNAL('clicked()'), self.load_prev_window) self.menu_layout.addWidget(upload_to_batch) self.menu_layout.addWidget(cancel) def load_list_window(self, get_captricity_objects, callback_func_generator): delete_layout(self.list_layout, delete_container=False) self.layout_.setCurrentIndex(NewUploadWindow.LIST_WINDOW) self.load_prev_window = self.load_menu_window self.load_current_window = lambda: self.load_list_window(get_captricity_objects, callback_func_generator) captricity_objects = get_captricity_objects() buttons = [] for obj in captricity_objects: button = QtGui.QPushButton(obj['name'], self) self.connect(button, QtCore.SIGNAL('clicked()'), callback_func_generator(obj)) buttons.append(button) create_button = QtGui.QPushButton('Create', self) self.connect(create_button, QtCore.SIGNAL('clicked()'), self.load_create_window) refresh_button = QtGui.QPushButton('Refresh', self) self.connect(refresh_button, QtCore.SIGNAL('clicked()'), self.load_current_window) back_button = QtGui.QPushButton('Back', self) self.connect(back_button, QtCore.SIGNAL('clicked()'), self.load_prev_window) actions_layout = QtGui.QHBoxLayout() actions_layout.addStretch(1) actions_layout.addWidget(create_button) actions_layout.addWidget(refresh_button) actions_layout.addWidget(back_button) button_layout = QtGui.QVBoxLayout() for button in buttons: button_layout.addWidget(button) self.list_layout.addLayout(button_layout) self.list_layout.addLayout(actions_layout) def load_confirm_window(self, upload_manager): delete_layout(self.confirm_layout, delete_container=False) self.layout_.setCurrentIndex(NewUploadWindow.CONFIRM_WINDOW) self.load_prev_window = self.load_current_window self.load_current_window = lambda: self.load_confirm_window(upload_manager) instructions = QtGui.QLabel('We will upload the following files:') list_widget = QtGui.QListWidget() for fname in upload_manager.files: list_widget.addItem(os.path.basename(fname)) next_button = QtGui.QPushButton('Next') self.connect(next_button, QtCore.SIGNAL('clicked()'), self.upload) cancel_button = QtGui.QPushButton('Cancel', self) self.connect(cancel_button, QtCore.SIGNAL('clicked()'), self.load_prev_window) actions_layout = QtGui.QHBoxLayout() actions_layout.addStretch(1) actions_layout.addWidget(cancel_button) actions_layout.addWidget(next_button) self.confirm_layout.addWidget(instructions) self.confirm_layout.addWidget(list_widget) self.confirm_layout.addLayout(actions_layout) def load_create_window(self): delete_layout(self.create_layout, delete_container=False) self.layout_.setCurrentIndex(NewUploadWindow.CREATE_WINDOW) self.load_prev_window = self.load_current_window self.load_current_window = lambda: self.load_create_window() instructions = QtGui.QLabel('Name this batch') self.new_batch_name = NewUploadWindow.DEFAULT_BATCH_NAME name_box = QtGui.QLineEdit(self) def name_box_changed(text): self.new_batch_name = text name_box.textChanged[str].connect(name_box_changed) next_button = QtGui.QPushButton('Next') self.connect(next_button, QtCore.SIGNAL('clicked()'), self.create_batch) cancel_button = QtGui.QPushButton('Cancel', self) self.connect(cancel_button, QtCore.SIGNAL('clicked()'), self.load_prev_window) actions_layout = QtGui.QHBoxLayout() actions_layout.addStretch(1) actions_layout.addWidget(cancel_button) actions_layout.addWidget(next_button) self.create_layout.addWidget(instructions) self.create_layout.addWidget(name_box) self.create_layout.addLayout(actions_layout) class UploadTracker(QtGui.QWidget): image_uploaded = QtCore.Signal() def __init__(self, upload_manager, parent=None): self.upload_manager = upload_manager self.upload_manager.link_pbar(self) super(UploadTracker, self).__init__(parent) self.load_window() self.image_uploaded.connect(self.handle_update) def load_window(self): self.resize(300, 50) self.label = QtGui.QLabel(self.upload_manager.label, self) self.pbar = QtGui.QProgressBar(self) self.pbar.setValue(0) self.pbar.setGeometry(0, 25, 200, 25) def handle_update(self): self.pbar.setValue(self.upload_manager.progress) class Uploader(object): def __init__(self, client, pool, directory): self.result_set = None self.linked_pbar = None self.client = client self.pool = pool self.directory = directory self.files = natural_sort(filter(is_supported_file, glob.glob(os.path.join(directory, '*')))) def link_pbar(self, pbar): self.linked_pbar = pbar def start(self): assert self.linked_pbar is not None if self.batch_id is None: new_batch = self.client.create_batchs() self.batch_id = new_batch['id'] self.result_set = [0 for i in xrange(len(self.files))] for idx, f in enumerate(self.files): self.pool.apply_async(upload_file, (self.client.api_token, self.batch_id, f), callback=self.upload_finished_callback_generator(idx)) def upload_finished_callback_generator(self, idx): def callback(result): if self.result_set is not None: self.result_set[idx] = 1 # Trigger a signal self.linked_pbar.image_uploaded.emit() return callback @property def progress(self): return int(sum(self.result_set) * 100 / len(self.result_set)) class UploadToBatch(Uploader): def __init__(self, client, pool, batch_id, directory): self.batch_id = batch_id super(UploadToBatch, self).__init__(client, pool, directory) self.label = 'Batch %s: %s' % (self.batch_id, self.directory) def upload_file(api_token, batch_id, f): client = Client(api_token) client.create_batch_files(batch_id, {'uploaded_file': open(f)}) <file_sep>captricity-python-client keyring PySide <file_sep># -*- mode: python -*- root = '/Users/yoriyasuyano/Documents/captricity/Captricity-Desktop-Uploader' a = Analysis(['capdesk.py'], pathex=[root], hiddenimports=[], hookspath=['pyinstaller-pyside-hooks/'], runtime_hooks=None) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name=os.path.join(root, 'dist', 'capdesk'), debug=False, strip=None, upx=False, console=False ) app = BUNDLE(exe, name=os.path.join(root, 'dist', 'capdesk.app'), icon='icons/CapIcon.icns') <file_sep>import sys import keyring import getpass import multiprocessing import PySide from captools.api import Client from new_upload import NewUploadWindow, UploadTracker APP_NAME = "capdesk" username = getpass.getuser() client = None class ApiTokenDialog(PySide.QtGui.QDialog): def __init__(self, parent=None): super(ApiTokenDialog, self).__init__(parent) self.resize(250, 100) self.setWindowTitle('API Token') self.instructions = PySide.QtGui.QLabel('Please enter your Captricity API Token', self) self.api_token_text = PySide.QtGui.QLineEdit(self) self.ok_button = PySide.QtGui.QPushButton('Ok', self) self.ok_button.clicked.connect(self.handle_ok) actions_layout = PySide.QtGui.QHBoxLayout() actions_layout.addStretch(1) actions_layout.addWidget(self.ok_button) layout = PySide.QtGui.QVBoxLayout() layout.addWidget(self.instructions) layout.addWidget(self.api_token_text) layout.addLayout(actions_layout) self.setLayout(layout) def handle_ok(self): self.api_token = str(self.api_token_text.text()).strip() try: self.client = Client(self.api_token) self.client.read_user_profile() keyring.set_password(APP_NAME, username, self.api_token) self.accept() except: PySide.QtGui.QMessageBox.warning(self, 'Required API Token', 'A valid Captricity API Token is required to use the Captricity Desktop Client') # Now initialize the main app class MainWindow(PySide.QtGui.QMainWindow): def __init__(self, client, parent=None): self.cap_client = client self.pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2) super(MainWindow, self).__init__(parent) self.resize(350, 250) self.setWindowTitle(APP_NAME) new_upload = PySide.QtGui.QAction('New Upload', self) new_upload.setShortcut('Ctrl+N') new_upload.setStatusTip('Initiate a new upload to Captricity') self.connect(new_upload, PySide.QtCore.SIGNAL('triggered()'), self.initiate_new_upload) exit = PySide.QtGui.QAction('Exit', self) exit.setShortcut('Ctrl+Q') exit.setStatusTip('Exit application') self.connect(exit, PySide.QtCore.SIGNAL('triggered()'), PySide.QtCore.SLOT('close()')) self.statusBar() menu = self.menuBar() file_menu = menu.addMenu('File') file_menu.addAction(new_upload) file_menu.addAction(exit) toolbar = self.addToolBar('Main') toolbar.addAction(new_upload) toolbar.addAction(exit) self.main_widget = MainWidget(self) self.setCentralWidget(self.main_widget) def initiate_new_upload(self): self.new_upload_window = NewUploadWindow(self.cap_client, self) self.new_upload_window.resize(350, 250) self.new_upload_window.show() def close_new_upload(self): self.new_upload_window = None def add_upload_tracker(self, upload_manager): self.main_widget.add_upload_tracker(upload_manager) class MainWidget(PySide.QtGui.QWidget): def __init__(self, parent=None): self.progress_bars = [] super(MainWidget, self).__init__(parent) self.container_widget = PySide.QtGui.QWidget() self.container_layout = PySide.QtGui.QVBoxLayout(self) self.container_widget.setLayout(self.container_layout) self.scroll_area = PySide.QtGui.QScrollArea() self.scroll_area.setVerticalScrollBarPolicy(PySide.QtCore.Qt.ScrollBarAlwaysOn) self.scroll_area.setHorizontalScrollBarPolicy(PySide.QtCore.Qt.ScrollBarAlwaysOff) self.scroll_area.setWidgetResizable(False) self.scroll_area.setWidget(self.container_widget) self.layout_ = PySide.QtGui.QVBoxLayout(self) self.layout_.addWidget(self.scroll_area) self.setLayout(self.layout_) def add_upload_tracker(self, upload_manager): pbar = UploadTracker(upload_manager) self.progress_bars.append(pbar) self.container_layout.addWidget(pbar) upload_manager.start() self.container_widget.resize(1000, 75 * len(self.progress_bars)) if __name__ == '__main__': app = PySide.QtGui.QApplication(sys.argv) # Obtain the API token from the keyring if it exists. Otherwise, have the user enter it. api_token = keyring.get_password(APP_NAME, username) if not api_token: #Open dialog box to obtain api_token from user and store it dialog = ApiTokenDialog() if not dialog.exec_() == PySide.QtGui.QDialog.Accepted: sys.exit(0) client = dialog.client else: client = Client(api_token) main = MainWindow(client) main.show() if sys.platform == 'darwin': main.raise_() sys.exit(app.exec_()) <file_sep>This is a desktop image uploader for Captricity to make it easier to batch upload a large number of files.
f669a153e1e87163bd36c34a0f85e5a9072d0234
[ "Markdown", "Python", "Text" ]
7
Python
yorinasub17/Captricity-Desktop-Uploader
9b19b98f181d7ae8216b10d8f2df59e42fd71eb7
9d9c1d011c821eb96e42bba39f77ed7d61bfd7e6
refs/heads/master
<repo_name>hebertjulio/TripPlanner<file_sep>/src/screens/TripsScreen/index.js import React, { Component } from 'react'; import { View, Text, FlatList } from 'react-native'; import Trip from './Trip' import isIphoneX from '../../utils/IsIphoneX'; export default class TripsScreen extends Component { static navigationOptions = { header: null }; renderItem = item => { return ( <Trip onPress={() => this.props.navigation.navigate('Trip')} title={item.item.name} price={item.item.price}/> ); }; render() { const trips = [ { id: '1', name: 'Eurotrip 2019', price: 'R$ 5000' }, { id: '2', name: 'Expedição Atacama', price: 'R$ 3000' }, { id: '3', name: 'Aventurando na África', price: 'R$ 4000' } ]; return ( <View style={{ backgroundColor: 'blue', flex: 1, justifyContent: 'space-between', alignItems: 'stretch' }}> <View style={{ backgroundColor: 'red', flex: 1 }}> <Text>Mapa</Text> </View> <View style={{ backgroundColor: 'pink' }}> <FlatList data={trips} renderItem={this.renderItem} horizontal pagingEnabled keyExtractor={ item => item.id } style={[ isIphoneX() ? { marginBottom: 20 } : null ]} /> </View> </View> ); }; }<file_sep>/src/screens/TripsScreen/Trip/styles.js import { StyleSheet } from 'react-native'; export default styles = StyleSheet.create({ wrapperTrip: { backgroundColor: 'white', paddingTop: 16, paddingLeft: 16, paddingRight: 16, paddingBottom: 16 }, image: { backgroundColor: 'green', height: 147, marginBottom: 6 }, price: { position: 'absolute', top: 144 - 32, right: 32, textAlign: 'right', backgroundColor: '#544F9B', paddingTop: 10, paddingRight: 16, paddingBottom: 10, paddingLeft: 16, color: 'white', fontWeight: 'bold', fontSize: 18 } });<file_sep>/src/screens/HomeScreen/index.js import React, { Component } from 'react'; import { View, Text, ImageBackground, Image, TouchableWithoutFeedback } from 'react-native'; import assets from './assets'; import styles from './styles'; import isIphoneX from '../../utils/IsIphoneX'; export default class HomeScreen extends Component { static navigationOptions = { header: null }; state = { show: true }; handleShow = () => { this.setState({ show: !this.state.show }); }; render() { return( <ImageBackground source={assets.background} imageStyle={{resizeMode: 'stretch'}} style={styles.background}> <View style={styles.wrapperLogoTripPlanner}> <Image source={assets.tripPlanner}/> </View> <View style={styles.wrapperLogoDevPleno}> <Image source={assets.devPleno}/> </View> <TouchableWithoutFeedback onPress={() => this.props.navigation.navigate('Trips')}> { !this.state.show ? <View style={[styles.buttonBackground, isIphoneX() ? {paddingBottom: 32} : null]}> <Text style={styles.buttonText}>Começar!</Text> </View> : <View style={styles.buttonEmptyStateBackground}> <Image source={assets.pin} style={styles.pin}/> <Text style={styles.buttonEmptyStateText}>Vamos planejar a sua primeira viagem?</Text> <Image source={assets.arrowRight} style={[styles.arrow, isIphoneX() ? {marginBottom: 16} : null]}/> </View> } </TouchableWithoutFeedback> </ImageBackground> ); } } <file_sep>/src/screens/HomeScreen/assets.js export default assets = { background: require('../../../assets/background.png'), tripPlanner: require('../../../assets/tripplanner.png'), devPleno: require('../../../assets/devpleno.png'), arrowRight: require('../../../assets/arrowright.png'), pin: require('../../../assets/pin.png') };
c4e8f1fc9b9ee1850b3bf38cb6d1ea0537e60275
[ "JavaScript" ]
4
JavaScript
hebertjulio/TripPlanner
22ddd304e3a2e665188efc7e71253c46a6387cd2
ba43f4c07e8216e3fd883384a94bf7aa5ef6172b
refs/heads/master
<repo_name>Yasin92X/carousel.js<file_sep>/readme.md # carousel.js: 高性能网页轮播库 > carousel.js是一个异步执行的网页轮播JS库,具有性能高,定制性强,SEO友好等优点,是制作高性能网站必备的JS库之一 ## 使用方法 * 在网页头部引入carousel.js,推荐添加async异步执行 * 编辑基础的HTML和CSS代码,使carousel在不运行的情况下,可正常查看,基础的符合carousel.js规范轮播结构包含以下四个组件: * carousel-container: 轮播容器,包含所有的轮播组件 * carousel-scroll: 轮播滚动器,包含所有的用于轮播的幻灯片 * carousel-indicator: (可选)轮播指示器,用于显示当前播放的幻灯片索引 * carousel-next-button和carousel-previous-button: (可选)翻页按钮,用于切换播放的幻灯片 * 编辑好HTML和CSS之后,对相应的标签添加属性以指定轮播库组件,一个demo如下: ``` <div class="container" carousel-container> <ul class="altas" carousel-scroll> <li><img src="example.jpg" alt="example"></li> <li><img src="example.jpg" alt="example"></li> <li><img src="example.jpg" alt="example"></li> <li><img src="example.jpg" alt="example"></li> </ul> <div class="indicator" carousel-indicator></div> <span carousel-next-button></span> <span carousel-previous-button></span> </div> ``` * carousel.js还支持更多自定义选项,可分别在不同的域内指定: * carousel-container: * carousel-loop 无缝循环滚动 * carousel-autoplay 自动滚动 * carousel-mousewheel 是否绑定鼠标滚轮切换幻灯片显示 * carousel-delay 需要指定值,自动滚动间隔,单位毫秒,默认6000毫秒 * carousel-duration 需要指定值,每次滚动时间,单位毫秒,默认600毫秒 * carousel-step 需要指定值,每次滚动的个数,默认为窗口可见的完整对象个数 * carousel-direction 需要指定值,滚动方向,x轴或y轴,默认x * carousel-scroll: * carousel-scroll-activeclass 可见的幻灯片类名,默认visible * carousel-indicator: * carousel-indicator-focusclass 焦点指示器类名,默认carousel-indicator-active ## 注意 * carousel.js支持不同宽度的幻灯片切换,**carousel-scroll下的幻灯片应为inline-block**, **carousel-scroll应该添加overflow:hidden属性** * carousel.js会根据系统配置自动往carousel-indicator添加子元素,元素类型为span,请根据展示需要自行配置样式 * 系统对正在显示的幻灯片动态添加了类名,可使用CSS动画属性进行动画个性化定制 * carousel-mousewheel绑定了鼠标滚轮事件切换幻灯片,如果此时使用carousel-loop,可能会造成鼠标滚轮被锁定,无法滚动网页,避免同时使用它们 * 关于使用问题,或上报bug请联系vip#<EMAIL>(#=>@) <file_sep>/script/carousel.js /* * Carousel.js 0.0.7 * Copyright Hito (<EMAIL>) All rights reserved * * * JS异步执行轮播组件库,由杨海涛编写,所有权力保留 * 使用方法: * 异步引用组件库,编写HTML和CSS,使HTML能在不适用JS条件下正常展示 * 给轮播容器指定carousel-container属性 * 给轮播滚动父元素指定carousel-scroll属性 * * * 可选展示功能: * 为轮播容器添加一个子元素,并给予carousel-indicator属性 * 即激活了轮播指示器功能,添加carousel-indicator-focusclass属性并赋值,即可指定焦点指示器类名 * 为录播容器添加2个元素,并给与carousel-next-button或carousel-previous-button * 即激活了前后翻页功能 * 注意: 为保持灵活性,基础样式请自行指定 * * 其他可选展示样式 * 为轮播容器添加不同属性,即可使用自定义功能 * carousel-loop 无缝循环滚动 * carousel-autoplay 自动滚动 * carousel-delay 自动滚动间隔,单位毫秒,默认6000毫秒 * carousel-duration 每次滚动时间,单位毫秒,默认600毫秒 * carousel-step 每次滚动的个数,默认为窗口可见的完整对象个数 * carousel-direction 滚动方向,x轴或y轴,默认x * * 为轮播carousel-scroll增加不同属性,可定义 * carousel-scroll-activeclass 可见的幻灯片class */ (function(w){ 'use strict'; var version = '0.0.7'; var readyState = w.document.readyState; var carousels; //第一次加载时执行初始化函数 if(readyState === "complete"){ init(); }else{ w.addEventListener("load", init); } //解析DOM,开始工作 function init(){ carousels = w.document.querySelectorAll('[carousel-container]'); carousels.forEach(function(carousel){ //是否循环滚动 var loop = carousel.hasAttribute('carousel-loop'); //是否自动滚动 var autoplay = carousel.hasAttribute('carousel-autoplay'); //每次滑动延迟时间 var delay = carousel.hasAttribute('carousel-delay') ? parseInt(carousel.getAttribute('carousel-delay')) : 6000; //每次动画持续时间 var duration = carousel.hasAttribute('carousel-duration') ? parseInt(carousel.getAttribute('carousel-duration')): 600; //每次滑动的子元素个数,默认为视野内的所有子元素 var step = carousel.hasAttribute('carousel-step') ? parseInt(carousel.getAttribute('carousel-step')) : 'auto'; //滑动的方向x轴或者y轴 var direction = carousel.hasAttribute('carousel-direction') ? ['x','y'].indexOf(carousel.getAttribute('carousel-direction')) == -1 ? 'x' : carousel.getAttribute('carousel-direction') : 'x'; //是否通过鼠标控制滚动 var mousewheel = carousel.hasAttribute('carousel-mousewheel'); //滚动元素的父元素 var carouselscroll = carousel.querySelector('[carousel-scroll]'); if(!carouselscroll) return; //可见幻灯片的属性 var carouselscrollactiveclass = carouselscroll.getAttribute('carousel-scroll-activeclass') || 'visible'; //初始化classname carousel.classList.add('carousel-container'); carouselscroll.classList.add('carousel-scroll'); if(direction === 'x') carouselscroll.classList.add('carousel-scroll-x'); else carouselscroll.classList.add('carousel-scroll-y'); //指示图标 var indicator = carousel.querySelector('[carousel-indicator]') var activeclass = indicator ? indicator.getAttribute('carousel-indicator-focusclass') || 'carousel-indicator-active' : 'carousel-indicator-active'; //上下按钮 var nextbutton = carousel.querySelector('[carousel-next-button]'); var previousbutton = carousel.querySelector('[carousel-previous-button]'); if(nextbutton){ nextbutton.classList.add('carousel-nextbutton'); nextbutton.setAttribute('role', 'button'); nextbutton.setAttribute('tabindex', '0'); } if(previousbutton){ previousbutton.classList.add('carousel-previousbutton'); previousbutton.setAttribute('role', 'button'); previousbutton.setAttribute('tabindex', '0'); } //初始化轮播对象 var carousel = new Carousel(carouselscroll, carouselscrollactiveclass, duration, step, loop, direction, indicator, activeclass, nextbutton, previousbutton, mousewheel); if(autoplay){ carousel.autoplay(delay); } }); } //轮播构造对象 function Carousel(carouselscroll, carouselscrollactiveclass, duration, step, loop, direction, indicator, activeclass, nextbutton, previousbutton, mousewheel){ //替代对象 var _this = this; //是否动画中 var in_transition = false; //是否可以动画 var eligible = true; //自动播放ID var autoplayid; //幻灯片容器HTML var html = carouselscroll.outerHTML; //幻灯片容器包裹元素 var carouselwrap; //轮播对象的原始位置 var carouselleft; var carouselright; var carouseltop; var carouselbottom; //轮播对象默认的宽度和高度 var carouselwidth; var carouselheight; //初始时滚动条的位置 var scrollY; var scrollX; //轮播scroll的宽度和高度 var scrollwidth; var scrollheight; //总幻灯片个数,不包含过渡幻灯片 var slidercount; //能够完整显示的幻灯片的数量 var slidercountinview; //每次滑动的个数 var step = step; //当前正在显示的幻灯片在滚动的子元素里的索引 var currentindex = 0; /* * 根据方向和索引获取相对于carouselscroll的偏移量 * @param index int carouselscroll中子元素索引 * @param direction string 方向,可选,默认为x */ function get_offset(){ if(arguments.length == 1){ var index = arguments[0]; direction = direction; }else if(arguments.length == 2){ var index = arguments[0]; direction = arguments[1]; }else{ return false; } var carousel = carouselscroll.children; if(index > carousel.length || index < 0) return false; var slider = carousel[index]; var rect = slider.getBoundingClientRect(); if(direction == 'x') return rect.left - carouselleft - (scrollX - w.scrollX); else return rect.top - carouseltop - (scrollY - w.scrollY); } /* * 获取视野内可显示的完整幻灯片数量 * @return int */ function get_slider_count_in_view(){ var containernum = ( direction === 'x' ) ? carouselwidth : carouselheight; var count = carouselscroll.children.length; for(var i in carouselscroll.children){ var slider = carouselscroll.children[i]; var rect = slider.getBoundingClientRect(); var num = ( direction == 'x' ) ? rect.right - carouselleft - (scrollX - w.scrollX) : rect.bottom - carouseltop - (scrollY - w.scrollY); if(num > containernum){ return parseInt(i); } } return count; } /* * 判断scroll容器是否被填满 * 通过最后一个元素 */ function is_filled(){ var sliders = carouselscroll.children; var slidercount = sliders.length; if(slidercount <= 1) return false; var lastitem = sliders[slidercount - 1]; var rect = lastitem.getBoundingClientRect(); if(direction == 'x') return rect.right - carouselleft >= carouselwidth; else return rect.bottom - carouseltop >= carouselheight; } /* * 根据索引和时间移动carouselscroll * @param index int carouselscroll中子元素索引 * @param duration int 移动时间 毫秒 * @param direction string 方向,可选,默认为x * 把carouselscroll移动到指定的位置 */ function move(){ if(arguments.length == 2){ var index = arguments[0]; var duration = arguments[1]; direction = direction; }else if(arguments.length == 3){ var index = arguments[0]; var duration = arguments[1]; direction = arguments[2]; }else{ return false; } var offset = get_offset(index); var transdis = parseFloat(carouselscroll.getAttribute('data-translate')) - offset; carouselscroll.style.transitionDuration = parseFloat(duration/1000) + 's'; carouselscroll.style.transitionDelay = '0s'; if(direction == 'x') carouselscroll.style.transform = 'translateX('+transdis+'px)'; else carouselscroll.style.transform = 'translateY('+transdis+'px)'; carouselscroll.setAttribute('data-translate', transdis); currentindex = index; } /* * 初始化数据 * 此函数在onload之后或resize时执行 * 用于初始化并生成相关数据,是系统的入口函数 */ function __init(){ //初始化滚动条位置 scrollY = w.scrollY; scrollX = w.scrollX; //给滚动元素嵌套一层父元素 if(!carouselwrap){ carouselwrap = document.createElement('div'); carouselwrap.className = 'carousel-wrap'; carouselscroll.parentNode.insertBefore(carouselwrap, carouselscroll); carouselwrap.appendChild(carouselscroll); } //获取轮播对象相关数据 var rect = carouselscroll.getBoundingClientRect(); carouselleft = rect.left; carouselright = rect.right; carouseltop = rect.top; carouselbottom = rect.bottom; carouselwidth = rect.width; carouselheight = rect.height; //给遮罩层添加高度和宽度数据 carouselscroll.parentNode.style.width = carouselwidth + 'px'; carouselscroll.parentNode.style.height = carouselheight + 'px'; //删除空白文本对象,以保证inline-block不会出现空白 carouselscroll.childNodes.forEach(function(node,i){ if(node.nodeType !== 1){ carouselscroll.removeChild(node); } }); //scroll容器必须被填满,否则不应有滑动功能 if(!is_filled()){ eligible = false; return false; } //保存原始幻灯片个数 slidercount = carouselscroll.children.length; //计算视野中显示的完整幻灯片个数 slidercountinview = get_slider_count_in_view(); //计算每次滑动的元素个数 if(step === 'auto') step = slidercountinview; else step = Math.min(step, slidercountinview); /* * 下面开始根据相关数据操作DOM */ //激活下一页按钮 enable_page_button(nextbutton); //默认状态下容器偏移量为0 carouselscroll.setAttribute('data-translate', 0); /* * 当需要进行LOOP时,则需要动态向前后插入幻灯片 * 为了保证无缝滚动,需要往前后插入视野中能够显示幻灯片的数量 * 系统只支持左对齐,所以需要往头部插入step个过渡幻灯片,往尾部插入slidercountinview+1个幻灯片 */ var positionoffset = 0; if(loop & currentindex === 0){ //获取原始幻灯片数据 var origin_sliders = carouselscroll.cloneNode(true).children; //先往往尾部需要插入的元素,减小效果抖动 for(var i = 0; i <= slidercountinview; i++){ var clone = origin_sliders[i].cloneNode(true); carouselscroll.appendChild(clone); } //再往头部插入的元素,并设置位移属性 for(var i = slidercount - 1; i >= slidercount - step; i--){ var slider = origin_sliders[i]; var clone = slider.cloneNode(true); carouselscroll.insertBefore(clone, carouselscroll.children[0]); } //设置看到默认为第一个幻灯片 var positionoffset = get_offset(step); if(direction === 'x'){ carouselscroll.style.left = - positionoffset + 'px'; }else{ carouselscroll.style.top = - positionoffset + 'px'; } currentindex = step; //上一页按钮可点击 enable_page_button(previousbutton); } //给所有幻灯片设置宽度和高 //并给视野中完整的幻灯片设置class var min = loop ? step : 0; var max = loop ? slidercountinview+step : slidercountinview; var order = 1; carouselscroll.childNodes.forEach(function(node, i){ if(node.nodeType === 1){ node.style.width = node.offsetWidth + 'px'; node.style.height = node.offsetHeight + 'px'; } if( i >= min && i < max){ node.classList.add(carouselscrollactiveclass); node.setAttribute('data-order', order); order++; } }); //通过最后一个元素计算scroll的高度和宽度并 //给scroll添加高度和宽度属性 var lastsliderrect = carouselscroll.lastElementChild.getBoundingClientRect(); if(direction === 'x'){ scrollwidth = lastsliderrect.right - carouselleft + positionoffset; scrollheight = carouselheight; }else{ scrollwidth = carouselwidth; scrollheight = lastsliderrect.bottom - carouseltop + positionoffset; } carouselscroll.style.width = scrollwidth + 'px'; carouselscroll.style.height = scrollheight + 'px'; //添加需要的指示器 if(indicator){ var count = Math.ceil(slidercount/step); indicator.innerHTML='<span></span>'.repeat(count); carousel_indicator(currentindex); } }; /* * 滑动的核心方法 * @param index 幻灯片相对caarouselscroll的索引 * 同时实现无缝循环和不循环两种效果 */ function slide(index){ if(in_transition){ return false; } in_transition = true; /* * 若loop, 则无缝过渡,在动画之前,需要根据当前位置,调整起始位置 * 如果当前位置已显示了过渡幻灯片,并 * **往前滚动:先跳转到尾部对应位置,然后往前滚动 * **往后滚动:先跳转到头部位置,然后往前滚动 */ if(loop){ /* * 如果当前位置偏移量小于step,则代表至少有一个过渡幻灯片在展示,此时位于头部 * 并且要移动的位置索引小于当前位置索引,则代表是从大往小移动 * 先跳转到尾部 */ if(currentindex < step && index < currentindex){ move(currentindex + slidercount, 0); index = index + slidercount; } /* 如果当前查看的最后一个幻灯片索引大于非过渡最后一个幻灯片的索引,代表此时位于尾部,至少一个过渡幻灯片已被展示 * 并且要移动的位置索引大于当前位置索引,则代表从小往大移动 * 先跳转到头部 */ else if(index > currentindex && currentindex + step - 1 > slidercount + step - 1){ move(currentindex - slidercount, 0); index = index - slidercount; } } /* * 若非loop, 则动画最多只能到头部或者尾部 */ else{ if(index < 0) index = 0; else if(index >= slidercount - slidercountinview) index = slidercount - slidercountinview; } //显示指示器 if(indicator) carousel_indicator(index); //以动画方式移动元素 move(index, duration); //同时: 在动画结束之后还原状态 setTimeout(function(){ if(!loop && currentindex >= slidercount - slidercountinview){ disable_page_button(nextbutton); } //如果不loop,到头部,则不能网上翻页 else if(!loop && currentindex == 0){ disable_page_button(previousbutton); } //正常不loop激活2个按钮 else if(!loop){ enable_page_button(nextbutton); enable_page_button(previousbutton); } //给正在展示的幻灯片增加一个class便于控制样式 var order = 1; carouselscroll.childNodes.forEach(function(c, i){ if(i >= index && i < index + slidercountinview){ c.classList.add(carouselscrollactiveclass); c.setAttribute('data-order', order); order++; }else{ c.classList.remove(carouselscrollactiveclass); c.removeAttribute('data-order'); } }); in_transition = false; }, duration); } /* * 显示指示器,对正在显示的高亮显示 * @param index int 当前查看的幻灯片索引 * @return null */ function carousel_indicator(index){ var indicators = indicator.querySelectorAll('span'); var indicatorcount = indicators.length; var remainder = slidercount % step; //求没有loop情况下的index if(loop){ if(index < step) index = index + slidercount - step; else if(index > slidercount + step) index = index - slidercount + step; else index = index - step; index = Math.ceil(index/step) % indicatorcount; }else{ index = Math.ceil(index/step); } indicator.querySelectorAll('span').forEach(function(c,i){ if(i == index) c.classList.add(activeclass); else c.classList.remove(activeclass); }); } /* * 根据参数激活前或后翻页按钮 * @param button string next|previous按钮 */ function enable_page_button(button){ if((button == 'next' || button == nextbutton) && nextbutton){ nextbutton.setAttribute('aria-disabled', 'false'); } else if((button == 'previous' || button == previousbutton) && previousbutton){ previousbutton.setAttribute('aria-disabled', 'false'); } } /* * 根据参数冻结前或后翻页按钮 * @param button string next|previous按钮 */ function disable_page_button(button){ if((button == 'next' || button == nextbutton) && nextbutton){ nextbutton.setAttribute('aria-disabled', 'true'); } else if((button == 'previous' || button == previousbutton) && previousbutton){ previousbutton.setAttribute('aria-disabled', 'true'); } } /* * 判断当前是否可以滑动 * @return boolean */ function disabled(){ return in_transition && eligible; } /* * 以下为对外暴露的接口 */ //自动滑动 this.autoplay = function(delay){ autoplayid = setInterval(function(){ slide(currentindex + step); }, delay); } //停止动画 this.stop = function(){ clearInterval(autoplayid); } /* * 以下为立即执行代码 * 初始化与事件绑定 */ //绑定下一页和上一页点击事件 if(nextbutton){ //下一页按钮默认冻结 nextbutton.setAttribute('aria-disabled', 'true'); nextbutton.addEventListener('click', function(e){ _this.stop(); if(disabled() || nextbutton.getAttribute('aria-disabled') == 'true') return false; slide(currentindex + step); }); } if(previousbutton){ //上一页按钮默认冻结 previousbutton.setAttribute('aria-disabled', 'true'); previousbutton.addEventListener('click', function(e){ _this.stop(); if(disabled() || previousbutton.getAttribute('aria-disabled') == 'true') return false; slide(currentindex - step); }); } //手动点击指示器事件 if(indicator){ indicator.addEventListener('click', function(e){ _this.stop(); var target = e.target || window.event.srcElement; if(disabled() || target.nodeName != 'SPAN') return false; var index = (Array.from(indicator.children).indexOf(target)); if(loop){ index = index * step + step; }else{ index = index * step; } slide(index); }); } /* * 拖拽功能 * 需要几组变量存放数据以获得拖拽距离 * initpageX,initpageY存放touchstart时的位置 * pageX,pageY存放touchmove时的位置 */ var initpageX = 0; var initpageY = 0; var pageX = 0; var pageY = 0; //绑定拖拽事件 carouselscroll.addEventListener('touchstart', function(ev){ _this.stop(); initpageX = ev.targetTouches[0].pageX; initpageY = ev.targetTouches[0].pageY; pageX = initpageX; pageY = initpageY; if(direction == 'x'){ carouselwrap.style.touchAction = 'pan-x'; }else{ carouselwrap.style.touchAction = 'pan-y'; } }, {passive: true}); carouselscroll.addEventListener('touchmove', function(ev){ var x = ev.targetTouches[0].pageX; var y = ev.targetTouches[0].pageY; var translate = parseFloat(carouselscroll.getAttribute('data-translate')); carouselscroll.style.transitionDuration = '0s'; carouselscroll.style.transitionDelay = '0s'; if(direction == 'x'){ var movedis = x - pageX; var transdis = translate + movedis; carouselscroll.style.transform = 'translateX('+transdis+'px)'; carouselscroll.setAttribute('data-translate', transdis); }else{ var movedis = y - pageY; var transdis = translate + movedis; carouselscroll.style.transform = 'translateY('+transdis+'px)'; carouselscroll.setAttribute('data-translate', transdis); } pageX = x; pageY = y; }, {passive: true}); carouselscroll.addEventListener('touchend', function(ev){ var x = ev.changedTouches[0].pageX; var y = ev.changedTouches[0].pageY; var basedis = get_offset(step) - get_offset(0); if(direction == 'x'){ var movedis = x - initpageX; }else{ var movedis = y - initpageY; } if(movedis < -basedis/3) slide(currentindex + step); else if(movedis > basedis/3) slide(currentindex - step); else slide(currentindex); carouselwrap.style.touchAction = 'none'; }, {passive: true}); /* * 鼠标滚动控制滑动 */ if(mousewheel){ var sliderslength = carouselscroll.children.length; carouselscroll.addEventListener('wheel', function(ev){ _this.stop(); if(event.deltaY > 0){ if(!loop && currentindex == sliderslength - 1 && !disabled()) return false; if(!disabled()){ slide(currentindex + step); } }else if(event.deltaY < 0){ if(!loop && currentindex == 0 && !disabled()) return false; if(!disabled()){ slide(currentindex - step); } } ev.preventDefault(); ev.stopPropagation(); }, {passive: false}); } //初始化 __init(); } //创建Style var nestedstyle = w.document.createElement('style'); nestedstyle.setAttribute('carousel-extension', version); nestedstyle.innerHTML='.carousel-container{position:relative}.carousel-wrap{position:relative;max-width:100%;max-height:100%;overflow:hidden}.carousel-scroll{position:absolute;display:block;width:100%;height:auto;transition-property:transform;transition-timing-function:ease-in-out}.carousel-scroll>*{box-sizing:border-box}.carousel-scroll-x{white-space:nowrap}.carousel-scroll-x>*{display:inline-block;vertical-align:bottom;white-space:initial}.carousel-scroll-y>*{display:block}.carousel-previousbutton[aria-disabled=true],.carousel-nextbutton[aria-disabled=true]{visibility:hidden}'; w.document.head.append(nestedstyle); })(window);
9452d1d324831b07912b6e41ad41b1a3f79da23d
[ "Markdown", "JavaScript" ]
2
Markdown
Yasin92X/carousel.js
681286643e6005f7caa2dbbc14ff25a45c666f02
d6e3266db70db9f8b30dbd5e8ad9772a26fb4f6b
refs/heads/master
<file_sep>/** * Created by Алексей on 09.07.2017. */ import React, {Component} from 'react' import Order from './Order' import Crm from './Crm' import './main.css' class Content extends Component { render() { return <section> <Order /> </section> } } Content.defaultProps = { activeTab: "Order" }; export default Content<file_sep>/** * Created by Алексей on 09.07.2017. */ import {createStore, applyMiddleware} from 'redux' import reducers from './reducers' let createStoreWithMiddleware; if(process.env.NODE_ENV !== 'production'){ const {logger} = require('redux-logger'); createStoreWithMiddleware = applyMiddleware( // logger )(createStore); } else { createStoreWithMiddleware = applyMiddleware( )(createStore); } const store = createStoreWithMiddleware(reducers,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); export default store<file_sep>/** * Created by Алексей on 10.07.2017. */ export const locale = { en:{ dashboard: 'dashboard', order: 'order' }, ru:{ dashboard: 'личный кабинет', order: 'заказ' } };<file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import Carousel from 'nuka-carousel' import {sliderDecorators} from './ControlButton' import {locale} from './locale' import './main.css' class Navigation extends Component { render() { const {itemSelectMenuIsOpen, items, activeValue, lang} = this.props; const sliderParams = { slidesToShow: itemSelectMenuIsOpen ? 4 : 6, }; return <section styleName="wrap"> <div styleName="slider"> <Carousel {...sliderParams} decorators={sliderDecorators}> {items.map((item,index)=> { return <div onClick={()=>{ this.props.setActiveItem(items.find( (elem)=>elem.name === item.name )) }} styleName={`item${activeValue === item.name ?' active':''}`} key={index}> {locale[lang][item.name] ? locale[lang][item.name] : item.name} </div> } )} </Carousel> </div> </section> } } Navigation.defaultProps = { items: [], activeItem: {}, itemSelectMenuIsOpen: true, lang: 'en' }; export default Navigation<file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import {connect} from 'react-redux' import _ from 'lodash' import {actions} from 'Root/actions' import ItemSelect from './ItemSelect' import ItemSettings from './ItemSettings' // import items from 'Root/constants/items.json' import items from 'Static/images/logos/res.json' import parameterDependencies from 'Root/constants/parametrsDependencies.json' import './main.css' function getInitialItemOrder(itemStructure){ const {subChoice, parameters} = itemStructure; const res = []; if (parameters){ res.push({name: itemStructure.name, value: parameters[0]}); } if(subChoice) { subChoice.forEach((e)=>{ res.push(getInitialItemOrder(e)); }) } return _.uniqBy(_.flattenDeep(res), e=>e.name); } class Constructor extends Component { componentWillMount(){ // TODO refactor forEach fetch(items).then(res=>res.json()).then((res)=>{ this.props.initOrderStructure(res); const a =[]; res.forEach(e=>{ a.push({ name: e.name, parameters: getInitialItemOrder(e) }); }); this.props.setOrder(a); }); fetch(parameterDependencies).then(r=>r.json()).then(r=>{ this.props.setParametersDependencies(r); }) } render(){ return <section styleName="common" style={{zIndex: 10}}> {this.props.sideMenuIsOpen ? null : <ItemSelect/>} <ItemSettings/> </section> } } const mapStateToProps = (state)=>({sideMenuIsOpen: state.sideMenu.isOpen}); export default connect(mapStateToProps,{...actions})(Constructor);<file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import {connect} from 'react-redux' import {locale} from './locale' import './main.css' class LeftMenu extends Component { render(){ const {sideMenuIsOpen, lang} = this.props; return <section styleName="common" > <a styleName="order__button"><p>{locale[lang].order}</p></a> {sideMenuIsOpen ? null : process.env.projectName === "admin" ? <p styleName="dashboard bold">{locale[lang].dashboard}</p> : null } <p styleName="bold">ed {this.props.ed}</p> </section> } } LeftMenu.defaultProps = { ed: "18.08.2017" }; const mapStateToProps = (state)=>({ sideMenuIsOpen: state.sideMenu.isOpen, lang: state.language.lang }); export default connect(mapStateToProps)(LeftMenu);<file_sep>/** * Created by Алексей on 07.07.2017. */ import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux' import store from './store' import './main.css' import Main from './Components/Main' ReactDOM.render( <Provider store={store}> <Main /> </Provider>, document.getElementById("root") );<file_sep>/** * Created by Алексей on 11.07.2017. */ import React, {Component} from 'react' import ReactDOM from 'react-dom' import {connect} from 'react-redux' // import {toggleItemsSelectMenu, toggleIsOpenAfterAnimation} from 'Root/actions' import {actions} from 'Root/actions' import arrow from './images/arrow.png' import './main.css' class HideButton extends Component { render() { return <button onClick={this.props.toggleItemsSelectMenu} styleName="select__visibility-button"> <img className="sss" styleName={`${this.props.menuOpen ? 'menu-opened' : ''}`} src={arrow} alt="arrow"/> </button> } } HideButton.defaultProps = {}; const mapState = (state)=>({ menuOpen: state.Constructor.itemSelectMenu.isOpen }); export default connect(mapState, {...actions})(HideButton)<file_sep>/** * Created by Алексей on 09.07.2017. */ import {combineReducers} from 'redux' import sideMenu from './SideMenu' import language from './Language' import Constructor from './Constructor' import order from './order' import orderStructure from './orderStructure' import parametersDependencies from './parametersDependencies' export default combineReducers({ sideMenu, language, Constructor, order, orderStructure, parametersDependencies })<file_sep>/** * Created by Алексей on 09.07.2017. */ export const locale = { en: { show: "show", hide: "hide", add: "add", remove: "delete" }, ru:{ show: "показать", hide: "спрятать", add: "добавить", remove: "удалить" } };<file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import ReactDOM from 'react-dom' import {connect} from 'react-redux' import {actions} from 'Root/actions' import Mtm from './Content/Mtm' import Rtw from './Content/Rtw' import './main.css' import HideButton from "./HideButton/index"; class Item extends Component{ render(){ const {name, active, onClick} = this.props; return <button style={{color: name===active ? "#8f7548": null}} styleName={`constructor__choice`} onClick={()=>{ onClick(name)} } >{name}</button> } } class ItemSelect extends Component { constructor(props){ super(props); this.state = { activeTab: "mtm", }; this.changeActive = this.changeActive.bind(this); }; componentDidMount(){ // TODO replace to the select menu component ReactDOM.findDOMNode(this).addEventListener("transitionend",(e)=>{ e.stopImmediatePropagation(); if (e.target.parentNode === ReactDOM.findDOMNode(this)){ this.props.toggleIsOpenAfterAnimation(); } }); } changeActive(active){ this.setState({ activeTab: active }); }; render(){ const {isOpen} = this.props; return <section styleName="common"> <HideButton /> <section styleName={`hiding ${isOpen ? '' : 'closed'}`}> <section styleName={`settings__block_wrap`}> <section styleName="constructor__choice-wrap"> <Item name="mtm" active={this.state.activeTab} onClick={this.changeActive}/> <Item name="rtw" active={this.state.activeTab} onClick={this.changeActive} /> </section> <section> {this.state.activeTab === "mtm" ? <Mtm /> : <Rtw /> } </section> </section> </section> </section> } } const mapStateToProps = (state)=>({ isOpen: state.Constructor.itemSelectMenu.isOpen, }); export default connect(mapStateToProps, {...actions})(ItemSelect);<file_sep>/** * Created by Алексей on 18.07.2017. */ import * as actions from '../constants/ActionTypes' // ItemSelectMenu export const toggleItemsSelectMenu = () => ({ type: actions.TOGGLE_ITEMS_SELECT_MENU }); export const toggleIsOpenAfterAnimation = ()=>({ type: actions.TOGGLE_AFTER_ANIMATION }); export const closeItemsSelectMenu = () => ({ type: actions.CLOSE_ITEMS_SELECT_MENU }); export const setActiveItem = (item) => ({ type: actions.SET_ACTIVE_ITEM, item }); export const setActiveItemParameter=(param) =>({ type: actions.SET_ACTIVE_ITEM_PARAMETER, param }); export const setParametersDependencies = (deps)=>({ type: actions.SET_PARAMETERS_DEPENDENCIES, deps });<file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import {connect} from 'react-redux' import MaterialView from './MaterialView' import OrderControls from './OrderControls/index' import './main.css' class ItemSettings extends Component { render(){ return <section styleName="wrap"> <MaterialView/> <OrderControls/> </section> } } export default ItemSettings<file_sep>/** * Created by Алексей on 07.07.2017. */ import React,{Component} from 'react' import logoImg from "./logo.png" import MenuToggler from './MenuToggler' import LeftMenu from './LeftMenu' import RightMenu from './RightMenu' import './main.css' const Logo = ()=> <div styleName="logo__block_wrap order-first"> <img src={logoImg} alt="Логотип"/> </div>; class Header extends Component { render(){ return <header styleName="common"> <MenuToggler /> <LeftMenu /> <Logo /> <RightMenu /> </header> } } export default Header; <file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import {connect} from 'react-redux' import {actions} from 'Root/actions' import {languages} from 'Root/constants/languages' import {locale} from './locale' import './main.css' import loginImg from './images/login.png' import downArrow from './images/down.png' class RightMenu extends Component { render(){ const {cost, locale, lang, changeLanguage } = this.props; return <section styleName="bold common order-third"> <p styleName="cost">{cost}{locale[lang].money}</p> <a styleName="account"><img src={loginImg} alt="login"/></a> <LanguageChoice changeLanguage={changeLanguage}/> </section> } } class LanguageChoice extends Component { constructor(props){ super(props); this.state = { langChoiceOpen: false } } render(){ const {langChoiceOpen} = this.state; const {changeLanguage} = this.props; return <section styleName="choice-wrap"> <button onClick={(()=>{this.setState({langChoiceOpen: !langChoiceOpen})}).bind(this)} styleName="language"> <p>language</p> <img src={downArrow} alt="arrow"/> </button> <LanguageList open={langChoiceOpen} changeLanguage={changeLanguage} /> </section> } } class LanguageList extends Component { render(){ const {languages, open, changeLanguage} = this.props; return <ul styleName={`languageList-wrap ${open ? 'open' : ''}`}> {languages.map((lang, key)=> <li styleName="language__list-item" onClick={()=>{changeLanguage(lang.value)}} key={key}>{lang.text}</li>)} </ul> } } LanguageList.defaultProps = { languages: languages }; RightMenu.defaultProps = { cost: 0, locale }; const mapStateToProps = (state)=>({lang: state.language.lang}); //TODO wtf? Y cant i mapDispatchToProps ??? // connect(()=>{},{changeLanguage})(LanguageList); export default connect(mapStateToProps, {...actions})(RightMenu)<file_sep>/** * Created by Алексей on 09.07.2017. */ import React, {Component} from 'react' import './main.css' const items = [ 'order', 'call', 'email', 'crm', 'settings' ]; class Navigation extends Component { render() { return <nav styleName="navigation-wrap"> {items.map((item,index)=>{ const img = require(`./images/${item}.png`); return <a onClick={(e)=>{}} styleName="navigation__link-item" key={index}> <img styleName="navigation__link-image" src={`${img}`} alt={`${item}`}/> </a> } )} </nav> } } Navigation.defaultProps = {}; export default Navigation<file_sep>/** * Created by Алексей on 07.07.2017. */ import React,{Component} from 'react' import Common from 'Common' import Preview from './Preview' import Constructor from "./Constructor"; import MobileInfo from './MobileInfo' import './main.css' import struct from 'Static/images/logos/res.json' class Main extends Component { render(){ return( <Common> <section styleName="common"> <Constructor /> <Preview/> <MobileInfo /> </section> </Common> ) }; } export default Main;<file_sep>/** * Created by Алексей on 08.07.2017. */ import React,{Component} from 'react' import Header from './Header' import SideMenu from './SideMenu' import './main.css' class Common extends Component { render(){ return <section styleName="common"> <SideMenu/> <section styleName="content-wrap"> <Header/> {this.props.children} </section> </section> } } export default Common<file_sep>/** * Created by Алексей on 20.07.2017. */ export const displayOrder = [ 'material', 'look', 'fason', 'silhouette', 'lapel', 'edges', 'furniture', 'pockets', 'front_pockets', 'back_pockets' ];<file_sep>/** * Created by Алексей on 08.07.2017. */ import React from 'react' const Rtw = ()=><div>Rtw section</div>; export default Rtw;<file_sep>/** * Created by Алексей on 14.07.2017. */ const testFolder = './type1/'; const fs = require('fs'); const files = []; fs.readdirSync(testFolder).forEach(file => { files.push( file.slice(0, file.indexOf(".png")) ); }); fs.writeFile(testFolder+"res.json", JSON.stringify(files) , function(err) { if(err) { return console.log(err); } console.log("The file was saved!"); }); // console.log(JSON.stringify(files));<file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import Display from './Display' import Footer from './Footer' import './main.css' class View extends Component { render() { return <section styleName="material__view-wrap"> <Display styleName="view" /> <Footer/> </section> } } View.defaultProps = {}; export default View<file_sep>/** * Created by Алексей on 19.07.2017. */ const fs = require('fs'); const path = require('path'); function getDirectories (srcpath) { return fs.readdirSync(srcpath) .filter(file => fs.lstatSync(path.join(srcpath, file)).isDirectory()) } function getFiles(srcpath) { return fs.readdirSync(srcpath) .filter(file => !fs.lstatSync(path.join(srcpath, file)).isDirectory()) } function makeObjectByFolderFullName(folderFullName, name){ const subFolders = getDirectories(folderFullName), files = getFiles(folderFullName).map(e=> path.basename(e, '.png')), parameters = [], subChoice = []; if (subFolders.length <= files.length || !subFolders){ files.forEach(fileName => { parameters.push(fileName) }) } subFolders.forEach((folder)=>{ subChoice.push( makeObjectByFolderFullName(path.resolve(folderFullName, folder), folder) ) }); return Object.assign({}, {name}, parameters.length > 0 ? {parameters} : null, subChoice.length > 0 ? {subChoice} : null ); } const items = []; getDirectories(path.resolve(__dirname)) .forEach(dir => items.push( makeObjectByFolderFullName(path.resolve(__dirname, dir), dir) )); fs.writeFile(path.resolve(__dirname, "res.json"), JSON.stringify(items) , function(err) { if(err) { return console.log(err); } console.log("The file was saved!"); });<file_sep>/** * Created by Алексей on 16.07.2017. */ import React from 'react' import prevArrow from'./images/prevArrow.png' import nextArrow from'./images/nextArrow.png' const imgStyle = { height: "1.5rem", paddingLeft: 20, paddingRight: 20, cursor: "pointer" }; export const ControlNextSlide = React.createClass({ render() { const {currentSlide, slideCount, slidesToShow} = this.props; return slideCount > currentSlide+slidesToShow ? <img src={ nextArrow } style={imgStyle} onClick={this.props.nextSlide}/> : null } }); // TODO it renders a million times per item click. wtf ??? export const ControlPrevSlide = React.createClass({ render() { const {currentSlide, slideCount, slidesToShow} = this.props; return slideCount > currentSlide+slidesToShow-1 && currentSlide > 0 ? <img src={ prevArrow } style={imgStyle} onClick={this.props.previousSlide}/> : null } }); export const sliderDecorators = [ { component: ControlPrevSlide, position: 'CenterLeft', style: { height: "100%" } }, { component:ControlNextSlide, position: 'CenterRight', style: { height: "100%" } } ];<file_sep>/** * Created by chep on 19.07.17. */ import { INIT_ORDER_STRUCTURE } from '../constants/ActionTypes' const initialState = []; const orderStructure = (state = initialState, action)=>{ switch (action.type){ case INIT_ORDER_STRUCTURE: return action.structure; default: return state; } }; export default orderStructure<file_sep>/** * Created by Алексей on 14.07.2017. */ export const locale = { en: { jacket: 'jacket', shirt: 'shirt', trousers: 'trousers', coat: 'coat', waistcoat: 'waistcoat', accessories: 'accessories' }, ru: { jacket: 'пиджак', shirt: 'рубашка', trousers: 'брюки', coat: 'пальто', waistcoat: 'жилет', accessories: 'аксессуары' } };<file_sep>/** * Created by Алексей on 09.07.2017. */ import React, {Component} from 'react' import './main.css' class Crm extends Component { render() { return <section>crm content</section> } } Crm.defaultProps = {}; export default Crm<file_sep>/** * Created by Алексей on 18.07.2017. */ import * as actions from '../constants/ActionTypes' // Side Menu export const openSideMenu =()=>({ type: actions.OPEN_SIDE_MENU }); export const closeSideMenu =()=>({ type: actions.CLOSE_SIDE_MENU }); <file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import {connect} from 'react-redux' import {actions} from 'Root/actions' import _ from 'lodash' import Navigation from '../../Navigation' import {displayOrder} from 'Root/constants/ItemOptionsDisplayOrder' import '../main.css' class Footer extends Component { render() { const {activeItem, structure, itemSelectMenuIsOpen, setActiveItemParameter} = this.props; const {pathesToShow} = this; if (!pathesToShow || pathesToShow.length===0) { this.pathesToShow = structure.map( e =>({ name: e.name, parameters: getPathByStructureObject(e), }) ) } const index = _.findIndex(pathesToShow, e => e.name === activeItem.name), parameters = this.pathesToShow.length>0 ? this.pathesToShow[index > -1 ? index : 0].parameters : []; return <Navigation {...{ items: [...parameters], lang: 'en', activeValue: activeItem.parameter, itemSelectMenuIsOpen, setActiveItem: setActiveItemParameter }}/>; } } Footer.defaultProps = { activeItem: {}, structure: [] }; const mapStateToProps = state => ({ activeItem: state.Constructor.activeItem, structure: state.orderStructure, itemSelectMenuIsOpen: state.Constructor.itemSelectMenu.isOpen, lang: state.language.lang }); export default connect(mapStateToProps, {...actions})(Footer) function flattStructureObject(structureObject={}){ return _.flatten([ structureObject.parameters ? [{ name: structureObject.name, text: '' }] : [], ...structureObject.subChoice ? structureObject.subChoice.map(item => flattStructureObject(item) ) :[] ]) } function getPathByStructureObject(object){ return sortByOrderArray(_.uniqBy(flattStructureObject(object), o=>o.name), displayOrder) } function sortByOrderArray(target=[],orderArray=displayOrder){ return target.sort( (a,b) => orderArray.indexOf(a.name) >= orderArray.indexOf(b.name) ? 1 : -1 ) }<file_sep>/** * Created by Алексей on 17.07.2017. */ import { ADD_ITEM, REMOVE_ITEM, SET_ACTIVE_ITEM, SET_ORDER, SET_ITEM_PARAMETER_VALUE } from '../constants/ActionTypes' const initialState = []; const order = (state = initialState, action)=>{ switch (action.type){ case ADD_ITEM: return addItem(state, action.item); case REMOVE_ITEM: return state.filter((elem)=>!(elem.name === action.item.name)); case SET_ACTIVE_ITEM: return addItem(state, action.item); case SET_ORDER: return action.order; case SET_ITEM_PARAMETER_VALUE: return { ...state }; default: return state; } }; const addItem = (items, item)=>{ return items.find((elem)=>elem.name === item.name) ? items : [...items, item] }; export default order<file_sep>/** * Created by Алексей on 14.07.2017. */ // TODO admin connection add export const items = [ {name:'jacket', type: 1}, {name:'shirt', type: 2}, {name:'trousers', type: 1}, {name:'coat', type: 1}, {name:'waistcoat', type: 1}, {name:'accessories', type: 2}, ];<file_sep>/** * Created by Алексей on 15.07.2017. */ import React, {Component} from 'react' import './main.css' class MaterialItem extends Component { render() { const {path, type, itemName} = this.props; return <img src={`${path}/${itemName}.png`} styleName="material__item" alt=""/> } } MaterialItem.defaultProps = { type: 1, itemName: '', path: '/' }; export default MaterialItem<file_sep>/** * Created by Алексей on 09.07.2017. */ import React, {Component} from 'react' import Mtm from './Mtm' import Rtw from './Rtw' import './main.css' class ModeSwitcher extends Component { render() { const {_this, tabs} = this.props; return <section styleName="order__modeSwitcher_wrap"> {tabs.map((tab, index)=> <ModeItem _this={_this} tab={tab} key={index}/> )} </section> } } ModeSwitcher.defaultProps = { tabs: [] }; class ModeItem extends Component { render(){ const {_this, tab} = this.props; return <button styleName={`order__modeSwitcher_item ${_this.state.activeTab.name === tab.tab.name ? 'active' : ''}`} onClick={()=>{_this.setState({activeTab: tab.tab})}} > {tab.name}</button> } } class Order extends Component { constructor(props){ super(props); this.state={ activeTab: Mtm } } render() { return <section styleName="sideMenu__order-section"> <ModeSwitcher _this={this} tabs={[{name: 'mtm', tab: Mtm}, {name: 'rtw', tab: Rtw}]}/> {React.createElement(this.state.activeTab)} </section> } } Order.defaultProps = {}; export default Order<file_sep>{ "name": "clothes", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server", "learn": "webpack", "prod": "cross-env NODE_ENV=production webpack -p" }, "repository": { "type": "git", "url": "git+https://github.com/AlekseyChepurko/Clothes.git" }, "author": "<NAME>", "license": "ISC", "bugs": { "url": "https://github.com/AlekseyChepurko/Clothes/issues" }, "homepage": "https://github.com/AlekseyChepurko/Clothes#readme", "devDependencies": { "babel-core": "^6.25.0", "babel-loader": "^7.0.0", "babel-plugin-transform-object-rest-spread": "^6.23.0", "babel-plugin-transform-react-jsx": "^6.24.1", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "chunk-manifest-webpack-plugin": "^1.1.0", "copy-webpack-plugin": "^4.0.1", "cross-env": "^5.0.1", "css-loader": "^0.28.4", "extract-text-webpack-plugin": "^2.1.2", "file-loader": "^0.11.2", "html-loader": "^0.4.5", "html-webpack-plugin": "^2.28.0", "image-webpack-loader": "^3.3.1", "node-sass": "^4.5.3", "postcss-font-magician": "^2.0.0", "postcss-loader": "^2.0.6", "postcss-media-minmax": "^3.0.0", "postcss-nested": "^2.0.2", "react-inlinesvg": "^0.6.0", "redux-logger": "^3.0.6", "sass-loader": "^6.0.5", "style-loader": "^0.18.2", "url-loader": "^0.5.9", "webpack": "^2.6.1", "webpack-bundle-analyzer": "^2.8.2", "webpack-chunk-hash": "^0.4.0", "webpack-cleanup-plugin": "^0.5.1", "webpack-dev-server": "^2.4.5" }, "dependencies": { "babel-plugin-react-css-modules": "^3.0.1", "expect": "^1.20.2", "lodash": "^4.17.4", "nuka-carousel": "^2.0.4", "react": "^15.5.4", "react-dom": "^15.5.4", "react-lazy-load": "^3.0.12", "react-redux": "^5.0.5", "redux": "^3.7.1" } } <file_sep>/** * Created by Алексей on 09.07.2017. */ // SideMenu export const OPEN_SIDE_MENU = 'OPEN_SIDE_MENU'; export const CLOSE_SIDE_MENU = 'CLOSE_SIDE_MENU'; // Language export const CHANGE_LANGUAGE = 'CHANGE_LANGUAGE'; // Select menu toggle export const TOGGLE_ITEMS_SELECT_MENU = 'TOGGLE_ITEMS_SELECT_MENU'; export const CLOSE_ITEMS_SELECT_MENU = 'CLOSE_ITEMS_SELECT_MENU'; // Item select export const SET_ACTIVE_ITEM = 'SET_ACTIVE_ITEM'; export const TOGGLE_AFTER_ANIMATION = 'TOGGLE_AFTER_ANIMATION'; export const SET_ACTIVE_ITEM_PARAMETER = 'SET_ACTIVE_ITEM_PARAMETER'; export const SET_PARAMETERS_DEPENDENCIES = 'SET_PARAMETERS_DEPENDENCIES'; // Order export const ADD_ITEM = 'ADD_ITEM'; export const REMOVE_ITEM = 'REMOVE_ITEM'; export const SET_ORDER = 'SET_ORDER'; export const INIT_ORDER_STRUCTURE = 'INIT_ORDER_STRUCTURE'; export const SET_ITEM_PARAMETER_VALUE = 'SET_ITEM_PARAMETER_VALUE';<file_sep>/** * Created by Алексей on 09.07.2017. */ import React, {Component} from 'react' import {connect} from 'react-redux' import DropdownMenu from 'Common/DropdownMenu' import {menu} from './MenuStructure' import './main.css' class Mtm extends Component { render() { return <DropdownMenu menu={menu[this.props.lang]} /> } } Mtm.defaultProps = { lang: 'en' }; export default connect((state)=>({lang: state.language.lang}))(Mtm)<file_sep>/** * Created by Алексей on 18.07.2017. */ import * as actions from '../constants/ActionTypes' // Order export const addItem = (item) => ({ type: actions.ADD_ITEM, item }); export const removeItem = (item) => ({ type: actions.REMOVE_ITEM, item }); export const setOrder=(order) => ({ type: actions.SET_ORDER, order }); export const initOrderStructure = structure => ({ type: actions.INIT_ORDER_STRUCTURE, structure }); export const setItemParameterValue = (payload)=>({ type: actions.SET_ITEM_PARAMETER_VALUE, payload });<file_sep># Clothes project <file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import {connect} from 'react-redux' import _ from 'lodash' import {items} from 'Root/constants/SelectItems' import {locale} from './locale' import {actions} from 'Root/actions' import './main.css' function getInitialItemOrder(itemStructure){ const {subChoice, parameters} = itemStructure; const res = []; if (parameters){ res.push({name: itemStructure.name, value: parameters[0]}); } if(subChoice) { subChoice.forEach((e)=>{ res.push(getInitialItemOrder(e)); }) } return _.uniqBy(_.flattenDeep(res), e=>e.name); } class Mtm extends Component { render(){ const { lang, setActiveItem, activeItem, chosenItems, addItem, orderStructure, removeItem} = this.props; return <ul styleName="common"> {items.map((item,index) => { return <Item onClick={setActiveItem} addItem={addItem} removeItem={removeItem} isActive={item.name === activeItem.name} isAdded={_.findIndex(chosenItems, e=>e.name===item.name ) !== -1} lang={lang} item={orderStructure.length===0 ? item : Object.assign({},{ parameters: getInitialItemOrder(orderStructure[_.findIndex(orderStructure, e=>e.name===item.name)]) }, item)} key={index}/> }) } </ul> } } class Item extends Component { constructor(props){ super(props); this.state={ hovered: false } } render(){ const { item, lang, isActive, isAdded, onClick, addItem, removeItem} = this.props; const image = require(`./items/${item.name}.png`), activeImage = require(`./items/${item.name}_picked.png`); return <li styleName={`mtm__item-wrap ${this.state.hovered ? "hovered" : ""} ${isActive ? "mtm__item-active" : ""}` } onClick={()=>{onClick(item)}} onMouseEnter={(()=>{this.setState({hovered: true})})} onMouseLeave={ (()=>{this.setState({hovered: false})})}> {/*TODO set visibility filter*/} <button className={`noOpacity`} styleName={`hiding top`}>{locale[lang].show}</button> <img src={isActive ? activeImage : image} styleName={`${item.name} item`}/> <AddAndRemoveButton className={`noOpacity`} item={item} onClick={isAdded ? removeItem : addItem} styleName={`hiding bottom`}> {locale[lang][`${isAdded ? "remove" : "add"}`]} </AddAndRemoveButton> </li> } } class AddAndRemoveButton extends Component{ render(){ const {item, onClick} = this.props; return <button onClick={(e)=>{e.stopPropagation(); onClick(item)}} className={`noOpacity`} styleName={`hiding bottom`}>{this.props.children}</button> } } const mapStateToProps = (state)=>({ lang: state.language.lang, activeItem: state.Constructor.activeItem, chosenItems: state.order, orderStructure: state.orderStructure }); export default connect(mapStateToProps, {...actions})(Mtm);<file_sep>/** * Created by Алексей on 08.07.2017. */ import React, {Component} from 'react' import {connect} from 'react-redux' import {locale} from './locale' import './main.css' class OrderControls extends Component { render() { return <section styleName="order__controls-wrap"> <button styleName="active order__controls-item">{locale.stylist[this.props.lang]}</button> <button styleName="order__controls-item">{locale.order[this.props.lang]}</button> </section> } } OrderControls.defaultProps = { lang: "en" }; const mapStateToProps = (state)=>({ lang: state.language.lang }); export default connect(mapStateToProps)(OrderControls)<file_sep>/** * Created by Алексей on 09.07.2017. */ import React, {Component} from 'react' import PropTypes from 'prop-types' import './main.css' class DropdownMenu extends Component { render(){ const {menu, isOpen} = this.props; return <ul styleName={`menu-wrap hiding ${isOpen ? 'open' : 'close'}`}> {menu.map((item, key)=> <MenuItem item={item} key={key} /> )} </ul> } } DropdownMenu.defaultProps = { menu: {}, isOpen: true }; DropdownMenu.propTypes = { menu: PropTypes.array, }; class MenuItem extends Component { constructor(props){ super(props); this.state = { isOpen: false }; this.toggleStatus = this.toggleStatus.bind(this); } toggleStatus(){ this.setState({isOpen: !this.state.isOpen}); } render(){ const {item} = this.props; return <li styleName="menu-item"> <div onClick={this.toggleStatus}>{item.text}</div> {item.subItem ? <DropdownMenu isOpen={this.state.isOpen} menu={item.subItem}/> : null } </li> } } MenuItem.defaultProps = { item: {text: ''} }; export default DropdownMenu <file_sep>/** * Created by Алексей on 14.07.2017. */ export const materials = { type1: { }, type2: {} };<file_sep>/** * Created by Алексей on 10.07.2017. */ export const locale ={ en: { money: "$", lang: 'language' }, ru: { money: '₽', lang: 'язык' } };
daef3be7bb69ba00e5f27cd9532250dd3b17445e
[ "JavaScript", "JSON", "Markdown" ]
43
JavaScript
AlekseyChepurko/Clothes
77f9629a7bb78c98442879c30518c0c6736f1122
27ab6ee67cb59aeffc0ff3b881ea4fb27f5fc8d3
refs/heads/master
<repo_name>mullfuchs/voteapp<file_sep>/seeders/seed.js module.exports = function(db) { db.vote.create({ mVote: 0, fVote: 0, }).success(function() { }); };<file_sep>/index.js var express = require('express'); var path = require('path'); var app = express(); var db = require("./models"); app.set('view engine', 'ejs'); app.use(express.static(path.join(__dirname, 'views'))); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', function(req, res) { db.vote.find({ where: {id: 0} }).then(function(voteOBJ) { res.render('index', {data: voteOBJ}); }); }); app.get('/voteMan', function(req, res){ db.vote.find({ where: {id: 0} }).then(function(voteOBJ){ var voteTotal = voteOBJ.mVote + 1; voteOBJ.updateAttributes({ mVote: voteTotal }).then(function(){ res.render('index', {data: voteOBJ}); }) }); }); app.get('/voteWoman', function(req, res){ db.vote.find({ where: {id: 0} }).then(function(voteOBJ){ var voteTotal = voteOBJ.fVote + 1; voteOBJ.updateAttributes({ fVote: voteTotal }).then(function(){ res.render('index', {data: voteOBJ}); }) }); }); app.listen(process.env.PORT || 3000);
85d6440cbaec7783b327510c102775c42c4dd77f
[ "JavaScript" ]
2
JavaScript
mullfuchs/voteapp
2586e7077ae8acb4a05fd8edc3744ec6f6d9a819
4959d5410790ad3a82eeebef690119ca35adf5fe
refs/heads/master
<repo_name>zhengsz123/travelBud<file_sep>/travelbudcore/src/main/resources/db/migration/V4.07__Delete_gasId_column.sql ALTER table station Drop column gas_id;<file_sep>/mvc/src/main/java/com/travel/mvc/config/SecurityConfig.java package com.travel.mvc.config; import com.travel.mvc.extend.security.MyAuthenticaitonEntrypoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyAuthenticaitonEntrypoint myAuthenticaitonEntrypoint; @Autowired private UserDetailsService userDetailsService; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ PasswordEncoder encoder = new BCryptPasswordEncoder(); auth.userDetailsService(userDetailsService).passwordEncoder(encoder); } protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().antMatchers("/api/users/login","/api/user/login","/api/user/signup","/api/users/signup", "/api/user/image","/api/users/image","/api/users/getImageInfo/{id}","/api/users/downloadImage/{id}","/api/user/email/{id}","/api/user/sms/{id}").permitAll() .and() .authorizeRequests().antMatchers("/api/**").hasAnyRole("REGISTERED_USER") .and() .authorizeRequests().antMatchers("/api/admin/**").hasAnyRole("ADMIN") .and() .exceptionHandling().authenticationEntryPoint(myAuthenticaitonEntrypoint) .and() .formLogin(); } @Bean(name = BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } <file_sep>/travelbudcore/src/main/resources/db/migration/V2.4__Add_gasType_tabel.sql DROP table gas; CREATE SEQUENCE gas_id_seq; create table gas ( id bigint not null DEFAULT NEXTVAL('gas_id_seq'), gas_type varchar(255) not NULL, primary key (id) ); ALTER SEQUENCE gas_id_seq OWNED BY gas.id; <file_sep>/travelbudcore/src/main/resources/db/migration/V2__Add_Usrname.sql ALTER TABLE users ADD COLUMN username varchar(255) NOT NULL;<file_sep>/travelbudcore/src/main/resources/db/migration/V3.09__Add_Image_Table.sql CREATE SEQUENCE image_id_seq; create table image ( id bigint not null DEFAULT NEXTVAL('image_id_seq'), url varchar(255) not NULL, primary key (id) ); ALTER SEQUENCE image_id_seq OWNED BY image.id;<file_sep>/travelbudcore/src/main/resources/db/migration/V4.01__Test.sql create table department ( dept_id integer not null, dept_name varchar(30) not null, dept_location varchar(30) not null, unique(dept_id) ); create table employee ( emp_id integer not null, emp_name varchar(50) not null, dept_id integer not null, salary integer not null, unique(emp_id) );<file_sep>/travelbudcore/src/main/java/com/travel/core/domain/Gas.java package com.travel.core.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.io.Serializable; import static javax.persistence.GenerationType.SEQUENCE; @Entity @Table(name = "gas") public class Gas implements Serializable { @Id @GeneratedValue(strategy = SEQUENCE, generator = "gas_id_seq") @SequenceGenerator(name = "gas_id_seq",sequenceName = "gas_id_seq",allocationSize = 1) @JsonIgnore private long id; @Column(name = "gas_type") private String gasType; // @Column(name = "gas_station") // private Station station; public void setGasType(String gasType) { this.gasType = gasType; } // public Station getStation() { // return station; // } // // public void setStation(Station station) { // this.station = station; // } public long getId() { return id; } public String getGasType() { return gasType; } }<file_sep>/travelbudcore/src/main/java/com/travel/core/repository/GasRepository.java package com.travel.core.repository; import com.travel.core.domain.Gas; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface GasRepository extends CrudRepository<Gas, Long> { // @Query("Select g FROM Gas g LEFT JOIN FETCH g.stations where g.id = ?1") // Optional<Gas> findByIdWithStations(Long Id); } <file_sep>/mvc/src/test/java/com/travel/core/service/EmailServiceTest.java package com.travel.core.service; import com.travel.core.config.DatabaseConfig; import com.travel.core.domain.User; import com.travel.core.email.RegistrationEmail; import com.travel.mvc.config.AppConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; import javax.mail.internet.MimeMessage; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @WebAppConfiguration @ContextConfiguration(classes = {AppConfig.class,DatabaseConfig.class}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("unit") public class EmailServiceTest { @Autowired private RegistrationEmail registrationEmail; @Autowired private JavaMailSenderImpl javaMailSender; @Test @Transactional public void confirmEmailTest(){ User u = new User(); MimeMessage mockMsg = Mockito.mock(MimeMessage.class); when(javaMailSender.createMimeMessage()).thenReturn(mockMsg); Map<String, Serializable> root = new HashMap<>(); u.setEmail("<EMAIL>"); u.setPassword("<PASSWORD>"); u.setLastName("zhang"); u.setFirstName("zhengshi"); u.setUsername("dameinv"); u.setAccountExpired(false); u.setEnabled(true); u.setCredentialExpired(false); u.setAccountLocked(false); registrationEmail.confirmEmail(u,root); verify(javaMailSender,times(1)).createMimeMessage(); verify(javaMailSender,times(1)).send(any(MimeMessage.class)); } } <file_sep>/travelbudcore/src/main/resources/db/migration/V3.07__Added_user_id.sql ALTER TABLE authorities ADD COLUMN user_id bigint;<file_sep>/travelbudcore/src/main/resources/db/migration/V3.08__Drop_users_id_col.sql ALTER table authorities DROP column users_id;<file_sep>/travelbudcore/src/main/resources/db/migration/V3.02__Changed_Column_Name.sql ALTER TABLE users Drop COLUMN password; ALTER TABLE users Drop COLUMN account_non_expired; ALTER TABLE users Drop COLUMN account_non_locked; ALTER TABLE users Drop COLUMN credential_non_expired; ALTER TABLE users Drop COLUMN enable_or_not; ALTER TABLE users ADD COLUMN password varchar(255) NOT NULL DEFAULT '<PASSWORD>'; ALTER TABLE users ADD COLUMN account_expired BOOlEAN NOT NULL DEFAULT FALSE; ALTER TABLE users ADD COLUMN account_locked BOOLEAN NOT NULL DEFAULT FALSE ; ALTER TABLE users ADD COLUMN credential_expired BOOLEAN NOT NULL DEFAULT FALSE ; ALTER TABLE users ADD COLUMN enabled BOOLEAN NOT NULL DEFAULT True;<file_sep>/travelbudcore/src/main/resources/db/migration/V3.03__Added_Email_Column.sql ALTER TABLE users ADD COLUMN email varchar(255) NOT NULL DEFAULT '<EMAIL>'; <file_sep>/api-core-boot/src/main/java/com/travelbud/apicoreboot/Jms/MyListener.java package com.travelbud.apicoreboot.Jms; import com.travel.core.service.EmailService; import com.travel.core.service.SmsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; import java.util.Map; @Component @EnableAutoConfiguration public class MyListener { @Autowired EmailService emailService; @Autowired SmsService smsService; protected final Logger logger = LoggerFactory.getLogger(getClass()); @JmsListener(destination = "${jms.queue.name}") public void processMessage(Map<String,Object> msg){ String msgType = (String)msg.get("msgType"); String msgText = (String)msg.get("msgText"); Long userID = Long.valueOf(msgText); Long id = Long.parseLong(msgText); emailService.sendConfirmEmail(id); //smsService.sendConfirmTextMessage(id); logger.info("receive msgType: "+msgType); logger.info("receive msgText: "+msgText); } } <file_sep>/ops/container/Dockerfile FROM tomcat:9.0.10-jre8 MAINTAINER <NAME> ARG APP_ENV=test ENV APP_ENV=test EXPOSE 8080 RUN rm -rf /usr/local/tomcat/webapps/ROOT COPY ./*.war /usr/local/tomcat/webapps/ROOT.war COPY ./setenv.test.sh /usr/local/tomcat/bin/setenv.sh<file_sep>/travelbudcore/src/main/resources/db/migration/V4.05__Add_GasPrice_table.sql CREATE SEQUENCE gasprices_id_seq; create table gasprices ( id bigint not null DEFAULT NEXTVAL('gasprices_id_seq'), gas_price double precision , primary key (id) ); ALTER SEQUENCE gasprices_id_seq OWNED BY gasprices.id;<file_sep>/travelbudcore/src/main/resources/db/migration/V3.06__Corrected_users_id_type.sql ALTER TABLE authorities DROP COLUMN users_id; ALTER TABLE authorities ADD COLUMN users_id bigint; <file_sep>/ops/container/setenv.prod.sh export spring.profiles.active="prod" export aws.region="us-east-1"<file_sep>/travelbudcore/src/main/java/com/travel/core/service/EmailService.java package com.travel.core.service; import com.travel.core.domain.User; import com.travel.core.email.RegistrationEmail; import com.travel.core.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; @Service public class EmailService { @Autowired private RegistrationEmail registrationEmail; @Autowired private UserRepository userRepository; @Transactional public void sendConfirmEmail(Long id){ Optional<User> optional = userRepository.findById(id); User user = optional.get(); registrationEmail.confirmEmail(user,null); } } <file_sep>/travelbudcore/src/main/resources/db/migration/V3.01__BUG_FIXED.sql ALTER TABLE users Drop COLUMN account_non_expired; ALTER TABLE users ADD COLUMN account_non_expired BOOLEAN NOT NULL DEFAULT True;<file_sep>/travelbudcore/src/main/resources/db/migration/V2.5__Add_Station_table.sql CREATE SEQUENCE station_id_seq; create table station ( id bigint not null DEFAULT NEXTVAL('station_id_seq'), gas_price varchar(255), gas_location varchar(255), gas_brand varchar(255) not NULL, primary key (id) ); ALTER SEQUENCE gas_id_seq OWNED BY gas.id; <file_sep>/api-core-boot/src/main/java/com/travelbud/apicoreboot/config/WorkerConfig.java package com.travelbud.apicoreboot.config; import org.springframework.context.annotation.Configuration; //@Import(ServiceConfig.class) @Configuration public class WorkerConfig { } <file_sep>/travelbudcore/src/main/resources/db/migration/V3.04__Created_Authority.sql CREATE SEQUENCE authority_id_seq; create table authorities ( id bigint not null DEFAULT NEXTVAL('authority_id_seq'), authority_role varchar(255) not NULL, users_id INTEGER, primary key (id) ); ALTER SEQUENCE authority_id_seq OWNED BY authorities.id; ALTER TABLE authorities ADD CONSTRAINT fk_authorities_user FOREIGN KEY(users_id) REFERENCES authorities(id);<file_sep>/travelbudcore/src/main/resources/db/migration/V4.03__Temp_revise_set_userid_to_null.sql ALTER table image drop column s3key; ALTER table image add column s3key varchar(255) DEFAULT 'default_s3key';<file_sep>/travelbudcore/src/main/resources/db/migration/V2.9__Correct_Fk_name.sql ALTER TABLE station DROP CONSTRAINT fk_station; ALTER TABLE station ADD CONSTRAINT fk_station_gas FOREIGN KEY(gas_id) REFERENCES station(id)<file_sep>/travelbudcore/src/main/java/com/travel/core/domain/User.java package com.travel.core.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import java.util.Collection; import static javax.persistence.GenerationType.SEQUENCE; @Entity @Table(name = "users") @JsonIgnoreProperties(ignoreUnknown = true) public class User implements UserDetails { @Id @GeneratedValue(strategy = SEQUENCE, generator = "users_id_seq") @SequenceGenerator(name = "users_id_seq", sequenceName = "users_id_seq") private long id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "username") private String username; @Column(name = "password") private String password; @Column(name = "account_Expired") private Boolean accountExpired; @Column(name = "account_locked") private Boolean accountLocked; @Column(name = "credential_expired") private Boolean credentialExpired; @Column(name = "enabled") private Boolean enabled; @Column(name = "email") private String email; @Column(name = "phone_number") private String phoneNumber; @Transient @JsonIgnore private Collection<GrantedAuthority> authorities; public void setAuthorities(Collection<GrantedAuthority> authorities) { this.authorities = authorities; } public String getEmail() { return email; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setEmail(String email) { this.email = email; } public void setLastName(String lastName) { this.lastName = lastName; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = <PASSWORD>; } public void setAccountExpired(Boolean accountExpired) { this.accountExpired = accountExpired; } public void setAccountLocked(Boolean accountLocked) { this.accountLocked = accountLocked; } public void setCredentialExpired(Boolean credentialExpired) { this.credentialExpired = credentialExpired; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public Boolean getAccountExpired() { return accountExpired; } public Boolean getAccountLocked() { return accountLocked; } public Boolean getCredentialExpired() { return credentialExpired; } public Boolean getEnabled() { return enabled; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public long getId() { return id; } @Override public String getUsername() { return username; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities ; } @Override public String getPassword() { return <PASSWORD>; } @Override public boolean isAccountNonExpired() { return !accountExpired; } @Override public boolean isAccountNonLocked() { return !accountLocked; } @Override public boolean isCredentialsNonExpired() { return !credentialExpired; } @Override public boolean isEnabled() { return enabled; } }<file_sep>/travelbudcore/src/main/java/com/travel/core/service/UserDetailsServiceImpl.java package com.travel.core.service; import com.travel.core.Utils; import com.travel.core.domain.Authority; import com.travel.core.domain.User; import com.travel.core.repository.AuthorityRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Locale; @Service public class UserDetailsServiceImpl implements UserDetailsService, MessageSourceAware { @Autowired private UserService userService; @Autowired private AuthorityService authorityService; @Autowired protected MessageSource messageSource; private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class); @Override @Transactional public UserDetails loadUserByUsername(String emailorUsername) { logger.debug(emailorUsername+" is trying to log in from spring security"); User domainUser = null; try { domainUser = userService.findByEmailOrUsername(emailorUsername); }catch (Exception repositoryProblem) { logger.debug("catch AuthenticationServiceException from AuthenticationProvider"); } if (domainUser == null) { throw new BadCredentialsException(messageSource.getMessage("AbstractUserDetailsAuthenticationProvider.UsernameNotFound", new Object[] {emailorUsername , "User {0} has no GrantedAuthority"}, Locale.US)); } domainUser.setAuthorities(Utils.getAuthorities(authorityService.findAuthoritiesByUserId(domainUser))); return domainUser; } @Override public void setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } @Autowired private AuthorityRepository authorityRepository; @Transactional(readOnly = true) public List<Authority> findAuthoritiesByUserId(User user){ List<Authority> authoritiesRoles = authorityRepository.findAuthoritiesByUserId(user.getId()); return authoritiesRoles; } }<file_sep>/ops/container/setenv.test.sh export CATALINA_OPTS="$CATALINA_OPTS -ea" export CATALINA_OPTS="$CATALINA_OPTS -Xms1g" export CATALINA_OPTS="$CATALINA_OPTS -Dspring.profiles.active=test" export CATALINA_OPTS="$CATALINA_OPTS -Daws.region=us-east-2<file_sep>/travelbudcore/src/main/resources/db/migration/V3.0__Implemented_serviceDetail.sql ALTER TABLE users ADD COLUMN password varchar(255) NOT NULL DEFAULT '<PASSWORD>'; ALTER TABLE users ADD COLUMN account_non_expired varchar(255) NOT NULL DEFAULT True; ALTER TABLE users ADD COLUMN account_non_locked BOOLEAN NOT NULL DEFAULT True; ALTER TABLE users ADD COLUMN credential_non_expired BOOLEAN NOT NULL DEFAULT True; ALTER TABLE users ADD COLUMN enable_or_not BOOLEAN NOT NULL DEFAULT True; <file_sep>/travelbudcore/src/main/resources/db/migration/V4.02__Added_s3key_column_to_image_table.sql ALTER table image add column s3key varchar(255) NOT NULL DEFAULT 'default_s3key';<file_sep>/travelbudcore/src/main/resources/db/migration/V3.05__Corrected_Fk.sql ALTER TABLE authorities DROP CONSTRAINT fk_authorities_user; ALTER TABLE authorities ADD CONSTRAINT fk_authorities_users FOREIGN KEY(users_id) REFERENCES authorities(id)<file_sep>/travelbudcore/src/main/resources/db/migration/V2.6__Add_gasID_Column.sql ALTER TABLE station ADD COLUMN gas_id varchar(255) NOT NULL;<file_sep>/ops/container/build.sh #!/bin/bash docker build -t travelbud-api -f Dockerfile . docker run --name travelBudDB docker rm -v ${imageName}<file_sep>/travelbudcore/src/main/resources/db/migration/V4.00__ADD_FK.sql ALTER table image Add column users_id bigint not null; ALTER table image ADD CONSTRAINT fk_image_users FOREIGN KEY(users_id) REFERENCES image(id);<file_sep>/travelbudcore/src/main/resources/db/migration/V2.8__Add_correct_gasID.sql ALTER TABLE station DROP COLUMN gas_id; ALTER TABLE station ADD COLUMN gas_id bigint DEFAULT NULL, ADD CONSTRAINT fk_station FOREIGN KEY(gas_id) REFERENCES station(id);<file_sep>/mvc/src/test/java/com/travel/core/repository/GasRepositoryTest.java package com.travel.core.repository; import com.travel.core.config.DatabaseConfig; import com.travel.mvc.config.AppConfig; import com.travel.core.domain.Gas; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @WebAppConfiguration @ContextConfiguration(classes = {AppConfig.class,DatabaseConfig.class}) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("unit") public class GasRepositoryTest { @Autowired private GasRepository gasRepository; @Test @Transactional public void findByIdTest(){ Gas tester = new Gas(); tester.setGasType("93"); gasRepository.save(tester); Optional<Gas> testGas = gasRepository.findById(tester.getId()); assertNotNull(testGas); assertEquals(tester.getId(),testGas.get().getId()); } } <file_sep>/travelbudcore/src/main/resources/db/migration/V4.04__Drop_users_id_col.sql ALTER table image DROP column users_id;<file_sep>/travelbudcore/src/main/resources/db/migration/V4.06__Add_2_fk_for_GasPrice_table.sql Alter table station drop column gas_price; ALTER table gasprices Add column gas_id bigint not null; ALTER table gasprices ADD CONSTRAINT fk_gasprices_gas FOREIGN KEY(gas_id) REFERENCES gasprices(id); ALTER table gasprices Add column station_id bigint not null; ALTER table gasprices ADD CONSTRAINT fk_gasprices_station FOREIGN KEY(station_id) REFERENCES gasprices(id);
30ba6429083361742eb90e957c50187296997a65
[ "Java", "SQL", "Dockerfile", "Shell" ]
38
SQL
zhengsz123/travelBud
019902f242eea0dc7e2350574baa82952c103fc5
73eb1dd5d9eb1e862ab44c68b170f1c92c29c4c0
refs/heads/master
<repo_name>soumilkanwal80/Anomaly-Detector<file_sep>/preprocess.py # This script extracts reshapes each video into 171x128 and stores them as a folder of frames, and creates our train-val split. import os, cv2, threading, shutil import numpy as np DATASET_PATH = "./dataset/" FEATURE_PATH = "./train_an/" VAL_PATH = "./val_an/" num_threads = 64 num_process = 16 CATEGORIES = os.listdir(DATASET_PATH) def processVideo(vid_path, name): if len(os.listdir(FEATURE_PATH + name)) > 0: return videoStream = cv2.VideoCapture(vid_path) print(name) frameCount = int(videoStream.get(cv2.CAP_PROP_FRAME_COUNT)) frameWidth = int(videoStream.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(videoStream.get(cv2.CAP_PROP_FRAME_HEIGHT)) count = 0 while True: ret, frame = videoStream.read() if ret == False: break frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = cv2.resize(frame, (171, 128)) cv2.imwrite(FEATURE_PATH + name + '/' + str(count) + '.png', frame) count = count + 1 def getPaths(): vid_paths = [] feature_paths = [] for category in CATEGORIES: video_path = DATASET_PATH + category + '/' if os.path.isdir(video_path) is True: videos = os.listdir(video_path) videos.sort() idx = 0 for video in videos: vid_paths.append(video_path + video) feature_paths.append(category + '/' + str(idx)) idx = idx + 1 return vid_paths, feature_paths def threadFunction(l1, l2): for i in range(len(l1)): processVideo(l1[i], l2[i]) def init(del_normal = True): for i in CATEGORIES: if os.path.isdir(FEATURE_PATH + i)== False and os.path.isdir(DATASET_PATH + i) == True: os.makedirs(FEATURE_PATH + i) video_paths, feature_paths = getPaths() for i in feature_paths: if os.path.isdir(FEATURE_PATH + i) == False: os.makedirs(FEATURE_PATH + i) for num in range(num_threads-1): low, up = int(2077*num/num_threads), int(2077*(num+1)/num_threads) threading.Thread(target = threadFunction, args = (video_paths[low:up], feature_paths[low:up])).start() for i in range(2077): processVideo(video_paths[i], feature_paths[i]) for i in CATEGORIES: os.makedirs(VAL_PATH + i) if del_normal == False: for i in CATEGORIES: if i == "normal": for j in range(100): shutil.move(FEATURE_PATH + i + '/' + str(j), VAL_PATH + i + '/' + str(j)) else: for j in range(4): shutil.move(FEATURE_PATH + i + '/' + str(j), VAL_PATH + i + '/' + str(j)) else: for i in CATEGORIES: if i == "normal": for j in range(len(os.listdir(FEATURE_PATH + i))): shutil.rmtree(FEATURE_PATH + i + '/' + str(j)) else: for j in range(4): shutil.move(FEATURE_PATH + i + '/' + str(j), VAL_PATH + i + '/' + str(j)) os.rmdir(FEATURE_PATH + "normal") os.rmdir(VAL_PATH + "normal") init(del_normal = True) FEATURE_PATH = "./train/" VAL_PATH = './val/' init(del_normal = False) <file_sep>/icfeatures.py from ic_code.demo.demo_feature_extraction import calculateImageFeatures from tqdm import tqdm import cv2, os from matplotlib import pyplot as plt import skvideo.io as skv from tqdm import tqdm import numpy as np ic_path = './train_2' ic_val_path = './val_2' src_path = './dataset' def extractICFeatures(category, file_name): vid = skv.vread(os.path.join(src_path, category, file_name)) features = [] for i in tqdm(range(vid.shape[0])): frame_features = calculateImageFeatures(vid[i]) frame_features = frame_features.mean(axis = 0) frame_features[np.isnan(frame_features)] = 0 features.append(frame_features) features = np.array(features) if os.path.isdir(ic_path) == False: os.makedirs(ic_path) for j in category: if os.path.isdir(os.path.join(ic_path, category)) == False: os.makedirs(os.path.join(ic_path, category)) np.save(os.path.join(ic_path, category, file_name.replace('mp4', '.npy')), features) category = os.listdir(src_path) if os.path.isdir(ic_val_path) == False: os.makedirs(ic_val_path) for j in category: if os.path.isdir(os.path.join(ic_val_path, j)) == False: os.makedirs(os.path.join(ic_val_path, j)) for i in category: for j in os.listdir(os.path.join(src_path, i)): extractICFeatures(i, j) for i in CATEGORIES: if i == "normal": for j in range(100): shutil.move(os.path.join(ic_path, i, str(j) + '.npy'), os.path.join(ic_val_path, i, str(j) + '.npy')) else: for j in range(4): shutil.move(os.path.join(ic_path, i, str(j) + '.npy'), os.path.join(ic_val_path, i, str(j) + '.npy')) <file_sep>/train_binary.py import numpy as np import torch import torchvision.models as tv import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset from tqdm import tqdm import torch.optim as optim import math import cv2, os from matplotlib import pyplot as plt import skvideo.io as skv from tqdm import tqdm from random import randint, seed, shuffle from torchvision import transforms from models import * res = tv.resnet101(pretrained=True) res = nn.Sequential(*list(res.children())[:-2]) res = res.eval() res3d = tv.video.r2plus1d_18(pretrained = True) res3d = nn.Sequential(*list(res3d.children())[:-1]) transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize( mean = np.array([0.485, 0.456, 0.406]), std = np.array([0.229, 0.224, 0.225]) ) ]) transform3d = transforms.Compose([ transforms.ToTensor(), transforms.Normalize( mean = np.array([0.43216, 0.394666, 0.37645]), std = np.array([0.22803, 0.22145, 0.216989]) ) ]) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') decoder = SERLOC_A_Binary(res, res3d).to(device) category = os.listdir('./train') cat2idx = {} idx2cat = {} for i in range(len(category)): cat2idx[category[i]] = i idx2cat[i] = category[i] def get_paths(mode = 'train'): IMG_PATH = './' + mode X = [] Y = [] Z = [] CATEGORIES = os.listdir(IMG_PATH) for i in range(len(CATEGORIES)): tmp_path = os.path.join(IMG_PATH, CATEGORIES[i]) for j in os.listdir(tmp_path): X.append(j) Y.append(i) Z.append(1) if idx2cat[i] == "normal": X.append(j) Y.append(i) Z.append(0) return X, Y, Z X_train, Y_train, Z_train = get_paths('train') X_val, Y_val, Z_val = get_paths('val') train_steps_per_epoch = int(len(X_train)/16) val_steps_per_epoch = int(len(X_val)/16) class VideoLoader(Dataset): def __init__(self, folder_name, label, Z, batch_size = 8, clip_len = 16, mode = 'train'): super() self.folder_name = folder_name self.label = label self.batch_size = batch_size self.mode = mode self.clip_len = clip_len self.max = self.__len__() self.iter = 0 self.Z = Z def __len__(self): return math.floor(len(self.folder_name)/self.batch_size) def __getitem__(self, idx): batch_folder_names = self.folder_name[idx*self.batch_size:(idx + 1)*self.batch_size] batch_label = self.label[idx*self.batch_size:(idx+1)*self.batch_size] batch_Z = self.Z[idx*self.batch_size:(idx+1)*self.batch_size] IMG_PATH = './' + self.mode FEATURE_PATH = './' + self.mode + '_2' # FLOW_PATH = './' + self.mode + '_flow_n' X = [] Y = [] C = [] F = [] X3D = [] for j in range(self.batch_size): folder_path = os.path.join(IMG_PATH, idx2cat[batch_label[j]], batch_folder_names[j]) feature_path = os.path.join(FEATURE_PATH, idx2cat[batch_label[j]], batch_folder_names[j]) + '.npy' #flow_path = os.path.join(FLOW_PATH, idx2cat[batch_label[j]], batch_folder_names[j]) caption_features = np.load(feature_path, allow_pickle = True) imgs = os.listdir(folder_path) num = len(imgs) start_idx = randint(0, num - self.clip_len) of = [] x = [] c = [] x3d = [] for i in range(self.clip_len): im = cv2.imread(folder_path + '/' + str(start_idx + i) + '.png') imo = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) im = transform(imo[8:120, 30:142, :].astype('float32')/255).numpy() im3d = transform3d(imo[8:120, 30:142, :].astype('float32')/255).numpy() if batch_Z[j] == 0: im = cv2.flip(im, 1) im3d = cv2.flip(im3d, 1) tmp = caption_features[start_idx + i] tmp[np.isnan(tmp)] = 0 c.append(tmp) x.append(im) x3d.append(im3d) X.append(np.array(x)) C.append(np.array(c)) X3D.append(np.array(x3d)) #print(j, len(batch_label), batch_label) if(cat2idx["normal"] == batch_label[j]): Y.append(0) else: Y.append(1) #print(len(batch_label), len(X)) #print(batch_label) return np.array(X), np.array(Y), np.array(C), np.array(X3D) def on_epoch_end(self): mapIndexPosition = list(zip(self.folder_name, self.label, self.Z)) shuffle(mapIndexPosition) self.folder_name, self.label, self.Z = zip(*mapIndexPosition) def __next__(self): #print(self.iter) if self.iter >= self.max: self.iter = 0 self.on_epoch_end() res = self.__getitem__(self.iter) self.iter = self.iter + 1 return res train_gen = VideoLoader(X_train, Y_train, Z_train,16, mode = 'train') val_gen = VideoLoader(X_val, Y_val, Z_val, 16, mode = 'val') criterion = nn.BCEWithLogitsLoss() optimizer = optim.Adam(decoder.parameters(), lr = 1e-5) for epoch in range(15): running_loss = 0 for steps in tqdm(range(train_steps_per_epoch)): optimizer.zero_grad() x, y_true, c, x3d = next(train_gen) x3d = torch.from_numpy(x3d).float().permute((0, 2, 1, 3, 4)).to(device) x = torch.from_numpy(x).float().to(device) y_true = torch.from_numpy(y_true).to(device).float().reshape((16, 1)) c = torch.from_numpy(c).float().to(device) y_pred = decoder(x, x3d, c) loss = criterion(y_pred, y_true) loss.backward() optimizer.step() running_loss+=loss.item() print(running_loss/train_steps_per_epoch) torch.save(decoder.state_dict(), './weights/serlocA_Binary.pt') <file_sep>/models.py import torch import torchvision.models as tv import torch.nn as nn import torch.nn.functional as F class SERLOC_A_Binary(nn.Module): def __init__(self, res101, res3d): super(SERLOC_A_Binary, self).__init__() self.res101 = res101 self.res3d = res3d.train() self.hidden_dim = 512 self.lstm1 = nn.LSTM(input_size=2048, hidden_size = self.hidden_dim, num_layers = 3, dropout = 0.2, bidirectional = True, batch_first = True) self.lstm2 = nn.LSTM(input_size=2048, hidden_size = self.hidden_dim, num_layers = 3, dropout = 0.2, bidirectional = True, batch_first = True) self.linear1 = nn.Linear(512*3, 512) self.final1 = nn.Linear(512, 1) #self.final4 = nn.Linear(512, 13) def forward(self, x, x3d, fv): y_1 = [] y_2 = [] y_3 = [] #print(x.shape, x3d.shape, fv.shape) with torch.no_grad(): self.h0_1 = torch.zeros(3*2, 1, self.hidden_dim).to(device) self.c0_1 = torch.zeros(3*2, 1, self.hidden_dim).to(device) self.h0_2 = torch.zeros(3*2, 1, self.hidden_dim).to(device) self.c0_2 = torch.zeros(3*2, 1, self.hidden_dim).to(device) for i in range(x.shape[0]): #print(x[i].shape) tmp = self.res101(x[i]) tmp = tmp.mean([2, 3]) tmp_fv = fv[i] #tmp = torch.cat([tmp, tmp_fv], 1) y_1.append(tmp) y_2.append(tmp_fv) y_4 = self.res3d(x3d) y_4 = y_4[:, :, -1, -1, -1] y_1 = torch.stack(y_1) y_2 = torch.stack(y_2) #print(y_1.shape, y_2.shape) x_1, _ = self.lstm1(y_1, (self.h0_1, self.c0_1)) x_1 = x_1[:, -1, 0:512] x_2, _ = self.lstm2(y_2, (self.h0_2, self.c0_2)) x_2 = x_2[:, -1, 0:512] x = torch.cat([x_1, x_2, y_4], axis = 1) x = self.final1(F.relu(self.linear1(x))) return x class SERLOC_B_Anomaly(nn.Module): def __init__(self, res101, res3d): super(SERLOC_B_Anomaly, self).__init__() self.res101 = res101 self.res3d = res3d.train() self.hidden_dim = 512 #Linear layers self.linear_o1 = nn.Linear(2048, 512) self.linear_res1 = nn.Linear(2048, 512) self.final1=nn.Linear(512*3, 512) self.final2 = nn.Linear(512, 12) self.dropout1=nn.Dropout(p=0.4) def forward(self, x, x3d, fv): #res features with torch.no_grad(): x_res = self.res101(x) x_res = x_res.mean([2, 3]) x_res1=F.relu(self.linear_res1(x_res)) #object features x_o1=F.relu(self.linear_o1(fv)) #res3d features x_res3d1 = self.res3d(x3d) x_res3d1 = x_res3d1[:, :, -1, -1, -1] cat1 = torch.cat([x_res1, x_o1, x_res3d1], axis = 1) dense1=F.relu(self.final1(cat1)) drop1=self.dropout1(dense1) x = self.final2(drop1) return x<file_sep>/dataset/README.md Get access to the dataset from here: https://cityscene.github.io/#/dataset Directory should look like this ./dataset ├── accident ├── carrying ├── explosion ├── fighting ├── graffiti ├── robbery ├── shooting ├── smoking ├── stealing ├── sweeping ├── walkingdog ├── normal └── README.md Delete README.md before running the python scripts <file_sep>/ic_code/demo/demo_feature_extraction.py #!/usr/bin/env python # coding: utf-8 # In[1]: import os import io import detectron2 # import some common detectron2 utilities from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.utils.visualizer import Visualizer from detectron2.data import MetadataCatalog # import some common libraries import numpy as np import cv2 import torch # Show the image in ipynb from IPython.display import clear_output, Image, display import PIL.Image def showarray(a, fmt='jpeg'): a = np.uint8(np.clip(a, 0, 255)) f = io.BytesIO() PIL.Image.fromarray(a).save(f, fmt) display(Image(data=f.getvalue())) # In[2]: # Load VG Classes data_path = os.path.join('./ic_code/demo', 'data/genome/1600-400-20') vg_classes = [] with open(os.path.join(data_path, 'objects_vocab.txt')) as f: for object in f.readlines(): vg_classes.append(object.split(',')[0].lower().strip()) MetadataCatalog.get("vg").thing_classes = vg_classes # In[3]: cfg = get_cfg() cfg.merge_from_file("./ic_code/configs/VG-Detection/faster_rcnn_R_101_C4_caffe.yaml") cfg.MODEL.RPN.POST_NMS_TOPK_TEST = 300 cfg.MODEL.ROI_HEADS.NMS_THRESH_TEST = 0.6 cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.2 # VG Weight cfg.MODEL.WEIGHTS = "http://nlp.cs.unc.edu/models/faster_rcnn_from_caffe.pkl" predictor = DefaultPredictor(cfg) # In[23]: NUM_OBJECTS = 36 from detectron2.modeling.postprocessing import detector_postprocess from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers, FastRCNNOutputs, fast_rcnn_inference_single_image def calculateImageFeatures(raw_image): with torch.no_grad(): raw_height, raw_width = raw_image.shape[:2] #print("Original image size: ", (raw_height, raw_width)) # Preprocessing image = predictor.transform_gen.get_transform(raw_image).apply_image(raw_image) #print("Transformed image size: ", image.shape[:2]) image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1)) inputs = [{"image": image, "height": raw_height, "width": raw_width}] images = predictor.model.preprocess_image(inputs) # Run Backbone Res1-Res4 features = predictor.model.backbone(images.tensor) # Generate proposals with RPN proposals, _ = predictor.model.proposal_generator(images, features, None) proposal = proposals[0] #print('Proposal Boxes size:', proposal.proposal_boxes.tensor.shape) # Run RoI head for each proposal (RoI Pooling + Res5) proposal_boxes = [x.proposal_boxes for x in proposals] features = [features[f] for f in predictor.model.roi_heads.in_features] box_features = predictor.model.roi_heads._shared_roi_transform( features, proposal_boxes ) feature_pooled = box_features.mean(dim=[2, 3]) # pooled to 1x1 #print('Pooled features size:', feature_pooled.shape) # Predict classes and boxes for each proposal. pred_class_logits, pred_proposal_deltas = predictor.model.roi_heads.box_predictor(feature_pooled) outputs = FastRCNNOutputs( predictor.model.roi_heads.box2box_transform, pred_class_logits, pred_proposal_deltas, proposals, predictor.model.roi_heads.smooth_l1_beta, ) probs = outputs.predict_probs()[0] boxes = outputs.predict_boxes()[0] # Note: BUTD uses raw RoI predictions, # we use the predicted boxes instead. # boxes = proposal_boxes[0].tensor # NMS for nms_thresh in np.arange(0.5, 1.0, 0.1): instances, ids = fast_rcnn_inference_single_image( boxes, probs, image.shape[1:], score_thresh=0.2, nms_thresh=nms_thresh, topk_per_image=NUM_OBJECTS ) if len(ids) == NUM_OBJECTS: break instances = detector_postprocess(instances, raw_height, raw_width) roi_features = feature_pooled[ids].detach() #print(instances) return roi_features.to('cpu').numpy() # In[62]: # from tqdm import tqdm # # In[39]: # DATA_PATH = '../../val' # CATEGORIES = os.listdir(DATA_PATH) # FEATURE_PATH = './val_features' # for i in CATEGORIES: # #print(i) # FOLDER_PATH = os.path.join(DATA_PATH, i) # for j in os.listdir(FOLDER_PATH): # if os.path.isdir(os.path.join(FEATURE_PATH, i)) == False: # os.makedirs(os.path.join(FEATURE_PATH, i)) # feat_list = [] # im_list = [] # # In[40]: # for i in CATEGORIES: # #print(i) # FOLDER_PATH = os.path.join(DATA_PATH, i) # for j in os.listdir(FOLDER_PATH): # FEATURE_FILE = os.path.join(FEATURE_PATH, i, str(j) + '.npy') # IMG_DIR = os.path.join(FOLDER_PATH, j) # feat_list.append(FEATURE_FILE) # im_list.append(IMG_DIR) # # In[63]: # def feature_save(args): # IMG_DIR, FEATURE_FILE = args # if os.path.isfile(FEATURE_FILE) == True: # print("hi") # return # print(FEATURE_FILE) # feat = [] # for k in range(len(os.listdir(IMG_DIR))): # im = cv2.imread(os.path.join(IMG_DIR, str(k) + '.png')) # feat.append(doit(im)) # np.save(FEATURE_FILE, feat) # # In[58]: # args = ('../../val/normal/56', './56.npy') # feature_save(args) # idx = [] # for i in range(4 + 1): # idx.append(int(1929*i/4)) # # In[60]: # #print(len(im_list)) # #comb= zip(im_list, feat_list) # #for i in range(4): # # comb.append(zip(im_list[idx[i]:idx[i+1]], feat_list[idx[i]:idx[i+1]])) # # In[64]: # def processfn(comb_it): # for i in tqdm(list(comb_it)): # #it = next(comb_it) # feature_save(i) # # In[72]: # #processfn(comb[0]) # #processfn(comb[1]) # #processfn(comb) # #processfn(comb[3]) <file_sep>/README.md # Anomaly-Detector This repository contains the source code for deep learning based hierarchial anomaly detector developed as a part of CitySCENE grand challenge organized at ACM MM, 2020. Our team MonIIT ranked second in general anomaly detection task(ROC AUC 87.94) and fourth in specific anomaly detection task(Macro F1 45.52). Link to the challenge website: https://cityscene.github.io/#/challenge Report: https://dl.acm.org/doi/10.1145/3394171.3416302 # Installation **Note: this repository requires Python 3.7+ to work** 1. Follow installation instructions from this repository to install detectoron2: https://github.com/airsplay/py-bottom-up-attention, this will also setup PyTorch and OpenCV. 2. Install tqdm and skvideo Pretrained weights can be downloaded from here: https://drive.google.com/drive/folders/1iYjCekm571GgJbd4m_kT7jNEW05nJkjm?usp=sharing # Running Assuming data is located in the path as mentioned in [dataset/README.md](https://github.com/soumilkanwal80/Anomaly-Detector/blob/master/dataset/README.md) ### Data Preprocessing ``` python preprocess.py # extracts and reshapes each video frame into 171x128 and stores them as a folder of frames, also creates our train-val split. python icfeatures.py # extract and stores mean pooled object representations ``` ### Training ``` python train_anomaly.py or python train_binary.py # training models from scratch ``` # Citation If you find this useful, please cite this work as follows: ``` @inproceedings{10.1145/3394171.3416302, author = {<NAME> <NAME> <NAME>}, title = {Large Scale Hierarchical Anomaly Detection and Temporal Localization}, year = {2020}, isbn = {9781450379885}, publisher = {Association for Computing Machinery}, address = {New York, NY, USA}, url = {https://doi.org/10.1145/3394171.3416302}, doi = {10.1145/3394171.3416302}, abstract = {Abnormal event detection is a non-trivial task in machine learning. The primary reason behind this is that the abnormal class occurs sparsely, and its temporal location may not be available. In this paper, we propose a multiple feature-based approach for CitySCENE challenge-based anomaly detection. For motion and context information, Res3D and Res101 architectures are used. Object-level information is extracted by object detection feature-based pooling. Fusion of three channels above gives relatively high performance on the challenge Test set for the general anomaly task. We also show how our method can be used for temporal localisation of the abnormal activity event in a video.}, booktitle = {Proceedings of the 28th ACM International Conference on Multimedia}, pages = {4674–4678}, numpages = {5}, keywords = {anomaly detection, convolutional neural networks, CitySCENE}, location = {Seattle, WA, USA}, series = {MM '20} } ```
dba5673ec7374586ba32e1e2689a1f8b70751c74
[ "Markdown", "Python" ]
7
Python
soumilkanwal80/Anomaly-Detector
5b1869a646a4d7fb5421577a406f893204ef80b1
20de1194c5a3dc3134f32c04657e772c4e6f4b81
refs/heads/main
<repo_name>Eev-Main/PeliculasTC5<file_sep>/Program.cs using System; using System.Collections.Generic; namespace Peliculas { class Program { static void Main(string[] args) { List<string> nombresDePelicula = new List<string>(); nombresDePelicula.Add("Toy Story"); nombresDePelicula.Add("Avengers"); nombresDePelicula.Add("Bicentennial Man"); nombresDePelicula.Add("BeetleJuice"); nombresDePelicula.Add("Silenc of the Lambs"); nombresDePelicula.Add("Bad Boys"); nombresDePelicula.Add("Bad Boys"); nombresDePelicula.Add("Aladdin"); nombresDePelicula.Add("Aladdin"); HashSet<string> nombresDePeliculaSet = new HashSet<string>(); nombresDePeliculaSet.Add("Toy Story"); nombresDePeliculaSet.Add("Avengers"); nombresDePeliculaSet.Add("Bicentennial Man"); nombresDePeliculaSet.Add("BeetleJuice"); nombresDePeliculaSet.Add("Silenc of the Lambs"); nombresDePeliculaSet.Add("Bad Boys"); nombresDePeliculaSet.Add("Bad Boys"); nombresDePeliculaSet.Add("Aladdin"); nombresDePeliculaSet.Add("Aladdin"); Console.WriteLine("Cant. de peliculas en nombreDePeliculas: " + nombresDePelicula.Count); Console.WriteLine("Cant. de peliculas en nombreDePeliculasSet: " + nombresDePeliculaSet.Count); HashSet<Pelicula> peliculaSet = new HashSet<Pelicula>(); peliculaSet.Add(new Pelicula("bad Boys", 1995)); peliculaSet.Add(new Pelicula("bad Boys", 1983)); peliculaSet.Add(new Pelicula("Aladdin", 2019)); peliculaSet.Add(new Pelicula("Aladdin", 2019)); //son objetos distintos incluso si tienen los mismos datos peliculaSet.Add(new Pelicula("Aladdin", 1992)); Console.WriteLine("Cant. de peliculas en nombreDePeliculasSet: " + peliculaSet.Count); //output= 5 //map -> Java //dictionary -> C# python //object -> Javascript Dictionary<string, string> nombresDePeliculasFavoritas = new Dictionary<string, string>(); nombresDePeliculasFavoritas.Add("Pablo", "Titanic"); nombresDePeliculasFavoritas.Add("Esteban", "The Fast and the Furious: Toky Drift"); nombresDePeliculasFavoritas.Add("octavio", "Barbie in the 12 dancing princesses"); string NombrePeliculaFavoritaPablo = nombresDePeliculasFavoritas.GetValueOrDefault("Pablo"); Console.WriteLine("nombre de la pelicula favorita de pablo: " + NombrePeliculaFavoritaPablo); string NombrePeliculaFavoritaRamiro = nombresDePeliculasFavoritas.GetValueOrDefault("Ramiro"); Console.WriteLine("nombre de la pelicula favorita de Ramiro: " + NombrePeliculaFavoritaRamiro); //null NombrePeliculaFavoritaRamiro = nombresDePeliculasFavoritas.GetValueOrDefault("Ramiro", "(ninguna)"); Console.WriteLine("nombre de la pelicula favorita de Ramiro: " + NombrePeliculaFavoritaRamiro); //ninguna nombresDePeliculasFavoritas.Add("Ramiro", "Shrek"); NombrePeliculaFavoritaRamiro = nombresDePeliculasFavoritas.GetValueOrDefault("Ramiro", "(ninguna)"); Console.WriteLine("nombre de la pelicula favorita de Ramiro: " + NombrePeliculaFavoritaRamiro); //Shrek //uso real de obtner valores de un Dictionary //out -> se decñara una nueva variable donde se recibira el resultado (el valor de "salida") if (nombresDePeliculasFavoritas.TryGetValue("Maria", out string nombresDePeliculasFavoritaMaria)) { //en caso de que si tenga un valor el dictionary, se entra a este else Console.WriteLine("nombrePeliculaFavoritaMaria " + nombresDePeliculasFavoritaMaria); } else { Console.WriteLine("Maria no tiene pelicula favorita"); } //lista Console.WriteLine("-------------------"); Console.WriteLine("Lista"); for (int i = 0; i < nombresDePelicula.Count; i++) { Console.WriteLine(nombresDePelicula[i]); } //HashSet Console.WriteLine("-------------------"); Console.WriteLine("set"); //foreach : elemento in conjunto foreach (string nombrePelicula in nombresDePeliculaSet) { Console.WriteLine(nombrePelicula); } //Dictionary Console.WriteLine("-------------------"); Console.WriteLine("Dictionary"); foreach (var Key in nombresDePeliculasFavoritas.Keys) { Console.WriteLine(Key); } foreach (var value in nombresDePeliculasFavoritas.Values) { Console.WriteLine(value); } foreach (var Key in nombresDePeliculasFavoritas.Keys) { Console.WriteLine(Key + ":" + nombresDePeliculasFavoritas.GetValueOrDefault(Key)); } } } } <file_sep>/README.md # PeliculasTC5 Practica en C# de estructura de datos con peliculas para institucion CRESP
4a6cd241e47d0a9f5d9e9738cae56b34864caa46
[ "Markdown", "C#" ]
2
C#
Eev-Main/PeliculasTC5
a2f4903f35ed5697e5bf38d53c94fb2a59af2b0e
7b1adb450b115137140a9cd8704454d2df7b435a
refs/heads/main
<repo_name>JohnDominicJasmin/QuizGameInJava<file_sep>/src/Computer_Category/Cat4.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Computer_Category; import QandA.front; import javax.swing.JOptionPane; /** * * @author micojasmin */ class hp3 extends hp2{ } public class Cat4 extends javax.swing.JFrame { hp3 h3 = new hp3(); public Cat4() { initComponents(); jButtonCheck.setVisible(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jRadioButton1Basic = new javax.swing.JRadioButton(); jRadioButtonPL = new javax.swing.JRadioButton(); jRadioButton3Fortran = new javax.swing.JRadioButton(); jRadioButtonPascal = new javax.swing.JRadioButton(); jButtonCheck = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(153, 255, 153)); jPanel1.setLayout(null); jTextArea1.setEditable(false); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("sansserif", 0, 18)); // NOI18N jTextArea1.setRows(5); jTextArea1.setText("Which of the following languages is more \nsuited to a structured program?"); jScrollPane1.setViewportView(jTextArea1); jPanel1.add(jScrollPane1); jScrollPane1.setBounds(20, 40, 420, 90); jRadioButton1Basic.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jRadioButton1Basic.setForeground(new java.awt.Color(0, 0, 0)); jRadioButton1Basic.setText("\tBASIC "); jRadioButton1Basic.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButton1Basic.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1BasicActionPerformed(evt); } }); jPanel1.add(jRadioButton1Basic); jRadioButton1Basic.setBounds(20, 190, 200, 40); jRadioButtonPL.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jRadioButtonPL.setForeground(new java.awt.Color(0, 0, 0)); jRadioButtonPL.setText("PL/1 "); jRadioButtonPL.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonPL.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonPLActionPerformed(evt); } }); jPanel1.add(jRadioButtonPL); jRadioButtonPL.setBounds(20, 140, 200, 40); jRadioButton3Fortran.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jRadioButton3Fortran.setForeground(new java.awt.Color(0, 0, 0)); jRadioButton3Fortran.setText("FORTRAN "); jRadioButton3Fortran.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButton3Fortran.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton3FortranActionPerformed(evt); } }); jPanel1.add(jRadioButton3Fortran); jRadioButton3Fortran.setBounds(240, 140, 200, 40); jRadioButtonPascal.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jRadioButtonPascal.setForeground(new java.awt.Color(0, 0, 0)); jRadioButtonPascal.setText("PASCAL"); jRadioButtonPascal.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonPascal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonPascalActionPerformed(evt); } }); jPanel1.add(jRadioButtonPascal); jRadioButtonPascal.setBounds(240, 190, 200, 40); jButtonCheck.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButtonCheck.setText("Check"); jButtonCheck.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButtonCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCheckActionPerformed(evt); } }); jPanel1.add(jButtonCheck); jButtonCheck.setBounds(344, 250, 90, 35); jButton2.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButton2.setText("Back"); jButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel1.add(jButton2); jButton2.setBounds(20, 250, 90, 35); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed new Cat3().setVisible(true); setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed private void jButtonCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCheckActionPerformed if (jRadioButtonPascal.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS CORRECT"); new Cat5().setVisible(true); setVisible(false); } else if (!jRadioButtonPascal.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS WRONG" + "\n" + --h3.life +" "+ "LIVES LEFT"); if (h3.life == 0) { h3.life=3; JOptionPane.showMessageDialog(rootPane, "GAME OVER!"); new front().setVisible(true); setVisible(false); } } }//GEN-LAST:event_jButtonCheckActionPerformed private void jRadioButtonPLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonPLActionPerformed if (jRadioButtonPL.isSelected()) { jButtonCheck.setVisible(true); jRadioButton1Basic.setEnabled(false); jRadioButton3Fortran.setEnabled(false); jRadioButtonPascal.setEnabled(false); } else if (!jRadioButtonPL.isSelected()) { jButtonCheck.setVisible(false); jRadioButton1Basic.setEnabled(true); jRadioButton3Fortran.setEnabled(true); jRadioButtonPascal.setEnabled(true); } }//GEN-LAST:event_jRadioButtonPLActionPerformed private void jRadioButton3FortranActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3FortranActionPerformed if (jRadioButton3Fortran.isSelected()) { jButtonCheck.setVisible(true); jRadioButton1Basic.setEnabled(false); jRadioButtonPL.setEnabled(false); jRadioButtonPascal.setEnabled(false); } else if (!jRadioButton3Fortran.isSelected()) { jButtonCheck.setVisible(false); jRadioButton1Basic.setEnabled(true); jRadioButtonPL.setEnabled(true); jRadioButtonPascal.setEnabled(true); } }//GEN-LAST:event_jRadioButton3FortranActionPerformed private void jRadioButton1BasicActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1BasicActionPerformed if (jRadioButton1Basic.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonPL.setEnabled(false); jRadioButton3Fortran.setEnabled(false); jRadioButtonPascal.setEnabled(false); } else if (!jRadioButton1Basic.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonPL.setEnabled(true); jRadioButton3Fortran.setEnabled(true); jRadioButtonPascal.setEnabled(true); } }//GEN-LAST:event_jRadioButton1BasicActionPerformed private void jRadioButtonPascalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonPascalActionPerformed if (jRadioButtonPascal.isSelected()) { jButtonCheck.setVisible(true); jRadioButton1Basic.setEnabled(false); jRadioButton3Fortran.setEnabled(false); jRadioButtonPL.setEnabled(false); } else if (!jRadioButtonPascal.isSelected()) { jButtonCheck.setVisible(false); jRadioButton1Basic.setEnabled(true); jRadioButton3Fortran.setEnabled(true); jRadioButtonPL.setEnabled(true); } }//GEN-LAST:event_jRadioButtonPascalActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Cat4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Cat4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Cat4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Cat4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Cat4().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton2; private javax.swing.JButton jButtonCheck; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton jRadioButton1Basic; private javax.swing.JRadioButton jRadioButton3Fortran; private javax.swing.JRadioButton jRadioButtonPL; private javax.swing.JRadioButton jRadioButtonPascal; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables } <file_sep>/src/Computer_Category/Cat3.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Computer_Category; import QandA.front; import javax.swing.JOptionPane; /** * * @author micojasmin */ class hp2 extends hp1{ } public class Cat3 extends javax.swing.JFrame { hp2 h2 = new hp2(); public Cat3() { initComponents(); jButtonCheck.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jFileChooser1 = new javax.swing.JFileChooser(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767)); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jRadioButtonEncapsulation = new javax.swing.JRadioButton(); jRadioButtonPOLY = new javax.swing.JRadioButton(); jRadioButtonAbstract = new javax.swing.JRadioButton(); jRadioButtonInterface = new javax.swing.JRadioButton(); jButtonCheck = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(255, 255, 153)); jPanel1.setLayout(null); jTextArea1.setEditable(false); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextArea1.setRows(5); jTextArea1.setText("Which one is not part of 4 instance of \nObject Oriented Programming (OOP)?"); jScrollPane1.setViewportView(jTextArea1); jPanel1.add(jScrollPane1); jScrollPane1.setBounds(20, 30, 420, 80); jRadioButtonEncapsulation.setBackground(new java.awt.Color(204, 204, 204)); jRadioButtonEncapsulation.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonEncapsulation.setForeground(new java.awt.Color(51, 51, 51)); jRadioButtonEncapsulation.setText("Encapsulation"); jRadioButtonEncapsulation.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonEncapsulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonEncapsulationActionPerformed(evt); } }); jPanel1.add(jRadioButtonEncapsulation); jRadioButtonEncapsulation.setBounds(240, 200, 200, 40); jRadioButtonPOLY.setBackground(new java.awt.Color(204, 204, 204)); jRadioButtonPOLY.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonPOLY.setForeground(new java.awt.Color(51, 51, 51)); jRadioButtonPOLY.setText("Polymorphism"); jRadioButtonPOLY.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonPOLY.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonPOLYActionPerformed(evt); } }); jPanel1.add(jRadioButtonPOLY); jRadioButtonPOLY.setBounds(20, 200, 200, 40); jRadioButtonAbstract.setBackground(new java.awt.Color(204, 204, 204)); jRadioButtonAbstract.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonAbstract.setForeground(new java.awt.Color(51, 51, 51)); jRadioButtonAbstract.setText("Abstract Class"); jRadioButtonAbstract.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonAbstract.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonAbstractActionPerformed(evt); } }); jPanel1.add(jRadioButtonAbstract); jRadioButtonAbstract.setBounds(20, 140, 200, 40); jRadioButtonInterface.setBackground(new java.awt.Color(204, 204, 204)); jRadioButtonInterface.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonInterface.setForeground(new java.awt.Color(51, 51, 51)); jRadioButtonInterface.setText("Interface"); jRadioButtonInterface.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonInterface.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonInterfaceActionPerformed(evt); } }); jPanel1.add(jRadioButtonInterface); jRadioButtonInterface.setBounds(240, 140, 200, 40); jButtonCheck.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButtonCheck.setText("Check"); jButtonCheck.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButtonCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCheckActionPerformed(evt); } }); jPanel1.add(jButtonCheck); jButtonCheck.setBounds(350, 250, 90, 35); jButton2.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButton2.setText("Back"); jButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel1.add(jButton2); jButton2.setBounds(20, 250, 90, 35); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jRadioButtonAbstractActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonAbstractActionPerformed if (jRadioButtonAbstract.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonEncapsulation.setEnabled(false); jRadioButtonInterface.setEnabled(false); jRadioButtonPOLY.setEnabled(false); } else if (!jRadioButtonAbstract.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonEncapsulation.setEnabled(true); jRadioButtonInterface.setEnabled(true); jRadioButtonPOLY.setEnabled(true); } }//GEN-LAST:event_jRadioButtonAbstractActionPerformed private void jRadioButtonInterfaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonInterfaceActionPerformed if (jRadioButtonInterface.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonEncapsulation.setEnabled(false); jRadioButtonAbstract.setEnabled(false); jRadioButtonPOLY.setEnabled(false); } else if (!jRadioButtonInterface.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonEncapsulation.setEnabled(true); jRadioButtonAbstract.setEnabled(true); jRadioButtonPOLY.setEnabled(true); } }//GEN-LAST:event_jRadioButtonInterfaceActionPerformed private void jRadioButtonPOLYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonPOLYActionPerformed if (jRadioButtonPOLY.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonEncapsulation.setEnabled(false); jRadioButtonInterface.setEnabled(false); jRadioButtonAbstract.setEnabled(false); } else if (!jRadioButtonPOLY.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonEncapsulation.setEnabled(true); jRadioButtonInterface.setEnabled(true); jRadioButtonAbstract.setEnabled(true); } }//GEN-LAST:event_jRadioButtonPOLYActionPerformed private void jRadioButtonEncapsulationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonEncapsulationActionPerformed if (jRadioButtonEncapsulation.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonAbstract.setEnabled(false); jRadioButtonInterface.setEnabled(false); jRadioButtonPOLY.setEnabled(false); } else if (!jRadioButtonEncapsulation.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonAbstract.setEnabled(true); jRadioButtonInterface.setEnabled(true); jRadioButtonPOLY.setEnabled(true); } }//GEN-LAST:event_jRadioButtonEncapsulationActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed new Cat2().setVisible(true); setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed private void jButtonCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCheckActionPerformed if (jRadioButtonInterface.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS CORRECT"); new Cat4().setVisible(true); setVisible(false); } else if (!jRadioButtonInterface.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS WRONG" + "\n" + --h2.life +" "+ "LIVES LEFT"); if (h2.life == 0) { h2.life=3; JOptionPane.showMessageDialog(rootPane, "GAME OVER!"); new front().setVisible(true); setVisible(false); } } }//GEN-LAST:event_jButtonCheckActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Cat3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Cat3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Cat3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Cat3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Cat3().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.Box.Filler filler1; private javax.swing.JButton jButton2; private javax.swing.JButton jButtonCheck; private javax.swing.JFileChooser jFileChooser1; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton jRadioButtonAbstract; private javax.swing.JRadioButton jRadioButtonEncapsulation; private javax.swing.JRadioButton jRadioButtonInterface; private javax.swing.JRadioButton jRadioButtonPOLY; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables } <file_sep>/src/Computer_Category/Cat6.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Computer_Category; import QandA.front; import javax.swing.JOptionPane; /** * * @author micojasmin */ class hp5 extends hp4{ } public class Cat6 extends javax.swing.JFrame { hp5 h5 = new hp5(); /** * Creates new form Cat6 */ public Cat6() { initComponents(); jButtonCheck.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jRadioButtonTechAdvancement = new javax.swing.JRadioButton(); jRadioButtonScientific_Code = new javax.swing.JRadioButton(); jRadioButtonAllOfTheAbove = new javax.swing.JRadioButton(); jRadioButtonOOP = new javax.swing.JRadioButton(); jButtonCheck = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(0, 102, 102)); jPanel1.setLayout(null); jTextArea1.setEditable(false); jTextArea1.setBackground(new java.awt.Color(102, 102, 102)); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("sansserif", 0, 18)); // NOI18N jTextArea1.setForeground(new java.awt.Color(204, 204, 204)); jTextArea1.setRows(5); jTextArea1.setText("\nWhat difference does the 5th generation computer \nhave from other generation computers?"); jScrollPane1.setViewportView(jTextArea1); jPanel1.add(jScrollPane1); jScrollPane1.setBounds(20, 10, 450, 131); jRadioButtonTechAdvancement.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonTechAdvancement.setForeground(new java.awt.Color(255, 255, 255)); jRadioButtonTechAdvancement.setText("Technological Advancement"); jRadioButtonTechAdvancement.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonTechAdvancement.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonTechAdvancementActionPerformed(evt); } }); jPanel1.add(jRadioButtonTechAdvancement); jRadioButtonTechAdvancement.setBounds(30, 150, 226, 40); jRadioButtonScientific_Code.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonScientific_Code.setForeground(new java.awt.Color(255, 255, 255)); jRadioButtonScientific_Code.setText("Scientific Code"); jRadioButtonScientific_Code.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonScientific_Code.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonScientific_CodeActionPerformed(evt); } }); jPanel1.add(jRadioButtonScientific_Code); jRadioButtonScientific_Code.setBounds(300, 150, 170, 40); jRadioButtonAllOfTheAbove.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonAllOfTheAbove.setForeground(new java.awt.Color(255, 255, 255)); jRadioButtonAllOfTheAbove.setText("All of the Above"); jRadioButtonAllOfTheAbove.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonAllOfTheAbove.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonAllOfTheAboveActionPerformed(evt); } }); jPanel1.add(jRadioButtonAllOfTheAbove); jRadioButtonAllOfTheAbove.setBounds(300, 200, 170, 40); jRadioButtonOOP.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonOOP.setForeground(new java.awt.Color(255, 255, 255)); jRadioButtonOOP.setText("Object Oriented Programming"); jRadioButtonOOP.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonOOP.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonOOPActionPerformed(evt); } }); jPanel1.add(jRadioButtonOOP); jRadioButtonOOP.setBounds(30, 200, 230, 40); jButtonCheck.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButtonCheck.setText("Check"); jButtonCheck.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButtonCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCheckActionPerformed(evt); } }); jPanel1.add(jButtonCheck); jButtonCheck.setBounds(370, 260, 90, 35); jButton1.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButton1.setText("Back"); jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel1.add(jButton1); jButton1.setBounds(30, 260, 90, 35); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 321, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jRadioButtonTechAdvancementActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonTechAdvancementActionPerformed if (jRadioButtonTechAdvancement.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonAllOfTheAbove.setEnabled(false); jRadioButtonOOP.setEnabled(false); jRadioButtonScientific_Code.setEnabled(false); } else if (!jRadioButtonTechAdvancement.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonOOP.setEnabled(true); jRadioButtonAllOfTheAbove.setEnabled(true); jRadioButtonScientific_Code.setEnabled(true); } }//GEN-LAST:event_jRadioButtonTechAdvancementActionPerformed private void jRadioButtonScientific_CodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonScientific_CodeActionPerformed if (jRadioButtonScientific_Code.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonTechAdvancement.setEnabled(false); jRadioButtonOOP.setEnabled(false); jRadioButtonAllOfTheAbove.setEnabled(false); } else if (!jRadioButtonScientific_Code.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonOOP.setEnabled(true); jRadioButtonScientific_Code.setEnabled(true); jRadioButtonAllOfTheAbove.setEnabled(true); } }//GEN-LAST:event_jRadioButtonScientific_CodeActionPerformed private void jRadioButtonOOPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonOOPActionPerformed if (jRadioButtonOOP.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonTechAdvancement.setEnabled(false); jRadioButtonScientific_Code.setEnabled(false); jRadioButtonAllOfTheAbove.setEnabled(false); } else if (!jRadioButtonOOP.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonTechAdvancement.setEnabled(true); jRadioButtonScientific_Code.setEnabled(true); jRadioButtonAllOfTheAbove.setEnabled(true); } }//GEN-LAST:event_jRadioButtonOOPActionPerformed private void jRadioButtonAllOfTheAboveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonAllOfTheAboveActionPerformed if (jRadioButtonAllOfTheAbove.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonTechAdvancement.setEnabled(false); jRadioButtonOOP.setEnabled(false); jRadioButtonScientific_Code.setEnabled(false); } else if (!jRadioButtonAllOfTheAbove.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonOOP.setEnabled(true); jRadioButtonScientific_Code.setEnabled(true); jRadioButtonTechAdvancement.setEnabled(true); } }//GEN-LAST:event_jRadioButtonAllOfTheAboveActionPerformed private void jButtonCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCheckActionPerformed if (jRadioButtonTechAdvancement.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS CORRECT"); new Cat7().setVisible(true); setVisible(false); } else if (!jRadioButtonTechAdvancement.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS WRONG" + "\n" + --h5.life +" "+ "LIVES LEFT"); if (h5.life == 0) { h5.life=3; JOptionPane.showMessageDialog(rootPane, "GAME OVER!"); new front().setVisible(true); setVisible(false); } } }//GEN-LAST:event_jButtonCheckActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed new Cat5().setVisible(true); setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Cat6.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Cat6.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Cat6.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Cat6.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Cat6().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButtonCheck; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton jRadioButtonAllOfTheAbove; private javax.swing.JRadioButton jRadioButtonOOP; private javax.swing.JRadioButton jRadioButtonScientific_Code; private javax.swing.JRadioButton jRadioButtonTechAdvancement; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables } <file_sep>/src/Animals_Category/Animals02.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Animals_Category; import Computer_Category.*; import QandA.front; import javax.swing.JOptionPane; /** * * @author micojasmin */ class Anims2 extends Anims1{ } public class Animals02 extends javax.swing.JFrame { public Animals02() { initComponents(); jButtonCheck.setVisible(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jRadioButtonDir = new javax.swing.JRadioButton(); jRadioButtonDotNEt = new javax.swing.JRadioButton(); jbuttonSheep = new javax.swing.JRadioButton(); jRadioButtonC_lang = new javax.swing.JRadioButton(); jButtonCheck = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(51, 113, 138)); jPanel1.setLayout(null); jTextArea1.setEditable(false); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextArea1.setRows(5); jTextArea1.setText("What type of animals is not nocturnal?"); jTextArea1.setOpaque(true); jScrollPane1.setViewportView(jTextArea1); jPanel1.add(jScrollPane1); jScrollPane1.setBounds(24, 29, 422, 70); jRadioButtonDir.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonDir.setText("<NAME>"); jRadioButtonDir.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonDir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonDirActionPerformed(evt); } }); jPanel1.add(jRadioButtonDir); jRadioButtonDir.setBounds(30, 190, 200, 40); jRadioButtonDotNEt.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonDotNEt.setText("<NAME>"); jRadioButtonDotNEt.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonDotNEt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonDotNEtActionPerformed(evt); } }); jPanel1.add(jRadioButtonDotNEt); jRadioButtonDotNEt.setBounds(250, 130, 200, 40); jbuttonSheep.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jbuttonSheep.setText("<NAME>"); jbuttonSheep.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jbuttonSheep.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbuttonSheepActionPerformed(evt); } }); jPanel1.add(jbuttonSheep); jbuttonSheep.setBounds(250, 190, 200, 40); jRadioButtonC_lang.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonC_lang.setText("<NAME>"); jRadioButtonC_lang.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonC_lang.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonC_langActionPerformed(evt); } }); jPanel1.add(jRadioButtonC_lang); jRadioButtonC_lang.setBounds(30, 130, 200, 40); jButtonCheck.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButtonCheck.setText("Check"); jButtonCheck.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButtonCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCheckActionPerformed(evt); } }); jPanel1.add(jButtonCheck); jButtonCheck.setBounds(352, 250, 90, 35); jButton2.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButton2.setText("Back"); jButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel1.add(jButton2); jButton2.setBounds(24, 250, 90, 35); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 470, 300)); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jbuttonSheepActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbuttonSheepActionPerformed // TODO add your handling code here: if (jbuttonSheep.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonC_lang.setEnabled(false); jRadioButtonDir.setEnabled(false); jRadioButtonDotNEt.setEnabled(false); } else if (!jbuttonSheep.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonC_lang.setEnabled(true); jRadioButtonDotNEt.setEnabled(true); jRadioButtonDir.setEnabled(true); } }//GEN-LAST:event_jbuttonSheepActionPerformed private void jRadioButtonC_langActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonC_langActionPerformed if (jRadioButtonC_lang.isSelected()) { jButtonCheck.setVisible(true); jbuttonSheep.setEnabled(false); jRadioButtonDir.setEnabled(false); jRadioButtonDotNEt.setEnabled(false); } else if (!jRadioButtonC_lang.isSelected()) { jButtonCheck.setVisible(false); jbuttonSheep.setEnabled(true); jRadioButtonDotNEt.setEnabled(true); jRadioButtonDir.setEnabled(true); } }//GEN-LAST:event_jRadioButtonC_langActionPerformed private void jRadioButtonDotNEtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonDotNEtActionPerformed if (jRadioButtonDotNEt.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonC_lang.setEnabled(false); jRadioButtonDir.setEnabled(false); jbuttonSheep.setEnabled(false); } else if (!jRadioButtonDotNEt.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonC_lang.setEnabled(true); jbuttonSheep.setEnabled(true); jRadioButtonDir.setEnabled(true); } }//GEN-LAST:event_jRadioButtonDotNEtActionPerformed private void jRadioButtonDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonDirActionPerformed if (jRadioButtonDir.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonC_lang.setEnabled(false); jbuttonSheep.setEnabled(false); jRadioButtonDotNEt.setEnabled(false); } else if (!jRadioButtonDir.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonC_lang.setEnabled(true); jRadioButtonDotNEt.setEnabled(true); jbuttonSheep.setEnabled(true); } }//GEN-LAST:event_jRadioButtonDirActionPerformed private void jButtonCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCheckActionPerformed if (jbuttonSheep.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS CORRECT"); new Animals03().setVisible(true); setVisible(false); } else if (!jbuttonSheep.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS WRONG" + "\n" + --Anims2.life +" "+ "LIVES LEFT"); if (Anims2.life == 0) { Anims2.life=3; JOptionPane.showMessageDialog(rootPane, "GAME OVER!"); new front().setVisible(true); setVisible(false); } } }//GEN-LAST:event_jButtonCheckActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed new Animals01().setVisible(true); setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Animals02.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Animals02.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Animals02.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Animals02.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Animals02().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton2; private javax.swing.JButton jButtonCheck; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton jRadioButtonC_lang; private javax.swing.JRadioButton jRadioButtonDir; private javax.swing.JRadioButton jRadioButtonDotNEt; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JRadioButton jbuttonSheep; // End of variables declaration//GEN-END:variables } <file_sep>/src/Computer_Category/Cat5.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Computer_Category; import QandA.front; import javax.swing.JOptionPane; /** * * @author micojasmin */ class hp4 extends hp3{ } public class Cat5 extends javax.swing.JFrame { hp4 h4 = new hp4(); /** * Creates new form Cat5 */ public Cat5() { initComponents(); jButtonCheck.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jRadioButtonDataProcessing = new javax.swing.JRadioButton(); jRadioButtonTransmission = new javax.swing.JRadioButton(); jRadioButtonDataFlow = new javax.swing.JRadioButton(); jRadioButtonDataCapture = new javax.swing.JRadioButton(); jButtonCheck = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jRadioButton1.setText("jRadioButton1"); jRadioButton3.setText("jRadioButton3"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(51, 51, 51)); jPanel1.setLayout(null); jTextArea1.setEditable(false); jTextArea1.setBackground(new java.awt.Color(51, 51, 51)); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("sansserif", 0, 18)); // NOI18N jTextArea1.setForeground(new java.awt.Color(204, 204, 204)); jTextArea1.setRows(5); jTextArea1.setText("A computer assisted method for the \nrecording and analyzing of existing or \nhypothetical systems is?\n"); jScrollPane1.setViewportView(jTextArea1); jPanel1.add(jScrollPane1); jScrollPane1.setBounds(24, 21, 415, 110); jRadioButtonDataProcessing.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonDataProcessing.setForeground(new java.awt.Color(204, 204, 204)); jRadioButtonDataProcessing.setText("Data Processing"); jRadioButtonDataProcessing.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonDataProcessing.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonDataProcessingActionPerformed(evt); } }); jPanel1.add(jRadioButtonDataProcessing); jRadioButtonDataProcessing.setBounds(240, 210, 200, 40); jRadioButtonTransmission.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonTransmission.setForeground(new java.awt.Color(204, 204, 204)); jRadioButtonTransmission.setText("Data Transmission"); jRadioButtonTransmission.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonTransmission.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonTransmissionActionPerformed(evt); } }); jPanel1.add(jRadioButtonTransmission); jRadioButtonTransmission.setBounds(21, 149, 200, 40); jRadioButtonDataFlow.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonDataFlow.setForeground(new java.awt.Color(204, 204, 204)); jRadioButtonDataFlow.setText("Data Flow"); jRadioButtonDataFlow.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonDataFlow.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonDataFlowActionPerformed(evt); } }); jPanel1.add(jRadioButtonDataFlow); jRadioButtonDataFlow.setBounds(240, 150, 200, 40); jRadioButtonDataCapture.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jRadioButtonDataCapture.setForeground(new java.awt.Color(204, 204, 204)); jRadioButtonDataCapture.setText("Data Capture"); jRadioButtonDataCapture.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jRadioButtonDataCapture.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonDataCaptureActionPerformed(evt); } }); jPanel1.add(jRadioButtonDataCapture); jRadioButtonDataCapture.setBounds(20, 210, 200, 40); jButtonCheck.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButtonCheck.setText("Check"); jButtonCheck.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButtonCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCheckActionPerformed(evt); } }); jPanel1.add(jButtonCheck); jButtonCheck.setBounds(350, 270, 90, 35); jButton2.setFont(new java.awt.Font("sansserif", 0, 15)); // NOI18N jButton2.setText("Back"); jButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel1.add(jButton2); jButton2.setBounds(20, 270, 91, 35); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jRadioButtonTransmissionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonTransmissionActionPerformed if (jRadioButtonTransmission.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonDataCapture.setEnabled(false); jRadioButtonDataFlow.setEnabled(false); jRadioButtonDataProcessing.setEnabled(false); } else if (!jRadioButtonTransmission.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonDataCapture.setEnabled(true); jRadioButtonDataFlow.setEnabled(true); jRadioButtonDataProcessing.setEnabled(true); } }//GEN-LAST:event_jRadioButtonTransmissionActionPerformed private void jRadioButtonDataFlowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonDataFlowActionPerformed if (jRadioButtonDataFlow.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonDataCapture.setEnabled(false); jRadioButtonTransmission.setEnabled(false); jRadioButtonDataProcessing.setEnabled(false); } else if (!jRadioButtonDataFlow.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonDataCapture.setEnabled(true); jRadioButtonTransmission.setEnabled(true); jRadioButtonDataProcessing.setEnabled(true); } }//GEN-LAST:event_jRadioButtonDataFlowActionPerformed private void jRadioButtonDataCaptureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonDataCaptureActionPerformed if (jRadioButtonDataCapture.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonTransmission.setEnabled(false); jRadioButtonDataFlow.setEnabled(false); jRadioButtonDataProcessing.setEnabled(false); } else if (!jRadioButtonDataCapture.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonTransmission.setEnabled(true); jRadioButtonDataFlow.setEnabled(true); jRadioButtonDataProcessing.setEnabled(true); } }//GEN-LAST:event_jRadioButtonDataCaptureActionPerformed private void jRadioButtonDataProcessingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonDataProcessingActionPerformed if (jRadioButtonDataProcessing.isSelected()) { jButtonCheck.setVisible(true); jRadioButtonDataCapture.setEnabled(false); jRadioButtonDataFlow.setEnabled(false); jRadioButtonTransmission.setEnabled(false); } else if (!jRadioButtonDataProcessing.isSelected()) { jButtonCheck.setVisible(false); jRadioButtonDataCapture.setEnabled(true); jRadioButtonDataFlow.setEnabled(true); jRadioButtonTransmission.setEnabled(true); } }//GEN-LAST:event_jRadioButtonDataProcessingActionPerformed private void jButtonCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCheckActionPerformed if (jRadioButtonDataCapture.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS CORRECT"); new Cat6().setVisible(true); setVisible(false); } else if (!jRadioButtonDataCapture.isSelected()) { JOptionPane.showMessageDialog(rootPane, "YOUR ANSWER IS WRONG" + "\n" + --h4.life +" "+ "LIVES LEFT"); if (h4.life == 0) { h4.life=3; JOptionPane.showMessageDialog(rootPane, "GAME OVER!"); new front().setVisible(true); setVisible(false); } } }//GEN-LAST:event_jButtonCheckActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed new Cat4().setVisible(true); setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Cat5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Cat5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Cat5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Cat5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Cat5().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton2; private javax.swing.JButton jButtonCheck; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton3; private javax.swing.JRadioButton jRadioButtonDataCapture; private javax.swing.JRadioButton jRadioButtonDataFlow; private javax.swing.JRadioButton jRadioButtonDataProcessing; private javax.swing.JRadioButton jRadioButtonTransmission; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
3a614332184b60d05a9039779dd4b83e345ee140
[ "Java" ]
5
Java
JohnDominicJasmin/QuizGameInJava
f2f960710d999a536f97c146341107ad63c69af2
fd8e1167708b4768b7871a8f9bde658ed00408e4
refs/heads/master
<file_sep># bike Bike class in Python from Coding Dojo work <file_sep>class Bike(object): def __init__(self, price, max_speed): print 'New Bike' self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print "Bike Price:", self.price print "Bike Max Speed:", self.max_speed if self.miles > 0: print "Miles riden:", self.miles else: print "What, no miles riden?" # return True def reverse(self): if self.miles >= 5: self.miles = self.miles - 5 print "Reversing. Mile ridden now: ",self.miles def ride(self): self.miles = self.miles + 10 print "Riding, nice job. Miles riden now: ",self.miles bike1 = Bike(300, 20) count = 0 while count < 4: bike1.ride() count += 1 bike1.reverse() bike1.displayInfo() bike2 = Bike(400, 30) count2 = 0 count2a = 0 while count2 < 3: bike2.ride() count2 += 1 while count2a < 3: bike2.reverse() count2a += 1 bike2.displayInfo() bike3 = Bike(200, 15) count3 = 0 while count3 < 4: bike2.reverse() count3 += 1 bike3.displayInfo()
87c3d3c6208f4da9aa9751467ad6aff56822c93c
[ "Markdown", "Python" ]
2
Markdown
daver234/bike
9124d64cafa241503f44027b30756ce625cff0b8
9ce1e55de3d50cff679cb602b17db8f85b33a1da
refs/heads/master
<repo_name>nosthas/Rock-Paper-Scissors<file_sep>/js/game-logic.js // All code should be written in this file. // Player One Variable let playerOneMoveOneType; let playerOneMoveOneValue; let playerOneMoveTwoType; let playerOneMoveTwoValue; let playerOneMoveThreeType; let playerOneMoveThreeValue; // Player Two Variable let playerTwoMoveOneType; let playerTwoMoveOneValue; let playerTwoMoveTwoType; let playerTwoMoveTwoValue; let playerTwoMoveThreeType; let playerTwoMoveThreeValue; // setPlayerMoves Function const setPlayerMoves = function(player, moveOneType, moveOneValue, moveTwoType, moveTwoValue, moveThreeType, moveThreeValue){ // Check if Value or Move is missing if (moveOneType === undefined || moveOneValue === undefined || moveTwoType === undefined || moveTwoValue === undefined || moveThreeType === undefined || moveThreeValue === undefined){ return; } // Check if Type is valid if ((moveOneType !== 'rock' && moveOneType !== 'paper' && moveOneType !== 'scissors') || (moveTwoType !== 'rock' && moveTwoType !== 'paper' && moveTwoType !== 'scissors') || (moveThreeType !== 'rock' && moveThreeType !== 'paper' && moveThreeType !== 'scissors')) { return; } // Check if Move is Greater than One if (moveOneValue < 1 || moveTwoValue < 1 || moveThreeValue < 1){ return; } // Check if Move Sum is less than 99 if (moveOneValue + moveTwoValue + moveThreeValue > 99){ return; } // Check for Player Type if (player === 'Player One') { playerOneMoveOneType = moveOneType; playerOneMoveOneValue = moveOneValue; playerOneMoveTwoType = moveTwoType; playerOneMoveTwoValue = moveTwoValue; playerOneMoveThreeType = moveThreeType; playerOneMoveThreeValue = moveThreeValue; } else if (player === 'Player Two') { playerTwoMoveOneType = moveOneType; playerTwoMoveOneValue = moveOneValue; playerTwoMoveTwoType = moveTwoType; playerTwoMoveTwoValue = moveTwoValue; playerTwoMoveThreeType = moveThreeType; playerTwoMoveThreeValue = moveThreeValue; } else { return false; } }; // getRoundWinner function const getRoundWinner = function(round) { // if (!playerOneMoveType || !playerOneMoveValue || !playerTwoMoveType || // !playerTwoMoveValue) { // return null; // } if (round && round === 1){ if(playerOneMoveOneType === playerTwoMoveOneType){ if(playerOneMoveOneValue > playerTwoMoveOneValue){ return 'Player One'; } else if (playerOneMoveOneValue < playerTwoMoveOneValue){ return 'Player Two'; } else { return 'Tie'; } } else { if(playerOneMoveOneType === 'rock') { if(playerTwoMoveOneType === 'scissors'){ return 'Player One'; } else { return 'Player Two'; } } else if(playerOneMoveOneType === 'paper') { if(playerTwoMoveOneType === 'rock'){ return 'Player One'; } else { return 'Player Two'; } } else if(playerOneMoveOneType === 'scissors') { if(playerTwoMoveOneType === 'paper'){ return 'Player One'; } else { return 'Player Two'; } } } } else if (round && round === 2){ if(playerOneMoveTwoType === playerTwoMoveTwoType){ if(playerOneMoveTwoValue > playerTwoMoveTwoValue){ return 'Player One'; } else if (playerOneMoveTwoValue < playerTwoMoveTwoValue){ return 'Player Two'; } else { return 'Tie'; } } else { if(playerOneMoveTwoType === 'rock') { if(playerTwoMoveTwoType === 'scissors'){ return 'Player One'; } else { return 'Player Two'; } } else if(playerOneMoveTwoType === 'paper') { if(playerTwoMoveTwoType === 'rock'){ return 'Player One'; } else { return 'Player Two'; } } else if(playerOneMoveTwoType === 'scissors') { if(playerTwoMoveTwoType === 'paper'){ return 'Player One'; } else { return 'Player Two'; } } } } else if (round && round === 3){ if(playerOneMoveThreeType === playerTwoMoveThreeType){ if(playerOneMoveThreeValue > playerTwoMoveThreeValue){ return 'Player One'; } else if (playerOneMoveThreeValue < playerTwoMoveThreeValue){ return 'Player Two'; } else { return 'Tie'; } } else { if(playerOneMoveThreeType === 'rock') { if(playerTwoMoveThreeType === 'scissors'){ return 'Player One'; } else { return 'Player Two'; } } else if(playerOneMoveThreeType === 'paper') { if(playerTwoMoveThreeType === 'rock'){ return 'Player One'; } else { return 'Player Two'; } } else if(playerOneMoveThreeType === 'scissors') { if(playerTwoMoveThreeType === 'paper'){ return 'Player One'; } else { return 'Player Two'; } } } } else if (!round || round > 3 || round < 1){ return null; } }; // getGameWinner Function const getGameWinner = function(){ if (!playerOneMoveOneType || !playerOneMoveTwoType || !playerOneMoveThreeType || !playerOneMoveOneValue || !playerOneMoveTwoValue || !playerOneMoveThreeValue || !playerTwoMoveOneType || !playerTwoMoveTwoType || !playerTwoMoveThreeType || !playerTwoMoveOneValue || !playerTwoMoveTwoValue || !playerTwoMoveThreeValue) { return null; } let p1 = 0; let p2 = 0; for (let i = 1; i <= 3; i++) { if(getRoundWinner(i) === 'Player One'){ p1++; } else if (getRoundWinner(i) === 'Player Two'){ p2++; } else if (getRoundWinner(i) === 'Tie'){ p1++; p2++; } } if (p1 > p2) { return 'Player One'; } else if (p1 < p2){ return 'Player Two'; } else { return 'Tie'; } } const setComputerMoves = function(){ const moves = ['rock','paper','scissors'] playerTwoMoveOneType = moves[Math.floor(Math.random()*3)]; playerTwoMoveTwoType = moves[Math.floor(Math.random()*3)]; playerTwoMoveThreeType = moves[Math.floor(Math.random()*3)]; //console.log(playerTwoMoveOneType, playerTwoMoveTwoType, playerTwoMoveThreeType); playerTwoMoveOneValue = Math.floor(Math.random() * 99); playerTwoMoveTwoValue = Math.floor(Math.random() * (99 - playerTwoMoveOneValue)); playerTwoMoveThreeValue = 99 - (playerTwoMoveOneValue + playerTwoMoveTwoValue); //console.log('Values: ' + playerTwoMoveOneValue + ', ' + playerTwoMoveTwoValue + ', '+ playerTwoMoveThreeValue); //console.log('Equals: ' + (playerTwoMoveOneValue + playerTwoMoveTwoValue + playerTwoMoveThreeValue)); };
40699a329faea8e7f714e9ddfefd814d8cf33873
[ "JavaScript" ]
1
JavaScript
nosthas/Rock-Paper-Scissors
8e523fd274159fbf276bb7e6c9a2b5905de1075e
37322699d5ccbce8cde77791b7c5ef5e4d6b4b94
refs/heads/master
<file_sep><?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; //Request::setTrustedProxies(array('127.0.0.1')); $app->match('/', function (Request $request) use ($app) { $form = $app['form.factory']->createBuilder(FormType::class) ->add('dni', TextType::class, array( 'attr' => array( 'class' => 'form-control', 'placeholder' => 'INGRESE SU DNI', ) )) ->add('submit', SubmitType::class, [ 'label' => 'Siguiente', 'attr' => array( 'class' => 'btn btn-success btn-lg', ) ]) ->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); return $app->redirect('tasas/'.$data['dni']); } return $app['twig']->render('index.html.twig', array( 'form' => $form->createView(), )); }) ->bind('homepage') ; $app->match('/tasas/{dni}', function (Request $request, $dni) use ($app) { return $app['twig']->render('tasas.html.twig', array()); }) ->bind('tasas') ; $app->error(function (\Exception $e, Request $request, $code) use ($app) { if ($app['debug']) { return; } // 404.html, or 40x.html, or 4xx.html, or error.html $templates = array( 'errors/'.$code.'.html.twig', 'errors/'.substr($code, 0, 2).'x.html.twig', 'errors/'.substr($code, 0, 1).'xx.html.twig', 'errors/default.html.twig', ); return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code); });
dc7185741fe16c168e2dc27a0862649f82f03ac4
[ "PHP" ]
1
PHP
aleher86/totem-ticket
abcc89818091cbf8f99b3858580469535f2334c7
fa8340db88b48fad60d2d68833b8451c47b8c94d
refs/heads/master
<repo_name>gilesw/aws-carb<file_sep>/lib/aws-carb/monkey_patches.rb #!/usr/bin/env ruby # monkeypatch shell spinner to fix some bugs.. module ShellSpinner class Runner def wrap_block(text = nil, colorize = true, &block) with_message(text) { with_spinner(&block) } end private # FIXME: better way to disable colours? #colorize = colorize ? lambda { |s,c| s.colorize(c) } : lambda { |s,c| s } #colorize.call(s, :red) def with_message(text = nil, colorize = false) begin print "#{text}... " unless text.nil? catch_user_output { yield } print "done\n".colorize(:green) unless text.nil? print user_output.colorize(:blue) rescue Exception => e print "\bfail\n".colorize(:red) unless text.nil? print user_output.colorize(:blue) re_raise_exception e end end end end def ShellSpinner(text = nil, colorize = true, &block) runner = ShellSpinner::Runner.new runner.wrap_block(text, colorize, &block) end # override the output from optparse to be a bit more aesthetically pleasing module Subcommands def print_actions subcommand_help = "#{'SUBCOMMAND'.colorize({:color => :white, :mode => :bold})}\n" @commands.each_pair do |c, opt| subcommand_help << "\n #{c} - #{opt.call.description}" end unless @aliases.empty? subcommand_help << "\n\naliases: \n" @aliases.each_pair { |name, val| subcommand_help << " #{name} - #{val}\n" } end subcommand_help << "\n\n help <command> - for more information on a specific command\n\n" end def command *names name = names.shift @commands ||= {} @aliases ||= {} names.each { |n| @aliases[n.to_s] = name.to_s } if names.length > 0 opt = lambda do OptionParser.new do |opts| yield opts opts.banner << "OPTIONS" end end @commands[name.to_s] = opt end end <file_sep>/lib/aws-carb/config.rb #!/usr/bin/env ruby module AWSCarb class Config include Singleton attr_accessor :config def create(cli_arguments) @config = load_file(cli_arguments.global.config_file) merge_cli_arguments_with_config(cli_arguments) establish_hostname_and_domain check_route53_settings end def check_route53_settings die 'route53: no zone id specified!' if @config[:route53][:zone].nil? die 'route53: no ttl specified!' if @config[:route53][:zone].nil? end def merge_cli_arguments_with_config(cli_arguments) begin config_sections = [:common, :general, :ec2, :route53, :user_data_template_variables, :user_data_template] # special condition: common command line arguments are shared between all instances first.. if cli_arguments.subcommand.config_overrides.common_variables @config[:common] ||= {} @config[:common].update cli_arguments.subcommand.config_overrides.common_variables end # all sections share 'common' variables.. config_sections.each do |section| @config[section] ||= {} @config[section].update @config[:common] end # merge the config overrides hashes into config if cli_arguments.subcommand.config_overrides cli_arguments.subcommand.config_overrides.marshal_dump.each do |key, value| next if key == :common # key differs from command line argument - we lose the _variables suffix config_key = key.to_s.gsub('_variables', '').to_sym @config[config_key] ||= {} @config[config_key].update cli_arguments.subcommand.config_overrides.send(key) end end # merge the convenience arguments.. config_sections.each do |section| if cli_arguments.subcommand.send(section.to_s) @config[section].update cli_arguments.subcommand.send(section.to_s).marshal_dump end end rescue => e puts "# failed to merge cli arguments with config" die e end end def load_file(cli_argument_config_file) # allow forcing of no config file.. return if cli_argument_config_file.empty? config_file = cli_argument_config_file begin @config = ActiveSupport::HashWithIndifferentAccess.new(YAML.load_file(config_file)) rescue => e puts "# failed to load config file: '#{config_file}'" die e end end # when looking for a key, check 'common' section first, then override if a value # in the supplied context is found.. def find_with_context(key, context) return @config[context][key] if @config[context][key] return @config[:common][key] if @config[:common][key] return nil end def [](key) @config[key] end # try and work out the hostname, presidence is: # # * config file # * user_data_template_variables cli args # # note: raw user_data is not checked (not to be confused with user_data_template or user_data_template_variables..) # def establish_hostname_and_domain ShellSpinner "# checking whether hostname and domain have been set", false do hostname, domain = nil @config[:route53][:hostname] = find_with_context(:hostname, :user_data_template_variables) if find_with_context(:hostname, :user_data_template_variables) @config[:route53][:domain] = find_with_context(:domain, :user_data_template_variables) if find_with_context(:domain, :user_data_template_variables) @config[:route53][:hostname] = find_with_context(:hostname, :route53) if find_with_context(:hostname, :route53) @config[:route53][:domain] = find_with_context(:domain, :route53) if find_with_context(:domain, :route53) help = <<-HEREDOC.strip_heredoc # # checked: # 'common', 'user_data_template_variables', # and 'route53' sections of config # --common-variables, --route53-variables, # and --user-data-template-variables # # route53 dynamic DNS will not be updated! HEREDOC domain = @config[:route53][:domain] hostname = @config[:route53][:hostname] if domain.nil? and hostname.nil? debug <<-HEREDOC.strip_heredoc # WARNING: hostname and domain not found" #{help} HEREDOC elsif domain and hostname.nil? debug <<-HEREDOC.strip_heredoc # WARNING: hostname not found #{help} HEREDOC elsif domain.nil? and hostname debug <<-HEREDOC.strip_heredoc # WARNING: domain not found #{help} HEREDOC else debug <<-HEREDOC.strip_heredoc # found hostname and domain: hostname: #{hostname} domain: #{domain} HEREDOC @config[:route53][:new_dns_records] = { :public => { :alias => "#{hostname}.#{domain}.", :target => nil }, :private => { :alias => "#{hostname}-private.#{domain}.", :target => nil } } end end puts end def display puts "# config:" ap @config puts end end end <file_sep>/lib/aws-carb/log4r.rb #!/usr/bin/env ruby logger = Log4r::Logger.new('carb') logger.outputters << Log4r::Outputter.stdout logger.outputters << Log4r::FileOutputter.new('carb', :filename => 'carb.log') def debug(message) logger.debug(message) end def info(message) logger.info(message) end def warn(message) logger.warn(message) end def error(message) logger.error(message) end def fatal(message) logger.fatal(message) end <file_sep>/lib/aws-carb/user_data.rb #!/usr/bin/env ruby module AWSCarb class UserData include Singleton attr_accessor :combined_user_data def create(config) user_data_template_resolved = resolve_template(config) @combined_user_data = combine_user_data(config, user_data_template_resolved) return @combined_user_data end def resolve_template(config) user_data_template = nil resolved_template = nil # FIXME: blank templates / empty templates / no template should work.. return nil unless config[:ec2] and config[:user_data_template][:file] ShellSpinner "# loading template", false do begin template_file = config[:user_data_template][:file] raise ArgumentError, "no such file: #{template_file}" unless File.exist?(template_file) user_data_template = File.read(template_file) rescue => e puts "# unable to open template file:" die e end end puts ShellSpinner "# parsing template" do begin resolved_template = Erubis::Eruby.new(user_data_template).result(config[:user_data_template_variables]) rescue => e puts "# failed to resolve variables in user_data_template:" die e end end puts return resolved_template end def combine_user_data(config, user_data_template_resolved) # if user_data_template and user_data are supplied then combine them, otherwise just # use user_data (which is empty by default) begin if config[:ec2].andand[:user_data] user_data = config[:ec2][:user_data] end if ! user_data_template_resolved.nil? and ! user_data.nil? puts "# combining user_data with user_data_template" user_data = user_data_template_resolved + user_data puts elsif ! user_data_template_resolved.nil? and user_data.nil? debug "# no raw user_data parsed in" user_data = user_data_template_resolved debug elsif user_data.nil? debug "# no user_data or user_data_template specified on the command line" user_data = "" debug else debug "# using user_data from cli argument" debug end rescue => e puts "# failed to combine user_data!" die e end return user_data end def display return if @combined_user_data.nil? puts "# --- beginning of user_data ---" puts begin puts @combined_user_data rescue => e puts "error: could not display user_data!" puts e end puts puts "# --- end of user_data ---" puts end end end <file_sep>/lib/aws-carb/helpers.rb #!/usr/bin/env ruby def die(error) if $GLOBAL_VERBOSE and error.respond_to?('backtrace') puts "# stack trace:" puts error.backtrace puts end puts "error: #{error}" exit 1 end def debug(message = nil) puts message if @GLOBAL_VERBOSE end <file_sep>/lib/aws-carb/cli_argument_parser.rb #!/usr/bin/env ruby include Subcommands module AWSCarb module CliArgumentParser def self.parse cli_arguments = OpenStruct.new cli_arguments.global = OpenStruct.new cli_arguments.subcommand = OpenStruct.new cli_arguments.subcommand.user_data_template = OpenStruct.new cli_arguments.subcommand.config_overrides = OpenStruct.new cli_arguments.subcommand.ec2 = OpenStruct.new cli_arguments.subcommand.route53 = OpenStruct.new cli_arguments.subcommand.purge = OpenStruct.new indent = ' ' * 10 banner = <<-HEREDOC.strip_heredoc #{File.basename($0)}(1) #{'NAME'.colorize({:color => :white, :mode => :bold})} carb #{'DESCRIPTION'.colorize({:color => :white, :mode => :bold})} amazon web services - cloudinit and route53 bootstrap HEREDOC # these are the only defaults we need to bother setting since they get used before we load the config file.. cli_arguments.global.verbose = false cli_arguments.global.config_file = File.join(Dir.home, ".carb/config", "config.yaml") global_options do |option| option.summary_width = 50 option.summary_indent = ' ' synopsis = <<-HEREDOC.strip_heredoc #{"SYNOPSIS".colorize({:color => :white, :mode => :bold})} #{File.basename($0)} [global options] [subcommand [options]] HEREDOC option.banner = banner + synopsis option.separator "#{'GLOBAL OPTIONS'.colorize({:color => :white, :mode => :bold})}" option.separator "" option.on("-c", "--config=FILE", "") do |file| cli_arguments.global.config_file = file end option.separator "" option.on("-v", "--verbose", "") do |boolean| cli_arguments.global.verbose = boolean # FIXME: use a stupidly named global(!!!!!) variable to avoid clashing with rubys $VERBOSE $GLOBAL_VERBOSE = boolean end option.separator "" option.separator " -h, --help" end command :create do |option| option.summary_width = 50 option.summary_indent = ' ' synopsis = <<-HEREDOC.strip_heredoc #{'SYNOPSIS'.colorize({:color => :white, :mode => :bold})} #{File.basename($0)} create [options] HEREDOC option.banner = banner + synopsis option.description = "create an ec2 instance" option.separator "" option.separator " user_data tempate options:" option.separator "" option.on "--user-data-template=FILE", "\n\n#{indent}user data template" do |user_data_template| cli_arguments.subcommand.user_data_template.file = user_data_template end option.separator "" option.on "--show-parsed-template=BOOLEAN", "\n\n#{indent}display parsed template file" do |show_parsed_template| cli_arguments.subcommand.user_data_template.show_parsed_template = show_parsed_template end option.separator "" option.separator "" option.separator " config file overrides:" option.separator "" option.on "--common-variables=HASH", String, "\n\n#{indent}common variables" do |common_variables| begin data = eval(common_variables) raise unless data.class == Hash cli_arguments.subcommand.config_overrides.common_variables = ActiveSupport::HashWithIndifferentAccess.new(data) rescue => e puts "# could not parse argument for --common-variables, is it a valid hash?" die e end end option.separator "" option.on "--general-variables=HASH", String, "\n\n#{indent}general variables" do |general_variables| begin data = eval(general_variables) raise unless data.class == Hash cli_arguments.subcommand.config_overrides.general_variables = ActiveSupport::HashWithIndifferentAccess.new(data) rescue => e puts "# could not parse argument for --general-variables, is it a valid hash?" die e end end option.separator "" option.on "--ec2-variables=HASH", String, "\n\n#{indent}ec2 variables" do |ec2_variables| begin data = eval(ec2_variables) raise unless data.class == Hash cli_arguments.subcommand.config_overrides.ec2_variables = ActiveSupport::HashWithIndifferentAccess.new(data) rescue => e puts "# could not parse argument for --ec2-variables, is it a valid hash?" die e end end option.separator "" option.on "--route53-variables=HASH", String, "\n\n#{indent}route53 variables" do |route53_variables| begin data = eval(route53_variables) raise unless data.class == Hash cli_arguments.subcommand.config_overrides.route53_variables = ActiveSupport::HashWithIndifferentAccess.new(data) rescue => e puts "# could not parse argument for --route53-variables, is it a valid hash?" die e end end option.separator "" option.on "--user-data-template-variables=HASH", String, "\n\n#{indent}user data template variables" do |user_data_template_variables| begin data = eval(user_data_template_variables) raise unless data.class == Hash cli_arguments.subcommand.config_overrides.user_data_template_variables = ActiveSupport::HashWithIndifferentAccess.new(data) rescue => e puts "# could not parse argument for --user-data-template-variables, is it a valid hash?" die e end end option.separator "" option.separator " long descriptions for these parameters can be found here:\n http://<TODO>" option.separator "" option.separator "" option.separator " ec2 config convenience arguments:" option.separator "" option.on "--ec2-access-key-id=STRING", "\n\n#{indent}access key id".downcase do |access_key_id| cli_arguments.subcommand.ec2.access_key_id = access_key_id end option.separator "" option.on "--ec2-secret-access-key=STRING", "\n\n#{indent}secret access key".downcase do |secret_access_key| cli_arguments.subcommand.ec2.secret_access_key = secret_access_key end option.separator "" option.on "--image-id=STRING", "\n\n#{indent}ID of the AMI you want to launch.".downcase do |image_id| cli_arguments.subcommand.ec2.image_id = image_id end option.separator "" option.on "--instance-type=STRING", "\n\n#{indent}The type of instance to launch, for example \"m1.small\".".downcase do |instance_type| cli_arguments.subcommand.ec2.instance_type = instance_type end option.separator "" option.on "--key-name=STRING", "\n\n#{indent}The name of the key pair to use.".downcase do |key_name| cli_arguments.subcommand.ec2.key_name = key_name end option.separator "" block_device_help = <<-HEREDOC.strip_heredoc virtual_name - (String) Specifies the virtual device name. device_name - (String) Specifies the device name (e.g., /dev/sdh). ebs - (Hash) Specifies parameters used to automatically setup Amazon\n#{indent} EBS volumes when the instance is launched. snapshot_id - (String) The ID of the snapshot from which the volume will be created. volume_size - (Integer) The size of the volume, in gigabytes. delete_on_termination - (Boolean) Specifies whether the Amazon EBS volume is\n#{indent} deleted on instance termination. volume_type - (String) Valid values include: standard io1 iops - (Integer) no_device - (String) Specifies the device name to suppress during instance launch. HEREDOC block_device_help = block_device_help.lines.map { |line| indent + " #{line}" } block_device_help = "\n\n#{indent}Specifies how block devices are exposed to the instance. Each mapping\n#{indent}is made up of a virtualName and a deviceName.\n" + block_device_help.join.downcase option.on "--block-device-mappings=ARRAY", block_device_help do |mappings_data| begin mappings = eval(mappings_data) raise "parsed value isn't an Array!" unless mappings.class == Array mappings.map! do |mapping| raise "mapping data isn't a hash!" unless mapping.class == Hash ActiveSupport::HashWithIndifferentAccess.new(mapping) end cli_arguments.subcommand.ec2.block_device_mappings = mappings rescue => e puts "# could not parse argument for --block-device-mappings, are your mappings" puts "# valid hashes contained in an array and are the hash values properly quoted?" die e end end option.separator "" option.on "--user-data=STRING", "\n\n#{indent}Arbitrary user data. note: this is merged with user_data_template if also specified.".downcase do |user_data| cli_arguments.subcommand.ec2.user_data = user_data end option.separator "" option.on "--iam-instance-profile=STRING", "\n\n#{indent}the name or ARN of an IAM instance profile.".downcase do |profile| cli_arguments.subcommand.ec2.iam_instance_profile = profile end option.separator "" option.on "--monitoring-enabled=BOOLEAN", "\n\n#{indent}enable CloudWatch monitoring.".downcase do |boolean| cli_arguments.subcommand.ec2.monitoring_enabled = boolean end option.separator "" option.on "--availability-zone=STRING", "\n\n#{indent}availability zone.".downcase do |zone| cli_arguments.subcommand.ec2.availability_zone = zone end option.separator "" option.on "--security-groups=ARRAY", Array, "\n\n#{indent}Security groups. can be a single value or an array of values.\n#{indent}Values should be space deliminated group name strings.".downcase do |groups| cli_arguments.subcommand.ec2.security_groups = groups end option.separator "" option.on "--security-group-ids=<ID>,<ID>,..", Array, "\n\n#{indent}security_group_ids accepts a single ID or an array of\n#{indent}security group IDs.".downcase do |group_ids| cli_arguments.subcommand.ec2.security_group_ids = group_ids end option.separator "" option.on "--disable-api-termination=BOOLEAN", "\n\n#{indent}instance termination via the instance API.".downcase do |api_termination_data| api_termination = case api_termination_data when "true" true when "false" false else raise ArgumentError, "unknown parameter for --disable-api-termination: #{api_termination_data}" end cli_arguments.subcommand.ec2.disable_api_termination = api_termination end option.separator "" option.on "--instance-initiated-shutdown-behavior=STRING", "\n\n#{indent}instance termination on instance-initiated shutdown".downcase do |shutdown_behavior| cli_arguments.subcommand.ec2.instance_initiated_shutdown_behavior = shutdown_behavior end option.separator "" option.on "--subnet=STRING", "\n\n#{indent}The VPC Subnet (or subnet id string) to launch the instance in.".downcase do |subnet| cli_arguments.subcommand.ec2.subnet = subnet end option.separator "" option.on "--private-ip-address=STRING", "\n\n#{indent}If you're using VPC, you can optionally use this option to assign the\n#{indent}instance a specific available IP address from the subnet (e.g., '10.0.0.25').\n#{indent}This option is not valid for instances launched outside a VPC (i.e.\n#{indent}those launched without the :subnet option).".downcase do |ip| cli_arguments.subcommand.ec2.private_ip_address = ip end option.separator "" option.on "--associate-public-ip-address=STRING", "\n\n#{indent}This option isn't documented but appears to exist in the code. For use when creating instances in a VPC.".downcase do |ip| cli_arguments.subcommand.ec2.associate_public_ip_address = ip end option.separator "" option.on "--dedicated-tenancy=BOOLEAN", "\n\n#{indent}Instances with dedicated tenancy will not share physical hardware with\n#{indent}instances outside their VPC. NOTE: Dedicated tenancy incurs an \n#{indent}additional service charge. This option is not valid for\n#{indent}instances launched outside a VPC (e.g.those launched without the :subnet option).".downcase do |tenancy| cli_arguments.subcommand.ec2.dedicated_tenancy = tenancy end option.separator "" option.on "--ebs-optimized=BOOLEAN", "\n\n#{indent}EBS-Optimized instances enable Amazon EC2 instances to fully utilize the\n#{indent}IOPS provisioned on an EBS volume. EBS-optimized instances deliver dedicated\n#{indent}throughput between Amazon EC2 and Amazon EBS, with options between\n#{indent}500 Mbps and 1000 Mbps depending on the instance type used. When attached\n#{indent}to EBS-Optimized instances, Provisioned IOPS volumes are designed to\n#{indent}deliver within 10% of their provisioned performance 99.9% of the time.\n#{indent}NOTE: EBS Optimized instances incur an additional service charge.\n#{indent}This option is only valid for certain instance types.".downcase do |ebs_optimized| cli_arguments.subcommand.ec2.ebs_optimized = ebs_optimized end option.separator "" option.separator " long descriptions for these parameters can be found here:\n http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/EC2/InstanceCollection.html" option.separator "" option.separator "" option.separator " route53 convenience arguments:" option.separator "" option.on "--route53-access-key-id=STRING", "\n\n#{indent}access key id".downcase do |access_key_id| cli_arguments.subcommand.route53.access_key_id = access_key_id end option.separator "" option.on "--route53-secret-access-key=STRING", "\n\n#{indent}secret access key".downcase do |secret_access_key| cli_arguments.subcommand.route53.secret_access_key = secret_access_key end option.separator "" option.on "--zone=STRING", "\n\n#{indent}route53 zone".downcase do |zone| cli_arguments.subcommand.route53.route = route end option.separator "" option.on "--ttl=STRING", "\n\n#{indent}ttl".downcase do |ttl| cli_arguments.subcommand.route53.ttl = ttl end option.separator "" end command :purge do |option| option.summary_width = 50 option.summary_indent = ' ' synopsis = <<-HEREDOC.strip_heredoc #{'SYNOPSIS'.colorize({:color => :white, :mode => :bold})} #{File.basename($0)} create [options] HEREDOC option.banner = banner + synopsis option.description = "purge an ec2 instance" option.separator "" option.separator " purge options:" option.separator "" option.on "--hostname=HOSTNAME", "\n\n#{indent}hostname of machine to purge" do |hostname| cli_arguments.subcommand.purge.hostname = hostname end option.separator "" option.on "--id=id", "\n\n#{indent}id of machine to purge" do |id| cli_arguments.subcommand.purge.id = id end option.separator "" end begin subcommand = opt_parse # show help if no arguments passed in if subcommand.nil? add_subcommand_help puts @global exit 1 end if ARGV.length > 0 raise ArgumentError, "unknown command line argument(s): #{ARGV.inspect.to_s}" end rescue => e puts e exit 1 end return subcommand.to_sym, cli_arguments end end end <file_sep>/lib/aws-carb/services/ec2.rb #!/usr/bin/env ruby module AWSCarb module Services class Ec2 include Singleton attr_reader :instance def client(config) @config = config @instance = nil ShellSpinner "# configuring ec2 session", false do begin @client = AWS::EC2.new(config[:ec2]) @client.regions[@config.find_with_context(:region, :ec2)] puts rescue => e puts "error: failed to create ec2 session, check that you're using a valid region!" die e end end end def instance_id(hostname) instances = @client.client.describe_instances.to_hash # find out if an instances Name tag matches the supplied hostname instances[:reservation_set].each do |reservation| reservation[:instances_set].each do |instance| instance[:tag_set].each do |tag| return instance[:instance_id] if tag[:key] == "Name" and tag[:value] == hostname end end end raise ArgumentError, "could not find instance with Name tag that matches the specified hostname!" end def delete_instance_by_hostname(hostname) delete_instance_by_id(instance_id(hostname)) end def delete_instance_by_id(id) ShellSpinner "# delete instance", false do begin instance = @client.instnaces[id] instance.exists? instance.api_termination_disabled? instance.delete end end end def create_instance ShellSpinner "# creating instance", false do # FIXME: this is naff begin allowed_ec2_parameters = [ :count, :iam_instance_profile, :block_device_mappings, :virtual_name, :device_name, :ebs, :snapshot_id, :volume_size, :delete_on_termination, :volume_type, :iops, :no_device, :monitoring_enabled, :availability_zone, :image_id, :key_name, :key_pair, :security_groups, :security_group_ids, :user_data, :instance_type, :kernel_id, :ramdisk_id, :disable_api_termination, :instance_initiated_shutdown_behavior, :subnet, :private_ip_address, :dedicated_tenancy, :ebs_optimized, :associate_public_ip_address, ] ec2_config = {} allowed_ec2_parameters.each do |param| ec2_config[param] = @config[:ec2][param] if @config[:ec2][param] end @instance = @client.instances.create(ec2_config) rescue => e puts "# failed to create new ec2 instance:" die e end end puts ShellSpinner "# awaiting build completion", false do sleep 1 until @instance.status != :pending end puts ShellSpinner "# awaiting running state", false do sleep 1 until @instance.status == :running end puts end end end end <file_sep>/lib/aws-carb/services/route53.rb #!/usr/bin/env ruby module AWSCarb # named so as not to clash with AWS module from aws-sdk module Services class Route53 include Singleton def client(config) @config = config begin ShellSpinner "# configuring route53 session", false do @client = ::AWS::Route53.new(@config[:route53]) end puts rescue => e puts "error: failed to create route53 session" die e end end def check_hostname_and_domain_availability ShellSpinner "# checking to see if hostname and domain have been configured", false do if @config[:route53].andand[:new_dns_records] else debug "# skipping route53 check since either hostname or domain wasn't found:" debug "hostname not found" if hostname.nil? debug "domain not found" if domain.nil? debug end end puts return unless @config[:route53].andand[:new_dns_records] ShellSpinner "# checking to see if record exists", false do begin record_sets = @client.hosted_zones[@config[:route53][:zone]].resource_record_sets @config[:route53][:new_dns_records].each_value do |record| die "error: record already exists: #{record[:alias]}" if record_sets[record[:alias], 'A'].exists? end rescue => e puts "# could not check to see if DNS records exist:" die e end end puts end def create_records(ec2) if @config[:route53][:new_dns_records].nil? debug "# skipping creation of new records on route53" debug return end ShellSpinner "# updating route53 with new A records for host", false do @config[:route53][:new_dns_records][:public][:target] = ec2.instance.ip_address @config[:route53][:new_dns_records][:private][:target] = ec2.instance.private_ip_address record_sets = @client.hosted_zones[@config[:route53][:zone]].resource_record_sets @config[:route53][:new_dns_records].each do |record_scope, record| new_record = record_sets[record[:alias], 'A'] raise "error: '#{record_scope}' record already exists: #{record[:alias]}" if new_record.exists? # this could be blank if we're adding to a vpc and the instance has no external IP next if record[:target].nil? new_record = { :name => record[:alias], :type => 'A', :options => { :ttl => @config[:route53][:ttl], :resource_records => [{ :value => record[:target] }] } } record_sets.create(new_record[:name], new_record[:type], new_record[:options]) end end puts end end end end <file_sep>/lib/aws-carb.rb #!/usr/bin/env ruby # require first to instantiate logger before anything else require 'log4r' require 'aws-carb/log4r' require 'aws-sdk' require 'yaml' require 'erubis' require 'awesome_print' require 'securerandom' require 'shell-spinner' require 'active_support' require 'active_support/core_ext' require 'active_support/core_ext/hash' require 'active_support/hash_with_indifferent_access' require 'active_support/core_ext/string/strip' require 'active_support/core_ext/hash/keys' require 'ostruct' require 'subcommand' require 'singleton' require 'andand' require 'colorize' require 'aws-carb/user_data' require 'aws-carb/monkey_patches' require 'aws-carb/config' require 'aws-carb/version' require 'aws-carb/cli_argument_parser' require 'aws-carb/helpers' require 'aws-carb/services/route53' require 'aws-carb/services/ec2' include ActiveSupport # module is broken up into: # # AWSCarb.* - main methods # AWSCarb::CliArugmentParser - argument parsing # AWSCarb::Config - argument checking / config checking # AWSCarb::UserData - parse user data template and possibly combine with user_data cli arg # AWSCarb::Services::Ec2 - build an ec2 instance # AWSCarb::Services::Route53 - create dns records in route53 # # stuff to override colouring of strings if not a terminal if ! $stdout.tty? String.class_eval do def colorize(args) self end end end module AWSCarb def self.banner banner = <<-HEREDOC.strip_heredoc :::::::: ::: ::::::::: ::::::::: :+: :+: :+: :+: :+: :+: :+: :+: +:+ +:+ +:+ +:+ +:+ +:+ +:+ +#+ +#++:++#++: +#++:++#: +#++:++#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ #+# #+# #+# #+# #+# #+# #+# #+# ######## ### ### ### ### ######### - cloudinit and route53 bootstrap - HEREDOC indent = ' ' * 6 puts banner.each_line.map { |line| indent + line } end def self.run # # configuration # # parse cli args subcommand, @cli_arguments = CliArgumentParser.parse # display banner on successful cli argument parsing.. banner ap subcommand case subcommand when :create self.create when :purge self.purge else raise StandardError, "unknown exception" end end def self.purge # check route53 # check ec2 instance api_terminate? # remove route53 ... # remove ec2 instance ... end def self.create # create a configuration based on our various data sources.. @config = Config.instance @config.create(@cli_arguments) @config.display if $GLOBAL_VERBOSE # load erb template and parse the template with user_data_template_variables # then merge user_data template with raw user_data (if provided) - # end up single user_data ready to pass into ec2 instance.. @user_data = UserData.instance combined_user_data = @user_data.create(@config) @config.config[:ec2][:user_data] = combined_user_data @user_data.display if @config[:user_data_template][:file] and ($GLOBAL_VERBOSE or @config[:show_parsed_template]) # # aws interaction # if @config[:route53].andand[:new_dns_records] @route53 = Services::Route53.instance @route53.client(@config) @route53.check_hostname_and_domain_availability end ## initialize ec2 object with credentials @ec2 = Services::Ec2.instance @ec2.client(@config) @ec2.create_instance if @config[:route53].andand[:new_dns_records] @route53.create_records(@ec2) end # # summary # show_instance_details end def self.show_instance_details instance_attributes = [] instance_data = {} ShellSpinner "# collecting instance data", false do instance_attributes << @ec2.instance.class.describe_call_attributes.keys instance_attributes << @ec2.instance.class.reservation_attributes.keys instance_attributes << @ec2.instance.class.mutable_describe_attributes.keys instance_attributes.flatten! begin instance_attributes.each do |attribute| # FIXME: You may only describe the sourceDestCheck attribute for VPC instances next if attribute == :source_dest_check value = @ec2.instance.send(attribute) next unless value next if attribute == :user_data if value.class == AWS::Core::Data::List instance_data[attribute] = value.to_a else instance_data[attribute] = value end end rescue => e puts e end end puts puts "# instance details:" puts instance_data.to_yaml puts summary = <<-HEREDOC.strip_heredoc # instance summary: id: #{@ec2.instance.id} HEREDOC summary += "public ip: #{@ec2.instance.public_ip_address}\n" if @ec2.instance.public_ip_address summary += "private ip: #{@ec2.instance.private_ip_address}\n" summary += "public aws fqdn: #{@ec2.instance.public_dns_name}\n" if @ec2.instance.public_dns_name summary += "private aws fqdn: #{@ec2.instance.private_dns_name}\n" unless @config[:route53][:new_dns_records].nil? # tests exist since if a machine is part of a vpc it may not have a public fqdn.. summary += "public fqdn: #{@config[:route53][:new_dns_records][:public][:alias]}\n" if @config[:route53][:new_dns_records][:public][:target] summary += "private fqdn: #{@config[:route53][:new_dns_records][:private][:alias]}\n" if @config[:route53][:new_dns_records][:private][:target] end if @ec2.instance.dns_name summary += <<-HEREDOC.strip_heredoc # connect: ssh #{@ec2.instance.dns_name} -l ubuntu HEREDOC end puts summary end end <file_sep>/README.md # amazon web services - cloudinit and route53 bootstrap ``` :::::::: ::: ::::::::: ::::::::: :+: :+: :+: :+: :+: :+: :+: :+: +:+ +:+ +:+ +:+ +:+ +:+ +:+ +#+ +#++:++#++: +#++:++#: +#++:++#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ #+# #+# #+# #+# #+# #+# #+# #+# ######## ### ### ### ### ######### - cloudinit and route53 bootstrap - ``` ## Install ### rubygems ``` gem build aws-carb.gemspec gem install --local aws-carb-*.gem ``` ### Dependencies If you've compiled your own ruby (rvm/rbenv, etc) then you will need to make sure ruby has support for various libraries. For debian based systems, do the following before compiling ruby: ``` sudo apt-get isntall libreadline-dev zlib1g-dev libssl-dev ``` ## Configuration At minimum, Carb needs to know your aws-ec2 credentials. The simplest way to allow this is to edit ~/.carb/config/config.yaml. See config/config.yaml.example for an example config. See aws-config project for credentials ## Example usage carb can be used to create ec2 instances ``` aws create ``` ## Temporary Quickstart Docs.. Leaving this stuff here until proper docs have been written: ``` # works on ruby > 1.9 gem install aws-carb # install config and template directories mkdir -p ~/.carb/{config,template} sudo updatedb cp `locate gems/aws-carb-0.0.3/examples/config/config.yaml.example` ~/.carb/config/config.yaml cp `locate gems/aws-carb-0.0.3/examples/template/basic.cloud-config.erb` ~/.carb/template/ # edit config.yaml - remember to specify an ssh key because without one your ec2 instance will be inaccessible! (copy your ssh key from id_rsa.pub as a string - not a file path) vim ~/.carb/config/config.yaml # examples: # create a basic instance like this (or put 'image_id' into 'ec2' section of config.yaml): carb create --image-id <ami id> # create an instance but bootstrap it with the user-data cloudinit template and also get some route53 goodness going on because hostname is set # run with verbose to see more interesting info # Note: parameters specified on the command line override variables set in the config file carb -v create --user-data-template ~/.carb/template/basic.cloud-config.erb --common-variables "{ 'hostname' => 'asdasdasasdasdsa' }" # list all the ec2 options: carb help create ``` ## Understanding block-device-mappings ### Description When specifying block-device mappings, each mapping must be a valid hash and must be contained in an array. Once the machine has booted the block device(s) will be available through their virtual block device, e.g: ``` # /dev/xv<disk><partition> /dev/sdc1 = /dev/xvc1 /dev/sdf0 = /dev/xvf0 ... ``` http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html ### Examples A typical block device mapping: ``` [{ 'device_name' => '/dev/sdf1', 'ebs' => { 'volume_size' => 500 } }] ``` Multiple block device mappings: ``` [ { 'device_name' => '/dev/sdf1', 'ebs' => { 'volume_size' => 500 } }, { 'device_name' => '/dev/sdf2', 'ebs' => { 'volume_size' => 500 } } ] ``` Typical command line usage: ``` carb -c ~/.carb/config/config.yaml -v create --user-data-template ~/.carb/template/basic.cloud-config.erb --block-device-mappings "[{ 'device_name' => '/dev/sdf1', 'ebs' => { 'volume_size' => 500 } }]" ``` Example customer command line usage: ``` ithaka sams carb -c ~/.carb/config/ithaka-lucid-xa.yaml -v create --user-data-template ~/.carb/template/cloud-config.erb --instance-type c3.xlarge --common-variables "{ 'hostname' => 'cspithsam08x1' }" --block-device-mappings "[{ 'device_name' => '/dev/sda1', 'ebs' => { 'volume_size' => 32, 'volume_type' => 'gp2' } }]" arb -c ~/.carb/config/ithaka-lucid-yb.yaml -v create --user-data-template ~/.carb/template/cloud-config.erb --instance-type c3.xlarge --common-variables "{ 'hostname' => 'cspithsam08y2' }" --block-device-mappings "[{ 'device_name' => '/dev/sda1', 'ebs' => { 'volume_size' => 32, 'volume_type' => 'gp2' } }]" ithaka star carb -c ~/.carb/config/ithaka-star-xa.yaml -v create --user-data-template ~/.carb/template/cloud-config.erb --instance-type c1.medium --common-variables "{ 'hostname' => 'cspithstar08x2' }" --block-device-mappings "[{ 'device_name' => '/dev/sda1', 'ebs' => { 'volume_size' => 12, 'volume_type' => 'gp2' } }]" carb -c ~/.carb/config/ithaka-star-yb.yaml -v create --user-data-template ~/.carb/template/cloud-config.erb --instance-type c1.medium --common-variables "{ 'hostname' => 'cspithstar08y2' }" --block-device-mappings "[{ 'device_name' => '/dev/sda1', 'ebs' => { 'volume_size' => 12, 'volume_type' => 'gp2' } }]" ithaka dataqa carb -c ~/.carb/config/ithaka-star-dataqa-x.yaml -v create --user-data-template ~/.carb/template/cloud-config.erb --instance-type c1.medium --common-variables "{ 'hostname' => 'cspithqastar08x2' }" single node sams in our aws account carb -c ~/.carb/config/sem-x.yaml -v create --user-data-template ~/.carb/template/cloud-config.erb --instance-type t2.medium --common-variables "{ 'hostname' => 'cspcolsam30x1' }" --block-device-mappings "[{ 'device_name' => '/dev/sda1', 'ebs' => { 'volume_size' => 32, 'volume_type' => 'gp2' } }]" ```
74feb1cf3810e2d8164fc92401e4c80bc7f3ccc7
[ "Markdown", "Ruby" ]
10
Ruby
gilesw/aws-carb
441623fe906e493724ff0682a9c88b9636b18a78
426aad31d372ee54474c740d5a52871d5239294d
refs/heads/master
<file_sep><?php /* Template Name: Original */ ?> <?php get_header(); ?> <article> <section> <h1>original</h1> </section> </article> <?php get_footer(); ?> <file_sep><?php get_template_part('common/head'); ?> <header> <h1>header</h1> </header><file_sep><?php add_theme_support("menus"); register_sidebar( array( "before_widget" => "<div class='widget'>", "after_widget" => "</div>", "before_title" => "<h3>", "after_title" => "</h3>" ) ); add_theme_support("post-thumbnails"); function winexcerpt($length) { global $post; $content = mb_substr(strip_tags($post -> post_content),0,$length); return $content; }<file_sep><?php get_template_part('common/head'); ?> <article> <section> <h1>test</h1> <section> <article> <?php get_template_part('common/foot'); ?><file_sep><!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title><?php wp_title('|', true, 'right'); bloginfo('name'); ?></title> <link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_uri(); ?>"> <?php wp_enqueue_script('jquery.js', get_bloginfo('template_url').'/js/jquery.js'); ?> <?php wp_enqueue_script('slider.js', get_bloginfo('template_url').'/js/slider.min.js'); ?> <?php wp_enqueue_script('main.js', get_bloginfo('template_url').'/js/main.js'); ?> <?php wp_enqueue_script('functions', get_bloginfo('template_url').'/js/functions.js'); ?> <script> </script> </head> <body><file_sep><?php /* Template Name: Blog */ ?> <?php get_header(); ?> <?php if(have_posts()): while(have_posts()): the_post(); ?> <article <?php post_class(); ?>> <h2> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </h2> <time datetime="<?php echo get_the_date('Y/m/d') ?>"> <?php echo get_the_date(); ?> </time> <?php the_category( ', ' ); ?> <?php the_content(); ?> </article> <?php endwhile; endif; ?> <div class="navigation"> <div class="prev"><?php previous_posts_link();?></div> <div class="next"><?php next_posts_link();?></div> </div> <?php get_footer(); ?><file_sep><?php get_template_part('common/foot'); <file_sep>var gulp = require('gulp'); var sass = require('gulp-sass'); // SassとCssの保存先を指定 gulp.task('sass', function(){ return gulp.src('./scss/style.scss') .pipe(sass({outputStyle: 'expanded'})) .pipe(gulp.dest('./')); }); //自動監視のタスクを作成(sass-watchと名付ける) gulp.task('watch', gulp.series( gulp.parallel('sass'), function(){ var watcher = gulp.watch('./scss/**/*.scss', gulp.task('sass')); watcher.on('change', function(event) { }); })); // タスク"watch"がgulpと入力しただけでdefaultで実行されるようになる gulp.task('default', gulp.task('watch'));
43db525969bcaea2b85b0fefc19689460674b940
[ "JavaScript", "PHP" ]
8
PHP
kadotami/wp-template
9f6a9c21458dec6c6963a23fa3437befc5946b5b
ac185b781294ed7da5c958820dfe5be1f0b93c15
refs/heads/master
<repo_name>vszed/FlappyBird<file_sep>/Assets/Script/GroundAndTube.cs //由于地面和水管移动要同步=>放弃单一职责=>高度集成 using System.Collections; using System.Collections.Generic; using UnityEngine; public class GroundAndTube : MonoBehaviour { private Data D_ins; //数据单例 // Use this for initialization void Start () { D_ins = Data.getInstance(); tubeInit(); //水管初始化 } // Update is called once per frame void Update () { if(D_ins.birdAlived == true) this.GroundAndTubeScroll(); } void tubeInit() //水管初始化 { D_ins.sp_tubeDown1.transform.position = new Vector2(D_ins.sp_tubeDown1.transform.position.x, Random.Range(2.4f, 6.6f)); //朝下水管高度 D_ins.sp_tubeUp1.transform.position = new Vector2(D_ins.sp_tubeDown1.transform.position.x, D_ins.sp_tubeDown1.transform.position.y - D_ins.TubeUpDownDistance); D_ins.sp_tubeDown2.transform.position = new Vector2(D_ins.sp_tubeDown1.transform.position.x + D_ins.TubeLeftRightDistance, Random.Range(2.4f, 6.6f)); //朝下水管高度 D_ins.sp_tubeUp2.transform.position = new Vector2(D_ins.sp_tubeDown2.transform.position.x, D_ins.sp_tubeDown2.transform.position.y - D_ins.TubeUpDownDistance); } void GroundAndTubeScroll() //水管&地面=>滚动及刷新 { //=====================地面=====================// var ground1Pos = D_ins.sp_ground1.transform.position; var ground2Pos = D_ins.sp_ground2.transform.position; D_ins.sp_ground1.transform.position = new Vector2(ground1Pos.x -= D_ins.GroundAndTubeSpeed * Time.deltaTime, ground1Pos.y); D_ins.sp_ground2.transform.position = new Vector2(ground2Pos.x -= D_ins.GroundAndTubeSpeed * Time.deltaTime, ground2Pos.y); if (ground2Pos.x <= -5.237f) { D_ins.sp_ground2.transform.position = new Vector2(5.237f, ground2Pos.y); } if (ground1Pos.x <= -5.237f) { D_ins.sp_ground1.transform.position = new Vector2(5.237f, ground1Pos.y); } if (D_ins.gameBegin == true) //游戏开始时才刷新水管 { //=====================水管=====================// D_ins.sp_tubeDown1.transform.position = new Vector2(D_ins.sp_tubeDown1.transform.position.x - D_ins.GroundAndTubeSpeed * Time.deltaTime, D_ins.sp_tubeDown1.transform.position.y); D_ins.sp_tubeUp1.transform.position = new Vector2(D_ins.sp_tubeDown1.transform.position.x, D_ins.sp_tubeUp1.transform.position.y); D_ins.sp_tubeDown2.transform.position = new Vector2(D_ins.sp_tubeDown2.transform.position.x - D_ins.GroundAndTubeSpeed * Time.deltaTime, D_ins.sp_tubeDown2.transform.position.y); D_ins.sp_tubeUp2.transform.position = new Vector2(D_ins.sp_tubeDown2.transform.position.x, D_ins.sp_tubeUp2.transform.position.y); //===================二者刷新===================// if (D_ins.sp_tubeDown1.transform.position.x < -D_ins.TubeDown1X) { D_ins.sp_tubeDown1.transform.position = new Vector2(D_ins.sp_tubeDown2.transform.position.x + D_ins.TubeLeftRightDistance, Random.Range(2.4f, 6.6f)); D_ins.sp_tubeUp1.transform.position = new Vector2(D_ins.sp_tubeDown1.transform.position.x, D_ins.sp_tubeDown1.transform.position.y - D_ins.TubeUpDownDistance); D_ins.Tube1point = true; } if (D_ins.sp_tubeDown2.transform.position.x < -D_ins.TubeDown1X) { D_ins.sp_tubeDown2.transform.position = new Vector2(D_ins.sp_tubeDown1.transform.position.x + D_ins.TubeLeftRightDistance, Random.Range(2.4f, 6.6f)); D_ins.sp_tubeUp2.transform.position = new Vector2(D_ins.sp_tubeDown2.transform.position.x, D_ins.sp_tubeDown2.transform.position.y - D_ins.TubeUpDownDistance); D_ins.Tube2point = true; } } } } <file_sep>/AndroidStudio/FlappyBird/local.properties sdk.dir=G:/Cocos/tools/Android-SDK-2 <file_sep>/Assets/Script/Data.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Data : MonoBehaviour { //音效(有默认值的) public AudioSource audio_hit; public AudioSource audio_swing; public AudioSource audio_die; public AudioSource audio_point; public AudioSource audio_swooshing; //精灵 public GameObject bkg; public GameObject sp_ground1; public GameObject sp_ground2; public GameObject sp_tubeDown1; public GameObject sp_tubeDown2; public GameObject sp_tubeUp1; public GameObject sp_tubeUp2; public GameObject sp_bird; public GameObject now_score1; //四位数字 public GameObject now_score2; public GameObject now_score3; public GameObject now_score4; public GameObject high_score1; //最高记录 public GameObject high_score2; public GameObject high_score3; public GameObject high_score4; public GameObject tip; public GameObject gameover; public GameObject scorePanel; public GameObject getReady; public GameObject btnOk; public GameObject medal; public GameObject newRecord; //数据(括号内为默认值) public int Nowscore; //当前游戏得分(0) public int LocalHighScore; //本地最高得分 public int GroundAndTubeSpeed; //地面&水管移动速度(2) public float TubeDown1X; //水管1朝下X坐标(3.3) public float TubeDown2X; //水管1朝下X坐标(6.3) public float TubeUpDownDistance; //水管上下间距(7.6) public float TubeLeftRightDistance; //水管左右间距(3.5) public float TubeDownMinHeight; //朝下水管高度要大于(2.4) public float TubeDownMaxHeight; //朝下水管高度要小于(6.6) //开关 public bool Tube1point; //能否得分 public bool Tube2point; //能否得分 public bool birdAlived; //是否存活 public bool gameBegin; //开始游戏 //数据单例 private static Data gameData; public static Data getInstance() //u3d特殊单例 { return gameData; } private Data() { } void Awake() { gameData = this; } // Use this for initialization void Start () { randBkg(); } // Update is called once per frame void Update () { } public void upDateLocalHighScore() //更新本地最高分 { LocalHighScore = PlayerPrefs.GetInt("LocalHighScore", 0); if (Nowscore > LocalHighScore) { PlayerPrefs.SetInt ("LocalHighScore", Nowscore); LocalHighScore = PlayerPrefs.GetInt("LocalHighScore", 0); newRecord.SetActive(true); //新纪录 } } void randBkg() { int value = Random.Range (0, 100); string path = null; if (value % 2 == 0) { path = "day"; } else { path = "night"; } var texture = (Texture2D)Resources.Load("Pictures/"+path); var sprite = Sprite.Create(texture, bkg.GetComponent<SpriteRenderer>().sprite.textureRect, new Vector2(0.5f, 0.5f)); bkg.GetComponent<SpriteRenderer> ().sprite = sprite; } public string randBirdColor() { int value = Random.Range (0, 100); if (value % 2 == 0) { return "blue"; } else if (value % 3 == 0) { return "red"; } else { return "yellow"; } } } <file_sep>/Assets/Script/Bird.cs //部分数据采用硬编码 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class Bird : MonoBehaviour { private string birdColor = null; //鸟颜色 private int bird_idx = 0; //鸟帧动画 private float currentTime; //当前时间 private float lastTime; //上次时间 private Data D_ins; //数据单例 bool moveRoam = false; //漫游上下开关 private static Bird birdInstance; //鸟单例 private Bird() { } public static Bird getInstance() //u3d特殊单例模式 { return birdInstance; } void Awake() { birdInstance = this; } void Start() { lastTime = Time.time; D_ins = Data.getInstance(); D_ins.now_score2.SetActive(false); D_ins.now_score3.SetActive(false); D_ins.now_score4.SetActive(false); //鸟随机颜色 birdColor = D_ins.randBirdColor(); var texture = (Texture2D)Resources.Load("Pictures/bird_"+birdColor+"_0"); var bird_sprite = Sprite.Create(texture, D_ins.sp_bird.GetComponent<SpriteRenderer>().sprite.textureRect, new Vector2(0.5f, 0.5f)); D_ins.sp_bird.GetComponent<SpriteRenderer> ().sprite = bird_sprite; } void Update() { birdAnimation(); if (D_ins.gameBegin == true) { birdControl(); } else { birdRoam(); //漫游 } } void birdAnimation() //鸟动画 { if (D_ins.birdAlived == true) { currentTime = Time.time; if (currentTime - lastTime > 0.12) //简易定时器 { Texture2D texture2d = (Texture2D)Resources.Load("Pictures/bird_" + birdColor + "_" + bird_idx); //更换角色图片 var sprite = Sprite.Create(texture2d, D_ins.sp_bird.GetComponent<SpriteRenderer>().sprite.textureRect, new Vector2(0.5f, 0.5f)); D_ins.sp_bird.GetComponent<SpriteRenderer>().sprite = sprite; bird_idx = bird_idx >= 2 ? bird_idx = 0 : ++bird_idx; lastTime = currentTime; } } } void birdRoam() //未开始游戏时漫游 { if (D_ins.sp_bird.transform.position.y < -0.45) moveRoam = true; //上移 else if (D_ins.sp_bird.transform.position.y > 0.5) moveRoam = false; //下移 var tempPos = D_ins.sp_bird.transform.position; if (moveRoam == false) D_ins.sp_bird.transform.position = new Vector2(tempPos.x, tempPos.y -= 0.5f * Time.deltaTime); else D_ins.sp_bird.transform.position = new Vector2(tempPos.x, tempPos.y += 0.5f * Time.deltaTime); if (Input.GetMouseButtonDown(0)) //获取游戏开始指令 { D_ins.gameBegin = true; //游戏开始 D_ins.sp_bird.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic; //以下来自birdControl函数 D_ins.audio_swing.Play(); D_ins.sp_bird.transform.rotation = Quaternion.Euler(0, 0, 30); //欧拉角 this.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static; this.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic; this.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 5.5f), ForceMode2D.Impulse); //隐藏UI元素 D_ins.getReady.SetActive(false); D_ins.tip.SetActive(false); } } void birdRotation() //鸟静态旋转动作 { if (D_ins.sp_bird.transform.rotation.z > -0.71) { D_ins.sp_bird.transform.Rotate(new Vector3(0, 0, -110 * Time.deltaTime)); } } void birdControl() //用户操控 { if (Input.GetMouseButtonDown(0) && D_ins.birdAlived == true) { D_ins.audio_swing.Play(); //播放音效 //向上旋转 D_ins.sp_bird.transform.rotation = Quaternion.Euler(0, 0, 30); //欧拉角 this.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static; this.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic; if (this.transform.position.y < 5.5) //防止小鸟飞出上边界 this.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 5.5f), ForceMode2D.Impulse); } else if (D_ins.sp_bird.transform.position.y > -3) //可下旋转临界值 { birdRotation(); } } void OnCollisionEnter2D(Collision2D coll) { if (D_ins.birdAlived == true) { D_ins.audio_hit.Play(); //需要立刻让鸟不模拟=>模拟 this.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static; this.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic; Invoke("scorePanelDisplay", 1.5f); if (this.transform.position.y > -2.3) { Invoke("playDieAudio", 0.4f); } } D_ins.birdAlived = false; foreach (var item in GameObject.FindGameObjectsWithTag("tube")) { item.GetComponent<BoxCollider2D>().isTrigger = true; } } void playDieAudio() { D_ins.audio_die.Play(); //死亡坠落声 } public void scorePanelDisplay() //计分板显示 { D_ins.now_score1.SetActive(false); D_ins.now_score2.SetActive(false); D_ins.now_score3.SetActive(false); D_ins.now_score4.SetActive(false); D_ins.gameover.SetActive(true); D_ins.btnOk.SetActive(true); D_ins.scorePanel.SetActive(true); D_ins.audio_swooshing.Play(); //分数显示 => 分数父节点:缩放、移动、更改childAlignment D_ins.now_score1.GetComponentInParent<RectTransform> ().localScale = new Vector2 (0.5f, 0.5f); D_ins.now_score1.GetComponentInParent<HorizontalLayoutGroup>().childAlignment = TextAnchor.UpperRight; D_ins.now_score1.GetComponentInParent<RectTransform>().position = new Vector2(1.245f, 0.413f); for (int i = 1; i <= D_ins.Nowscore.ToString().ToCharArray().Length; i++) { switch (i) { case 1: D_ins.now_score1.SetActive(true); break; case 2: D_ins.now_score2.SetActive(true); break; case 3: D_ins.now_score3.SetActive(true); break; case 4: D_ins.now_score4.SetActive(true); break; } } //奖杯显示: 铜=>10+; 银=>20+; 金=>30+; 铂金=>40+; Sprite sp_medal; Texture2D tex_medal; string path_medal = null; if (D_ins.Nowscore >= 40) { path_medal = "platinum"; } else if (D_ins.Nowscore >= 30) { path_medal = "gold"; } else if (D_ins.Nowscore >= 20) { path_medal = "silver"; } else if (D_ins.Nowscore >= 10) { path_medal = "bronze"; } if (path_medal != null) { tex_medal = (Texture2D)Resources.Load("Pictures/"+path_medal); sp_medal = Sprite.Create(tex_medal, D_ins.medal.GetComponent<SpriteRenderer>().sprite.textureRect, new Vector2(0.5f, 0.5f)); D_ins.medal.GetComponent<SpriteRenderer>().sprite = sp_medal; D_ins.medal.SetActive(true); } //显示本地最高分 D_ins.upDateLocalHighScore(); Debug.Log(D_ins.LocalHighScore); char []high_score = D_ins.LocalHighScore.ToString().ToCharArray(); for (int i = 0; i < high_score.Length; i++) { Texture2D texture2d = (Texture2D)Resources.Load("Pictures/" + high_score[i]); //更换角色图片 var sprite = Sprite.Create(texture2d, D_ins.now_score1.GetComponent<SpriteRenderer>().sprite.textureRect, new Vector2(0.5f, 0.5f)); switch (i) //改位值 { case 0: D_ins.high_score1.SetActive(true); D_ins.high_score1.GetComponent<SpriteRenderer>().sprite = sprite; break; case 1: D_ins.high_score2.SetActive(true); D_ins.high_score2.GetComponent<SpriteRenderer>().sprite = sprite; break; case 2: D_ins.high_score3.SetActive(true); D_ins.high_score3.GetComponent<SpriteRenderer>().sprite = sprite; break; case 3: D_ins.high_score4.SetActive(true); D_ins.high_score4.GetComponent<SpriteRenderer>().sprite = sprite; break; } } } public void btn_ok_onClick() { D_ins.audio_swooshing.Play(); Invoke("refreshScene", 0.7f); D_ins.btnOk.GetComponent<Button>().interactable = false; //按钮不可点击 //D_ins.btnOk.SetActive(false); //按钮隐藏 } public void refreshScene() //游戏结束刷新场景 { SceneManager.LoadScene("MainScene"); D_ins.Tube1point = true; //重置开关 D_ins.Tube2point = true; D_ins.birdAlived = true; D_ins.gameBegin = false; D_ins.Nowscore = 0; } } <file_sep>/Assets/Script/NowScore.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class NowScore : MonoBehaviour { private Data D_ins; //数据单例 // Use this for initialization void Start () { D_ins = Data.getInstance(); } // Update is called once per frame void Update () { getScore(); } void getScore() //得分函数 { if (D_ins.sp_tubeDown1.transform.position.x <= -0.97 && D_ins.Tube1point == true) { D_ins.audio_point.Play(); //得分音效 D_ins.Tube1point = false; //得分开关控制 ++D_ins.Nowscore; refresh(); //刷新分数显示 } else if (D_ins.sp_tubeDown2.transform.position.x <= -0.97 && D_ins.Tube2point == true) { D_ins.audio_point.Play(); D_ins.Tube2point = false; ++D_ins.Nowscore; refresh(); } } void refresh() //刷新并显示得分 { char []arr_score = D_ins.Nowscore.ToString().ToCharArray(); for (int i = 0; i < arr_score.Length; i++) { Texture2D texture2d = (Texture2D)Resources.Load("Pictures/" + arr_score[i]); //更换角色图片 var sprite = Sprite.Create(texture2d, D_ins.now_score1.GetComponent<SpriteRenderer>().sprite.textureRect, new Vector2(0.5f, 0.5f)); switch (i) //改位值 { case 0: D_ins.now_score1.SetActive(true); D_ins.now_score1.GetComponent<SpriteRenderer>().sprite = sprite; break; case 1: D_ins.now_score2.SetActive(true); D_ins.now_score2.GetComponent<SpriteRenderer>().sprite = sprite; break; case 2: D_ins.now_score3.SetActive(true); D_ins.now_score3.GetComponent<SpriteRenderer>().sprite = sprite; break; case 3: D_ins.now_score4.SetActive(true); D_ins.now_score4.GetComponent<SpriteRenderer>().sprite = sprite; break; } } } } <file_sep>/Assets/Script/LogoScene.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LogoScene : MonoBehaviour { public AudioSource vszed; void Awake() { //锁帧:60 只在垂直同步为关的情况下奏效 Application.targetFrameRate = 60; } // Use this for initialization void Start () { Invoke("playSound", 0.5f); Invoke("jumpNextScene", 5); } // Update is called once per frame void Update () { } void playSound() { vszed.Play(); } void jumpNextScene() { SceneManager.LoadScene("MainScene"); } }
96d699f0411d0e7968d6280d975423f68404f1cb
[ "C#", "INI" ]
6
C#
vszed/FlappyBird
500e3ffbd977dc0e6b2143e840d8a5c338155e1d
b1f7b6fc8f8c28d56946cd22d75e4ea4afd7ab04
refs/heads/master
<repo_name>nitschkematthew/Symbiodatabaceae<file_sep>/Combining_databases/combining_databases.rmd --- title: "Combining ITS2 databases" author: "MNitschke" date: "23/04/2020" output: html_document --- ```{r} library(tidyverse) library(readr) library(Biostrings) library(ape) source("../Helper_functions/help.R") ``` # ITS2 database http://its2-old.bioapps.biozentrum.uni-wuerzburg.de - subsample to 1 sequence per genus ```{r} ITS2db_seqs <- readDNAStringSet("../Published_ITS2_databases/ITS2_db.fas") %>% DNAStringSet_to_df() ITS2db_seqs <- ITS2db_seqs %>% mutate(taxid = word(as.character(names), 1, sep = "\\ ")) ITS2db_taxid <- read_tsv("../Published_ITS2_databases/ITS2_db.tax", col_names = c("taxid", "taxonomy")) %>% mutate(taxid = as.character(taxid)) ITS2db <- left_join(ITS2db_seqs, ITS2db_taxid) %>% drop_na() %>% separate(taxonomy, into = c("domain", "phylum", "class", "order", "family", "genus", "species"), remove = FALSE, fill = "left", sep = ";", extra = "drop") %>% filter(genus != "Symbiodinium") %>% # First remove all Symbiodinium seqs group_by(genus) %>% sample_n(1) %>% ungroup() %>% unite(col = "taxonomy", domain, phylum, class, order, family, genus, species, sep = ";") %>% select(names = taxonomy, seqs) ``` # Symbiodatabaceae ```{r} SDB <- readDNAStringSet("../SDB_to_DADA2/Symbiodatabaceae_DADA2.fasta") %>% DNAStringSet_to_df() ``` # Dinophyceae ```{r} Dinop <- readDNAStringSet("../Dinophyceae/Dinophyceae_ITS2_DADA2.fasta") %>% DNAStringSet_to_df() ``` # Final combined ITS2db enriched for Symbiodiniaceae and Dinophyceae ```{r} rbind(ITS2db, SDB, Dinop) %>% df_to_DNAStringset() %>% writeXStringSet('ITS2dbn1_Dinophy_Symbio.fasta') ``` <file_sep>/README.md # Symbiodatabaceae Workflow to produce a custom Symbiodiniaceae ITS2 reference database <file_sep>/Helper_functions/help.R # Convert a DNAStringSet into a data.frame to use with tidyverse functions DNAStringSet_to_df <- function(DNAStringSet){ seq_df <- data.frame(names = names(DNAStringSet), seqs = paste(DNAStringSet)) return(seq_df) } # Convert a data.frame (seq_df) into a DNAStringSet to use with Biostrings functions df_to_DNAStringset <- function(df, seqs = "seqs", names = "names"){ DNAstr <- DNAStringSet(df[[seqs]]) names(DNAstr) <- df[[names]] return(DNAstr) } # FIX THIS # Convert data.frame (seq_df) into a DNAbin object to use with ape/insect functions # df_to_DNAbin <- function(seq_df, seqs = "seqs", names = "names"){ # DNA <- as.character(seq_df[[seqs]]) # names(DNA) <- seq_df[[names]] # return(DNA) # } # Convert DNAbin to DNAStringSet to use with Biostrings functions DNAbin_to_DNAStringSet <- function(DNAbin){ DNAstrings <- DNAbin %>% as.character() %>% lapply(.,paste0, collapse="") %>% unlist() %>% DNAStringSet() return(DNAstrings) } # Convert DNAstringset to DNAbin DNAStringSet_to_DNAbin <- function(DNAStringSet){ DNAbin <- as.DNAbin(DNAStringSet) return(DNAbin) } # Convert DNAbin to data.frame (seq_df) to use with tidyverse functions DNAbin_to_df <- function(DNAbin){ seq_df <- data.frame(names = labels(DNAbin), seqs = paste(DNAbin)) return(seq_df) } # Read fasta file into df fasta_to_df <- function(filepath){ fasta_stringset <- readDNAStringSet(filepath) seq_df <- DNAStringSet_to_df(fasta_stringset) return(seq_df) } # Write seq_df to .fasta file # Extract accession numbers (assuming each accession finishes with a .1) from DNAstringset to use in database merging extract_accn <- function(DNAStringSet){ names <- names(DNAStringSet) accn <- stringi::stri_extract(names, regex='[^.]*') return(accn) } # Dereplicate a DNAStringSet and concatenate the names together with | as the delimiter derep_cat_names <- function(dnaSet){ if (!is(dnaSet, "DNAStringSet")) { dnaSet <- DNAStringSet(dnaSet) } if (is.null(names(dnaSet))) { message("No names attribute found in dnaSet object...", "using artifically generated names") names(dnaSet) <- paste("read", 1:length(dnaSet), sep = "-") } seq_df <- DNAStringSet_to_df(dnaSet) %>% distinct(names, .keep_all = TRUE) %>% # Remove any duplicated IDs mutate(accession = str_sub(names, start = -8)) %>% distinct(accession, .keep_all = TRUE) %>% # Remove and duplicated accession numbers ungroup() %>% group_by(seqs) %>% summarise(names = paste(names, collapse = '|')) %>% # Concatenate identical sequences ungroup() seq_ss <- df_to_DNAStringset(seq_df, "seqs", "names") return(seq_ss) } # Function to retrieve the query from genbank nucleotide database in fasta format using accession numbers. # If the accession number no longer exists in the database, include the accession in the output as 404NotFound fetch_seqs <- function(query){ recs <- try(entrez_fetch(db = "nuccore", id = query, rettype = "fasta")) if(str_detect(recs[1], "Error|Fail")){ recs <- paste0(">", query, "_404NotFound\nAAAAAAAAAA\n\n") return(recs) } else{ return(recs) } } # Run virtualPCR from insect in a loop using multiple primer pairs virtualPCR_multiplex <- function(DNAbin, fwd_list, rev_list){ if(length(fwd_list) != length(rev_list)){message("Error: Must have equal number of primer pair combinations")} else{ PCR <- list() for(i in 1:length(fwd_list)){ trim <- virtualPCR(DNAbin, up = fwd_list[i], down = rev_list[i], minfsc = 50, minrsc = 50, rcdown = FALSE, trimprimers = FALSE) trim <- DNAbin_to_DNAStringSet(trim) PCR[[i]] <- trim message(paste("Finished round ", i)) } return(PCR) } } <file_sep>/SDB_to_DADA2/SDB_to_DADA2.Rmd --- title: "SDB_to_DADA2" author: "MNitschke" date: "12/12/2019" --- If you use the RDP classifier built-in to DADA2 to assign taxonomy to sequences [with the function assignTaxonomy()], a reference database is expected in a .fasta format with the taxonomic ranks separated by ; as the sequence identifier. E.g. >Eukaryota;Dinoflagellata;Dinophyceae;Suessiales;Symbiodiniaceae;Symbiodinium;A131_EF656432 AACCAATGGCCTCTTGAACGTGCATTGCGCTCTTGGGATATGCCTGAGAGCATGTCTGCTTCAGTGCTTCTACTTTCATTTTCTGCTGCTCTTGT..... >Eukaryota;Dinoflagellata;Dinophyceae;Suessiales;Symbiodiniaceae;Symbiodinium;A132_AB190284 AACCAATGGCCTCTTGAACGTGCATTGCGCTCTTGGGATATGCCTGAGAGCATGTCTGCTTCAGTGCTTCTACTTTCATTTTCTGCTGCTCTTGT...... The following is my workflow to add taxonomy to the Symbiodatabaceae.fasta file for use in DADA2. ```{r} library(ape) library(insect) library(aphid) library(kmer) library(Biostrings) library(phangorn) library(hiReadsProcessor) library(DECIPHER) library(rentrez) library(alignfigR) library(reshape2) library(tidyverse) library(viridis) ``` # Helper functions ```{r} # Import a set of helper functions. E.g. converting between data types, fetching sequences from NCBI, deprelicating, extracting accession numbers, etc source("../Helper_functions/help.R") ``` # Create taxonomy heirarchy ```{r} # Load in Symbiodatabaceae fasta file SDB <- readDNAStringSet("../Symbiodatabaceae/Symbiodatabaceae.fasta") %>% DNAStringSet_to_df() ``` ```{r} # The taxonomy of the Symbiodiniaceae tax <- "Eukaryota;Dinoflagellata;Dinophyceae;Suessiales;Symbiodiniaceae" ``` ```{r} # String matching. Any sequence ID that starts with "A", eg: A1, will be piped into "Symbiodinium", "C" into Cladocopium, etc. We will check these binnings further along in this workflow. SDB_tax <- SDB %>% mutate(genus = case_when(str_sub(names, start = 1, end = 1) == "A" ~ 'Symbiodinium', str_sub(names, start = 1, end = 1) == "B" ~ 'Breviolum', str_sub(names, start = 1, end = 1) == "C" ~ 'Cladocopium', str_sub(names, start = 1, end = 1) == "D" & str_sub(names, start = 1, end = 4) == "D1.1" ~ "Foraminifera_D", str_sub(names, start = 1, end = 1) == "D" & str_sub(names, start = 1, end = 4) == "D1.2" ~ "Foraminifera_D", str_sub(names, start = 1, end = 1) == "D" ~ 'Durusdinium', str_sub(names, start = 1, end = 1) == "E" ~ 'Effrenium', str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F1" ~ "Fugacium", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F5" ~ "Fugacium", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 3) == "N_A" ~ "Symbiodinium_F", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F_" ~ "Symbiodinium_F", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F2" ~ "Symbiodinium_Fr2", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F3" ~ "Freudenthalidium", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F4" ~ "Symbiodinium_Fr4", str_sub(names, start = 1, end = 1) == "G" ~ 'Gerakladium', str_sub(names, start = 1, end = 1) == "H" ~ 'Halluxium', str_sub(names, start = 1, end = 1) == "I" ~ 'Symbiodinium_I', TRUE ~ "Unknown")) %>% mutate(taxonomy = tax) %>% unite(col = "names", taxonomy, genus, names, sep = ";") ``` # Use kmer to produce alignment-free distance matrix to make sure the assigned taxonomies make sense based on kmer similarity ```{r} dist <- SDB_tax %>% arrange(names) %>% df_to_DNAStringset() %>% DNAStringSet_to_DNAbin() %>% kdistance(k = 6, residues = "DNA", method = "edgar") dist_m <- dist %>% as.matrix() long_dist <- melt(dist_m)[melt(lower.tri(dist_m))$value,] %>% mutate(Var1 = str_remove(Var1, "Eukaryota;Dinoflagellata;Dinophyceae;Suessiales;Symbiodiniaceae;"), Var2 = str_remove(Var2, "Eukaryota;Dinoflagellata;Dinophyceae;Suessiales;Symbiodiniaceae;")) %>% mutate(Var1 = case_when(str_detect(Var1, "|") ~ word(Var1 , 1, sep = "\\|"), TRUE ~ Var1), Var2 = case_when(str_detect(Var2, "|") ~ word(Var2 , 1, sep = "\\|"), TRUE ~ Var2)) %>% mutate(genus1 = word(Var1 , 1, sep = "\\;"), genus2 = word(Var2 , 1, sep = "\\;")) %>% mutate(value = 1-value) unknown_dist_summary <- long_dist %>% filter(genus1 == "Unknown") %>% group_by(genus1, genus2) %>% summarise(meankdist = mean(value), sdkdist = sd(value)) # Most unknown sequences included in SymbioGBR are likely to be Cladocopium, except for Symbiodinium_AB253788 which looks like Gerakladium. Revise the taxonomy accordingly. F_dist_summary <- long_dist %>% filter(genus1 == "Symbiodinium_F") %>% group_by(genus1, genus2) %>% summarise(meankdist = mean(value), sdkdist = sd(value)) # Most of the Symbiodinium_F sequences are closest to Fugacium. Revise the taxonomy accordingly. ``` # Revised taxonomy ```{r} SDB_tax_revised <- SDB %>% mutate(genus = case_when(str_sub(names, start = 1, end = 1) == "A" ~ 'Symbiodinium', str_sub(names, start = 1, end = 1) == "B" ~ 'Breviolum', str_sub(names, start = 1, end = 1) == "C" ~ 'Cladocopium', str_sub(names, start = 1, end = 1) == "D" & str_sub(names, start = 1, end = 4) == "D1.1" ~ "Foraminifera_D", str_sub(names, start = 1, end = 1) == "D" & str_sub(names, start = 1, end = 4) == "D1.2" ~ "Foraminifera_D", str_sub(names, start = 1, end = 1) == "D" ~ 'Durusdinium', str_sub(names, start = 1, end = 1) == "E" ~ 'Effrenium', str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F1" ~ "Fugacium", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F5" ~ "Fugacium", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 3) == "N_A" ~ "Fugacium", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F_" ~ "Fugacium", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F2" ~ "Symbiodinium_Fr2", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F3" ~ "Freudenthalidium", str_sub(names, start = 1, end = 1) == "F" & str_sub(names, start = 1, end = 2) == "F4" ~ "Symbiodinium_Fr4", str_sub(names, start = 1, end = 1) == "G" ~ 'Gerakladium', str_sub(names, start = 1, end = 1) == "H" ~ 'Halluxium', str_sub(names, start = 1, end = 1) == "I" ~ 'Symbiodinium_I', str_detect(names, "Symbiodinium_AB253788") ~ 'Gerakladium', # This is quite an interesting sequence - closest is Gerakladium TRUE ~ "Cladocopium")) %>% # The rest are Cladocopium mutate(taxonomy = tax) %>% unite(col = "names", taxonomy, genus, names, sep = ";") ``` # Check revised taxonomy again ```{r} # Produced new kdistances on revised taxonomy dist_revised <- SDB_tax_revised %>% arrange(names) %>% df_to_DNAStringset() %>% DNAStringSet_to_DNAbin() %>% kdistance(k = 6, residues = "DNA", method = "edgar") dist_m_revised <- dist_revised %>% as.matrix() long_dist_revised <- melt(dist_m_revised)[melt(lower.tri(dist_m_revised))$value,] %>% mutate(Var1 = str_remove(Var1, "Eukaryota;Dinoflagellata;Dinophyceae;Suessiales;Symbiodiniaceae;"), Var2 = str_remove(Var2, "Eukaryota;Dinoflagellata;Dinophyceae;Suessiales;Symbiodiniaceae;")) %>% mutate(Var1 = case_when(str_detect(Var1, "|") ~ word(Var1 , 1, sep = "\\|"), TRUE ~ Var1), Var2 = case_when(str_detect(Var2, "|") ~ word(Var2 , 1, sep = "\\|"), TRUE ~ Var2)) %>% mutate(genus1 = word(Var1 , 1, sep = "\\;"), genus2 = word(Var2 , 1, sep = "\\;")) %>% mutate(value = 1-value) long_dist_revised_summary <- long_dist_revised %>% group_by(genus1, genus2) %>% summarise(meankdist = mean(value), sdkdist = sd(value)) # Looking pretty good in terms of genus-binning according to k-distance. ggplot(data = long_dist_revised_summary) + theme_bw() + geom_tile(aes(x = genus2, y = genus1, fill = meankdist)) + scale_fill_viridis(name = "kdist") + theme(aspect.ratio = 1, axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) + coord_fixed() + scale_x_discrete(limits = levels(long_dist_revised_summary$genus1)) + scale_y_discrete(limits = levels(long_dist_revised_summary$genus2)) ``` # Write the Symbiodatabaceae output with the updated taxonomy ```{r} SDB_tax_revised %>% df_to_DNAStringset() %>% writeXStringSet("Symbiodatabaceae_DADA2.fasta") ```<file_sep>/Symbiodatabaceae/Symbiodatabaceae.Rmd --- title: "SymbioDatabaceae" author: "<NAME>" date: "12-Dec-2019" --- The code below is my workflow to curate a Symbiodiniaceae ITS2 reference database comprising the sequence data from GeoSymbio (Franklin et al 2012) and SymbioGBR (Tonk et al 2013). The final .fasta file is internally consistent, dereplicated, and has NCBI accession numbers as part of the identifier. Note: This is a base database of combined Geosymbio and SymbioGBR sequences. I will eventually fork and expand the base database with more recent studies. # Load in libraries ```{r} library(ape) library(insect) library(aphid) library(kmer) library(Biostrings) library(hiReadsProcessor) library(DECIPHER) library(rentrez) library(alignfigR) library(tidyverse) library(knitr) ``` # Helper functions ```{r} # Import a set of helper functions. E.g. converting between data types, fetching sequences from NCBI, deprelicating, extracting accession numbers, etc source("../Helper_functions/help.R") ``` # GeoSymbio <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2012). GeoSymbio: a hybrid, cloud-based web application of global geospatial bioinformatics and ecoinformatics for Symbiodinium-host symbioses. Molecular Ecology Resources, 12(2), 369-373. ```{r} # Import geosymbio table data and update taxonomy. NOTE!! Clade D and Clade G eventually have to be checked for the foraminifera specific D & G lineages, which should not be classified as Durusdinium or Gerakladium. Same for Temperate clade A which should not be classified as Symbiodinium. geosymbio <- read.csv("../Published_Symbiodiniaceae_databases/GeoSymbio_Database.csv") %>% mutate(Symbiont_Genus = case_when( Clade == "A" ~ 'Symbiodinium', Clade == "B" ~ 'Breviolum', Clade == "C" ~ 'Cladocopium', Clade == "D" ~ 'Durusdinium', Clade == "E" ~ 'Effrenium', Clade == "F" & str_detect(Type, "F1|F5") ~ "Fugacium", Clade == "F" & str_detect(Type, "N_A") ~ "Symbiodinium_F", Clade == "F" & str_detect(Type, "F2") ~ "Symbiodinium_Fr2", Clade == "F" & str_detect(Type, "F3") ~ "Freudenthalidium", Clade == "F" & str_detect(Type, "F4") ~ "Symbiodinium_Fr4", Clade == "G" ~ 'Gerakladium', Clade == "H" ~ 'Halluxium', Clade == "I" ~ 'Symbiodinium_I'), Genbank = trimws(Genbank)) # Import geosymbio sequence data directly downloaded from website geosymbio.fasta <- readDNAStringSet("../Published_Symbiodiniaceae_databases/GeoSymbio_ITS2_LocalDatabase.fasta") ``` ## Inspect missing sequences In the geosymbio table data there are Types that are not represented in the geosymbio sequence file. Of these, there are Types with multiple records and multiple accession numbers. ```{r} geosymbio <- geosymbio %>% mutate(type_in_fasta = geosymbio$Type %in% names(geosymbio.fasta)) genbank_no_types <- geosymbio %>% group_by(Clade, Type, Genbank) %>% filter(type_in_fasta == FALSE, !str_detect(Genbank, "same|Same|N_A")) %>% count() # This is a table of the types without a representative sequence in the geosymbio fasta, and the number of times they appear in the geosymbio records # Furthermore, as the GeoSymbio_ITS2_LocalDatabase.fasta file doesnt specify the accession numbers, it just seems easier to start from scratch and build up a list of sequences matching the Geosymbio table accession lists. This was my motivation for starting this workflow in the first instance. ``` ## Fetch all ITS2 sequences from Genbank listed in GeoSymbio using NCBI accession numbers ```{r} # Get list of genbank accession numbers accn <- geosymbio %>% group_by(Clade, Type, Genbank) %>% # There are Types that have more than one accession number filter(!str_detect(Genbank, "same|Same|N_A")) %>% count() ## Retrieve these from genbank query <- trimws(accn$Genbank) # Some have trailing white space - use trimws() to remove it # Set my API key set_entrez_key("<KEY>") # Call fetch_seqs and send all output to fasta # Note: this appends to the geosymbio_all.fasta file so if you stop the script halfway through, delete the file before restarting. for(i in 1:length(query)){ q <- query[i] seq <- fetch_seqs(q) cat(seq, file = "geosymbio_all.fasta", append = TRUE) Sys.sleep(0.5) # Wait between calls so we dont get IP banned by NCBI :( } # Check result versus query and check if any seqs were missing from the DB geosymbio_all <- readDNAStringSet("geosymbio_all.fasta") geosymbio_all_accn <- extract_accn(geosymbio_all) any(str_detect(geosymbio_all_accn, "404NotFound")) # Any seqs 404notfound? FALSE = missing sequences all(query %in% geosymbio_all_accn) # All accession numbers from query found in fasta? TRUE = all worked! ``` ## Inspect sequence lengths Some of the sequences we retrieved contain extra data (anything from the 18S through to the 28S). For the purposes of this database I want the ITS2 sequence data (which should be between 250-350 bp in length) - so we need to remove the flanking 18S/ITS1/5.8S and 28S regions ```{r} DNAStringSet_to_df(geosymbio_all) %>% mutate(width = str_length(seqs)) %>% ggplot() + geom_histogram(binwidth = 20, aes(width)) + theme(aspect.ratio = 1) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + scale_x_continuous(breaks = seq(100, 2075, by = 100)) # Here we see that there is large number of sequences > 300 bp ``` ```{r} # First lets check the short sequences and how they line up AACCAA..... DNAStringSet_to_df(geosymbio_all) %>% mutate(width = str_length(seqs)) %>% filter(width < 400) %>% select(-width) %>% mutate(seqs = str_sub(seqs, start = 1, end = 100)) %>% # Inspect first 100 bp df_to_DNAStringset() %>% writeXStringSet("short_inspect_start.fasta") my_data <- read_alignment("short_inspect_start.fasta") plot_alignment(my_data, "dna") # The majority of sequences start in same place (AACCAA) - some dont. # Write short sequencs to fasta DNAStringSet_to_df(geosymbio_all) %>% mutate(width = str_length(seqs)) %>% filter(width < 400) %>% select(-width) %>% df_to_DNAStringset() %>% writeXStringSet("short.fasta") # Next lets trim the long sequences and then plot them as above DNAStringSet_to_df(geosymbio_all) %>% mutate(width = str_length(seqs)) %>% filter(width >= 400) %>% select(-width) %>% df_to_DNAStringset() %>% as.DNAbin() # Define the standard ITS2 primers fwd <- "AATCAATGGCCTCCTGAA" rev <- "ATGAAGTCAGGCAAGCGA" trim <- virtualPCR(too_long, up = fwd, down = rev, rcdown = FALSE) trim %>% DNAbin_to_df() %>% mutate(seqs = str_sub(seqs, start = 1, end = 100)) %>% df_to_DNAStringset() %>% writeXStringSet("long.fasta") my_data <- read_alignment("long.fasta") plot_alignment(my_data, "dna") # Looks good. The trimming worked # Bind the short and trimmed sequences and filter it to contain only those that start with "AACC". short.fas <- DNAStringSet_to_df(geosymbio_all) %>% mutate(width = str_length(seqs)) %>% filter(width < 400) %>% select(-width) longtrim.fas <- trim %>% DNAbin_to_DNAStringSet() %>% DNAStringSet_to_df() rbind(short.fas, longtrim.fas) %>% filter(str_sub(seqs, start = 1, end = 4) == "AACC") %>% df_to_DNAStringset() %>% writeXStringSet("short_plus_long_trimmed.fasta") # Next inspect all those sequences that fail the trimming and the above "AACC" selection short_plus_long_trimmed <- readDNAStringSet("short_plus_long_trimmed.fasta") %>% DNAStringSet_to_df() DNAStringSet_to_df(geosymbio_all) %>% mutate(trimmed = names %in% short_plus_long_trimmed$names) %>% filter(trimmed == FALSE) %>% mutate(width = str_length(seqs)) select(-trimmed) %>% mutate(seqs = str_sub(seqs, start = 1, end = 100)) %>% df_to_DNAStringset() %>% writeXStringSet("fails.fasta") my_data <- read_alignment("fails.fasta") plot_alignment(my_data, "dna") # There are blocks of sequences that are in alignment - they probably come from the same studies. But certainly some sequences are partial ITS2 only ``` ## Curate the sequences that failed trimming To know where each sequence needs to be trimmed we will need to produce an alignment for each genus. The ITS2 is hypervariable-enough that typical alignment methods will fail when attempting to input sequences from multiple genera. ```{r} fails <- DNAStringSet_to_df(geosymbio_all) %>% mutate(trimmed = names %in% short_plus_long_trimmed$names) %>% filter(trimmed == FALSE) %>% mutate(accn = stringi::stri_extract(names, regex='[^.]*')) geosymbio_merge <- select(geosymbio, Clade, Symbiont_Genus, Type, Genbank) fails_meta <- left_join(fails, geosymbio_merge, by = c("accn" = "Genbank")) ``` ### Symbiodinium ```{r} fails_meta %>% filter(Symbiont_Genus == "Symbiodinium") %>% select(-accn, -Clade, -Symbiont_Genus, - Type) %>% df_to_DNAStringset() %>% AlignSeqs() %>% writeXStringSet("Symbiodinium_fails_aligned.fasta") Symbiodinium_aligned <- read_alignment("Symbiodinium_fails_aligned.fasta") plot_alignment(Symbiodinium_aligned, "dna") # Alignment looks good - ITS2 region we want starts at position 425 and ends at position 693 of the alignment readDNAStringSet("Symbiodinium_fails_aligned.fasta") %>% DNAStringSet_to_df() %>% mutate(seqs = str_sub(seqs, start = 425, end = 693)) %>% mutate(seqs = str_remove_all(seqs, "-")) %>% df_to_DNAStringset() %>% writeXStringSet("Symbiodinium_fails_ITS2.fasta") ``` ### Breviolum ```{r} # GU907630 doesnt appear to be an ITS2 sequence and is described on NCBI as a microsatellite flanking region Si15 fails_meta %>% filter(Symbiont_Genus == "Breviolum", accn != "GU907630") %>% select(-accn, -Clade, -Symbiont_Genus, - Type) %>% df_to_DNAStringset() %>% AlignSeqs() %>% writeXStringSet("Breviolum_fails_aligned.fasta") Breviolum_aligned <- read_alignment("Breviolum_fails_aligned.fasta") plot_alignment(Breviolum_aligned, "dna") # Alignment looks good - ITS2 region we want starts at position 380 ("AACCGATGGC") and ends at the final position of the alignment readDNAStringSet("Breviolum_fails_aligned.fasta") %>% DNAStringSet_to_df() %>% mutate(seqs = str_sub(seqs, start = 380)) %>% mutate(seqs = str_remove_all(seqs, "-")) %>% df_to_DNAStringset() %>% writeXStringSet("Breviolum_fails_ITS2.fasta") ``` ### Cladocopium ```{r} # We found our first conspicuous accession number errors: The accessions filtered out below do not belong to Symbiodinium in the NCBI nucleotide database fails_meta %>% filter(Symbiont_Genus == "Cladocopium", accn != "FN298428", # Remove the errors as described above accn != "FL919241", accn != "FL919242", accn != "FL919244", Type != "C90") %>% # Remove the C90 sequences as they are mostly 28S and only a short fraction of the ITS2 select(-accn, -Clade, -Symbiont_Genus, - Type) %>% df_to_DNAStringset() %>% AlignSeqs() %>% writeXStringSet("Cladocopium_fails_aligned.fasta") Cladocopium_aligned <- read_alignment("Cladocopium_fails_aligned.fasta") plot_alignment(Cladocopium_aligned, "dna") # Alignment looks great! ITS2 starts at position 421 and ends at position 717 of the alignment readDNAStringSet("Cladocopium_fails_aligned.fasta") %>% DNAStringSet_to_df() %>% mutate(seqs = str_sub(seqs, start = 421, end = 717)) %>% mutate(seqs = str_remove_all(seqs, "-")) %>% df_to_DNAStringset() %>% writeXStringSet("Cladocopium_fails_ITS2.fasta") ``` ### Durusdinium ```{r} fails_meta %>% filter(Symbiont_Genus == "Durusdinium") %>% select(-accn, -Clade, -Symbiont_Genus, - Type) %>% df_to_DNAStringset() %>% AlignSeqs() %>% writeXStringSet("Durusdinium_fails_aligned.fasta") Durusdinium_aligned <- read_alignment("Durusdinium_fails_aligned.fasta") plot_alignment(Durusdinium_aligned, "dna") # Alignment looks great - ITS2 region we want starts at position 426 of the alignment readDNAStringSet("Durusdinium_fails_aligned.fasta") %>% DNAStringSet_to_df() %>% mutate(seqs = str_sub(seqs, start = 426, end = 709)) %>% mutate(seqs = str_remove_all(seqs, "-")) %>% df_to_DNAStringset() %>% writeXStringSet("Durusdinium_fails_ITS2.fasta") ``` ### Fr2, Freudenthalidium, Fr4, Fugacium ```{r} fails_meta %>% filter(Clade == "F") %>% select(-accn, -Clade, -Symbiont_Genus, - Type) %>% df_to_DNAStringset() %>% AlignSeqs() %>% writeXStringSet("Clade_F_fails_aligned.fasta") Clade_F_aligned <- read_alignment("Clade_F_fails_aligned.fasta") plot_alignment(Clade_F_aligned, "dna") # Alignment looks good - ITS2 region we want starts at position 398 and ends at 714 of the alignment. Quite of a number of the sequences start without the first part of 5.8s and are also partial sequences readDNAStringSet("Clade_F_fails_aligned.fasta") %>% DNAStringSet_to_df() %>% mutate(seqs = str_sub(seqs, start = 398, end = 714)) %>% mutate(seqs = str_remove_all(seqs, "-")) %>% filter(seqs != "") %>% # Two sequences do not contain ITS2 information df_to_DNAStringset() %>% writeXStringSet("Clade_F_fails_ITS2.fasta") ``` ### Gerakladium ```{r} fails_meta %>% filter(Symbiont_Genus == "Gerakladium") %>% select(-accn, -Clade, -Symbiont_Genus, - Type) %>% df_to_DNAStringset() %>% AlignSeqs() %>% writeXStringSet("Gerakladium_fails_aligned.fasta") Gerakladium_aligned <- read_alignment("Gerakladium_fails_aligned.fasta") plot_alignment(Gerakladium_aligned, "dna") # Alignment looks good - ITS2 region we want starts at position 415 and ends at 752 of the alignment. readDNAStringSet("Gerakladium_fails_aligned.fasta") %>% DNAStringSet_to_df() %>% mutate(seqs = str_sub(seqs, start = 415, end = 752)) %>% mutate(seqs = str_remove_all(seqs, "-")) %>% df_to_DNAStringset() %>% writeXStringSet("Gerakladium_fails_ITS2.fasta") ``` ### Halluxium ```{r} ## All of these sequences are partial - so we need to bring in some complete ITS2 sequences from Clade_H to line them up fails_meta %>% filter(Symbiont_Genus == "Halluxium") %>% select(-accn, -Clade, -Symbiont_Genus, - Type) %>% df_to_DNAStringset() %>% AlignSeqs() %>% writeXStringSet("Halluxium_fails_aligned.fasta") Clade_H_aligned <- read_alignment("Halluxium_fails_aligned.fasta") plot_alignment(Clade_H_aligned, "dna") # Alignment looks good - ITS2 region we want ends at position 244 of the alignment. readDNAStringSet("Halluxium_fails_aligned.fasta") %>% DNAStringSet_to_df() %>% mutate(seqs = str_sub(seqs, start = 1, end = 244)) %>% mutate(seqs = str_remove_all(seqs, "-")) %>% df_to_DNAStringset() %>% writeXStringSet("Halluxium_fails_ITS2.fasta") ``` ### Effrenium ```{r} # Only one Effrenium sequence failed fails_meta %>% filter(Symbiont_Genus == "Effrenium") %>% select(-accn, -Clade, -Symbiont_Genus, - Type, -trimmed) %>% mutate(seqs = str_sub(seqs, start = 414, end = 701)) %>% df_to_DNAStringset() %>% writeXStringSet("Effrenium_fails_ITS2.fasta") ``` ## Join the short sequences, the long_trimmed sequences, and the sequences that failed trimming and were aligned and trimmed manually ```{r} short_plus_long_trimmed <- readDNAStringSet("short_plus_long_trimmed.fasta") %>% DNAStringSet_to_df() Symbiodinium <- readDNAStringSet("Symbiodinium_fails_ITS2.fasta") %>% DNAStringSet_to_df() Breviolum <- readDNAStringSet("Breviolum_fails_ITS2.fasta") %>% DNAStringSet_to_df() Cladocopium <- readDNAStringSet("Cladocopium_fails_ITS2.fasta") %>% DNAStringSet_to_df() Durusdinium <- readDNAStringSet("Durusdinium_fails_ITS2.fasta") %>% DNAStringSet_to_df() Clade_F <- readDNAStringSet("Clade_F_fails_ITS2.fasta") %>% DNAStringSet_to_df() Gerakladium <- readDNAStringSet("Gerakladium_fails_ITS2.fasta") %>% DNAStringSet_to_df() Halluxium <- readDNAStringSet("Halluxium_fails_ITS2.fasta") %>% DNAStringSet_to_df() Effrenium <- readDNAStringSet("Effrenium_fails_ITS2.fasta") %>% DNAStringSet_to_df() geosymbio_curated_sequences <- rbind(short_plus_long_trimmed, Symbiodinium, Breviolum, Cladocopium, Durusdinium, Clade_F, Gerakladium, Halluxium, Effrenium) %>% mutate(accn = stringi::stri_extract(names, regex='[^.]*')) %>% left_join(., geosymbio, by = c("accn" = "Genbank")) %>% select(seqs, accn, Clade, Type) %>% mutate(names = case_when( Type == "N_A" ~ paste(Clade, accn, sep = "_"), Type != "N_A" ~ paste(Type, accn, sep = "_"))) geosymbio_curated_sequences %>% select(names, seqs) %>% df_to_DNAStringset() %>% writeXStringSet("geosymbio_curated.fasta") ``` # Manual editing of mis-labelled reads in NCBI ```{r} readDNAStringSet("geosymbio_curated.fasta") %>% DNAStringSet_to_df() %>% mutate(new_names = case_when(names == "C3_AF333516" ~ "F_AF333516", # LaJeunesse (2001) <NAME>: Incorrectly entered in NCBI as C3. In the paper is listed as a "F" sequence TRUE ~ as.character(names))) %>% select(names = new_names, seqs) %>% df_to_DNAStringset() %>% writeXStringSet("geosymbio_curated.fasta") ``` # SymbioGBR <NAME>., <NAME>., <NAME>., & <NAME>. (2013). SymbioGBR: a web-based database of Symbiodinium associated with cnidarian hosts on the Great Barrier Reef. BMC ecology, 13(1), 7. ```{r} # Import geosymbio sequence data directly downloaded from website symbioGBR.fasta <- readDNAStringSet("../Published_Symbiodiniaceae_databases/SymbioGBR.fasta") ``` ```{r} # Get the geosymbio data we curated above geosymbio_curated <- readDNAStringSet("geosymbio_curated.fasta") %>% DNAStringSet_to_df() symbioGBR.df <- symbioGBR.fasta %>% DNAStringSet_to_df() ``` # Freudenthalidium heronense, F. endolithicum, and Halluxium pauxillum type sequences Nitschke, <NAME>., <NAME>., <NAME> & <NAME>. (2020) Description of Freudenthalidium gen. nov. and Halluxium gen. nov. to formally recognize clades Fr3 and H as genera in the family Symbiodiniaceae (Dinophyceae), Journal of Phycology ```{r} Fr3_H <- readDNAStringSet("../Species_ITS2_types/Nitschke_et_al_JPhycol_2020.fasta") %>% DNAStringSet_to_df() ``` # Symbiodatabaceae ```{r} # Bind the two datasets together Symbiodatabaceae <- rbind(geosymbio_curated, symbioGBR.df, Fr3_H) # Dereplicate and concatenate the two datasets --- # Note: During the writing of derep_cat_names function it became evident that geosymbio does not consistently label genbank accession numbers with same_as. Some are not labelled with same_as, despite being identical sequences, from the same study, where the samples came from different depths. Whereas other entries that come from different depths/hosts but have the same sequences, are labelled with same_as_ Symbiodatabaceae %>% df_to_DNAStringset() %>% derep_cat_names() %>% writeXStringSet("Symbiodatabaceae.fasta") # SymbioDatabaceae.fasta is a curated geosymbio ITS2 sequence database in Type_Accession format. We have increased the number of sequences from 409 in the GeoSymbio_ITS2_LocalDatabase.fasta file that can be downloaded in from the Geosymbio webpage, to 776 sequences, and each sequence can be traced back to its reference accession. The file is dereplicated to contain unique accession numbers and sequences, during which the names of the replicates were concatenated. ``` <file_sep>/Dinophyceae/NCBI_imports.Rmd --- title: "Untitled" author: "MNitschke" date: "21/04/2020" output: html_document --- ```{r} library(tidyverse) library(readr) library(rentrez) library(Biostrings) library(ape) library(taxize) library(insect) source("../Helper_functions/help.R") ``` # Load in NCBI search: Dinophyceae[Organism] AND internal transcribed spacer 2[All Fields] ```{r} Dinophy_nt <- read_delim("Dinophyceae[Organism] AND internal transcribed spacer 2[All Fields].txt", delim = "\n", col_names = "NCBI_record") Dinophy_nt <- Dinophy_nt %>% mutate(variable = rep(c("names", "length", "accession"), nrow(Dinophy_nt) / 3), key = rep(1:(nrow(Dinophy_nt) / 3), each = 3)) %>% pivot_wider(id_cols = key, names_from = variable, values_from = NCBI_record) %>% select(-key) %>% filter(!str_detect(names, "Symbiodinium|Cladocopium|Durusdinium|Gerakladium|Breviolum|Halluxium|Freudenthalidium|Fugacium|Symbiodiniaceae")) %>% mutate(length = str_remove(length, " bp linear DNA")) %>% type_convert(col_types = cols(length = col_number())) %>% mutate(accession = case_when(str_detect(accession, " ") ~ word(as.character(accession), 1, sep = "\\ "), TRUE ~ accession)) %>% filter(!str_detect(names, "internal transcribed spacer 2, partial")) %>% filter(!str_detect(names, "ITS2 \\(partial\\)")) %>% separate(names, into = c("number", "genus", "species", "extra"), remove = FALSE, extra = "merge") %>% mutate(species = case_when(str_detect(species, "cf") ~ paste("cf ", word(as.character(extra), 1, sep = "\\ ")), TRUE ~ species)) # List of distinct species Dinophy_nt_s1 <- Dinophy_nt %>% distinct(genus, species, .keep_all = TRUE) ``` # Get the taxonomy of the distinct genera ```{r} fetch_taxonomy <- function(query){ recs <- try(classification(query, db = 'ncbi')) return(recs) } query <- unique(Dinophy_nt_s1$genus) # Lets get the taxonomy for each genus outputlist <- list() for(i in 1:length(query)){ q <- query[i] tax <- fetch_taxonomy(q) outputlist[i] <- tax Sys.sleep(0.5) # Wait between calls so we dont get IP banned by NCBI :( } saveRDS(outputlist, "taxonomylist.rds") # Parse out the taxonomy levels that you require taxdata = data.frame() for(x in 1:length(outputlist)){ tryCatch({ class = filter(outputlist[[x]], rank == "class")$name order = filter(outputlist[[x]], rank == "order")$name family = filter(outputlist[[x]], rank == "family")$name genus = filter(outputlist[[x]], rank == "genus")$name row <- data.frame(cbind(kingdom = "Eukaryota", phylum = "Dinoflagellata", class = class, order = order, family = family, genus = genus)) taxdata <- bind_rows(taxdata, row) }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")}) } taxdata <- taxdata %>% drop_na() %>% filter(class != "Insecta") write_csv(taxdata, "taxdata-full.csv") # Just a few genera have NA's in higher ranks. Remove these ``` # Get the query sequences ```{r} query_df <- Dinophy_nt %>% filter(genus %in% taxdata$genus) query <- trimws(query_df$accession) # Some have trailing white space - use trimws() to remove it # Set my API key set_entrez_key("<KEY>") # Call fetch_seqs and send all output to fasta # Note: this appends to the geosymbio_all.fasta file so if you stop the script halfway through, delete the file before restarting. for(i in 1:length(query)){ q <- query[i] seq <- fetch_seqs(q) cat(seq, file = "Dinophyceae.fasta", append = TRUE) Sys.sleep(0.5) # Wait between calls so we dont get IP banned by NCBI :( } ``` # Trim the sequences to ITS2 ```{r} # Define the standard fwd ITS2 primer that begins in the 5.8s fwd <- "GTGAATTGCAGAACTCCGTG" fasta <- readDNAStringSet("Dinophyceae.fasta") %>% DNAStringSet_to_DNAbin() trim <- virtualPCR(fasta, up = fwd) trim %>% DNAbin_to_DNAStringSet() %>% DNAStringSet_to_df() %>% mutate(seqs = str_sub(seqs, start = 1, end = 330)) %>% mutate(length = str_length(seqs)) %>% filter(length > 250) %>% select(-length) %>% distinct(seqs, .keep_all = TRUE) %>% df_to_DNAStringset() %>% writeXStringSet("Dinophyceae_trim.fasta") ``` # Combine into DADA2 format ```{r} taxdata <- read_csv("taxdata-full.csv") seq_data <- readDNAStringSet("Dinophyceae_trim.fasta") %>% DNAStringSet_to_df() %>% mutate(accession = word(as.character(names), 1, sep = "\\ ")) %>% select(-names) %>% left_join(Dinophy_nt, .) %>% drop_na() %>% left_join(., taxdata) seq_data %>% select(kingdom, phylum, class, order, family, genus, species, seqs) %>% mutate(species = paste0(genus, " ", species)) %>% unite(col = "names", kingdom, phylum, class, order, family, genus, species, sep = ";") %>% df_to_DNAStringset() %>% writeXStringSet("Dinophyceae_ITS2_DADA2.fasta") ```
94052b5d0f024844d5f46cfa57eda9b264017c40
[ "Markdown", "R", "RMarkdown" ]
6
RMarkdown
nitschkematthew/Symbiodatabaceae
2320cbdda104c451f837ab62869941574c2d2071
c368afbf0bce252da805f61f902e6861035c383c
refs/heads/master
<file_sep>package main import "fmt" func main() { fmt.Print("Enter text: ") var input string fmt.Scanln(&input) fmt.Print(input) fmt.Print("Enter text: ") var number int fmt.Scanln(&number) fmt.Println(number) }
9a27e5413284122ac004e5e095e30e46900e3a4e
[ "Go" ]
1
Go
Necuser1/golang
760ed8eaf16fd60c56f93911a6bb94c11b1207e5
0c67bec2b06b0b5479a96d2aea03f36b9caa0ef9
refs/heads/master
<repo_name>zoyi/sdk-ibeacon-ios-kddi<file_sep>/ZBeaconKit/MonitoringManager.swift // // MonitoringManager.swift // ZBeaconKit // // Created by 이수완 on 2016. 10. 31.. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import CoreLocation protocol MonitoringManagerDelegate: class { func didEnterBeaconRegion(uuid: String, major: Int, minor: Int, forReigon region: CLRegion) func didExitBeaconRegion(uuid: String, major: Int, minor: Int, forReigon region: CLRegion) } class MonitoringManager: RangingServiceDelegate, MonitoringServiceDelegate { // MARK: - Properties var beaconRegion: CLBeaconRegion! var monitoringService = MonitoringService() let rangingService = RangingService() weak var delegate: MonitoringManagerDelegate? // MARK: - Constructors init(region: CLBeaconRegion, delegate: MonitoringManagerDelegate? = nil) { precondition(region.major == nil) precondition(region.minor == nil) self.beaconRegion = region self.delegate = delegate self.monitoringService.delegate = self self.rangingService.delegate = self } // MARK: - MonitoringManager methods func startMonitoring() { self.monitoringService.startMonitoring(withRegion: self.beaconRegion) } func stopMonitoring() { self.monitoringService.stopMonitoring() self.rangingService.stopRanging() } // MARK: - Ranging methods fileprivate func startRanging() { self.rangingService.region = CLBeaconRegion( proximityUUID: self.beaconRegion.proximityUUID, identifier: self.beaconRegion.identifier) } fileprivate func stopRanging() { self.rangingService.stopRanging() } // MARK: - MonitoringServiceDelegate methods func didChangeState(_ region: CLBeaconRegion, state: CLRegionState) { if state == .inside { self.didEnterRegion(region) } else if state == .outside { self.didExitRegion(region) } } func didEnterRegion(_ region: CLBeaconRegion) { self.startRanging() } func didExitRegion(_ region: CLBeaconRegion) { let uuid = region.proximityUUID.uuidString let values = PrefStore.get(uuid: uuid) guard values.count == 2 else { return } PrefStore.clear(uuid: uuid) let (major, minor) = (values[0], values[1]) self.delegate?.didExitBeaconRegion(uuid: uuid, major: major, minor: minor, forReigon: region) } // MARK: - Ranging Service delegate methods func didRangeBeacon(_ beacon: CLBeacon, forRegion region: CLBeaconRegion) { self.stopRanging() let uuid = beacon.proximityUUID.uuidString let major = beacon.major.intValue let minor = beacon.minor.intValue PrefStore.save(uuid: uuid, major: major, minor: minor) self.delegate?.didEnterBeaconRegion(uuid: uuid, major: major, minor: minor, forReigon: region) } func didFailRangeBeacon(forRegion region: CLBeaconRegion) { self.stopRanging() } } <file_sep>/Example/ZBeaconKitExample/ZBeaconKitExample/ViewController.swift // // ViewController.swift // ZBeaconKitExample // // Created by R3alFr3e on 2/21/18. // Copyright © 2018 ZOYI. All rights reserved. // import UIKit import CoreLocation import ZBeaconKitKDDI import UserNotifications import MessageUI class ViewController: UIViewController, DebugDelegate, CLLocationManagerDelegate, MFMailComposeViewControllerDelegate { let manager = CLLocationManager() var logText = "" var retryCount = 0 @IBOutlet weak var logView: UITextView! override func viewDidLoad() { debugDelegate = self self.manager.delegate = self self.logView.isEditable = false self.logView.isSelectable = false } @IBAction func exportTapped(_ sender: Any) { if MFMailComposeViewController.canSendMail() { let composeVC = MFMailComposeViewController() composeVC.mailComposeDelegate = self composeVC.setToRecipients(["<EMAIL>"]) composeVC.setSubject("ZBeaconKit log") composeVC.setMessageBody(self.logText, isHTML: false) self.present(composeVC, animated: true, completion: nil) } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } @IBAction func buttonTapped(_ sender: AnyObject) { print("start button tapped") let appDelegate = UIApplication.shared.delegate as? AppDelegate appDelegate?.manager.start() } @IBAction func stopTapped(_ sender: AnyObject) { print("stop button tapped") let appDelegate = UIApplication.shared.delegate as? AppDelegate appDelegate?.manager.stop() } @IBAction func clearLogs(_ sender: Any) { logView.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func debug(with message: String, color: UIColor) { DispatchQueue.main.async { [weak self] in let attributedText = NSMutableAttributedString(attributedString: (self?.logView.attributedText)!) let newText = NSMutableAttributedString(string: message) newText.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: NSRange(location: 0, length: message.count)) attributedText.append(newText) self?.logView.attributedText = attributedText } } func debug(with message: String) { self.logText += message } func receive(with event: ZBeaconEvent) { switch event { case .enter(let region): DispatchQueue.main.async { [weak self] in if UIApplication.shared.applicationState == .background { let body = region.proximityUUID.uuidString self?.sendNotification(with: "Enter to region", body: body) } self?.debug(with: "Enter to region:\n\t\(region.proximityUUID)\n", color: UIColor.black) } case .exit(let region): DispatchQueue.main.async { [weak self] in if UIApplication.shared.applicationState == .background { let body = region.proximityUUID.uuidString self?.sendNotification(with: "Exit from region", body: body) } self?.debug(with: "Exit from region:\n\t\(region.proximityUUID)\n", color: UIColor.black) } case .state(let region, let state): DispatchQueue.main.async { [weak self] in let area = state == .inside ? "inside" : state == .outside ? "outside" : "unknown" self?.debug(with: "Received state: \(area)\n\t\(region.proximityUUID)\n\n", color: UIColor.black) self?.manager.startRangingBeacons(in: region) } case .sent(let data, let event): DispatchQueue.main.async { [weak self] in if UIApplication.shared.applicationState == .background { self?.sendNotification(with: "Data has sent", body: "Data has sent to server for **\(event)** event\n\tfor \(data["ibeacon_uuid"]!)\n\n") } self?.debug(with: "Data has sent to server for **\(event)** event\n\tfor \(data["ibeacon_uuid"]!)\n\n", color: UIColor.blue) } case .error(let data, let event): DispatchQueue.main.async { [weak self] in if UIApplication.shared.applicationState == .background { self?.sendNotification(with: "Error sending data", body: "[Error] data sent **\(event)** event\n\tfor \(data["ibeacon_uuid"]!)\n\n") } self?.debug(with: "[Error] data sent **\(event)** event\n\tfor \(data["ibeacon_uuid"]!)\n\n", color: UIColor.blue) } } } func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) { for beacon in beacons { if beacon.proximityUUID == region.proximityUUID { self.debug(with: "Found valid beacon from ranging\n\t\(region.proximityUUID)\n", color: UIColor.black) self.debug(with: "============= Ranging checking ============\n", color: UIColor.black) self.debug(with: "\(beacon)\n", color: UIColor.black) self.manager.stopRangingBeacons(in: region) self.retryCount = 0 self.debug(with: "============== Checking end ==============\n\n", color: UIColor.black) break } } if self.retryCount == 10 { self.debug(with: "Stop ranging to validate for region:\n\t\(region.proximityUUID).\nReached max retry\n", color: UIColor.black) self.manager.stopRangingBeacons(in: region) } } private func sendNotification(with title: String, body: String) { let content = UNMutableNotificationContent() content.title = title content.body = body content.sound = UNNotificationSound.default() let notification = UNNotificationRequest(identifier: "zbeacon-sdk", content: content, trigger: nil) UNUserNotificationCenter.current().add(notification, withCompletionHandler: nil) } } <file_sep>/ZBeaconKit/CLRegion.swift // // CLRegion.swift // ZBeaconKit // // Created by <NAME> on 1/7/16. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import CoreLocation extension CLRegion { func isSpecific() -> Bool { guard let region = self as? CLBeaconRegion else { return false } return region.major != nil } } <file_sep>/ZBeaconKit/PrefStore.swift // // PrefStore.swift // ZBeaconKit // // Created by 이수완 on 2017. 8. 16.. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import CoreLocation class PrefStore { // MARK: - Beacon static func getKey(uuid: String) -> String { return "ZBeaconKit_Beacon_\(uuid.lowercased())" } static func save(uuid: String, major: Int, minor: Int) { UserDefaults.standard.set("\(major):\(minor)", forKey: getKey(uuid: uuid)) } static func get(uuid: String) -> [Int] { guard let value = UserDefaults.standard.string(forKey: getKey(uuid: uuid)) else { return [] } let values = value.components(separatedBy: ":") guard values.count == 2 else { return [] } guard let major = Int(values[0]), let minor = Int(values[1]) else { return [] } return [major, minor] } static func clear(uuid: String) { UserDefaults.standard.removeObject(forKey: getKey(uuid: uuid)) } // MARK: - Area static func getAreaKey(uuid: String) -> String { return "ZBeaconKit_Area_\(uuid.lowercased())" } static func saveArea(uuid: String, name: String) { UserDefaults.standard.set(name, forKey: getAreaKey(uuid: uuid)) } static func getArea(uuid: String) -> String? { return UserDefaults.standard.string(forKey: getAreaKey(uuid: uuid)) } } <file_sep>/README.md # ZBeaconKit for KDDI ## Prerequisites - `Location Always Usage` permission should be enabled(*For iBeacon Region monitoring*). - Device Bluetooth Service should always be active(*iBeacon is one of BLE Beacon specs, it needs Bluetooth to work properly*). ## Integrating ZBeaconKit for KDDI to your iOS App. ### Adding `Location Always Usage` permission. Add `NSLocationAlwaysUsageDescription`, `NSLocationAlwaysAndWhenInUseUsageDescription`, `NSLocationWhenInUseUsageDescription` keys into your project `info.plist`. [more informations](https://developer.apple.com/documentation/corelocation/choosing_the_authorization_level_for_location_services/requesting_always_authorization) </br> - for ios < 11 - `NSLocationAlwaysUsageDescription` - for ios >= 11 - `NSLocationAlwaysAndWhenInUseUsageDescription` - `NSLocationWhenInUseUsageDescription` > you can change messages. ```xml <key>NSLocationAlwaysAndWhenInUseUsageDescription</key> <string>Will you allow this app to always know your location?</string> <key>NSLocationAlwaysUsageDescription</key> <string>Will you allow this app to always know your location?</string> <key>NSLocationWhenInUseUsageDescription</key> <string>Do you allow this app to know your current location?</string> ``` ![](http://s3.ap-northeast-2.amazonaws.com/zoyi-github-assets/wiki/ZBeacon/add-location-always-usage-permission.png) ### [install](https://cocoapods.org/) `Cocoapods` - Add below into your Podfile ```pod target YOUR_PROJECT_TARGET do pod 'ZBeaconKitKDDI' end ``` - run following code ``` pod repo update pod install ``` ### [Install](https://github.com/Carthage/Carthage/releases) `carthage`. ![](http://s3.ap-northeast-2.amazonaws.com/zoyi-github-assets/wiki/ZBeacon/install-carthage.png) ### Adding copy file run script. - On your application targets’ “Build Phases” settings tab, click the “+” icon and choose “New Run Script Phase”. Create a Run Script with the following contents: ``` /usr/local/bin/carthage copy-frameworks ``` and add the paths to the frameworks you want to use under “Input Files”, e.g.: ``` $(SRCROOT)/ZBeaconKitKDDI.framework ``` ![](http://s3.ap-northeast-2.amazonaws.com/zoyi-github-assets/wiki/ZBeacon/add-copy-file-run-script.png) ### The last step, configure your App specific info. #### If you are building with Swift - Import `ZBeaconKitKDDI`, configure your App authentication information. ```swift import ZBeaconKitKDDI ... override func viewDidLoad() { super.viewDidLoad() let manager = Manager( email: "<EMAIL>", authToken: "<PASSWORD>", target: .Production // For development, use .Development ) Manager.debugMode = true // For debugging Manager.customerId = self.generateSampleCustomerId() // You must start manager manually. manager.start() // And if you want to stop, manager.stop() } func generateSampleCustomerId() -> String { let deviceId = UIDevice.current.identifierForVendor?.uuidString let deviceIdWithSalt = deviceId! + "YOUR_SALT" return deviceIdWithSalt.hmac(.sha512, key: "YOUR_KEY_FOR_HMAC") } ``` #### If you are building with Objective-C - Enable `Embedded Content Contains Swift Code` flag in `Build Settings`. ![](https://s3.ap-northeast-2.amazonaws.com/zoyi-github-assets/wiki/ZBeacon/enable-embedded-content-contains-swift-code.png) - Import `<ZBeaconKitKDDI/ZBeaconKit.h>`, configure your App authentication information. ```objective-c - (void)viewDidLoad { [super viewDidLoad]; self.manager = [[Manager alloc] initWithEmail:@"<EMAIL>" authToken:@"<PASSWORD>6" target:TargetProduction]; // For development, use TargetDevelopment [Manager setDebugMode:true]; // For debugging NSString *deviceId = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; NSString *deviceIdWithSalt = [deviceId stringByAppendingString:@"YOUR_SALT"]; NSString *customerId = [self hmac: deviceIdWithSalt withKey: @"YOUR_KEY_FOR_HMAC"]; [Manager setCustomerId: customerId]; // You must start manager manually. [self.manager start]; NSLog(@"%@", [Manager customerId]); NSLog(@"%@", [Manager packageId]); // And if you want to stop, [self.manager stop]; } - (NSString *) hmac: (NSString *)plaintext withKey:(NSString *)key { const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; const char *cData = [plaintext cStringUsingEncoding:NSASCIIStringEncoding]; unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)]; const unsigned char *buffer = (const unsigned char *)[HMACData bytes]; NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2]; for (int i = 0; i < HMACData.length; ++i){ [HMAC appendFormat:@"%02x", buffer[i]]; } return HMAC; } ``` ### Deployment Target **Note** that you must describe _deployment target_ to manager when initializing. The deployment target depends on ZOYI's actual O2O server endpoint. This flag is only used for mutual test with ZOYI Corp. So most of 3rd parties does not need to change this. Case of Swift: ```swift // Set target as PRODUCTION let manager = Manager( email: "...", authToken: "...", target: .Production ) // Set target as DEVELOPMENT (signals can not be seen by BLE API) let manager = Manager( email: "...", authToken: "...", target: .Development ) ``` Objective-C: ```objective-c // Set target as PRODUCTION self.manager = [[Manager alloc] initWithEmail:@"..." authToken:@"..." target:TargetProduction]; // Set target as DEVELOPMENT (signals can not be seen by BLE API) self.manager = [[Manager alloc] initWithEmail:@"..." authToken:@"..." target:TargetDevelopment]; ``` <file_sep>/Example/ZBeaconKitExample/Podfile # Uncomment the next line to define a global platform for your project platform :ios, '10.0' target 'ZBeaconKitExample' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for ZBeaconKitExample pod 'ZBeaconKitKDDI', :path => '../..' end <file_sep>/ZBeaconKitTests/ZBeaconKitTests.swift // // ZBeaconKitTests.swift // ZBeaconKitTests // // Created by <NAME> on 12/21/15. // Copyright © 2018 ZOYI. All rights reserved. // import XCTest @testable import ZBeaconKit class ZBeaconKitTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } func testNSNumberExtension() { print(NSNumber(short: 61463).hexValue) XCTAssertEqual(NSNumber(short: 61463).hexValue, "F017", "NSNumber extension hexValue test failed.") } } <file_sep>/How to build.md # ZBeaconKit ## How to build? ### Cocoapods In your Podfile, add ```` target 'Example' do use_frameworks! ... your pods # Pods for ZBeaconKitExample pod 'ZBeaconKit', :path => '../..' end ```` and run `pod repo update` then `pod install` ### Carthage This project could simply be built with [Carthage](https://github.com/Carthage/Carthage). In case you are first get to know carthage, here is a brief description of how to build carthage. 1. install carthage.(better to use homebrew) 2. open project root folder. 3. Modify Manager.currentPackageVersion if needed 4. build ZBeaconKit with command: `carthage build --no-skip-current` 5. the `ZBeaconKit.framework` could be found in `$(PROJECT_ROOT)/Carthage/Build/iOS`. <file_sep>/ZBeaconKit/LocationService.swift // // LocationService.swift // ZBeaconKit // // Created by <NAME> on 12/21/15. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import CoreLocation class LocationService: NSObject, CLLocationManagerDelegate { let locationManager = CLLocationManager() func activeLocationManager() { self.locationManager.delegate = self } func inactiveLocationManager() { self.locationManager.delegate = nil } } <file_sep>/ZBeaconKit/CLBeaconRegion.swift // // CLBeaconRegion.swift // ZBeaconKit // // Created by <NAME> on 12/21/15. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import CoreLocation extension CLBeaconRegion { func isEqualTo(_ region: CLBeaconRegion) -> Bool { return region.proximityUUID.uuidString == self.proximityUUID.uuidString } } <file_sep>/ZBeaconKit/NSDate.swift // // NSDate.swift // ZBeaconKit // // Created by <NAME> on 12/31/15. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation extension Date { var microsecondsIntervalSince1970: UInt64 { return UInt64(self.timeIntervalSince1970 * 1000 * 1000); } } <file_sep>/ZBeaconKit/Manager.swift // // Manager.swift // ZBeaconKit // // Created by <NAME> on 12/21/15. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import UIKit import CoreLocation import AdSupport func dlog<T>( _ object: @autoclosure () -> T, color: UIColor = UIColor.black) { guard Manager.debugMode else { return } let message = "[ZBeaconKit] \(Date()): \(object())\n\n" print(message, terminator: "") debugDelegate?.debug(with: message) } enum IBeaconRegionEvent: String { case Enter = "enter" case Exit = "leave" } @objc public enum Target: Int { case Production case Development } /** debugging purpose **/ public protocol DebugDelegate: class { func debug(with message: String) func debug(with message: String, color: UIColor) func receive(with event: ZBeaconEvent) } public enum ZBeaconEvent { case error(data: [String: Any], event: String) case sent(data: [String: Any], event: String) case enter(region: CLBeaconRegion) case exit(region: CLBeaconRegion) case state(region: CLBeaconRegion, state: CLRegionState) } public var debugDelegate: DebugDelegate? = nil @objc public final class Manager: NSObject, MonitoringManagerDelegate { // MARK: - Properties @objc public static var debugMode = false @objc public static let packageId = Bundle.main.bundleIdentifier; @objc public static var uuids = [String]() @objc public static var customerId: String? = nil @objc public static var advId: String? = nil var packageVersionEndpoint: String { switch self.target { case .Production: return "https://api-kddi.walkinsights.com/api/v1/plugins/ios" case .Development: return "https://rails-staging.walkinsights.com/api/v1/plugins/ios" } } var uuidEndpoint: String { switch self.target { case .Production: return "https://api-kddi.walkinsights.com/api/v1/square_ibeacons" case .Development: return "https://rails-staging.walkinsights.com/api/v1/square_ibeacons" } } var dataEndpoint: String { switch self.target { case .Production: return "https://dropwizard-kddi.walkinsights.com/api/v1/ibeacon_signals" case .Development: return "https://dropwizard-staging.walkinsights.com/api/v1/ibeacon_signals" } } static let model = UIDevice.current.modelName static let systemInfo = UIDevice.current.systemInfo static let currentPackageVersion = "1.0.0" fileprivate var monitoringManagers = [MonitoringManager]() fileprivate var authHeader: [String: String] fileprivate let target: Target fileprivate var retryCount = 0 fileprivate let retryTimeInterval = 60.0 fileprivate let maxRetryCount = 5 // MARK: - Initialize @objc public init(email: String, authToken token: String, target: Target = .Production) { self.authHeader = [ "X-User-Email" : email, "X-User-Token" : token ] self.target = target super.init() if ASIdentifierManager.shared().isAdvertisingTrackingEnabled { Manager.advId = ASIdentifierManager.shared().advertisingIdentifier.uuidString } } // MARK: - Public methods @objc public func start() { self.stop() if Manager.customerId == nil { dlog("[LOG] customer id has not set") } self.retryCount = 0 self.fetchPackageVersion() } @objc public func restart() { self.start() } @objc public func stop() { self.monitoringManagers.forEach { $0.stopMonitoring() } self.monitoringManagers = [MonitoringManager]() } // MARK: - MonitoringManagerDelegate methods func didEnterBeaconRegion(uuid: String, major: Int, minor: Int, forReigon region: CLRegion) { self.sendEvent(.Enter, uuid: uuid, major: major, minor: minor) } func didExitBeaconRegion(uuid: String, major: Int, minor: Int, forReigon region: CLRegion) { self.sendEvent(.Exit, uuid: uuid, major: major, minor: minor) } // MARK: - Private help methods private func startMonitoring() { Manager.uuids.forEach { (uuid) in let region = CLBeaconRegion(proximityUUID: UUID(uuidString: uuid)!, identifier: "ZBEACON-" + uuid) region.notifyEntryStateOnDisplay = true let manager = MonitoringManager(region: region, delegate: self) manager.startMonitoring() self.monitoringManagers.append(manager) } dlog("[INFO] All start monitoring \(self.monitoringManagers.count)") debugDelegate?.debug(with: "Start monitoring for\n\t\(Manager.uuids.joined(separator: "\n\t"))\n\n", color: UIColor.black) } func fetchPackageVersion() { do { dlog("[INFO] Try to fetch package version") let opt = try HTTP.GET( self.packageVersionEndpoint, parameters: nil, headers: nil, requestSerializer: HTTPParameterSerializer()) opt.start({ [weak self] response in if response.error != nil { dlog("[ERR] Did fetch package version with ERROR: \(response.error!)") self?.startRetryTimer() } else { if let json = try? JSONSerialization.jsonObject(with: response.data, options: []), let result = json as? [String: AnyObject], let ibeaconPlugins = result["ibeacon_plugins"], let newestVersion = ibeaconPlugins["newest_version"] as? String, let minimumVersion = ibeaconPlugins["minimum_version"] as? String { dlog("[INFO] Did fetch package version with response: \(result)") // get current version let cv = Manager.currentPackageVersion if cv.compare(minimumVersion, options: .numeric) == .orderedSame || cv.compare(minimumVersion, options: .numeric) == .orderedDescending { // current version is newer than or equal to minimum version if cv.compare(newestVersion, options: .numeric) == .orderedAscending { // current version is older than newest version dlog("[INFO] Warning: Newest version \(newestVersion) is available") } self?.fetchUUIDs() } else { dlog("[ERR] Current version is not compatible. Need to upgrade to newest version: \(newestVersion)") } } } }) } catch { dlog("[ERR] Error on request to fetch package version") self.startRetryTimer() } } @objc func fetchUUIDs() { do { dlog("[INFO] Try to fetch uuids") let opt = try HTTP.GET( self.uuidEndpoint, parameters: nil, headers: self.authHeader, requestSerializer: HTTPParameterSerializer()) opt.start({ [weak self] response in if response.error != nil { dlog("[ERR] Did fetch uuids with ERROR: \(response.error!)") self?.startRetryTimer() } else { if let json = try? JSONSerialization.jsonObject(with: response.data, options: []), let result = json as? [String: AnyObject], let ibeacons = result["square_ibeacons"] as? [AnyObject] { dlog("[INFO] Did fetch uuids with response: \(ibeacons)") self?.retryCount = 0 Manager.uuids = [String]() ibeacons.enumerated().forEach({ if let uuid = ibeacons[$0.offset]["uuid"] as? String, let name = ibeacons[$0.offset]["name"] as? String { PrefStore.saveArea(uuid: uuid, name: name) Manager.uuids.append(uuid) } }) DispatchQueue.main.async(execute: { [weak self] in self?.startMonitoring() }) } } }) } catch { dlog("[ERR] Error on request to fetch uuids: \(error)") self.startRetryTimer() } } fileprivate func startRetryTimer() { if self.retryCount < self.maxRetryCount { dlog("[INFO] Set timer to retry fetch") self.retryCount = self.retryCount + 1 DispatchQueue.main.async { if #available(iOS 10.0, *) { Timer.scheduledTimer( withTimeInterval: self.retryTimeInterval, repeats: false, block: { (_) in self.fetchUUIDs() }) } else { Timer.scheduledTimer( timeInterval: self.retryTimeInterval, target: self, selector: #selector(self.fetchUUIDs), userInfo: nil, repeats: false) } } } } fileprivate func sendEvent( _ type: IBeaconRegionEvent, uuid: String, major: Int, minor: Int) { guard let advId = Manager.advId, advId != "" else { dlog("[ERR] Could not send signal due to missing advertise id") return } var params: [String: Any] = [ "package_id": Manager.packageId ?? "", "event": type.rawValue, "ad_id": advId, "ibeacon_uuid": uuid, "major": major, "minor": minor, "area": PrefStore.getArea(uuid: uuid) ?? "", "os": "ios", "device": Manager.model, "ts": "\(Date().microsecondsIntervalSince1970)", "sdk_version": Manager.currentPackageVersion ] if let customerId = Manager.customerId { params["customer_id"] = customerId } do { dlog("[REQ] Try to send event with params: \(params)\n") let opt = try HTTP.POST(self.dataEndpoint, parameters: params, requestSerializer: JSONParameterSerializer()) opt.start({ response in if response.error != nil { dlog("[ERR] Did send event with ERROR: \(response.error!)") debugDelegate?.receive(with: .error(data: params, event: type.rawValue)) if response.statusCode == 426 { dlog("[ERR] UnsupportedSDKVersionError: stop monitoring") debugDelegate?.receive(with: .error(data: params, event: type.rawValue)) self.stop() } } else { debugDelegate?.receive(with: .sent(data: params, event: type.rawValue)) dlog("[RES] Did send event to zoyi server response: \(response.data)\n") } }) } catch { dlog("[ERR] Error on create a new event request: \(error)") debugDelegate?.receive(with: .error(data: params, event: type.rawValue)) } } } <file_sep>/ZBeaconKit/RangingService.swift // // RangingService.swift // ZBeaconKit // // Created by sean on 08/16/17. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import CoreLocation import UIKit protocol RangingServiceDelegate: class { func didRangeBeacon(_ beacon: CLBeacon, forRegion region: CLBeaconRegion) func didFailRangeBeacon(forRegion region: CLBeaconRegion) } /** * CLLocationManagerDelegate method didRangeBeacons will not get called when * delegate method was implemented other than UIViewController. */ final class RangingService: UIViewController, CLLocationManagerDelegate { let locationManager = CLLocationManager() var rangingQueue = [CLBeaconRegion]() var isRanging = false // MARK: - Properties var region: CLBeaconRegion? { willSet(newRegion) { if !self.locationManager.rangedRegions.isEmpty && region?.isEqual(newRegion) == false { self.stopRanging() } if let region = newRegion { self.rangingQueue.append(region) } } didSet { self.startRanging() } } weak var delegate: RangingServiceDelegate? // MARK: - Initialize required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience init() { self.init(nibName: nil, bundle: nil) if #available(iOS 9.0, *){ self.locationManager.allowsBackgroundLocationUpdates = true } } deinit { self.stopRanging() } // MARK: - Ranging methods func startRanging() { guard !self.isRanging else { dlog("[INFO] Ranging is happening .. will execute after finish current one") return } guard let region = self.rangingQueue.first else { dlog("[INFO] Cancel to start ranging because region is nil") return } self.isRanging = true self.locationManager.delegate = self self.locationManager.startRangingBeacons(in: region) dlog("[INFO] Start ranging for region: \(region)") } func stopRanging() { guard let region = self.rangingQueue.first else { dlog("[INFO] Cancel to stop ranging because region is nil") return } self.isRanging = false self.rangingQueue.remove(at: 0) self.locationManager.stopRangingBeacons(in: region) dlog("[INFO] Stop ranging for region: \(region)") //consume ranging queue if let range = self.rangingQueue.first, self.rangingQueue.count != 0 { dlog("[INFO] Consuming ranging queue for \(range)") self.startRanging() } } // MARK: - Location Manager Delegate methods func locationManager( _ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) { guard manager.isEqual(self.locationManager) else { return } var rangedBeacon: CLBeacon? = nil for beacon in beacons { if beacon.proximityUUID.uuidString == region.proximityUUID.uuidString { if rangedBeacon == nil { rangedBeacon = beacon } else if rangedBeacon!.rssi < beacon.rssi { rangedBeacon = beacon } } } if let rBeacon = rangedBeacon { dlog("[INFO] did range beacon: \(rBeacon), for region: \(region)") self.delegate?.didRangeBeacon(rBeacon, forRegion: region) } else { dlog("[INFO] did fail range beacon for region: \(region)") self.delegate?.didFailRangeBeacon(forRegion: region) } } func locationManager( _ manager: CLLocationManager, rangingBeaconsDidFailFor region: CLBeaconRegion, withError error: Error) { dlog("[INFO] did fail range beacon for region: \(region), with error: \(error)") self.isRanging = false self.delegate?.didFailRangeBeacon(forRegion: region) } } <file_sep>/ZBeaconKit/UIDevice.swift // // UIDevice.swift // ZBeaconKit // // Created by <NAME> on 1/8/16. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import UIKit extension UIDevice { var modelName: String { switch UIDevice.current.systemVersion.compare("8.0.0", options: NSString.CompareOptions.numeric) { case .orderedSame, .orderedDescending: // iOS >= 8.0 var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) return machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } case .orderedAscending: return self.model // iOS < 8.0 } } var systemInfo: String { return self.systemName + " " + self.systemVersion } } <file_sep>/ZBeaconKit/CLBeacon.swift // // CLBeacon.swift // ZBeaconKit // // Created by <NAME> on 12/21/15. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import CoreLocation extension CLBeacon { func isSameUUIDWith(_ beacon: CLBeacon) -> Bool { return self.proximityUUID.uuidString == beacon.proximityUUID.uuidString } func isSameUUIDNMajorWith(_ beacon: CLBeacon) -> Bool { return isSameUUIDWith(beacon) && self.major.int32Value == beacon.major.int32Value } } <file_sep>/ZBeaconKit/NSNumber.swift // // NSNumber.swift // ZBeaconKit // // Created by <NAME> on 12/31/15. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation extension NSNumber { var hexValue: String { return String(format: "%2X", self.intValue) } } <file_sep>/ZBeaconKit/MonitoringService.swift // // MonitoringService.swift // ZBeaconKit // // Created by 이수완 on 2016. 10. 31.. // Copyright © 2018 ZOYI. All rights reserved. // import Foundation import CoreLocation import UIKit protocol MonitoringServiceDelegate: class { func didEnterRegion(_ region: CLBeaconRegion) func didExitRegion(_ region: CLBeaconRegion) func didChangeState(_ region: CLBeaconRegion, state: CLRegionState) } final class MonitoringService: UIViewController, CLLocationManagerDelegate { let locationManager = CLLocationManager() var isMonitoring = false var beaconRegion: CLBeaconRegion? weak var delegate: MonitoringServiceDelegate? required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience init() { self.init(nibName: nil, bundle: nil) if #available(iOS 9.0, *){ self.locationManager.allowsBackgroundLocationUpdates = true } self.activeLocationManager() self.prepareMonitoring() } func activeLocationManager() { self.locationManager.delegate = self } func inactiveLocationManager() { self.locationManager.delegate = nil } // MARK: - Help methods func isResponsibleFor(_ region: CLRegion, manager: CLLocationManager) -> Bool { return region.isEqual(beaconRegion) && manager.isEqual(locationManager) && manager.monitoredRegions.contains(region) } // MARK: - Monitoring methods func startMonitoring(withRegion region: CLBeaconRegion) { self.beaconRegion = region self.turnOnMonitoring() } func stopMonitoring() { guard let region = self.beaconRegion else { return } dlog("[INFO] Stop monitoring for region: \(region)") self.locationManager.stopMonitoring(for: region) self.beaconRegion = nil self.isMonitoring = false } fileprivate func turnOnMonitoring() { guard let region = self.beaconRegion else { return } dlog("[INFO] Start monitoring for region: \(region)") self.locationManager.startMonitoring(for: region) self.isMonitoring = true } fileprivate func prepareMonitoring() { dlog("[INFO] Prepare to start monitoring...") guard CLLocationManager.locationServicesEnabled() else { dlog("[ERR] Couldn't turn on monitoring: Location services are not enabled.") return } guard CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) else { dlog("[ERR] Couldn't turn on region monitoring: Region monitoring is not available for CLBeaconRegion class.") return } switch CLLocationManager.authorizationStatus() { case .authorizedAlways: break case .authorizedWhenInUse, .denied, .restricted: dlog("[ERR] Couldn't turn on monitoring: Required Location Access (Always) missing.") case .notDetermined: dlog("[INFO] About to request location authorization.") self.locationManager.requestAlwaysAuthorization() } } // MARK: - Location Manager Delegate methods func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { guard manager.isEqual(locationManager) else { return } switch status { case .authorizedAlways: if self.beaconRegion != nil && !self.isMonitoring { self.turnOnMonitoring() } case .authorizedWhenInUse, .denied, .restricted: dlog("[ERR] Couldn't turn on monitoring: Required Location Access (Always) missing.") default: break } } func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) { if let beaconRegion = region as? CLBeaconRegion { dlog("[INFO] Detect state \(state.rawValue) for region (\(beaconRegion)") self.delegate?.didChangeState(beaconRegion, state: state) debugDelegate?.receive(with: .state(region: beaconRegion, state: state)) } } func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { guard isResponsibleFor(region, manager: manager) else { return } if let beaconRegion = region as? CLBeaconRegion { dlog("[INFO] Did enter monitoring for region: \(beaconRegion)") self.delegate?.didEnterRegion(beaconRegion) debugDelegate?.receive(with: .enter(region: beaconRegion)) } } func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { guard isResponsibleFor(region, manager: manager) else { return } if let beaconRegion = region as? CLBeaconRegion { dlog("[INFO] Did exit monitoring for region: \(beaconRegion)") self.delegate?.didExitRegion(beaconRegion) debugDelegate?.receive(with: .exit(region: beaconRegion)) } } }
ccf79aa3a53e3707cd0019f05272cbad9ad58402
[ "Swift", "Ruby", "Markdown" ]
17
Swift
zoyi/sdk-ibeacon-ios-kddi
e3847c6389a24c119e0630652618ca40938987d6
b46a2ea316e1211bfbb40f0bbfa2a49b1d13b33a
refs/heads/master
<repo_name>TatoProgramming/WebGLProjects<file_sep>/terrainGen/README.txt You do have to run this using a webserver Features: Blending the water Random terrain generation Skybox <file_sep>/billards/Artem.js /** * Created by Taylor on 9/12/2017. * decided to create a JS library for this class. * I can develop it over the semester and put useful things in this */ (function (window) { 'use strict'; function define_library() { var Artem = {}; Artem.red = [1.0, 0.0, 0.0, 1.0]; Artem.green = [0.0, 1.0, 0.0, 1.0]; Artem.blue = [0.0, 0.0, 1.0, 1.0]; Artem.white = [1.0, 1.0, 1.0, 1.0]; Artem.black = [0.0, 0.0, 0.0, 1.0]; Artem.purple = [1.0, 0.0, 1.0, 1.0]; Artem.yellow = [1.0, 1.0, 0.0, 1.0]; Artem.gray = [0.5, 0.5, 0.5, 1.0]; Artem.orange = [1.0, 0.5, 0.0, 1.0]; Artem.brown = [0.647059, 0.164706, 0.164706, 1.0]; /** * Creates a circle * @param radius - radius of the circles * @param numberOfVertices - number of vertices * @param color - Can specify a color if wanted. * @returns {{radius: *, positionVertices: Array, colorVertices: Array}} */ Artem.createCircle = function (radius, numberOfVertices, color = null) { // TODO: figure out how to get this to work in plain javascript, without using the MV library. var circle = { radius: radius, positionVertices: [], colorVertices: [] }; var pi2 = 2.0 * Math.PI; for (var i = 0; i < numberOfVertices; ++i) { var position = (i / numberOfVertices) * pi2; circle.positionVertices.push( vec2( circle.radius * Math.cos(position), circle.radius * Math.sin(position) ) ); if (color) circle.colorVertices.push(color); } return circle; }; Artem.createRectangle = function (bottomLeftX, bottomLeftY, topRightX, topRightY, color = null) { var rectangle = { positionVertices: [], colorVertices: [], mvMatrix: mat4() }; rectangle.positionVertices.push(vec2(bottomLeftX, bottomLeftY)); rectangle.positionVertices.push(vec2(topRightX, bottomLeftY)); rectangle.positionVertices.push(vec2(topRightX, topRightY)); rectangle.positionVertices.push(vec2(bottomLeftX, topRightY)); if(color) for (var i = 0; i < 4; ++i) rectangle.colorVertices.push(color); return rectangle; }; /** * Gets the distance between two points */ Artem.distance = function (x1, y1, x2, y2) { return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); }; /** * Get the distance between two vectors */ Artem.distanceVec2 = function (firstVec2, secondVec2) { return this.distance(firstVec2[0], firstVec2[1], secondVec2[0], secondVec2[1]); }; Artem.multVec2ByScalar = function (vec, scalar) { return vec2(vec[0] * scalar, vec[1] * scalar); }; Artem.getReflectionVec2 = function(firstVec2, secondVec2){ var dotProd = dot(firstVec2, secondVec2); var refectionVector = this.multVec2ByScalar(secondVec2, dotProd * 2); refectionVector = subtract(refectionVector, firstVec2); return refectionVector; }; Artem.magnitude = function(vec2){ return Math.sqrt(Math.pow(vec2[0], 2) + Math.pow(vec2[1],2)); }; return Artem } if (typeof(Artem) === 'undefined') { window.Artem = define_library(); } else { console.log("Artem already defined."); } })(window); function createCircle(radius, numberOfVertices, vertices, scale) { createCircleWithColor(radius, numberOfVertices, vertices, null, scale) } function createCircleWithColor(radius, numberOfVertices, vertices, colorVertices, scale) { for (var i = 0; i < numberOfVertices; ++i) { vertices.push( vec2( radius * Math.cos((i / numberOfVertices) * 2.0 * Math.PI), radius * Math.sin((i / numberOfVertices) * 2.0 * Math.PI) ) ); // if(colorVertices != null) colorVertices.push(vec4(0.0, 0.0, 0.0, 0.0)); } scaleVertices(vertices, scale); } <file_sep>/rayMarch/README.txt Be sure to submit a screenshot of your image(s). Add any extra features below: Real-Time rendering/animation Shadows! moonScene.html Raymarching rendering of a scene shadows fog real time rendering Anti-aliasing fractal.html -- not entirely my code. This was an experimentation that didn't work out well Real time rendering of fractals shadows -- stuff that is not mine menger sponge sierpinski's tetrahedron mandelbulb <file_sep>/rayTracer/raytrace.js function getColorTestPattern(x, y) { x = (x+1)/2; y = (y+1)/2; return vec3(x, 1-x, y); } /** * x and y are the normalized device coordinates (-1, -1) to (1, 1). * Return a vec3 with the color at this (normalized) pixel coordinate. */ function getColor(x, y) { // TODO return vec3(0, 0, 0); } <file_sep>/terrainGen/cube.js /** * Created by Taylor on 10/20/2017. */ var Cube = function(imagesArr){ // Set up vertices, normals and texture coords var pointsArray = []; var colorsArray = []; var normalArray = []; var textureCoordsData = []; var cubeMap; var cubeMap2; loadTextureCube(); var vertices = [ vec4(-0.5, -0.5, 0.5, 1.0), vec4(-0.5, 0.5, 0.5, 1.0), vec4(0.5, 0.5, 0.5, 1.0), vec4(0.5, -0.5, 0.5, 1.0), vec4(-0.5, -0.5, -0.5, 1.0), vec4(-0.5, 0.5, -0.5, 1.0), vec4(0.5, 0.5, -0.5, 1.0), vec4(0.5, -0.5, -0.5, 1.0) ]; var texCoord = [ vec2(0, 0), vec2(0, 1), vec2(1, 1), vec2(1, 0) ]; createCube(); for(var i = 0; i < pointsArray.length; ++i){ colorsArray.push(vec4(0.0, 0.0, 0.0, 1.0)); } this.vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW); this.colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW); this.textureBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.textureBuffer); gl.bufferData(gl.ARRAY_BUFFER, flatten(textureCoordsData), gl.STATIC_DRAW); // loadTextureCubeGeneric(urls, gl.TEXTURE0); this.numPoints = pointsArray.length; function loadTextureCube(){ var ct = 0; var img = new Array(6); var urls = [ "daylight/xpos.png", "daylight/xneg.png", "daylight/ypos.png", "daylight/yneg.png", "daylight/zpos.png", "daylight/zneg.png" ]; for(var i = 0; i < 6; i++){ img[i] = new Image(); img[i].onload = function(){ ct++; if(ct === 6){ cubeMap = gl.createTexture(); gl.bindTexture(gl.TEXTURE_CUBE_MAP, cubeMap); gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img[0]); gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img[1]); gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img[2]); gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img[3]); gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img[4]); gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img[5]); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.activeTexture(gl.TEXTURE0); } }; img[i].src = urls[i]; } } function quad(a, b, c, d){ pointsArray.push(vertices[a]); textureCoordsData.push(texCoord[0]); pointsArray.push(vertices[b]); textureCoordsData.push(texCoord[1]); pointsArray.push(vertices[c]); textureCoordsData.push(texCoord[2]); pointsArray.push(vertices[a]); textureCoordsData.push(texCoord[0]); pointsArray.push(vertices[c]); textureCoordsData.push(texCoord[2]); pointsArray.push(vertices[d]); textureCoordsData.push(texCoord[3]); } function createCube(){ quad(1, 0, 3, 2); quad(2, 3, 7, 6); quad(3, 0, 4, 7); quad(6, 5, 1, 2); quad(4, 5, 6, 7); quad(5, 4, 0, 1); } }; <file_sep>/terrainGen/terrainGenerator.js /** * Created by Taylor on 10/19/2017. */ "use strict"; var MountainTerrain = function(parameters){ var inc = parameters.inc; var max = parameters.max; var offset = parameters.offset; var coeff1 = parameters.coeff1; var coeff2 = parameters.coeff2; var power = parameters.power; var seed = parameters.seed; var points2D = []; var normals = []; var vertices = []; var colors = []; // var inc = 0.05; // var max = 5; var min = -max; // var seed = Math.random(); // var offset = 0.04; // console.log(seed); // noise.seed(0.33662259779794024); var offsetCalc = inc - offset; noise.seed(seed); // TODO: create these value to be set by the user to give them control // TODO: make the iterations fit to a size. var zCord = min; for(var i = min; i <= max; i += inc){ var xCord = min; var innerArr = []; for(var j = min; j <= max; j += inc){ var e = noise.perlin2(xCord, zCord) + coeff1 * noise.perlin2(2 * xCord, 2 * zCord) // Todo create a way to set these co-ef + coeff2 * noise.perlin2(4 * xCord, 4 * zCord); var pow = Math.pow(e, power); // TODO: Create a way to set the power var y = isNaN(pow) ? 0 : pow; innerArr.push(vec4(xCord + random(-offset, offset), y, zCord + random(-offset, offset), 1.0)); // innerArr.push(vec4(xCord, y, zCord , 1.0)); xCord += inc; } points2D.push(innerArr); zCord += inc; } // createMesh(points2D); // createColors(); createTriangles(points2D); this.normals = normals; this.vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW); this.colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW); this.normalBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer); gl.bufferData(gl.ARRAY_BUFFER, flatten(normals), gl.STATIC_DRAW); this.numVertices = vertices.length; function random(min, max){ return Math.random() * (max - min) + min; } function createMesh(points){ for(var i = 0; i < points.length - 1; ++i){ for(var j = 0; j < points.length - 1; ++j){ var a = points[i][j]; var b = points[i][j + 1]; var c = points[i + 1][j]; var d = points[i + 1][j + 1]; vertices.push(a); vertices.push(b); vertices.push(b); vertices.push(d); vertices.push(d); vertices.push(a); vertices.push(a); vertices.push(c); vertices.push(c); vertices.push(d); } } } function createColors(){ for(var i = 0; i < vertices.length; ++i){ colors.push(getBiomeColor(vertices[i])); } } function createTriangles(points){ for(var i = 0; i < points.length - 1; ++i){ for(var j = 0; j < points.length - 1; ++j){ var a = points[i][j]; var b = points[i][j + 1]; var c = points[i + 1][j]; var d = points[i + 1][j + 1]; // find max y push color 3 times vertices.push(a); vertices.push(c); vertices.push(d); // console.log(maxY([a,c,d])); createNormals(a, c, d); pushTriColor(maxY([a, c, d])); // find max y push color 3 times vertices.push(a); vertices.push(b); vertices.push(d); createNormals(a, d, b); pushTriColor(maxY([a, b, d])); } } // for (var i = 0; i < this.points2D.length; ++i) { // for (var j = 0; j < this.points2D.length; ++j) { // // } // } } function createNormals(a, b, c){ var normal = computeNormalTriangle(a, b, c); for(var i = 0; i < 3; ++i){ normals.push(normal); } } function pushTriColor(y){ for(var i = 0; i < 3; ++i){ colors.push(getBiomeColor(y)) } } function maxY(points){ var max = points[0][1]; for(var i = 1; i < points.length; ++i){ var y = points[i][1]; if(max < y){ max = y; } } // console.log(max); return max; } function getBiomeColor(y){ if(y < -0.1){ return vec4(146 / 255, 129 / 255, 124 / 255); }else if(y < -0.02){ return vec4(1.0, 0.8, 0.6, 1.0); }else if(y < 0.2){ return vec4(0.2, 0.5, 0.0, 1.0); }else if(y < 0.4){ return vec4(0.4, 0.5, 0.3, 1.0); }else if(y < 0.8){ return vec4(0.5, 0.5, 0.5, 1.0); }else{ return vec4(1.0, 1.0, 1.0, 1.0); } } function computeNormalTriangle(a, b, c){ var u = subtract(c, a); var v = subtract(c, b); var crossProduct = cross(u, v); crossProduct.push(1.0); return normalize(crossProduct, true); } }; <file_sep>/terrainGen/water.js /** * Created by Taylor on 10/27/2017. */ var Water = function(inc, max, yHeight, color){ var vertices = []; var normals = []; var min = -max; var animationSize = 10; this.uColor = color; this.seed = Math.random(); noise.seed(this.seed); // var cubeMap;/ // function generatePoints(time){ var points = []; var zCoord = min; for(var i = min; i <= max; i += inc){ var xCoord = min; var innerArr = []; for(var j = min; j <= max; j += inc){ var xTime = xCoord + time; var zTime = zCoord + time; var e = noise.perlin2(xTime * 8, zTime * 8); innerArr.push(vec4(xCoord, e / 15 + yHeight, zCoord)); xCoord += inc; } points.push(innerArr); zCoord += inc; } createTriangles(points); // } // for(var i = 0; i < animationSize; ++i){ // generatePoints(i); // } // generatePoints(0); this.vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW); this.normalBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer); gl.bufferData(gl.ARRAY_BUFFER, flatten(normals), gl.STATIC_DRAW); if(vertices.length !== normals.length) throw "Normals and vertices are not the same length"; this.numVertices = vertices.length; function createTriangles(points){ for(var i = 0; i < points.length - 1; ++i){ for(var j = 0; j < points.length - 1; ++j){ var a = points[i][j]; var b = points[i][j + 1]; var c = points[i + 1][j]; var d = points[i + 1][j + 1]; // find max y push color 3 times vertices.push(a); vertices.push(c); vertices.push(d); createNormals(a, c, d); // pushTriColor(maxY([a, c, d])); // find max y push color 3 times vertices.push(a); vertices.push(b); vertices.push(d); createNormals(a, d, b); // pushTriColor(maxY([a, b, d])); } } } function createNormals(a, b, c){ var normal = computeNormalTriangle(a, b, c); for(var i = 0; i < 3; ++i){ normals.push(normal); } } function computeNormalTriangle(a, b, c){ var u = subtract(c, a); var v = subtract(c, b); var crossProduct = cross(u, v); crossProduct.push(1.0); return normalize(crossProduct, true); } }; <file_sep>/billards/common/util.js /** * Created by Taylor on 9/7/2017. */ /** * Gets a random number between a range * @param min - min value * @param max - max value * @returns {*} */ function getRandomRangedNumber(min, max) { return Math.random() * (max - min) + min; } /** * Get a random number between 0.0 and 1.0 * @returns {*} */ function getRandomNumberBetween0and1() { return getRandomRangedNumber(0.0, 1.0); } /** * Generates a zero or a one randomly * @returns {*} */ function randomOneOrZero() { return getRandomRangedNumber(0, 1); } /** * Scales the vertices * @param s - size * @param vertices - the vertices array to scale */ function scaleVertices(s, vertices) { for (var i = 0; i < vertices.length; ++i) { vertices[i] = scale(s, vertices[i]); } } <file_sep>/serpinskiCarpet/js/code.js /** * Created by Taylor on 8/23/2017. */ var gl; var canvasWidth, canvasHeight; var bufferId; var colorBufferId; var vertices = []; var colors = []; var fullScreen = false; var button = false; var oneThird = 1 / 3; var twoThird = 2 / 3; var numberOfIteration = 0; var a = vec2(-2, -2); //a var b = vec2(2, -2); //d var c = vec2(-2, 2); //m var f = vec2(2, 2); //p /** * Renders the lines */ function render() { vertices = []; divideSquare(a, b, c, f, numberOfIteration); scaleVertices(0.5, vertices); gl.clear(gl.COLOR_BUFFER_BIT); // send to points to the buffer gl.bindBuffer(gl.ARRAY_BUFFER, bufferId); gl.bufferData(gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW); if (button) { gl.drawArrays(gl.POINTS, 0, vertices.length); } else { gl.drawArrays(gl.TRIANGLES, 0, vertices.length); } } function test() { button = !button; render(); } function selectionChange(element) { numberOfIteration = parseInt(element.value); console.log(numberOfIteration); render(); } window.onload = function init() { var canvas = document.getElementById("gl-canvas"); if (fullScreen) { canvas.width = window.innerWidth; canvas.height = window.innerHeight; } canvasWidth = canvas.width; canvasHeight = canvas.height; gl = WebGLUtils.setupWebGL(canvas); if (!gl) { alert("WebGL is not available!"); } // Configures gl.viewport(0, 0, canvasWidth, canvasHeight); gl.clearColor(0.0, 0.0, 0.0, 1.0); var program = initShaders(gl, "vertex-shader", "fragment-shader"); gl.useProgram(program); bufferId = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, bufferId); var vPosition = gl.getAttribLocation(program, "vPosition"); gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vPosition); render(); }; function topRightSquare(k, l, p, o) { vertices.push(k); vertices.push(l); vertices.push(p); vertices.push(k); vertices.push(o); vertices.push(p); } function middleRightSquare(g, h, l, k) { vertices.push(g); vertices.push(h); vertices.push(l); vertices.push(g); vertices.push(k); vertices.push(l); } function bottomLeftSquare(a, b, f, e) { vertices.push(a); vertices.push(b); vertices.push(f); vertices.push(a); vertices.push(e); vertices.push(f); } function middleLeftSquare(e, f, j, i) { vertices.push(e); vertices.push(f); vertices.push(j); vertices.push(e); vertices.push(i); vertices.push(j); } function topLeftSquare(i, j, n, m) { vertices.push(i); vertices.push(j); vertices.push(n); vertices.push(i); vertices.push(m); vertices.push(n); } function bottomMiddleSquare(b, c, g, f) { vertices.push(b); vertices.push(c); vertices.push(g); vertices.push(b); vertices.push(f); vertices.push(g); } function topMiddleSquare(j, k, o, n) { vertices.push(j); vertices.push(k); vertices.push(o); vertices.push(j); vertices.push(n); vertices.push(o); } function bottomRightSquare(c, d, h, g) { vertices.push(c); vertices.push(d); vertices.push(h); vertices.push(c); vertices.push(g); vertices.push(h); } /* m------------n------------o------------p | | | | | | | | | tl | tm | tr | | | | | | | | | i------------j------------k------------l | | | | | | | | | ml | m | mr | | | | | | | | | e------------f------------g------------h | | | | | | | | | bl | bm | br | | | | | | | | | a------------b------------c------------d */ function divideSquare(a, d, m, p, count) { // calculate the points var b = mix(a, d, oneThird); var c = mix(a, d, twoThird); var e = mix(a, m, oneThird); var f = vec2(b[0], e[1]); var g = vec2(c[0], e[1]); var h = mix(d, p, oneThird); var i = mix(a, m, twoThird); var j = vec2(b[0], i[1]); var k = vec2(c[0], i[1]); var l = mix(d, p, twoThird); var n = mix(m, p, oneThird); var o = mix(m, p, twoThird); if (count === 0) { bottomLeftSquare(a, b, f, e); middleLeftSquare(e, f, j, i); topLeftSquare(i, j, n, m); bottomMiddleSquare(b, c, g, f); topMiddleSquare(j, k, o, n); bottomRightSquare(c, d, h, g); middleRightSquare(g, h, l, k); topRightSquare(k, l, p, o); } else { --count; divideSquare(a, b, e, f, count); divideSquare(b, c, f, g, count); divideSquare(c, d, g, h, count); divideSquare(a, b, e, f, count); divideSquare(e, f, i, j, count); divideSquare(g, h, k, l, count); divideSquare(i, j, m, n, count); divideSquare(j, k, n, o, count); divideSquare(k, l, o, p, count); } } <file_sep>/README.md # WebGLProjects A collection of webgl projects I did in Advanced Computer Graphics course at Idaho State University. <file_sep>/billards/billiards.js "use strict"; //------------------------------------------------------------ // Global variables //------------------------------------------------------------ // Feature Idea: Have a course prediction for the white ball so that you can do cool shots // Feature Idea: balls explode into to pixels after getting it into the hole var gl; var circle; // the circle obj with the vertices var cue; var ballBufferId; var tableBufferId; var vectorLinesBufferId; var cueBuffferId; var line = [vec2(0, 0), vec2(0, 0.5)]; var mvMatrixLoc; var uColor; var vPosition; var vectorLines = []; var deltaTime; var lastUpdate; var program; var initMousePosition; var debugMode = false; var pulling = false; var table; // gets the time between updates function calculateDeltaTime() { var now = Date.now(); deltaTime = (now - lastUpdate) / 1000; lastUpdate = now; } function animate() { // TODO: compute elapsed time from last render and update the balls' // positions and velocities accordingly. calculateDeltaTime(); table.updateTable(deltaTime); } function tick() { requestAnimFrame(tick); render(); animate(); } //------------------------------------------------------------ // render() //------------------------------------------------------------ function renderBalls() { gl.bindBuffer(gl.ARRAY_BUFFER, ballBufferId); gl.bufferData(gl.ARRAY_BUFFER, flatten(circle.positionVertices), gl.STATIC_DRAW); gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vPosition); for (var i = 0; i < table.balls.length; ++i) { gl.uniform4fv(uColor, flatten(table.balls[i].uColor)); gl.uniformMatrix4fv(mvMatrixLoc, false, flatten(table.balls[i].mvMatrix)); gl.drawArrays(gl.TRIANGLE_FAN, 0, circle.positionVertices.length); } } function renderCue() { gl.bindBuffer(gl.ARRAY_BUFFER, cueBuffferId); gl.bufferData(gl.ARRAY_BUFFER, flatten(cue.tipVertices), gl.STATIC_DRAW); gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vPosition); gl.uniform4fv(uColor, flatten(cue.tipColor.uColor)); gl.uniformMatrix4fv(mvMatrixLoc, false, flatten(cue.mvMatrix)); gl.drawArrays(gl.TRIANGLE_FAN, 0, cue.tipVertices.length); } function renderTable() { gl.bindBuffer(gl.ARRAY_BUFFER, tableBufferId); gl.bufferData(gl.ARRAY_BUFFER, flatten(table.rect.positionVertices), gl.STATIC_DRAW); gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vPosition); for (var i = 0; i < table.surfaces.length; ++i) { gl.uniform4fv(uColor, flatten(table.surfaces[i].uColor)); gl.uniformMatrix4fv(mvMatrixLoc, false, flatten(table.surfaces[i].mvMatrix)); gl.drawArrays(gl.TRIANGLE_FAN, 0, table.rect.positionVertices.length); } } // helpful for debugging shows all of the vectors function renderVectors() { // create all of the vector lines for the acceleration and velocity for (var j = 0; j < table.balls.length; ++j) { var ball = table.balls[j]; if (Artem.magnitude(ball.velocity) > 0) { vectorLines.push(new Lines(Artem.blue, ball.position, ball.velocity)); vectorLines.push(new Lines(Artem.red, ball.position, ball.acceleration)); } } gl.bindBuffer(gl.ARRAY_BUFFER, vectorLinesBufferId); gl.bufferData(gl.ARRAY_BUFFER, flatten(line), gl.STATIC_DRAW); gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vPosition); for (var i = 0; i < vectorLines.length; ++i) { gl.uniform4fv(uColor, flatten(vectorLines[i].color)); gl.uniformMatrix4fv(mvMatrixLoc, false, flatten(vectorLines[i].mvMatrix)); gl.drawArrays(gl.LINES, 0, 2); } vectorLines = []; } function render() { gl.clear(gl.COLOR_BUFFER_BIT); renderTable(); renderBalls(); // renderCue(); if (debugMode) { renderVectors(); } } //------------------------------------------------------------ // Initialization //------------------------------------------------------------ /** * Initializes webgl, shaders and event callbacks. */ window.onload = function init() { var canvas = document.getElementById('gl-canvas'); var canvasWidth = canvas.width; var canvasHeight = canvas.height; gl = WebGLUtils.setupWebGL(canvas); if (!gl) { alert("WebGL isn't available"); } // creates a circle which contains circle = Artem.createCircle(0.03, 50); table = new BilliardsTable(-0.9, -0.5, 0.9, 0.5); // cue = new CueStick(); //---------------------------------------- // Configure WebGL //---------------------------------------- gl.viewport(0, 0, canvasWidth, canvasHeight); gl.clearColor(0.0, 0.0, 0.0, 1.0); // load shaders and initialize attribute buffers program = initShaders(gl, "vertex-shader", "fragment-shader"); gl.useProgram(program); uColor = gl.getUniformLocation(program, "uColor"); mvMatrixLoc = gl.getUniformLocation(program, "mvMatrix"); vPosition = gl.getAttribLocation(program, "vPosition"); ballBufferId = gl.createBuffer(); tableBufferId = gl.createBuffer(); vectorLinesBufferId = gl.createBuffer(); cueBuffferId = gl.createBuffer(); canvas.addEventListener("mousedown", function (event) { var mousePosition = getMousePosition(event); if (Artem.distanceVec2(mousePosition, table.whiteBall.position) <= table.whiteBall.radius) { pulling = true; initMousePosition = mousePosition; } cue = CueStick(table.whiteBall.position, mousePosition) }); canvas.addEventListener("mouseup", function (event) { if (pulling) { var mousePos = getMousePosition(event); var vectorBetween = subtract(mousePos, initMousePosition); table.whiteBall.applyForce(Artem.multVec2ByScalar(vectorBetween, -5.0)); pulling = false; } }); lastUpdate = Date.now(); tick(); }; function poolParty(){ var ball = new Ball(circle.radius, vec4(Math.random(), Math.random(), Math.random(), 1.0), 0.0,0.0); ball.velocity = vec2(getRandomRangedNumber(-1,1), getRandomRangedNumber(-1,1)); table.balls.push(ball); } function toggleDebugMode() { debugMode = !debugMode; } function getMousePosition(event) { var mouseX = (event.offsetX / gl.canvas.width) * 2 - 1; var mouseY = (1 - (event.offsetY / gl.canvas.height)) * 2 - 1; return vec2(mouseX, mouseY); } // class for the ball class Ball { constructor(radius, uColor, xCenter, yCenter) { this.radius = radius; this.uColor = uColor; this.isWhiteBall = uColor == Artem.white; this.isBlackBall = uColor == Artem.black; this.mvMatrix = mat4(); this.position = vec2(xCenter, yCenter); this.velocity = vec2(); this.coefFriction = 0; this.acceleration = vec2(); } update(deltaTime) { this.updateAcceleration(); this.updateVelocity(deltaTime); this.updatePosition(deltaTime); this.mvMatrix = translate(this.position[0], this.position[1], 0); } updatePosition(t) { this.position = add( add( Artem.multVec2ByScalar(this.acceleration, 0.5 * t * t), // 1/2 * a * t^2 Artem.multVec2ByScalar(this.velocity, t) // v * t ), this.position // x ); } updateAcceleration() { this.acceleration = Artem.multVec2ByScalar(this.velocity, -1.0); } updateVelocity(t) { this.velocity = add(Artem.multVec2ByScalar(this.acceleration, t), this.velocity); if (Artem.magnitude(this.velocity) < 0.005) { this.velocity = vec2(); } } // check to see if a ball is colliding with another ball isColliding(otherBall) { var d = Artem.distanceVec2(this.position, otherBall.position); return d <= this.radius + otherBall.radius; } collision(otherBall) { var normal = normalize(subtract(this.position, otherBall.position)); var negNormal = Artem.multVec2ByScalar(normal, -1.0); var normalVelocity1 = Artem.multVec2ByScalar(negNormal, dot(this.velocity, negNormal)); var normalVelocity2 = Artem.multVec2ByScalar(normal, dot(otherBall.velocity, normal)); var tangentVelocity1 = subtract(this.velocity, normalVelocity1); var tangentVelocity2 = subtract(otherBall.velocity, normalVelocity2); this.velocity = add(normalVelocity2, tangentVelocity1); otherBall.velocity = add(normalVelocity1, tangentVelocity2); // var d = Artem.distanceVec2(this.position, otherBall.position); // // if (d <= this.radius + this.radius) { // // console.log("thingy: "+ d + " inside"); // normal = Artem.multVec2ByScalar(normal, this.radius / 2 - 0.001); // negNormal = Artem.multVec2ByScalar(negNormal, this.radius / 2 - 0.001); // // console.log(negNormal); // // console.log(normal); // this.position = add(this.position, normal); // otherBall.position = add(otherBall.position, negNormal); // // } } applyForce(vec2) { this.velocity = vec2; } } // TODO: create this class CueStick { constructor(whiteBallPosition, mousePosition) { this.tipVertices = []; this.tipVertices.push(whiteBallPosition); this.tipVertices.push(mousePosition); this.mvMatrix = mat4(); this.tipColor = Artem.white; } } // class for the table class BilliardsTable { constructor(x1, y1, x2, y2) { this.balls = []; this.surfaces = []; this.rect = Artem.createRectangle(x1, y1, x2, y2); this.rightBoundary = x2; this.leftBoundary = x1; this.topBoundary = y2; this.bottomBoundary = y1; this.rightWallVec = normalize(subtract(vec2(x2, y2), vec2(x2, y1))); this.leftWallVec = normalize(subtract(vec2(x1, y1), vec2(x1, y2))); this.topWallVec = normalize(subtract(vec2(x2, y2), vec2(x1, y2))); this.bottomWallVec = normalize(subtract(vec2(x2, y1), vec2(x1, y1))); this.setUpTable(); this.whiteBall = this.balls[0]; } createTableSurface() { var surface1 = { mvMatrix: mult(this.rect.mvMatrix, scalem(1.1, 1.2, 1.1)), uColor: Artem.gray }; this.surfaces.push(surface1); var surface = { mvMatrix: mat4(), uColor: vec4(0.0, 0.7, 0.0, 1.0) }; this.surfaces.push(surface); } updateTable(deltaTime) { // maybe there is a better way to handle the collisions // collision loop for (var i = 0; i < this.balls.length; ++i) { var ball = this.balls[i]; // check collisions for (var j = i + 1; j < this.balls.length; ++j) { if (ball.isColliding(this.balls[j])) { ball.collision(this.balls[j]); } // var d = Artem.distanceVec2(ball.position, this.balls[j].position); // if (d <= ball.radius * 4 && debugMode) { // var normal = normalize(subtract(ball.position, this.balls[j].position)); // var negNormal = Artem.multVec2ByScalar(normal, -1.0); // // vectorLines.push(new Lines(Artem.purple, ball.position, normal)); // vectorLines.push(new Lines(Artem.purple, this.balls[j].position, negNormal)); // // var normalVelocity1 = Artem.multVec2ByScalar(negNormal, dot(ball.velocity, negNormal)); // var normalVelocity2 = Artem.multVec2ByScalar(normal, dot(this.balls[j].velocity, normal)); // // vectorLines.push(new Lines(Artem.yellow, ball.position, normalVelocity1)); // vectorLines.push(new Lines(Artem.yellow, this.balls[j].position, normalVelocity2)); // // var tangentVelocity1 = subtract(ball.velocity, normalVelocity1); // var tangentVelocity2 = subtract(this.balls[j].velocity, normalVelocity2); // // vectorLines.push(new Lines(Artem.black, ball.position, tangentVelocity1)); // vectorLines.push(new Lines(Artem.black, this.balls[j].position, tangentVelocity2)); // } } this.wallCollision(ball); this.balls[i].update(deltaTime); } } wallCollision(ball) { if (ball.position[0] + ball.radius >= this.rightBoundary) { ball.velocity = Artem.getReflectionVec2(ball.velocity, this.rightWallVec); } else if (ball.position[0] - ball.radius <= this.leftBoundary) { ball.velocity = Artem.getReflectionVec2(ball.velocity, this.leftWallVec); } else if (ball.position[1] + ball.radius >= this.topBoundary) { ball.velocity = Artem.getReflectionVec2(ball.velocity, this.topWallVec); } else if (ball.position[1] - ball.radius <= this.bottomBoundary) { ball.velocity = Artem.getReflectionVec2(ball.velocity, this.bottomWallVec); } } setUpTable() { var xOff = 0.3; var yOff = 0.0; this.balls.push(new Ball(circle.radius, Artem.white, -0.5, 0.0)); this.balls.push(new Ball(circle.radius, Artem.red, -0.095 + xOff, 0.0 + yOff)); this.balls.push(new Ball(circle.radius, Artem.purple, -0.0325 + xOff, 0.0325 + yOff)); this.balls.push(new Ball(circle.radius, Artem.orange, -0.0325 + xOff, -0.0325 + yOff)); this.balls.push(new Ball(circle.radius, Artem.gray, 0.0325 + xOff, 0.065 + yOff)); this.balls.push(new Ball(circle.radius, Artem.green, 0.0325 + xOff, 0.0 + yOff)); this.balls.push(new Ball(circle.radius, Artem.blue, 0.0325 + xOff, -0.065 + yOff)); this.balls.push(new Ball(circle.radius, Artem.red, 0.095 + xOff, -0.0975 + yOff)); this.balls.push(new Ball(circle.radius, Artem.gray, 0.095 + xOff, 0.0975 + yOff)); this.balls.push(new Ball(circle.radius, Artem.green, 0.095 + xOff, 0.0325 + yOff)); this.balls.push(new Ball(circle.radius, Artem.blue, 0.095 + xOff, -0.0325 + yOff)); this.balls.push(new Ball(circle.radius, Artem.yellow, 0.15 + xOff, -0.13 + yOff)); this.balls.push(new Ball(circle.radius, Artem.black, 0.15 + xOff, -0.065 + yOff)); this.balls.push(new Ball(circle.radius, Artem.purple, 0.15 + xOff, 0.13 + yOff)); this.balls.push(new Ball(circle.radius, Artem.orange, 0.15 + xOff, 0.065 + yOff)); this.balls.push(new Ball(circle.radius, Artem.brown, 0.15 + xOff, 0.0 + yOff)); this.createTableSurface(); } } class Lines { constructor(color, position, vector) { this.color = color; this.vector = vector; this.position = position; this.mvMatrix = mult(mat4(), translate(position[0], position[1], 0.0)); this.rotate(); } rotate() { var vec = vec2(0, 1); var magVec = Artem.magnitude(this.vector); var a = dot(vec, this.vector); var b = Artem.magnitude(vec) * magVec; var angle = Math.acos(a / b) * (180 / Math.PI); if (this.vector[0] < 0) { angle = -angle; } this.mvMatrix = mult(this.mvMatrix, rotateZ(angle)); this.mvMatrix = mult(this.mvMatrix, scalem(magVec * .5, magVec * .5, 1)); } } <file_sep>/motionCap/mocap.js "use strict"; var canvas; var gl; var audio; const near = 0.01; const far = 100; const radius = 5; var atX = 0.0; var atY = 0.0; var atZ = 0.0; // Viewing var aspect = 1.0; var view = "A"; var angle = 0; var fieldOfView = 10.0; var frameNumber = 0; var isPaused = false; // Data var bvh; var sphere; var floor; var axis; var segment; var lineBufferId; var lineColorBufferId; var sphereProgram, lineProgram; var vPosition; var mvMatrix, pMatrix, nMatrix; var reader = new FileReader(); var matrixStack = []; var positionStack = []; reader.onload = function (e) { var text = reader.result; }; function pushPosition(xOffset, yOffset, zOffSet) { if (positionStack.length === 0) { positionStack.push(new Vec4Position(xOffset, yOffset, zOffSet)); } else { var previousPosition = peekPositionStack(); var newPosition = new Vec4Position( previousPosition.x + xOffset, previousPosition.y + yOffset, previousPosition.z + zOffSet ); positionStack.push(newPosition); } } function popPosition() { positionStack.pop(); } function playAudio(fileName) { audio = new Audio(fileName); audio.play(); } function stopAudio() { audio.stop(); } function peekPositionStack() { return positionStack[positionStack.length - 1]; } function pushMatrix() { matrixStack.push(mat4(mvMatrix)); } function popMatrix() { mvMatrix = matrixStack.pop(); } var setCamera = function () { const at = scale(0.01, vec3(atX, atY, atZ)); const theta = radians(angle); var up = vec3(0.0, 1.0, 0.0); var eye = vec3(radius * Math.sin(theta), radius * Math.sin(radians(10.0)), radius * Math.cos(theta)); pMatrix = perspective(fieldOfView, aspect, near, far); mvMatrix = lookAt(eye, at, up); }; function render() { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); setCamera(); renderFloor(); mvMatrix = mult(mvMatrix, scalem(0.01, 0.01, 0.01)); var root = bvh.roots[0]; renderChildNode(root, bvh.frames[frameNumber]); if (!isPaused) { frameNumber++; } if (frameNumber >= bvh.numFrames) { frameNumber = 0; } requestAnimFrame(render); } function getDistance(v, u) { if (v.length !== u.length) { throw "Not equal in size"; } var sum = 0.0; for (var i = 0; i < v.length; ++i) { sum += Math.pow(v[i] - u[i], 2); } return Math.sqrt(sum); } function getChildPosition(node, frame) { var offset = node.channelOffset; var zPos = node.channels.indexOf("Zposition"); var xPos = node.channels.indexOf("Xposition"); var yPos = node.channels.indexOf("Yposition"); var x = xPos < 0 ? node.offsets[0] : frame[offset + xPos]; var y = yPos < 0 ? node.offsets[1] : frame[offset + yPos]; var z = zPos < 0 ? node.offsets[2] : frame[offset + zPos]; return vec3(x, y, z); } function renderChildNode(node, frame) { // console.log(parent.name); for (var i = 0; i < node.children.length; ++i) { var offset = node.channelOffset; pushMatrix(); var zRot = node.channels.indexOf("Zrotation"); var xRot = node.channels.indexOf("Xrotation"); var yRot = node.channels.indexOf("Yrotation"); var zPos = node.channels.indexOf("Zposition"); var xPos = node.channels.indexOf("Xposition"); var yPos = node.channels.indexOf("Yposition"); var x = xPos < 0 ? node.offsets[0] : frame[offset + xPos]; var y = yPos < 0 ? node.offsets[1] : frame[offset + yPos]; var z = zPos < 0 ? node.offsets[2] : frame[offset + zPos]; if (node.name === "Hips") { atX = frame[offset + xPos]; atY = frame[offset + yPos]; atZ = frame[offset + zPos]; }else{ pushMatrix(); var v = vec3(x, y, z); var vMag = length(v); var xPrime = vec3(1, 0, 0); var abritAxis = cross(v, xPrime); var vDotx = dot(v, xPrime); // var normalized = vMag * mag(xPrime); var theta1 = -(Math.acos(vDotx/vMag) * 180) / Math.PI; mvMatrix = mult(mvMatrix, scalem(vMag, vMag, vMag)); mvMatrix = mult(mvMatrix, rotate(theta1, abritAxis)); renderSegment(); popMatrix(); } mvMatrix = mult(mvMatrix, translate(x, y, z)); mvMatrix = mult(mvMatrix, rotateZ(frame[offset + zRot])); mvMatrix = mult(mvMatrix, rotateY(frame[offset + yRot])); mvMatrix = mult(mvMatrix, rotateX(frame[offset + xRot])); pushMatrix(); if (node.name === "Head") { mvMatrix = mult(mvMatrix, scalem(1.2, 1.7, 1.2)); } else { mvMatrix = mult(mvMatrix, scalem(.5, .5, .5)); } renderSphere(); popMatrix(); renderChildNode(node.children[i], frame); popMatrix(); } } function mag(u) { return Math.sqrt(Math.pow(u[0], 2) + Math.pow(u[1], 2) + Math.pow(u[2], 2)); } var Vec4Position = function (x, y, z) { this.x = x; this.y = y; this.z = z; this.h = 1.0; }; var LineProgram = function () { this.program = initShaders(gl, "line-vshader", "line-fshader"); gl.useProgram(this.program); this.vertexLoc = gl.getAttribLocation(this.program, "vPosition"); this.colorLoc = gl.getAttribLocation(this.program, "vColor"); this.mvMatrixLoc = gl.getUniformLocation(this.program, "mvMatrix"); this.pMatrixLoc = gl.getUniformLocation(this.program, "pMatrix"); this.nMatrixLoc = gl.getUniformLocation(this.program, "nMatrix"); }; var SphereProgram = function () { this.program = initShaders(gl, "sphere-vshader", "sphere-fshader"); gl.useProgram(this.program); this.vertexLoc = gl.getAttribLocation(this.program, "vPosition"); this.normalLoc = gl.getAttribLocation(this.program, "vNormal"); this.colorLoc = gl.getAttribLocation(this.program, "vColor"); this.mvMatrixLoc = gl.getUniformLocation(this.program, "mvMatrix"); this.pMatrixLoc = gl.getUniformLocation(this.program, "pMatrix"); this.nMatrixLoc = gl.getUniformLocation(this.program, "nMatrix"); }; var LinesProgram = function () { this.program = initShaders(gl, "lines-vshader", "lines-fshader"); gl.useProgram(this.program); this.vertexLoc = gl.getAttribLocation(this.program, "vPosition"); this.colorLoc = gl.getAttribLocation(this.program, "vColor"); }; function renderAxis() { gl.useProgram(lineProgram.program); gl.enableVertexAttribArray(lineProgram.vertexLoc); gl.bindBuffer(gl.ARRAY_BUFFER, axis.vertexBuffer); gl.vertexAttribPointer(lineProgram.vertexLoc, 4, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(lineProgram.colorLoc); gl.bindBuffer(gl.ARRAY_BUFFER, axis.colorBuffer); gl.vertexAttribPointer(lineProgram.colorLoc, 4, gl.FLOAT, false, 0, 0); gl.uniformMatrix4fv(lineProgram.mvMatrixLoc, false, flatten(mvMatrix)); gl.uniformMatrix4fv(lineProgram.pMatrixLoc, false, flatten(pMatrix)); gl.drawArrays(gl.LINES, 0, axis.numPoints); } function renderFloor() { gl.useProgram(lineProgram.program); gl.enableVertexAttribArray(lineProgram.vertexLoc); gl.bindBuffer(gl.ARRAY_BUFFER, floor.vertexBuffer); gl.vertexAttribPointer(lineProgram.vertexLoc, 4, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(lineProgram.colorLoc); gl.bindBuffer(gl.ARRAY_BUFFER, floor.colorBuffer); gl.vertexAttribPointer(lineProgram.colorLoc, 4, gl.FLOAT, false, 0, 0); gl.uniformMatrix4fv(lineProgram.mvMatrixLoc, false, flatten(mvMatrix)); gl.uniformMatrix4fv(lineProgram.pMatrixLoc, false, flatten(pMatrix)); gl.drawArrays(gl.LINES, 0, floor.numPoints); } function renderSegment() { gl.useProgram(lineProgram.program); gl.enableVertexAttribArray(lineProgram.vertexLoc); gl.bindBuffer(gl.ARRAY_BUFFER, segment.vertexBuffer); gl.vertexAttribPointer(lineProgram.vertexLoc, 4, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(lineProgram.colorLoc); gl.bindBuffer(gl.ARRAY_BUFFER, segment.colorBuffer); gl.vertexAttribPointer(lineProgram.colorLoc, 4, gl.FLOAT, false, 0, 0); gl.uniformMatrix4fv(lineProgram.mvMatrixLoc, false, flatten(mvMatrix)); gl.uniformMatrix4fv(lineProgram.pMatrixLoc, false, flatten(pMatrix)); // gl.drawArrays(gl.LINES, 0, segment.numPoints); } function renderSphere() { gl.useProgram(sphereProgram.program); // gl.enableVertexAttribArray(sphereProgram.vertexLoc); gl.bindBuffer(gl.ARRAY_BUFFER, sphere.vertexBuffer); gl.vertexAttribPointer(sphereProgram.vertexLoc, 4, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(sphereProgram.normalLoc); gl.bindBuffer(gl.ARRAY_BUFFER, sphere.normalBuffer); gl.vertexAttribPointer(sphereProgram.normalLoc, 4, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(sphereProgram.colorLoc); gl.bindBuffer(gl.ARRAY_BUFFER, sphere.colorBuffer); gl.vertexAttribPointer(sphereProgram.colorLoc, 4, gl.FLOAT, false, 0, 0); nMatrix = normalMatrix(mvMatrix, false); gl.uniformMatrix4fv(sphereProgram.mvMatrixLoc, false, flatten(mvMatrix)); gl.uniformMatrix4fv(sphereProgram.pMatrixLoc, false, flatten(pMatrix)); gl.uniformMatrix4fv(sphereProgram.nMatrixLoc, false, flatten(nMatrix)); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, sphere.indexBuffer); gl.drawElements(gl.TRIANGLES, sphere.numIndices, gl.UNSIGNED_SHORT, 0); } /** * Parses a BVH file and places the result in the bvh variable. */ function parse(input) { var antlr4 = require('antlr4/index'); var BVHLexer = require('parser/BVHLexer'); var BVHListener = require('parser/BVHListener'); var BVHParser = require('parser/BVHParser'); require('./BVH'); var chars = new antlr4.InputStream(input); var lexer = new BVHLexer.BVHLexer(chars); var tokens = new antlr4.CommonTokenStream(lexer); var parser = new BVHParser.BVHParser(tokens); parser.buildParseTrees = true; var tree = parser.mocap(); bvh = new BVH(); antlr4.tree.ParseTreeWalker.DEFAULT.walk(bvh, tree); // TODO: add any initialization code upon loading a BVH file console.log(bvh); } function keyDown(e) { switch (e.keyCode) { case 37: // left angle--; break; case 38: // up fieldOfView = fieldOfView <= 0.0 ? 0.0 : fieldOfView - 1; break; case 39: // right angle++; break; case 40: // down fieldOfView = fieldOfView >= 100.0 ? 100.0 : fieldOfView + 1; break; case 32: isPaused = !isPaused; break; case "F".charCodeAt(0): // F or f break; default: // To see what the code for a certain key is, uncomment this line, // reload the page in the browser and press the key. // console.log("Unrecognized key press: " + e.keyCode); break; } } function kungFu() { playAudio("Song/KungFu.mp3"); // parse(file.open()); parse(kungFu1); } window.onload = function init() { document.onkeydown = keyDown; canvas = document.getElementById("gl-canvas"); gl = WebGLUtils.setupWebGL(canvas); if (!gl) { alert("WebGL isn't available"); } gl.viewport(0, 0, canvas.width, canvas.height); aspect = canvas.width / canvas.height; gl.clearColor(0.5, 0.5, 0.5, 1.0); gl.enable(gl.DEPTH_TEST); axis = new Axis(); floor = new Floor(); sphere = new Sphere(1, 20, 20); lineBufferId = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, lineBufferId); lineColorBufferId = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, lineColorBufferId); // Load shaders and initialize attribute buffers lineProgram = new LineProgram(); sphereProgram = new SphereProgram(); segment = new Segment(); // // Listen for a file to be loaded and parse var fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', function (e) { var file = fileInput.files[0]; if (file && file.name) { if (file.name.match(/.*\.bvh/)) { var reader = new FileReader(); reader.onload = function (e) { parse(reader.result); frameNumber = 0; render(); if (audio) { audio.pause(); } }; reader.readAsText(file); } else { console.log("File not supported! " + file.type); } } }); // // Parse a default file. // // TODO: change this to testData1 when you're ready to start rendering // // animation. These strings are defined in test1.bvh.js and test2.bvh.js. parse(testData1); render(); };
87bd3fa769d95d80b990d1ad7e7ab404342e02a3
[ "JavaScript", "Text", "Markdown" ]
12
Text
TatoProgramming/WebGLProjects
983ff8ae082b3dad703d8ff474648f8c607a3239
16e85cb9662847bdcbc9db4fa3c56af7a65edcfd
refs/heads/master
<file_sep>//Assignment Operators let x = 5; //Addition Assignment x+=1; //x = x + 1 //Subtraction Assignment x -= 1; //x = x - 1 //Multiplication Assignment x*= 1; // x = x * 1 //Division Assignment x/= 1; // x = x / 1 //Remainder(or Modulus) Assignment x %= 2 //x = x % 1 //Exponential Assignment x**= 1 //x= x ** 1<file_sep>// FOR OF LOOPS //FOR OF LOOPS OVER !!ARRAYS!! //The for... of statement creates a loop iterating over iterable objects, meaning it can numerically look over these items. let student = {name: 'Peter', awesome: true, degree: 'Javanscript', Week: 1}; for(item of student) { console.log(item); } //student is not iterable let catArray = ['tabby','british shorthair','burmese', 'maine coon', 'rag doll']; for(cat of catArray) console.log(cat) //for(cat in catArray){ FOR IN GIVES YOU NUMBERS ON AN ARRAY // console.log(cat); //}<file_sep>// Types //1.Booleans let on = true console.log(on) let off = false; console.log(off); //2.Null //empty value, empty container (not 0, not undefined) let empty = null console.log(empty); //3. Undefined //no value assigned let undef = undefined; console.log(undef); let grass; console.log(grass); //4.Numbers let degrees= 90; console.log(degrees); let precise = 999999999999999 console.log(precise); let rounded = 9999999999999999 console.log(rounded); let notQuite = 0.2+0.1 console.log(notQuite); let numbersAreHard = (0.2 * 10 + 0.1 * 10) / 10; console.log(numbersAreHard); //5.Strings //Strings are any value within quotes let stringOne = "double quotes"; let stringTwo = 'singe quotes'; console.log(stringOne , stringTwo); let first = 1050 + 100; //additions let second = '1050' + '100'; //concatnation console.log(first); console.log(second); console.log(typeof first); console.log(typeof second); let third = 1050 + '100'; console.log(third); console.log(typeof third); //Challenge!! /* First Name <NAME> houseNumber aptNumber street city state zipcode Set each variable to its respective type. cons.log you whole address (with the space between variable). */ let firstName = "Cody"; let lastName = "Blackwell"; let houseNumber = 2977 let street = "Kings Court"; let city = "Carmel"; let state = "Indiana"; let zipCode = 46032; console.log(firstName, lastName + ',', houseNumber , street + ',', city + ',', state , zipCode); //6. Objects //A collection of key-value pairings //Hold multiple data types //Denotes by { } //Has keys and values (ex. color (key): 'blue' (value), separated with a colon.) //Each key is separated with a comma. let burritosNow = { size: 'large', quantity: 4, now: true }; console.log(burritosNow); console.log(typeof burritosNow); //Arrays //Arrays are great for lists //Denotes by [ ] //Has values ('blue', 'green', 'yellow') separated by commas. let burritos = ['large', 4, true]; console.log(burritos); console.log(typeof burritos); <file_sep>//Objects //Objects store multiple objects that are similar in structure. This is great for out JS logic. //Objects can hold multiple datatypes //Denoted with { } // Key - Value Pairs //example let netflix = { id: 1, name: "<NAME>", seasons: { season1: { seasonInfo: { episodeInfo: [ { episode: 1, episodeName: "Pilot"}, { episode: 2, episodeName: "Magazine Profile"}, { episode: 3, episodeName: "Shots and Salsa"}, { episode: 4, episodeName: "Mannequin"} ] } }, season2: { seasonInfo: { episodeInfo: [ {episode: 5, episodeName: "Shoplifter"}, {episode: 6, episodeName: "Secret Shopper"}, {episode: 7, episodeName: "Color Wars"}, {episode: 8, episodeName: "Wedding Day Sale"}, {episode: 9, episodeName: "All-Nighter"} ] } }, season3: { seasonInfo: { episodeInfo: [ {episode: 10, episodeName: ""}, {episode: 11, episodeName: ""}, {episode: 12, episodeName: ""}, {episode: 13, episodeName: ""}, {episode: 14, episodeName: ""} ] } } } } //dot notation //console.log("All data ", netflix) //console.log('Just season info: ', netflix.seasons.season1.seasonInfo) //console.log('Episode Name: ', netflix.seasons.season1.seasonInfo.episodeInfo[0].episodeName) /* pick an episode to show using dot notation, walk through the netflix object and print off both the episode and the episode name */ console.log('Episode Name: ', netflix.seasons.season2.seasonInfo.episodeInfo[2].episodeName, 'episode', netflix.seasons.season2.seasonInfo.episodeInfo[2].episode)<file_sep>//If //IF syntax //if (condition){ //logic // console.log('words') //} let isOn = true; if (isOn == true) { console.log('The light is on!') }; if (isOn) { console.log('The light is on!') }; let isOff = false; if(isOff == false) { console.log('The light is off') }; weather = 65; if(weather <70) { console.log('Wear a jacket') };<file_sep>//variables //variable are containers for storing data values (words, sentences, numbers, objects, etc); var a = 1; var b = 2; console.log(a+b); /* Notes: 1.a variable must begin with a letter, underscore, or dollar sign 2. numbers may follow the above characters, but cannot come first. 3. Javascript is case sensitive -- hello and Hello are different variables 4. Variables must be identified with unique names. */ var x; console.log('Declaration:', x) x=10; console.log('Initialization 1', x) x=33; console.log('Initialization', x) var y = 'hello'; console.log('Both: ', x, y) // Var, Let, and Const; //Var = old keyword //Let = new keyword //Const = New keyowrd(declares unchangeable variables) var today = 'great!'; const elevenFifty = 'Wonderful'; console.log(today, elevenFifty); today = 'lovely'; console.log(today, elevenFifty); elevenFifty = 'super'; console.log(today, elevenFifty); //doesnt work, already a const assigned to elevenFifty<file_sep>//FOR IN LOOPS //Great for iterating over values in an object //The For in statement iterates over a specified variable over all the enumerable properties of an object let student = {name: 'Peter', awesome: true, degree: 'Javascript', week: 1}; for(item in student) { console.log('item=>', item); //name, awesome, degree, week "KEYS" console.log('student[item]', student[item]); // } let dogArray = ['collie', 'pittbull', 'newfie', 'st bernard', 'dachshund']; for(dog in dogArray){ console.log(dog) } let catArray = ['tabby', 'british short haired', 'burmese', 'maine coon', 'rag doll']; for(cat in catArray){ console.log(cat) }//NOT USED FOR ARRAYS, USED FOR OBJECTS //Challenge: Write a forin loop that capitalizes the first letter of a student's name //let studentName = 'cody'; //for(let n in studentName) // console.log(studentName.charAt(0).toUpperCase()); WRONG //} //CORRECT ANSWER let studentName = 'cody'; let capName; for(let n in studentName){ if (n==0) { capName= studentName[n].toUpperCase(); } else { capName+= studentName[n].toLowerCase() } } console.log(capName); <file_sep>//Parameters //ex function hi(parameter1, parameter2){ console.log(parameter1, parameter2) console.log('hi'); } function pet(animal) { console.log(`i have a ${animal} for a pet.`); } pet('cat'); pet('dog'); pet('turtle'); pet('DRAGON'); pet('rock'); //Challenge: Write a function that tkes two parameters: //One parameter is for a first name, //The other parameter is for a last name; //Have them come together in a variable inside the function. //console.log 'Hello, my name is <NAME>' //Call your function function myName(firstName, lastName){ let fullName=firstName + ' ' + lastName; console.log(`Hello, my name is ${fullName}.`) } myName('slim','shady');<file_sep>//For Loops /* A loop is a programming tool that repeats a set of instructions until a specified condition is met. Has 3 parameters, have to tell it where to start and where to stop, and by what incriments */ const vactionSpot = (['Florence','Copenhagen','Istanbul']); console.log(vactionSpot[0]); console.log(vacationSpot[1]); console.log(vacationSpot[2]); //Types of loops /* For statement Do while statements while statement labeled statement break statement continue statement For in statement For of statement */ // initialization; stopping condition; iteration statement for (let i=0; i<10; i++) { console.log(i); } //Challenge-> count to 20 from 0 by 2 for (let i=0; i<21; i+=2) { console.log(i); } //Challenge-> count from 10 down to 0, by 1 for (i = 10; i>=0; i--){ console.log(i) } //challenge -> use a for loop, count from 0, going down by 2's to -24 for(i = 0; i>= -24; i-=2){ console.log(i); } //Challenge-> using a for loop, go through a name and dispay each letter individually let name = 'cody' for(p=0; p < name.length; p++) { console.log(name[p]) } //Challenge: Make a loop where you add up all the number from 1 to 50 (should equal 1275) let sum=0; for(i=1;i<=50; i++) { sum = sum + i } console.log(sum)<file_sep>// RETURNS function capitalizeName(name) { let capName = ''; for (let l in name) { if(l ==0) { capName += name[l].toUpperCase(); }else { capName += name[l].toLowerCase(); } } console.log(capName) return capName } const myName = capitalizeName('cOdY') console.log(myName+ ' how are you doing?') //Challenge //make a tip calculator using a function //have it RETURN the value //capture that reurned value in a variable //Print the variable /*function tipAmount(tip) { let tipPercentage = ''; WRONG for(let billTotal in tip) { if(billTotal == 50) { tipPercentage /= billTotal.tipAmount(.20) } else{ tipPercentage /= billTotal.tipAmount(.15) WRONG } } console.log(tipPercentage) return tipPercentage } const myTip = tipAmount(.20) console.log(myTip + " Great service!!") */ function tipCalc(bill) { let tip = (bill * 0.2); return tip.toFixed(2); } let bill = 19.88 let totalTip = tipCalc(19.88); //console.log(totalTip); console.log(`If my bill is ${bill}, my tip will be ${totalTip}.`) function checker(word) { let palindrone = 'noon'; for(let i in 'noon'){ if (i == 0) { word[0] == word[3]; word[1] == word[2]; } else { console.log("This is not a palindrone."); } //write an if statement that evaluates if a string is the same backwards and forward. If it is the same, return the word back out. If it is not the same, return 'This is not a palindrone'. Use the function scafold provided console.log(palindrone) return palindrone } } const noon = checker('noon') const instructors = [ { first: "Autumn", last: "Henderson", language: "JS", powerLevel: 200 }, { first: "Alecx", last: "Moritz", language: "JS", powerLevel: 176 }, { first: "David", last: "Whitt", language: "JS", powerLevel: 198 }, { first: "Tyler", last: "Shelton", language: "JS", powerLevel: 234 }, { first: "Ingeborg", last: "Slegers", language: "JS", powerLevel: 182 }, { first: "Zachary", last: "Maynard", language: "JS", powerLevel: 167 } ]; //Use the array provided for each challenge. If you dont know how to use these array methods, look them up on MDN or //another sight. CONSOLE LOG THE ANSWER. // Array.prototype.filter() // 1. Filter the list of inventors for those who have a powerlevel over 175. /* let over175; const result = instructors.filter(instructors=> instructors.powerLevel > 175) console.log(result); */ // Array.prototype.map() // 2. Give us an array of the instructors' first and last names let firstAndLast=console.log(Object.values(instructors[first[last]])) // Array.prototype.sort() // 3. Sort the instructors by powerlevel, highest to lowest let ordered; // Array.prototype.reduce() // 4. What is the cumulative power level of all of the instructors? let reduced; // 5. What is the average powerlevel of the instructors. let average; const people = [ "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" ]; // 6. sort Exercise // Sort the people alphabetically by last name let sorted; <file_sep>/************* * DECLARATIONS!!! *************/ //Block of code that performs logic //Declarations get hoisted function hi(){ console.log('HI') }<file_sep>/************** CALLING FUNCTIONS ************/ function hi(){ console.log('HI') }; hi(); //Challenge: Create a function that, when invoked, lists out the numbers 1-10 function hi(){ for(let x=1; x <= 10; x++) { console.log(x); } } hi() //Challenge: Given the array, create a function that lists out the values individually. let arr = ["this", 'is', 'really', 'cool']; function hi() { for(arr of arr) { console.log(arr); } } hi() function checker(phrase) { let palindrone = "<NAME>"; if (true) { console.log(palindrone); } else { console.log("This is not a palindrone."); } //write an if statement that evaluates if a string is the same backwards and forward. If it is the same, return the word back out. If it is not the same, return 'This is not a palindrone'. Use the function scafold provided } checker() module.exports = checker; <file_sep>//Ternaries //Ternaries are a shorthand version of an if else if statement let x = 6 if (x < 0) { console.log("yes") } else{ console.log('no') } //Ternary (x > 0) ? console.log('yes') : console.log('no'); //condition statement if (x == 0) { console.log('Hello') } else if (x<0) { console.log('Goodbye') }else { console.log('hi') } //ternery operator let x = 6; (x==0) ? console.log('Hello') : (x<0) ? console.log('hi') : console.log('Goodbye'); //Challenge let age = 25; (age<=25) ? console.log('Rent a car') : (age>=21) ? console.log('Yay! You can drink!') : (age>= 18) ? console.log('Yay! You can Vote!') : console.log('Too Young'); //Switch code made into Terneray Operation let yep=-8; (yep<0 && yep>-10) ? console.log('worked') : (yep>0) ? console.log("worked!!") : console.log('did not work');<file_sep>//Arrays //Arrays are an object. They are a container that can hold multiple datatypes. //Has [ ] brackets //Great for lists let students = ['Sebastion', 'Eric', 'Micheal', 16, 74, false, ['Nick', 'Charles', 'Ethan']] //console.log(typeof students); //console.log(students instanceof Array); console.log(students[1]) console.log(students[6][1]) let food = ['Pecan Pie', 'Shrimp', 'Quesadilla', 'Cheese Cake', 'Hotdog']; //food.push('Pizza') //adds pizza to the end of the array //food.splice(1, 1, 'Bananas') //food.splice(2, 0, 'Sweet Potato Pie')// first parameter is the index within the array, 2nd is the number of items i am wanting to remove 3rd name of item you want to add in/replace in the array //food.pop(); //removes the last item in my array //food.shift(); //removes first item in my array food.unshift('Muffin', 'Apples'); //adds elements to the front of the array console.log(food) for(f in food) { console.log(food [f]); //console.log(f) } <file_sep>//Arrow Functions //Normal function coffee() { console.log('coffee is good'); } //Fat Arrow let coffee = () => { console.log('fat arrow coffee'); } coffee(); //Concise Body //Concise bodies do not need paranthesis. Unless you have more than one parameter //Return is implied 'ie' built in let apples = x=> console.log(`There are ${x} apples.`); apples(10); //Two parameters let apples = (x,y) => console.log(`There are ${x} apples and ${y} pears.`); apples(10,5); //Block Body let apples = (x) => {console.log(`There are ${x} apples.`); } apples(10);
73a7c29f9caa3565e8761423877620ec8a79e567
[ "JavaScript" ]
15
JavaScript
Bcb67/jsFundamentals
8d6cdf7ced7c5eaf09a1daafa51b8843b6d93699
53746466364e2035ba0ac7ad9fa39ff5bc590171
refs/heads/master
<file_sep>#!/Users/shanyang/Applications/anaconda3/bin/python import systemstructure; import displacement; import intensity; import normalcoordinate; import numpy as np; # all the input files follows the same atomic order and they are following the same atomic order as in TDEP def main(): """ import POSCAR SPOSCAR and XDARCAR """ #AIMD=systemstructure.SystemStructure(); #AIMD.read_poscar('/Users/shanyang/Desktop/SnS/harmonic-thermal-expansition/energy-cutoff/SnS-Pnma/POSCAR') #AIMD.read_xdatcar('/Users/shanyang/Desktop/SnS/harmonic-thermal-expansition/energy-cutoff/SnS-Pnma/MD-cutoff/MD-1/XDATCAR') """ output system informations """ #AIMD.get_info(); #AIMD.atomic_mass(10,15); #AIMD.warrap_error_fract() #AIMD.supercell_fract_to_direct() #AIMD.fract_supercell_to_unitcell() #AIMD.warrap_error_fract_unitcell() """ Calculate atomic displacement """ #disp=displacement.Displacement(); #disp.read_poscar('/Users/shanyang/Desktop/SnS/harmonic-thermal-expansition/energy-cutoff/SnS-Pnma/POSCAR') #disp.read_xdatcar('/Users/shanyang/Desktop/SnS/harmonic-thermal-expansition/energy-cutoff/SnS-Pnma/MD-cutoff/MD-1/XDATCAR') #disp.get_info() #disp.warrap_error_fract() #disp.supercell_fract_to_direct() #disp.displacement_fract_at_t() #disp.displacement_direct_at_t() #disp.fract_supercell_to_unitcell() #disp.warrap_error_fract_unitcell() #disp.warrap_error_fract_unitcell() """ Calculate Bragg intensity """ #i = intensity.Intensity(); #i.read_poscar('/Users/shanyang/Desktop/SnS/harmonic-thermal-expansition/energy-cutoff/SnS-Pnma/POSCAR'); #i.read_xdatcar('/Users/shanyang/Desktop/SnS/harmonic-thermal-expansition/energy-cutoff/SnS-Pnma/MD-cutoff/MD-1/XDATCAR'); #i.get_info() #i.warrap_error_fract() #i.fract_supercell_to_unitcell() #wave_vector=np.array([2,4,3]) #atomic_form_factor= np.array([30,50]) #supercell_size = np.array([2,4,4]) #timestep_size = 0.001 #(ps) #i.intensity(wave_vector,supercell_size,atomic_form_factor) #print(i.intensity_FFT(timestep_size,0,255)) """ Calcuate normal coordinate """ nc=normalcoordinate.NormalCoordinate(); nc.read_poscar('/Users/shanyang/Desktop/SnS/harmonic-thermal-expansition/energy-cutoff/SnS-Pnma/POSCAR') nc.read_xdatcar('/Users/shanyang/Desktop/SnS/harmonic-thermal-expansition/energy-cutoff/SnS-Pnma/MD-cutoff/MD-1/XDATCAR') nc.get_info() nc.warrap_error_fract() nc.supercell_fract_to_direct() nc.fract_supercell_to_unitcell() # in order to calculate direct coordinate, need to calculate fract coordinate first nc.displacement_fract_at_t() nc.displacement_direct_at_t() # load eigenvector supercell_size=np.array([2,4,4]) atomic_mass= np.array([45,80]) wave_vector=np.array([0,0,0]) # the wave vector that you used to generate eigenvector nc.read_eigenvector('/Users/shanyang/Desktop/photo_excitation_module/module/eigenvector_example') nc.read_sposcar('/Users/shanyang/Desktop/SeSn-0.025-pnma/infile.ssposcar'); nc.generate_eigenvector_supercell(supercell_size) nc.eigenvector_supercell_phase(wave_vector) nc.atomic_mass(atomic_mass[0],atomic_mass[1]) nc.conj_eigenvector_supercell_phase_mass() nc.normalcoordinate() timestep_size = 0.001 #(ps) nc.normalcoordinate_FFT(timestep_size, 0, 255) if __name__ == '__main__': main() <file_sep>import sys; from systemstructure import SystemStructure; from displacement import Displacement; from eigenvector import Eigenvector; import matplotlib.pyplot as plt; import numpy as np; class NormalCoordinate(Displacement,Eigenvector): # /Users/shanyang/Desktop/SeSn-0.025-pnma/eigenvector.txt """ N in the normal coordinate is the number of unitcells in supercell """ # def correlate(self,time_step,time_start,time_end): # """ # t_0 is the time origin # t_d is the time delay # C_(t_d)=sum A(t_0)A(t_0+t_d) over from 0 to t_0 and take the average # """ # self._auto_correlate= np.empty((time_end-time_start),dtype=complex) # temp_normal_coordinate = self._normal_coordinate[time_start:time_end]; # for t in range(time_end-time_start): # self._auto_correlate[t] = np.dot(temp_normal_coordinate,np.roll(temp_normal_coordinate,t))/(time_end-time_start); # plt.figure() # plt.plot(np.arange(time_start,time_end),self._auto_correlate.real) # plt.show(); # self._fs_nc = 0.001; # self._freq_nc = np.fft.fftfreq(time_end-time_start,self._fs_nc) # self._auto_correlate_fft = np.abs(np.fft.fft(self._auto_correlate.real)) # plt.figure() # plt.plot(self._freq_nc,self._auto_correlate_fft) # plt.xlim(np.array([0,5])) # plt.show() # return self._auto_correlate.real def normalcoordinate(self): self._normal_coordinate_item = np.empty((self._count),dtype=complex) self._normal_coordinate = np.empty((self._steps),dtype=complex) for t in range(self._steps): for atom in range(self._total_number): self._normal_coordinate_item[t*self._total_number+atom] = np.dot(self._conj_eigenvector_supercell_phase_mass[atom,:],self._displacement_direct_t[t*self._total_number+atom,:]) self._normal_coordinate[t] = np.sum(self._normal_coordinate_item[t*self._total_number:(t+1)*self._total_number])/np.prod(self._supercell_size) return self._normal_coordinate.real def normalcoordinate_auto_correlate(self,time_start, time_end): """ t_0 is the time origin t_d is the time delay C_(t_d)=sum A(t_0)A(t_0+t_d) over from 0 to t_0 and take the average """ self._normal_coordinate_auto_correlate = np.empty((time_end-time_start),dtype=complex) temp_normal_coordinate = self._normal_coordinate[time_start:time_end]; for t in range(time_end-time_start): self._normal_coordinate_auto_correlate[t] = np.dot(temp_normal_coordinate,np.roll(temp_normal_coordinate,t))/(time_end-time_start); return self._normal_coordinate_auto_correlate.real def normalcoordinate_FFT(self,timestep_size,time_start, time_end): self._fs_nc = timestep_size; self._freq_nc = np.fft.fftfreq(time_end-time_start,self._fs_nc) self._normal_coordinate_fft = np.abs(np.fft.fft(self._normal_coordinate.real[time_start:time_end])) return self._freq_nc, self._normal_coordinate_fft def normalcoordinate_auto_correlate_FFT(self,timestep_size,time_start, time_end): self._fs_nc = timestep_size; self._freq_nc = np.fft.fftfreq(time_end-time_start,self._fs_nc) self._normal_coordinate_auto_correlate_fft = np.abs(np.fft.fft(self._normal_coordinate_auto_correlate)) return self._freq_nc, self._normal_coordinate_auto_correlate_fft def plot_normalcoordinate(self,time_start,time_end): plt.figure() plt.plot(np.arange(time_start,time_end),self._normal_coordinate.real[time_start:time_end]) plt.xlim([time_start, time_end]) plt.xlabel('Time (fs)') plt.ylabel(r'Normal Coordinate Q ($amu^{0.5}\AA$)') plt.show() return def plot_normalcoordinate_auto_correlate(self,time_start,time_end): plt.figure() plt.plot(np.arange(time_start,time_end),self._normal_coordinate_auto_correlate.real) plt.xlim([time_start, time_end]) plt.xlabel('Time (fs)') plt.ylabel(r'Normal Coordinate Auto_correlation $<Q(t)Q(t\')>$') plt.show() return def plot_normalcoordinate_FFT(self,xlim): plt.figure() plt.plot(self._freq_nc,self._normal_coordinate_fft) plt.xlim(xlim[0],xlim[1]) plt.xlabel('Frequency (THz)') plt.ylabel('Amplitude') plt.xlim() plt.show() return def plot_normalcoordinate_auto_correlate_FFT(self,xlim,ylim): plt.figure() plt.plot(self._freq_nc,self._normal_coordinate_auto_correlate_fft) plt.xlim(xlim[0],xlim[1]) plt.ylim(ylim[0],ylim[1]) plt.xlabel('Frequency (THz)') plt.ylabel('Amplitude') plt.xlim() plt.show() return <file_sep>import sys; import numpy as np; from systemstructure import SystemStructure; import matplotlib.pyplot as plt class Displacement(SystemStructure): """ calculate atomic displacement in unit (A)""" def displacement_fract_at_t(self): self._displacement_fract_t=np.zeros((self._count,3)) self._xdatcar_fract_supercell_equal = self._xdatcar_fract[0:self._total_number,:] for t in range(self._steps): self._displacement_fract_t[t*self._total_number:(t+1)*self._total_number,:]=self._xdatcar_fract[t*self._total_number:(t+1)*self._total_number,:]-self._xdatcar_fract_supercell_equal return self._displacement_fract_t def displacement_direct_at_t(self): self._displacement_direct_t=np.zeros((self._count,3)) abc_supercell=[np.linalg.norm(self._a_supercell_vector), np.linalg.norm(self._b_supercell_vector), np.linalg.norm(self._c_supercell_vector)] for t in range(self._count): self._displacement_direct_t[t*self._total_number:(t+1)*self._total_number,:]=self._displacement_fract_t[t*self._total_number:(t+1)*self._total_number,:]*abc_supercell return self._displacement_direct_t <file_sep>import numpy as np; from systemstructure import SystemStructure; class Eigenvector(SystemStructure): def read_eigenvector(self,path): """ the eigenvector belongs to the yaml file in phonopy, which contains the real part and imiginary part """ self._read_eigenvector_unitcell=[]; try: with open(path,'r') as eigenvector: while True: line=eigenvector.readline(); if not line: break; else: self._read_eigenvector_unitcell.append(line.strip().split()); except FileNotFoundError as e: print('Eigenvector file does not exist: {}'.format(e)) self._eigenvector_unitcell= np.asarray(self._read_eigenvector_unitcell); return; def generate_eigenvector_supercell(self,supercell_size): """ transfer the unitcell eigenvector to supercell eigenvector """ self._supercell_size = supercell_size; self._atoms_unitcell = self._eigenvector_unitcell.shape[0]; self._eigenvector_supercell = []; for atom in range(self._atoms_unitcell): for x in range(self._supercell_size[0]): for y in range(self._supercell_size[1]): for z in range(self._supercell_size[2]): self._eigenvector_supercell.append(self._eigenvector_unitcell[atom]); self._eigenvector_supercell = np.asarray(self._eigenvector_supercell,dtype= float); return self._eigenvector_supercell; # def read_sposcar(self,supercell_path): # self._sposcar = super().read_poscar(supercell_path) # return self._sposcar; def eigenvector_supercell_phase(self,wave_vector): """ the eigenvector in supercell does not include the relative phase of atoms in difference cell, which depends on the wave vector the wave vector is based on the unitcell self._coef: 1. calculate the dot product to change the supercell fract to unitcell fract 2. calculate the product of q*r 3. calculate the phase exp(i*2*pi*q*r) comment: q is wave vector """ # PATH:/Users/shanyang/Desktop/SeSn-0.025-pnma/infile.ssposcar self._wave_vector = wave_vector; self._coef=np.empty([self._eigenvector_supercell.shape[0],1],dtype=complex) self._eigenvector_supercell_phase=np.empty([self._eigenvector_supercell.shape[0],3],dtype=complex) for atom in range(self._total_number): self._coef[atom]= np.exp(2j*np.pi*np.dot(self._sposcar_fract[atom,:]*self._supercell_size,self._wave_vector)) self._complex_eigen_x = np.complex(self._eigenvector_supercell[atom,0],self._eigenvector_supercell[atom,1]); self._complex_eigen_y = np.complex(self._eigenvector_supercell[atom,2],self._eigenvector_supercell[atom,3]); self._complex_eigen_z = np.complex(self._eigenvector_supercell[atom,4],self._eigenvector_supercell[atom,5]); self._eigenvector_supercell_phase[atom,:] = self._coef[atom]*np.array([self._complex_eigen_x,self._complex_eigen_y,self._complex_eigen_z],dtype=complex); #print(self._eigenvector_supercell_phase); return self._eigenvector_supercell_phase; def conj_eigenvector_supercell_phase_mass(self): """ calculate all the parts conj(e)*np.sqrt(mass) except the displacement """ self._conj_eigenvector_supercell_phase_mass=np.empty([self._eigenvector_supercell.shape[0],3],dtype=complex) count_start = 0; count_current = 0; for key,value in zip(self._element_mass,self._element_numbers): count_start = count_current; count_current = count_current+int(value); for atom in range(count_start, count_current): self._conj_eigenvector_supercell_phase_mass[atom,:]= np.sqrt(key)*np.conj(self._eigenvector_supercell_phase[atom,:]) return self._conj_eigenvector_supercell_phase_mass; <file_sep>import sys; from systemstructure import SystemStructure; import matplotlib.pyplot as plt; import numpy as np; class Intensity(SystemStructure): def intensity(self, wave_vector,supercell_size, atomic_form_factor): """ calculate bragg intensity for every step for wave_vector based on unitcell """ self._element_form_factor = dict(zip(atomic_form_factor,self._element_numbers)) self._structure_factor = np.empty(self._steps,dtype=complex); self._intensity = np.empty(self._steps, dtype = float); temp_matrix = np.empty(self._count,dtype=complex); for t in range(self._steps): count_start = 0; count_current = 0; for key in self._element_form_factor: value = self._element_form_factor[key] count_start = count_current; count_current = count_current+int(value); for atom in range(count_start, count_current): temp_matrix[t*self._total_number+atom] = float(key)*np.exp(2*np.pi*np.array([-1j])*np.dot(self._xdatcar_fract_unitcell[t*self._total_number+atom,:],wave_vector)) self._structure_factor[t] = np.sum(temp_matrix[t*self._total_number:(t+1)*self._total_number], axis=0)/np.prod(supercell_size) self._intensity[t] = np.absolute(self._structure_factor[t])**2 return self._intensity def intensity_FFT(self,timestep_size,time_start, time_end): """ calculate the FFT of intensity with timestep_size in unit of (ps), the unit of output frequency is (THz)""" self._fs = timestep_size; self._freq = np.fft.fftfreq(time_end-time_start,self._fs) self._fft = np.abs(np.fft.fft(self._intensity[time_start:time_end])) return self._freq, self._fft def intensity_auto_correlation(self, wave_vector,supercell_size, atomic_form_factor, time_start, time_end): """ t_0 is the time origin t_d is the time delay C_(t_d)=sum A(t_0)A(t_0+t_d) over from 0 to t_0 and take the average """ self._intensity_auto_correlation = np.empty(time_end-time_start, dtype = complex) temp_intensity= self._structure_factor[time_start:time_end] for t in range(time_end-time_start): self._intensity_auto_correlation[t]= np.dot(temp_intensity,np.roll(temp_intensity,t))/(time_end-time_start); return self._intensity_auto_correlation.real def intensity_auto_correlation_FFT(self,timestep_size,time_start, time_end): """ calculate the FFT of intensity calculated from auto correlaion with timestep_size in unit of (ps), the unit of output frequency is (THz)""" self._fs = timestep_size; self._freq = np.fft.fftfreq(time_end-time_start,self._fs) self._intensity_auto_correlation_fft = np.abs(np.fft.fft(self._intensity_auto_correlation.real)) return self._freq, self._intensity_auto_correlation_fft def plot_intensity(self,xlim): plt.figure() plt.plot(self._intensity) plt.xlim(xlim[0],xlim[1]) plt.xlabel('Time (fs)') plt.ylabel('Intensity') plt.show() return def plot_intensity_auto_correlation(self,xlim): plt.figure() plt.plot(np.arange(xlim[0],xlim[1]),self._intensity_auto_correlation.real) plt.xlim(xlim[0],xlim[1]) plt.xlabel('Time (fs)') plt.ylabel('Intensity from auto correlation function') plt.show() return def plot_intensity_FFT(self,xlim,ylim): plt.figure() plt.plot(self._freq,self._fft) plt.xlim(xlim[0],xlim[1]) plt.ylim(ylim[0],ylim[1]) plt.xlabel('Frequency (THz)') plt.ylabel('Amplitude') plt.show() return def plot_intensity_auto_correlation_FFT(self,xlim,ylim): plt.figure() plt.plot(self._freq,self._intensity_auto_correlation_fft) plt.xlim(xlim[0],xlim[1]) plt.ylim(ylim[0],ylim[1]) plt.xlabel('Frequency (THz)') plt.ylabel('Amplitude') plt.show() return <file_sep>import sys; import numpy as np; class SystemStructure: def read_poscar(self,path): """ read the POSCAR (VASP) file, which you used to generate supercell """ try: with open(path,'r') as poscar: self._system_unitcell=poscar.readline() self._scale_unitcell=float(poscar.readline().rstrip('\n').rstrip()); self._a_unitcell_vector=np.array([float(i)*self._scale_unitcell for i in poscar.readline().rstrip('\n').split()]) self._b_unitcell_vector=np.array([float(i)*self._scale_unitcell for i in poscar.readline().rstrip('\n').split()]) self._c_unitcell_vector=np.array([float(i)*self._scale_unitcell for i in poscar.readline().rstrip('\n').split()]) self._latticevector_matrix_unitcell=np.round(np.stack((self._a_unitcell_vector,self._b_unitcell_vector,self._c_unitcell_vector)),6) poscar.readline() poscar.readline() self._poscar=[] while True: line=poscar.readline().rstrip('\n').split(); if not line: break if (self._isfloat(*[items for items in line])): self._poscar.append(line) self._poscar_fract = np.asarray(self._poscar, dtype= float) except FileNotFoundError as e: print('POSCAR file does not exist: {}'.format(e)) return; def read_sposcar(self,path): """ read the SPOSCAR (VASP) suprcell file """ try: with open(path,'r') as sposcar: sposcar.readline() sposcar.readline() sposcar.readline() sposcar.readline() sposcar.readline() self._element_names = [name for name in sposcar.readline().rstrip('\n').split()] self._element_numbers = np.array([int(number) for number in sposcar.readline().rstrip('\n').split()]) self._total_number = np.sum(self._element_numbers) self._sposcar=[] while True: line=sposcar.readline().rstrip('\n').split(); if not line: break if (self._isfloat(*[items for items in line])): self._sposcar.append(line) self._sposcar_fract = np.asarray(self._sposcar, dtype= float) except FileNotFoundError as e: print('SPOSCAR file does not exist: {}'.format(e)) except IOE as e: print('IO error'.format(e)) raise e return self._sposcar_fract; def read_xdatcar(self,path): """ read the XDARCAR file from AIMD (VASP) """ try: with open(path,'r') as xdatcar: self._system=xdatcar.readline() self._scale_supercell=float(xdatcar.readline().rstrip('\n').rstrip()); self._a_supercell_vector=np.array([float(i)*self._scale_supercell for i in xdatcar.readline().rstrip('\n').split()]) self._b_supercell_vector=np.array([float(i)*self._scale_supercell for i in xdatcar.readline().rstrip('\n').split()]) self._c_supercell_vector=np.array([float(i)*self._scale_supercell for i in xdatcar.readline().rstrip('\n').split()]) self._latticevector_matrix_supercell=np.round(np.stack((self._a_supercell_vector,self._b_supercell_vector,self._c_supercell_vector)),6) self._element_names = [name for name in xdatcar.readline().rstrip('\n').split()] self._element_numbers = np.array([int(number) for number in xdatcar.readline().rstrip('\n').split()]) self._total_number = np.sum(self._element_numbers) self._xdatcar=[] self._count = 0 while True: line=xdatcar.readline().rstrip('\n').split(); if not line: break if (self._isfloat(*[items for items in line])): self._xdatcar.append(line) self._count +=1 self._xdatcar_fract = np.asarray(self._xdatcar,dtype = float) self._steps = int(self._count/self._total_number) except FileNotFoundError as e: print('XDARCAR file does not exist:{}'.format(e)) raise e except IOE as e: print('IO error'.format(e)) raise e return self._xdatcar_fract; def _isfloat(self,*value): for it in value: try: float(it) except ValueError: return False return True; def get_info(self): """ Print out system informations from POSCAR and XDATCAR file.""" for self._name, self._number in zip(self._element_names,self._element_numbers): print('Element name: %s Element number: %s' %(self._name,self._number)) print('Total number: %s' %(self._total_number)) print('Time steps: %s' %(self._steps)) print('Lattice parameter for unitcell:') print(self._latticevector_matrix_unitcell) print('Lattice parameter for supercell:') print(self._latticevector_matrix_supercell) return def atomic_mass(self,*arg): """take atomic mass in element order from input unit (a.u) """ self._element_mass=[] for mass in arg: self._element_mass.append(float(mass)); self._element_mass = np.asarray(self._element_mass, dtype = float) def warrap_error_fract(self): """ clean warrap error when atoms are jumping from one side to the other """ self._equil_fract = self._xdatcar_fract[0:self._total_number,:] for t in range(int(self._steps)): for atom in range(self._total_number): for xyz in range(3): if (self._xdatcar_fract[t*self._total_number+atom,xyz]-self._equil_fract[atom,xyz]) > 0.5: self._xdatcar_fract[t*self._total_number+atom,xyz]=self._xdatcar_fract[t*self._total_number+atom,xyz]-1 elif (self._xdatcar_fract[t*self._total_number+atom,xyz]-self._equil_fract[atom,xyz]) < (-0.5): self._xdatcar_fract[t*self._total_number+atom,xyz]=self._xdatcar_fract[t*self._total_number+atom,xyz]+1 return self._xdatcar_fract def supercell_fract_to_direct(self): """ charge from fract coordinate to direct coordinate unit(A)""" self._xdatcar_direct_supercell = np.zeros((self._count,3)) abc_supercell=[np.linalg.norm(self._a_supercell_vector), np.linalg.norm(self._b_supercell_vector), np.linalg.norm(self._c_supercell_vector)] for posi in range(self._count): self._xdatcar_direct_supercell[posi,:] = self._xdatcar_fract[posi,:]*abc_supercell return self._xdatcar_direct_supercell def fract_supercell_to_unitcell(self): """ change fraction coordinate from supercell to unitcell """ self._xdatcar_fract_unitcell = np.zeros((self._count,3)) abc_supercell=[np.linalg.norm(self._a_supercell_vector), np.linalg.norm(self._b_supercell_vector), np.linalg.norm(self._c_supercell_vector)] abc_unitcell=[np.linalg.norm(self._a_unitcell_vector), np.linalg.norm(self._b_unitcell_vector), np.linalg.norm(self._c_unitcell_vector)] for posi in range(self._count): self._xdatcar_fract_unitcell[posi,:] = self._xdatcar_fract[posi,:]*abc_supercell/abc_unitcell%np.array([1,1,1]) return self._xdatcar_fract_unitcell def warrap_error_fract_unitcell(self): """ clean warrap error when atoms are jumping from one unitcell to the other unitcell """ self._equil_fract_unitcell = self._xdatcar_fract_unitcell[0:self._total_number,:] for t in range(int(self._steps)): for atom in range(self._total_number): for xyz in range(3): if (self._xdatcar_fract_unitcell[t*self._total_number+atom,xyz]-self._equil_fract_unitcell[atom,xyz]) >= 0.5: self._xdatcar_fract_unitcell[t*self._total_number+atom,xyz]=self._xdatcar_fract_unitcell[t*self._total_number+atom,xyz]-1 elif (self._xdatcar_fract_unitcell[t*self._total_number+atom,xyz]-self._equil_fract_unitcell[atom,xyz]) <= (-0.5): self._xdatcar_fract_unitcell[t*self._total_number+atom,xyz]=self._xdatcar_fract_unitcell[t*self._total_number+atom,xyz]+1 return self._xdatcar_fract_unitcell <file_sep># atomic_motions_under_photo_exciation <br> Calculate bragg and diffuse intensity and normal coordinate from AIMD (VASP) <br> Keep updating right now ....please wait for the full descriptions... <file_sep>import normalcoordinate; import numpy as np; import sys; import matplotlib.pyplot as plt; import pdb; def main(): """ Calcuate normal coordinate for wave vector q and eigenvector at q for branch v the atomic order follow the TDEP for SPOSCAR and XDATCAR """ nc=normalcoordinate.NormalCoordinate(); nc.read_poscar('./test_example/POSCAR') nc.read_xdatcar('/Users/shanyang/Desktop/SeSn-0.025-pnma/AIMD/old-XDATCAR/XDATCAR') nc.get_info() nc.warrap_error_fract() nc.supercell_fract_to_direct() nc.fract_supercell_to_unitcell() nc.displacement_fract_at_t() nc.displacement_direct_at_t() supercell_size=np.array([2,4,4]) atomic_mass= np.array([78.96,118.71]) wave_vector=np.array([0.5,0,0]) # load eigenvector # 0.3688768784THz TA at [0.25,0,0] nc.read_eigenvector('./test_example/eigenvector_TA_0500') # load sposcar nc.read_sposcar('./test_example/infile.ssposcar'); nc.generate_eigenvector_supercell(supercell_size) nc.eigenvector_supercell_phase(wave_vector) nc.atomic_mass(atomic_mass[0],atomic_mass[1]) nc.conj_eigenvector_supercell_phase_mass() pdb.set_trace(); nc.normalcoordinate() time_start =0; time_end = 12022; nc.plot_normalcoordinate(time_start, time_end) timestep_size = 0.001 nc.normalcoordinate_FFT(timestep_size, time_start, 4253) nc.plot_normalcoordinate_FFT(np.array([0,5])) nc.normalcoordinate_FFT(timestep_size, 4253, time_end) nc.plot_normalcoordinate_FFT(np.array([0,5])) #before photo_exciation nc.normalcoordinate_auto_correlate(time_start, 4253) nc.plot_normalcoordinate_auto_correlate(time_start,4253) nc.normalcoordinate_auto_correlate_FFT(timestep_size, time_start, 4253) nc.plot_normalcoordinate_auto_correlate_FFT(np.array([0,5]),np.array([0,800])) #after photo_excitation nc.normalcoordinate_auto_correlate(4253, time_end) nc.plot_normalcoordinate_auto_correlate(4253,time_end) nc.normalcoordinate_auto_correlate_FFT(timestep_size, 4253, time_end) nc.plot_normalcoordinate_auto_correlate_FFT(np.array([0,5]),np.array([0,800])) if __name__ == '__main__': main() <file_sep>import systemstructure; import intensity; import numpy as np; import pdb signal = intensity.Intensity(); signal.read_poscar('./test_example/POSCAR'); signal.read_xdatcar('/Users/shanyang/Desktop/SeSn-0.025-pnma/AIMD/old-XDATCAR/XDATCAR'); signal.get_info() signal.warrap_error_fract() signal.fract_supercell_to_unitcell() wave_vector=np.array([3,0,1]) atomic_form_factor= np.array([34,50]) supercell_size = np.array([2,4,4]) timestep_size = 0.001 #(ps) time_end = 12022; time_start = 0; signal.intensity(wave_vector,supercell_size,atomic_form_factor) pdb.set_trace() signal.plot_intensity(np.array([time_start,4253])) signal.intensity_FFT(timestep_size,time_start,4253) signal.plot_intensity_FFT(np.array([0,5]),np.array([0,10**5])) signal.plot_intensity(np.array([4253,time_end])) signal.intensity_FFT(timestep_size,4253,time_end) signal.plot_intensity_FFT(np.array([0,5]),np.array([0,10**5])) signal.intensity_auto_correlation(wave_vector,supercell_size,atomic_form_factor,time_start,4253) signal.plot_intensity_auto_correlation(np.array([time_start,4253])) signal.intensity_auto_correlation_FFT(timestep_size,time_start,4253) signal.plot_intensity_auto_correlation_FFT(np.array([0,5]),np.array([0,10**5])) signal.intensity_auto_correlation(wave_vector,supercell_size,atomic_form_factor,4253,time_end) signal.plot_intensity_auto_correlation(np.array([4253,time_end])) signal.intensity_auto_correlation_FFT(timestep_size,4253,time_end) signal.plot_intensity_auto_correlation_FFT(np.array([0,5]),np.array([0,10**5]))
8890b5fe6ca3c2f4fe3731ea11e405cf010e41a1
[ "Markdown", "Python" ]
9
Python
syang-creater/atomic_motions_under_photo_excitation
dc0e576ba85f1a17121f87cc89a45109158920df
e295029dd0321834fc0284d14ef17e38e0da7486
refs/heads/master
<repo_name>matthewmorrone/newsImprover<file_sep>/README.md # newsImprover chrome extension that does what it says, drastically so <file_sep>/improve.js var replacements = { "Witnesses":"These dudes I know", "Allegedly":"Kinda probably", "New study":"Tumblr post", "Rebuild":"Avenge", "Space":"Spaaace", "Google Glass":"Virtual Boy", "Smartphone":"Pokedex", "Electric":"Atomic", "Senator":"Elf-lord", "Car":"Cat", "Election":"Eating contest", "Congressional leaders":"River spirits", "Homeland security":"Homestar Runner", "Could not be reached for comment":"Is guilty and everyone knows it" } walk(document.body) function walk(node) { var child, next switch (node.nodeType) { case 1: // Element case 9: // Document case 11: // Document fragment child = node.firstChild while (child) { next = child.nextSibling walk(child) child = next } break case 3: // Text node handleText(node) break } } function handleText(textNode) { var v = textNode.nodeValue v = v.replace(/\bWitnesses\b/g, "These dudes I know") v = v.replace(/\bwitnesses\b/g, "these dudes I know") v = v.replace(/\bAllegedly\b/g, "Kinda probably") v = v.replace(/\ballegedly\b/g, "kinda probably") v = v.replace(/\bNew study\b/g, "Tumblr post") v = v.replace(/\bnew study\b/g, "tumblr post") v = v.replace(/\bRebuild\b/g, "Avenge") v = v.replace(/\brebuild\b/g, "avenge") v = v.replace(/\bSpace\b/g, "Spaaace") v = v.replace(/\bspace\b/g, "spaaace") v = v.replace(/\bGoogle Glass\b/g, "Virtual Boy") v = v.replace(/\bSmartphone\b/g, "Pokedex") v = v.replace(/\bsmartphone\b/g, "pokedex") v = v.replace(/\bElectric\b/g, "Atomic") v = v.replace(/\belectric\b/g, "atomic") v = v.replace(/\bSenator\b/g, "Elf-lord") v = v.replace(/\bsenator\b/g, "elf-lord") v = v.replace(/\bCar\b/g, "Cat") v = v.replace(/\bcar\b/g, "cat") v = v.replace(/\bElection\b/g, "Eating contest") v = v.replace(/\belection\b/g, "eating contest") v = v.replace(/\bCongressional leaders\b/g, "River spirits") v = v.replace(/\bcongressional leaders\b/g, "river spirits") v = v.replace(/\bHomeland Security\b/g, "Homestar Runner") v = v.replace(/\bCould not be reached for comment\b/g, "Is guilty and everyone knows it") v = v.replace(/\bcould not be reached for comment\b/g, "is guilty and everyone knows it") textNode.nodeValue = v } // for (var key in replacements) // { // var obj = replacements[key] // for (var prop in obj) // { // if(obj.hasOwnProperty(prop)) // { // var regex = new RegExp("\b"+prop+"\b/g", "g") // v = v.replace(regex, obj[prop]) // } // } // }
d0d94fb53d71139b34c0c10ccdefed14f24e6251
[ "Markdown", "JavaScript" ]
2
Markdown
matthewmorrone/newsImprover
4feaaa83b984e6d458d948291eed43217e3eab15
5076f7743137fcf784205a54708a17f7f4b8fc41
refs/heads/master
<file_sep>report({ "testSuite": "BackstopJS", "tests": [ { "pair": { "reference": "..\\bitmaps_reference\\backstop_default_todo_app_homepage_0__0_phone.png", "test": "..\\bitmaps_test\\20190607-115702\\backstop_default_todo_app_homepage_0__0_phone.png", "selector": "", "fileName": "backstop_default_todo_app_homepage_0__0_phone.png", "label": "todo app homepage", "requireSameDimensions": true, "misMatchThreshold": 10, "url": "http://localhost:8080/", "referenceUrl": "", "expect": 0, "viewportLabel": "phone", "engineErrorMsg": "require(...) is not a function", "error": "Reference file not found C:\\Users\\mayn\\Desktop\\react-todo-app\\backstop_data\\bitmaps_reference\\backstop_default_todo_app_homepage_0__0_phone.png" }, "status": "fail" }, { "pair": { "reference": "..\\bitmaps_reference\\backstop_default_todo_app_homepage_0__1_tablet.png", "test": "..\\bitmaps_test\\20190607-115702\\backstop_default_todo_app_homepage_0__1_tablet.png", "selector": "", "fileName": "backstop_default_todo_app_homepage_0__1_tablet.png", "label": "todo app homepage", "requireSameDimensions": true, "misMatchThreshold": 10, "url": "http://localhost:8080/", "referenceUrl": "", "expect": 0, "viewportLabel": "tablet", "engineErrorMsg": "require(...) is not a function", "error": "Reference file not found C:\\Users\\mayn\\Desktop\\react-todo-app\\backstop_data\\bitmaps_reference\\backstop_default_todo_app_homepage_0__1_tablet.png" }, "status": "fail" }, { "pair": { "reference": "..\\bitmaps_reference\\backstop_default_todo_app_homepage_0__2_desktop.png", "test": "..\\bitmaps_test\\20190607-115702\\backstop_default_todo_app_homepage_0__2_desktop.png", "selector": "", "fileName": "backstop_default_todo_app_homepage_0__2_desktop.png", "label": "todo app homepage", "requireSameDimensions": true, "misMatchThreshold": 10, "url": "http://localhost:8080/", "referenceUrl": "", "expect": 0, "viewportLabel": "desktop", "engineErrorMsg": "require(...) is not a function", "error": "Reference file not found C:\\Users\\mayn\\Desktop\\react-todo-app\\backstop_data\\bitmaps_reference\\backstop_default_todo_app_homepage_0__2_desktop.png" }, "status": "fail" }, { "pair": { "reference": "..\\bitmaps_reference\\backstop_default_add_new_task_0__0_phone.png", "test": "..\\bitmaps_test\\20190607-115702\\backstop_default_add_new_task_0__0_phone.png", "selector": "", "fileName": "backstop_default_add_new_task_0__0_phone.png", "label": "add new task", "requireSameDimensions": true, "misMatchThreshold": 10, "url": "http://localhost:8080/", "referenceUrl": "", "expect": 0, "viewportLabel": "phone", "engineErrorMsg": "require(...) is not a function", "error": "Reference file not found C:\\Users\\mayn\\Desktop\\react-todo-app\\backstop_data\\bitmaps_reference\\backstop_default_add_new_task_0__0_phone.png" }, "status": "fail" }, { "pair": { "reference": "..\\bitmaps_reference\\backstop_default_add_new_task_0__1_tablet.png", "test": "..\\bitmaps_test\\20190607-115702\\backstop_default_add_new_task_0__1_tablet.png", "selector": "", "fileName": "backstop_default_add_new_task_0__1_tablet.png", "label": "add new task", "requireSameDimensions": true, "misMatchThreshold": 10, "url": "http://localhost:8080/", "referenceUrl": "", "expect": 0, "viewportLabel": "tablet", "engineErrorMsg": "require(...) is not a function", "error": "Reference file not found C:\\Users\\mayn\\Desktop\\react-todo-app\\backstop_data\\bitmaps_reference\\backstop_default_add_new_task_0__1_tablet.png" }, "status": "fail" }, { "pair": { "reference": "..\\bitmaps_reference\\backstop_default_add_new_task_0__2_desktop.png", "test": "..\\bitmaps_test\\20190607-115702\\backstop_default_add_new_task_0__2_desktop.png", "selector": "", "fileName": "backstop_default_add_new_task_0__2_desktop.png", "label": "add new task", "requireSameDimensions": true, "misMatchThreshold": 10, "url": "http://localhost:8080/", "referenceUrl": "", "expect": 0, "viewportLabel": "desktop", "engineErrorMsg": "require(...) is not a function", "error": "Reference file not found C:\\Users\\mayn\\Desktop\\react-todo-app\\backstop_data\\bitmaps_reference\\backstop_default_add_new_task_0__2_desktop.png" }, "status": "fail" } ], "id": "backstop_default" });<file_sep>describe("todolist test",() => { cy.visit("http://localhost:8080"); cy.waitForElementVisible('body'); cy.pause(1000); cy.get('#app > div > form > input').type('吃海底捞'); cy.get('#app > div > form > button').click(); });<file_sep>describe("todolist test",() => { it("add a new todo task", () => { cy.visit("http://localhost:8080"); cy.wait(1000); cy.get('#app > div > form > input').type('吃海底捞'); cy.get('#app > div > form > button').click(); cy.wait(1000); }); it("add a new todo task", () => { cy.get('#app > div > form > input').type('完成web作业'); cy.get('#app > div > form > button').click(); cy.wait(1000); }); it("edit first todo task", () => { cy.get('#app > div > table > tbody > tr:nth-child(1) > td:nth-child(2) > button:nth-child(1)').click() cy.get('#app > div > table > tbody > tr:nth-child(1) > td:nth-child(1) > form > input').clear(); cy.get('#app > div > table > tbody > tr:nth-child(1) > td:nth-child(1) > form > input').type('吃小龙坎'); cy.wait(1000); cy.get("#app > div > table > tbody > tr:nth-child(1) > td:nth-child(2) > button:nth-child(1)").click() cy.wait(1000); }); it("delete first todo task", () => { cy.get('#app > div > table > tbody > tr:nth-child(1) > td:nth-child(2) > button.delete-btn').click() cy.wait(1000); }); after(() => { cy.clearCookies(); }); });<file_sep># E2E_and_Backstop # e2e test: add a new task ![image missing](https://github.com/Geziii/E2E_and_Backstop/blob/master/imgs/add.jpg) edit a task ![image missing](https://github.com/Geziii/E2E_and_Backstop/blob/master/imgs/edit.jpg) save edited task ![image missing](https://github.com/Geziii/E2E_and_Backstop/blob/master/imgs/save%20edit.jpg) delete a task ![image missing](https://github.com/Geziii/E2E_and_Backstop/blob/master/imgs/delete.jpg) # Backstop comparison desktop ![image missing](https://github.com/Geziii/E2E_and_Backstop/blob/master/imgs/desktop.png) tablet ![image missing](https://github.com/Geziii/E2E_and_Backstop/blob/master/imgs/tablet.png) phone ![image missing](https://github.com/Geziii/E2E_and_Backstop/blob/master/imgs/phone.png)
385c8ea2a3540bb99689c6ea9d26d9cd3711544c
[ "JavaScript", "Markdown" ]
4
JavaScript
Geziii/E2E_and_Backstop
9afd23b9d3f7b9bbf137676deab505da25ea3d51
4cfa2c508d9353f072107ce66809f9ef2fec5cc6
refs/heads/master
<file_sep> import React, { Component } from 'react'; import { View, ScrollView, Text, Button, } from 'react-native'; import { SearchForm } from '../components/SearchForm'; // import DrawerNavigator from '../Routers/DrawerNavigator'; // import { StackNavigator, DrawerNavigator, TabsNavigator } from '../Routers'; export default class HomeScreen extends Component { static navigationOptions = { header: null }; render() { return ( <ScrollView> <SearchForm /> </ScrollView> ); } } // export default HomeScreen;
58301a342e030a0504061fec3adeec6b897fd487
[ "JavaScript" ]
1
JavaScript
DanielSameh/MidMe
1122c46d6e44c941a55397cf163e6b3651505b54
04fc299b4f9025e1b989d075645acb3deab8ce3a
refs/heads/master
<repo_name>k-hamada/exercism<file_sep>/go/error-handling/README.md # Error Handling Implement various kinds of error handling and resource management. An important point of programming is how to handle errors and close resources even if errors occur. If you are new to Go errors or panics we recommend reading [the documentation on these topics](https://blog.golang.org/defer-panic-and-recover) first for context. In this exercise you will be required to define a function `Use(o ResourceOpener, input string) error` that opens a resource, calls Frob(input) on the result resource and then closes that resource (in all cases). Your function should properly handle errors and panics. `ResourceOpener o` will be a function you may invoke directly `o()` in an attempt to "open" the resource. It returns a Resource and error value in the [idiomatic Go fashion](https://blog.golang.org/error-handling-and-go): See the [common.go](./common.go) file for the definitions of Resource, ResourceOpener, FrobError and TransientError. You will define your solution to be in the same package as [common.go](./common.go) and [error\_handling\_test.go](./error_handling_test.go): "erratum". This will make those types available for use in your solution. There will be a few places in your Use function where errors may occur: * Invoking the ResourceOpener function passed into Use as the first parameter, it may fail with an error of type TransientError, if so keep trying to open the resource. If it is some other sort of error, return it from your `Use` function. * Calling the Frob function on the Resource returned from the ResourceOpener function, it may **panic** with a FrobError (or another type of error). If it is indeed a FrobError you will have to call the Resource's `Defrob` function *using the panic FrobError's `.defrobTag` variable as input to the `Defrob` function*. Either way `Use` should return the error. * *Also note*: if the Resource was opened successfully make sure to call its Close function no matter what (even if errors have occurred). Testing for specific error types may be performed by [type assertions](https://golang.org/ref/spec#Type_assertions). You may also need to look at [named return values](https://blog.golang.org/error-handling-and-go) as a helpful way to return error information from panic recovery. ## Running the tests To run the tests run the command `go test` from within the exercise directory. If the test suite contains benchmarks, you can run these with the `-bench` flag: go test -bench . Keep in mind that each reviewer will run benchmarks on a different machine, with different specs, so the results from these benchmark tests may vary. ## Further information For more detailed information about the Go track, including how to get help if you're having trouble, please visit the exercism.io [Go language page](http://exercism.io/languages/go/about). ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/bowling/src/lib.rs #[derive(Debug, PartialEq)] pub enum Error { NotEnoughPinsLeft, GameComplete, } #[derive(Eq, PartialEq, Debug)] enum Frame { Open(u16, u16), Last(u16), Spare(u16, u16), Strike, } #[derive(Default)] pub struct BowlingGame { roll: Option<u16>, frames: Vec<Frame>, finished: bool, } impl BowlingGame { pub fn new() -> Self { Default::default() } pub fn roll(&mut self, pins: u16) -> Result<(), Error> { if pins > 10 { return Err(Error::NotEnoughPinsLeft); } if let Some(n) = self.roll { if n + pins > 10 { return Err(Error::NotEnoughPinsLeft); } } if let Some(Frame::Last(n)) = self.frames.last() { if n + pins > 10 { return Err(Error::NotEnoughPinsLeft); } } if self.finished { return Err(Error::GameComplete); } let (frame, roll) = { if let Some(n) = self.roll { if n + pins == 10 { (Some(Frame::Spare(n, pins)), None) } else { (Some(Frame::Open(n, pins)), None) } } else if pins == 10 { (Some(Frame::Strike), None) } else if self.frames.len() >= 10 { (Some(Frame::Last(pins)), None) } else { (None, Some(pins)) } }; self.finished = match (self.frames.len(), self.frames.last(), &frame) { (11, _, _) => true, (10, Some(Frame::Spare(_, _)), _) => true, (_, _, Some(Frame::Strike)) => false, (9, _, Some(Frame::Spare(_, _))) => false, (9, _, None) => false, (9, _, _) => true, _ => false, }; if let Some(frame) = frame { self.frames.push(frame); } self.roll = roll; Ok(()) } pub fn score(&self) -> Option<u16> { if !self.finished { return None; } let mut score = 0; for i in 0..9 { score += match ( self.frames.get(i), self.frames.get(i + 1), self.frames.get(i + 2), ) { (Some(Frame::Open(a, b)), _, _) => a + b, (Some(Frame::Spare(_, _)), Some(Frame::Open(a, _)), _) => 10 + a, (Some(Frame::Spare(_, _)), Some(Frame::Spare(a, _)), _) => 10 + a, (Some(Frame::Spare(_, _)), Some(Frame::Strike), Some(Frame::Open(a, _))) => 20 + a, (Some(Frame::Spare(_, _)), Some(Frame::Strike), Some(Frame::Spare(a, _))) => 20 + a, (Some(Frame::Strike), Some(Frame::Open(a, b)), _) => 10 + a + b, (Some(Frame::Strike), Some(Frame::Spare(_, _)), _) => 20, (Some(Frame::Strike), Some(Frame::Strike), Some(Frame::Open(a, _))) => 20 + a, (Some(Frame::Strike), Some(Frame::Strike), Some(Frame::Spare(a, _))) => 20 + a, (Some(Frame::Strike), Some(Frame::Strike), Some(Frame::Strike)) => 30, (Some(Frame::Last(a)), _, _) => *a, _ => 0, }; } if let Some(last_frames) = self.frames.get(9..) { for last_frame in last_frames { score += match last_frame { Frame::Open(a, b) => a + b, Frame::Spare(a, b) => a + b, Frame::Strike => 10, Frame::Last(a) => *a, }; } }; Some(score) } } <file_sep>/rust/diffie-hellman/src/lib.rs extern crate num_bigint; extern crate num_traits; extern crate primal_check; extern crate rand; use num_bigint::ToBigInt; use num_traits::cast::ToPrimitive; use primal_check::miller_rabin as is_prime; use rand::{thread_rng, Rng}; pub fn private_key(p: u64) -> u64 { let mut rng = thread_rng(); loop { let k = rng.gen_range(2, p); if is_prime(k) { return k; } } } pub fn public_key(p: u64, g: u64, a: u64) -> u64 { modpow(g, a, p) } pub fn secret(p: u64, b_pub: u64, a: u64) -> u64 { modpow(b_pub, a, p) } fn modpow(base: u64, exponent: u64, modulus: u64) -> u64 { let b = ToBigInt::to_bigint(&base).unwrap(); let e = ToBigInt::to_bigint(&exponent).unwrap(); let m = ToBigInt::to_bigint(&modulus).unwrap(); b.modpow(&e, &m).to_u64().unwrap() } <file_sep>/rust/dot-dsl/src/lib.rs pub mod graph { use std::collections::HashMap; use graph::graph_items::edge::Edge; use graph::graph_items::node::Node; pub struct Graph { pub edges: Vec<Edge>, pub nodes: Vec<Node>, pub attrs: HashMap<String, String>, } impl Graph { pub fn new() -> Self { Graph { edges: Vec::new(), nodes: Vec::new(), attrs: HashMap::new(), } } pub fn with_nodes(mut self, nodes: &Vec<Node>) -> Self { for node in nodes { self.nodes.push(node.clone()); } self } pub fn with_edges(mut self, edges: &Vec<Edge>) -> Self { for edge in edges { self.edges.push(edge.clone()); } self } pub fn with_attrs(mut self, attrs: &[(&str, &str)]) -> Self { for (k, v) in attrs { self.attrs.insert(k.to_string(), v.to_string()); } self } } pub mod graph_items { pub mod edge { use std::collections::HashMap; #[derive(Clone, Debug, PartialEq)] pub struct Edge { left: String, right: String, attrs: HashMap<String, String>, } impl Edge { pub fn new(left: &str, right: &str) -> Self { Edge { left: left.to_string(), right: right.to_string(), attrs: HashMap::new() } } pub fn with_attrs(mut self, attrs: &[(&str, &str)]) -> Self { for (k, v) in attrs { self.attrs.insert(k.to_string(), v.to_string()); } self } } } pub mod node { use std::collections::HashMap; #[derive(Clone, Debug, PartialEq)] pub struct Node { value: String, attrs: HashMap<String, String>, } impl Node { pub fn new(value: &str) -> Self { Node { value: value.to_string(), attrs: HashMap::new() } } pub fn with_attrs(mut self, attrs: &[(&str, &str)]) -> Self { for (k, v) in attrs { self.attrs.insert(k.to_string(), v.to_string()); } self } } } } } <file_sep>/rust/isbn-verifier/src/lib.rs /// Determines whether the supplied string is a valid ISBN number pub fn is_valid_isbn(isbn: &str) -> bool { let numbers = isbn.chars().flat_map(|c| parse(c)).collect::<Vec<_>>(); if numbers.iter().rev().skip(1).any(|&n| n == 10) { return false; } (1..11).rev().zip(numbers).map(|(i, n)| i * n).sum::<u32>() % 11 == 0 } fn parse(number: char) -> Option<u32> { if number.is_digit(10) { return number.to_digit(10); } if number.eq_ignore_ascii_case(&'x') { return Some(10); } None } #[test] fn test_parse_1() { assert_eq!(Some(1), parse('1')); } #[test] fn test_parse_10() { assert_eq!(Some(10), parse('x')); assert_eq!(Some(10), parse('X')); } #[test] fn test_parse_err() { assert_eq!(None, parse('a')); } <file_sep>/go/clock/README.md # Clock Implement a clock that handles times without dates. You should be able to add and subtract minutes to it. Two clocks that represent the same time should be equal to each other. ## Running the tests To run the tests run the command `go test` from within the exercise directory. If the test suite contains benchmarks, you can run these with the `-bench` flag: go test -bench . Keep in mind that each reviewer will run benchmarks on a different machine, with different specs, so the results from these benchmark tests may vary. ## Further information For more detailed information about the Go track, including how to get help if you're having trouble, please visit the exercism.io [Go language page](http://exercism.io/languages/go/about). ## Source Pairing session with <NAME> [https://twitter.com/ebdrummond](https://twitter.com/ebdrummond) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/binary-search/src/lib.rs pub fn find(array: &[usize], key: usize) -> Option<usize> { find_impl(array, key, 0, array.len()) } fn find_impl(array: &[usize], key: usize, min: usize, max: usize) -> Option<usize> { if max < min { return None; } let mid = min + (max - min) / 2; match (array.get(mid), mid) { (None, _) => None, (Some(&n), 0) if n > key => None, (Some(&n), _) if n > key => find_impl(array, key, min, mid - 1), (Some(&n), _) if n < key => find_impl(array, key, mid + 1, max), (_, _) => Some(mid) } } <file_sep>/go/grains/grains.go package grains import ( "fmt" "math/bits" ) // Square - how many grains were on each square func Square(n int) (uint64, error) { switch { case n < 0: return 0, fmt.Errorf("negative square") case n == 0: return 0, fmt.Errorf("square 0") case n == 1: return 1, nil default: return bits.RotateLeft64(1, n-1), nil case 64 < n: return 0, fmt.Errorf("square greater than 64") } } // Total - total number of grains func Total() uint64 { r, ch := uint64(0), make(chan uint64) for i := 1; i <= 64; i++ { go func(i int, c chan<- uint64) { if n, err := Square(i); err == nil { c <- n } else { c <- 0 } }(i, ch) } for i := 1; i <= 64; i++ { r += <-ch } return r } <file_sep>/typescript/simple-cipher/simple-cipher.ts class SimpleCipher { KEYSET = '<KEY>' readonly key: string readonly offsets: number[] constructor(key?: string) { if (key != null) { if (key.length === 0 || Array.from(key).some(c => !this.KEYSET.includes(c))) { throw new Error('Bad key') } this.key = key } else { this.key = this.generateKey(100) } this.offsets = Array.from(this.key).map(c => this.KEYSET.indexOf(c)) } generateKey(length: number) { const randomString = () => this.KEYSET.charAt(Math.floor(Math.random() * this.KEYSET.length)) return [...Array(length)].map(randomString, this).join('') } codepoints(text: string) { return Array.from(text).map(c => c.charCodeAt(0)) } cipher(code: number, base: number, offset: number) { return String.fromCharCode(base + ((code - base + offset) % 26)) } encode(text: string) { return this.codepoints(text) .map((code, index) => this.cipher(code, 97, this.getShift(index))) .join('') } decode(text: string) { return this.codepoints(text) .map((code, index) => this.cipher(code, 97, this.getUnshift(index))) .join('') } getShift(index: number) { return this.offsets[index % this.offsets.length] } getUnshift(index: number) { return 26 - (this.getShift(index) % 26) } } export default SimpleCipher <file_sep>/elixir/gigasecond/README.md # Gigasecond Calculate the moment when someone has lived for 10^9 seconds. A gigasecond is 10^9 (1,000,000,000) seconds. ## Running tests Execute the tests with: ```bash $ elixir gigasecond_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source Chapter 9 in <NAME>'s online Learn to Program tutorial. [http://pine.fm/LearnToProgram/?Chapter=09](http://pine.fm/LearnToProgram/?Chapter=09) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/sieve/src/lib.rs use std::collections::HashMap; pub fn primes_up_to(n: usize) -> Vec<usize> { let hash_map: HashMap<usize, _> = (2..n+1) .flat_map(|i| (2..) .map(move |x| x * i) .take_while(|x| x <= &n) ) .map(|x| (x, ())) .collect(); (2..n+1) .filter(|i| !hash_map.contains_key(i)) .collect() } <file_sep>/rust/pig-latin/src/lib.rs pub fn translate(text: &str) -> String { text.split_whitespace() .map(|word| { let words = word.to_string(); let (first, last) = words.split_at(split_size(word)); format!("{}{}ay", last, first) }) .collect::<Vec<_>>() .join(" ") } fn split_size(word: &str) -> usize { let rules = vec![ ("squ", 3), ("thr", 3), ("sch", 3), ("ch", 2), ("qu", 2), ("th", 2), ("a", 0), ("o", 0), ("i", 0), ("u", 0), ("e", 0), ("xr", 0), ("yt", 0), ]; for rule in rules { if word.starts_with(rule.0) { return rule.1; } } return 1; } <file_sep>/elixir/nth-prime/README.md # Nth Prime Given a number n, determine what the nth prime is. By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. If your language provides methods in the standard library to deal with prime numbers, pretend they don't exist and implement them yourself. ## Running tests Execute the tests with: ```bash $ elixir bob_test.exs ``` (Replace `bob_test.exs` with the name of the test file.) ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source A variation on Problem 7 at Project Euler [http://projecteuler.net/problem=7](http://projecteuler.net/problem=7) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/typescript/grade-school/grade-school.ts type Grade = string type Students = string[] type Roster = Map<Grade, Students> export default class GradeSchool { readonly roster: Roster = new Map() studentRoster(): Roster { const result = new Map() for (const [key, value] of this.roster.entries()) { result.set(key, [... value]) } return result } addStudent(student: string, grade: number) { const value = [... this.studentsInGrade(grade), student] value.sort() this.roster.set(this.toKey(grade), value) } studentsInGrade(grade: number): Students { return [... this.roster.get(this.toKey(grade)) || []] } toKey(grade: number): Grade { return grade.toString() } }<file_sep>/rust/reverse-string/src/lib.rs extern crate unicode_segmentation; use unicode_segmentation::UnicodeSegmentation; pub fn reverse(word: &str) -> String { UnicodeSegmentation::graphemes(word, true).rev().collect::<String>() } <file_sep>/rust/robot-simulator/src/lib.rs #[derive(PartialEq, Debug)] pub enum Direction { North, East, South, West, } pub struct Robot { x: isize, y: isize, d: Direction, } impl Robot { pub fn new(x: isize, y: isize, d: Direction) -> Self { Robot { x, y, d } } pub fn turn_right(self) -> Self { let d = match self.direction() { &Direction::North => Direction::East, &Direction::East => Direction::South, &Direction::South => Direction::West, &Direction::West => Direction::North, }; Robot { d, ..self } } pub fn turn_left(self) -> Self { let d = match self.direction() { &Direction::North => Direction::West, &Direction::East => Direction::North, &Direction::South => Direction::East, &Direction::West => Direction::South, }; Robot { d, ..self } } pub fn advance(self) -> Self { let (move_x, move_y) = match self.direction() { &Direction::North => ( 0, 1), &Direction::East => ( 1, 0), &Direction::South => ( 0, -1), &Direction::West => (-1, 0), }; Robot { x: self.x + move_x, y: self.y + move_y, ..self } } pub fn instructions(self, instructions: &str) -> Self { let mut robot = self; for instruction in instructions.chars() { match instruction { 'R' => robot = robot.turn_right(), 'L' => robot = robot.turn_left(), 'A' => robot = robot.advance(), _ => panic!("crash"), } } robot } pub fn position(&self) -> (isize, isize) { (self.x, self.y) } pub fn direction(&self) -> &Direction { &self.d } } <file_sep>/typescript/matrix/matrix.ts class Matrix { rows: number[][]; columns: number[][]; constructor(input: string) { this.rows = input.split(/\n/).map(i => i.split(/\s/).map(t => parseInt(t))) this.columns = this.transpose(this.rows) } transpose(array: number[][]): number[][] { return array[0].map((_, c) => array.map(r => r[c])) } } export default Matrix <file_sep>/rust/luhn-trait/src/lib.rs pub struct Luhn(Vec<u32>); impl Luhn { pub fn is_valid(self) -> bool { let digits = self.0; if digits.len() <= 1 { return false; } let sum = digits .iter() .rev() .enumerate() .map(|(i, &n)| if i % 2 == 0 { n } else { n * 2 }) .map(|n| if n < 10 { n } else { n - 9 }) .sum::<u32>(); sum % 10 == 0 } } impl From<String> for Luhn { fn from(input: String) -> Self { input .chars() .filter(|c| !c.is_whitespace()) .map(|c| { if c.is_ascii_digit() { c.to_digit(10) } else { None } }) .collect::<Option<Vec<_>>>() .map_or_else(|| Luhn(Vec::new()), |v| Luhn(v)) } } pub trait ValidLuhn { fn valid_luhn(self) -> bool; } impl ValidLuhn for String { fn valid_luhn(self) -> bool { Luhn::from(self).is_valid() } } impl ValidLuhn for &'static str { fn valid_luhn(self) -> bool { Luhn::from(self.to_string()).is_valid() } } impl ValidLuhn for usize { fn valid_luhn(self) -> bool { Luhn::from(self.to_string()).is_valid() } } impl ValidLuhn for u8 { fn valid_luhn(self) -> bool { Luhn::from(self.to_string()).is_valid() } } impl ValidLuhn for u16 { fn valid_luhn(self) -> bool { Luhn::from(self.to_string()).is_valid() } } impl ValidLuhn for u32 { fn valid_luhn(self) -> bool { Luhn::from(self.to_string()).is_valid() } } impl ValidLuhn for u64 { fn valid_luhn(self) -> bool { Luhn::from(self.to_string()).is_valid() } } <file_sep>/rust/run-length-encoding/src/lib.rs struct Char { c: char, i: usize, } impl Char { pub fn new(c: char, i: usize) -> Char { Char { c: c, i: i } } pub fn same(&self, c: char) -> bool { self.c == c } pub fn increment(&mut self) -> () { self.i += 1 } pub fn encode(&self) -> String { if self.i <= 1 { format!("{}", self.c) } else { format!("{}{}", self.i, self.c) } } pub fn decode(&self) -> String { format!("{}", self.c).repeat(self.i) } } pub fn encode(code: &str) -> String { if code.len() == 0 { return String::new(); } let codes = code.chars().collect::<Vec<char>>(); let mut chars: Vec<Char> = vec![]; let mut last = Char::new(codes[0], 1); for c in codes.into_iter().skip(1) { if last.same(c) { last.increment(); } else { chars.push(last); last = Char::new(c, 1); } } chars.push(last); chars.iter().map(|c| c.encode()).collect() } pub fn decode(code: &str) -> String { if code.len() == 0 { return String::new(); } let codes = code.chars().collect::<Vec<char>>(); let mut chars: Vec<Char> = vec![]; let mut n = String::new(); for c in codes.into_iter() { if c.is_digit(10) { n.push(c); } else { chars.push(Char::new(c, n.parse().unwrap_or(1))); n.clear(); } } chars.iter().map(|c| c.decode()).collect() } <file_sep>/rust/robot-name/src/lib.rs use rand::seq::SliceRandom; pub struct Robot(String); const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const NUMBER: &[u8] = b"0123456789"; fn id_generator() -> String { let mut rng = &mut rand::thread_rng(); let alphabet = ALPHABET.choose_multiple(&mut rng, 2).cloned(); let number = NUMBER.choose_multiple(&mut rng, 3).cloned(); let id = alphabet.chain(number).collect(); String::from_utf8(id).unwrap_or_default() } impl Robot { pub fn new() -> Self { Robot(id_generator()) } pub fn name(&self) -> &str { &self.0 } pub fn reset_name(&mut self) { self.0 = id_generator(); } } <file_sep>/go/robot-name/robotname.go package robotname import ( crand "crypto/rand" "encoding/binary" "math/rand" ) const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" const number = "0123456789" var set = make(map[string]struct{}) type Robot struct { rand *rand.Rand name string } func (robot *Robot) Name() string { if robot.rand == nil { robot.Reset() } return robot.name } func (robot *Robot) Reset() { again: robot.rand = rand.New(rand.NewSource(randSeed())) robot.name = robot.randomStr(2, alphabet) + robot.randomStr(3, number) if _, exist := set[robot.name]; exist { goto again } set[robot.name] = struct{}{} } func (robot *Robot) randomStr(n int, charset string) string { b := make([]byte, n) for i := range b { b[i] = charset[robot.rand.Intn(len(charset))] } return string(b) } func randSeed() int64 { var seed int64 err := binary.Read(crand.Reader, binary.LittleEndian, &seed) if err != nil { panic(err) } return seed } <file_sep>/rust/raindrops/Cargo.toml [package] name = "raindrops" version = "1.0.0" <file_sep>/go/space-age/space_age.go package space type Planet string const EarthSeconds = 31557600 var planets = map[Planet]float64{ "Mercury": 0.2408467 * EarthSeconds, "Venus": 0.6151972 * EarthSeconds, "Earth": EarthSeconds, "Mars": 1.8808158 * EarthSeconds, "Jupiter": 11.862615 * EarthSeconds, "Saturn": 29.447498 * EarthSeconds, "Uranus": 84.016846 * EarthSeconds, "Neptune": 164.79132 * EarthSeconds, } func Age(seconds float64, planet Planet) float64 { if v, ok := planets[planet]; ok { return seconds / v } return 0.0 } <file_sep>/rust/nucleotide-count/src/lib.rs use std::collections::HashMap; const NUCLEOTIDES: [char; 4] = ['A', 'C', 'G', 'T']; fn is_valid(dna: &str) -> bool { dna.to_string().chars().all(|n| NUCLEOTIDES.contains(&n) ) } pub fn count(nucleotide: char, dna: &str) -> Result<usize, ()> { if !NUCLEOTIDES.contains(&nucleotide) || !is_valid(dna) { return Err(()) }; let count = dna.match_indices(nucleotide).count(); Ok(count) } pub fn nucleotide_counts(dna: &str) -> Result<HashMap<char, usize>, ()> { if !is_valid(dna) { return Err(()) } let mut hashmap = HashMap::new(); for nucleotide in NUCLEOTIDES.iter() { hashmap.insert(*nucleotide, 0); } for nucleotide in dna.to_string().chars() { *hashmap.entry(nucleotide).or_insert(0) += 1; } Ok(hashmap) } <file_sep>/rust/hello-world/Cargo.toml [package] name = "hello-world" version = "1.0.0" <file_sep>/rust/perfect-numbers/Cargo.toml [package] name = "perfect_numbers" version = "1.1.0" [dependencies] <file_sep>/rust/series/src/lib.rs pub fn series(digits: &str, len: usize) -> Vec<String> { match digits.len() { l if l == 0 => vec!["".to_string(); 6], l if l >= len => (0 .. l - len + 1).into_iter() .map(|i| digits[i .. i + len].to_string()) .collect::<Vec<_>>(), _ => vec![] } } <file_sep>/rust/armstrong-numbers/src/lib.rs pub fn is_armstrong_number(num: u32) -> bool { let number = num.to_string(); let len = number.len() as u32; num == number.chars().map(|i| i.to_digit(10).unwrap().pow(len)).sum() } <file_sep>/rust/luhn-from/src/lib.rs pub struct Luhn(Vec<u32>); impl From<String> for Luhn { fn from(input: String) -> Self { input .chars() .filter(|c| !c.is_whitespace()) .map(|c| { if c.is_ascii_digit() { c.to_digit(10) } else { None } }) .collect::<Option<Vec<_>>>() .map_or_else(|| Luhn(Vec::new()), |v| Luhn(v)) } } impl From<&'static str> for Luhn { fn from(input: &'static str) -> Self { Luhn::from(input.to_string()) } } impl From<usize> for Luhn { fn from(input: usize) -> Self { Luhn::from(input.to_string()) } } impl From<u8> for Luhn { fn from(input: u8) -> Self { Luhn::from(input.to_string()) } } impl From<u16> for Luhn { fn from(input: u16) -> Self { Luhn::from(input.to_string()) } } impl From<u32> for Luhn { fn from(input: u32) -> Self { Luhn::from(input.to_string()) } } impl From<u64> for Luhn { fn from(input: u64) -> Self { Luhn::from(input.to_string()) } } impl Luhn { pub fn is_valid(self) -> bool { let digits = self.0; if digits.len() <= 1 { return false; } let sum = digits .iter() .rev() .enumerate() .map(|(i, &n)| if i % 2 == 0 { n } else { n * 2 }) .map(|n| if n < 10 { n } else { n - 9 }) .sum::<u32>(); sum % 10 == 0 } } <file_sep>/rust/grep/src/lib.rs use failure::Error; use std::fs; pub struct Flags { n: bool, i: bool, l: bool, x: bool, v: bool, } impl Flags { pub fn new(flags: &[&str]) -> Self { Flags { n: flags.contains(&"-n"), i: flags.contains(&"-i"), l: flags.contains(&"-l"), x: flags.contains(&"-x"), v: flags.contains(&"-v"), } } } struct GrepPattern { context: String, case_insensitive: bool, match_entire_lines: bool, invert: bool, } impl GrepPattern { fn new(context: &str, flag: &Flags) -> Self { let context = if flag.i { context.to_lowercase() } else { context.to_string() }; let case_insensitive = flag.i; let match_entire_lines = flag.x; let invert = flag.v; GrepPattern { context, case_insensitive, match_entire_lines, invert, } } fn include(&self, line: &str) -> bool { let included = match (self.case_insensitive, self.match_entire_lines) { (true, true) => line.to_lowercase() == self.context, (true, false) => line.to_lowercase().contains(&self.context), (false, true) => line == self.context, (false, false) => line.contains(&self.context), }; included ^ self.invert } } struct GrepLine { context: String, file: String, number: usize, } impl GrepLine { pub fn new(context: &str, file: &str, index: usize) -> Self { GrepLine { context: context.to_string(), file: file.to_string(), number: index + 1, } } fn include(&self, pattern: &GrepPattern) -> bool { pattern.include(&self.context) } fn to_string(&self, flags: &Flags, many_files: bool) -> String { if flags.l { return self.file.to_string(); } match (flags.n, flags.l || many_files) { (true, true) => format!("{}:{}:{}", self.file, self.number, self.context), (true, false) => format!("{}:{}", self.number, self.context), (false, true) => format!("{}:{}", self.file, self.context), (false, false) => self.context.to_string(), } } } pub fn grep(pattern: &str, flags: &Flags, files: &[&str]) -> Result<Vec<String>, Error> { let pattern = GrepPattern::new(pattern, flags); let many_files = files.len() > 1; files .iter() .map(|file| fs::read_to_string(file).map(|contents| (file, contents))) .collect::<Result<Vec<_>, _>>() .map(|files| { files .iter() .flat_map(|(name, contents)| file_grep(name, contents, &pattern, flags, many_files)) .collect() }) .map_err(std::convert::Into::into) } fn file_grep( name: &str, contents: &str, pattern: &GrepPattern, flags: &Flags, many_files: bool, ) -> Vec<String> { let mut candidate = contents .lines() .enumerate() .map(|(i, line)| GrepLine::new(line, name, i)) .filter(|line| line.include(pattern)) .map(|line| line.to_string(flags, many_files)) .collect::<Vec<_>>(); if flags.l { candidate.dedup(); }; candidate } <file_sep>/rust/atbash-cipher/src/lib.rs /// "Encipher" with the Atbash cipher. pub fn encode(plain: &str) -> String { plain .chars() .filter_map(|c| match c { '0'...'9' => Some(c), 'A'...'z' => Some(atbash(c.to_ascii_lowercase())), _ => None, }) .collect::<Vec<_>>() .chunks(5) .map(|window| window.iter().collect::<String>()) .collect::<Vec<_>>() .join(" ") } /// "Decipher" with the Atbash cipher. pub fn decode(cipher: &str) -> String { cipher .chars() .filter_map(|c| match c { '0'...'9' => Some(c), 'a'...'z' => Some(atbash(c)), _ => None, }) .collect() } fn atbash(c: char) -> char { ((25 - ((c as u8) - 97)) + 97) as char } <file_sep>/typescript/linked-list/linked-list.ts class Node<T> { value: T next: Node<T> | undefined constructor(value: T, next: Node<T> | undefined) { this.value = value this.next = next } } export default class LinkedList<T> { head: Node<T> | undefined = undefined push(value: T) { this.head = new Node(value, this.head) } pop(): T { const head = this.head if (head === undefined) { throw new Error() } this.head = head.next return head.value } shift(): T { let head = this.head if (!head) { throw new Error() } if (!head.next) { if (!head.value) { throw new Error() } this.head = undefined return head.value } let tail = head.next while (tail.next !== undefined) { head = tail tail = tail.next } head.next = undefined return tail.value } unshift(value: T) { const node = new Node(value, undefined) let head = this.head if (head === undefined) { this.head = node return } while (head.next !== undefined) { head = head.next } head.next = node } delete(value: T) { let head = this.head if (head === undefined) { return } if (head.value === value) { this.head = head.next } while (head.next !== undefined) { if (head.next.value !== value) { head = head.next } else { head.next = head.next.next } } } count(): number { let count = 0 let head = this.head while (head !== undefined) { head = head.next count++ } return count } }<file_sep>/elixir/queen-attack/README.md # Queen Attack Given the position of two queens on a chess board, indicate whether or not they are positioned so that they can attack each other. In the game of chess, a queen can attack pieces which are on the same row, column, or diagonal. A chessboard can be represented by an 8 by 8 array. So if you're told the white queen is at (2, 3) and the black queen at (5, 6), then you'd know you've got a set-up like so: ```text _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ W _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ B _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ``` You'd also be able to answer whether the queens can attack each other. In this case, that answer would be yes, they can, because both pieces share a diagonal. ## Running tests Execute the tests with: ```bash $ elixir queen_attack_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source J Dalbey's Programming Practice problems [http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html](http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/wordy/src/lib.rs enum Calculate { Integer(i32), Plus, Minus, Multiplied, Divided } impl Calculate { fn new(command: &str) -> Option<Self> { match (command, command.parse()) { (_, Ok(n)) => Some(Calculate::Integer(n)), ("plus", _) => Some(Calculate::Plus), ("minus", _) => Some(Calculate::Minus), ("multiplied", _) => Some(Calculate::Multiplied), ("divided", _) => Some(Calculate::Divided), _ => None, } } } pub struct WordProblem { commands: Vec<Calculate> } impl WordProblem { pub fn new(command: &str) -> Self { WordProblem { commands: command.trim_left_matches("What is ") .trim_right_matches('?') .split_whitespace() .filter_map(|s| Calculate::new(s)) .collect::<Vec<_>>() } } pub fn answer(&self) -> Option<i32> { match self.commands.split_first() { Some((_, [])) => None, Some((&Calculate::Integer(i), commands)) => commands.chunks(2).fold(Some(i), |acc, chunk| { match chunk { [Calculate::Plus, Calculate::Integer(n)] => acc.map(|m| m + n), [Calculate::Minus, Calculate::Integer(n)] => acc.map(|m| m - n), [Calculate::Multiplied, Calculate::Integer(n)] => acc.map(|m| m * n), [Calculate::Divided, Calculate::Integer(n)] => acc.map(|m| m / n), _ => None } }), _ => None } } } <file_sep>/elixir/saddle-points/README.md # Saddle Points Detect saddle points in a matrix. So say you have a matrix like so: ```text 0 1 2 |--------- 0 | 9 8 7 1 | 5 3 2 <--- saddle point at (1,0) 2 | 6 6 7 ``` It has a saddle point at (1, 0). It's called a "saddle point" because it is greater than or equal to every element in its row and less than or equal to every element in its column. A matrix may have zero or more saddle points. Your code should be able to provide the (possibly empty) list of all the saddle points for any given matrix. Note that you may find other definitions of matrix saddle points online, but the tests for this exercise follow the above unambiguous definition. ## Running tests Execute the tests with: ```bash $ elixir saddle_points_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source J Dalbey's Programming Practice problems [http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html](http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/elixir/pascals-triangle/README.md # Pascal's Triangle Compute Pascal's triangle up to a given number of rows. In Pascal's Triangle each number is computed by adding the numbers to the right and left of the current position in the previous row. ```text 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 # ... etc ``` ## Running tests Execute the tests with: ```bash $ elixir pascals_triangle_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source Pascal's Triangle at Wolfram Math World [http://mathworld.wolfram.com/PascalsTriangle.html](http://mathworld.wolfram.com/PascalsTriangle.html) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/queen-attack/src/lib.rs pub struct ChessPosition { file: i8, rank: i8 } impl ChessPosition { pub fn new(file: i8, rank: i8) -> Result<ChessPosition, ()> { if file < 0 || 8 <= file || rank < 0 || 8 <= rank { return Err(()); } Ok(ChessPosition { file, rank }) } } pub struct Queen { position: ChessPosition } impl Queen { pub fn new(position: ChessPosition) -> Queen { Queen { position } } pub fn can_attack(self, other: &Queen) -> bool { if self.position.file == other.position.file { return true; } if self.position.rank == other.position.rank { return true; } if (self.position.file - self.position.rank) == (other.position.file - other.position.rank) { return true; } if (self.position.file + self.position.rank) == (other.position.file + other.position.rank) { return true; } return false; } } <file_sep>/go/flatten-array/README.md # Flatten Array Take a nested list and return a single flattened list with all values except nil/null. The challenge is to write a function that accepts an arbitrarily-deep nested list-like structure and returns a flattened structure without any nil/null values. For Example input: [1,[2,3,null,4],[null],5] output: [1,2,3,4,5] ## Running the tests To run the tests run the command `go test` from within the exercise directory. If the test suite contains benchmarks, you can run these with the `-bench` flag: go test -bench . Keep in mind that each reviewer will run benchmarks on a different machine, with different specs, so the results from these benchmark tests may vary. ## Further information For more detailed information about the Go track, including how to get help if you're having trouble, please visit the exercism.io [Go language page](http://exercism.io/languages/go/about). ## Source Interview Question [https://reference.wolfram.com/language/ref/Flatten.html](https://reference.wolfram.com/language/ref/Flatten.html) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/sieve/Cargo.toml [package] name = "sieve" version = "1.1.0" <file_sep>/rust/spiral-matrix/src/lib.rs #[derive(Copy, Clone, Debug)] enum Direction { RIGHT, DOWN, LEFT, UP, } pub fn spiral_matrix(size: usize) -> Vec<Vec<usize>> { if size == 0 { return vec![]; }; let mut matrix = vec![vec![0; size]; size]; let mut x = 0; let mut y = 0; let mut direction = Direction::RIGHT; let w = size - 1; let h = size - 1; for i in 1..size * size + 1 { matrix[y][x] = i; direction = match direction { Direction::RIGHT if x >= w => Direction::DOWN, Direction::DOWN if y >= h => Direction::LEFT, Direction::LEFT if x == 0 => Direction::UP, Direction::UP if y == 0 => Direction::RIGHT, Direction::RIGHT if matrix[y][x + 1] != 0 => Direction::DOWN, Direction::DOWN if matrix[y + 1][x] != 0 => Direction::LEFT, Direction::LEFT if matrix[y][x - 1] != 0 => Direction::UP, Direction::UP if matrix[y - 1][x] != 0 => Direction::RIGHT, Direction::RIGHT => Direction::RIGHT, Direction::DOWN => Direction::DOWN, Direction::LEFT => Direction::LEFT, Direction::UP => Direction::UP, }; match direction { Direction::RIGHT => x += 1, Direction::DOWN => y += 1, Direction::LEFT => x -= 1, Direction::UP => y -= 1, } } matrix } <file_sep>/go/clock/example_clock_test.go package clock import "fmt" func ExampleClock_new() { // a new clock clock1 := New(10, 30) fmt.Println(clock1.String()) // Output: 10:30 } func ExampleClock_Add_add() { // create a clock clock := New(10, 30) // add 30 minutes to it clock = clock.Add(30) fmt.Println(clock.String()) // Output: 11:00 } func ExampleClock_Add_subtract() { // create a clock clock := New(10, 30) // subtract an hour and a half from it clock = clock.Add(-90) fmt.Println(clock.String()) // Output: 09:00 } func ExampleClock_compare() { // a new clock clock1 := New(10, 30) // a second clock, same as the first clock2 := New(10, 30) // are the clocks equal? fmt.Println(clock2 == clock1) // change the second clock clock2 = clock2.Add(30) // are the clocks equal now? fmt.Println(clock2 == clock1) // Output: // true // false } <file_sep>/rust/collatz-conjecture/src/lib.rs // return Some(x) where x is the number of steps required to reach 1 pub fn collatz(n: u64) -> Option<u64> { do_collatz(n, 0) } fn do_collatz(n: u64, count: u64) -> Option<u64> { match (n, n % 2) { (0, _) => None, (1, _) => Some(count), (i, 0) => do_collatz(i / 2, count + 1), (i, _) => do_collatz(i * 3 + 1, count + 1) } } <file_sep>/rust/luhn/src/lib.rs /// Check a Luhn checksum. pub fn is_valid(code: &str) -> bool { let codes: Option<Vec<_>> = code.chars() .map(|c| if c.is_ascii_digit() || c.is_whitespace() { Some(c) } else { None } ) .collect(); if codes.is_none() { return false; } let digits: Vec<_> = codes.unwrap() .iter() .flat_map(|c| c.to_digit(10) ) .collect(); if digits.len() <= 1 { return false; } let sum = digits .iter() .rev() .enumerate() .map(|(i, &n)| if i % 2 == 0 { n } else { n * 2 } ) .map(|n| if n < 10 { n } else { n - 9 } ) .sum::<u32>(); sum % 10 == 0 } <file_sep>/rust/gigasecond/Cargo.toml [package] name = "gigasecond" version = "1.0.0" [dependencies] chrono = "0.4" <file_sep>/go/clock/clock.go package clock import "fmt" // Clock have minutes type Clock struct { minutes int } // MinutesPerDay 1 day == 24 hour * 60 minute const MinutesPerDay = 24 * 60 // New is constructor func New(hour, minute int) Clock { newMinute := hour*60 + minute for newMinute < 0 { newMinute += MinutesPerDay } newMinute %= MinutesPerDay return Clock{minutes: newMinute} } func (c Clock) hour() int { return c.minutes / 60 % 24 } func (c Clock) minute() int { return c.minutes % 60 } // String is stringer func (c Clock) String() string { return fmt.Sprintf("%02d:%02d", c.hour(), c.minute()) } // Add is calculation func (c Clock) Add(minutes int) Clock { return New(c.hour(), c.minute()+minutes) } <file_sep>/rust/saddle-points/Cargo.toml [package] name = "saddle-points" version = "1.1.0" [dependencies] <file_sep>/elixir/flatten-array/README.md # Flatten Array Take a nested list and return a single flattened list with all values except nil/null. The challenge is to write a function that accepts an arbitrarily-deep nested list-like structure and returns a flattened structure without any nil/null values. For Example input: [1,[2,3,null,4],[null],5] output: [1,2,3,4,5] ## Running tests Execute the tests with: ```bash $ elixir flatten_array_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source Interview Question [https://reference.wolfram.com/language/ref/Flatten.html](https://reference.wolfram.com/language/ref/Flatten.html) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/palindrome-products/src/lib.rs use std::collections::HashSet; pub type Palindrome = u64; pub fn get_palindrome_products(min: u64, max: u64) -> Vec<Palindrome> { let range = (min..max+1).collect::<Vec<_>>(); let products = range.iter().flat_map(|n| range.iter().filter_map(move |m| { let product = n * m; if is_palindromic(product) { Some(product) } else { None } }) ).collect::<HashSet<_>>(); products.into_iter().collect::<Vec<_>>() } pub fn min(palindromes: &[Palindrome]) -> Option<Palindrome> { palindromes.iter().min().map(|n| *n) } pub fn max(palindromes: &[Palindrome]) -> Option<Palindrome> { palindromes.iter().max().map(|n| *n) } fn is_palindromic(n: u64) -> bool { let mut base = n; let mut result = 0; while base > 0 { result = result * 10 + base % 10; base /= 10; } n == result } <file_sep>/elixir/sieve/README.md # Sieve Use the Sieve of Eratosthenes to find all the primes from 2 up to a given number. The Sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2. Create your range, starting at two and continuing up to and including the given limit. (i.e. [2, limit]) The algorithm consists of repeating the following over and over: - take the next available unmarked number in your list (it is prime) - mark all the multiples of that number (they are not prime) Repeat until you have processed each number in your range. When the algorithm terminates, all the numbers in the list that have not been marked are prime. The wikipedia article has a useful graphic that explains the algorithm: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Notice that this is a very specific algorithm, and the tests don't check that you've implemented the algorithm, only that you've come up with the correct list of primes. ## Running tests Execute the tests with: ```bash $ elixir sieve_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source Sieve of Eratosthenes at Wikipedia [http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/accumulate/src/lib.rs pub fn map_function(list: Vec<i32>, f: &Fn(i32) -> i32) -> Vec<i32> { let mut result = Vec::new(); for item in list { result.push(f(item)); } result } pub fn map_closure<F>(list: Vec<i32>, f: F) -> Vec<i32> where F: Fn(i32) -> i32 { let mut result = Vec::new(); for item in list { result.push(f(item)); } result } <file_sep>/rust/diamond/src/lib.rs pub fn get_diamond(c: char) -> Vec<String> { let n = c as u8 - 64; if n == 1 { return vec![c.to_string()] }; let mut res = vec![]; for i in 0..n { let mut s = String::new(); let alphabet = (65 + i) as char; let padding = n - i - 1; for _ in 0..padding { s.push(' '); } s.push(alphabet); if i != 0 { let center = 2 * i - 1; for _ in 0..center { s.push(' '); } s.push(alphabet); } for _ in 0..padding { s.push(' '); } res.push(s); } let mut bottom = res.clone(); bottom.reverse(); bottom.remove(0); res.append(&mut bottom); res } <file_sep>/go/tournament/tournament.go package tournament import ( "bufio" "errors" "fmt" "io" "sort" "strings" ) type Teams []*Team func (t Teams) Len() int { return len(t) } func (t Teams) Swap(i, j int) { t[i], t[j] = t[j], t[i] } func (t Teams) Less(i, j int) bool { if t[i].Points() == t[j].Points() { return t[i].Name < t[j].Name } return t[i].Points() > t[j].Points() } func (t Teams) String() string { var s string for _, v := range t { s += fmt.Sprint(v) } return s } type Header struct{} func (h *Header) String() string { return fmt.Sprintf("%-30s | %2s | %2s | %2s | %2s | %2s\n", "Team", "MP", "W", "D", "L", "P") } type Team struct { Name string Played, Won, Drawn, Lost int } func (t *Team) Play() { t.Played++ } func (t *Team) Win() { t.Won++ } func (t *Team) Lose() { t.Lost++ } func (t *Team) Draw() { t.Drawn++ } func (t *Team) Points() int { return t.Won*3 + t.Drawn*1 } func (t *Team) String() string { return fmt.Sprintf("%-30s | %2d | %2d | %2d | %2d | %2d\n", t.Name, t.Played, t.Won, t.Drawn, t.Lost, t.Points()) } var teams = make(map[string]*Team) func clear() { teams = make(map[string]*Team) } func Tally(in io.Reader, out io.Writer) error { defer clear() reader := bufio.NewReader(in) for { line, _, err := reader.ReadLine() if err != nil { break } if len(line) == 0 { continue } parse := strings.Split(string(line), ";") if len(parse) != 3 { continue } apply0, apply1, err := GetAcrion(parse[2]) if err != nil { continue } PlayedTeam(parse[0], apply0) PlayedTeam(parse[1], apply1) } if (len(teams)) == 0 { return errors.New("empty") } fmt.Fprint(out, new(Header)) results := Teams{} for _, v := range teams { results = append(results, v) } sort.Sort(results) fmt.Fprint(out, results) return nil } func GetAcrion(result string) (apply0, apply1 func(*Team), err error) { switch result { case "win": apply0 = func(t *Team) { t.Win() } apply1 = func(t *Team) { t.Lose() } case "loss": apply0 = func(t *Team) { t.Lose() } apply1 = func(t *Team) { t.Win() } case "draw": apply0 = func(t *Team) { t.Draw() } apply1 = func(t *Team) { t.Draw() } default: err = errors.New(result) } return } func PlayedTeam(name string, fn func(*Team)) { team, ok := teams[name] if ok == true { team.Play() fn(team) } else { newTeam := &Team{Name: name} teams[name] = newTeam newTeam.Play() fn(newTeam) } } <file_sep>/go/tree-building/tree_building.go package tree import ( "errors" "sort" ) type Record struct { ID, Parent int } type Node struct { ID int Children []*Node } const rootID int = 0 func Build(records []Record) (*Node, error) { if len(records) == 0 { return nil, nil } sort.Slice(records, func(i, j int) bool { return records[i].ID < records[j].ID }) tree := map[int]*Node{} for i, r := range records { if r.ID != i { return nil, errors.New("non continuous") } node := &Node{ID: r.ID} if r.ID == rootID { if r.Parent != 0 { return nil, errors.New("root node has parent") } } else { parent := tree[r.Parent] if parent == nil { return nil, errors.New("parent node not found") } parent.Children = append(parent.Children, node) } tree[r.ID] = node } return tree[rootID], nil } <file_sep>/typescript/clock/clock.ts export default class Clock { readonly total_minute: number constructor(hour: number, minute: number = 0) { this.total_minute = hour * 60 + minute } private get hour(): number { const h = Math.floor(this.total_minute / 60 % 24) return h >= 0 ? h : 24 + h } private get minute(): number { const m = this.total_minute % 60 return m >= 0 ? m : 60 + m } private padTwo(n: number): string { return n.toString().padStart(2, '0') } toString(): string { return `${this.padTwo(this.hour)}:${this.padTwo(this.minute)}` } plus(minute: number): Clock { return new Clock(0, this.total_minute + minute) } minus(minute: number): Clock { return new Clock(0, this.total_minute - minute) } equals(other: Clock): boolean { return this.toString() === other.toString() } }<file_sep>/typescript/rational-numbers/rational-numbers.ts export default class Rational { constructor(public readonly numerator: number, public readonly denominator: number) { } add(other: Rational): Rational { const numerator = this.numerator * other.denominator + other.numerator * this.denominator const denominator = this.denominator * other.denominator return this.reduced_rational(numerator, denominator) } sub(other: Rational): Rational { const numerator = this.numerator * other.denominator - other.numerator * this.denominator const denominator = this.denominator * other.denominator return this.reduced_rational(numerator, denominator) } mul(other: Rational): Rational { const numerator = this.numerator * other.numerator const denominator = this.denominator * other.denominator return this.reduced_rational(numerator, denominator) } div(other: Rational): Rational { const numerator = this.numerator * other.denominator const denominator = this.denominator * other.numerator if (denominator === 0) { throw new Error('zero divide') } return this.reduced_rational(numerator, denominator) } abs(): Rational { const numerator = Math.abs(this.numerator) const denominator = Math.abs(this.denominator) return this.reduced_rational(numerator, denominator) } exprational(n: number): Rational { if (n >= 0) { const numerator = this.numerator ** n const denominator = this.denominator ** n return this.reduced_rational(numerator, denominator) } else { const m = Math.abs(n) const numerator = this.denominator ** m const denominator = this.numerator ** m return this.reduced_rational(numerator, denominator) } } expreal(n: number): number { return 10 ** (Math.log10(n ** this.numerator) / this.denominator) } reduce(): Rational { return this.reduced_rational(this.numerator, this.denominator) } private reduced_rational(numerator: number, denominator: number): Rational { const sign = denominator >= 0 ? 1 : -1 const gcd = this.gcd(Math.abs(numerator), Math.abs(denominator)) return new Rational(sign * numerator / gcd, sign * denominator / gcd) } private gcd(x: number, y: number): number { return y === 0 ? x : this.gcd(y, x % y) } }<file_sep>/go/isogram/isogram.go package isogram import ( "strings" ) var ignore = map[rune]struct{}{ '-': struct{}{}, ' ': struct{}{}, } // IsIsogram isogram is a word or phrase without a repeating letter func IsIsogram(s string) bool { set := make(map[rune]struct{}) for _, r := range strings.ToLower(s) { if _, skip := ignore[r]; skip { continue } if _, ok := set[r]; ok { return false } set[r] = struct{}{} } return true } <file_sep>/rust/nth-prime/src/lib.rs #![crate_type = "lib"] #![crate_name = "nth_prime"] pub fn nth(n: usize) -> Result<usize, usize> { if n <= 0 { return Err(n); } (2..) .filter(|&i| is_prime(i) ) .nth(n - 1) .ok_or(n) } fn is_prime(n: usize) -> bool { if n <= 2 { return true; } if n % 2 == 0 { return false; } (2..) .take_while(|i| i * i <= n ) .all(|i| n % i != 0 ) } <file_sep>/rust/crypto-square/src/lib.rs pub fn encrypt(input: &str) -> String { let chars = normalize(input).chars().collect::<Vec<_>>(); mapping(square(chars.len())) .iter() .map(|row| { row.iter() .map(|&n| chars.get(n).unwrap_or(&' ')) .collect::<String>() }) .collect::<Vec<_>>() .join(" ") } fn normalize(input: &str) -> String { input .chars() .filter(|c| c.is_alphanumeric()) .map(|c| c.to_lowercase().to_string()) .collect() } fn square(size: usize) -> (usize, usize) { for c in 1.. { for r in c - 1..c + 1 { if c * r >= size { return (c, r); } } } return (0, 0); } fn mapping((c, r): (usize, usize)) -> Vec<Vec<usize>> { (0..c).map(|n| step_by(n, c, r)).collect() } fn step_by(offset: usize, step: usize, len: usize) -> Vec<usize> { let mut res = Vec::with_capacity(len); let mut i = 0; while res.len() < len { res.push(i + offset); i += step; } res } <file_sep>/rust/pangram/src/lib.rs pub fn is_pangram(sentence: &str) -> bool { let mut chars = sentence.to_string() .chars() .filter_map(|c| if c.is_ascii_alphabetic() { Some(c.to_ascii_lowercase()) } else { None }) .collect::<Vec<_>>(); chars.sort(); chars.dedup(); chars.len() == 26 } <file_sep>/rust/etl/src/lib.rs use std::collections::BTreeMap; pub fn transform(input: &BTreeMap<i32, Vec<char>>) -> BTreeMap<char, i32> { input.iter() .flat_map(|(key, values)| values.iter() .map(|v| (v.to_ascii_lowercase(), *key) ) .collect::<Vec<_>>() ) .collect() } <file_sep>/rust/largest-series-product/src/lib.rs #[derive(Debug, PartialEq)] pub enum Error { SpanTooLong, InvalidDigit(char), } pub fn lsp(string_digits: &str, span: usize) -> Result<u64, Error> { if span == 0 { return Ok(1) } if string_digits.len() < span { return Err(Error::SpanTooLong) } string_digits.chars() .map(|c| c.to_digit(10).map(|n| n as u64).ok_or(c) ) .collect::<Result<Vec<_>, _>>() .map_err(|c| Error::InvalidDigit(c) ) .map(|digits| digits.windows(span) .map(|window| window.iter().product() ) .max() .unwrap() ) } <file_sep>/rust/scrabble-score/src/lib.rs #[macro_use] extern crate lazy_static; use std::collections::HashMap; lazy_static! { static ref SCORE_MAP: HashMap<char, u32> = { [('A', 1), ('B', 3), ('C', 3), ('D', 2), ('E', 1), ('F', 4), ('G', 2), ('H', 4), ('I', 1), ('J', 8), ('K', 5), ('L', 1), ('M', 3), ('N', 1), ('O', 1), ('P', 3), ('Q', 10), ('R', 1), ('S', 1), ('T', 1), ('U', 1), ('V', 4), ('W', 4), ('X', 8), ('Y', 4), ('Z', 10)] .iter().cloned().collect() }; } pub fn score(words : &str) -> u32 { words.to_string() .chars() .map(|char| SCORE_MAP.get(&char.to_ascii_uppercase()).unwrap_or(&0) ) .sum() } <file_sep>/rust/rotational-cipher/src/lib.rs pub fn rotate(letters: &str, n: u8) -> String { letters .chars() .map(|c| match (c.is_ascii_alphabetic(), c.is_ascii_uppercase()) { (true, true) => rot(c, 'A', n), (true, false) => rot(c, 'a', n), _ => c } ) .collect() } fn rot(letter: char, base_letter: char, n: u8) -> char { let code_point = letter as u8; let base_code_point = base_letter as u8; let rot_code_point = base_code_point + (code_point - base_code_point + n % 26) % 26; rot_code_point as char } <file_sep>/elixir/tournament/README.md # Tournament Tally the results of a small football competition. Based on an input file containing which team played against which and what the outcome was, create a file with a table like this: ``` Team | MP | W | D | L | P Devastating Donkeys | 3 | 2 | 1 | 0 | 7 Allegoric Alaskans | 3 | 2 | 0 | 1 | 6 Blithering Badgers | 3 | 1 | 0 | 2 | 3 Courageous Californians | 3 | 0 | 1 | 2 | 1 ``` What do those abbreviations mean? - MP: Matches Played - W: Matches Won - D: Matches Drawn (Tied) - L: Matches Lost - P: Points A win earns a team 3 points. A draw earns 1. A loss earns 0. The outcome should be ordered by points, descending. In case of a tie, teams are ordered alphabetically. ### Input Your tallying program will receive input that looks like: ``` Allegoric Alaskans;Blithering Badgers;win Devastating Donkeys;Courageous Californians;draw Devastating Donkeys;Allegoric Alaskans;win Courageous Californians;Blithering Badgers;loss Blithering Badgers;Devastating Donkeys;loss Allegoric Alaskans;Courageous Californians;win ``` The result of the match refers to the first team listed. So this line ``` Allegoric Alaskans;Blithering Badgers;win ``` Means that the Allegoric Alaskans beat the Blithering Badgers. This line: ``` Courageous Californians;Blithering Badgers;loss ``` Means that the Blithering Badgers beat the Courageous Californians. And this line: ``` Devastating Donkeys;Courageous Californians;draw ``` Means that the Devastating Donkeys and Courageous Californians tied. Formatting the output is easy with `String`'s padding functions. All number columns can be left-padded with spaces to a width of 2 characters, while the team name column can be right-padded with spaces to a width of 30. ## Running tests Execute the tests with: ```bash $ elixir bob_test.exs ``` (Replace `bob_test.exs` with the name of the test file.) ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/pascals-triangle/src/lib.rs pub struct PascalsTriangle { n: u32 } impl PascalsTriangle { pub fn new(row_count: u32) -> Self { PascalsTriangle { n: row_count } } pub fn rows(&self) -> Vec<Vec<u32>> { let mut rows = vec![]; for i in 1..self.n+1 { let mut row = vec![]; for j in 0..i { row.push(self.c(i-1, j)); } rows.push(row); } rows } fn c(&self, n: u32, m:u32) -> u32 { self.f(n) / (self.f(m) * self.f(n - m)) } fn f(&self, n: u32) -> u32 { if n == 0 { 1 } else { n * self.f(n - 1) } } } <file_sep>/rust/bob/src/lib.rs pub fn reply(message: &str) -> &str { let message = message.trim(); if is_silence(message) { return "Fine. Be that way!" } match (is_shout(message), is_ask(message)) { (true, true) => "Calm down, I know what I'm doing!", (true, _ ) => "Whoa, chill out!", (_ , true) => "Sure.", _ => "Whatever." } } fn is_shout(message: &str) -> bool { message == message.to_uppercase() && message != message.to_lowercase() } fn is_ask(message: &str) -> bool { message.ends_with("?") } fn is_silence(message: &str) -> bool { message.is_empty() } <file_sep>/rust/word-count/src/lib.rs use std::collections::HashMap; /// Count occurrences of words. pub fn word_count(words: &str) -> HashMap<String, u32> { let mut map: HashMap<String, u32> = HashMap::new(); words.split(|c: char| !c.is_alphanumeric() ) .filter(|word| word.len() != 0 ) .for_each(|word| *map.entry(word.to_lowercase().to_string()).or_insert(0) += 1 ); map } <file_sep>/rust/armstrong-numbers/README.md # Armstrong Numbers An [Armstrong number](https://en.wikipedia.org/wiki/Narcissistic_number) is a number that is the sum of its own digits each raised to the power of the number of digits. For example: - 9 is an Armstrong number, because `9 = 9^1 = 9` - 10 is *not* an Armstrong number, because `10 != 1^2 + 0^2 = 2` - 153 is an Armstrong number, because: `153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153` - 154 is *not* an Armstrong number, because: `154 != 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190` Write some code to determine whether a number is an Armstrong number. ## Rust Installation Refer to the [exercism help page][help-page] for Rust installation and learning resources. ## Writing the Code Execute the tests with: ```bash $ cargo test ``` All but the first test have been ignored. After you get the first test to pass, remove the ignore flag (`#[ignore]`) from the next test and get the tests to pass again. The test file is located in the `tests` directory. You can also remove the ignore flag from all the tests to get them to run all at once if you wish. Make sure to read the [Modules](https://doc.rust-lang.org/book/second-edition/ch07-00-modules.html) chapter if you haven't already, it will help you with organizing your files. ## Feedback, Issues, Pull Requests The [exercism/rust](https://github.com/exercism/rust) repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help! If you want to know more about Exercism, take a look at the [contribution guide](https://github.com/exercism/docs/blob/master/contributing-to-language-tracks/README.md). [help-page]: http://exercism.io/languages/rust [modules]: https://doc.rust-lang.org/book/second-edition/ch07-00-modules.html [cargo]: https://doc.rust-lang.org/book/second-edition/ch14-00-more-about-cargo.html ## Source Wikipedia [https://en.wikipedia.org/wiki/Narcissistic_number](https://en.wikipedia.org/wiki/Narcissistic_number) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/simple-linked-list/src/lib.rs pub struct SimpleLinkedList<T> { head: Option<Box<Node<T>>>, len: usize, } struct Node<T> { element: T, next: Option<Box<Node<T>>>, } pub struct IntoIter<T>(SimpleLinkedList<T>); impl<T> SimpleLinkedList<T> { pub fn new() -> Self { SimpleLinkedList::<T> { head: None, len: 0 } } pub fn len(&self) -> usize { self.len } pub fn push(&mut self, element: T) { self.len += 1; self.head = Some(Box::new(Node::new(element, self.head.take()))) } pub fn pop(&mut self) -> Option<T> { self.head.take().map(|node| { self.len -= 1; let node = *node; self.head = node.next; node.element }) } pub fn peek(&self) -> Option<&T> { self.head.as_ref().map(|node| &node.element) } pub fn into_iter(self) -> IntoIter<T> { IntoIter(self) } } impl<T> Iterator for IntoIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.0.pop() } } impl<T: Clone> SimpleLinkedList<T> { pub fn rev(&self) -> SimpleLinkedList<T> { let mut list: SimpleLinkedList<T> = SimpleLinkedList::new(); let mut current = self.head.as_ref(); while let Some(node) = current { list.push(node.element.clone()); current = node.next.as_ref(); } list } } impl<'a, T: Clone> From<&'a [T]> for SimpleLinkedList<T> { fn from(items: &[T]) -> Self { let mut list: SimpleLinkedList<T> = SimpleLinkedList::new(); for item in items { list.push(item.clone()); } list } } impl<T> Into<Vec<T>> for SimpleLinkedList<T> { fn into(self) -> Vec<T> { let mut vec = self.into_iter().collect::<Vec<_>>(); vec.reverse(); vec } } impl<T> Node<T> { pub fn new(element: T, next: Option<Box<Node<T>>>) -> Self { Node::<T> { element: element, next: next, } } } <file_sep>/go/twelve-days/twelve_days.go package twelve type Songs struct { Number int } func (s Songs) Count() string { var t string switch s.Number { case 1: t = "first" case 2: t = "second" case 3: t = "third" case 4: t = "fourth" case 5: t = "fifth" case 6: t = "sixth" case 7: t = "seventh" case 8: t = "eighth" case 9: t = "ninth" case 10: t = "tenth" case 11: t = "eleventh" case 12: t = "twelfth" } return t } func (s Songs) Song() string { var t string for i := s.Number; 0 < i; i-- { switch i { case 1: t += "a Partridge in a Pear Tree." case 2: t += "two Turtle Doves, and " case 3: t += "three French Hens, " case 4: t += "four Calling Birds, " case 5: t += "five Gold Rings, " case 6: t += "six Geese-a-Laying, " case 7: t += "seven Swans-a-Swimming, " case 8: t += "eight Maids-a-Milking, " case 9: t += "nine Ladies Dancing, " case 10: t += "ten Lords-a-Leaping, " case 11: t += "eleven Pipers Piping, " case 12: t += "twelve Drummers Drumming, " } } return t } func Song() string { var s string for i := 1; i <= 12; i++ { s += Verse(i) + "\n" } return s } func Verse(i int) string { songs := Songs{Number: i} return "On the " + songs.Count() + " day of Christmas my true love gave to me, " + songs.Song() } <file_sep>/rust/prime-factors/Cargo.toml [package] name = "prime_factors" version = "1.1.0" authors = ["sacherjj <<EMAIL>>"] [dependencies] <file_sep>/typescript/secret-handshake/secret-handshake.ts const Events = { 'wink': 0b00001, 'double blink': 0b00010, 'close your eyes': 0b00100, 'jump': 0b01000, } export default class HandShake { readonly n: number; readonly reverse: boolean; constructor(n: number) { this.n = n this.reverse = this.match(n, 0b10000) } commands(): string[] { return Object.entries(Events) .filter(([_, value]) => this.match(this.n, value)) .map(([key, _]) => key) .sort(_ => this.reverse ? 1 : 0) } match(lhs: number, rhs: number): boolean { return (lhs & rhs) !== 0 } }<file_sep>/rust/atbash-cipher/Cargo.toml [package] name = "atbash-cipher" version = "1.1.0" <file_sep>/go/sublist/README.md # Sublist Given two lists determine if the first list is contained within the second list, if the second list is contained within the first list, if both lists are contained within each other or if none of these are true. Specifically, a list A is a sublist of list B if by dropping 0 or more elements from the front of B and 0 or more elements from the back of B you get a list that's completely equal to A. Examples: * A = [1, 2, 3], B = [1, 2, 3, 4, 5], A is a sublist of B * A = [3, 4, 5], B = [1, 2, 3, 4, 5], A is a sublist of B * A = [3, 4], B = [1, 2, 3, 4, 5], A is a sublist of B * A = [1, 2, 3], B = [1, 2, 3], A is equal to B * A = [1, 2, 3, 4, 5], B = [2, 3, 4], A is a superlist of B * A = [1, 2, 4], B = [1, 2, 3, 4, 5], A is not a superlist of, sublist of or equal to B ## Running the tests To run the tests run the command `go test` from within the exercise directory. If the test suite contains benchmarks, you can run these with the `-bench` flag: go test -bench . Keep in mind that each reviewer will run benchmarks on a different machine, with different specs, so the results from these benchmark tests may vary. ## Further information For more detailed information about the Go track, including how to get help if you're having trouble, please visit the exercism.io [Go language page](http://exercism.io/languages/go/about). ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/bob/Cargo.toml [package] name = "bob" version = "1.2.0" <file_sep>/rust/diffie-hellman/Cargo.toml [package] name = "diffie-hellman" version = "0.1.0" [dependencies] primal-check = "0.2.3" rand = "0.4" num-bigint = "0.1" num-traits = "0.1" <file_sep>/rust/phone-number/src/lib.rs pub fn number(user_number: &str) -> Option<String> { let input_number = user_number.chars() .filter_map(|c| if c.is_ascii_digit() { c.to_digit(10) } else { None } ) .collect::<Vec<_>>(); let phone_number = if input_number.len() == 10 { Some(input_number.as_slice()) } else if input_number.len() == 11 && input_number.get(0) == Some(&1) { input_number.get(1..) } else { None }; if let Some(number) = phone_number { match number { [n1, _, _, n2, _, _, _, _, _, _] if n1 >= &2 && n2 >= &2 => number.into_iter().cloned().filter_map(|i| std::char::from_digit(i, 10)).collect::<String>().into(), _ => None } } else { None } } <file_sep>/rust/beer-song/src/lib.rs pub fn verse(n: i32) -> String { format!( "{}, {}.\n{}, {}.\n", bottle_of_bear_on_the_wall(n), bottle_of_bear(n).to_lowercase(), take_beer(n), bottle_of_bear_on_the_wall(n - 1).to_lowercase() ) } pub fn sing(start: i32, end: i32) -> String { (end .. start + 1).rev() .map(|n| verse(n)) .collect::<Vec<_>>() .join("\n") } fn bottle(n: i32) -> String { match n { -1 => bottle(99), 0 => "No more bottles".to_string(), 1 => "1 bottle".to_string(), _ => format!("{} bottles", n) } } fn take_beer(n: i32) -> String { match n { 0 => "Go to the store and buy some more".to_string(), 1 => "Take it down and pass it around".to_string(), _ => "Take one down and pass it around".to_string() } } fn bottle_of_bear(n: i32) -> String { format!("{} of beer", bottle(n)) } fn bottle_of_bear_on_the_wall(n: i32) -> String { format!("{} on the wall", bottle_of_bear(n)) } <file_sep>/rust/largest-series-product/Cargo.toml [package] name = "largest-series-product" version = "1.1.0" <file_sep>/rust/two-bucket/src/lib.rs use std::collections::HashSet; use std::collections::VecDeque; use std::hash::{Hash, Hasher}; #[derive(PartialEq, Eq, Debug)] pub enum Bucket { One, Two, } /// A struct to hold your results in. #[derive(PartialEq, Eq, Debug)] pub struct BucketStats { /// The total number of "moves" it should take to reach the desired number of liters, including /// the first fill. pub moves: u8, /// Which bucket should end up with the desired number of liters? (Either "one" or "two") pub goal_bucket: Bucket, /// How many liters are left in the other bucket? pub other_bucket: u8, } /// Solve the bucket problem pub fn solve(capacity_1: u8, capacity_2: u8, goal: u8, start_bucket: &Bucket) -> BucketStats { let mut queue = VecDeque::new(); let mut checked = HashSet::new(); let (start, ignore) = match start_bucket { &Bucket::One => ((Buckets::new(capacity_1, 0)), Buckets::new(0, capacity_2)), &Bucket::Two => ((Buckets::new(0, capacity_2)), Buckets::new(capacity_1, 0)), }; queue.push_back(start); checked.insert(ignore); while let Some(buckets) = queue.pop_front() { if checked.contains(&buckets) { continue; } if let Some(stats) = buckets.check(goal) { return stats; } queue.push_back(buckets.move_to_one(capacity_1)); queue.push_back(buckets.move_to_two(capacity_2)); queue.push_back(buckets.fill_at_one(capacity_1)); queue.push_back(buckets.fill_at_two(capacity_2)); queue.push_back(buckets.empty_at_one()); queue.push_back(buckets.empty_at_two()); checked.insert(buckets); } return BucketStats { moves: 0, goal_bucket: Bucket::One, other_bucket: 0, }; } struct Buckets { bucket_1: u8, bucket_2: u8, moves: u8, } impl Buckets { fn new(bucket_1: u8, bucket_2: u8) -> Self { Buckets::new_with_moved(bucket_1, bucket_2, 1) } fn new_with_moved(bucket_1: u8, bucket_2: u8, moves: u8) -> Self { Buckets { bucket_1, bucket_2, moves, } } fn move_to_one(&self, capacity_1: u8) -> Self { let space_1 = (capacity_1 - self.bucket_1).min(self.bucket_2); Buckets::new_with_moved( self.bucket_1 + space_1, self.bucket_2 - space_1, self.moves + 1, ) } fn move_to_two(&self, capacity_2: u8) -> Self { Buckets::move_to_one(&self.swap(), capacity_2).swap() } fn fill_at_one(&self, capacity_1: u8) -> Self { Buckets::new_with_moved(self.bucket_1.max(capacity_1), self.bucket_2, self.moves + 1) } fn fill_at_two(&self, capacity_2: u8) -> Self { Buckets::new_with_moved(self.bucket_1, self.bucket_2.max(capacity_2), self.moves + 1) } fn empty_at_one(&self) -> Self { Buckets::new_with_moved(0, self.bucket_2, self.moves + 1) } fn empty_at_two(&self) -> Self { Buckets::empty_at_one(&self.swap()).swap() } fn swap(&self) -> Self { Buckets::new_with_moved(self.bucket_2, self.bucket_1, self.moves) } fn check(&self, goal: u8) -> Option<BucketStats> { match goal { _ if goal == self.bucket_1 => Some(BucketStats { moves: self.moves, goal_bucket: Bucket::One, other_bucket: self.bucket_2, }), _ if goal == self.bucket_2 => Some(BucketStats { moves: self.moves, goal_bucket: Bucket::Two, other_bucket: self.bucket_1, }), _ => None, } } } impl PartialEq for Buckets { fn eq(&self, other: &Buckets) -> bool { self.bucket_1 == other.bucket_1 && self.bucket_2 == other.bucket_2 } } impl Eq for Buckets {} impl Hash for Buckets { fn hash<H: Hasher>(&self, state: &mut H) { self.bucket_1.hash(state); self.bucket_2.hash(state); } } <file_sep>/rust/prime-factors/src/lib.rs pub fn factors(n: u64) -> Vec<u64> { let mut number = n; let mut factors = vec![]; let mut candidate = 2; while number > 1 { while number % candidate == 0 { factors.push(candidate); number /= candidate } candidate += 1 } factors } <file_sep>/go/error-handling/error_handling.go package erratum func Use(o ResourceOpener, input string) (err error) { var res Resource for { res, err = o() if err == nil { break } if _, ok := err.(TransientError); ok { continue } return } defer res.Close() defer func() { if rec := recover(); rec != nil { if frob, ok := rec.(FrobError); ok { res.Defrob(frob.defrobTag) } err = rec.(error) } }() res.Frob(input) return } <file_sep>/rust/bracket-push/src/lib.rs struct Bracket(char); impl Bracket { pub fn to_close(&self) -> Option<char> { match self.0 { '[' => Some(']'), '{' => Some('}'), '(' => Some(')'), _ => None, } } pub fn is_close(&self) -> bool { match self.0 { ']' | '}' | ')' => true, _ => false, } } } pub struct Brackets(Vec<Bracket>); impl From<&'static str> for Brackets { fn from(sentence: &str) -> Self { Brackets(sentence.chars().map(|c| Bracket(c)).collect()) } } impl Brackets { pub fn are_balanced(&self) -> bool { let mut stack = Vec::new(); for bracket in self.0.iter() { if let Some(close) = bracket.to_close() { stack.push(close); } else if bracket.is_close() { if Some(bracket.0) != stack.pop() { return false; } } } stack.is_empty() } } <file_sep>/go/matrix/matrix.go package matrix import ( "errors" "strconv" "strings" ) type Matrix struct { data [][]int rows, cols int } func (m Matrix) Rows() [][]int { dst := make([][]int, m.rows) for i := range dst { dst[i] = make([]int, m.cols) copy(dst[i], m.data[i]) } return dst } func (m Matrix) Cols() [][]int { rows := m.Rows() dst := make([][]int, m.cols) for i := 0; i < m.cols; i++ { dst[i] = make([]int, m.rows) for j := 0; j < m.rows; j++ { dst[i][j] = rows[j][i] } } return dst } func (m Matrix) Set(i, j, k int) bool { if i < 0 || m.rows <= i || j < 0 || m.cols <= j { return false } m.data[i][j] = k return true } func New(s string) (*Matrix, error) { m := new(Matrix) rows := strings.Split(s, "\n") m.rows = len(rows) m.data = make([][]int, m.rows) for i, row := range rows { cols := strings.Split(strings.TrimSpace(row), " ") if m.cols != 0 && m.cols != len(cols) { return nil, errors.New("invalid") } m.cols = len(cols) m.data[i] = make([]int, m.cols) for j, col := range cols { n, err := strconv.Atoi(col) if err != nil { return nil, err } m.data[i][j] = n } } return m, nil } <file_sep>/rust/scrabble-score/Cargo.toml [package] name = "scrabble-score" version = "1.1.0" [dependencies] lazy_static = "1.0" <file_sep>/rust/hello-world/GETTING_STARTED.md # Getting Started These exercises lean on Test-Driven Development (TDD), but they're not an exact match. The following steps assume that you are in the same directory as the exercise. You must have rust installed. Follow the [Installation chapter in the Rust book](https://doc.rust-lang.org/book/second-edition/ch01-01-installation.html). The [Rust language section](http://exercism.io/languages/rust) section from exercism is also useful. ## Step 1 Run the test suite. It can be run with `cargo`, which is installed with rust. ``` $ cargo test ``` This will compile the `hello-world` crate and run the test, which fails. ``` running 1 test test test_hello_world ... FAILED failures: ---- test_hello_world stdout ---- thread 'test_hello_world' panicked at 'assertion failed: `(left == right)` (left: `"Hello, World!"`, right: `"Goodbye, World!"`)', tests/hello-world.rs:5 failures: test_hello_world test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured ``` ### Understanding Test Failures The `test_hello_world` failure states that it is expecting the value, `"Hello, World!"`, to be returned from `hello()`. The left side of the assertion (at line 5) should be equal to the right side. ``` ---- test_hello_world stdout ---- thread 'test_hello_world' panicked at 'assertion failed: `(left == right)` (left: `"Hello, World!"`, right: `"Goodbye, World!"`)', tests/hello-world.rs:5 ``` ### Fixing the Error To fix it, open up `src/lib.rs` and change the `hello` function to return `"Hello, World!"` instead of `"Goodbye, World!"`. ```rust pub fn hello() -> &'static str { "Hello, World!" } ``` ## Step 2 Run the test again. This time, it will pass. ``` running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured Running target/debug/deps/hello_world-bd1f06dc726ef14f running 1 test test test_hello_world ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured Doc-tests hello-world running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured ``` ## Submit Once the test is passing, you can submit your code with the following command: ``` $ exercism submit src/lib.rs ``` <file_sep>/rust/pascals-triangle/Cargo.toml [package] name = "pascals-triangle" version = "1.3.0" <file_sep>/rust/tournament/src/lib.rs use std::collections::HashMap; struct Match<'a> { name: &'a str, won: u32, drawn: u32, lost: u32, } impl<'a> Match<'a> { fn new(name: &'a str) -> Self { Match { name, won: 0, drawn: 0, lost: 0, } } fn played(&self) -> u32 { self.won + self.drawn + self.lost } fn point(&self) -> u32 { self.won * 3 + self.drawn } fn output(&self) -> String { format!( "{:30} | {:2} | {:2} | {:2} | {:2} | {:2}", self.name, self.played(), self.won, self.drawn, self.lost, self.point() ) } } pub fn tally(input: &str) -> String { let mut map: HashMap<&str, Match> = HashMap::new(); for line in input.lines() { match &line.split(';').collect::<Vec<_>>()[..] { [a, b, "win"] | [b, a, "loss"] => { map.entry(a).or_insert_with(|| Match::new(a)).won += 1; map.entry(b).or_insert_with(|| Match::new(b)).lost += 1; } [a, b, "draw"] => { map.entry(a).or_insert_with(|| Match::new(a)).drawn += 1; map.entry(b).or_insert_with(|| Match::new(b)).drawn += 1; } _ => continue, } } let mut output = String::from( format!("{:30} | {:>2} | {:>2} | {:>2} | {:>2} | {:>2}", "Team", "MP", "W", "D", "L", "P") ); let mut values = map.values().collect::<Vec<_>>(); values.sort_by(|a, b| b.point().cmp(&a.point()).then(a.name.cmp(&b.name))); for value in values { output.push_str("\n"); output.push_str(&value.output()); } output } <file_sep>/go/raindrops/raindrops.go package raindrops import "strconv" // Convert Number to Pling Plang Plong or Number func Convert(i int) string { var res string if i%3 == 0 { res += "Pling" } if i%5 == 0 { res += "Plang" } if i%7 == 0 { res += "Plong" } if res == "" { res += strconv.Itoa(i) } return res } <file_sep>/rust/minesweeper/src/lib.rs use std::collections::HashMap; pub fn annotate(minefield: &[&str]) -> Vec<String> { let mut cells = HashMap::new(); let mut history = vec![]; let h = minefield.len(); for (i, line) in minefield.iter().enumerate() { let w = line.len(); let mut coordinates = vec![]; for (j, c) in line.chars().enumerate() { let point = Point { i, j, h, w }; coordinates.push(point.coordinate()); let cell = cells .entry(point.coordinate()) .or_insert_with(Cell::default); cell.configure(c); if !cell.has_mine { continue; } point.neighbor().iter().for_each(|n_point| { cells .entry(n_point.coordinate()) .or_insert_with(Cell::default) .increment() }); } history.push(coordinates); } history .iter() .map(|rows| { rows.iter() .map(|point| cells.get(&point).unwrap().to_string()) .collect::<String>() }) .collect::<Vec<_>>() } #[derive(Default)] struct Cell { count: u8, has_mine: bool, } impl Cell { fn configure(&mut self, field: char) { self.has_mine = field == '*'; } fn increment(&mut self) { self.count += 1; } fn to_string(&self) -> String { if self.has_mine { return String::from("*"); } if self.count == 0 { return String::from(" "); } format!("{}", self.count) } } struct Point { i: usize, j: usize, w: usize, h: usize, } impl Point { fn coordinate(&self) -> (usize, usize) { (self.i, self.j) } fn neighbor(&self) -> Vec<Point> { let mut points = vec![]; let left = 0 < self.j; let right = self.j < self.w - 1; let top = 0 < self.i; let bottom = self.i < self.h - 1; if left && top { points.push(Point { i: self.i - 1, j: self.j - 1, w: self.w, h: self.h, }); } if top { points.push(Point { i: self.i - 1, j: self.j, w: self.w, h: self.h, }); } if top && right { points.push(Point { i: self.i - 1, j: self.j + 1, w: self.w, h: self.h, }); } if left { points.push(Point { i: self.i, j: self.j - 1, w: self.w, h: self.h, }); } if right { points.push(Point { i: self.i, j: self.j + 1, w: self.w, h: self.h, }); } if left && bottom { points.push(Point { i: self.i + 1, j: self.j - 1, w: self.w, h: self.h, }); } if bottom { points.push(Point { i: self.i + 1, j: self.j, w: self.w, h: self.h, }); } if bottom && right { points.push(Point { i: self.i + 1, j: self.j + 1, w: self.w, h: self.h, }); } points } } <file_sep>/elixir/sublist/README.md # Sublist Given two lists determine if the first list is contained within the second list, if the second list is contained within the first list, if both lists are contained within each other or if none of these are true. Specifically, a list A is a sublist of list B if by dropping 0 or more elements from the front of B and 0 or more elements from the back of B you get a list that's completely equal to A. Examples: * A = [1, 2, 3], B = [1, 2, 3, 4, 5], A is a sublist of B * A = [3, 4, 5], B = [1, 2, 3, 4, 5], A is a sublist of B * A = [3, 4], B = [1, 2, 3, 4, 5], A is a sublist of B * A = [1, 2, 3], B = [1, 2, 3], A is equal to B * A = [1, 2, 3, 4, 5], B = [2, 3, 4], A is a superlist of B * A = [1, 2, 4], B = [1, 2, 3, 4, 5], A is not a superlist of, sublist of or equal to B ## Running tests Execute the tests with: ```bash $ elixir bob_test.exs ``` (Replace `bob_test.exs` with the name of the test file.) ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/custom-set/src/lib.rs use std::fmt::Debug; #[derive(Debug, PartialEq)] pub struct CustomSet<T> { items: Vec<T>, } impl<T: Debug + Clone + PartialEq + Ord> CustomSet<T> { pub fn new(input: &[T]) -> Self { let mut items = input.to_vec(); items.sort(); items.dedup(); CustomSet { items } } pub fn contains(&self, element: &T) -> bool { self.items.as_slice().contains(element) } pub fn add(&mut self, element: T) { if self.contains(&element) { return; } self.items.push(element); self.items.sort() } pub fn is_subset(&self, other: &Self) -> bool { let other_slice = other.items.as_slice(); self.items.iter().all(|item| other_slice.contains(item)) } pub fn is_empty(&self) -> bool { self.items.is_empty() } pub fn is_disjoint(&self, other: &Self) -> bool { let other_slice = other.items.as_slice(); !self.items.iter().any(|item| other_slice.contains(item)) } pub fn intersection(&self, other: &Self) -> Self { let other_slice = other.items.as_slice(); let items = self.items.iter() .cloned() .filter(|item| other_slice.contains(&item)) .collect::<Vec<_>>(); Self::new(&items) } pub fn difference(&self, other: &Self) -> Self { let other_slice = other.items.as_slice(); let items = self.items.iter() .cloned() .filter(|item| !other_slice.contains(&item)) .collect::<Vec<_>>(); Self::new(&items) } pub fn union(&self, other: &Self) -> Self { let items = self.items.iter() .chain(other.items.iter()) .cloned() .collect::<Vec<_>>(); Self::new(&items) } } <file_sep>/rust/pythagorean-triplet/src/lib.rs pub fn find() -> Option<u32> { const N : u32 = 1000; for a in 1..N { for b in a..N-a { let c = N - a - b; if (a*a + b*b == c*c) { return Some(a * b * c) } } } return None } <file_sep>/rust/say/Cargo.toml [package] name = "say" version = "1.1.0" authors = ["sacherjj <<EMAIL>>"] <file_sep>/rust/perfect-numbers/src/lib.rs use std::cmp::Ordering; #[derive(Debug, PartialEq, Eq)] pub enum Classification { Abundant, Perfect, Deficient } pub fn classify(num: u64) -> Option<Classification> { if num <= 0 { return None; } match num.cmp(&factor_sum(num)) { Ordering::Less => Classification::Abundant, Ordering::Greater => Classification::Deficient, Ordering::Equal => Classification::Perfect, }.into() } fn factor_sum(num: u64) -> u64 { (1..num/2+1) .filter(|&i| num % i == 0) .sum() } <file_sep>/rust/sublist/src/lib.rs #[derive(Debug, PartialEq)] pub enum Comparison { Equal, Sublist, Superlist, Unequal } pub fn sublist<T: PartialEq>(a: &[T], b: &[T]) -> Comparison { if a == b { return Comparison::Equal } if is_sublist(a, b) { return Comparison::Sublist; } if is_sublist(b, a) { return Comparison::Superlist; } Comparison::Unequal } fn is_sublist<T: PartialEq>(a: &[T], b: &[T]) -> bool { if a.is_empty() { return true; } if b.is_empty() { return false; } for n in 0..a.len() { if b.get(n .. n + a.len()).map_or(false, |c| a == c) { return true; } } false } <file_sep>/go/difference-of-squares/diffsquares.go package diffsquares // SquareOfSums (1 + ... + n)² func SquareOfSums(n int) int { s := (n * (1 + n)) / 2 return s * s } // SumOfSquares (1² + ... + n²) func SumOfSquares(n int) int { return (n * (n + 1) * (2*n + 1)) / 6 } // Difference SquareOfSums - SumOfSquares func Difference(n int) int { return SquareOfSums(n) - SumOfSquares(n) } <file_sep>/rust/isogram/Cargo.toml [package] name = "isogram" version = "1.3.0" <file_sep>/rust/scrabble-score/README.md # Scrabble Score Given a word, compute the scrabble score for that word. ## Letter Values You'll need these: ```text Letter Value A, E, I, O, U, L, N, R, S, T 1 D, G 2 B, C, M, P 3 F, H, V, W, Y 4 K 5 J, X 8 Q, Z 10 ``` ## Examples "cabbage" should be scored as worth 14 points: - 3 points for C - 1 point for A, twice - 3 points for B, twice - 2 points for G - 1 point for E And to total: - `3 + 2*1 + 2*3 + 2 + 1` - = `3 + 2 + 6 + 3` - = `5 + 9` - = 14 ## Extensions - You can play a double or a triple letter. - You can play a double or a triple word. ## Rust Installation Refer to the [exercism help page][help-page] for Rust installation and learning resources. ## Writing the Code Execute the tests with: ```bash $ cargo test ``` All but the first test have been ignored. After you get the first test to pass, remove the ignore flag (`#[ignore]`) from the next test and get the tests to pass again. The test file is located in the `tests` directory. You can also remove the ignore flag from all the tests to get them to run all at once if you wish. Make sure to read the [Modules](https://doc.rust-lang.org/book/second-edition/ch07-00-modules.html) chapter if you haven't already, it will help you with organizing your files. ## Feedback, Issues, Pull Requests The [exercism/rust](https://github.com/exercism/rust) repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help! If you want to know more about Exercism, take a look at the [contribution guide](https://github.com/exercism/docs/blob/master/contributing-to-language-tracks/README.md). [help-page]: http://exercism.io/languages/rust [modules]: https://doc.rust-lang.org/book/second-edition/ch07-00-modules.html [cargo]: https://doc.rust-lang.org/book/second-edition/ch14-00-more-about-cargo.html ## Source Inspired by the Extreme Startup game [https://github.com/rchatley/extreme_startup](https://github.com/rchatley/extreme_startup) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/go/acronym/acronym.go package acronym import ( "regexp" "strings" ) // Abbreviate split space and hyphen func Abbreviate(s string) string { var a string for _, w := range regexp.MustCompile("\\s|\\-").Split(s, 5) { a = a + strings.ToUpper(string([]rune(w)[0])) } return a } <file_sep>/rust/rna-transcription/Cargo.toml [package] name = "rna-transcription" version = "1.0.0" <file_sep>/go/luhn/luhn.go package luhn import ( "strconv" "strings" ) // Valid check at luhn algorithm func Valid(input string) bool { r := []rune(strings.Trim(input, " ")) if len(r) <= 1 { return false } total := 0 for i, alt := len(r)-1, false; i >= 0; i-- { s := string(r[i]) if n, err := strconv.Atoi(s); err == nil { if alt { n *= 2 if n > 9 { n -= 9 } } total += n alt = !alt } else if s != " " { return false } } return total%10 == 0 } <file_sep>/rust/leap/Cargo.toml [package] name = "leap" version = "1.0.0" <file_sep>/rust/allergies/Cargo.toml [package] name = "allergies" version = "1.1.0" [dependencies] bitflags = "1.0" <file_sep>/rust/twofer/Cargo.toml [package] name = "twofer" version = "1.2.0" [dependencies] <file_sep>/rust/allergies/src/lib.rs #[macro_use] extern crate bitflags; bitflags! { pub struct Allergen: u32 { const Eggs = 0b00000001; const Peanuts = 0b00000010; const Shellfish = 0b00000100; const Strawberries = 0b00001000; const Tomatoes = 0b00010000; const Chocolate = 0b00100000; const Pollen = 0b01000000; const Cats = 0b10000000; } } impl Allergen { fn values() -> Vec<Allergen> { vec![ Allergen::Eggs, Allergen::Peanuts, Allergen::Shellfish, Allergen::Strawberries, Allergen::Tomatoes, Allergen::Chocolate, Allergen::Pollen, Allergen::Cats, ] } } pub struct Allergies { score: Allergen, } impl Allergies { pub fn new(score: u32) -> Self { Allergies { score: Allergen::from_bits_truncate(score), } } pub fn is_allergic_to(&self, allergen: &Allergen) -> bool { self.score.contains(*allergen) } pub fn allergies(&self) -> Vec<Allergen> { Allergen::values() .into_iter() .filter(|allergen| self.is_allergic_to(&allergen)) .collect::<Vec<_>>() } } <file_sep>/ecmascript/simple-cipher/simple-cipher.js class Cipher { constructor(key) { this.KEY_SET = '<KEY>'; this.constructor.validate(key, this.KEY_SET); this.key = key || this.constructor.generateKey(100, this.KEY_SET); this.offsets = this.constructor.offsets(this.key, this.KEY_SET); } static validate(key, keyset) { if (key === undefined) return; if ((key.length === 0) || (Array.from(key).some(k => !keyset.includes(k)))) { throw new Error('Bad key'); } } static generateKey(length, keyset) { const randomString = () => keyset.charAt(Math.floor(Math.random() * keyset.length)); return [...Array(length)].map(randomString, this).join(''); } static offsets(key, keyset) { return Array.from(key).map(k => keyset.indexOf(k)); } static codepoints(text) { return Array.from(text).map(word => word.charCodeAt(0)); } static cipher(code, base, offset) { return String.fromCharCode(base + (((code - base) + offset) % 26)); } encode(text) { return this.constructor.codepoints(text) .map((code, index) => this.constructor.cipher(code, 97, this.getShift(index)), this) .join(''); } decode(text) { return this.constructor.codepoints(text) .map((code, index) => this.constructor.cipher(code, 97, this.getUnshift(index)), this) .join(''); } getShift(index) { return this.offsets[index % this.offsets.length]; } getUnshift(index) { return 26 - (this.getShift(index) % 26); } } export default Cipher; <file_sep>/go/sublist/sublist.go package sublist type Relation string const ( IsEqual Relation = "equal" IsSublist Relation = "sublist" IsSuperlist Relation = "superlist" IsUnequal Relation = "unequal" ) func Sublist(listOne, listTwo []int) Relation { lenOne, lenTwo := len(listOne), len(listTwo) if (lenOne == lenTwo) && compare(listOne, listTwo) { return IsEqual } if (lenOne < lenTwo) && isSublist(listOne, listTwo, lenOne, lenTwo) { return IsSublist } if (lenOne > lenTwo) && isSublist(listTwo, listOne, lenTwo, lenOne) { return IsSuperlist } return IsUnequal } func isSublist(listOne, listTwo []int, lenOne, lenTwo int) bool { for i := 0; i <= (lenTwo - lenOne); i++ { if compare(listOne, listTwo[i:i+lenOne]) { return true } } return false } func compare(a, b []int) bool { b = b[:len(a)] for i, v := range a { if v != b[i] { return false } } return true } <file_sep>/rust/raindrops/src/lib.rs pub fn raindrops(n: usize) -> String { let rem3 = n % 3 == 0; let rem5 = n % 5 == 0; let rem7 = n % 7 == 0; if !(rem3 || rem5 || rem7) { return n.to_string() } let mut s = String::new(); if rem3 { s.push_str("Pling") } if rem5 { s.push_str("Plang") } if rem7 { s.push_str("Plong") } s } <file_sep>/elixir/list-ops/README.md # List Ops Implement basic list operations. In functional languages list operations like `length`, `map`, and `reduce` are very common. Implement a series of basic list operations, without using existing functions. ## Running tests Execute the tests with: ```bash $ elixir list_ops_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/reverse-string/Cargo.toml [package] name = "reverse_string" version = "1.0.0" authors = ["<NAME> <<EMAIL>>"] [dependencies] unicode-segmentation = "1.1.0" <file_sep>/typescript/binary-search/binary-search.ts export default class BinarySearch<T> { static readonly NOT_FOUND: number = -1 readonly array: T[] constructor(array: T[]) { if (!this.validate(array)) return this.array = array } indexOf(key: T): number { return this.bsearch(this.array, key, 0, this.array.length - 1) } private validate(array: T[]): boolean { for (let i = 0, l = array.length - 1; i < l; i++) { if (array[i] > array[i + 1]) { return false } } return true } private bsearch(array: T[], key: T, min: number, max: number): number { if (max < min) { return BinarySearch.NOT_FOUND } const mid = Math.floor((max + min) / 2) if (array[mid] > key) { return this.bsearch(array, key, min, mid - 1) } else if (array[mid] < key) { return this.bsearch(array, key, mid + 1, max) } else { return mid } } } <file_sep>/elixir/meetup/README.md # Meetup Calculate the date of meetups. Typically meetups happen on the same day of the week. In this exercise, you will take a description of a meetup date, and return the actual meetup date. Examples of general descriptions are: - The first Monday of January 2017 - The third Tuesday of January 2017 - The wednesteenth of January 2017 - The last Thursday of January 2017 The descriptors you are expected to parse are: first, second, third, fourth, fifth, last, monteenth, tuesteenth, wednesteenth, thursteenth, friteenth, saturteenth, sunteenth Note that "monteenth", "tuesteenth", etc are all made up words. There was a meetup whose members realized that there are exactly 7 numbered days in a month that end in '-teenth'. Therefore, one is guaranteed that each day of the week (Monday, Tuesday, ...) will have exactly one date that is named with '-teenth' in every month. Given examples of a meetup dates, each containing a month, day, year, and descriptor calculate the date of the actual meetup. For example, if given "The first Monday of January 2017", the correct meetup date is 2017/1/2. ## Running tests Execute the tests with: ```bash $ elixir meetup_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source <NAME> mentioned a Boulder meetup that happens on the Wednesteenth of every month [https://twitter.com/copiousfreetime](https://twitter.com/copiousfreetime) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/elixir/binary-search-tree/README.md # Binary Search Tree Insert and search for numbers in a binary tree. When we need to represent sorted data, an array does not make a good data structure. Say we have the array `[1, 3, 4, 5]`, and we add 2 to it so it becomes `[1, 3, 4, 5, 2]` now we must sort the entire array again! We can improve on this by realizing that we only need to make space for the new item `[1, nil, 3, 4, 5]`, and then adding the item in the space we added. But this still requires us to shift many elements down by one. Binary Search Trees, however, can operate on sorted data much more efficiently. A binary search tree consists of a series of connected nodes. Each node contains a piece of data (e.g. the number 3), a variable named `left`, and a variable named `right`. The `left` and `right` variables point at `nil`, or other nodes. Since these other nodes in turn have other nodes beneath them, we say that the left and right variables are pointing at subtrees. All data in the left subtree is less than or equal to the current node's data, and all data in the right subtree is greater than the current node's data. For example, if we had a node containing the data 4, and we added the data 2, our tree would look like this: 4 / 2 If we then added 6, it would look like this: 4 / \ 2 6 If we then added 3, it would look like this 4 / \ 2 6 \ 3 And if we then added 1, 5, and 7, it would look like this 4 / \ / \ 2 6 / \ / \ 1 3 5 7 ## Running tests Execute the tests with: ```bash $ elixir binary_search_tree_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source <NAME> [https://twitter.com/josh_cheek](https://twitter.com/josh_cheek) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/elixir/series/README.md # Series Given a string of digits, output all the contiguous substrings of length `n` in that string. For example, the string "49142" has the following 3-digit series: - 491 - 914 - 142 And the following 4-digit series: - 4914 - 9142 And if you ask for a 6-digit series from a 5-digit string, you deserve whatever you get. Note that these series are only required to occupy *adjacent positions* in the input; the digits need not be *numerically consecutive*. ## Running tests Execute the tests with: ```bash $ elixir bob_test.exs ``` (Replace `bob_test.exs` with the name of the test file.) ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source A subset of the Problem 8 at Project Euler [http://projecteuler.net/problem=8](http://projecteuler.net/problem=8) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/isogram/src/lib.rs use std::collections::HashSet; const WITHOUT : [char; 2] = ['-', ' ']; pub fn check(sentence : &str) -> bool { let chars = sentence.to_lowercase().chars().filter(|c| !WITHOUT.contains(c)).collect::<Vec<_>>(); chars.len() == chars.into_iter().collect::<HashSet<_>>().len() } <file_sep>/rust/isbn-verifier/Cargo.toml [package] name = "isbn-verifier" version = "1.1.0" <file_sep>/rust/protein-translation/src/lib.rs pub struct CodonsInfo<'a> { pairs: Vec<(&'a str, &'a str)>, } impl<'a> CodonsInfo<'a> { pub fn name_for(&self, codon: &str) -> Option<&'a str> { self.pairs .iter() .find(|(p_codon, _)| p_codon == &codon) .map(|&(_, p_name)| p_name) } pub fn of_rna(&self, rna: &str) -> Option<Vec<&'a str>> { rna.chars() .collect::<Vec<_>>() .chunks_exact(3) .map(|chunk| chunk.iter().collect::<String>()) .map(|codon| self.name_for(&codon)) .take_while(|name| name.map_or(false, |name| name != "stop codon")) .into_iter() .collect::<Option<Vec<_>>>() .filter(|x| !x.is_empty()) } } pub fn parse<'a>(pairs: Vec<(&'a str, &'a str)>) -> CodonsInfo<'a> { CodonsInfo { pairs } } <file_sep>/rust/saddle-points/src/lib.rs pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> { let mut result = vec![]; for (row, n1) in max(&input) { for (col, n2) in min(&transpose(&input)) { if n1 == n2 { result.push((row, col)) } } } result } fn transpose(input: &[Vec<u64>]) -> Vec<Vec<u64>> { let mut result = vec![]; let n = input.len(); let m = input[0].len(); for j in 0..m { let mut item = vec![]; for i in 0..n { item.push(input[i][j]); } result.push(item); } result } fn max(input: &[Vec<u64>]) -> Vec<(usize, &u64)> { input .iter() .enumerate() .filter(|&(_, t)| t.len() != 0) .map(|(i, t)| (i, t.iter().max().unwrap())) .collect::<Vec<(_, _)>>() } fn min(input: &[Vec<u64>]) -> Vec<(usize, &u64)> { input .iter() .enumerate() .filter(|&(_, t)| t.len() != 0) .map(|(i, t)| (i, t.iter().min().unwrap())) .collect::<Vec<(_, _)>>() } <file_sep>/go/matrix/README.md # Matrix Given a string representing a matrix of numbers, return the rows and columns of that matrix. So given a string with embedded newlines like: > 9 8 7 > 5 3 2 > 6 6 7 representing this matrix: ```plain 0 1 2 |--------- 0 | 9 8 7 1 | 5 3 2 2 | 6 6 7 ``` your code should be able to spit out: - A list of the rows, reading each row left-to-right while moving top-to-bottom across the rows, - A list of the columns, reading each column top-to-bottom while moving from left-to-right. The rows for our example matrix: - 9, 8, 7 - 5, 3, 2 - 6, 6, 7 And its columns: - 9, 5, 6 - 8, 3, 6 - 7, 2, 7 ## Running the tests To run the tests run the command `go test` from within the exercise directory. If the test suite contains benchmarks, you can run these with the `-bench` flag: go test -bench . Keep in mind that each reviewer will run benchmarks on a different machine, with different specs, so the results from these benchmark tests may vary. ## Further information For more detailed information about the Go track, including how to get help if you're having trouble, please visit the exercism.io [Go language page](http://exercism.io/languages/go/about). ## Source Warmup to the `saddle-points` warmup. [http://jumpstartlab.com](http://jumpstartlab.com) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/rna-transcription/src/lib.rs #[derive(Copy, Clone, Debug, PartialEq)] pub enum Nucleotide { G, C, T, A, U, Error } impl From<char> for Nucleotide { fn from(c: char) -> Self { match c.to_ascii_uppercase() { 'A' => Nucleotide::A, 'C' => Nucleotide::C, 'G' => Nucleotide::G, 'T' => Nucleotide::T, 'U' => Nucleotide::U, _ => Nucleotide::Error, } } } impl Nucleotide { fn is_dna(self) -> Option<Self> { match self { Nucleotide::A | Nucleotide::C | Nucleotide::G | Nucleotide::T => Some(self), _ => None } } fn is_rna(self) -> Option<Self> { match self { Nucleotide::A | Nucleotide::C | Nucleotide::G | Nucleotide::U => Some(self), _ => None } } fn to_rna(self) -> Option<Self> { match self { Nucleotide::A => Some(Nucleotide::U), Nucleotide::C => Some(Nucleotide::G), Nucleotide::G => Some(Nucleotide::C), Nucleotide::T => Some(Nucleotide::A), _ => None } } } #[derive(Debug)] pub struct DNA { pub nucleotides: Vec<Nucleotide> } #[derive(Debug)] pub struct RNA { pub nucleotides: Vec<Nucleotide> } impl DNA { pub fn new(rna: &str) -> Result<Self, ()> { Self::parse(rna) .map(|nucleotides| Self::create(nucleotides) ) .ok_or(()) } fn parse(nucleotides: &str) -> Option<Vec<Nucleotide>> { nucleotides.chars() .map(|c| Nucleotide::from(c) ) .map(|c| Self::verify(c) ) .collect::<Option<Vec<_>>>() } fn verify(n: Nucleotide) -> Option<Nucleotide> { n.is_dna() } fn create(nucleotides: Vec<Nucleotide>) -> Self { DNA { nucleotides: nucleotides } } } impl RNA { pub fn new(rna: &str) -> Result<Self, ()> { Self::parse(rna) .map(|nucleotides| Self::create(nucleotides) ) .ok_or(()) } fn parse(nucleotides: &str) -> Option<Vec<Nucleotide>> { nucleotides.chars() .map(|c| Nucleotide::from(c) ) .map(|c| Self::verify(c) ) .collect::<Option<Vec<_>>>() } fn verify(n: Nucleotide) -> Option<Nucleotide> { n.is_rna() } fn create(nucleotides: Vec<Nucleotide>) -> Self { RNA { nucleotides: nucleotides } } } impl PartialEq for DNA { fn eq(&self, other: &Self) -> bool { self.nucleotides == other.nucleotides } } impl PartialEq for RNA { fn eq(&self, other: &Self) -> bool { self.nucleotides == other.nucleotides } } impl DNA { pub fn to_rna(&self) -> RNA { self.nucleotides .iter() .map(|n| n.to_rna() ) .collect::<Option<Vec<_>>>() .map(|nucleotides| RNA { nucleotides: nucleotides } ) .unwrap() } } <file_sep>/elixir/markdown/README.md # Markdown Refactor a Markdown parser. The markdown exercise is a refactoring exercise. There is code that parses a given string with [Markdown syntax](https://guides.github.com/features/mastering-markdown/) and returns the associated HTML for that string. Even though this code is confusingly written and hard to follow, somehow it works and all the tests are passing! Your challenge is to re-write this code to make it easier to read and maintain while still making sure that all the tests keep passing. It would be helpful if you made notes of what you did in your refactoring in comments so reviewers can see that, but it isn't strictly necessary. The most important thing is to make the code better! ## Running tests Execute the tests with: ```bash $ elixir markdown_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/sieve/README.md # Sieve Use the Sieve of Eratosthenes to find all the primes from 2 up to a given number. The Sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2. It does not use any division or remainder operation. Create your range, starting at two and continuing up to and including the given limit. (i.e. [2, limit]) The algorithm consists of repeating the following over and over: - take the next available unmarked number in your list (it is prime) - mark all the multiples of that number (they are not prime) Repeat until you have processed each number in your range. When the algorithm terminates, all the numbers in the list that have not been marked are prime. The wikipedia article has a useful graphic that explains the algorithm: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Notice that this is a very specific algorithm, and the tests don't check that you've implemented the algorithm, only that you've come up with the correct list of primes. A good first test is to check that you do not use division or remainder operations (div, /, mod or % depending on the language). ## Rust Installation Refer to the [exercism help page][help-page] for Rust installation and learning resources. ## Writing the Code Execute the tests with: ```bash $ cargo test ``` All but the first test have been ignored. After you get the first test to pass, open the tests source file wich is located in the `tests` directory and remove the `#[ignore]` flag from the next test and get the tests to pass again. Each separate test is a function with `#[test]` flag above it. Continue, until you pass every test. If you wish to run all tests without editing the tests source file, use: ```bash $ cargo test -- --ignored ``` To run a specific test, for example `some_test`, you can use: ```bash $ cargo test some_test ``` If the specfic test is ignored use: ```bash $ cargo test some_test -- --ignored ``` To learn more about Rust tests refer to the [online test documentation][rust-tests] Make sure to read the [Modules](https://doc.rust-lang.org/book/second-edition/ch07-00-modules.html) chapter if you haven't already, it will help you with organizing your files. ## Feedback, Issues, Pull Requests The [exercism/rust](https://github.com/exercism/rust) repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help! If you want to know more about Exercism, take a look at the [contribution guide](https://github.com/exercism/docs/blob/master/contributing-to-language-tracks/README.md). [help-page]: http://exercism.io/languages/rust [modules]: https://doc.rust-lang.org/book/second-edition/ch07-00-modules.html [cargo]: https://doc.rust-lang.org/book/second-edition/ch14-00-more-about-cargo.html [rust-tests]: https://doc.rust-lang.org/book/second-edition/ch11-02-running-tests.html ## Source Sieve of Eratosthenes at Wikipedia [http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/go/bob/bob.go package bob import ( "regexp" "strings" ) func say(s string) bool { return len(s) == 0 } func yell(s string) bool { re := regexp.MustCompile("[A-Za-z]+") ws := re.FindAllString(s, -1) y := len(ws) != 0 for _, w := range ws { y = y && strings.ToUpper(w) == w } return y } func ask(s string) bool { return strings.HasSuffix(s, "?") } // Hey bob func Hey(remark string) string { remark = strings.TrimSpace(remark) switch { case say(remark): return "Fine. Be that way!" case yell(remark): return "Whoa, chill out!" case ask(remark): return "Sure." default: return "Whatever." } } <file_sep>/rust/twofer/tests/two-fer.rs extern crate twofer; use twofer::twofer; #[test] fn empty_string() { assert_eq!(twofer(""), "One for you, one for me."); } #[test] #[ignore] fn alice() { assert_eq!(twofer("Alice"), "One for Alice, one for me."); } #[test] #[ignore] fn bob() { assert_eq!(twofer("Bob"), "One for Bob, one for me."); }<file_sep>/rust/acronym/Cargo.toml [package] name = "acronym" version = "1.0.0" [dependencies] <file_sep>/rust/grains/Cargo.toml [package] name = "grains" version = "1.1.0" <file_sep>/go/parallel-letter-frequency/frequency.go package letter type FreqMap map[rune]int func Frequency(s string) FreqMap { m := FreqMap{} for _, r := range s { m[r]++ } return m } func frequencies(ss []string) <-chan FreqMap { out := make(chan FreqMap, len(ss)) go func() { defer close(out) for _, s := range ss { out <- Frequency(s) } }() return out } func sum(in <-chan FreqMap) <-chan FreqMap { out := make(chan FreqMap, 1) go func() { defer close(out) res := FreqMap{} for f := range in { for k, v := range f { res[k] += v } } out <- res }() return out } func ConcurrentFrequency(ss []string) FreqMap { return <-sum(frequencies(ss)) } <file_sep>/rust/variable-length-quantity/src/lib.rs #[derive(Debug, PartialEq)] pub enum Error { IncompleteNumber, Overflow, } /// Convert a list of numbers to a stream of bytes encoded with variable length encoding. pub fn to_bytes(values: &[u32]) -> Vec<u8> { let mut res = vec![]; for value in values { res.append(&mut to_byte(value)); } res } fn to_byte(value: &u32) -> Vec<u8> { let mut res = vec![]; res.push((value & 0x7F) as u8); let mut val: u32 = value >> 7; while val > 0 { res.push((0x80 + (val & 0x7f)) as u8); val >>= 7 } res.reverse(); res } /// Given a stream of bytes, extract all numbers which are encoded in there. pub fn from_bytes(bytes: &[u8]) -> Result<Vec<u32>, Error> { let mut res = vec![]; let mut value = 0u32; for byte in bytes { value = value << 7 | (byte & 0x7F) as u32; if byte < &0x80 { res.push(value); value = 0u32; } if value > u32::max_value() >> 7 { return Err(Error::Overflow); } } if res.is_empty() { return Err(Error::IncompleteNumber); } Ok(res) } <file_sep>/elixir/wordy/README.md # Wordy Parse and evaluate simple math word problems returning the answer as an integer. ## Iteration 1 — Addition Add two numbers together. > What is 5 plus 13? Evaluates to 18. Handle large numbers and negative numbers. ## Iteration 2 — Subtraction, Multiplication and Division Now, perform the other three operations. > What is 7 minus 5? 2 > What is 6 multiplied by 4? 24 > What is 25 divided by 5? 5 ## Iteration 3 — Multiple Operations Handle a set of operations, in sequence. Since these are verbal word problems, evaluate the expression from left-to-right, _ignoring the typical order of operations._ > What is 5 plus 13 plus 6? 24 > What is 3 plus 2 multiplied by 3? 15 (i.e. not 9) ## Bonus — Exponentials If you'd like, handle exponentials. > What is 2 raised to the 5th power? 32 ## Running tests Execute the tests with: ```bash $ elixir wordy_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source Inspired by one of the generated questions in the Extreme Startup game. [https://github.com/rchatley/extreme_startup](https://github.com/rchatley/extreme_startup) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/go/hamming/hamming.go package hamming import ( "fmt" ) // Distance : Hammint distance func Distance(a, b string) (int, error) { if len(a) != len(b) { return -1, fmt.Errorf("invalid strings len(a) == %d, len(b) == %d", len(a), len(b)) } if a == b { return 0, nil } var res int var rb = []rune(b) for i, ar := range a { if rb[i] != ar { res++ } } return res, nil } <file_sep>/go/gigasecond/gigasecond.go package gigasecond import "time" // AddGigasecond Add 10^9 (1,000,000,000) seconds func AddGigasecond(t time.Time) time.Time { a := t.Add(1000000000 * time.Second) return a } <file_sep>/ecmascript/rna-transcription/rna-transcription.js class Transcriptor { constructor() { this.COMPLEMENT_TABLE = { G: 'C', C: 'G', T: 'A', A: 'U', }; } toRna(dna) { return Array.from(dna).map(this.lookup, this).join(''); } lookup(dna) { const transcribed = this.COMPLEMENT_TABLE[dna]; if (!transcribed) { throw new Error('Invalid input DNA.'); } return transcribed; } } export default Transcriptor; <file_sep>/rust/acronym/src/lib.rs pub fn abbreviate(text: &str) -> String { text.chars() .scan(' ', |prev, word| { let ret; if !prev.is_ascii_alphabetic() && word.is_ascii_alphabetic() || prev.is_lowercase() && word.is_uppercase() { ret = Some(Some(word.to_ascii_uppercase())); } else { ret = Some(None); } *prev = word; ret }) .flat_map(|o| o) .collect() } <file_sep>/go/flatten-array/flatten.go package flatten func Flatten(i interface{}) interface{} { list := i.([]interface{}) idx := 0 ilen := len(list) result := make([]interface{}, 0) for idx < ilen { if _, ok := list[idx].([]interface{}); ok { value := Flatten(list[idx]).([]interface{}) j := 0 jlen := len(value) for j < jlen { if value[j] != nil { result = append(result, value[j]) } j += 1 } } else { if list[idx] != nil { result = append(result, list[idx]) } } idx += 1 } return result } <file_sep>/elixir/change/README.md # Change Correctly determine the fewest number of coins to be given to a customer such that the sum of the coins' value would equal the correct amount of change. ## For example - An input of 15 with [1, 5, 10, 25, 100] should return one nickel (5) and one dime (10) or [0, 1, 1, 0, 0] - An input of 40 with [1, 5, 10, 25, 100] should return one nickel (5) and one dime (10) and one quarter (25) or [0, 1, 1, 1, 0] ## Edge cases - Does your algorithm work for any given set of coins? - Can you ask for negative change? - Can you ask for a change value smaller than the smallest coin value? ## Running tests Execute the tests with: ```bash $ elixir change_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source Software Craftsmanship - Coin Change Kata [https://web.archive.org/web/20130115115225/http://craftsmanship.sv.cmu.edu:80/exercises/coin-change-kata](https://web.archive.org/web/20130115115225/http://craftsmanship.sv.cmu.edu:80/exercises/coin-change-kata) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/go/scrabble-score/scrabble.go package scrabble import "strings" type scrabble struct { letterScore map[string]int } func (s *scrabble) register(lv letterValue) { for _, l := range strings.Split(lv.letter, ", ") { s.letterScore[strings.ToLower(l)] = lv.value } } func (s *scrabble) score(letter string) int { return s.letterScore[strings.ToLower(letter)] } type letterValue struct { letter string value int } // Score scrabble score func Score(words string) int { s := &scrabble{make(map[string]int)} letterValues := []letterValue{ {"A, E, I, O, U, L, N, R, S, T", 1}, {"D, G", 2}, {"B, C, M, P", 3}, {"F, H, V, W, Y", 4}, {"K", 5}, {"J, X", 8}, {"Q, Z", 10}, } for _, lv := range letterValues { s.register(lv) } totalscore := 0 for _, r := range words { totalscore += s.score(string(r)) } return totalscore } <file_sep>/rust/proverb/src/lib.rs pub fn build_proverb(list: Vec<&str>) -> String { let len = list.len(); if len <= 0 { return String::new(); } let iter = list.iter(); iter.clone().take(len - 1).zip(iter.clone().skip(1)) .map(|(x, y)| format!("For want of a {} the {} was lost.", x, y)) .chain(vec![format!("And all for the want of a {}.", iter.clone().next().unwrap())]) .collect::<Vec<_>>() .join("\n") } <file_sep>/typescript/atbash-cipher/atbash-cipher.ts export default class AtbashCipher { readonly plain: string = 'abcdefghijklmnopqrstuvwxyz1234567890' readonly cipher: string = 'zyxwvutsrqponmlkjihgfedcba1234567890' encode(input: string): string { return this.chunk(this.translate(input, this.plain, this.cipher)) .map((words) => words.join('')).join(' ') } decode(input: string): string { return this.translate(input, this.cipher, this.plain) .join('') } private translate(input: string, plain_map: string, cipher_map: string): string[] { return [... input] .filter((char) => /[A-Za-z0-9]/.test(char)) .map((char) => cipher_map[plain_map.indexOf(char.toLowerCase())]) } private chunk(input: string[], chunk_size: number = 5): string[][] { const result = [] const length = input.length let r_index = 0 let c_index = 0 while (c_index < length) { result[r_index++] = input.slice(c_index, c_index + chunk_size) c_index += chunk_size } return result } }<file_sep>/rust/say/src/lib.rs pub fn encode(n : u64) -> String { match n { 0 => String::from("zero"), _ => do_encode(n).trim().to_string() } } fn do_encode(n : u64) -> String { match n { 1 ... 9 => a_digit(n), 11 ... 19 => teen_digit(n), 10 ... 90 if n % 10 == 0 => ty_digit(n / 10), 20 ... 99 => format!("{}-{}", ty_digit(n / 10), do_encode(n % 10)), 100 ... 999 => format!("{} hundred {}", do_encode(n / 100), do_encode(n % 100)), 1_000 ... 999_999 => format!("{} thousand {}", do_encode(n / 1_000), do_encode(n % 1_000)), 1_000_000 ... 999_999_999 => format!("{} million {}", do_encode(n / 1_000_000), do_encode(n % 1_000_000)), 1_000_000_000 ... 999_999_999_999 => format!("{} billion {}", do_encode(n / 1_000_000_000), do_encode(n % 1_000_000_000)), 1_000_000_000_000 ... 999_999_999_999_999 => format!("{} trillion {}", do_encode(n / 1_000_000_000_000), do_encode(n % 1_000_000_000_000)), 1_000_000_000_000_000 ... 999_999_999_999_999_999 => format!("{} quadrillion {}", do_encode(n / 1_000_000_000_000_000), do_encode(n % 1_000_000_000_000_000)), 1_000_000_000_000_000_000 ... 9_999_999_999_999_999_999 => format!("{} quintillion {}", do_encode(n / 1_000_000_000_000_000_000), do_encode(n % 1_000_000_000_000_000_000)), _ => String::new() } } fn a_digit(n: u64) -> String { let word = match n { 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine", _ => "" }; String::from(word) } fn teen_digit(n: u64) -> String { match n { 11 => "eleven".to_string(), 12 => "twelve".to_string(), 13 => "thirteen".to_string(), 15 => "fifteen".to_string(), 18 => "eighteen".to_string(), _ => format!("{}teen", a_digit(n % 10)) } } fn ty_digit(n: u64) -> String { match n { 1 => "ten".to_string(), 2 => "twenty".to_string(), 3 => "thirty".to_string(), 4 => "forty".to_string(), 5 => "fifty".to_string(), 8 => "eighty".to_string(), _ => format!("{}ty", a_digit(n)) } } <file_sep>/rust/clock/src/lib.rs use std::fmt; #[derive(Debug)] pub struct Clock { minutes: i32 } impl Clock { pub fn new(h: i32, m: i32) -> Clock { Clock { minutes: (h * 60 + m) % -1440 + 1440 } } pub fn add_minutes(&self, minute: i32) -> Clock { Clock::new(0, self.minutes + minute) } pub fn get_hour(&self) -> i32 { self.minutes / 60 % 24 } pub fn get_minute(&self) -> i32 { self.minutes % 60 } } impl fmt::Display for Clock { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:02}:{:02}", self.get_hour(), self.get_minute()) } } impl PartialEq for Clock { fn eq(&self, other: &Clock) -> bool { self.get_hour() == other.get_hour() && self.get_minute() == other.get_minute() } } <file_sep>/elixir/simple-linked-list/README.md # Simple Linked List Write a simple linked list implementation that uses Elements and a List. The linked list is a fundamental data structure in computer science, often used in the implementation of other data structures. They're pervasive in functional programming languages, such as Clojure, Erlang, or Haskell, but far less common in imperative languages such as Ruby or Python. The simplest kind of linked list is a singly linked list. Each element in the list contains data and a "next" field pointing to the next element in the list of elements. This variant of linked lists is often used to represent sequences or push-down stacks (also called a LIFO stack; Last In, First Out). As a first take, lets create a singly linked list to contain the range (1..10), and provide functions to reverse a linked list and convert to and from arrays. When implementing this in a language with built-in linked lists, implement your own abstract data type. ## Running tests Execute the tests with: ```bash $ elixir bob_test.exs ``` (Replace `bob_test.exs` with the name of the test file.) ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source Inspired by 'Data Structures and Algorithms with Object-Oriented Design Patterns in Ruby', singly linked-lists. [http://www.brpreiss.com/books/opus8/html/page96.html#SECTION004300000000000000000](http://www.brpreiss.com/books/opus8/html/page96.html#SECTION004300000000000000000) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/elixir/diffie-hellman/README.md # <NAME> Diffie-Hellman key exchange. Alice and Bob use Diffie-Hellman key exchange to share secrets. They start with prime numbers, pick private keys, generate and share public keys, and then generate a shared secret key. ## Step 0 The test program supplies prime numbers p and g. ## Step 1 Alice picks a private key, a, greater than 1 and less than p. Bob does the same to pick a private key b. ## Step 2 Alice calculates a public key A. A = g**a mod p Using the same p and g, Bob similarly calculates a public key B from his private key b. ## Step 3 Alice and Bob exchange public keys. Alice calculates secret key s. s = B**a mod p Bob calculates s = A**b mod p The calculations produce the same result! Alice and Bob now share secret s. For generating random numbers, Erlang's `:rand.uniform` or `Enum.random` are good places to start. `:math.pow |> round` can be used to find the power of a number, and `rem` for the modulus. Neither of those works particularly well (or quickly) for very large integers. Cryptography generally makes use of numbers larger than 1024 bits. Erlang's :crypto module has a useful function for finding the modulus of a power, particularly for enormous integers, but you might need :binary to decode it. ## Running tests Execute the tests with: ```bash $ elixir diffie_hellman_test.exs ``` ### Pending tests In the test suites, all but the first test have been skipped. Once you get a test passing, you can unskip the next one by commenting out the relevant `@tag :pending` with a `#` symbol. For example: ```elixir # @tag :pending test "shouting" do assert Bob.hey("WATCH OUT!") == "Whoa, chill out!" end ``` Or, you can enable all the tests by commenting out the `ExUnit.configure` line in the test suite. ```elixir # ExUnit.configure exclude: :pending, trace: true ``` For more detailed information about the Elixir track, please see the [help page](http://exercism.io/languages/elixir). ## Source Wikipedia, 1024 bit key from www.cryptopp.com/wiki. [http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange](http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. <file_sep>/rust/difference-of-squares/Cargo.toml [package] name = "difference-of-squares" version = "1.2.0" <file_sep>/rust/sum-of-multiples/src/lib.rs use std::collections::HashSet; pub fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 { factors.iter() .flat_map(|&n| (n..limit).filter(|i| i % n == 0).collect::<Vec<_>>()) .collect::<HashSet<_>>().iter() .sum() } <file_sep>/rust/etl/Cargo.toml [package] name = "etl" version = "1.0.0"
9411dd9c527086104b8fa016bdc904694fbbd607
[ "Markdown", "TOML", "JavaScript", "Rust", "TypeScript", "Go" ]
146
Markdown
k-hamada/exercism
6f728c688353944e4b12f53fdadc49893047fc53
92c3bdd1eeaa6fabeedafe2fe94d8896b468d65d
refs/heads/master
<file_sep>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var appState = { takingPicture: true, imageUri: "" }; var APP_STORAGE_KEY = "exampleAppState"; var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); // var tackPic = document.getElementById('take-picture-button'); document.getElementById("take-picture-button").addEventListener("click", function() { // Because the camera plugin method launches an external Activity, // there is a chance that our application will be killed before the // success or failure callbacks are called. See onPause() and // onResume() where we save and restore our state to handle this case appState.takingPicture = true; navigator.camera.getPicture(cameraSuccessCallback, cameraFailureCallback, { sourceType: Camera.PictureSourceType.CAMERA, destinationType: Camera.DestinationType.FILE_URI, targetWidth: 250, targetHeight: 250 } ); }); } }; // Here are the callbacks we pass to getPicture() function cameraSuccessCallback(imageUri) { appState.takingPicture = false; appState.imageUri = imageUri; document.getElementById("get-picture-result").src = imageUri; } function cameraFailureCallback(error) { appState.takingPicture = false; console.log(error); } app.initialize();<file_sep># CordovaDemo 打包jar jar xvm libname.jar com/ <file_sep>package com.xwang.myapp; import android.annotation.TargetApi; import android.os.Build; import android.text.TextUtils; import android.util.ArrayMap; import java.util.HashMap; /** * Created by xwangly on 2016/6/24. */ @TargetApi(Build.VERSION_CODES.KITKAT) public class JSBridge { public static final String BRIDGE_NAME = "JSBridge"; private static JSBridge INSTANCE = new JSBridge(); private boolean isEnable=true; private HashMap<String, Class<? extends IInject>> mClassMap = new HashMap<>(); private JSBridge() { mClassMap.put(BRIDGE_NAME, JSLogical.class); } public static JSBridge getInstance() { return INSTANCE; } public boolean addInjectPair(String name, Class<? extends IInject> clazz) { if (!mClassMap.containsKey(name)) { mClassMap.put(name, clazz); return true; } return false; } public boolean removeInjectPair(String name,Class<? extends IInject> clazz) { if (TextUtils.equals(name, BRIDGE_NAME)) { return false; } Class clazzValue=mClassMap.get(name); if(null!=clazzValue && (clazzValue == clazz)){ mClassMap.remove(name); return true; } return false; } public HashMap<String, Class<? extends IInject>> getInjectPair() { return mClassMap; } }
c508a344cb212a2f6c2af67220e097b7d6847f08
[ "JavaScript", "Java", "Markdown" ]
3
JavaScript
xwangly/CordovaDemo
48317da1f7728e5978c0cfbad1a9fa9808104f36
8a5f3974d9e06a37859739dc4760ab22b68d56bc
refs/heads/master
<file_sep># これはHello Worldと表示するプログラムです puts "Hello World" # これはコメントアウトされるため何も処理を行いません # puts "Hello Ruby" # ↓ここに全角スペースがある puts "Hello World"<file_sep>def register_book # 本の著者、タイトル、価格をユーザーに入力させ、保存する puts '著者を入力してください' puts 'タイトルを入力してください' puts '価格を入力してください' gets.to_i end def show_books(books) puts "見たい番号を入力してください" # 保存された本の一覧を出力する end def show_detail # 選択された本の詳細な情報(著者、タイトル、価格)を出力する end def average_price # 全ての本の平均価格を算出する end while true do puts "番号を入力してください" puts "0: 本を登録する" puts "1: 本の一覧を見る" puts "2: 終了する" case gets.to_i when 0 # 本の登録を行う when 1 # 保存された本の一覧を出力する when 2 exit else puts '無効な値です' end end<file_sep>profile = {} profile[name] = "太郎" profile[age] = "26" profile[adress] = "高知" puts profile profiles << profile profiles2 = {} profile[name] = "次郎" profile[age] = "27" profile[adress] = "愛媛" puts profile profiles << profiles2 def withdraw(balance, amount) fee = 110  # 手数料 "1000円引き落としました。残高は98890円です"# 引き落とし額と残高を表示する、もしくは残高より多く引き落としたら残高不足と表示 end balance = 100000  # 残高 puts "いくら引き落としますか?(手数料110円かかります)" money = gets.to_i withdraw(balance, money) if test elsif else end<file_sep># 変数の定義 post = {} puts "ジャンルを入力してください:" post[:genre] = gets.chomp puts "タイトルを入力してください:" post[:title] = gets.chomp puts "感想を入力してください:" post[:review] = gets.chomp line = "---------------------------" # レビューの描画 puts "ジャンル : #{post[:genre]}\n#{line}" puts "タイトル : #{post[:title]}\n#{line}" puts "感想 :\n#{post[:review]}\n#{line}"
9c3838757d9bf79b53ffa4754a3a22113ec87eaa
[ "Ruby" ]
4
Ruby
okamoto-shinichiro/sample
bf287ff9831b58da0420bf02545f8b93f39ed41b
23bfb51de8286e5eaf137838792543cb048d6fc6
refs/heads/master
<repo_name>numinix/numinix_product_fields<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/markup/install.sql ALTER TABLE `products` ADD `products_markup` FLOAT DEFAULT '0' AFTER `products_price`;<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/ground_only/YOUR_ADMIN/includes/npf_includes/npf_sql/ground_only.php <?php $parameters['ground_only'] = ''; $npf_fields .= ', p.ground_only'; // eof<file_sep>/optional_catalog/includes/templates/YOUR_TEMPLATE/product_info/extra_main_template_vars/numinix_product_fields.php <?php /** * product_info header_php.php * * @package page * @copyright Copyright 2003-2007 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: numinix_product_fields.php 4 2011-09-28 01:00:29Z numinix $ */ // Begin Numinix Product Fields if (SHOW_PRODUCT_INFO_DIAMETER == 1) { $npf_attributes .= ', p.products_diameter'; $flag_show_product_info_diameter = 1; } if (SHOW_PRODUCT_INFO_DIMENSIONS == 1) { $npf_attributes .= ', p.products_length, p.products_width, p.products_height, p.products_dim_type'; $flag_show_product_info_dimensions = 1;} if (SHOW_PRODUCT_INFO_ACTUAL_WEIGHT == 1) { $npf_attributes .= ', p.products_actual_weight, p.products_weight_type'; $flag_show_product_info_actual_weight = 1; } if (SHOW_PRODUCT_INFO_CONDITION == 1) { $npf_attributes .= ', p.products_condition'; $flag_show_product_info_condition = 1; } if (SHOW_PRODUCT_INFO_UPC == 1 || SHOW_PRODUCT_INFO_ISBN == 1) { $npf_attributes .= ', p.products_upc, p.products_isbn'; $flag_show_product_info_upc = 1; $flag_show_product_info_isbn = 1; } if (SHOW_PRODUCT_INFO_OUT_OF_STOCK == 1) { $npf_attributes .= ', p.out_of_stock'; $flag_show_product_info_out_of_stock = 1; } if (SHOW_PRODUCT_INFO_SKU == 1) { $npf_attributes .= ', p.products_sku'; $flag_show_product_info_sku = 1; } if (SHOW_PRODUCT_INFO_CARE_INSTRUCTIONS == 1) $npf_attributes .= ', pd.care_instructions'; if (SHOW_PRODUCT_INFO_DESCRIPTION2 == 1) $npf_attributes .= ', pd.products_description2'; // build query $products_query = "SELECT p.products_weight" . $npf_attributes . " FROM " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd WHERE p.products_id = " . (int)$_GET['products_id'] . " AND p.products_id = pd.products_id AND pd.language_id = '" . (int)$_SESSION['languages_id'] . "' LIMIT 1"; // execute query $products = $db->Execute($products_query); // store variables $products_length = $products->fields['products_length']; $products_width = $products->fields['products_width']; $products_height = $products->fields['products_height']; $products_diameter = $products->fields['products_diameter']; $products_weight = $products->fields['products_weight']; $products_actual_weight = $products->fields['products_actual_weight']; $products_dim_type = strtolower($products->fields['products_dim_type']); $products_weight_type = strtolower($products->fields['products_weight_type']); $products_description2 = $products->fields['products_description2']; $care_instructions = $products->fields['care_instructions']; $products_condition = $products->fields['products_condition']; $products_upc = $products->fields['products_upc']; $products_isbn = $products->fields['products_isbn']; $products_out_of_stock = $products->fields['out_of_stock']; $products_sku = $products->fields['products_sku']; // create conversions if (SHOW_PRODUCT_INFO_CONVERSIONS == 1) { if ($products_weight_type == 'kgs') { $products_weight2 = round($products_weight * 2.20462262, 2); $products_actual_weight2 = round($products_actual_weight * 2.20462262, 2); $products_weight_type2 = 'lbs'; } else { $products_weight2 = round($products_weight * 0.45359237, 2); $products_actual_weight2 = round($products_actual_weight * 0.45359237, 2); $products_weight_type2 = 'kgs'; } if ($products_dim_type == 'cm') { $products_dim_type2 = 'in'; $conversion = 0.393700787; } else { $products_dim_type2 = 'cm'; $conversion = 2.54; } if (SHOW_PRODUCT_INFO_SMALLER_UNITS == 1) { if ($products_weight_type == 'kgs') { $products_weight_type = 'g'; $products_weight_type2 = 'oz'; $products_weight = $products_weight * 1000; $products_weight2 = $products_weight2 * 16; $products_actual_weight = $products_actual_weight * 1000; $products_actual_weight2 = $products_actual_weight2 * 16; } else { $products_weight_type = 'oz'; $products_weight_type2 = 'g'; $products_weight = $products_weight * 0.0625; $products_weight2 = $products_weight2 * 0.001; $products_actual_weight = $products_actual_weight * 0.0625; $products_actual_weight2 = $products_actual_weight2 * 0.001; } } $products_weight_display = TEXT_PRODUCT_WEIGHT . $products_weight . $products_weight_type . '/' . $products_weight2 . $products_weight_type2; $products_actual_weight_display = TEXT_PRODUCTS_ACTUAL_WEIGHT . $products_actual_weight . $products_weight_type . '/' . $products_actual_weight2 . $products_weight_type2; $products_dim_display = TEXT_PRODUCT_DIMENSIONS . ($products_length > 0 ? TEXT_PRODUCTS_LENGTH . $products_length . $products_dim_type . ' (' . round($products_length * $conversion, 1) . $products_dim_type2 . ') ' : '') . ($products_width > 0 ? TEXT_PRODUCTS_WIDTH . $products_width . $products_dim_type . ' (' . round($products_width * $conversion, 1) . $products_dim_type2 . ') ' : '') . ($products_height > 0 ? TEXT_PRODUCTS_HEIGHT . $products_height . $products_dim_type . ' (' . round($products_height * $conversion, 1) . $products_dim_type2 . ')' : ''); $products_diameter_display = TEXT_PRODUCTS_DIAMETER . ($products_diameter > 0 ? $products_diameter . $products_dim_type . ' (' . round($products_diameter * $conversion, 1) . $products_dim_type2 . ') ' : ''); } else { if (SHOW_PRODUCT_INFO_SMALLER_UNITS == 1) { if ($products_weight_type = 'kgs') { $products_weight_type = 'g'; $products_weight = $products_weight * 1000; } else { $products_weight_type = 'oz'; $products_weight = $products_weight * 0.0625; } } $products_weight_display = TEXT_PRODUCT_WEIGHT . $products_weight . $products_weight_type; $products_actual_weight_display = TEXT_PRODUCTS_ACTUAL_WEIGHT . $products_actual_weight . $products_weight_type; $products_dim_display = TEXT_PRODUCT_DIMENSIONS . ($products_length > 0 ? TEXT_PRODUCTS_LENGTH . $products_length . $products_dim_type . ' ' : '') . ($products_width > 0 ? TEXT_PRODUCTS_WIDTH . $products_width . $products_dim_type . ' ' : '') . ($products_height > 0 ? TEXT_PRODUCTS_HEIGHT . $products_height . $products_dim_type : ''); $products_diameter_display = TEXT_PRODUCTS_DIAMETER . ($products_diameter > 0 ? $products_diameter . $products_dim_type : ''); } //End Numinix Product Fields<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/air_only/YOUR_ADMIN/includes/npf_includes/npf_sql/air_only.php <?php $parameters['air_only'] = ''; $npf_fields .= ', p.air_only'; // eof<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/air_only/install.sql ALTER TABLE `products` ADD `air_only` tinyint(1) NOT NULL default 0;<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/ground_only/YOUR_ADMIN/includes/languages/english/npf_definitions/ground_only.php <?php define('TEXT_PRODUCTS_GROUND_ONLY', 'Ground Shipping Only: '); // eof<file_sep>/admin_menu_for_zc1.3.x/YOUR_ADMIN/includes/boxes/extra_boxes/numinix_product_fields_catalog_dhtml.php <?php /** * Numinix Product Fields */ // this is used for admin-menu display: $za_contents[] = array('text' => TEXT_NUMINIX_PRODUCT_FIELDS, 'link' => zen_href_link(NUMINIX_PRODUCT_FIELDS_FILENAME, '', 'NONSSL'));<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/dropship/YOUR_ADMIN/includes/npf_includes/npf_sql_array/dropship.php <?php $sql_data_array['dropship'] = zen_db_prepare_input($_POST['dropship']); // eof<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/matching_products/install.sql ALTER TABLE products ADD matching_products varchar(300) NULL default NULL; ALTER TABLE products ADD matching_color varchar(300) NULL default NULL; ALTER TABLE products ADD matching_fleece varchar(300) NULL default NULL; ALTER TABLE products ADD matching_tank varchar(300) NULL default NULL; ALTER TABLE products ADD matching_gender varchar(300) NULL default NULL; ALTER TABLE products ADD matching_youth varchar(300) NULL default NULL; ALTER TABLE products ADD matching_tshirt varchar(300) NULL default NULL;<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/dropship/YOUR_ADMIN/includes/npf_includes/npf_sql/dropship.php <?php $parameters['dropship'] = ''; $npf_fields .= ', p.dropship'; // eof<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/markup/YOUR_ADMIN/includes/npf_includes/npf_sql_array/products_markup.php <?php $sql_data_array['products_markup'] = zen_db_prepare_input($_POST['products_markup']); // eof<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/disallowed_zone/install.sql ALTER TABLE products ADD disallowed_zone int(11) NULL default NULL;<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/continental_shipping/install.sql ALTER TABLE products ADD continental_shipping varchar(32) NULL default NULL; ALTER TABLE products ADD products_sh_na varchar(32) NULL default NULL; ALTER TABLE products ADD products_sh_sa varchar(32) NULL default NULL after products_sh_na; ALTER TABLE products ADD products_sh_eu varchar(32) NULL default NULL after products_sh_sa; ALTER TABLE products ADD products_sh_af varchar(32) NULL default NULL after products_sh_eu; ALTER TABLE products ADD products_sh_as varchar(32) NULL default NULL after products_sh_af; ALTER TABLE products ADD products_sh_au varchar(32) NULL default NULL after products_sh_as;<file_sep>/catalog/YOUR_ADMIN/includes/installers/numinix_product_fields/2_3_1.php <?php // fix issue with product fields variable <file_sep>/optional_catalog/includes/languages/english/extra_definitions/numinix_product_fields.php <?php /** * product_info.php * * @package page * @copyright Copyright 2003-2007 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: numinix_product_fields.php 4 2011-09-28 01:00:29Z numinix $ */ define('TEXT_PRODUCTS_ACTUAL_WEIGHT', 'Products Weight: '); define('TEXT_PRODUCT_DIMENSIONS', 'Dimensions: '); define('TEXT_PRODUCTS_LENGTH', ''); define('TEXT_PRODUCTS_WIDTH', ''); define('TEXT_PRODUCTS_HEIGHT', ''); define('TEXT_PRODUCTS_DIAMETER', 'Diameter: '); define('TEXT_PRODUCTS_CONDITION', 'Condition: '); define('TEXT_PRODUCTS_UPC', 'UPC: '); define('TEXT_PRODUCTS_ISBN', 'ISBN: '); define('TEXT_PRODUCTS_OUT_OF_STOCK', 'Out of Stock'); define('TEXT_PRODUCTS_SKU', 'SKU: ');<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/stock_by_attributes_link/install.sql ALTER TABLE products ADD stock_by_attributes_link varchar(256) NULL default NULL; <file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/air_only/YOUR_ADMIN/includes/languages/english/npf_definitions/air_only.php <?php define('TEXT_PRODUCTS_AIR_ONLY', 'Air Shipping Only: '); // eof<file_sep>/uninstall.sql ALTER TABLE products DROP COLUMN products_epier; ALTER TABLE products DROP COLUMN products_ebay; ALTER TABLE products DROP COLUMN products_ebid; ALTER TABLE products DROP COLUMN products_sh_na; ALTER TABLE products DROP COLUMN products_sh_sa; ALTER TABLE products DROP COLUMN products_sh_eu; ALTER TABLE products DROP COLUMN products_sh_af; ALTER TABLE products DROP COLUMN products_sh_as; ALTER TABLE products DROP COLUMN products_sh_au; ALTER TABLE products DROP COLUMN products_condition; ALTER TABLE products DROP COLUMN products_upc; ALTER TABLE products DROP COLUMN products_isbn; ALTER TABLE products DROP COLUMN products_weight_type; ALTER TABLE products DROP COLUMN products_dim_type; ALTER TABLE products DROP COLUMN products_length; ALTER TABLE products DROP COLUMN products_width; ALTER TABLE products DROP COLUMN products_height; ALTER TABLE products DROP COLUMN products_ready_to_ship; ALTER TABLE products DROP COLUMN products_EHF; ALTER TABLE products DROP COLUMN products_category; ALTER TABLE products DROP COLUMN products_barcode; ALTER TABLE products DROP COLUMN products_diameter; ALTER TABLE products DROP COLUMN products_actual_weight; DELETE FROM product_type_layout WHERE configuration_key = 'SHOW_PRODUCT_INFO_DIMENSIONS'; DELETE FROM product_type_layout WHERE configuration_key = 'SHOW_PRODUCT_INFO_DIAMETER'; DELETE FROM product_type_layout WHERE configuration_key = 'SHOW_PRODUCT_INFO_CONVERSIONS'; DELETE FROM product_type_layout WHERE configuration_key = 'SHOW_PRODUCT_INFO_SMALLER_UNITS'; DELETE FROM product_type_layout WHERE configuration_key = 'SHOW_PRODUCT_INFO_ACTUAL_WEIGHT'; SET @configuration_group_id=0; SELECT @configuration_group_id:=configuration_group_id FROM configuration WHERE configuration_key= 'NUMINIX_PRODUCT_FIELDS_VERSION' LIMIT 1; DELETE FROM configuration WHERE configuration_group_id = @configuration_group_id AND configuration_group_id <> 0; DELETE FROM configuration_group WHERE configuration_group_id = @configuration_group_id AND configuration_group_id <> 0;<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/ground_only/YOUR_ADMIN/includes/npf_includes/npf_sql_array/ground_only.php <?php $sql_data_array['ground_only'] = zen_db_prepare_input($_POST['ground_only']); // eof<file_sep>/catalog/YOUR_ADMIN/includes/functions/extra_functions/npf_functions.php <?php function dirList($directory) { // create an array to hold directory list $results = array(); if (is_dir($directory)){ // create a handler for the directory if ($handler = opendir($directory)){ // keep going until all files in directory have been read while ($file = readdir($handler)) { // if $file isn't this directory or its parent, // add it to the results array if ($file != '.' && $file != '..') $results[] = $file; } asort($results); // tidy up: close the handler closedir($handler); // done! } } return $results; } function zen_get_products_description2($product_id, $language_id) { global $db; $product = $db->Execute("select products_description2 from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int) $product_id . "' and language_id = '" . (int) $language_id . "'"); return $product->fields['products_description2']; } function zen_get_products_video_embed($product_id, $language_id) { global $db; $product = $db->Execute("select products_video_embed from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int) $product_id . "' and language_id = '" . (int) $language_id . "'"); return $product->fields['products_video_embed']; } function npf_add_prebuilt_fields($field) { $array_of_files = array( 'languages/english/npf_definitions/' . $field . '.php', 'npf_includes/npf_custom_execute/' . $field . '.php', 'npf_includes/npf_description_sql_array/' . $field . '.php', 'npf_includes/npf_modules/' . $field . '.php', 'npf_includes/npf_process/' . $field . '.php', 'npf_includes/npf_sql/' . $field . '.php', 'npf_includes/npf_sql_array/' . $field . '.php', 'npf_includes/npf_templates/' . $field . '.php', 'npf_includes/npf_preview/' . $field . '.php', 'npf_includes/npf_preview_info/' . $field . '.php', ); $npf_copy_failed_count = 0; foreach ($array_of_files as $possible_file) { if (!npf_copy_file($field, $possible_file)){ $npf_copy_failed_count ++; } } if( $npf_copy_failed_count == count($array_of_files) ){ // if none of the files gets copied over, something is wrong for sure return false; } return true; } function npf_copy_file($field, $folder) { if (file_exists(DIR_FS_ADMIN . NPF_INCLUDES_PREBUILT_FOLDER . $field . '/YOUR_ADMIN/includes/' . $folder)) { $contents = file_get_contents(DIR_FS_ADMIN . NPF_INCLUDES_PREBUILT_FOLDER . $field . '/YOUR_ADMIN/includes/' . $folder); $copy_file_result = file_put_contents(DIR_FS_ADMIN . DIR_WS_INCLUDES . $folder, $contents); if ($copy_file_result == 0 || $copy_file_result == false) { return false; } return true; } else { return false; } } function npf_sql_patch($string) { global $db; $string = str_replace("`", "", $string); $string = str_replace(" products ", " " . DB_PREFIX . "products ", $string); $string = str_replace(" product_type_layout ", " " . DB_PREFIX . "product_type_layout ", $string); $string = str_replace(" products_description ", " " . DB_PREFIX . "products_description ", $string); $query_array = explode(';', $string); foreach ($query_array as $query) { if (strlen($query) > 5) { $db->Execute($query . ';'); } } } if (!function_exists('npf_field_value')) { function npf_field_value($id, $field) { global $db; $product = $db->Execute("SELECT * FROM " . TABLE_PRODUCTS . " WHERE products_id=" . (int) $id . " LIMIT 1"); $value = $product->fields[$field]; return $value; } } function add_custom_field($field_name, $type, $length = '300') { global $db, $messageStack; $field = str_replace(" ", "_", strtolower($field_name)); $nice_field_name = ucwords(strtolower(str_replace("_", " ", $field))); global $sniffer; if ($sniffer->field_exists(TABLE_PRODUCTS, $field)) { $messageStack->add('ERROR!! Product field ' . $field . ' already exists', 'caution'); return; } $lang_defines = strtoupper($field); switch ($type) { case "file": $sql_type = "varchar(" . $length . ") NULL default NULL"; $string_input_field = "zen_draw_file_field('" . $field . "'); if(\$pinfo->" . $field . " != ''){echo \$pinfo->" . $field . ";}"; break; case "checkbox": $string_input_field = "zen_draw_checkbox_field('" . $field . "', 1, (\$pInfo->" . $field . ") ? true : false);"; $sql_type = "tinyint(1) NOT NULL default 0"; break; case "text": default: $sql_type = "varchar(" . $length . ") NULL default NULL"; $string_input_field = "zen_draw_input_field('" . $field . "',(\$pInfo->" . $field . "),zen_set_field_length(TABLE_PRODUCTS, '" . $field . "'));"; break; } //files $admin_start_file = "<?php // File Generated by Numinix Product Fields // @package admin // @copyright Copyright 2003-2013 Zen Cart Development Team // @copyright Portions Copyright 2003 osCommerce // @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 // if (!defined('IS_ADMIN_FLAG')) { die('Illegal Access'); } "; $string_npf_lang_file = " define('TEXT_" . $lang_defines . "', '" . $nice_field_name . ": '); // eof"; file_put_contents(NPF_DEFINITIONS_FOLDER . $field . '.php', $admin_start_file.$string_npf_lang_file); $string_npf_sql_file = " \$parameters['" . $field . "'] = ''; \$npf_fields .= ', p." . $field . "'; // eof"; file_put_contents(NPF_INCLUDES_SQL_FOLDER . $field . '.php', $admin_start_file.$string_npf_sql_file); $string_npf_sql_array_file = " if(isset(\$_POST['" . $field . "']) && \$_POST['" . $field . "'] != ''){ \$sql_data_array['" . $field . "'] = zen_db_prepare_input(\$_POST['" . $field . "']); }"; file_put_contents(NPF_INCLUDES_SQL_ARRAY_FOLDER . $field . '.php', $admin_start_file.$string_npf_sql_array_file); $string_npf_templates_file = " <tr> <td colspan=\"2\"><?php echo zen_draw_separator('pixel_trans.gif', '1', '10'); ?></td> </tr> <tr bgcolor=\"#DDEACC\"> <td class=\"main\"><?php echo TEXT_" . $lang_defines . "; ?></td> <td class=\"main\"><?php echo zen_draw_separator('pixel_trans.gif', '24', '15') . '&nbsp;' . " . $string_input_field . " ?></td> </tr> <tr> <td colspan=\"2\"><?php echo zen_draw_separator('pixel_trans.gif', '1', '10'); ?></td> </tr>"; file_put_contents(NPF_INCLUDES_TEMPLATES_FOLDER . $field . '.php', $string_npf_templates_file); if ($type == 'file') { $process_string = " "; file_put_contents(NPF_INCLUDES_PROCESSING_FOLDER . $field . '.php', $admin_start_file.$process_string); $preview_string = " if (!isset(\$_GET['read']) || \$_GET['read'] == 'only') { \$products_" . $field . " = new upload('" . $field . "'); \$products_" . $field . "->set_destination(DIR_FS_CATALOG .'".NPF_UPLOAD_FOLDER."/'); if (\$products_" . $field . "->parse() && \$products_" . $field . "->save(\$_POST['overwrite'])) { \$products_" . $field . "_name = '".NPF_UPLOAD_FOLDER."/' . \$products_" . $field . "->filename; } else { \$products_" . $field . "_name = (isset(\$_POST['" . $field . "']) ? \$_POST['" . $field . "'] : ''); } }"; file_put_contents(NPF_INCLUDES_PREVIEW_FOLDER . $field . '.php', $admin_start_file.$preview_string); $preview_info_string = ' echo zen_draw_hidden_field(\'' . $field . '\', stripslashes($products_' . $field . '_name));'; file_put_contents(NPF_INCLUDES_PREVIEW_INFO_FOLDER . $field . '.php', $admin_start_file.$preview_info_string); } //add the field to the DB $db->Execute("ALTER TABLE `" . DB_PREFIX . "products` ADD `" . $field . "` " . $sql_type . ";"); $messageStack->add($nice_field_name . " added", 'success'); } <file_sep>/catalog/YOUR_ADMIN/numinix_product_fields.php <?php /** * @package admin * @copyright Copyright 2003-2010 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: numinix_product_fields.php 2014-0919 1:05PM CDT bislewl $ */ require('includes/application_top.php'); $add_npf_field = zen_db_prepare_input($_POST['add_npf_field']); $add_custom_npf_field = zen_db_prepare_input($_POST['add_custom_npf_field']); $add_custom_npf_field_name = zen_db_prepare_input($_POST['add_custom_npf_field_name']); $add_custom_npf_field_type = zen_db_prepare_input($_POST['add_custom_npf_field_type']); $add_custom_npf_field_length = zen_db_prepare_input($_POST['add_custom_npf_field_length']); $file_posted = basename($_FILES["file_download"]); if($add_npf_field != ''){ $field = $add_npf_field; //move files if (!npf_add_prebuilt_fields($field)) { $messageStack->add('The selected field was unable to be installed due to insufficient server permissions, please contact your host.','error'); } else { //execute SQL Patch $query_string = file_get_contents(NPF_INCLUDES_PREBUILT_FOLDER.$field.'/install.sql'); npf_sql_patch($query_string); $messageStack->add(ucwords(strtolower(str_replace("_", " ", $field)))." added", 'success'); } } if($add_custom_npf_field == "Y"){ if($add_custom_npf_field_length == ''){ $add_custom_npf_field_length = '300'; } add_custom_field($add_custom_npf_field_name, $add_custom_npf_field_type, $add_custom_npf_field_length); } $current_product_fields = array(); $tableFields = $db->metaColumns(TABLE_PRODUCTS); $columnName = strtoupper($columnName); //loop to traverse tableFields result set foreach($tableFields as $key=>$value) { $current_product_fields[] = strtolower($key); } $pdtableFields = $db->metaColumns(TABLE_PRODUCTS_DESCRIPTION); $pdcolumnName = strtoupper($pdcolumnName); //loop to traverse tableFields result set foreach($pdtableFields as $key=>$value) { $current_product_fields[] = strtolower($key); } sort($current_product_fields); $dirs = scandir(NPF_INCLUDES_PREBUILT_FOLDER); $prebuilt_fields = array(); foreach ($dirs as $dir) { if ($dir != '.' && $dir != '..') { if (is_dir(NPF_INCLUDES_PREBUILT_FOLDER . '/' . $dir) && !in_array($dir, $current_product_fields)) { $prebuilt_fields[] = $dir; } } } sort($prebuilt_fields); ?> <!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <html <?php echo HTML_PARAMS; ?>> <head> <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>"> <title><?php echo TITLE; ?> - Numinix Product Fields</title> <link rel="stylesheet" type="text/css" href="includes/stylesheet.css"> <link rel="stylesheet" type="text/css" href="includes/cssjsmenuhover.css" media="all" id="hoverJS"> <script language="javascript" src="includes/menu.js"></script> <script language="javascript" src="includes/general.js"></script> <script type="text/javascript"> <!-- function init() { cssjsmenu('navbar'); if (document.getElementById) { var kill = document.getElementById('hoverJS'); kill.disabled = true; } } // --> </script> </head> <body onLoad="init()"> <!-- header //--> <?php require(DIR_WS_INCLUDES . 'header.php'); ?> <!-- header_eof //--> <table border="0" width="100%" cellspacing="2" cellpadding="2"> <tr> <td width="100%" valign="top"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td class="pageHeading">Numinix Product Fields</td> <td class="pageHeading" align="right"><img src="images/pixel_trans.gif" border="0" alt="" width="57" height="40"></td> </tr> <tr> <td> <table width="700px"> <tr> <th align="left">Available Fields</th> <th align="right">Current Product Fields</th> </tr> <tr> <td align="left"> <?php foreach($prebuilt_fields as $prebuilt_ready_field){ echo zen_draw_form('npf_fields',NUMINIX_PRODUCT_FIELDS_FILENAME); echo zen_draw_hidden_field('add_npf_field',$prebuilt_ready_field); $nice_name_prebuilt_field = ucwords(strtolower(str_replace("_", " ", $prebuilt_ready_field))); echo zen_draw_input_field('submit', 'Add Field', '', false, 'submit'); echo $nice_name_prebuilt_field." "; echo '</form><br/>'; } ?> </td> <td align="right"> <?php foreach($current_product_fields as $current_product_field){ echo $current_product_field.'<br/>'; } ?> </td> </tr> </table> </td> </tr> </table> <br/> <hr/> <br/> <br/> <h2>Add your own Custom Field</h2> <br/> <?php echo zen_draw_form('custom_npf_fields',NUMINIX_PRODUCT_FIELDS_FILENAME); echo zen_draw_hidden_field('add_custom_npf_field',"Y"); echo " Field Name:".zen_draw_input_field('add_custom_npf_field_name'); $pull_down_array[] = array( 'id' => 'text', 'text' => 'Text'); $pull_down_array[] = array( 'id' => 'checkbox', 'text' => 'Checkbox'); $pull_down_array[] = array( 'id' => 'file', 'text' => 'File'); echo " Type:".zen_draw_pull_down_menu('add_custom_npf_field_type',$pull_down_array); //echo zen_draw_input_field('add_custom_npf_field_length','300'); echo " ".zen_draw_input_field('submit', 'Add Field', '', false, 'submit'); echo '</form><br/>'; ?> <hr/> </td> </tr> </table> </td> </tr> </table> <!-- body_eof //--> <!-- footer //--> <?php require(DIR_WS_INCLUDES . 'footer.php'); ?> <!-- footer_eof //--> </body> </html> <?php require(DIR_WS_INCLUDES . 'application_bottom.php'); <file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/care_instructions/YOUR_ADMIN/includes/npf_includes/npf_templates/care_instructions.php <?php for ($i=0, $n=sizeof($languages); $i<$n; $i++) { ?> <tr> <td class="main" valign="top"><?php if ($i == 0) echo TEXT_CARE_INSTRUCTIONS; ?></td> <td colspan="2"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="main" width="25" valign="top"><?php echo zen_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']); ?>&nbsp;</td> <td class="main" width="100%"> <?php echo zen_draw_textarea_field('care_instructions[' . $languages[$i]['id'] . ']', 'soft', '100%', '30', (isset($care_instructions[$languages[$i]['id']])) ? stripslashes($care_instructions[$languages[$i]['id']]) : zen_get_care_instructions($pInfo->products_id, $languages[$i]['id'])); ?> </td> </tr> </table> </td> </tr> <?php } ?><file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/markup/YOUR_ADMIN/includes/languages/english/npf_definitions/products_markup.php <?php define('TEXT_PRODUCTS_MARKUP', 'Product\'s Price Markup %: '); // eof<file_sep>/catalog/YOUR_ADMIN/includes/installers/numinix_product_fields/2_2_0.php <?php // Added support for zencart.com plugin new version notification // Improved uninstall.sql<file_sep>/catalog/YOUR_ADMIN/includes/installers/numinix_product_fields/2_0_0.php <?php // remove old field functions file // that function is now included in the npf_functions.php if(file_exists(DIR_FS_ADMIN.'includes/functions/extra_functions/npf_fields_functions.php')){ unlink(DIR_FS_ADMIN.'includes/functions/extra_functions/npf_fields_functions.php'); } // For Admin Pages $zc150 = (PROJECT_VERSION_MAJOR > 1 || (PROJECT_VERSION_MAJOR == 1 && substr(PROJECT_VERSION_MINOR, 0, 3) >= 5)); if ($zc150) { // continue Zen Cart 1.5.0 // delete configuration menu $db->Execute("DELETE FROM ".TABLE_ADMIN_PAGES." WHERE page_key = 'catalogNPF' LIMIT 1;"); // add configuration menu if (!zen_page_key_exists('catalogNPF')) { if ((int)$configuration_group_id > 0) { zen_register_admin_page('catalogNPF', 'TEXT_NUMINIX_PRODUCT_FIELDS', 'NUMINIX_PRODUCT_FIELDS_FILENAME', '', 'catalog', 'Y', $configuration_group_id); $messageStack->add('Enabled Numinix Product Fields Catalog Menu Item.', 'success'); } } } global $sniffer; if (!$sniffer->field_exists(TABLE_PRODUCTS, 'products_condition')) $db->Execute("ALTER TABLE ".TABLE_PRODUCTS." ADD products_condition varchar(32) NULL default NULL;"); $condition_query = $db->Execute("SELECT configuration_key FROM ".TABLE_PRODUCT_TYPE_LAYOUT." WHERE configuration_key='SHOW_PRODUCT_INFO_CONDITION'"); if($condition_query->Recordcount() == 0){ $db->Execute("INSERT INTO ".TABLE_PRODUCT_TYPE_LAYOUT." (configuration_id, configuration_title, configuration_key, configuration_value, configuration_description, product_type_id, sort_order, last_modified, date_added, use_function, set_function) VALUES (NULL, 'Show Condition', 'SHOW_PRODUCT_INFO_CONDITION', '0', 'Show product condition on product info page (requires Numinix Product Fields)?', 1, 17, NULL, NOW(), NULL, 'zen_cfg_select_option(array(\'1\', \'0\'),');"); }<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/disallowed_zone/YOUR_ADMIN/includes/languages/english/npf_definitions/disallowed_zone.php <?php define('TEXT_PRODUCTS_DISALLOWED_ZONE', 'Disallowed Zone: '); define('TEXT_SELECT_AN_OPTION', 'Please Select'); // eof<file_sep>/readme.txt See /docs/Numinix Product Fields/readme.html for documentation<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/wholesale_price/install.sql ALTER TABLE `products` ADD `products_price_w` VARCHAR( 150 ) DEFAULT '0' AFTER `products_price`; ALTER TABLE `products` ADD `wholesale_price` VARCHAR( 150 ) DEFAULT '0' AFTER `products_price`;<file_sep>/catalog/YOUR_ADMIN/includes/installers/numinix_product_fields/2_1_2.php <?php /* * Fields to sort alphabetically by filename. */ <file_sep>/catalog/YOUR_ADMIN/includes/functions/extra_functions/npf_fields_functions.php <?php //Blank file to overwrite old file, installer will delete this automatically <file_sep>/catalog/YOUR_ADMIN/includes/extra_datafiles/numinix_product_fields.php <?php define('NUMINIX_PRODUCT_FIELDS_FILENAME','numinix_product_fields.php');<file_sep>/catalog/YOUR_ADMIN/includes/installers/numinix_product_fields/2_4_3.php <?php // Fix installation of prebuilt fields // Add true/false check for file copy function. // Pre-built fields installation fails if none of the files is copied over. // Rename prebuilt_fields folders to the correct ones. // Update docs <file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/care_instructions/YOUR_ADMIN/includes/functions/extra_functions/care_instructions.php <?php function zen_get_care_instructions($product_id, $language_id) { global $db; $product = $db->Execute("select care_instructions from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int)$product_id . "' and language_id = '" . (int)$language_id . "'"); return $product->fields['care_instructions']; }<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/disallowed_zone/YOUR_ADMIN/includes/npf_includes/npf_sql/disallowed_zone.php <?php $parameters['disallowed_zone'] = ''; $npf_fields .= ', p.disallowed_zone'; // eof<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/dropship/YOUR_ADMIN/includes/languages/english/npf_definitions/dropship.php <?php define('TEXT_PRODUCTS_DROPSHIP', 'Dropship: '); // eof<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/care_instructions/YOUR_ADMIN/includes/npf_includes/npf_sql/care_instructions.php <?php $parameters['care_instructions'] = ''; //asa modification $npf_fields .= ', pd.care_instructions'; // eof<file_sep>/catalog/YOUR_ADMIN/includes/installers/numinix_product_fields/2_1_0.php <?php //added npf field function to catalog side<file_sep>/catalog/includes/functions/extra_functions/npf_field_functions.php <?php /* * npf_field_value to obtain a product field for display/use in catalog * Example use of function: * echo npf_field_value($product_id,'products_msrp'); */ if (!function_exists('npf_field_value')) { function npf_field_value($id, $field){ global $db; $product = $db->Execute("SELECT * FROM ".TABLE_PRODUCTS." WHERE products_id=".(int)$id." LIMIT 1"); $value = $product->fields[$field]; return $value; } } <file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/additional_skus/install.sql ALTER TABLE products ADD additional_skus varchar(250) NULL default NULL; ALTER TABLE products ADD additional_skus_only int(1) NULL default NULL;<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/dimensions/YOUR_ADMIN/includes/npf_includes/npf_templates/dimensional_shipping.php <tr> <td colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '1', '10'); ?></td> </tr> <tr bgcolor="#DDEACC"> <td class="main"><?php echo TEXT_PRODUCTS_WEIGHT_UNITS;?></td> <td class="main" colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '24', '15') . '&nbsp;' . zen_draw_radio_field('products_weight_type', UNITS_KGS, $in_weight_type) . '&nbsp;' . UNITS_KGS . ' ' . zen_draw_radio_field('products_weight_type', UNITS_LBS, $out_weight_type) . '&nbsp;' . UNITS_LBS; ?> </td> </tr> <tr bgcolor="#DDEACC"> <td class="main"><?php echo TEXT_PRODUCTS_DIM_UNITS; ?></td> <td class="main" colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '24', '15') . '&nbsp;' . zen_draw_radio_field('products_dim_type', UNITS_CM, $in_dim_type) . '&nbsp;' . UNITS_CM . ' ' . zen_draw_radio_field('products_dim_type', UNITS_IN, $out_dim_type) . '&nbsp;' . UNITS_IN; ?></td> </tr> <tr bgcolor="#DDEACC"> <td class="main"><?php echo TEXT_PRODUCTS_LENGTH; ?></td> <td class="main" colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '24', '15') . '&nbsp;' . zen_draw_input_field('products_length', $pInfo->products_length); ?></td> </tr> <tr bgcolor="#DDEACC"> <td class="main"><?php echo TEXT_PRODUCTS_WIDTH; ?></td> <td class="main" colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '24', '15') . '&nbsp;' . zen_draw_input_field('products_width', $pInfo->products_width); ?></td> </tr> <tr bgcolor="#DDEACC"> <td class="main"><?php echo TEXT_PRODUCTS_HEIGHT; ?></td> <td class="main" colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '24', '15') . '&nbsp;' . zen_draw_input_field('products_height', $pInfo->products_height); ?></td> </tr> <tr bgcolor="#DDEACC"> <td class="main"><?php echo TEXT_PRODUCTS_DIAMETER; ?></td> <td class="main" colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '24', '15') . '&nbsp;' . zen_draw_input_field('products_diameter', $pInfo->products_diameter); ?></td> </tr> <tr bgcolor="#DDEACC"> <td class="main"><?php echo TEXT_PRODUCTS_READY_TO_SHIP; ?></td> <td class="main" colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '24', '15') . '&nbsp;' . zen_draw_checkbox_field('products_ready_to_ship', '1', (int)$pInfo->products_ready_to_ship) . '&nbsp;' . TEXT_PRODUCTS_READY_TO_SHIP_SELECTION . '&nbsp;' ?></td> </tr> <tr> <td colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '1', '10'); ?></td> </tr> <file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/care_instructions/YOUR_ADMIN/includes/languages/english/npf_definitions/care_instructions.php <?php define('TEXT_CARE_INSTRUCTIONS', 'Care Instructions:'); // eof<file_sep>/catalog/YOUR_ADMIN/includes/installers/numinix_product_fields/2_3_0.php <?php //fixed issues with adding custom fields //added support for file uploads (still a bit buggy yet though) <file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/care_instructions/YOUR_ADMIN/includes/npf_includes/npf_description_sql_array/care_instructions.php <?php $sql_data_array['care_instructions'] = zen_db_prepare_input($_POST['care_instructions'][$language_id]);<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/dropship/install.sql ALTER TABLE products ADD dropship int(1) NULL default 0;<file_sep>/catalog/YOUR_ADMIN/includes/installers/numinix_product_fields/2_4_0.php <?php $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_group_id, configuration_key, configuration_title, configuration_value, configuration_description) VALUES (" . (int) $configuration_group_id . ", 'NPF_UPLOAD_FOLDER', 'Upload Folder for Files', 'media', 'This is the directory that files will be uploaded to. Default is media' );"); if(version_compare(PROJECT_VERSION_MAJOR.".".PROJECT_VERSION_MINOR, "1.5.0") >= 0) { // continue Zen Cart 1.5.0 // add to configuration menus if (function_exists('zen_page_key_exists') && function_exists('zen_register_admin_page') && !zen_page_key_exists('configNPF')) { zen_register_admin_page('configNPF', 'TEXT_NUMINIX_PRODUCT_FIELDS', 'FILENAME_CONFIGURATION', 'gID='.(int)$configuration_group_id, 'configuration', 'Y', 999); $messageStack->add('NPF Configuration menu.', 'success'); } }<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/ground_only/install.sql ALTER TABLE `products` ADD `ground_only` tinyint(1) NOT NULL default 0;<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/markup/YOUR_ADMIN/includes/npf_includes/npf_sql/products_markup.php <?php $parameters['products_markup'] = ''; $npf_fields .= ', p.products_markup'; // eof<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/air_only/YOUR_ADMIN/includes/npf_includes/npf_sql_array/air_only.php <?php $sql_data_array['air_only'] = zen_db_prepare_input($_POST['air_only']); // eof<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/disallowed_zone/YOUR_ADMIN/includes/npf_includes/npf_sql_array/disallowed_zone.php <?php $sql_data_array['disallowed_zone'] = zen_db_prepare_input($_POST['disallowed_zone']); // eof<file_sep>/catalog/YOUR_ADMIN/includes/npf_includes/prebuilt_fields/disallowed_zone/YOUR_ADMIN/includes/npf_includes/npf_templates/disallowed_zone.php <tr> <td colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '1', '10'); ?></td> </tr> <tr bgcolor="#DDEACC"> <td class="main"><?php echo TEXT_PRODUCTS_DISALLOWED_ZONE; ?></td> <td class="main"><?php echo zen_draw_separator('pixel_trans.gif', '24', '15') . '&nbsp;' . str_replace('<select name="disallowed_zone">', '<select name="disallowed_zone"><option value="0">' . TEXT_SELECT_AN_OPTION . '</option>', zen_geo_zones_pull_down('name="disallowed_zone"', $pInfo->disallowed_zone)); ?></td> </tr> <tr> <td colspan="2"><?php echo zen_draw_separator('pixel_trans.gif', '1', '10'); ?></td> </tr>
e949d007b62468ff3fe063da83f88e7fb87cf1eb
[ "SQL", "Text", "PHP" ]
50
SQL
numinix/numinix_product_fields
5c514720686ec451ff49ce98392c5f08bb01caf9
e61e919668801557b21ea92ee9d7f50e765fd6eb
refs/heads/master
<repo_name>paulm29/resume<file_sep>/resume_angular.js var app = angular.module("myApp", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "career_objectives.html" }) .when("/career_objectives", { templateUrl : "career_objectives.html" }) .when("/employment_history", { templateUrl : "employment_history.html" }) .when("/key_skills", { templateUrl : "key_skills.html" }) .when("/professional_associations", { templateUrl : "professional_associations.html" }) .when("/qualifications", { templateUrl : "qualifications.html" }) .when("/referees", { templateUrl : "referees.html" }) .otherwise({ template: "Click on the links above" }); }); app.controller('qualificationsController', function($scope) { $scope.qualifications = [ { year: '2014', title: 'Certificate IV in Training and Assessment', university: 'Southbank Institute of Technology, Brisbane', result: '', img: 'tafe-queensland-logo1.png', likes: 0 }, { year: '2013', title: 'Graduate Diploma of Education (Secondary)', university: 'Griffith University, Brisbane', result: 'GPA: 6.67 (scale 1-7, 7 highest), Griffith Award for Academic Excellence', img: 'griffith-logo-g7.png', likes: 0 }, { year: '2004-2006', title: 'Bachelor of Information Technology (Software Engineering)', university: 'Queensland University of Technology, Brisbane', result: 'GPA: 5.875', img: 'qut-logo-brisbane-australia.jpg', likes: 0 } ]; $scope.plusOne = function(index) { $scope.qualifications[index].likes += 1; }; }); /* app.directive("w3TestDirective", function() { return { restrict : "A", template : "<b>I was made in a directive constructor!</b>" }; }); app.controller('myCtrl', function($scope) { $scope.firstName= "John"; $scope.lastName= "Doe"; $scope.changeName = function() { $scope.firstname = "Nelly"; } $scope.names = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sweden'}, {name:'Kai',country:'Denmark'} ]; }); app.controller("PostsCtrl", function($scope, $http) { $scope.getUsersFromLocal = function() { $http.get('http://www.w3schools.com/angular/customers.php'). success(function(data) { $scope.myData = data; console.log(data); }); }; $scope.getUsersFromLocal(); //call ajax method }); */ //$http.get('resume_angular_employment_history.json'). // When naming a directive, you must use a camel case name, w3TestDirective, but when invoking it, you must use - separated name, w3-test-directive: // <w3-test-directive></w3-test-directive> // <div w3-test-directive></div> // <div class="w3-test-directive"></div> // <!-- directive: w3-test-directive --> /* The legal restrict values are: E for Element name A for Attribute C for Class M for Comment By default the value is EA, meaning that both Element names and attribute names can invoke the directive. */ function writeEmail() { var m = 'paul'; m += '.'; m += 'robotham'; m += '@'; m += 'gmail'; m += '.com'; document.getElementById('emailHref').href = "mailto:" + m; document.getElementById('emailText').innerHTML = m; }<file_sep>/README.md # resume Versions of my resume using different client-side technologies, such as HTML5. CSS3, jQuery, Angular, Bootstrap, React, etc. <file_sep>/resume_jq.js $(document).ready(function() { /* $('.item').mouseenter(function() { $(this).animate({ height: '+=10px' }); }); $('.item').mouseleave(function() { $(this).animate({ height: '-=10px' }); }); */ $('.item').click(function(event) { //$('div').fadeIn(1000); //$(this).toggle(1000); $('.item').fadeTo('fast',1); $(this).fadeTo('fast',0.25); $('section').hide(); link = event.target.id; console.log(link); section = "#" + link.substr(0,link.length-5); console.log(section); $('#contact').show(); $(section).show(); }); $('section').hide(); $('#contact').show(); $('#career_objectives').show(); $('#career_objectives_link').fadeTo('fast',0.25); writeEmail(); }); function writeEmail() { var m = 'paul'; m += '.'; m += 'robotham'; m += '@'; m += 'gmail'; m += '.com'; document.getElementById('emailHref').href = "mailto:" + m; document.getElementById('emailText').innerHTML = m; }<file_sep>/key_skills.html <section id="key_skills"> <h2>Key skills</h2> <ul> <li>Front end: HTML, CSS, JavaScript, jQuery, Angular, Bootstrap</li> <li>Back end: Spring MVC, Serlets, JSP, SOAP, REST, JPA</li> <li>Database/Servers: Tomcat, Glassfish, MySQL, DB2</li> </ul> </section>
926606b46ed6747958466fc16d08bb8b31b2ef1d
[ "JavaScript", "HTML", "Markdown" ]
4
JavaScript
paulm29/resume
34d8713b7009f2569c197120512a2475f48c2049
b3b4e70fd0edae605da7d1661ef4f99862756125
refs/heads/master
<repo_name>fipanther/posprop<file_sep>/load.py """ ____ __ _________ / __ \____ _____ / \/ / ____/ / /_/ / __ \/ ___/ / /\_/ / / / ____/ /_/ (__ ) / / / / /___ /_/ \____/____/ /_/ /_/\____/ Import data <NAME>, Australian National University v. 1.2 """ from __future__ import division, print_function import sys import numpy as np import scipy as sp import math from scipy.integrate import quad import os import matplotlib.pyplot as plt c_dir = os.getcwd() sys.path.append(c_dir) import user_functions as usr # Physical constants required in simulation kbev = 8.6E-5 # Boltzmann constant in units eV/K ec = 4.8E-10 # Electron charge in cgs units hbar = 1.05E-27 # h/2pi in cgs units kberg = 1.3E-16 # Boltzmann constant in cgs units me = 9.11E-28 # Electron mass in cgs units mp = 511E3 # positron rest mass in units eV/c^2 c = 3E10 # speed of light in cgs r0 = 2.82E-13 # classical electron radius in units cm a = 0.0072 # fine structure constant kev = 1E3 # kiloelectronvolts # Load in the H-process cross-sections. Sources discussed in Murphy+2005 #arr_H_ion = np.loadtxt(str(c_dir)+"/h_process/ion_xsec.txt",skiprows=0) #Jones+1993 and Hoffman+1997 #arr_H_ex = np.loadtxt(str(c_dir)+"/h_process/ex_xsec.txt",skiprows=0) #Calc by Kernoghan+1996 and Stein+1998 #arr_H_cx = np.loadtxt(str(c_dir)+"/h_process/cx_extrap.txt",skiprows=0) #Zhou+1997 # ## Load in the He-process cross-sections. Sources discussed in Murpy+2005, update #arr_He_ion = np.loadtxt(str(c_dir)+"/he_process/heion_xsec.txt",skiprows=0) #Jacobsen+1995 #arr_He_ex = np.loadtxt(str(c_dir)+"/he_process/heex_xsec.txt",skiprows=0) #Mori+Sueoka 1994 #arr_He_cx = np.loadtxt(str(c_dir)+"/he_process/hece_xsec.txt",skiprows=0) #Overton+1993 # ## Load in the radiative recombination cross-section (Gould1989) #arr_rad = np.loadtxt(str(c_dir)+"/e_process/radrecomb.txt", skiprows=0) def d_xsec(energy): gamma = 1+((energy)/(mp)) beta = np.sqrt(1-(1/(1+((energy)/mp)))**2) if energy<75*kev: s = ((np.pi*r0**2)/beta)*(2*np.pi*0.0072/beta)/(1-np.exp(-2*np.pi*0.0072/beta)) else: s = (np.pi*r0**2/(4*gamma**2*beta))*(2*(beta**2-2)+((3-beta**4)/beta)*np.log((1+beta)/(1-beta))) return s #d_free = [] #en = np.linspace(1,5000, 1000) #for i in en: # aa = d_xsec(i)*10**5 # d_free.append(aa) # Move these into a separate file - they're fairly redundant # # if you would like to plot the raw cross-sections for these processes, please uncomment the following # ###Helium cross-sections - Log-Log plot ## #plt.figure() #plt.plot(np.log10(arr_He_ion[:,0]),np.log10(arr_He_ion[:,1]), 'r:', lw = 2, label = '$\mathrm{He\,ionization}$') #plt.plot(np.log10(arr_He_ex[:,0]), np.log10(arr_He_ex[:,1]), 'r--', lw = 2, label = '$\mathrm{He\,excitation}$') ##plt.plot(np.log10(arr_He_cx[:,0]), np.log10(arr_He_cx[:,1]), 'r-', label = '$\mathrm{He\,charge\,exchange}$') #plt.title("$\mathrm{Atomic\,cross-sections}$") #plt.xlabel(r"$\log_{10}(E/\mathrm{eV})$", fontsize = '14') #plt.ylabel(r"$\log_{10}(\sigma/\mathrm{cm}^2)$", fontsize = '14') ##plt.legend(loc = 'best', fontsize = '12') ##plt.ylim([-17.2,-15.5]) ##plt.xlim([0.9,2.8]) ##plt.savefig('Hexsec') ## ###Hydrogen cross-sections - Log-Log plot ## ## ##plt.figure() #plt.plot(np.log10(arr_H_ion[:,0]),np.log10(arr_H_ion[:,1]), 'b:' , lw = 2, label = '$\mathrm{H\,ionization}$') #plt.plot(np.log10(arr_H_ex[:,0]), np.log10(arr_H_ex[:,1]), 'b--', lw = 2, label = '$\mathrm{H\,excitation}$') ###plt.plot(np.log10(arr_H_cx[:,0]), np.log10(arr_H_cx[:,1]), 'b-', label = '$\mathrm{H\,charge\,exchange}$') ##plt.plot(np.log10(en), np.log10(d_free), 'c-', label = '$\mathrm{Direct\,annihilation\,(x10}^5)$') ##plt.title("$\mathrm{Hydrogen\,cross-sections}$") ##plt.xlabel(r"$\log_{10}(E/\mathrm{eV})$") ##plt.ylabel(r"$\log_{10}(\sigma/\mathrm{cm}^2)$") #plt.legend(loc = 'best', fontsize = '12') #plt.ylim([-17.2,-15.5]) #plt.xlim([0.9,2.8]) #plt.savefig('Hxsec') # # # # Load the rates at thermalization as a function of temperature #arr_df = np.loadtxt(str(c_dir)+"/rates_data/rate_dfree.txt",skiprows=0) #Crannell et al #arr_hcx = np.loadtxt(str(c_dir)+"/rates_data/rate_hcx.txt",skiprows=0) #Computed from x-sec above #arr_hdb = np.loadtxt(str(c_dir)+"/rates_data/rate_hdab.txt",skiprows=0) #Murphy+2005 #arr_hedb = np.loadtxt(str(c_dir)+"/rates_data/rate_hedab.txt",skiprows=0) #Murphy+2005 #arr_rr = np.loadtxt(str(c_dir)+"/rates_data/rate_rr.txt",skiprows=0) #<NAME>, private communication #arr_hecx = np.loadtxt(str(c_dir)+"/rates_data/rate_hece.txt",skiprows=0) #Murphy+2005 # # # ## Move these to a new file ## Normalized rates: Log-Log plot # #plt.figure #plt.plot(np.log10(arr_df[:,1]),np.log10(arr_df[:,0]), 'r-' ,lw = 2, label = 'Direct free') #plt.plot(np.log10(arr_hcx[:,0]), np.log10(arr_hcx[:,1,]), 'b--',lw = 2, label = 'Charge exchange w/ H') #plt.plot(np.log10(arr_hdb[:,0]), np.log10(arr_hdb[:,1]), 'c:', lw = 2, label = 'Direct bound H') #plt.plot(np.log10(arr_hedb[:,0]), np.log10(arr_hedb[:,1]), 'y-', lw = 2, label = 'Direct bound He') #plt.plot(np.log10(arr_rr[:,0]), np.log10(arr_rr[:,1]), 'g-', lw = 2, label = 'Radiative Recombination') #plt.plot(np.log10(arr_hecx[:,0]), np.log10(arr_hecx[:,1]), 'y--', lw = 2, label = 'CX on He') #plt.title("reaction rates/target density") #plt.xlabel("log(T/K)") #plt.ylabel("log($\mathrm{cm}^3$/$\mathrm{s}$)") #plt.legend(loc = 'best') #plt.xlim([2,8]) #plt.ylim([-19,-5]) #plt.show() # # initialize the formulae to calculate the energy loss processes # # dE_io - ionization continuum losses # dE_pl - plasma losses # dE_sy - synchrotron losses # dE_br - bremsstrahlung losses # dE_ic - inverse Compton losses # # ionization continuum losses (ref. Prantzos et al. 2011) def dE_io(energy, n_neu, Z, e_ion): """ Ionization continuum losses due to interactions with neutral atoms with density n_neu of species Z with ionization energy e_ion """ if energy>e_ion: return (7.7E-9)*(n_neu*Z/usr.rel_bet(energy, mp))*(np.log((usr.rel_gam(energy, mp)-1)*((usr.rel_gam(energy, mp)*usr.rel_bet(energy, mp)*mp)**2)/(2*e_ion**2))+(1/8)) else: return 0 def dE_pl(energy, ne_free, temperature): """ Plasma continuum losses due to e+ interactions with free electrons with density ne_free in plasma of T = temperature """ if ne_free == 0: """ Avoid weird NaNs if there are no free electrons """ rt = 0 elif energy>=1E3 or temperature >= 1E4: """ For high energies and temperatures, just use the approximation from Prantzos+2011 """ rt = ((7.7/2.1)*10**-9)*(ne_free/usr.rel_bet(energy, mp))*(np.log(usr.rel_bet(energy, mp)/ne_free)+73.6) elif energy<1E3 or temperature < 1E4: """ For low energies and temperatures, use the full plasma losses formula from Huba 2004 (NRL Plasma Formulary) """ u = abs(np.sqrt(2*energy/mp)-np.sqrt((8*kbev*temperature)/(np.pi*mp))) rmax = np.sqrt(kberg*temperature/(4*np.pi*ne_free*(ec**2))) if (ec**2/(me*u**2))>hbar/(2*me*u): rmin =(ec**2/(me*u**2)) else: rmin =hbar/(2*me*u) cl = np.log(rmax/rmin) funcint = lambda x: ((x**(1/2))*math.exp(-x))-(((energy/(kbev*temperature))**(1/2))*math.exp(-energy/kbev*temperature)) integ = quad(funcint,0,(energy/(kbev*temperature))) rt =((1.7*10**-8))*(ne_free/usr.rel_bet(energy, mp))*cl*integ[0] return rt def dE_sy(energy, B): """ Synchrotron losses (ref Blumenthal & Gould 1970) - B is specified in microGauss, averaged over pitch angle """ return (9.9E-16)*B**2*usr.rel_gam(energy, mp)**2*usr.rel_bet(energy, mp)**2*(2/3) def dE_bri(energy, n_ion, Z): """ Bremsstrahlung energy losses from a fully ionized gas of species Z with density n_ion """ return (3.6E-11)*Z*(Z+1)*n_ion*usr.rel_gam(energy, mp)*(np.log(2*usr.rel_gam(energy, mp))-0.33) def dE_brn(energy, nH, nHe, xH, xHe, xHe2): """ Bremsstrahlung energy losses from a neutral gas with total H density nH and total He density nHe with ionization fractions xH, xHe and xHe2 """ return ((4.1E-10)*(1-xH)*nH*usr.rel_gam(energy,mp))+((1.1E-9)*(1-xHe-xHe2)*nHe*usr.rel_gam(energy, mp)) def dE_ic(energy, urad): """ Inverse Compton energy losses in radiation field with density urad - use the CMB field as a default. Blumenthal+Gould 1970 """ return (2.6E-14)*urad*(usr.rel_gam(energy, mp)**2)*(usr.rel_bet(energy, mp)**2) def de_ad(energy, time, r_0, rho_now, rho_prev, vel, mass = 511E3): """ Calculates the adiabatic energy loss rate as a function of time """ amu = 1.67E-24 msun = 1.989E33 yrs = 24*3600*365.25 kpc = 3.086E21 v = vel*100*1000 g = usr.adiabatic_gamma(energy, mass) r = r_0*kpc de_ad_out = (((2**(2-g))*2*v*rho_now*energy*(g-1))/(rho_prev*(r+(v*time))))*((2*rho_now/rho_prev)**(g-2)) return de_ad_out <file_sep>/user_functions.py """ ____ __ _________ / __ \____ _____ / \/ / ____/ / /_/ / __ \/ ___/ / /\_/ / / / ____/ /_/ (__ ) / / / / /___ /_/ \____/____/ /_/ /_/\____/ User-defined functions by <NAME> Australian National University """ from __future__ import division, print_function import numpy as np def find_nearest(array, value): """ Finds the nearest value to one given in an array """ idx = (np.abs(array-value)).argmin() return idx, array[idx] def rel_gam(energy, mass): """ Relativistic gamma for particle of given mass and kinetic energy """ return 1+(energy/mass) def rel_bet(energy, mass): """ Relativisitc beta for particle of given mass and kinetic energy """ return np.sqrt(1-(1/(1+((energy)/mass)))**2) def find_first(array, value): """ finds the first instance of a value in an array and returns the index """ for i in range(len(array)): if array[i]==value: out = i break return out def adiabatic_gamma(energy, mass = 511E3): # Thanks to <NAME> """ Calculates adiabatic index as a function of energy """ gamma_out = 1 + (1/3*(rel_bet(energy, mass)**2))/((1 - np.sqrt(1 - rel_bet(energy, mass)**2))) return gamma_out <file_sep>/par_init.py """ ____ __ _________ / __ \____ _____ / \/ / ____/ / /_/ / __ \/ ___/ / /\_/ / / / ____/ /_/ (__ ) / / / / /___ /_/ \____/____/ /_/ /_/\____/ Initialize and update parameters <NAME>, Australian National University v. 1.2 """ from __future__ import division, print_function import sys import numpy as np from scipy.interpolate import interp1d import matplotlib import matplotlib.pyplot as plt import os matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) matplotlib.rcParams.update({'font.size': 22}) c_dir = os.getcwd() sys.path.append(c_dir) import user_functions as usr import load as ld # Import the external simulation information s_yr = 3.15576*10**7 timing_ext = np.linspace(0, 1E6*s_yr, 1E3) #arr_nesim = [1]*100000 #arr_nHsim = [1000]*100000 arr_nHesim = [0]*100000 arr_xHsim = [0.01]*100000 arr_xHesim = [0]*100000 arr_xHe2sim = [0]*100000 arr_temperaturesim = [8000]*100000 arr_Bsim = [50]*100000 arr_rhosim = [1E-25]*100000 model_parameters = [0.100, 500] # Initialize the simulation def initialize_MCmp(paramset, arrays0, arrays1, arrays2, arrays3, arrays4, arrays5, arrays6, arrays7, arraystime, arrays8): """ Initialize the data arrays for each MC particle Parameters: paramset: tuple length 9 containing the first value in the arrays from the external simulation [E, H, He, xH, xHe, xHe2, T, B, rho] """ if not arrays0: arrays0.append(paramset[0]) if not arrays1: arrays1.append(paramset[1]) if not arrays2: arrays2.append(paramset[2]) if not arrays3: arrays3.append(paramset[3]) if not arrays4: arrays4.append(paramset[4]) if not arrays5: arrays5.append(paramset[5]) if not arrays6: arrays6.append(paramset[6]) if not arrays7: arrays7.append(paramset[7]) if not arraystime: arraystime.append(0) if not arrays8: arrays8.append(paramset[8]) return def dumparr(arrays0, arrays1, arrays2, arrays3, arrays4, arrays5, arrays6, arrays7, arrays8, arraystime, timeidx): """ Dump the data arrays at the end of the particle's life (deprecated) """ del arrays0[:], arrays1[:], arrays2[:], arrays3[:], arrays4[:], arrays5[:], arrays6[:], arrays7[:], arrays8[:], arraystime[:] timeidx = 0 return # Update the energy def update_epacket(current_energy, energy_lost, arrname): return arrname.append(current_energy - energy_lost) # Update the time def update_timing(dt, tnow, arrname): return arrname.append(tnow+dt) # Update the ISM parameters add in rho def update_params(dt, idx_now, idx_next, arrays1, arrays2, arrays3, arrays4, arrays5, arrays6, arrays7, arrays8, time_sim, time_ext, sim_nH): """ Updates the ISM parameters after a timestep. """ # Set the times as parameters inside function t_now = time_sim[idx_now] t_next = time_ext[idx_next] t_up = time_sim[idx_now]+dt t_mid = t_now+((t_next-t_now)/2) if t_up <t_mid: """ If the updated time is closer to the current time than the end of the external timestep, stick with the ISM parameters from the previous timestep """ nH_next = arrays1[idx_now] nHe_next = arrays2[idx_now] xH_next = arrays3[idx_now] xHe_next = arrays4[idx_now] xHe2_next = arrays5[idx_now] T_next = arrays6[idx_now] B_next = arrays7[idx_now] rho_next = arrays8[idx_now] elif t_up > t_mid: """ If the updated time is closer to the end of the external timestep than the beginning, use the ISM parameters from the beginning of the next external timestep """ nH_next = sim_nH[idx_next] nHe_next = arr_nHesim[idx_next] xH_next = arr_xHsim[idx_next] xHe_next = arr_xHesim[idx_next] xHe2_next = arr_xHe2sim[idx_next] T_next = arr_temperaturesim[idx_next] B_next = arr_Bsim[idx_next] rho_next = arr_rhosim[idx_next] elif t_up == t_mid: """ If the updated time is right in the middle, use the ISM parameters from the beginning of the next external timestep. This is a separate elif statememt because for some reason having it in the same elif statement as either of the others (>= or <=) seems to break the simulation. Probably some Python thing? """ nH_next = sim_nH[idx_next] nHe_next = arr_nHesim[idx_next] xH_next = arr_xHsim[idx_next] xHe_next = arr_xHesim[idx_next] xHe2_next = arr_xHe2sim[idx_next] T_next = arr_temperaturesim[idx_next] B_next = arr_Bsim[idx_next] rho_next = arr_rhosim[idx_now] return arrays1.append(float(nH_next)), arrays2.append(float(nHe_next)), arrays3.append(float(xH_next)), arrays4.append(float(xHe_next)), arrays5.append(float(xHe2_next)), arrays6.append(float(T_next)), arrays7.append(float(B_next)), arrays8.append(float(rho_next)) def X_ism(arrays0, arrays1, arrays2, arrays3, arrays4, arrays5, arrays6, arrays7, arrays8): """ Read in the current parameters from the arrays """ energy = arrays0[len(arrays0)-1] n_H = arrays1[len(arrays0)-1] n_He = arrays2[len(arrays0)-1] x_H = arrays3[len(arrays0)-1] x_He = arrays4[len(arrays0)-1] x_He2 = arrays5[len(arrays0)-1] T = arrays6[len(arrays0)-1] B = arrays7[len(arrays0)-1] rho = arrays8[len(arrays0)-1] return [energy, n_H, n_He, x_H, x_He, x_He2, T, B, rho] def Hxsec(energy, nH_neu): """ Load the hydrogen cross sections into a convenient array """ if nH_neu ==0: """ Avoid those pesky NaN's if there are no neutral hydrogen atoms """ return [0,0,0] else: temp = usr.find_nearest(ld.arr_H_ion[:,0], energy) if energy<14.6648 or energy> 684.091: xsec_Hi = 0 else: xsec_Hi = ld.arr_H_ion[temp[0],1] temp = usr.find_nearest(ld.arr_H_ex[:,0], energy) if energy<9.977 or energy>597.605: xsec_Hex = 0 else: xsec_Hex = ld.arr_H_ex[temp[0],1] temp = usr.find_nearest(ld.arr_H_cx[:,0], energy) if energy<6.87 or energy>960: xsec_Hc = 0 else: xsec_Hc = ld.arr_H_cx[temp[0],1] return [xsec_Hi, xsec_Hex, xsec_Hc] # Load the current helium cross sections into a convenient array def Hexsec(energy, nHe_neu): """ Load the helium cross sections into a convenient array """ if nHe_neu==0: """ Avoid those pesky NaNs if there are no neutral helium atoms """ return [0,0,0] else: temp = usr.find_nearest(ld.arr_He_ion[:,0], energy) if energy<31.97 or energy>985.959: xsec_Hei = 0 else: xsec_Hei = ld.arr_He_ion[temp[0],1] temp = usr.find_nearest(ld.arr_He_ex[:,0], energy) if energy<23.09 or energy>1045.4: xsec_Heex = 0 else: xsec_Heex = ld.arr_He_ex[temp[0],1] temp = usr.find_nearest(ld.arr_He_cx[:,0], energy) if energy<18.94 or energy>995.66: xsec_Hec = 0 else: xsec_Hec = ld.arr_He_cx[temp[0],1] return [xsec_Hei, xsec_Heex, xsec_Hec] def d_xsec(energy): """ define the direct annihilation x-section """ if energy<70*ld.kev: """ At low energies, use the classical x-sec with quantum correction factor """ return (np.pi*ld.r0**2/(usr.rel_bet(energy, ld.mp)))*((2*np.pi*ld.a/usr.rel_bet(energy, ld.mp))/(1-np.exp(-2*np.pi*ld.a/usr.rel_bet(energy, ld.mp)))) else: """ At high energies use the Dirac cross-section """ return (np.pi*ld.r0**2/(usr.rel_gam(energy, ld.mp)+1))*(((usr.rel_gam(energy, ld.mp)**2 + 4*usr.rel_gam(energy,ld.mp) + 1)/(usr.rel_gam(energy, ld.mp)**2 - 1))*np.log(usr.rel_gam(energy, ld.mp)+ np.sqrt(usr.rel_gam(energy, ld.mp)**2 - 1)) - ((usr.rel_gam(energy, ld.mp) + 3)/(np.sqrt(usr.rel_gam(energy, ld.mp)**2 - 1)))) def norm_xsec(energy, nH_tot, nHe_tot, x_H, x_He, x_He2): """ Total normalized interaction cross-section """ nH_neu = (1-x_H)*nH_tot nHe_neu = (1-x_He-x_He2)*nHe_tot ne = (nH_tot)+(2*nHe_tot) norm_H = nH_neu*sum(Hxsec(energy, nH_neu)) norm_He = nHe_neu*sum(Hexsec(energy, nHe_neu)) norm_e = ne*d_xsec(energy) return norm_H+norm_He+norm_e # DO THIS ## Load the current thermalized annihilation rates at current temperature into a convenient array #def arr_rate(temperature, n_e, n_H, n_He, x_H, x_He, x_He2): # # Multiply out the density factor in this to simplify the do_science run # # Direct-free annihilation # temp = usr.find_nearest(ld.arr_df[:,1],temperature) # if temperature>1E8 or n_e ==0: # r_df = 0 # else: # r_df = n_e*ld.arr_df[temp[0], 0] # # temp = usr.find_nearest(ld.arr_rr[:,0],temperature) # if temperature>1E8 or n_e==0: # r_rr = 0 # else: # r_rr = n_e*ld.arr_rr[temp[0],1] # # grid isn't fine enough on radiative recomb. # # temp = usr.find_nearest(ld.arr_hcx[:,0],temperature) # if temperature<1994 or temperature>1E8: # r_hcx = 0 # else: # r_hcx = n_H*(1-x_H)*ld.arr_hcx[temp[0],1] # # temp = usr.find_nearest(ld.arr_hecx[:,0], temperature) # if temperature<5843 or temperature>1E8: # r_hecx = 0 # else: # r_hecx = n_He*(1-x_He-x_He2)*ld.arr_hecx[temp[0],1] # # temp = usr.find_nearest(ld.arr_hdb[:,0], temperature) # if temperature >1E4: # r_hdb = 0 # else: # r_hdb = n_H*(1-x_H)*ld.arr_hdb[temp[0],1] # # temp = usr.find_nearest(ld.arr_hedb[:,0], temperature) # if temperature>1E8: # r_hedb = 0 # else: # r_hedb = n_He*(1-x_He*x_He2)*ld.arr_hedb[temp[0],1] # # return [r_df, r_rr, r_hcx, r_hecx, r_hdb, r_hedb] def eloss_rate(energy, nH_tot, nHe_tot, x_H, x_He, x_He2, B, temperature): """ energy loss rates """ nH_neu = (1-x_H)*nH_tot nHe_neu = (1-x_He-x_He2)*nHe_tot ne = (x_H*nH_tot)+((x_He+2*x_He2)*nHe_tot) if energy>13.8: ion = ld.dE_io(energy, nH_neu, 1, 13.8)+ld.dE_io(energy, nHe_neu, 2, 20) else: ion = 0 pla = ld.dE_pl(energy, ne, temperature) syn = ld.dE_sy(energy, B) bre = ld.dE_bri(energy, x_H*nH_tot, 1)+ld.dE_bri(energy, (x_He+2*x_He2)*nHe_tot, 2) + ld.dE_brn(energy, nH_neu, nHe_neu, x_H, x_He, x_He2) ic = ld.dE_ic(energy, 0.26) return [ion, abs(pla), syn, bre, ic, (ion+pla+syn+bre+ic)] # ene = np.logspace(0, 12, 1E3) # ion = [] # pl = [] # syn = [] # bre = [] # ic = [] # for i in ene: # ion.append(eloss_rate(i, 1, 0, 0.1, 0, 0, 10, 8000)[0]) # pl.append(abs(eloss_rate(i, 1, 0, .1, 0, 0, 10, 8000)[1])) # syn.append(eloss_rate(i, 1, 0, 0.1, 0, 0, 10, 8000)[2]) # bre.append(eloss_rate(i, 1, 0, 0.1, 0, 0, 10, 8000)[3]) # ic.append(eloss_rate(i, 1, 0, 0.1, 0, 0, 10, 8000)[4]) # plt.figure(figsize = (20,10)) # plt.plot(ene, pl, 'k-',lw = 2 ,label = '$\mathrm{Plasma}$') # plt.plot(ene, ion, 'k--', lw = 2 ,label = '$\mathrm{Ionization}$') # plt.plot(ene, syn, 'k:',lw = 2 ,label = '$\mathrm{Synchrotron\,(10\mu G)}$') # plt.plot(ene, bre, 'k-', lw = 2 ,linestyle='dashdot',label = '$\mathrm{Bremsstrahlung\,(total)}$') # line, = plt.plot(ene, ic, 'k-', lw = 2 ,label = '$\mathrm{Inverse\,Compton}$') # line.set_dashes([8, 4, 2, 4, 2, 4]) # plt.ylim([1E-17, 1E-2]) # plt.xscale('log') # plt.yscale('log') # plt.tick_params(axis='both', which='major', labelsize=28) # plt.xlabel('$\log[\mathrm{energy/eV}]$', fontsize=35) # plt.ylabel('$\log[dE/dt\,/\mathrm{s/eV}]$', fontsize=35) # plt.legend(loc = 'best', fontsize = 28) # plt.tight_layout() # plt.savefig('energyloss.pdf',bbox_inches='tight',format='pdf')
2d61451ac360bad58555b7732d9fd2e600642459
[ "Python" ]
3
Python
fipanther/posprop
c0e568f53a479be76a35751757bc12bb9f8a753c
af219e46c15703c2c069d1e3afcf954a446dd409
refs/heads/master
<file_sep><?php class Ukm extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('cookie'); $this->load->helper('url'); $this->load->helper('form'); $this->load->model('ukm_model'); $this->load->model('data_model'); } public function buat_proposal() { if (get_cookie('user_id') == NULL || get_cookie('jenis_user') == 'funder') { echo "Anda tidak bisa membuat proposal.<br>"; echo "Silakan <a href='../masuk'>Masuk</a> atau <a href='../daftar'>Daftar</a> terlebih dahulu."; } else { $data_user = $this->data_model->get_user(get_cookie('user_id')); $data['user'] = $data_user->result_array()[0]['nama']; $this->load->view('header-ukm', $data); $this->load->view('buat-proposal'); $this->load->view('footer'); } } public function daftar() { if (get_cookie('user_id') == NULL || get_cookie('jenis_user') == 'funder') { echo "Anda belum login atau anda tidak mendaftar sebagai UKM.<br>"; echo "Silakan <a href='../masuk'>Masuk</a> atau <a href='../daftar'>Daftar</a> terlebih dahulu."; } else { $data_user = $this->data_model->get_user(get_cookie('user_id')); $data['user'] = $data_user->result_array()[0]['nama']; $data['list_sektor'] = $this->data_model->get_list_sektor(); $data['list_bentuk_usaha'] = $this->data_model->get_bentuk_usaha(); $this->load->view('header-ukm', $data); $this->load->view('daftar-ukm', $data); $this->load->view('footer'); } } public function daftar_pemilik() { if (get_cookie('user_id') == NULL || get_cookie('jenis_user') == 'funder') { echo "Anda belum login atau anda tidak mendaftar sebagai UKM.<br>"; echo "Silakan <a href='../masuk'>Masuk</a> atau <a href='../daftar'>Daftar</a> terlebih dahulu."; } else { $data_user = $this->data_model->get_user(get_cookie('user_id')); $data['user'] = $data_user->result_array()[0]['nama']; $data['list_provinsi'] = $this->data_model->get_list_provinsi(); $this->load->view('header-ukm', $data); $this->load->view('daftar-pemilik-ukm', $data); $this->load->view('footer'); } } public function proses_pendaftaran() { if (get_cookie('user_id') == NULL || get_cookie('jenis_user') == 'funder') { echo "Anda belum login atau anda tidak mendaftar sebagai UKM.<br>"; echo "Silakan <a href='../masuk'>Masuk</a> atau <a href='../daftar'>Daftar</a> terlebih dahulu."; } else { $this->ukm_model->proses_pendaftaran(); redirect('ukm/daftar_pemilik', 'refresh'); } } public function proses_pendaftaran_pemilik() { if (get_cookie('user_id') == NULL || get_cookie('jenis_user') == 'funder') { echo "Anda belum login atau anda tidak mendaftar sebagai UKM.<br>"; echo "Silakan <a href='../masuk'>Masuk</a> atau <a href='../daftar'>Daftar</a> terlebih dahulu."; } else { $this->ukm_model->proses_pendaftaran_pemilik(); redirect('index.php', 'refresh'); } } public function proses_proposal() { if (get_cookie('user_id') == NULL || get_cookie('jenis_user') == 'funder') { echo "Anda belum login atau anda tidak mendaftar sebagai UKM.<br>"; echo "Silakan <a href='../masuk'>Masuk</a> atau <a href='../daftar'>Daftar</a> terlebih dahulu."; } else { $this->ukm_model->proses_proposal(); redirect('index.php', 'refresh'); } } public function lihat_proposal($id_proposal=NULL) { if ($id_proposal === NULL) { show_404(); } else { $data_user = $this->data_model->get_user(get_cookie('user_id')); $data_proposal = $this->data_model->get_proposal($id_proposal); $id_ukm = $data_proposal->result_array()[0]['id_ukm']; $data['user'] = $data_user->result_array()[0]['nama']; $data['proposal'] = $data_proposal; $data['jenis_user'] = get_cookie('jenis_user'); $data['ukm'] = $this->data_model->get_user($id_ukm)->result_array()[0]['nama']; $data['pendanaan'] = $this->data_model->get_pendanaan($id_proposal)->result_array()[0]; if (get_cookie('jenis_user') == 'ukm') { $this->load->view('header-ukm', $data); } else if (get_cookie('jenis_user') == 'funder') { $this->load->view('header-funder', $data); } else { $this->load->view('header'); } $this->load->view('lihat-proposal', $data); $this->load->view('footer'); } } public function kelola_proposal($id_proposal=NULL) { if ($id_proposal === NULL) { show_404(); } else { $data_user = $this->data_model->get_user(get_cookie('user_id')); $data['user'] = $data_user->result_array()[0]['nama']; $data['pendanaan'] = $this->data_model->get_pendanaan($id_proposal)->result_array()[0]; $data['proposal'] = $this->data_model->get_detail_proposal($id_proposal); $this->load->view('header-ukm', $data); $this->load->view('kelola-proposal', $data); $this->load->view('footer'); } } } ?><file_sep><?php class User extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('user_model'); $this->load->model('data_model'); $this->load->helper('cookie'); $this->load->helper('form'); $this->load->helper('url'); } public function daftar() { $this->load->helper('url'); $data['list_provinsi'] = $this->data_model->get_list_provinsi(); $this->load->view('header'); $this->load->view('daftar', $data); $this->load->view('footer'); } public function masuk() { $this->load->view('header'); $this->load->view('masuk'); $this->load->view('footer'); } public function keluar() { delete_cookie('user_id'); delete_cookie('jenis_user'); redirect('index.php', 'refresh'); } public function proses_daftar() { $proses_sukses = $this->user_model->proses_daftar(); if ($proses_sukses == '1') { echo "Akun berhasil dibuat. Silakan gunakan akun untuk <a href='../masuk'>masuk</a> ke UKMJaya"; } else { echo "Gagal membuat akun. <a href='../daftar'>Kembali</a>"; } } public function proses_masuk() { $user = $this->user_model->proses_masuk(); if ($user == 0) { echo "Gagal masuk ke akun. <a href='../masuk'>Kembali</a>"; } else { if ($user[0]['id_funder'] == NULL) { set_cookie('user_id', $user[0]['id_ukm'], 3600, 'localhost'); set_cookie('jenis_user', 'ukm', 3600, 'localhost'); } else { set_cookie('user_id', $user[0]['id_funder'], 3600, 'localhost'); set_cookie('jenis_user', 'funder', 3600, 'localhost'); } redirect('index.php', 'refresh'); } } public function danai_proposal() { } } ?><file_sep><?php class Ukm_model extends CI_Model { public function __construct() { $this->load->database(); $this->load->helper('cookie'); $this->load->helper('string'); } public function proses_pendaftaran() { $data_ukm = array( 'id_ukm' => get_cookie('user_id'), 'sektor' => $this->input->post('sektor_usaha'), 'subsektor' => $this->input->post('sub_sektor_usaha'), 'jenis' => $this->input->post('jenis_usaha'), 'bentuk' => $this->input->post('bentuk_usaha'), 'jumlah_aset' => $this->input->post('jumlah_aset'), 'jumlah_omzet' => $this->input->post('jumlah_omzet'), 'alamat' => $this->input->post('alamat_usaha'), 'desa_kel' => $this->input->post('desa_kel_usaha'), 'kecamatan' => $this->input->post('kecamatan_usaha'), 'kode_pos' => $this->input->post('kode_pos') ); $this->db->insert('data_ukm', $data_ukm); } public function proses_pendaftaran_pemilik() { $data_pemilik = array( 'id_ukm' => get_cookie('user_id'), 'nama' => $this->input->post('nama'), 'no_ktp' => $this->input->post('no_ktp'), 'alamat_rt_rw' => $this->input->post('alamat'), 'desa_kel' => $this->input->post('desa_kel'), 'kecamatan' => $this->input->post('kecamatan'), 'provinsi' => $this->input->post('provinsi'), 'kab_kota' => $this->input->post('kab_kota'), 'kode_pos' => $this->input->post('kode_pos'), 'no_telepon' => $this->input->post('no_tlp'), 'no_hp' => $this->input->post('no_hp') ); $this->db->insert('data_pemilik_ukm', $data_pemilik); } public function proses_proposal() { $batas_waktu = $this->input->post('batas_waktu'); $waktu_penggunaan = $this->input->post('waktu_penggunaan'); $waktu_pengembalian = $this->input->post('waktu_pengembalian'); if (strtotime($batas_waktu) < strtotime($waktu_penggunaan) && strtotime($batas_waktu) < strtotime($waktu_pengembalian) && strtotime($waktu_penggunaan) < strtotime($waktu_pengembalian)) { $id_proposal = random_string('nozero', 15); $data_proposal = array( 'id_proposal' => $id_proposal, 'id_ukm' => get_cookie('user_id'), 'kebutuhan_dana' => $this->input->post('kebutuhan_dana'), 'konten' => $this->input->post('alasan'), 'batas_waktu' => $this->input->post('batas_waktu'), 'waktu_penggunaan' => $this->input->post('waktu_penggunaan'), 'waktu_pengembalian' => $this->input->post('waktu_pengembalian') ); $this->db->insert('proposal', $data_proposal); $jenis = $this->input->post('jenis'); foreach ($this->input->post('jumlah') as $key => $j) { $data_hadiah = array( 'id_hadiah' => random_string('nozero', 17), 'id_proposal' => $id_proposal, 'hadiah' => $jenis[$key], 'minimal_pinjaman' => $j ); $this->db->insert('hadiah_proposal', $data_hadiah); } } } } ?><file_sep><?php class Funder_model extends CI_Model { public function __construct() { $this->load->database(); } public function proses_pendanaan($id_funder) { $data_dana = array( 'id_funder' => $id_funder, 'id_proposal' => $this->input->post('id_proposal'), 'jumlah' => $this->input->post('jumlah'), 'waktu_pendanaan' => date('Y-m-d H:i:s'), 'id_hadiah' => $this->input->post('pilihan_hadiah') ); $this->db->insert('dana', $data_dana); } } ?><file_sep> <script src="<?php echo base_url('/resources/jquery/jquery/dist/jquery.js') ?>"></script> <script type="text/javascript"> var i = 1; function tambah_hadiah() { $('#hadiah').append('<div style="background-color: #18BC9C; padding: 15px; margin-bottom: 5px;" id="hadiah-'.concat(i).concat('"><button type="button" class="btn" style="background-color:white;padding:0 4px; float:right;" onclick="hapus_hadiah(\'#hadiah-').concat(i).concat('\')"><span class="glyphicon glyphicon-remove" style="color:#18BC9C;"></span></button><p class="label-form">Untuk jumlah pinjaman</p><p class="label-form"> Rp <input type="text" name="jumlah[]" style="color:black; width:70%;"> atau lebih</p><p class="label-form">Hadiah yang diberikan</p><textarea style="width:100%; color:black;" rows="3" name="jenis[]"></textarea></div>')); i = i+1; } function hapus_hadiah(id) { $(id).remove(); } </script> <style> .label-form { text-align: left; font-size: 14px; } .label-hadiah { margin-bottom: 0px; } </style> <!-- Buat Proposal --> <header> <div class="container" style="padding-top: 150px;"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8" style="background-color:#2C3E50; padding-left: 35px; padding-right: 35px; padding-top: 15px; padding-bottom: 15px;"> <h3 style="text-align: center; margin-bottom: 30px;">Buat Proposal Pendanaan</h3> <?php echo form_open('ukm/proses_proposal'); ?> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Kebutuhan Dana (Rp.)</p> <input type="text" name="kebutuhan_dana" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Jelaskan kenapa anda membutuhkan dana tersebut</p> <textarea name="alasan" class="form-control" rows="10"></textarea> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Batas Waktu Pendanaan Proposal</p> <div class="col-md-6" style="padding:0px;"> <input type="date" name="batas_waktu" class="form-control buat-proposal"> </div> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Batas Waktu Penggunaan Dana dan Pembuatan Hadiah</p> <div class="col-md-6" style="padding:0px;"> <input type="date" name="waktu_penggunaan" class="form-control buat-proposal"> </div> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Batas Waktu Pengembalian Dana Pinjaman dan Pengiriman Hadiah</p> <div class="col-md-6" style="padding:0px;"> <input type="date" name="waktu_pengembalian" class="form-control buat-proposal"> </div> </div> </div> <div class="row control-group" style="margin-bottom: 20px;"> <div class="form-group col-xs-12"> <p class="label-form">Pilihan Hadiah</p> <div id="hadiah"> </div> <p style="font-size:14px; text-align: right;">Tambah Pilihan Hadiah <button type="button" class="btn" style="background-color: white;" onclick="tambah_hadiah()"> <span class="glyphicon glyphicon-plus" style="color:#18BC9C;"></span> </button> </p> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <input type="submit" class="form-control" value="Buat Proposal" style="width:115px; margin:0px auto; display:block;"> </div> </div> </form> </div> </div> </div> </header><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->load->helper('url'); $this->load->helper('cookie'); $this->load->model('data_model'); $data['proposal_populer'] = $this->data_model->get_proposal_populer(); if (get_cookie('user_id') == NULL) { $this->load->view('header'); $this->load->view('index', $data); } else { $data_user = $this->data_model->get_user(get_cookie('user_id')); $data['user'] = $data_user->result_array()[0]['nama']; if (get_cookie('jenis_user') == 'ukm') { $this->load->view('header-ukm', $data); $check_user = $this->data_model->check_ukm(get_cookie('user_id')); if ($check_user->result_array()[0]['ada_data_ukm'] == 0 && $check_user->result_array()[0]['ada_data_pemilik'] == 0 ) { $this->load->view('index-ukm-baru'); } else { $data['ukm'] = $this->data_model->get_data_ukm(get_cookie('user_id')); $data['pemilik_ukm'] = $this->data_model->get_pemilik_ukm(get_cookie('user_id')); $data['proposal_ukm'] = $this->data_model->get_proposal_ukm(get_cookie('user_id')); $this->load->view('index-ukm', $data); } } else { $this->load->view('header-funder', $data); $this->load->view('index'); } } $this->load->view('footer'); } } <file_sep> <script src="<?php echo base_url('/resources/jquery/jquery/dist/jquery.js') ?>"></script> <script type="text/javascript"> $(document).ready(function() { $('#sektor_usaha').change(function() { $('#sub_sektor > option').remove(); var id_sektor = $('#sektor_usaha').val(); $.ajax({ type: "POST", url : "http://localhost/ukmjaya/data/get_sub_sektor/"+id_sektor, success : function(sektor) { $.each(sektor, function(id,name) { var opt = $('<option/>'); opt.val(id); opt.text(name); $('#sub_sektor').append(opt); }); } }); }); }); </script> <style> .label-form { text-align: left; font-size: 14px; } </style> <header> <div class="container" style="padding-top: 150px;"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8" style="background-color:#2C3E50; padding-left: 35px; padding-right: 35px; padding-top: 15px; padding-bottom: 15px;"> <h3 style="text-align: center; margin-bottom: 30px;">Pendaftaran UKM</h3> <?php echo form_open('ukm/proses_pendaftaran'); ?> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Sektor Usaha</p> <?php $sektor_usaha[''] = "Pilih Sektor"; foreach($list_sektor->result() as $row) { $sektor_usaha[$row->id] = $row->nama; } echo form_dropdown('sektor_usaha', $sektor_usaha, '', 'id="sektor_usaha" class="form-control"'); ?> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Sub Sektor Usaha</p> <?php $sub_sektor_usaha[''] = "Pilih Sub Sektor"; echo form_dropdown('sub_sektor_usaha', $sub_sektor_usaha, '', 'id="sub_sektor" class="form-control"'); ?> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Jenis Usaha</p> <input type="text" name="jenis_usaha" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Bentuk Usaha</p> <?php $bentuk_usaha[''] = "Pilih Bentuk Usaha"; foreach($list_bentuk_usaha->result() as $row) { $bentuk_usaha[$row->id] = $row->nama; } echo form_dropdown('bentuk_usaha', $bentuk_usaha, '', 'class="form-control"'); ?> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Jumlah Aset</p> <input type="text" name="jumlah_aset" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Jumlah Omzet</p> <input type="text" name="jumlah_omzet" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Alamat Lengkap Usaha</p> <input type="text" name="alamat_usaha" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Desa/Kelurahan Usaha</p> <input type="text" name="desa_kel_usaha" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Kecamatan Usaha</p> <input type="text" name="kecamatan_usaha" class="form-control"> </div> </div> <div class="row control-group" style="margin-bottom: 20px;"> <div class="form-group col-xs-12"> <p class="label-form">Kode Pos Usaha</p> <input type="text" name="kode_pos" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <input type="submit" class="form-control" value="Lanjut" style="width:106px; margin:0px auto; display:block;"> </div> </div> </form> </div> </div> </div> </header><file_sep> <style> .proposal { text-align: left; font-size:18px; } .timeline { font-size:16px; } .left { text-align:left; } .right { text-align: right; } </style> <!-- Lihat Proposal --> <header> <?php foreach ($proposal->result() as $row) { ?> <div class="container" style="padding-top: 100px;"> <div class="row" style="margin-bottom: 50px;"> <div class="col-lg-12"> <div class="intro-text"> <span class="name" style="font-size:4.5em;"><NAME></span> <span class="name" style="font-size:1.75em;">oleh <?php echo $ukm; ?></span> </div> </div> </div> <div class="row"> <div class="col-md-8"> <h2 style="margin-bottom:30px;">Tentang Proposal</h2> <p class="proposal"> <?php echo $row->konten; ?> </p> <?php $bulan = array('','Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'); ?> <div class="row" style="padding-left: 15px; padding-right: 15px;"> <h2>Timeline Proposal</h2> <div class="row"> <div class="col-md-6"> <p class="timeline left">Pendanaan</p> </div> <div class="col-md-6"> <p class="timeline right"> <?php echo $bulan[date("n", strtotime($row->batas_waktu))]; echo date(" Y", strtotime($row->batas_waktu)); ?> </p> </div> </div> <div class="row"> <div class="col-md-6"> <p class="timeline left">Penggunaan dana dan pembuatan hadiah</p> </div> <div class="col-md-6"> <p class="timeline right"> <?php echo $bulan[date("n", strtotime($row->waktu_penggunaan))]; echo date(" Y", strtotime($row->waktu_penggunaan)); ?> </p> </div> </div> <div class="row"> <div class="col-md-6"> <p class="timeline left">Pengembalian dana pinjaman dan pengiriman hadiah</p> </div> <div class="col-md-6"> <p class="timeline right"> <?php echo $bulan[date("n", strtotime($row->waktu_pengembalian))]; echo date(" Y", strtotime($row->waktu_pengembalian)); ?> </p> </div> </div> </div> </div> <div class="col-md-4" style="text-align: left; padding-left:50px;"> <div class="row"> <h2><?php echo $pendanaan['jumlah_funder']; ?></h2> <p>funder</p> </div> <div class="row"> <h2 style="text-transform:none;"> Rp<?php if ($pendanaan['jumlah_dana'] == NULL) { echo "0"; } else { echo number_format($pendanaan['jumlah_dana'],0,",","."); } ?> </h2> <p>dari target Rp<?php echo number_format($row->kebutuhan_dana,0,",","."); ?></p> </div> <div class="row"> <h2><?php echo ceil((strtotime($row->batas_waktu)-time())/60/60/24); ?></h2> <p>hari lagi</p> </div> <?php if ($jenis_user == 'funder') { ?> <div class="row" style="margin-top:15px;"> <a href="<?php echo $row->id_proposal; ?>/danai_proposal"> <button type="button" class="btn btn-primary" style="font-size:22px;width:60%;">Danai Permintaan</button> </a> </div> <?php } ?> </div> </div> </div> <?php } ?> </header><file_sep> <style> .panel-ukm { background-color: #2C3E50; padding: 10px; } .judul-panel { color: white; font-size: 20px; padding: 10px 0; } .text-biasa { color: white; font-size: 14px; text-align: left; padding-left: 5px; } .text-bawah { margin-bottom: 25px; } </style> <!-- Index UKM --> <header> <div class="container" style="padding-top: 100px;"> <div class="row" style="margin-bottom: 50px;"> <div class="col-lg-12"> <div class="intro-text"> <span class="name">HALAMAN UKM</span> </div> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="panel-ukm"> <b><p class="judul-panel">Data UKM</p></b> <?php foreach ($ukm->result() as $row) { ?> <p class="text-biasa">Nama : <?php echo $user; ?></p> <p class="text-biasa">Sektor UKM : <?php echo ucwords(strtolower($row->nama));?></p> <p class="text-biasa">Jenis UKM : <?php echo $row->jenis;?></p> <p class="text-biasa text-bawah">Alamat : <?php echo $row->alamat; ?></p> <?php } ?> <!-- <button class="btn btn-default">Ubah Data UKM</button> --> </div> </div> <div class="col-sm-4"> <div class="panel-ukm"> <b><p class="judul-panel">Data Pemilik UKM</p></b> <?php foreach ($pemilik_ukm->result() as $row) { ?> <p class="text-biasa">Nama : <?php echo $row->nama; ?></p> <p class="text-biasa">Alamat : <?php echo $row->alamat_rt_rw; ?></p> <p class="text-biasa">No Telepon : <?php echo $row->no_telepon; ?></p> <p class="text-biasa text-bawah">No Handphone : <?php echo $row->no_hp; ?></p> <?php } ?> <!-- <button class="btn btn-default">Ubah Data Pemilik UKM</button> --> </div> </div> <div class="col-sm-4"> <div class="panel-ukm"> <b><p class="judul-panel">Histori Proposal</p></b> <?php $i = 1; foreach ($proposal_ukm->result() as $row) { echo "<div class=\"row\">"; echo "<div class=\"col-md-6\">"; if ($proposal_ukm->num_rows() == $i) { echo "<p class=\"text-biasa text-bawah\">Proposal ".$i."<br>"; } else { echo "<p class=\"text-biasa\">Proposal ".$i."<br>"; } if (time() < strtotime($row->batas_waktu)) { echo "Pendanaan Proposal</p>"; echo "</div>"; echo "<div class=\"col-md-2\" style=\"margin-right:10px;\"><a href=\"proposal/".$row->id_proposal."/kelola_proposal\"><button class=\"btn btn-default\">Kelola</button></a></div>"; } else if (time() > strtotime($row->batas_waktu) && time() < strtotime($row->waktu_penggunaan)) { echo "Penggunaan Dana dan Pembuatan Hadiah</p>"; echo "</div><div class=\"col-md-2\"></div>"; } else if (time() > strtotime($row->waktu_pengembalian)) { echo "Selesai</p>"; echo "</div><div class=\"col-md-3\"></div>"; } else { echo "Pengembalian Dana Pinjaman</p>"; echo "</div><div class=\"col-md-3\"></div>"; } echo "<div class=\"col-md-3\"><a href=\"proposal/".$row->id_proposal."\"><button class=\"btn btn-default\">Lihat</button></a></div>"; echo "</div>"; $i = $i+1; } ?> </div> </div> </div> <hr> <div class="row"> <h1 style="margin-bottom: 30px;">Ingin mendapatkan pendanaan?</h1> <a href="ukm/buat_proposal"><button class="btn btn-primary" style="width:50%;height:60px;font-size:20px;">Buat Proposal</button></a> </div> </div> </header><file_sep> <script src="<?php echo base_url('/resources/jquery/jquery/dist/jquery.js') ?>"></script> <script type="text/javascript"> function change_hadiah(str) { $('#pilihan_hadiah > option').remove(); if (str > 0) { opt = $('<option/>'); opt.val(0); opt.text('Saya hanya ingin meminjamkan uang'); $('#pilihan_hadiah').append(opt); $.ajax({ type: "POST", url : "http://localhost/ukmjaya/data/get_hadiah_proposal/"+<?php echo $proposal->result_array()[0]['id_proposal']; ?>+"/"+str, success : function(hadiah) { $.each(hadiah, function(id_hadiah,hadiah) { opt = $('<option/>'); opt.val(id_hadiah); opt.text(hadiah); $('#pilihan_hadiah').append(opt); }); } }); document.getElementById("button_lanjut").className = "btn btn-default"; } else { document.getElementById("button_lanjut").className = "btn btn-default disabled"; } } </script> <style> .text-biasa { font-size:16px; text-align: left; } </style> <!-- Danai Proposal --> <header> <div class="container" style="padding-top: 100px;"> <div class="row" style="margin-bottom: 50px;"> <div class="col-lg-12"> <div class="intro-text"> <span class="name" style="font-size:4.5em;">Permintaan Pendanaan</span> <span class="name" style="font-size:1.75em;">oleh <?php echo $ukm; ?></span> </div> </div> </div> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8"> <div class="row" style="background-color: #2C3E50; padding: 15px;"> <h2 style="margin-bottom:30px;">Danai Permintaan</h2> <?php echo form_open('funder/proses_pendanaan'); ?> <p class="text-biasa">Jumlah yang ingin dipinjamkan (Rp.)</p> <input type="hidden" name="id_proposal" value="<?php echo $proposal->result_array()[0]['id_proposal']; ?>"> <input type="text" name="jumlah" id="jumlah_pinjaman" class="form-control" style="width:65%; margin-bottom: 20px; height: 40px; font-size:18px;" onkeyup="change_hadiah(this.value)" onkeydown="change_hadiah(this.value)"> <div class="row"> <div class="col-md-8"> <p class="text-biasa">Pilih Hadiah</p> <select id="pilihan_hadiah" name="pilihan_hadiah" class="form-control" style="color:black;"></select> </div> <div class="col-md-4"> <button type="submit" id="button_lanjut" class="btn btn-default disabled" style="width:100%; height:66px;">Lanjut</button> </div> </div> </form> </div> </div> </div> </div> </header><file_sep><?php class Data extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('data_model'); } public function index() { } public function get_list_kab_kota($id_provinsi) { header('Content-Type: application/x-json; charset=utf-8'); echo(json_encode($this->data_model->get_list_kab_kota($id_provinsi))); } public function get_user($id_user) { header('Content-Type: application/x-json; charset=utf-8'); echo(json_encode($this->data_model->get_user($id_user))); } public function get_sub_sektor($id_sektor) { header('Content-Type: application/x-json; charset=utf-8'); echo(json_encode($this->data_model->get_sub_sektor($id_sektor))); } public function get_hadiah_proposal($id_proposal = "", $jumlah_pinjaman = 0) { header('Content-Type: application/x-json; charset=utf-8'); echo(json_encode($this->data_model->get_hadiah_proposal($id_proposal, $jumlah_pinjaman))); } } ?><file_sep><?php class Data_model extends CI_Model { public function __construct() { $this->load->database(); } public function get_list_provinsi() { return $this->db->get('data_provinsi'); } public function get_list_kab_kota($id_provinsi=NULL) { if ($id_provinsi === NULL) { return $this->db->get('data_kab_kota'); } else { $this->db->where('id_provinsi', $id_provinsi); $query = $this->db->get('data_kab_kota'); $list_kota = array(); if ($query->result()) { foreach($query->result() as $kota) { $list_kota[$kota->id] = $kota->nama; } return $list_kota; } else { return false; } } } public function get_user($id_user=NULL) { if ($id_user == NULL) { return $this->db->get('user'); } else { $this->db->where('id_user', $id_user); return $this->db->get('user'); } } public function check_ukm($id_ukm) { return $this->db->query("SELECT (SELECT COUNT(*) FROM data_ukm WHERE id_ukm = ".$id_ukm.") AS ada_data_ukm, (SELECT COUNT(*) FROM data_pemilik_ukm WHERE id_ukm = ".$id_ukm.") AS ada_data_pemilik FROM dual"); } public function get_list_sektor() { return $this->db->get('data_sektor'); } public function get_sub_sektor($id_sektor) { $this->db->where('id_sektor', $id_sektor); $query = $this->db->get('data_sub_sektor'); $list_sub_sektor = array(); if ($query->result()) { foreach($query->result() as $subsektor) { $list_sub_sektor[$subsektor->id] = $subsektor->nama; } return $list_sub_sektor; } else { return false; } } public function get_bentuk_usaha() { return $this->db->get('data_bentuk_usaha'); } public function get_proposal($id_proposal) { $this->db->where('id_proposal', $id_proposal); return $this->db->get('proposal'); } public function get_proposal_ukm($id_ukm) { $this->db->where('id_ukm', $id_ukm); return $this->db->get('proposal'); } public function get_pendanaan($id_proposal) { $this->db->select('sum(jumlah) AS jumlah_dana, count(id_funder) AS jumlah_funder'); $this->db->where('id_proposal', $id_proposal); return $this->db->get('dana'); } public function get_hadiah_proposal($id_proposal, $jumlah_pinjaman) { $this->db->where('id_proposal', $id_proposal); $this->db->where('minimal_pinjaman <=', $jumlah_pinjaman); $query = $this->db->get('hadiah_proposal'); $list_hadiah = array(); if ($query->result()) { foreach ($query->result() as $row) { $list_hadiah[$row->id_hadiah] = $row->hadiah; } return $list_hadiah; } else { return false; } } public function get_proposal_populer() { return $this->db->query("SELECT proposal.id_proposal, (sum(jumlah)/kebutuhan_dana*100) AS persentase, nama, batas_waktu FROM dana RIGHT JOIN proposal ON dana.id_proposal = proposal.id_proposal JOIN user ON proposal.id_ukm = user.id_user WHERE is_populer = true GROUP BY proposal.id_proposal"); } public function get_data_ukm($id_ukm) { $this->db->select('*'); $this->db->from('data_ukm'); $this->db->join('data_sektor', 'data_ukm.sektor = data_sektor.id'); $this->db->where('id_ukm', $id_ukm); return $this->db->get(); } public function get_pemilik_ukm($id_ukm) { $this->db->where('id_ukm', $id_ukm); return $this->db->get('data_pemilik_ukm'); } public function get_detail_proposal($id_proposal) { return $this->db->query("SELECT jumlah, hadiah, nama, waktu_pendanaan FROM `dana` JOIN `hadiah_proposal` ON `dana`.`id_proposal` = `hadiah_proposal`.`id_proposal` JOIN `user` ON `dana`.`id_funder` = `user`.`id_user` WHERE `dana`.id_proposal = ".$id_proposal); } } ?><file_sep> <style> .text-biasa { color: black; font-size: 15px; } .image-index { margin-bottom: 0px; } .panel-ukm { background-color: white; height: 100px; padding-left: 10px; padding-right: 10px; } .judul-panel { padding-top: 10px; } .rapat-kiri { text-align: left; } .rapat-kanan { text-align: right; } </style> <!-- Proyek Populer --> <header> <div class="container" style="padding-top: 150px;"> <div class="row" style="margin-bottom: 50px;"> <div class="col-lg-12"> <div class="intro-text"> <span class="name">PROPOSAL UKM POPULER</span> </div> </div> </div> <div class="row"> <?php foreach ($proposal_populer->result() as $row) { ?> <a href="<?php echo base_url('proposal/'.$row->id_proposal); ?>"> <div class="col-sm-4"> <img src="<?php echo base_url(); ?>resources/img/portfolio/cabin.png" class="img-responsive image-index" alt=""> <div class="panel-ukm"> <b><p class="judul-panel text-biasa rapat-kiri"><?php echo $row->nama; ?></p></b> <div class="progress" style="margin-bottom: 10px;"> <div class="progress-bar" role="progressbar" style="width: <?php echo $row->persentase; ?>%;"> </div> </div> <div class="row"> <div class="col-md-6"> <p class="text-biasa rapat-kiri"> <?php if ($row->persentase == NULL) echo 0; else echo number_format($row->persentase, 0); ?>% </p> </div> <div class="col-md-6"><p class="text-biasa rapat-kanan"><?php echo ceil((strtotime($row->batas_waktu)-time())/60/60/24); ?> hari lagi</p></div> </div> </div> </div> </a> <?php } ?> </div> </div> </header><file_sep> <!-- Form Masuk --> <header> <div class="container" style="padding-top: 135px; padding-bottom: 80px;"> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4" style="background-color:#2C3E50; padding-left: 35px; width: 430px; padding-right: 35px; padding-top: 15px; padding-bottom: 15px;"> <h3 style="text-align: center; margin-bottom: 30px;">Masuk Akun</h3> <?php echo form_open('user/proses_masuk'); ?> <div class="row control-group"> <div class="form-group col-xs-12"> <p style="text-align:left; font-size:14px;">Email</p> <input type="text" name="email" class="form-control"> </div> </div> <div class="row control-group" style="margin-bottom: 20px;"> <div class="form-group col-xs-12"> <p style="text-align:left; font-size:14px;">Kata sandi</p> <input type="password" name="password" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <input type="submit" class="form-control" value="Masuk" style="width:106px; margin:0px auto; display:block;"> </div> </div> </form> <hr> <h4 style="text-align: center; margin-bottom: 25px; margin-top: 30px;">Belum Punya Akun?</h4> <a href="<?php echo base_url(); ?>daftar"><h5 style="text-align: center; margin-bottom: 20px;">Daftar Di Sini</h5></a> </div> </div> </div> </header><file_sep> <script src="<?php echo base_url('/resources/jquery/jquery/dist/jquery.js') ?>"></script> <script type="text/javascript"> $(document).ready(function() { $('#provinsi').change(function() { $('#kota > option').remove(); var id_provinsi = $('#provinsi').val(); $.ajax({ type: "POST", url : "http://localhost/ukmjaya/data/get_list_kab_kota/"+id_provinsi, success : function(kota) { $.each(kota, function(id,name) { var opt = $('<option/>'); opt.val(id); opt.text(name); $('#kota').append(opt); }); } }); }); }); </script> <style> .label-form { text-align: left; font-size: 14px; } </style> <header> <div class="container" style="padding-top: 150px;"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8" style="background-color:#2C3E50; padding-left: 35px; padding-right: 35px; padding-top: 15px; padding-bottom: 15px;"> <h3 style="text-align: center; margin-bottom: 30px;">Pendaftaran Pemilik UKM</h3> <?php echo form_open('ukm/proses_pendaftaran_pemilik'); ?> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Nama Lengkap</p> <input type="text" name="nama" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">No KTP</p> <input type="text" name="no_ktp" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Alamat Lengkap</p> <input type="text" name="alamat" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Desa/Kelurahan</p> <input type="text" name="desa_kel" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Kecamatan</p> <input type="text" name="kecamatan" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Provinsi</p> <?php $options_provinsi[''] = "Pilih Provinsi"; foreach($list_provinsi->result() as $row) { $options_provinsi[$row->id] = $row->nama; } echo form_dropdown('provinsi', $options_provinsi, '', 'id="provinsi" class="form-control"'); ?> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Kabupaten/Kota</p> <?php $kota[''] = "Pilih Kabupaten/Kota"; echo form_dropdown('kab_kota', $kota, '', 'id="kota" class="form-control"'); ?> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">Kode Pos</p> <input type="text" name="kode_pos" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form">No Telepon</p> <input type="text" name="no_tlp" class="form-control"> </div> </div> <div class="row control-group" style="margin-bottom: 20px;"> <div class="form-group col-xs-12"> <p class="label-form">No Handphone</p> <input type="text" name="no_hp" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <input type="submit" class="form-control" value="Lanjut" style="width:106px; float: center;"> </div> </div> </form> </div> </div> </div> </header><file_sep> <style> table, tr, td, th { border : 1px solid black; } </style> <header> <div class="container" style="padding-top: 100px;"> <div class="row" style="margin-bottom: 50px;"> <div class="col-lg-12"> <div class="intro-text"> <span class="name">KELOLA PROPOSAL</span> </div> </div> </div> <div class="row"> <div class="col-md-6" style="text-align:left;"> <h3>Dana yang masuk</h3> <h1 style="text-transform:none;"> Rp<?php if ($pendanaan['jumlah_dana'] == NULL) { echo "0"; } else { echo number_format($pendanaan['jumlah_dana'],0,",","."); } ?> </h1> </div> <div class="col-md-6" style="text-align:right;"> <h3>Jumlah Funder</h3> <h1 style="text-transform:none;"><?php echo $pendanaan['jumlah_funder']; ?></h1> </div> </div> <hr> <div class="row"> <table> <tr> <th>Nama</th> <th>Jumlah Pinjaman</th> <th>Pilihan Hadiah</th> <th>Waktu Pendanaan</th> </tr> <?php foreach ($proposal->result() as $row) { ?> <tr> <td><?php echo $row->nama; ?></td> <td><?php echo $row->jumlah; ?></td> <td><?php echo $row->hadiah; ?></td> <td><?php echo $row->waktu_pendanaan; ?></td> </tr> <?php } ?> </table> </div> </div> </header><file_sep> <script src="<?php echo base_url('/resources/jquery/jquery/dist/jquery.js') ?>"></script> <script type="text/javascript"> $(document).ready(function() { $('#provinsi').change(function() { $('#kota > option').remove(); var id_provinsi = $('#provinsi').val(); $.ajax({ type: "POST", url : "http://localhost/ukmjaya/data/get_list_kab_kota/"+id_provinsi, success : function(kota) { $.each(kota, function(id,name) { var opt = $('<option/>'); opt.val(id); opt.text(name); $('#kota').append(opt); }); } }); }); }); </script> <style> .label-form-daftar { text-align:left; font-size:14px; } </style> <!-- Form Daftar --> <header> <div class="container" style="padding-top: 130px;""> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4" style="background-color:#2C3E50; padding-left: 35px; width: 430px; padding-right: 35px; padding-top: 15px; padding-bottom: 15px;"> <h3 style="text-align: center; margin-bottom: 30px;">Daftar Akun</h3> <?php echo form_open('user/proses_daftar'); ?> <div class="row control-group"> <div class="col-md-6" style="text-align:left;"> Saya mendaftar sebagai </div> <div class="col-md-3"> <div class="form-group"> <input name="jenis_user" value="ukm" type="radio"> UKM </div> </div> <div class="col-md-3"> <div class="form-group"> <input name="jenis_user" value="funder" type="radio"> Funder </div> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form-daftar">Nama</p> <input type="text" name="nama" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form-daftar">Email</p> <input type="text" name="email" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form-daftar">Kata sandi</p> <input type="<PASSWORD>" name="password" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form-daftar">Masukkan kembali kata sandi</p> <input type="<PASSWORD>" name="c_password" class="form-control"> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <p class="label-form-daftar">Provinsi</p> <?php $options_provinsi[''] = "Pilih Provinsi"; foreach($list_provinsi->result() as $row) { $options_provinsi[$row->id] = $row->nama; } echo form_dropdown('provinsi', $options_provinsi, '', 'id="provinsi" class="form-control"'); ?> </div> </div> <div class="row control-group" style="margin-bottom: 20px;"> <div class="form-group col-xs-12"> <p class="label-form-daftar">Kabupaten/Kota</p> <?php $kota[''] = "Pilih Kabupaten / Kota"; echo form_dropdown('kab_kota', $kota, '', 'id="kota" class="form-control"'); ?> </div> </div> <div class="row control-group"> <div class="form-group col-xs-12"> <input type="submit" class="form-control" value="Daftar" style="width:106px; margin:0px auto; display:block;"> </div> </div> </form> </div> </div> </div> </header><file_sep><?php class Funder extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('cookie'); $this->load->helper('url'); $this->load->helper('form'); $this->load->model('data_model'); $this->load->model('ukm_model'); $this->load->model('funder_model'); } public function danai_proposal($id_proposal=NULL) { if ($id_proposal === NULL) { show_404(); } else { if (get_cookie('jenis_user') == 'ukm' || get_cookie('user_id') == NULL) { echo "Anda belum login atau anda tidak mendaftar sebagai Funder.<br>"; echo "Silakan <a href='../../masuk'>Masuk</a> atau <a href='../../daftar'>Daftar</a> terlebih dahulu."; } else { $data_user = $this->data_model->get_user(get_cookie('user_id')); $data_proposal = $this->data_model->get_proposal($id_proposal); $id_ukm = $data_proposal->result_array()[0]['id_ukm']; $data['proposal'] = $data_proposal; $data['ukm'] = $this->data_model->get_user($id_ukm)->result_array()[0]['nama']; $data['user'] = $data_user->result_array()[0]['nama']; $this->load->view('header-funder', $data); $this->load->view('danai-proposal', $data); $this->load->view('footer'); } } } public function proses_pendanaan() { if (get_cookie('jenis_user') == 'ukm' || get_cookie('user_id') == NULL) { echo "Anda belum login atau anda tidak mendaftar sebagai Funder.<br>"; echo "Silakan <a href='../../masuk'>Masuk</a> atau <a href='../../daftar'>Daftar</a> terlebih dahulu."; } else { $this->funder_model->proses_pendanaan(get_cookie('user_id')); } } } ?><file_sep># UKMJaya Platform Crowdfunding UKM Indonesia ## Template [Freelancer](http://startbootstrap.com/template-overviews/freelancer/) ## References * [Navbar Search](http://bootsnipp.com/snippets/featured/navbar-search-add-on-bs-3) * [Remove Index.php] (http://only4ututorials.blogspot.co.id/2014/03/how-to-remove-indexphp-from-codeigniter.html) * [Progress Bar] (http://getbootstrap.com/components/) * [CodeIgniter] (https://codeigniter.com) * [Kickstarter] (https://www.kickstarter.com/) * [Kitabisa] (https://kitabisa.com/) * [Stack Overflow] (http://stackoverflow.com/) * [W3Schools] (http://www.w3schools.com/) ## Copyright and License Copyright 2013-2016 Blackrock Digital LLC. Code released under the [MIT](https://github.com/BlackrockDigital/startbootstrap-freelancer/blob/gh-pages/LICENSE) license. <file_sep><?php class User_model extends CI_Model { public function __construct() { $this->load->database(); $this->load->helper('string'); date_default_timezone_set("Asia/Jakarta"); } public function proses_daftar() { $password = $this->input->post('password'); $c_password = $this->input->post('c_password'); $jenis_user = $this->input->post('jenis_user'); $id_user = random_string('numeric', 7); if ($password == $c_password) { $data_user = array( 'id_user' => $id_user, 'nama' => $this->input->post('nama'), 'email' => $this->input->post('email'), 'password'=> $<PASSWORD>, 'kab_kota' => $this->input->post('kab_kota'), 'provinsi' => $this->input->post('provinsi'), 'waktu_join' => date('Y-m-d H:i:s'), 'is_banned' => 0 ); $this->db->insert('user', $data_user); $data_jenis_user = array( 'id_user' => $id_user ); if ($jenis_user == 'ukm') { $this->db->insert('ukm', $data_jenis_user); } else { $this->db->insert('funder', $data_jenis_user); } return true; } else { return false; } } public function proses_masuk() { $email = $this->input->post('email'); $password = $this->input->post('password'); $query = $this->db->query("SELECT funder.id_user AS id_funder, ukm.id_user AS id_ukm FROM user LEFT JOIN ukm ON user.id_user = ukm.id_user LEFT JOIN funder ON user.id_user = funder.id_user WHERE email = '".$email."' AND password = '".$<PASSWORD>."'"); $hasil = $query->result_array(); if (count($hasil) > 0) { return $hasil; } else { return 0; } } } ?>
c347f7449d83e8815e997e57ea42f388684c211c
[ "Markdown", "PHP" ]
20
PHP
fauzannaufan/UKMJaya
e4dc87d90b65e7314b8a038b6e413097b06e60f5
a493cff510b3bfb8d04627c0827e4c5527d5e22b
refs/heads/main
<file_sep># iOS15-UIRefreshControl-issue-reproduction https://developer.apple.com/forums/thread/691858 https://user-images.githubusercontent.com/1888355/136479136-860fcf8d-dbc9-4145-a466-6e0ca711092d.mp4 <file_sep>// // ViewController.swift // DemoRefreshControl // // Created by Muukii on 2021/10/08. // import MondrianLayout import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let contentView = UIView() contentView.backgroundColor = .systemOrange let scrollView = UIScrollView() scrollView.addSubview(contentView) scrollView.alwaysBounceVertical = true contentView.mondrian.layout .height(.exact(300)) .top(.to(scrollView.contentLayoutGuide)) .horizontal(.to(scrollView.frameLayoutGuide)) .activate() let refreshControl = UIRefreshControl() scrollView.addSubview(refreshControl) view.mondrian.buildSubviews { ZStackBlock(alignment: .attach(.all)) { scrollView } } refreshControl.addAction( .init(handler: { [unowned refreshControl] action in if refreshControl.isRefreshing { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { refreshControl.endRefreshing() } } }), for: .valueChanged ) } }
d4a9bf0b9236d4d702b465dbf10b67a77fd8d854
[ "Markdown", "Swift" ]
2
Markdown
muukii/iOS15-UIRefreshControl-issue-reproduction
3333272ceb0b2efcf557f3f1515c9d54eb0d3643
66bbdf0b5dc5c7ca53ae4b10915a552cef2f25c4
refs/heads/master
<file_sep>import discord from discord.ext import commands import urllib.parse, urllib.request, re import datetime import os import random import traceback import bs4 import asyncio import threading import requests access_token = os.environ["BOT_TOKEN"] client = discord.Client() badword_list = ['섹스', '느금마', '애미', '애비', '장애인', '느금', '보지', '자지', '니애미', 'badwordtest1', 'badwordtest2'] badwords = [] colours = [discord.Color.dark_orange(),discord.Color.orange(),discord.Color.dark_gold(),discord.Color.gold(),discord.Color.dark_magenta(), discord.Color.magenta(),discord.Color.red(),discord.Color.dark_red(),discord.Color.blue(),discord.Color.dark_blue(),discord.Color.teal(), discord.Color.dark_teal(),discord.Color.green(),discord.Color.dark_green(),discord.Color.purple(),discord.Color.dark_purple()] regionals = {'a': '\N{REGIONAL INDICATOR SYMBOL LETTER A}', 'b': '\N{REGIONAL INDICATOR SYMBOL LETTER B}', 'c': '\N{REGIONAL INDICATOR SYMBOL LETTER C}', 'd': '\N{REGIONAL INDICATOR SYMBOL LETTER D}', 'e': '\N{REGIONAL INDICATOR SYMBOL LETTER E}', 'f': '\N{REGIONAL INDICATOR SYMBOL LETTER F}', 'g': '\N{REGIONAL INDICATOR SYMBOL LETTER G}', 'h': '\N{REGIONAL INDICATOR SYMBOL LETTER H}', 'i': '\N{REGIONAL INDICATOR SYMBOL LETTER I}', 'j': '\N{REGIONAL INDICATOR SYMBOL LETTER J}', 'k': '\N{REGIONAL INDICATOR SYMBOL LETTER K}', 'l': '\N{REGIONAL INDICATOR SYMBOL LETTER L}', 'm': '\N{REGIONAL INDICATOR SYMBOL LETTER M}', 'n': '\N{REGIONAL INDICATOR SYMBOL LETTER N}', 'o': '\N{REGIONAL INDICATOR SYMBOL LETTER O}', 'p': '\N{REGIONAL INDICATOR SYMBOL LETTER P}', 'q': '\N{REGIONAL INDICATOR SYMBOL LETTER Q}', 'r': '\N{REGIONAL INDICATOR SYMBOL LETTER R}', 's': '\N{REGIONAL INDICATOR SYMBOL LETTER S}', 't': '\N{REGIONAL INDICATOR SYMBOL LETTER T}', 'u': '\N{REGIONAL INDICATOR SYMBOL LETTER U}', 'v': '\N{REGIONAL INDICATOR SYMBOL LETTER V}', 'w': '\N{REGIONAL INDICATOR SYMBOL LETTER W}', 'x': '\N{REGIONAL INDICATOR SYMBOL LETTER X}', 'y': '\N{REGIONAL INDICATOR SYMBOL LETTER Y}', 'z': '\N{REGIONAL INDICATOR SYMBOL LETTER Z}', '0': '0⃣', '1': '1⃣', '2': '2⃣', '3': '3⃣', '4': '4⃣', '5': '5⃣', '6': '6⃣', '7': '7⃣', '8': '8⃣', '9': '9⃣', '!': '\u2757', '?': '\u2753', ' ': ' '} # client = commands.Bot(command_prefix='!') @client.event async def on_ready(): print("Bot is ready.") print(client.user.name) print(client.user.id) print("--------------------") await client.change_presence(activity=discord.Streaming(platform='Twitch', name='빈아 도와줘', url='https://www.twitch.tv/b2n1_ow/', twitch_name='b2n1_ow')) # await client.get_channel(675198423502290944).send('안녕하세요 저는 빈이봇이에요! 도움이 필요할 땐 "빈아 도와줘"를 적어주세요~') @client.event async def on_message(message): admins = [524980170554212363, 264231194680360960] welcome_channel = client.get_channel(683228020823031833) notice_channel = client.get_channel(675198423502290944) # botcmd_channel = client.get_channel(650340295061536769) badword_log_channel = client.get_channel(683229891126099989) b2n1_id = client.get_guild(536868994808807435) if any(x in message.content for x in badword_list) and message.guild == b2n1_id: for badword in badword_list: if badword in message.content: badwords.append(badword) print(badwords) from datetime import datetime embed = discord.Embed( description="{0}님이 {1} **채널에서 욕설을 사용했습니다.**".format(message.author.mention, message.channel.mention), timestamp=datetime.utcnow(), colour=discord.Colour.red() ) embed.set_author(name=message.author, icon_url=message.author.avatar_url) embed.add_field(name="제거된 메시지", value=message.content) embed.add_field(name="감지된 욕설 ({0})".format(len(badwords)), value=", ".join(str(i) for i in badwords), inline=False) embed.set_footer(text="ID: {0}".format(message.author.id)) await message.delete() await badword_log_channel.send(embed=embed) # 개인 메시지 if isinstance(message.channel, discord.DMChannel) and message.author != client.user: # 받은 DM을 포스팅할 채널 dm_channels = [683229891126099989] # 받음=빨강, 보냄=파랑 from datetime import datetime embed = discord.Embed( description=message.author.mention + " to " + client.user.mention, timestamp=datetime.utcnow(), colour=discord.Colour.red() ) """ if message.author == client.user: embed = discord.Embed( description=message.author.mention + " to " + message.channel.recipient.mention, timestamp=datetime.utcnow(), colour=discord.Colour.blue() ) """ embed.set_author(name=message.author, icon_url=message.author.avatar_url) embed.add_field(name="받은 메시지:", value=message.content) embed.set_footer(text="ID: {0}".format(str(message.author.id))) for x in dm_channels: await client.get_channel(x).send(embed=embed) # 관리자 명령어 if message.author.id in admins and message.author != client.user: if message.content.startswith(">>") and message.author != client.user: result = '' for x in range(2, len(message.content)): letter = message.content[x:x + 1].lower() if letter in regionals: result = result + regionals[letter] + " " print(result) if result != '': await message.channel.send(result) if message.content.startswith('빈아 말해 '): msg = message.content[6:] await message.delete() await message.channel.send(msg) if message.content.startswith('빈아 읽어 '): msg = message.content[6:] await message.delete() await message.channel.send(msg, tts=True) if message.content.startswith('-diff'): msg = message.content[6:] await message.channel.send("```diff\n{0}\n```".format(msg)) if message.content.startswith("-dm"): author = message.mentions[0] msg = message.content[4:] msg = msg[msg.find(' ') + 1:] await author.send(msg) if message.content.startswith("-dmid"): author = message.guild.get_member(int(message.content[4:22])) msg = message.content[23:] await author.send(msg) # 자유 명령어 if message.content == "빈아 도와줘": from datetime import datetime embed = discord.Embed( title='저를 부를 땐 앞에 "빈아"를 붙여주세요!', timestamp=datetime.utcnow(), colour=discord.Colour.green() ) embed.set_author(name='빈이봇 명령어 목록', icon_url=message.guild.icon_url) embed.set_thumbnail(url=message.guild.icon_url) embed.add_field(name="관리자 명령어", value="`말해`, `읽어`", inline=False) embed.add_field(name="유저 명령어", value="`도와줘`, `안녕`, `멤버수`, `관리자`, `영웅추천`, `고마워`", inline=False) embed.add_field(name="검색 명령어", value="`누구야`, `유튜브`, `배틀태그`", inline=False) await message.channel.send(embed=embed) if message.content.startswith("빈아 안녕"): await message.channel.send("안녕하세요, {.mention}님 !".format(message.author)) if message.content.startswith("빈아 누구야 "): author = message.author if len(message.content[7:]) > 0: author = message.mentions[0] import datetime date = datetime.datetime.utcfromtimestamp(((int(author.id) >> 22) + 1420070400000) / 1000) embed = discord.Embed( description=author.mention, colour=discord.Colour.green() ) embed.add_field(name="이름", value=author, inline=True) embed.add_field(name="서버닉네임", value=author.display_name, inline=True) embed.add_field(name="가입일", value=str(date.year) + "년" + str(date.month) + "월" + str(date.day) + "일", inline=True) embed.add_field(name="아이디", value=author.id, inline=True) embed.set_thumbnail(url=author.avatar_url) await message.channel.send("", embed=embed) if message.content.startswith("빈아 고마워"): thankmsg = ["헤헿", "^^", " (っ˘ڡ˘ς) ", "{0} 저도 고마워요!".format(message.author.mention), "응"] await message.channel.send(random.choice(thankmsg)) if message.content == "빈아 멤버수": await message.channel.send(f"현재 **{message.guild.name}** 서버에는 **{message.guild.member_count}**명이 있어요!") if message.content == "빈아 관리자": await message.channel.send(", ".join(str(message.guild.get_member(i)) for i in admins)) if message.content.startswith("빈아 영웅추천"): tank = ["D.va", "라인하르트", "레킹볼", "로드호그", "시그마", "오리사", "윈스턴", "자리야"] damage = ["겐지", "둠피스트", "리퍼", "맥크리", "메이", "바스티온", "솔저: 76", "솜브라", "시메트라", "애쉬", "위도우메이커", "정크랫", "토르비욘", "트레이서", "파라", "한조"] support = ["루시우", "메르시", "모이라", "바티스트", "브리기테", "아나", "젠야타"] all_heroes = ["D.va", "겐지", "둠피스트", "라인하르트", "레킹볼", "로드호그", "루시우", "리퍼", "맥크리", "메르시", "메이", "모이라", "바스티온", "바티스트", "브리기테", "솔저: 76", "솜브라", "시그마", "시메트라", "아나", "애쉬", "오리사", "위도우메이커", "윈스턴", "자리야", "정크랫", "젠야타", "토르비욘", "트레이서", "파라", "한조"] role = message.content[8:9].lower() if role == "탱": result = random.choice(tank) elif role == "딜": result = random.choice(damage) elif role == "힐": result = random.choice(support) else: result = random.choice(all_heroes) htm_content = urllib.request.urlopen("https://playoverwatch.com/ko-kr/heroes").read() htm_content = str(htm_content) print(htm_content) profile_img = re.findall(r'<img class="portrait" src="(https://.*?png)"', htm_content) print(profile_img) for i in profile_img: print(i) embed = discord.Embed( title=result, description=message.author.mention ) for x in range(0, len(all_heroes)): print(result + ", " + all_heroes[x]) if result == all_heroes[x]: embed.set_thumbnail(url=profile_img[x]) break # await message.channel.send("{0.mention} **{1}** 하세요".format(message.author, result)) await message.channel.send(embed=embed) if message.content.startswith("빈아 유튜브 "): search = message.content[7:] query_string = urllib.parse.urlencode({ 'search_query': search }) htm_content = urllib.request.urlopen( 'http://www.youtube.com/results?' + query_string ) search_results = re.findall('href=\"\\/watch\\?v=(.{11})', htm_content.read().decode()) randomNum = random.randrange(0, len(search_results)) print("총 {0}개 검색, {1}번 출력".format(len(search_results), randomNum)) await message.channel.send('{0}중 {1}\n'.format(len(search_results), randomNum) + 'http://www.youtube.com/watch?v=' + search_results[randomNum]) if message.content.startswith("빈아 배틀태그 "): tag = message.content[8:] battletag = tag.replace("#", "-") print(f"Replace tag '{tag}' to '{battletag}'") url = 'https://playoverwatch.com/ko-kr/career/pc/' + battletag url = urllib.parse.urlsplit(url) url = list(url) url[2] = urllib.parse.quote(url[2]) profile_url = urllib.parse.urlunsplit(url) print(f"{tag}'s Profile: {profile_url}") htm_content = urllib.request.urlopen(profile_url).read() htm_content = bs4.BeautifulSoup(htm_content, 'html.parser') htm_content = str(htm_content) # print(f"Found HTML: {htm_content}") profile_img = re.findall(r'<img class="player-portrait" src="(https://.*?png)"', htm_content) if len(profile_img) < 1: print(f"Failed to find {tag}'s profile.") await message.channel.send("유저 정보를 찾을 수 없습니다.\n(배틀태그 검색은 대소문자를 구분하므로 대소문자를 정확히 입력해야 합니다.)") return isPublic = htm_content.find('<div class="masthead-permission-level-container u-center-block">') == -1 print(f"Is profile public: {isPublic}") print("Profile icon: " + profile_img[0]) quickplay_img = re.findall(r'data-js="heroMastheadImage" style="background-image: (https://.*?png)">', htm_content) player_level_img = htm_content[htm_content.find('<div class="player-level" style'):htm_content.find('<div class="player-rank" style')] player_level_img = re.findall(r' (https://.*?png) ', player_level_img) print(player_level_img) exist_tank = htm_content.find("돌격 실력 평점") != -1 exist_damage = htm_content.find("공격 실력 평점") != -1 exist_support = htm_content.find("지원 실력 평점") != -1 print(f"돌격: {exist_tank}, 공격: {exist_damage}, 지원: {exist_support}") print(quickplay_img) from datetime import datetime embed = discord.Embed( title=f"🔗 프로필 링크", timestamp=datetime.utcnow(), # description=f"🔓 공개 프로필" if isPublic == True else f"🔒 비공개 프로필", colour=discord.Colour.orange(), url=profile_url ) embed.set_author(name=tag, icon_url=profile_img[0]) embed.set_footer(text=f"🔓 공개 프로필" if isPublic == True else f"🔒 비공개 프로필") if quickplay_img: embed.set_image(url=quickplay_img[0]) if exist_tank or exist_damage or exist_support: if exist_tank: tank_html = htm_content[htm_content.find("돌격 실력 평점"):htm_content.find("돌격 실력 평점") + 200] tank_tier = re.findall(r'<img class="competitive-rank-tier-icon" src="(https://.*?png)"', tank_html) tank_level = re.findall(r'<div class="competitive-rank-level">(.*?)</div>', tank_html) embed.set_thumbnail(url=tank_tier[0]) embed.add_field(name="돌격 실력 평점", value=f"```fix\n{tank_level[0]}```") if exist_damage: damage_html = htm_content[htm_content.find("공격 실력 평점"):htm_content.find("공격 실력 평점") + 200] damage_tier = re.findall(r'<img class="competitive-rank-tier-icon" src="(https://.*?png)"', damage_html) damage_level = re.findall(r'<div class="competitive-rank-level">(.*?)</div>', damage_html) embed.set_thumbnail(url=damage_tier[0]) embed.add_field(name="공격 실력 평점", value=f"```fix\n{damage_level[0]}```") if exist_support: support_html = htm_content[htm_content.find("지원 실력 평점"):htm_content.find("지원 실력 평점") + 200] support_tier = re.findall(r'<img class="competitive-rank-tier-icon" src="(https://.*?png)"', support_html) support_level = re.findall(r'<div class="competitive-rank-level">(.*?)</div>', support_html) embed.set_thumbnail(url=support_tier[0]) embed.add_field(name="지원 실력 평점", value=f"```fix\n{support_level[0]}```") else: embed.set_thumbnail(url=profile_img[0]) await message.channel.send(embed=embed) if message.content == "빈아 서버정보": findbots = sum(1 for message.author in message.guild.members if message.author.bot) embed = discord.Embed() if message.guild.icon: embed.set_thumbnail(url=message.guild.icon_url) if message.guild.banner: embed.set_image(url=message.guild.banner_url_as(format="png")) embed.add_field(name="Server Name", value=message.guild.name, inline=True) embed.add_field(name="Server ID", value=message.guild.id, inline=True) embed.add_field(name="Members", value=message.guild.member_count, inline=True) embed.add_field(name="Bots", value=findbots, inline=True) embed.add_field(name="Owner", value=message.guild.owner, inline=True) embed.add_field(name="Region", value=message.guild.region, inline=True) embed.add_field(name="Created", value=message.guild.created_at, inline=True) await message.channel.send(content=f"ℹ information about **{message.guild.name}**", embed=embed) if message.content == "빈아 입장테스트": from datetime import datetime embed = discord.Embed( title="🔗 서버 재참가 링크", description=f"Hey! {message.author.mention},", timestamp = datetime.utcnow(), colour=random.choice(colours), url="https://discord.gg/gpcBuuk" ) embed.set_author(name=message.author, icon_url=message.author.avatar_url) embed.set_footer(text=f"유저 ID: {message.author.id}") # embed.set_thumbnail(url=message.author.avatar_url) embed.add_field( name=f"Welcome to the **B2n1's Viewers'** Server !", value=f"**빈이시청자** 서버에 오신것을 진심으로 환영합니다! 🎊" ) embed.add_field( name=f"Don't forget to read the **annoucement**!", value=f"공지사항 {notice_channel.mention}, 꼭 잊지 말고 읽어주세요!", inline=False ) await message.author.send(embed=embed) await message.channel.send(message.author.mention, embed=embed) if message.content.startswith("빈아 유저정보 "): waiting = await message.channel.send(embed=discord.Embed(description='유저 정보를 불러오는중', color=discord.Color.blue())) if len(message.mentions) > 0: author = message.mentions[0] else: author = message.author import datetime registered = datetime.datetime.utcfromtimestamp(((int(author.id) >> 22) + 1420070400000) / 1000) embed = discord.Embed( description=author.mention, colour=discord.Colour.red() ) embed.set_author(name=author, icon_url=author.avatar_url) embed.add_field(name="Registered", value=f'{str(registered.year)}년 {str(registered.month)}월 {str(registered.day)}일') embed.add_field(name=f'Roles [{len(author.roles)-1}]', value="".join(i.mention for i in author.roles if str(i) != '@everyone'), inline=False) embed.set_footer(text=f"ID: {author.id}") await waiting.delete() await message.channel.send(embed=embed) if message.content == "빈아 현재시간": import datetime utcnow = datetime.datetime.utcnow() time_gap = datetime.timedelta(hours=9) kor_time = utcnow + time_gap date = kor_time.strftime(f"%Y년 %m월 %d일 {'오전' if kor_time.strftime('%p') == 'AM' else '오후'} %I시 %M분") await message.channel.send(date) @client.event async def on_member_join(member): welcome_channel = client.get_channel(683228020823031833) notice_channel = client.get_channel(675198423502290944) # botcmd_channel = client.get_channel(650340295061536769) from datetime import datetime embed = discord.Embed( title="🔗 서버 재참가 링크", description=f"Hey! {member.mention},", timestamp=datetime.utcnow(), colour=random.choice(colours), url="https://discord.gg/gpcBuuk" ) embed.set_author(name=member, icon_url=member.avatar_url) embed.set_footer(text=f"유저 ID: {member.id}") embed.add_field( name=f"Welcome to the **B2n1's Viewers'** Server !", value=f"**빈이시청자** 서버에 오신것을 진심으로 환영합니다! 🎊" ) embed.add_field( name=f"Don't forget to read the **annoucement**!", value=f"공지사항 {notice_channel.mention}, 꼭 잊지 말고 읽어주세요!", inline=False ) await member.send(embed=embed) await welcome_channel.send(member.mention, embed=embed) @client.event async def on_member_remove(member): bye_channel = client.get_channel(683232177227300900) msg = f"👋 잘가요 {member} {member.mention}님, 나중에 또봐요! `ಥ_ಥ`" await bye_channel.send(msg) client.run(access_token)
f07523e6955bf6c6692d2d1784d26d30f2b74990
[ "Python" ]
1
Python
owo-hub/b2n1
d6b72302beeb1b7b5b29dc68bab5faeea1543575
78033276d426ae99d93db640fd4d57199f401104
refs/heads/master
<file_sep>import React from 'react'; import { StyleSheet, View } from 'react-native'; import { NativeModules, LayoutAnimation, TouchableNativeFeedback, Text, PanResponder, Animated } from 'react-native' const { UIManager } = NativeModules UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true); const createMockCollection = nb => Array.apply(null, {length: nb }).map(Number.call, Number) const DATA = [ createMockCollection(5), createMockCollection(5) ] class Panel extends React.Component { constructor(props) { super(props) this.state = { pan: new Animated.ValueXY(), opacity: new Animated.Value(1) } } componentWillMount() { this._val = { x:0, y:0 } this.state.pan.addListener((value) => this._val = value); this.panResponder = PanResponder.create({ onStartShouldSetPanResponder: (e, gesture) => true, onPanResponderGrant: (e, gesture) => { Animated.timing(this.state.opacity, { toValue: 0.5, duration: 200 }).start() this.state.pan.setOffset({ x: this._val.x, y: this._val.y }) this.state.pan.setValue({ x:0, y:0}) }, onPanResponderMove: Animated.event([ null, { dx: this.state.pan.x, dy: this.state.pan.y } ]), onPanResponderRelease: (e, gesture) => { Animated.timing(this.state.opacity, { toValue: 1, duration: 200 }).start() } }) } render() { const panStyle = { transform: this.state.pan.getTranslateTransform() } return ( <Animated.View {...this.panResponder.panHandlers} style={[panStyle, styles.panel, { opacity:this.state.opacity }]} > <Text style={styles.label}>{this.props.label}</Text> </Animated.View> ) } } class MyView extends React.Component { render() { return ( <TouchableNativeFeedback onPress={() => this.props.onFocusChange(this.props.id)} > <View style={[ styles.view, { backgroundColor: this.props.color, flex: this.props.flex, }]}> {this.props.data.map(a => ( <Panel key={a} label={a} /> ))} </View> </TouchableNativeFeedback> ) } } export default class App extends React.Component { state = { focusOn: 0, flex : [3, 1] } _onPress = (focus) => { // Animate the update LayoutAnimation.spring() const flex = focus === 0 ? [3, 1] : [1, 3] this.setState({ focusOn: focus, flex }) } render() { const colors = ['orangered', 'greenyellow'] return ( <View style={styles.container}> {[0,1].map(i => ( <MyView id={i} key={i} data={DATA[i]} color={colors[i]} flex={this.state.flex[i]} onFocusChange={this._onPress} /> ))} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', }, view : { padding: 20, justifyContent: 'space-around', }, panel : { backgroundColor: 'snow', height: 50, alignItems: 'center', justifyContent: 'center', borderRadius: 5 }, label: { fontSize: 40, color: 'lightgrey' } }); <file_sep># RN Mock layout Workbench / mock layout, using AnimatedLayout, Animated & PanResponder. The drill is to : * swap focus between two (or more) screen views, * while drag'n-droping panels from within each of them ; * in order to sort elements, or to create (filiation) relationships between them. And by the way : learning back React _without_ redux, of which I might have got too accustomed of. To be followed... ## Licence MIT ## See also / credits * https://snack.expo.io/@yoobidev/draggable-component
f9f7b57638417d034b22304387209297394e3d03
[ "JavaScript", "Markdown" ]
2
JavaScript
atopus/rn-mock-layout
57622e275b0faa4aedebbe3fd72732d128a95fa2
c3eebc15d74b622940319fc3e34fc14609351248
refs/heads/master
<file_sep>import React, { Component } from 'react'; import {CardElement, injectStripe} from 'react-stripe-elements'; class PaymentForm extends Component { constructor(props){ super(props); } state = { stripeToken: "", name: "", email: "", productData: { price: this.props.price, description: this.props.description } } changeHandler = (e) =>{ this.setState({[e.target.name] : e.target.value}); } getStripeToken = async(e) => { e.preventDefault(); let token = await this.props.stripe.createToken({name: this.state.name}); console.log(token); console.log(this.state.productData.price); console.log(this.state.productData.description); //make the call to the NodeJs Striper Server to create the charge let response = await fetch("http://localhost:8000/charge", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: this.state.name, email: this.state.email, description: this.state.productData.description, amount: this.state.productData.price, token: token.id }) }); if (response.ok){ console.log("Charge Added"); } } render() { return ( <form onSubmit={this.getStripeToken} className="paymentForm"> <input type="text" name="name" onChange={this.changeHandler} placeholder="Your Name"/> <input type="email" name="email" onChange={this.changeHandler} placeholder="Your Email"/> <CardElement /> <input type="submit" value="Pay" /> </form> ); } } export default injectStripe(PaymentForm); <file_sep>import React, { Component } from 'react'; import {Elements} from 'react-stripe-elements'; import PaymentForm from "../payment-form/paymentForm"; class Products extends Component { state = { products: [], } componentDidMount = () =>{ console.log("products component mounted"); fetch("http://localhost:8000/") .then(response => { return response.json(); }) .then(blob => { this.setState({products: blob.data}); console.log(this.state.products); }) .catch(err => { console.log(err); }) } render() { return ( <div className="products"> <h2>Products.</h2> <div className="productsContainer"> {this.state.products.map(product => { return( <div key={product._id} className="product"> <img src={product.image} alt={product.image} /> <div> <h3>{product.name}</h3> <p>{product.description}</p> <p className="price"> &#x24; {product.amount}</p> </div> <Elements> <PaymentForm price={product.amount} description={product.description} productName = {product.name} /> </Elements> </div> ) }) } </div> </div> ); } } export default Products;
1b1e4ff86f25f956f9c84f85c18153b78b04f90a
[ "JavaScript" ]
2
JavaScript
AldoHub/React-Stripe-Elements
75bb207c66b675419b440d9498284dac0512b945
88f97f601475b0f45bfe43a375dc4e615be32415
refs/heads/master
<file_sep>jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.127.12:3306/springmvc?characterEncoding=utf-8 jdbc.username=root jdbc.password=<PASSWORD> <file_sep>package edu.dlpuzcl.springmvc.controller; import edu.dlpuzcl.springmvc.pojo.Item; import edu.dlpuzcl.springmvc.pojo.QueryVO; import edu.dlpuzcl.springmvc.service.ItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.jws.WebParam; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller public class ItemController { @Autowired private ItemService itemService; @RequestMapping public ModelAndView itemList() { ModelAndView modelAndView = new ModelAndView(); List<Item> itemList = itemService.getItemList(); modelAndView.addObject("itemList", itemList); modelAndView.setViewName("itemList"); return modelAndView; } /** * 根据ID查询商品信息,跳转修改商品界面 * 演示默认支持参数传递 * model和modelman返回数据模型 * @param model * @return */ // @RequestMapping("itemEdit") // public String itemEdit(Model model, ModelMap modelMap,HttpServletRequest request) { // ModelAndView modelAndView = new ModelAndView(); // String id = request.getParameter("id"); // //查询商品信息 // Item itemById = itemService.getItemById(new Integer(id)); // //返回数据模型 // model.addAttribute("item",itemById); // //modelAndView.addObject("item",itemById); // //modelAndView.setViewName("itemEdit"); // return "itemEdit"; // // } @RequestMapping("itemEdit") public String itemEdit(Model model, @RequestParam(value="id",required=true,defaultValue = "1") Integer ids) { //查询商品信息 Item itemById = itemService.getItemById(new Integer(ids)); //返回数据模型 model.addAttribute("item",itemById); //modelAndView.addObject("item",itemById); //modelAndView.setViewName("itemEdit"); return "itemEdit"; } /** * 修改商品的操作 * 演示pojo参数绑定 * @param item * @return */ @RequestMapping("updateItem" ) public String updateItem(Item item,Model model){ itemService.updateItem(item); model.addAttribute("item",item); model.addAttribute("msg","修改商品信息成功"); return "itemEdit"; } @RequestMapping("quItem") public String queryItem(QueryVO queryVO,Model model){ if(queryVO.getItem()!=null){ System.out.println(queryVO.getItem()); System.out.println("9999999999"); } System.out.println("88888888888999"); //模拟搜索商品 List<Item> itemListm = itemService.getItemList(); model.addAttribute("item",itemListm); return "itemList"; } }
1733a1981f35bafbdb8a3a51cb8fbf9610cec39d
[ "Java", "INI" ]
2
INI
dlpuzcl/springmvc
96be95e382717cd899f638632f729da00865761f
ff25c05fabd80dc9a4da8fdb8c26c2e59427f9b0
refs/heads/master
<repo_name>jurastrol/11-peliculasapp<file_sep>/src/app/components/pelicula/pelicula.component.ts import { Component, OnInit } from '@angular/core'; import { PeliculasService } from '../../services/peliculas.service'; import { ActivatedRoute, Router } from '@angular/router'; import { Location } from '@angular/common'; @Component({ selector: 'app-pelicula', templateUrl: './pelicula.component.html', styles: [] }) export class PeliculaComponent implements OnInit { infoPelicula: any = {}; constructor(private activatedrouter: ActivatedRoute, private location: Location, // tslint:disable-next-line: variable-name private _ps: PeliculasService) { this.activatedrouter.params.subscribe(params => { this.getPelicula(params.id); }); } ngOnInit(): void { } getPelicula(id: string) { this._ps.getPelicula(id).subscribe( pelicula => { console.log(pelicula); this.infoPelicula = pelicula; }); } regresar() { this.location.back(); } } <file_sep>/src/app/pipes/image.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'image' }) export class ImagePipe implements PipeTransform { transform(images: string): string { if ( !images ) { return 'assets/noimage.jpg'; } if ( images.length > 0) { return `http://image.tmdb.org/t/p/w300${images}`; } else { return 'assets/noimage.jpg'; } } } <file_sep>/src/app/services/peliculas.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class PeliculasService { private apikey = '<KEY>'; private urlMoviedb = 'https://api.themoviedb.org/3'; peliculas: any[] = []; constructor( private http: HttpClient) { } getPopulares() { const url = `${this.urlMoviedb}/discover/movie?sort_by=popularity.desc&api_key=${this.apikey}&language=es`; return this.http.get(url).pipe(map( (res: any) => res.results)); } getCartelera() { // tslint:disable-next-line: max-line-length const desde = new Date(); const hasta = new Date(); hasta.setDate(hasta.getDate() + 7); const desdeStr = desde.toISOString().substring(0, 10); const hastaStr = hasta.toISOString().substring(0, 10); console.log(desdeStr); console.log(hastaStr); // tslint:disable-next-line: max-line-length const url = `${this.urlMoviedb}/discover/movie?primary_release_date.gte=${desdeStr}&primary_release_date.lte=${hastaStr}&api_key=${this.apikey}&language=es`; return this.http.get( url ).pipe(map( (res: any) => res.results)); } getPopularesNinos() { // tslint:disable-next-line: max-line-length const url = `${this.urlMoviedb}/discover/movie?certification_country=US&certification.lte=G&sort_by=popularity.desc&api_key=${this.apikey}&language=es`; console.log(url); return this.http.get(url).pipe(map( (res: any) => res.results)); } getPelicula(id: string) { // tslint:disable-next-line: max-line-length const url = `${this.urlMoviedb}/movie/${id}?api_key=${this.apikey}&language=es`; console.log(url); return this.http.get(url); } buscarPelicula( texto: string) { const url = `${ this.urlMoviedb }/search/movie?query=${ texto }&sort_by=popularity.desc&api_key=${ this.apikey }&language=es`; return this.http.get( url ).pipe(map( (res: any) => { this.peliculas = res.results; return res.results; })); } } <file_sep>/src/app/components/search/search.component.ts import { Component, OnInit } from '@angular/core'; import { PeliculasService } from '../../services/peliculas.service'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styles: [] }) export class SearchComponent implements OnInit { peliculas: any[] = []; // tslint:disable-next-line: variable-name constructor( public _ps: PeliculasService) { } ngOnInit(): void { } buscarPelicula(nombre: string) { if (nombre.length === 0) { return 0; } this._ps.buscarPelicula(nombre).subscribe(data => { // console.log(data[0].poster_path); this.peliculas = data; }); } }
1915d457300b907387517b75a7ffbc8528a8dfd0
[ "TypeScript" ]
4
TypeScript
jurastrol/11-peliculasapp
c9d5efbe542a82bc40492812ceec35db1f09977f
dbb457a2540379babaa1a73a73ff508e3344dc6d
refs/heads/master
<file_sep>import { Injectable, EventEmitter } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Product } from './../models/product'; import { SearchProductInput } from '../models/searchProductInput'; import { ProductCart } from '../models/product-cart'; @Injectable() export class ProductService { // Event used to trigger the search on the ProductComponent searchProduct = new EventEmitter<SearchProductInput>(); searchInput : SearchProductInput; addProductToCart = new EventEmitter<ProductCart>(); reOrderProducts = new EventEmitter<number>(); products : ProductCart[] = []; private productsUrl = 'app/products'; // URL to web api, this code must be replaced with real web Api uri, when not using mocking constructor(private http: Http) { } getProducts(): Promise<Array<Product>> { return this.http .get(this.productsUrl) .toPromise() .then((response) => { return response.json().data as Product[]; }) .catch(this.handleError); } onSearch(searchInput: SearchProductInput){ this.searchInput = searchInput; console.log(this.searchInput); this.searchProduct.emit(searchInput); } onAddProductToCart(product: Product, qty: number){ console.log("onAddProductToCart"); let productCart = new ProductCart(); productCart.id = product.id; productCart.idCategorie = product.idCategorie; productCart.name = product.name; productCart.price = product.price; productCart.images = product.images; productCart.totalItens = qty; productCart.totalPrice = product.price; this.products.push(productCart); this.addProductToCart.emit(productCart); } onReorderProducts(ordenation : number){ console.log("Emiting Event Reordenation:" + ordenation); this.reOrderProducts.emit(ordenation); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } }<file_sep>import { InMemoryDbService } from 'angular-in-memory-web-api'; // This classe has the responsability of give the Mock information, this way its possible // to make real http request, when the real api become available, the real API can be used export class InMemoryCatalogoDbService implements InMemoryDbService { createDb() { let sites = [ { id: 1, logo: "assets/images/site/logo_ciandt.png" } ] let categories = [ { id: 1, name: "Kitchen", img: "assets/images/kitchen/kitchen_principal.jpg" }, { id: 2, name: "Sports", img: "assets/images/sports/sports_principal.jpg" }, { id: 3, name: "Office", img: "assets/images/office/office_principal.jpg" }, { id: 4, name: "Apparel",img: "assets/images/apparel/apparel_principal.jpg" } ] let products = [ { id: 1, name: "Blender High Tech", idCategorie: 1, price: 54.99, images: [ { id: 1, src: "assets/images/kitchen/kitchen_1_1.jpg" }, { id: 2, src: "assets/images/kitchen/kitchen_1_2.jpg" }, { id: 3, src: "assets/images/kitchen/kitchen_1_3.jpg" } ], description: "This is a High Tech Blender, it will prepare juices and vitamins with gorgeous flavor.", detail: "<p>Volts : 220V</p><p>Color: Black</p>" }, { id: 2, name: "Metal Silver Microwave", idCategorie: 1, price: 129.99, images: [ { id: 1, src: "assets/images/kitchen/kitchen_2_1.jpg" }, { id: 2, src: "assets/images/kitchen/kitchen_2_2.jpg" }, { id: 3, src: "assets/images/kitchen/kitchen_2_3.jpg" } ], description: "This is a Metal Siver Microwave, maintain your food always hot, and make delicious lunchs using this appliance.", detail: "<p>Volts : 220V</p><p>Color: Silver</p>" }, { id: 3, name: "Red Multifunction Toaster", idCategorie: 1, price: 34.90, images: [ { id: 1, src: "assets/images/kitchen/kitchen_3_1.jpg" }, { id: 2, src: "assets/images/kitchen/kitchen_3_2.jpg" }, { id: 3, src: "assets/images/kitchen/kitchen_3_3.jpg" } ], description: "This is a High Tech Multifunction Toaster, give a new life to that old bread.", detail: "<p>Volts : 220V</p><p>Color: Red</p>" }, { id: 4, name: "Palmeiras T-Shirt I 17/18", idCategorie: 2, price: 1499.99, images: [ { id: 1, src: "assets/images/sports/sports_1_1.jpg" }, { id: 2, src: "assets/images/sports/sports_1_2.jpg" }, { id: 3, src: "assets/images/sports/sports_1_3.jpg" } ], description: "The greatest Soccer Team of all times, when it surges the imposing green white.", detail: "<p>Size : P | M | G</p><p>Color: Green</p>" }, { id: 5, name: "São Paulo T-Shirt II 17/18", idCategorie: 2, price: 24.99, images: [ { id: 1, src: "assets/images/sports/sports_2_1.jpg" }, { id: 2, src: "assets/images/sports/sports_2_2.jpg" }, { id: 3, src: "assets/images/sports/sports_2_3.jpg" }, { id: 4, src: "assets/images/sports/sports_2_4.jpg" } ], description: "The seconde strength in Soccer League.", detail: "<p>Size : P | M | G</p><p>Color: Pink</p>" }, { id: 6, name: "<NAME>-Shirt II 17/18", idCategorie: 2, price: 1.99, images: [ { id: 1, src: "assets/images/sports/sports_3_1.jpg" }, { id: 2, src: "assets/images/sports/sports_3_2.jpg" }, { id: 3, src: "assets/images/sports/sports_3_3.jpg" } ], description: "The Gamba's T-Shirt.", detail: "<p>Second Division : Yes</p><p>World Championships: 2</p><p>Libertadores: 1</p>" }, { id: 7, name: "Football Boots Adidas 17 TF Male", idCategorie: 2, price: 89.99, images: [ { id: 1, src: "assets/images/sports/sports_4_1.jpg" }, { id: 2, src: "assets/images/sports/sports_4_2.jpg" }, { id: 3, src: "assets/images/sports/sports_4_3.jpg" } ], description: "Powerfull acessorie to make a lot of Goals against your friends.", detail: "<p>Color : White</p><p>Field: Grass</p>" }, { id: 8, name: "Backpack for notebook", idCategorie: 3, price: 59.49, images: [ { id: 1, src: "assets/images/office/office_1_1.jpg" }, { id: 2, src: "assets/images/office/office_1_2.jpg" }, { id: 3, src: "assets/images/office/office_1_3.jpg" } ], description: "Beautiful and useful backpack for notebook.", detail: "<p>Color : Black</p>" }, { id: 9, name: "Notebook IdeaPad 320", idCategorie: 3, price: 1399.99, images: [ { id: 1, src: "assets/images/office/office_2_1.jpg" }, { id: 2, src: "assets/images/office/office_2_2.jpg" }, { id: 3, src: "assets/images/office/office_2_3.jpg" } ], description: "High Tech Notebook with the latest configuration and Linux as SO.", detail: "<p>Color : Black and Silver</p><p>Volts: 220V</p>" }, { id: 10, name: "Monochrome Printer", idCategorie: 3, price: 209.99, images: [ { id: 1, src: "assets/images/office/office_3_1.jpg" }, { id: 2, src: "assets/images/office/office_3_2.jpg" }, { id: 3, src: "assets/images/office/office_3_3.jpg" } ], description: "A printer with the most economic plan and cost benefit.", detail: "<p>Color : Black</p>" }, { id: 11, name: "Black T-Shirt for Woman", idCategorie: 4, price: 39.49, images: [ { id: 1, src: "assets/images/apparel/apparel_1_1.jpg" }, { id: 2, src: "assets/images/apparel/apparel_1_2.jpg" }, { id: 3, src: "assets/images/apparel/apparel_1_3.jpg" } ], description: "Beautiful piece of clothe, your wife will be pretty happy if you get this for her.", detail: "<p>Color : Black</p>" }, { id: 12, name: "Blue Shorts for Men", idCategorie: 4, price: 18.89, images: [ { id: 1, src: "assets/images/apparel/apparel_2_1.jpg" }, { id: 2, src: "assets/images/apparel/apparel_2_2.jpg" }, { id: 3, src: "assets/images/apparel/apparel_2_3.jpg" } ], description: "A Blue shorts for man.", detail: "<p>Color : Blue</p>" }, { id: 13, name: "Captain's America T-Shirt", idCategorie: 4, price: 109.99, images: [ { id: 1, src: "assets/images/apparel/apparel_3_1.jpg" }, { id: 2, src: "assets/images/apparel/apparel_3_2.jpg" }, { id: 3, src: "assets/images/apparel/apparel_3_3.jpg" } ], description: "The best T-Shirt from store.", detail: "<p>Enterprise : Marvel</p>" } ] return { sites, categories, products }; } }<file_sep>import { Image } from "./image"; export class Product { id : number; name : string; idCategorie : number; price: number; images: Image[]; description: string; detail: string; }<file_sep>import { Injectable, EventEmitter } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import 'rxjs/add/operator/toPromise'; @Injectable() export class ShopService { action : string = ""; total = 0; shoppingCartEvent = new EventEmitter<string>(); updateTotalItens = new EventEmitter<number>(); constructor(private http: Http) { } private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } onShoppingCartEvent(action: string){ this.action = action; this.shoppingCartEvent.emit(action); } onUpdateTotalItens(totalOrderItens: number){ this.total = totalOrderItens; this.updateTotalItens.emit(totalOrderItens); } }<file_sep># desafio-web-developer Projeto Teste de E-commerce ## Instalação Clone o repositório: ``` git@github.com:cloterjr/desafio-web-developer.git ``` Instale as depêndencias: ``` npm install ``` ## Execução Abra o terminal: ``` ng serve ``` ou ``` npm start ``` ## Objetivo do Projeto Este projeto foi construido com através de um desafio proposta para a construçao de um protótipo de E-commerce. Ele tem por objetivo simular alguns processos básicos de uma loja virtual como busca, visão de detalhe do produto e adição ao carrinho de compras. ## Tecnologias Foi desenvolvido somente a aplicação Web, com os dados sendo mockados atraves da implementacao da classe **InMemoryDbService**, a qual dispobiliza dados pré-determinados durante a execução e nos permite configurar requições http reais, a vantagem é que assim é possível desenvolver praticamente todo o projeto web sem a necessidade de uma API real. O projeto foi desenvolvido utilizando o framework **Angular**. ## Principais Motivações Durante a criação deste projeto me vi forçado a entender e estudar mais a fundo a mecânica dos E-commerces, acessei alguns sites dos principais players para conseguir assimilar o fluxo correto de uma ferramenta deste seguimento. Minha principal motivação foi a utilização do framework **Angular** e dos recursos que este framework disponibiliza para o desenvolvedor, realmente é um framework fantástico, possibilita uma alta produtividade. ## Desafios encontrados Tive que dividir o tempo de entrega do desafio com as minhas tarefas do dia a dia, atualmente sou desenvolvedor Full Stack (.Net/Java) e estou bastante atribulado com meus projetos :). ## Observacoes - Busquei atender todos os requisitos funcionais solicitados. - Em relação ao layout deixei o mais proximo possivel das telas passadas. - Decidi por utilizar uma estrutura mais simplista na arquitetura do projeto. - Pasta **pages** contem os componentes "base" da aplicação. - Criei 3 servicos, sendo um responsavel por obter configuracoes do site, um por obter informações dos produtos e outro por executar eventos relacionados ao carrinho de compras. ## Futuro Projeto Pretendo melhorar ainda mais este projeto e criar também um projeto real de API para explorar e me aprofundar no processo de E-commerce. ##Linkedin Segue link do meu [perfil](https://www.linkedin.com/in/cloter-gonçalves-barbosa-jr-b9405837) no linkedin para quem quiser add, podemos conversar bastante sobre o projeto e outros desafios relacionados a Java, .Net, Angular, Banco de Dados.<file_sep>import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { ProductService } from './../../services/product.service'; import { SiteService } from './../../services/site.service'; import { Product } from './../../models/product'; import { SearchProductInput } from '../../models/searchProductInput'; import { Categorie } from '../../models/categorie'; @Component({ selector: 'product', templateUrl: './product.component.html', styleUrls: ['./product.component.scss'] }) export class ProductComponent implements OnInit { searchProductInput : SearchProductInput; products : Product[] = []; error : any; categorie : Categorie; categories : Categorie[] = []; constructor(private route: ActivatedRoute, private router: Router, private productService : ProductService, private siteService : SiteService) { } async ngOnInit() { this.productService.searchProduct.subscribe(input=>{ this.searchProductInput = input; this.getProducts(); }); this.searchProductInput = new SearchProductInput(); await this.route.params.subscribe(params => { let _search = this.route.snapshot.queryParams['search']; if(_search != undefined && _search != null && _search != ""){ this.searchProductInput.searchTerm = _search; }else{ this.searchProductInput.searchTerm = ""; } this.searchProductInput.categorieId = +params.id; if(this.searchProductInput && this.searchProductInput.categorieId != 0) { this.siteService .getCategories() .then(categories => { this.categories = categories this.categorie = this.categories.find(c=>c.id == this.searchProductInput.categorieId); }); } this.getProducts(); }); this.productService.reOrderProducts.subscribe(ordenation => { if(ordenation == 1){ this.products = this.products.sort(function(a, b){ if(a.name < b.name) return -1; if(a. name > b.name) return 1; return 0; }); }else if(ordenation == 2){ this.products = this.products.sort(function(a, b){ if(a.name < b.name) return 1; if(a. name > b.name) return -1; return 0; }); } }); } getProducts(): void { this.productService .getProducts() .then(products =>{ let productsAux: Product [] = []; // Case the searchTerm is not null, the return of the Product Services is filtered by the searchTerm variable if(this.searchProductInput && this.searchProductInput.searchTerm && this.searchProductInput.searchTerm != "") { products.forEach(p=>{ if(this.searchProductInput == undefined || this.searchProductInput.searchTerm == "" || p.name.toLowerCase().indexOf(this.searchProductInput.searchTerm.toLowerCase()) > -1){ productsAux.push(p); } }); products = productsAux; } else if(this.searchProductInput && this.searchProductInput.categorieId != 0) { products.forEach(p=>{ if(this.searchProductInput == undefined || this.searchProductInput.categorieId == 0 || p.idCategorie == this.searchProductInput.categorieId){ productsAux.push(p); } }); products = productsAux; } this.products = products; }) .catch(error => this.error = error); } viewProductDetail(productId : number) : void { this.router.navigate(['/catalog', { outlets: { 'content': ['product', productId] } }]); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { SiteService } from '../../../services/site.service'; import { ProductService } from './../../../services/product.service'; import { Site } from '../../../models/site'; import { Categorie } from '../../../models/categorie'; import { SearchProductInput } from '../../../models/searchProductInput'; import { ShopService } from '../../../services/shop.service'; @Component({ selector: 'menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.scss'] }) export class MenuComponent implements OnInit { sites : Site[] = []; categories: Categorie[] = []; categorie: Categorie; selectedCategorie : number; totalOrderItens = 0; site : Site = null; searchTerm : string = ""; error : any; logo : string = ""; constructor(private router: Router, private siteService : SiteService, private productService: ProductService, private shopService: ShopService) { } ngOnInit() { this.getSiteConfiguration(); this.getMenu(); this.shopService.updateTotalItens.subscribe(total => { this.totalOrderItens = total; }); } // Get some configuration to render the page, actually just the logo // The idea is to customize the site with a diferent logo per User getSiteConfiguration(): void { this.siteService .getSiteConfiguration() .then(sites => { if(sites.length > 0) { this.site = sites[0]; } }) .catch(error => this.error = error); } // This method has the responsability of search in the database by the term sended, or category Id. search(searchTerm : string, categorieId : number, categorie: string) : void { if(searchTerm && searchTerm != ""){ this.selectedCategorie = 0; categorieId = 0; this.searchTerm = searchTerm; if(this.router.url.indexOf('/catalog/(content:categorie/0)') > -1){ let input : SearchProductInput = new SearchProductInput(); input.searchTerm = this.searchTerm; input.categorieId = this.selectedCategorie; input.categorie = categorie; this.productService.searchProduct.emit(input); } else{ this.router.navigate(['/catalog', { outlets: { 'content': ['categorie',0] } }],{queryParams:{search:this.searchTerm}}); } }else if(categorieId && categorieId != 0){ this.selectedCategorie = categorieId; this.searchTerm = ""; searchTerm = ""; if(categorieId != 0) { this.siteService .getCategories() .then(categories => { this.categories = categories this.categorie = this.categories.find(c=>c.id == categorieId); }); } this.router.navigate(['/catalog', { outlets: { 'content': ['categorie',categorieId] } }]); } } // This Method get the list of Categories to create the main menu. getMenu() : void { this.siteService .getCategories() .then(categories => this.categories = categories) .catch(error => this.error = error); } // This method trigger the event to open the side Menu that contains the shopping cart. openShoppingCart(action : string){ this.shopService.onShoppingCartEvent(action); } //this method has the responsability of reordenate the list of products by getting the option // ZA | AZ reorder(option : number) { this.productService.onReorderProducts(+option); } } <file_sep>export class Site { id : number; logo : string; }<file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule, Routes } from '@angular/router'; import { routing } from './app.routing.module'; import { InMemoryWebApiModule } from 'angular-in-memory-web-api'; import { InMemoryCatalogoDbService } from './utils/InMemoryCatalogoDbService'; import * as $ from 'jquery'; import { AppComponent } from './app.component'; import { SiteService } from './services/site.service'; import { ProductService } from './services/product.service'; import { CatalogComponent } from './pages/catalog.component'; import { ProductComponent } from './pages/product/product.component'; import { MenuComponent } from './pages/comum/menu/menu.component'; import { SideMenuComponent } from './pages/comum/side-menu/side-menu.component'; import { ShopService } from './services/shop.service'; import { ProductDetailComponent } from './pages/product-detail/product-detail.component'; import { FooterComponent } from './pages/comum/footer/footer.component'; @NgModule({ declarations: [ AppComponent, CatalogComponent, ProductComponent, MenuComponent, SideMenuComponent, ProductDetailComponent, FooterComponent ], imports: [ BrowserModule, routing, FormsModule, HttpModule, InMemoryWebApiModule.forRoot(InMemoryCatalogoDbService, { delay: 600 }) ], providers: [ProductService, SiteService, ShopService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>export class SearchProductInput { searchTerm : string; categorieId : number; categorie : string; }<file_sep>import { ShopService } from './../services/shop.service'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ProductService } from '../services/product.service'; @Component({ selector: 'catalog', templateUrl: './catalog.component.html', styleUrls: ['./catalog.component.scss'] }) export class CatalogComponent implements OnInit { constructor(private router: Router, private productService: ProductService) { } ngOnInit() { this.productService.addProductToCart.subscribe(product=>{ window.alert(`${product.name} Added to Cart.`); }); this.router.navigate(['/catalog', { outlets: { 'content': ['categorie',0] } }]); } } <file_sep>export class Image { id : number; src : string; }<file_sep>import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Site } from './../models/site'; import { Categorie } from '../models/categorie'; @Injectable() export class SiteService { private sitesUrl = 'app/sites'; // URL to web api private categoriesUrl = 'app/categories'; // URL to web api constructor(private http: Http) { } getSiteConfiguration(): Promise<Array<Site>> { return this.http .get(this.sitesUrl) .toPromise() .then((response) => { return response.json().data as Site[]; }) .catch(this.handleError); } getCategories(): Promise<Array<Categorie>> { return this.http .get(this.categoriesUrl) .toPromise() .then((response) => { return response.json().data as Categorie[]; }) .catch(this.handleError); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } }<file_sep>import { Product } from "./product"; export class ProductCart extends Product{ totalItens: number; totalPrice : number; }<file_sep>import { ShopService } from './../../services/shop.service'; import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ProductService } from './../../services/product.service'; import { Product } from '../../models/product'; @Component({ selector: 'app-product-detail', templateUrl: './product-detail.component.html', styleUrls: ['./product-detail.component.scss'] }) export class ProductDetailComponent implements OnInit { productId : number; product : Product; error : any; constructor(private route: ActivatedRoute, private productService : ProductService) { } ngOnInit() { this.route.params.subscribe(params => { this.productId = params.id; this.getProductDetail(); }); } getProductDetail() : void { this.productService.getProducts() .then(products => { products.forEach(product=>{ if(product.id == this.productId){ this.product = product; } }); }) .catch(error => this.error = error); } addToCart(product : Product, qty: any){ if(qty == null){ qty = 0; } if(qty == 0){ window.alert("You must set the quantity to proceed with the purchase."); } else{ this.productService.onAddProductToCart(product, parseInt(qty)); } } } <file_sep>import { SearchProductInput } from './../../../models/searchProductInput'; import { Product } from './../../../models/product'; import { ShopService } from './../../../services/shop.service'; import { Component, OnInit } from '@angular/core'; import { ProductService } from '../../../services/product.service'; import { ProductCart } from '../../../models/product-cart'; @Component({ selector: 'side-menu', templateUrl: './side-menu.component.html', styleUrls: ['./side-menu.component.scss'] }) export class SideMenuComponent implements OnInit { cart : ProductCart[] = []; action : string = ""; totalOrder : number = 0; totalOrderItens : number = 0; constructor(private shopService : ShopService, private productService : ProductService) { } ngOnInit() { // the subscribe that intercepts a event and open the cart in the side menu this.shopService.shoppingCartEvent.subscribe(action => { console.log(`Abrindo carrinho pelo SideMenuComponent`); this.action = action; if(action == "open"){ this.openShoppingCart(); } else if(action == "open"){ this.closeShoppingCart(); } }); // this method has the responsability of adding the product to cart. this.productService.addProductToCart.subscribe(product => { console.log(`Product Added to Shop Cart`); console.log(product); console.log(this.cart.find(p=>p.id == product.id)); if(this.cart.find(p=>p.id == product.id)) { console.log("Product Already exists in the Cart"); console.log(this.cart); this.cart.find(p=>p.id == product.id).totalItens += product.totalItens; this.cart.find(p=>p.id == product.id).totalPrice = this.cart.find(p=>p.id == product.id).totalItens * product.price; }else{ console.log("Product don't exists in the Cart"); console.log(this.cart); let productCart = new ProductCart(); productCart.id = product.id; productCart.idCategorie = product.idCategorie; productCart.name = product.name; productCart.price = product.price; productCart.images = product.images; productCart.totalItens = product.totalItens; productCart.totalPrice = product.price * product.totalItens; this.cart.push(productCart); } this.updateTotalOrder(null,null); }); } openShoppingCart() : void { document.getElementById("mySidenav").style.width = "30%"; } closeShoppingCart() : void{ document.getElementById("mySidenav").style.width = "0"; } removeProduct(productId : number) : void{ this.cart.splice(this.cart.findIndex(p=>p.id == productId),1); this.updateTotalOrder(null, null); } // Update the values of the order updateTotalOrder(id: number, value:any) : void{ try { if(value == null){ value = 0; } let _total = parseInt(value); this.totalOrder = 0; this.totalOrderItens = 0; if(id != null && id != 0 && _total >= 0){ console.log(`Id:${id}`); console.log(`Value:${_total}`); this.cart.find(p=>p.id == id).totalItens = _total; } this.cart.forEach(product=>{ this.totalOrder+=(product.totalItens * product.price); if(product.totalItens > 0){ this.totalOrderItens+=product.totalItens; } }); this.shopService.onUpdateTotalItens(this.totalOrderItens); } catch (error) { console.log(error); } } } <file_sep>import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { CatalogComponent } from './pages/catalog.component'; import { ProductDetailComponent } from './pages/product-detail/product-detail.component'; import { ProductComponent } from './pages/product/product.component'; const appRoutes: Routes = [ { path: "", pathMatch: "full", redirectTo: "catalog" }, { path: "catalog", component: CatalogComponent, children: [ { path: 'categorie/:id', component: ProductComponent, outlet: 'content' }, { path: 'product/:id', component: ProductDetailComponent, outlet: 'content' } ] } ]; export const routing = RouterModule.forRoot(appRoutes);
881562ba34d0dd83adae5da5ad17d12b1217b38d
[ "Markdown", "TypeScript" ]
17
TypeScript
SimassoftCodeChallenge/desafio-web-developer
311f7fe02c596d146a4f4a800d1751e1e4d233f9
6bf159e6ec0afdf22653dab6872ab950d5f315fc
HEAD
<repo_name>amerizalde/html5gamedev<file_sep>/static/js/createjs_proj/level06.js (function () { var stage, shapes = [], slots = [], score = 0; /* Create a Queue */ function init() { loadComplete(); } function loadComplete() { setupStage(); addActors(); } /* Setup the Stage and Loop */ function setupStage() { // reference to the canvas stage = new create.Stage(document.getElementById('level06')); stage.enableMouseOver(); var txt = new create.Text( "Click and drag the bottom squares to the right slot.", "20px Arial", "#ff7700"); txt.textBaseline = "middle"; txt.textAlign = "center"; txt.x = stage.canvas.width / 2; txt.y = stage.canvas.height / 2; stage.addChild(txt); // create a Ticker that will call stage.update() around 60 times a second create.Ticker.setFPS(60); create.Ticker.setPaused(false); // id, callback function create.Ticker.addEventListener("tick", tick); } function tick(e) { // don't update if paused if(!e.paused){ stage.update(); } } /* Add the Actors */ function addActors() { addShapes(); addBlocks(); } function addShapes () { var colors = ['blue', 'red', 'green', 'yellow']; var i, shape, slot; for (i = 0; i < colors.length; i++) { slot = new create.Shape(); slot.graphics.beginStroke(colors[i]); slot.graphics.beginFill('#fff'); slot.graphics.drawRect(0, 0, 100, 100); slot.regX = slot.regY = 50; slot.key = i; slot.y = 80; slot.x = (i * 130) + 100; stage.addChild(slot); slots.push(slot); shape = new create.Shape(); shape.graphics.beginFill(colors[i]); shape.graphics.drawRect(0, 0, 100, 100); shape.regX = shape.regY = 50; shape.key = i; shapes.push(shape); } } function addBlocks () { var i, r, shape; var theLength = shapes.length; for (i = 0; i < theLength; i++) { r = Math.floor(Math.random() * shapes.length); shape = shapes[r]; shape.homeY = 320; shape.homeX = (i * 130) + 100; shape.y = shape.homeY; shape.x = shape.homeX; shape.addEventListener("mousedown", startDrag); stage.addChild(shape); shapes.splice(r, 1); } } function startDrag (e) { var shape = e.target, slot = slots[shape.key]; stage.setChildIndex(shape, stage.getNumChildren() - 1); stage.addEventListener('stagemousemove', function (e) { shape.x = e.stageX; shape.y = e.stageY; }); stage.addEventListener('stagemouseup', function (e) { stage.removeAllEventListeners(); var pt = slot.globalToLocal(stage.mouseX, stage.mouseY); if (shape.hitTest(pt.x, pt.y)) { shape.removeEventListener("mousedown", startDrag); score++; create.Tween.get(shape) .to({x: slot.x, y: slot.y}, 200, create.Ease.quadOut) .call(checkGame); } else { create.Tween.get(shape) .to({x: shape.homeX, y: shape.homeY}, 200, create.Ease.quadOut); } }); } function checkGame() { if (score == 4) { alert("You Win!"); } } return init(); })(); <file_sep>/static/webGL/js/rotateTut.js function createSceneTut(engine) { // creation of the scene var scene = new BABYLON.Scene(engine); // Adding a light to the scene var light = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 100, 100), scene); // Adding of the Arc Rotate Camera var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 100, new BABYLON.Vector3.Zero(), scene); // END OF BASIC SETUP // params == name, size, scene var box1 = BABYLON.Mesh.CreateBox("Box1", 6.0, scene); var box2 = BABYLON.Mesh.CreateBox("Box2", 6.0, scene); var box3 = BABYLON.Mesh.CreateBox("Box3", 6.0, scene); // arrange the primitives box1.position = new BABYLON.Vector3(-20, 0, 0); // one way to position an object box2.position.x = -10; // another way to position an object box3.position.x = 0; // rotate the boxes box1.rotation.x = Math.PI / 4; // or box1.rotation = new BABYLON.Vector3(Math.PI / 4, 0, 0); box2.rotation.y = Math.PI / 6; // scale the boxes box3.scaling.x = 2; // moving an object in relation to another object's position box3.parent = box1; box3.position.z = -10; return scene; } <file_sep>/static/js/spritesheet_remix/no_phaser.js // swap space var dragSrcEl = null; var frameWidth = null; var frameHeight = null; function handleOnClick(e){ // `e` is the mouse event // `this` is the element clicked e.preventDefault(); console.log(e); console.log(this); // get the element inside this div with the class .count. var count_div = this.querySelector('.count'); // get the current text, parse for the number, increase it by 1, and store it. var incrementor = parseInt(count_div.getAttribute('data-col-clicks')) + 1; // update the view count_div.setAttribute('data-col-clicks', incrementor); count_div.textContent = 'x ' + incrementor; } // callback that changes the object's opacity to 0.4 function handleDragStart(e) { // this.style.opacity = '0.4'; dragSrcEl = this; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/html', this.innerHTML); } // callback that allows the drop function handleDragOver(e) { if (e.preventDefault) { e.preventDefault(); } e.dataTransfer.dropEffect = 'move'; return false; }; // occurs as soon as the draggable enter the element space function handleDragEnter(e) { // this / e.target is the current hover target. this.classList.add('over'); } // occurs as soon as the draggable leaves the element space function handleDragLeave(e) { // this / e.target is previous element. this.classList.remove('over'); } function handleDrop(e) { // this / e.target is current target element. if (e.stopPropagation) { e.stopPropagation(); // stop the redirect } // don't do anything if we are dropping on the same spot. if (dragSrcEl != this){ // swap the element html with what's in the swap space dragSrcEl.innerHTML = this.innerHTML; this.innerHTML = e.dataTransfer.getData('text/html'); } return false; } function handleDragEnd(e) { // this / e.target is the source node. [].forEach.call(cols, function (col) { col.classList.remove('over'); }); } var cols = document.querySelectorAll('#columns .column'); [].forEach.call(cols, function(col) { col.addEventListener('dragstart', handleDragStart, false); col.addEventListener('dragenter', handleDragEnter, false); col.addEventListener('dragover', handleDragOver, false); col.addEventListener('dragleave', handleDragLeave, false); col.addEventListener('drop', handleDrop, false); col.addEventListener('dragend', handleDragEnd, false); col.addEventListener('click', handleOnClick, false); }); <file_sep>/static/webGL/js/lampTut.js function createSceneTut(engine) { // creation of the scene var scene = new BABYLON.Scene(engine); // Adding of the Arc Rotate Camera var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 100, new BABYLON.Vector3.Zero(), scene); // END OF BASIC SETUP // make 3 spheres var sphere1 = BABYLON.Mesh.CreateSphere("Sphere1", 10.0, 6.0, scene); var sphere2 = BABYLON.Mesh.CreateSphere("Sphere2", 2.0, 7.0, scene); var sphere3 = BABYLON.Mesh.CreateSphere("Sphere3", 10.0, 8.0, scene); // arrange the spheres sphere1.position.x = -40; sphere2.position.x = -30; // make 3 materials var materialSphere1 = new BABYLON.StandardMaterial("tex1", scene); var materialSphere2 = new BABYLON.StandardMaterial("tex2", scene); var materialSphere3 = new BABYLON.StandardMaterial("tex3", scene); // apply the materials sphere1.material = materialSphere1; sphere2.material = materialSphere2; sphere3.material = materialSphere3; // alternative assignment // sphere1.material = new BABYLON.StandardMaterial("tex1", scene); // add an alpha to the materials materialSphere1.alpha = 0.5; materialSphere2.alpha = 0.8; materialSphere3.alpha = 1.0; // WORKAROUND FOR LOADING IMAGES DURING LOCAL DEV // https://github.com/cesanta/mongoose // add textures to the materials // params = path to image, scene materialSphere1.diffuseTexture = new BABYLON.Texture("images/textures/01.jpg", scene); materialSphere2.diffuseTexture = new BABYLON.Texture("images/textures/02.jpg", scene); materialSphere3.diffuseTexture = new BABYLON.Texture("images/textures/03.jpg", scene); // set u, v scales materialSphere1.diffuseTexture.uScale = 5.0; materialSphere1.diffuseTexture.vScale = 5.0; materialSphere1.diffuseTexture.uScale = 2.0; materialSphere1.diffuseTexture.vScale = 2.0; materialSphere1.diffuseTexture.uScale = 1.0; materialSphere1.diffuseTexture.vScale = 1.0; // materialSphere1.diffuseTexture.hasAlpha = true; // materialSphere1.wireframe = true; // Adding a light to the scene // params == name, position, scene var pointy1 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 100, 100), scene); pointy1.diffuse = new BABYLON.Color3(1, 0, 0); // red diffuse pointy1.specular = new BABYLON.Color3(1, 1, 1); // white specular pointy1.intensity = 0.8; var sunny1 = new BABYLON.DirectionalLight("Dir0", new BABYLON.Vector3(10, 100, 100), scene); sunny1.diffuse = new BABYLON.Color3(0.1, 0.9, 0.9); sunny1.specular = new BABYLON.Color3(1, 1, 1); return scene; } <file_sep>/static/js/testingGround/game_bak.js // create a Game object BasicGame.Game = function (game) { }; // add methods and properties BasicGame.Game.prototype = { // the Phaser Game Loop -- preload, create, [update, render, repeat] create: function () { this.ROWS = 8; this.COLS = 6; this.SCALE = 0.52; this.TILE_W = 141 * this.SCALE; this.TILE_H = 190 * this.SCALE; this.table = new Array(this.ROWS * this.COLS); this.pick_one = null; this.pick_two = null; this.matchedcount = this.table.length / 2; this.setTable(); }, update: function () { if (this.showText) { this.returnText = this.add.text( this.game.width / 2, this.game.height / 2 + 20, 'Press Z or Tap Game to go back to Main Menu', {font: '16px Audiowide', fill: '#fff'}); this.returnText.anchor.setTo(0.5, 0.5); if (this.input.activePointer.isDown) { this.quitGame(); } } }, // create-related functions setTable: function () { var suits = ["Clubs", "Hearts", "Diamonds", "Spades"]; var ranks = ["A", "K", 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2']; for (var i = 0; i < this.ROWS * this.COLS; i++) { var suit = suits[Math.floor(Math.random() * suits.length)]; var rank = ranks[Math.floor(Math.random() * ranks.length)]; var cardFrame = "card" + suit + rank; this.table[i] = cardFrame; this.table[this.table.length - i] = cardFrame; } // create a sprite group this.cards = this.add.group(); // add physics body to all sprites created // must be set before the sprites are added this.cards.enableBody = true; this.cards.physicsBodyType = Phaser.Physics.ARCADE; // create sprites this.cards.createMultiple(this.ROWS * this.COLS, "cards", "cardBack_blue2"); this.cards.setAll('outOfBoundsKill', true); this.cards.setAll('checkWorldBounds', true); this.cards.setAll('inputEnabled', true); // force a property into the sprite object this.cards.setAll('reveal', 0, false, false, 0, true); for (var i = 0; i < this.ROWS * this.COLS; i++) { // get the first sprite not in use. var card = this.cards.getFirstExists(false); // set the index here so that it matches up with a index in this.table // for lookup in revealCard() card.reveal = i; // move to position card.reset( i % this.COLS * this.TILE_W, // x Math.floor(i / this.COLS) * this.TILE_H // y ); // adjust to screen card.scale.setTo(this.SCALE, this.SCALE); // add event card.events.onInputDown.add(this.revealCard, this); } }, quitGame: function (pointer) { // Here you should destroy anything you no longer need. // Stop music, delete sprites, purge caches, free resources, all that good stuff. this.cards.destroy(); // Then let's go back to the main menu. this.state.start('MainMenu'); }, pickACard: function (card, pointer) { var suits = ["Clubs", "Hearts", "Diamonds", "Spades"]; var ranks = ["A", "K", 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2']; // https://stackoverflow.com/questions/4550505/getting-random-value-from-an-array var suit = suits[Math.floor(Math.random() * suits.length)]; var rank = ranks[Math.floor(Math.random() * ranks.length)]; // set the frame to a valid name from the 'cards' atlas. card.frameName = "card" + suit + rank; }, revealCard: function (card, pointer) { // flip back the previous picks if (this.pick_one && this.pick_two) { this.flip(); } // reveal the pick card.frameName = this.table[card.reveal]; // juice up the interaction card.bringToTop(); this.add.tween(card.scale).to( {x: 0.75, y: 0.75}, 100, Phaser.Easing.Bounce.Out, true, 0, false, true); if (this.pick_one === null) { // the first pick this.pick_one = card; } else { // the second pick this.pick_two = this.pick_one; this.pick_one = card; } if (this.pick_one && this.pick_two) { // we have two picks so check for a match this.checkMatches(); } }, checkMatches: function () { if (this.pick_one.frameName === this.pick_two.frameName) { // MATCH! this.dissolve(); // decrement so we know if the game is over this.matchedcount--; if (this.matchedcount <= 0) { this.endGameText(true); } } else { // NOT A MATCH! return; } }, flip: function () { // "flipping the cards back over" this.pick_one.frameName = "cardBack_blue2"; this.pick_two.frameName = "cardBack_blue2"; this.pick_one = null; this.pick_two = null; }, dissolve: function () { // the card sprites are set to kill themselves if they run out of bounds, // so no need to call it explicitly. // this is all the dropping animation. this.pick_one.bringToTop(); this.pick_two.bringToTop(); this.pick_one.body.reset(this.pick_one.x, this.pick_one.y); this.pick_one.body.velocity.y = 1000; this.pick_two.body.reset(this.pick_two.x, this.pick_two.y); this.pick_two.body.velocity.y = 1000; this.add.tween(this.pick_one.body.velocity.y).to( 1000, 250, Phaser.Easing.Back.In, true, 0, false, false); this.add.tween(this.pick_two.body.velocity.y).to( 1000, 100, Phaser.Easing.Back.In, true, 0, false, false); this.add.tween(this.pick_one.scale).to( {x: 0.0, y: 0.0}, 1000, Phaser.Easing.Bounce.Out, true, 0, false, false); this.add.tween(this.pick_two.scale).to( {x: 0.0, y: 0.0}, 1000, Phaser.Easing.Bounce.Out, true, 0, false, false); }, endGameText: function (win) { // play again? this.showText = true; }, }; <file_sep>/static/js/flappy_clone/game_over.js // create the GameOver object BasicGame.GameOver = function (game) { }; // add methods and properties BasicGame.GameOver.prototype = { create: function () { this.setupBackground(); this.setupPlayer(); this.setupNPC(); this.setupBullets(); //this.setupSFX(); // the controls this.cursors = this.input.keyboard.createCursorKeys(); this.setupKeys() }, // create-related functions setupBackground: function () { }, setupPlayer: function () { }, setupNPC: function () { }, setupBullets: function () { }, setupKeys: function () { }, setupSFX: function () { }, // update-related functions update: function () { this.processPlayerInput(); }, checkCollisions: function () { }, guineaHit: function (enemy, bullet) { }, damageNPC: function (enemy, amount) { }, tweenFX: function (npc) { }, textFX: function (npc) { }, wordTween: function(word) { }, processPlayerInput: function () { if (this.input.keyboard.isDown(Phaser.Keyboard.Z) || this.input.activePointer.isDown) { // quit here } }, quitGame: function (pointer) { // Here you should destroy anything you no longer need. // Stop music, delete sprites, purge caches, free resources, all that good stuff. // Then let's go back to the main menu. this.state.start('MainMenu'); }, }; <file_sep>/static/js/createjs_proj/level09.js (function () { var stage, livesTxt, gameOverTxt, win; var answer = "CREATEJS IS&AWESOME", abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", lives = 5, lettersNeeded = 0; // counter /* Create a Queue */ function init() { loadComplete(); } function loadComplete() { setupStage(); drawBoard(); drawLetters(); drawMessages(); } /* Setup the Stage and Loop */ function setupStage() { // reference to the canvas stage = new create.Stage(document.getElementById('level09')); // create a Ticker that will call stage.update() around 60 times a second create.Ticker.setFPS(60); create.Ticker.setPaused(false); // id, callback function create.Ticker.addEventListener("tick", tick); } function tick(e) { // don't update if paused if(!e.paused){ stage.update(); } } function drawBoard () { // declare all variables you will use in the function before using them // not required, but highly recommended var i, c, box; var xPos = 20, // start position for first box yPos = 90; for (i = 0; i < answer.length; i++) { c = answer[i]; // draw a box per character, skipping any spaces // line breaks are handled in the next block if (c != " " && c != "&") { lettersNeeded++; box = new create.Shape(); box.graphics.beginStroke("#000"); box.graphics.drawRect(0, 0, 20, 24); box.regX = 10; box.regY = 12; box.x = xPos; box.y = yPos; box.name = 'box_' + i; box.key = c; stage.addChild(box); } xPos += 26; // line break if (c === '&') { yPos += 40; xPos = 20; } } } function drawMessages () { var txt = new create.Text("WORD GAME", "26px Arial"); txt.color = "#990000"; txt.x = txt.y = 10; stage.addChild(txt); livesTxt = new create.Text("LIVES: " + lives, "16px Arial"); livesTxt.textAlign = 'right'; livesTxt.y = 16; livesTxt.x = stage.canvas.width - 10; stage.addChild(livesTxt); } function drawLetters () { // draw the alphabet pool var i, c, txt, btn; var cnt = 0, xPos = 20, yPos = 200; for (i = 0; i < abc.length; i++) { c = abc[i]; btn = new create.Shape(); btn.graphics.beginFill("#000"); btn.graphics.beginStroke("#000"); btn.graphics.drawRect(0, 0, 20, 24); btn.regX = 10; btn.regY = 12; btn.x = xPos; btn.y = yPos; stage.addChild(btn); txt = new create.Text(c); txt.color = "#FFF"; txt.textAlign = 'center'; txt.textBaseline = 'middle'; txt.x = xPos; txt.y = yPos; stage.addChild(txt); // add pointer interaction btn.txt = txt; btn.addEventListener('click', onLetterClick); xPos += 24; cnt++; if (cnt === 13) { yPos += 30; xPos = 20; } } } function onLetterClick (e) { var btn = e.target, txt = btn.txt; btn.removeEventListener('click', onLetterClick); checkForMatches(txt); checkGame(); } function checkForMatches (txt) { // check if the letter chosen is a match. var i, c, box, txtClone; var letter = txt.text, match = false, len = answer.length; for (i = 0; i < len; i++) { c = answer[i]; if (c === " " || c == '&') { continue; } // check every box, if the letter matches the key of that box, // clone the letter to that box (the reveal!). box = stage.getChildByName('box_' + i); if (box.key === letter) { lettersNeeded--; match = true; txtClone = txt.clone(); txtClone.color = "#000"; txtClone.x = box.x; txtClone.y = box.y; stage.addChild(txtClone); } } // remove the letter from the pool stage.removeChild(txt); // if there was no match, lose a life. if (!match) { lives--; livesTxt.text = "LIVES: " + lives; } } function checkGame () { if (lettersNeeded === 0) { win = true; gameOver(); } else if (lives === 0) { win = false; gameOver(); } } function gameOver () { stage.removeAllChildren(); var msg = win ? "YOU WIN!" : "YOU LOSE."; gameOverTxt = new create.Text(msg, "36px Arial"); gameOverTxt.alpha = 0; gameOverTxt.color = win ? 'blue' : 'red'; gameOverTxt.textAlign = 'center'; gameOverTxt.textBaseline = 'middle'; gameOverTxt.x = stage.canvas.width / 2; gameOverTxt.y = stage.canvas.height / 2; stage.addChild(gameOverTxt); create.Tween.get(gameOverTxt).to({alpha: 1}, 1000); } return init(); })(); <file_sep>/notes.md ### Genres - shoot'm'up -- started - beat'm'up - platformer/runner - puzzle -- started - exploration/adventure [look, take, use, talk to, give to] - strategy - simulator - rpg - fps shooter #### Composite Element Ideas Final Death, Real-Time, Stealth, NewGame+, Nintendo Hard, World Altering, Character Growth, Quicktime Events, One Button, Mini-Game, Character Customization, Loot, Programmable, Physics, Procedural Content, Sandbox/Persistence, Turn-Based, Rock-Paper-Scissors, A.I. #### A two-stat magic system Player: { health: 0, stamina: 0, power: 0, } Stamina becomes the energy element, with power being the scalar. Health remains the lifespan. Stamina drains when action is taken and renews rapidly under normal conditions, and slowly when under a negative effect. Under positive effect it doesnt drain at all. Power is the scalar by which [damage/shield duration] is calculated. Increasing power does not increase capacity, only damage. Stamina increases capacity for action, but not the power of the action. <file_sep>/static/js/toadAttack/app.js window.onload = function () { // the canvas var canvas = document.getElementById('gameContainer'); if (!BABYLON.Engine.isSupported()) { window.alert('Browser not supported'); } else { var engine = new BABYLON.Engine(canvas, true); // create scene scene = setupScene(engine); scene.activeCamera.attachControl(canvas); // Register a render loop engine.runRenderLoop(function () { scene.render(); gameUpdate(); }); // on resize events window.addEventListener("resize", function () { engine.resize(); }); } }; <file_sep>/static/js/shmup/mainMenu.js BasicGame.MainMenu = function (game) { }; BasicGame.MainMenu.prototype = { create: function () { // sprites are loaded in the order added here. this.sea = this.add.tileSprite(0, 0, this.game.width, this.game.height, 'sea'); this.sea.autoScroll(0, 5); this.setupPlayer(); this.musicPregame = this.add.audio('pregame'); this.musicPregame.play("", 0, 1, true); this.add.tween(this.musicPregame) .from({volume: 0}, 2000, Phaser.Easing.Linear.Out, true); this.add.tween(this.player) .from({y: this.world.height + 50}, 5000, Phaser.Easing.Elastic.Out, true); this.titlePNG = this.add.sprite(this.world.centerX, 200, 'title'); this.titlePNG.anchor.setTo(0.5, 0.5); this.loadingText = this.add.text( this.game.width / 2, this.game.height / 2, "Press Z or tap/click game to start", { font: "20px Audiowide", fill: "#fff" }); this.loadingText.anchor.setTo(0.5, 0.5); this.add.text( this.game.width / 2, this.game.height - 64, "image assets Copyright (c) 2002 <NAME>", { font: "10px monospace", fill: "#fff", align: "center"}).anchor.setTo(0.5, 0.5); this.add.text( this.game.width / 2, this.game.height - 32, "sound assets Copyright (c) 2012 - 2013 <NAME>", { font: "10px monospace", fill: "#fff", align: "center"}).anchor.setTo(0.5, 0.5); }, update: function () { if (this.input.keyboard.isDown(Phaser.Keyboard.Z) || this.input.activePointer.isDown) { this.startGame(); } // Do some nice funky main menu effect here }, startGame: function (pointer) { // Ok, the Play Button has been clicked or touched, so let's stop the music (otherwise it'll carry on playing) // this.musicPregame.stop(); this.musicPregame.stop(); // And start the actual game this.state.start('Game'); }, // create-related functions setupPlayer: function () { // ## PLAYER this.player = this.add.sprite( this.game.width / 2, this.game.height - 100, 'player'); this.player.anchor.setTo(0.5, 0.5); this.player.animations.add('fly', [0, 1, 2], 20, true); this.player.play('fly'); }, }; <file_sep>/static/webGL/js/sceneTut.js function createSceneTut(engine) { // creation of the scene var scene = new BABYLON.Scene(engine); // Adding a light to the scene var light = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 100, 100), scene); // Adding of the Arc Rotate Camera var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 100, new BABYLON.Vector3.Zero(), scene); // END OF BASIC SETUP // params == name, size, scene var box = BABYLON.Mesh.CreateBox("Box", 6.0, scene); // params == name, # of segments, size, scene var sphere = BABYLON.Mesh.CreateSphere("Sphere", 10.0, 10.0, scene); // params == name, size, scene var plane = BABYLON.Mesh.CreatePlane("Plane", 50.0, scene); // params == name, height, diameterTop, diameterBot, tessellation, scene, updatable var cylinder = BABYLON.Mesh.CreateCylinder("Cylinder", 3, 3, 3, 6, scene, false); // params = name, diameter, thickness, tesselation, scene, updatable var torus = BABYLON.Mesh.CreateTorus("Torus", 5, 1, 10, scene, false); // arrange the primitives box.position = new BABYLON.Vector3(-10, 0, 0); sphere.position = new BABYLON.Vector3(-10, 30, 0); plane.position = new BABYLON.Vector3(30, 5, 0); cylinder.position = new BABYLON.Vector3(-30, 0, 5); torus.position = new BABYLON.Vector3(-10, 0, -30); return scene; } <file_sep>/static/js/spritesheet_remix/mainMenu.js // global variable for access inside callbacks var spriteData = { img: new Image(), width: null, height: null, rows: null, columns: null, }; function setSpriteData () { spriteData.width = document.querySelector('[name="width"]').value; spriteData.height = document.querySelector('[name="height"]').value; spriteData.columns = document.querySelector('[name="columns"]').value; spriteData.rows = document.querySelector('[name="rows"]').value; // console.log(spriteData.img.src); } BasicGame.MainMenu = function (game) { }; BasicGame.MainMenu.prototype = { create: function () { // sprites are loaded in the order added here. // this.bg = this.add.tileSprite(0, 0, this.camera.width, this.camera.height, 'background'); // title /*this.titlePNG = this.add.sprite( this.world.centerX, 200, 'backgrounds', 'title.png'); this.titlePNG.anchor.setTo(0.5, 0.5); this.add.tween(this.titlePNG).from({y: -8}, 1000, Phaser.Easing.Bounce.Out, true);*/ this.loadingText = this.add.text( this.camera.width / 2, this.camera.height / 2, "DRAG AND DROP your image file HERE!", { font: "30px monospace", fill: "#ff66ff" }); this.loadingText.anchor.setTo(0.5, 0.5); this.add.text( this.camera.width / 2, this.camera.height - 32, "Copyright (c) 2014 <NAME>", { font: "12px monospace", fill: "#ff00ff", align: "center"}).anchor.setTo(0.5, 0.5); //robertnyman.com/2011/03/10/using-html5-canvas-drag-and-drop-and-file-api-to-offer-the-cure/ this.setupDrop(); }, update: function () { // if all sprite data is entered correctly, continue to game state. if (spriteData.img.src && this.loadingText.text == "DRAG AND DROP your image file HERE!") { // console.log(spriteData.img.src) this.loadingText.text = "Thanks! Please complete the form and submit!"; } if ((spriteData.img.src !== null) && (spriteData.width !== null) && (spriteData.height !== null) && (spriteData.rows !== null) && (spriteData.columns !== null)) { $("#spriteData").hide(); this.state.start('Game'); } }, startGame: function (pointer) { // Ok, the Play Button has been clicked or touched, so let's stop the music (otherwise it'll carry on playing) // this.musicPregame.stop(); // And start the actual game // this.state.start('Game'); }, // create-related functions setupDrop: function () { // get a handle on the canvas through Phaser var canvas = this.game.context.canvas; // override the dragover and drop events canvas.addEventListener("dragover", function (evt) { evt.preventDefault(); }, false); canvas.addEventListener("drop", function (evt) { evt.preventDefault(); var files = evt.dataTransfer.files; if (files.length > 0) { var file = files[0]; // verify dropped file is an image, // and that FileReader is even usable on this browser if (typeof FileReader !== "undefined" && file.type.indexOf("image") != -1) { var reader = new FileReader(); reader.onload = function (evt) { spriteData.img.src = evt.target.result; }; reader.readAsDataURL(file); } } }, false); }, }; <file_sep>/static/js/createjs_proj/level02.js (function () { var stage; /* Create a Queue */ function init() { loadComplete(); } function loadComplete() { setupStage(); addActors(); } /* Setup the Stage and Loop */ function setupStage() { // reference to the canvas stage = new create.Stage(document.getElementById('level02')); // create a Ticker that will call stage.update() around 60 times a second create.Ticker.setFPS(60); create.Ticker.setPaused(false); // id, callback function create.Ticker.addEventListener("tick", tick); } function tick(e) { // don't update if paused if(!e.paused){ stage.update(); } } /* Add the Actors */ function addActors() { // draw a red square var g = new create.Graphics().beginStroke("#000") .beginFill("#FF0000") .drawRect(0, 0, 100, 100); // attach it to a Shape container var square = new create.Shape(g); square.x = square.y = 100; // add the square Shape to the canvas stage.addChild(square); // another way var circle = new create.Shape(); circle.graphics.beginStroke("#000"); circle.graphics.beginFill("#00FFFF"); circle.graphics.drawCircle(0, 0, 50); circle.x = 250; circle.y = 70; stage.addChild(circle); // star var poly = new create.Shape(); poly.graphics.beginStroke("#000"); poly.graphics.beginFill("#FF00FF"); poly.graphics.drawPolyStar(0, 0, 60, 6, 0.6); poly.x = 480; poly.y = 70; stage.addChild(poly); // lines var tri = new create.Shape(); tri.graphics.beginStroke("#000"); tri.graphics.beginFill("#00FF00"); tri.graphics.moveTo(stage.canvas.clientWidth / 2, stage.canvas.clientHeight / 2) .lineTo(0, stage.canvas.clientHeight / 2) .lineTo(100, 100) .lineTo(stage.canvas.clientWidth / 2, stage.canvas.clientHeight / 2); tri.x = 20; tri.y = 150; stage.addChild(tri); } return init(); })(); <file_sep>/static/js/flappy_clone/game.js // create a Game object BasicGame.Game = function (game) { }; // add methods and properties BasicGame.Game.prototype = { create: function () { this.setupBackground(); this.setupPlayer(); this.setupKeys() }, // create-related functions setupBackground: function () { this.bg = this.add.tileSprite(0, 0, this.world.width, this.world.height, 'background'); }, setupPlayer: function () { }, setupNPC: function () { }, setupKeys: function () { // lock these keys out of the browser this.input.keyboard.addKeyCapture( [ Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT, Phaser.Keyboard.SPACEBAR ] ); }, setupSFX: function () { }, // update-related functions update: function () { this.checkCollisions(); this.processPlayerInput(); }, checkCollisions: function () { }, guineaHit: function (enemy, bullet) { }, damageNPC: function (enemy, amount) { }, tweenFX: function (npc) { }, textFX: function (npc) { }, wordTween: function(word) { }, processPlayerInput: function () { }, fire: function() { }, quitGame: function (pointer) { // Here you should destroy anything you no longer need. // Stop music, delete sprites, purge caches, free resources, all that good stuff. // Then let's go back to the main menu. this.state.start('GameOver'); }, }; <file_sep>/static/js/testingGround/game.js // create a Game object BasicGame.Game = function (game) { }; // add methods and properties BasicGame.Game.prototype = { create: function () { this.setupBackground(); this.setupPlayer(); this.setupNPC(); this.setupBullets(); //this.setupSFX(); // the controls this.cursors = this.input.keyboard.createCursorKeys(); this.setupKeys() }, // create-related functions setupBackground: function () { this.bg = this.add.tileSprite(0, 0, this.world.width, this.world.height, 'background'); }, setupPlayer: function () { this.player = this.add.sprite( this.world.centerX, this.world.height - 80, 'guinea', 'playerShip1_green.png'); this.player.anchor.setTo(0.5, 0.5); this.player.scale = {'x': 0.5, 'y': 0.5}; this.game.physics.enable(this.player, Phaser.Physics.ARCADE); this.player.speed = 300; this.player.body.collideWorldBounds = true; // 20x20 pixel hitbox, centered a little bit higher than the center this.player.body.setSize(20, 20, 0, -5); this.weaponLevel = 0; }, setupNPC: function () { this.gp1 = this.add.sprite( this.world.centerX, this.world.centerY, 'guinea', 'ufoRed.png'); this.gp1.anchor.setTo(0.5, 0.5); this.gp1.scale = {'x': 0.5, 'y': 0.5}; this.gp1.health = 500; this.game.physics.enable(this.gp1, Phaser.Physics.ARCADE); }, setupBullets: function () { // add an empty sprite group into the game this.bulletPool = this.add.group(); // add physics to the whole group this.bulletPool.enableBody = true; this.bulletPool.physicsBodyType = Phaser.Physics.ARCADE; // add 50 bullet sprites in the group. // by default, this uses the first frame of the sprite sheet and sets // the initial state as non-existing (i.e killed/dead) this.bulletPool.createMultiple(3, 'guinea', 'laserGreen03.png'); // sets the anchors of all sprites this.bulletPool.setAll('anchor.x', 0.5); this.bulletPool.setAll('anchor.y', 0.5); // Automatically kill the sprites when they go out of bounds this.bulletPool.setAll('outOfBoundsKill', true); this.bulletPool.setAll('checkWorldBounds', true); this.nextShotAt = 0; this.shotDelay = 250; }, setupKeys: function () { // lock these keys out of the browser this.input.keyboard.addKeyCapture( [ Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT, Phaser.Keyboard.SPACEBAR ] ); }, setupSFX: function () { this.testSnd = this.add.audio('sfx2'); }, // update-related functions update: function () { this.checkCollisions(); this.processPlayerInput(); }, checkCollisions: function () { // Bullet/ Guinea Collision this.physics.arcade.overlap( // (obj1, obj2, callback, optional_callback, context) this.bulletPool, this.gp1, this.guineaHit, null, this); }, guineaHit: function (enemy, bullet) { // the order of the incoming arguments matters // the first argument is the obj2 of the collision, // and the second argument is the obj1. 7/19/2014 // remove the bullet bullet.kill(); // enemy reaction this.damageNPC(enemy, 1); }, damageNPC: function (enemy, amount) { // show the bat word this.textFX(enemy); // decrement the enemy health enemy.damage(amount); // if still alive, animate if (enemy.alive) { this.tweenFX(enemy); } }, tweenFX: function (npc) { var duration = 150; // this is fast enough that the sprites return to their // original position when tween-spammed. this.add.tween(npc).from({y: npc.y - 10}, duration, Phaser.Easing.Back.Out, true); }, textFX: function (npc) { // add a sprite from the wordPool with a lifespan of 150 offset from the npc location // at a random rotation? var i = Math.floor(Math.random() * 16); var word = this.add.sprite( npc.x - 10, npc.y - 10, "batwords", i); word.scale = {'x': 0.25, 'y': 0.25}; word.anchor.setTo(0.5, 0.5); word.lifespan = 150; this.wordTween(word); }, wordTween: function(word) { this.add.tween(word).to({x: word.x - 20, y: word.y - 20}, word.lifespan, Phaser.Easing.Linear.Out, true); this.add.tween(word).to({alpha: 0}, word.lifespan, Phaser.Easing.Linear.Out, true); }, processPlayerInput: function () { var damper = 0.77; this.player.body.velocity.x = 0; this.player.body.velocity.y = 0; // horizontal movement if (this.cursors.left.isDown) { this.player.body.velocity.x = -this.player.speed; this.bg.autoScroll(50, 5); } else if (this.cursors.right.isDown) { this.player.body.velocity.x = this.player.speed; this.bg.autoScroll(-50, 5); } else { this.bg.autoScroll(0, 10); } // attacking if (this.input.keyboard.isDown(Phaser.Keyboard.Z) || this.input.activePointer.isDown) { /*if (this.returnText && this.returnText.exists) { this.quitGame(); } else { this.fire(); }*/ this.fire(); } }, fire: function() { // delay -- No firing if dead either! if (!this.player.alive || this.nextShotAt > this.time.now) { return; } this.nextShotAt = this.time.now + this.shotDelay; var bullet; if (this.weaponLevel === 0) { // too many bullets on screen! if (this.bulletPool.countDead() === 0) return; bullet = this.bulletPool.getFirstExists(false); // Reset (revive) the sprite and place it in a new location bullet.reset(this.player.x, this.player.y - 20); bullet.body.velocity.y = -500; } else { if (this.bulletPool.countDead() < this.weaponLevel * 2) return; for (var i = 0; i < this.weaponLevel; i++) { bullet = this.bulletPool.getFirstExists(false); // spawn left bullet slightly off center bullet.reset(this.player.x - (10 + i * 6), this.player.y - 20); this.physics.arcade.velocityFromAngle( -95 - i * 10, 500, bullet.body.velocity); bullet = this.bulletPool.getFirstExists(false); // spawn right bullet slightly right off center bullet.reset(this.player.x + (10 + i * 6), this.player.y - 20); this.physics.arcade.velocityFromAngle( -85 + i * 10, 500, bullet.body.velocity); } } }, quitGame: function (pointer) { // Here you should destroy anything you no longer need. // Stop music, delete sprites, purge caches, free resources, all that good stuff. this.player.destroy(); this.bg.destroy(); this.gp1.destroy(); this.testSnd.stop(); this.testSnd = null; // Then let's go back to the main menu. this.state.start('Game'); }, render: function () { this.game.debug.body(this.player); this.game.debug.body(this.gp1); } }; <file_sep>/static/js/toadAttack/game.js var TOAD_MODEL; var ENDINGS = []; var ENEMIES = []; function setupScene(engine) { // create scene var scene = new BABYLON.Scene(engine); // pass the scene to the setup functions setupLights(scene); setupCameras(scene); addLanes(scene, scene.activeCamera); //return the complete scene return scene; } function setupLights(scene) { // add light var light = new BABYLON.DirectionalLight( "Hemi", new BABYLON.Vector3(0, -1, 0), scene); var white = new BABYLON.Color3(1, 1, 1); var nearBlack = new BABYLON.Color3(.01, .01, .01); light.diffuse = white; light.groundColor = white; light.specular = white; } function setupCameras(scene) { // add camera var camera = new BABYLON.FreeCamera( "Camera", new BABYLON.Vector3(0, 4, -10), scene); camera.setTarget(new BABYLON.Vector3(0, 0, 10)); } function addPrimitives(scene) { var box = BABYLON.Mesh.CreateBox("Box", 6.0, scene); var sphere = BABYLON.Mesh.CreateSphere("Sphere", 10.0, 3.0, scene); var plane = BABYLON.Mesh.CreatePlane("Plane", 50.0, scene); var cylinder = BABYLON.Mesh.CreateCylinder( "cylinder", 3, 3, 3, 6, scene, false); var torus = BABYLON.Mesh.CreateTorus( "torus", 5, 1, 10, scene, false); box.position.x = -10; plane.rotation.y = 180; plane.position.z = -20; } function axis(scene, size) { //X axis var x = BABYLON.Mesh.CreateCylinder("x", size, 0.1, 0.1, 6, scene, false); x.material = new BABYLON.StandardMaterial("xColor", scene); x.material.diffuseColor = new BABYLON.Color3(1, 0, 0); x.position = new BABYLON.Vector3(size/2, 0, 0); x.rotation.z = Math.PI / 2; //Y axis var y = BABYLON.Mesh.CreateCylinder("y", size, 0.1, 0.1, 6, scene, false); y.material = new BABYLON.StandardMaterial("yColor", scene); y.material.diffuseColor = new BABYLON.Color3(0, 1, 0); y.position = new BABYLON.Vector3(0, size / 2, 0); //Z axis var z = BABYLON.Mesh.CreateCylinder("z", size, 0.1, 0.1, 6, scene, false); z.material = new BABYLON.StandardMaterial("zColor", scene); z.material.diffuseColor = new BABYLON.Color3(0, 0, 1); z.position = new BABYLON.Vector3(0, 0, size/2); z.rotation.x = Math.PI / 2; }; function addLanes(scene, camera) { var LANES = 3; var LANE_INTERVAL = 5; var LANE_POSITIONS = []; var createLane = function (id, pos) { var lane = BABYLON.Mesh.CreateBox("lane" + id, 1, scene); lane.scaling.y = 0.1; lane.scaling.x = 3.0; lane.scaling.z = 800; lane.position.x = pos; lane.position.z = lane.scaling.z / 2 - 200; var ground = new BABYLON.StandardMaterial("ground", scene); var texture = new BABYLON.Texture("assets/toadAttack/ground.jpg", scene); texture.uScale = 40; texture.vScale = 2; ground.diffuseTexture = texture; lane.material = ground; }; var createEnding = function(id, pos) { var ending = BABYLON.Mesh.CreateGround(id, 3, 4, 1, scene); ending.position.x = pos; ending.position.y = 0.1; ending.position.z = 1.0; var mat = new BABYLON.StandardMaterial("endingMat", scene); mat.diffuseColor = new BABYLON.Color3(0.8, 0.2, 0.2); ending.material = mat; return ending; }; var currentLanePosition = LANE_INTERVAL * -1 * (LANES / 2); for (var i = 0; i < LANES; i++) { LANE_POSITIONS[i] = currentLanePosition; createLane(i, currentLanePosition); var e = createEnding(i, currentLanePosition); ENDINGS.push(e); currentLanePosition += LANE_INTERVAL; } camera.position.x = LANE_POSITIONS[Math.floor(LANES / 2)]; // import a .babylon model file BABYLON.SceneLoader.ImportMesh( "red_toad", // key "assets/toadAttack/", // path "toad.babylon", // file scene, function (meshes) { var m = meshes[0]; m.position = new BABYLON.Vector3(0, 2, 0); m.rotation.y = 90; m.isVisible = true; m.scaling = new BABYLON.Vector3(0.5, 0.5, 0.5); TOAD_MODEL = m; } ); var createEnemy = function () { // starting position of toads var pos_z = 100; // random lane var pos_x = LANE_POSITIONS[Math.floor(Math.random() * LANES)]; // create a clone of the template var shroom = TOAD_MODEL.clone(TOAD_MODEL.name); shroom.id = TOAD_MODEL.name + (ENEMIES.length + 1); shroom.killed = false; shroom.visible = true; shroom.position = new BABYLON.Vector3( pos_x, shroom.position.y / 2, pos_z); ENEMIES.push(shroom); }; setInterval(createEnemy, 1000); } function gameUpdate() { ENEMIES.forEach(function (shroom) { if (shroom.killed) { // nothing } else { shroom.position.z -= 0.5; shroom.rotation.y += 0.1; } }); } <file_sep>/static/js/createjs_proj/shared.js create = createjs; const KEY_A = 65, KEY_S = 83, KEY_D = 68, KEY_W = 87, KEY_E = 69, KEY_Q = 81, KEY_F = 70, KEY_Z = 90, KEY_X = 88, KEY_C = 67, KEY_R = 82, KEY_T = 84, KEY_SPACE = 32, KEY_LEFT = 37, KEY_UP = 38, KEY_RIGHT = 39, KEY_DOWN = 40; // requestAnimationFrame() shim by <NAME> // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ window.requestAnimFrame = (function(callback, element) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function */ callback, /* DOMElement */ element){ window.setTimeout(callback, 1000 / 60); }; })(); /** * Behaves the same as setInterval except uses requestAnimationFrame() where possible for better performance * @param {function} fn The callback function * @param {int} delay The delay in milliseconds */ window.requestInterval = function(fn, delay) { if( !window.requestAnimationFrame && !window.webkitRequestAnimationFrame && !(window.mozRequestAnimationFrame && window.mozCancelRequestAnimationFrame) && // Firefox 5 ships without cancel support !window.oRequestAnimationFrame && !window.msRequestAnimationFrame) return window.setInterval(fn, delay); var start = new Date().getTime(), handle = new Object(); function loop() { var current = new Date().getTime(), delta = current - start; if(delta >= delay) { fn.call(); start = new Date().getTime(); } handle.value = requestAnimFrame(loop); }; handle.value = requestAnimFrame(loop); return handle; } /** * Behaves the same as clearInterval except uses cancelRequestAnimationFrame() where possible for better performance * @param {int|object} fn The callback function */ window.clearRequestInterval = function(handle) { window.cancelAnimationFrame ? window.cancelAnimationFrame(handle.value) : window.webkitCancelAnimationFrame ? window.webkitCancelAnimationFrame(handle.value) : window.webkitCancelRequestAnimationFrame ? window.webkitCancelRequestAnimationFrame(handle.value) : /* Support for legacy API */ window.mozCancelRequestAnimationFrame ? window.mozCancelRequestAnimationFrame(handle.value) : window.oCancelRequestAnimationFrame ? window.oCancelRequestAnimationFrame(handle.value) : window.msCancelRequestAnimationFrame ? window.msCancelRequestAnimationFrame(handle.value) : clearInterval(handle); }; /** * Behaves the same as setTimeout except uses requestAnimationFrame() where possible for better performance * @param {function} fn The callback function * @param {int} delay The delay in milliseconds */ window.requestTimeout = function(fn, delay) { if( !window.requestAnimationFrame && !window.webkitRequestAnimationFrame && !(window.mozRequestAnimationFrame && window.mozCancelRequestAnimationFrame) && // Firefox 5 ships without cancel support !window.oRequestAnimationFrame && !window.msRequestAnimationFrame) return window.setTimeout(fn, delay); var start = new Date().getTime(), handle = new Object(); function loop(){ var current = new Date().getTime(), delta = current - start; delta >= delay ? fn.call() : handle.value = requestAnimFrame(loop); }; handle.value = requestAnimFrame(loop); return handle; }; /** * Behaves the same as clearTimeout except uses cancelRequestAnimationFrame() where possible for better performance * @param {int|object} fn The callback function */ window.clearRequestTimeout = function(handle) { window.cancelAnimationFrame ? window.cancelAnimationFrame(handle.value) : window.webkitCancelAnimationFrame ? window.webkitCancelAnimationFrame(handle.value) : window.webkitCancelRequestAnimationFrame ? window.webkitCancelRequestAnimationFrame(handle.value) : /* Support for legacy API */ window.mozCancelRequestAnimationFrame ? window.mozCancelRequestAnimationFrame(handle.value) : window.oCancelRequestAnimationFrame ? window.oCancelRequestAnimationFrame(handle.value) : window.msCancelRequestAnimationFrame ? window.msCancelRequestAnimationFrame(handle.value) : clearTimeout(handle); }; <file_sep>/static/js/peppermintFalls/game.js // create a Game object BasicGame.Game = function (game) { this.clickCircle = new Phaser.Circle( this.game.width / 2, this.game.height - 100, 44); }; // add methods and properties BasicGame.Game.prototype = { create: function () { this.bg = this.add.sprite(0, 0, 'backgrounds', 'background.png'); this.setupPlayer(); this.setupDrops(); }, setupPlayer: function () { // ## PLAYER this.player = this.add.sprite( this.game.width / 2, this.game.height - 100, 'grubby' ); this.player.anchor.setTo(0.5, 0.5); this.player.scale.setTo(5, 5); this.player.smoothed = false; this.game.physics.enable(this.player, Phaser.Physics.ARCADE); this.player.body.collideWorldBounds = true; this.player.body.velocity.x = 0; this.player.body.velocity.y = 0; this.player.speed = 300; this.player.animations.add('open', [0, 2, 3], 9, false); this.player.animations.add('close', [3, 2, 0], 9, false); this.player.animations.add('chew', [0, 2, 3, 2, 0], 10, true); this.player.animations.add('left', [1], 1, false); this.player.animations.add('right', [4], 1, false); this.player.animations.add('idle', [0], 1, false); this.player.play('idle'); this.mouseX = this.player.x; // dont let a computer decide your starting value for you! this.score = 0; console.log("player setup complete"); }, setupDrops: function () { this.candyPool = this.add.group(); this.candyPool.enableBody = true; this.candyPool.physicsBodyType = Phaser.Physics.ARCADE; this.candyPool.createMultiple(50, 'misc', "candyDrop.png"); this.candyPool.setAll('anchor.x', 0.5); this.candyPool.setAll('anchor.y', 0.5); this.candyPool.setAll('scale.x', 2); this.candyPool.setAll('scale.y', 2); this.candyPool.setAll('smoothed', false); this.candyPool.setAll('outOfBoundsKill', true); this.candyPool.setAll('checkWorldBounds', true); this.candyPool.setAll('reward', 100, false, false, 0, true); // spawn when game starts this.nextCandyAt = 0; this.candyDelay = 1000; }, // update-related functions update: function () { this.checkCollision(); this.spawnCandy(); if (this.input.activePointer.isDown) { this.clickCircle.x = this.input.activePointer.circle.x; this.clickCircle.diameter = this.input.activePointer.circle.diameter; } this.processPlayerInput(); }, processPlayerInput: function () { this.player.body.velocity.x = 0; this.player.body.velocity.y = 0; if (this.input.keyboard.isDown(Phaser.Keyboard.Z) || this.input.activePointer.isDown) { if (this.returnText && this.returnText.exists) { this.quitGame(); } } if (this.player.x > this.mouseX && Math.abs(this.player.x - this.mouseX) > 15) { this.player.body.velocity.x = -this.player.speed; } else if (this.player.x < this.mouseX && Math.abs(this.player.x - this.mouseX) > 15) { this.player.body.velocity.x = this.player.speed; } if (this.clickCircle.contains(this.player.x, this.player.y)) { this.player.body.velocity.x = 0; this.player.body.velocity.y = 0; } }, spawnCandy: function () { if (this.nextCandyAt < this.time.now && this.candyPool.countDead() > 0) { this.nextCandyAt = this.time.now + this.candyDelay; // reset the clock var candy = this.candyPool.getFirstExists(false); // get the first candy not active // spawn at a random location at the top of the screen candy.reset( this.rnd.integerInRange(30, this.game.width - 30), // x 0, // y 1) candy.body.velocity.y = this.rnd.integerInRange(20, 80); // random speed } }, checkCollision: function () { this.physics.arcade.overlap( this.player, this.candyPool, this.gobble, null, this); }, gobble: function (player, candy) { if (candy.frameName !== 'sprout.png') { this.eat(candy); } else { // eww, sprouts! } }, eat: function (candy) { this.score += candy.reward; candy.kill(); }, quitGame: function (pointer) { // Then let's go back to the main menu. this.state.start('Boot'); }, }; <file_sep>/static/js/shmup/preloader.js BasicGame.Preloader = function (game) { this.background = null; this.preloadBar = null; this.ready = false; }; BasicGame.Preloader.prototype = { preload: function () { // Show the loading progress bar asset we loaded in boot.js this.stage.backgroundColor = '#2d2d2d'; this.preloadBar = this.add.sprite( 0, 0, 'preloaderBar'); this.add.text( this.game.width / 2, this.game.height / 2, "Loading...", { font: "64px Audiowide", fill: "#fff" }).anchor.setTo(0.5, 0.5); // This sets the preloadBar sprite as a loader sprite. // What that does is automatically crop the sprite from 0 to full-width // as the files below are loaded in. this.load.setPreloadSprite(this.preloadBar); // Here we load the rest of the assets our game needs. this.load.image('titlepage', 'assets/shmup/Phaser_splash.jpg'); this.load.image('sea', 'assets/shmup/sea.png'); this.load.image('bullet', 'assets/shmup/bullet.png'); this.load.image('enemyBullet', 'assets/shmup/enemy-bullet.png'); this.load.image('powerup1', 'assets/shmup/powerup1.png'); this.load.image('title', 'assets/shmup/title.png'); this.load.audio('explosion', ['assets/shmup/explodemini.wav']); this.load.audio('playerExplosion', ['assets/shmup/player-explosion.wav']); this.load.audio('enemyFire', ['assets/shmup/enemy-fire.wav']); this.load.audio('playerFire', ['assets/shmup/player-fire.wav']); this.load.audio('powerUp', ['assets/shmup/powerup.wav']); //this.load.audio('titleMusic', ['audio/main_menu.mp3']); this.load.spritesheet('greenEnemy', 'assets/shmup/enemy.png', 32, 32); this.load.spritesheet('whiteEnemy', 'assets/shmup/shooting-enemy.png', 32, 32); this.load.spritesheet('boss', 'assets/shmup/boss.png', 93, 75); this.load.spritesheet('explosion', 'assets/shmup/explosion.png', 32, 32); this.load.spritesheet('player', 'assets/shmup/player.png', 64, 64); // + lots of other required assets here this.load.atlas('batwords', 'assets/bat-words/bat-words.png', 'assets/bat-words/bat-words.json', null, 0); this.load.audio('pregame', 'assets/shmup/silent_kilt.ogg'); this.load.audio('game', 'assets/shmup/pixellated_zombies.ogg'); this.load.audio('bossBattle', 'assets/shmup/watch_out.ogg'); this.load.audio('endgame', 'assets/shmup/sad_Exploring.ogg'); }, create: function () { // Once the load has finished we disable the crop because we're going to sit in the update loop for a short while as the music decodes this.preloadBar.cropEnabled = false; }, update: function () { // You don't actually need to do this, but I find it gives a much smoother game experience. // Basically it will wait for our audio file to be decoded before proceeding to the MainMenu. // You can jump right into the menu if you want and still play the music, but you'll have a few // seconds of delay while the mp3 decodes - so if you need your music to be in-sync with your menu // it's best to wait for it to decode here first, then carry on. // If you don't have any music in your game then put the game.state.start line into the create function and delete // the update function completely. if (this.cache.isSoundDecoded('pregame') && this.ready == false) { this.ready = true; this.state.start('MainMenu'); } } }; <file_sep>/static/js/createjs_proj/level03.js (function () { var stage, direction = 1, speed = 10, circle; /* Create a Queue */ function init() { loadComplete(); } function loadComplete() { setupStage(); addActors(); } /* Setup the Stage and Loop */ function setupStage() { // reference to the canvas stage = new create.Stage(document.getElementById('level03')); // create a Ticker that will call stage.update() around 60 times a second create.Ticker.setFPS(60); create.Ticker.setPaused(false); // id, callback function create.Ticker.addEventListener("tick", tick); } function tick(e) { // don't update if paused if(!e.paused){ updateActor(); renderActor(); stage.update(); } } /* Add the Actors */ function addActors() { circle = new create.Shape(); circle.graphics.beginStroke("#000"); circle.graphics.beginFill("#FFF000"); circle.graphics.drawCircle(0, 0, 50); circle.radius = 50; circle.x = 100; circle.y = 300; stage.addChild(circle); } function updateActor() { // bounce off the walls! var nextX = circle.x + (speed * direction); if (nextX > stage.canvas.width - circle.radius) { nextX = stage.canvas.width - circle.radius; direction *= -1; } else if (nextX < circle.radius) { nextX = circle.radius; direction *= -1; } circle.nextX = nextX; } function renderActor() { circle.x = circle.nextX; } return init(); })(); <file_sep>/README.md Live Github Page - http://amerizalde.github.io/html5gamedev/?mobile=1 Games can also be played locally using the script localdev.py. You will need Python 3 and Flask installed on your computer. The script uses the index.html from the /static directory, not the one in the top level. Run `python localdev.py` from a command-line window. Go to `localhost:5000` in your browser. #### [!SHMUP - Classic Plane Shoot'em Up](http://amerizalde.github.io/html5gamedev/shmup.html) A demo shooter based on the teachings in [Bibat's HTML5 Shoot'em Up in an Afternoon](https://leanpub.com/html5shootemupinanafternoon/). #### [Concentration](http://amerizalde.github.io/html5gamedev/concentration.html) A memory matching game. #### [Sprite Remix](http://amerizalde.github.io/html5gamedev/spritesheet_remix.html) A tool to customize sprite animations. Built with [Phaser](https://phaser.io/) and [JQuery](http://jquery.com/). <file_sep>/static/js/turret_example/Preloader.js BasicGame.Preloader = function (game) { this.background = null; this.preloadBar = null; this.ready = false; }; BasicGame.Preloader.prototype = { preload: function () { // These are the assets we loaded in Boot.js // A nice sparkly background and a loading progress bar this.background = this.add.tileSprite(0, 0, this.game.width, this.game.height, 'bg'); this.preloadBar = this.add.sprite(this.game.width / 2, this.game.height / 2 - 30, 'preloaderBar'); // This sets the preloadBar sprite as a loader sprite. // What that does is automatically crop the sprite from 0 to full-width // as the files below are loaded in. this.load.setPreloadSprite(this.preloadBar); // Here we load the rest of the assets our game needs. // As this is just a Project Template I've not provided these assets, swap them for your own. this.load.image('bg', '/static/assets/images/tileback01.jpg'); this.load.image('titlepage', '/static/assets/images/phaser.png'); this.load.atlas('playButton', '/static/assets/images/xbox360.png', '/static/assets/images/xbox360.json'); this.load.spritesheet('arrows', '/static/assets/images/arrows.png', 23, 31); this.load.spritesheet('balls', '/static/assets/discover_phaser/balls.png', 17, 17); // + lots of other required assets here }, create: function () { // Once the load has finished we disable the crop because we're going to sit in the update loop for a short while as the music decodes this.preloadBar.cropEnabled = false; }, update: function () { // You don't actually need to do this, but I find it gives a much smoother game experience. // Basically it will wait for our audio file to be decoded before proceeding to the MainMenu. // You can jump right into the menu if you want and still play the music, but you'll have a few // seconds of delay while the mp3 decodes - so if you need your music to be in-sync with your menu // it's best to wait for it to decode here first, then carry on. // If you don't have any music in your game then put the game.state.start line into the create function and delete // the update function completely. // if (this.cache.isSoundDecoded('titleMusic') && this.ready == false) // { // this.ready = true; this.state.start('MainMenu'); // } } }; <file_sep>/static/js/candy_conquest/app.js var game; window.onload = function() { // Create your Phaser game and inject it into the gameContainer div. // We did it in a window.onload event, but you can do it anywhere (requireJS load, anonymous function, jQuery dom ready, - whatever floats your boat) game = new Phaser.Game( 800,// * window.devicePixelRatio, // width -- .devicePixelRatio covers retina displays 480,// * window.devicePixelRatio, // height Phaser.CANVAS, // renderer 'gameContainer'); // DOM element to inject to // Add the States your game has. // You don't have to do this in the html, it could be done in your Boot state too, but for simplicity I'll keep it here. game.state.add('Boot', BasicGame.Boot); game.state.add('Preloader', BasicGame.Preloader); game.state.add('MainMenu', BasicGame.MainMenu); game.state.add('Game', BasicGame.Game); // Now start the Boot state. game.state.start('Boot'); }; // doesnt seem to do anything window.onresize = function () { var height = 800, width = 480; height = game.canvas.height < height ? game.canvas.height : height; width = game.canvas.width < width ? game.canvas.width : width; game.canvas.height = height; game.canvas.width = width; game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.pageAlignHorizontally = true; game.scale.setScreenSize(); if (game.renderType === Phaser.WEBGL) game.renderer.resize (width, height); }; <file_sep>/static/js/peppermintFalls/mainMenu.js BasicGame.MainMenu = function (game) { }; BasicGame.MainMenu.prototype = { create: function () { // sprites are loaded in the order added here. this.bg = this.add.sprite(0, 0, 'backgrounds', 'background.png'); this.setupPlayer(); /* this.musicPregame = this.add.audio('pregame'); this.musicPregame.play("", 0, 1, true); this.add.tween(this.musicPregame) .from({volume: 0}, 2000, Phaser.Easing.Linear.Out, true); */ this.entrance = this.add.tween(this.player) .from({x: -20}, 2000, Phaser.Easing.Quadratic.Out, true); this.player.play("chew"); this.titlePNG = this.add.sprite( this.world.centerX, 200, 'backgrounds', 'title.png'); this.titlePNG.anchor.setTo(0.5, 0.5); this.add.tween(this.titlePNG).from({y: -8}, 1000, Phaser.Easing.Bounce.Out, true); this.loadingText = this.add.text( this.world.centerX, this.world.centerY, "Press Z or tap/click game to start", { font: "20px Audiowide", fill: "#fff" }); this.loadingText.anchor.setTo(0.5, 0.5); this.add.text( this.world.centerX, this.game.height - 32, "Copyright (c) 2014 <NAME>", { font: "10px monospace", fill: "#fff", align: "center"}).anchor.setTo(0.5, 0.5); console.log("create complete"); }, update: function () { if (this.input.keyboard.isDown(Phaser.Keyboard.Z) || this.input.activePointer.isDown) { this.state.start('Game'); } // Do some nice funky main menu effect here }, startGame: function (pointer) { // Ok, the Play Button has been clicked or touched, so let's stop the music (otherwise it'll carry on playing) // this.musicPregame.stop(); // And start the actual game // this.state.start('Game'); }, // create-related functions setupPlayer: function () { console.log("player setup start"); // ## PLAYER this.player = this.add.sprite( this.game.width / 2, this.game.height - 100, 'grubby' ); this.player.anchor.setTo(0.5, 0.5); this.player.scale.setTo(4, 4); this.player.animations.add('open', [0, 2, 3], 9, false); this.player.animations.add('close', [3, 2, 0], 9, false); this.player.animations.add('chew', [0, 2, 3, 2, 0], 10, true); this.player.animations.add('left', [1], 1, false); this.player.animations.add('right', [4], 1, false); this.player.animations.add('idle', [0], 1, false); this.player.play('idle'); console.log("player setup complete"); }, }; <file_sep>/static/js/spritesheet_remix_2/game.js // create a Game object BasicGame.Game = function (game) { this.dummy = null; this.previewBox = null; this.framesGroup = null; this.spritesheet = null; this.fps = 24; this.resetPreviewArray = false; this.previewState = false; this.gameOver = false; this.scalar = 1; }; BasicGame.Game.prototype = { preload: function () { var frameWidth = Math.floor(spriteData.width / spriteData.columns); var frameHeight = Math.floor(spriteData.height / spriteData.rows); this.scalar = this.scaleDownToFit(frameWidth); console.log(this.scalar); this.load.spritesheet( 'previewData', spriteData.img.src, frameWidth, frameHeight); this.spritesheet = 'previewData'; }, // built-in create function create: function () { // sprites are loaded in the order added here. // previewBox is used for positioning the animation preview. this.previewBox = new Phaser.Rectangle( this.camera.view.centerX, this.camera.view.height - 200, 100, 100); this.previewBox.anchor = {'x': 0.5, 'y': 0.5}; // this determines the order of frames played this.previewArray = [0,]; this.setupFramesManager(this.spritesheet); this.setupButtons(); // show something to start this.preview(); $("frameManager").show(); $("#frameData").text(this.previewArray); $("#codeAssist").show(); }, setupFramesManager: function (atlas) { if (this.framesGroup) { this.framesGroup.destroy(); } this.framesGroup = this.add.group(); // retrieve the atlas from the cache, to access the frames directly. var data = this.cache.getFrameData(atlas); var img; // a cursor var cx = 0; var cy = 0; for (var i = 0; i < data._frames.length; i++) { // determine the x, y to set the next frame at if (cx >= this.game.width - data._frames[i].width) { cx = 0; cy += data._frames[i].height; } // create the next frame sprite img = this.add.sprite(cx, cy, atlas, data._frames[i].index); img.scale = {'x': this.scalar, 'y': this.scalar}; console.log(img); img.inputEnabled = true; img.health = 0; // used as a counter. this.addLabel(img, img.health.toString(), "18px", "center"); // add a callback that fires when this frame is clicked. img.events.onInputDown.add(this.use, img); this.framesGroup.add(img); // move the cursor cx += img.width; } }, setupButtons: function () { // preview button this.previewBtn = this.add.sprite( this.game.width / 2, this.game.height / 2, 'gui', "buttonSquare_grey.png"); this.addLabel(this.previewBtn, "Play", "20px", "center", 0.5); this.previewBtn.anchor = {'x': 0.5, 'y': 0.5}; this.previewBtn.inputEnabled = true; this.previewBtn.events.onInputDown.add(this.onDownFix, this.previewBtn); this.previewBtn.events.onInputDown.add(this.callPreview, this.previewBtn); this.previewBtn.events.onInputUp.add(this.onUpFix, this.previewBtn); this.previewBtn.events.onInputOver.add(this.onOverFix, this.previewBtn); this.previewBtn.events.onInputOut.add(this.onOutFix, this.previewBtn); // reset button this.resetBtn = this.add.sprite( this.game.width / 2 + this.previewBtn.width, this.game.height / 2, 'gui', "buttonSquare_grey.png"); this.addLabel(this.resetBtn, "Reset", "14px", "center", 0.5); this.resetBtn.anchor = {'x': 0.5, 'y': 0.5}; this.resetBtn.inputEnabled = true; this.resetBtn.events.onInputDown.add(this.onDownFix, this.resetBtn); this.resetBtn.events.onInputDown.add(this.callResetPreview, this.resetBtn); this.resetBtn.events.onInputUp.add(this.onUpFix, this.resetBtn); this.resetBtn.events.onInputOver.add(this.onOverFix, this.resetBtn); this.resetBtn.events.onInputOut.add(this.onOutFix, this.resetBtn); // quit button this.quitBtn = this.add.sprite( this.game.width / 2 + this.previewBtn.width + this.resetBtn.width, this.game.height / 2, 'gui', "buttonSquare_grey.png"); this.addLabel(this.quitBtn, "Done", "14px", "center", 0.5); this.quitBtn.anchor = {'x': 0.5, 'y': 0.5}; this.quitBtn.inputEnabled = true; this.quitBtn.events.onInputDown.add(this.onDownFix, this.quitBtn); this.quitBtn.events.onInputDown.add(this.callQuit, this.quitBtn); this.quitBtn.events.onInputUp.add(this.onUpFix, this.quitBtn); this.quitBtn.events.onInputOver.add(this.onOverFix, this.quitBtn); this.quitBtn.events.onInputOut.add(this.onOutFix, this.quitBtn); }, // these helpers create 'buttons' out of sprites onUpFix: function (btn) { btn.frameName = "buttonSquare_grey.png"; }, onDownFix: function (btn) { btn.frameName = "buttonSquare_grey_pressed.png"; }, onOverFix: function (btn) { btn.frameName = "buttonSquare_grey_over.png"; }, onOutFix: function (btn) { btn.frameName = "buttonSquare_grey.png"; }, // add the frame's index to the previewArray use: function(ctx) { var frames = ctx.game.state.callbackContext.previewArray; ctx.health += 1; // the label ctx.children[0].text = ctx.health.toString(); frames.push(parseInt(ctx._frame.index)); ctx.game.state.callbackContext.previewArray = frames; $("#frameData").text(ctx.game.state.callbackContext.previewArray); }, // create an animation from the spritesheet using the frame order // in the previewArray preview: function () { // create a reusable sprite for the animation preview if (this.dummy) { this.dummy.animations.stop(); this.dummy.animations.currentAnim.destroy(); } else { this.dummy = this.add.sprite( this.previewBox.x, this.previewBox.y, this.spritesheet ); } // update the animation this.dummy.animations.add( 'preview', this.previewArray, this.fps, true, true ); // play it this.dummy.play('preview'); }, callResetPreview: function (ctx) { ctx.game.state.callbackContext.resetPreviewArray = true; }, callPreview: function(ctx) { ctx.game.state.callbackContext.previewState = true; }, callQuit: function(ctx) { ctx.game.state.callbackContext.gameOver = true; }, // add a label to a sprite addLabel: function (ctx, text, fontsize, alignment, anchor) { if (!anchor) { anchor = 0; } var label = new Phaser.Text( ctx.game, 0, 0, text, { font: "Droid Sans Mono", fontSize: fontsize, fill: "#ff0000", align: alignment, } ); label.anchor.setTo(anchor); ctx.addChild(label); }, // built in functions update: function () { if (this.previewState) { this.previewState = false; this.preview(); } if (this.resetPreviewArray) { this.resetPreviewArray = false; this.updateLabels(); this.previewArray = [0,]; // clear the array without destroying it. $("#frameData").text(this.previewArray); this.preview(); } if (this.gameOver) { this.quit(); } }, updateLabels: function () { // reset the display this.framesGroup.setAll('health', 0); // children[0].text does not work here. this.framesGroup.setAll('children.0.text', '0'); }, quit: function () { this.gameOver = false; // reset spriteData spriteData = { img: new Image(), width: null, height: null, rows: null, columns: null, }; this.dummy = null; $('input[name="width"]').val(''); $('input[name="height"]').val(''); $('input[name="rows"]').val(''); $('input[name="columns"]').val(''); $("#spriteData").show(); $("#codeAssist").hide(); $("#frameData").text(""); // go back to the Main Menu this.state.start('MainMenu'); }, render: function () { //this.game.debug.geom(this.previewBox, 'rgba(250, 0, 250, 1)'); }, scaleDownToFit: function (frameWidth) { // find a scalar that keeps the frames near 10 to a row var fw = frameWidth; var maxWidth = Math.floor(this.game.width / 15); var scalar = 1.0; if (fw < maxWidth) return 1; // nothing to change while (fw > maxWidth) { scalar = scalar - 0.1; fw = frameWidth * scalar; } return scalar; }, }; <file_sep>/static/js/candy_conquest/game.js // create a Game object BasicGame.Game = function (game) { }; // add methods and properties BasicGame.Game.prototype = { create: function () { // sprites are loaded in the order added here. this.setupWorld(); this.setupPlayer(); this.setupCamera(); }, setupWorld: function () { this.bg = this.add.tilemap('level'); this.bg.addTilesetImage('level_sheet', 'tiles'); this.layer = this.bg.createLayer('layer_1'); this.bg.setCollisionByExclusion([12], true, this.layer); this.layer.resizeWorld(); this.layer.wrap = true; this.layer.debug = true; this.game.physics.arcade.gravity.y = 500; }, setupPlayer: function () { // ## PLAYER this.player = this.add.sprite( 70, this.game.height - 100, 'p1' ); this.player.anchor.setTo(0.5, 0.5); this.player.scale.setTo(0.5, 0.5); this.game.physics.enable(this.player, Phaser.Physics.ARCADE); this.player.body.collideWorldBounds = true; this.player.body.velocity.x = 0; this.player.body.velocity.y = 0; this.player.speed = 300; // wrap around horizontally, not vertically this.world.wrap(this.player, 0, false, true, false); this.player.animations.add('idle', [1,4,1,28], 1, true); this.player.animations.add('left', [4,5,6,7,8,9,10,11,12,13,14,15], 6, true); this.player.animations.add('right', [20,21,22,23,24,25,26,27,28,29,30,31], 6, true); this.player.animations.add('hit_left', [2,3,0], 1, false); this.player.animations.add('jump_left', [26], 1, false); this.player.animations.add('jump_right', [10], 1, false); this.player.play('idle'); this.score = 0; console.log("player setup complete"); }, setupCamera: function () { this.camera.follow(this.player); }, // update-related functions update: function () { // wrap around horizontally, not vertically this.world.wrap(this.player, 0, false, true, false); this.processPlayerInput(); this.checkCollision(); }, processPlayerInput: function () { // key config var left = Phaser.Keyboard.A; var right = Phaser.Keyboard.D; var up = Phaser.Keyboard.W; var down = Phaser.Keyboard.S; var jump = Phaser.Keyboard.W; // zero out the velocity this.player.body.velocity.x = 0; // this.player.body.velocity.y = 0; // wrap if (this.input.keyboard.isDown(Phaser.Keyboard.Z) || this.input.activePointer.isDown) { if (this.returnText && this.returnText.exists) { this.quitGame(); } } // movement // left if (this.input.keyboard.isDown(left) && this.player.body.blocked.down) { this.player.body.velocity.x = -this.player.speed; } else if (this.input.keyboard.isDown(left)) { this.player.body.velocity.x = -this.player.speed * 0.25; } // right if (this.input.keyboard.isDown(right) && this.player.body.blocked.down) { this.player.body.velocity.x = this.player.speed; } else if (this.input.keyboard.isDown(right)) { this.player.body.velocity.x = this.player.speed * 0.25; } // jump if (this.input.keyboard.justPressed(jump)) { if (this.player.body.blocked.down) { this.player.body.velocity.y = -600; console.log("JUMPING!"); } console.log(this.player.body.blocked); } // cancel if (this.input.keyboard.isDown(left) && this.input.keyboard.isDown(right)) { this.player.body.velocity.x = this.player.body.velocity.x * 0.05; } }, checkCollision: function () { this.physics.arcade.collide(this.player, this.layer); }, gobble: function (player, candy) { }, eat: function (candy) { this.score += candy.reward; candy.kill(); }, quitGame: function (pointer) { // Then let's go back to the main menu. this.state.start('Boot'); }, render: function () { this.game.debug.spriteCoords(this.player, 32, 400); this.game.debug.bodyInfo(this.player, 32, 32); }, }; /* KEYBOARD Key Code cheat sheet -- delete for production copy Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; Phaser.Keyboard.A = "A".charCodeAt(0); Phaser.Keyboard.B = "B".charCodeAt(0); Phaser.Keyboard.C = "C".charCodeAt(0); Phaser.Keyboard.D = "D".charCodeAt(0); Phaser.Keyboard.E = "E".charCodeAt(0); Phaser.Keyboard.F = "F".charCodeAt(0); Phaser.Keyboard.G = "G".charCodeAt(0); Phaser.Keyboard.H = "H".charCodeAt(0); Phaser.Keyboard.I = "I".charCodeAt(0); Phaser.Keyboard.J = "J".charCodeAt(0); Phaser.Keyboard.K = "K".charCodeAt(0); Phaser.Keyboard.L = "L".charCodeAt(0); Phaser.Keyboard.M = "M".charCodeAt(0); Phaser.Keyboard.N = "N".charCodeAt(0); Phaser.Keyboard.O = "O".charCodeAt(0); Phaser.Keyboard.P = "P".charCodeAt(0); Phaser.Keyboard.Q = "Q".charCodeAt(0); Phaser.Keyboard.R = "R".charCodeAt(0); Phaser.Keyboard.S = "S".charCodeAt(0); Phaser.Keyboard.T = "T".charCodeAt(0); Phaser.Keyboard.U = "U".charCodeAt(0); Phaser.Keyboard.V = "V".charCodeAt(0); Phaser.Keyboard.W = "W".charCodeAt(0); Phaser.Keyboard.X = "X".charCodeAt(0); Phaser.Keyboard.Y = "Y".charCodeAt(0); Phaser.Keyboard.Z = "Z".charCodeAt(0); Phaser.Keyboard.ZERO = "0".charCodeAt(0); Phaser.Keyboard.ONE = "1".charCodeAt(0); Phaser.Keyboard.TWO = "2".charCodeAt(0); Phaser.Keyboard.THREE = "3".charCodeAt(0); Phaser.Keyboard.FOUR = "4".charCodeAt(0); Phaser.Keyboard.FIVE = "5".charCodeAt(0); Phaser.Keyboard.SIX = "6".charCodeAt(0); Phaser.Keyboard.SEVEN = "7".charCodeAt(0); Phaser.Keyboard.EIGHT = "8".charCodeAt(0); Phaser.Keyboard.NINE = "9".charCodeAt(0); Phaser.Keyboard.NUMPAD_0 = 96; Phaser.Keyboard.NUMPAD_1 = 97; Phaser.Keyboard.NUMPAD_2 = 98; Phaser.Keyboard.NUMPAD_3 = 99; Phaser.Keyboard.NUMPAD_4 = 100; Phaser.Keyboard.NUMPAD_5 = 101; Phaser.Keyboard.NUMPAD_6 = 102; Phaser.Keyboard.NUMPAD_7 = 103; Phaser.Keyboard.NUMPAD_8 = 104; Phaser.Keyboard.NUMPAD_9 = 105; Phaser.Keyboard.NUMPAD_MULTIPLY = 106; Phaser.Keyboard.NUMPAD_ADD = 107; Phaser.Keyboard.NUMPAD_ENTER = 108; Phaser.Keyboard.NUMPAD_SUBTRACT = 109; Phaser.Keyboard.NUMPAD_DECIMAL = 110; Phaser.Keyboard.NUMPAD_DIVIDE = 111; Phaser.Keyboard.F1 = 112; Phaser.Keyboard.F2 = 113; Phaser.Keyboard.F3 = 114; Phaser.Keyboard.F4 = 115; Phaser.Keyboard.F5 = 116; Phaser.Keyboard.F6 = 117; Phaser.Keyboard.F7 = 118; Phaser.Keyboard.F8 = 119; Phaser.Keyboard.F9 = 120; Phaser.Keyboard.F10 = 121; Phaser.Keyboard.F11 = 122; Phaser.Keyboard.F12 = 123; Phaser.Keyboard.F13 = 124; Phaser.Keyboard.F14 = 125; Phaser.Keyboard.F15 = 126; Phaser.Keyboard.COLON = 186; Phaser.Keyboard.EQUALS = 187; Phaser.Keyboard.UNDERSCORE = 189; Phaser.Keyboard.QUESTION_MARK = 191; Phaser.Keyboard.TILDE = 192; Phaser.Keyboard.OPEN_BRACKET = 219; Phaser.Keyboard.BACKWARD_SLASH = 220; Phaser.Keyboard.CLOSED_BRACKET = 221; Phaser.Keyboard.QUOTES = 222; Phaser.Keyboard.BACKSPACE = 8; Phaser.Keyboard.TAB = 9; Phaser.Keyboard.CLEAR = 12; Phaser.Keyboard.ENTER = 13; Phaser.Keyboard.SHIFT = 16; Phaser.Keyboard.CONTROL = 17; Phaser.Keyboard.ALT = 18; Phaser.Keyboard.CAPS_LOCK = 20; Phaser.Keyboard.ESC = 27; Phaser.Keyboard.SPACEBAR = 32; Phaser.Keyboard.PAGE_UP = 33; Phaser.Keyboard.PAGE_DOWN = 34; Phaser.Keyboard.END = 35; Phaser.Keyboard.HOME = 36; Phaser.Keyboard.LEFT = 37; Phaser.Keyboard.UP = 38; Phaser.Keyboard.RIGHT = 39; Phaser.Keyboard.DOWN = 40; Phaser.Keyboard.INSERT = 45; Phaser.Keyboard.DELETE = 46; Phaser.Keyboard.HELP = 47; Phaser.Keyboard.NUM_LOCK = 144; */ <file_sep>/static/js/createjs_proj/level08.js (function () { var stage; /* Create a Queue */ function init() { loadComplete(); } function loadComplete() { setupStage(); } /* Setup the Stage and Loop */ function setupStage() { // reference to the canvas stage = new create.Stage(document.getElementById('level08')); var domElement = new create.DOMElement("instructions"); domElement.visible = false; domElement.alpha = 0; domElement.x = stage.canvas.width / 2; domElement.y = 200; domElement.visible = true; stage.addChild(domElement); create.Tween.get(domElement) .wait(1000) .to({y: 40, alpha: 1}, 2000, create.Ease.quadOut); // create a Ticker that will call stage.update() around 60 times a second create.Ticker.setFPS(60); create.Ticker.setPaused(false); // id, callback function create.Ticker.addEventListener("tick", tick); } function tick(e) { // don't update if paused if(!e.paused){ stage.update(); } } return init(); })(); <file_sep>/static/js/match3/match3_bak.js // create a Game object BasicGame.Game = function (game) { this.TILE_SIZE = 48; this.FIELD_SIZE = 8; this.TILE_TYPES = 6; this.OFFSET_X = 48; this.OFFSET_Y = 50; this.g_array = new Array(this.FIELD_SIZE * this.FIELD_SIZE); this.selectedGem = null; this.selectedGemStartPos = null; this.selectedGemTween = null; this.shiftedGem = null; this.shiftedGemTween = null; this.highlight = null; }; // add methods and properties BasicGame.Game.prototype = { // the Phaser Game Loop -- preload, create, [update, render, repeat] create: function () { this.buildLevel(); this.drawLevel(); this.setupHighlight(); this.selectedGemStartPos = { x: 0, y: 0, }; this.allowInput = true; }, update: function () { /* when the mouse is released with a gem selected: check for matches remove matched gems drop down gems above removed gems refill the board */ }, // create-related functions buildLevel: function () { for (var i = 0; i < this.FIELD_SIZE * this.FIELD_SIZE; i++) { do { this.g_array[i] = Math.ceil(Math.random() * this.TILE_TYPES); } while (this.isHorizontalMatch(i) || this.isVerticalMatch(i)); } }, setupHighlight: function () { this.highlight = this.add.graphics(0, 0); this.highlight.lineStyle(2, 0xffffff, 0); this.highlight.beginFill(0xffffff); this.highlight.drawRect(48, 50, this.TILE_SIZE, this.TILE_SIZE); this.gem_selected = this.game.add.sprite(0, 0, null); this.gem_selected.mask = this.highlight; this.gem_selected.blendMode = PIXI.blendModes.SCREEN; }, // update-related functions processPlayerInput: function () { if (this.input.activePointer.justReleased()) { if (this.selectedGem != null) { // check and kill gem matches if (this.shiftedGem != null) { // check and kill gem matches } // remove killed gems // null out selected and shifted gems placeholders } } if (this.selectedGem != null) { // check if selected gem can be moved to mouse position // if so, move it // if there is a previously shifted gem, move it to the selected // gem's position. // if there is a gem already at the mouse position, swap the selected // gem with the new shifted gem. } }, processDelayedEffects: function () { }, render: function () { // DEBUGGING CODE // this.game.debug.body(this.player); }, quitGame: function (pointer) { // Then let's go back to the main menu. }, addToScore: function (score) { }, explode: function(sprite) { }, displayEnd: function (win) { }, rowNumber: function (i) { // return the row arg i is a part of. return Math.floor(i / this.FIELD_SIZE); }, colNumber: function (i) { // return the column arg i is a part of. return i % this.FIELD_SIZE; }, isHorizontalMatch: function (i) { // checking from right to left, return true if all three locations // contain the same number return this.colNumber(i) >= 2 && this.g_array[i] === this.g_array[i - 1] && this.g_array[i] === this.g_array[i - 2] && this.rowNumber(i) === this.rowNumber(i - 2); }, isVerticalMatch: function (i) { // checking from bottom to top, return true if all three locations // contain the same number. return this.rowNumber(i) >= 2 && this.g_array[i] === this.g_array[i - this.FIELD_SIZE] && this.g_array[i] === this.g_array[i - 2 * this.FIELD_SIZE]; }, drawLevel: function () { this.gems = this.add.group(); for (var i = 0; i < this.FIELD_SIZE * this.FIELD_SIZE; i++) { var tile = this.g_array[i]; var item = this.gems.create( i % this.FIELD_SIZE * this.TILE_SIZE + this.OFFSET_X, // x position Math.floor(i / this.FIELD_SIZE) * this.TILE_SIZE + this.OFFSET_Y, // y position "tile_"+tile); item.inputEnabled = true; item.events.onInputOver.add(this.pointerIsOver, this); // change origin to midpoint for rotation juice later. item.anchor.setTo(0.5, 0.5); } // force a 'reward' property onto all the gems for scoring. this.gems.setAll('reward', 100, false, false, 0, true); }, pointerIsOver: function (gem, pointer) { this.gem_selected.reset( gem.x - this.OFFSET_X - gem.width / 2, gem.y - this.OFFSET_Y - gem.height / 2); }, }; <file_sep>/static/js/createjs_proj/level01.js (function () { var stage; var queue; /* Create a Queue */ function init() { queue = new createjs.LoadQueue(); queue.installPlugin(create.Sound); // id, callback function queue.addEventListener("complete", loadComplete); queue.loadManifest([ {id: "ufo", src: '/static/assets/testingGrounds/ufoRed.png'}, ]); } function loadComplete() { setupStage(); buildUfos(); } /* Setup the Stage and Loop */ function setupStage() { // reference to the canvas stage = new create.Stage(document.getElementById('level01')); // create a Ticker that will call stage.update() around 60 times a second create.Ticker.setFPS(60); create.Ticker.setPaused(false); // id, callback function create.Ticker.addEventListener("tick", tick); } function tick(e) { // don't update if paused if(!e.paused){ stage.update(); } } /* Add the Actors */ function buildUfos() { var img = queue.getResult("ufo"); var i, sound, ufo; for (i = 0; i < 3; i++) { // sprite from image ufo = new create.Bitmap(img); ufo.x = i * 200; // add sprite to stage stage.addChild(ufo); // animate the sprite create.Tween.get(ufo) .wait(i * 1000) .to({y : 480}, 1000, create.Ease.quadOut) .call(ufoComplete); // is saving a reference to the sound necessary here? sound = create.Sound.play('woosh', create.Sound.INTERRUPT_NONE, i * 1000); } } function ufoComplete() { stage.removeChild(this); if (!stage.getNumChildren()) { create.Sound.play('chime'); } } return init(); })(); <file_sep>/localdev.py import flask app = flask.Flask(__name__) ### ROUTES @app.route('/') def index(): return flask.redirect("/static/index.html") @app.route('/index') def redirects(): return flask.redirect('/') @app.route("/favicon.ico") def favicon(): return flask.redirect("/static/favicon.ico") if __name__ == "__main__": app.run(debug=True) <file_sep>/static/js/candy_conquest/mainMenu.js BasicGame.MainMenu = function (game) { }; BasicGame.MainMenu.prototype = { create: function () { // sprites are loaded in the order added here. this.bg = this.add.tilemap('level'); this.bg.addTilesetImage('level_sheet', 'tiles'); var layer = this.bg.createLayer('layer_1'); layer.resizeWorld(); layer.wrap = true; this.setupIntro(); console.log("create complete"); }, update: function () { if (this.input.activePointer.isDown) { this.state.start('Game'); } // Do some nice funky main menu effect here }, startGame: function (pointer) { // Ok, the Play Button has been clicked or touched, so let's stop the music (otherwise it'll carry on playing) // this.musicPregame.stop(); // And start the actual game // this.state.start('Game'); }, // create-related functions setupIntro: function () { // logo this.logoPNG = this.add.sprite( this.game.width / 2, 200, 'logo'); this.logoPNG.anchor.setTo(0.5, 0.5); this.add.tween(this.logoPNG).from({y: -10}, 1000, Phaser.Easing.Bounce.Out, true); }, }; <file_sep>/static/js/createjs_proj/tpl.js (function () { var stage; /* Create a Queue */ function init() { loadComplete(); } function loadComplete() { setupStage(); } /* Setup the Stage and Loop */ function setupStage() { // reference to the canvas stage = new create.Stage(document.getElementById('canvas')); // create a Ticker that will call stage.update() around 60 times a second create.Ticker.setFPS(60); create.Ticker.setPaused(false); // id, callback function create.Ticker.addEventListener("tick", tick); } function tick(e) { // don't update if paused if(!e.paused){ stage.update(); } } return init(); })(); <file_sep>/static/js/createjs_proj/level10.js (function () { const WALL_THICKNESS = 20, PADDLE_WIDTH = 100, PADDLE_SPEED = 16, PUCK_SPEED = 5, PADDLE_HITS_FOR_NEW_LEVEL = 5, SCORE_BOARD_HEIGHT = 50; var stage, canvas, paddle, puck, board, scoreTxt, livesTxt, messageTxt, messageInterval, leftWall, rightWall, ceiling, floor; var leftKeyDown = false, // state switches rightKeyDown = false, // state switches bricks = [], // hold a reference to the board of bricks paddleHits = 0, // used to determine when the next level is needed combo = 0, // for scoring multiplier lives = 5, score = 0, level = 0, gameRunning = true, levels = [ {color: '#705000', points: 1}, {color: '#743fab', points: 2}, {color: '#4f5e04', points: 3}, {color: '#1b5b97', points: 4}, {color: '#c6c43b', points: 5}, {color: '#1a6d68', points: 6}, {color: '#aa7223', points: 7}, {color: '#743fab', points: 8}, {color: '#4f5e04', points: 9}, {color: '#1b5b97', points: 10}, {color: '#c6c43b', points: 11}, {color: '#1a6d68', points: 12} ]; /* Create a Queue */ function init() { loadComplete(); } function loadComplete() { setupStage(); newGame(); } /* Setup the Stage and Loop */ function setupStage() { // reference to the canvas canvas = document.getElementById('level10'); stage = new create.Stage(canvas); // create a Ticker that will call stage.update() around 60 times a second create.Ticker.setFPS(60); create.Ticker.setPaused(false); // id, callback function create.Ticker.addEventListener("tick", tick); } function tick(e) { // don't update if paused if(!e.paused){ runGame(); stage.update(); } } // ------- SETUP functions --------- function newGame () { buildWalls(); buildMessageBoard(); buildPaddle(); buildPuck(); setControls(); newLevel(); newLevel(); console.log("debug: setup complete"); } function buildWalls () { var wall = new create.Shape(); wall.graphics.beginFill("#333"); wall.graphics.drawRect(0, 0, WALL_THICKNESS, canvas.height); stage.addChild(wall); wall = new create.Shape(); wall.graphics.beginFill("#333"); wall.graphics.drawRect(0, 0, WALL_THICKNESS, canvas.height); wall.x = canvas.width - WALL_THICKNESS; stage.addChild(wall); wall = new create.Shape(); wall.graphics.beginFill("#333"); wall.graphics.drawRect(0, 0, canvas.width, WALL_THICKNESS); stage.addChild(wall); leftWall = WALL_THICKNESS; rightWall = canvas.width - WALL_THICKNESS; ceiling = WALL_THICKNESS; } function buildMessageBoard () { board = new create.Shape(); board.graphics.beginFill("#333"); board.graphics.drawRect(0, 0, canvas.width, SCORE_BOARD_HEIGHT); board.y = canvas.height - SCORE_BOARD_HEIGHT; stage.addChild(board); livesTxt = new create.Text('lives: ' + lives, '20px Times', '#fff'); livesTxt.y = board.y + 10; livesTxt.x = WALL_THICKNESS; stage.addChild(livesTxt); scoreTxt = new create.Text('score: ' + score, '20px Times', '#fff'); scoreTxt.textAlign = 'right'; scoreTxt.y = board.y + 10; scoreTxt.x = canvas.width - WALL_THICKNESS; stage.addChild(scoreTxt); messageTxt = new create.Text('Press spacebar to pause.', '18px Times', '#fff'); messageTxt.textAlign = 'center'; messageTxt.y = board.y + 10; messageTxt.x = canvas.width / 2; stage.addChild(messageTxt); } function buildPaddle () { paddle = new create.Shape(); paddle.width = PADDLE_WIDTH; paddle.height = 20; paddle.graphics.beginFill("#3e6dc0") .drawRect(0, 0, paddle.width, paddle.height); paddle.nextX = 0; paddle.x = 20; paddle.y = canvas.height - paddle.height - SCORE_BOARD_HEIGHT; stage.addChild(paddle); } function buildPuck () { puck = new create.Shape(); puck.graphics.beginFill("#FFFFFF") .drawRect(0, 0, 10, 10); puck.width = 10; puck.height = 10; puck.x = canvas.width - 100; puck.y = 160; puck.velX = PUCK_SPEED; puck.velY = PUCK_SPEED; puck.isAlive = true; stage.addChild(puck); } function setControls () { window.onkeydown = handleKeyDown; window.onkeyup = handleKeyUp; } function handleKeyDown (e) { switch (e.keyCode) { case KEY_LEFT: leftKeyDown = true; break; case KEY_RIGHT: rightKeyDown = true; break; } } function handleKeyUp (e) { switch (e.keyCode) { case KEY_LEFT: leftKeyDown = false; break; case KEY_RIGHT: rightKeyDown = false; break; case KEY_SPACE: if (gameRunning) { create.Ticker.setPaused(create.Ticker.getPaused() ? false : true); } else { resetGame(); } break; } } function newLevel () { var i, brick, freeLifeTxt; var data = levels[level], xPos = WALL_THICKNESS, yPos = WALL_THICKNESS, freeLife = Math.round(Math.random() *20), paddleHits = 0; shiftBricksDown(); for (i = 0; i < 20; i++) { brick = new create.Shape(); brick.graphics.beginFill(i === freeLife ? '#009900' : data.color); brick.graphics.drawRect(0, 0, 76, 20); brick.graphics.endFill(); brick.width = 76; brick.height = 20; brick.x = xPos; brick.y = yPos; brick.points = data.points; brick.freeLife = false; bricks.push(brick); stage.addChild(brick); // add text into block position if (i === freeLife) { freeLifeTxt = new create.Text('1UP', '12px Times', '#fff'); freeLifeTxt.x = brick.x + (brick.width / 2); freeLifeTxt.y = brick.y + 4; freeLifeTxt.width = brick.width; freeLifeTxt.textAlign = 'center'; brick.freeLife = freeLifeTxt; stage.addChild(freeLifeTxt); } xPos += 76; if (xPos > (brick.width * 10)) { xPos = WALL_THICKNESS; yPos += brick.height; } level++; if (level === levels.length) { level--; } } } function shiftBricksDown () { var i, brick; var shiftHeight = 80, len = bricks.length; for (i = 0; i < len; i++) { brick = bricks[i]; brick.y += shiftHeight; if (brick.freeLife) brick.freeLife.y += shiftHeight; } } // ------ LOOP functions ------- function runGame () { update(); render(); evalPuck(); evalGame(); } function update () { updatePaddle(); updatePuck(); checkPaddle(); checkBricks(); } function render () {} function evalPuck () {} function evalGame () {} function resetGame () {} function updatePaddle () {} function updatePuck () {} function checkPaddle () {} function checkBricks () {} return init(); })();
a6c80fcda11c7409719ac6961009ab6fef6acad3
[ "JavaScript", "Python", "Markdown" ]
33
JavaScript
amerizalde/html5gamedev
67a733505619bf95961780821fda26b99cbc458e
f79c6c26c852b4ed25e970aac99628773d89dc54
refs/heads/master
<repo_name>erik-sn/web-app<file_sep>/Dockerfile # # ---- Base Node ---- FROM node:10.16.0-alpine AS base # set working directory WORKDIR /code # copy all code here COPY . . # # ---- Dependencies ---- FROM base AS dependencies # install node packages RUN npm set progress=false # install ALL node_modules, including 'devDependencies' RUN npm install # # ---- Test ---- FROM dependencies AS test RUN npm run lint && npm run test # # ---- Build ---- # install only production files FROM dependencies AS build RUN npm run build # # ---- Release ---- FROM build AS release # next.js runs on port 3000 EXPOSE 3000 # start runs the express server with production environment variable CMD npm run start<file_sep>/README.md # Web app template A node server based on next.js that has some extra features: - Linting with eslint `npm run lint` - Testing with jest `npm run test` - Deployments with docker <file_sep>/components/nav/Nav.js import styles from './nav.scss'; const Nav = () => <nav className={styles.nav} />; export default Nav; <file_sep>/components/Container.js import Head from 'next/head'; import styles from '../styles/index.scss'; import Nav from './nav/Nav'; import Footer from './footer/Footer'; const style = ` #__next { position: absolute; height: 100%; width: 100%; } `; const Container = ({ children, className }) => ( <> <Head> <title>Website</title> <style>{style}</style> </Head> <Nav /> <div className={`${styles.container} ${className}`}>{children}</div> <Footer /> </> ); export default Container; <file_sep>/utils/images.js export default { searchIcon: '/static/img/search.svg', }; <file_sep>/pages/index.js import styles from '../styles/index.scss'; import Container from '../components/Container'; import images from '../utils/images'; const Index = () => ( <Container className={styles.index} showNavSearch={false}> <h1>Hello, World</h1> <img src={images.searchIcon} alt="search icon" /> </Container> ); export default Index; <file_sep>/__tests__/index.test.js import { shallow } from 'enzyme'; import App from '../pages/index'; describe('With Enzyme', () => { let wrapper; beforeEach(() => { wrapper = shallow(<App />); }); it('App renders', () => { expect(wrapper.find('Container')).toHaveLength(1); }); });
6af58b0b14c6ba90686b0f5fca61dd50828d2645
[ "Markdown", "JavaScript", "Dockerfile" ]
7
Dockerfile
erik-sn/web-app
49c1b39c36d37fcacf75762ec734c617bca3e181
fd4ba2753112a3e0333c64237c2e81b51e4b6912
refs/heads/master
<repo_name>JasonLiuys/Flask<file_sep>/venv/venv/hello.py from flask import Flask #导入Flask拓展 app = Flask(__name__) #创建Flask实例 #需要传入__name__,作用是为了确定资源所在的路径 #Flask中定义路由是通过装饰器实现的 #路由默认只支持GET,如果需要增加,需要自行指定 @app.route('/', methods=['GET', 'POST']) #定义路由及视图函数 def index(): return 'hello flask' #使用同一个视图函数,来显示不同用户的订单信息 #<>定义路由参数,<>内需要起个名字 @app.route('/orders/<int:order_id>') def get_order_id(order_id): #需要在视图函数括号内填入参数名,后面的代码才能使用 #有时需要对路由做访问优化,订单ID应该是int类型 return 'order_id %s' % order_id #启动程序 if __name__ == '__main__': #执行了app.run.就会将Flask程序运行在一个简易的服务器 app.run() <file_sep>/venv/venv/template.py from flask import Flask, render_template #导入jinja2拓展 app = Flask(__name__) #创建Flask实例 @app.route('/', methods=['GET', 'POST']) #定义路由及视图函数 def index(): #比如需要传入网址 url_str = 'www.baidu.com' my_list = [1,3,5,7,9] my_dict = { 'name' : 'jason', 'url' : 'www.baidu.com' } #通常,模板中变量名和数据中的变量名保持一致 return render_template('index.html', url_str=url_str, my_list = my_list, my_dict = my_dict) #启动程序 if __name__ == '__main__': #执行了app.run.就会将Flask程序运行在一个简易的服务器 app.run() <file_sep>/venv/venv/WTF.py from flask import Flask, render_template, request, flash #导入Flask拓展 from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired,EqualTo app = Flask(__name__) #创建Flask实例 #需要传入__name__,作用是为了确定资源所在的路径 app.secret_key = 'jason' #Flask中定义路由是通过装饰器实现的 #路由默认只支持GET,如果需要增加,需要自行指定 # 目的:实现一个简单的登陆的逻辑处理 # 1.路由需要判断请求方式(get与post) # 2.获取请求的参数 # 3.判断参数是否填写 & 密码是否相同 # 4.如果判断没有问题,那么返回一个success #给模板传消息用flash,模板中需要遍历消息,flash需要对内容加密->设置secret_key #使用WTF实现表单,自定义表单类 class LoginForm(FlaskForm): username = StringField('用户名:', validators=[DataRequired()]) password = PasswordField('密码:', validators=[DataRequired()]) password2 = PasswordField('确认密码:', validators=[DataRequired(), EqualTo('password', '密码填入不一致')]) submit= SubmitField('提交') @app.route('/form' , methods=['GET', 'POST']) def login(): login_form = LoginForm() # 1.判断请求方式 if request.method == 'POST': # 2.获取请求的参数 username = request.form.get('username') password = request.form.get('<PASSWORD>') password2 = request.form.get('<PASSWORD>') # 3. 验证参数.WTF可以一句话实现所有校验 if login_form.validate_on_submit(): print ("success") return 'success' else: flash('参数有误') return render_template('WTF.html', form = login_form) @app.route('/', methods=['GET', 'POST']) #定义路由及视图函数 def index(): #request : 请求对象 --> 获取请求方式,数据 # 1.判断请求方式 if request.method == 'POST': # 2.获取请求的参数 username = request.form.get('username') password = request.form.get('<PASSWORD>') password2 = request.form.get('<PASSWORD>') print (username) # 3.判断参数是否填写 & 密码是否相同 if not all([username, password, password2]): #print ("参数不完整") flash(u"参数不完整") elif password != password2: #print("密码不一致") flash(u"密码不一致") else: return 'success' return render_template('WTF.html') #启动程序 if __name__ == '__main__': #执行了app.run.就会将Flask程序运行在一个简易的服务器 app.run()
73437e6968c6732353e3c5d45b1fb46f0bca3350
[ "Python" ]
3
Python
JasonLiuys/Flask
47f059ede4c4e5abd143a4d6449373add3df5a90
57c3986e17137c108eb355d7e48db351dc4259cb
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Mail; use Redirect; use Auth; use Session; class MailController extends Controller { public function enviarCertificado(Request $request){ // dd($request->all()); global $emailto; $emailto = $request->all()['useremail']; Mail::send('mails.certificado', $request->all(), function($email){ $email->subject('Certificado electoral'); $email->to(Auth::User()->email); }); Session::flash('message', 'El Certificado fue enviado al correo'); return Redirect::to('votante'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Mesa extends Model { protected $table = 'mesa'; protected $primaryKey = 'id'; protected $fillable = [ 'id', 'nombre', 'lugar_id' ]; public function usuarios(){ return $this->hasMany('App\User'); } public function votos(){ return $this->hasMany('App\Voto'); } public function lugar(){ return $this->belongsTo('App\Lugar'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { // $table->increments('id'); $table->string('codigo', 12)->unique(); $table->string('nombre1', 30); $table->string('nombre2', 30)->nullable(); $table->string('apellido1', 30); $table->string('apellido2', 30); $table->string('email',50)->unique(); $table->string('password'); $table->string('rol_id',1)->nullable(); $table->string('tipo_id',3)->nullable(); $table->integer('programa_id')->unsigned()->nullable(); $table->integer('mesa_id')->unsigned()->nullable(); $table->integer('estado_id')->unsigned()->nullable(); $table->rememberToken(); $table->timestamps(); $table->primary('codigo'); $table->foreign('rol_id')->references('id')->on('rol')->onDelete('cascade'); $table->foreign('tipo_id')->references('id')->on('tipo')->onDelete('cascade'); $table->foreign('programa_id')->references('id')->on('programa')->onDelete('cascade'); $table->foreign('mesa_id')->references('id')->on('mesa')->onDelete('cascade'); $table->foreign('estado_id')->references('id')->on('estado')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } } <file_sep> $(document).ready(function(){ $('.modal').modal(); $('select').material_select(); // logica modal confirmacion elimanacion var urlDelete = '#'; $('a.btnDelete').click(function(e){ e.preventDefault(); urlDelete = $(this).attr('href'); $('#modal-confirmarEliminacion').modal('open'); }); $('a#btnEliminar').click(function(){ location.href = urlDelete; }); }); <file_sep>USE db_votaciones; INSERT INTO `facultad`(`id`, `nombre`, `created_at`, `updated_at`) VALUES (1,'Ingenieria','2018-05-04 03:58:05','2018-05-04 03:58:05'), (2,'Ciencias de la Educación','2018-05-04 03:58:05','2018-05-04 03:58:05'), (3,'Ciencias de la Salud','2018-05-04 03:58:05','2018-05-04 03:58:05'), (4,'Humanidades','2018-05-04 03:58:05','2018-05-04 03:58:05'); INSERT INTO `programa`(`id`, `nombre`, `facultad_id`, `created_at`, `updated_at`) VALUES (1,'Ingenieria de Sistemas',1,'2018-05-04 03:59:01','2018-05-04 03:59:01'), (2,'Ingeniería Electronica',1,'2018-05-04 03:59:01','2018-05-04 03:59:01'), (3,'Medicina',3,'2018-05-04 03:59:01','2018-05-04 03:59:01'), (4,'Derecho',4,'2018-05-04 03:59:01','2018-05-04 03:59:01'); INSERT INTO `lugar`(`id`, `nombre`, `created_at`, `updated_at`) VALUES (1,'Lugar N1','2018-05-04 04:06:14','2018-05-04 04:06:14'), (2,'Lugar N2','2018-05-04 04:06:14','2018-05-04 04:06:14'), (3,'Lugar N3','2018-05-04 04:06:14','2018-05-04 04:06:14'), (4,'Lugar N4','2018-05-04 04:06:14','2018-05-04 04:06:14'); INSERT INTO `mesa`(`id`, `nombre`, `lugar_id`, `created_at`, `updated_at`) VALUES (1,'Mesa M01',1,'2018-05-04 04:07:06','2018-05-04 04:07:06'), (2,'Mesa M02',2,'2018-05-04 04:07:06','2018-05-04 04:07:06'), (3,'Mesa M03',3,'2018-05-04 04:07:06','2018-05-04 04:07:06'), (4,'Mesa M04',4,'2018-05-04 04:07:06','2018-05-04 04:07:06'); INSERT INTO `rol`(`id`, `nombre`, `descripcion`, `created_at`, `updated_at`) VALUES ('A','Administrador','Es quien como su nombre lo indica administra el sitio','2018-05-04 04:02:21','2018-05-04 04:02:21'), ('V','Votante','Es quien tiene la facultad de ejercer el voto','2018-05-04 06:01:51','2018-05-04 06:01:51'); INSERT INTO `estado`(`id`, `nombre`, `descripcion`, `created_at`, `updated_at`) VALUES (1, 'No ha votado', 'No puede votar sin autorizacion', '2018-05-04 06:01:51', '2018-05-04 06:01:51'), (2, 'Autorizado', 'Puede votar', '2018-05-04 06:01:51', '2018-05-04 06:01:51'), (3, 'Votando', 'Puede votar', '2018-05-04 06:01:51', '2018-05-04 06:01:51'), (4, 'Voto', 'Ya realizo el proceso de votacion', '2018-05-04 06:01:51', '2018-05-04 06:01:51'); INSERT INTO `tipo`(`id`, `nombre`, `descripcion`, `created_at`, `updated_at`) VALUES ('EST', 'Estudiante', 'Descripcion del Estudiante', '2018-05-04 06:01:51', '2018-05-04 06:01:51'), ('DOC', 'Docente', 'Descripcion del Docente', '2018-05-04 06:01:51', '2018-05-04 06:01:51'), ('EGR', 'Egresado', 'Descripcion del Egresado', '2018-05-04 06:01:51', '2018-05-04 06:01:51'); INSERT INTO `users` (`codigo`, `nombre1`, `nombre2`, `apellido1`, `apellido2`, `email`, `password`, `rol_id`, `tipo_id`, `programa_id`, `mesa_id`, `estado_id`, `remember_token`, `created_at`, `updated_at`) VALUES ('1000', 'Voto', '-', 'en Blanco', '-', '<EMAIL>', '-', NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-04 06:01:51', '2018-05-04 06:01:51'), ('2000', 'Voto', '-', 'en Blanco', '-', '<EMAIL>', '-', NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-04 06:01:51', '2018-05-04 06:01:51'), ('3000', 'Voto', '-', 'en Blanco', '-', '<EMAIL>', '-', NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-04 06:01:51', '2018-05-04 06:01:51'), ('4000', 'Voto', '-', 'en Blanco', '-', '<EMAIL>', '-', NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-04 06:01:51', '2018-05-04 06:01:51'), ('2015110020', 'Juan', 'Jose', 'Meza', 'Gamarra', '<EMAIL>', <PASSWORD>$apxivIWBt4POzh2gDhoebe02J62OHTzC11bFAByaJkc4Hsyeb4RT.', 'A', NULL, NULL, NULL, NULL, NULL, '2018-05-04 09:07:06', '2018-05-04 09:07:06'), ('2015110010', 'Admin', 'A', 'Nis', 'Trador', '<EMAIL>', '$2y$10$gep6e5nZIlfdxc8PwWVmxOCmnjIk/SDNnXEjoJheRBYKy1Z10Ciae', 'A', NULL, NULL, NULL, NULL, NULL, '2018-05-04 09:07:06', '2018-05-04 09:07:06'), ('2012102030', 'Pedro', 'Jose', 'Pineda', 'Palaez', '<EMAIL>', '$2y$10$DWIsaWSMhyddxtN8xQ310eyrM4kcqkzWH2Vb270CWE/g2vcB.xiD2', 'V', 'DOC', 3, 2, 2, NULL, '2018-05-06 05:20:33', '2018-05-06 05:20:33'), ('2013102030', 'Mariana', 'Lucia', 'Herrera', 'Gil', '<EMAIL>', '$2y$10$k/WrasETksDtyGdwVQPDK.V3Q/s3iz6wxG3Xu1vVXiNy3tANdd9MG', 'V', 'EST', 2, 1, 2, NULL, '2018-05-06 05:19:30', '2018-05-06 05:27:13'), ('2014102030', 'Nicolas', 'Jose', 'Ariza', 'Nieto', '<EMAIL>', '$2y$10$PvUyrRK3J684WU1j554vdOChxKRYaSp7Nrp6JVVWccFGhx4JQek/2', 'V', 'EGR', 4, 3, 2, NULL, '2018-05-06 05:15:48', '2018-05-06 05:15:48'), ('2015113040', 'Laura', 'Marcela', 'Perez', 'Lopez', '<EMAIL>', '$2y$10$nkG7Wxi25IK2WpTeisyGc..vzpKa2g12O6MR78pjbwfZa6Sr7LlDq', 'V', 'EST', 4, 4, 1, NULL, '2018-05-06 05:23:39', '2018-05-06 05:28:04'), ('2016114010', 'Andrea', 'Maria', 'Lopez', 'Martinez', '<EMAIL>', '$2y$10$CwOZcQvLdXtVZcF9Sbd6FOeKJrzurbajmXihEOecks6/Akjmp3Hky', 'V', 'DOC', 3, 1, 1, NULL, '2018-05-04 09:07:06', '2018-05-06 05:26:30'), ('2016123040', 'Ana', 'Gabriella', 'Diaz', 'Anaya', '<EMAIL>', '$2y$10$KdEhTwa7LrjIMdnwuyqM9eXbrv99qfn1HjlIMF8ZAw5.UA1phmwd6', 'V', 'EST', 3, 1, 2, NULL, '2018-05-06 05:24:42', '2018-05-06 05:24:42'), ('2017114020', 'Luis', 'Fernando', 'Hernadez', 'Gamarra', '<EMAIL>', '$2y$10$4aTUWiBMpLFFi2GyQKFyHeWKttKH8QnflG6189n4SFU5H.jlzdapC', 'V', 'DOC', 2, 2, 4, NULL, '2018-05-04 09:07:06', '2018-05-06 05:09:46'), ('2018114030', 'Jorge', 'Luis', 'Suarez', 'Bula', '<EMAIL>', '$2y$10$x.b7HkcnxddLtT2CV0dPe.WrDsupLmIqzLgexYxTqTmqt3YanAo6y', 'V', 'EGR', 3, 4, 2, NULL, '2018-05-04 09:07:06', '2018-05-04 09:07:06'); INSERT INTO `organo` (`id`, `nombre`, `descripcion`, `created_at`, `updated_at`) VALUES (1, 'Consejo Superior', 'Sin descripcion', '2018-05-06 05:35:15', '2018-05-06 05:35:15'), (2, 'Consejo Academico', 'Sin descripcion', '2018-05-06 05:35:45', '2018-05-06 05:35:45'), (3, 'Consejo del IDEA', 'Sin descripcion', '2018-05-06 05:36:04', '2018-05-06 05:36:04'), (4, 'Consejo de Facultad', 'Sin descripcion', '2018-05-06 05:36:20', '2018-05-06 05:36:20'); INSERT INTO `candidato` (`id`, `numero`, `foto`, `organo_id`, `created_at`, `updated_at`) VALUES ('1000', 'BLANCO', 'blanco.jpg', 1, '2018-05-06 05:45:33', '2018-05-06 05:45:33'), ('2000', 'BLANCO', 'blanco.jpg', 2, '2018-05-06 05:45:33', '2018-05-06 05:45:33'), ('3000', 'BLANCO', 'blanco.jpg', 3, '2018-05-06 05:45:33', '2018-05-06 05:45:33'), ('4000', 'BLANCO', 'blanco.jpg', 4, '2018-05-06 05:45:33', '2018-05-06 05:45:33'), ('2014102030', '01', '2014102030.jpg', 1, '2018-05-06 05:40:24', '2018-05-06 05:40:24'), ('2012102030', '02', '2012102030.jpg', 1, '2018-05-06 05:43:02', '2018-05-06 05:43:02'), ('2013102030', '03', '2013102030.jpg', 2, '2018-05-06 05:44:01', '2018-05-06 05:44:01'), ('2016114010', '04', '2016114010.jpg', 2, '2018-05-06 05:44:39', '2018-05-06 05:44:39'), ('2018114030', '05', '2018114030.jpg', 3, '2018-05-06 05:45:33', '2018-05-06 05:45:33'), ('2017114020', '06', '2017114020.jpg', 3, '2018-05-06 05:48:45', '2018-05-06 05:48:45'), ('2015113040', '07', '2015113040.jpg', 4, '2018-05-06 05:46:17', '2018-05-06 05:46:17'), ('2016123040', '08', '2016123040.jpg', 4, '2018-05-06 05:50:22', '2018-05-06 05:50:22'); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Session; use Redirect; use App\User; use App\Rol; use App\Programa; use App\Mesa; class UsuarioController extends Controller { public function __construct(){ $this->middleware('auth'); } public function redirect(){ if(Auth::User()->rol_id == 'A'){ // redireccion si es un administrador return redirect()->route('admin.index'); }elseif (Auth::User()->rol_id == 'J'){ // redireccion si es un jurado return redirect()->route('jurado.index'); }elseif (Auth::User()->rol_id == 'V'){ // redireccion si es un votante return redirect()->route('votante.index'); } return view('usuario.noEncontrado'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Http\Request; use Auth; use Redirect; use App\User; use App\Mesa; use App\Organo; use App\Candidato; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function mi_login(){ return view('usuario.login'); } public function index(){ $organos = Organo::all(); $candidatos = Candidato::all(); $date = getDate(); // dd($organos); return view('usuario.index')->with('organos', $organos)->with('candidatos', $candidatos)->with('date',$date); } public function buscarMesa(Request $request){ $user = User::find($request->all()['codigo']); // dd($user); return view('usuario.mi-mesa')->with('user', $user); } } <file_sep><?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use DB; class User extends Authenticatable { use Notifiable; // protected $table = 'users'; protected $primaryKey = 'codigo'; public $incrementing = false; protected $fillable = [ 'codigo', 'nombre1', 'nombre2', 'apellido1', 'apellido2', 'email', 'password', 'rol_id', 'tipo_id', 'programa_id', 'mesa_id', 'estado_id' ]; protected $hidden = [ 'remember_token' ]; public function rol(){ return $this->belongsTo('App\Rol'); } public function programa(){ return $this->belongsTo('App\Programa'); } public function mesa(){ return $this->belongsTo('App\Mesa'); } public function tipo(){ return $this->belongsTo('App\Tipo'); } public function estado(){ return $this->belongsTo('App\Estado'); } public function candidato(){ return $this->hasOne('App\Candidato'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Redirect; use App\User; use App\Mesa; use App\Voto; use App\Organo; use App\Candidato; class JuradoController extends Controller { public function __construct(){ $this->middleware('auth'); } public function jurado_index(){ $mesa = Mesa::where('id', Auth::User()->mesa_id)->first(); $date = getDate(); // dd($mesa->usuarios[0]->rol); return view('usuario.jurado.inicio-jurado')->with('usuarios',$mesa->usuarios)->with('date',$date); } public function autorizar($codigo){ $usuario = User::find($codigo); $usuario->estado_id = 2; $usuario->save(); return Redirect::to('/jurado'); } public function desautorizar($codigo){ $usuario = User::find($codigo); $usuario->estado_id = 1; $usuario->save(); return Redirect::to('/jurado'); } public function buscarVotante(Request $request){ // $mesa = Mesa::where('id', Auth::User()->mesa_id)->first(); $date = getDate(); $user = User::where('codigo',$request->all()['codigo'])->get(); if ((count($user)>0) && ($user[0]->mesa_id != (int) $request->all()['mesa_id'] )){ // dd( $user[0]); return view('usuario.jurado.inicio-jurado')->with('usuarios',$user)->with('date',$date)->with("useri",$user[0]); } return view('usuario.jurado.inicio-jurado')->with('usuarios',$user)->with('date',$date); } public function resultados(){ $organos = Organo::all(); $candidatos = Candidato::all(); // dd($organos); return view('usuario.jurado.resultados')->with('organos', $organos)->with('candidatos', $candidatos); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Candidato extends Model { protected $table = 'candidato'; protected $primaryKey = 'id'; protected $fillable = [ 'id', 'numero', 'organo_id', 'foto' ]; public function usuario(){ return $this->belongsTo('App\User', 'id'); } public function organo(){ return $this->belongsTo('App\Organo'); } public function votos(){ return $this->hasMany('App\Voto'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Programa extends Model { protected $table = 'programa'; protected $primaryKey = 'id'; protected $fillable = [ 'id', 'nombre', 'facultad_id' ]; public function usuarios(){ return $this->hasMany('App\User'); } public function facultad(){ return $this->belongsTo('App\Facultad'); } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.7.7 -- https://www.phpmyadmin.net/ -- -- Servidor: localhost -- Tiempo de generación: 08-05-2018 a las 01:33:49 -- Versión del servidor: 10.1.30-MariaDB -- Versión de PHP: 7.2.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `db_votaciones` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `candidato` -- CREATE TABLE `candidato` ( `id` varchar(12) COLLATE utf8mb4_unicode_ci NOT NULL, `numero` varchar(10) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `foto` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `organo_id` int(10) UNSIGNED NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `candidato` -- INSERT INTO `candidato` (`id`, `numero`, `foto`, `organo_id`, `created_at`, `updated_at`) VALUES ('1000', 'BLANCO', 'voto_en_blanco.jpg', 1, '2018-05-06 10:45:33', '2018-05-06 10:45:33'), ('2000', 'BLANCO', 'voto_en_blanco.jpg', 2, '2018-05-06 10:45:33', '2018-05-06 10:45:33'), ('2012102030', '02', 'candidato_2012102030.jpg', 1, '2018-05-06 10:43:02', '2018-05-06 10:43:02'), ('2013102030', '03', 'candidato_2013102030.jpg', 2, '2018-05-06 10:44:01', '2018-05-06 10:44:01'), ('2014102030', '01', 'candidato_2014102030.jpg', 1, '2018-05-06 10:40:24', '2018-05-06 10:40:24'), ('2015113040', '07', 'candidato_2015113040.jpg', 4, '2018-05-06 10:46:17', '2018-05-06 10:46:17'), ('2016114010', '04', 'candidato_2016114010.jpg', 2, '2018-05-06 10:44:39', '2018-05-06 10:44:39'), ('2016123040', '08', 'candidato_2016123040.jpg', 4, '2018-05-06 10:50:22', '2018-05-06 10:50:22'), ('2017114020', '06', 'candidato_2017114020.jpg', 3, '2018-05-06 10:48:45', '2018-05-06 10:48:45'), ('2018114030', '05', 'candidato_2018114030.jpg', 3, '2018-05-06 10:45:33', '2018-05-06 10:45:33'), ('3000', 'BLANCO', 'voto_en_blanco.jpg', 3, '2018-05-06 10:45:33', '2018-05-06 10:45:33'), ('4000', 'BLANCO', 'voto_en_blanco.jpg', 4, '2018-05-06 10:45:33', '2018-05-06 10:45:33'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `estado` -- CREATE TABLE `estado` ( `id` int(10) UNSIGNED NOT NULL, `nombre` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL, `descripcion` text COLLATE utf8mb4_unicode_ci, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `estado` -- INSERT INTO `estado` (`id`, `nombre`, `descripcion`, `created_at`, `updated_at`) VALUES (1, 'No ha votado', 'No puede votar sin autorizacion', '2018-05-04 11:01:51', '2018-05-04 11:01:51'), (2, 'Autorizado', 'Puede votar', '2018-05-04 11:01:51', '2018-05-04 11:01:51'), (3, 'Votando', 'Puede votar', '2018-05-04 11:01:51', '2018-05-04 11:01:51'), (4, 'Voto', 'Ya realizo el proceso de votacion', '2018-05-04 11:01:51', '2018-05-04 11:01:51'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `facultad` -- CREATE TABLE `facultad` ( `id` int(10) UNSIGNED NOT NULL, `nombre` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `facultad` -- INSERT INTO `facultad` (`id`, `nombre`, `created_at`, `updated_at`) VALUES (1, 'Ingenieria', '2018-05-04 08:58:05', '2018-05-04 08:58:05'), (2, 'Ciencias de la Educación', '2018-05-04 08:58:05', '2018-05-04 08:58:05'), (3, 'Ciencias de la Salud', '2018-05-04 08:58:05', '2018-05-04 08:58:05'), (4, 'Humanidades', '2018-05-04 08:58:05', '2018-05-04 08:58:05'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `lugar` -- CREATE TABLE `lugar` ( `id` int(10) UNSIGNED NOT NULL, `nombre` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `lugar` -- INSERT INTO `lugar` (`id`, `nombre`, `created_at`, `updated_at`) VALUES (1, 'Lugar N1', '2018-05-04 09:06:14', '2018-05-04 09:06:14'), (2, 'Lugar N2', '2018-05-04 09:06:14', '2018-05-04 09:06:14'), (3, 'Lugar N3', '2018-05-04 09:06:14', '2018-05-04 09:06:14'), (4, 'Lugar N4', '2018-05-04 09:06:14', '2018-05-04 09:06:14'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `mesa` -- CREATE TABLE `mesa` ( `id` int(10) UNSIGNED NOT NULL, `nombre` varchar(15) COLLATE utf8mb4_unicode_ci NOT NULL, `lugar_id` int(10) UNSIGNED NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `mesa` -- INSERT INTO `mesa` (`id`, `nombre`, `lugar_id`, `created_at`, `updated_at`) VALUES (1, 'Mesa M01', 1, '2018-05-04 09:07:06', '2018-05-04 09:07:06'), (2, 'Mesa M02', 2, '2018-05-04 09:07:06', '2018-05-04 09:07:06'), (3, 'Mesa M03', 3, '2018-05-04 09:07:06', '2018-05-04 09:07:06'), (4, 'Mesa M04', 4, '2018-05-04 09:07:06', '2018-05-04 09:07:06'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (17, '2018_05_03_000001_create_rol_table', 1), (18, '2018_05_03_000002_create_facultad_table', 1), (19, '2018_05_03_000003_create_programa_table', 1), (20, '2018_05_03_120811_create_lugar_table', 1), (21, '2018_05_03_120819_create_mesa_table', 1), (22, '2018_05_03_121523_create_organo_table', 1), (23, '2018_05_07_164427_create_estado_table', 1), (24, '2018_05_07_164442_create_tipo_table', 1), (25, '2019_10_12_000000_create_users_table', 1), (26, '2019_10_12_100000_create_password_resets_table', 1), (27, '2020_05_03_000002_create_candidato_table', 1), (28, '2020_05_03_000003_create_voto_table', 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `organo` -- CREATE TABLE `organo` ( `id` int(10) UNSIGNED NOT NULL, `nombre` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL, `descripcion` text COLLATE utf8mb4_unicode_ci, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `organo` -- INSERT INTO `organo` (`id`, `nombre`, `descripcion`, `created_at`, `updated_at`) VALUES (1, 'Consejo Superior', 'Sin descripcion', '2018-05-06 10:35:15', '2018-05-06 10:35:15'), (2, 'Consejo Academico', 'Sin descripcion', '2018-05-06 10:35:45', '2018-05-06 10:35:45'), (3, 'Consejo del IDEA', 'Sin descripcion', '2018-05-06 10:36:04', '2018-05-06 10:36:04'), (4, 'Consejo de Facultad', 'Sin descripcion', '2018-05-06 10:36:20', '2018-05-06 10:36:20'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `programa` -- CREATE TABLE `programa` ( `id` int(10) UNSIGNED NOT NULL, `nombre` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `facultad_id` int(10) UNSIGNED NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `programa` -- INSERT INTO `programa` (`id`, `nombre`, `facultad_id`, `created_at`, `updated_at`) VALUES (1, 'Ingenieria de Sistemas', 1, '2018-05-04 08:59:01', '2018-05-04 08:59:01'), (2, 'Ingeniería Electronica', 1, '2018-05-04 08:59:01', '2018-05-04 08:59:01'), (3, 'Medicina', 3, '2018-05-04 08:59:01', '2018-05-04 08:59:01'), (4, 'Derecho', 4, '2018-05-04 08:59:01', '2018-05-04 08:59:01'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `rol` -- CREATE TABLE `rol` ( `id` varchar(1) COLLATE utf8mb4_unicode_ci NOT NULL, `nombre` varchar(15) COLLATE utf8mb4_unicode_ci NOT NULL, `descripcion` text COLLATE utf8mb4_unicode_ci, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `rol` -- INSERT INTO `rol` (`id`, `nombre`, `descripcion`, `created_at`, `updated_at`) VALUES ('A', 'Administrador', 'Es quien como su nombre lo indica administra el sitio', '2018-05-04 09:02:21', '2018-05-04 09:02:21'), ('V', 'Votante', 'Es quien tiene la facultad de ejercer el voto', '2018-05-04 11:01:51', '2018-05-04 11:01:51'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tipo` -- CREATE TABLE `tipo` ( `id` varchar(3) COLLATE utf8mb4_unicode_ci NOT NULL, `nombre` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL, `descripcion` text COLLATE utf8mb4_unicode_ci, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `tipo` -- INSERT INTO `tipo` (`id`, `nombre`, `descripcion`, `created_at`, `updated_at`) VALUES ('DOC', 'Docente', 'Descripcion del Docente', '2018-05-04 11:01:51', '2018-05-04 11:01:51'), ('EGR', 'Egresado', 'Descripcion del Egresado', '2018-05-04 11:01:51', '2018-05-04 11:01:51'), ('EST', 'Estudiante', 'Descripcion del Estudiante', '2018-05-04 11:01:51', '2018-05-04 11:01:51'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `users` -- CREATE TABLE `users` ( `codigo` varchar(12) COLLATE utf8mb4_unicode_ci NOT NULL, `nombre1` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL, `nombre2` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `apellido1` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL, `apellido2` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `rol_id` varchar(1) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `tipo_id` varchar(3) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `programa_id` int(10) UNSIGNED DEFAULT NULL, `mesa_id` int(10) UNSIGNED DEFAULT NULL, `estado_id` int(10) UNSIGNED DEFAULT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `users` -- INSERT INTO `users` (`codigo`, `nombre1`, `nombre2`, `apellido1`, `apellido2`, `email`, `password`, `rol_id`, `tipo_id`, `programa_id`, `mesa_id`, `estado_id`, `remember_token`, `created_at`, `updated_at`) VALUES ('1000', 'Voto', '-', 'en Blanco', '-', '<EMAIL>', '-', NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-04 11:01:51', '2018-05-04 11:01:51'), ('2000', 'Voto', '-', 'en Blanco', '-', '<EMAIL>', '-', NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-04 11:01:51', '2018-05-04 11:01:51'), ('2012102030', 'Pedro', 'Jose', 'Pineda', 'Palaez', '<EMAIL>', '$2y$10$DWIsaWSMhyddxtN8xQ310eyrM4kcqkzWH2Vb270CWE/g2vcB.xiD2', 'V', 'DOC', 3, 2, 2, NULL, '2018-05-06 10:20:33', '2018-05-06 10:20:33'), ('2013102030', 'Mariana', 'Lucia', 'Herrera', 'Gil', '<EMAIL>', '$2y$10$k/WrasETksDtyGdwVQPDK.V3Q/s3iz6wxG3Xu1vVXiNy3tANdd9MG', 'V', 'EST', 2, 1, 2, NULL, '2018-05-06 10:19:30', '2018-05-06 10:27:13'), ('2014102030', 'Nicolas', 'Jose', 'Ariza', 'Nieto', '<EMAIL>', '$2y$10$PvUyrRK3J684WU1j554vdOChxKRYaSp7Nrp6JVVWccFGhx4JQek/2', 'V', 'EGR', 4, 3, 2, NULL, '2018-05-06 10:15:48', '2018-05-06 10:15:48'), ('2015110010', 'Admin', 'A', 'Nis', 'Trador', '<EMAIL>', '$2y$10$gep6e5nZIlfdxc8PwWVmxOCmnjIk/SDNnXEjoJheRBYKy1Z10Ciae', 'A', NULL, NULL, NULL, NULL, NULL, '2018-05-04 14:07:06', '2018-05-04 14:07:06'), ('2015110020', 'Juan', 'Jose', 'Meza', 'Gamarra', '<EMAIL>', '$2y$10$apxivIWBt4POzh2gDhoebe02J62OHTzC11bFAByaJkc4Hsyeb4RT.', 'A', NULL, NULL, NULL, NULL, NULL, '2018-05-04 14:07:06', '2018-05-04 14:07:06'), ('2015113040', 'Laura', 'Marcela', 'Perez', 'Lopez', '<EMAIL>', '$2y$10$nkG7Wxi25IK2WpTeisyGc..vzpKa2g12O6MR78pjbwfZa6Sr7LlDq', 'V', 'EST', 4, 4, 1, NULL, '2018-05-06 10:23:39', '2018-05-06 10:28:04'), ('2016114010', 'Andrea', 'Maria', 'Lopez', 'Martinez', '<EMAIL>', <PASSWORD>', 'V', 'DOC', 3, 1, 1, NULL, '2018-05-04 14:07:06', '2018-05-06 10:26:30'), ('2016123040', 'Ana', 'Gabriella', 'Diaz', 'Anaya', '<EMAIL>', '$2y$10$KdEhTwa7LrjIMdnwuyqM9eXbrv99qfn1HjlIMF8ZAw5.UA1phmwd6', 'V', 'EST', 3, 1, 2, NULL, '2018-05-06 10:24:42', '2018-05-06 10:24:42'), ('2017114020', 'Luis', 'Fernando', 'Hernadez', 'Gamarra', '<EMAIL>', '$2y$10$4aTUWiBMpLFFi2GyQKFyHeWKttKH8QnflG6189n4SFU5H.jlzdapC', 'V', 'DOC', 2, 2, 4, NULL, '2018-05-04 14:07:06', '2018-05-06 10:09:46'), ('2018114030', 'Jorge', 'Luis', 'Suarez', 'Bula', '<EMAIL>', '$2y$10$x.b7HkcnxddLtT2CV0dPe.WrDsupLmIqzLgexYxTqTmqt3YanAo6y', 'V', 'EGR', 3, 4, 2, NULL, '2018-05-04 14:07:06', '2018-05-04 14:07:06'), ('3000', 'Voto', '-', 'en Blanco', '-', '<EMAIL>', '-', NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-04 11:01:51', '2018-05-04 11:01:51'), ('4000', 'Voto', '-', 'en Blanco', '-', '<EMAIL>', '-', NULL, NULL, NULL, NULL, NULL, NULL, '2018-05-04 11:01:51', '2018-05-04 11:01:51'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `voto` -- CREATE TABLE `voto` ( `id` int(10) UNSIGNED NOT NULL, `mesa_id` int(10) UNSIGNED NOT NULL, `candidato_id` varchar(12) COLLATE utf8mb4_unicode_ci NOT NULL, `cantidad` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `candidato` -- ALTER TABLE `candidato` ADD PRIMARY KEY (`id`), ADD KEY `candidato_organo_id_foreign` (`organo_id`); -- -- Indices de la tabla `estado` -- ALTER TABLE `estado` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `facultad` -- ALTER TABLE `facultad` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `lugar` -- ALTER TABLE `lugar` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `mesa` -- ALTER TABLE `mesa` ADD PRIMARY KEY (`id`), ADD KEY `mesa_lugar_id_foreign` (`lugar_id`); -- -- Indices de la tabla `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `organo` -- ALTER TABLE `organo` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`); -- -- Indices de la tabla `programa` -- ALTER TABLE `programa` ADD PRIMARY KEY (`id`), ADD KEY `programa_facultad_id_foreign` (`facultad_id`); -- -- Indices de la tabla `rol` -- ALTER TABLE `rol` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `tipo` -- ALTER TABLE `tipo` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`codigo`), ADD UNIQUE KEY `users_codigo_unique` (`codigo`), ADD UNIQUE KEY `users_email_unique` (`email`), ADD KEY `users_rol_id_foreign` (`rol_id`), ADD KEY `users_tipo_id_foreign` (`tipo_id`), ADD KEY `users_programa_id_foreign` (`programa_id`), ADD KEY `users_mesa_id_foreign` (`mesa_id`), ADD KEY `users_estado_id_foreign` (`estado_id`); -- -- Indices de la tabla `voto` -- ALTER TABLE `voto` ADD PRIMARY KEY (`id`), ADD KEY `voto_mesa_id_foreign` (`mesa_id`), ADD KEY `voto_candidato_id_foreign` (`candidato_id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `estado` -- ALTER TABLE `estado` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `facultad` -- ALTER TABLE `facultad` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `lugar` -- ALTER TABLE `lugar` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `mesa` -- ALTER TABLE `mesa` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=29; -- -- AUTO_INCREMENT de la tabla `organo` -- ALTER TABLE `organo` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `programa` -- ALTER TABLE `programa` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `voto` -- ALTER TABLE `voto` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `candidato` -- ALTER TABLE `candidato` ADD CONSTRAINT `candidato_id_foreign` FOREIGN KEY (`id`) REFERENCES `users` (`codigo`) ON DELETE CASCADE, ADD CONSTRAINT `candidato_organo_id_foreign` FOREIGN KEY (`organo_id`) REFERENCES `organo` (`id`) ON DELETE CASCADE; -- -- Filtros para la tabla `mesa` -- ALTER TABLE `mesa` ADD CONSTRAINT `mesa_lugar_id_foreign` FOREIGN KEY (`lugar_id`) REFERENCES `lugar` (`id`) ON DELETE CASCADE; -- -- Filtros para la tabla `programa` -- ALTER TABLE `programa` ADD CONSTRAINT `programa_facultad_id_foreign` FOREIGN KEY (`facultad_id`) REFERENCES `facultad` (`id`) ON DELETE CASCADE; -- -- Filtros para la tabla `users` -- ALTER TABLE `users` ADD CONSTRAINT `users_estado_id_foreign` FOREIGN KEY (`estado_id`) REFERENCES `estado` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `users_mesa_id_foreign` FOREIGN KEY (`mesa_id`) REFERENCES `mesa` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `users_programa_id_foreign` FOREIGN KEY (`programa_id`) REFERENCES `programa` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `users_rol_id_foreign` FOREIGN KEY (`rol_id`) REFERENCES `rol` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `users_tipo_id_foreign` FOREIGN KEY (`tipo_id`) REFERENCES `tipo` (`id`) ON DELETE CASCADE; -- -- Filtros para la tabla `voto` -- ALTER TABLE `voto` ADD CONSTRAINT `voto_candidato_id_foreign` FOREIGN KEY (`candidato_id`) REFERENCES `candidato` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `voto_mesa_id_foreign` FOREIGN KEY (`mesa_id`) REFERENCES `mesa` (`id`) ON DELETE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Organo extends Model { protected $table = 'organo'; protected $primaryKey = 'id'; protected $fillable = [ 'id', 'nombre', 'descripcion' ]; public function candidatos(){ return $this->hasMany('App\Candidato'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Session; use Redirect; use App\User; use App\Rol; use App\Programa; use App\Mesa; use App\Tipo; use App\Estado; class AdminController extends Controller { public function __construct(){ $this->middleware('auth'); } public function admin_index(){ $usuarios = User::where('rol_id', '<>', 'A')->orderBy('estado_id', 'asc')->get(); $datos_select = $this->datos_select_usuario(); // dd($datos_select['roles'][1]->nombre[0]); return view('usuario.admin.inicio-admin')->with('usuarios',$usuarios)->with('datos_select', $datos_select); } public function usuario_create(Request $request){ $usuario = new User($request->all()); $usuario->password = <PASSWORD>($request-><PASSWORD>); $usuario->estado_id = 1; // dd($usuario); $usuario->save(); Session::flash('message', 'Registro exitoso!'); return Redirect::to('/admin'); } public function datos_select_usuario(){ // para los valores de los select en formulario de registro $roles = Rol::where('id', '<>', 'A')->get(); $programas = Programa::all(); $mesas = Mesa::all(); $tipos = Tipo::all(); $estados = Estado::all(); return ['roles'=>$roles, 'programas'=>$programas, 'mesas'=>$mesas, 'tipos'=>$tipos, 'estados'=>$estados]; } public function usuario_form_edit($codigo){ $usuario = User::find($codigo); $datos_select = $this->datos_select_usuario(); return view('usuario.admin.usuario-form-edit')->with('usuario', $usuario)->with('datos_select', $datos_select); } public function usuario_update($codigo, Request $request){ $usuario = User::find($codigo); $usuario->fill($request->all()); // dd($usuario); $usuario->save(); Session::flash('message', 'Actualizacion exitosa!'); return Redirect::to('/admin'); // return redirect()->back(); } public function usuario_delete($codigo){ $usuario = User::find($codigo); $usuario->delete(); Session::flash('message', 'Eliminacion exitosa!'); return Redirect::to('/admin'); } public function autorizar_usuario($codigo){ // $usuario = User::where('codigo','=',$codigo)->first(); $usuario = User::find($codigo); $usuario->estado = 'Autorizado'; $usuario->save(); Session::flash('message', 'El usuario '.$usuario->codigo.' ahora se encuentra autorizado para votar'); return Redirect::to('/admin'); } public function desautorizar_usuario($codigo){ // $usuario = User::where('codigo','=',$codigo)->first(); $usuario = User::find($codigo); $usuario->estado = 'No ha votado'; $usuario->save(); Session::flash('message', 'El usuario '.$usuario->codigo.' se ha desautorizado para votar'); return Redirect::to('/admin'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use App\User; use App\Voto; use App\Organo; use App\Candidato; class VotanteController extends Controller { public function __construct(){ $this->middleware('auth'); } public function votante_index(){ $organos = Organo::all(); $date = getDate(); return view('usuario.votante.inicio-votante')->with('organos',$organos)->with('date',$date); } public function votar(Request $request){ foreach ($request->all() as $key => $candidato_id){ if ($key != "_token" && $key != "mesa_id"){ echo $candidato_id.'<br>'; $voto = new Voto(); $voto->mesa_id = $request->mesa_id; $voto->candidato_id = $candidato_id; $voto->save(); } } $usuario = User::find(Auth::User()->codigo); $usuario->estado_id = 4; $usuario->save(); // dd($usuario); return Redirect()->route('votante.index'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Voto extends Model { protected $table = 'voto'; protected $primaryKey = 'id'; protected $fillable = [ 'id', 'mesa_id', 'candidato_id', 'cantidad' ]; public function candidato(){ return $this->belongsTo('App\Candidato'); } public function mesa(){ return $this->belongsTo('App\Mesa'); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'Controller@index')->name('index'); Route::get('/inicio-sesion', 'Controller@mi_login')->name('miLogin'); Route::post('/buscar-mi-mesa', 'Controller@buscarMesa')->name('buscarMesa'); Route::get('/redireccionar-usuario', 'UsuarioController@redirect')->name('usuario.redirect'); Route::post('/enviar', 'MailController@enviarCertificado')->name('enviarCertificado'); Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() { Route::get('/', 'AdminController@admin_index')->name('admin.index'); Route::group(['prefix' => 'usuario'], function() { Route::post('create', 'AdminController@usuario_create')->name('usuario.create'); Route::get('edit/{codigo}', 'AdminController@usuario_form_edit')->name('usuario.form-edit'); Route::put('update/{codigo}', 'AdminController@usuario_update')->name('usuario.update'); Route::get('delete/{codigo}', 'AdminController@usuario_delete')->name('usuario.delete'); Route::get('autorizar/{codigo}', 'AdminController@autorizar_usuario')->name('usuario.autorizar'); Route::get('desautorizar/{codigo}', 'AdminController@desautorizar_usuario')->name('usuario.desautorizar'); }); }); Route::group(['prefix' => 'votante', 'middleware' => 'auth'], function() { Route::get('/', 'VotanteController@votante_index')->name('votante.index'); Route::post('votar', 'VotanteController@votar')->name('votante.votar'); }); Route::group(['prefix' => 'jurado', 'middleware' => 'auth'], function() { Route::get('/', 'JuradoController@jurado_index')->name('jurado.index'); // Route::post('votar', 'JuradoController@otra')->name('jurado.otra'); Route::get('autorizar/{codigo}', 'JuradoController@autorizar')->name('autorizar'); Route::get('desautorizar/{codigo}', 'JuradoController@desautorizar')->name('desautorizar'); Route::post('buscarVotante', 'JuradoController@buscarVotante')->name('buscarVotante'); Route::get('resultados/', 'JuradoController@resultados')->name('resultados'); }); Route::get('/welcome', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home');
2cd22f51b0e7caa00bb4e3879cb640332773913c
[ "JavaScript", "SQL", "PHP" ]
17
PHP
samir04m/votacionesUnimagLaravel
502994545971c2b77a81583e383aceb6ed2ffb70
43ee97b934739dc3bce22e970d7005fda0e25ee4
refs/heads/master
<file_sep>window.onload = function() { makelist(); document.getElementById('dish-form').addEventListener('submit', addRecipe); } function makelist(){ console.log("hi"); var goodDishes, badDishes; var dishes = [ "Roasted Brussels Sprouts", "Truffel Salt Burrito", "Vegan Philly Style Cheese Steak", "Fresh Brussels Sprouts Soup", "Split Pea Pizza with Cherry Tomatoes and Chocolate Shavings", "Brussels Sprouts with Toasted Breadcrumbs, Parmesan, and Lemon", "Cheesy Maple Roasted Brussels Sprouts and Broccoli with Dried Cherries", "Parmesan Toast with Green Onions and Thyme", "Hot Cheesy Roasted Brussels Sprout Dip", "Gazpacho with Lime and Potato Sauce", "Pomegranate Roasted Brussels Sprouts with Red Grapes and Farro", "Roasted Brussels Sprout and Red Potato Salad", "Smoked Gouda and Poppy Seed Crackers", "Smoky Buttered Brussels Sprouts", "Margherita Pizza with Mushrooms and Canteloupe", "Orange Glazed Vegan Chicken Cutlet", "Sweet and Spicy Roasted Brussels Sprouts", "Smoky Buttered Brussels Sprouts", "Jelly Bean Ice Cream", "Brussels Sprouts and Egg Salad with Hazelnuts" ] goodDishes = dishes.filter( function(dish) { return (/^.*Brussels Sprouts.*$/).test(dish) }); badDishes = dishes.filter( function(dish) { return !(/^.*Brussels Sprouts.*$/).test(dish) }); for( var i = 0 ; i < goodDishes.length ; i++) { var listRecipe = document.createElement("li"); console.log(listRecipe); listRecipe.innerHTML = goodDishes[i]; document.getElementsByTagName("ul")[0].appendChild(listRecipe); console.log(document.getElementsByTagName("ul")[0]); } } function addRecipe(evt) { evt.preventDefault(); var new_recipe = this.dish_name.value; var listRecipe = document.createElement("li"); listRecipe.innerHTML = new_recipe; document.getElementsByTagName("ul")[0].appendChild(listRecipe); } function Clear(obj) { return obj.value=''; }
a5f5a87a242603712351a4707305ac75e43b5daf
[ "JavaScript" ]
1
JavaScript
edvio4/javascripted-brussels-sprouts
ab213189b96013ce3d20cdc3ab74c363a96613c4
0f6ca569682b19e6996c0159f83705efab8e4619
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.siscon.view; import SIGU.paneles.SIUPanel; import SIGU.recursos.Arena; import SIGU.recursos.Grid; import SIGU.ventanas.SIUSecundario; import java.awt.Color; /** * * @author neo */ public class VITabvar extends SIUSecundario{ private SIUPanel panelTitulo; private SIUPanel panelDatos; private SIUPanel panelBotones; public VITabvar(VPrincipal ventanaPrincipal, String tipoSize) { super(ventanaPrincipal, tipoSize); construirPaneles(); } private void construirPaneles(){ panelTitulo = new SIUPanel(this, new Grid(0, 0, 12, 2)); panelTitulo.setColorFondo(Color.orange, 1); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.siscon.model; /** * * @author neo */ public class Tabvar { private int record; private int tipo; private int numero; private String descri; private int codcon; private int correl; private double monto; private String observ; private String fecha; private String fecha2; private double monto2; private double tipcam; private int numnit; public Tabvar(int record) { this.record = record; } public int getRecord() { return record; } public void setRecord(int record) { this.record = record; } public int getTipo() { return tipo; } public void setTipo(int tipo) { this.tipo = tipo; } public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public String getDescri() { return descri; } public void setDescri(String descri) { this.descri = descri; } public int getCodcon() { return codcon; } public void setCodcon(int codcon) { this.codcon = codcon; } public int getCorrel() { return correl; } public void setCorrel(int correl) { this.correl = correl; } public double getMonto() { return monto; } public void setMonto(double monto) { this.monto = monto; } public String getObserv() { return observ; } public void setObserv(String observ) { this.observ = observ; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public String getFecha2() { return fecha2; } public void setFecha2(String fecha2) { this.fecha2 = fecha2; } public double getMonto2() { return monto2; } public void setMonto2(double monto2) { this.monto2 = monto2; } public double getTipcam() { return tipcam; } public void setTipcam(double tipcam) { this.tipcam = tipcam; } public int getNumnit() { return numnit; } public void setNumnit(int numnit) { this.numnit = numnit; } @Override public String toString() { return "Tabvar{" + "record=" + record + ", tipo=" + tipo + ", numero=" + numero + ", descri=" + descri + ", codcon=" + codcon + ", correl=" + correl + ", monto=" + monto + ", observ=" + observ + ", fecha=" + fecha + ", fecha2=" + fecha2 + ", monto2=" + monto2 + ", tipcam=" + tipcam + ", numnit=" + numnit + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.siscon.bd; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author neo */ public class Conexion { private Connection conexion; private final String base_datos = "bd_siscon"; private final String usuario = "root"; private final String contrasena = ""; private final String servidor = "jdbc:mysql://localhost/"+base_datos; private PreparedStatement consulta; private ResultSet resultado; public Conexion(){ try { Class.forName("com.mysql.jdbc.Driver"); conexion = DriverManager.getConnection(servidor,usuario,contrasena); //System.out.println("la conexion fue un EXITO"); } catch (ClassNotFoundException | SQLException e) { System.out.println("Imposible realizar conexion con la Base de Datos"); } } public void cerrar_conexion(){ try { if(resultado != null) resultado.close(); if(consulta != null) consulta.close(); if(conexion != null) conexion.close(); //System.out.println("se cerro exitosamente la conexion"); } catch (SQLException ex) { Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex); } } public Connection getConexion(){ return conexion; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.siscon.view; import SIGU.botones.SIUBoton; import SIGU.etiquetas.SIUEtiqueta; import SIGU.paneles.SIUPanel; import SIGU.recursos.Grid; import SIGU.tablas.ModeloTabla; import SIGU.tablas.SIUTabla; import SIGU.ventanas.SIUSecundario; import com.siscon.controller.CTabvar; import com.siscon.model.Tabvar; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.SwingConstants; /** * * @author neo */ public class VMostrarTabvar extends SIUSecundario{ private VPrincipal ventanaPrincipal; private SIUPanel panel; private SIUPanel panelTitulo; private SIUBoton botonSalir; private SIUEtiqueta iuTitulo; private SIUPanel panelTabla; private SIUTabla iuTabla; /** * * @param ventanaPrincipal * @param tipoSize */ public VMostrarTabvar(VPrincipal ventanaPrincipal, String tipoSize) { super(ventanaPrincipal, tipoSize); this.ventanaPrincipal = ventanaPrincipal; construirPaneles(); setEventos(); } private void construirPaneles(){ panel = new SIUPanel(this, new Grid(0, 0, 12, 12)); panel.setColorFondo(Color.WHITE, 0); panelTitulo = new SIUPanel(panel, new Grid(51, 13, 0, 0, 12, 1), true); iuTitulo = new SIUEtiqueta(panelTitulo, "TABLA 'TABVAR'", new Grid(0, 0, 43, 12), 24, "CENTER", new Color(120, 0, 0)); botonSalir = new SIUBoton(panelTitulo, new Grid(44, 2, 5, 8), "Salir", "/imagenes/cerrar.png", 16, 20, 8, SwingConstants.RIGHT, SwingConstants.CENTER, 'r', "salir de la ventana"); panelTabla = new SIUPanel(panel, new Grid(0, 1, 12, 10), true); construirPanelTabla(); } private void construirPanelTabla(){ ArrayList<Tabvar> lista = CTabvar.getLista(); iuTabla = new SIUTabla( panelTabla, new Grid(0, 0, 12, 12), new String[]{"RECORD", "TIPO", "NUMERO", "DESCRI", "CODCON", "CORREL", "MONTO", "OBSERV", "FECHA", "FECHA2", "MONTO2", "TIPCAM", "NUMNIT"}, new Class[]{Integer.class, Integer.class, Integer.class, String.class, Integer.class, Integer.class, Double.class, String.class, String.class, String.class, Double.class, Integer.class, Integer.class}, new int[]{4,4,4,20,8,8,8,8,8,8,6,6,8}, lista, new ModeloTabla<Tabvar>(){ @Override public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return lista.get(rowIndex).getRecord(); case 1: return lista.get(rowIndex).getTipo(); case 2: return lista.get(rowIndex).getNumero(); case 3: return lista.get(rowIndex).getDescri(); case 4: return lista.get(rowIndex).getCodcon(); case 5: return lista.get(rowIndex).getCorrel(); case 6: return lista.get(rowIndex).getMonto(); case 7: return lista.get(rowIndex).getObserv(); case 8: return lista.get(rowIndex).getFecha(); case 9: return lista.get(rowIndex).getFecha2(); case 10: return lista.get(rowIndex).getMonto2(); case 11: return lista.get(rowIndex).getTipcam(); case 12: return lista.get(rowIndex).getNumnit(); default: return null; } } }); } private void setEventos(){ botonSalir.addActionListener((ActionEvent e) -> { dispose(); }); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.siscon.view; import SIGU.botones.SIUBoton; import SIGU.campoTexto.SIUCampoTexto; import SIGU.campoTexto.SIUFormatoCampoTexto; import SIGU.etiquetas.SIUEtiqueta; import SIGU.paneles.SIUPanel; import SIGU.recursos.Arena; import SIGU.recursos.Fecha; import SIGU.recursos.Grid; import SIGU.ventanas.SIUSecundario; import com.siscon.controller.CTabvar; import com.siscon.model.Tabvar; import com.toedter.calendar.JDateChooser; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.border.LineBorder; /** * * @author neo */ public class VTabvar extends SIUSecundario{ private VPrincipal iuPrincipal; private SIUPanel panel; //construccion de panel1 private SIUPanel panel1; private SIUEtiqueta etiqueta1; private SIUEtiqueta etiqueta2; private SIUEtiqueta etiqueta3; private SIUEtiqueta etiqueta4; private SIUEtiqueta etiqueta5; //construccion de panel2 private SIUPanel panel2; private SIUPanel panelTipo; private SIUPanel panelNumero; private SIUPanel panelDescripcion; private SIUPanel panelInstrucciones; private SIUCampoTexto campoTipo; private SIUCampoTexto campoNumero; private SIUCampoTexto campoDescripcion; private SIUPanel panelCampos; private SIUEtiqueta etiquetaNombre; private SIUCampoTexto campoNombre; private SIUEtiqueta etiquetaCodigoContable; private SIUCampoTexto campoCodigoContable; private SIUEtiqueta etiquetaCorrelativo; private SIUCampoTexto campoCorrelativo; private SIUEtiqueta etiquetaMonto1; private SIUFormatoCampoTexto campoMonto1; private SIUEtiqueta etiquetaMonto2; private SIUFormatoCampoTexto campoMonto2; private SIUEtiqueta etiquetaFecha1; private SIUFormatoCampoTexto campoFecha1; private JDateChooser campoDate1 = new JDateChooser("dd/MM/yyyy", "##/##/####", '_'); private SIUEtiqueta etiquetaFecha2; private SIUFormatoCampoTexto campoFecha2; private JDateChooser campoDate2 = new JDateChooser("dd/MM/yyyy", "##/##/####", '_'); private SIUPanel panelInstruccionesFormato; private SIUEtiqueta etiqueta6; private SIUPanel panel3; private SIUBoton botonCerrar; private SIUBoton botonImprimir; private SIUBoton botonLimpiar; private SIUBoton botonEliminar; private SIUBoton botonModificar; private SIUBoton botonGrabar; private SIUBoton botonMostrar; private Color colorFondoTitulo = new Color(232, 237, 244); private Color colorFondoDatos = new Color(235, 235, 235); private String estadoOp = ""; /** * * @param iuPrincipal * @param sizeView */ public VTabvar(VPrincipal iuPrincipal, String sizeView) { super(iuPrincipal, sizeView); this.iuPrincipal = iuPrincipal; construirPaneles(); setEventos(); setEstadosIniciales(false); setEstadoBotonesIniciales(false); } private void construirPaneles(){ panel = new SIUPanel(this, new Grid(55, 30, 0, 0, 12, 12)); panel.setColorFondo(Color.WHITE, 0); panel1 = new SIUPanel(panel, new Grid(106, 7, 0, 0, 54, 3), true); panel1.setColorFondo(colorFondoTitulo, 0); construriPanel1(); panel2 = new SIUPanel(panel, new Grid(106, 39, 1, 5, 53, 13), true); //panel2.mostrarPuntos(true); construirPanel2(); panel3 = new SIUPanel(panel, new Grid(72, 12, 1, 26, 53, 2), false); construirPanel3(); } private void construriPanel1(){ etiqueta1 = new SIUEtiqueta(panel1, "CAMARA FORESTAL", new Grid(1, 1, 20, 2), 16, "LEFT"); etiqueta2 = new SIUEtiqueta(panel1, "EJECUTIVO", new Grid(1, 3, 20, 2), 16, "LEFT"); etiqueta3 = new SIUEtiqueta(panel1, "PROCESOS DE PARAMETROS - TABLAS", new Grid(21, 1, 50, 2), 16, "CENTER"); etiqueta3.setSubrayarTexto(true); etiqueta4 = new SIUEtiqueta(panel1, "SISTEMA CONTABLE SISCON @v7.1. 2020", new Grid(73, 1, 33, 2), 16, "LEFT"); etiqueta5 = new SIUEtiqueta(panel1, "FECHA: "+new Fecha().getFecha1(), new Grid(73, 3, 33, 2), 16, "LEFT"); } private void construirPanel2(){ panelTipo = new SIUPanel(panel2, new Grid(0, 0, 5, 2), true); panelTipo.setColorFondo(colorFondoDatos, 0); etiqueta1 = new SIUEtiqueta(panelTipo, "TIPO", new Grid(0, 0, 12, 12), 11, "CENTER"); panelNumero = new SIUPanel(panel2, new Grid(6, 0, 7, 2), true); panelNumero.setColorFondo(colorFondoDatos, 0); etiqueta2 = new SIUEtiqueta(panelNumero, "NUMERO", new Grid(0, 0, 12, 12), 11, "CENTER"); panelDescripcion = new SIUPanel(panel2, new Grid(14, 0, 30, 2), true); panelDescripcion.setColorFondo(colorFondoDatos, 0); etiqueta3 = new SIUEtiqueta(panelDescripcion, "DESCRIPCION GENERICA", new Grid(0, 0, 12, 12), 11, "CENTER"); campoTipo = new SIUCampoTexto(panel2, 2, 12, new Grid(0, 2, 5, 3)); campoTipo.setRestriccion("^[0-9]+([,\\.][0-9]*)?$"); campoNumero = new SIUCampoTexto(panel2, 2, 12, new Grid(6, 2, 7, 3)); campoNumero.setRestriccion("^[0-9]+([,\\.][0-9]*)?$"); campoDescripcion = new SIUCampoTexto(panel2, 30, 12, new Grid(14, 2, 30, 3)); campoDescripcion.setRestriccion("[\\p{Alpha}\\p{Alnum}\\p{Space}\\.\\/\\(\\)\\-]"); panelInstrucciones = new SIUPanel(panel2, new Grid(46, 2, 58, 3), true); panelInstrucciones.setColorFondo(colorFondoDatos, 0); etiqueta4 = new SIUEtiqueta(panelInstrucciones, "INSTRUCCIONES FORMATO", new Grid(0, 0, 12, 12), 11, "CENTER"); panelCampos = new SIUPanel(panel2, new Grid(132, 17, 0, 5, 44, 34), false); etiquetaNombre = new SIUEtiqueta(panelCampos, "a. Nombre:", new Grid(2, 2, 30, 2), 12, "LEFT"); etiquetaNombre.setFont(new Font("Verdana", Font.BOLD, 12)); etiquetaNombre.setBorder(new LineBorder(colorFondoDatos)); etiquetaCodigoContable = new SIUEtiqueta(panelCampos, "b. Codigo Contable:", new Grid(2, 4, 35, 2), 12, "LEFT"); etiquetaCodigoContable.setFont(new Font("Verdana", Font.BOLD, 12)); etiquetaCodigoContable.setBorder(new LineBorder(colorFondoDatos)); etiquetaCorrelativo = new SIUEtiqueta(panelCampos, "c. Correlativo:", new Grid(2, 6, 30, 2), 12, "LEFT"); etiquetaCorrelativo.setFont(new Font("Verdana", Font.BOLD, 12)); etiquetaCorrelativo.setBorder(new LineBorder(colorFondoDatos)); etiquetaMonto1 = new SIUEtiqueta(panelCampos, "d. Monto1.:", new Grid(2, 8, 20, 2), 12, "LEFT"); etiquetaMonto1.setFont(new Font("Verdana", Font.BOLD, 12)); etiquetaMonto1.setBorder(new LineBorder(colorFondoDatos)); etiquetaMonto2 = new SIUEtiqueta(panelCampos, "2.:", new Grid(2, 10, 19, 2), 12, "RIGHT"); etiquetaMonto2.setFont(new Font("Verdana", Font.BOLD, 12)); etiquetaMonto2.setBorder(new LineBorder(colorFondoDatos)); etiquetaFecha1 = new SIUEtiqueta(panelCampos, "e. Fecha1.:", new Grid(2, 12, 19, 2), 12, "LEFT"); etiquetaFecha1.setFont(new Font("Verdana", Font.BOLD, 12)); etiquetaFecha1.setBorder(new LineBorder(colorFondoDatos)); etiquetaFecha2 = new SIUEtiqueta(panelCampos, "2.:", new Grid(2, 14, 19, 2), 12, "RIGHT"); etiquetaFecha2.setFont(new Font("Verdana", Font.BOLD, 12)); //etiquetaFecha2.setBorder(new LineBorder(colorFondoDatos)); campoNombre = new SIUCampoTexto(panelCampos, 20, 12, new Grid(42, 2, 90, 2)); campoNombre.setRestriccion("[\\p{Alpha}\\p{Alnum}\\p{Space}\\.\\/\\(\\)\\-]"); //campoNombre.setEditar(false); campoCodigoContable = new SIUCampoTexto(panelCampos, 8, 12, new Grid(42, 4, 30, 2)); campoCodigoContable.setRestriccion("^[0-9]+([,\\.][0-9]*)?$");//"^[1-9][0-9]?$"); //campoCodigoContable.setEditar(false); campoCorrelativo = new SIUCampoTexto(panelCampos, 6, 12, new Grid(42, 6, 30, 2)); campoCorrelativo.setRestriccion("^[0-9]+([,\\.][0-9]*)?$"); //campoCorrelativo.setEditar(false); campoMonto1 = new SIUFormatoCampoTexto(panelCampos, new Grid(42, 8, 30, 2), "#.##", 12, SwingConstants.LEFT); //campoMonto1.setEditar(false); campoMonto2 = new SIUFormatoCampoTexto(panelCampos, new Grid(42, 10, 30, 2), "#.##", 12, SwingConstants.LEFT); //campoMonto2.setEditar(false); campoFecha1 = new SIUFormatoCampoTexto(panelCampos, new Grid(42, 12, 30, 2), 12, SwingConstants.LEFT); campoFecha1.formatoFecha.setVisible(false); campoDate1.setBounds(campoFecha1.formatoFecha.getX(), campoFecha1.formatoFecha.getY(), campoFecha1.formatoFecha.getWidth(), campoFecha1.formatoFecha.getHeight()); //campoDate1.getCalendarButton().setVisible(false); campoDate1.getDateEditor().getUiComponent().setForeground(new Color(2, 67, 109)); campoDate1.getDateEditor().getUiComponent().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(KeyEvent.VK_ENTER == e.getKeyCode()){ campoDate1.getDateEditor().getUiComponent().transferFocus(); } if(KeyEvent.VK_ESCAPE == e.getKeyCode()) campoDate1.getDateEditor().getUiComponent().transferFocusBackward(); } }); panelCampos.add(campoDate1); //campoFecha1.setEditar(false); campoFecha2 = new SIUFormatoCampoTexto(panelCampos, new Grid(42, 14, 30, 2), 12, SwingConstants.LEFT); campoFecha2.formatoFecha.setVisible(false); campoDate2.setBounds(campoFecha2.formatoFecha.getX(), campoFecha2.formatoFecha.getY(), campoFecha2.formatoFecha.getWidth(), campoFecha2.formatoFecha.getHeight()); //campoDate2.getCalendarButton().setVisible(false); campoDate2.getDateEditor().getUiComponent().setForeground(new Color(2, 67, 109)); campoDate2.getDateEditor().getUiComponent().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(KeyEvent.VK_ENTER == e.getKeyCode()){ campoDate2.getDateEditor().getUiComponent().transferFocus(); } if(KeyEvent.VK_ESCAPE == e.getKeyCode()) campoDate2.getDateEditor().getUiComponent().transferFocusBackward(); } }); panelCampos.add(campoDate2); panelInstruccionesFormato = new SIUPanel(panel2, new Grid(132, 17,46, 5, 58, 34), true); etiqueta6 = new SIUEtiqueta(panelInstruccionesFormato, "Denominacion Parametro - Tabla x15", new Grid(2, 2, 128, 2), 14, "LEFT"); etiqueta6.setFont(new Font("Verdana", Font.BOLD, 14)); etiqueta6 = new SIUEtiqueta(panelInstruccionesFormato, "Campo de integracion Contable n8", new Grid(2, 4, 128, 2), 14, "LEFT"); etiqueta6.setFont(new Font("Verdana", Font.BOLD, 14)); etiqueta6 = new SIUEtiqueta(panelInstruccionesFormato, "Campo encargado de Numerar n6", new Grid(2, 6, 128, 2), 14, "LEFT"); etiqueta6.setFont(new Font("Verdana", Font.BOLD, 14)); etiqueta6 = new SIUEtiqueta(panelInstruccionesFormato, "Rangos Monetarios n8,2", new Grid(2, 8, 128, 2), 14, "LEFT"); etiqueta6.setFont(new Font("Verdana", Font.BOLD, 14)); etiqueta6 = new SIUEtiqueta(panelInstruccionesFormato, "Rango de Fechas dd/mm/aaaa", new Grid(2, 12, 128, 2), 14, "LEFT"); etiqueta6.setFont(new Font("Verdana", Font.BOLD, 14)); } private void construirPanel3(){ botonCerrar = new SIUBoton(panel3, new Grid(66, 1, 6, 10), "CERRAR", "/imagenes/cerrar.png", 14, 20, 4, SwingConstants.RIGHT, SwingConstants.CENTER, 'C', "boton para cerrar la ventana"); botonImprimir = new SIUBoton(panel3, new Grid(58, 1, 6, 10), "IMPRIMIR", "/imagenes/printer.png", 14, 20, 4, SwingConstants.RIGHT, SwingConstants.CENTER, 'P', "boton para imprimir"); botonLimpiar = new SIUBoton(panel3, new Grid(50, 1, 6, 10), "LIMPIAR", "/imagenes/erase.png", 14, 20, 4, SwingConstants.RIGHT, SwingConstants.CENTER, 'L', "boton para limpiar la pantalla"); botonEliminar = new SIUBoton(panel3, new Grid(42, 1, 6, 10), "ELIMINAR", "/imagenes/delete.png", 14, 20, 4, SwingConstants.RIGHT, SwingConstants.CENTER, 'E', "boton para eliminar un registro de la tabla"); botonModificar = new SIUBoton(panel3, new Grid(32, 1, 8, 10), "MODIFICAR", "/imagenes/edit.png", 14, 20, 8, SwingConstants.RIGHT, SwingConstants.CENTER, 'O', "boton para limpiar la pantalla"); botonGrabar = new SIUBoton(panel3, new Grid(24, 1, 6, 10), "GRABAR", "/imagenes/save.png", 14, 20, 4, SwingConstants.RIGHT, SwingConstants.CENTER, 'G', "boton para guardar el nuevo registro"); botonMostrar = new SIUBoton(panel3, new Grid(16, 1, 6, 10), "MOSTRAR", "/imagenes/ojos.png", 14, 20, 4, SwingConstants.RIGHT, SwingConstants.CENTER, 'T', "boton para mostrar los registros"); } private void limpiarCampos(){ estadoOp = ""; campoTipo.setText(""); campoNumero.setText(""); campoDescripcion.setText(""); campoNombre.setText(""); campoCodigoContable.setText(""); campoCorrelativo.setText(""); campoMonto1.formatoNumerico.setText(""); campoMonto2.formatoNumerico.setText(""); campoDate1.setCalendar(null); campoDate2.setCalendar(null); setEstadosIniciales(false); setEstadoBotonesIniciales(false); } private void setEstadosIniciales(boolean estado){ campoDescripcion.setEditar(estado); campoNombre.setEditar(estado); campoCodigoContable.setEditar(estado); campoCorrelativo.setEditar(estado); campoMonto1.setEditarNumeros(estado); campoMonto2.setEditarNumeros(estado); campoDate1.getDateEditor().getUiComponent().setFocusable(estado); campoDate1.getDateEditor().getUiComponent().setEnabled(estado); campoDate2.getDateEditor().getUiComponent().setFocusable(estado); campoDate2.getDateEditor().getUiComponent().setEnabled(estado); campoDescripcion.setText(""); campoNombre.setText(""); campoCodigoContable.setText(""); campoCorrelativo.setText(""); campoMonto1.formatoNumerico.setText(""); campoMonto2.formatoNumerico.setText(""); campoDate1.setCalendar(null); campoDate2.setCalendar(null); } private void setEstadoBotonesIniciales(boolean estado){ botonImprimir.setEnabled(estado); botonEliminar.setEnabled(estado); botonModificar.setEnabled(estado); botonGrabar.setEnabled(estado); } private void setCrearNuevoTabvar(){ if(estadoOp.isEmpty() || !estadoOp.equalsIgnoreCase("GRABAR")){ setEstadosIniciales(true); botonGrabar.setEnabled(true); botonModificar.setEnabled(false); botonEliminar.setEnabled(false); campoDescripcion.requestFocus(); JOptionPane.showMessageDialog(iuPrincipal, "Lo siento, no existe ningun registro con los datos iniciales....\npodra grabar un nuevo registro...!", "ADVERTENCIA", JOptionPane.WARNING_MESSAGE); } estadoOp = "GRABAR"; } private void mostrarDatosTabvar(Tabvar tabvar){ estadoOp = "MODIFICAR"; setEstadoBotonesIniciales(false); setEstadosIniciales(true); botonModificar.setEnabled(true); botonEliminar.setEnabled(true); campoTipo.setText(String.valueOf(tabvar.getTipo())); campoNumero.setText(String.valueOf(tabvar.getNumero())); campoDescripcion.setText(tabvar.getDescri()); campoNombre.setText(tabvar.getObserv()); campoCodigoContable.setText(String.valueOf(tabvar.getCodcon())); campoCorrelativo.setText(String.valueOf(tabvar.getCorrel())); campoMonto1.formatoNumerico.setText(String.valueOf(tabvar.getMonto())); campoMonto2.formatoNumerico.setText(String.valueOf(tabvar.getMonto2())); if(tabvar.getFecha() == null) campoDate1.setCalendar(null); else campoDate1.setDate(new Fecha(tabvar.getFecha()).getDate()); if(tabvar.getFecha2() == null) campoDate2.setCalendar(null); else campoDate2.setDate(new Fecha(tabvar.getFecha2()).getDate()); } private boolean noExistenCamposVacios(){ boolean verificador = false; if(!campoTipo.getText().isEmpty()){ if(!campoNumero.getText().isEmpty()){ verificador = true; } } return verificador; } private void eliminarRegistro(){ if(!campoTipo.getText().isEmpty()){ if(!campoNumero.getText().isEmpty()){ int tipo = Integer.parseInt(campoTipo.getText()); int numero = Integer.parseInt(campoNumero.getText()); if(tipo > 0 && numero > 0){ int resp = JOptionPane.showConfirmDialog(iuPrincipal, "¿Esta seguro?", "Alerta!", JOptionPane.YES_NO_OPTION); if(resp == 0){ Tabvar tabvar = CTabvar.getTabvar(tipo, numero); if(tabvar == null){ JOptionPane.showMessageDialog(null, "Lo siento, pero no existe el registro TABVAR con TIPO = "+tipo+" y NUMERO = "+numero+" en la BASE DE DATOS....!", "ADVERTENCIA", JOptionPane.WARNING_MESSAGE); }else{ if(CTabvar.eliminarTabvar(tabvar)){ JOptionPane.showMessageDialog(iuPrincipal, "se ha eliminado los datos del registro TABVAR correctamente...!"); limpiarCampos(); } } } } } } } private void mostrarTabla(){ VMostrarTabvar iuMostrar = new VMostrarTabvar(iuPrincipal, "mediano"); iuMostrar.mostrarVentana(); } private void modificarDatosRegistro(){ if(!campoTipo.getText().isEmpty()){ if(!campoNumero.getText().isEmpty()){ int tipo = Integer.parseInt(campoTipo.getText()); int numero = Integer.parseInt(campoNumero.getText()); if(tipo > 0 && numero > 0){ Tabvar tabvar = CTabvar.getTabvar(tipo, numero); if(tabvar == null){ JOptionPane.showMessageDialog(null, "Lo siento, pero no existe el registro TABVAR con TIPO = "+tipo+" y NUMERO = "+numero+" en la BASE DE DATOS....!", "ADVERTENCIA", JOptionPane.WARNING_MESSAGE); }else{ if(noExistenCamposVacios()){ tabvar.setTipo(Integer.parseInt(campoTipo.getText())); tabvar.setNumero(Integer.parseInt(campoNumero.getText())); tabvar.setDescri(campoDescripcion.getText()); tabvar.setObserv(campoNombre.getText()); if(campoCodigoContable.getText().isEmpty()) tabvar.setCodcon(0); else tabvar.setCodcon(Integer.parseInt(campoCodigoContable.getText())); if(campoCorrelativo.getText().isEmpty()) tabvar.setCorrel(0); else tabvar.setCorrel(Integer.parseInt(campoCorrelativo.getText())); if(campoMonto1.formatoNumerico.getText().isEmpty()) tabvar.setMonto(0); else tabvar.setMonto(Double.parseDouble(campoMonto1.formatoNumerico.getText())); if(campoMonto2.formatoNumerico.getText().isEmpty()) tabvar.setMonto2(0); else tabvar.setMonto2(Double.parseDouble(campoMonto2.formatoNumerico.getText())); if(campoDate1.getDate() != null) tabvar.setFecha(new Fecha().getFecha(campoDate1.getDate(), "yyyy-MM-dd")); else tabvar.setFecha(null); if(campoDate2.getDate() != null) tabvar.setFecha2(new Fecha().getFecha(campoDate2.getDate(), "yyyy-MM-dd")); else tabvar.setFecha2(null); //System.out.println("la tabvar PARA MODIFICAR ES: "+tabvar.toString()); if(CTabvar.modificarTabvar(tabvar)){ JOptionPane.showMessageDialog(iuPrincipal, "se ha modiicado los datos del registro TABVAR correctamente...!"); limpiarCampos(); } } } } } } } private void guardarNuevoRegistro(){ if(noExistenCamposVacios()){ Tabvar tabvar = new Tabvar(0); tabvar.setTipo(Integer.parseInt(campoTipo.getText())); tabvar.setNumero(Integer.parseInt(campoNumero.getText())); tabvar.setDescri(campoDescripcion.getText()); tabvar.setObserv(campoNombre.getText()); if(campoCodigoContable.getText().isEmpty()) tabvar.setCodcon(0); else tabvar.setCodcon(Integer.parseInt(campoCodigoContable.getText())); if(campoCorrelativo.getText().isEmpty()) tabvar.setCorrel(0); else tabvar.setCorrel(Integer.parseInt(campoCorrelativo.getText())); if(campoMonto1.formatoNumerico.getText().isEmpty()) tabvar.setMonto(0); else tabvar.setMonto(Double.parseDouble(campoMonto1.formatoNumerico.getText())); if(campoMonto2.formatoNumerico.getText().isEmpty()) tabvar.setMonto2(0); else tabvar.setMonto2(Double.parseDouble(campoMonto2.formatoNumerico.getText())); if(campoDate1.getDate() != null) tabvar.setFecha(new Fecha().getFecha(campoDate1.getDate(), "yyyy-MM-dd")); else tabvar.setFecha(null); if(campoDate2.getDate() != null) tabvar.setFecha2(new Fecha().getFecha(campoDate2.getDate(), "yyyy-MM-dd")); else tabvar.setFecha2(null); System.out.println("la tabvar es: "+tabvar.toString()); if(CTabvar.guardarTabvar(tabvar)){ JOptionPane.showMessageDialog(iuPrincipal, "se ha guardado un nuevo registro de TABVAR correctamente...!"); limpiarCampos(); } } } private void setEventos(){ botonCerrar.addActionListener((ActionEvent e) -> { dispose(); }); botonLimpiar.addActionListener((ActionEvent e) -> { limpiarCampos(); }); botonGrabar.addActionListener((ActionEvent e) -> { guardarNuevoRegistro(); }); botonModificar.addActionListener((ActionEvent e) -> { modificarDatosRegistro(); }); botonEliminar.addActionListener((ActionEvent e) -> { eliminarRegistro(); }); botonMostrar.addActionListener((ActionEvent e) -> { mostrarTabla(); }); campoNumero.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { if(!campoTipo.getText().isEmpty()){ if(!campoNumero.getText().isEmpty()){ int tipo = Integer.parseInt(campoTipo.getText()); int numero = Integer.parseInt(campoNumero.getText()); if(tipo > 0 && numero > 0){ Tabvar tabvar = CTabvar.getTabvar(tipo, numero); if(tabvar == null){ setCrearNuevoTabvar(); }else{ mostrarDatosTabvar(tabvar); } } } } } }); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.siscon.controller; import SIGU.main.Principal; import com.siscon.view.VPrincipal; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * * @author neo */ public class CPrincipal { public static void main(String[] arg){ try { // setTheme(String themeName, String licenseKey, String logoString) //com.jtattoo.plaf.acryl.AcrylLookAndFeel.setTheme("Green", "INSERT YOUR LICENSE KEY HERE", "my company"); UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex); } VPrincipal iuPrincipal = new VPrincipal("SISTEMA CONTABILIDAD SISCON @Version v7.1. 2020", "/imagenes/icono.png"); iuPrincipal.setVisible(true); } }
e5369f6b4965e621187fbf265bd5f44869017dc3
[ "Java" ]
6
Java
rudolfPaco/siscon
c8ef26c7abe1a7e38fe831257786be58a9704b73
b8e973600ce00c0728debc0daa810ab3022383ba
refs/heads/master
<file_sep>/* global describe, it */ var wordomat = require('../') var should = require('should') describe('basic', function () { it('should exist', function (done) { should.exist(wordomat()) should(typeof wordomat()).equal('object') done() }) it('should have default options', function (done) { should.exist(wordomat().options) done() }) it('should have override default options', function (done) { var opts = { case: 'uppercase' } var mat = wordomat(opts) should.exist(mat.options) should(mat.options.case).equal('uppercase') should(mat.options.case).not.equal(false) should(mat.options.requiredLetters).equal(false) done() }) it('should return the correct number of words', function (done) { var opts = { wordCount: 5 } var mat = wordomat(opts) should(mat.data.length).equal(5) done() }) it('should return words that are within the same specified length', function (done) { var opts = { minLength: 5, maxLength: 5 } var mat = wordomat(opts) should(mat.data.length).be.above(1) mat.data.forEach(function (word) { should(word.length).equal(5) should(word.length).not.be.above(5) should(word.length).not.be.below(5) }) done() }) it('should return words that are within different specified lengths', function (done) { var opts = { minLength: 2, maxLength: 10 } var mat = wordomat(opts) should(mat.data.length).be.above(1) mat.data.forEach(function (word) { should(word.length).not.be.above(10) should(word.length).not.be.below(2) }) done() }) // TODO // it('should return a nice error when word lengths don’t make sense', function (done) { // var opts = { minLength: 2, maxLength: 1 } // var mat = wordomat(opts) // done() // }) // it('should process long phrases', function (done) { // }) }) <file_sep># Contributing If you’d like to update the word lists, please open a Pull Request against Nina’s repo, rather than this one: [ninastoessinger/word-o-mat](https://github.com/ninastoessinger/word-o-mat). The included JSON files are build from those source files automatically. To run the project locally, first clone it by running the following command in your terminal: ```sh # Clone the project git clone https://github.com/kennethormandy/word-o-mat # Move into the project directory cd word-o-mat ``` Next, with a recent version of [Node.js installed](https://nodejs.org), install the project’s dependencies from [npm](https://npmjs.org), the package manager for JavaScript which came included with Node.js. ```sh # Install dependencies npm install ``` This will also install the word-o-mat RoboFont plugin as a development dependency, so you can rebuild the word lists, if you’d like. There is a build script already written to do this, which you can run using the following command: ```sh # Rebuild the word lists npm run build ``` If you’d like to make any changes, please consider adding a test for it first. You can run the existing tests with: ```sh # Run the tests npm test ``` ![](preview.gif) <file_sep>/* global describe, it */ var wordomat = require('../') var should = require('should') describe('required', function () { it('should limit to words that contain certain characters', function (done) { var opts = { requiredLetters: 'aein', requiredLettersOnly: false } var mat = wordomat(opts) should(mat.data.length).be.above(1) mat.data.forEach(function (word) { should(word.match(/a|e|i|n/g)).not.equal(null) should(word.match(/a|e|i|n/g).length).be.above(0) }) done() }) it('should limit to words that contain all the required characters', function (done) { var opts = { requiredLetters: 'aein', requiredLettersOnly: true } var mat = wordomat(opts) should(mat.data.length).be.above(1) mat.data.forEach(function (word) { should(word.match(/a/)).not.equal(null) should(word.match(/e/)).not.equal(null) should(word.match(/i/)).not.equal(null) should(word.match(/n/)).not.equal(null) }) done() }) it('should limit to words that contain all the required characters with custom word list', function (done) { var opts = { requiredLetters: 'aein', requiredLettersOnly: true } var mat = wordomat(opts, ['abcd', 'neia', 'nin', 'aeeinna']) should(mat.data.length).equal(2) mat.data.forEach(function (word) { should(word.match(/a/)).not.equal(null) should(word.match(/e/)).not.equal(null) should(word.match(/i/)).not.equal(null) should(word.match(/n/)).not.equal(null) }) done() }) it('should process short phrases', function (done) { var opts = { requiredLetters: 'a' } var mat = wordomat(opts, ['Mission Gothic', 'Abraham Lincoln', 'Mission Script', 'Majesti Banner', 'Dude Hank Pro', 'Klinic Slab']) should(mat.data.length).equal(4) should(mat.data.indexOf('Mission Gothic')).equal(-1) should(mat.data.indexOf('Mission Script')).equal(-1) should(mat.data.indexOf('Abraham Lincoln')).be.above(-1) should(mat.data.indexOf('Dude Hank Pro')).be.above(-1) should(mat.data.indexOf('Majesti Banner')).be.above(-1) should(mat.data.indexOf('Klinic Slab')).be.above(-1) done() }) it('should process short phrases with more complicated required letters', function (done) { var opts = { requiredLetters: 'aMnA' } var mat = wordomat(opts, ['Mission Gothic', '<NAME>', 'Mission Script', 'Dude Hank Pro', 'Klinic Slab', 'Majesti Ban ner', '<NAME>', 'D’u*d e W i l l i e']) should(mat.data.length).equal(6) should(mat.data.indexOf('Mission Gothic')).be.above(-1) should(mat.data.indexOf('Mission Script')).be.above(-1) should(mat.data.indexOf('Abraham Lincoln')).be.above(-1) should(mat.data.indexOf('Dude Hank Pro')).be.above(-1) should(mat.data.indexOf('Majesti Ban ner')).be.above(-1) should(mat.data.indexOf('Klinic Slab')).be.above(-1) should(mat.data.indexOf('Dude June')).equal(-1) should(mat.data.indexOf('D’u*d e W i l l i e')).equal(-1) should(mat.data.indexOf('<NAME>')).equal(-1) done() }) }) <file_sep>module.exports = { catalan: require('./resources/catalan'), czech: require('./resources/czech'), danish: require('./resources/danish'), dutch: require('./resources/dutch'), ukacd: require('./resources/ukacd'), finnish: require('./resources/finnish'), french: require('./resources/french'), german: require('./resources/german'), hungarian: require('./resources/hungarian'), icelandic: require('./resources/icelandic'), italian: require('./resources/italian'), latin: require('./resources/latin'), norwegian: require('./resources/norwegian'), polish: require('./resources/polish'), slovak: require('./resources/slovak'), spanish: require('./resources/spanish'), vietnamese: require('./resources/vietnamese') } <file_sep>// ISC via https://github.com/npm/npm-expansions/blob/5322c9dd9716927622fffa89e8756931faa11d9c/bin/build.js var fs = require('fs') var path = require('path') var inpath = path.resolve('./node_modules/word-o-mat/word-o-mat.roboFontExt/resources') fs.readdir(inpath, function (err, files) { if (err) { console.error(err) } else { files.forEach(function (file) { // console.log(file) convert(file) }) } }) var convert = function (infile) { var filename = infile.split(path.extname(infile))[0] + '.json' var outfile = path.resolve('./lib/resources/', filename) var list = fs .readFileSync(path.resolve(inpath, infile), 'utf8') .split('*****')[1] .split('\n') .map(function (e) { return e.trim() }) .filter(function (e) { return (e.length > 0) }) // .filter(function (e) { return e.charAt(0).toLowerCase() === 'n' }) .sort(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()) }) fs.writeFileSync(outfile, JSON.stringify(list, null, 2)) } <file_sep>/* global describe, it */ var wordomat = require('../') var should = require('should') var opts = { wordCount: 10, sort: 'alphabetical' } describe('language', function () { it('none specified', function (done) { opts.lang = false var mat = wordomat(opts) should(mat.data.length).equal(10) should(mat.data[4]).not.equal('Arabië') done() }) it('Dutch', function (done) { opts.lang = 'dutch' var mat = wordomat(opts) should(mat.data.length).equal(10) should(mat.data[4]).equal('Arabië') done() }) it('Catalan', function (done) { opts.lang = 'catalan' var mat = wordomat(opts) should(mat.data.length).equal(10) should(mat.data[4]).equal('abadane') done() }) it('Latin', function (done) { opts.lang = 'latin' var mat = wordomat(opts) should(mat.data.length).equal(10) should(mat.data[0]).equal('Abdēra') done() }) it('Polish', function (done) { opts.lang = 'polish' var mat = wordomat(opts) should(mat.data.length).equal(10) should(mat.data[0]).equal('absolutnie') done() }) it('Vietnamese', function (done) { opts.lang = 'vietnamese' var mat = wordomat(opts) should(mat.data.length).equal(10) should(mat.data[0]).equal('Bình') done() }) }) <file_sep># TODO ![word-o-mat screenshot](/screenshot.png) New in major version 2.2: - [ ] **GREP pattern matching**: As an alternative to specifying lists of required letters (which is still there and unchanged), word-o-mat now also supports pattern matching with regular expressions for more fine-grained control. (Please make sure your regex does not contradict parameters set in the “Basic settings” panel, as the script does not [yet] cleverly check for such things.) - [x] **Language support**: Additional option to get words in **any** available language (mind that this will be slower). Also new wordlists for Latin, Polish, Icelandic, Vietnamese syllables (the latter is a rather short list, but I thought it may still be useful to include). Implemented correct capitalization of German ß to SS. - [x] word-o-mat is UTF-8 compliant, so you can also use it for languages other than English (I’ve only tested it for Latin-based languages for now). This uses the Unicode info of the glyphs, so make sure you have your codepoints assigned properly. - [x] Limit to # of words - [x] Between # and # characters - [x] Select language(s) - [x] Define key characters: ______ (case sensitive) - [x] Allow characters other than key characters: yes/no - [x] Change case: keep, all uppercase, all lowercase, capitalize - [ ] Filter proper nouns: yes/no (filter by case?) - [ ] Filter words, phrases, or both - [x] Sort results alphabetically - [x] By word length (# of letters) - [ ] or by # of key characters contained - [ ] GREP pattern matching - [x] Word-o-Mat word lists - [x] Custom word list e.g. Input: gaoesf Output: flagpoles flages poles foes lop … <file_sep>/* global describe, it */ var wordomat = require('../') var should = require('should') describe('sort', function () { it('random', function (done) { var opts = { requiredLetters: 'aein', sort: 'random' } var mat = wordomat(opts) should(mat.data.length).be.above(1) done() }) it('alphabetical', function (done) { var opts = { sort: 'alphabetical' } var mat = wordomat(opts, ['Tommaso', 'Nelma', 'Abraham', 'Airplane', 'Vevey']) should(mat.data.length).equal(5) should(mat.data[0]).equal('Abraham') should(mat.data[1]).equal('Airplane') should(mat.data[2]).equal('Nelma') should(mat.data[3]).equal('Tommaso') should(mat.data[4]).equal('Vevey') done() }) it('phrases', function (done) { var opts = { sort: 'alphabetical', maxLength: 100 } var lyrics = [ 'I don’t wanna bore you with how I feel', 'But when the walls came down, the shit got real', 'I never thought I would ever be here', 'Looking out on my life as if there was no there there' ] var mat = wordomat(opts, lyrics) should(mat.data[0]).equal('But when the walls came down, the shit got real') should(mat.data[1]).equal('I don’t wanna bore you with how I feel') should(mat.data[2]).equal('I never thought I would ever be here') should(mat.data[3]).equal('Looking out on my life as if there was no there there') done() }) it('length', function (done) { var opts = { sort: 'length', minLength: 1, maxLength: 100, wordCount: 10 } var mat = wordomat(opts, [ 'Supercalifragilisticexpialidocious', 'Pneumonoultramicroscopicsilicovolcanoconiosis', 'Honorificabilitudinitatibus', 'a', 'Donaudampfschiffahrtselektrizitätenhauptbetriebswerkbauunterbeamtengesellschaft', 'Δήμητρα μέΆπω Κόραν τε ΚΆυμένοιο άΆοΧον' ]) for (var i = 0; i < (mat.data.length - 1); i++) { should(mat.data[i + 1].length).aboveOrEqual(mat.data[i].length) } should(mat.data[0]).equal('a') should(mat.data.length).equal(6) done() }) }) <file_sep># word-o-mat Looking for words that contain _q_ but not _u_? Or French words that use an _a_, a _g_? Generate a list of words, based on your specific requirements, for type specimens, type sketching, spacing, and more. This is a library for Node.js based on [Nina Stössinger’s amazing RoboFont extension](https://github.com/ninastoessinger/word-o-mat). ## Getting started To install word-o-mat, with a recent version of [Node.js installed](https://nodejs.org), run the following command in your terminal: ```sh npm install --save word-o-mat ``` The module is now a dependency of your project. Next, `require` it and pass in your desired options: ```js var wordomat = require('word-o-mat') var mat = wordomat({ wordCount: 5 }) console.log(mat.data) // Returns something like… // ['económicamente', 'számára', 'ascents', 'mataran', 'spalla'] ``` From here, you can start to pass in your own options to get the exact kind of words or phrases you are looking for: ```js var wordomat = require('word-o-mat') var mat = wordomat({ wordCount: 5, // Total number of words minLength: 8, // Shortest permitted word length maxLength: 30, // Longest permitted word length requiredLetters: 'înc', // Words with “î,” “n,” and “c” requiredLettersOnly: true, // …and must have all of them lang: 'french', // Use the French word-o-mat list case: 'upper', // Convert them to uppercase sort: 'alphabetical' // And sort them alphabetically }) console.log(mat.data) // Returns something like… // ['CONNAÎTRA', 'CONNAÎTRE', 'CONNAÎTREZ', 'CONTREMAÎTRE', 'DÉCHAÎNÉ'] ``` <!-- ## API --> ## Word Lists This module includes the up-to-date word lists built into the original word-o-mat plugin, manually corrected by the following people where noted: <!-- - English --> - Catalan ([<NAME>](https://github.com/casasin)) - Czech - Danish - Dutch (Nina Stössinger) - Finnish - French ([La Police Type Foundry](https://github.com/LaPolice) and David Hodgetts) - German (Nina Stössinger) - Hungarian - Icelandic - Italian ([<NAME>](https://github.com/roberto-arista)) - Latin ([<NAME>](http://www.frerejones.com/)) - Norwegian ([<NAME>](https://monokrom.no/)) - Polish - Slovak - Spanish - Vietnamese syllables Word lists usually contain between 5,000 and 30,000 words each (only the Vietnamese one is much shorter) and are derived from various open/CC licensed sources; please check the individual files in the [original repo](https://github.com/ninastoessinger/word-o-mat) for details. If you’d like to update the word lists, please open a Pull Request against Nina’s repo, rather than this one. The included JSON files are build from those source files automatically. ## License [The MIT License (MIT)](LICENSE.md) Copyright © 2014–2015 [<NAME>](http://ninastoessinger.com/)<br> Copyright © 2015–2017 [<NAME>](http://kennethormandy.com/)
884f9d1f7d463e04100bf1833acd702945242db0
[ "JavaScript", "Markdown" ]
9
JavaScript
kennethormandy/word-o-mat
bcf0847728a2a5dcfa07a1927b7a4938495d58a5
b39eafd217df74e1db3f14e88db720dbe409f5e0
refs/heads/master
<file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-tab-discovery', templateUrl: 'tab-discovery.page.html', styleUrls: ['tab-discovery.page.scss'] }) export class TabDiscoveryPage {} <file_sep>import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-tab-more', templateUrl: 'tab-more.page.html', styleUrls: ['tab-more.page.scss'] }) export class TabMorePage { constructor(public router: Router) { } goLoginPage() { this.router.navigateByUrl('/login'); } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable({ providedIn: 'root' }) export class RestService { constructor(public http: Http) { } } <file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-tab-chat', templateUrl: 'tab-chat.page.html', styleUrls: ['tab-chat.page.scss'] }) export class TabChatPage {} <file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-tab-notification', templateUrl: 'tab-notification.page.html', styleUrls: ['tab-notification.page.scss'] }) export class TabNotificationPage {} <file_sep># QAapp Ionic project
241c62d80659256f41cc136b9af1cd15d5a962da
[ "Markdown", "TypeScript" ]
6
TypeScript
scofieldwenwen/QAapp
5cc80a5d550057d3254ba7561aa525108e19f5a0
30df472f81f61572ba7e1a2f1d03c65f6d19b891
refs/heads/master
<repo_name>2655398311/weibo_extract_Emotional-analysis<file_sep>/strategy.py # -*- coding:utf-8 -*- from pyhanlp import HanLP import pandas as pd import random from collections import defaultdict import re class TrieNode(object): def __init__(self, value=None): # 值 self.value = value # fail指针 self.fail = None # 尾标志:标志为i表示第i个模式串串尾,默认为0 self.tail = 0 # 子节点,{value:TrieNode} self.children = {} class Trie(object): def __init__(self, words): # print("初始化") # 根节点 self.root = TrieNode() # 模式串个数 self.count = 0 self.words = words for word in words: self.insert(word) self.ac_automation() # print("初始化完毕") def insert(self, sequence): """ 基操,插入一个字符串 :param sequence: 字符串 :return: """ self.count += 1 cur_node = self.root if type(sequence)!=str: sequence=str(sequence) for item in sequence: if item not in cur_node.children: # 插入结点 child = TrieNode(value=item) cur_node.children[item] = child cur_node = child else: cur_node = cur_node.children[item] cur_node.tail = self.count def ac_automation(self): """ 构建失败路径 :return: """ queue = [self.root] # BFS遍历字典树 while len(queue): temp_node = queue[0] # 取出队首元素 queue.remove(temp_node) for value in temp_node.children.values(): # 根的子结点fail指向根自己 if temp_node == self.root: value.fail = self.root else: # 转到fail指针 p = temp_node.fail while p: # 若结点值在该结点的子结点中,则将fail指向该结点的对应子结点 if value.value in p.children: value.fail = p.children[value.value] break # 转到fail指针继续回溯 p = p.fail # 若为None,表示当前结点值在之前都没出现过,则其fail指向根结点 if not p: value.fail = self.root # 将当前结点的所有子结点加到队列中 queue.append(value) def search(self, text): """ 模式匹配 :param self: :param text: 长文本 :return: """ p = self.root # 记录匹配起始位置下标 start_index = 0 # 成功匹配结果集 rst = defaultdict(list) for i in range(len(text)): single_char = text[i] while single_char not in p.children and p is not self.root: p = p.fail # 有一点瑕疵,原因在于匹配子串的时候,若字符串中部分字符由两个匹配词组成,此时后一个词的前缀下标不会更新 # 这是由于KMP算法本身导致的,目前与下文循环寻找所有匹配词存在冲突 # 但是问题不大,因为其标记的位置均为匹配成功的字符 if single_char in p.children and p is self.root: start_index = i # 若找到匹配成功的字符结点,则指向那个结点,否则指向根结点 if single_char in p.children: p = p.children[single_char] else: start_index = i p = self.root temp = p while temp is not self.root: # 尾标志为0不处理,但是tail需要-1从而与敏感词字典下标一致 # 循环原因在于,有些词本身只是另一个词的后缀,也需要辨识出来 if temp.tail: rst[self.words[temp.tail - 1]].append((start_index, i)) temp = temp.fail return rst def direct_search(test_text): # 并行检索 # 策略1:直接量化。优先“汉语情感词极值表.txt”,然后“情感词汇本体.xlsx”; #1.1 mode = [] pro_df1 = pd.read_csv('dict_res/jizhi_first.csv',encoding='utf-8') words1 = list(pro_df1['word']) model_fir = Trie(words1) temp1 = model_fir.search(test_text) for i in list(model_fir.search(test_text).keys()): temp1[i] = [temp1[i][0],float(pro_df1.loc[pro_df1['word']==i,['value']].sum())] mode.append(temp1) #1.2 pro_df2 = pd.read_csv('dict_res/jizhi_second.csv',encoding='utf-8') words2 = list(pro_df2['word']) model_sec = Trie(words2) temp2 = model_sec.search(test_text) for i in list(model_sec.search(test_text).keys()): temp2[i] = [temp2[i][0],float(pro_df2.loc[pro_df2['word']==i,['value']].sum())] mode.append(temp2) return temp1, temp2 def indirect_search(test_text): # 策略2:间接量化。再然后总表“negtive_all.txt”和“positive_all.txt”; # 2.1消极 neg_dict = open('dict_res/negtive_all.txt', encoding='utf-8').read().split('\n') model_th = Trie(neg_dict) temp3 = model_th.search(test_text) for i in list(model_th.search(test_text).keys()): temp3[i] = [temp3[i][0], -2.5] # 2.2积极 pos_dict = open('dict_res/positive_all.txt', encoding='utf-8').read().split('\n') model_fo = Trie(pos_dict) temp4 = model_fo.search(test_text) for i in list(model_fo.search(test_text).keys()): temp4[i] = [temp4[i][0], 2.5] temp_res = work_bn(temp4,temp3) return temp_res def remove(test_text): a = HanLP.segment(test_text) rem = dict() curs = 0 for i in a: if str(i.nature) in ['ns','nz']: rem[str(i.word)] = [(curs,curs+len(str(i.word))-1)] curs += len(str(i.word)) return rem def result_correct(test_text): # 策略3:修正。情绪修饰词的权重,正向表“程度级别.txt”和反向表“否定.txt” modify = dict() weight_dict = {'极其': 1.9, '很': 1.7, '超': 1.5,'较': 0.9, '稍': 0.7, '欠': 0.5, '否定': -0.9} for i in list(weight_dict.keys()): weight = open('dict_res/{}.txt'.format(i), encoding='utf-8').read().split('\n') # print(weight) model_add = Trie(weight).search(test_text) if model_add: for spe in model_add.keys(): modify[spe] = [model_add[spe][0],weight_dict[i]] return modify #位置词归一化 def work_bn(base,accord):#base是短而错,accord是长而对 temp_res = dict(base) if accord and base: for i, j in base.items(): for m in accord.values(): if j[0][0] >= m[0][0] and j[0][1] <= m[0][1]: try: temp_res.pop(i) except: print(temp_res,i) # 积极/消极归一 temp_res.update(accord) return temp_res def bn_march(test_text): direct = direct_search(test_text) indirect = indirect_search(test_text) rem = remove(test_text) # 积/消极词与极性值归一 direct1, direct2 = direct res1 = dict() # 剔乱码 if direct1: direct1 = work_bn(direct1, indirect) direct1 = work_bn(direct1, rem) # 剔地址 for i in direct1.keys(): if i not in rem.keys(): res1[i] = direct1[i] res2 = dict() if direct2: direct2 = work_bn(direct2, indirect) direct2 = work_bn(direct2, rem) for i in direct2.keys(): if i not in rem.keys(): res2[i] = direct2[i] return res1,res2 def weight(test_text,μ): res1, res2 = bn_march(test_text) res_final = dict() # 1,并集部分(已去交) # first词本结果 spec1 = set(res1.keys()) - set(res2.keys()) for i in list(spec1): res_final[i] = res1[i] # second词本结果 spec2 = set(res2.keys()) - set(res1.keys()) for i in list(spec2): res_final[i] = res2[i] # 2,交集部分结果加权平均得结果 spec3 = set(res1.keys()) & set(res2.keys()) for i in list(spec3): res_final[i] = [res1[i],res1[i][1] * μ + res2[i][1]* (1 - μ)] return res_final def combine(test_text,μ=0.9): test_text = test_text[test_text.find(':')+1:] test_text = ','.join(re.compile(r'[\u4e00-\u9fa5]+').findall(test_text)) correct = result_correct(test_text) res = weight(test_text,μ) res_update = res.copy() score = 0 for i1,i2 in correct.items(): sig = False for j1,j2 in res.items(): try: j2[0][0] - i2[0][1] except: j2 = j2[0] if j2[0][0] - i2[0][1]<3: res_update[j1][1] = j2[1] * i2[1] sig = True else: pass if sig: break for i in res_update.values(): score += i[1] if score>5: score=5 elif score<-5: score=-5 elif -1<score<1: score=(random.random()-0.5)*2 return score #不,-0.35529151896253897 if __name__ == "__main__": test_text = "合肥求拼!!江浙沪皖很讨厌!!" a = pd.read_csv('yuqing.csv',encoding='utf-8') a['score'] = a['comment_content'].apply(combine) print(a.head(5)) <file_sep>/dsadsa.py import pandas as pd a = pd.read_csv('blog.csv',encoding='gbk') print(a.head(5))<file_sep>/README.md # weibo_extract_Emotional-analysis weibo_extract_Emotional analysis <file_sep>/dict_handle.py # #词典整理 import pandas as pd # # #,否定词典 # no_dict = open('data/其他词典和分类/否定词典/否定.txt') # text_no = no_dict.readlines() # for i in text_no: # print(i) # # #情感词典及多分类 # multi_dict = open('abc1.txt',encoding='utf-8') # mutli_res = open('multi.txt','w',encoding='utf-8') # text_multi = multi_dict.readlines() # for i in text_multi: # mutli_res.writelines(i.replace('\t',',')) # # multi_dict = pd.read_csv('multi.csv',encoding='utf-8') # # a = list(set(multi_dict['Class'])) # a = ['感动','祝愿', '喜欢', '佩服','道谢', '舒畅','赞成', '激动', '愿意', '高兴','留恋', '心静', '感激' # '喜爱', '无愧', '得意', '满意', '振奋', '称赞', '镇定', '倾心'] # b= ['委屈', '烦闷', '忧愁', '责骂', '心虚', '慌张', '仇恨', '厌烦', '惭愧', # '鄙视', '责怪', '失望', '哭泣', '不满', '悲伤', '怨恨', '漠视' # '害怕', '着急', '痛苦', '不安', '惆怅', '愤怒'] # f = open('dict_res/贬义1.txt','w',encoding='utf-8') # baoyi = [] # for i in b: # baoyi += (list(multi_dict[multi_dict['Class']==i]['Instance'])) # baoyi = list(set(baoyi)) # for i in baoyi: # f.writelines(i+'\n') # # 情感词汇本体 # base_dict = import pandas as pd # a = pd.read_excel('dict_res/褒贬词及其近义词.xls') # a[a['褒贬色彩']=='贬义'].to_csv('dict_res/贬义词.csv',index=False) # f = open('dict_res/贬义.txt','w',encoding='utf-8') # temp = open('dict_res/贬义词.txt',encoding='gbk').read().replace(',','\n').replace('/','\n').replace('\n\n','\n') # f.write(temp) # str_all = '' # for i in range(8): # f = open('data/中间处理/n' + str(i + 1) + '.txt', encoding='utf-8') # str_all += f.read()+'\n' # # str_final = str_all.replace('\n\n','\n').replace('\n\n','\n').replace('\n\n','\n')\ # .replace('\n\n','\n').replace('\n\n','\n').replace('\n\n','\n')\ # .replace('\n\n','\n').replace('\n\n','\n').replace('\n\n','\n') # # str_final = list(set(str_final.split('\n'))) # print(len(str_final)) # str_final = '\n'.join(str_final) # print(str_final) # f1 = open('negtive_all.txt','w',encoding='utf-8') # f1.write(str_final) # 得正情感词16129,负情感词12397 # f1 = open('jizhi.txt','w',encoding='utf-8') # f = open('dict_res/汉语情感词极值表.txt',encoding='utf-8') # text = f.read().replace('\t',',') # f1.write(text) # import pandas as pd # a = pd.read_csv('dict_res/jizhi.csv',encoding='utf-8') # a['value'] = 5 - 10*(max(a['极值'])-a['极值'])/(max(a['极值'])-min(a['极值'])) # a1 = a[['词语','value']] # print(min(a1['value'])) # print(max(a1['value'])) # a1.to_csv('dict_res/jizhi_first.csv',encoding = 'utf-8',index = False) # # b = pd.read_excel('dict_res/情感词汇本体.xlsx',encoding = 'utf-8') # b1 = b[b['极性']==2] # b2 = b[b['极性']!=2] # b1['极性'] = -1 # c = b1.append(b2) # c['极值'] = c['强度']*c['极性']*5/9 # d = c[['词语','极值']] # print(min(d['极值'])) # print(max(d['极值'])) # print(c[c['极值']==9]) # print(b[b['极性']==3]) # d.to_csv('dict_res/jizhi_second.csv',encoding = 'utf-8',index = False) # a = pd.read_csv('dict_res/jizhi_second.csv',encoding = 'utf-8') # c = a.loc[a['word']=='不错',['value']].sum() # if c.any(): # print(c) # a1 = list(a['word']) # b = open('dict_res/程度级别.txt ',encoding = 'utf-8') # b1 = b.read().split('\n') # print(set(a1)&set(b1)) # # print({1,2}=={2,2}) # # from pyhanlp import HanLP # # a = HanLP.segment('我在 豪泰 旗舰店') # print(a) print([][0])<file_sep>/strategy_v3.py from pyhanlp import HanLP import pandas as pd import re import random import datetime import warnings import time import redis import jieba.analyse as analyse warnings.filterwarnings('ignore') from clickhouse_driver import Client import json import os import urllib.request # 1、构建url # 2、构建一下请求头部 def bobao(content): #情感分析机器人 url = 'https://oapi.dingtalk.com/robot/send?access_token=09ac4be869c6be7f1c640d9b450a9b288d6b37a779cff53fe7a6eb613e0536de' header = {"Content-Type": "application/json", "Charset": "UTF-8"} # 3、构建请求数据 data = { "msgtype": "text", "text": {"content": content}, "at": { "atMobiles": [ False ], "isAtAll": False } # @全体成员(在此可设置@特定某人) } # 4、对请求的数据进行json封装 sendData = json.dumps(data) # 将字典类型数据转化为json格式 sendData = sendData.encode("utf-8") # python3的Request要求data为byte类型 # 5、发送请求 request = urllib.request.Request(url=url, data=sendData, headers=header) # 6、将请求发回的数据构建成为文件格式 opener = urllib.request.urlopen(request) # 7、打印返回的结果 print(opener.read()) '''clickhouse数据库连接''' client2 = Client(host='10.228.83.251',port = '19000', user='default', database='putao', password='<PASSWORD>') '''redis链接''' redis_pool = redis.ConnectionPool(host='10.228.83.85', port=6379, decode_responses=True) redis_conn = redis.Redis(connection_pool=redis_pool) def dict_join(comment_list): res = 0 miu = 0 temp1 = 0 #1,程度词典 miu_all = dict() weight_dict = {'extremely': 1.9, 'very': 1.7, 'exceed': 1.5, 'relative': 0.9, 'slight': 0.7, 'owe': 0.5, 'not': -0.9} for i in list(weight_dict.keys()): weight = open('dict_res/{}.txt'.format(i), encoding='utf-8').read().split('\n') for j in comment_list: if j in weight: miu_all[j] = weight_dict[i] if miu_all: miu = sum(miu_all.values())/len(miu_all.values()) #2,极值词典一、二 pro_df1 = pd.read_csv('dict_res/jizhi_first.csv',encoding='utf-8') pro_df2 = pd.read_csv('dict_res/jizhi_second.csv',encoding='utf-8') baselist1 = [] for i in comment_list: base1 = pro_df1.loc[pro_df1['word'] == i,['value']].sum() baselist1.append(float(base1)) base2 = pro_df2.loc[pro_df2['word'] == i, ['value']].sum() baselist1.append(float(base2)) #归一化 if baselist1: temp1 = abs(max(baselist1))+abs(min(baselist1)) #定正负 if sum(baselist1)>0: base_f1 = temp1 else: base_f1= -temp1 #3,积/消极词典 neg_count = 0 pos_count = 0 neg_dict = open('dict_res/negtive_all.txt', encoding='utf-8').read().split('\n') pos_dict = open('dict_res/positive_all.txt', encoding='utf-8').read().split('\n') for i in comment_list: if i in neg_dict: neg_count += 1 else: pos_count += 1 if abs(miu*base_f1)>1: if pos_count>=neg_count: res = abs(miu*base_f1) else: res = -abs(miu * base_f1) else: if (not neg_count) & (not pos_count): res = 2*random.random() else: res = 4 *random.random() * (pos_count - neg_count) / (neg_count + pos_count) return res def clean(inp_text): text =str(inp_text) #1,加载停用词 stop_dict = open('dict_res/HIT_stop_words.txt',encoding='utf-8').read().split('\n') #2,取中文 text = text[text.find(':')+1:] text = ','.join(re.compile(r'[\u4e00-\u9fa5]+').findall(text)) #3,分词去停用词 text_update = [] a = HanLP.segment(text) for i in a: if (str(i.word) not in stop_dict) and (str(i.nature) not in ['ns']): text_update.append(i.word) return text_update def get_score(text): comment_list = clean(text) res = dict_join(comment_list) if abs(res)>=4.9: res = 4*res/(abs(int(res))+1)#平滑 elif abs(res)<=1: res = 2*res return round(res,2) # topic,version1 # select platform_cid,blog_id,blog_content from putao.f_weibo_blog where DATEDIFF(hh,NOW(),publish_time)<7 limit 1000 def siglerow(text, keyword_num=1): text = text[text.find(':') + 1:] text = ','.join(re.compile(r'[\u4e00-\u9fa5]+').findall(text)) kw1 = analyse.textrank(text,keyword_num,allowPOS=('ns','n','vn','b')) kw2 = HanLP.extractKeyword(text,1) k_words = HanLP.segment(text) kw3 = '' for i in k_words: if str(i.nature)[0] == 'n': kw3 = str(i.word) break kw4 = analyse.textrank(text,keyword_num) if kw1: return str(kw1[0]) # jieba关键词,仅限于地点,名词,动名词 elif kw2: return str(kw2[0]) # hanlp关键词 elif kw3: return kw3 # 仅限于地点,名词,动名词 elif kw4: return str(kw4[0]) else: return '' if __name__ =="__main__": data_set_name = 'jiankong_fenxi' sc_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') start_zhixing = '程序开始执行 执行时间%s!' % (sc_time) bobao(content=start_zhixing) click_house = client2.execute("select * from putao.f_weibo_blog_comment where comment_time>='2020-02-17 00:00:00' limit 10", types_check=True) col = client2.execute('DESCRIBE TABLE putao.f_weibo_blog_comment') col = pd.DataFrame(col) data = pd.DataFrame(click_house,columns=col[0].tolist()) data_list = [data.ix[i].to_dict() for i in data.index.values] data_li = [] data_limit = 2 count = 0 for i in data_list: msg_name = str(i) producte = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if redis_conn.sismember(data_set_name,msg_name): continue else: redis_conn.sadd(data_set_name,msg_name) count+=1 score = get_score(i['comment_content']) update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') extract_words = siglerow(i['comment_content']) dict_aa = [{'comment_id':i['comment_id'],'keyword':extract_words,'score':score,'update_time':update_time}] data_frame = pd.DataFrame(dict_aa) data_li.append(data_frame) #批量入库 if len(data_li) >= data_limit: for data_frame in data_li: data_frame = data_frame.values.tolist() print(data_frame) client2.execute('INSERT INTO f_weibo_blog_comment_an VALUES', data_frame, types_check=True) data_li = [] if len(data_li) >= 0: for data_frame in data_li: data_frame = data_frame.values.tolist() print(data_frame) client2.execute('INSERT INTO f_weibo_blog_comment_an VALUES', data_frame, types_check=True) data_li = [] bb = '生产了%s条数据! 生产时间%s' % (count, producte) bobao(content=bb) end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') if len(data_li)==0: b = '程序执行完成! 结束时间%s'%(end_time) bobao(content=b)
cdb8103123317f237d668fd5c4c703b31479f6d9
[ "Markdown", "Python" ]
5
Python
2655398311/weibo_extract_Emotional-analysis
bd56ecd1f53fee408003508fe1759df82c0c869a
78c815bbabd0013f294a3e7db48d584faa752932
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; public class Redo : MonoBehaviour { public AudioClip button; private UnityEngine.iOS.ADBannerView banner = null; private void OnMouseDown(){ GetComponent<AudioSource>().PlayOneShot(button,5f); AutoFade.LoadLevel("Game" ,0.5f,0.5f,Color.white); /*banner = new UnityEngine.iOS.ADBannerView(UnityEngine.iOS.ADBannerView.Type.MediumRect, UnityEngine.iOS.ADBannerView.Layout.Top); UnityEngine.iOS.ADBannerView.onBannerWasClicked += OnBannerClicked; UnityEngine.iOS.ADBannerView.onBannerWasLoaded += OnBannerLoaded;*/ } /*void OnBannerClicked() { Debug.Log("Clicked!\n"); } void OnBannerLoaded() { Debug.Log("Loaded!\n"); banner.visible = true; }*/ } <file_sep>using UnityEngine; using System.Collections; public class BGLooper : MonoBehaviour { int numBGPanels = 4; float max = 6f; float min = 3f; void Start(){ GameObject[] array = GameObject.FindGameObjectsWithTag ("Pipe"); foreach(GameObject pipe in array){ Vector3 pos = pipe.transform.position; pos.y = Random.Range (min,max); pipe.transform.position = pos; } } void OnTriggerEnter2D(Collider2D collider){ Debug.Log ("Triggered " + collider.name); if (collider.name == "LongCloud") { float widthOfBGObject = ((BoxCollider2D)collider).size.x; Vector3 pos = collider.transform.position; pos.x += widthOfBGObject * numBGPanels; collider.transform.position = pos; } if(collider.name == "bgSky1"){ float widthOfBGObject = ((BoxCollider2D)collider).size.x; Vector3 pos = collider.transform.position; pos.x += widthOfBGObject * 14; collider.transform.position = pos; } if(collider.name == "1"){ float widthOfBGObject = ((BoxCollider2D)collider).size.x; Vector3 pos = collider.transform.position; pos.x += widthOfBGObject * 4; if (collider.tag == "Pipe") { pos.y = Random.Range (min, max); } collider.transform.position = pos; } } } <file_sep>using UnityEngine; using System.Collections; public class TimeElapsed : MonoBehaviour { static float timer= 0f; // set duration time in seconds in the Inspector static float highScore = 0f; void Start(){ GetComponent<GUIText>().fontSize = Screen.width/6; highScore = PlayerPrefs.GetFloat ("highScore", 0); timer = 0f; } void Update(){ if (!GameObject.Find("PlayerBird").GetComponent<BirdMovement>().dead) { timer += Time.deltaTime; } if(timer>highScore){ highScore = timer; } GetComponent<GUIText>().text = timer.ToString("F0"); } void OnDestroy(){ PlayerPrefs.SetFloat ("highScore", highScore); PlayerPrefs.SetFloat ("score", timer); } } <file_sep>using UnityEngine; using System.Collections; using iAds = UnityEngine.iOS.ADBannerView; public class iAds : MonoBehaviour { private UnityEngine.iOS.ADBannerView banner = null; void Start() { banner = new UnityEngine.iOS.ADBannerView(UnityEngine.iOS.ADBannerView.Type.Banner, UnityEngine.iOS.ADBannerView.Layout.BottomCenter); UnityEngine.iOS.ADBannerView.onBannerWasClicked += OnBannerClicked; UnityEngine.iOS.ADBannerView.onBannerWasLoaded += OnBannerLoaded; } void OnBannerClicked() { Debug.Log("Clicked!\n"); } void OnBannerLoaded() { Debug.Log("Loaded!\n"); banner.visible = true; } }<file_sep>using UnityEngine; using System.Collections; public class TipSelector : MonoBehaviour { // Use this for initialization public GUIText referencetotext; void Start () { GetComponent<GUIText>().fontSize = Screen.width/30; int which = Random.Range (1,7); if(which ==1) referencetotext.text = "Tip: Always be flicking"; if (which == 2) referencetotext.text = "Tip: Fast flick = fast movement"; if (which == 3) referencetotext.text = "Tip: To move a little = flick slow over small distance"; if (which == 4) referencetotext.text = "Tip: Flick with index finger"; if (which == 5) referencetotext.text = "Tip: Movement is sensitive to flick speed"; if (which == 6) referencetotext.text = "Tip: Only flick up and down, not sideways"; } }<file_sep>using UnityEngine; using System.Collections; public class StartMenuCloudMovement : MonoBehaviour { // Update is called once per frame void FixedUpdate () { transform.position = transform.position + Vector3.left * 0.1f; } } <file_sep>using UnityEngine; using System.Collections; public class RateiOS : MonoBehaviour { public AudioClip button; private void OnMouseDown(){ GetComponent<AudioSource>().PlayOneShot (button, 5f); Application.OpenURL("http://appstore.com/benjaminyue"); } } <file_sep>using UnityEngine; using System.Collections; using ADInterstitialAd = UnityEngine.iOS.ADInterstitialAd; public class interstatial : MonoBehaviour { private ADInterstitialAd fullscreenAd = null; void Start() { fullscreenAd = new ADInterstitialAd(); ADInterstitialAd.onInterstitialWasLoaded += OnFullscreenLoaded; } void OnFullscreenLoaded() { fullscreenAd.Show(); } }<file_sep>using UnityEngine; public class BirdMovement : MonoBehaviour { Vector3 velocity = Vector3.zero; public float flapSpeed = 100f; public float forwardSpeed = 1f; public bool didFlap = false; public Animator animator; public bool dead = false; float deathCooldown; public bool godMode = false; // Values to set: Touch public float comfortZone = 70.0f; public float minSwipeDist = 14.0f; public float maxSwipeTime = 0.5f; private float startTime; private Vector2 startPos; private bool couldBeSwipe; private float time = 0.0f; public SwipeDirection lastSwipe = BirdMovement.SwipeDirection.None; public float lastSwipeTime; public enum SwipeDirection { None, Up, Down } float velocityOfSwipe=0; //Touch control initialization void Start () { animator = transform.GetComponentInChildren<Animator>(); if(animator == null) { Debug.LogError("Didn't find animator!"); } } public AudioClip swoosh; // Do Graphic & Input updates here void Update() { if(dead) { deathCooldown -= Time.deltaTime; if(deathCooldown <= 0) { AutoFade.LoadLevel("EndMenu" ,0.5f,0.5f,Color.white); } } else { /*if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0) ) { didFlap = true; }*/ if (Input.touchCount > 0) { Touch touch = Input.touches[0]; switch (touch.phase) { case TouchPhase.Began: lastSwipe = BirdMovement.SwipeDirection.None; lastSwipeTime = 0; couldBeSwipe = true; startPos = touch.position; startTime = Time.time; break; case TouchPhase.Moved: if (Mathf.Abs(touch.position.x - startPos.x) > comfortZone) { Debug.Log("Not a swipe. Swipe strayed " + (int)Mathf.Abs(touch.position.x - startPos.x) + "px which is " + (int)(Mathf.Abs(touch.position.x - startPos.x) - comfortZone) + "px outside the comfort zone."); couldBeSwipe = false; } break; case TouchPhase.Ended: if (couldBeSwipe) { float swipeTime = Time.time - startTime; float swipeDist = (new Vector3(0, touch.position.y, 0) - new Vector3(0, startPos.y, 0)).magnitude; if ((swipeTime < maxSwipeTime) && (swipeDist > minSwipeDist)) { // Swipe GetComponent<AudioSource>().PlayOneShot(swoosh,0.9f); float swipeValue = Mathf.Sign(touch.position.y - startPos.y); // If positive swipe direction = upward swipe. // If negative swipe direction = downward swipe. if (swipeValue > 0){ lastSwipe = BirdMovement.SwipeDirection.Up; didFlap = true; velocityOfSwipe = swipeDist/swipeTime/50; } else if (swipeValue < 0){ lastSwipe = BirdMovement.SwipeDirection.Down; didFlap = true; velocityOfSwipe = -swipeDist/swipeTime/50; } lastSwipeTime = Time.time; } } break; } } } } // physics engine updates here void FixedUpdate () { if(dead) return; GetComponent<Rigidbody2D>().AddForce( Vector2.right * forwardSpeed ); animator.SetTrigger("DoFlap"); if(didFlap) { /*rigidbody2D.velocity = Vector2.right; rigidbody2D.AddForce( Vector2.up * flapSpeed ); animator.SetTrigger("DoFlap"); didFlap = false;*/ if(velocityOfSwipe != 0){ GetComponent<Rigidbody2D>().AddForce( Vector2.up * velocityOfSwipe ); didFlap = false; } } if(GetComponent<Rigidbody2D>().velocity.y > 0) { float angle = Mathf.Lerp (0, 55, (GetComponent<Rigidbody2D>().velocity.y / 3f) ); transform.rotation = Quaternion.Euler(0, 0, angle); } else { float angle = Mathf.Lerp (0, -90, (-GetComponent<Rigidbody2D>().velocity.y / 3f) ); transform.rotation = Quaternion.Euler(0, 0, angle); } } public AudioClip impact1; public AudioClip impact2; public AudioClip impact3; public AudioClip impact4; public AudioClip impact5; void OnCollisionEnter2D(Collision2D collision) { if(godMode) return; GameObject soundObject = GameObject.Find("Music"); AudioSource audioSource = soundObject.GetComponent<AudioSource>(); audioSource.Pause (); int which = Random.Range (1, 6); if(which ==1) GetComponent<AudioSource>().PlayOneShot(impact1,0.4f); if(which ==2) GetComponent<AudioSource>().PlayOneShot(impact2); if(which ==3) GetComponent<AudioSource>().PlayOneShot(impact3); if(which ==4) GetComponent<AudioSource>().PlayOneShot(impact4); if(which ==5) GetComponent<AudioSource>().PlayOneShot(impact5); animator.SetTrigger("Death"); dead = true; deathCooldown = 0.5f; } } <file_sep>using UnityEngine; using System.Runtime.InteropServices; public class ShareiOSInstagramFunction { static string imagePath = Application.temporaryCachePath + "/temp.png"; static bool HasHandshook = false; [DllImport("__Internal")] static extern void _handshake(); public static void HandShake() { _handshake(); HasHandshook = true; } [DllImport ("__Internal")] static extern void _postToInstagram (string message, string imagePath); public static void PostToInstagram(string message, byte[] imageByteArr) { if(!HasHandshook) HandShake(); System.IO.File.WriteAllBytes(imagePath, imageByteArr); _postToInstagram(message, imagePath); } }<file_sep>using UnityEngine; using System.Collections; public class Score : MonoBehaviour { // Use this for initialization void Start () { GetComponent<GUIText>().fontSize = Screen.width/10; GetComponent<GUIText>().text = (PlayerPrefs.GetFloat ("score")).ToString("F0"); } } <file_sep>using UnityEngine; using System.Collections; public class ShareiOSInstagram : MonoBehaviour { Texture2D _texture; RenderTexture _renderTexture; public AudioClip button; private void OnMouseDown(){ GetComponent<AudioSource>().PlayOneShot(button,5f); StartCoroutine(PostToInstagram()); } byte[] GrabScreenshot() { if(_texture != null) Destroy(_texture); // Initialize and render _renderTexture = new RenderTexture(Screen.width, Screen.height, 24); Camera.main.targetTexture = _renderTexture; Camera.main.Render(); RenderTexture.active = _renderTexture; // Read pixels _texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); _texture.ReadPixels(new Rect(0,0,Screen.width,Screen.height), 0, 0); // Clean up Camera.main.targetTexture = null; RenderTexture.active = null; DestroyImmediate(_renderTexture); return _texture.EncodeToPNG(); } IEnumerator PostToInstagram() { yield return new WaitForEndOfFrame(); int score = (int)PlayerPrefs.GetFloat ("score"); ShareiOSInstagramFunction.PostToInstagram("WHOA...Just Got " + score + " in Bobo's Challenge #Bobos http://itunes.com/apps/BenjaminYue/BobosChallenge", GrabScreenshot()); } }<file_sep>using UnityEngine; using System.Collections; public class ShareiOSTwitter : MonoBehaviour { public AudioClip button; private void OnMouseDown(){ GetComponent<AudioSource>().PlayOneShot (button, 5f); int score = (int)PlayerPrefs.GetFloat ("score"); ShareToTwitter ("WHOA...Just Got " + score + " in Bobo's Challenge #Bobos http://itunes.com/apps/BenjaminYue/BobosChallenge"); } private const string TWITTER_ADDRESS = "http://twitter.com/intent/tweet"; private const string TWEET_LANGUAGE = "en"; void ShareToTwitter (string textToDisplay) { // Application.OpenURL("twitter:///user?screen_name=username"); Application.OpenURL("twitter://post?message=WHAO!%20...%20finally%20got%20a%20high%20score%20in%20Bobo's%20Challenge%20%23Bobos%20bit%2ely%2f1I5jTZL"); } } <file_sep>using UnityEngine; using System.Collections; public class RegularUpdate : MonoBehaviour { // Update is called once per frame public AudioClip click; void OnMouseDown () { if (Input.GetMouseButtonDown(0)) { GetComponent<AudioSource>().PlayOneShot(click,7f); AutoFade.LoadLevel("Game" ,0.7f,0.7f,Color.black); } } } <file_sep>using UnityEngine; using System.Collections; public class ProductionTimer : MonoBehaviour { float timeLeft = 1f; // Update is called once per frame void Update () { timeLeft -= Time.deltaTime; if(timeLeft<0){ AutoFade.LoadLevel("start menu" ,1,1,Color.black); } } }
4b6f010edbee8d0509aa595eccee7224d2302c6f
[ "C#" ]
15
C#
benjaminyue/BoboChallenge
6020d1e523c055f2839c76fdd0ecb4e35dc9fdf4
1ddef562a1765084852b4f02655ba83ffc8c6a0e
refs/heads/master
<repo_name>amyhenning/todo<file_sep>/spec/factories.rb FactoryBot.define do factory :task do title "Do the dishes" done false end end<file_sep>/README.md # ToDo ToDo is a single-page to-do list application that uses jQuery to allow for dynamic creation, status updates, deletion, and highlighting of tasks. ## Features * Double-click any task to highlight or un-highlight it * Create, update, and delete tasks without page refreshes ## Screenshots ![unhighlighted](https://github.com/amyhenning/todo/blob/master/app/assets/images/unhighlighted.png?raw=true) List both complete and incomplete tasks; delete any task dynamically by clicking on the red 'x' that appears when hovering over a task's row ![highlighted](https://github.com/amyhenning/todo/blob/master/app/assets/images/highlighted.png?raw=true) Toggle highlighting tasks by double-clicking
90f913cebbe31cf0fe1b5c224402082cfecb85a8
[ "Markdown", "Ruby" ]
2
Ruby
amyhenning/todo
495cc64d10384df5b09a5b5be930ab5d59d6534c
3ab3965dda161bd7ae3ab5c3905640406325c56b
refs/heads/master
<file_sep>import datetime from django.db import models from django.template import Context, Template from django.utils.translation import ugettext_lazy as _ from django_extensions.db.fields import AutoSlugField from django_extensions.db.models import TimeStampedModel ROLE_CHOICES = ( (0, _('Project Leader')), (1, _('Scout Leader')), (2, _('Scout')), ) class Participant(TimeStampedModel): name = models.CharField(max_length=50) email = models.EmailField(blank=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES) slug = AutoSlugField(populate_from='name') work = models.ManyToManyField('eagle_project.Work', blank=True, null=True) # donations def get_total_hours(self): pass def __unicode__(self): """ Make the model human readable. """ return '%s, %s' % (self.name, self.get_role_display()) class Meta: ordering = ('created',) get_latest_by = 'created' class Work(TimeStampedModel): title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title') hours = models.FloatField() description = models.TextField() date = models.DateField() def __unicode__(self): """ Make the model human readable. """ t = Template("{{ title }}, {{ hours }} hour{{ hours|pluralize }}") c = Context({'title': self.title, 'hours': self.hours}) return t.render(c) class Meta: ordering = ('date',) get_latest_by = 'date' verbose_name_plural = "Work" # class Donation(TimeStampedModel): # title = models.CharField(max_length=100) # slug = AutoSlugField(populate_from='title') # amount = models.FloatField() # description = models.TextField() # date = models.DateField() # # class Meta: # [-]<file_sep>from django.conf.urls.defaults import * template_subdirectory = 'common/' # template subdirectory urlpatterns = patterns('django.views.generic.simple', ('^$', 'direct_to_template', {'template': '%shome.html' % template_subdirectory}, 'home'), ('^about/$', 'direct_to_template', {'template': '%sabout.html' % template_subdirectory}, 'about'), ('^samples/$', 'direct_to_template', {'template': '%ssamples.html' % template_subdirectory}, 'samples'), ('^qanda/$', 'direct_to_template', {'template': '%sqanda.html' % template_subdirectory}, 'qanda'), ) <file_sep>from django.conf import settings from django.core.mail import send_mail from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from contact.models import Message class MessageForm(ModelForm): def __init__(self, data=None, files=None, request=None, *args, **kwargs): if request is None: raise TypeError("Keyword argument 'request' must be supplied") super(MessageForm, self).__init__(data=data, files=files, *args, **kwargs) self.request = request error_css_class = 'error' required_css_class = 'required' def get_message_dict(self): self.subject = "The Product Photo: %s, %s" % (self.cleaned_data['name'], self.cleaned_data['from_email'],) self.message = self.cleaned_data['message'] + "\n\n-%s" % self.cleaned_data['name'] self.recipient_list = [a[1] for a in settings.ADMINS] self.from_email = self.cleaned_data['from_email'] if not self.is_valid(): raise ValueError(_("Message cannot be sent from invalid contact form")) message_dict = {} for message_part in ('from_email', 'message', 'recipient_list', 'subject'): attr = getattr(self, message_part) message_dict[message_part] = callable(attr) and attr() or attr return message_dict def save(self, fail_silently=False): send_mail(fail_silently=fail_silently, **self.get_message_dict()) super(MessageForm, self).save() class Meta: model = Message fields = ('name', 'from_email', 'message') <file_sep># Django settings for pandolph project. import os PROJECT_DIR = os.path.dirname(__file__) import socket if socket.gethostname() == 'Peyton-Randolphs-MacBook.local': DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'test.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } else: DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'pphoto', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': '<PASSWORD>', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } TEMPLATE_DEBUG = DEBUG ADMINS = ( ('<NAME>', '<EMAIL>'), ) MANAGERS = ADMINS EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = '<PASSWORD>' EMAIL_HOST_USER = '<EMAIL>' EMAIL_PORT = 587 EMAIL_USE_TLS = True # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 2 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = os.path.join(PROJECT_DIR, 'static') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = "/static/" # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '%sadmin-media/' % MEDIA_URL # Make this unique, and don't share it with anybody. SECRET_KEY = '%hi!vwfljjo6amniv-2hod&rxfqy(70-x89a-2)2(sacp03e%3' # List of processors to add context to every template TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request", "django.contrib.messages.context_processors.messages" ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) if DEBUG: MIDDLEWARE_CLASSES = ( # 'django.middleware.cache.UpdateCacheMiddleware', # 'django.middleware.http.ConditionalGetMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', # 'django.middleware.cache.FetchFromCacheMiddleware', ) else: MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.http.ConditionalGetMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) ROOT_URLCONF = 'pphoto.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(PROJECT_DIR, 'templates') ) INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.databrowse', 'django.contrib.flatpages', 'django.contrib.markup', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sitemaps', 'django.contrib.sites', 'common', 'compressor', 'contact', 'debug_toolbar', 'django_extensions', 'eagle_project', 'order', 'typogrify', ) FORCE_LOWERCASE_TAGS = True SEND_BROKEN_LINK_EMAILS = False SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' if DEBUG: CACHE_BACKEND = 'locmem://' else: CACHE_BACKEND = 'memcached://127.0.0.1:11211/' CACHE_MIDDLEWARE_SECONDS = 86400 * 7 # One week CACHE_MIDDLEWARE_KEY_PREFIX = 'pphoto-' CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True def custom_show_toolbar(request): return DEBUG DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar, } # Django CSS settings COMPILER_FORMATS = { '.less': { 'binary_path':'lessc', 'arguments': '*.less' }, } if not DEBUG: COMPRESS_CSS_FILTERS = ['compressor.filters.csstidy.CSSTidyFilter'] COMPRESS = True INTERNAL_IPS = ('127.0.0.1',)<file_sep>from django.conf import settings from django.conf.urls.defaults import * from django.contrib.auth.decorators import login_required from django.contrib.sitemaps import GenericSitemap from django.contrib import databrowse from eagle_project.models import Participant, Work databrowse.site.register(Participant) databrowse.site.register(Work) from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pandolph/', include('pandolph.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^databrowse/(.*)', login_required(databrowse.site.root)), (r'^order/', include('pphoto.order.urls')), (r'^contact/', include('pphoto.contact.urls')), (r'^', include('pphoto.common.urls')), ) if settings.DEBUG: urlpatterns += patterns('django.views.static', (r'^static/(?P<path>.*)$', 'serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), )<file_sep>import datetime from django.contrib.localflavor.us.models import PhoneNumberField, USStateField from django.db import models from django.utils.translation import ugettext_lazy as _ from django_extensions.db.models import TimeStampedModel class Contact(TimeStampedModel): name = models.CharField(max_length=70) email = models.EmailField(max_length=320) phone = PhoneNumberField(blank=True) address = models.CharField(max_length=320, blank=True) city = models.CharField(max_length=100, blank=True) state = USStateField(blank=True) zipcode = models.CharField(max_length=10, blank=True) class Product(TimeStampedModel): kind = models.CharField(max_length=200) quantity = models.PositiveIntegerField() assembly = models.BooleanField(default=False) class Order(TimeStampedModel): ip = models.IPAddressField(default="172.16.31.10", verbose_name = _("IP Address")) contact = models.ForeignKey(Contact) product = models.ForeignKey(Product) comments = models.TextField(blank=True) <file_sep># from django.contrib import admin # from order.models import Order # # class OrderAdmin(admin.ModelAdmin): # fieldsets = ( # (None, { # 'fields': ('name', 'from_email', 'message', 'responded_to',) # }), # ('Advanced Info', { # 'classes': ('collapse',), # 'fields' : ('ip',) # }), # ) # list_display = ('name', 'from_email', 'responded_to') # list_editable = ('responded_to',) # list_per_page = 50 # save_on_top = True # search_fields = ('name', 'from_email',) # # admin.site.register(Order, OrderAdmin)<file_sep>from django.contrib import admin from contact.models import Message class MessageAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('name', 'from_email', 'message', 'responded_to',) }), ('Advanced Info', { 'classes': ('collapse',), 'fields' : ('ip',) }), ) list_display = ('name', 'from_email', 'responded_to') list_editable = ('responded_to',) list_per_page = 50 save_on_top = True search_fields = ('name', 'from_email',) admin.site.register(Message, MessageAdmin)<file_sep>from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from order.forms import OrderWizard, ContactInfoForm, ProductInfoForm from order.views import order_view urlpatterns = patterns('', url(r'^$', OrderWizard([ProductInfoForm, ContactInfoForm]), {}, 'order_form'), url(r'^completed/$', direct_to_template, { 'template': 'order/order_form_sent.html' }, 'order_form_sent'), )<file_sep>""" A collection of reusable utilities """ import re from django import template from django.conf import settings register = template.Library() SAMPLE_LIST = [ 'wineglasses', 'barstool', 'cuisinartcups', '10pcpots', 'toaster', 'readingglasses', 'slippers', 'bathbody', 'hopediamond', 'gemstonebracelet', 'floralnecklace', 'tie', 'luggage', 'golfbasket', 'lamp', 'smithsonianpillow', 'smartbear', 'toycar', 'umbrella', 'lion', 'curtainrods', 'grilltools', 'drill', 'yellowvalve', ] @register.simple_tag def active(request, pattern): """ Determines the active navigational link based on the current path. """ if pattern == '/': pattern = '^/$' # Regexp compatible; prevent unintentional highlighting if re.search(pattern, request.path): return 'active' return '' def parse_ttag(token, given_tags = None): tagname, bits = (lambda x: (x[0], x[1:]))(token.split_contents()) tags = [bits[0]] possible_tags = given_tags or ['as', 'for', 'limit', 'exclude'] for index, bit in enumerate(bits): if bit.strip() in possible_tags: tags.append(bits[index+1]) return tags @register.tag(name="make_sample_list") def do_sample_list(parser, token): tags = parse_ttag(token, ['as']) return MakeSampleListNode(*tags) class MakeSampleListNode(template.Node): def __init__(self, context_var='sample_list'): self.context_var = context_var def render(self, context): context[self.context_var] = SAMPLE_LIST return ''<file_sep>from django.contrib import admin from eagle_project.models import Participant, Work#, Donation class ParticipantAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('name', 'email', 'role', 'work') }), # ('Advanced Info', { # 'classes': ('collapse',), # 'fields' : ('created', 'slug',) # }), ) list_display = ('name', 'email') list_per_page = 50 save_on_top = True search_fields = ('name', 'email',) class ParticipantInline(admin.StackedInline): model = Participant.work.through extra = 20 verbose_name = "Worker" verbose_name_plural = "Workers" class WorkAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('title', 'description', 'hours', 'date',) }), # ('Advanced Info', { # 'classes': ('collapse',), # 'fields' : ('slug',) # }), ) inlines = (ParticipantInline,) list_display = ('title', 'date', 'hours',) list_per_page = 50 save_on_top = True search_fields = ('title', 'description',) # class DonationAdmin(admin.ModelAdmin): # fieldsets = ( # (None, { # 'fields': ('title', 'description', 'hours', 'date',) # }), # # ('Advanced Info', { # # 'classes': ('collapse',), # # 'fields' : ('slug',) # # }), # ) # list_display = ('title', 'date', 'hours',) # list_per_page = 50 # save_on_top = True # search_fields = ('title', 'description',) admin.site.register(Participant, ParticipantAdmin) admin.site.register(Work, WorkAdmin) # admin.site.register(Donation, DonationAdmin)<file_sep>import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ from django_extensions.db.fields import AutoSlugField ROLE_CHOICES = ( (0, _('Project Leader')), (1, _('Scout Leader')), (2, _('Scout')), ) class Participant(models.Model): name = models.CharField(max_length=50) email = models.EmailField(blank=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES) slug = AutoSlugField(populate_from='name') created_date= models.DateTimeField(default=datetime.datetime.now(), editable=False, verbose_name=_('Created on')) work = models.ManyToManyField('eagleproject.Work', blank=True, null=True) # donations def get_total_hours(self): pass class Meta: ordering = ['created_date'] get_latest_by = 'created_date' class Work(models.Model): title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title') hours = models.FloatField() description = models.TextField() date = models.DateField() created_date= models.DateTimeField(default=datetime.datetime.now(), editable=False, verbose_name=_('Created on')) class Meta: ordering = ['date'] get_latest_by = 'date' verbose_name_plural = "Work" # class Donation(models.Model): # title = models.CharField(max_length=100) # slug = AutoSlugField(populate_from='title') # amount = models.FloatField() # description = models.TextField() # date = models.DateField() # created_date= models.DateTimeField(default=datetime.datetime.now(), editable=False, verbose_name=_('Created on')) # # class Meta: # [-]<file_sep>import itertools from django.conf import settings from django.core.mail import send_mail from django import forms from django.contrib.formtools.wizard import FormWizard from django.contrib.localflavor.us.forms import USPhoneNumberField from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ ASSEMBLY_CHOICES = ( ('N', 'No'), ('Y', 'Yes'), ) ANGLE_CHOICES = ( ('N', 'No preference'), ('L', 'Low'), ('M', 'Medium'), ('H', 'High'), ) EFFECT_CHOICES = ( ('N', 'No preference'), ('D', 'Drop shadow'), ('R', 'Reflection'), ('O', 'Outline'), ) FOCUS_CHOICES = ( ('N', 'No preference'), ('F', 'Full focus'), ('S', 'Selective focus'), ) DELIVERY_CHOICES = ( ('W', 'Web download (FTP)'), ('D', 'CD shipped overnight (additional charge)'), ) RESOLUTION_CHOICES = ( ('W', 'Web resolution (800x526 pixels)'), ('H', 'High resolution (5000x4000 pixels, additional charge)'), ) class ProductInfoForm(forms.Form): error_css_class = 'error' required_css_class = 'required' single_quantity = forms.IntegerField(widget=forms.widgets.TextInput(attrs={'class':'short'}), label=_('Single item'), initial=0, required=False, min_value=0, ) small_group_quantity = forms.IntegerField(widget=forms.widgets.TextInput(attrs={'class':'short'}), label=_('Small group'), initial=0, required=False, min_value=0, ) large_group_quantity = forms.IntegerField(widget=forms.widgets.TextInput(attrs={'class':'short'}), label=_('Large group'), initial=0, required=False, min_value=0, error_messages={ 'min_value': 'Please enter a number greater than 0.' } ) assembly_required = forms.BooleanField(label=_('Assembly required?'), initial='N', widget=forms.widgets.RadioSelect(choices=ASSEMBLY_CHOICES, attrs={'class':'radio'})) angle = forms.BooleanField(label=_('Preferred shooting angle'), initial='N', widget=forms.widgets.RadioSelect(choices=ANGLE_CHOICES, attrs={'class':'radio'})) effects = forms.BooleanField(label=_('Desired effects'), initial='N', widget=forms.widgets.RadioSelect(choices=EFFECT_CHOICES, attrs={'class':'radio'})) focus = forms.BooleanField(label=_('Focus style'), initial='N', widget=forms.widgets.RadioSelect(choices=FOCUS_CHOICES, attrs={'class':'radio'})) class ContactInfoForm(forms.Form): error_css_class = 'error' required_css_class = 'required' name = forms.CharField(max_length=70, error_messages={'required': 'Please enter your name.'}) email = forms.EmailField(max_length=320, error_messages={'required': 'Please enter your email address.', 'invalid':'Please enter a valid email address.'}, ) phone = USPhoneNumberField(label=_('Phone number'), error_messages={'required': 'Please enter your phone number.', 'invalid': 'Please enter your phone number in the form XXX-XXX-XXXX.'} ) company = forms.CharField(max_length=70, required=False, label=_('Company (optional)')) # address = forms.CharField(widget=forms.widgets.Textarea(attrs={'class':'smaller'}), label=_('Full address'), # error_messages={'required': 'Please enter your full address, including Street, City, State, and ZIP Code.'} # ) # resolution = forms.BooleanField(label=_('Image resolution'), initial='W', # widget=forms.widgets.RadioSelect(choices=RESOLUTION_CHOICES, attrs={'class':'radio'})) deliver_via = forms.BooleanField(label=_('Deliver via'), initial='W', widget=forms.widgets.RadioSelect(choices=DELIVERY_CHOICES, attrs={'class':'radio'})) # date = forms.DateField(label=_('Preferred date (optional)'), required=False, # error_messages={'invalid': 'Please enter a date in the form MM/DD/YYYY.'} # ) comments = forms.CharField(widget=forms.widgets.Textarea(), required=False, label=_('Additional comments (optional)'), ) # class DeliveryInfoForm(forms.Form): # error_css_class = 'error' # required_css_class = 'required' # # # resolution = forms.BooleanField(label=_('Image resolution'), initial='W', # # widget=forms.widgets.RadioSelect(choices=RESOLUTION_CHOICES, attrs={'class':'radio'})) # deliver_via = forms.BooleanField(label=_('Deliver via'), initial='W', # widget=forms.widgets.RadioSelect(choices=DELIVERY_CHOICES, attrs={'class':'radio'})) # # date = forms.DateField(label=_('Preferred date (optional)'), required=False, # # error_messages={'invalid': 'Please enter a date in the form MM/DD/YYYY.'} # # ) # comments = forms.CharField(widget=forms.widgets.Textarea(), required=False, # label=_('Additional comments (optional)'), # ) class OrderWizard(FormWizard): def get_message_dict(self, form_list): form_data_list = [form.cleaned_data for form in form_list] self.form_data = {} for x in form_data_list: self.form_data.update(x) self.subject = 'Order: %s, %s' % (self.form_data['name'], self.form_data['email']) self.message = render_to_string('order/email_template.txt', {'form_data': self.form_data}) self.recipient_list = [a[1] for a in settings.ADMINS] self.from_email = self.form_data['email'] message_dict = {} for message_part in ('from_email', 'message', 'recipient_list', 'subject'): attr = getattr(self, message_part) message_dict[message_part] = callable(attr) and attr() or attr return message_dict def get_template(self, step): return 'order/step%d.html' % step # def save(self, fail_silently=False): # send_mail(fail_silently=fail_silently, **self.get_message_dict()) # super(OrderForm, self).save() def done(self, request, form_list, fail_silently=True): send_mail(fail_silently=fail_silently, **self.get_message_dict(form_list)) success_url = reverse('order_form_sent') return HttpResponseRedirect(success_url) <file_sep>import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ from django_extensions.db.models import TimeStampedModel class Message(TimeStampedModel): name = models.CharField(max_length=50) from_email = models.EmailField(max_length=320, verbose_name=_("Email")) message = models.TextField(verbose_name=_("Message")) ip = models.IPAddressField(default="127.0.0.1", verbose_name = _("IP Address")) responded_to = models.BooleanField() <file_sep>from django.contrib import admin from eagleproject.models import Participant, Work#, Donation class ParticipantAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('name', 'email', 'role', 'work') }), # ('Advanced Info', { # 'classes': ('collapse',), # 'fields' : ('created_date', 'slug',) # }), ) list_display = ('name', 'email') list_per_page = 50 save_on_top = True search_fields = ('name', 'email',) class WorkAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('title', 'description', 'hours', 'date',) }), # ('Advanced Info', { # 'classes': ('collapse',), # 'fields' : ('slug',) # }), ) list_display = ('title', 'date', 'hours',) list_per_page = 50 save_on_top = True search_fields = ('title', 'description',) # class DonationAdmin(admin.ModelAdmin): # fieldsets = ( # (None, { # 'fields': ('title', 'description', 'hours', 'date',) # }), # # ('Advanced Info', { # # 'classes': ('collapse',), # # 'fields' : ('slug',) # # }), # ) # list_display = ('title', 'date', 'hours',) # list_per_page = 50 # save_on_top = True # search_fields = ('title', 'description',) admin.site.register(Participant, ParticipantAdmin) admin.site.register(Work, WorkAdmin) # admin.site.register(Donation, DonationAdmin)<file_sep>from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from contact.forms import MessageForm from contact.views import contact_form urlpatterns = patterns('', url(r'^$', contact_form, {'form_class': MessageForm}, 'contact_form'), url(r'^sent/$', direct_to_template, { 'template': 'contact/contact_form_sent.html' }, 'contact_form_sent'), )
f3cbdec1bc5bf31c56139f24a96f4718d380dbdd
[ "Python" ]
16
Python
peyton/pphoto
53f2e1309b8ec5a5bf29ad7d09b805ad945a5010
17f27bfee540f7bd5772e77bc1088e96bd68ce3d
refs/heads/master
<repo_name>serjolas1/store<file_sep>/requirements.txt Flask Flask-Session cs50 <file_sep>/app.py from cs50 import SQL from flask import Flask, render_template, redirect, request, session from flask_session import Session #create app app = Flask(__name__) #configure app app.config['SESSION_TYPE'] = 'filesystem' app.config['SESSION_PERMANENT'] = False Session(app) #connect to db db = SQL('sqlite:///store.db') @app.route('/') def index(): books = db.execute("SELECT * FROM books") return render_template('index.html', books=books) @app.route('/cart', methods=["GET", "POST"]) def cart(): if "cart" not in session: session['cart'] = [] #POST if request.method == 'POST': id = request.form.get('id') add(id) #GET books = [] for i in session['cart']: book = db.execute("SELECT * FROM books WHERE id = (?)", i['id']) books.append({ "name": book[0]['name'], "amount": i['amount'] }) return render_template('cart.html', books=books, clear=len(books)==0) @app.route('/remove', methods=["POST"]) def remove(): name = request.form.get('name') id = db.execute("SELECT id FROM books WHERE name = (?)", name)[0]['id'] for i in session['cart']: if i['id'] == str(id): print(i['id']) if i['amount'] > 1: i['amount'] -= 1 else: session['cart'].remove(i) return redirect('/cart') def add(id): for a in session['cart']: if a['id'] and a['amount'] and a['id'] == id: a['amount'] += 1 return session['cart'].append({ "id": id, "amount": 1 })
2a55652cbe5f130c8762c5e9a65b53ed4515193d
[ "Python", "Text" ]
2
Text
serjolas1/store
6fffadbd728c5366ec9754db15213afc04083aa8
c35045f24645fb2ed58848d24594981ca313dd48
refs/heads/master
<file_sep># Way2Automation - A demo project to show automation of Way2Automation demo site <file_sep>[SuiteResult context=AutomateWay2Automation]<file_sep>package com.way2automation.common; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; public class generalMethods { private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; public static void waitForAjax(WebDriver driver) { new WebDriverWait(driver, 180).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { JavascriptExecutor js = (JavascriptExecutor) driver; return (Boolean) js.executeScript("return jQuery.active == 0"); } }); } public static String randomAlphaNumeric(int count) { StringBuilder builder = new StringBuilder(); while (count-- != 0) { int character = (int) (Math.random() * ALPHA_NUMERIC_STRING.length()); builder.append(ALPHA_NUMERIC_STRING.charAt(character)); } return builder.toString(); } } <file_sep><h2>Methods that were not run</h2><table> <tr><td>com.way2automation.demo.tests.AutomateWay2Automation.Alerts</td></tr> <tr><td>com.way2automation.demo.tests.AutomateWay2Automation.FramesAndWindows</td></tr> <tr><td>com.way2automation.demo.tests.AutomateWay2Automation.dynamicElements</td></tr> <tr><td>com.way2automation.demo.tests.AutomateWay2Automation.WidgetDatePicker</td></tr> </table>
b23b8f45f41ebf4fb80418d9cb342c9e7e00a4e1
[ "Markdown", "Java", "HTML", "INI" ]
4
Markdown
TheGeekonQuality/Way2Automation
bc067b233faf7afa87a1bf700c0eb7e478df650a
f60bb9020f92ba4c5a3d33b5a5c68c70c3472633
refs/heads/master
<file_sep>const Koa = require('koa') const cors = require('@koa/cors') const InitManager = require('./core/init') const bodyParser = require('koa-bodyparser') const catchError = require('./middlewares/exception') const app = new Koa() require('./app/models/user') app.use(cors()) app.use(bodyParser()) app.use(catchError) InitManager.initCore(app) if (global.config.env === 'dev') { } app.listen(3030, () => { }) <file_sep>import bookmark from './bookmark.svg' import comment from './comment.svg' const ICON = { bookmark, comment } export default ICON <file_sep>module.exports = { env: 'dev', // env: 'prod', database: { dbName: 'noter', host: '172.16.17.32', port: 3306, user: 'noter', pwd: '<PASSWORD>' }, security: { secretKey: 'abcdefg', // 秘钥 expiresIn: 60 * 60 * 24 * 30, // 令牌过期时间 一个月 }, github: { // client_id: '907e089d8acd7d59d6ea', client_id: '00d361bef1a3c27055fd', scope: 'user:email', // client_secret: '<KEY>' client_secret: '<KEY>' }, wx: { appId: 'wx55b5e6eac0880945', appSecret: '<KEY>', loginUrl: 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code' }, host: 'http://localhost:3030/' } <file_sep>import { Icon, Spin } from 'antd' import React, { Suspense } from 'react' import './style.less' import { Link } from 'react-router-dom' import { Placeholder } from 'semantic-ui-react' import ICON from '../../asset/icon' import FixedBar from '../../component/FixedBar' import ImageLoader from '../../component/ImageLoader' import { axios_get } from '../../util/axios' import { FIND_MENU } from '../../constant/config' import { SYSTEM_CONFIG } from '../../constant/config' import LazyLoad from 'react-lazyload' import { dateToFromNow } from '../../util/date' const {BASE_QINIU_URL} = SYSTEM_CONFIG.qiniu class Find extends React.Component { state = { currtab: 'all', // all || follow || hot || tag currNotes: [], loading: false, fetchingNote: false, hotList: [], tagList: [] } async componentDidMount() { this.setState({fetchingNote: true}) axios_get('note/list') .then(data => { this.setState({currNotes: data, fetchingNote: false}) }) axios_get('note/hot') .then(data => { this.setState({hotList: data}) }) axios_get('tag') .then(data => { this.setState({tagList: data}) }) } /** * 修改标签 */ doChangeTab = (e) => { let key switch (e.target.innerText) { case '所有': key = 'all' break case '标签': key = 'tag' break default: key = 'all' } if (key === 'all') { axios_get('note/list') .then(data => { this.setState({currNotes: data, fetchingNote: false}) }) } this.setState({currtab: key}) } doSearch = (id) => { axios_get('note/byTag/' + id) .then(data => { this.setState({ currNotes: data.data }) }) } render() { const {currtab, currNotes, loading, fetchingNote, hotList, tagList} = this.state const NoteCard = ({note}) => ( <div className="note-card"> <div style={{width: 400, overflow: 'hidden'}}> <LazyLoad height={200} once throttle={250} placeholder={ <Placeholder style={{height: 200, width: 400}}> <Placeholder.Image/> </Placeholder> } > <ImageLoader src={note.cover ? BASE_QINIU_URL + note.cover + '?imageslim' : `https://picsum.photos/400/200?random=${Math.floor(Math.random() * 1000)}`} /> </LazyLoad> </div> <div className="card-content"> <div className="note-title"> <Link to={`/note/${note.id}`}>{note.title}</Link> </div> <div className="note-attr"> <div className="user"> <img className="user-icon" src={note.avatar} alt=""/> <span className="username">{note.user_name}</span> <span className="update-time">{dateToFromNow(note.created_at)}</span> </div> <div className="like"> <div><img src={ICON.bookmark} alt=""/><span>{note.like_num}</span></div> <div><img src={ICON.comment} alt=""/><span>{note.collect_num}</span></div> </div> </div> </div> </div> ) return ( <Suspense fallback={<div>Loading...</div>}> <div className="g-find"> <div className="m-find-tab"> <ul> {FIND_MENU.map(item => <li key={item.key} onClick={this.doChangeTab} className={`${currtab === item.key && 'active'}`} >{item.title}</li> )} </ul> </div> <div className="m-find"> { loading ? <Icon type="loading" style={{fontSize: 48}}/> : <Spin spinning={fetchingNote} indicator={<Icon type="loading" style={{fontSize: 32, color: '#fd281a'}}/>}> {currtab === 'tag' && ( <div className="m-tags-wrap"> {tagList.map(tag => { return <div className="m-tag" key={'tab' + tag.name} onClick={this.doSearch.bind(this, tag.id)}># <span>{tag.name}</span></div> })} </div> )} <div className="note-list"> {currtab === 'all' && currNotes.map((item, i) => <NoteCard key={`node-${i}`} note={item}/>)} {currtab === 'tag' && currNotes.map((item, i) => <NoteCard key={`node-${i}`} note={item}/>)} {currNotes.length === 0 && ( <div className="no-data">没有更多数据 😯</div> )} </div> </Spin> } <div className="find-right-bar"> <div className="title"> 最热 · 精选 </div> <div className="hot-list"> {hotList.map(item => ( <div className="item" key={'hot-' + item.id}> <div className="avatar"> <img src={item.avatar} alt=""/> </div> <div className="info"> <div className="item-name">{item.user_name}</div> <Link to={'note/' + item.id}> <span className="item-title">{item.title}</span> </Link> </div> </div> ))} </div> </div> </div> <FixedBar/> </div> </Suspense> ) } } export default Find <file_sep>/** * 游览器原生 base64 编码 * @param jwt * @return {string} */ export const encodeJWT = (jwt) => `Basic ${window.btoa(jwt + ':')}` <file_sep>export { ArrowUpOutlined, EditOutlined, UserOutlined, PlusOutlined, LoadingOutlined, GithubOutlined, BarChartOutlined, } from '@ant-design/icons/lib/index.es'<file_sep> # webpack-noter-optimization 第一次 ![image-20200304205939420](http://qn-noter.yunxi.site/imagehost/m9qjl.png) ![image-20200304211848832](http://qn-noter.yunxi.site/imagehost/ub6m7.png-style1) ## 移除 semantic.min.css,采用CDN引入 ## hash标记包 ```javascript output: { path: path.resolve(__dirname, '../dist'), filename: devMode ? 'js/[name].[hash].js' : 'js/[name].[contenthash].js', chunkFilename: devMode ? 'chunks/[name].[hash:4].js' : 'chunks/[name].[contenthash].js', }, ``` `chunkname`我的理解是未被列在`entry`中,却又需要被打包出来的文件命名配置。什么场景需要呢?我们项目就遇到过,在按需加载(异步)模块的时候,这样的文件是没有被列在`entry`中的,如使用CommonJS的方式异步加载模块: - ExtractTextPlugin:提取样式到css文件 ![image-20200305101609119](http://qn-noter.yunxi.site/imagehost/k8ogm.png-style1) ## 打包开缓存 .cache 文件夹 ## happypack ![image-20200305102135980](http://qn-noter.yunxi.site/imagehost/8qtqg.png-style1) ## 路由懒加载 ![image-20200305114153334](http://qn-noter.yunxi.site/imagehost/ckh1w.png-style1) ```jsx // lazy.js 二次封装lazy const retry = (fn, retriesLeft = 5, interval = 500) => { return new Promise((resolve, reject) => { fn() .then(resolve) .catch((error) => { setTimeout(() => { if (retriesLeft === 1) { reject(error) } else { retry(fn, retriesLeft - 1, interval).then(resolve, reject) } }, interval) }) }) } const lazy = (fn) => React.lazy(() => retry(fn)) export default lazy // WaitingComponent export default (Component) => { return props => ( <Suspense fallback={<div>Loading...</div>}> <Component {...props} /> </Suspense> ) } // App.js const Find = lazy(() => import('./page/find')) const Write = lazy(() => import('./page/write')) const Profile = lazy(() => import('./page/profile')) const Login = lazy(() => import('./page/login')) const MyNote = lazy(() => import('./page/mynote')) const Note = lazy(() => import('./page/note')) const Edit = lazy(() => import('./page/edit')) const Setting = lazy(() => import('./page/setting')) <Route exact path='/' component={WaitingComponent(Find)} /> ... ``` ## source-map https://segmentfault.com/a/1190000020320871 ## 阶段性成果 ![image-20200305114858851](http://qn-noter.yunxi.site/imagehost/o774l.png-style1) 在 fast 3G 速度下,已经可以达到10s加载了 ![image-20200305114955719](http://qn-noter.yunxi.site/imagehost/o5y3z.png-style1) ![image-20200305115105726](http://qn-noter.yunxi.site/imagehost/i5n8s.png-style1) 目前测一下,??? 才17分?? ![image-20200305122518922](http://qn-noter.yunxi.site/imagehost/3ojbr.png-style1) 目前来看还有两个问题 - antd 的 icons 全量引入问题 - 第三方库没有单独打包 接下来进行代码分割。 ## 代码分割 第三方库单独打包有几个好处。 首先,第三方库其实改动不大的,经常改的其实是我们业务代码。所以第三方库单独打包,也就是有独有的 hash,这样做了缓存之后就能长期让用户命中强缓存,而我们业务代码改来改去也不会影响第三方库的缓存。 ![image-20200305132245077](http://qn-noter.yunxi.site/imagehost/cfhkc.png-style1) ![image-20200305132212935](http://qn-noter.yunxi.site/imagehost/gey5r.png-style1) 这么打完之后,发现其实主要还是第三方库的问题(就是你,antd) ## antd图标处理 ```javascript // 安装@ant-design/icons // yarn add @ant-design/icons // src/icons.js export { ArrowUpOutline, EditOutline, UserOutline, PlusOutline, LoadingOutline, GithubOutline, BarChartOutline, } from '@ant-design/icons/lib/index.es' // webpack.prod.js ... resolve: { alias: { "@ant-design/icons/lib/dist$": path.resolve(__dirname, "./src/icons.js") } }, ... ``` 方法二:升级到 antd 4.0 ## Nginx Gzip 压缩 ![image-20200305131314343](http://qn-noter.yunxi.site/imagehost/tiqrv.png-style1) 立竿见影 ![image-20200305131641917](http://qn-noter.yunxi.site/imagehost/5txq0.png-style1) 速度有了一倍左右的提升。 ![image-20200305131729013](http://qn-noter.yunxi.site/imagehost/emeho.png-style1) 坑:SVG 转 base64 无法显示+报错 <file_sep># yunxi-cms ## 进度 | 日期 | 模块 | 学习内容 | 其他 | | ---- | ---- | ------------------------------------ | ---- | | 11.28 | 底层 | 深入学习async/await及其在koa中的用法 | | | 11.29 | 底层 | koa自定义参数校验 | | | 11.30 | 底层 | 全局异步异常捕捉中间件 | 同理,日志也可以类似处理吧 | | 12.1 | 底层 | LinValidator校验库,初步sequelize | | | 12.2 | 底层 | 自定义异常, user接口, 密码加密 | | | 12.3 | 基础 | 用户登录逻辑, Token令牌 | | | 12.5 | 业务 | token生成、校验业务逻辑 | | | 12.6 | 业务 | note、user、tag业务模型,业务表、实体表区别 | | | 12.7 | 业务 | 点赞、收藏业务 | | | 12.8 | 业务 | 整理业务 | | | 12.9 | 业务 | 文章管理相关业务、JSON序列化 | | | 12.20| 业务 | 文章展示接口 | | | 12.21| 业务 | github一键登录接口 | | | 12.22| 基础 | 代码规范化审查、文档撰写 | | ## Best Practice ### 安全 - uid 号码放在auth中传递,禁止让客户端作为参数传递(篡改).例如用户A篡改uid后获取的token,可以套出数据库中所有其他用户的数据 - 报`Internal Server Error`错误,多半是没加await - 二次重发机制,用户无感知地刷新令牌 ### 缓存 - 期刊的标题/描述/图片/出版日期等,这些都是数据库生成后基本不会改变的内容,因此非常适合将其缓存到客户端中 - 但是有些数据经常改变,比如点赞数,这就适合单独再做一个接口 - 相比后端缓存,前端缓存是解决性能问题的最有效方案 - 但是前端缓存局限性很大 ### 转型 - JSON传输可以识别字符串or数字 - URL或者params传输的是字符串,服务器手动转型 ### 数据库/ORM - MYSQL - Sequelize的一个bug,查询后对数据修改,必须设置`useScope=false` - 禁止在循环中查询数据库,因为查询次数受数据影响. 改为使用in查询 - Sequelize千万千万别在Model子类下面写构造函数! ### JS - 所有对象的`key`都是字符串!!! 如果是 [key], 则key可以是一个表达式,但是最终结果还是字符串!!! - `for...in` 和 `for...of`循环的区别 - forEach() 内不得用 async/await - 不知道什么原因报BUG,看看有没有循环导入! ### 其他 - 并发/并行 - js宏任务/微任务, EventLoop ### 数据过滤/JSON序列化 - sequelize查询的时候使用scope - 查出来之后,手动挑一些字段,包装成一个对象返回,这样很呆,数据简单的时候可以做 - JSON序列化的时候过滤字段(定义`toJSON`方法) - 那也就是说,在`Model`类上定义toJSON方法即可实现过滤模型 - 别把exclude的字段挂到原型链上,这样是把代码写死了,最好在API层面决定要过滤哪些字段,麻烦就麻烦点吧,但是确保了安全和灵活 ## 后端目录结构 ``` |---server | |---app | | |---api | | | |---v1 | | | | |---like.js | | | | |---note.js | | | | |---tag.js | | | | |---token.js | | | | |---upload.js | | | | |---user.js | | |---lib | | | |---auth.js | | | |---exception.js | | |---models | | | |---bookComment.js | | | |---favor.js | | | |---note.js | | | |---tag.js | | | |---user.js | | |---services | | | |---wx.js | | |---validators | | | |---validator.js | | |---config | | | |---config.js | | |---core | | | |---db.js | | | |---httpExcepyion.js | | | |---init.js | | | |---lin-validator-v2.js | | | |---lin-validator.js | | | |---utils.js | | |---middlewares | | | |---auth.js | | | |---exception.js | | |---upload ```<file_sep>import React from 'react' import './style.less' import { withRouter } from 'react-router' import FixedBar from '../../component/FixedBar' import NoteBar from '../../component/NoteBar' import { axios_get } from '../../util/axios' import { SYSTEM_CONFIG } from '../../constant/config' import { dateToFromNow } from '../../util/date' const {BASE_QINIU_URL} = SYSTEM_CONFIG.qiniu @withRouter class Note extends React.Component { state = { note: {}, status: {like: false, collect: false} } componentDidMount() { const noteId = this.props.match.params.id this.setState({loading: true}) const token = window.localStorage.getItem('token') if (token) { axios_get('note/isFavor/' + noteId) .then(data => { this.setState({status: data}) }) } axios_get('note/' + noteId) .then(data => { this.setState({note: data}) }) .finally(() => this.setState({loading: false})) } doLike = () => { const noteId = this.props.match.params.id const url = `favor/${this.state.status.like ? 'dislike' : 'like'}/${noteId}` axios_get(url) .then(data => { const _status = {...this.state.status} _status.like = !_status.like data.ok === 1 && this.setState({status: _status}) }) } doCollect = () => { const noteId = this.props.match.params.id const url = `favor/${this.state.status.collect ? 'disCollect' : 'collect'}/${noteId}` axios_get(url) .then(data => { const _status = {...this.state.status} _status.collect = !_status.collect data.ok === 1 && this.setState({status: _status}) }) } render() { const {note, status} = this.state return ( <div className="g-note"> <div className="m-header"> <div className="header-img"> <img src={note.cover ? BASE_QINIU_URL + note.cover + '?imageslim' : 'https://picsum.photos/600/300'} alt=""/> </div> <div className="title"> {note && note.title} </div> <div className="info"> <div className="name"> <span className="user-icon"> <img src={note && note.avatar} alt=""/> </span> <span className="name"> {note && note.user_name} </span> </div> <div className="time">{dateToFromNow(note.created_at)}</div> </div> </div> <div className="content"> <div className="braft-output-content" dangerouslySetInnerHTML={{__html: note && note.html}}/> </div> <FixedBar/> <NoteBar status={status} doLike={this.doLike} doCollect={this.doCollect}/> </div> ) } } export default Note <file_sep>const Router = require('koa-router') const router = new Router({ prefix: '/v1/note' }) const { AddNoteValidator, NoteValidator, PublishNoteValidator, PositiveIntegerValidator } = require('../../validators/validator') const { Note } = require('../../models/note') const { success } = require('../../lib/helper') const { Auth } = require('../../../middlewares/auth') const dayjs = require('dayjs') const multer = require('@koa/multer') // 文件上传中间件 var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'upload/') }, filename: function (req, file, cb) { let type = file.originalname.split('.').splice(-1) cb(null, `IMG_${dayjs((new Date())).format('YYYYMMDDhhmmss')}.${type}`) } }) // 初始化中间件 const upload = multer({ storage }) /** * 新增文章 */ router.post('/add', new Auth().m, async ctx => { const v = await new AddNoteValidator().validate(ctx) const note = v.get('body') note.author = ctx.auth.uid await Note.addNote(note) success('新增成功') }) /** * 获取所有文章 */ router.get('/', async () => { const notes = await Note.showAllNotes() success('已更新', notes) }) /** * 获取所有文章 */ router.get('/list', async () => { const notes = await Note.showAllNotes(false) success('已更新', notes) }) /** * 获取最热文章 */ router.get('/hot', async () => { const notes = await Note.showHotNotes() success(null, notes) }) /** * 按点赞量降序获取文章 */ router.get('/like', async () => { const notes = await Note.showLikedNotes() success('ok', notes) }) /** * 按收藏量降序获取所有文章 */ router.get('/collect', async () => { const notes = await Note.showCollectedNotes() success('ok', notes) }) /** * 文章发布接口 */ router.post('/publish', async ctx => { const v = await new PublishNoteValidator().validate(ctx, { id: 'id' }) await Note.update({ status: 2, where: { id: v.get('body.id') } }) }) /** * 按照标题查询文章(模糊查询) */ router.get('/search/:title', async ctx => { const v = await new NoteValidator().validate(ctx) const notes = await Note.queryNoteByTitle(v.get('path.title')) success(null, notes) }) /** * 文章图片上传接口 */ router.post('/upload', new Auth().m, upload.single('file'), ctx => { const path = ctx.file.path.replace('\\', '/') success('ok', { path }) } ) /** * 获取当前用户的文章 */ router.get('/mine', new Auth().m, async ctx => { const notes = await Note.queryNoteByAuthor(ctx.auth.uid) success('已更新', { notes }) }) /** * 删除用户文章接口,同时删除该文章的所有点赞收藏记录 */ router.get('/delete/:id', new Auth().m, async ctx => { const v = await new PositiveIntegerValidator().validate(ctx, { id: 'id' }) await Note.deleteNote(v.get('path.id')) success('删除成功', { ok: 1 }) }) /** * 用户请求文章编辑接口 */ router.get('/modify/:id', new Auth().m, async ctx => { const v = await new PositiveIntegerValidator().validate(ctx, { id: 'id' }) const content = await Note.modifyNote(v.get('path.id'), ctx.auth.uid) success('开始更改', { content }) }) /** * 文章更新接口 */ router.post('/update', new Auth().m, async ctx => { const id = ctx.auth.uid ctx.request.body.author = id const v = await new AddNoteValidator().validate(ctx) const newNote = v.get('body') await Note.updateNote(newNote) success('文章已更新', { ok: 1 }); }) /** * 文章详情接口 */ router.get('/:id', async ctx => { const v = await new PositiveIntegerValidator().validate(ctx, { id: 'id' }) const id = v.get('path.id') const content = await Note.queryNoteById(id) success(null, content) }) /** * 判断用户是否对此文章点赞接口 */ router.get('/isFavor/:id', new Auth().m, async ctx => { const v = await new PositiveIntegerValidator().validate(ctx, { id: 'id' }) const r = await Promise.all([ Note.isLike(ctx.auth.uid, v.get('path.id')), Note.isCollect(ctx.auth.uid, v.get('path.id')) ]) success(null, { like: r[0], collect: r[1] }) }) /** * 按照标签获取文章 */ router.get('/byTag/:id', async ctx => { const v = await new NoteValidator().validate(ctx) const tags = v.get('path.id') const data = await Note.queryNoteByTag(tags) success(null, { data }) }) module.exports = router <file_sep>import React from 'react' import './style.less' import bookmark from './bookmark.png' import collected from './collected.png' import like from './like.png' import liked from './liked.png' export default (props) => { let hasCollected = (props.status && props.status.collect) return ( <div className="g-notebar"> <div className="m-icon" onClick={props.doLike} > <img style={{height: 18}} src={(props.status && props.status.like) ? liked : like} alt=""/> </div> <div className="m-icon" onClick={props.doCollect} > <img style={{height: hasCollected ? 42 : 28}} src={(props.status && props.status.collect) ? collected : bookmark} alt=""/> </div> </div> ) } <file_sep>const { Sequelize, Model } = require('sequelize') const { db } = require('../../core/db') /** * 文章标签业务 */ class Tag extends Model { /** * 展示所有用户标签 */ static async showTags() { return await Tag.findAll({ where: { author: 0 } }) } /** * 添加标签方法 * @param name 标签名 * @param author 作者id */ static async addTags(name, author) { return await Tag.create({ name: name, author: author }) } } Tag.init({ // 记录Id id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, // TAG名称 name: Sequelize.STRING(100), author: Sequelize.INTEGER }, { sequelize: db, tablename: 'tag' }) module.exports = { Tag }<file_sep># NOTER数据字典 ## user表 |字段名|类型|含义|约束|备注| | :--------: | :---: | :----: | :--------: | :--------: | |id|int|记录id|Primary_Key(id)| | |user_name|varchar(64)|用户名| | | |password|varchar(128)|密码| | <PASSWORD> | |github_id|int|githubId| | | |real_name|varchar(64)|真实姓名| | | |sex|int|性别| | 1-男;2-女 | |email|varchar(255)|邮箱| | | |expertise|varchar(255)|专长| | | |desc|varchar(255)|简介| | | |avatar|varchar(255)|github图片| | 存图片地址 | ## note表 |字段名|类型|含义|约束|备注| | :--------: | :---: | :----: | :--------: | :--------:| |id|int|记录id|Primary_Key(id)| | |title|varchar(255)|标题| | | |cover|varchar(255)|标题| | 存图片hash值 | |raw|text|json内容| | 存json | |html|text|h5内容| | 存H5标签 | |author|int|作者id| Foreign_Key(user) | | |like_num|int|点赞数量| | 默认为0 | |collect_num|int|收藏数量| | 默认为0 | |tag|varchar(100)|文章类型| | TAG序号数组,比如1,2,3对应TAG表1,2,3 | |status|int| 状态 | | 1-草稿;2-发布 | ## favor表 |字段名|类型|含义|约束|备注| | :--------: | :---: | :----: | :--------: | :--------:| | id | int | 记录id | Primary_Key(id) | | | uid | int | 用户id| Foreign_Key(user)| | | art_id | int | 笔记文章id | Foreign_Key(note) | | type | int | 喜欢类型 | | 1-点赞 2-收藏 | ## TAG表 |字段名|类型|含义|约束|备注| | :--------: | :---: | :----: | :--------: | :--------:| | id | int | 记录id | Primary_Key(id) | | | name | varchar(100) | TAG名称 | | | | author | int | 用户id | Foreign_Key | 0-管理员,其他-用户(不加载) | <file_sep>import React from 'react' const retry = (fn, retriesLeft = 5, interval = 500) => { return new Promise((resolve, reject) => { fn() .then(resolve) .catch((error) => { setTimeout(() => { if (retriesLeft === 1) { reject(error) } else { retry(fn, retriesLeft - 1, interval).then(resolve, reject) } }, interval) }) }) } const lazy = (fn) => React.lazy(() => retry(fn)) export default lazy <file_sep>import { SYSTEM_CONFIG } from '../constant/config' export const API_BASE = "http://127.0.0.1:3030/" // export const API_BASE = 'http://172.22.203.70:3030/v1/' const _api = (endpoint) => API_BASE + endpoint const CLIENT_ID = SYSTEM_CONFIG.github.client_id const SCOPE = SYSTEM_CONFIG.github.scope export const NOTE_LIST = _api('note') export const USER_LIST = _api('user') export const GITHUB_LOGIN = `https://github.com/login/oauth/authorize?client_id=${CLIENT_ID}&scope=${SCOPE}` <file_sep>import { Button, Form, Input as AntInput, message, Select, Spin, Upload } from 'antd' import { computed } from 'mobx' import { inject, observer } from 'mobx-react' import React from 'react' import './style.less' import { axios_get, axios_post } from '../../util/axios' const {Option} = Select @Form.create() @inject('userStore') @observer class Setting extends React.Component { state = { submitting: false } @computed get currUser() { return this.props.userStore.currUser } handleSubmit = (e) => { e.preventDefault() this.props.form.validateFields((error, values) => { if (!error) { const submitData = {...values} this.setState({submitting: true}) axios_post('user/modify', submitData) .then(data => { if (data && data.ok === 1) { setTimeout(() => { window.location.href = '/profile' }, 1000) } }) .finally(() => { this.setState({submitting: false}) }) } else { message.error('提交发生错误') } }) } render() { const {submitting} = this.state const {getFieldDecorator} = this.props.form return ( <div className="g-setting"> <div className="m-title">账号设置</div> <Form onSubmit={this.handleSubmit} className="m-setting-form"> <div className="m-form"> <Form.Item style={{marginBottom: 10}} label='用户名'> {getFieldDecorator('userName', { initialValue: this.currUser.userName || '' })( <AntInput size="large" placeholder="用户名" />, )} </Form.Item> <Form.Item style={{marginBottom: 10}} label='常用邮箱'> {getFieldDecorator('email', { initialValue: this.currUser.email || '' })( <AntInput size="large" placeholder="常用邮箱" />, )} </Form.Item> <Form.Item style={{marginBottom: 10}} label='真实姓名'> {getFieldDecorator('realName', { initialValue: this.currUser.realName || '' })( <AntInput size="large" placeholder="真实姓名" />, )} </Form.Item> <Form.Item style={{marginBottom: 10}} label='个人简介'> {getFieldDecorator('desc', { initialValue: this.currUser.desc || '' })( <AntInput size="large" placeholder="个人简介" />, )} </Form.Item> </div> <div style={{textAlign: 'center'}}> <Button size="large" className="setting-save" htmlType="submit" loading={submitting}>保存</Button> </div> </Form> </div> ) } } export default Setting <file_sep>### 性能优化 [SPA 网页首屏渲染优化](https://zhuanlan.zhihu.com/p/25696102) <file_sep>import { inject, observer } from 'mobx-react' import React from 'react' import BraftEditor from 'braft-editor' import { Form, Input as AntInput, Button, Icon, Select, Spin, message, Upload, Modal } from 'antd' import debounce from 'lodash/debounce' import { SYSTEM_CONFIG } from '../../constant/config' import 'braft-editor/dist/index.css' import './style.less' import { axios_get, axios_post } from '../../util/axios' const { Option } = Select const { BASE_QINIU_URL, QINIU_SERVER } = SYSTEM_CONFIG.qiniu @Form.create() @inject() @observer class Write extends React.Component { constructor(props) { super(props) this.lastFetchId = 0 this.fetchUser = debounce(this.fetchUser, 800) } state = { data: [], value: [], fetching: false, submitting: false, qiniuToken: null, loading: false } async componentDidMount() { axios_post('token/qiniu').then((data) => { this.setState({ qiniuToken: data.token }, () => { console.log('fdskjl', this.state) }) }) } fetchUser = () => { this.setState({ data: [], fetching: true }) axios_get('tag') .then(body => { const data = body.map(tag => ({ text: tag.name, value: tag.id, })) this.setState({ data, fetching: false }) }) } handleChange = info => { if (info.file.status === 'uploading') { this.setState({ loading: true }) return } if (info.file.status === 'done') { this.setState({ loading: false, imageHash: info.file.response.hash }) this.props.form.setFieldsValue({ cover: info.file.response.hash, }) } } handleSubmit = (event) => { event.preventDefault() this.props.form.validateFields((error, values) => { if (!error) { const submitData = { title: values.title, raw: values.content.toRAW(), html: values.content.toHTML(), tag: values.tag.map(item => item.key).join(','), cover: values.cover, status: 2 } this.setState({ submitting: true }) axios_post('note/add', submitData) .then(data => { }) .finally(() => { this.setState({ submitting: false }) }) } else { message.error('提交发生错误') } }) } myUploadFn = (param) => { const serverURL = QINIU_SERVER const xhr = new XMLHttpRequest const fd = new FormData() const token = this.state.qiniuToken const successFn = (response) => { param.success({ url: BASE_QINIU_URL + JSON.parse(xhr.responseText).hash + '?imageslim' }) } const progressFn = (event) => { // 上传进度发生变化时调用param.progress param.progress(event.loaded / event.total * 100) } const errorFn = (response) => { // 上传发生错误时调用param.error param.error({ msg: 'unable to upload.' }) } xhr.upload.addEventListener("progress", progressFn, false) xhr.addEventListener("load", successFn, false) xhr.addEventListener("error", errorFn, false) xhr.addEventListener("abort", errorFn, false) fd.append('file', param.file) fd.append('token', token) xhr.open('POST', serverURL, true) xhr.send(fd) } render() { const { getFieldDecorator } = this.props.form const { fetching, data, submitting, imageHash, qiniuToken, loading } = this.state const uploadButton = ( <div> <Icon type="plus" /> <div className="ant-upload-text">上传题图</div> </div> ) const editorProps = { media: { uploadFn: this.myUploadFn } } return ( <div className="g-write"> <Form onSubmit={this.handleSubmit} className="m-form"> <Form.Item style={{ marginBottom: 0 }}> {getFieldDecorator('cover', { rules: [{ required: false, message: '请上传题图' }], })( <div className="upload"> <div style={{ margin: '0 auto', textAlign: 'center' }}> <Spin spinning={loading}> <Upload name="file" listType="picture-card" className="avatar-uploader" showUploadList={false} action={QINIU_SERVER} data={{ token: qiniuToken }} onChange={this.handleChange} > {imageHash ? <img src={BASE_QINIU_URL + imageHash + '?imageslim'} alt="image" style={{ width: '100%' }} /> : uploadButton} </Upload> </Spin> </div> </div> )} </Form.Item> <Form.Item style={{ marginBottom: 5 }}> {getFieldDecorator('title', { rules: [{ required: true, message: '请输入标题' }], initialValue: '' })( <AntInput className="title-input" placeholder="请输入标题" />, )} </Form.Item> <Form.Item> {getFieldDecorator('content', { validateTrigger: 'onBlur', rules: [{ required: true, validator: (_, value, callback) => { if (value.isEmpty()) { callback('请输入正文内容') } else { callback() } } }], })( <BraftEditor {...editorProps} ref={instance => this.editorInstance = instance} className="m-editor" placeholder="请输入正文内容" /> )} </Form.Item> <Form.Item className="m-flex-row"> {getFieldDecorator('tag', { rules: [{ required: true, }], })( <Select size="large" mode="multiple" labelInValue placeholder="选择标签..." notFoundContent={fetching ? <Spin size="small" /> : null} filterOption={false} onSearch={this.fetchUser} style={{ width: '400px' }} > {data.map(d => ( <Option key={d.value}>{d.text}</Option> ))} </Select> )} <Button size="large" htmlType="submit" loading={submitting}>提交</Button> </Form.Item> </Form> </div> ) } } export default Write <file_sep>const Router = require('koa-router') const router = new Router({ prefix: '/v1/user' }) const { User } = require('../../models/user') const { RegisterValidator, UserModifyValidator } = require('../../validators/validator') const { success } = require('../../lib/helper') const { Auth } = require('../../../middlewares/auth') /** * 注册功能 */ router.post('/register', async (ctx, next) => { const v = await new RegisterValidator().validate(ctx) const user = { email: v.get('body.email'), password: <PASSWORD>('<PASSWORD>'), userName: v.get('body.username') } await User.create(user) success() }) router.post('/bind', new Auth().m, async (ctx) => { const v = await new UserModifyValidator().validate(ctx) await User.setEmailPwd(ctx.auth.uid, v.get('body')) success('绑定成功', {ok: 1}) }) /** * 获取用户信息 */ router.get('/info', new Auth().m, async ctx => { const user = await User.getUserInfo(ctx.auth.uid) success('登陆成功', user) }) /** * 用户信息编辑 */ router.post('/modify', new Auth().m, async ctx => { const v = await new UserModifyValidator().validate(ctx) await User.modifyInfo(v.get('body'), ctx.auth.uid) success('信息更新成功', {ok: 1}) }) /** * 用户所获得的所有点赞、收藏、文章总数接口 */ router.get('/status', new Auth().m, async ctx => { const r = await Promise.all([ User.likeTotal(ctx.auth.uid), User.collectTotal(ctx.auth.uid), User.noteTotal(ctx.auth.uid) ]) success(null, { likeNum: r[0], collectNum: r[1], noteNum: r[2] }) }) module.exports = router <file_sep>import React from 'react' import { Router, Route, Switch } from 'react-router-dom' import LoginGuard from './component/LoginGuard' import NavWrapper from './component/NavWrapper' import WaitingComponent from './component/WaitingComponent' import lazy from './util/lazy' import './style/global.less' const Find = lazy(() => import('./page/find')) const Write = lazy(() => import('./page/write')) const Profile = lazy(() => import('./page/profile')) const Login = lazy(() => import('./page/login')) const MyNote = lazy(() => import('./page/mynote')) const Note = lazy(() => import('./page/note')) const Edit = lazy(() => import('./page/edit')) const Setting = lazy(() => import('./page/setting')) import history from './history' class App extends React.Component { constructor(props) { super(props) } render() { return ( <Router history={history}> <div className='app-root'> <NavWrapper /> <div className="g-content"> <LoginGuard> <Switch> <Route exact path='/' component={WaitingComponent(Find)} /> <Route exact path='/login' component={WaitingComponent(Login)} /> <Route exact path='/find' component={WaitingComponent(Find)} /> <Route exact path='/write' component={WaitingComponent(Write)} /> <Route exact path='/mynote' component={WaitingComponent(MyNote)} /> <Route exact path='/profile' component={WaitingComponent(Profile)} /> <Route exact path='/note/:id' component={WaitingComponent(Note)} /> <Route exact path='/edit/:id' component={WaitingComponent(Edit)} /> <Route exact path='/setting' component={WaitingComponent(Setting)} /> </Switch> </LoginGuard> </div> </div> </Router> ) } } export default App <file_sep>const { db } = require('../../core/db') const { Sequelize, Model } = require('sequelize') const bcryptjs = require('bcryptjs') /** * User 模板,数据库生成user表 */ class User extends Model { /** * 验证邮箱口令 * @param email 邮箱 * @param plainPassword <PASSWORD> */ static async verifyEmailPassword(email, plainPassword) { const user = await User.findOne({ where: { email: email } }) // 没有对应用户 if (!user) { throw new global.errs.AuthFailed('账号不存在!') } const correct = bcryptjs.compareSync(plainPassword, user.password) if (!correct) { throw new global.errs.AuthFailed('密码不正确!') } return user } /** * 用户设置邮箱密码 * @param id 用户id */ static async setEmailPwd(id, info) { await User.update({ ...info }, { where: { id: id } }) } /** * github一键登录 * @param githubId github的用户id * @param userName github的用户名 * @param email github绑定的用户邮箱 */ static async getUserByGithubId(gitUser) { const user = await User.findOne({ where: { githubId: gitUser.id, } }) if (user) { return user } else { return await User.create({ githubId: gitUser.id, userName: gitUser.login, email: gitUser.email, avatar: gitUser.avatar_url, desc: gitUser.bio }) } } /** * 获取用户信息 * @param id 用户id */ static async getUserInfo(id) { return await User.findByPk(id) } /** * 修改用户信息 * @param info 更新信息 * @param id 用户id */ static async modifyInfo(info, id) { return await User.update({ ...info }, { where: { id: id } }) } /** * 获得用户被点赞总数接口 * @param id 用户id */ static async likeTotal(id) { // 防止循环引用 const { Note } = require('../models/note') const total = await Note.sum('like_num', { where: { author: id } }) return total } /** * 获得用户被收藏总数接口 * @param id 用户id */ static async collectTotal(id) { // 防止循环引用 const { Note } = require('../models/note') const total = await Note.sum('collect_num', { where: { author: id } }) return total } /** * 获得用户文章总数接口 * @param id 用户id */ static async noteTotal(id) { // 防止循环引用 const { Note } = require('../models/note') const total = await Note.count({ where: { author: id } }) return total } } User.init({ // 记录ID id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, // 用户名 userName: Sequelize.STRING(64), // 邮箱 email: { type: Sequelize.STRING, // 最大长度 unique: true, // 唯一 }, // 密码 password: { // 观察者模式 type: Sequelize.STRING(128), set(val) { const salt = bcryptjs.genSaltSync(10) // 10 表示生成盐的成本,越高越安全 const hashPassword = bcryptjs.hashSync(val, salt) this.setDataValue('passwordset', hashPassword) // this 代表User类 } }, // GitHubId githubId: { type: Sequelize.INTEGER, unique: true, // 唯一 }, // 真实姓名 realName: Sequelize.STRING(64), // 性别 sex: Sequelize.INTEGER, // 邮箱 email: Sequelize.STRING(255), // 专长 expertise: Sequelize.STRING(255), // 简介 desc: Sequelize.STRING(255), // 用户头像 avatar: Sequelize.STRING(255) }, { sequelize: db, tableName: 'user' }) module.exports = { User } <file_sep>const Router = require('koa-router') const router = new Router({ prefix: '/v1/tag' }) const { Tag } = require('../../models/tag') const { success } = require('../../lib/helper') const { Auth } = require('../../../middlewares/auth') const { TagAddValidator } = require('../../validators/validator') /** * 获取所有标签接口 */ router.get('/', async () => { const tags = await Tag.showTags() success(null, tags) }) /** * 自定义标签接口 */ router.post('/add', new Auth().m, async ctx => { const v = await new TagAddValidator().validate(ctx) const name = v.get('body.name') await Tag.addTags(name, 0) success() }) /** * 返回所有系统定义tags */ router.get('/getAllTags', new Auth().m, async ctx => { const tags = await Tag.showTags() success(null, tags) }) module.exports = router<file_sep>const { LinValidator, Rule } = require('../../core/lin-validator-v2') const { User } = require('../models/user') const { LoginType, ArtType } = require('../lib/enum') const { Note } = require('../models/note') const { Tag } = require('../models/tag') /** * 通用id校验 */ class PositiveIntegerValidator extends LinValidator { constructor() { super() this.id = [ new Rule('isInt', '需要正整数', { min: 1 }) ] } } /** * 注册校验器 */ class RegisterValidator extends LinValidator { constructor() { super() this.email = [ new Rule('isEmail', '不符合Email规范') ] this.password1 = [ new Rule('isLength', '密码长度为6~32字符', { min: 6, max: 32 }), new Rule('matches', '密码至少1个大写字母,1个小写字母和1个数字', /^[\w_-]{6,16}$/) ] this.password2 = <PASSWORD> this.username = [ new Rule('isLength', '昵称长度为4~32字符', { min: 4, max: 32 }) ] } // 校验两次密码是否相同方法 validatePassword(vals) { const pwd1 = vals.body.password1 const pwd2 = vals.body.password2 if (pwd1 !== pwd2) { throw new Error('两个密码必须相同') } } // 验证邮箱是被已被注册 async validateEmail(vals) { const email = vals.body.email const user = await User.findOne({ where: { email: email } }) // 如果已存在该Email if (user) { throw new Error('该Email已被注册!') } } } /** * 用户编辑校验器 */ class UserModifyValidator extends LinValidator { constructor() { super() } } /** * 标签添加校验器 */ class TagAddValidator extends LinValidator { constructor() { super() } } /** * 生成token校验器 */ class TokenValidator extends LinValidator { constructor() { super() this.account = [ new Rule('isLength', '不符合账号规则', { min: 4, max: 32 }) ] this.secret = [ new Rule('isOptional'), new Rule('isLength', '密码至少6个字符!', { min: 6, max: 128 }) ] } // 校验登录类型 validateLoginType(vals) { if (!vals.body.type) { throw new Error('缺少type参数') } if (!LoginType.isThisType(vals.body.type)) { throw new Error('type参数不合法') } } } /** * 不能为空校验器 */ class NotEmptyValidator extends LinValidator { constructor() { super() this.token = [ new Rule('isLength', '不允许为空', { min: 1 }) ] } } /** * 点赞校验器 * 点赞数必须为非负数 */ class LikeValidator extends PositiveIntegerValidator { constructor() { super() //this.validateType = checkArtType } } /** * Classic校验器 * 校验 type 和 id, 和 LikeValidator 一样,直接继承 */ class ClassicValidator extends LikeValidator { constructor() { super() this.validateType = checkArtType } } /** * 获取短评校验器 */ class AddShortCommentValidator extends PositiveIntegerValidator { constructor() { super() this.content = [ new Rule('isLength', '短评长度为1-24字符', { min: 1, max: 24 }) ] } } /** * 书籍搜索参数校验 */ class SearchValidator extends LinValidator { constructor() { super() // keyword 要查询的关键字 this.q = [ new Rule('isLength', '搜索关键字q不能为空', { min: 1, max: 16 }), ] // 分页: // 老版分页需要pageNum/perPage两个参数 // 现在一般用start/count两个参数 this.start = [ new Rule('isInt', '参数不合法', { min: 0, max: 60000 }), new Rule('isOptional', '', 0), // 不传start的话,默认给个0 ] this.count = [ new Rule('isInt', '参数不合法', { min: 1, max: 20 }), new Rule('isOptional', '', 20), // 不传count的话,默认给个20 ] } } /** * 新增文章校验 */ class AddNoteValidator extends LinValidator { constructor() { super() this.title = [ new Rule('isLength', '文章标题须在1-32个字符之间', { min: 1, max: 32 }) ] this.tag = [ new Rule('isLength', '需要TagsID序列', { min: 1, max: 50 }) ] this.status = [ new Rule('isInt', '需要正整数且为1或2', { min: 1, max: 2 }) ] } } /** * 发布文章,即将文章状态从草稿改为发布 */ class PublishNoteValidator extends PositiveIntegerValidator { constructor() { super() } // 这样写主要还是防止他人直接通过id来更改状态,所以校验id与作者id是否匹配 async validateNote(vals) { const id = vals.body.id const writerId = vals.body.writerId const note = await Note.findOne({ id: id, writerId: writerId }) if (!note) { throw new Error('系统异常,需要发布的文章与当前用户不匹配') } else if (!(note.raw && note.html)) { throw new Error('不可文章内容不得为空') } } } /** * Note类基础校验器 */ class NoteValidator extends LinValidator { constructor() { super() } } /** * Note更新校验器 */ class NoteUpdateValidator extends PositiveIntegerValidator { constructor() { super() this.title = [ new Rule('isLength', '文章标题须在1-32个字符之间', { min: 1, max: 32 }) ] this.tag = [ new Rule('isLength', '需要TagsID序列', { min: 1, max: 50 }) ] } } /** * Tags类基础校验器 */ class TagsValidator extends LinValidator { constructor() { super() } async validateTag(vals) { const name = vals.body.name const tag = await Tag.findOne({ where: { name: name } }) if (tag) { throw new Error('此Tag已存在') } } } /** * loginType 检查 * @param vals */ function checkLoginType(vals) { const type = parseInt(vals.body.type || vals.path.type) if (!type) { throw new Error('缺少loginType参数') } if (!LoginType.isThisType(type)) { throw new Error('loginType参数不合法') } } /** * artType 检查 * @param vals */ function checkArtType(vals) { const type = parseInt(vals.body.type || vals.path.type) if (!type) { throw new Error('缺少artType参数') } if (!ArtType.isThisType(type)) { throw new Error('artType参数不合法') } } module.exports = { PositiveIntegerValidator, RegisterValidator, TokenValidator, NotEmptyValidator, LikeValidator, ClassicValidator, SearchValidator, AddShortCommentValidator, AddNoteValidator, PublishNoteValidator, NoteValidator, UserModifyValidator, TagAddValidator, } <file_sep>import { qiniu } from '../secret'; export const MENU_MAIN = [ { title: '发现', icon: 'lightbulb outline', path: '/' }, { title: '我的笔记', icon: 'book', path: '/mynote' }, ]; export const FIND_MENU = [ { title: '所有', key: 'all', icon: '' }, { title: '标签', key: 'tag', icon: '' }, ]; export const SYSTEM_CONFIG = { github: { // client_id: '907e089d8acd7d59d6ea', client_id: '00d361bef1a3c27055fd', scope: 'user:email', }, qiniu: { AccessKey: '<KEY>', SecretKey: qiniu.SecretKey, BASE_QINIU_URL: 'http://qn-noter.yunxi.site/', QINIU_SERVER: 'https://upload-z2.qiniup.com', }, }; <file_sep>import { action, observable, reaction, runInAction } from 'mobx' import { axios_get, axios_post } from '../util/axios' class NoteStore { @action getNotes = () => { } @action getNotesMine = () => { } } export default new NoteStore() <file_sep># Noter ## 服务端架构 ![image.png](https://i.loli.net/2019/12/23/tUmcZPMHG7sVNwJ.png) ![@7R_VODYJ9P2PF_HB___NQC.png](https://i.loli.net/2019/12/23/4hCmX5dyPUAjuoc.png) ![__2_UPA5MH__DH70PO_071L.png](https://i.loli.net/2019/12/23/cVIAQ82Ty4mNUKJ.png) ![OPZI_1W_1KNJRHOV_D@O49T.png](https://i.loli.net/2019/12/23/tPXNOljIThSEL6z.png) ![UE3RW5T_6_8D6KOC__S@UU0.png](https://i.loli.net/2019/12/23/fgxz8I9PT42SKnJ.png) ![9_VN7DR_OX__N_IC__W583V.png](https://i.loli.net/2019/12/23/cBKatnh8pjoPYEy.png) ## 代码实现 ### 服务端 - Node.js:**Koa** - ORM:**Sequelize** - 代码规范 / 格式化:**ESLint** - 加密:**bcrypt.js** - 参数校验:**validator.js** - 数据模拟:**Faker.js** ### 其它 - 数据库:**MySQL 5.7** - 服务器:**Nginx 反向代理** - 进程守护:**PM2** ### 前端 - React - AntD + Semantic UI ## 功能 #### 业务 - 作为一个内容型网站所必须的CRUD - 发现 - 所有笔记 - 根据标签筛选笔记 - 最热、精选列表 - 点赞、收藏数目 - 我的笔记 - 编辑我的笔记 - 删除我的笔记 - 查看笔记 - 点赞、收藏 - 写文章(**富文本编辑器**) - 个人主页 - 个人成就 - 个人信息 - 账号设置 - Github **OAuth2 一键登录** - **全局消息提示** - **全局请求异常拦截**(axios 拦截器) - 例如未登录——提示并跳转登录页 #### 系统 - 服务端全局异常处理 - 路由参数自定义校验 - Token 令牌认证机制 - 鉴权(游客、用户) - 记住用户,自动登录 - 图片采用七牛云OSS + 压缩 + **懒加载**,减少服务端下行压力 ## 内存 前端打包大小约 **5MB** 服务端打包约 **12MB**,运行时内存约 **40MB** ## 响应时间 服务器响应 < **30ms** 最复杂页面约 **1.5S** 已缓存情况下网页加载**< 150ms** ## 解决的大问题 #### OAuth2 登录 采用相对复杂和严格的授权码模式。 通过客户端的后台服务器,与"服务提供商"的认证服务器进行互动。 https://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html #### 大量的图片 内容型网站,大量图片需要加载。 使用七牛云 OSS 对象存储,配合图片压缩解决,不受限于 1Mbps 带宽。 #### 响应速度慢 **减小首屏加载速度** - 路由拆分 + 懒加载 - nginx 缓存 - 减小请求响应体积 **减少打包大小** - 大型库使用替代版本(moment.js => day.js) - Webpack rewireUglifyjs 插件 -50% - CDN 引入库文件 - 删除SourceMap文件 - 60% #### 刷新404 前端路由,刷新会服务器请求真实路径,结果404。 采用 History + Nginx 配置解决。 ### 富文本编辑器适配 原本的编辑器很好用,但是仍然需要自定义一些功能。 <file_sep>const qiniu = require('qiniu') qiniu.conf.ACCESS_KEY = '<KEY>' qiniu.conf.SECRET_KEY = '<KEY>' const bucket = 'noter-v2' const getToken = () => { const putPolicy = new qiniu.rs.PutPolicy({ scope: bucket }) return putPolicy.uploadToken() } module.exports = { getToken }<file_sep>const Router = require('koa-router') const router = new Router({ prefix: '/v1/favor' }) const { Auth } = require('../../../middlewares/auth') const { LikeValidator } = require('../../validators/validator') const { Favor } = require('../../models/favor') const { success } = require('../../lib/helper') /** * note点赞接口 */ router.get('/like/:noteId', new Auth(8).m, async ctx => { const v = await new LikeValidator().validate(ctx, { id: 'noteId' }) await Favor.like( ctx.auth.uid, v.get('path.noteId') ) success('点赞成功', {ok: 1}) }) /** * note取消点赞接口 */ router.get('/dislike/:noteId', new Auth(8).m, async ctx => { const v = await new LikeValidator().validate(ctx, { id: 'noteId' }) await Favor.dislike( ctx.auth.uid, v.get('path.noteId') ) success('取消点赞成功', {ok: 1}) }) /** * note收藏接口 */ router.get('/collect/:noteId', new Auth(8).m, async ctx => { const v = await new LikeValidator().validate(ctx, { id: 'noteId' }) await Favor.collect( ctx.auth.uid, v.get('path.noteId') ) success('收藏成功', {ok: 1}) }) /** * note取消收藏接口 */ router.get('/disCollect/:noteId', new Auth(8).m, async ctx => { const v = await new LikeValidator().validate(ctx, { id: 'noteId' }) await Favor.cancelCollect( ctx.auth.uid, v.get('path.noteId') ) success('取消收藏成功', {ok: 1}) }) module.exports = router <file_sep>const { Sequelize, Model, Op } = require('sequelize') const { db } = require('../../core/db') const { Tag } = require('../models/tag') /** * 笔记文章业务 */ class Note extends Model { /** * 用于JSON序列化 */ toJSON() { let origin = { id: this.id, title: this.title, raw: this.raw, html: this.html, author: this.writerId, tag: this.tag, likeNum: this.likeNum, collectNum: this.collectNum }; return origin; } /** * 新增文章,存草稿或者直接发布 */ static async addNote(note) { return await Note.create({ ...note }) } /** * 按更新时间降序排序 */ static async showAllNotes(content = true) { let sql = ` SELECT u.user_name, u.avatar, n.* FROM note n LEFT JOIN user u ON n.author = u.id order by n.created_at DESC ` if (!content) { sql = ` SELECT u.user_name, u.avatar, n.title,n.id,n.author,n.created_at,n.like_num,n.collect_num,n.tag,n.cover FROM note n LEFT JOIN user u ON n.author = u.id order by n.created_at DESC ` } let notes = await db.query(sql, { raw: true }) notes = this.common(notes) return notes } /** * 按更新时间降序排序 */ static async showHotNotes() { let notes = await db.query( ` SELECT u.user_name, u.avatar, n.title,n.tag,n.id FROM note n LEFT JOIN user u ON n.author = u.id order by n.updated_at DESC LIMIT 0,3 ` , { raw: true }) notes = this.common(notes) return notes } /** * 按点赞数目降序排序 */ static async showLikedNotes() { let notes = await db.query( ` SELECT u.user_name, u.avatar, n.* FROM note n LEFT JOIN user u ON n.author = u.id order by n.like_num DESC ` , { raw: true }) notes = this.common(notes) return notes } /** * 按收藏数目降序排序 */ static async showCollectedNotes() { let notes = await db.query( ` SELECT u.user_name, u.avatar, n.* FROM note n LEFT JOIN user u ON n.author = u.id order by n.collect_num DESC ` , { raw: true }) notes = this.common(notes) return notes } /** * 按标题搜索文章(模糊查询),按更新时间降序排序 * @param title */ static async queryNoteByTitle(title) { let notes = await db.query( ` SELECT u.user_name, u.avatar, n.* FROM note n LEFT JOIN user u ON n.author = u.id WHERE n.title LIKE '%${title}%' order by n.created_at DESC ` , { raw: true }) notes = this.common(notes) return notes } /** * 查询用户所有文章,降序排序 * @param id 用户ID */ static async queryNoteByAuthor(id) { let notes = await db.query( ` SELECT u.user_name, u.avatar, n.* FROM note n LEFT JOIN user u ON n.author = u.id WHERE n.author = ${id} order by n.created_at DESC ` , { raw: true }) notes = this.common(notes) return notes } /** * 查询文章详情 * @param id */ static async queryNoteById(id) { let content = await db.query( ` SELECT n.title,n.cover,n.html,n.tag,n.like_num,n.collect_num,u.avatar,n.author,n.created_at,u.user_name FROM note n LEFT JOIN user u ON n.author = u.id WHERE n.id = ${id} ` ) content = content[0][0] let tagObj = {} await Tag.findAll({ raw: true }).map(item => { tagObj[item.id] = item.name }) let tagIds = content.tag.split(',').map(item => { return { id: item, name: tagObj[item] } }) content.tag = tagIds return content } /** * 文章的删除操作,同时通过事务删除点赞收藏表中的数据 * @param id 用户ID */ static async deleteNote(id) { const note = await Note.findByPk(id) if (!note) { throw new global.errs.NotFound('Note is not found!') } // 局部引用、防止循环引用 const { Favor } = require('../models/favor') db.transaction(async t => { await note.destroy({ force: true, transaction: t }) return await Favor.destroy({ where: { artId: id }, force: true, transaction: t }) }) } /** * 申请编辑文章方法 * @param noteId 需要编辑的文章id * @param id 当前登陆用户id * 返回笔记的raw */ static async modifyNote(noteId, id) { const content = await Note.findByPk(noteId, { attributes: { exclude: ['html'] }, raw: true }) if (!content) { throw new global.errs.NotFound('文章不存在') } else if (content.author !== id) { throw new global.errs.NoteError('这不是您的文章') } return content } /** * 更新文章 * @param note 文章实体 */ static async updateNote(note) { const oldNote = Note.findByPk(note.id) if (!oldNote) { throw new global.errs.NotFound() } Note.update({ ...note }, { where: { id: note.id } }) } /** * 判断文章是否被当前用户点赞 * @param uid 当前登录用户 * @param noteId 文章id */ static async isLike(uid, noteId) { const { Favor } = require('../models/favor') let like = await Favor.findOne({ where: { uid: uid, artId: noteId, type: 1 } }) if (like) { return true } else { return false } } /** * 判断文章是否被当前用户收藏 * @param uid 当前登录用户 * @param noteId 文章id */ static async isCollect(uid, noteId) { const { Favor } = require('../models/favor') let collect = await Favor.findOne({ where: { uid: uid, artId: noteId, type: 2 } }) if (collect) { return true } else { return false } } /** * 根据标签获取文章 * @param tag */ static async queryNoteByTag(tag) { let data = [] let notes = await db.query( ` SELECT u.user_name, u.avatar, n.title,n.id,n.author,n.created_at,n.like_num,n.collect_num,n.tag,n.cover FROM note n LEFT JOIN user u ON n.author = u.id order by n.created_at DESC ` , { raw: true }) notes = notes[0] notes.map(item => { let flag = item.tag.split(',').indexOf(String(tag)) if (flag !== -1) { data.push(item) } }) return this.common([data]) } /** * 获取文章视图公共方法 * @param notes */ static async common(notes) { let tagObj = {} await Tag.findAll({ raw: true }).map(item => { tagObj[item.id] = item.name }) notes = notes[0].map(item => { let tags = item.tag.split(',').map(item => { return { id: item, name: tagObj[item] } }) item.tags = tags return item }) return notes } } Note.init({ // 记录ID id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, // 标题 title: Sequelize.STRING(255), // 文章封面 cover: Sequelize.STRING(255), // json内容 raw: Sequelize.TEXT, // html内容 html: Sequelize.TEXT, // 作者Id author: Sequelize.INTEGER, // 文章类型 tag: Sequelize.STRING(100), // 点赞数量 likeNum: { type: Sequelize.INTEGER, defaultValue: 0 }, // 收藏数量 collectNum: { type: Sequelize.INTEGER, defaultValue: 0 }, // 所处状态 status: { type: Sequelize.INTEGER, defaultValue: 1 //处于草稿状态 } }, { sequelize: db, tableName: 'note' }) module.exports = { Note } <file_sep>const Sequelize = require('sequelize') const { dbName, user, pwd, host, port } = require('../config/config').database const { Model } = require('sequelize') const { unset, clone, isArray } = require('lodash') /** * Sequelize数据库配置 */ const db = new Sequelize(dbName, user, pwd, { dialect: 'mysql', // 数据库类型 host: host, port: port, logging: false, // console中是否显示具体sql timezone: '+08:00', // 设置东八时区,重要 define: { timestamps: true, paranoid: true, underscored: true, // 自动将驼峰转下划线 scopes: { noTS: { attributes: { exclude: ['updatedAt', 'deletedAt', 'createdAt'] } } } } }) db.sync({ force: false }) /** * 全局:返回的时候删除三个时间戳 * 功能简单粗暴单一 */ Model.prototype.toJSON = function () { let data = clone(this.dataValues) unset(data, 'updatedAt') unset(data, 'createdAt') unset(data, 'deletedAt') for (let key in data) { if (key === 'image') { data[key] = global.config.host + data[key] } } // 待删除字段 if (isArray(this.exclude)) { this.exclude.forEach(val => { unset(data, val) }) } return data } module.exports = { db } <file_sep>import authStore from './auth' import userStore from './user' export default { authStore, userStore } <file_sep>const Router = require('koa-router') const router = new Router({ prefix: '/v1/upload' }) const path = require('path') const send = require('koa-send') /** * 获取静态资源接口 */ router.get('/:filename', async (ctx) => { const filename = ctx.params.filename await send(ctx, filename, { root: path.resolve(__dirname, '../../../upload') }) }) module.exports = router<file_sep>/** * JS类来模拟枚举 */ /** * 登录方式枚举类 * @type {{USER_MINI_PROGRAM: number, USER_EMAIL: number, USER_MOBILE: number, ADMIN_EMAIL: number}} */ const LoginType = { USER_MINI_PROGRAM: 100, // 小程序登录 USER_EMAIL: 101, // 邮箱登录 USER_MOBILE: 102, // 手机号登录 ADMIN_EMAIL: 200, // 管理员邮箱登录 isThisType } /** * Art类型枚举类 * @type {{MUSIC: number, MOVIE: number, BOOK: number, SENTENCE: number}} */ const ArtType = { MOVIE: 100, MUSIC: 200, SENTENCE: 300, BOOK: 400, isThisType } /** * 判断val是否属于该类型 * @param val * @returns {boolean} */ function isThisType(val) { for (let key in this) { if (this[key] === val) { return true } } return false } module.exports = { LoginType, ArtType, } <file_sep>const Router = require('koa-router') const { TokenValidator, NotEmptyValidator } = require('../../validators/validator') const { LoginType } = require('../../lib/enum') const { User } = require('../../models/user') const router = new Router({ prefix: '/v1/token' }) const { generateToken } = require('../../../core/util') const { Auth } = require('../../../middlewares/auth') const { MXManager } = require('../../services/wx') const { github } = require('../../../config/config') const { success } = require('../../lib/helper') const { getToken } = require('../../services/qiniu') const axios = require('axios') /** * 校验令牌 */ router.post('/', async (ctx) => { // API 有权限,非公开API必须携带令牌才能访问 // 如果令牌过期或者不合法,则禁止访问该非公开API const v = await new TokenValidator().validate(ctx) let token switch (v.get('body.type')) { case LoginType.USER_EMAIL: token = await emailLogin(v.get('body.account'), v.get('body.secret')) break case LoginType.USER_MINI_PROGRAM: token = await MXManager.codeToToken(v.get('body.account')) break default: throw new global.errs.ParameterException('没有响应的异常处理函数') } ctx.body = { code: 200, data: { token }, message: null } }) /** * 验证令牌接口 */ router.post('/verify', async (ctx) => { const v = await new NotEmptyValidator().validate(ctx) const res = Auth.verifyToken(v.get('body.token')) ctx.body = { result: res } }) /** * github一键登录接口 */ router.get('/github', async ctx => { const code = ctx.query.code const r = await axios.post('https://github.com/login/oauth/access_token', { client_id: github.client_id, client_secret: github.client_secret, code: code }) if (r && r.status === 200) { if (r.data.split('=')[0] === 'access_token') { const tr = await axios.get('https://api.github.com/user?' + r.data) if (tr && tr.status === 200) { const { token, user } = await githubLogin(tr.data) success(user.userName + '欢迎您', { token, user, type: 233 }) } } else { throw new global.errs.Forbidden() } } }) /** * 验证令牌接口 */ router.post('/qiniu', async (ctx) => { const token = getToken() success(null, { token }) }) /** * 校验用户账号密码是否和数据库中一致, * 如果一致,则颁布一个令牌 * * @param account * @param secret * @returns {Promise<void>} */ async function emailLogin(account, secret) { const user = await User.verifyEmailPassword(account, secret) return generateToken(user.id, Auth.USER) } /** * 用户github登录方法 * @param githubId */ async function githubLogin(gitUser) { const user = await User.getUserByGithubId(gitUser) const token = generateToken(user.id, Auth.USER) return { token, user } } module.exports = router <file_sep>import dayjs from 'dayjs' // 5天毫秒数 const DAY_5 = 24 * 60 * 60 * 1000 // 友好地显示时间:刚刚、几分钟前、几天前等 export function dateToFromNow(date) { let ret // 五天内显示相对时间 if (new Date() - date < DAY_5) { ret = dayjs(date).fromNow() } else { ret = dayjs(date).format('YY/MM/DD') } return ret } <file_sep>import React from 'react' import './style.less' import { Icon as SemiIcon } from 'semantic-ui-react' import { Icon } from 'antd' import { Link } from 'react-router-dom' const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop if (c > 0) { window.requestAnimationFrame(scrollToTop) window.scrollTo(0, c - c / 8) } } export default () => ( <div className="g-fixedbar"> <Link to='/write'> <div className="m-icon m-red" onClick={() => { }}> <Icon type="edit" /> </div> </Link> <div className="m-icon m-grey" onClick={() => { scrollToTop() }} > <SemiIcon name="arrow up" /> </div> </div> )
c3f034f1ab8885928800f19d9f4c3d37022edf14
[ "JavaScript", "Markdown" ]
36
JavaScript
HytonightYX/noter-v2
0ddd29d0b1abaa97014af124ff62739079d85f1f
9a2b8913bf21056518bac697512f3623b9995559
refs/heads/master
<file_sep>import java.util.ArrayList; public class StackDetails { private int maxHeight; private int totBlocks; private int maxIndex; private ArrayList<ArrayList<Block>> stack = new ArrayList<ArrayList<Block>>(); public StackDetails(int maxHeight, int totBlocks, ArrayList<ArrayList<Block>> stack, int maxIndex) { this.setMaxHeight(maxHeight); this.setTotBlocks(totBlocks); this.setStack(stack); this.setMaxIndex(maxIndex); } public int getMaxHeight() { return maxHeight; } public void setMaxHeight(int maxHeight) { this.maxHeight = maxHeight; } public int getTotBlocks() { return totBlocks; } public void setTotBlocks(int totBlocks) { this.totBlocks = totBlocks; } public ArrayList<ArrayList<Block>> getStack() { return stack; } public void setStack(ArrayList<ArrayList<Block>> stack) { this.stack = stack; } public int getMaxIndex() { return maxIndex; } public void setMaxIndex(int maxIndex) { this.maxIndex = maxIndex; } } <file_sep># algorithmsAssignment11 ## Each File There are three files that we are submitting: Block.java, BlockStackingProblem.java, and StackDetails.java. The Block class represents a block object, which is used to instantiate the length, width, height, and baseArea of a block. The purpose of the StackDetails class is to be able to store all the outputs that we want such as the number of blocks used, maximum height, and the different blocks and their respective orientations used to achieve this maximum height. The BlockStackingProblem is the main class that calculates the maxHeight that can be produced with the given block dimensions. ## How to compile and run code To compile this code, you first clone the repository onto your desktop. BlockStackingProblem.java and Block.java should be in your src folder. You should put your input file in this folder as well. If not you can use the "mv" command to move it to the same folder that has the java files. Once this is done, you open up your terminal and "cd" into the folder containing the java files--perhaps the src folder. Compile the java code with the following command: javac Block.java Then, javac StackDetails.java Finally, javac BlockStackingProblem.java You should now have a Block.class file, StackDetails.class, and BlockStackingProblem.class file in the folder. You can check by writing "ls" in the command line. Finally you run the java program with the file you're reading and the file you're outputting by typing the following command: java BlockStackingProblem "inputfilename.txt" "outputfilename.txt" You should see your output file in the folder. <file_sep>## Description of Algorithm 1) Our algorithm generates the 3 different orientations that are possible for each of the blocks that are given. This means that there are 3 different combinations of a base area and a height because a block has a length, width, and a height, but the block can also be oriented such that the length or width can also be the height. 2) Then, organize the base areas of each respective orientation in descending order. 3) Block Stacking Problem(i)= {Maximum(Block Stacking Problem(j)) + height(i) such that j < i, width(j) > width(i), length(j) > length(i). To summarize what this means, it is just the maximum height with box i at the top of the stack. 4) Finally, the overall maximum is the maximum of doing Block Stacking Problem(i) from 0<i<n where n is the total orientations of all boxes. <br /> This is correct because the solution to this problem exhibits optimal substructure. The algorithm breaks this down into smaller sub problems by starting with the orientation with the largest base area. Then, in descending order, finding the heights of the blocks that are allowed to be stacked below it and adding up those heights for that respective block orientation. Finally we are finding the top block orientation that allowed for the maximum height. <br /> The time complexity of this algorithm is O(n^2) because for each block orientation, we check the maximum height they can achieve based on all the maximum heights of the block orientations that have a greater base area than it, and add the maximum if it satisfies the conditions that the length and width are larger than it. We know this is O(n^2), where n is the total numer of block orientations, because in our code implementation, this part was done in a nested for loop where we iterated through each block orientation and then found the max heights of the blocks that came before it (which have a smaller base area). ## Interesting Design Decision Our interesting design decision was that we chose to optimize the maximum in a bottom up manner, instead of a top down manner. We chose to do it in a bottom up manner so that we can add the maximum height that is acheived from block orientations that have a larger base area and add it to the block that the iteration is on. We decided against a top down manner to avoid having to recalculate duplicate work. ## Overview of code implementing algorithm Our code implements the first part of our algorithm with the method maximumHeight in the BlockStackingProblem class. In that class, we get the blocks different orientations and then store them in an array. In that same method, we sort the array using the sort method to get the blocks in order based on their base. Then finally, we calculate the max height that can be obtained for every block orientation at the top, and any blocks with a smaller base area goes below it. ## How we tested our code and the results We tested our code by making a sample input file with the following input 10 <br /> 383 886 777 <br /> 915 793 335 <br /> 386 492 649 <br /> 421 362 27 <br /> 690 59 763 <br /> 926 540 426 <br /> 172 736 211 <br /> 368 567 429 <br /> 782 530 862 <br /> 123 67 135 <br /> and ensured that we got the following output, as well as a height of 5588: 12 <br /> 793 915 335<br /> 782 862 530<br /> 530 782 862<br /> 492 649 386<br /> 429 567 368<br /> 426 540 926<br /> 386 492 649<br /> 368 429 567<br /> 362 421 27<br /> 172 211 736<br /><br /> 123 135 67<br /> 67 123 135<br /> This was the first sample file that was given to us, and we also tested it on the second sample file. We made sure that the output that we got was the same output that was in the output file given to us. We ran the program with this input file and wrote to an output file, seeing if we got the expected output. If we got this number in our output file, we knew our algorithm succesfully worked. Otherwise, we edited our algorithm. In addition, we tested it on potential edge cases that we found, and made sure that the algorithm was consistent for all cases.
5040b86a5764b4fb516727e8cb49125fd817ef8c
[ "Markdown", "Java" ]
3
Java
kielong/algorithmsAssignment11
3c3b7f90c4dbb387713eea4f50cfdbe1e012eadf
37e58baab0377b941520f22026f991afc28c00ba
refs/heads/master
<file_sep>import styled from 'styled-components' import colors from './../styles/colors' export default styled.h2` padding-bottom: .3em; font-size: 1.5em; color: ${colors.main}; border-bottom: 1px solid ${colors.main}; ` <file_sep>import styled from 'styled-components' export const BitcoinIcon = styled.img` height: 45px; margin-top: 10px; float: left; margin-right: 10px; ` export const PageTitle = styled.h1` margin-left: 20px; margin-top: 0px; font-size: 1.5em; ` <file_sep>import styled from 'styled-components' export default styled.div` padding: 1.5em; ` <file_sep># bitcoin-stats https://zamarrowski.github.io/bitcoin-stats/ <file_sep>import React from 'react' import Paper from 'material-ui/Paper' import TextField from 'material-ui/TextField' import Ionicon from 'react-ionicons' import { ExchangeRateContainer, MoneyTitle, Label, Value } from './styles' import colors from './../styles/colors' const getIcon = (newValue, lastValue) => { if (newValue > lastValue) { return 'ios-arrow-dropup-circle' } else if (newValue < lastValue) { return 'ios-arrow-dropdown-circle' } } const getColor = (newValue, lastValue) => { if (newValue > lastValue) { return colors.secondary } else if (newValue < lastValue) { return colors.red } } export default props => <ExchangeRateContainer> <Paper style={{padding: '10px'}} zDepth={1}> <MoneyTitle> {props.newInfo.symbol} - {props.name} <Ionicon fontSize="1.3em" style={{ marginLeft: '5px', verticalAlign: 'bottom'}} icon={getIcon(props.newInfo.last, props.oldInfo.last)} color={getColor(props.newInfo.last, props.oldInfo.last)} /> </MoneyTitle> <div> <Label>Value: </Label> <Value>{props.newInfo['last']}{props.newInfo.symbol}</Value> </div> <div> <p>Convert {props.name} to Bitcoin:</p> <TextField hintText="Quantity" fullWidth={true} onChange={(e, value) => props.onTypeQuantity(value, props.name)} /><br /> In BTC {props.toBTC} </div> </Paper> </ExchangeRateContainer> <file_sep>import React, { Component } from 'react' import AppBar from 'material-ui/AppBar' import { BitcoinIcon, PageTitle } from './styles' import bitcoinImage from './../images/icon_bitcoin.png' class Header extends Component { render() { return ( <div> <AppBar title={ <div> <BitcoinIcon src={bitcoinImage}/> <PageTitle>Bitcoin stats</PageTitle> </div> } showMenuIconButton={false} /> </div> ) } } export default Header <file_sep>import React, { Component } from 'react' import Ionicon from 'react-ionicons' import { Container } from './styles' import ExchangeRate from './../ExchangeRate/ExchangeRate' import TitleSection from './../common/TitleSection' import colors from './../styles/colors' import exchangeRatesServices from './exchangeRates.services' class ExchangeRatesContainer extends Component { constructor() { super() this.state = { oldExchangeRates: null, newExchangeRates: null, toBTC: {} } } componentDidMount() { this._getExchanges() setInterval(() => { this._getExchanges() }, 5000) } render() { return( <div> <TitleSection> <Ionicon icon="md-globe" color={colors.main} style={{verticalAlign: "bottom", marginRight: "5px"}} fontSize="1.2em" /> Exchange rates </TitleSection> <Container> {Object.keys(this.state.newExchangeRates || {}).map((key, index) => ( <ExchangeRate name={key} newInfo={this.state.newExchangeRates[key] || {}} oldInfo={this.state.oldExchangeRates[key] || {}} key={index} toBTC={this.state.toBTC[key]} onTypeQuantity={this._getExchange.bind(this)} /> ))} </Container> </div> ) } _getExchange(value, currency) { value = Number(value) if (value) { exchangeRatesServices.convertToBTC(value, currency).then(response => { let toBTC = Object.assign({}, this.state.toBTC) toBTC[`${currency}`] = response this.setState({ toBTC }) }) } } _getExchanges() { exchangeRatesServices.getExchangeRates().then(exchangeRates => { if (!this.state.newExchangeRates) { this.setState({ newExchangeRates: exchangeRates, oldExchangeRates: exchangeRates }) } else { this.setState((state) => { return { newExchangeRates: exchangeRates, oldExchangeRates: state.newExchangeRates } }) } }) } } export default ExchangeRatesContainer <file_sep>import axios from 'axios' export default { getExchangeRates: () => { return axios.get('https://blockchain.info/es/ticker').then(response => { return response.data }) }, convertToBTC: (value, currency) => { return axios.get(`https://blockchain.info/tobtc?currency=${currency}&value=${value}`).then(response => { return response.data }) } }
3d6535eb286d37abf1df043331301b4224487008
[ "JavaScript", "Markdown" ]
8
JavaScript
zamarrowski/bitcoin-stats
03b0a2cb7a2226592473678396a7ae9c57b5af9d
991ccfcab8fa9acf6b6bec971a026cfb66a1e1f6
refs/heads/master
<file_sep>#include <iostream> #include <stdlib.h> #include <time.h> #include <math.h> #include <vector> #include <memory> #include <iomanip> using namespace std; int ** RandomMatrix(int size, int range) { int ** matrix; matrix = new(int * [size]); for(int i=0; i<size; i++) matrix[i] = new(int [size]); srand(time(NULL)); for(int i=0; i<size; i++) for(int j=0; j<size; j++) matrix[i][j] = rand() % range; return matrix; } int * ColumnSum(int **matrix, int size) { int *sum; return sum; } int * RowSum(int **matrix, int size) { int *sum; return sum; } typedef vector< int > IntRow; typedef vector< IntRow > IntTable; auto_ptr< IntTable > getZigZagArray( int dimension ) { auto_ptr< IntTable > zigZagArrayPtr( new IntTable( dimension, IntRow( dimension ) ) ); // fill along diagonal stripes (oriented as "/") int lastValue = dimension * dimension - 1; int currNum = 1; int currDiag = 0; int loopFrom; int loopTo; int i; int row; int col; do { if ( currDiag < dimension ) // if doing the upper-left triangular half { loopFrom = 0; loopTo = currDiag; } else // doing the bottom-right triangular half { loopFrom = currDiag - dimension + 1; loopTo = dimension - 1; } for ( i = loopFrom; i <= loopTo; i++ ) { if ( currDiag % 2 == 0 ) // want to fill upwards { row = loopTo - i + loopFrom; col = i; } else // want to fill downwards { row = i; col = loopTo - i + loopFrom; } ( *zigZagArrayPtr )[ row ][ col ] = currNum++; } currDiag++; } while ( currDiag <= lastValue ); return zigZagArrayPtr; } auto_ptr< IntTable > getInverseZigZagArray( int dimension ) { auto_ptr< IntTable > zigZagArrayPtr( new IntTable( dimension, IntRow( dimension ) ) ); // fill along diagonal stripes (oriented as "/") int lastValue = dimension * dimension - 1; int currNum = 1; int currDiag = 0; int loopFrom; int loopTo; int i; int row; int col; do { if ( currDiag < dimension ) // if doing the upper-left triangular half { loopFrom = 0; loopTo = currDiag; } else // doing the bottom-right triangular half { loopFrom = currDiag - dimension + 1; loopTo = dimension - 1; } for ( i = loopFrom; i <= loopTo; i++ ) { if ( currDiag % 2 == 0 ) // want to fill upwards { row = loopTo - i + loopFrom; col = i; } else // want to fill downwards { row = i; col = loopTo - i + loopFrom; } ( *zigZagArrayPtr )[ col ][ row ] = currNum++; } currDiag++; } while ( currDiag <= lastValue ); return zigZagArrayPtr; } void printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr ) { size_t dimension = zigZagArrayPtr->size(); int fieldWidth = static_cast< int >( floor( log10( static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; size_t col; for ( size_t row = 0; row < dimension; row++ ) { for ( col = 0; col < dimension; col++ ) cout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ]<< "\t"; cout << endl; } } void printZigZagLine( const auto_ptr< IntTable >& zigZagArrayPtr ) { size_t dimension = zigZagArrayPtr->size(); int fieldWidth = static_cast< int >( floor( log10( static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; size_t col; for ( size_t row = 0; row < dimension; row++ ) { for ( col = 0; col < dimension; col++ ) cout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ]<< " "; //cout << endl; } } int **ZigZagMatrix(int size, int order) { if(order==1){ printZigZagArray( getZigZagArray(size) ); } else if(order==2){ printZigZagArray( getInverseZigZagArray(size) ); } else{ cout << "you entered a wrong order" << endl; } } int **ZigZagLine(int size, int order) { if(order==1){ printZigZagLine( getZigZagArray(size) ); } else if(order==2){ printZigZagLine( getInverseZigZagArray(size) ); } else{ cout << endl; } } int main(int argc, char** argv) { int s, r; int **data; int *t; int order; cout << "Input the matrix size: "; cin >> s; cout << "Input the range of every matrix element: "; cin >> r; cout << "Input the zigzag matrix order(1 or 2): "; cin >> order; cout << "The Zigzag matrix is " << endl; int **zz = ZigZagMatrix(s,order); cout << endl; cout << "The Zigzag matrix in line is " << endl; int **zzline = ZigZagLine(s,order); cout << endl; // Got a matrix data = RandomMatrix(s, r); // Show the matrix cout << "The matrix is " << endl; for(int i=0; i<s; i++) { for(int j=0; j<s; j++) cout << data[i][j] << "\t"; cout << endl; } int total = 0; for(int i=0; i<s; i++) { for(int j=0; j<s; j++) total += data[i][j]; } cout << "The sum of the matrix is" << endl; cout << total << endl; int colsum = 0; //t = ColumnSum(data, s); cout << "The sum of each column is" << endl; for (int i = 0; i < s; ++i) { for (int j= 0; j < s; ++j) { colsum = colsum + data[j][i]; } cout << colsum << "\t"; colsum = 0; } cout << endl; int sumrow = 0; //t = RowSum(data, s); cout << "The sum of each row is"<< endl; for (int i = 0; i < s; ++i) { for (int j= 0; j < s; ++j) { sumrow = sumrow + data[i][j]; } cout << sumrow << "\t"; sumrow = 0; } return 0; }
933f27fa147798e07cf9a6d6c7550a13ee2edfe0
[ "C++" ]
1
C++
chienyld/zigzag
2f8982b624b247af1b1c50112a947e1b02e80d85
403d24e55097b3191cc4d41803f045b30d912d99
refs/heads/master
<repo_name>elnormous/sgscript<file_sep>/ext/sgsapitest.c #include <stdio.h> #include <time.h> #define SGS_INTERNAL #define SGS_USE_FILESYSTEM #include "sgs_int.h" const char* outfile = "apitests-output.log"; const char* outfile_errors = "apitests-errors.log"; #define DEFINE_TEST( name ) static void at_##name() typedef void (*testfunc) (); typedef struct _test_t { testfunc fn; const char* nm; } test_t; #define TST( name ) { at_##name, #name } extern test_t all_tests[]; const char* testname; int all_tests_count(); void exec_tests() { int i, count = all_tests_count(); fclose( fopen( outfile, "w" ) ); fclose( fopen( outfile_errors, "w" ) ); for( i = 0; i < count; ++i ) { testname = all_tests[ i ].nm; printf( "- [%02d] %-20s ...", i+1, all_tests[ i ].nm ); all_tests[ i ].fn(); printf( " OK\n" ); } } int #ifdef _MSC_VER __cdecl #endif main( int argc, char** argv ) { printf( "\n//\n/// SGScript [API] test framework\n//\n" ); exec_tests(); return 0; } /* API */ void atf_abort(){ abort(); } void atf_error( const char* msg, int line ) { printf( "\nERROR at line %d\n%s\n", line, msg ); atf_abort(); } void atf_warning( const char* msg, int line ) { printf( "\nWARNING at line %d\n%s\n", line, msg ); } #define atf_defmsg( chk ) "test failed: \"" #chk "\"" #define atf_assert_( chk, msg, line ) do{ if( !(chk) ) atf_error( msg, line ); }while(0) #define atf_assert( chk ) atf_assert_( chk, atf_defmsg( chk ), __LINE__ ) #define atf_check_( chk, msg, line ) do{ if( !(chk) ) atf_warning( msg, line ); }while(0) #define atf_check( chk ) atf_check_( chk, atf_defmsg( chk ), __LINE__ ) void atf_assert_string_( const char* str1, const char* str2, const char* msg, int line ) { const char* s1 = str1, *s2 = str2; if( str1 == NULL || str2 == NULL ) { printf( "\nERROR at line %d\n%s (at least one of the strings is NULL)\n", line, msg ); atf_abort(); } do { if( *s1 != *s2 ) { const char* spaces = " "; printf( "\nERROR at line %d\n%s (mismatch at pos. %d)\n", line, msg, (int)(size_t)( s1-str1+1 ) ); printf( "...%-20s...\n", s1 - 10 > str1 ? s1 : str1 ); printf( "...%-20s...\n", s2 - 10 > str2 ? s2 : str2 ); printf( " %.*s^\n", (int)(size_t)( s1 - str1 > 10 ? 10 : s1 - str1 ), spaces ); atf_abort(); } s1++; s2++; } while( *s1 && *s2 ); } #define atf_assert_string( str1, str2 ) \ atf_assert_string_( str1, str2, atf_defmsg( str1 == str2 ), __LINE__ ) /*************\ * * * T E S T S * * * \*************/ FILE* outfp; FILE* errfp; sgs_Context* get_context() { SGS_CTX = sgs_CreateEngine(); atf_assert_( C, "could not create context (out of memory?)", __LINE__ ); outfp = fopen( outfile, "a" ); atf_assert_( outfp, "could not create output file", __LINE__ ); errfp = fopen( outfile_errors, "a" ); atf_assert_( errfp, "could not create error output file", __LINE__ ); fprintf( outfp, "//\n/// O U T P U T o f %s\n//\n\n", testname ); sgs_SetOutputFunc( C, SGSOUTPUTFN_DEFAULT, outfp ); atf_assert( C->output_ctx == outfp ); sgs_SetErrOutputFunc( C, SGSOUTPUTFN_DEFAULT, errfp ); atf_assert( C->erroutput_ctx == errfp ); return C; } void destroy_context( SGS_CTX ) { sgs_DestroyEngine( C ); fclose( outfp ); fclose( errfp ); } int sgs_dummy_func( SGS_CTX ){ return 0; } sgs_ObjInterface sgs_dummy_iface[1] = {{ "dummy", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }}; DEFINE_TEST( create_and_destroy ) { SGS_CTX = get_context(); destroy_context( C ); } DEFINE_TEST( stack_101 ) { sgs_Variable sgs_dummy_var; SGS_CTX = get_context(); sgs_dummy_var.type = SVT_NULL; atf_assert( C->stack_base == C->stack_off ); atf_assert( C->stack_top == C->stack_off ); sgs_PushNull( C ); sgs_PushBool( C, 1 ); sgs_PushInt( C, 1337 ); sgs_PushReal( C, 13.37 ); sgs_PushStringBuf( C, "what is this", 7 ); sgs_PushString( C, "what is this" ); sgs_PushCFunction( C, sgs_dummy_func ); sgs_PushObject( C, NULL, sgs_dummy_iface ); sgs_PushVariable( C, &sgs_dummy_var ); atf_assert( C->stack_base == C->stack_off ); atf_assert( sgs_StackSize( C ) == 9 ); atf_assert( C->stack_top == C->stack_off + 9 ); atf_assert( C->stack_off[0].type == SVT_NULL ); atf_assert( C->stack_off[1].type == SVT_BOOL ); atf_assert( C->stack_off[2].type == SVT_INT ); atf_assert( C->stack_off[3].type == SVT_REAL ); atf_assert( C->stack_off[4].type == SVT_STRING ); atf_assert( C->stack_off[5].type == SVT_STRING ); atf_assert( C->stack_off[6].type == SVT_CFUNC ); atf_assert( C->stack_off[7].type == SVT_OBJECT ); atf_assert( C->stack_off[8].type == SVT_NULL ); atf_assert( C->stack_off[1].data.B == 1 ); atf_assert( C->stack_off[2].data.I == 1337 ); atf_assert( C->stack_off[3].data.R == 13.37 ); atf_assert( C->stack_off[4].data.S->size == 7 ); atf_assert_string( var_cstr( C->stack_off+4 ), "what is" ); atf_assert( C->stack_off[5].data.S->size == 12 ); atf_assert_string( var_cstr( C->stack_off+5 ), "what is this" ); atf_assert( C->stack_off[6].data.C == sgs_dummy_func ); atf_assert( C->stack_off[7].data.O->data == NULL ); atf_assert( C->stack_off[7].data.O->iface == sgs_dummy_iface ); atf_assert( sgs_Pop( C, 10 ) == SGS_EINVAL ); atf_assert( sgs_StackSize( C ) == 9 ); atf_assert( C->stack_top == C->stack_off + 9 ); atf_assert( sgs_Pop( C, 9 ) == SGS_SUCCESS ); atf_assert( C->stack_off == C->stack_top ); atf_assert( C->stack_base == C->stack_off ); atf_assert( sgs_StackSize( C ) == 0 ); destroy_context( C ); } DEFINE_TEST( stack_insert ) { sgs_Variable sgs_dummy_var; SGS_CTX = get_context(); sgs_dummy_var.type = SVT_NULL; sgs_PushInt( C, 1 ); sgs_PushInt( C, 2 ); atf_assert( C->stack_top == C->stack_off + 2 ); atf_assert( sgs_InsertVariable( C, 3, &sgs_dummy_var ) == SGS_EBOUNDS ); atf_assert( sgs_InsertVariable( C, -4, &sgs_dummy_var ) == SGS_EBOUNDS ); atf_assert( sgs_InsertVariable( C, -3, &sgs_dummy_var ) == SGS_SUCCESS ); atf_assert( sgs_InsertVariable( C, 3, &sgs_dummy_var ) == SGS_SUCCESS ); atf_assert( sgs_InsertVariable( C, 2, &sgs_dummy_var ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 5 ); atf_assert( C->stack_off[0].type == SVT_NULL ); atf_assert( C->stack_off[1].type == SVT_INT ); atf_assert( C->stack_off[2].type == SVT_NULL ); atf_assert( C->stack_off[3].type == SVT_INT ); atf_assert( C->stack_off[4].type == SVT_NULL ); atf_assert( sgs_Pop( C, 5 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 0 ); destroy_context( C ); } DEFINE_TEST( stack_arraydict ) { SGS_CTX = get_context(); sgs_PushNull( C ); sgs_PushString( C, "key-one" ); sgs_PushInt( C, 5 ); sgs_PushString( C, "key-two" ); atf_assert( sgs_PushArray( C, 5 ) == SGS_EINVAL ); atf_assert( sgs_PushArray( C, 0 ) == SGS_SUCCESS ); atf_assert( sgs_Pop( C, 1 ) == SGS_SUCCESS ); sgs_PushNull( C ); sgs_PushString( C, "key-one" ); sgs_PushInt( C, 5 ); sgs_PushString( C, "key-two" ); atf_assert( sgs_PushArray( C, 4 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 5 ); atf_assert( sgs_PushDict( C, 6 ) == SGS_EINVAL ); atf_assert( sgs_PushDict( C, 5 ) == SGS_EINVAL ); atf_assert( sgs_PushDict( C, 0 ) == SGS_SUCCESS ); atf_assert( sgs_Pop( C, 1 ) == SGS_SUCCESS ); atf_assert( sgs_PushDict( C, 4 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 2 ); atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 0 ); /* TODO: test "not a string key" in dict creation */ destroy_context( C ); } DEFINE_TEST( stack_pushstore ) { SGS_CTX = get_context(); sgs_PushNull( C ); sgs_PushInt( C, 5 ); atf_assert( sgs_PushItem( C, 2 ) == SGS_EBOUNDS ); atf_assert( sgs_PushItem( C, -3 ) == SGS_EBOUNDS ); atf_assert( sgs_PushItem( C, -2 ) == SGS_SUCCESS ); atf_assert( sgs_PushItem( C, 1 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 4 ); atf_assert( sgs_StoreItem( C, -5 ) == SGS_EBOUNDS ); atf_assert( sgs_StoreItem( C, 4 ) == SGS_EBOUNDS ); atf_assert( sgs_StoreItem( C, -3 ) == SGS_SUCCESS ); atf_assert( sgs_StoreItem( C, 0 ) == SGS_SUCCESS ); atf_assert( C->stack_off[1].type == SVT_INT ); atf_assert( C->stack_off[1].data.I == 5 ); atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 0 ); destroy_context( C ); } DEFINE_TEST( stack_propindex ) { SGS_CTX = get_context(); atf_assert( sgs_PushProperty( C, -1, "nope" ) == SGS_EBOUNDS ); sgs_PushString( C, "key-one" ); atf_assert( sgs_PushIndexII( C, 0, 1, 0 ) == SGS_EBOUNDS ); atf_assert( sgs_PushIndexII( C, 0, 0, 0 ) == SGS_EINVAL ); sgs_PushInt( C, 15 ); atf_assert( sgs_PushIndexII( C, -2, -1, 0 ) == SGS_EBOUNDS ); atf_assert( sgs_Pop( C, 1 ) == SGS_SUCCESS ); sgs_PushInt( C, 5 ); atf_assert( sgs_PushIndexII( C, -2, -1, 0 ) == SGS_SUCCESS ); atf_assert( sgs_Pop( C, 1 ) == SGS_SUCCESS ); sgs_PushString( C, "key-two" ); sgs_PushNull( C ); atf_assert( sgs_PushDict( C, 4 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 1 ); destroy_context( C ); } DEFINE_TEST( globals_101 ) { SGS_CTX = get_context(); atf_assert( sgs_PushGlobal( C, "array" ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 1 ); atf_assert( sgs_PushGlobal( C, "donut_remover" ) == SGS_ENOTFND ); atf_assert_( sgs_StackSize( C ) == 1, "wrong stack size after failed PushGlobal", __LINE__ ); atf_assert( sgs_PushArray( C, 1 ) == SGS_SUCCESS ); atf_assert_( sgs_StackSize( C ) == 1, "wrong stack size after PushArray", __LINE__ ); atf_assert( sgs_StoreGlobal( C, "yarra" ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 0 ); destroy_context( C ); } DEFINE_TEST( libraries ) { SGS_CTX = get_context(); atf_assert( sgs_LoadLib_Fmt( C ) == SGS_SUCCESS ); atf_assert( sgs_LoadLib_IO( C ) == SGS_SUCCESS ); atf_assert( sgs_LoadLib_Math( C ) == SGS_SUCCESS ); atf_assert( sgs_LoadLib_OS( C ) == SGS_SUCCESS ); atf_assert( sgs_LoadLib_String( C ) == SGS_SUCCESS ); atf_assert( sgs_PushGlobal( C, "fmt_text" ) == SGS_SUCCESS ); atf_assert( sgs_PushGlobal( C, "io_file" ) == SGS_SUCCESS ); atf_assert( sgs_PushGlobal( C, "pow" ) == SGS_SUCCESS ); atf_assert( sgs_PushGlobal( C, "os_date_string" ) == SGS_SUCCESS ); atf_assert( sgs_PushGlobal( C, "string_replace" ) == SGS_SUCCESS ); destroy_context( C ); } DEFINE_TEST( function_calls ) { SGS_CTX = get_context(); atf_assert( sgs_PushGlobal( C, "array" ) == SGS_SUCCESS ); atf_assert( sgs_Call( C, 5, 1 ) == SGS_EINVAL ); atf_assert( sgs_Call( C, 1, 0 ) == SGS_EINVAL ); atf_assert( sgs_Call( C, 0, 0 ) == SGS_SUCCESS ); atf_assert( sgs_PushGlobal( C, "array" ) == SGS_SUCCESS ); atf_assert( sgs_Call( C, 0, 1 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 1 ); atf_assert( sgs_ItemType( C, -1 ) == SVT_OBJECT ); atf_assert( sgs_PushGlobal( C, "array" ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 2 ); atf_assert( sgs_ThisCall( C, 1, 0 ) == SGS_EINVAL ); atf_assert( sgs_ThisCall( C, 0, 0 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 0 ); destroy_context( C ); } DEFINE_TEST( complex_gc ) { SGS_CTX = get_context(); const char* str = "o = { a = [ { b = {}, c = 5 }, { d = { e = {} }, f = [] } ], g = [] };" "o.a[0].parent = o; o.a[1].d.parent = o; o.a[1].d.e.parent = o.a[1].d;" "o.a[1].f.push(o); o.g.push( o.a[1].f ); o.a.push( o.a );"; atf_assert( sgs_ExecString( C, str ) == SGS_SUCCESS ); atf_assert( sgs_GCExecute( C ) == SGS_SUCCESS ); destroy_context( C ); } void output_strcat( void* ud, SGS_CTX, const void* ptr, size_t size ) { char* dst = (char*) ud; const char* src = (const char*) ptr; if( strlen( dst ) + size + 1 > 64 ) { /* WP: good enough for these tests */ printf( "size: %d, whole string: %s%s\n", (int) size, dst, src ); fflush( stdout ); } atf_assert( strlen( dst ) + size + 1 <= 64 ); strcat( dst, src ); } DEFINE_TEST( commands ) { char pbuf[ 64 ] = {0}; SGS_CTX = get_context(); const char* str = "print('1');print('2','3');print();" "print '4'; print '5', '6'; print;"; sgs_SetOutputFunc( C, output_strcat, pbuf ); atf_assert( sgs_ExecString( C, str ) == SGS_SUCCESS ); sgs_SetOutputFunc( C, SGSOUTPUTFN_DEFAULT, outfp ); atf_assert_string( pbuf, "123456" ); destroy_context( C ); } DEFINE_TEST( debugging ) { int rvc; SGS_CTX = get_context(); sgs_PushNull( C ); sgs_PushBool( C, 1 ); sgs_PushInt( C, 1337 ); sgs_PushReal( C, 3.14 ); sgs_PushString( C, "wat" ); sgs_EvalString( C, "return function(){};", &rvc ); sgs_PushGlobal( C, "print" ); sgs_PushArray( C, 0 ); sgs_PushDict( C, 0 ); atf_assert( sgs_StackSize( C ) == 9 ); sgs_Stat( C, SGS_STAT_DUMP_STACK ); sgs_Stat( C, SGS_STAT_DUMP_GLOBALS ); sgs_Stat( C, SGS_STAT_DUMP_OBJECTS ); sgs_Stat( C, SGS_STAT_DUMP_FRAMES ); destroy_context( C ); } DEFINE_TEST( varpaths ) { SGS_CTX = get_context(); const char* str = "global o = { a = [ { b = {}, c = 5 }, { d = { e = {} }, f = [] } ], g = [] };" "o.a[0].parent = o; o.a[1].d.parent = o; o.a[1].d.e.parent = o.a[1].d;" "o.a[1].f.push(o); o.g.push( o.a[1].f ); o.a.push( o.a );"; atf_assert( sgs_ExecString( C, str ) == SGS_SUCCESS ); atf_assert( sgs_PushGlobal( C, "o" ) == SGS_SUCCESS ); /* basic property retrieval */ atf_assert( sgs_PushPath( C, -1, "p", "g" ) == SGS_SUCCESS ); atf_assert( sgs_ItemType( C, -1 ) == SVT_OBJECT ); atf_assert( sgs_IsObject( C, -1, sgsstd_array_iface ) ); atf_assert( sgs_Pop( C, 1 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 1 ); /* properties and indices */ atf_assert( sgs_PushPath( C, -1, "piso", "a", 1, 1, "d", 0 ) == SGS_SUCCESS ); atf_assert( sgs_ItemType( C, -1 ) == SVT_OBJECT ); atf_assert( sgs_IsObject( C, -1, sgsstd_dict_iface ) ); atf_assert( sgs_Pop( C, 1 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 1 ); /* storing data */ sgs_PushInt( C, 42 ); atf_assert( sgs_StorePath( C, -2, "pippp", "a", 1, "d", "e", "test" ) == SGS_SUCCESS ); atf_assert( sgs_PushPath( C, -1, "pippp", "a", 1, "d", "e", "test" ) == SGS_SUCCESS ); atf_assert( sgs_ItemType( C, -1 ) == SVT_INT ); atf_assert( (C->stack_top-1)->data.I == 42 ); atf_assert( sgs_Pop( C, 1 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 1 ); destroy_context( C ); } DEFINE_TEST( iterators ) { SGS_CTX = get_context(); /* ARRAY ITERATOR */ sgs_PushBool( C, 1 ); sgs_PushInt( C, 42 ); sgs_PushString( C, "wat" ); atf_assert( sgs_StackSize( C ) == 3 ); atf_assert( sgs_PushArray( C, 3 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 1 ); /* test iteration */ atf_assert( sgs_PushIterator( C, 0 ) == SGS_SUCCESS ); atf_assert( (C->stack_top-1)->type == SVT_OBJECT ); atf_assert( (C->stack_top-1)->data.O->iface == sgsstd_array_iter_iface ); for(;;) { int ret = sgs_IterAdvance( C, -1 ); atf_assert( SGS_SUCCEEDED( ret ) ); if( !ret ) break; } atf_assert( sgs_Pop( C, 1 ) == SGS_SUCCESS ); /* test keys & values */ atf_assert( sgs_PushIterator( C, 0 ) == SGS_SUCCESS ); atf_assert( (C->stack_top-1)->type == SVT_OBJECT ); atf_assert( (C->stack_top-1)->data.O->iface == sgsstd_array_iter_iface ); /* - values 1 */ atf_assert( sgs_IterAdvance( C, -1 ) == 1 ); atf_assert( sgs_IterPushData( C, -1, 1, 1 ) == SGS_SUCCESS ); atf_assert( sgs_ItemType( C, -2 ) == SVT_INT ); atf_assert( sgs_GetInt( C, -2 ) == 0 ); atf_assert( sgs_ItemType( C, -1 ) == SVT_BOOL ); atf_assert( sgs_GetBool( C, -1 ) == 1 ); atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); /* - values 2 */ atf_assert( sgs_IterAdvance( C, -1 ) == 1 ); atf_assert( sgs_IterPushData( C, -1, 1, 1 ) == SGS_SUCCESS ); atf_assert( sgs_ItemType( C, -2 ) == SVT_INT ); atf_assert( sgs_GetInt( C, -2 ) == 1 ); atf_assert( sgs_ItemType( C, -1 ) == SVT_INT ); atf_assert( sgs_GetInt( C, -1 ) == 42 ); atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); /* - values 3 */ atf_assert( sgs_IterAdvance( C, -1 ) == 1 ); atf_assert( sgs_IterPushData( C, -1, 1, 1 ) == SGS_SUCCESS ); atf_assert( sgs_ItemType( C, -2 ) == SVT_INT ); atf_assert( sgs_GetInt( C, -2 ) == 2 ); atf_assert( sgs_ItemType( C, -1 ) == SVT_STRING ); atf_assert( sgs_GetStringSize( C, -1 ) == 3 ); atf_assert( strcmp( sgs_GetStringPtr( C, -1 ), "wat" ) == 0 ); atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); /* - end */ atf_assert( sgs_IterAdvance( C, -1 ) == 0 ); /* clean up */ atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 0 ); /* DICT ITERATOR */ sgs_PushString( C, "1st" ); sgs_PushBool( C, 1 ); sgs_PushString( C, "2nd" ); sgs_PushInt( C, 42 ); sgs_PushString( C, "3rd" ); sgs_PushString( C, "wat" ); atf_assert( sgs_StackSize( C ) == 6 ); atf_assert( sgs_PushDict( C, 6 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 1 ); /* test iteration */ atf_assert( sgs_PushIterator( C, 0 ) == SGS_SUCCESS ); atf_assert( (C->stack_top-1)->type == SVT_OBJECT ); atf_assert( (C->stack_top-1)->data.O->iface == sgsstd_dict_iter_iface ); for(;;) { int ret = sgs_IterAdvance( C, -1 ); atf_assert( SGS_SUCCEEDED( ret ) ); if( !ret ) break; } atf_assert( sgs_Pop( C, 1 ) == SGS_SUCCESS ); /* test keys & values */ atf_assert( sgs_PushIterator( C, 0 ) == SGS_SUCCESS ); atf_assert( (C->stack_top-1)->type == SVT_OBJECT ); atf_assert( (C->stack_top-1)->data.O->iface == sgsstd_dict_iter_iface ); /* - values 1 */ atf_assert( sgs_IterAdvance( C, -1 ) == 1 ); atf_assert( sgs_IterPushData( C, -1, 1, 1 ) == SGS_SUCCESS ); atf_assert( sgs_ItemType( C, -2 ) == SVT_STRING ); atf_assert( sgs_GetStringSize( C, -2 ) == 3 ); atf_assert( strcmp( sgs_GetStringPtr( C, -2 ), "1st" ) == 0 ); atf_assert( sgs_ItemType( C, -1 ) == SVT_BOOL ); atf_assert( sgs_GetBool( C, -1 ) == 1 ); atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); /* - values 2 */ atf_assert( sgs_IterAdvance( C, -1 ) == 1 ); atf_assert( sgs_IterPushData( C, -1, 1, 1 ) == SGS_SUCCESS ); atf_assert( sgs_ItemType( C, -2 ) == SVT_STRING ); atf_assert( sgs_GetStringSize( C, -2 ) == 3 ); atf_assert( strcmp( sgs_GetStringPtr( C, -2 ), "2nd" ) == 0 ); atf_assert( sgs_ItemType( C, -1 ) == SVT_INT ); atf_assert( sgs_GetInt( C, -1 ) == 42 ); atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); /* - values 3 */ atf_assert( sgs_IterAdvance( C, -1 ) == 1 ); atf_assert( sgs_IterPushData( C, -1, 1, 1 ) == SGS_SUCCESS ); atf_assert( sgs_ItemType( C, -2 ) == SVT_STRING ); atf_assert( sgs_GetStringSize( C, -2 ) == 3 ); atf_assert( strcmp( sgs_GetStringPtr( C, -2 ), "3rd" ) == 0 ); atf_assert( sgs_ItemType( C, -1 ) == SVT_STRING ); atf_assert( sgs_GetStringSize( C, -1 ) == 3 ); atf_assert( strcmp( sgs_GetStringPtr( C, -1 ), "wat" ) == 0 ); atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); /* - end */ atf_assert( sgs_IterAdvance( C, -1 ) == 0 ); /* clean up */ atf_assert( sgs_Pop( C, 2 ) == SGS_SUCCESS ); atf_assert( sgs_StackSize( C ) == 0 ); destroy_context( C ); } test_t all_tests[] = { TST( create_and_destroy ), TST( stack_101 ), TST( stack_insert ), TST( stack_arraydict ), TST( stack_pushstore ), TST( stack_propindex ), TST( globals_101 ), TST( libraries ), TST( function_calls ), TST( complex_gc ), TST( commands ), TST( debugging ), TST( varpaths ), TST( iterators ), }; int all_tests_count(){ return sizeof(all_tests)/sizeof(test_t); } <file_sep>/src/sgscript.h #ifndef SGSCRIPT_H_INCLUDED #define SGSCRIPT_H_INCLUDED #define SGS_VERSION_MAJOR 0 #define SGS_VERSION_MINOR 9 #define SGS_VERSION_INCR 5 #define SGS_VERSION "0.9.5" #define SGS_API_VERSION 12 #define SGS_VERSION_OFFSET 8 #define SGS_VERSION_INT ( ( ( ( SGS_VERSION_MAJOR << SGS_VERSION_OFFSET ) | \ SGS_VERSION_MINOR ) << SGS_VERSION_OFFSET ) | SGS_VERSION_INCR ) #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include "sgs_cfg.h" #include "sgs_xpc.h" #ifdef SGS_INTERNAL # define SVT_NULL SGS_VT_NULL # define SVT_BOOL SGS_VT_BOOL # define SVT_INT SGS_VT_INT # define SVT_REAL SGS_VT_REAL # define SVT_STRING SGS_VT_STRING # define SVT_FUNC SGS_VT_FUNC # define SVT_CFUNC SGS_VT_CFUNC # define SVT_OBJECT SGS_VT_OBJECT # define SVT_PTR SGS_VT_PTR # define StkIdx sgs_StkIdx #endif /* API self-doc helpers */ #define SGSRESULT int /* output code */ #define SGSBOOL int /* true (1) / false (0) */ #define SGSMIXED int32_t /* usable (x >= 0) value on success, error code (x < 0) on failure */ /* Output codes */ #define SGS_SUCCESS 0 /* success (no errors) */ #define SGS_ENOTFND -1 /* item was not found */ #define SGS_ECOMP -2 /* compile error */ #define SGS_ENOTOBJ -3 /* argument was not an object */ #define SGS_ENOTSUP -4 /* not supported */ #define SGS_EBOUNDS -5 /* index out of bounds */ #define SGS_EINVAL -6 /* invalid value was passed */ #define SGS_EINPROC -7 /* process was interrupted */ /* Code tests */ #define SGS_FAILED( e ) ((e)<0) #define SGS_SUCCEEDED( e ) ((e)>=0) /* Accessible / transferable data */ typedef int32_t sgs_Bool; typedef int64_t sgs_Int; typedef double sgs_Real; typedef int32_t sgs_SizeVal; typedef int32_t sgs_StkIdx; typedef struct _LNTable sgs_LNTable; typedef struct _sgs_Context sgs_Context; typedef struct _sgs_Variable sgs_Variable; typedef struct _sgs_StackFrame sgs_StackFrame; typedef int (*sgs_CFunc) ( sgs_Context* ); #define sgs_Integer sgs_Int #define sgs_Float sgs_Real #define SGS_SF_METHOD 0x01 #define SGS_SF_HASTHIS 0x02 #define SGS_SF_ABORTED 0x04 struct _sgs_StackFrame { sgs_Variable* func; uint16_t* lntable; const uint32_t* code; const uint32_t* iptr; const uint32_t* iend; const uint32_t* lptr; const char* nfname; const char* filename; sgs_StackFrame* prev; sgs_StackFrame* next; sgs_StackFrame* cached; sgs_StkIdx argbeg; sgs_StkIdx argend; int32_t errsup; uint8_t argcount; uint8_t inexp; uint8_t expected; uint8_t flags; }; /* Memory management */ typedef void* (*sgs_MemFunc) ( void* /* userdata */, void* /* curmem */, size_t /* numbytes */ ); /* unlike realloc, if size = 0, this function MUST return NULL */ static void* sgs_DefaultMemFunc( void* ud, void* ptr, size_t size ) { UNUSED( ud ); if( ptr && size ) return realloc( ptr, size ); else if( size ) return malloc( size ); if( ptr ) free( ptr ); return NULL; } /* Main output */ typedef void (*sgs_OutputFunc) ( void* /* userdata */, sgs_Context* /* ctx / SGS_CTX */, const void* /* ptr */, size_t /* size */ ); /* Debug output */ #define SGS_INFO 100 /* information about potential issues and state of the system */ #define SGS_WARNING 200 /* non-fatal problems */ #define SGS_ERROR 300 /* fatal problems */ typedef void (*sgs_MsgFunc) ( void* /* data */, sgs_Context* /* ctx / SGS_CTX */, int /* type */, const char* /* message */ ); /* Event Hook */ /* additional info can be found in the last stack frame */ #define SGS_HOOK_ENTER 1 /* entered a function */ #define SGS_HOOK_EXIT 2 /* exited a function */ #define SGS_HOOK_STEP 3 /* about to execute an instruction */ typedef void (*sgs_HookFunc) ( void* /* userdata */, sgs_Context* /* ctx / SGS_CTX */, int /* event_id */ ); /* Virtual machine state */ #define SGS_STOP_ON_FIRST_ERROR 0x0001 #define SGS_HAS_ERRORS 0x00010000 #define SGS_MUST_STOP (0x00020000 | SGS_HAS_ERRORS) /* Statistics / debugging */ #define SGS_STAT_VERSION 0 #define SGS_STAT_APIVERSION 1 #define SGS_STAT_OBJCOUNT 2 #define SGS_STAT_MEMSIZE 3 #define SGS_STAT_NUMALLOCS 4 #define SGS_STAT_NUMFREES 5 #define SGS_STAT_NUMBLOCKS 6 #define SGS_STAT_DUMP_STACK 10 #define SGS_STAT_DUMP_GLOBALS 11 #define SGS_STAT_DUMP_OBJECTS 12 #define SGS_STAT_DUMP_FRAMES 13 #define SGS_STAT_DUMP_STATS 14 #define SGS_STAT_XDUMP_STACK 20 /* Virtual machine control */ #define SGS_CNTL_STATE 1 #define SGS_CNTL_GET_STATE 2 #define SGS_CNTL_MINLEV 3 #define SGS_CNTL_GET_MINLEV 4 #define SGS_CNTL_APILEV 5 #define SGS_CNTL_GET_APILEV 6 #define SGS_CNTL_ERRNO 7 #define SGS_CNTL_SET_ERRNO 8 #define SGS_CNTL_GET_ERRNO 9 #define SGS_CNTL_ERRSUP 10 #define SGS_CNTL_GET_ERRSUP 11 /* Object actions */ #define SGS_ACT_ARRAY_PUSH 1 #define SGS_ACT_ARRAY_POP 2 #define SGS_ACT_ARRAY_POPRET 3 #define SGS_ACT_ARRAY_FIND 4 #define SGS_ACT_ARRAY_RM_ONE 5 #define SGS_ACT_ARRAY_RM_ALL 6 #define SGS_ACT_DICT_UNSET 11 #define SGS_ACT_MAP_UNSET 21 /* Context internals */ /* - variable type flags, primary and extended */ #define SGS_VT_NULL 0 #define SGS_VT_BOOL 1 #define SGS_VT_INT 2 #define SGS_VT_REAL 3 #define SGS_VT_STRING 4 #define SGS_VT_FUNC 5 #define SGS_VT_CFUNC 6 #define SGS_VT_OBJECT 7 #define SGS_VT_PTR 8 #define SGS_VT__COUNT 9 /* - object data */ typedef struct sgs_ObjData sgs_VarObj; typedef int (*sgs_ObjCallback) ( sgs_Context*, sgs_VarObj*, int /* arg */ ); typedef int (*sgs_OC_Self) ( sgs_Context*, sgs_VarObj* ); typedef int (*sgs_OC_SlPr) ( sgs_Context*, sgs_VarObj*, int ); typedef int (*sgs_OC_V1Pr) ( sgs_Context*, sgs_VarObj*, sgs_Variable*, int ); typedef int (*sgs_OC_V2Pr) ( sgs_Context*, sgs_VarObj*, sgs_Variable*, sgs_Variable*, int ); typedef struct _sgs_ObjInterface { const char* name; sgs_OC_Self destruct; sgs_OC_Self gcmark; sgs_OC_V1Pr getindex; sgs_OC_V2Pr setindex; sgs_OC_SlPr convert; sgs_OC_Self serialize; sgs_OC_SlPr dump; sgs_OC_SlPr getnext; sgs_OC_Self call; sgs_OC_V2Pr expr; } sgs_ObjInterface; struct sgs_ObjData { sgs_SizeVal refcount; uint32_t appsize; uint8_t redblue; /* red or blue? mark & sweep */ void* data; /* should have offset=8 with packing alignment>=8 */ sgs_ObjInterface* iface; sgs_VarObj* prev; /* pointer to previous GC object */ sgs_VarObj* next; /* pointer to next GC object */ }; typedef struct _sgs_iStr sgs_iStr; struct _sgs_iStr { sgs_SizeVal refcount; uint32_t size; uint32_t hash; int isconst; }; #define sgs_str_cstr( pstr ) (((char*)(pstr))+sizeof(sgs_iStr)) #define sgs_str_c_cstr( pstr ) (((const char*)(pstr))+sizeof(sgs_iStr)) #define sgs_var_cstr( var ) sgs_str_cstr( (var)->data.S ) typedef struct _sgs_iFunc sgs_iFunc; typedef union _sgs_VarData { sgs_SizeVal* pRC; sgs_Bool B; sgs_Int I; sgs_Real R; sgs_iStr* S; sgs_iFunc* F; sgs_CFunc C; sgs_VarObj* O; void* P; } sgs_VarData; struct _sgs_Variable { uint32_t type; sgs_VarData data; }; typedef struct _sgs_String32 { sgs_iStr data; char buf[32]; } sgs_String32; /* parameter flags / special values */ #define SGS_GETNEXT_KEY 0x01 #define SGS_GETNEXT_VALUE 0x02 #define SGS_EOP_ADD 0 #define SGS_EOP_SUB 1 #define SGS_EOP_MUL 2 #define SGS_EOP_DIV 3 #define SGS_EOP_MOD 4 #define SGS_EOP_COMPARE 5 #define SGS_EOP_NEGATE 6 #define SGS_CONVOP_CLONE 0x10000 #define SGS_CONVOP_TYPEOF 0x20000 #define SGS_CONVOP_TOITER 0x30000 #define SGS_BOP_AND 0 #define SGS_BOP_OR 1 #define SGS_BOP_XOR 2 #define SGS_BOP_LSH 3 #define SGS_BOP_RSH 4 /* Engine context */ #define SGS_CTX sgs_Context* C SGS_APIFUNC sgs_Context* sgs_CreateEngineExt ( sgs_MemFunc memfunc, void* mfuserdata ); static SGS_INLINE sgs_Context* sgs_CreateEngine() { return sgs_CreateEngineExt( sgs_DefaultMemFunc, NULL ); } SGS_APIFUNC void sgs_DestroyEngine( SGS_CTX ); #define SGS_CODE_ER 0 /* error codes */ #define SGS_CODE_VT 1 /* variable type */ #define SGS_CODE_OP 2 /* VM instruction */ SGS_APIFUNC const char* sgs_CodeString( int type, int val ); /* Core systems */ #define SGSOUTPUTFN_DEFAULT ((sgs_OutputFunc)-1) SGS_APIFUNC void sgs_GetOutputFunc( SGS_CTX, sgs_OutputFunc* outf, void** outc ); SGS_APIFUNC void sgs_SetOutputFunc( SGS_CTX, sgs_OutputFunc func, void* ctx ); SGS_APIFUNC void sgs_Write( SGS_CTX, const void* ptr, size_t size ); SGS_APIFUNC SGSBOOL sgs_Writef( SGS_CTX, const char* what, ... ); SGS_APIFUNC void sgs_GetErrOutputFunc( SGS_CTX, sgs_OutputFunc* outf, void** outc ); SGS_APIFUNC void sgs_SetErrOutputFunc( SGS_CTX, sgs_OutputFunc func, void* ctx ); SGS_APIFUNC void sgs_ErrWrite( SGS_CTX, const void* ptr, size_t size ); SGS_APIFUNC SGSBOOL sgs_ErrWritef( SGS_CTX, const char* what, ... ); #define SGSMSGFN_DEFAULT ((sgs_MsgFunc)-1) #define SGSMSGFN_DEFAULT_NOABORT ((sgs_MsgFunc)-2) SGS_APIFUNC void sgs_GetMsgFunc( SGS_CTX, sgs_MsgFunc* outf, void** outc ); SGS_APIFUNC void sgs_SetMsgFunc( SGS_CTX, sgs_MsgFunc func, void* ctx ); SGS_APIFUNC int sgs_Msg( SGS_CTX, int type, const char* what, ... ); typedef int (*sgs_ErrorOutputFunc) ( void*, const char*, ... ); #define SGS_ERRORINFO_STACK 0x01 #define SGS_ERRORINFO_ERROR 0x02 #define SGS_ERRORINFO_FULL (SGS_ERRORINFO_STACK | SGS_ERRORINFO_ERROR) SGS_APIFUNC void sgs_WriteErrorInfo( SGS_CTX, int flags, sgs_ErrorOutputFunc func, void* ctx, int type, const char* msg ); SGS_APIFUNC void sgs_PushErrorInfo( SGS_CTX, int flags, int type, const char* msg ); SGS_APIFUNC SGSBOOL sgs_GetHookFunc( SGS_CTX, sgs_HookFunc* outf, void** outc ); SGS_APIFUNC void sgs_SetHookFunc( SGS_CTX, sgs_HookFunc func, void* ctx ); SGS_APIFUNC void* sgs_Memory( SGS_CTX, void* ptr, size_t size ); #define sgs_Malloc( C, size ) sgs_Memory( C, NULL, size ) #define sgs_Free( C, ptr ) sgs_Memory( C, ptr, 0 ) #define sgs_Realloc sgs_Memory /* assumes SGS_CTX: */ #define sgs_Alloc( what ) (what*) sgs_Malloc( C, sizeof(what) ) #define sgs_Alloc_n( what, cnt ) (what*) sgs_Malloc( C, sizeof(what) * cnt ) #define sgs_Alloc_a( what, app ) (what*) sgs_Malloc( C, sizeof(what) + app ) #define sgs_Dealloc( ptr ) sgs_Free( C, ptr ) SGS_APIFUNC SGSRESULT sgs_EvalBuffer( SGS_CTX, const char* buf, size_t size, int* rvc ); SGS_APIFUNC SGSRESULT sgs_EvalFile( SGS_CTX, const char* file, int* rvc ); SGS_APIFUNC SGSBOOL sgs_IncludeExt( SGS_CTX, const char* name, const char* searchpath ); SGS_APIFUNC SGSRESULT sgs_Compile( SGS_CTX, const char* buf, size_t size, char** outbuf, size_t* outsize ); SGS_APIFUNC SGSRESULT sgs_DumpCompiled( SGS_CTX, const char* buf, size_t size ); SGS_APIFUNC SGSRESULT sgs_Abort( SGS_CTX ); SGS_APIFUNC ptrdiff_t sgs_Stat( SGS_CTX, int type ); SGS_APIFUNC int32_t sgs_Cntl( SGS_CTX, int what, int32_t val ); SGS_APIFUNC void sgs_StackFrameInfo( SGS_CTX, sgs_StackFrame* frame, const char** name, const char** file, int* line ); SGS_APIFUNC sgs_StackFrame* sgs_GetFramePtr( SGS_CTX, int end ); #ifndef SGS_STRINGLENGTHFUNC #define SGS_STRINGLENGTHFUNC strlen #endif #define sgs_ExecBuffer( C, buf, sz ) sgs_EvalBuffer( C, buf, sz, NULL ) #define sgs_ExecString( C, str ) sgs_ExecBuffer( C, str, SGS_STRINGLENGTHFUNC( str ) ) #define sgs_EvalString( C, str, rvc ) sgs_EvalBuffer( C, str, SGS_STRINGLENGTHFUNC( str ), rvc ) #define sgs_ExecFile( C, str ) sgs_EvalFile( C, str, NULL ) #define sgs_Include( C, str ) sgs_IncludeExt( C, str, NULL ) #define sgs_WriteStr( C, str ) sgs_Write( C, str, SGS_STRINGLENGTHFUNC( str ) ) #define sgs_ErrWriteStr( C, str ) sgs_ErrWrite( C, str, SGS_STRINGLENGTHFUNC( str ) ) /* Additional libraries */ SGS_APIFUNC SGSRESULT sgs_LoadLib_Fmt( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_LoadLib_IO( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_LoadLib_Math( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_LoadLib_OS( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_LoadLib_RE( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_LoadLib_String( SGS_CTX ); #define SGS_RC_END() { NULL, NULL } typedef struct _sgs_RegFuncConst { const char* name; sgs_CFunc value; } sgs_RegFuncConst; SGS_APIFUNC SGSRESULT sgs_RegFuncConsts( SGS_CTX, const sgs_RegFuncConst* list, int size ); typedef struct _sgs_RegIntConst { const char* name; sgs_Int value; } sgs_RegIntConst; SGS_APIFUNC SGSRESULT sgs_RegIntConsts( SGS_CTX, const sgs_RegIntConst* list, int size ); typedef struct _sgs_RegRealConst { const char* name; sgs_Real value; } sgs_RegRealConst; SGS_APIFUNC SGSRESULT sgs_RegRealConsts( SGS_CTX, const sgs_RegRealConst* list, int size ); SGS_APIFUNC SGSRESULT sgs_RegisterType( SGS_CTX, const char* name, sgs_ObjInterface* iface ); SGS_APIFUNC SGSRESULT sgs_UnregisterType( SGS_CTX, const char* name ); SGS_APIFUNC sgs_ObjInterface* sgs_FindType( SGS_CTX, const char* name ); /* The core interface */ /* OBJECT CREATION */ SGS_APIFUNC void sgs_InitNull( sgs_Variable* out ); SGS_APIFUNC void sgs_InitBool( sgs_Variable* out, sgs_Bool value ); SGS_APIFUNC void sgs_InitInt( sgs_Variable* out, sgs_Int value ); SGS_APIFUNC void sgs_InitReal( sgs_Variable* out, sgs_Real value ); SGS_APIFUNC void sgs_InitStringBuf( SGS_CTX, sgs_Variable* out, const char* str, sgs_SizeVal size ); SGS_APIFUNC void sgs_InitString( SGS_CTX, sgs_Variable* out, const char* str ); SGS_APIFUNC void sgs_InitCFunction( sgs_Variable* out, sgs_CFunc func ); SGS_APIFUNC void sgs_InitObject( SGS_CTX, sgs_Variable* out, void* data, sgs_ObjInterface* iface ); SGS_APIFUNC void* sgs_InitObjectIPA( SGS_CTX, sgs_Variable* out, uint32_t added, sgs_ObjInterface* iface ); SGS_APIFUNC void sgs_InitPtr( sgs_Variable* out, void* ptr ); SGS_APIFUNC void sgs_InitObjectPtr( sgs_Variable* out, sgs_VarObj* obj ); SGS_APIFUNC SGSRESULT sgs_InitArray( SGS_CTX, sgs_Variable* out, sgs_SizeVal numitems ); SGS_APIFUNC SGSRESULT sgs_InitDict( SGS_CTX, sgs_Variable* out, sgs_SizeVal numitems ); SGS_APIFUNC SGSRESULT sgs_InitMap( SGS_CTX, sgs_Variable* out, sgs_SizeVal numitems ); /* STACK & SUB-ITEMS */ SGS_APIFUNC void sgs_PushNull( SGS_CTX ); SGS_APIFUNC void sgs_PushBool( SGS_CTX, sgs_Bool value ); SGS_APIFUNC void sgs_PushInt( SGS_CTX, sgs_Int value ); SGS_APIFUNC void sgs_PushReal( SGS_CTX, sgs_Real value ); SGS_APIFUNC void sgs_PushStringBuf( SGS_CTX, const char* str, sgs_SizeVal size ); SGS_APIFUNC void sgs_PushString( SGS_CTX, const char* str ); SGS_APIFUNC void sgs_PushCFunction( SGS_CTX, sgs_CFunc func ); SGS_APIFUNC void sgs_PushObject( SGS_CTX, void* data, sgs_ObjInterface* iface ); SGS_APIFUNC void* sgs_PushObjectIPA( SGS_CTX, uint32_t added, sgs_ObjInterface* iface ); SGS_APIFUNC void sgs_PushPtr( SGS_CTX, void* ptr ); SGS_APIFUNC void sgs_PushObjectPtr( SGS_CTX, sgs_VarObj* obj ); SGS_APIFUNC SGSRESULT sgs_PushArray( SGS_CTX, sgs_SizeVal numitems ); SGS_APIFUNC SGSRESULT sgs_PushDict( SGS_CTX, sgs_SizeVal numitems ); SGS_APIFUNC SGSRESULT sgs_PushMap( SGS_CTX, sgs_SizeVal numitems ); SGS_APIFUNC SGSRESULT sgs_PushVariable( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC SGSRESULT sgs_StoreVariable( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC SGSRESULT sgs_PushItem( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSRESULT sgs_StoreItem( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSRESULT sgs_InsertVariable( SGS_CTX, int pos, sgs_Variable* var ); /* almost-raw access */ SGS_APIFUNC SGSRESULT sgs_GetIndexPPP( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, sgs_Variable* out, int isprop ); SGS_APIFUNC SGSRESULT sgs_SetIndexPPP( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, sgs_Variable* val, int isprop ); SGS_APIFUNC SGSRESULT sgs_PushIndexPP( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, int isprop ); SGS_APIFUNC SGSRESULT sgs_StoreIndexPP( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, int isprop ); /* intermixed stack indices */ SGS_APIFUNC SGSRESULT sgs_GetIndexIPP( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, sgs_Variable* out, int isprop ); SGS_APIFUNC SGSRESULT sgs_GetIndexPIP( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, sgs_Variable* out, int isprop ); SGS_APIFUNC SGSRESULT sgs_GetIndexIIP( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, sgs_Variable* out, int isprop ); SGS_APIFUNC SGSRESULT sgs_GetIndexPPI( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, sgs_StkIdx out, int isprop ); SGS_APIFUNC SGSRESULT sgs_GetIndexIPI( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, sgs_StkIdx out, int isprop ); SGS_APIFUNC SGSRESULT sgs_GetIndexPII( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, sgs_StkIdx out, int isprop ); SGS_APIFUNC SGSRESULT sgs_GetIndexIII( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, sgs_StkIdx out, int isprop ); SGS_APIFUNC SGSRESULT sgs_SetIndexIPP( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, sgs_Variable* val, int isprop ); SGS_APIFUNC SGSRESULT sgs_SetIndexPIP( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, sgs_Variable* val, int isprop ); SGS_APIFUNC SGSRESULT sgs_SetIndexIIP( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, sgs_Variable* val, int isprop ); SGS_APIFUNC SGSRESULT sgs_SetIndexPPI( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, sgs_StkIdx val, int isprop ); SGS_APIFUNC SGSRESULT sgs_SetIndexIPI( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, sgs_StkIdx val, int isprop ); SGS_APIFUNC SGSRESULT sgs_SetIndexPII( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, sgs_StkIdx val, int isprop ); SGS_APIFUNC SGSRESULT sgs_SetIndexIII( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, sgs_StkIdx val, int isprop ); SGS_APIFUNC SGSRESULT sgs_PushIndexIP( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, int isprop ); SGS_APIFUNC SGSRESULT sgs_PushIndexPI( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, int isprop ); SGS_APIFUNC SGSRESULT sgs_PushIndexII( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, int isprop ); SGS_APIFUNC SGSRESULT sgs_StoreIndexIP( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, int isprop ); SGS_APIFUNC SGSRESULT sgs_StoreIndexPI( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, int isprop ); SGS_APIFUNC SGSRESULT sgs_StoreIndexII( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, int isprop ); /* raw & simplified global access */ SGS_APIFUNC SGSRESULT sgs_GetGlobalPP( SGS_CTX, sgs_Variable* idx, sgs_Variable* out ); SGS_APIFUNC SGSRESULT sgs_SetGlobalPP( SGS_CTX, sgs_Variable* idx, sgs_Variable* val ); /* special case sub-variable access */ SGS_APIFUNC SGSRESULT sgs_PushProperty( SGS_CTX, sgs_StkIdx obj, const char* name ); SGS_APIFUNC SGSRESULT sgs_StoreProperty( SGS_CTX, sgs_StkIdx obj, const char* name ); SGS_APIFUNC SGSRESULT sgs_PushNumIndex( SGS_CTX, sgs_StkIdx obj, sgs_Int idx ); SGS_APIFUNC SGSRESULT sgs_StoreNumIndex( SGS_CTX, sgs_StkIdx obj, sgs_Int idx ); SGS_APIFUNC SGSRESULT sgs_PushGlobal( SGS_CTX, const char* name ); SGS_APIFUNC SGSRESULT sgs_StoreGlobal( SGS_CTX, const char* name ); SGS_APIFUNC void sgs_GetEnv( SGS_CTX, sgs_Variable* out ); SGS_APIFUNC SGSRESULT sgs_SetEnv( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC void sgs_PushEnv( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_StoreEnv( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_PushPath( SGS_CTX, sgs_StkIdx item, const char* path, ... ); SGS_APIFUNC SGSRESULT sgs_StorePath( SGS_CTX, sgs_StkIdx item, const char* path, ... ); SGS_APIFUNC int sgs_ArgErrorExt( SGS_CTX, int argid, int gotthis, const char* expect, const char* expfx ); SGS_APIFUNC int sgs_ArgError( SGS_CTX, int argid, int gotthis, int expect, int is_strict ); #define sgs_FuncArgError( C, argid, expect, strict ) sgs_ArgError( C, argid, 0, expect, strict ) #define sgs_MethodArgError( C, argid, expect, strict ) sgs_ArgError( C, argid, 1, expect, strict ) typedef int (*sgs_ArgCheckFunc) ( sgs_Context* /* ctx / SGS_CTX */, int /* argid */, va_list* /* args */, int /* flags */ ); #define SGS_LOADARG_STRICT 0x01 #define SGS_LOADARG_WRITE 0x02 #define SGS_LOADARG_OPTIONAL 0x04 #define SGS_LOADARG_INTSIGN 0x08 #define SGS_LOADARG_INTRANGE 0x10 #define SGS_LOADARG_INTCLAMP 0x20 SGS_APIFUNC SGSMIXED sgs_LoadArgsExtVA( SGS_CTX, int from, const char* cmd, va_list* args ); SGS_APIFUNC SGSMIXED sgs_LoadArgsExt( SGS_CTX, int from, const char* cmd, ... ); SGS_APIFUNC SGSBOOL sgs_LoadArgs( SGS_CTX, const char* cmd, ... ); SGS_APIFUNC SGSBOOL sgs_ParseMethod( SGS_CTX, sgs_ObjInterface* iface, void** ptrout, const char* method_name, const char* func_name ); #define SGS_PARSE_METHOD( C, iface, ptr, objname, methodname ) \ sgs_ParseMethod( C, iface, (void**) &ptr, #objname "." #methodname, #objname "_" #methodname ) SGS_APIFUNC SGSRESULT sgs_Pop( SGS_CTX, sgs_StkIdx count ); SGS_APIFUNC SGSRESULT sgs_PopSkip( SGS_CTX, sgs_StkIdx count, sgs_StkIdx skip ); SGS_APIFUNC sgs_StkIdx sgs_StackSize( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_SetStackSize( SGS_CTX, sgs_StkIdx size ); SGS_APIFUNC sgs_StkIdx sgs_AbsIndex( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSBOOL sgs_IsValidIndex( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSBOOL sgs_PeekStackItem( SGS_CTX, sgs_StkIdx item, sgs_Variable* out ); SGS_APIFUNC SGSBOOL sgs_GetStackItem( SGS_CTX, sgs_StkIdx item, sgs_Variable* out ); SGS_APIFUNC SGSRESULT sgs_SetStackItem( SGS_CTX, sgs_StkIdx item, sgs_Variable* val ); SGS_APIFUNC uint32_t sgs_ItemType( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC void sgs_Assign( SGS_CTX, sgs_Variable* var_to, sgs_Variable* var_from ); SGS_APIFUNC SGSRESULT sgs_ArithOp( SGS_CTX, sgs_Variable* out, sgs_Variable* A, sgs_Variable* B, int op ); SGS_APIFUNC SGSRESULT sgs_IncDec( SGS_CTX, sgs_Variable* out, sgs_Variable* A, int inc ); /* CLOSURES */ SGS_APIFUNC SGSRESULT sgs_ClPushNulls( SGS_CTX, sgs_StkIdx num ); SGS_APIFUNC SGSRESULT sgs_ClPushItem( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSRESULT sgs_ClPop( SGS_CTX, sgs_StkIdx num ); SGS_APIFUNC SGSRESULT sgs_MakeClosure( SGS_CTX, sgs_Variable* func, sgs_StkIdx clcount, sgs_Variable* out ); SGS_APIFUNC SGSRESULT sgs_ClGetItem( SGS_CTX, sgs_StkIdx item, sgs_Variable* out ); SGS_APIFUNC SGSRESULT sgs_ClSetItem( SGS_CTX, sgs_StkIdx item, sgs_Variable* var ); /* OPERATIONS */ SGS_APIFUNC SGSRESULT sgs_FCallP( SGS_CTX, sgs_Variable* callable, int args, int expect, int gotthis ); #define sgs_CallP( C, callable, args, expect ) sgs_FCallP( C, callable, args, expect, 0 ) #define sgs_ThisCallP( C, callable, args, expect ) sgs_FCallP( C, callable, args, expect, 1 ) SGS_APIFUNC SGSRESULT sgs_FCall( SGS_CTX, int args, int expect, int gotthis ); #define sgs_Call( C, args, expect ) sgs_FCall( C, args, expect, 0 ) #define sgs_ThisCall( C, args, expect ) sgs_FCall( C, args, expect, 1 ) SGS_APIFUNC SGSRESULT sgs_GlobalCall( SGS_CTX, const char* name, int args, int expect ); SGS_APIFUNC SGSRESULT sgs_TypeOf( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSRESULT sgs_DumpVar( SGS_CTX, int maxdepth ); SGS_APIFUNC SGSRESULT sgs_GCExecute( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_PadString( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_ToPrintSafeString( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_StringConcat( SGS_CTX, sgs_StkIdx args ); SGS_APIFUNC SGSRESULT sgs_CloneItem( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSMIXED sgs_ObjectAction( SGS_CTX, sgs_StkIdx item, int act, int arg ); SGS_APIFUNC SGSRESULT sgs_Serialize( SGS_CTX ); SGS_APIFUNC SGSRESULT sgs_SerializeObject( SGS_CTX, sgs_StkIdx args, const char* func ); SGS_APIFUNC SGSRESULT sgs_Unserialize( SGS_CTX ); SGS_APIFUNC int sgs_Compare( SGS_CTX, sgs_Variable* v1, sgs_Variable* v2 ); SGS_APIFUNC SGSBOOL sgs_EqualTypes( sgs_Variable* v1, sgs_Variable* v2 ); /* CONVERSION / RETRIEVAL */ /* pointer versions */ SGS_APIFUNC sgs_Bool sgs_GetBoolP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC sgs_Int sgs_GetIntP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC sgs_Real sgs_GetRealP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC void* sgs_GetPtrP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC sgs_Bool sgs_ToBoolP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC sgs_Int sgs_ToIntP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC sgs_Real sgs_ToRealP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC void* sgs_ToPtrP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC char* sgs_ToStringBufP( SGS_CTX, sgs_Variable* var, sgs_SizeVal* outsize ); #define sgs_ToStringP( ctx, var ) sgs_ToStringBufP( ctx, var, NULL ) SGS_APIFUNC char* sgs_ToStringBufFastP( SGS_CTX, sgs_Variable* var, sgs_SizeVal* outsize ); #define sgs_ToStringFastP( ctx, var ) sgs_ToStringBufFast( ctx, var, NULL ) SGS_APIFUNC SGSBOOL sgs_IsObjectP( sgs_Variable* var, sgs_ObjInterface* iface ); #define sgs_IsTypeP( C, var, name ) sgs_IsObjectP( var, sgs_FindType( C, name ) ) SGS_APIFUNC SGSBOOL sgs_IsCallableP( sgs_Variable* var ); SGS_APIFUNC SGSBOOL sgs_ParseBoolP( SGS_CTX, sgs_Variable* var, sgs_Bool* out ); SGS_APIFUNC SGSBOOL sgs_ParseIntP( SGS_CTX, sgs_Variable* var, sgs_Int* out ); SGS_APIFUNC SGSBOOL sgs_ParseRealP( SGS_CTX, sgs_Variable* var, sgs_Real* out ); SGS_APIFUNC SGSBOOL sgs_ParseStringP( SGS_CTX, sgs_Variable* var, char** out, sgs_SizeVal* size ); SGS_APIFUNC SGSBOOL sgs_ParseObjectPtrP( SGS_CTX, sgs_Variable* var, sgs_ObjInterface* iface, sgs_VarObj** out, int strict ); SGS_APIFUNC SGSBOOL sgs_ParsePtrP( SGS_CTX, sgs_Variable* var, void** out ); SGS_APIFUNC SGSMIXED sgs_ArraySizeP( SGS_CTX, sgs_Variable* var ); /* index versions */ SGS_APIFUNC sgs_Bool sgs_GetBool( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC sgs_Int sgs_GetInt( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC sgs_Real sgs_GetReal( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC void* sgs_GetPtr( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC sgs_Bool sgs_ToBool( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC sgs_Int sgs_ToInt( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC sgs_Real sgs_ToReal( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC void* sgs_ToPtr( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC char* sgs_ToStringBuf( SGS_CTX, sgs_StkIdx item, sgs_SizeVal* outsize ); #define sgs_ToString( ctx, item ) sgs_ToStringBuf( ctx, item, NULL ) SGS_APIFUNC char* sgs_ToStringBufFast( SGS_CTX, sgs_StkIdx item, sgs_SizeVal* outsize ); #define sgs_ToStringFast( ctx, item ) sgs_ToStringBufFast( ctx, item, NULL ) SGS_APIFUNC SGSBOOL sgs_IsObject( SGS_CTX, sgs_StkIdx item, sgs_ObjInterface* iface ); #define sgs_IsType( C, item, name ) sgs_IsObject( C, item, sgs_FindType( C, name ) ) SGS_APIFUNC SGSBOOL sgs_IsCallable( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSBOOL sgs_ParseBool( SGS_CTX, sgs_StkIdx item, sgs_Bool* out ); SGS_APIFUNC SGSBOOL sgs_ParseInt( SGS_CTX, sgs_StkIdx item, sgs_Int* out ); SGS_APIFUNC SGSBOOL sgs_ParseReal( SGS_CTX, sgs_StkIdx item, sgs_Real* out ); SGS_APIFUNC SGSBOOL sgs_ParseString( SGS_CTX, sgs_StkIdx item, char** out, sgs_SizeVal* size ); SGS_APIFUNC SGSBOOL sgs_ParseObjectPtr( SGS_CTX, sgs_StkIdx item, sgs_ObjInterface* iface, sgs_VarObj** out, int strict ); SGS_APIFUNC SGSBOOL sgs_ParsePtr( SGS_CTX, sgs_StkIdx item, void** out ); SGS_APIFUNC SGSMIXED sgs_ArraySize( SGS_CTX, sgs_StkIdx item ); /* global versions */ SGS_APIFUNC sgs_Bool sgs_GlobalBool( SGS_CTX, const char* name ); SGS_APIFUNC sgs_Int sgs_GlobalInt( SGS_CTX, const char* name ); SGS_APIFUNC sgs_Real sgs_GlobalReal( SGS_CTX, const char* name ); SGS_APIFUNC char* sgs_GlobalStringBuf( SGS_CTX, const char* name, sgs_SizeVal* outsize ); #define sgs_GlobalString( C, name ) sgs_GlobalStringBuf( C, name, NULL ) /* iterator interface fns - pointer sources */ SGS_APIFUNC SGSRESULT sgs_PushIteratorP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC SGSRESULT sgs_GetIteratorP( SGS_CTX, sgs_Variable* var, sgs_Variable* out ); SGS_APIFUNC SGSMIXED sgs_IterAdvanceP( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC SGSMIXED sgs_IterPushDataP( SGS_CTX, sgs_Variable* var, int key, int value ); SGS_APIFUNC SGSMIXED sgs_IterGetDataP( SGS_CTX, sgs_Variable* var, sgs_Variable* key, sgs_Variable* value ); /* iterator interface fns - stack sources */ SGS_APIFUNC SGSRESULT sgs_PushIterator( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSRESULT sgs_GetIterator( SGS_CTX, sgs_StkIdx item, sgs_Variable* out ); SGS_APIFUNC SGSMIXED sgs_IterAdvance( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC SGSMIXED sgs_IterPushData( SGS_CTX, sgs_StkIdx item, int key, int value ); SGS_APIFUNC SGSMIXED sgs_IterGetData( SGS_CTX, sgs_StkIdx item, sgs_Variable* key, sgs_Variable* value ); SGS_APIFUNC SGSBOOL sgs_IsNumericString( const char* str, sgs_SizeVal size ); /* EXTENSION UTILITIES */ SGS_APIFUNC SGSBOOL sgs_Method( SGS_CTX ); SGS_APIFUNC SGSBOOL sgs_HideThis( SGS_CTX ); SGS_APIFUNC SGSBOOL sgs_ForceHideThis( SGS_CTX ); SGS_APIFUNC void sgs_Acquire( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC void sgs_AcquireArray( SGS_CTX, sgs_Variable* var, sgs_SizeVal count ); SGS_APIFUNC void sgs_Release( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC void sgs_ReleaseArray( SGS_CTX, sgs_Variable* var, sgs_SizeVal count ); SGS_APIFUNC SGSRESULT sgs_GCMark( SGS_CTX, sgs_Variable* var ); SGS_APIFUNC SGSRESULT sgs_GCMarkArray( SGS_CTX, sgs_Variable* var, sgs_SizeVal count ); SGS_APIFUNC void sgs_ObjAcquire( SGS_CTX, sgs_VarObj* obj ); SGS_APIFUNC void sgs_ObjRelease( SGS_CTX, sgs_VarObj* obj ); SGS_APIFUNC SGSRESULT sgs_ObjGCMark( SGS_CTX, sgs_VarObj* obj ); SGS_APIFUNC void sgs_ObjAssign( SGS_CTX, sgs_VarObj** dest, sgs_VarObj* src ); SGS_APIFUNC void sgs_ObjCallDtor( SGS_CTX, sgs_VarObj* obj ); SGS_APIFUNC char* sgs_GetStringPtrP( sgs_Variable* var ); SGS_APIFUNC sgs_SizeVal sgs_GetStringSizeP( sgs_Variable* var ); SGS_APIFUNC sgs_VarObj* sgs_GetObjectStructP( sgs_Variable* var ); SGS_APIFUNC void* sgs_GetObjectDataP( sgs_Variable* var ); SGS_APIFUNC sgs_ObjInterface* sgs_GetObjectIfaceP( sgs_Variable* var ); SGS_APIFUNC int sgs_SetObjectDataP( sgs_Variable* var, void* data ); SGS_APIFUNC int sgs_SetObjectIfaceP( sgs_Variable* var, sgs_ObjInterface* iface ); SGS_APIFUNC char* sgs_GetStringPtr( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC sgs_SizeVal sgs_GetStringSize( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC sgs_VarObj* sgs_GetObjectStruct( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC void* sgs_GetObjectData( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC sgs_ObjInterface* sgs_GetObjectIface( SGS_CTX, sgs_StkIdx item ); SGS_APIFUNC int sgs_SetObjectData( SGS_CTX, sgs_StkIdx item, void* data ); SGS_APIFUNC int sgs_SetObjectIface( SGS_CTX, sgs_StkIdx item, sgs_ObjInterface* iface ); SGS_APIFUNC int sgs_HasFuncName( SGS_CTX ); SGS_APIFUNC void sgs_FuncName( SGS_CTX, const char* fnliteral ); #define SGSFN( x ) sgs_FuncName( C, x ) #define SGSBASEFN( x ) if( !sgs_HasFuncName( C ) ) sgs_FuncName( C, x ) static SGS_INLINE int sgs_Errno( SGS_CTX, int clear ) { sgs_Cntl( C, SGS_CNTL_ERRNO, clear ); return clear; } #define sgs_SetErrno( C, err ) sgs_Cntl( C, SGS_CNTL_SET_ERRNO, err ) #define sgs_GetLastErrno( C ) sgs_Cntl( C, SGS_CNTL_GET_ERRNO, 0 ) SGS_APIFUNC void sgs_InitStringBuf32( sgs_Variable* var, sgs_String32* S, const char* str, size_t len ); #define sgs_InitString32( var, S, str ) sgs_InitStringBuf32( var, S, str, SGS_STRINGLENGTHFUNC(str) ) SGS_APIFUNC void sgs_PushStringBuf32( SGS_CTX, sgs_String32* S, const char* str, size_t len ); #define sgs_PushString32( C, S, str ) sgs_PushStringBuf32( C, S, str, SGS_STRINGLENGTHFUNC(str) ) SGS_APIFUNC void sgs_CheckString32( sgs_String32* S ); SGS_APIFUNC SGSBOOL sgs_IsFreedString32( sgs_String32* S ); /* predefined output / messaging functions */ static SGS_INLINE void sgs_StdOutputFunc( void* userdata, SGS_CTX, const void* ptr, size_t size ) { UNUSED( C ); fwrite( ptr, 1, size, (FILE*) userdata ); } static SGS_INLINE void sgs_StdMsgFunc_NoAbort( void* ctx, SGS_CTX, int type, const char* msg ) { UNUSED( ctx ); sgs_WriteErrorInfo( C, SGS_ERRORINFO_FULL, (sgs_ErrorOutputFunc) sgs_ErrWritef, C, type, msg ); } static SGS_INLINE void sgs_StdMsgFunc( void* ctx, SGS_CTX, int type, const char* msg ) { sgs_StdMsgFunc_NoAbort( ctx, C, type, msg ); if( type >= SGS_ERROR ) sgs_Abort( C ); } /* utility macros */ #define SGS_RETURN_THIS( C ) sgs_Method( C ); sgs_SetStackSize( C, 1 ); return 1; #define SGS_ARGS_GETINDEXFUNC SGS_CTX, sgs_VarObj* obj, sgs_Variable* key, int isprop #define SGS_ARGS_SETINDEXFUNC SGS_CTX, sgs_VarObj* obj, sgs_Variable* key, sgs_Variable* val, int isprop #define SGS_BEGIN_INDEXFUNC char* str; UNUSED( isprop ); if( sgs_ParseStringP( C, key, &str, NULL ) ){ #define SGS_END_INDEXFUNC } return SGS_ENOTFND; #define SGS_CASE( name ) if( !strcmp( str, name ) ) #define SGS_RETURN_NULL() { sgs_PushNull( C ); return SGS_SUCCESS; } #define SGS_RETURN_BOOL( value ) { sgs_PushBool( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_INT( value ) { sgs_PushInt( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_REAL( value ) { sgs_PushReal( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_CFUNC( value ) { sgs_PushCFunction( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_OBJECT( value ) { sgs_PushObjectPtr( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_VAR( value ) { sgs_PushVariable( C, value ); return SGS_SUCCESS; } #define SGS_PARSE_BOOL( out ) { sgs_Bool V; if( sgs_ParseBoolP( C, val, &V ) ){ out = V; return SGS_SUCCESS; } return SGS_EINVAL; } #define SGS_PARSE_INT( out ) { sgs_Int V; if( sgs_ParseIntP( C, val, &V ) ){ out = V; return SGS_SUCCESS; } return SGS_EINVAL; } #define SGS_PARSE_REAL( out ) { sgs_Real V; if( sgs_ParseRealP( C, val, &V ) ){ out = V; return SGS_SUCCESS; } return SGS_EINVAL; } #define SGS_PARSE_OBJECT( iface, out, nonull ) { return sgs_ParseObjectPtrP( C, val, iface, &out, nonull ) ? SGS_SUCCESS : SGS_EINVAL; } #define SGS_PARSE_OBJECT_IF( iface, out, nonull, cond ) if( ( !(nonull) && val->type == SGS_VT_NULL ) || ( val->type == SGS_VT_OBJECT && (cond) ) ) \ { return sgs_ParseObjectPtrP( C, val, iface, &out, nonull ) ? SGS_SUCCESS : SGS_EINVAL; } #ifdef __cplusplus } #endif #endif /* SGSCRIPT_H_INCLUDED */ <file_sep>/src/sgs_fnt.c #define SGS_INTERNAL #define SGS_REALLY_INTERNAL #include "sgs_int.h" static int isoneofN( char ch, const char* what, int size ) { const char* end = what + size; while( what < end ) { if( ch == *what++ ) return TRUE; } return FALSE; } static int is_keyword( TokenList tok, const char* text ) { return *tok == ST_KEYWORD && tok[ 1 ] == strlen( text ) && strncmp( (const char*) tok + 2, text, tok[ 1 ] ) == 0; } static int is_ident( TokenList tok, const char* text ) { return *tok == ST_IDENT && tok[ 1 ] == strlen( text ) && strncmp( (const char*) tok + 2, text, tok[ 1 ] ) == 0; } /* debugging */ static void dumpnode( FTNode* N ) { switch( N->type ) { case SFT_FCALL: printf( "FCALL" ); break; case SFT_INDEX: printf( "INDEX" ); break; case SFT_MIDXSET: printf( "MULTI_INDEX_SET" ); break; case SFT_MPROPSET: printf( "MULTI_PROPERTY_SET" ); break; case SFT_ARGMT: printf( "ARG " ); sgsT_DumpToken( N->token ); break; case SFT_ARGLIST: printf( "ARG_LIST" ); break; case SFT_VARLIST: printf( "VAR_LIST" ); break; case SFT_GVLIST: printf( "GLOBAL_VAR_LIST" ); break; case SFT_USELIST: printf( "USE_LIST" ); break; case SFT_EXPLIST: printf( "EXPR_LIST" ); break; case SFT_ARRLIST: printf( "ARRAY_LIST" ); break; case SFT_MAPLIST: printf( "MAP_LIST" ); break; case SFT_RETURN: printf( "RETURN" ); break; case SFT_BLOCK: printf( "BLOCK" ); break; case SFT_IFELSE: printf( "IF/ELSE" ); break; case SFT_WHILE: printf( "WHILE" ); break; case SFT_DOWHILE: printf( "DO/WHILE" ); break; case SFT_FOR: printf( "FOR" ); break; case SFT_FOREACH: printf( "FOR_EACH" ); break; case SFT_BREAK: printf( "BREAK" ); if( *sgsT_Next( N->token ) == ST_NUMINT ) { sgs_Int val; AS_INTEGER( val, sgsT_Next( N->token ) + 1 ); printf( " %" PRId64, val ); } break; case SFT_CONT: printf( "CONTINUE" ); if( *sgsT_Next( N->token ) == ST_NUMINT ) { sgs_Int val; AS_INTEGER( val, sgsT_Next( N->token ) + 1 ); printf( " %" PRId64, val ); } break; case SFT_FUNC: printf( "FUNC" ); break; default: if( N->token ) sgsT_DumpToken( N->token ); if( N->type == SFT_OPER_P ) printf( " [post]" ); break; } } static void ft_dump( FTNode* node, int level ) { int i; FTNode* N = node; if( !node ) return; for( i = 0; i < level; ++i ) printf( " " ); dumpnode( N ); printf( "\n" ); if( node->child ) { for( i = 0; i < level; ++i ) printf( " " ); printf( "{\n" ); ft_dump( node->child, level + 1 ); for( i = 0; i < level; ++i ) printf( " " ); printf( "}\n" ); } ft_dump( node->next, level ); } void sgsFT_Dump( FTNode* tree ) { ft_dump( tree, 0 ); } /* // C O M P I L E R */ typedef struct _ftcomp { SGS_CTX; TokenList at; } FTComp; #define SFTC FTComp* F #define SFTRET static FTNode* #define SFTC_AT F->at #define SFTC_NEXT F->at = sgsT_Next( F->at ) #define SFTC_IS( type ) (*F->at == (type)) /* WP: char/uchar conversion */ #define SFTC_IN( buf, sz ) isoneofN( (char) *F->at, buf, sz ) #define SFTC_HASERR ( F->C->state & SGS_HAS_ERRORS ) #define SFTC_SETERR F->C->state |= SGS_HAS_ERRORS #define SFTC_ISKEY( name ) is_keyword( F->at, name ) #define SFTC_IS_ID( name ) is_ident( F->at, name ) #define SFTC_LINENUM sgsT_LineNum( F->at ) #define SFTC_PRINTERR( what ) sgs_Msg( F->C, SGS_ERROR, "[line %d] " what, SFTC_LINENUM ) #define SFTC_UNEXP sgs_Msg( F->C, SGS_ERROR, "Unexpected end of code", SFTC_LINENUM ) static FTNode* _make_node( SGS_CTX, int type, TokenList token, FTNode* next, FTNode* child ) { FTNode* node = sgs_Alloc( FTNode ); node->type = type; node->token = token; node->next = next; node->child = child; return node; } #define make_node( ty, tok, next, ch ) _make_node( F->C, ty, tok, next, ch ) void sgsFT_Destroy( SGS_CTX, FTNode* tree ) { if( tree->next ) sgsFT_Destroy( C, tree->next ); if( tree->child ) sgsFT_Destroy( C, tree->child ); sgs_Dealloc( tree ); } #define SFTC_DESTROY( node ) sgsFT_Destroy( F->C, node ) SFTRET parse_exp( SFTC, char* endtoklist, int etlsize ); SFTRET parse_stmt( SFTC ); SFTRET parse_stmtlist( SFTC, char end ); SFTRET parse_function( SFTC, int inexp ); SFTRET parse_arg( SFTC, int argid, char end ) { FTNode* node = NULL; char toks[ 3 ] = { ',', 0, 0 }; toks[1] = end; FUNC_BEGIN; if( SFTC_IS(0) ) { SFTC_UNEXP; goto fail; } if( SFTC_IS( ST_KEYWORD ) ) { SFTC_PRINTERR( "Argument name cannot be a reserved keyword" ); goto fail; } if( !SFTC_IS( ST_IDENT ) && !SFTC_IS( ST_KEYWORD ) ) { sgs_Msg( F->C, SGS_ERROR, "[line %d] Unexpected token while parsing argument %d", SFTC_LINENUM, argid ); goto fail; } node = make_node( SFT_ARGMT, SFTC_AT, NULL, NULL ); SFTC_NEXT; if( SFTC_IS( ST_OP_SET ) ) { SFTC_NEXT; if( SFTC_IS( end ) || SFTC_IS( ',' ) ) { SFTC_PRINTERR( "Expected initializing expression" ); goto fail; } node->child = parse_exp( F, toks, 2 ); if( !node->child ) goto fail; } FUNC_END; return node; fail: if( node ) SFTC_DESTROY( node ); SFTC_SETERR; FUNC_END; return 0; } /* FUNC / parses a list of arguments ARGS / context, function tree, token stream ERRS / unexpected token, @parse_arg */ SFTRET parse_arglist( SFTC, char end ) { FTNode* arglist = make_node( SFT_ARGLIST, NULL, NULL, NULL ); FTNode* curnode = NULL; FTNode* argnode; int id = 1; FUNC_BEGIN; for(;;) { if( SFTC_IS( end ) ) { break; } else if( SFTC_IS( 0 ) ) { SFTC_UNEXP; goto fail; } else if( id == 1 || SFTC_IS( ',' ) ) { if( id != 1 ) SFTC_NEXT; argnode = parse_arg( F, id, end ); if( !argnode && F->C->state & SGS_MUST_STOP ) { goto fail; } if( curnode ) curnode->next = argnode; else arglist->child = argnode; curnode = argnode; id++; } else { sgs_Msg( F->C, SGS_ERROR, "[line %d] Expected ',' or '%c'", SFTC_LINENUM, end ); goto fail; } } FUNC_END; return arglist; fail: SFTC_SETERR; SFTC_DESTROY( arglist ); return NULL; } /* FUNC / calculates the weight of the part ARGS / context, part of function tree ERRS / none */ static int part_weight( FTNode* part, int isfcall, int binary ) { sgs_BreakIf( !part ); if( part->type == SFT_OPER && ST_OP_ASSIGN( *part->token ) ) return 40; if( isfcall ) return 7; if( part->type == SFT_OPER ) { sgs_TokenType type = *part->token; if( binary ) { if( ST_OP_BOOL( type ) ) return 30; if( type == ST_OP_RWCMP ) return 28; /* lower split prio .. */ if( ST_OP_COMP( type ) ) return 29; /* .. than other comp ops */ if( type == ST_OP_CAT ) return 27; if( ST_OP_BINOPS( type ) ) return 26; if( ST_OP_BINADD( type ) ) return 25; if( ST_OP_BINMUL( type ) ) return 24; if( type == ST_OP_MMBR ) return 7; if( type == ST_OP_NOT ) return 7; return 11; } /* unary operators */ return 10; } /* everything else */ return -1; } static LineNum findlinenum( FTNode* node ) /* local, next, child */ { LineNum ln = -1; if( node->token ) return sgsT_LineNum( node->token ); ln = findlinenum( node->next ); if( ln != -1 ) return ln; ln = findlinenum( node->child ); if( ln != -1 ) return ln; return -1; } static LineNum predictlinenum( FTNode* node ) /* next, child, local */ { LineNum ln = -1; ln = findlinenum( node->next ); if( ln != -1 ) return ln; ln = predictlinenum( node->child ); if( ln != -1 ) return ln; if( node->token ) return sgsT_LineNum( node->token ); return -1; } static int level_exp( SGS_CTX, FTNode** tree ) { FTNode* node = *tree, *prev = NULL, *mpp = NULL; int weight = 0, curwt, isfcall, binary, count = 0; FUNC_BEGIN; sgs_BreakIf( !C || !tree ); if( !*tree ) { FUNC_END; return 0; } /* find the most powerful part (mpp) */ while( node ) { count++; /* only interested in operators and subexpressions */ if( node->type != SFT_OPER && node->type != SFT_EXPLIST && node->type != SFT_ARRLIST ) goto _continue; /* function tree test */ isfcall = node->type == SFT_EXPLIST || node->type == SFT_ARRLIST; if( isfcall ) isfcall = !!prev; if( isfcall ) isfcall = prev->type != SFT_OPER || !ST_OP_BINARY( *prev->token ); /* op tests */ binary = node->type == SFT_OPER; if( binary ) binary = prev && node->next; if( binary ) binary = prev->type != SFT_OPER || *prev->token == ST_OP_INC || *prev->token == ST_OP_DEC; /* HACK: discard unary operators following unary operators */ if( !binary && !isfcall && mpp && mpp->next == node && ST_OP_UNARY( *mpp->token ) ) goto _continue; /* weighting */ curwt = part_weight( node, isfcall, binary ); if( ( curwt == 40 && curwt > weight ) || ( curwt != 40 && curwt >= weight ) ) { weight = curwt; mpp = node; } /* move to next */ _continue: prev = node; node = node->next; } if( mpp ) { /* function call */ if( mpp->type == SFT_EXPLIST || mpp->type == SFT_ARRLIST ) { int ret1, ret2; TokenList mpp_token = mpp->token; FTNode* se1 = *tree, *se2 = mpp, *se1i = *tree; while( se1i ) { if( se1i->next == mpp ) se1i->next = NULL; se1i = se1i->next; } FUNC_ENTER; ret1 = level_exp( C, &se1 ); if( !ret1 ) { *tree = NULL; if( se1 ) sgsFT_Destroy( C, se1 ); if( se2 ) sgsFT_Destroy( C, se2 ); FUNC_END; return 0; } if( mpp->type == SFT_ARRLIST && !mpp->child && mpp->next && mpp->next->type == SFT_MAPLIST ) { /* a multiset (index) expression */ mpp->type = SFT_MIDXSET; mpp->child = se1; mpp->child->next = mpp->next; mpp->next = NULL; *tree = mpp; FUNC_END; return 1; } FUNC_ENTER; ret2 = level_exp( C, &se2 ); if( !ret2 ) { *tree = NULL; if( se1 ) sgsFT_Destroy( C, se1 ); if( se2 ) sgsFT_Destroy( C, se2 ); FUNC_END; return 0; } if( *mpp_token == ST_SBRKL ) { /* array */ if( !se2->child || se2->child->next ) { sgs_Msg( C, SGS_ERROR, "[line %d] Invalid number of arguments " "in an array accessor", sgsT_LineNum( mpp_token ) ); *tree = NULL; if( se1 ) sgsFT_Destroy( C, se1 ); if( se2 ) sgsFT_Destroy( C, se2 ); FUNC_END; return 0; } se1->next = se2->child; se2->child = NULL; sgsFT_Destroy( C, se2 ); *tree = _make_node( C, SFT_INDEX, mpp_token, NULL, se1 ); FUNC_END; return 1; } se1->next = se2; *tree = _make_node( C, SFT_FCALL, mpp_token, NULL, se1 ); FUNC_END; return 1; } /* binary ops */ if( mpp->type == SFT_OPER ) { if( mpp == *tree ) prev = NULL; else { prev = *tree; while( prev->next != mpp ) prev = prev->next; } /* binary operators */ if( mpp != *tree && mpp->next && ( prev->type != SFT_OPER || *prev->token == ST_OP_INC || *prev->token == ST_OP_DEC ) ) { TokenList mpptoken = mpp->token; int ret1, ret2; FTNode* se1 = *tree, *se2 = mpp->next, *se1i = *tree; while( se1i ) { if( se1i->next == mpp ) se1i->next = NULL; se1i = se1i->next; } mpp->next = NULL; FUNC_ENTER; ret1 = level_exp( C, &se1 ); if( !ret1 ) { *tree = NULL; if( se1 ) sgsFT_Destroy( C, se1 ); if( se2 ) sgsFT_Destroy( C, se2 ); sgsFT_Destroy( C, mpp ); FUNC_END; return 0; } if( mpptoken && *mpptoken == ST_OP_MMBR && !mpp->child && se2->type == SFT_MAPLIST ) { /* a multiset (property) expression */ mpp->type = SFT_MPROPSET; mpp->child = se1; mpp->child->next = se2; mpp->next = NULL; *tree = mpp; FUNC_END; return 1; } sgsFT_Destroy( C, mpp ); FUNC_ENTER; ret2 = level_exp( C, &se2 ); if( !ret2 ) { *tree = NULL; if( se1 ) sgsFT_Destroy( C, se1 ); if( se2 ) sgsFT_Destroy( C, se2 ); FUNC_END; return 0; } se1->next = se2; *tree = _make_node( C, SFT_OPER, mpptoken, NULL, se1 ); FUNC_END; if( *mpptoken == ST_OP_CAT || *mpptoken == ST_OP_CATEQ ) { /* merge in CAT on first operand (works only with non-assignment op) */ if( *mpptoken == ST_OP_CAT && *se1->token == ST_OP_CAT ) { /* target tree: tree { se1:children, se2 } */ FTNode* tmp = se1->child; while( tmp->next ) tmp = tmp->next; tmp->next = se2; (*tree)->child = se1->child; se1->child = NULL; se1->next = NULL; sgsFT_Destroy( C, se1 ); } /* merge in CAT on second operand */ if( *se2->token == ST_OP_CAT ) { /* target tree: tree { children without se2, se2:children } */ FTNode* tmp = (*tree)->child; while( tmp->next && tmp->next != se2 ) tmp = tmp->next; sgs_BreakIf( tmp->next == NULL ); tmp->next = se2->child; se2->child = NULL; sgsFT_Destroy( C, se2 ); } } FUNC_END; return 1; } /* unary operators must be one of these cases: - no tokens before operator - is inc|dec and there are tokens either before or after the operator - can't have both, can't have neither */ else if( ST_OP_UNARY( *mpp->token ) && ( mpp == *tree || ( ( *mpp->token == ST_OP_INC || *mpp->token == ST_OP_DEC ) && ( mpp != *tree ) != ( !!mpp->next ) ) ) ) { int ret1; if( !mpp->next ) { FTNode* pp = *tree; if( pp == mpp ) goto fail; while( pp->next != mpp ) pp = pp->next; pp->next = NULL; mpp->child = *tree; *tree = mpp; mpp->type = SFT_OPER_P; } else { mpp->child = mpp->next; mpp->next = NULL; } FUNC_ENTER; ret1 = level_exp( C, &mpp->child ); if( !ret1 ) { FUNC_END; return 0; } FUNC_END; return 1; } /* problems */ else goto fail; } } if( count <= 1 ) { FUNC_END; return 1; } /* in case we failed unexpectedly, dump & debug */ sgs_Msg( C, SGS_ERROR, "[line %d] Missing operators or separators", predictlinenum( *tree ) ); C->state |= SGS_HAS_ERRORS; #if SGS_DEBUG && SGS_DEBUG_DATA sgsFT_Dump( *tree ); #endif FUNC_END; return 0; fail: sgs_Msg( C, SGS_ERROR, "[line %d] Invalid expression", sgsT_LineNum( mpp->token ) ); #if SGS_DEBUG && SGS_DEBUG_DATA sgsFT_Dump( *tree ); #endif FUNC_END; return 0; } SFTRET parse_exp( SFTC, char* endtoklist, int etlsize ) { FTNode* node, *cur; char prev = 0; FUNC_BEGIN; if( SFTC_IS( 0 ) ) { SFTC_UNEXP; SFTC_SETERR; FUNC_END; return NULL; } /* special cases */ if( SFTC_ISKEY( "var" ) ) { SFTC_NEXT; node = parse_arglist( F, endtoklist[ endtoklist[0] == ',' ] ); if( node ) node->type = SFT_VARLIST; FUNC_END; return node; } if( SFTC_ISKEY( "global" ) ) { SFTC_NEXT; node = parse_arglist( F, endtoklist[ endtoklist[0] == ',' ] ); if( node ) node->type = SFT_GVLIST; FUNC_END; return node; } cur = node = make_node( 0, NULL, NULL, NULL ); for(;;) { if( SFTC_IN( endtoklist, etlsize ) ) { break; } else if( SFTC_IS( 0 ) ) { SFTC_UNEXP; goto fail; } else if( SFTC_IS( ST_STRING ) || SFTC_IS( ST_NUMINT ) || SFTC_IS( ST_NUMREAL ) ) cur = cur->next = make_node( SFT_CONST, SFTC_AT, NULL, NULL ); else if( SFTC_IS( ST_IDENT ) ) cur = cur->next = make_node( SFT_IDENT, SFTC_AT, NULL, NULL ); else if( SFTC_IS( ST_KEYWORD ) ) { if( SFTC_ISKEY( "function" ) ) { cur->next = parse_function( F, 1 ); if( !cur->next ) goto fail; cur = cur->next; continue; } else cur = cur->next = make_node( SFT_KEYWORD, SFTC_AT, NULL, NULL ); } else if( ST_ISOP( *SFTC_AT ) ) cur = cur->next = make_node( SFT_OPER, SFTC_AT, NULL, NULL ); else if( ST_ISSPEC( *SFTC_AT ) ) { /* array accesor / argument list / subexpression */ if( SFTC_IS( '(' ) || SFTC_IS( '[' ) ) { int isidx = prev == ST_IDENT || prev == ')' || prev == ']'; char cend = SFTC_IS( '(' ) ? ')' : ']'; FTNode* exprlist = make_node( SFTC_IS( '(' ) ? SFT_EXPLIST : SFT_ARRLIST, SFTC_AT, NULL, NULL ); FTNode* expr, * curexpr = NULL; char endcstr[ 3 ] = { ',', 0, 0 }; endcstr[1] = cend; SFTC_NEXT; /* if this is an empty expression (for a function call), do not process it further */ if( !SFTC_IS( cend ) ) { for(;;) { /* if not index, extra ',' is allowed */ if( !isidx && SFTC_IS( cend ) ) { SFTC_NEXT; break; } FUNC_ENTER; expr = parse_exp( F, endcstr, 2 ); if( !expr ) { SFTC_DESTROY( exprlist ); goto fail; } if( curexpr ) curexpr->next = expr; else exprlist->child = expr; curexpr = expr; if( SFTC_IS( cend ) ) { SFTC_NEXT; break; } SFTC_NEXT; } } else SFTC_NEXT; cur = cur->next = exprlist; continue; } /* dictionary */ else if( SFTC_IS( '{' ) ) { TokenList startok = SFTC_AT; FTNode* expr = NULL, *fexp = NULL; /* dictionary expression */ SFTC_NEXT; while( !SFTC_IS( '}' ) ) { if( !SFTC_IS( ST_IDENT ) && !SFTC_IS( ST_STRING ) ) { SFTC_PRINTERR( "Expected key identifier in dictionary expression" ); break; } if( !fexp ) expr = fexp = make_node( SFT_IDENT, SFTC_AT, NULL, NULL ); else { expr->next = make_node( SFT_IDENT, SFTC_AT, NULL, NULL ); expr = expr->next; } SFTC_NEXT; if( !SFTC_IS( ST_OP_SET ) ) { SFTC_PRINTERR( "Expected '=' in dictionary expression " "/ missing closing bracket before '{'" ); break; } SFTC_NEXT; expr->next = parse_exp( F, ",}", 2 ); if( !expr->next ) break; else expr = expr->next; if( SFTC_IS( ',' ) ) SFTC_NEXT; } if( !SFTC_IS( '}' ) ) { if( fexp ) SFTC_DESTROY( fexp ); SFTC_SETERR; } else { cur->next = make_node( SFT_MAPLIST, startok, NULL, fexp ); cur = cur->next; } } else { sgs_Msg( F->C, SGS_ERROR, "[line %d] Unexpected token '%c' found!", SFTC_LINENUM, *SFTC_AT ); F->C->state |= SGS_MUST_STOP; } } else { SFTC_PRINTERR( "INTERNAL ERROR in parse_exp: unknown token found!" ); F->C->state |= SGS_MUST_STOP; } if( F->C->state & SGS_MUST_STOP ) { SFTC_DESTROY( node ); FUNC_END; return NULL; } /* WP: char/uchar conversion */ prev = (char) *SFTC_AT; SFTC_NEXT; } cur = node->next; sgs_Free( F->C, node ); node = cur; if( !node ) { SFTC_PRINTERR( "Empty expression found" ); goto fail; } if( !level_exp( F->C, &node ) ) goto fail; FUNC_END; return node; fail: SFTC_SETERR; if( node ) SFTC_DESTROY( node ); FUNC_END; return NULL; } SFTRET parse_explist( SFTC, char endtok ) { FTNode* explist = make_node( SFT_EXPLIST, SFTC_AT, NULL, NULL ); FTNode* curexp = NULL, *node; char endtoklist[] = { ',', 0, 0 }; endtoklist[1] = endtok; FUNC_BEGIN; for(;;) { if( SFTC_IS( endtok ) ) { break; } else if( SFTC_IS( 0 ) ) { SFTC_UNEXP; goto fail; } else if( SFTC_IS( ',' ) || SFTC_AT == explist->token ) { if( SFTC_AT != explist->token ) SFTC_NEXT; node = parse_exp( F, endtoklist, 2 ); if( !node ) goto fail; if( curexp ) curexp->next = node; else explist->child = node; curexp = node; } else { sgs_Msg( F->C, SGS_ERROR, "[line %d] Expected ',' or '%c'", SFTC_LINENUM, endtok ); goto fail; } } FUNC_END; return explist; fail: SFTC_SETERR; SFTC_DESTROY( explist ); FUNC_END; return NULL; } SFTRET parse_if( SFTC ) { FTNode *node = NULL, *nexp = NULL, *nif = NULL, *nelse = NULL; TokenList begin = SFTC_AT; FUNC_BEGIN; SFTC_NEXT; if( !SFTC_IS( '(' ) ) { SFTC_PRINTERR( "Expected '(' after 'if'" ); goto fail; } SFTC_NEXT; nexp = parse_exp( F, ")", 1 ); if( !nexp ) goto fail; SFTC_NEXT; nif = parse_stmt( F ); if( !nif ) goto fail; if( SFTC_ISKEY( "else" ) ) { SFTC_NEXT; nelse = parse_stmt( F ); if( !nelse ) goto fail; } nexp->next = nif; nif->next = nelse; node = make_node( SFT_IFELSE, begin, NULL, nexp ); FUNC_END; return node; fail: if( nexp ) SFTC_DESTROY( nexp ); if( nif ) SFTC_DESTROY( nif ); if( nelse ) SFTC_DESTROY( nelse ); SFTC_SETERR; FUNC_END; return NULL; } SFTRET parse_while( SFTC ) { FTNode *node, *nexp = NULL, *nwhile = NULL; TokenList begin = SFTC_AT; FUNC_BEGIN; SFTC_NEXT; if( !SFTC_IS( '(' ) ) { SFTC_PRINTERR( "Expected '(' after 'while'" ); goto fail; } SFTC_NEXT; nexp = parse_exp( F, ")", 1 ); if( !nexp ) goto fail; SFTC_NEXT; nwhile = parse_stmt( F ); if( !nwhile ) goto fail; nexp->next = nwhile; node = make_node( SFT_WHILE, begin, NULL, nexp ); FUNC_END; return node; fail: if( nexp ) SFTC_DESTROY( nexp ); if( nwhile ) SFTC_DESTROY( nwhile ); SFTC_SETERR; FUNC_END; return NULL; } SFTRET parse_dowhile( SFTC ) { FTNode *node, *nexp = NULL, *nwhile = NULL; TokenList begin = SFTC_AT; FUNC_BEGIN; SFTC_NEXT; nwhile = parse_stmt( F ); if( !nwhile ) goto fail; if( !SFTC_ISKEY( "while" ) ) { SFTC_PRINTERR( "Expected 'while' after statement in do/while" ); goto fail; } SFTC_NEXT; if( !SFTC_IS( '(' ) ) { SFTC_PRINTERR( "Expected '(' after 'while'" ); goto fail; } SFTC_NEXT; nexp = parse_exp( F, ")", 1 ); if( !nexp ) goto fail; SFTC_NEXT; nexp->next = nwhile; node = make_node( SFT_DOWHILE, begin, NULL, nexp ); FUNC_END; return node; fail: if( nexp ) SFTC_DESTROY( nexp ); if( nwhile ) SFTC_DESTROY( nwhile ); SFTC_SETERR; FUNC_END; return NULL; } SFTRET parse_for( SFTC ) { FTNode *node, *ninit = NULL, *nexp = NULL, *nincr = NULL, *nwhile = NULL; TokenList begin = SFTC_AT; FUNC_BEGIN; SFTC_NEXT; if( !SFTC_IS( '(' ) ) { SFTC_PRINTERR( "Expected '(' after 'for'" ); goto fail; } SFTC_NEXT; ninit = parse_explist( F, ';' ); if( !ninit ) goto fail; SFTC_NEXT; nexp = parse_explist( F, ';' ); if( !nexp ) goto fail; SFTC_NEXT; nincr = parse_explist( F, ')' ); if( !nincr ) goto fail; SFTC_NEXT; nwhile = parse_stmt( F ); if( !nwhile ) goto fail; ninit->next = nexp; nexp->next = nincr; nincr->next = nwhile; node = make_node( SFT_FOR, begin, NULL, ninit ); FUNC_END; return node; fail: if( ninit ) SFTC_DESTROY( ninit ); if( nexp ) SFTC_DESTROY( nexp ); if( nincr ) SFTC_DESTROY( nincr ); if( nwhile ) SFTC_DESTROY( nwhile ); SFTC_SETERR; FUNC_END; return NULL; } SFTRET parse_foreach( SFTC ) { /* (x: => null=>ident (x,x: => ident=>ident (x,: => ident=>null */ FTNode *node, *nvar = NULL, *nkey = NULL, *nexp = NULL, *nwhile = NULL; TokenList begin = SFTC_AT; FUNC_BEGIN; SFTC_NEXT; if( !SFTC_IS( '(' ) ) { SFTC_PRINTERR( "Expected '(' after 'foreach'" ); goto fail; } SFTC_NEXT; if( !SFTC_IS( ST_IDENT ) ) { SFTC_PRINTERR( "Expected identifier after '(' in 'foreach'" ); goto fail; } /* (x:e) */ nkey = make_node( SFT_NULL, SFTC_AT, NULL, NULL ); nvar = make_node( SFT_IDENT, SFTC_AT, NULL, NULL ); SFTC_NEXT; if( !SFTC_IS( ':' ) && !SFTC_IS( ',' ) ) { SFTC_PRINTERR( "Expected ':' or ',' after identifier in 'foreach'" ); goto fail; } if( SFTC_IS( ',' ) ) { SFTC_NEXT; if( !SFTC_IS( ST_IDENT ) && !SFTC_IS( ':' ) ) { SFTC_PRINTERR( "Expected identifier or ':' after ',' in 'foreach'" ); goto fail; } if( SFTC_IS( ST_IDENT ) ) { /* (x,x:e) */ nkey->type = SFT_IDENT; nvar->token = SFTC_AT; SFTC_NEXT; } else { /* (x,:e) */ nkey->type = SFT_IDENT; nvar->type = SFT_NULL; } if( !SFTC_IS( ':' ) ) { SFTC_PRINTERR( "Expected ':' after identifier #2 or ',' in 'foreach'" ); goto fail; } } SFTC_NEXT; nexp = parse_explist( F, ')' ); if( !nexp ) goto fail; SFTC_NEXT; nwhile = parse_stmt( F ); if( !nwhile ) goto fail; nkey->next = nvar; nvar->next = nexp; nexp->next = nwhile; node = make_node( SFT_FOREACH, begin, NULL, nkey ); FUNC_END; return node; fail: if( nvar ) SFTC_DESTROY( nvar ); if( nkey ) SFTC_DESTROY( nkey ); if( nexp ) SFTC_DESTROY( nexp ); if( nwhile ) SFTC_DESTROY( nwhile ); FUNC_END; return NULL; } SFTRET parse_function( SFTC, int inexp ) { int hasname = 0; FTNode *node, *nname = NULL, *nargs = NULL, *nbody = NULL, *nclos = NULL; TokenList begin = SFTC_AT; FUNC_BEGIN; SFTC_NEXT; if( !inexp ) { if( !SFTC_IS( ST_IDENT ) ) { SFTC_PRINTERR( "Expected identifier after 'function'" ); goto fail; } } if( SFTC_IS( ST_IDENT ) ) { hasname = 1; nname = make_node( SFT_IDENT, SFTC_AT, NULL, NULL ); SFTC_NEXT; if( SFTC_IS( ST_OP_MMBR ) ) { nname = make_node( SFT_OPER, SFTC_AT, NULL, nname ); SFTC_NEXT; if( !SFTC_IS( ST_IDENT ) ) { SFTC_PRINTERR( "Expected identifier after 'function', identifier and '.'" ); goto fail; } else { nname->child->next = make_node( SFT_IDENT, SFTC_AT, NULL, NULL ); SFTC_NEXT; } } } if( !SFTC_IS( '(' ) ) { if( !hasname ) SFTC_PRINTERR( "Expected '(' after 'function'" ); else SFTC_PRINTERR( "Expected '(' after 'function' and its name" ); goto fail; } SFTC_NEXT; nargs = parse_arglist( F, ')' ); if( !nargs ) goto fail; SFTC_NEXT; if( SFTC_ISKEY( "use" ) ) { /* closure */ SFTC_NEXT; if( !SFTC_IS( '(' ) ) { SFTC_PRINTERR( "Expected '(' after 'use' in 'function'" ); goto fail; } SFTC_NEXT; nclos = parse_arglist( F, ')' ); if( !nclos ) goto fail; nclos->type = SFT_USELIST; SFTC_NEXT; } else nclos = make_node( SFT_USELIST, SFTC_AT, NULL, NULL ); if( !SFTC_IS( '{' ) && !SFTC_IS( ST_OP_SET ) ) { SFTC_PRINTERR( "Expected '{', '=' or 'use'" ); goto fail; } if( SFTC_IS( ST_OP_SET ) ) { SFTC_NEXT; nbody = parse_explist( F, ';' ); if( !nbody ) goto fail; nbody->type = SFT_RETURN; SFTC_NEXT; } else { nbody = parse_stmt( F ); if( !nbody ) goto fail; } nargs->next = nclos; nclos->next = nbody; nbody->next = nname; node = make_node( SFT_FUNC, begin, NULL, nargs ); FUNC_END; return node; fail: if( nname ) SFTC_DESTROY( nname ); if( nargs ) SFTC_DESTROY( nargs ); if( nclos ) SFTC_DESTROY( nclos ); if( nbody ) SFTC_DESTROY( nbody ); SFTC_SETERR; FUNC_END; return NULL; } SFTRET parse_command( SFTC, int multi ) { FTNode *nargs = NULL; TokenList begin = SFTC_AT; FUNC_BEGIN; SFTC_NEXT; nargs = parse_explist( F, ';' ); if( !nargs ) goto fail; SFTC_NEXT; if( multi ) { /* one argument to one function call */ FTNode *r = NULL, *n = NULL, *p = nargs->child; if( !p ) { if( nargs ) SFTC_DESTROY( nargs ); FUNC_END; return make_node( SFT_BLOCK, begin, NULL, NULL ); } nargs->child = NULL; SFTC_DESTROY( nargs ); while( p ) { FTNode* nn = make_node( SFT_FCALL, begin, NULL, make_node( SFT_IDENT, begin, make_node( SFT_EXPLIST, p->token, NULL, p ), NULL ) ); FTNode* pp = p; p = p->next; pp->next = NULL; if( !r ) r = n = nn; else n = n->next = nn; } return make_node( SFT_BLOCK, begin, NULL, r ); } else { /* one function call */ FTNode* nname = make_node( SFT_IDENT, begin, nargs, NULL ); FUNC_END; return make_node( SFT_FCALL, begin, NULL, nname ); } fail: if( nargs ) SFTC_DESTROY( nargs ); SFTC_SETERR; FUNC_END; return NULL; } SFTRET parse_stmt( SFTC ) { FTNode* node; FUNC_BEGIN; if( SFTC_IS(0) ) { SFTC_UNEXP; goto fail; } /* IF / ELSE */ if( SFTC_ISKEY( "if" ) ) { node = parse_if( F ); FUNC_END; return node; } else if( SFTC_ISKEY( "else" ) ) { SFTC_PRINTERR( "Found 'else' without matching 'if'" ); goto fail; } /* WHILE */ else if( SFTC_ISKEY( "while" ) ) { node = parse_while( F ); FUNC_END; return node; } /* DO / WHILE */ else if( SFTC_ISKEY( "do" ) ) { node = parse_dowhile( F ); FUNC_END; return node; } /* FOR */ else if( SFTC_ISKEY( "for" ) ) { node = parse_for( F ); FUNC_END; return node; } /* FOREACH */ else if( SFTC_ISKEY( "foreach" ) ) { node = parse_foreach( F ); FUNC_END; return node; } /* BREAK */ else if( SFTC_ISKEY( "break" ) ) { TokenList orig = SFTC_AT; SFTC_NEXT; if( SFTC_IS( ST_NUMINT ) ) { sgs_Int blev; AS_INTEGER( blev, SFTC_AT + 1 ); if( blev < 1 || blev > 255 ) { SFTC_PRINTERR( "Invalid break level (can be between 1 and 255)" ); goto fail; } SFTC_NEXT; } if( !SFTC_IS( ';' ) ) { SFTC_UNEXP; goto fail; } SFTC_NEXT; node = make_node( SFT_BREAK, orig, NULL, NULL ); FUNC_END; return node; } /* CONTINUE */ else if( SFTC_ISKEY( "continue" ) ) { TokenList orig = SFTC_AT; SFTC_NEXT; if( SFTC_IS( ST_NUMINT ) ) { sgs_Int blev; AS_INTEGER( blev, SFTC_AT + 1 ); if( blev < 1 || blev > 255 ) { SFTC_PRINTERR( "Invalid continue level (can be between 1 and 255)" ); goto fail; } SFTC_NEXT; } if( !SFTC_IS( ';' ) ) { SFTC_UNEXP; goto fail; } SFTC_NEXT; node = make_node( SFT_CONT, orig, NULL, NULL ); FUNC_END; return node; } /* FUNCTION */ else if( SFTC_ISKEY( "function" ) ) { node = parse_function( F, 0 ); FUNC_END; return node; } /* RETURN */ else if( SFTC_ISKEY( "return" ) ) { SFTC_NEXT; node = parse_explist( F, ';' ); if( !node ) goto fail; node->type = SFT_RETURN; SFTC_NEXT; FUNC_END; return node; } /* VAR / GLOBAL - reuse code in parse_exp */ else if( SFTC_ISKEY( "var" ) || SFTC_ISKEY( "global" ) ) { node = parse_exp( F, ";", 1 ); if( !node ) goto fail; if( !SFTC_IS( ';' ) ) { SFTC_UNEXP; SFTC_DESTROY( node ); goto fail; } SFTC_NEXT; FUNC_END; return node; } /* COMMAND HELPERS */ #define NOT_FCALL ( !sgsT_Next( F->at ) || '(' != *sgsT_Next( F->at ) ) /* SIMPLE COMMANDS */ else if( SFTC_IS_ID( "print" ) && NOT_FCALL ) { node = parse_command( F, 0 ); FUNC_END; return node; } /* MULTIPLIED COMMANDS */ else if( SFTC_IS_ID( "include" ) && NOT_FCALL ) { node = parse_command( F, 1 ); FUNC_END; return node; } /* BLOCK OF STATEMENTS */ else if( SFTC_IS( ST_CBRKL ) ) { SFTC_NEXT; node = parse_stmtlist( F, '}' ); if( !node ) goto fail; SFTC_NEXT; FUNC_END; return node; } /* SEPARATED STATEMENTS */ else { node = parse_explist( F, ';' ); if( node ) { SFTC_NEXT; FUNC_END; return node; } else goto fail; } fail: SFTC_SETERR; FUNC_END; return NULL; } SFTRET parse_stmtlist( SFTC, char end ) { FTNode* stmtlist = make_node( SFT_BLOCK, NULL, NULL, NULL ); FTNode* curstmt = NULL; FUNC_BEGIN; for(;;) { if( SFTC_IS( end ) ) { break; } else if( SFTC_IS( 0 ) ) { SFTC_UNEXP; SFTC_SETERR; goto fail; } else { FTNode* stmt = parse_stmt( F ); if( curstmt ) curstmt->next = stmt; else stmtlist->child = stmt; curstmt = stmt; } if( F->C->state & SGS_MUST_STOP ) goto fail; } FUNC_END; return stmtlist; fail: SFTC_DESTROY( stmtlist ); SFTC_SETERR; FUNC_END; return NULL; } FTNode* sgsFT_Compile( SGS_CTX, TokenList tlist ) { FTNode* ret; FTComp F; { F.C = C; F.at = tlist; } ret = parse_stmtlist( &F, 0 ); return ret; } <file_sep>/src/sgs_proc.c #include <math.h> #include <stdarg.h> #include <ctype.h> #define SGS_INTERNAL #define SGS_REALLY_INTERNAL #define SGS_INTERNAL_STRINGTABLES #include "sgs_xpc.h" #include "sgs_int.h" #define TYPENAME( type ) sgs_VarNames[ type ] #define IS_REFTYPE( type ) ( type == SVT_STRING || type == SVT_FUNC || type == SVT_OBJECT ) #define VAR_ACQUIRE( pvar ) { \ if( IS_REFTYPE( (pvar)->type ) ) (*(pvar)->data.pRC)++; } #define VAR_RELEASE( pvar ) { \ if( IS_REFTYPE( (pvar)->type ) ) var_release( C, pvar ); \ (pvar)->type = SVT_NULL; } #define STK_UNITSIZE sizeof( sgs_Variable ) static void stk_popskip( SGS_CTX, StkIdx num, StkIdx skip ); #define stk_pop( C, num ) stk_popskip( C, num, 0 ) #define _STACK_PREPARE ptrdiff_t _stksz = 0; #define _STACK_PROTECT _stksz = C->stack_off - C->stack_base; C->stack_off = C->stack_top; #define _STACK_PROTECT_SKIP( n ) do{ _stksz = C->stack_off - C->stack_base; \ C->stack_off = C->stack_top - (n); }while(0) #define _STACK_UNPROTECT stk_pop( C, STACKFRAMESIZE ); C->stack_off = C->stack_base + _stksz; #define _STACK_UNPROTECT_SKIP( n ) do{ StkIdx __n = (n); \ stk_popskip( C, STACKFRAMESIZE - __n, __n ); \ C->stack_off = C->stack_base + _stksz; }while(0) typedef union intreal_s { sgs_Int i; sgs_Real r; } intreal_t; /* to work with both insertion and removal algorithms, this function has the following rules: - return the index of the first found item with the right size or just after the right size - if all sizes are less than specified, return the size of the object pool */ static int32_t objpool_binary_search( SGS_CTX, uint32_t appsize ) { int32_t pmin = 0, pmax = C->objpool_size - 1; while( pmin <= pmax ) { int32_t pos = ( pmax + pmin ) / 2; uint32_t ssize = C->objpool_data[ pos ].appsize; if( ssize == appsize ) return pos; else if( ssize < appsize ) pmin = pos + 1; else if( ssize > appsize ) pmax = pos - 1; } return pmin; } static void var_free_object( SGS_CTX, object_t* O ) { if( O->prev ) O->prev->next = O->next; if( O->next ) O->next->prev = O->prev; if( C->objs == O ) C->objs = O->next; #if SGS_OBJPOOL_SIZE > 0 if( O->appsize <= SGS_OBJPOOL_MAX_APPMEM ) { int32_t pos = 0; if( C->objpool_size ) { pos = objpool_binary_search( C, O->appsize ); if( C->objpool_size < SGS_OBJPOOL_SIZE && pos < C->objpool_size ) { memmove( C->objpool_data + pos + 1, C->objpool_data + pos, sizeof( sgs_ObjPoolItem ) * (size_t) ( C->objpool_size - pos ) ); } if( pos >= SGS_OBJPOOL_SIZE ) pos = SGS_OBJPOOL_SIZE - 1; if( C->objpool_size >= SGS_OBJPOOL_SIZE ) sgs_Dealloc( C->objpool_data[ pos ].obj ); } C->objpool_data[ pos ].obj = O; C->objpool_data[ pos ].appsize = O->appsize; if( C->objpool_size < SGS_OBJPOOL_SIZE ) C->objpool_size++; } else sgs_Dealloc( O ); #else sgs_Dealloc( O ); #endif C->objcount--; } static void var_destruct_object( SGS_CTX, object_t* O ) { if( O->iface->destruct ) { int ret; _STACK_PREPARE; _STACK_PROTECT; ret = O->iface->destruct( C, O ); _STACK_UNPROTECT; if( SGS_FAILED( ret ) ) sgs_Msg( C, SGS_ERROR, "failed to call the destructor" ); } } void sgsVM_VarDestroyObject( SGS_CTX, object_t* O ) { var_destruct_object( C, O ); var_free_object( C, O ); } static void var_destroy_string( SGS_CTX, string_t* S ) { #if SGS_STRINGTABLE_MAXLEN >= 0 sgs_Variable tmp; tmp.type = SVT_STRING; tmp.data.S = S; VHTVar* p = (int32_t) S->size <= SGS_STRINGTABLE_MAXLEN ? vht_get( &C->stringtable, &tmp ) : NULL; if( p && p->key.data.S == S ) { S->refcount = 2; /* the 'less code' way to avoid double free */ vht_unset( &C->stringtable, C, &tmp ); printf( "unset string %s\n", str_cstr(S) ); } #endif sgs_Dealloc( S ); } static void var_release( SGS_CTX, sgs_VarPtr p ); static void var_destroy_func( SGS_CTX, func_t* F ) { sgs_VarPtr var = (sgs_VarPtr) func_consts( F ), vend = (sgs_VarPtr) (void*) ASSUME_ALIGNED( func_bytecode( F ), 16 ); while( var < vend ) { VAR_RELEASE( var ); var++; } sgs_Dealloc( F->lineinfo ); membuf_destroy( &F->funcname, C ); membuf_destroy( &F->filename, C ); sgs_Dealloc( F ); } static void var_acquire( SGS_CTX, sgs_VarPtr p ) { UNUSED( C ); if( IS_REFTYPE( p->type ) ) (*p->data.pRC)++; } static void var_release( SGS_CTX, sgs_VarPtr p ) { uint32_t type = p->type; (*p->data.pRC) -= 1; if( (*p->data.pRC) <= 0 ) { switch( type ) { case SVT_STRING: var_destroy_string( C, p->data.S ); break; case SVT_FUNC: var_destroy_func( C, p->data.F ); break; case SVT_OBJECT: var_destroy_object( C, p->data.O ); break; } } } static void var_create_0str( SGS_CTX, sgs_VarPtr out, uint32_t len ) { out->type = SVT_STRING; out->data.S = sgs_Alloc_a( string_t, len + 1 ); out->data.S->refcount = 1; out->data.S->size = len; out->data.S->hash = 0; out->data.S->isconst = 0; var_cstr( out )[ len ] = 0; } void sgsVM_VarCreateString( SGS_CTX, sgs_Variable* out, const char* str, sgs_SizeVal len ) { sgs_Hash hash; uint32_t ulen = (uint32_t) len; /* WP: string limit */ sgs_BreakIf( !str ); if( len < 0 ) ulen = (uint32_t) strlen( str ); /* WP: string limit */ hash = sgs_HashFunc( str, ulen ); if( (int32_t) ulen <= SGS_STRINGTABLE_MAXLEN ) { VHTVar* var = vht_get_str( &C->stringtable, str, ulen, hash ); if( var ) { *out = var->key; out->data.S->refcount++; return; } } var_create_0str( C, out, ulen ); memcpy( str_cstr( out->data.S ), str, ulen ); out->data.S->hash = hash; out->data.S->isconst = 1; if( (int32_t) ulen <= SGS_STRINGTABLE_MAXLEN ) { vht_set( &C->stringtable, C, out, NULL ); out->data.S->refcount--; } } static void var_create_str( SGS_CTX, sgs_Variable* out, const char* str, sgs_SizeVal len ) { uint32_t ulen = (uint32_t) len; /* WP: string limit */ sgs_BreakIf( !str ); if( len < 0 ) ulen = (uint32_t) strlen( str ); /* WP: string limit */ var_create_0str( C, out, ulen ); memcpy( str_cstr( out->data.S ), str, ulen ); } static void var_create_obj( SGS_CTX, sgs_Variable* out, void* data, sgs_ObjInterface* iface, uint32_t xbytes ) { object_t* obj = NULL; #if SGS_OBJPOOL_SIZE > 0 if( xbytes <= SGS_OBJPOOL_MAX_APPMEM ) { int32_t pos = objpool_binary_search( C, xbytes ); if( pos < C->objpool_size && C->objpool_data[ pos ].appsize == xbytes ) { obj = C->objpool_data[ pos ].obj; C->objpool_size--; if( pos < C->objpool_size ) { memmove( C->objpool_data + pos, C->objpool_data + pos + 1, sizeof( sgs_ObjPoolItem ) * (size_t) ( C->objpool_size - pos ) ); } } } #endif if( !obj ) obj = sgs_Alloc_a( object_t, xbytes ); obj->appsize = xbytes; obj->data = data; if( xbytes ) obj->data = ((char*)obj) + sizeof( object_t ); obj->iface = iface; obj->redblue = C->redblue; obj->next = C->objs; obj->prev = NULL; obj->refcount = 1; if( obj->next ) /* ! */ obj->next->prev = obj; C->objcount++; C->objs = obj; out->type = SVT_OBJECT; out->data.O = obj; } /* Call stack */ static int vm_frame_push( SGS_CTX, sgs_Variable* func, uint16_t* T, instr_t* code, size_t icnt ) { sgs_StackFrame* F; if( C->sf_count >= SGS_MAX_CALL_STACK_SIZE ) { sgs_Msg( C, SGS_ERROR, "Max. call stack size reached" ); return 0; } F = C->sf_last ? C->sf_last->cached : C->sf_cached; if( !F ) { F = sgs_Alloc( sgs_StackFrame ); F->cached = NULL; if( C->sf_last ) C->sf_last->cached = F; else C->sf_cached = F; } C->sf_count++; F->func = func; F->code = code; F->iptr = code; F->lptr = code; F->iend = code + icnt; if( func && func->type == SVT_FUNC ) { func_t* fn = func->data.F; F->lptr = F->iptr = F->code = func_bytecode( fn ); F->iend = F->iptr + ( ( fn->size - fn->instr_off ) / sizeof( instr_t ) ); } F->lntable = T; F->nfname = NULL; F->filename = C->filename; F->next = NULL; F->prev = C->sf_last; F->errsup = 0; if( C->sf_last ) { F->errsup = C->sf_last->errsup; C->sf_last->next = F; } else C->sf_first = F; C->sf_last = F; if( C->hook_fn ) C->hook_fn( C->hook_ctx, C, SGS_HOOK_ENTER ); return 1; } static void vm_frame_pop( SGS_CTX ) { sgs_StackFrame* F = C->sf_last; if( C->hook_fn ) C->hook_fn( C->hook_ctx, C, SGS_HOOK_EXIT ); C->sf_count--; if( F->prev ) F->prev->next = NULL; C->sf_last = F->prev; if( C->sf_first == F ) C->sf_first = NULL; } /* Stack management */ #define USING_STACK #define DBG_STACK_CHECK /* TODO fix */ static SGS_INLINE sgs_VarPtr stk_gettop( SGS_CTX ) { #if SGS_DEBUG && SGS_DEBUG_VALIDATE && SGS_DEBUG_EXTRA sgs_BreakIf( C->stack_top == C->stack_base ); DBG_STACK_CHECK #endif return C->stack_top - 1; } static SGS_INLINE StkIdx stk_absindex( SGS_CTX, StkIdx stkid ) { /* WP: stack limit */ if( stkid < 0 ) return (StkIdx) ( C->stack_top - C->stack_off ) + stkid; else return stkid; } static SGS_INLINE sgs_VarPtr stk_getpos( SGS_CTX, StkIdx stkid ) { #if SGS_DEBUG && SGS_DEBUG_VALIDATE && SGS_DEBUG_EXTRA DBG_STACK_CHECK if( stkid < 0 ) sgs_BreakIf( -stkid > C->stack_top - C->stack_off ) else sgs_BreakIf( stkid >= C->stack_top - C->stack_off ) #endif if( stkid < 0 ) return C->stack_top + stkid; else return C->stack_off + stkid; } static SGS_INLINE void stk_setvar( SGS_CTX, StkIdx stkid, sgs_VarPtr var ) { sgs_VarPtr vpos = stk_getpos( C, stkid ); VAR_RELEASE( vpos ); *vpos = *var; VAR_ACQUIRE( vpos ); } static SGS_INLINE void stk_setvar_leave( SGS_CTX, StkIdx stkid, sgs_VarPtr var ) { sgs_VarPtr vpos = stk_getpos( C, stkid ); VAR_RELEASE( vpos ); *vpos = *var; } #define stk_getlpos( C, stkid ) (C->stack_off + stkid) static SGS_INLINE void stk_setlvar( SGS_CTX, StkIdx stkid, sgs_VarPtr var ) { sgs_VarPtr vpos = stk_getlpos( C, stkid ); VAR_RELEASE( vpos ); *vpos = *var; VAR_ACQUIRE( vpos ); } static SGS_INLINE void stk_setlvar_leave( SGS_CTX, StkIdx stkid, sgs_VarPtr var ) { sgs_VarPtr vpos = stk_getlpos( C, stkid ); VAR_RELEASE( vpos ); *vpos = *var; } static SGS_INLINE void stk_setlvar_null( SGS_CTX, StkIdx stkid ) { sgs_VarPtr vpos = stk_getlpos( C, stkid ); VAR_RELEASE( vpos ); } static void stk_makespace( SGS_CTX, StkIdx num ) { /* StkIdx item stack limit */ ptrdiff_t stkoff, stkend; size_t nsz; StkIdx stksz = (StkIdx) ( C->stack_top - C->stack_base ); sgs_BreakIf( num < 0 ); if( stksz + num <= (StkIdx) C->stack_mem ) return; sgs_BreakIf( stksz + num < 0 ); /* overflow test */ stkoff = C->stack_off - C->stack_base; stkend = C->stack_top - C->stack_base; DBG_STACK_CHECK nsz = (size_t) ( stksz + num ) + C->stack_mem * 2; /* MAX( stksz + num, C->stack_mem * 2 ); */ C->stack_base = (sgs_VarPtr) sgs_Realloc( C, C->stack_base, sizeof( sgs_Variable ) * nsz ); C->stack_mem = (uint32_t) nsz; C->stack_off = C->stack_base + stkoff; C->stack_top = C->stack_base + stkend; } static void stk_push( SGS_CTX, sgs_VarPtr var ) { stk_makespace( C, 1 ); *C->stack_top++ = *var; VAR_ACQUIRE( var ); } static void stk_push_leave( SGS_CTX, sgs_VarPtr var ) { stk_makespace( C, 1 ); *C->stack_top++ = *var; } static void stk_push_null( SGS_CTX ) { stk_makespace( C, 1 ); (C->stack_top++)->type = SVT_NULL; } static void stk_push_nulls( SGS_CTX, StkIdx cnt ) { sgs_VarPtr tgt; stk_makespace( C, cnt ); tgt = C->stack_top + cnt; while( C->stack_top < tgt ) (C->stack_top++)->type = SVT_NULL; } static sgs_Variable* stk_insert_pos( SGS_CTX, StkIdx off ) { sgs_Variable *op, *p; stk_makespace( C, 1 ); op = C->stack_off + off, p = C->stack_top; while( p != op ) { *p = *(p-1); p--; } C->stack_top++; return op; } static void stk_insert_null( SGS_CTX, StkIdx off ) { stk_insert_pos( C, off )->type = SVT_NULL; } static void stk_clean( SGS_CTX, sgs_VarPtr from, sgs_VarPtr to ) { /* WP: stack limit */ size_t oh = (size_t) ( C->stack_top - to ); sgs_VarPtr p = from, pend = to; sgs_BreakIf( C->stack_top < to ); sgs_BreakIf( to < from ); sgs_BreakIf( from < C->stack_base ); DBG_STACK_CHECK while( p < pend ) { VAR_RELEASE( p ); p++; } C->stack_top -= to - from; if( oh ) memmove( from, to, oh * STK_UNITSIZE ); } static void stk_popskip( SGS_CTX, StkIdx num, StkIdx skip ) { sgs_VarPtr off, ptr; if( num <= 0 ) return; DBG_STACK_CHECK off = C->stack_top - skip; ptr = off - num; stk_clean( C, ptr, off ); } static void stk_pop1( SGS_CTX ) { sgs_BreakIf( C->stack_top - C->stack_off < 1 ); DBG_STACK_CHECK C->stack_top--; VAR_RELEASE( C->stack_top ); } static void stk_pop1nr( SGS_CTX ) { sgs_BreakIf( C->stack_top - C->stack_off < 1 ); DBG_STACK_CHECK C->stack_top--; } static void stk_pop2( SGS_CTX ) { sgs_BreakIf( C->stack_top - C->stack_off < 1 ); DBG_STACK_CHECK C->stack_top -= 2; VAR_RELEASE( C->stack_top ); VAR_RELEASE( C->stack_top + 1 ); } static void varr_reverse( sgs_Variable* beg, sgs_Variable* end ) { sgs_Variable tmp; end--; while( beg < end ) { tmp = *beg; *beg = *end; *end = tmp; beg++; end--; } } static void stk_transpose( SGS_CTX, StkIdx first, StkIdx all ) { /* assuming: - first >= 0 (1+) - all > first (implies all > 1 -- 2+) */ varr_reverse( C->stack_top - all, C->stack_top - all + first ); varr_reverse( C->stack_top - all, C->stack_top ); } /* The Closure Stack */ static void closure_deref( SGS_CTX, sgs_Closure* cl ) { if( --cl->refcount < 1 ) { VAR_RELEASE( &cl->var ); sgs_Dealloc( cl ); } } #define CLSTK_UNITSIZE sizeof( sgs_Closure* ) static void clstk_makespace( SGS_CTX, StkIdx num ) { /* WP: stack limit */ ptrdiff_t stkoff, stkend; size_t nsz; StkIdx stksz = (StkIdx) ( C->clstk_top - C->clstk_base ); sgs_BreakIf( num < 0 ); if( stksz + num <= (StkIdx) C->clstk_mem ) return; sgs_BreakIf( stksz + num < 0 ); /* overflow test */ stkoff = C->clstk_off - C->clstk_base; stkend = C->clstk_top - C->clstk_base; nsz = (size_t) ( stksz + num ) + C->clstk_mem * 2; /* MAX( stksz + num, C->clstk_mem * 2 ); */ C->clstk_base = (sgs_Closure**) sgs_Realloc( C, C->clstk_base, CLSTK_UNITSIZE * nsz ); C->clstk_mem = (uint32_t) nsz; C->clstk_off = C->clstk_base + stkoff; C->clstk_top = C->clstk_base + stkend; } static void clstk_push( SGS_CTX, sgs_Closure* var ) { clstk_makespace( C, 1 ); var->refcount++; *C->clstk_top++ = var; } static void clstk_push_nulls( SGS_CTX, int num ) { clstk_makespace( C, num ); while( num ) { sgs_Closure* cc = sgs_Alloc( sgs_Closure ); cc->refcount = 1; cc->var.type = SVT_NULL; *C->clstk_top++ = cc; num--; } } static void clstk_clean( SGS_CTX, sgs_Closure** from, sgs_Closure** to ) { /* WP: stack limit */ size_t oh = (size_t) ( C->clstk_top - to ); sgs_Closure** p = from, **pend = to; sgs_BreakIf( C->clstk_top < to ); sgs_BreakIf( to < from ); sgs_BreakIf( from < C->clstk_base ); while( p < pend ) { closure_deref( C, *p ); p++; } C->clstk_top -= to - from; if( oh ) memmove( from, to, oh * CLSTK_UNITSIZE ); } static void clstk_pop( SGS_CTX, int num ) { clstk_clean( C, C->clstk_top - num, C->clstk_top ); } static sgs_Closure* clstk_get( SGS_CTX, int num ) { sgs_BreakIf( num < 0 || C->clstk_off + num >= C->clstk_top ); return C->clstk_off[ num ]; } void sgsVM_PushClosures( SGS_CTX, sgs_Closure** cls, int num ) { clstk_makespace( C, num ); while( num-- ) { (*cls)->refcount++; *C->clstk_top++ = *cls++; } } /* Conversions */ static sgs_Bool var_getbool( SGS_CTX, const sgs_VarPtr var ) { switch( var->type ) { case SVT_NULL: return FALSE; case SVT_BOOL: return var->data.B; case SVT_INT: return var->data.I != 0; case SVT_REAL: return var->data.R != 0; case SVT_STRING: return !!var->data.S->size; case SVT_FUNC: return TRUE; case SVT_CFUNC: return TRUE; case SVT_OBJECT: { int ret; sgs_VarObj* O = var->data.O; _STACK_PREPARE; if( !O->iface->convert ) return TRUE; _STACK_PROTECT; ret = O->iface->convert( C, O, SVT_BOOL ); if( SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1 && stk_gettop( C )->type == SVT_BOOL ) { sgs_Bool v = stk_gettop( C )->data.B; _STACK_UNPROTECT; return v; } _STACK_UNPROTECT; return TRUE; } case SVT_PTR: return var->data.P != NULL; default: return FALSE; } } static sgs_Int var_getint( SGS_CTX, sgs_VarPtr var ) { switch( var->type ) { case SVT_BOOL: return (sgs_Int) var->data.B; case SVT_INT: return var->data.I; case SVT_REAL: return (sgs_Int) var->data.R; case SVT_STRING: return util_atoi( str_cstr( var->data.S ), var->data.S->size ); case SVT_OBJECT: { int ret; sgs_VarObj* O = var->data.O; _STACK_PREPARE; if( !O->iface->convert ) break; _STACK_PROTECT; ret = O->iface->convert( C, O, SVT_INT ); if( SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1 && stk_gettop( C )->type == SVT_INT ) { sgs_Int v = stk_gettop( C )->data.I; _STACK_UNPROTECT; return v; } _STACK_UNPROTECT; } break; case SVT_PTR: return (sgs_Int) (size_t) var->data.P; } return 0; } static sgs_Real var_getreal( SGS_CTX, sgs_Variable* var ) { switch( var->type ) { case SVT_BOOL: return (sgs_Real) var->data.B; case SVT_INT: return (sgs_Real) var->data.I; case SVT_REAL: return var->data.R; case SVT_STRING: return util_atof( str_cstr( var->data.S ), var->data.S->size ); case SVT_OBJECT: { int ret; sgs_VarObj* O = var->data.O; _STACK_PREPARE; if( !O->iface->convert ) break; _STACK_PROTECT; ret = O->iface->convert( C, O, SVT_REAL ); if( SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1 && stk_gettop( C )->type == SVT_REAL ) { sgs_Real v = stk_gettop( C )->data.R; _STACK_UNPROTECT; return v; } _STACK_UNPROTECT; } break; case SVT_PTR: return (sgs_Real) (size_t) var->data.P; } return 0; } static void* var_getptr( SGS_CTX, sgs_VarPtr var ) { switch( var->type ) { case SVT_BOOL: return (void*) (size_t) var->data.B; case SVT_INT: return (void*) (size_t) var->data.I; case SVT_REAL: return (void*) (size_t) var->data.R; case SVT_STRING: return (void*) (size_t) str_cstr( var->data.S ); case SVT_OBJECT: { int ret; sgs_VarObj* O = var->data.O; _STACK_PREPARE; if( !O->iface->convert ) break; _STACK_PROTECT; ret = O->iface->convert( C, O, SVT_PTR ); if( SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1 && stk_gettop( C )->type == SVT_PTR ) { void* v = stk_gettop( C )->data.P; _STACK_UNPROTECT; return v; } _STACK_UNPROTECT; return O->data; } case SVT_PTR: return var->data.P; } return NULL; } static SGS_INLINE sgs_Int var_getint_simple( sgs_VarPtr var ) { switch( var->type ) { case SVT_BOOL: return (sgs_Int) var->data.B; case SVT_INT: return var->data.I; case SVT_REAL: return (sgs_Int) var->data.R; case SVT_STRING: return util_atoi( str_cstr( var->data.S ), var->data.S->size ); } return 0; } static SGS_INLINE sgs_Real var_getreal_simple( sgs_Variable* var ) { switch( var->type ) { case SVT_BOOL: return (sgs_Real) var->data.B; case SVT_INT: return (sgs_Real) var->data.I; case SVT_REAL: return var->data.R; case SVT_STRING: return util_atof( str_cstr( var->data.S ), var->data.S->size ); } return 0; } #define var_initnull( v ) \ do{ sgs_VarPtr __var = (v); __var->type = SVT_NULL; }while(0) #define var_initbool( v, value ) \ do{ sgs_VarPtr __var = (v); __var->type = SVT_BOOL; __var->data.B = value; }while(0) #define var_initint( v, value ) \ do{ sgs_VarPtr __var = (v); __var->type = SVT_INT; __var->data.I = value; }while(0) #define var_initreal( v, value ) \ do{ sgs_VarPtr __var = (v); __var->type = SVT_REAL; __var->data.R = value; }while(0) #define var_initptr( v, value ) \ do{ sgs_VarPtr __var = (v); __var->type = SVT_PTR; __var->data.P = value; }while(0) #define var_setnull( C, v ) \ do{ sgs_VarPtr var = (v); VAR_RELEASE( var ); var->type = SVT_NULL; }while(0) #define var_setbool( C, v, value ) \ do{ sgs_VarPtr var = (v); if( var->type != SVT_BOOL ) \ { VAR_RELEASE( var ); var->type = SVT_BOOL; } var->data.B = value; }while(0) #define var_setint( C, v, value ) \ do{ sgs_VarPtr var = (v); if( var->type != SVT_INT ) \ { VAR_RELEASE( var ); var->type = SVT_INT; } var->data.I = value; }while(0) #define var_setreal( C, v, value ) \ do{ sgs_VarPtr var = (v); if( var->type != SVT_REAL ) \ { VAR_RELEASE( var ); var->type = SVT_REAL; } var->data.R = value; }while(0) #define var_setptr( C, v, value ) \ do{ sgs_VarPtr var = (v); if( var->type != SVT_PTR ) \ { VAR_RELEASE( var ); var->type = SVT_PTR; } var->data.P = value; }while(0) static void init_var_string( SGS_CTX, sgs_Variable* out, sgs_Variable* var ) { char buf[ 32 ]; out->type = SVT_NULL; out->data.S = NULL; switch( var->type ) { case SVT_NULL: var_create_str( C, out, "null", 4 ); break; case SVT_BOOL: if( var->data.B ) var_create_str( C, out, "true", 4 ); else var_create_str( C, out, "false", 5 ); break; case SVT_INT: sprintf( buf, "%" PRId64, var->data.I ); var_create_str( C, out, buf, -1 ); break; case SVT_REAL: sprintf( buf, "%g", var->data.R ); var_create_str( C, out, buf, -1 ); break; case SVT_FUNC: var_create_str( C, out, "function", 8 ); break; case SVT_CFUNC: var_create_str( C, out, "C function", 10 ); break; case SVT_OBJECT: { int ret; sgs_VarObj* O = var->data.O; _STACK_PREPARE; if( !O->iface->convert ) { var_create_str( C, out, O->iface->name, -1 ); break; } _STACK_PROTECT; if( C->sf_count >= SGS_MAX_CALL_STACK_SIZE ) ret = SGS_EINPROC; else { C->sf_count++; ret = O->iface->convert( C, O, SVT_STRING ); C->sf_count--; } if( SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1 && stk_gettop( C )->type == SVT_STRING ) { *out = *stk_gettop( C ); out->data.S->refcount++; /* cancel release from stack to transfer successfully */ _STACK_UNPROTECT; } else { var_create_str( C, out, O->iface->name, -1 ); _STACK_UNPROTECT; } } break; case SVT_PTR: sprintf( buf, "ptr(%p)", var->data.P ); var_create_str( C, out, buf, -1 ); break; } sgs_BreakIf( out->type != SVT_STRING ); } static void vm_convert_bool( SGS_CTX, sgs_Variable* var ) { sgs_Bool value; if( var->type == SVT_BOOL ) return; value = var_getbool( C, var ); VAR_RELEASE( var ); var_initbool( var, value ); } static void vm_convert_int( SGS_CTX, sgs_Variable* var ) { sgs_Int value; if( var->type == SVT_INT ) return; value = var_getint( C, var ); VAR_RELEASE( var ); var_initint( var, value ); } static void vm_convert_real( SGS_CTX, sgs_Variable* var ) { sgs_Real value; if( var->type == SVT_REAL ) return; value = var_getreal( C, var ); VAR_RELEASE( var ); var_initreal( var, value ); } static void vm_convert_string( SGS_CTX, sgs_Variable* var ) { sgs_Variable out; if( var->type == SVT_STRING ) return; init_var_string( C, &out, var ); VAR_RELEASE( var ); *var = out; } static void vm_convert_ptr( SGS_CTX, sgs_Variable* var ) { void* value; if( var->type == SVT_PTR ) return; value = var_getptr( C, var ); VAR_RELEASE( var ); var_initptr( var, value ); } #define CI stk_getpos( C, item ) static void vm_convert_stack_bool( SGS_CTX, StkIdx item ) { if( CI->type != SVT_BOOL ) { sgs_Bool v = var_getbool( C, CI ); var_setbool( C, CI, v ); } } static void vm_convert_stack_int( SGS_CTX, StkIdx item ) { if( CI->type != SVT_INT ) { sgs_Int v = var_getint( C, CI ); var_setint( C, CI, v ); } } static void vm_convert_stack_real( SGS_CTX, StkIdx item ) { if( CI->type != SVT_REAL ) { sgs_Real v = var_getreal( C, CI ); var_setreal( C, CI, v ); } } static void vm_convert_stack_string( SGS_CTX, StkIdx item ) { sgs_Variable out; if( CI->type == SVT_STRING ) return; init_var_string( C, &out, CI ); stk_setvar_leave( C, item, &out ); } static void vm_convert_stack_ptr( SGS_CTX, StkIdx item ) { if( CI->type != SVT_PTR ) { void* v = var_getptr( C, CI ); var_setptr( C, CI, v ); } } #undef CI /* VM mutation */ static SGSRESULT vm_gettype( SGS_CTX, StkIdx item ) { const char* ty = "ERROR"; sgs_Variable* A; if( !sgs_IsValidIndex( C, item ) ) return SGS_EBOUNDS; A = stk_getpos( C, item ); switch( A->type ) { case SVT_NULL: ty = "null"; break; case SVT_BOOL: ty = "bool"; break; case SVT_INT: ty = "int"; break; case SVT_REAL: ty = "real"; break; case SVT_STRING: ty = "string"; break; case SVT_CFUNC: ty = "cfunc"; break; case SVT_FUNC: ty = "func"; break; case SVT_OBJECT: { sgs_VarObj* O = A->data.O; if( O->iface->convert ) { int ret; _STACK_PREPARE; _STACK_PROTECT; ret = O->iface->convert( C, O, SGS_CONVOP_TYPEOF ); if( SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1 ) { _STACK_UNPROTECT_SKIP( 1 ); return SGS_SUCCESS; } _STACK_UNPROTECT; } ty = O->iface->name ? O->iface->name : "object"; } break; case SVT_PTR: ty = "pointer"; break; } sgs_PushString( C, ty ); return SGS_SUCCESS; } static SGSRESULT vm_gcmark( SGS_CTX, sgs_Variable* var ) { if( var->type != SVT_OBJECT || var->data.O->redblue == C->redblue || !var->data.O->iface->gcmark ) return SGS_SUCCESS; else { int ret; sgs_VarObj* O = var->data.O; _STACK_PREPARE; O->redblue = C->redblue; _STACK_PROTECT; ret = O->iface->gcmark( C, O ); _STACK_UNPROTECT; return ret; } } /* Object property / array accessor handling */ int sgs_specfn_call( SGS_CTX ) { int ret; int method_call = sgs_Method( C ); SGSFN( "call" ); if( !sgs_IsCallable( C, 0 ) ) return sgs_Msg( C, SGS_WARNING, "not called on function type" ); if( sgs_StackSize( C ) < 2 ) { sgs_Msg( C, SGS_WARNING, method_call ? "at least one argument expected (this)" : "at least two arguments expected (function, this)" ); return 0; } sgs_PushItem( C, 0 ); ret = sgs_ThisCall( C, sgs_StackSize( C ) - 3, C->sf_last->expected ); if( SGS_FAILED( ret ) ) return sgs_Msg( C, SGS_WARNING, "failed with error %d (%s)", ret, sgs_CodeString( SGS_CODE_ER, ret ) ); return C->sf_last->expected; } int sgs_specfn_apply( SGS_CTX ) { int ret; int method_call = sgs_Method( C ); sgs_SizeVal i, asize; SGSFN( "apply" ); if( !sgs_IsCallable( C, 0 ) ) return sgs_Msg( C, SGS_WARNING, "not called on function type" ); if( ( asize = sgs_ArraySize( C, 2 ) ) < 0 ) return sgs_Msg( C, SGS_WARNING, "argument %d is not an array", method_call ? 2 : 3 ); if( sgs_StackSize( C ) < 3 ) { return sgs_Msg( C, SGS_WARNING, method_call ? "two argument expected (this, args)" : "three arguments expected (function, this, args)" ); } sgs_PushItem( C, 1 ); for( i = 0; i < asize; ++i ) sgs_PushNumIndex( C, 2, i ); sgs_PushItem( C, 0 ); ret = sgs_ThisCall( C, asize, C->sf_last->expected ); if( SGS_FAILED( ret ) ) return sgs_Msg( C, SGS_WARNING, "failed with error %d (%s)", ret, sgs_CodeString( SGS_CODE_ER, ret ) ); return C->sf_last->expected; } static int vm_getidx_builtin( SGS_CTX, sgs_Variable* outmaybe, sgs_Variable* obj, sgs_Variable* idx ) { int res; sgs_Int pos, size; if( obj->type == SVT_STRING ) { size = obj->data.S->size; sgs_PushVariable( C, idx ); res = sgs_ParseInt( C, -1, &pos ); stk_pop1( C ); if( !res ) { sgs_Msg( C, SGS_WARNING, "Expected integer as string index" ); return SGS_EINVAL; } if( pos >= size || pos < -size ) { sgs_Msg( C, SGS_WARNING, "String index out of bounds" ); return SGS_EBOUNDS; } pos = ( pos + size ) % size; sgs_InitStringBuf( C, outmaybe, var_cstr( obj ) + pos, 1 ); return 0; } sgs_Msg( C, SGS_WARNING, "Cannot index variable of type '%s'", TYPENAME( obj->type ) ); return SGS_ENOTFND; } static int vm_getprop_builtin( SGS_CTX, sgs_Variable* outmaybe, sgs_Variable* obj, sgs_Variable* idx ) { if( idx->type == SVT_STRING ) { const char* prop = var_cstr( idx ); switch( obj->type ) { case SVT_STRING: if( !strcmp( prop, "length" ) ) { outmaybe->type = SVT_INT; outmaybe->data.I = obj->data.S->size; return 0; } break; case SVT_FUNC: case SVT_CFUNC: if( !strcmp( prop, "call" ) ) { outmaybe->type = SVT_CFUNC; outmaybe->data.C = sgs_specfn_call; return 0; } if( !strcmp( prop, "apply" ) ) { outmaybe->type = SVT_CFUNC; outmaybe->data.C = sgs_specfn_apply; return 0; } break; } sgs_Msg( C, SGS_WARNING, "Property '%s' not found on " "object of type '%s'", prop, TYPENAME( obj->type ) ); } sgs_Msg( C, SGS_WARNING, "Property of type '%s' not found on " "object of type '%s'", TYPENAME( idx->type ), TYPENAME( obj->type ) ); return SGS_ENOTFND; } extern int sgsstd_array_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* idx, int prop ); extern int sgsstd_dict_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* idx, int prop ); static SGSRESULT vm_runerr_getprop( SGS_CTX, SGSRESULT type, StkIdx origsize, sgs_Variable* idx, int isprop ) { if( type == SGS_ENOTFND ) { char* p; const char* err = isprop ? "Readable property not found" : "Cannot find readable value by index"; stk_push( C, idx ); p = sgs_ToString( C, -1 ); sgs_Msg( C, SGS_WARNING, "%s: \"%s\"", err, p ); } else if( type == SGS_EBOUNDS ) { sgs_Msg( C, SGS_WARNING, "Index out of bounds" ); } else if( type == SGS_EINVAL ) { sgs_Msg( C, SGS_WARNING, "Invalid value type used for %s read", isprop ? "property" : "index" ); } else if( type == SGS_EINPROC ) { sgs_Cntl( C, SGS_CNTL_ERRSUP, 0 ); /* fatal error */ sgs_Msg( C, SGS_ERROR, "%s read process interrupted, possibly by infinite recursion", isprop ? "Property" : "Index" ); } else if( type == SGS_ENOTSUP ) { sgs_Msg( C, SGS_WARNING, "%s read operation not supported on the given variable type", isprop ? "Property" : "Index" ); } else { sgs_Msg( C, SGS_WARNING, "Unknown error on %s read", isprop ? "property" : "index" ); } stk_pop( C, STACKFRAMESIZE - origsize ); return type; } #define VM_GETPROP_ERR( type ) vm_runerr_getprop( C, type, origsize, idx, isprop ) static SGSRESULT vm_runerr_setprop( SGS_CTX, SGSRESULT type, StkIdx origsize, sgs_Variable* idx, int isprop ) { if( type == SGS_ENOTFND ) { char* p; const char* err = isprop ? "Writable property not found" : "Cannot find writable value by index"; stk_push( C, idx ); p = sgs_ToString( C, -1 ); sgs_Msg( C, SGS_WARNING, "%s: \"%s\"", err, p ); } else if( type == SGS_EBOUNDS ) { sgs_Msg( C, SGS_WARNING, "Index out of bounds" ); } else if( type == SGS_EINVAL ) { sgs_Msg( C, SGS_WARNING, "Invalid value type used for %s write", isprop ? "property" : "index" ); } else if( type == SGS_EINPROC ) { sgs_Cntl( C, SGS_CNTL_ERRSUP, 0 ); /* fatal error */ sgs_Msg( C, SGS_ERROR, "%s write process interrupted, possibly by infinite recursion", isprop ? "Property" : "Index" ); } else if( type == SGS_ENOTSUP ) { sgs_Msg( C, SGS_WARNING, "%s write operation not supported on the given variable type", isprop ? "Property" : "Index" ); } else { sgs_Msg( C, SGS_WARNING, "Unknown error on %s write", isprop ? "property" : "index" ); } stk_pop( C, STACKFRAMESIZE - origsize ); return type; } #define VM_SETPROP_ERR( type ) vm_runerr_setprop( C, type, origsize, idx, isprop ) #define var_setvar( C, to, from ) do{ *(to) = *(from); var_acquire( C, (to) ); }while(0) /* VM_GETPROP - two output states: -- 1 is returned, there is a value in the stack -- 0 is returned, valmaybe receives data - if error is returned, no value is available anywhere */ #define VM_GETPROP_RETTOP( ret, ptr ) \ do{ if( !ret ){ stk_push_leave( C, (ptr) ); } }while(0) #define VM_GETPROP_RETIDX( ret, ptr, idx ) \ do{ if( ret ){ stk_setlvar_leave( C, idx, stk_gettop( C ) ); stk_pop1nr( C ); } \ else{ stk_setlvar_leave( C, idx, (ptr) ); } }while(0) #define VM_GETPROP_RETPTR( ret, ptr ) \ do{ if( ret ){ *(ptr) = *stk_gettop( C ); VAR_ACQUIRE( (ptr) ); stk_pop1( C ); } }while(0) static SGSMIXED vm_getprop( SGS_CTX, sgs_Variable* outmaybe, sgs_Variable* obj, sgs_Variable* idx, int isprop ) { int ret = SGS_ENOTSUP, isobj = obj->type == SVT_OBJECT; StkIdx origsize = STACKFRAMESIZE; if( isobj && obj->data.O->iface == sgsstd_dict_iface ) { VHTable* ht = (VHTable*) obj->data.O->data; if( idx->type == SVT_INT && isprop ) { int32_t off = (int32_t) idx->data.I; if( off < 0 || off >= vht_size( ht ) ) return VM_GETPROP_ERR( SGS_EBOUNDS ); else { var_setvar( C, outmaybe, &ht->vars[ off ].val ); return 0; } } else if( idx->type == SVT_STRING ) { VHTVar* var = vht_get( ht, idx ); if( !var ) return VM_GETPROP_ERR( SGS_ENOTFND ); else { var_setvar( C, outmaybe, &var->val ); return 0; } } else { stk_push( C, idx ); if( !sgs_ToString( C, -1 ) ) return VM_GETPROP_ERR( SGS_EINVAL ); else { VHTVar* var = vht_get( ht, stk_gettop( C ) ); if( !var ) return VM_GETPROP_ERR( SGS_ENOTFND ); else { var_setvar( C, outmaybe, &var->val ); stk_pop1( C ); return 0; } } } } else if( isobj && obj->data.O->iface == sgsstd_array_iface ) { sgs_Variable idxvar = *idx; VAR_ACQUIRE( &idxvar ); ret = sgsstd_array_getindex( C, obj->data.O, &idxvar, isprop ); VAR_RELEASE( &idxvar ); if( SGS_SUCCEEDED( ret ) ) ret = 1; /* assuming that on success, the stack has one additional value on top */ } else if( isobj && obj->data.O->iface == sgsstd_map_iface ) { VHTVar* var; VHTable* ht = (VHTable*) obj->data.O->data; /* vht_get does not modify search key */ var = vht_get( ht, idx ); if( !var ) return VM_GETPROP_ERR( SGS_ENOTFND ); else { var_setvar( C, outmaybe, &var->val ); return 0; } } else if( isobj && obj->data.O->iface->getindex ) { sgs_VarObj* O = obj->data.O; sgs_Variable idxvar = *idx; _STACK_PREPARE; if( C->sf_count >= SGS_MAX_CALL_STACK_SIZE ) return SGS_EINPROC; C->sf_count++; _STACK_PROTECT; VAR_ACQUIRE( &idxvar ); ret = O->iface->getindex( C, O, &idxvar, isprop ); VAR_RELEASE( &idxvar ); C->sf_count--; if( SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1 ) { _STACK_UNPROTECT_SKIP( 1 ); ret = 1; } else { _STACK_UNPROTECT; ret = SGS_ENOTFND; } } else { return isprop ? vm_getprop_builtin( C, outmaybe, obj, idx ) : vm_getidx_builtin( C, outmaybe, obj, idx ); } if( SGS_FAILED( ret ) ) return VM_GETPROP_ERR( ret ); return ret; } static void vm_getprop_safe( SGS_CTX, sgs_StkIdx out, sgs_Variable* obj, sgs_Variable* idx, int isprop ) { sgs_Variable tmp; SGSRESULT res = vm_getprop( C, &tmp, obj, idx, isprop ); if( SGS_FAILED( res ) ) { stk_setlvar_null( C, out ); return; } VM_GETPROP_RETIDX( res, &tmp, out ); } static SGSRESULT vm_setprop( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, sgs_Variable* src, int isprop ) { int ret; StkIdx origsize = STACKFRAMESIZE; if( isprop && idx->type != SVT_INT && idx->type != SVT_STRING ) { ret = SGS_EINVAL; } else if( obj->type == SVT_OBJECT && obj->data.O->iface->setindex ) { sgs_Variable idxvar = *idx; sgs_Variable srcvar = *src; sgs_VarObj* O = obj->data.O; _STACK_PREPARE; if( C->sf_count >= SGS_MAX_CALL_STACK_SIZE ) return SGS_EINPROC; C->sf_count++; _STACK_PROTECT; VAR_ACQUIRE( &idxvar ); VAR_ACQUIRE( &srcvar ); ret = O->iface->setindex( C, O, &idxvar, &srcvar, isprop ); VAR_RELEASE( &idxvar ); VAR_RELEASE( &srcvar ); C->sf_count--; _STACK_UNPROTECT; } else ret = SGS_ENOTSUP; if( ret != SGS_SUCCESS ) return VM_SETPROP_ERR( ret ); stk_pop( C, STACKFRAMESIZE - origsize ); return ret; } /* OPs */ static SGSRESULT vm_clone( SGS_CTX, sgs_Variable* var ) { /* strings are supposed to be immutable (even though C functions can accidentally or otherwise modify them with relative ease) */ if( var->type == SVT_OBJECT ) { int ret = SGS_ENOTFND; sgs_VarObj* O = var->data.O; if( O->iface->convert ) { _STACK_PREPARE; _STACK_PROTECT; ret = O->iface->convert( C, O, SGS_CONVOP_CLONE ); _STACK_UNPROTECT_SKIP( SGS_FAILED( ret ) ? 0 : 1 ); } if( SGS_FAILED( ret ) ) return ret; } else { /* even though functions are immutable, they're also impossible to modify, thus there is little need for showing an error when trying to convert one, especially if it's a part of some object to be cloned */ stk_push( C, var ); } return SGS_SUCCESS; } static SGSBOOL vm_op_concat_ex( SGS_CTX, StkIdx args ) { StkIdx i; uint32_t totsz = 0, curoff = 0; sgs_Variable N; if( args < 2 ) return 1; if( STACKFRAMESIZE < args ) return 0; for( i = 1; i <= args; ++i ) { vm_convert_stack_string( C, -i ); totsz += stk_getpos( C, -i )->data.S->size; } var_create_0str( C, &N, totsz ); for( i = args; i >= 1; --i ) { sgs_Variable* var = stk_getpos( C, -i ); memcpy( var_cstr( &N ) + curoff, var_cstr( var ), var->data.S->size ); curoff += var->data.S->size; } stk_setvar_leave( C, -args, &N ); stk_pop( C, args - 1 ); return 1; } static void vm_op_concat( SGS_CTX, StkIdx out, sgs_Variable* A, sgs_Variable* B ) { sgs_Variable lA = *A, lB = *B; int ssz = STACKFRAMESIZE; stk_push( C, &lA ); stk_push( C, &lB ); vm_op_concat_ex( C, 2 ); stk_setlvar( C, out, stk_gettop( C ) ); stk_pop( C, STACKFRAMESIZE - ssz ); } static SGSBOOL vm_op_negate( SGS_CTX, sgs_Variable* out, sgs_Variable* A ) { sgs_Variable lA = *A; VAR_ACQUIRE( &lA ); VAR_RELEASE( out ); switch( lA.type ) { case SVT_NULL: /* guaranteed to be NULL after release */ break; case SVT_BOOL: var_initint( out, -lA.data.B ); break; case SVT_INT: var_initint( out, -lA.data.I ); break; case SVT_REAL: var_initreal( out, -lA.data.R ); break; case SVT_OBJECT: { int ret = SGS_ENOTFND; sgs_VarObj* O = lA.data.O; /* WP: stack limit */ if( O->iface->expr ) { _STACK_PREPARE; StkIdx ofs = (StkIdx) ( out - C->stack_off ); _STACK_PROTECT; ret = O->iface->expr( C, O, A, NULL, SGS_EOP_NEGATE ); if( SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1 ) { C->stack_off[ ofs ] = *stk_gettop( C ); stk_pop1nr( C ); } _STACK_UNPROTECT; } if( SGS_FAILED( ret ) ) { sgs_Msg( C, SGS_ERROR, "Given object does not support negation." ); /* guaranteed to be NULL after release */ } } VAR_RELEASE( &lA ); return 0; default: sgs_Msg( C, SGS_WARNING, "Negating variable of type %s is not supported.", TYPENAME( lA.type ) ); VAR_RELEASE( &lA ); return 0; } VAR_RELEASE( &lA ); return 1; } static void vm_op_boolinv( SGS_CTX, int16_t out, sgs_Variable *A ) { int val = !var_getbool( C, A ); var_setbool( C, C->stack_off + out, val ); } static void vm_op_invert( SGS_CTX, int16_t out, sgs_Variable *A ) { sgs_Int val = ~var_getint( C, A ); var_setint( C, C->stack_off + out, val ); } static SGSRESULT vm_op_incdec( SGS_CTX, sgs_VarPtr out, sgs_Variable *A, int diff ) { switch( A->type ) { case SVT_INT: var_setint( C, out, A->data.I + diff ); break; case SVT_REAL: var_setreal( C, out, A->data.R + diff ); break; default: var_setnull( C, out ); sgs_Msg( C, SGS_ERROR, "Cannot %screment non-numeric variables!", diff > 0 ? "in" : "de" ); return SGS_EINVAL; } return SGS_SUCCESS; } #define ARITH_OP_ADD SGS_EOP_ADD #define ARITH_OP_SUB SGS_EOP_SUB #define ARITH_OP_MUL SGS_EOP_MUL #define ARITH_OP_DIV SGS_EOP_DIV #define ARITH_OP_MOD SGS_EOP_MOD static SGSRESULT vm_arith_op( SGS_CTX, sgs_VarPtr out, sgs_VarPtr a, sgs_VarPtr b, int op ) { if( a->type == SVT_REAL && b->type == SVT_REAL ) { sgs_Real A = a->data.R, B = b->data.R, R; switch( op ){ case ARITH_OP_ADD: R = A + B; break; case ARITH_OP_SUB: R = A - B; break; case ARITH_OP_MUL: R = A * B; break; case ARITH_OP_DIV: if( B == 0 ) goto div0err; R = A / B; break; case ARITH_OP_MOD: if( B == 0 ) goto div0err; R = fmod( A, B ); break; default: R = 0; break; } var_setreal( C, out, R ); return SGS_SUCCESS; } if( a->type == SVT_INT && b->type == SVT_INT ) { sgs_Int A = a->data.I, B = b->data.I, R; switch( op ){ case ARITH_OP_ADD: R = A + B; break; case ARITH_OP_SUB: R = A - B; break; case ARITH_OP_MUL: R = A * B; break; case ARITH_OP_DIV: if( B == 0 ) goto div0err; var_setreal( C, out, ((sgs_Real) A) / ((sgs_Real) B) ); return SGS_SUCCESS; break; case ARITH_OP_MOD: if( B == 0 ) goto div0err; R = A % B; break; default: R = 0; break; } var_setint( C, out, R ); return SGS_SUCCESS; } if( a->type == SVT_OBJECT || b->type == SVT_OBJECT ) { int ret; sgs_Variable lA = *a, lB = *b; VAR_ACQUIRE( &lA ); VAR_ACQUIRE( &lB ); /* WP: stack limit */ StkIdx ofs = (StkIdx) ( out - C->stack_off ); if( a->type == SVT_OBJECT && a->data.O->iface->expr ) { sgs_VarObj* O = a->data.O; _STACK_PREPARE; _STACK_PROTECT; ret = O->iface->expr( C, O, &lA, &lB, op ); USING_STACK ret = SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1; if( ret ) { _STACK_UNPROTECT_SKIP( 1 ); stk_setlvar_leave( C, ofs, C->stack_top - 1 ); C->stack_top--; /* skip acquire/release */ } else { _STACK_UNPROTECT; } if( ret ) { VAR_RELEASE( &lA ); VAR_RELEASE( &lB ); return SGS_SUCCESS; } } if( b->type == SVT_OBJECT && b->data.O->iface->expr ) { sgs_VarObj* O = b->data.O; _STACK_PREPARE; _STACK_PROTECT; ret = O->iface->expr( C, O, &lA, &lB, op ); USING_STACK ret = SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1; if( ret ) { _STACK_UNPROTECT_SKIP( 1 ); stk_setlvar_leave( C, ofs, C->stack_top - 1 ); C->stack_top--; /* skip acquire/release */ } else { _STACK_UNPROTECT; } if( ret ) { VAR_RELEASE( &lA ); VAR_RELEASE( &lB ); return SGS_SUCCESS; } } VAR_RELEASE( &lA ); VAR_RELEASE( &lB ); goto fail; } /* if either variable is of a basic callable type */ if( a->type == SVT_FUNC || a->type == SVT_CFUNC || b->type == SVT_FUNC || b->type == SVT_CFUNC || a->type == SVT_PTR || b->type == SVT_PTR ) goto fail; /* if either are REAL or STRING */ if( a->type == SVT_REAL || b->type == SVT_STRING || a->type == SVT_STRING || b->type == SVT_REAL ) { sgs_Real A = var_getreal_simple( a ), B = var_getreal_simple( b ), R; switch( op ){ case ARITH_OP_ADD: R = A + B; break; case ARITH_OP_SUB: R = A - B; break; case ARITH_OP_MUL: R = A * B; break; case ARITH_OP_DIV: if( B == 0 ) goto div0err; R = A / B; break; case ARITH_OP_MOD: if( B == 0 ) goto div0err; R = fmod( A, B ); break; default: R = 0; break; } var_setreal( C, out, R ); } else { sgs_Int A = var_getint_simple( a ), B = var_getint_simple( b ), R; switch( op ){ case ARITH_OP_ADD: R = A + B; break; case ARITH_OP_SUB: R = A - B; break; case ARITH_OP_MUL: R = A * B; break; case ARITH_OP_DIV: if( B == 0 ) goto div0err; var_setreal( C, out, ((sgs_Real) A) / ((sgs_Real) B) ); return SGS_SUCCESS; case ARITH_OP_MOD: if( B == 0 ) goto div0err; R = A % B; break; default: R = 0; break; } var_setint( C, out, R ); } return SGS_SUCCESS; div0err: VAR_RELEASE( out ); sgs_Msg( C, SGS_ERROR, "Division by 0" ); return SGS_EINPROC; fail: VAR_RELEASE( out ); sgs_Msg( C, SGS_ERROR, "Specified arithmetic operation is not supported on the given set of arguments" ); return SGS_EINVAL; } #define VAR_IOP( pfx, op ) \ static void vm_op_##pfx( SGS_CTX, int16_t out, sgs_Variable* a, sgs_Variable* b ) { \ sgs_Int A = var_getint( C, a ); \ sgs_Int B = var_getint( C, b ); \ var_setint( C, C->stack_off + out, A op B ); \ } VAR_IOP( and, & ) VAR_IOP( or, | ) VAR_IOP( xor, ^ ) VAR_IOP( lsh, << ) VAR_IOP( rsh, >> ) /* returns 0 if equal, >0 if A is bigger, <0 if B is bigger */ #define _SGS_SIGNDIFF( a, b ) ((a)==(b)?0:((a)<(b)?-1:1)) static int vm_compare( SGS_CTX, sgs_VarPtr a, sgs_VarPtr b ) { const uint32_t ta = a->type, tb = b->type; /* both are INT */ if( ta == SVT_INT && tb == SVT_INT ) return _SGS_SIGNDIFF( a->data.I, b->data.I ); /* both are REAL */ if( ta == SVT_REAL && tb == SVT_REAL ) return _SGS_SIGNDIFF( a->data.R, b->data.R ); /* either is OBJECT */ if( ta == SVT_OBJECT || tb == SVT_OBJECT ) { int ret = SGS_ENOTSUP, suc; sgs_Real out = _SGS_SIGNDIFF( ta, tb ); sgs_Variable lA = *a, lB = *b; VAR_ACQUIRE( &lA ); VAR_ACQUIRE( &lB ); if( ta == SVT_OBJECT && a->data.O->iface->expr ) { sgs_VarObj* O = a->data.O; _STACK_PREPARE; _STACK_PROTECT; ret = O->iface->expr( C, O, &lA, &lB, SGS_EOP_COMPARE ); USING_STACK suc = SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1; if( suc ) out = var_getreal( C, C->stack_top - 1 ); _STACK_UNPROTECT; if( suc ) { VAR_RELEASE( &lA ); VAR_RELEASE( &lB ); return _SGS_SIGNDIFF( out, 0 ); } } if( tb == SVT_OBJECT && b->data.O->iface->expr ) { sgs_VarObj* O = b->data.O; _STACK_PREPARE; _STACK_PROTECT; ret = O->iface->expr( C, O, &lA, &lB, SGS_EOP_COMPARE ); USING_STACK suc = SGS_SUCCEEDED( ret ) && STACKFRAMESIZE >= 1; if( suc ) out = var_getreal( C, C->stack_top - 1 ); _STACK_UNPROTECT; if( suc ) { VAR_RELEASE( &lA ); VAR_RELEASE( &lB ); return _SGS_SIGNDIFF( out, 0 ); } } VAR_RELEASE( &lA ); VAR_RELEASE( &lB ); /* fallback: check for equality */ if( ta == tb ) return _SGS_SIGNDIFF( a->data.O, b->data.O ); else return _SGS_SIGNDIFF( ta, tb ); } /* both are FUNC/CFUNC */ if( ( ta == SVT_FUNC || ta == SVT_CFUNC ) && ( tb == SVT_FUNC || tb == SVT_CFUNC ) ) { if( ta != tb ) return _SGS_SIGNDIFF( ta, tb ); if( ta == SVT_FUNC ) return _SGS_SIGNDIFF( a->data.F, b->data.F ); else return _SGS_SIGNDIFF( (void*)a->data.C, (void*)b->data.C ); } /* either is STRING */ if( ta == SVT_STRING || tb == SVT_STRING ) { /* other is NULL */ if( ta == SVT_NULL || tb == SVT_NULL ) return _SGS_SIGNDIFF( ta, tb ); ptrdiff_t out; sgs_Variable A = *a, B = *b; stk_push( C, &A ); stk_push( C, &B ); vm_convert_stack_string( C, -2 ); vm_convert_stack_string( C, -1 ); a = stk_getpos( C, -2 ); b = stk_getpos( C, -1 ); out = memcmp( var_cstr( a ), var_cstr( b ), MIN( a->data.S->size, b->data.S->size ) ); if( out == 0 && a->data.S->size != b->data.S->size ) out = (ptrdiff_t) ( a->data.S->size - b->data.S->size ); stk_pop2( C ); return _SGS_SIGNDIFF( out, 0 ); } /* default comparison */ { sgs_Real ra = var_getreal( C, a ); sgs_Real rb = var_getreal( C, b ); return _SGS_SIGNDIFF( ra, rb ); } } static int vm_forprep( SGS_CTX, StkIdx outiter, sgs_VarPtr obj ) { int ret = SGS_ENOTSUP; sgs_VarObj* O = obj->data.O; VAR_RELEASE( stk_getlpos( C, outiter ) ); if( obj->type != SVT_OBJECT ) { sgs_Msg( C, SGS_ERROR, "Variable of type '%s' " "doesn't have an iterator", TYPENAME( obj->type ) ); return SGS_ENOTSUP; } if( O->iface->convert ) { _STACK_PREPARE; _STACK_PROTECT; ret = SGS_SUCCEEDED( O->iface->convert( C, O, SGS_CONVOP_TOITER ) ) && STACKFRAMESIZE >= 1; _STACK_UNPROTECT_SKIP( ret ); if( ret ) { stk_setlvar_leave( C, outiter, stk_gettop( C ) ); stk_pop1nr( C ); ret = SGS_SUCCESS; } else ret = SGS_EINPROC; } if( SGS_FAILED( ret ) ) { sgs_Msg( C, SGS_ERROR, "Object '%s' doesn't have an iterator", obj->data.O->iface->name ); return SGS_ENOTSUP; } return SGS_SUCCESS; } static SGSMIXED vm_fornext( SGS_CTX, StkIdx outkey, StkIdx outval, sgs_VarPtr iter ) { StkIdx expargs = 0; int flags = 0, ret = SGS_ENOTSUP; sgs_VarObj* O = iter->data.O; _STACK_PREPARE; if( iter->type != SVT_OBJECT ) { sgs_Msg( C, SGS_ERROR, "Iterator is not an object" ); return SGS_EINVAL; } if( O->iface == sgsstd_array_iter_iface ) { sgsstd_array_iter_t* it = (sgsstd_array_iter_t*) O->data; sgsstd_array_header_t* hdr = (sgsstd_array_header_t*) it->ref.data.O->data; if( it->size != hdr->size ) return SGS_EINPROC; else if( outkey < 0 && outval < 0 ) { it->off++; return it->off < it->size; } else { if( outkey >= 0 ) var_setint( C, stk_getlpos( C, outkey ), it->off ); if( outval >= 0 ) stk_setlvar( C, outval, hdr->data + it->off ); return SGS_SUCCESS; } } if( outkey >= 0 ){ flags |= SGS_GETNEXT_KEY; expargs++; } if( outval >= 0 ){ flags |= SGS_GETNEXT_VALUE; expargs++; } _STACK_PROTECT; if( O->iface->getnext ) ret = O->iface->getnext( C, O, flags ); if( SGS_FAILED( ret ) || STACKFRAMESIZE < expargs ) { _STACK_UNPROTECT; sgs_Msg( C, SGS_ERROR, "Failed to retrieve data from iterator" ); return ret; } _STACK_UNPROTECT_SKIP( expargs ); if( !flags ) return ret; else { if( outkey >= 0 ) stk_setlvar( C, outkey, stk_getpos( C, -2 + (outval<0) ) ); if( outval >= 0 ) stk_setlvar( C, outval, stk_gettop( C ) ); stk_pop( C, expargs ); } return SGS_SUCCESS; } static void vm_make_array( SGS_CTX, int args, int outpos ) { int ret; sgs_Variable arr; sgs_BreakIf( sgs_StackSize( C ) < args ); ret = sgsSTD_MakeArray( C, &arr, args ); sgs_BreakIf( ret != SGS_SUCCESS ); UNUSED( ret ); stk_setvar_leave( C, outpos, &arr ); } static void vm_make_dict( SGS_CTX, int args, int outpos ) { int ret; sgs_Variable arr; sgs_BreakIf( sgs_StackSize( C ) < args ); ret = sgsSTD_MakeDict( C, &arr, args ); sgs_BreakIf( ret != SGS_SUCCESS ); UNUSED( ret ); stk_setvar_leave( C, outpos, &arr ); } static void vm_make_closure( SGS_CTX, int args, sgs_Variable* func, int16_t outpos ) { int ret; sgs_BreakIf( C->clstk_top - C->clstk_off < args ); /* WP: range not affected by conversion */ ret = sgsSTD_MakeClosure( C, func, (uint32_t) args ); sgs_BreakIf( ret != SGS_SUCCESS ); UNUSED( ret ); stk_setvar_leave( C, outpos, stk_gettop( C ) ); stk_pop1nr( C ); } static int vm_exec( SGS_CTX, sgs_Variable* consts, rcpos_t constcount ); /* Call the virtual machine. Args must equal the number of arguments pushed before the function - function expects the following items on stack: [this][args] - before call, stack is set up to display only the [args] part - [this] can be uncovered with sgs_Method - arguments are transposed to form [invextraargs][this][reqargs] - return value count is checked against the active range at the moment of return - upon return, this function replaces [this][args] with [expect] */ static int vm_call( SGS_CTX, int args, int clsr, int gotthis, int expect, sgs_Variable* func ) { sgs_Variable V = *func; ptrdiff_t stkcallbase, stkoff = C->stack_off - C->stack_base, clsoff = C->clstk_off - C->clstk_base; int rvc = 0, ret = 1, allowed; gotthis = !!gotthis; stkcallbase = C->stack_top - args - gotthis - C->stack_base; sgs_BreakIf( STACKFRAMESIZE < args + gotthis ); allowed = vm_frame_push( C, &V, NULL, NULL, 0 ); C->stack_off = C->stack_top - args; C->clstk_off = C->clstk_top - clsr; if( allowed ) { /* WP (x2): stack size limit */ C->sf_last->argbeg = (StkIdx) stkcallbase; C->sf_last->argend = (StkIdx) ( C->stack_top - C->stack_base ); /* WP: argument count limit */ C->sf_last->argcount = (uint8_t) args; C->sf_last->inexp = (uint8_t) args; /* WP: returned value count limit */ C->sf_last->expected = (uint8_t) expect; C->sf_last->flags = gotthis ? SGS_SF_METHOD : 0; if( func->type == SVT_CFUNC ) { rvc = (*func->data.C)( C ); if( rvc > STACKFRAMESIZE ) { sgs_Msg( C, SGS_ERROR, "Function returned more variables than there was on the stack" ); rvc = 0; ret = 0; } if( rvc < 0 ) { sgs_Msg( C, SGS_ERROR, "The function could not be called" ); rvc = 0; ret = 0; } } else if( func->type == SVT_FUNC ) { func_t* F = func->data.F; int stkargs = args + ( F->gotthis && gotthis ); int expargs = F->numargs + F->gotthis; C->sf_last->inexp = F->numargs; /* if <this> was expected but wasn't properly passed, insert a NULL in its place */ if( F->gotthis && !gotthis ) { stk_insert_null( C, 0 ); C->stack_off++; C->sf_last->argend++; gotthis = TRUE; stkargs = args + ( F->gotthis && gotthis ); } /* if <this> wasn't expected but was passed, ignore it */ /* add flag to specify presence of "this" */ if( F->gotthis ) C->sf_last->flags |= SGS_SF_HASTHIS; /* fix argument stack */ if( stkargs > expargs ) { int first = F->numargs + gotthis; int all = args + gotthis; stk_transpose( C, first, all ); C->stack_off += all - first; } else stk_push_nulls( C, expargs - stkargs ); stk_push_nulls( C, F->numtmp ); if( F->gotthis && gotthis ) C->stack_off--; { /* WP: const limit */ rcpos_t constcnt = (rcpos_t) ( F->instr_off / sizeof( sgs_Variable* ) ); rvc = vm_exec( C, func_consts( F ), constcnt ); } if( F->gotthis && gotthis ) C->stack_off++; } else if( func->type == SVT_OBJECT ) { sgs_VarObj* O = func->data.O; rvc = SGS_ENOTSUP; if( O->iface->call ) rvc = O->iface->call( C, O ); if( rvc > STACKFRAMESIZE ) { sgs_Msg( C, SGS_ERROR, "Object returned more variables than there was on the stack" ); rvc = 0; ret = 0; } if( rvc < 0 ) { sgs_Msg( C, SGS_ERROR, "The object could not be called" ); rvc = 0; ret = 0; } } else { sgs_Msg( C, SGS_ERROR, "Variable of type '%s' " "cannot be called", TYPENAME( func->type ) ); ret = 0; } } /* remove all stack items before the returned ones */ stk_clean( C, C->stack_base + stkcallbase, C->stack_top - rvc ); C->stack_off = C->stack_base + stkoff; /* remove all closures used in the function */ clstk_clean( C, C->clstk_off, C->clstk_top ); C->clstk_off = C->clstk_base + clsoff; if( allowed ) { if( ret && C->sf_last->flags & SGS_SF_ABORTED ) ret = -1; vm_frame_pop( C ); } if( rvc > expect ) stk_pop( C, rvc - expect ); else stk_push_nulls( C, expect - rvc ); return ret; } #if SGS_DEBUG && SGS_DEBUG_VALIDATE static SGS_INLINE sgs_Variable* const_getvar( sgs_Variable* consts, rcpos_t count, rcpos_t off ) { sgs_BreakIf( off >= count ); return consts + off; } #endif /* Main VM execution loop */ static int vm_exec( SGS_CTX, sgs_Variable* consts, rcpos_t constcount ) { sgs_StackFrame* SF = C->sf_last; int32_t ret = 0; sgs_Variable* cptr = consts; const instr_t* pend = SF->iend; #if SGS_DEBUG && SGS_DEBUG_VALIDATE ptrdiff_t stkoff = C->stack_top - C->stack_off; # define RESVAR( v ) ( CONSTVAR(v) ? const_getvar( cptr, constcount, CONSTDEC(v) ) : stk_getlpos( C, (v) ) ) #else # define RESVAR( v ) ( CONSTVAR(v) ? ( cptr + CONSTDEC(v) ) : stk_getlpos( C, (v) ) ) #endif UNUSED( constcount ); #if SGS_DEBUG && SGS_DEBUG_INSTR { const char *name, *file; sgs_StackFrameInfo( C, SF, &name, &file, NULL ); printf( ">>>\n\t'%s' in %s\n>>>\n", name, file ); } #endif while( SF->iptr < pend ) { const instr_t I = *SF->iptr; #define pp SF->iptr #define instr INSTR_GET_OP(I) #define argA INSTR_GET_A(I) #define argB INSTR_GET_B(I) #define argC INSTR_GET_C(I) #define argE INSTR_GET_E(I) const sgs_VarPtr p1 = C->stack_off + argA; #if SGS_DEBUG # if SGS_DEBUG_INSTR printf( "*** [at 0x%04X] %s ***\n", pp - SF->code, sgs_OpNames[ instr ] ); # endif # if SGS_DEBUG_STATE sgsVM_StackDump( C ); # endif #endif UNUSED( sgs_ErrNames ); UNUSED( sgs_OpNames ); if( C->hook_fn ) C->hook_fn( C->hook_ctx, C, SGS_HOOK_STEP ); switch( instr ) { case SI_NOP: break; case SI_PUSH: { sgs_Variable var = *RESVAR( argB ); stk_push( C, &var ); break; } case SI_INT: { switch( argC ) { case SGS_INT_ERRSUP_INC: SF->errsup++; break; case SGS_INT_ERRSUP_DEC: SF->errsup--; break; } break; } case SI_RETN: { ret = argA; sgs_BreakIf( ( C->stack_top - C->stack_off ) - stkoff < ret && "internal error: stack was corrupted" ); pp = pend; break; } case SI_JUMP: { int16_t off = (int16_t) argE; pp += off; sgs_BreakIf( pp+1 > pend || pp+1 < SF->code ); break; } case SI_JMPT: { int16_t off = (int16_t) argE; sgs_BreakIf( pp+1 + off > pend || pp+1 + off < SF->code ); if( var_getbool( C, RESVAR( argC ) ) ) pp += off; break; } case SI_JMPF: { int16_t off = (int16_t) argE; sgs_BreakIf( pp+1 + off > pend || pp+1 + off < SF->code ); if( !var_getbool( C, RESVAR( argC ) ) ) pp += off; break; } case SI_CALL: { sgs_Variable fnvar = *stk_getlpos( C, argC ); int i, expect = argA, args_from = argB & 0xff, args_to = argC; int gotthis = ( argB & 0x100 ) != 0; stk_makespace( C, args_to - args_from ); for( i = args_from; i < args_to; ++i ) { *C->stack_top++ = C->stack_off[ i ]; VAR_ACQUIRE( C->stack_off + i ); } vm_call( C, args_to - args_from - gotthis, 0, gotthis, expect, &fnvar ); if( expect ) { for( i = expect - 1; i >= 0; --i ) stk_setlvar( C, args_from + i, C->stack_top - expect + i ); stk_pop( C, expect ); } break; } case SI_FORPREP: vm_forprep( C, argA, RESVAR( argB ) ); break; case SI_FORLOAD: vm_fornext( C, argB < 0x100 ? (int)argB : -1, argC < 0x100 ? (int)argC : -1, RESVAR( argA ) ); break; case SI_FORJUMP: { rcpos_t off = argE; sgs_BreakIf( pp+1 > pend || pp+1 < SF->code ); if( vm_fornext( C, -1, -1, RESVAR( argC ) ) < 1 ) pp += off; break; } #define a1 argA #define ARGS_2 const sgs_VarPtr p2 = RESVAR( argB ); #define ARGS_3 const sgs_VarPtr p2 = RESVAR( argB ), p3 = RESVAR( argC ); case SI_LOADCONST: { stk_setlvar( C, argC, cptr + argE ); break; } case SI_GETVAR: { ARGS_2; sgsSTD_GlobalGet( C, p1, p2 ); break; } case SI_SETVAR: { ARGS_3; sgsSTD_GlobalSet( C, p2, p3 ); break; } case SI_GETPROP: { ARGS_3; vm_getprop_safe( C, a1, p2, p3, TRUE ); break; } case SI_SETPROP: { ARGS_3; vm_setprop( C, p1, p2, p3, TRUE ); break; } case SI_GETINDEX: { ARGS_3; vm_getprop_safe( C, a1, p2, p3, FALSE ); break; } case SI_SETINDEX: { ARGS_3; vm_setprop( C, p1, p2, p3, FALSE ); break; } case SI_GENCLSR: clstk_push_nulls( C, argA ); break; case SI_PUSHCLSR: clstk_push( C, clstk_get( C, argA ) ); break; case SI_MAKECLSR: vm_make_closure( C, argC, RESVAR( argB ), (int16_t) argA ); clstk_pop( C, argC ); break; case SI_GETCLSR: stk_setlvar( C, argA, &clstk_get( C, argB )->var ); break; case SI_SETCLSR: { sgs_VarPtr p3 = RESVAR( argC ), cv = &clstk_get( C, argB )->var; VAR_RELEASE( cv ); *cv = *p3; VAR_ACQUIRE( RESVAR( argC ) ); } break; case SI_SET: { ARGS_2; VAR_RELEASE( p1 ); *p1 = *p2; VAR_ACQUIRE( p1 ); break; } case SI_MCONCAT: { vm_op_concat_ex( C, argB ); stk_setlvar_leave( C, argA, stk_gettop( C ) ); stk_pop1nr( C ); break; } case SI_CONCAT: { ARGS_3; vm_op_concat( C, a1, p2, p3 ); break; } case SI_NEGATE: { ARGS_2; vm_op_negate( C, p1, p2 ); break; } case SI_BOOL_INV: { ARGS_2; vm_op_boolinv( C, (int16_t) a1, p2 ); break; } case SI_INVERT: { ARGS_2; vm_op_invert( C, (int16_t) a1, p2 ); break; } case SI_INC: { ARGS_2; vm_op_incdec( C, p1, p2, +1 ); break; } case SI_DEC: { ARGS_2; vm_op_incdec( C, p1, p2, -1 ); break; } case SI_ADD: { ARGS_3; if( p2->type == SVT_REAL && p3->type == SVT_REAL ){ var_setreal( C, p1, p2->data.R + p3->data.R ); break; } if( p2->type == SVT_INT && p3->type == SVT_INT ){ var_setint( C, p1, p2->data.I + p3->data.I ); break; } vm_arith_op( C, p1, p2, p3, ARITH_OP_ADD ); break; } case SI_SUB: { ARGS_3; if( p2->type == SVT_REAL && p3->type == SVT_REAL ){ var_setreal( C, p1, p2->data.R - p3->data.R ); break; } if( p2->type == SVT_INT && p3->type == SVT_INT ){ var_setint( C, p1, p2->data.I - p3->data.I ); break; } vm_arith_op( C, p1, p2, p3, ARITH_OP_SUB ); break; } case SI_MUL: { ARGS_3; if( p2->type == SVT_REAL && p3->type == SVT_REAL ){ var_setreal( C, p1, p2->data.R * p3->data.R ); break; } if( p2->type == SVT_INT && p3->type == SVT_INT ){ var_setint( C, p1, p2->data.I * p3->data.I ); break; } vm_arith_op( C, p1, p2, p3, ARITH_OP_MUL ); break; } case SI_DIV: { ARGS_3; vm_arith_op( C, p1, p2, p3, ARITH_OP_DIV ); break; } case SI_MOD: { ARGS_3; vm_arith_op( C, p1, p2, p3, ARITH_OP_MOD ); break; } case SI_AND: { ARGS_3; vm_op_and( C, (int16_t) a1, p2, p3 ); break; } case SI_OR: { ARGS_3; vm_op_or( C, (int16_t) a1, p2, p3 ); break; } case SI_XOR: { ARGS_3; vm_op_xor( C, (int16_t) a1, p2, p3 ); break; } case SI_LSH: { ARGS_3; vm_op_lsh( C, (int16_t) a1, p2, p3 ); break; } case SI_RSH: { ARGS_3; vm_op_rsh( C, (int16_t) a1, p2, p3 ); break; } #define STRICTLY_EQUAL( val ) if( p2->type != p3->type || ( p2->type == SVT_OBJECT && \ p2->data.O->iface != p3->data.O->iface ) ) { var_setbool( C, p1, val ); break; } #define VCOMPARE( op ) { int cr = vm_compare( C, p2, p3 ) op 0; var_setbool( C, C->stack_off + a1, cr ); } case SI_SEQ: { ARGS_3; STRICTLY_EQUAL( FALSE ); VCOMPARE( == ); break; } case SI_SNEQ: { ARGS_3; STRICTLY_EQUAL( TRUE ); VCOMPARE( != ); break; } case SI_EQ: { ARGS_3; VCOMPARE( == ); break; } case SI_NEQ: { ARGS_3; VCOMPARE( != ); break; } case SI_LT: { ARGS_3; VCOMPARE( < ); break; } case SI_GTE: { ARGS_3; VCOMPARE( >= ); break; } case SI_GT: { ARGS_3; VCOMPARE( > ); break; } case SI_LTE: { ARGS_3; VCOMPARE( <= ); break; } case SI_RAWCMP: { ARGS_3; var_setint( C, C->stack_off + a1, vm_compare( C, p2, p3 ) ); break; } case SI_ARRAY: { vm_make_array( C, argB, argA ); break; } case SI_DICT: { vm_make_dict( C, argB, argA ); break; } #undef VCOMPARE #undef STRICTLY_EQUAL #undef ARGS_2 #undef ARGS_3 #undef a1 #undef RESVAR #undef pp default: sgs_Msg( C, SGS_ERROR, "Illegal instruction executed: 0x%08X", I ); break; } sgs_BreakIf( STACKFRAMESIZE < stkoff ); SF->lptr = ++SF->iptr; } #if SGS_DEBUG && SGS_DEBUG_STATE /* TODO restore memcheck */ sgsVM_StackDump( C ); #endif return ret; } /* INTERNAL INERFACE */ static size_t funct_size( const func_t* f ) { size_t sz = f->size + f->funcname.mem + f->filename.mem; const sgs_Variable* beg = (const sgs_Variable*) (const void*) func_c_consts( f ); const sgs_Variable* end = (const sgs_Variable*) (const void*) ASSUME_ALIGNED( func_c_bytecode( f ), 4 ); while( beg < end ) sz += sgsVM_VarSize( beg++ ); return sz; } size_t sgsVM_VarSize( const sgs_Variable* var ) { size_t out; if( !var ) return 0; out = sizeof( sgs_Variable ); switch( var->type ) { case SVT_FUNC: out += funct_size( var->data.F ); break; /* case SVT_OBJECT: break; */ case SVT_STRING: out += var->data.S->size + sizeof( string_t ); break; } return out; } void sgsVM_VarDump( const sgs_Variable* var ) { /* WP: variable size limit */ printf( "%s (size:%d)", TYPENAME( var->type ), (uint32_t) sgsVM_VarSize( var ) ); switch( var->type ) { case SVT_NULL: break; case SVT_BOOL: printf( " = %s", var->data.B ? "True" : "False" ); break; case SVT_INT: printf( " = %" PRId64, var->data.I ); break; case SVT_REAL: printf( " = %f", var->data.R ); break; case SVT_STRING: printf( " [rc:%"PRId32"] = \"", var->data.S->refcount ); print_safe( stdout, var_cstr( var ), MIN( var->data.S->size, 16 ) ); printf( var->data.S->size > 16 ? "...\"" : "\"" ); break; case SVT_FUNC: printf( " [rc:%"PRId32"]", var->data.F->refcount ); break; case SVT_CFUNC: printf( " = %p", (void*)(size_t) var->data.C ); break; case SVT_OBJECT: printf( "TODO [object impl]" ); break; case SVT_PTR: printf( " = %p", var->data.P ); break; } } void sgsVM_StackDump( SGS_CTX ) { ptrdiff_t i, stksz = C->stack_top - C->stack_base; /* WP: stack limit */ printf( "STACK (size=%d, bytes=%d/%d)--\n", (int) stksz, (int)( stksz * (ptrdiff_t) STK_UNITSIZE ), (int)( C->stack_mem * STK_UNITSIZE ) ); for( i = 0; i < stksz; ++i ) { sgs_VarPtr var = C->stack_base + i; if( var == C->stack_off ) printf( "-- offset --\n" ); printf( " " ); sgsVM_VarDump( var ); printf( "\n" ); } printf( "--\n" ); } int sgsVM_ExecFn( SGS_CTX, int numtmp, void* code, size_t codesize, void* data, size_t datasize, int clean, uint16_t* T ) { ptrdiff_t stkoff = C->stack_off - C->stack_base; int rvc = 0, allowed; allowed = vm_frame_push( C, NULL, T, (instr_t*) code, codesize / sizeof( instr_t ) ); stk_push_nulls( C, numtmp ); if( allowed ) { /* WP: const limit */ rvc = vm_exec( C, (sgs_Variable*) data, (rcpos_t) ( datasize / sizeof( sgs_Variable* ) ) ); } C->stack_off = C->stack_base + stkoff; if( clean ) stk_pop( C, (StkIdx) ( C->stack_top - C->stack_off ) ); /* WP: stack limit */ else { /* keep only returned values */ stk_clean( C, C->stack_off, C->stack_top - rvc ); } if( allowed ) vm_frame_pop( C ); return rvc; } int sgsVM_VarCall( SGS_CTX, sgs_Variable* var, int args, int clsr, int expect, int gotthis ) { return vm_call( C, args, clsr, gotthis, expect, var ); } /* ---- The core interface ---- */ /* OBJECT CREATION */ void sgs_InitNull( sgs_Variable* out ) { out->type = SVT_NULL; } void sgs_InitBool( sgs_Variable* out, sgs_Bool value ) { out->type = SVT_BOOL; out->data.B = value ? 1 : 0; } void sgs_InitInt( sgs_Variable* out, sgs_Int value ) { out->type = SVT_INT; out->data.I = value; } void sgs_InitReal( sgs_Variable* out, sgs_Real value ) { out->type = SVT_REAL; out->data.R = value; } void sgs_InitStringBuf( SGS_CTX, sgs_Variable* out, const char* str, sgs_SizeVal size ) { if( str ) var_create_str( C, out, str, size ); else var_create_0str( C, out, (uint32_t) size ); /* WP: string limit */ } void sgs_InitString( SGS_CTX, sgs_Variable* out, const char* str ) { sgs_BreakIf( !str && "sgs_InitString: str = NULL" ); var_create_str( C, out, str, -1 ); } void sgs_InitCFunction( sgs_Variable* out, sgs_CFunc func ) { out->type = SVT_CFUNC; out->data.C = func; } void sgs_InitObject( SGS_CTX, sgs_Variable* out, void* data, sgs_ObjInterface* iface ) { var_create_obj( C, out, data, iface, 0 ); } void* sgs_InitObjectIPA( SGS_CTX, sgs_Variable* out, uint32_t added, sgs_ObjInterface* iface ) { var_create_obj( C, out, NULL, iface, added ); return out->data.O->data; } void sgs_InitPtr( sgs_Variable* out, void* ptr ) { out->type = SVT_PTR; out->data.P = ptr; } void sgs_InitObjectPtr( sgs_Variable* out, sgs_VarObj* obj ) { out->type = SVT_OBJECT; out->data.O = obj; VAR_ACQUIRE( out ); } SGSRESULT sgs_InitArray( SGS_CTX, sgs_Variable* out, sgs_SizeVal numitems ) { return sgsSTD_MakeArray( C, out, numitems ); } SGSRESULT sgs_InitDict( SGS_CTX, sgs_Variable* out, sgs_SizeVal numitems ) { return sgsSTD_MakeDict( C, out, numitems ); } SGSRESULT sgs_InitMap( SGS_CTX, sgs_Variable* out, sgs_SizeVal numitems ) { return sgsSTD_MakeMap( C, out, numitems ); } /* STACK & SUB-ITEMS */ void sgs_PushNull( SGS_CTX ) { stk_push_null( C ); } void sgs_PushBool( SGS_CTX, sgs_Bool value ) { sgs_Variable var; var.type = SVT_BOOL; var.data.B = value ? 1 : 0; stk_push_leave( C, &var ); } void sgs_PushInt( SGS_CTX, sgs_Int value ) { sgs_Variable var; var.type = SVT_INT; var.data.I = value; stk_push_leave( C, &var ); } void sgs_PushReal( SGS_CTX, sgs_Real value ) { sgs_Variable var; var.type = SVT_REAL; var.data.R = value; stk_push_leave( C, &var ); } void sgs_PushStringBuf( SGS_CTX, const char* str, sgs_SizeVal size ) { sgs_Variable var; if( str ) var_create_str( C, &var, str, size ); else var_create_0str( C, &var, (uint32_t) size ); /* WP: string limit */ stk_push_leave( C, &var ); } void sgs_PushString( SGS_CTX, const char* str ) { sgs_Variable var; sgs_BreakIf( !str && "sgs_PushString: str = NULL" ); var_create_str( C, &var, str, -1 ); stk_push_leave( C, &var ); } void sgs_PushCFunction( SGS_CTX, sgs_CFunc func ) { sgs_Variable var; var.type = SVT_CFUNC; var.data.C = func; stk_push_leave( C, &var ); } void sgs_PushObject( SGS_CTX, void* data, sgs_ObjInterface* iface ) { sgs_Variable var; var_create_obj( C, &var, data, iface, 0 ); stk_push_leave( C, &var ); } void* sgs_PushObjectIPA( SGS_CTX, uint32_t added, sgs_ObjInterface* iface ) { sgs_Variable var; var_create_obj( C, &var, NULL, iface, added ); stk_push_leave( C, &var ); return var.data.O->data; } void sgs_PushPtr( SGS_CTX, void* ptr ) { sgs_Variable var; var.type = SVT_PTR; var.data.P = ptr; stk_push_leave( C, &var ); } void sgs_PushObjectPtr( SGS_CTX, sgs_VarObj* obj ) { sgs_Variable var; var.type = SVT_OBJECT; var.data.O = obj; stk_push( C, &var ); /* a new reference must be created */ } SGSRESULT sgs_PushArray( SGS_CTX, sgs_SizeVal numitems ) { int res; sgs_Variable var; if( SGS_FAILED( res = sgsSTD_MakeArray( C, &var, numitems ) ) ) return res; stk_push_leave( C, &var ); return SGS_SUCCESS; } SGSRESULT sgs_PushDict( SGS_CTX, sgs_SizeVal numitems ) { int res; sgs_Variable var; if( SGS_FAILED( res = sgsSTD_MakeDict( C, &var, numitems ) ) ) return res; stk_push_leave( C, &var ); return SGS_SUCCESS; } SGSRESULT sgs_PushMap( SGS_CTX, sgs_SizeVal numitems ) { int res; sgs_Variable var; if( SGS_FAILED( res = sgsSTD_MakeMap( C, &var, numitems ) ) ) return res; stk_push_leave( C, &var ); return SGS_SUCCESS; } SGSRESULT sgs_PushVariable( SGS_CTX, sgs_Variable* var ) { if( var->type >= SGS_VT__COUNT ) return SGS_EINVAL; stk_push( C, var ); return SGS_SUCCESS; } SGSRESULT sgs_StoreVariable( SGS_CTX, sgs_Variable* var ) { if( !STACKFRAMESIZE ) return SGS_ENOTFND; *var = *stk_gettop( C ); VAR_ACQUIRE( var ); stk_pop1( C ); return SGS_SUCCESS; } SGSRESULT sgs_PushItem( SGS_CTX, StkIdx item ) { if( !sgs_IsValidIndex( C, item ) ) return SGS_EBOUNDS; { sgs_Variable copy = *stk_getpos( C, item ); stk_push( C, &copy ); return SGS_SUCCESS; } } SGSRESULT sgs_StoreItem( SGS_CTX, StkIdx item ) { int ret; StkIdx g; C->stack_top--; ret = sgs_IsValidIndex( C, item ); g = stk_absindex( C, item ); C->stack_top++; if( !ret ) return SGS_EBOUNDS; stk_setlvar( C, g, stk_getpos( C, -1 ) ); stk_pop1( C ); return SGS_SUCCESS; } SGSRESULT sgs_InsertVariable( SGS_CTX, int pos, sgs_Variable* var ) { sgs_Variable* vp; if( pos > sgs_StackSize( C ) || pos < -sgs_StackSize( C ) - 1 ) return SGS_EBOUNDS; if( pos < 0 ) pos = sgs_StackSize( C ) + pos + 1; vp = stk_insert_pos( C, pos ); *vp = *var; VAR_ACQUIRE( var ); return SGS_SUCCESS; } #define _EL_BACKUP int32_t oel = C->minlev; #define _EL_SETMAX C->minlev = C->apilev; #define _EL_RESET C->minlev = oel; SGSRESULT sgs_GetIndexPPP( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, sgs_Variable* out, int isprop ) { int ret; _EL_BACKUP; _EL_SETMAX; ret = vm_getprop( C, out, obj, idx, isprop ); if( SGS_SUCCEEDED( ret ) ) VM_GETPROP_RETPTR( ret, out ); _EL_RESET; return SGS_FAILED( ret ) ? ret : SGS_SUCCESS; } SGSRESULT sgs_SetIndexPPP( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, sgs_Variable* val, int isprop ) { int ret; _EL_BACKUP; _EL_SETMAX; ret = vm_setprop( C, obj, idx, val, isprop ); _EL_RESET; return SGS_FAILED( ret ) ? ret : SGS_SUCCESS; } SGSRESULT sgs_PushIndexPP( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, int isprop ) { int ret; sgs_Variable tmp; _EL_BACKUP; _EL_SETMAX; ret = vm_getprop( C, &tmp, obj, idx, isprop ); if( SGS_SUCCEEDED( ret ) ) VM_GETPROP_RETTOP( ret, &tmp ); _EL_RESET; return SGS_FAILED( ret ) ? ret : SGS_SUCCESS; } SGSRESULT sgs_StoreIndexPP( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, int isprop ) { int ret; sgs_Variable val; if( !sgs_PeekStackItem( C, -1, &val ) ) return SGS_EINPROC; ret = sgs_SetIndexPPP( C, obj, idx, &val, isprop ); if( SGS_SUCCEEDED( ret ) ) stk_pop1( C ); return ret; } SGSRESULT sgs_GetIndexIPP( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, sgs_Variable* out, int isprop ) { int res; sgs_Variable vO; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_GetIndexPPP( C, &vO, idx, out, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_GetIndexPIP( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, sgs_Variable* out, int isprop ) { int res; sgs_Variable vI; if( ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_GetIndexPPP( C, obj, &vI, out, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_GetIndexIIP( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, sgs_Variable* out, int isprop ) { int res; sgs_Variable vO, vI; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_GetIndexPPP( C, &vO, &vI, out, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_GetIndexPPI( SGS_CTX, sgs_Variable* obj, sgs_Variable* idx, sgs_StkIdx out, int isprop ) { int res; sgs_Variable vV; if( ( res = sgs_GetIndexPPP( C, obj, idx, &vV, isprop ) ) || ( res = sgs_SetStackItem( C, out, &vV ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_GetIndexIPI( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, sgs_StkIdx out, int isprop ) { int res; sgs_Variable vO, vV; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_GetIndexPPP( C, &vO, idx, &vV, isprop ) ) || ( res = sgs_SetStackItem( C, out, &vV ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_GetIndexPII( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, sgs_StkIdx out, int isprop ) { int res; sgs_Variable vI, vV; if( ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_GetIndexPPP( C, obj, &vI, &vV, isprop ) ) || ( res = sgs_SetStackItem( C, out, &vV ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_GetIndexIII( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, sgs_StkIdx out, int isprop ) { int res; sgs_Variable vO, vI, vV; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_GetIndexPPP( C, &vO, &vI, &vV, isprop ) ) || ( res = sgs_SetStackItem( C, out, &vV ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_SetIndexIPP( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, sgs_Variable* val, int isprop ) { int res; sgs_Variable vO; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_SetIndexPPP( C, &vO, idx, val, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_SetIndexPIP( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, sgs_Variable* val, int isprop ) { int res; sgs_Variable vI; if( ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_SetIndexPPP( C, obj, &vI, val, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_SetIndexIIP( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, sgs_Variable* val, int isprop ) { int res; sgs_Variable vO, vI; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_SetIndexPPP( C, &vO, &vI, val, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_SetIndexIPI( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, sgs_StkIdx val, int isprop ) { int res; sgs_Variable vO, vV; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PeekStackItem( C, val, &vV ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_SetIndexPPP( C, &vO, idx, &vV, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_SetIndexPII( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, sgs_StkIdx val, int isprop ) { int res; sgs_Variable vI, vV; if( ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PeekStackItem( C, val, &vV ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_SetIndexPPP( C, obj, &vI, &vV, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_SetIndexIII( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, sgs_StkIdx val, int isprop ) { int res; sgs_Variable vO, vI, vV; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PeekStackItem( C, val, &vV ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_SetIndexPPP( C, &vO, &vI, &vV, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_PushIndexIP( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, int isprop ) { int res; sgs_Variable vO; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PushIndexPP( C, &vO, idx, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_PushIndexPI( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, int isprop ) { int res; sgs_Variable vI; if( ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PushIndexPP( C, obj, &vI, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_PushIndexII( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, int isprop ) { int res; sgs_Variable vO, vI; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PushIndexPP( C, &vO, &vI, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_StoreIndexIP( SGS_CTX, sgs_StkIdx obj, sgs_Variable* idx, int isprop ) { int res; sgs_Variable vO; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_StoreIndexPP( C, &vO, idx, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_StoreIndexPI( SGS_CTX, sgs_Variable* obj, sgs_StkIdx idx, int isprop ) { int res; sgs_Variable vI; if( ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_StoreIndexPP( C, obj, &vI, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_StoreIndexII( SGS_CTX, sgs_StkIdx obj, sgs_StkIdx idx, int isprop ) { int res; sgs_Variable vO, vI; if( ( res = sgs_PeekStackItem( C, obj, &vO ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_PeekStackItem( C, idx, &vI ) ? SGS_SUCCESS : SGS_EBOUNDS ) || ( res = sgs_StoreIndexPP( C, &vO, &vI, isprop ) ) ) return res; return SGS_SUCCESS; } SGSRESULT sgs_GetGlobalPP( SGS_CTX, sgs_Variable* idx, sgs_Variable* out ) { int ret; _EL_BACKUP; out->type = SVT_NULL; _EL_SETMAX; ret = sgsSTD_GlobalGet( C, out, idx ); _EL_RESET; return ret; } SGSRESULT sgs_SetGlobalPP( SGS_CTX, sgs_Variable* idx, sgs_Variable* val ) { sgs_Variable vO; vO.type = SVT_OBJECT; vO.data.O = C->_G; return sgs_SetIndexPPP( C, &vO, idx, val, 0 ); } SGSRESULT sgs_PushProperty( SGS_CTX, sgs_StkIdx obj, const char* name ) { int ret; if( !sgs_IsValidIndex( C, obj ) ) return SGS_EBOUNDS; obj = stk_absindex( C, obj ); sgs_PushString( C, name ); ret = sgs_PushIndexII( C, obj, -1, TRUE ); stk_popskip( C, 1, SGS_SUCCEEDED( ret ) ? 1 : 0 ); return ret; } SGSRESULT sgs_StoreProperty( SGS_CTX, StkIdx obj, const char* name ) { int ret; if( !sgs_IsValidIndex( C, obj ) ) return SGS_EBOUNDS; obj = stk_absindex( C, obj ); sgs_PushString( C, name ); ret = sgs_SetIndexIII( C, obj, -1, -2, TRUE ); stk_pop( C, ret == SGS_SUCCESS ? 2 : 1 ); return ret; } SGSRESULT sgs_PushNumIndex( SGS_CTX, StkIdx obj, sgs_Int idx ) { sgs_Variable ivar; ivar.type = SVT_INT; ivar.data.I = idx; return sgs_PushIndexIP( C, obj, &ivar, FALSE ); } SGSRESULT sgs_StoreNumIndex( SGS_CTX, StkIdx obj, sgs_Int idx ) { sgs_Variable ivar; ivar.type = SVT_INT; ivar.data.I = idx; return sgs_StoreIndexIP( C, obj, &ivar, FALSE ); } SGSRESULT sgs_PushGlobal( SGS_CTX, const char* name ) { int ret; _EL_BACKUP; sgs_Variable str; sgs_VarPtr pos; sgs_PushString( C, name ); pos = stk_getpos( C, -1 ); str = *pos; sgs_Acquire( C, &str ); _EL_SETMAX; ret = sgsSTD_GlobalGet( C, pos, pos ); _EL_RESET; sgs_Release( C, &str ); if( ret != SGS_SUCCESS ) sgs_Pop( C, 1 ); return ret; } SGSRESULT sgs_StoreGlobal( SGS_CTX, const char* name ) { int ret; _EL_BACKUP; if( sgs_StackSize( C ) < 1 ) return SGS_EINPROC; sgs_PushString( C, name ); _EL_SETMAX; ret = sgsSTD_GlobalSet( C, stk_getpos( C, -1 ), stk_getpos( C, -2 ) ); _EL_RESET; sgs_Pop( C, ret == SGS_SUCCESS ? 2 : 1 ); return ret; } void sgs_GetEnv( SGS_CTX, sgs_Variable* out ) { sgs_InitObjectPtr( out, C->_G ); } SGSRESULT sgs_SetEnv( SGS_CTX, sgs_Variable* var ) { if( var->type != SVT_OBJECT || var->data.O->iface != sgsstd_dict_iface ) return SGS_ENOTSUP; sgs_ObjRelease( C, C->_G ); C->_G = var->data.O; VAR_ACQUIRE( var ); return SGS_SUCCESS; } void sgs_PushEnv( SGS_CTX ) { sgs_PushObjectPtr( C, C->_G ); } SGSRESULT sgs_StoreEnv( SGS_CTX ) { int ret; sgs_Variable var; if( !sgs_PeekStackItem( C, -1, &var ) ) return SGS_EINPROC; ret = sgs_SetEnv( C, &var ); if( SGS_SUCCEEDED( ret ) ) stk_pop1( C ); return SGS_SUCCESS; } /* o = offset (isprop=true) (sizeval) p = property (isprop=true) (null-terminated string) s = super-secret property (isprop=true) (sizeval, buffer) i = index (isprop=false) (sizeval) k = key (isprop=false) (null-terminated string) n = null-including key (isprop=false) (sizeval, buffer) */ static SGSRESULT sgs_PushPathBuf( SGS_CTX, StkIdx item, const char* path, size_t plen, va_list* pargs ) { #define args *pargs int ret = sgs_PushItem( C, item ); size_t i = 0; if( ret != SGS_SUCCESS ) return ret; while( i < plen ) { sgs_Variable key; sgs_SizeVal S = -1; char* P = NULL; int prop = -1; char a = path[ i++ ]; if( a == 'o' ){ prop = 1; S = va_arg( args, sgs_SizeVal ); } else if( a == 'p' ){ prop = 1; P = va_arg( args, char* ); if( !P ) return SGS_EINVAL; } else if( a == 's' ){ prop = 1; S = va_arg( args, sgs_SizeVal ); P = va_arg( args, char* ); if( !P ) return SGS_EINVAL; } else if( a == 'i' ){ prop = 0; S = va_arg( args, sgs_SizeVal ); } else if( a == 'k' ){ prop = 0; P = va_arg( args, char* ); if( !P ) return SGS_EINVAL; } else if( a == 'n' ){ prop = 0; S = va_arg( args, sgs_SizeVal ); P = va_arg( args, char* ); if( !P ) return SGS_EINVAL; } else return SGS_EINVAL; if( P ) { if( S >= 0 ) sgs_InitStringBuf( C, &key, P, S ); else sgs_InitString( C, &key, P ); } else if( S >= 0 ) sgs_InitInt( &key, S ); else return SGS_EINPROC; ret = sgs_PushIndexIP( C, -1, &key, prop ); VAR_RELEASE( &key ); if( ret != SGS_SUCCESS ) return ret; stk_popskip( C, 1, 1 ); } #undef args return ret; } SGSRESULT sgs_PushPath( SGS_CTX, StkIdx item, const char* path, ... ) { int ret; StkIdx ssz = STACKFRAMESIZE; va_list args; va_start( args, path ); item = stk_absindex( C, item ); ret = sgs_PushPathBuf( C, item, path, strlen(path), &args ); if( ret == SGS_SUCCESS ) stk_popskip( C, STACKFRAMESIZE - ssz - 1, 1 ); else stk_pop( C, STACKFRAMESIZE - ssz ); va_end( args ); return ret; } SGSRESULT sgs_StorePath( SGS_CTX, StkIdx item, const char* path, ... ) { int ret; size_t len = strlen( path ); StkIdx val, ssz = STACKFRAMESIZE; va_list args; if( ssz < 1 ) return SGS_EINPROC; if( !*path ) return sgs_StoreItem( C, item ); va_start( args, path ); item = stk_absindex( C, item ); val = stk_absindex( C, -1 ); ret = sgs_PushPathBuf( C, item, path, len - 1, &args ); if( ret == SGS_SUCCESS ) { sgs_Variable key; sgs_SizeVal S = -1; char* P = NULL; int prop = -1; char a = path[ len - 1 ]; ret = SGS_EINVAL; if( a == 'o' ){ prop = 1; S = va_arg( args, sgs_SizeVal ); } else if( a == 'p' ){ prop = 1; P = va_arg( args, char* ); if( !P ) goto fail; } else if( a == 's' ){ prop = 1; S = va_arg( args, sgs_SizeVal ); P = va_arg( args, char* ); if( !P ) goto fail; } else if( a == 'i' ){ prop = 0; S = va_arg( args, sgs_SizeVal ); } else if( a == 'k' ){ prop = 0; P = va_arg( args, char* ); if( !P ) goto fail; } else if( a == 'n' ){ prop = 0; S = va_arg( args, sgs_SizeVal ); P = va_arg( args, char* ); if( !P ) goto fail; } else goto fail; if( P ) { if( S >= 0 ) sgs_InitStringBuf( C, &key, P, S ); else sgs_InitString( C, &key, P ); } else if( S >= 0 ) sgs_InitInt( &key, S ); else { ret = SGS_EINPROC; goto fail; } ret = sgs_SetIndexIPI( C, -1, &key, val, prop ); VAR_RELEASE( &key ); if( ret != SGS_SUCCESS ) return ret; ssz--; } fail: va_end( args ); stk_pop( C, STACKFRAMESIZE - ssz ); return ret; } /* argument unpacking: n - null (not sure why but I had a free letter here) b - boolean c,w,l,q,i - integers (int8,int16,int32,int64 x2) f,d,r - floats (reals) (float32,float64 x2) s,m - strings (string,string+size) p - function (callable, actually; p stands for "procedure"; returns a SGSBOOL always, useful only for optional arguments) a,t,h,o - objects (array,dict,map,specific iface) & - pointer (void*) v - any variable (returns sgs_Variable, checks if valid index or non-null if strict) x - custom check/return function ? - check only, no writeback ! - strict check (no conversions) -,+ - signed/unsigned (changes checked ranges and return value signs) | - optional arguments follow # - check ranges ^ - clamp ranges ~ - ignore ranges < - move argument pointer 1 item back > - move argument pointer 1 item forward @ - treat as method (1st arg = this, argnum -= 1) . - check if there are no more arguments */ int sgs_ArgErrorExt( SGS_CTX, int argid, int gotthis, const char* expect, const char* expfx ) { const char* got = sgs_StackSize( C ) <= argid ? "nothing" : sgs_CodeString( SGS_CODE_VT, (int) sgs_ItemType( C, argid ) ); if( argid == 0 && gotthis ) return sgs_Msg( C, SGS_WARNING, "'this' - expected %s%s, got %s", expfx, expect, got ); else return sgs_Msg( C, SGS_WARNING, "argument %d - expected %s%s, got %s", argid + !gotthis, expfx, expect, got ); } int sgs_ArgError( SGS_CTX, int argid, int gotthis, int expect, int is_strict ) { return sgs_ArgErrorExt( C, argid, gotthis, sgs_CodeString( SGS_CODE_VT, expect ), is_strict ? "strict " : "" ); } #define argerr sgs_ArgError #define argerrx sgs_ArgErrorExt SGSMIXED sgs_LoadArgsExtVA( SGS_CTX, int from, const char* cmd, va_list* args ) { int opt = 0; int strict = 0; int range = 0; /* <0: clamp, >0: check */ int isig = 1; int nowrite = 0; int method = 0; while( *cmd ) { switch( *cmd ) { case '|': opt = 1; break; case '#': range = 1; break; case '^': range = -1; break; case '~': range = 0; break; case '-': isig = 1; break; case '+': isig = 0; break; case '!': strict = 1; break; case '?': nowrite = 1; break; case '<': from--; if( from < 0 ) { sgs_Msg( C, SGS_WARNING, "cannot move argument pointer before 0" ); return SGS_EINVAL; } break; case '>': from++; break; case '@': method = 1; break; case '.': if( from < sgs_StackSize( C ) ) { sgs_Msg( C, SGS_WARNING, "function expects exactly %d arguments, %d given", from - method, sgs_StackSize( C ) - method ); return 0; } break; case 'n': { if( sgs_ItemType( C, from ) != SVT_NULL ) { argerr( C, from, method, SVT_NULL, 0 ); return opt; } if( !nowrite ) { *va_arg( *args, SGSBOOL* ) = 1; } } strict = 0; nowrite = 0; from++; break; case 'b': { sgs_Bool b; if( opt && sgs_ItemType( C, from ) == SVT_NULL ) { if( !nowrite ) va_arg( *args, sgs_Bool* ); break; } if( !sgs_ParseBool( C, from, &b ) || ( strict && sgs_ItemType( C, from ) != SVT_BOOL ) ) { argerr( C, from, method, SVT_BOOL, strict ); return opt; } if( !nowrite ) { *va_arg( *args, sgs_Bool* ) = b; } } strict = 0; nowrite = 0; from++; break; case 'c': case 'w': case 'l': case 'q': case 'i': { sgs_Int i, imin = INT64_MIN, imax = INT64_MAX; if( opt && sgs_ItemType( C, from ) == SVT_NULL ) { if( !nowrite ) { switch( *cmd ) { case 'c': va_arg( *args, uint8_t* ); break; case 'w': va_arg( *args, uint16_t* ); break; case 'l': va_arg( *args, uint32_t* ); break; case 'q': va_arg( *args, uint64_t* ); break; case 'i': va_arg( *args, sgs_Int* ); break; } } break; } if( range ) { if( *cmd == 'c' && isig ){ imin = INT8_MIN; imax = INT8_MAX; } else if( *cmd == 'c' && !isig ){ imin = 0; imax = UINT8_MAX; } else if( *cmd == 'w' && isig ){ imin = INT16_MIN; imax = INT16_MAX; } else if( *cmd == 'w' && !isig ){ imin = 0; imax = UINT16_MAX; } else if( *cmd == 'l' && isig ){ imin = INT32_MIN; imax = INT32_MAX; } else if( *cmd == 'l' && !isig ){ imin = 0; imax = UINT32_MAX; } } if( !sgs_ParseInt( C, from, &i ) || ( strict && sgs_ItemType( C, from ) != SVT_INT ) ) { argerr( C, from, method, SVT_INT, strict ); return opt; } if( range > 0 && ( i < imin || i > imax ) ) { sgs_Msg( C, SGS_WARNING, "integer argument %d (%" PRId64 ") out of range [%" PRId64 ",%" PRId64 "]", from, i, imin, imax ); return opt; } else if( range < 0 ) { if( i < imin ) i = imin; else if( i > imax ) i = imax; } if( !nowrite ) { switch( *cmd ) { case 'c': *va_arg( *args, uint8_t* ) = (uint8_t) i; break; case 'w': *va_arg( *args, uint16_t* ) = (uint16_t) i; break; case 'l': *va_arg( *args, uint32_t* ) = (uint32_t) i; break; case 'q': *va_arg( *args, uint64_t* ) = (uint64_t) i; break; case 'i': *va_arg( *args, sgs_Int* ) = i; break; } } } strict = 0; nowrite = 0; from++; break; case 'f': case 'd': case 'r': { sgs_Real r; if( opt && sgs_ItemType( C, from ) == SVT_NULL ) { if( !nowrite ) { switch( *cmd ) { case 'f': va_arg( *args, float* ); break; case 'd': va_arg( *args, double* ); break; case 'r': va_arg( *args, sgs_Real* ); break; } } break; } if( !sgs_ParseReal( C, from, &r ) || ( strict && sgs_ItemType( C, from ) != SVT_REAL ) ) { argerr( C, from, method, SVT_REAL, strict ); return opt; } if( !nowrite ) { switch( *cmd ) { case 'f': *va_arg( *args, float* ) = (float) r; break; case 'd': *va_arg( *args, double* ) = r; break; case 'r': *va_arg( *args, sgs_Real* ) = r; break; } } } strict = 0; nowrite = 0; from++; break; case 's': case 'm': { char* str; sgs_SizeVal sz; if( opt && sgs_ItemType( C, from ) == SVT_NULL ) { if( !nowrite ) { va_arg( *args, char** ); if( *cmd == 'm' ) va_arg( *args, sgs_SizeVal* ); } break; } if( ( strict && sgs_ItemType( C, from ) != SVT_STRING ) || !sgs_ParseString( C, from, &str, &sz ) ) { argerr( C, from, method, SVT_STRING, strict ); return opt; } if( !nowrite ) { *va_arg( *args, char** ) = str; if( *cmd == 'm' ) *va_arg( *args, sgs_SizeVal* ) = sz; } } strict = 0; nowrite = 0; from++; break; case 'p': { if( opt && sgs_ItemType( C, from ) == SVT_NULL ) { if( !nowrite ) va_arg( *args, SGSBOOL* ); break; } if( !sgs_IsCallable( C, from ) ) { argerrx( C, from, method, "callable", "" ); return opt; } if( !nowrite ) { *va_arg( *args, SGSBOOL* ) = 1; } } strict = 0; nowrite = 0; from++; break; case 'a': case 't': case 'h': case 'o': { sgs_ObjInterface* ifc = NULL; const char* ostr = "custom object"; if( *cmd == 'a' ){ ifc = sgsstd_array_iface; ostr = "array"; } if( *cmd == 't' ){ ifc = sgsstd_dict_iface; ostr = "dict"; } if( *cmd == 'h' ){ ifc = sgsstd_map_iface; ostr = "map"; } if( *cmd == 'o' ) ifc = va_arg( *args, sgs_ObjInterface* ); if( opt && sgs_ItemType( C, from ) == SVT_NULL ) { if( !nowrite ) { switch( *cmd ) { case 'a': va_arg( *args, sgs_SizeVal* ); break; case 't': case 'h': va_arg( *args, sgs_SizeVal* ); break; case 'o': va_arg( *args, void** ); break; } } break; } if( sgs_ItemType( C, from ) != SVT_OBJECT || ( ifc != NULL && !sgs_IsObject( C, from, ifc ) ) ) { argerrx( C, from, method, ostr, "" ); return opt; } if( !nowrite ) { sgs_VarObj* O = sgs_GetObjectStruct( C, from ); switch( *cmd ) { case 'a': *va_arg( *args, sgs_SizeVal* ) = ((sgsstd_array_header_t*) O->data)->size; break; case 't': case 'h': *va_arg( *args, sgs_SizeVal* ) = vht_size( ((VHTable*) O->data) ); break; case 'o': *va_arg( *args, void** ) = O->data; break; } } } strict = 0; nowrite = 0; from++; break; case '&': { void* ptr; if( opt && sgs_ItemType( C, from ) == SVT_NULL ) { if( !nowrite ) va_arg( *args, void** ); break; } if( !sgs_ParsePtr( C, from, &ptr ) ) { argerrx( C, from, method, "pointer", "" ); return opt; } if( !nowrite ) { *va_arg( *args, void** ) = ptr; } } strict = 0; nowrite = 0; from++; break; case 'v': { if( opt && sgs_ItemType( C, from ) == SVT_NULL ) { if( !nowrite ) va_arg( *args, sgs_Variable* ); break; } if( from >= sgs_StackSize( C ) || ( strict && sgs_ItemType( C, from ) == SVT_NULL ) ) { argerrx( C, from, method, strict ? "non-null" : "any", "" ); return opt; } if( !nowrite ) { int owr = sgs_PeekStackItem( C, from, va_arg( *args, sgs_Variable* ) ); UNUSED( owr ); sgs_BreakIf( !owr ); } } strict = 0; nowrite = 0; from++; break; case 'x': { sgs_ArgCheckFunc acf = va_arg( *args, sgs_ArgCheckFunc ); int flags = 0; if( strict ) flags |= SGS_LOADARG_STRICT; if( !nowrite ) flags |= SGS_LOADARG_WRITE; if( opt ) flags |= SGS_LOADARG_OPTIONAL; if( isig ) flags |= SGS_LOADARG_INTSIGN; if( range > 0 ) flags |= SGS_LOADARG_INTRANGE; if( range < 0 ) flags |= SGS_LOADARG_INTCLAMP; if( !acf( C, from, args, flags ) ) { return opt; } } strict = 0; nowrite = 0; from++; break; case ' ': case '\t': case '\n': case '\r': break; default: return SGS_EINVAL; } if( opt && from >= sgs_StackSize( C ) ) break; cmd++; } return 1; } SGSMIXED sgs_LoadArgsExt( SGS_CTX, int from, const char* cmd, ... ) { SGSMIXED ret; va_list args; va_start( args, cmd ); ret = sgs_LoadArgsExtVA( C, from, cmd, &args ); va_end( args ); return ret; } SGSBOOL sgs_LoadArgs( SGS_CTX, const char* cmd, ... ) { SGSBOOL ret; va_list args; va_start( args, cmd ); ret = sgs_LoadArgsExtVA( C, 0, cmd, &args ) > 0; va_end( args ); return ret; } SGSBOOL sgs_ParseMethod( SGS_CTX, sgs_ObjInterface* iface, void** ptrout, const char* method_name, const char* func_name ) { int method_call = sgs_Method( C ); SGSFN( method_call ? method_name : func_name ); if( !sgs_IsObject( C, 0, iface ) ) { sgs_ArgErrorExt( C, 0, method_call, iface->name, "" ); return FALSE; } *ptrout = sgs_GetObjectData( C, 0 ); sgs_ForceHideThis( C ); return TRUE; } SGSRESULT sgs_Pop( SGS_CTX, StkIdx count ) { if( STACKFRAMESIZE < count || count < 0 ) return SGS_EINVAL; stk_pop( C, count ); return SGS_SUCCESS; } SGSRESULT sgs_PopSkip( SGS_CTX, StkIdx count, StkIdx skip ) { if( STACKFRAMESIZE < count + skip || count < 0 || skip < 0 ) return SGS_EINVAL; stk_popskip( C, count, skip ); return SGS_SUCCESS; } StkIdx sgs_StackSize( SGS_CTX ) { return STACKFRAMESIZE; } SGSRESULT sgs_SetStackSize( SGS_CTX, StkIdx size ) { StkIdx diff; if( size < 0 ) return SGS_EINVAL; diff = STACKFRAMESIZE - size; if( diff > 0 ) stk_pop( C, diff ); else stk_push_nulls( C, -diff ); return SGS_SUCCESS; } StkIdx sgs_AbsIndex( SGS_CTX, StkIdx item ) { return stk_absindex( C, item ); } SGSBOOL sgs_IsValidIndex( SGS_CTX, StkIdx item ) { item = stk_absindex( C, item ); return ( item >= 0 && item < STACKFRAMESIZE ); } SGSBOOL sgs_PeekStackItem( SGS_CTX, StkIdx item, sgs_Variable* out ) { if( !sgs_IsValidIndex( C, item ) ) return FALSE; *out = *stk_getpos( C, item ); return TRUE; } SGSBOOL sgs_GetStackItem( SGS_CTX, sgs_StkIdx item, sgs_Variable* out ) { if( !sgs_IsValidIndex( C, item ) ) { out->type = SVT_NULL; return FALSE; } *out = *stk_getpos( C, item ); VAR_ACQUIRE( out ); return TRUE; } SGSRESULT sgs_SetStackItem( SGS_CTX, sgs_StkIdx item, sgs_Variable* val ) { if( val->type >= SGS_VT__COUNT ) return SGS_EINVAL; if( !sgs_IsValidIndex( C, item ) ) return SGS_EBOUNDS; stk_setvar( C, item, val ); return SGS_SUCCESS; } uint32_t sgs_ItemType( SGS_CTX, StkIdx item ) { if( !sgs_IsValidIndex( C, item ) ) return 0; return stk_getpos( C, item )->type; } void sgs_Assign( SGS_CTX, sgs_Variable* var_to, sgs_Variable* var_from ) { if( var_to == var_from ) return; VAR_RELEASE( var_to ); *var_to = *var_from; VAR_ACQUIRE( var_to ); } SGSRESULT sgs_ArithOp( SGS_CTX, sgs_Variable* out, sgs_Variable* A, sgs_Variable* B, int op ) { if( op < 0 || op > SGS_EOP_NEGATE ) { VAR_RELEASE( out ); return SGS_ENOTSUP; } if( op == SGS_EOP_NEGATE ) return vm_op_negate( C, out, A ) ? SGS_SUCCESS : SGS_EINVAL; return vm_arith_op( C, out, A, B, op ); } SGSRESULT sgs_IncDec( SGS_CTX, sgs_Variable* out, sgs_Variable* A, int inc ) { return vm_op_incdec( C, out, A, inc ? 1 : -1 ); } /* CLOSURES */ SGSRESULT sgs_ClPushNulls( SGS_CTX, sgs_StkIdx num ) { if( num < 0 ) return SGS_EINVAL; clstk_push_nulls( C, num ); return SGS_SUCCESS; } SGSRESULT sgs_ClPushItem( SGS_CTX, sgs_StkIdx item ) { if( item < 0 || C->clstk_off + item >= C->clstk_top ) return SGS_EBOUNDS; clstk_push( C, clstk_get( C, item ) ); return SGS_SUCCESS; } SGSRESULT sgs_ClPop( SGS_CTX, sgs_StkIdx num ) { if( C->clstk_top + num > C->clstk_top ) return SGS_EINPROC; clstk_pop( C, num ); return SGS_SUCCESS; } SGSRESULT sgs_MakeClosure( SGS_CTX, sgs_Variable* func, sgs_StkIdx clcount, sgs_Variable* out ) { int ret; if( C->clstk_top - C->clstk_off < clcount ) return SGS_EINPROC; /* WP: range not affected by conversion */ ret = sgsSTD_MakeClosure( C, func, (uint32_t) clcount ); sgs_BreakIf( ret != SGS_SUCCESS ); UNUSED( ret ); *out = *stk_gettop( C ); stk_pop1nr( C ); clstk_pop( C, clcount ); return SGS_SUCCESS; } SGSRESULT sgs_ClGetItem( SGS_CTX, sgs_StkIdx item, sgs_Variable* out ) { if( item < 0 || C->clstk_off + item >= C->clstk_top ) return SGS_EBOUNDS; *out = clstk_get( C, item )->var; VAR_ACQUIRE( out ); return SGS_SUCCESS; } SGSRESULT sgs_ClSetItem( SGS_CTX, sgs_StkIdx item, sgs_Variable* var ) { if( item < 0 || C->clstk_off + item >= C->clstk_top ) return SGS_EBOUNDS; sgs_Variable* cv = &clstk_get( C, item )->var; VAR_RELEASE( cv ); *cv = *var; VAR_ACQUIRE( var ); return SGS_SUCCESS; } /* OPERATIONS */ SGSRESULT sgs_FCallP( SGS_CTX, sgs_Variable* callable, int args, int expect, int gotthis ) { int ret; if( STACKFRAMESIZE < args + ( gotthis ? 1 : 0 ) ) return SGS_EINVAL; ret = vm_call( C, args, 0, gotthis, expect, callable ); if( ret == -1 ) return 1; return ret ? SGS_SUCCESS : SGS_EINPROC; } SGSRESULT sgs_FCall( SGS_CTX, int args, int expect, int gotthis ) { int ret; sgs_Variable func; int stksize = sgs_StackSize( C ); gotthis = gotthis ? 1 : 0; if( stksize < args + gotthis + 1 ) return SGS_EINVAL; func = *stk_getpos( C, -1 ); stk_pop1nr( C ); ret = vm_call( C, args, 0, gotthis, expect, &func ); VAR_RELEASE( &func ); if( ret == -1 ) return 1; return ret ? SGS_SUCCESS : SGS_EINPROC; } SGSRESULT sgs_GlobalCall( SGS_CTX, const char* name, int args, int expect ) { int ret; ret = sgs_PushGlobal( C, name ); if( SGS_FAILED( ret ) ) return ret; ret = sgs_Call( C, args, expect ); if( ret == SGS_EINVAL ) sgs_Pop( C, 1 ); return ret; } SGSRESULT sgs_TypeOf( SGS_CTX, StkIdx item ) { return vm_gettype( C, item ); } SGSRESULT sgs_DumpVar( SGS_CTX, int maxdepth ) { if( sgs_StackSize( C ) < 1 ) return SGS_EINPROC; if( maxdepth <= 0 ) { sgs_Pop( C, 1 ); sgs_PushString( C, "..." ); return SGS_SUCCESS; } { int ret = SGS_SUCCESS; sgs_Variable* var = stk_getpos( C, -1 ); switch( var->type ) { case SVT_NULL: sgs_PushString( C, "null" ); break; case SVT_BOOL: sgs_PushString( C, var->data.B ? "bool (true)" : "bool (false)" ); break; case SVT_INT: { char buf[ 32 ]; sprintf( buf, "int (%" PRId64 ")", var->data.I ); sgs_PushString( C, buf ); } break; case SVT_REAL: { char buf[ 32 ]; sprintf( buf, "real (%g)", var->data.R ); sgs_PushString( C, buf ); } break; case SVT_STRING: { char buf[ 532 ]; char* bptr = buf; char* bend = buf + 512; char* source = var_cstr( var ); uint32_t len = var->data.S->size; char* srcend = source + len; sprintf( buf, "string [%"PRId32"] \"", len ); bptr += strlen( buf ); while( source < srcend && bptr < bend ) { if( *source == ' ' || isgraph( (int)*source ) ) *bptr++ = *source++; else { static const char* hexdigs = "0123456789ABCDEF"; bptr[ 0 ] = '\\'; bptr[ 1 ] = 'x'; bptr[ 2 ] = hexdigs[ (*source & 0xf0) >> 4 ]; bptr[ 3 ] = hexdigs[ *source & 0xf ]; bptr += 4; source++; } } if( source != srcend ) { *bptr++ = '.'; *bptr++ = '.'; *bptr++ = '.'; } *bptr++ = '"'; /* WP: string limit */ sgs_PushStringBuf( C, buf, (sgs_SizeVal) ( bptr - buf ) ); } break; case SVT_FUNC: { MemBuf mb = membuf_create(); func_t* F = var->data.F; const char* str1 = F->funcname.size ? "SGS function '" : "SGS function <anonymous>"; const char* str2 = F->funcname.size ? "' defined at " : " defined at "; const char* str3 = "'"; membuf_appbuf( &mb, C, str1, strlen(str1) ); if( F->funcname.size ) membuf_appbuf( &mb, C, F->funcname.ptr, F->funcname.size ); if( F->filename.size ) { char lnbuf[ 32 ]; membuf_appbuf( &mb, C, str2, strlen(str2) ); membuf_appbuf( &mb, C, F->filename.ptr, F->filename.size ); sprintf( lnbuf, ":%d", (int) F->linenum ); membuf_appbuf( &mb, C, lnbuf, strlen(lnbuf) ); } else if( F->funcname.size ) membuf_appbuf( &mb, C, str3, strlen(str3) ); /* WP: various limits */ sgs_PushStringBuf( C, mb.ptr, (sgs_SizeVal) mb.size ); membuf_destroy( &mb, C ); } break; case SVT_CFUNC: { char buf[ 32 ]; sprintf( buf, "C function (%p)", var->data.C ); sgs_PushString( C, buf ); } break; case SVT_OBJECT: { char buf[ 32 ]; int q; _STACK_PREPARE; object_t* obj = var->data.O; sprintf( buf, "object (%p) [%"PRId32"] ", (void*) obj, obj->refcount ); sgs_PushString( C, buf ); if( obj->iface->dump ) { _STACK_PROTECT; ret = obj->iface->dump( C, obj, maxdepth - 1 ); q = SGS_SUCCEEDED( ret ); _STACK_UNPROTECT_SKIP( q ); if( q ) sgs_StringConcat( C, 2 ); } } break; case SVT_PTR: { char buf[ 32 ]; sprintf( buf, "pointer (%p)", var->data.P ); sgs_PushString( C, buf ); } break; default: sgs_BreakIf( "Invalid variable type in sgs_DumpVar!" ); ret = SGS_EINVAL; break; } if( ret == SGS_SUCCESS ) sgs_PopSkip( C, 1, 1 ); return ret; } } SGSRESULT sgs_GCExecute( SGS_CTX ) { int ret = SGS_SUCCESS; sgs_VarPtr vbeg, vend; object_t* p; C->redblue = !C->redblue; C->gcrun = TRUE; /* -- MARK -- */ /* GCLIST / currently executed "main" function */ vbeg = C->gclist; vend = vbeg + C->gclist_size; while( vbeg < vend ){ ret = vm_gcmark( C, vbeg ); if( ret != SGS_SUCCESS ) goto end; vbeg++; } /* STACK */ vbeg = C->stack_base; vend = C->stack_top; while( vbeg < vend ){ ret = vm_gcmark( C, vbeg++ ); if( ret != SGS_SUCCESS ) goto end; } /* GLOBALS */ sgsSTD_GlobalGC( C ); /* -- SWEEP -- */ /* destruct objects */ p = C->objs; while( p ){ object_t* pn = p->next; if( p->redblue != C->redblue ){ var_destruct_object( C, p ); } p = pn; } /* free variables */ p = C->objs; while( p ){ object_t* pn = p->next; if( p->redblue != C->redblue ) var_free_object( C, p ); p = pn; } end: C->gcrun = FALSE; return ret; } SGSRESULT sgs_PadString( SGS_CTX ) { const char* padding = " "; const uint32_t padsize = 2; if( sgs_StackSize( C ) < 1 ) return SGS_EINPROC; { uint32_t i; char* ostr; const char* cstr; sgs_Variable* var = stk_getpos( C, -1 ); if( var->type != SVT_STRING ) return SGS_EINVAL; cstr = var_cstr( var ); for( i = 0; cstr[ i ]; ) if( cstr[ i ] == '\n' ) i++; else cstr++; if( var->data.S->size + i * padsize > 0x7fffffff ) return SGS_EINPROC; /* WP: implemented error condition */ sgs_PushStringBuf( C, NULL, (StkIdx) ( var->data.S->size + i * padsize ) ); cstr = var_cstr( stk_getpos( C, -2 ) ); ostr = var_cstr( stk_getpos( C, -1 ) ); while( *cstr ) { *ostr++ = *cstr; if( *cstr == '\n' ) { const char* ppd = padding; while( *ppd ) *ostr++ = *ppd++; } cstr++; } } sgs_PopSkip( C, 1, 1 ); return SGS_SUCCESS; } SGSRESULT sgs_ToPrintSafeString( SGS_CTX ) { char* buf = NULL; sgs_SizeVal size = 0, i; if( !( buf = sgs_ToStringBuf( C, -1, &size ) ) ) return SGS_EINPROC; MemBuf mb = membuf_create(); for( i = 0; i < size; ++i ) { if( isgraph( (int)buf[ i ] ) || buf[ i ] == ' ' ) membuf_appchr( &mb, C, buf[ i ] ); else { char chrs[32]; sprintf( chrs, "\\x%02X", (int) buf[ i ] ); membuf_appbuf( &mb, C, chrs, 4 ); } } sgs_Pop( C, 1 ); if( mb.size > 0x7fffffff ) return SGS_EINPROC; /* WP: implemented error condition */ sgs_PushStringBuf( C, mb.ptr, (sgs_SizeVal) mb.size ); membuf_destroy( &mb, C ); return SGS_SUCCESS; } SGSRESULT sgs_StringConcat( SGS_CTX, StkIdx args ) { return vm_op_concat_ex( C, args ) ? SGS_SUCCESS : SGS_EINVAL; } SGSRESULT sgs_CloneItem( SGS_CTX, StkIdx item ) { int ret; sgs_Variable copy; if( !sgs_PeekStackItem( C, item, &copy ) ) return SGS_EBOUNDS; ret = vm_clone( C, &copy ); if( SGS_SUCCEEDED( ret ) ) return SGS_SUCCESS; return ret; } static int _serialize_function( SGS_CTX, sgs_iFunc* func, MemBuf* out ) { sgs_CompFunc F; { F.consts = membuf_create(); F.code = membuf_create(); F.lnbuf = membuf_create(); F.gotthis = func->gotthis; F.numargs = func->numargs; F.numtmp = func->numtmp; F.numclsr = func->numclsr; } F.consts.ptr = ((char*)(func+1)); F.consts.size = F.consts.mem = func->instr_off; F.code.ptr = ((char*)(func+1)) + func->instr_off; F.code.size = F.code.mem = func->size - func->instr_off; F.lnbuf.ptr = (char*) func->lineinfo; F.lnbuf.size = ( func->size - func->instr_off ) / 2; return sgsBC_Func2Buf( C, &F, out ); } static int _unserialize_function( SGS_CTX, const char* buf, size_t sz, sgs_iFunc** outfn ) { func_t* F; sgs_CompFunc* nf = NULL; if( sgsBC_ValidateHeader( buf, sz ) < SGS_HEADER_SIZE ) return 0; if( sgsBC_Buf2Func( C, "<anonymous>", buf, sz, &nf ) ) return 0; F = sgs_Alloc_a( func_t, nf->consts.size + nf->code.size ); F->refcount = 0; /* WP: const/instruction limits */ F->size = (uint32_t) ( nf->consts.size + nf->code.size ); F->instr_off = (uint32_t) nf->consts.size; F->gotthis = nf->gotthis; F->numargs = nf->numargs; F->numtmp = nf->numtmp; F->numclsr = nf->numclsr; { size_t lnc = nf->lnbuf.size / sizeof( sgs_LineNum ); F->lineinfo = sgs_Alloc_n( sgs_LineNum, lnc ); memcpy( F->lineinfo, nf->lnbuf.ptr, nf->lnbuf.size ); } F->funcname = membuf_create(); F->linenum = 0; F->filename = membuf_create(); /* set from current if possible? */ memcpy( func_consts( F ), nf->consts.ptr, nf->consts.size ); memcpy( func_bytecode( F ), nf->code.ptr, nf->code.size ); membuf_destroy( &nf->consts, C ); membuf_destroy( &nf->code, C ); membuf_destroy( &nf->lnbuf, C ); sgs_Dealloc( nf ); *outfn = F; return 1; } static void serialize_output_func( void* ud, SGS_CTX, const void* ptr, size_t datasize ) { MemBuf* B = (MemBuf*) ud; membuf_appbuf( B, C, ptr, datasize ); } SGSRESULT sgs_Serialize( SGS_CTX ) { int ret = SGS_SUCCESS; sgs_Variable V; MemBuf B = membuf_create(); sgs_OutputFunc dofn = NULL; void* doud = NULL; int ep = C->output_fn != serialize_output_func; if( !sgs_PeekStackItem( C, -1, &V ) ) return SGS_EBOUNDS; if( ep ) { dofn = C->output_fn; doud = C->output_ctx; sgs_SetOutputFunc( C, serialize_output_func, &B ); } if( V.type == SVT_OBJECT ) { sgs_VarObj* O = V.data.O; _STACK_PREPARE; if( !O->iface->serialize ) { sgs_Msg( C, SGS_WARNING, "Cannot serialize object of type '%s'", O->iface->name ); ret = SGS_ENOTSUP; goto fail; } _STACK_PROTECT; ret = O->iface->serialize( C, O ); _STACK_UNPROTECT; if( ret != SGS_SUCCESS ) goto fail; } else if( V.type == SVT_CFUNC ) { sgs_Msg( C, SGS_WARNING, "Cannot serialize C functions" ); ret = SGS_EINVAL; goto fail; } else { char pb[2]; { pb[0] = 'P'; /* WP: basetype limited to bits 0-7, sign interpretation does not matter */ pb[1] = (char) V.type; } sgs_Write( C, pb, 2 ); switch( V.type ) { case SVT_NULL: break; /* WP: V.data.B uses only bit 0 */ case SVT_BOOL: { char b = (char) V.data.B; sgs_Write( C, &b, 1 ); } break; case SVT_INT: sgs_Write( C, &V.data.I, sizeof( sgs_Int ) ); break; case SVT_REAL: sgs_Write( C, &V.data.R, sizeof( sgs_Real ) ); break; case SVT_STRING: sgs_Write( C, &V.data.S->size, 4 ); sgs_Write( C, var_cstr( &V ), V.data.S->size ); break; case SVT_FUNC: { MemBuf Bf = membuf_create(); ret = _serialize_function( C, V.data.F, &Bf ); if( ret != 0 ) { sgs_Write( C, &Bf.size, 4 ); sgs_Write( C, Bf.ptr, Bf.size ); ret = SGS_SUCCESS; } else ret = SGS_EINPROC; membuf_destroy( &Bf, C ); if( ret != SGS_SUCCESS ) goto fail; } break; default: sgs_Msg( C, SGS_ERROR, "sgs_Serialize: Unknown memory error" ); ret = SGS_EINPROC; goto fail; } } sgs_Pop( C, 1 ); fail: if( ep ) { sgs_SetOutputFunc( C, dofn, doud ); if( ret == SGS_SUCCESS ) { if( B.size > 0x7fffffff ) { sgs_Msg( C, SGS_WARNING, "Serialized string too long" ); ret = SGS_EINVAL; } else /* WP: added error condition */ sgs_PushStringBuf( C, B.ptr, (sgs_SizeVal) B.size ); } membuf_destroy( &B, C ); } return ret; } SGSRESULT sgs_SerializeObject( SGS_CTX, StkIdx args, const char* func ) { size_t len = strlen( func ); char pb[7] = { 'C', 0, 0, 0, 0, 0, 0 }; { /* WP: they were pointless */ pb[1] = (char)((args)&0xff); pb[2] = (char)((args>>8)&0xff); pb[3] = (char)((args>>16)&0xff); pb[4] = (char)((args>>24)&0xff); } if( len >= 255 ) return SGS_EINVAL; if( C->output_fn != serialize_output_func ) return SGS_EINPROC; /* WP: have error condition + sign interpretation doesn't matter */ pb[ 5 ] = (char) len; sgs_Write( C, pb, 6 ); sgs_Write( C, func, len ); sgs_Write( C, pb + 6, 1 ); return SGS_SUCCESS; } SGSRESULT sgs_Unserialize( SGS_CTX ) { char* str, *strend; sgs_SizeVal size; if( !sgs_ParseString( C, -1, &str, &size ) ) return SGS_EINVAL; strend = str + size; while( str < strend ) { char c = *str++; if( c == 'P' ) { if( str >= strend ) return SGS_EINPROC; c = *str++; switch( c ) { case SVT_NULL: sgs_PushNull( C ); break; case SVT_BOOL: if( str >= strend ) return SGS_EINPROC; sgs_PushBool( C, *str++ ); break; case SVT_INT: if( str >= strend-7 ) return SGS_EINPROC; else { sgs_Int val; AS_INTEGER( val, str ); sgs_PushInt( C, val ); } str += 8; break; case SVT_REAL: if( str >= strend-7 ) return SGS_EINPROC; else { sgs_Real val; AS_REAL( val, str ); sgs_PushReal( C, val ); } str += 8; break; case SVT_STRING: { sgs_SizeVal strsz; if( str >= strend-3 ) return SGS_EINPROC; AS_INT32( strsz, str ); str += 4; if( str > strend - strsz ) return SGS_EINPROC; sgs_PushStringBuf( C, str, strsz ); str += strsz; } break; case SVT_FUNC: { sgs_Variable tmp; sgs_SizeVal bcsz; sgs_iFunc* fn; if( str >= strend-3 ) return SGS_EINPROC; AS_INT32( bcsz, str ); str += 4; if( str > strend - bcsz ) return SGS_EINPROC; /* WP: conversion does not affect values */ if( !_unserialize_function( C, str, (size_t) bcsz, &fn ) ) return SGS_EINPROC; tmp.type = SVT_FUNC; tmp.data.F = fn; sgs_PushVariable( C, &tmp ); str += bcsz; } break; default: return SGS_EINPROC; } } else if( c == 'C' ) { int32_t argc; int fnsz, ret; if( str >= strend-4 ) return SGS_EINPROC; AS_INT32( argc, str ); str += 4; fnsz = *str++ + 1; if( str > strend - fnsz ) return SGS_EINPROC; ret = sgs_GlobalCall( C, str, argc, 1 ); if( ret != SGS_SUCCESS ) return ret; str += fnsz; } else { return SGS_EINPROC; } } return SGS_SUCCESS; } int sgs_Compare( SGS_CTX, sgs_Variable* v1, sgs_Variable* v2 ) { return vm_compare( C, v1, v2 ); } SGSBOOL sgs_EqualTypes( sgs_Variable* v1, sgs_Variable* v2 ) { return v1->type == v2->type && ( v1->type != SVT_OBJECT || v1->data.O->iface == v2->data.O->iface ); } /* CONVERSION / RETRIEVAL */ /* pointer versions */ sgs_Bool sgs_GetBoolP( SGS_CTX, sgs_Variable* var ){ return var_getbool( C, var ); } sgs_Int sgs_GetIntP( SGS_CTX, sgs_Variable* var ){ return var_getint( C, var ); } sgs_Real sgs_GetRealP( SGS_CTX, sgs_Variable* var ){ return var_getreal( C, var ); } void* sgs_GetPtrP( SGS_CTX, sgs_Variable* var ){ return var_getptr( C, var ); } sgs_Bool sgs_ToBoolP( SGS_CTX, sgs_Variable* var ) { vm_convert_bool( C, var ); return var->data.B; } sgs_Int sgs_ToIntP( SGS_CTX, sgs_Variable* var ) { vm_convert_int( C, var ); return var->data.I; } sgs_Real sgs_ToRealP( SGS_CTX, sgs_Variable* var ) { vm_convert_real( C, var ); return var->data.R; } void* sgs_ToPtrP( SGS_CTX, sgs_Variable* var ) { vm_convert_ptr( C, var ); return var->data.P; } char* sgs_ToStringBufP( SGS_CTX, sgs_Variable* var, sgs_SizeVal* outsize ) { vm_convert_string( C, var ); if( outsize ) /* WP: string limit */ *outsize = (sgs_SizeVal) var->data.S->size; return var_cstr( var ); } char* sgs_ToStringBufFastP( SGS_CTX, sgs_Variable* var, sgs_SizeVal* outsize ) { if( var->type == SVT_OBJECT ) { sgs_PushVariable( C, var ); sgs_TypeOf( C, -1 ); sgs_StoreVariable( C, var ); stk_pop1( C ); } return sgs_ToStringBufP( C, var, outsize ); } SGSBOOL sgs_IsObjectP( sgs_Variable* var, sgs_ObjInterface* iface ) { return var->type == SVT_OBJECT && var->data.O->iface == iface; } SGSBOOL sgs_IsCallableP( sgs_Variable* var ) { uint32_t ty = var->type; if( ty == SVT_FUNC || ty == SVT_CFUNC ) return 1; if( ty == SVT_OBJECT && var->data.O->iface->call ) return 1; return 0; } SGSBOOL sgs_ParseBoolP( SGS_CTX, sgs_Variable* var, sgs_Bool* out ) { uint32_t ty = var->type; if( ty == SVT_NULL || ty == SVT_CFUNC || ty == SVT_FUNC || ty == SVT_STRING ) return FALSE; if( out ) *out = sgs_GetBoolP( C, var ); return TRUE; } SGSBOOL sgs_ParseIntP( SGS_CTX, sgs_Variable* var, sgs_Int* out ) { sgs_Int i; if( var->type == SVT_NULL || var->type == SVT_FUNC || var->type == SVT_CFUNC ) return FALSE; if( var->type == SVT_STRING ) { intreal_t OIR; const char* ostr = var_cstr( var ); const char* str = ostr; int res = util_strtonum( &str, str + var->data.S->size, &OIR.i, &OIR.r ); if( str == ostr ) return FALSE; if( res == 1 ) i = OIR.i; else if( res == 2 ) i = (sgs_Int) OIR.r; else return FALSE; } else i = sgs_GetIntP( C, var ); if( out ) *out = i; return TRUE; } SGSBOOL sgs_ParseRealP( SGS_CTX, sgs_Variable* var, sgs_Real* out ) { sgs_Real r; if( var->type == SVT_NULL || var->type == SVT_FUNC || var->type == SVT_CFUNC ) return FALSE; if( var->type == SVT_STRING ) { intreal_t OIR; const char* ostr = var_cstr( var ); const char* str = ostr; int res = util_strtonum( &str, str + var->data.S->size, &OIR.i, &OIR.r ); if( str == ostr ) return FALSE; if( res == 1 ) r = (sgs_Real) OIR.i; else if( res == 2 ) r = OIR.r; else return FALSE; } else r = sgs_GetRealP( C, var ); if( out ) *out = r; return TRUE; } SGSBOOL sgs_ParseStringP( SGS_CTX, sgs_Variable* var, char** out, sgs_SizeVal* size ) { char* str; uint32_t ty; ty = var->type; if( ty == SVT_NULL || ty == SVT_FUNC || ty == SVT_CFUNC ) return FALSE; str = sgs_ToStringBufP( C, var, size ); if( out ) *out = str; return str != NULL; } SGSBOOL sgs_ParseObjectPtrP( SGS_CTX, sgs_Variable* var, sgs_ObjInterface* iface, sgs_VarObj** out, int strict ) { if( !strict && var->type == SGS_VT_NULL ) { if( *out ) sgs_ObjRelease( C, *out ); *out = NULL; return TRUE; } if( sgs_IsObjectP( var, iface ) ) { if( *out ) sgs_ObjRelease( C, *out ); *out = sgs_GetObjectStructP( var ); sgs_ObjAcquire( C, *out ); return TRUE; } return FALSE; } SGSBOOL sgs_ParsePtrP( SGS_CTX, sgs_Variable* var, void** out ) { if( var->type != SVT_NULL && var->type != SVT_PTR ) return FALSE; if( out ) *out = var->type != SVT_NULL ? var->data.P : NULL; return TRUE; } SGSMIXED sgs_ArraySizeP( SGS_CTX, sgs_Variable* var ) { if( var->type != SVT_OBJECT || var->data.O->iface != SGSIFACE_ARRAY ) return SGS_EINVAL; return ((sgsstd_array_header_t*)var->data.O->data)->size; } /* index versions */ sgs_Bool sgs_GetBool( SGS_CTX, StkIdx item ) { sgs_Variable* var; if( !sgs_IsValidIndex( C, item ) ) return 0; var = stk_getpos( C, item ); return var_getbool( C, var ); } sgs_Int sgs_GetInt( SGS_CTX, StkIdx item ) { sgs_Variable* var; if( !sgs_IsValidIndex( C, item ) ) return 0; var = stk_getpos( C, item ); return var_getint( C, var ); } sgs_Real sgs_GetReal( SGS_CTX, StkIdx item ) { sgs_Variable* var; if( !sgs_IsValidIndex( C, item ) ) return 0; var = stk_getpos( C, item ); return var_getreal( C, var ); } void* sgs_GetPtr( SGS_CTX, StkIdx item ) { sgs_Variable* var; if( !sgs_IsValidIndex( C, item ) ) return NULL; var = stk_getpos( C, item ); return var_getptr( C, var ); } sgs_Bool sgs_ToBool( SGS_CTX, StkIdx item ) { if( !sgs_IsValidIndex( C, item ) ) return 0; vm_convert_stack_bool( C, item ); return stk_getpos( C, item )->data.B; } sgs_Int sgs_ToInt( SGS_CTX, StkIdx item ) { if( !sgs_IsValidIndex( C, item ) ) return 0; vm_convert_stack_int( C, item ); return stk_getpos( C, item )->data.I; } sgs_Real sgs_ToReal( SGS_CTX, StkIdx item ) { if( !sgs_IsValidIndex( C, item ) ) return 0; vm_convert_stack_real( C, item ); return stk_getpos( C, item )->data.R; } void* sgs_ToPtr( SGS_CTX, StkIdx item ) { if( !sgs_IsValidIndex( C, item ) ) return 0; vm_convert_stack_ptr( C, item ); return stk_getpos( C, item )->data.P; } char* sgs_ToStringBuf( SGS_CTX, StkIdx item, sgs_SizeVal* outsize ) { sgs_Variable* var; if( !sgs_IsValidIndex( C, item ) ) return NULL; vm_convert_stack_string( C, item ); var = stk_getpos( C, item ); if( outsize ) /* WP: string limit */ *outsize = (sgs_SizeVal) var->data.S->size; return var_cstr( var ); } char* sgs_ToStringBufFast( SGS_CTX, StkIdx item, sgs_SizeVal* outsize ) { if( !sgs_IsValidIndex( C, item ) ) return NULL; if( stk_getpos( C, item )->type == SVT_OBJECT ) { StkIdx g = stk_absindex( C, item ); stk_push( C, stk_getlpos( C, g ) ); sgs_TypeOf( C, -1 ); stk_setlvar( C, g, stk_getpos( C, -1 ) ); stk_pop2( C ); } return sgs_ToStringBuf( C, item, outsize ); } SGSBOOL sgs_IsObject( SGS_CTX, StkIdx item, sgs_ObjInterface* iface ) { sgs_Variable* var; if( !sgs_IsValidIndex( C, item ) ) return FALSE; var = stk_getpos( C, item ); return var->type == SVT_OBJECT && var->data.O->iface == iface; } SGSBOOL sgs_IsCallable( SGS_CTX, StkIdx item ) { uint32_t ty = sgs_ItemType( C, item ); if( ty == SVT_FUNC || ty == SVT_CFUNC ) return 1; if( ty == SVT_OBJECT && sgs_GetObjectIface( C, item )->call ) return 1; return 0; } SGSBOOL sgs_ParseBool( SGS_CTX, StkIdx item, sgs_Bool* out ) { if( !sgs_IsValidIndex( C, item ) ) return FALSE; return sgs_ParseBoolP( C, stk_getpos( C, item ), out ); } SGSBOOL sgs_ParseInt( SGS_CTX, StkIdx item, sgs_Int* out ) { if( !sgs_IsValidIndex( C, item ) ) return FALSE; return sgs_ParseIntP( C, stk_getpos( C, item ), out ); } SGSBOOL sgs_ParseReal( SGS_CTX, StkIdx item, sgs_Real* out ) { if( !sgs_IsValidIndex( C, item ) ) return FALSE; return sgs_ParseRealP( C, stk_getpos( C, item ), out ); } SGSBOOL sgs_ParseString( SGS_CTX, StkIdx item, char** out, sgs_SizeVal* size ) { char* str; uint32_t ty; if( !sgs_IsValidIndex( C, item ) ) return FALSE; ty = sgs_ItemType( C, item ); if( ty == SVT_NULL || ty == SVT_FUNC || ty == SVT_CFUNC ) return FALSE; str = sgs_ToStringBuf( C, item, size ); if( out ) *out = str; return str != NULL; } SGSBOOL sgs_ParseObjectPtr( SGS_CTX, sgs_StkIdx item, sgs_ObjInterface* iface, sgs_VarObj** out, int strict ) { if( !sgs_IsValidIndex( C, item ) ) return FALSE; return sgs_ParseObjectPtrP( C, stk_getpos( C, item ), iface, out, strict ); } SGSBOOL sgs_ParsePtr( SGS_CTX, StkIdx item, void** out ) { if( !sgs_IsValidIndex( C, item ) ) return FALSE; return sgs_ParsePtrP( C, stk_getpos( C, item ), out ); } SGSMIXED sgs_ArraySize( SGS_CTX, StkIdx item ) { if( sgs_ItemType( C, item ) != SVT_OBJECT || sgs_GetObjectIface( C, item ) != SGSIFACE_ARRAY ) return SGS_EINVAL; return ((sgsstd_array_header_t*)sgs_GetObjectData( C, item ))->size; } sgs_Bool sgs_GlobalBool( SGS_CTX, const char* name ) { sgs_Bool v; if( SGS_FAILED( sgs_PushGlobal( C, name ) ) ) return 0; v = var_getbool( C, stk_gettop( C ) ); stk_pop1( C ); return v; } sgs_Int sgs_GlobalInt( SGS_CTX, const char* name ) { sgs_Int v; if( SGS_FAILED( sgs_PushGlobal( C, name ) ) ) return 0; v = var_getint( C, stk_gettop( C ) ); stk_pop1( C ); return v; } sgs_Real sgs_GlobalReal( SGS_CTX, const char* name ) { sgs_Real v; if( SGS_FAILED( sgs_PushGlobal( C, name ) ) ) return 0; v = var_getreal( C, stk_gettop( C ) ); stk_pop1( C ); return v; } char* sgs_GlobalStringBuf( SGS_CTX, const char* name, sgs_SizeVal* outsize ) { char* buf; if( SGS_FAILED( sgs_PushGlobal( C, name ) ) ) return NULL; if( !sgs_ParseString( C, -1, &buf, outsize ) ) { stk_pop1( C ); return NULL; } return buf; } SGSRESULT sgs_PushIteratorP( SGS_CTX, sgs_Variable* var ) { int ret; sgs_PushNull( C ); ret = vm_forprep( C, stk_absindex( C, -1 ), var ); if( SGS_FAILED( ret ) ) stk_pop1( C ); return ret; } SGSRESULT sgs_GetIteratorP( SGS_CTX, sgs_Variable* var, sgs_Variable* out ) { int ret; sgs_PushNull( C ); ret = vm_forprep( C, stk_absindex( C, -1 ), var ); if( SGS_FAILED( ret ) ) stk_pop1( C ); else sgs_StoreVariable( C, out ); return ret; } SGSMIXED sgs_IterAdvanceP( SGS_CTX, sgs_Variable* var ) { sgs_SizeVal ret; _EL_BACKUP; _EL_SETMAX; ret = vm_fornext( C, -1, -1, var ); _EL_RESET; return ret; } SGSMIXED sgs_IterPushDataP( SGS_CTX, sgs_Variable* var, int key, int value ) { _EL_BACKUP; sgs_SizeVal ret; StkIdx idkey, idval; if( !key && !value ) return SGS_SUCCESS; if( key ) { sgs_PushNull( C ); idkey = stk_absindex( C, -1 ); } else idkey = -1; if( value ) { sgs_PushNull( C ); idval = stk_absindex( C, -1 ); } else idval = -1; _EL_SETMAX; ret = vm_fornext( C, idkey, idval, var ); _EL_RESET; if( SGS_FAILED( ret ) ) stk_pop( C, !!key + !!value ); return ret; } SGSMIXED sgs_IterGetDataP( SGS_CTX, sgs_Variable* var, sgs_Variable* key, sgs_Variable* value ) { _EL_BACKUP; sgs_SizeVal ret; if( !key && !value ) return SGS_SUCCESS; if( key ) sgs_PushNull( C ); if( value ) sgs_PushNull( C ); _EL_SETMAX; ret = vm_fornext( C, key?stk_absindex(C,value?-2:-1):-1, value?stk_absindex(C,-1):-1, var ); _EL_RESET; if( SGS_SUCCEEDED( ret ) ) { if( value ) sgs_StoreVariable( C, value ); if( key ) sgs_StoreVariable( C, key ); } else stk_pop( C, !!key + !!value ); return ret; } SGSRESULT sgs_PushIterator( SGS_CTX, StkIdx item ) { sgs_Variable var; if( !sgs_PeekStackItem( C, item, &var ) ) return SGS_EBOUNDS; return sgs_PushIteratorP( C, &var ); } SGSRESULT sgs_GetIterator( SGS_CTX, StkIdx item, sgs_Variable* out ) { sgs_Variable var; if( !sgs_PeekStackItem( C, item, &var ) ) return SGS_EBOUNDS; return sgs_GetIteratorP( C, &var, out ); } SGSMIXED sgs_IterAdvance( SGS_CTX, StkIdx item ) { sgs_Variable var; if( !sgs_PeekStackItem( C, item, &var ) ) return SGS_EBOUNDS; return sgs_IterAdvanceP( C, &var ); } SGSMIXED sgs_IterPushData( SGS_CTX, StkIdx item, int key, int value ) { sgs_Variable var; if( !sgs_PeekStackItem( C, item, &var ) ) return SGS_EBOUNDS; return sgs_IterPushDataP( C, &var, key, value ); } SGSMIXED sgs_IterGetData( SGS_CTX, sgs_StkIdx item, sgs_Variable* key, sgs_Variable* value ) { sgs_Variable var; if( !sgs_PeekStackItem( C, item, &var ) ) return SGS_EBOUNDS; return sgs_IterGetDataP( C, &var, key, value ); } SGSBOOL sgs_IsNumericString( const char* str, sgs_SizeVal size ) { intreal_t out; const char* ostr = str; return util_strtonum( &str, str + size, &out.i, &out.r ) != 0 && str != ostr; } /* EXTENSION UTILITIES */ SGSBOOL sgs_Method( SGS_CTX ) { if( C->sf_last && HAS_FLAG( C->sf_last->flags, SGS_SF_METHOD ) && !HAS_FLAG( C->sf_last->flags, SGS_SF_HASTHIS ) ) { C->stack_off--; C->sf_last->flags |= SGS_SF_HASTHIS; return TRUE; } return FALSE; } SGSBOOL sgs_HideThis( SGS_CTX ) { if( C->sf_last && HAS_FLAG( C->sf_last->flags, (SGS_SF_METHOD|SGS_SF_HASTHIS) ) ) { C->stack_off++; /* WP: implicit conversion to int */ C->sf_last->flags &= (uint8_t) ~SGS_SF_HASTHIS; return TRUE; } return FALSE; } SGSBOOL sgs_ForceHideThis( SGS_CTX ) { if( !C->sf_last ) return FALSE; if( HAS_FLAG( C->sf_last->flags, SGS_SF_METHOD ) ) return sgs_HideThis( C ); if( STACKFRAMESIZE < 1 ) return FALSE; C->stack_off++; C->sf_last->flags = ( C->sf_last->flags | SGS_SF_METHOD ) & (uint8_t) (~SGS_SF_HASTHIS); return TRUE; } void sgs_Acquire( SGS_CTX, sgs_Variable* var ) { UNUSED( C ); VAR_ACQUIRE( var ); } void sgs_AcquireArray( SGS_CTX, sgs_Variable* var, sgs_SizeVal count ) { sgs_Variable* vend = var + count; while( var < vend ) sgs_Acquire( C, var++ ); } void sgs_Release( SGS_CTX, sgs_Variable* var ) { if( var->type == SVT_OBJECT && C->gcrun ) { /* if running GC, dereference without destroying */ (*var->data.pRC) -= 1; return; } VAR_RELEASE( var ); } void sgs_ReleaseArray( SGS_CTX, sgs_Variable* var, sgs_SizeVal count ) { sgs_Variable* vend = var + count; while( var < vend ) sgs_Release( C, var++ ); } SGSRESULT sgs_GCMark( SGS_CTX, sgs_Variable* var ) { return vm_gcmark( C, var ); } SGSRESULT sgs_GCMarkArray( SGS_CTX, sgs_Variable* var, sgs_SizeVal count ) { SGSRESULT res = SGS_SUCCESS; sgs_Variable* vend = var + count; while( var < vend ) { if( SGS_FAILED( vm_gcmark( C, var++ ) ) ) res = SGS_EINPROC; } return res; } void sgs_ObjAcquire( SGS_CTX, sgs_VarObj* obj ) { sgs_Variable var; var.type = SVT_OBJECT; var.data.O = obj; sgs_Acquire( C, &var ); } void sgs_ObjRelease( SGS_CTX, sgs_VarObj* obj ) { sgs_Variable var; var.type = SVT_OBJECT; var.data.O = obj; sgs_Release( C, &var ); } SGSRESULT sgs_ObjGCMark( SGS_CTX, sgs_VarObj* obj ) { sgs_Variable var; var.type = SVT_OBJECT; var.data.O = obj; return sgs_GCMark( C, &var ); } void sgs_ObjAssign( SGS_CTX, sgs_VarObj** dest, sgs_VarObj* src ) { if( *dest ) sgs_ObjRelease( C, *dest ); *dest = src; if( src ) sgs_ObjAcquire( C, src ); } void sgs_ObjCallDtor( SGS_CTX, sgs_VarObj* obj ) { var_destruct_object( C, obj ); } #define DBLCHK( what, fval )\ sgs_BreakIf( what );\ if( what ) return fval; #define _OBJPREP_P( ret ) \ DBLCHK( var->type != SVT_OBJECT, ret ) char* sgs_GetStringPtrP( sgs_Variable* var ) { DBLCHK( var->type != SVT_STRING, NULL ) return var_cstr( var ); } sgs_SizeVal sgs_GetStringSizeP( sgs_Variable* var ) { DBLCHK( var->type != SVT_STRING, 0 ) /* WP: string limit */ return (sgs_SizeVal) var->data.S->size; } sgs_VarObj* sgs_GetObjectStructP( sgs_Variable* var ) { _OBJPREP_P( NULL ); return var->data.O; } void* sgs_GetObjectDataP( sgs_Variable* var ) { _OBJPREP_P( NULL ); return var->data.O->data; } sgs_ObjInterface* sgs_GetObjectIfaceP( sgs_Variable* var ) { _OBJPREP_P( NULL ); return var->data.O->iface; } int sgs_SetObjectDataP( sgs_Variable* var, void* data ) { _OBJPREP_P( 0 ); var->data.O->data = data; return 1; } int sgs_SetObjectIfaceP( sgs_Variable* var, sgs_ObjInterface* iface ) { _OBJPREP_P( 0 ); var->data.O->iface = iface; return 1; } #define _OBJPREP( ret ) \ sgs_Variable* var; \ DBLCHK( !sgs_IsValidIndex( C, item ), ret ) \ var = stk_getpos( C, item ); \ DBLCHK( var->type != SVT_OBJECT, ret ) char* sgs_GetStringPtr( SGS_CTX, StkIdx item ) { sgs_Variable* var; DBLCHK( !sgs_IsValidIndex( C, item ), NULL ) var = stk_getpos( C, item ); DBLCHK( var->type != SVT_STRING, NULL ) return var_cstr( var ); } sgs_SizeVal sgs_GetStringSize( SGS_CTX, StkIdx item ) { sgs_Variable* var; DBLCHK( !sgs_IsValidIndex( C, item ), 0 ) var = stk_getpos( C, item ); DBLCHK( var->type != SVT_STRING, 0 ) /* WP: string limit */ return (sgs_SizeVal) var->data.S->size; } sgs_VarObj* sgs_GetObjectStruct( SGS_CTX, StkIdx item ) { _OBJPREP( NULL ); return var->data.O; } void* sgs_GetObjectData( SGS_CTX, StkIdx item ) { _OBJPREP( NULL ); return var->data.O->data; } sgs_ObjInterface* sgs_GetObjectIface( SGS_CTX, StkIdx item ) { _OBJPREP( NULL ); return var->data.O->iface; } int sgs_SetObjectData( SGS_CTX, StkIdx item, void* data ) { _OBJPREP( 0 ); var->data.O->data = data; return 1; } int sgs_SetObjectIface( SGS_CTX, StkIdx item, sgs_ObjInterface* iface ) { _OBJPREP( 0 ); var->data.O->iface = iface; return 1; } #undef DBLCHK <file_sep>/ext/sgscppbctest.cpp #include "sgscppbctest.h" void pushVec3( SGS_CTX, float x, float y, float z ) { SGS_PUSHCLASS( C, Vec3, (x,y,z) ); } int main( int argc, char** argv ) { printf( "\n//\n/// SGScript / CPPBC test\n//\n" ); SGS_CTX = sgs_CreateEngine(); printf( "\n> push Vec3(1,2,3)" ); pushVec3( C, 1, 2, 3 ); printf( "\n> print object: " ); sgs_PushItem( C, -1 ); sgs_GlobalCall( C, "print", 1, 0 ); printf( "\n> print property 'Vec3.length': " ); sgs_PushProperty( C, -1, "length" ); sgs_GlobalCall( C, "print", 1, 0 ); printf( "\n> print result of method 'Vec3.getLength()': " ); sgs_PushItem( C, -1 ); sgs_PushProperty( C, -1, "getLength" ); sgs_ThisCall( C, 0, 1 ); sgs_GlobalCall( C, "print", 1, 0 ); printf( "\n> print object after method 'Vec3.setLength(4.5)': " ); sgs_PushItem( C, -1 ); sgs_PushReal( C, 4.5 ); sgs_PushProperty( C, -2, "setLength" ); sgs_ThisCall( C, 1, 0 ); sgs_GlobalCall( C, "print", 1, 0 ); printf( "\n" ); sgs_DestroyEngine( C ); return 0; } <file_sep>/ext/sgsxgmath.c #include <stdio.h> #include "sgsxgmath.h" #define XGM_WARNING( err ) sgs_Msg( C, SGS_WARNING, err ) #define XGM_OHDR XGM_VT* hdr = (XGM_VT*) data->data; #define XGM_FLAHDR xgm_vtarray* flarr = (xgm_vtarray*) data->data; #define XGM_VMUL_INNER2(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]) #define XGM_VMUL_INNER3(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2]) #define XGM_VMUL_INNER4(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2]+(a)[3]*(b)[3]) #define XGM_BB2_EXPAND_V2(b,v) \ if( (b)[0] > (v)[0] ) (b)[0] = (v)[0]; \ if( (b)[1] > (v)[1] ) (b)[1] = (v)[1]; \ if( (b)[2] < (v)[0] ) (b)[2] = (v)[0]; \ if( (b)[3] < (v)[1] ) (b)[3] = (v)[1]; SGSBOOL sgs_ParseVT( SGS_CTX, sgs_StkIdx item, XGM_VT* out ) { sgs_Real val; if( sgs_ParseReal( C, item, &val ) ) { *out = (XGM_VT) val; return 1; } return 0; } SGSBOOL sgs_ParseVTP( SGS_CTX, sgs_Variable* var, XGM_VT* out ) { sgs_Real val; if( sgs_ParseRealP( C, var, &val ) ) { *out = (XGM_VT) val; return 1; } return 0; } /* 2 D V E C T O R */ #define VEC2_IFN( fn ) \ int is_method = sgs_Method( C ); \ sgs_FuncName( C, is_method ? "vec2." #fn : "vec2_" #fn ); \ if( !sgs_IsObject( C, 0, xgm_vec2_iface ) ) \ return sgs_ArgErrorExt( C, 0, is_method, "vec2", "" ); \ XGM_VT* data = (XGM_VT*) sgs_GetObjectData( C, 0 ); static int xgm_v2m_rotate( SGS_CTX ) { XGM_VT angle, s, c; VEC2_IFN( fn ); if( !sgs_LoadArgs( C, "@>f", &angle ) ) return 0; c = (XGM_VT) cos( angle ); s = (XGM_VT) sin( angle ); sgs_PushVec2( C, data[0] * c - data[1] * s, data[0] * s + data[1] * c ); return 1; } static int xgm_v2_convert( SGS_CTX, sgs_VarObj* data, int type ) { XGM_OHDR; if( type == SGS_CONVOP_CLONE ) { sgs_PushVec2p( C, hdr ); return SGS_SUCCESS; } else if( type == SGS_VT_STRING ) { char buf[ 128 ]; sprintf( buf, "vec2(%g;%g)", hdr[0], hdr[1] ); sgs_PushString( C, buf ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_v2_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int prop ) { char* str; XGM_OHDR; if( key->type == SGS_VT_INT ) { sgs_Int pos = sgs_GetIntP( C, key ); if( pos != 0 && pos != 1 ) return SGS_ENOTFND; sgs_PushReal( C, hdr[ pos ] ); return SGS_SUCCESS; } if( !sgs_ParseStringP( C, key, &str, NULL ) ) return SGS_EINVAL; if( !strcmp( str, "x" ) ){ sgs_PushReal( C, hdr[ 0 ] ); return SGS_SUCCESS; } if( !strcmp( str, "y" ) ){ sgs_PushReal( C, hdr[ 1 ] ); return SGS_SUCCESS; } if( !strcmp( str, "length" ) ) { sgs_PushReal( C, sqrt( XGM_VMUL_INNER2( hdr, hdr ) ) ); return SGS_SUCCESS; } if( !strcmp( str, "length_squared" ) ) { sgs_PushReal( C, XGM_VMUL_INNER2( hdr, hdr ) ); return SGS_SUCCESS; } if( !strcmp( str, "normalized" ) ) { XGM_VT lensq = XGM_VMUL_INNER2( hdr, hdr ); if( lensq ) { lensq = (XGM_VT) 1.0 / (XGM_VT) sqrt( lensq ); sgs_PushVec2( C, hdr[0] * lensq, hdr[1] * lensq ); } else sgs_PushVec2( C, 0, 0 ); return SGS_SUCCESS; } if( !strcmp( str, "angle" ) ){ sgs_PushReal( C, atan2( hdr[1], hdr[0] ) ); return SGS_SUCCESS; } if( !strcmp( str, "perp" ) ){ sgs_PushVec2( C, -hdr[1], hdr[0] ); return SGS_SUCCESS; } if( !strcmp( str, "perp2" ) ){ sgs_PushVec2( C, hdr[1], -hdr[0] ); return SGS_SUCCESS; } if( !strcmp( str, "rotate" ) ){ sgs_PushCFunction( C, xgm_v2m_rotate ); return SGS_SUCCESS; } if( !strcmp( str, "size" ) ){ sgs_PushInt( C, 2 ); return SGS_SUCCESS; } return SGS_ENOTFND; } static int xgm_v2_setindex( SGS_ARGS_SETINDEXFUNC ) { XGM_VT* hdr = (XGM_VT*) obj->data; if( key->type == SGS_VT_INT ) { sgs_Real vv; if( !sgs_ParseRealP( C, val, &vv ) ) return SGS_EINVAL; sgs_Int pos = sgs_GetIntP( C, key ); if( pos != 0 && pos != 1 ) return SGS_ENOTFND; hdr[ pos ] = (XGM_VT) vv; return SGS_SUCCESS; } else { sgs_Real vv; char* str; if( !sgs_ParseStringP( C, key, &str, NULL ) ) return SGS_EINVAL; SGS_CASE( "x" ) { if( !sgs_ParseRealP( C, val, &vv ) ) return SGS_EINVAL; hdr[0] = (XGM_VT) vv; return SGS_SUCCESS; } SGS_CASE( "y" ) { if( !sgs_ParseRealP( C, val, &vv ) ) return SGS_EINVAL; hdr[1] = (XGM_VT) vv; return SGS_SUCCESS; } SGS_CASE( "angle" ) { if( !sgs_ParseRealP( C, val, &vv ) ) return SGS_EINVAL; XGM_VT curang = (XGM_VT) atan2( hdr[1], hdr[0] ); XGM_VT c = (XGM_VT) cos( (XGM_VT) vv - curang ); XGM_VT s = (XGM_VT) sin( (XGM_VT) vv - curang ); XGM_VT x = hdr[0] * c - hdr[1] * s, y = hdr[0] * s + hdr[1] * c; hdr[0] = x; hdr[1] = y; return SGS_SUCCESS; } } return SGS_ENOTFND; } static int xgm_v2_expr( SGS_CTX, sgs_VarObj* data, sgs_Variable* A, sgs_Variable* B, int type ) { if( type == SGS_EOP_ADD || type == SGS_EOP_SUB || type == SGS_EOP_MUL || type == SGS_EOP_DIV || type == SGS_EOP_MOD ) { XGM_VT r[ 2 ], v1[ 2 ], v2[ 2 ]; if( !sgs_ParseVec2P( C, A, v1, 0 ) || !sgs_ParseVec2P( C, B, v2, 0 ) ) return SGS_EINVAL; if( ( type == SGS_EOP_DIV || type == SGS_EOP_MOD ) && ( v2[0] == 0 || v2[1] == 0 ) ) { const char* errstr = type == SGS_EOP_DIV ? "vec2 operator '/' - division by zero" : "vec2 operator '%' - modulo by zero"; sgs_Msg( C, SGS_ERROR, errstr ); return SGS_EINPROC; } if( type == SGS_EOP_ADD ) { r[0] = v1[0] + v2[0]; r[1] = v1[1] + v2[1]; } else if( type == SGS_EOP_SUB ) { r[0] = v1[0] - v2[0]; r[1] = v1[1] - v2[1]; } else if( type == SGS_EOP_MUL ) { r[0] = v1[0] * v2[0]; r[1] = v1[1] * v2[1]; } else if( type == SGS_EOP_DIV ) { r[0] = v1[0] / v2[0]; r[1] = v1[1] / v2[1]; } else { r[0] = (XGM_VT) fmod( v1[0], v2[0] ); r[1] = (XGM_VT) fmod( v1[1], v2[1] ); } sgs_PushVec2p( C, r ); return SGS_SUCCESS; } else if( type == SGS_EOP_COMPARE ) { XGM_VT *v1, *v2; if( !sgs_IsObjectP( A, xgm_vec2_iface ) || !sgs_IsObjectP( B, xgm_vec2_iface ) ) return SGS_EINVAL; v1 = (XGM_VT*) sgs_GetObjectDataP( A ); v2 = (XGM_VT*) sgs_GetObjectDataP( B ); if( v1[0] != v2[0] ) sgs_PushReal( C, v1[0] - v2[0] ); else sgs_PushReal( C, v1[1] - v2[1] ); return SGS_SUCCESS; } else if( type == SGS_EOP_NEGATE ) { XGM_OHDR; sgs_PushVec2( C, -hdr[0], -hdr[1] ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_v2_serialize( SGS_CTX, sgs_VarObj* data ) { XGM_OHDR; sgs_PushReal( C, hdr[0] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; sgs_PushReal( C, hdr[1] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; return sgs_SerializeObject( C, 2, "vec2" ); } static int xgm_v2_dump( SGS_CTX, sgs_VarObj* data, int maxdepth ) { UNUSED( maxdepth ); return xgm_v2_convert( C, data, SGS_VT_STRING ); } static int xgm_vec2( SGS_CTX ) { int argc = sgs_StackSize( C ); XGM_VT v[ 2 ] = { 0, 0 }; SGSFN( "vec2" ); if( !sgs_LoadArgs( C, "f|f.", v, v + 1 ) ) return 0; if( argc == 1 ) v[1] = v[0]; sgs_PushVec2p( C, v ); return 1; } static int xgm_vec2_dot( SGS_CTX ) { XGM_VT v1[2], v2[2]; SGSFN( "vec2_dot" ); if( !sgs_LoadArgs( C, "!x!x", sgs_ArgCheck_Vec2, v1, sgs_ArgCheck_Vec2, v2 ) ) return 0; sgs_PushReal( C, XGM_VMUL_INNER2( v1, v2 ) ); return 1; } /* 3 D V E C T O R */ static int xgm_v3_convert( SGS_CTX, sgs_VarObj* data, int type ) { XGM_OHDR; if( type == SGS_CONVOP_CLONE ) { sgs_PushVec3p( C, hdr ); return SGS_SUCCESS; } else if( type == SGS_VT_STRING ) { char buf[ 192 ]; sprintf( buf, "vec3(%g;%g;%g)", hdr[0], hdr[1], hdr[2] ); sgs_PushString( C, buf ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_v3_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int prop ) { char* str; sgs_SizeVal size; XGM_OHDR; if( key->type == SGS_VT_INT ) { sgs_Int pos = sgs_GetIntP( C, key ); if( pos != 0 && pos != 1 && pos != 2 ) return SGS_ENOTFND; sgs_PushReal( C, hdr[ pos ] ); return SGS_SUCCESS; } if( sgs_ParseStringP( C, key, &str, &size ) ) { if( !strcmp( str, "x" ) ){ sgs_PushReal( C, hdr[ 0 ] ); return SGS_SUCCESS; } if( !strcmp( str, "y" ) ){ sgs_PushReal( C, hdr[ 1 ] ); return SGS_SUCCESS; } if( !strcmp( str, "z" ) ){ sgs_PushReal( C, hdr[ 2 ] ); return SGS_SUCCESS; } if( !strcmp( str, "length" ) ) { sgs_PushReal( C, sqrt( XGM_VMUL_INNER3( hdr, hdr ) ) ); return SGS_SUCCESS; } if( !strcmp( str, "length_squared" ) ) { sgs_PushReal( C, XGM_VMUL_INNER3( hdr, hdr ) ); return SGS_SUCCESS; } if( !strcmp( str, "normalized" ) ) { XGM_VT lensq = XGM_VMUL_INNER3( hdr, hdr ); if( lensq ) { lensq = (XGM_VT) 1.0 / (XGM_VT) sqrt( lensq ); sgs_PushVec3( C, hdr[0] * lensq, hdr[1] * lensq, hdr[2] * lensq ); } else sgs_PushVec3( C, 0, 0, 0 ); return SGS_SUCCESS; } if( !strcmp( str, "size" ) ){ sgs_PushInt( C, 3 ); return SGS_SUCCESS; } } return SGS_ENOTFND; } static int xgm_v3_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* vv, int prop ) { sgs_Real val; XGM_OHDR; if( !sgs_ParseRealP( C, vv, &val ) ) return SGS_EINVAL; if( key->type == SGS_VT_INT ) { sgs_Int pos = sgs_GetIntP( C, key ); if( pos != 0 && pos != 1 && pos != 2 ) return SGS_ENOTFND; hdr[ pos ] = (XGM_VT) val; return SGS_SUCCESS; } else { char* str; sgs_SizeVal size; if( sgs_ParseStringP( C, key, &str, &size ) ) { if( !strcmp( str, "x" ) ){ hdr[0] = (XGM_VT) val; return SGS_SUCCESS; } if( !strcmp( str, "y" ) ){ hdr[1] = (XGM_VT) val; return SGS_SUCCESS; } if( !strcmp( str, "z" ) ){ hdr[2] = (XGM_VT) val; return SGS_SUCCESS; } } } return SGS_ENOTFND; } static int xgm_v3_expr( SGS_CTX, sgs_VarObj* data, sgs_Variable* A, sgs_Variable* B, int type ) { if( type == SGS_EOP_ADD || type == SGS_EOP_SUB || type == SGS_EOP_MUL || type == SGS_EOP_DIV || type == SGS_EOP_MOD ) { XGM_VT r[3], v1[3], v2[3]; if( !sgs_ParseVec3P( C, A, v1, 0 ) || !sgs_ParseVec3P( C, B, v2, 0 ) ) return SGS_EINVAL; if( ( type == SGS_EOP_DIV || type == SGS_EOP_MOD ) && ( v2[0] == 0 || v2[1] == 0 || v2[2] == 0 ) ) { const char* errstr = type == SGS_EOP_DIV ? "vec3 operator '/' - division by zero" : "vec3 operator '%' - modulo by zero"; sgs_Msg( C, SGS_ERROR, errstr ); return SGS_EINPROC; } if( type == SGS_EOP_ADD ) { r[0] = v1[0] + v2[0]; r[1] = v1[1] + v2[1]; r[2] = v1[2] + v2[2]; } else if( type == SGS_EOP_SUB ) { r[0] = v1[0] - v2[0]; r[1] = v1[1] - v2[1]; r[2] = v1[2] - v2[2]; } else if( type == SGS_EOP_MUL ) { r[0] = v1[0] * v2[0]; r[1] = v1[1] * v2[1]; r[2] = v1[2] * v2[2]; } else if( type == SGS_EOP_DIV ) { r[0] = v1[0] / v2[0]; r[1] = v1[1] / v2[1]; r[2] = v1[2] / v2[2]; } else { r[0] = (XGM_VT) fmod( v1[0], v2[0] ); r[1] = (XGM_VT) fmod( v1[1], v2[1] ); r[2] = (XGM_VT) fmod( v1[2], v2[2] ); } sgs_PushVec3p( C, r ); return SGS_SUCCESS; } else if( type == SGS_EOP_COMPARE ) { XGM_VT *v1, *v2; if( !sgs_IsObjectP( A, xgm_vec3_iface ) || !sgs_IsObjectP( B, xgm_vec3_iface ) ) return SGS_EINVAL; v1 = (XGM_VT*) sgs_GetObjectDataP( A ); v2 = (XGM_VT*) sgs_GetObjectDataP( B ); if( v1[0] != v2[0] ) sgs_PushReal( C, v1[0] - v2[0] ); else if( v1[1] != v2[1] ) sgs_PushReal( C, v1[1] - v2[1] ); else sgs_PushReal( C, v1[2] - v2[2] ); return SGS_SUCCESS; } else if( type == SGS_EOP_NEGATE ) { XGM_OHDR; sgs_PushVec3( C, -hdr[0], -hdr[1], -hdr[2] ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_v3_serialize( SGS_CTX, sgs_VarObj* data ) { XGM_OHDR; sgs_PushReal( C, hdr[0] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; sgs_PushReal( C, hdr[1] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; sgs_PushReal( C, hdr[2] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; return sgs_SerializeObject( C, 3, "vec3" ); } static int xgm_v3_dump( SGS_CTX, sgs_VarObj* data, int unused ) { return xgm_v3_convert( C, data, SGS_VT_STRING ); } static int xgm_vec3( SGS_CTX ) { int argc = sgs_StackSize( C ); XGM_VT v[ 3 ] = { 0, 0, 0 }; SGSFN( "vec3" ); if( !sgs_LoadArgs( C, "f|ff.", v, v + 1, v + 2 ) ) return 0; if( argc == 2 ) return XGM_WARNING( "expected 1 or 3 real values" ); if( argc == 1 ) v[2] = v[1] = v[0]; sgs_PushVec3p( C, v ); return 1; } static int xgm_vec3_dot( SGS_CTX ) { XGM_VT v1[3], v2[3]; SGSFN( "vec3_dot" ); if( !sgs_LoadArgs( C, "!x!x", sgs_ArgCheck_Vec3, v1, sgs_ArgCheck_Vec3, v2 ) ) return 0; sgs_PushReal( C, XGM_VMUL_INNER3( v1, v2 ) ); return 1; } static int xgm_vec3_cross( SGS_CTX ) { XGM_VT v1[3], v2[3]; SGSFN( "vec3_cross" ); if( !sgs_LoadArgs( C, "!x!x", sgs_ArgCheck_Vec3, v1, sgs_ArgCheck_Vec3, v2 ) ) return 0; sgs_PushVec3( C, v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0] ); return 1; } /* 4 D V E C T O R */ static int xgm_v4_convert( SGS_CTX, sgs_VarObj* data, int type ) { XGM_OHDR; if( type == SGS_CONVOP_CLONE ) { sgs_PushVec4p( C, hdr ); return SGS_SUCCESS; } else if( type == SGS_VT_STRING ) { char buf[ 256 ]; sprintf( buf, "vec4(%g;%g;%g;%g)", hdr[0], hdr[1], hdr[2], hdr[3] ); sgs_PushString( C, buf ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_v4_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int prop ) { char* str; XGM_OHDR; if( key->type == SGS_VT_INT ) { sgs_Int pos = sgs_GetIntP( C, key ); if( pos != 0 && pos != 1 && pos != 2 && pos != 3 ) return SGS_ENOTFND; sgs_PushReal( C, hdr[ pos ] ); return SGS_SUCCESS; } if( sgs_ParseStringP( C, key, &str, NULL ) ) { if( !strcmp( str, "x" ) ){ sgs_PushReal( C, hdr[ 0 ] ); return SGS_SUCCESS; } if( !strcmp( str, "y" ) ){ sgs_PushReal( C, hdr[ 1 ] ); return SGS_SUCCESS; } if( !strcmp( str, "z" ) ){ sgs_PushReal( C, hdr[ 2 ] ); return SGS_SUCCESS; } if( !strcmp( str, "w" ) ){ sgs_PushReal( C, hdr[ 3 ] ); return SGS_SUCCESS; } if( !strcmp( str, "length" ) ) { sgs_PushReal( C, sqrt( XGM_VMUL_INNER4( hdr, hdr ) ) ); return SGS_SUCCESS; } if( !strcmp( str, "length_squared" ) ) { sgs_PushReal( C, XGM_VMUL_INNER4( hdr, hdr ) ); return SGS_SUCCESS; } if( !strcmp( str, "normalized" ) ) { XGM_VT lensq = XGM_VMUL_INNER4( hdr, hdr ); if( lensq ) { lensq = (XGM_VT) 1.0 / (XGM_VT) sqrt( lensq ); sgs_PushVec4( C, hdr[0] * lensq, hdr[1] * lensq, hdr[2] * lensq, hdr[3] * lensq ); } else sgs_PushVec4( C, 0, 0, 0, 0 ); return SGS_SUCCESS; } if( !strcmp( str, "size" ) ){ sgs_PushInt( C, 4 ); return SGS_SUCCESS; } } return SGS_ENOTFND; } static int xgm_v4_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* vv, int prop ) { sgs_Real val; XGM_OHDR; if( !sgs_ParseRealP( C, vv, &val ) ) return SGS_EINVAL; if( key->type == SGS_VT_INT ) { sgs_Int pos = sgs_GetIntP( C, key ); if( pos != 0 && pos != 1 && pos != 2 && pos != 3 ) return SGS_ENOTFND; hdr[ pos ] = (XGM_VT) val; return SGS_SUCCESS; } else { char* str; if( sgs_ParseStringP( C, key, &str, NULL ) ) { if( !strcmp( str, "x" ) ){ hdr[0] = (XGM_VT) val; return SGS_SUCCESS; } if( !strcmp( str, "y" ) ){ hdr[1] = (XGM_VT) val; return SGS_SUCCESS; } if( !strcmp( str, "z" ) ){ hdr[2] = (XGM_VT) val; return SGS_SUCCESS; } if( !strcmp( str, "w" ) ){ hdr[3] = (XGM_VT) val; return SGS_SUCCESS; } } } return SGS_ENOTFND; } static int xgm_v4_expr( SGS_CTX, sgs_VarObj* data, sgs_Variable* A, sgs_Variable* B, int type ) { if( type == SGS_EOP_ADD || type == SGS_EOP_SUB || type == SGS_EOP_MUL || type == SGS_EOP_DIV || type == SGS_EOP_MOD ) { XGM_VT r[4], v1[4], v2[4]; if( !sgs_ParseVec4P( C, A, v1, 0 ) || !sgs_ParseVec4P( C, B, v2, 0 ) ) return SGS_EINVAL; if( ( type == SGS_EOP_DIV || type == SGS_EOP_MOD ) && ( v2[0] == 0 || v2[1] == 0 || v2[2] == 0 || v2[3] == 0 ) ) { const char* errstr = type == SGS_EOP_DIV ? "vec4 operator '/' - division by zero" : "vec4 operator '%' - modulo by zero"; sgs_Msg( C, SGS_ERROR, errstr ); return SGS_EINPROC; } if( type == SGS_EOP_ADD ) { r[0] = v1[0] + v2[0]; r[1] = v1[1] + v2[1]; r[2] = v1[2] + v2[2]; r[3] = v1[3] + v2[3]; } else if( type == SGS_EOP_SUB ) { r[0] = v1[0] - v2[0]; r[1] = v1[1] - v2[1]; r[2] = v1[2] - v2[2]; r[3] = v1[3] - v2[3]; } else if( type == SGS_EOP_MUL ) { r[0] = v1[0] * v2[0]; r[1] = v1[1] * v2[1]; r[2] = v1[2] * v2[2]; r[3] = v1[3] * v2[3]; } else if( type == SGS_EOP_DIV ) { r[0] = v1[0] / v2[0]; r[1] = v1[1] / v2[1]; r[2] = v1[2] / v2[2]; r[3] = v1[3] / v2[3]; } else { r[0] = (XGM_VT) fmod( v1[0], v2[0] ); r[1] = (XGM_VT) fmod( v1[1], v2[1] ); r[2] = (XGM_VT) fmod( v1[2], v2[2] ); r[3] = (XGM_VT) fmod( v1[3], v2[3] ); } sgs_PushVec4p( C, r ); return SGS_SUCCESS; } else if( type == SGS_EOP_COMPARE ) { XGM_VT *v1, *v2; if( !sgs_IsObjectP( A, xgm_vec4_iface ) || !sgs_IsObjectP( B, xgm_vec4_iface ) ) return SGS_EINVAL; v1 = (XGM_VT*) sgs_GetObjectDataP( A ); v2 = (XGM_VT*) sgs_GetObjectDataP( B ); if( v1[0] != v2[0] ) sgs_PushReal( C, v1[0] - v2[0] ); else if( v1[1] != v2[1] ) sgs_PushReal( C, v1[1] - v2[1] ); else if( v1[2] != v2[2] ) sgs_PushReal( C, v1[2] - v2[2] ); else sgs_PushReal( C, v1[3] - v2[3] ); return SGS_SUCCESS; } else if( type == SGS_EOP_NEGATE ) { XGM_OHDR; sgs_PushVec4( C, -hdr[0], -hdr[1], -hdr[2], -hdr[3] ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_v4_serialize( SGS_CTX, sgs_VarObj* data ) { XGM_OHDR; sgs_PushReal( C, hdr[0] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; sgs_PushReal( C, hdr[1] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; sgs_PushReal( C, hdr[2] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; sgs_PushReal( C, hdr[3] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; return sgs_SerializeObject( C, 4, "vec4" ); } static int xgm_v4_dump( SGS_CTX, sgs_VarObj* data, int unused ) { return xgm_v4_convert( C, data, SGS_VT_STRING ); } static int xgm_vec4( SGS_CTX ) { int argc = sgs_StackSize( C ); XGM_VT v[ 4 ] = { 0, 0, 0, 0 }; SGSFN( "vec4" ); if( !sgs_LoadArgs( C, "f|fff.", v, v + 1, v + 2, v + 3 ) ) return 0; if( argc == 1 ) v[3] = v[2] = v[1] = v[0]; else if( argc == 2 ) { v[3] = v[1]; v[2] = v[1] = v[0]; } sgs_PushVec4( C, v[0], v[1], v[2], v[3] ); return 1; } static int xgm_vec4_dot( SGS_CTX ) { XGM_VT v1[4], v2[4]; SGSFN( "vec4_dot" ); if( !sgs_LoadArgs( C, "!x!x", sgs_ArgCheck_Vec4, v1, sgs_ArgCheck_Vec4, v2 ) ) return 0; sgs_PushReal( C, XGM_VMUL_INNER4( v1, v2 ) ); return 1; } /* 2 D A A B B */ static int xgm_aabb2_expand( SGS_CTX ); static int xgm_b2_convert( SGS_CTX, sgs_VarObj* data, int type ) { XGM_OHDR; if( type == SGS_CONVOP_CLONE ) { sgs_PushAABB2( C, hdr[0], hdr[1], hdr[2], hdr[3] ); return SGS_SUCCESS; } else if( type == SGS_VT_STRING ) { char buf[ 256 ]; sprintf( buf, "aabb2(%g;%g - %g;%g)", hdr[0], hdr[1], hdr[2], hdr[3] ); sgs_PushString( C, buf ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_b2_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int prop ) { char* str; XGM_OHDR; if( sgs_ParseStringP( C, key, &str, NULL ) ) { SGS_CASE( "x1" ) SGS_RETURN_REAL( hdr[0] ) SGS_CASE( "y1" ) SGS_RETURN_REAL( hdr[1] ) SGS_CASE( "x2" ) SGS_RETURN_REAL( hdr[2] ) SGS_CASE( "y2" ) SGS_RETURN_REAL( hdr[3] ) SGS_CASE( "p1" ) SGS_RETURN_VEC2P( hdr ) SGS_CASE( "p2" ) SGS_RETURN_VEC2P( hdr + 2 ) SGS_CASE( "width" ) SGS_RETURN_REAL( hdr[2] - hdr[0] ) SGS_CASE( "height" ) SGS_RETURN_REAL( hdr[3] - hdr[1] ) SGS_CASE( "center" ) SGS_RETURN_VEC2( (hdr[0]+hdr[2])*0.5f, (hdr[1]+hdr[3])*0.5f ) SGS_CASE( "area" ) SGS_RETURN_REAL( (hdr[2] - hdr[0]) * (hdr[3] - hdr[1]) ) SGS_CASE( "valid" ) SGS_RETURN_BOOL( hdr[2] >= hdr[0] && hdr[3] >= hdr[1] ) SGS_CASE( "expand" ) SGS_RETURN_CFUNC( xgm_aabb2_expand ) } return SGS_ENOTFND; } static int xgm_b2_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* vv, int prop ) { char* str; XGM_OHDR; if( sgs_ParseStringP( C, key, &str, NULL ) ) { if( !strcmp( str, "x1" ) ) return sgs_ParseVTP( C, vv, &hdr[0] ) ? SGS_SUCCESS : SGS_EINVAL; if( !strcmp( str, "y1" ) ) return sgs_ParseVTP( C, vv, &hdr[1] ) ? SGS_SUCCESS : SGS_EINVAL; if( !strcmp( str, "x2" ) ) return sgs_ParseVTP( C, vv, &hdr[2] ) ? SGS_SUCCESS : SGS_EINVAL; if( !strcmp( str, "y2" ) ) return sgs_ParseVTP( C, vv, &hdr[3] ) ? SGS_SUCCESS : SGS_EINVAL; if( !strcmp( str, "p1" ) ) return sgs_ParseVec2P( C, vv, hdr, 1 ) ? SGS_SUCCESS : SGS_EINVAL; if( !strcmp( str, "p2" ) ) return sgs_ParseVec2P( C, vv, hdr + 2, 1 ) ? SGS_SUCCESS : SGS_EINVAL; } return SGS_ENOTFND; } static int xgm_b2_expr( SGS_CTX, sgs_VarObj* data, sgs_Variable* A, sgs_Variable* B, int type ) { if( type == SGS_EOP_COMPARE ) { XGM_VT *v1, *v2; if( !sgs_IsObjectP( A, xgm_aabb2_iface ) || !sgs_IsObjectP( B, xgm_aabb2_iface ) ) return SGS_EINVAL; v1 = (XGM_VT*) sgs_GetObjectDataP( A ); v2 = (XGM_VT*) sgs_GetObjectDataP( B ); if( v1[0] != v2[0] ) sgs_PushReal( C, v1[0] - v2[0] ); else if( v1[1] != v2[1] ) sgs_PushReal( C, v1[1] - v2[1] ); else if( v1[2] != v2[2] ) sgs_PushReal( C, v1[2] - v2[2] ); else sgs_PushReal( C, v1[3] - v2[3] ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_b2_serialize( SGS_CTX, sgs_VarObj* data ) { XGM_OHDR; sgs_PushReal( C, hdr[0] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; sgs_PushReal( C, hdr[1] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; sgs_PushReal( C, hdr[2] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; sgs_PushReal( C, hdr[3] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; return sgs_SerializeObject( C, 4, "aabb2" ); } static int xgm_b2_dump( SGS_CTX, sgs_VarObj* data, int maxdepth ) { UNUSED( maxdepth ); return xgm_b2_convert( C, data, SGS_VT_STRING ); } static int xgm_aabb2( SGS_CTX ) { XGM_VT b[4] = { 0, 0, 0, 0 }; SGSFN( "aabb2" ); if( !sgs_LoadArgs( C, "ffff", b, b + 1, b + 2, b + 3 ) ) return 0; sgs_PushAABB2p( C, b ); return 1; } static int xgm_aabb2v( SGS_CTX ) { XGM_VT b[4] = { 0, 0, 0, 0 }; SGSFN( "aabb2v" ); if( !sgs_LoadArgs( C, "!x!x", sgs_ArgCheck_Vec2, b, sgs_ArgCheck_Vec2, b + 2 ) ) return 0; sgs_PushAABB2p( C, b ); return 1; } static int xgm_aabb2_intersect( SGS_CTX ) { XGM_VT b1[4], b2[4]; SGSFN( "aabb2_intersect" ); if( !sgs_LoadArgs( C, "xx", sgs_ArgCheck_AABB2, b1, sgs_ArgCheck_AABB2, b2 ) ) return 0; sgs_PushBool( C, b1[0] < b2[2] && b2[0] < b1[2] && b1[1] < b2[3] && b2[1] < b1[3] ); return 1; } static int xgm_aabb2_expand( SGS_CTX ) { XGM_VT* bb, tmp[4]; int i, ssz = sgs_StackSize( C ); int method_call = sgs_Method( C ); SGSFN( method_call ? "aabb2.expand" : "aabb2_expand" ); if( !sgs_IsObject( C, 0, xgm_aabb2_iface ) ) return sgs_ArgErrorExt( C, 0, method_call, "aabb2", "" ); bb = (XGM_VT*) sgs_GetObjectData( C, 0 ); for( i = 1; i < ssz; ++i ) { if( sgs_ParseVec2( C, i, tmp, 0 ) ) { XGM_BB2_EXPAND_V2( bb, tmp ); } else if( sgs_ParseAABB2( C, i, tmp ) ) { XGM_BB2_EXPAND_V2( bb, tmp ); XGM_BB2_EXPAND_V2( bb, tmp + 2 ); } else return sgs_ArgErrorExt( C, i, 0, "aabb2 or vec2", "" ); } return 0; } /* C O L O R */ static int xgm_col_convert( SGS_CTX, sgs_VarObj* data, int type ) { XGM_OHDR; if( type == SGS_CONVOP_CLONE ) { sgs_PushColorp( C, hdr ); return SGS_SUCCESS; } else if( type == SGS_VT_STRING ) { char buf[ 256 ]; sprintf( buf, "color(%g;%g;%g;%g)", hdr[0], hdr[1], hdr[2], hdr[3] ); sgs_PushString( C, buf ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_col_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int prop ) { char* str; XGM_OHDR; if( key->type == SGS_VT_INT ) { sgs_Int pos = sgs_GetInt( C, 0 ); if( pos != 0 && pos != 1 && pos != 2 && pos != 3 ) return SGS_ENOTFND; sgs_PushReal( C, hdr[ pos ] ); return SGS_SUCCESS; } if( sgs_ParseStringP( C, key, &str, NULL ) ) { if( !strcmp( str, "r" ) ){ sgs_PushReal( C, hdr[ 0 ] ); return SGS_SUCCESS; } if( !strcmp( str, "g" ) ){ sgs_PushReal( C, hdr[ 1 ] ); return SGS_SUCCESS; } if( !strcmp( str, "b" ) ){ sgs_PushReal( C, hdr[ 2 ] ); return SGS_SUCCESS; } if( !strcmp( str, "a" ) ){ sgs_PushReal( C, hdr[ 3 ] ); return SGS_SUCCESS; } if( !strcmp( str, "size" ) ){ sgs_PushInt( C, 4 ); return SGS_SUCCESS; } } return SGS_ENOTFND; } static int xgm_col_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* vv, int prop ) { sgs_Real val; XGM_OHDR; if( !sgs_ParseRealP( C, vv, &val ) ) return SGS_EINVAL; if( key->type == SGS_VT_INT ) { sgs_Int pos = sgs_GetIntP( C, key ); if( pos != 0 && pos != 1 && pos != 2 && pos != 3 ) return SGS_ENOTFND; hdr[ pos ] = (XGM_VT) val; return SGS_SUCCESS; } else { char* str; if( !sgs_ParseStringP( C, key, &str, NULL ) ) { if( !strcmp( str, "r" ) ){ hdr[0] = (XGM_VT) val; return SGS_SUCCESS; } if( !strcmp( str, "g" ) ){ hdr[1] = (XGM_VT) val; return SGS_SUCCESS; } if( !strcmp( str, "b" ) ){ hdr[2] = (XGM_VT) val; return SGS_SUCCESS; } if( !strcmp( str, "a" ) ){ hdr[3] = (XGM_VT) val; return SGS_SUCCESS; } } } return SGS_ENOTFND; } static int xgm_col_expr( SGS_CTX, sgs_VarObj* data, sgs_Variable* A, sgs_Variable* B, int type ) { if( type == SGS_EOP_ADD || type == SGS_EOP_SUB || type == SGS_EOP_MUL || type == SGS_EOP_DIV || type == SGS_EOP_MOD ) { XGM_VT r[4], v1[4], v2[4]; if( !sgs_ParseColorP( C, A, v1, 0 ) || !sgs_ParseColorP( C, B, v2, 0 ) ) return SGS_EINVAL; if( ( type == SGS_EOP_DIV || type == SGS_EOP_MOD ) && ( v2[0] == 0 || v2[1] == 0 || v2[2] == 0 || v2[3] == 0 ) ) { const char* errstr = type == SGS_EOP_DIV ? "color operator '/' - division by zero" : "color operator '%' - modulo by zero"; sgs_Msg( C, SGS_ERROR, errstr ); return SGS_EINPROC; } if( type == SGS_EOP_ADD ) { r[0] = v1[0] + v2[0]; r[1] = v1[1] + v2[1]; r[2] = v1[2] + v2[2]; r[3] = v1[3] + v2[3]; } else if( type == SGS_EOP_SUB ) { r[0] = v1[0] - v2[0]; r[1] = v1[1] - v2[1]; r[2] = v1[2] - v2[2]; r[3] = v1[3] - v2[3]; } else if( type == SGS_EOP_MUL ) { r[0] = v1[0] * v2[0]; r[1] = v1[1] * v2[1]; r[2] = v1[2] * v2[2]; r[3] = v1[3] * v2[3]; } else if( type == SGS_EOP_DIV ) { r[0] = v1[0] / v2[0]; r[1] = v1[1] / v2[1]; r[2] = v1[2] / v2[2]; r[3] = v1[3] / v2[3]; } else { r[0] = (XGM_VT) fmod( v1[0], v2[0] ); r[1] = (XGM_VT) fmod( v1[1], v2[1] ); r[2] = (XGM_VT) fmod( v1[2], v2[2] ); r[3] = (XGM_VT) fmod( v1[3], v2[3] ); } sgs_PushColorp( C, r ); return SGS_SUCCESS; } else if( type == SGS_EOP_COMPARE ) { XGM_VT *v1, *v2; if( !sgs_IsObjectP( A, xgm_vec4_iface ) || !sgs_IsObjectP( B, xgm_vec4_iface ) ) return SGS_EINVAL; v1 = (XGM_VT*) sgs_GetObjectDataP( A ); v2 = (XGM_VT*) sgs_GetObjectDataP( B ); if( v1[0] != v2[0] ) sgs_PushReal( C, v1[0] - v2[0] ); else if( v1[1] != v2[1] ) sgs_PushReal( C, v1[1] - v2[1] ); else if( v1[2] != v2[2] ) sgs_PushReal( C, v1[2] - v2[2] ); else sgs_PushReal( C, v1[3] - v2[3] ); return SGS_SUCCESS; } else if( type == SGS_EOP_NEGATE ) { XGM_OHDR; sgs_PushColor( C, -hdr[0], -hdr[1], -hdr[2], -hdr[3] ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_col_serialize( SGS_CTX, sgs_VarObj* data ) { int i; XGM_OHDR; for( i = 0; i < 4; ++i ) { sgs_PushReal( C, hdr[0] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; } return sgs_SerializeObject( C, 4, "color" ); } static int xgm_col_dump( SGS_CTX, sgs_VarObj* data, int unused ) { return xgm_col_convert( C, data, SGS_VT_STRING ); } static int xgm_color( SGS_CTX ) { int argc = sgs_StackSize( C ); XGM_VT v[ 4 ] = { 0, 0, 0, 0 }; SGSFN( "color" ); if( !sgs_LoadArgs( C, "f|fff.", v, v + 1, v + 2, v + 3 ) ) return 0; sgs_PushColorvp( C, v, argc ); return 1; } /* 4 x 4 M A T R I X */ typedef XGM_VT VEC3[3]; typedef XGM_VT VEC4[4]; typedef VEC4 MAT4[4]; #define MAT4_DUMP( M ) \ puts( "--- MATRIX DUMP ---" ); \ printf( "%g %g %g %g\n", M[0][0], M[0][1], M[0][2], M[0][3] ); \ printf( "%g %g %g %g\n", M[1][0], M[1][1], M[1][2], M[1][3] ); \ printf( "%g %g %g %g\n", M[2][0], M[2][1], M[2][2], M[2][3] ); \ printf( "%g %g %g %g\n", M[3][0], M[3][1], M[3][2], M[3][3] ); \ puts( "--- --- END --- ---" ); void MAT4_Transpose( MAT4 mtx ) { XGM_VT tmp; #define _MSWAP( a, b ) { tmp = a; a = b; b = tmp; } _MSWAP( mtx[0][1], mtx[1][0] ); _MSWAP( mtx[0][2], mtx[2][0] ); _MSWAP( mtx[0][3], mtx[3][0] ); _MSWAP( mtx[1][2], mtx[2][1] ); _MSWAP( mtx[1][3], mtx[3][1] ); _MSWAP( mtx[2][3], mtx[3][2] ); #undef _MSWAP } void MAT4_Multiply( MAT4 out, MAT4 A, MAT4 B ) { MAT4 tmp; tmp[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0] + A[0][2] * B[2][0] + A[0][3] * B[3][0]; tmp[0][1] = A[0][0] * B[0][1] + A[0][1] * B[1][1] + A[0][2] * B[2][1] + A[0][3] * B[3][1]; tmp[0][2] = A[0][0] * B[0][2] + A[0][1] * B[1][2] + A[0][2] * B[2][2] + A[0][3] * B[3][2]; tmp[0][3] = A[0][0] * B[0][3] + A[0][1] * B[1][3] + A[0][2] * B[2][3] + A[0][3] * B[3][3]; tmp[1][0] = A[1][0] * B[0][0] + A[1][1] * B[1][0] + A[1][2] * B[2][0] + A[1][3] * B[3][0]; tmp[1][1] = A[1][0] * B[0][1] + A[1][1] * B[1][1] + A[1][2] * B[2][1] + A[1][3] * B[3][1]; tmp[1][2] = A[1][0] * B[0][2] + A[1][1] * B[1][2] + A[1][2] * B[2][2] + A[1][3] * B[3][2]; tmp[1][3] = A[1][0] * B[0][3] + A[1][1] * B[1][3] + A[1][2] * B[2][3] + A[1][3] * B[3][3]; tmp[2][0] = A[2][0] * B[0][0] + A[2][1] * B[1][0] + A[2][2] * B[2][0] + A[2][3] * B[3][0]; tmp[2][1] = A[2][0] * B[0][1] + A[2][1] * B[1][1] + A[2][2] * B[2][1] + A[2][3] * B[3][1]; tmp[2][2] = A[2][0] * B[0][2] + A[2][1] * B[1][2] + A[2][2] * B[2][2] + A[2][3] * B[3][2]; tmp[2][3] = A[2][0] * B[0][3] + A[2][1] * B[1][3] + A[2][2] * B[2][3] + A[2][3] * B[3][3]; tmp[3][0] = A[3][0] * B[0][0] + A[3][1] * B[1][0] + A[3][2] * B[2][0] + A[3][3] * B[3][0]; tmp[3][1] = A[3][0] * B[0][1] + A[3][1] * B[1][1] + A[3][2] * B[2][1] + A[3][3] * B[3][1]; tmp[3][2] = A[3][0] * B[0][2] + A[3][1] * B[1][2] + A[3][2] * B[2][2] + A[3][3] * B[3][2]; tmp[3][3] = A[3][0] * B[0][3] + A[3][1] * B[1][3] + A[3][2] * B[2][3] + A[3][3] * B[3][3]; memcpy( out, tmp, sizeof(tmp) ); }; int MAT4_Invert( MAT4 out, MAT4 M ) { XGM_VT inv[16], *m = M[0], *outInv = out[0], det; int i; inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10]; inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10]; inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9]; inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9]; inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10]; inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10]; inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9]; inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9]; inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6]; inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6]; inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5]; inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5]; inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6]; inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6]; inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5]; inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]; det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12]; if( det == 0 ) return 0; det = 1.0f / det; for( i = 0; i < 16; ++i ) outInv[ i ] = inv[ i ] * det; return 1; } void MAT4_Transform( VEC4 out, VEC4 v, MAT4 mtx ) { VEC4 r_; int i, j; for(j=0; j<4; ++j) { r_[j] = 0.; for(i=0; i<4; ++i) { r_[j] += mtx[i][j] * v[i]; } } memcpy(out, r_, sizeof(r_)); } void MAT4_TransformPos( VEC3 out, VEC3 pos, MAT4 mtx ) { VEC4 tmp, xpos = {pos[0],pos[1],pos[2],1}; MAT4_Transform( tmp, xpos, mtx ); out[0] = tmp[0] / tmp[3]; out[1] = tmp[1] / tmp[3]; out[2] = tmp[2] / tmp[3]; } void MAT4_TransformNormal( VEC3 out, VEC3 pos, MAT4 mtx ) { VEC4 tmp, xpos = {pos[0],pos[1],pos[2],0}; MAT4_Transform( tmp, xpos, mtx ); out[0] = tmp[0]; out[1] = tmp[1]; out[2] = tmp[2]; } void MAT4_Translate( MAT4 out, XGM_VT x, XGM_VT y, XGM_VT z ) { out[0][0] = out[1][1] = out[2][2] = out[3][3] = 1.0f; out[0][1] = out[0][2] = out[0][3] = 0.0f; out[1][0] = out[1][2] = out[1][3] = 0.0f; out[2][0] = out[2][1] = out[2][3] = 0.0f; out[3][0] = x; out[3][1] = y; out[3][2] = z; } void MAT4_RotateDefaultAxis( MAT4 out, int axis0, int axis1, XGM_VT angle ) { int x, y; XGM_VT s = (XGM_VT) sin( angle ); XGM_VT c = (XGM_VT) cos( angle ); for( y = 0; y < 4; ++y ) for( x = 0; x < 4; ++x ) out[x][y] = x == y ? 1.0f : 0.0f; out[ axis0 ][ axis0 ] = c; out[ axis0 ][ axis1 ] = -s; out[ axis1 ][ axis0 ] = s; out[ axis1 ][ axis1 ] = c; } void MAT4_RotateAxisAngle( MAT4 out, XGM_VT x, XGM_VT y, XGM_VT z, XGM_VT angle ) { XGM_VT s = (XGM_VT) sin( angle ); XGM_VT c = (XGM_VT) cos( angle ); XGM_VT Ic = 1 - c; out[3][0] = out[3][1] = out[3][2] = 0; out[0][3] = out[1][3] = out[2][3] = 0; out[3][3] = 1; out[0][0] = x * x * Ic + c; out[0][1] = y * x * Ic - z * s; out[0][2] = z * x * Ic + y * s; out[1][0] = x * y * Ic + z * s; out[1][1] = y * y * Ic + c; out[1][2] = z * y * Ic - x * s; out[2][0] = x * z * Ic - y * s; out[2][1] = y * z * Ic + x * s; out[2][2] = z * z * Ic + c; } void MAT4_Scale( MAT4 out, XGM_VT x, XGM_VT y, XGM_VT z ) { out[0][1] = out[0][2] = out[0][3] = 0.0f; out[1][0] = out[1][2] = out[1][3] = 0.0f; out[2][0] = out[2][1] = out[2][3] = 0.0f; out[3][0] = out[3][1] = out[3][2] = 0.0f; out[0][0] = x; out[1][1] = y; out[2][2] = z; out[3][3] = 1.0f; } #define XGM_M4_IHDR( funcname ) MAT4* M; \ if( !SGS_PARSE_METHOD( C, xgm_mat4_iface, M, mat4, funcname ) ) return 0; static int xgm_m4i_identity( SGS_CTX ) { XGM_M4_IHDR( identity ); MAT4_Scale( *M, 1, 1, 1 ); SGS_RETURN_THIS( C ); } static int xgm_m4i_multiply( SGS_CTX ) { MAT4 M2; XGM_M4_IHDR( multiply ); if( !sgs_LoadArgs( C, "x", sgs_ArgCheck_Mat4, M2 ) ) return 0; MAT4_Multiply( *M, *M, M2 ); SGS_RETURN_THIS( C ); } static int xgm_m4i_multiply_left( SGS_CTX ) { MAT4 M2; XGM_M4_IHDR( multiply_left ); if( !sgs_LoadArgs( C, "x", sgs_ArgCheck_Mat4, M2 ) ) return 0; MAT4_Multiply( *M, M2, *M ); SGS_RETURN_THIS( C ); } static int xgm_m4i_multiply2( SGS_CTX ) { MAT4 M1, M2; XGM_M4_IHDR( multiply2 ); if( !sgs_LoadArgs( C, "xx", sgs_ArgCheck_Mat4, M1, sgs_ArgCheck_Mat4, M2 ) ) return 0; MAT4_Multiply( *M, M1, M2 ); SGS_RETURN_THIS( C ); } static int xgm_m4i_transpose( SGS_CTX ) { XGM_M4_IHDR( transpose ); MAT4_Transpose( *M ); return 0; } static int xgm_m4i_transpose_from( SGS_CTX ) { MAT4 M2; XGM_M4_IHDR( transpose_from ); if( !sgs_LoadArgs( C, "x", sgs_ArgCheck_Mat4, M2 ) ) return 0; memcpy( *M, M2, sizeof(M2) ); MAT4_Transpose( *M ); return 0; } static int xgm_m4i_invert( SGS_CTX ) { XGM_M4_IHDR( invert ); sgs_PushBool( C, MAT4_Invert( *M, *M ) ); return 1; } static int xgm_m4i_invert_from( SGS_CTX ) { MAT4 M2; XGM_M4_IHDR( invert_from ); if( !sgs_LoadArgs( C, "x", sgs_ArgCheck_Mat4, M2 ) ) return 0; sgs_PushBool( C, MAT4_Invert( *M, M2 ) ); return 1; } static int xgm_m4i_translate( SGS_CTX ) { sgs_Bool reset = 0; XGM_VT x, y, z; MAT4 tmp; XGM_M4_IHDR( translate ); if( !sgs_LoadArgs( C, "fff|b", &x, &y, &z, &reset ) ) return 0; MAT4_Translate( tmp, x, y, z ); if( !reset ) MAT4_Multiply( *M, *M, tmp ); else memcpy( *M, tmp, sizeof(tmp) ); SGS_RETURN_THIS( C ); } static int xgm_m4i_translate_v3( SGS_CTX ) { sgs_Bool reset = 0; XGM_VT v3[3]; MAT4 tmp; XGM_M4_IHDR( translate ); if( !sgs_LoadArgs( C, "x|b", sgs_ArgCheck_Vec3, v3, &reset ) ) return 0; MAT4_Translate( tmp, v3[0], v3[1], v3[2] ); if( !reset ) MAT4_Multiply( *M, *M, tmp ); else memcpy( *M, tmp, sizeof(tmp) ); SGS_RETURN_THIS( C ); } static int xgm_m4i_rotateX( SGS_CTX ) { sgs_Bool reset = 0; XGM_VT angle; MAT4 tmp; XGM_M4_IHDR( rotateX ); if( !sgs_LoadArgs( C, "f|b", &angle, &reset ) ) return 0; MAT4_RotateDefaultAxis( tmp, 1, 2, angle ); if( !reset ) MAT4_Multiply( *M, *M, tmp ); else memcpy( *M, tmp, sizeof(tmp) ); SGS_RETURN_THIS( C ); } static int xgm_m4i_rotateY( SGS_CTX ) { sgs_Bool reset = 0; XGM_VT angle; MAT4 tmp; XGM_M4_IHDR( rotateY ); if( !sgs_LoadArgs( C, "f|b", &angle, &reset ) ) return 0; MAT4_RotateDefaultAxis( tmp, 0, 2, angle ); if( !reset ) MAT4_Multiply( *M, *M, tmp ); else memcpy( *M, tmp, sizeof(tmp) ); SGS_RETURN_THIS( C ); } static int xgm_m4i_rotateZ( SGS_CTX ) { sgs_Bool reset = 0; XGM_VT angle; MAT4 tmp; XGM_M4_IHDR( rotateZ ); if( !sgs_LoadArgs( C, "f|b", &angle, &reset ) ) return 0; MAT4_RotateDefaultAxis( tmp, 0, 1, angle ); if( !reset ) MAT4_Multiply( *M, *M, tmp ); else memcpy( *M, tmp, sizeof(tmp) ); SGS_RETURN_THIS( C ); } static int xgm_m4i_rotate_axis_angle( SGS_CTX ) { sgs_Bool reset = 0; XGM_VT x, y, z, angle; MAT4 tmp; XGM_M4_IHDR( rotate_axis_angle ); if( !sgs_LoadArgs( C, "ffff|b", &x, &y, &z, &angle, &reset ) ) return 0; MAT4_RotateAxisAngle( tmp, x, y, z, angle ); if( !reset ) MAT4_Multiply( *M, *M, tmp ); else memcpy( *M, tmp, sizeof(tmp) ); SGS_RETURN_THIS( C ); } static int xgm_m4i_rotate_axis_angle_v3( SGS_CTX ) { sgs_Bool reset = 0; XGM_VT v3[3], angle; MAT4 tmp; XGM_M4_IHDR( rotate_axis_angle ); if( !sgs_LoadArgs( C, "xf|b", sgs_ArgCheck_Vec3, v3, &angle, &reset ) ) return 0; MAT4_RotateAxisAngle( tmp, v3[0], v3[1], v3[2], angle ); if( !reset ) MAT4_Multiply( *M, *M, tmp ); else memcpy( *M, tmp, sizeof(tmp) ); SGS_RETURN_THIS( C ); } static int xgm_m4i_scale( SGS_CTX ) { sgs_Bool reset = 0; XGM_VT x, y, z; MAT4 tmp; XGM_M4_IHDR( scale ); if( !sgs_LoadArgs( C, "fff|b", &x, &y, &z, &reset ) ) return 0; MAT4_Scale( tmp, x, y, z ); if( !reset ) MAT4_Multiply( *M, *M, tmp ); else memcpy( *M, tmp, sizeof(tmp) ); SGS_RETURN_THIS( C ); } static int xgm_m4i_scale_v3( SGS_CTX ) { sgs_Bool reset = 0; XGM_VT v3[3]; MAT4 tmp; XGM_M4_IHDR( scale_v3 ); if( !sgs_LoadArgs( C, "x|b", sgs_ArgCheck_Vec3, v3, &reset ) ) return 0; MAT4_Scale( tmp, v3[0], v3[1], v3[2] ); if( !reset ) MAT4_Multiply( *M, *M, tmp ); else memcpy( *M, tmp, sizeof(tmp) ); SGS_RETURN_THIS( C ); } static int xgm_m4i_transform( SGS_CTX ) { VEC4 v4; XGM_M4_IHDR( transform ); if( !sgs_LoadArgs( C, "x", sgs_ArgCheck_Vec4, v4 ) ) return 0; MAT4_Transform( v4, v4, *M ); sgs_PushVec4p( C, v4 ); return 1; } static int xgm_m4i_transform_pos( SGS_CTX ) { VEC3 v3; XGM_M4_IHDR( transform_pos ); if( !sgs_LoadArgs( C, "x", sgs_ArgCheck_Vec3, v3 ) ) return 0; MAT4_TransformPos( v3, v3, *M ); sgs_PushVec3p( C, v3 ); return 1; } static int xgm_m4i_transform_normal( SGS_CTX ) { VEC3 v3; XGM_M4_IHDR( transform_normal ); if( !sgs_LoadArgs( C, "x", sgs_ArgCheck_Vec3, v3 ) ) return 0; MAT4_TransformNormal( v3, v3, *M ); sgs_PushVec3p( C, v3 ); return 1; } static int xgm_m4_convert( SGS_CTX, sgs_VarObj* data, int type ) { XGM_OHDR; if( type == SGS_CONVOP_CLONE ) { sgs_PushMat4( C, hdr, 0 ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_m4_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int prop ) { char* str; XGM_OHDR; if( key->type == SGS_VT_INT ) { sgs_Int pos = sgs_GetIntP( C, key ); if( pos < 0 || pos > 15 ) return SGS_ENOTFND; sgs_PushReal( C, hdr[ pos ] ); return SGS_SUCCESS; } if( sgs_ParseStringP( C, key, &str, NULL ) ) { SGS_CASE( "identity" ) SGS_RETURN_CFUNC( xgm_m4i_identity ) SGS_CASE( "multiply" ) SGS_RETURN_CFUNC( xgm_m4i_multiply ) SGS_CASE( "multiply_left" ) SGS_RETURN_CFUNC( xgm_m4i_multiply_left ) SGS_CASE( "multiply2" ) SGS_RETURN_CFUNC( xgm_m4i_multiply2 ) SGS_CASE( "transpose" ) SGS_RETURN_CFUNC( xgm_m4i_transpose ) SGS_CASE( "transpose_from" ) SGS_RETURN_CFUNC( xgm_m4i_transpose_from ) SGS_CASE( "invert" ) SGS_RETURN_CFUNC( xgm_m4i_invert ) SGS_CASE( "invert_from" ) SGS_RETURN_CFUNC( xgm_m4i_invert_from ) SGS_CASE( "translate" ) SGS_RETURN_CFUNC( xgm_m4i_translate ) SGS_CASE( "translate_v3" ) SGS_RETURN_CFUNC( xgm_m4i_translate_v3 ) SGS_CASE( "rotateX" ) SGS_RETURN_CFUNC( xgm_m4i_rotateX ) SGS_CASE( "rotateY" ) SGS_RETURN_CFUNC( xgm_m4i_rotateY ) SGS_CASE( "rotateZ" ) SGS_RETURN_CFUNC( xgm_m4i_rotateZ ) SGS_CASE( "rotate_axis_angle" ) SGS_RETURN_CFUNC( xgm_m4i_rotate_axis_angle ) SGS_CASE( "rotate_axis_angle_v3" ) SGS_RETURN_CFUNC( xgm_m4i_rotate_axis_angle_v3 ) SGS_CASE( "scale" ) SGS_RETURN_CFUNC( xgm_m4i_scale ) SGS_CASE( "scale_v3" ) SGS_RETURN_CFUNC( xgm_m4i_scale_v3 ) SGS_CASE( "transform" ) SGS_RETURN_CFUNC( xgm_m4i_transform ) SGS_CASE( "transform_pos" ) SGS_RETURN_CFUNC( xgm_m4i_transform_pos ) SGS_CASE( "transform_normal" ) SGS_RETURN_CFUNC( xgm_m4i_transform_normal ) if( *str == 'm' && str[1] && str[2] && !str[3] ) { int nx = str[1] - '0'; int ny = str[2] - '0'; if( nx >= 0 && nx < 4 && ny >= 0 && ny < 4 ) { /* rows = x, columns = y, matrix is column-major */ sgs_PushReal( C, hdr[ ny + nx * 4 ] ); return SGS_SUCCESS; } } if( !strcmp( str, "size" ) ){ sgs_PushInt( C, 16 ); return SGS_SUCCESS; } } return SGS_ENOTFND; } static int xgm_m4_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* vv, int prop ) { char* str; XGM_OHDR; sgs_Real val; if( key->type == SGS_VT_INT ) { sgs_Int pos = sgs_GetIntP( C, key ); if( pos < 0 || pos > 15 ) return SGS_ENOTFND; if( sgs_ParseRealP( C, vv, &val ) ) { hdr[ pos ] = (XGM_VT) val; return SGS_SUCCESS; } else return SGS_EINVAL; } if( sgs_ParseStringP( C, key, &str, NULL ) ) { if( *str == 'm' && str[1] && str[2] && !str[3] ) { int nx = str[1] - '0'; int ny = str[2] - '0'; if( nx >= 0 && nx < 4 && ny >= 0 && ny < 4 ) { if( sgs_ParseRealP( C, vv, &val ) ) { /* rows = x, columns = y, matrix is column-major */ hdr[ ny + nx * 4 ] = (XGM_VT) val; return SGS_SUCCESS; } else return SGS_EINVAL; } } } return SGS_ENOTFND; } static int xgm_m4_expr( SGS_CTX, sgs_VarObj* data, sgs_Variable* A, sgs_Variable* B, int type ) { if( type == SGS_EOP_COMPARE ) { int i; XGM_VT *v1, *v2; if( !sgs_IsObjectP( A, xgm_mat4_iface ) || !sgs_IsObjectP( B, xgm_mat4_iface ) ) return SGS_EINVAL; v1 = (XGM_VT*) sgs_GetObjectDataP( A ); v2 = (XGM_VT*) sgs_GetObjectDataP( B ); for( i = 0; i < 15; ++i ) { if( v1[i] != v2[i] ) { sgs_PushReal( C, v1[i] - v2[0] ); break; } } if( i == 15 ) sgs_PushReal( C, 0 ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_m4_serialize( SGS_CTX, sgs_VarObj* data ) { int i; XGM_OHDR; for( i = 0; i < 16; ++i ) { sgs_PushReal( C, hdr[0] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; } return sgs_SerializeObject( C, 16, "mat4" ); } static int xgm_m4_dump( SGS_CTX, sgs_VarObj* data, int maxdepth ) { char bfr[ 1024 ]; XGM_OHDR; UNUSED( maxdepth ); snprintf( bfr, 1024, "\n%10.6g %10.6g %10.6g %10.6g" "\n%10.6g %10.6g %10.6g %10.6g" "\n%10.6g %10.6g %10.6g %10.6g" "\n%10.6g %10.6g %10.6g %10.6g", hdr[0], hdr[4], hdr[8], hdr[12], hdr[1], hdr[5], hdr[9], hdr[13], hdr[2], hdr[6], hdr[10], hdr[14], hdr[3], hdr[7], hdr[11], hdr[15] ); bfr[ 1023 ] = 0; sgs_PushString( C, "mat4\n(" ); sgs_PushString( C, bfr ); if( sgs_PadString( C ) ) return SGS_EINPROC; sgs_PushString( C, "\n)" ); if( sgs_StringConcat( C, 3 ) ) return SGS_EINPROC; return SGS_SUCCESS; } static int xgm_mat4( SGS_CTX ) { XGM_VT v[ 16 ]; int argc = sgs_StackSize( C ); SGSFN( "mat4" ); if( !argc ) { int i; for( i = 0; i < 16; ++i ) v[ i ] = 0; v[0] = v[5] = v[10] = v[15] = 1; sgs_PushMat4( C, v, 0 ); return 1; } else if( argc == 1 && sgs_ParseMat4( C, 0, v ) ) { sgs_PushMat4( C, v, 0 ); return 1; } else if( argc >= 3 && argc <= 4 ) { if( sgs_ParseVec4( C, 0, v, 0 ) && sgs_ParseVec4( C, 1, v+4, 0 ) && sgs_ParseVec4( C, 2, v+8, 0 ) ) { if( !sgs_ParseVec4( C, 3, v+12, 0 ) ) { v[12] = v[13] = v[14] = 0; v[15] = 1; } sgs_PushMat4( C, v, 0 ); return 1; } } else if( argc == 16 ) { int i; for( i = 0; i < 16; ++i ) { sgs_Real val; if( !sgs_ParseReal( C, i, &val ) ) break; v[ i ] = (XGM_VT) val; } if( i == 16 ) { sgs_PushMat4( C, v, 0 ); return 1; } } return sgs_Msg( C, SGS_WARNING, "expected 0 arguments or " "1 mat4 argument or 3-4 vec4 arguments or 16 real arguments" ); } /* F L O A T A R R A Y */ static int xgm_fla_destruct( SGS_CTX, sgs_VarObj* data ) { XGM_FLAHDR; if( flarr->data ) sgs_Dealloc( flarr->data ); return SGS_SUCCESS; } static int xgm_fla_convert( SGS_CTX, sgs_VarObj* data, int type ) { XGM_FLAHDR; if( type == SGS_CONVOP_CLONE ) { sgs_PushFloatArray( C, flarr->data, flarr->size ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int xgm_fla_serialize( SGS_CTX, sgs_VarObj* data ) { sgs_SizeVal i; XGM_FLAHDR; for( i = 0; i < flarr->size; ++i ) { sgs_PushReal( C, flarr->data[ i ] ); if( sgs_Serialize( C ) ) return SGS_EINPROC; } return sgs_SerializeObject( C, flarr->size, "floatarray" ); } static int xgm_fla_dump( SGS_CTX, sgs_VarObj* data, int maxdepth ) { XGM_FLAHDR; sgs_SizeVal i, vc = flarr->size > 64 ? 64 : flarr->size; sgs_PushString( C, "\n{" ); for( i = 0; i < vc; ++i ) { char bfr[ 128 ]; snprintf( bfr, 128, "\n%10.6g", flarr->data[ i ] ); bfr[ 127 ] = 0; sgs_PushString( C, bfr ); } if( vc < flarr->size ) { sgs_PushString( C, "\n..." ); vc++; } if( vc > 1 ) /* concatenate all numbers and "..." if it exists" */ sgs_StringConcat( C, vc ); sgs_PadString( C ); sgs_PushString( C, "\n}" ); sgs_StringConcat( C, 3 ); return SGS_SUCCESS; } static int xgm_fla_getindex_aabb2( SGS_CTX, xgm_vtarray* flarr ) { if( flarr->size < 2 ) { XGM_WARNING( "cannot get AABB2 of floatarray with size < 2" ); return SGS_EINPROC; } else { sgs_SizeVal i; XGM_VT bb[4] = { flarr->data[0], flarr->data[1], flarr->data[0], flarr->data[1] }; for( i = 2; i < flarr->size; i += 2 ) { XGM_VT* pp = flarr->data + i; if( bb[0] > pp[0] ) bb[0] = pp[0]; if( bb[1] > pp[1] ) bb[1] = pp[1]; if( bb[2] < pp[0] ) bb[2] = pp[0]; if( bb[3] < pp[1] ) bb[3] = pp[1]; } sgs_PushAABB2p( C, bb ); return SGS_SUCCESS; } } /* methods */ #define XGM_FLA_IHDR( funcname ) xgm_vtarray* flarr; \ if( !SGS_PARSE_METHOD( C, xgm_floatarr_iface, flarr, floatarray, funcname ) ) return 0; #define XGM_FLA_UNOPMETHOD( opname, opcode ) \ static int xgm_fla_##opname( SGS_CTX ) \ { \ sgs_SizeVal i; \ XGM_VT R, A; \ UNUSED( A ); \ \ XGM_FLA_IHDR( opname ) \ \ for( i = 0; i < flarr->size; ++i ) \ { \ A = flarr->data[ i ]; opcode; flarr->data[ i ] = R; \ } \ return 0; \ } XGM_FLA_UNOPMETHOD( clear, R = 0 ); XGM_FLA_UNOPMETHOD( set1, R = 1 ); XGM_FLA_UNOPMETHOD( negate, R = -A ); #define XGM_FLA_BINOPMETHOD( opname, opcode ) \ static int xgm_fla_##opname( SGS_CTX ) \ { \ XGM_VT v4f1[ 4 ] = {0}; \ XGM_VT* vfa1 = v4f1; \ sgs_SizeVal i, sz, unit1 = 1, stride1 = 0; \ XGM_VT R, A, B; \ UNUSED( A ); \ \ XGM_FLA_IHDR( opname ) \ \ if( sgs_ParseVec2( C, 0, vfa1, 0 ) ) unit1 = 2; \ else if( sgs_ParseVec3( C, 0, vfa1, 0 ) ) unit1 = 3; \ else if( sgs_ParseVec4( C, 0, vfa1, 0 ) ) unit1 = 4; \ else if( sgs_ParseFloatArray( C, 0, &vfa1, &sz ) ) \ { \ if( sz != flarr->size ) \ return XGM_WARNING( "array sizes don't match" ); \ stride1 = 1; \ } \ else return XGM_WARNING( "expected real, vec[2|3|4] or floatarray" ); \ \ for( i = 0; i < flarr->size; ++i ) \ { \ A = flarr->data[ i ]; B = vfa1[ i % unit1 ]; opcode; flarr->data[ i ] = R; \ vfa1 += stride1; \ } \ return 0; \ } XGM_FLA_BINOPMETHOD( assign, R = B ); XGM_FLA_BINOPMETHOD( negate_from, R = -B ); XGM_FLA_BINOPMETHOD( add_assign, R = A + B ); XGM_FLA_BINOPMETHOD( sub_assign, R = A - B ); XGM_FLA_BINOPMETHOD( mul_assign, R = A * B ); XGM_FLA_BINOPMETHOD( div_assign, R = A / B ); XGM_FLA_BINOPMETHOD( mod_assign, R = fmodf( A, B ) ); XGM_FLA_BINOPMETHOD( pow_assign, R = (XGM_VT) pow( A, B ) ); #define XGM_FLA_TEROPMETHOD( opname, opcode ) \ static int xgm_fla_##opname( SGS_CTX ) \ { \ XGM_VT v4f1[ 4 ] = {0}, v4f2[ 4 ] = {0}; \ XGM_VT* vfa1 = v4f1, *vfa2 = v4f2; \ sgs_SizeVal i, sz, unit1 = 1, unit2 = 1, stride1 = 0, stride2 = 0; \ XGM_VT R, A, B, T; \ UNUSED( T ); \ \ XGM_FLA_IHDR( opname ) \ \ if( sgs_ParseVec2( C, 0, vfa1, 0 ) ) unit1 = 2; \ else if( sgs_ParseVec3( C, 0, vfa1, 0 ) ) unit1 = 3; \ else if( sgs_ParseVec4( C, 0, vfa1, 0 ) ) unit1 = 4; \ else if( sgs_ParseFloatArray( C, 0, &vfa1, &sz ) ) \ { \ if( sz != flarr->size ) \ return XGM_WARNING( "array sizes (this : argument 1) don't match" ); \ stride1 = 1; \ } \ else return XGM_WARNING( "expected real, vec[2|3|4] or floatarray as argument 1" ); \ \ if( sgs_ParseVec2( C, 1, vfa2, 0 ) ) unit2 = 2; \ else if( sgs_ParseVec3( C, 1, vfa2, 0 ) ) unit2 = 3; \ else if( sgs_ParseVec4( C, 1, vfa2, 0 ) ) unit2 = 4; \ else if( sgs_ParseFloatArray( C, 1, &vfa2, &sz ) ) \ { \ if( sz != flarr->size ) \ return XGM_WARNING( "array sizes (this : argument 2) don't match" ); \ stride2 = 1; \ } \ else return XGM_WARNING( "expected real, vec[2|3|4] or floatarray as argument 2" ); \ \ for( i = 0; i < flarr->size; ++i ) \ { \ T = flarr->data[ i ]; A = vfa1[ i % unit1 ]; B = vfa2[ i % unit2 ]; opcode; flarr->data[ i ] = R; \ vfa1 += stride1; \ vfa2 += stride2; \ } \ return 0; \ } XGM_FLA_TEROPMETHOD( add, R = A + B ); XGM_FLA_TEROPMETHOD( sub, R = A - B ); XGM_FLA_TEROPMETHOD( mul, R = A * B ); XGM_FLA_TEROPMETHOD( div, R = A / B ); XGM_FLA_TEROPMETHOD( mod, R = fmodf( A, B ) ); XGM_FLA_TEROPMETHOD( pow, R = (XGM_VT) pow( A, B ) ); static XGM_VT randlerp( XGM_VT A, XGM_VT B ) { XGM_VT t = (XGM_VT) rand() / (XGM_VT) RAND_MAX; return A * (1-t) + B * t; } XGM_FLA_TEROPMETHOD( randbox, R = randlerp( A, B ) ); XGM_FLA_TEROPMETHOD( randext, R = randlerp( A - B, A + B ) ); XGM_FLA_TEROPMETHOD( multiply_add_assign, R = T + A * B ); XGM_FLA_TEROPMETHOD( lerp_to, R = T * (1-B) + A * B ); /* WP: assuming string buffer data alignment >= 8 */ #define XGM_FLA_CONVMETHOD( opname, typename ) \ static int xgm_fla_##opname( SGS_CTX ) \ { \ float scale = 1; \ sgs_SizeVal i; \ typename* data; \ XGM_FLA_IHDR( opname ) \ if( !sgs_LoadArgs( C, "|f", &scale ) ) \ return 0; \ \ sgs_PushStringBuf( C, NULL, (sgs_SizeVal) ( sizeof(typename) * (size_t) flarr->size ) ); \ data = (typename*) (void*) sgs_GetStringPtr( C, -1 ); \ for( i = 0; i < flarr->size; ++i ) \ { \ data[ i ] = (typename) ( flarr->data[ i ] * scale ); \ } \ return 1; \ } XGM_FLA_CONVMETHOD( to_int8_buffer, int8_t ); XGM_FLA_CONVMETHOD( to_int16_buffer, int16_t ); XGM_FLA_CONVMETHOD( to_int32_buffer, int32_t ); XGM_FLA_CONVMETHOD( to_int64_buffer, int64_t ); XGM_FLA_CONVMETHOD( to_uint8_buffer, uint8_t ); XGM_FLA_CONVMETHOD( to_uint16_buffer, uint16_t ); XGM_FLA_CONVMETHOD( to_uint32_buffer, uint32_t ); XGM_FLA_CONVMETHOD( to_uint64_buffer, uint64_t ); XGM_FLA_CONVMETHOD( to_float32_buffer, float ); XGM_FLA_CONVMETHOD( to_float64_buffer, double ); static int xgm_fla_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int isprop ) { XGM_FLAHDR; if( isprop ) { char* str; if( sgs_ParseStringP( C, key, &str, NULL ) ) { if( !strcmp( str, "aabb2" ) ) return xgm_fla_getindex_aabb2( C, flarr ); if( !strcmp( str, "size" ) ){ sgs_PushInt( C, flarr->size ); return SGS_SUCCESS; } if( !strcmp( str, "size2" ) ){ sgs_PushInt( C, flarr->size / 2 ); return SGS_SUCCESS; } if( !strcmp( str, "size3" ) ){ sgs_PushInt( C, flarr->size / 3 ); return SGS_SUCCESS; } if( !strcmp( str, "size4" ) ){ sgs_PushInt( C, flarr->size / 4 ); return SGS_SUCCESS; } if( !strcmp( str, "size16" ) ){ sgs_PushInt( C, flarr->size / 16 ); return SGS_SUCCESS; } SGS_CASE( "clear" ) SGS_RETURN_CFUNC( xgm_fla_clear ) SGS_CASE( "set1" ) SGS_RETURN_CFUNC( xgm_fla_set1 ) SGS_CASE( "negate" ) SGS_RETURN_CFUNC( xgm_fla_negate ) SGS_CASE( "assign" ) SGS_RETURN_CFUNC( xgm_fla_assign ) SGS_CASE( "negate_from" ) SGS_RETURN_CFUNC( xgm_fla_negate_from ) SGS_CASE( "add_assign" ) SGS_RETURN_CFUNC( xgm_fla_add_assign ) SGS_CASE( "sub_assign" ) SGS_RETURN_CFUNC( xgm_fla_sub_assign ) SGS_CASE( "mul_assign" ) SGS_RETURN_CFUNC( xgm_fla_mul_assign ) SGS_CASE( "div_assign" ) SGS_RETURN_CFUNC( xgm_fla_div_assign ) SGS_CASE( "mod_assign" ) SGS_RETURN_CFUNC( xgm_fla_mod_assign ) SGS_CASE( "pow_assign" ) SGS_RETURN_CFUNC( xgm_fla_pow_assign ) SGS_CASE( "add" ) SGS_RETURN_CFUNC( xgm_fla_add ) SGS_CASE( "sub" ) SGS_RETURN_CFUNC( xgm_fla_sub ) SGS_CASE( "mul" ) SGS_RETURN_CFUNC( xgm_fla_mul ) SGS_CASE( "div" ) SGS_RETURN_CFUNC( xgm_fla_div ) SGS_CASE( "mod" ) SGS_RETURN_CFUNC( xgm_fla_mod ) SGS_CASE( "pow" ) SGS_RETURN_CFUNC( xgm_fla_pow ) SGS_CASE( "randbox" ) SGS_RETURN_CFUNC( xgm_fla_randbox ) SGS_CASE( "randext" ) SGS_RETURN_CFUNC( xgm_fla_randext ) SGS_CASE( "multiply_add_assign" ) SGS_RETURN_CFUNC( xgm_fla_multiply_add_assign ) SGS_CASE( "lerp_to" ) SGS_RETURN_CFUNC( xgm_fla_lerp_to ) SGS_CASE( "to_int8_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_int8_buffer ) SGS_CASE( "to_int16_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_int16_buffer ) SGS_CASE( "to_int32_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_int32_buffer ) SGS_CASE( "to_int64_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_int64_buffer ) SGS_CASE( "to_uint8_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_uint8_buffer ) SGS_CASE( "to_uint16_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_uint16_buffer ) SGS_CASE( "to_uint32_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_uint32_buffer ) SGS_CASE( "to_uint64_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_uint64_buffer ) SGS_CASE( "to_float32_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_float32_buffer ) SGS_CASE( "to_float64_buffer" ) SGS_RETURN_CFUNC( xgm_fla_to_float64_buffer ) } } else { sgs_SizeVal pos = (sgs_SizeVal) sgs_GetIntP( C, key ); if( pos < 0 || pos > flarr->size ) return SGS_ENOTFND; sgs_PushReal( C, flarr->data[ pos ] ); return SGS_SUCCESS; } return SGS_ENOTFND; } static int xgm_fla_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* vv, int isprop ) { sgs_Real val; XGM_FLAHDR; if( key->type == SGS_VT_INT ) { sgs_SizeVal pos = (sgs_SizeVal) sgs_GetIntP( C, key ); if( pos < 0 || pos > flarr->size ) return SGS_ENOTFND; if( sgs_ParseRealP( C, vv, &val ) ) { flarr->data[ pos ] = (XGM_VT) val; return SGS_SUCCESS; } else return SGS_EINVAL; } return SGS_ENOTFND; } static XGM_VT* _xgm_pushvxa( SGS_CTX, sgs_SizeVal size, sgs_SizeVal cc ) { xgm_vtarray* np = (xgm_vtarray*) sgs_PushObjectIPA( C, sizeof(xgm_vtarray), xgm_floatarr_iface ); np->size = size * cc; np->mem = size * cc; np->data = size ? sgs_Alloc_n( XGM_VT, (size_t)( np->mem * cc ) ) : NULL; return np->data; } static int xgm_floatarray_buffer( SGS_CTX ) { XGM_VT* data; sgs_Int size; sgs_SizeVal i, sz; SGSFN( "floatarray_buffer" ); if( !sgs_LoadArgs( C, "i", &size ) ) return 0; sz = (sgs_SizeVal) size; data = _xgm_pushvxa( C, sz, 1 ); for( i = 0; i < sz; ++i ) data[ i ] = 0; return 1; } static int xgm_floatarray( SGS_CTX ) { sgs_SizeVal asize; SGSFN( "floatarray" ); /* create floatarray from array */ if( ( asize = sgs_ArraySize( C, 0 ) ) >= 0 ) { XGM_VT* fdata = _xgm_pushvxa( C, asize, 1 ); sgs_PushIterator( C, 0 ); while( sgs_IterAdvance( C, -1 ) > 0 ) { sgs_IterPushData( C, -1, 0, 1 ); if( !sgs_ParseVT( C, -1, fdata ) ) return XGM_WARNING( "failed to parse array" ); fdata++; sgs_Pop( C, 1 ); } sgs_Pop( C, 1 ); return 1; } if( sgs_ItemType( C, 0 ) == SGS_VT_INT || sgs_ItemType( C, 0 ) == SGS_VT_REAL ) { sgs_StkIdx i, ssz = sgs_StackSize( C ); XGM_VT* fdata = _xgm_pushvxa( C, ssz, 1 ); for( i = 0; i < ssz; ++i ) { fdata[ 0 ] = (XGM_VT) sgs_GetReal( C, i ); fdata++; } return 1; } return XGM_WARNING( "expected array of floats or float list" ); } static int xgm_vec2array( SGS_CTX ) { sgs_SizeVal asize; SGSFN( "vec2array" ); /* create vec2array from array */ if( ( asize = sgs_ArraySize( C, 0 ) ) >= 0 ) { XGM_VT* fdata = _xgm_pushvxa( C, asize, 2 ); sgs_PushIterator( C, 0 ); while( sgs_IterAdvance( C, -1 ) > 0 ) { sgs_IterPushData( C, -1, 0, 1 ); if( !sgs_ParseVec2( C, -1, fdata, 0 ) ) return XGM_WARNING( "failed to parse array" ); fdata += 2; sgs_Pop( C, 1 ); } sgs_Pop( C, 1 ); return 1; } /* create vec2array from list of vec2 */ if( sgs_IsObject( C, 0, xgm_vec2_iface ) ) { sgs_StkIdx i, ssz = sgs_StackSize( C ); XGM_VT* fdata = _xgm_pushvxa( C, ssz, 2 ); for( i = 0; i < ssz; ++i ) { if( !sgs_ParseVec2( C, i, fdata, 1 ) ) return sgs_Msg( C, SGS_WARNING, "failed to parse argument %d as vec2", i + 1 ); fdata += 2; } return 1; } if( sgs_ItemType( C, 0 ) == SGS_VT_INT || sgs_ItemType( C, 0 ) == SGS_VT_REAL ) { sgs_StkIdx i, ssz = sgs_StackSize( C ); XGM_VT* fdata; if( ssz % 2 != 0 ) return XGM_WARNING( "scalar argument count not multiple of 2" ); fdata = _xgm_pushvxa( C, ssz, 2 ); for( i = 0; i < ssz; i += 2 ) { fdata[ 0 ] = (XGM_VT) sgs_GetReal( C, i+0 ); fdata[ 1 ] = (XGM_VT) sgs_GetReal( C, i+1 ); fdata += 2; } return 1; } return XGM_WARNING( "expected array of vec2, vec2 list or float list" ); } static int xgm_vec3array( SGS_CTX ) { sgs_SizeVal asize; SGSFN( "vec3array" ); /* create vec3array from array */ if( ( asize = sgs_ArraySize( C, 0 ) ) >= 0 ) { XGM_VT* fdata = _xgm_pushvxa( C, asize, 3 ); sgs_PushIterator( C, 0 ); while( sgs_IterAdvance( C, -1 ) > 0 ) { sgs_IterPushData( C, -1, 0, 1 ); if( !sgs_ParseVec3( C, -1, fdata, 0 ) ) return XGM_WARNING( "failed to parse array" ); fdata += 3; sgs_Pop( C, 1 ); } sgs_Pop( C, 1 ); return 1; } /* create vec3array from list of vec3 */ if( sgs_IsObject( C, 0, xgm_vec3_iface ) ) { sgs_StkIdx i, ssz = sgs_StackSize( C ); XGM_VT* fdata = _xgm_pushvxa( C, ssz, 3 ); for( i = 0; i < ssz; ++i ) { if( !sgs_ParseVec3( C, i, fdata, 1 ) ) return sgs_Msg( C, SGS_WARNING, "failed to parse argument %d as vec3", i + 1 ); fdata += 3; } return 1; } if( sgs_ItemType( C, 0 ) == SGS_VT_INT || sgs_ItemType( C, 0 ) == SGS_VT_REAL ) { sgs_StkIdx i, ssz = sgs_StackSize( C ); XGM_VT* fdata; if( ssz % 3 != 0 ) return XGM_WARNING( "scalar argument count not multiple of 3" ); fdata = _xgm_pushvxa( C, ssz, 3 ); for( i = 0; i < ssz; i += 3 ) { fdata[ 0 ] = (XGM_VT) sgs_GetReal( C, i+0 ); fdata[ 1 ] = (XGM_VT) sgs_GetReal( C, i+1 ); fdata[ 2 ] = (XGM_VT) sgs_GetReal( C, i+2 ); fdata += 3; } return 1; } return XGM_WARNING( "expected array of vec3, vec3 list or float list" ); } static int xgm_vec4array( SGS_CTX ) { sgs_SizeVal asize; SGSFN( "vec4array" ); /* create vec4array from array */ if( ( asize = sgs_ArraySize( C, 0 ) ) >= 0 ) { XGM_VT* fdata = _xgm_pushvxa( C, asize, 4 ); sgs_PushIterator( C, 0 ); while( sgs_IterAdvance( C, -1 ) > 0 ) { sgs_IterPushData( C, -1, 0, 1 ); if( !sgs_ParseVec4( C, -1, fdata, 0 ) ) return XGM_WARNING( "failed to parse array" ); fdata += 4; sgs_Pop( C, 1 ); } sgs_Pop( C, 1 ); return 1; } /* create vec4array from list of vec4 */ if( sgs_IsObject( C, 0, xgm_vec4_iface ) ) { sgs_StkIdx i, ssz = sgs_StackSize( C ); XGM_VT* fdata = _xgm_pushvxa( C, ssz, 4 ); for( i = 0; i < ssz; ++i ) { if( !sgs_ParseVec4( C, i, fdata, 1 ) ) return sgs_Msg( C, SGS_WARNING, "failed to parse argument %d as vec4", i + 1 ); fdata += 4; } return 1; } if( sgs_ItemType( C, 0 ) == SGS_VT_INT || sgs_ItemType( C, 0 ) == SGS_VT_REAL ) { sgs_StkIdx i, ssz = sgs_StackSize( C ); XGM_VT* fdata; if( ssz % 4 != 0 ) return XGM_WARNING( "scalar argument count not multiple of 4" ); fdata = _xgm_pushvxa( C, ssz, 4 ); for( i = 0; i < ssz; i += 4 ) { fdata[ 0 ] = (XGM_VT) sgs_GetReal( C, i+0 ); fdata[ 1 ] = (XGM_VT) sgs_GetReal( C, i+1 ); fdata[ 2 ] = (XGM_VT) sgs_GetReal( C, i+2 ); fdata[ 3 ] = (XGM_VT) sgs_GetReal( C, i+3 ); fdata += 4; } return 1; } return XGM_WARNING( "expected array of vec4, vec4 list or float list" ); } #define XGM_FLA_BUFCREATEFUNC( funcname, typename ) \ static int xgm_##funcname( SGS_CTX ) \ { \ float scale = 1; \ sgs_SizeVal i, bufsize, offset = 0, stride = 1; \ typename* bufdata; \ XGM_VT* data; \ if( !sgs_LoadArgs( C, "m|fll", &bufdata, &bufsize, &scale, &stride, &offset ) ) \ return 0; \ \ bufsize /= (sgs_SizeVal) sizeof( typename ); \ data = _xgm_pushvxa( C, bufsize, 1 ); \ for( i = offset; i < bufsize; i += stride ) \ *data++ = scale * (XGM_VT) bufdata[ i ]; \ return 1; \ } XGM_FLA_BUFCREATEFUNC( floatarray_from_int8_buffer, int8_t ); XGM_FLA_BUFCREATEFUNC( floatarray_from_int16_buffer, int16_t ); XGM_FLA_BUFCREATEFUNC( floatarray_from_int32_buffer, int32_t ); XGM_FLA_BUFCREATEFUNC( floatarray_from_int64_buffer, int64_t ); XGM_FLA_BUFCREATEFUNC( floatarray_from_uint8_buffer, uint8_t ); XGM_FLA_BUFCREATEFUNC( floatarray_from_uint16_buffer, uint16_t ); XGM_FLA_BUFCREATEFUNC( floatarray_from_uint32_buffer, uint32_t ); XGM_FLA_BUFCREATEFUNC( floatarray_from_uint64_buffer, uint64_t ); XGM_FLA_BUFCREATEFUNC( floatarray_from_float32_buffer, float ); XGM_FLA_BUFCREATEFUNC( floatarray_from_float64_buffer, double ); /* UTILITY FUNCTIONS */ static int xgm_ray_plane_intersect( SGS_CTX ) { /* vec3 ray_pos, vec3 ray_dir, vec4 plane; returns <distance to intersection, signed origin distance from plane> \ <false> on (near-)parallel */ XGM_VT pos[3], dir[3], plane[4], sigdst, dirdot; SGSFN( "ray_plane_intersect" ); if( !sgs_LoadArgs( C, "xxx", sgs_ArgCheck_Vec3, pos, sgs_ArgCheck_Vec3, dir, sgs_ArgCheck_Vec4, plane ) ) return 0; sigdst = XGM_VMUL_INNER3( pos, plane ) - plane[3]; dirdot = XGM_VMUL_INNER3( dir, plane ); if( fabs( dirdot ) < XGM_SMALL_VT ) { sgs_PushBool( C, 0 ); return 1; } else { sgs_PushReal( C, -sigdst / dirdot ); sgs_PushReal( C, sigdst ); return 2; } } sgs_ObjInterface xgm_vec2_iface[1] = {{ "vec2", NULL, NULL, xgm_v2_getindex, xgm_v2_setindex, xgm_v2_convert, xgm_v2_serialize, xgm_v2_dump, NULL, NULL, xgm_v2_expr }}; sgs_ObjInterface xgm_vec3_iface[1] = {{ "vec3", NULL, NULL, xgm_v3_getindex, xgm_v3_setindex, xgm_v3_convert, xgm_v3_serialize, xgm_v3_dump, NULL, NULL, xgm_v3_expr }}; sgs_ObjInterface xgm_vec4_iface[1] = {{ "vec4", NULL, NULL, xgm_v4_getindex, xgm_v4_setindex, xgm_v4_convert, xgm_v4_serialize, xgm_v4_dump, NULL, NULL, xgm_v4_expr }}; sgs_ObjInterface xgm_aabb2_iface[1] = {{ "aabb2", NULL, NULL, xgm_b2_getindex, xgm_b2_setindex, xgm_b2_convert, xgm_b2_serialize, xgm_b2_dump, NULL, NULL, xgm_b2_expr }}; sgs_ObjInterface xgm_color_iface[1] = {{ "color", NULL, NULL, xgm_col_getindex, xgm_col_setindex, xgm_col_convert, xgm_col_serialize, xgm_col_dump, NULL, NULL, xgm_col_expr }}; sgs_ObjInterface xgm_mat4_iface[1] = {{ "mat4", NULL, NULL, xgm_m4_getindex, xgm_m4_setindex, xgm_m4_convert, xgm_m4_serialize, xgm_m4_dump, NULL, NULL, xgm_m4_expr }}; sgs_ObjInterface xgm_floatarr_iface[1] = {{ "vec2array", xgm_fla_destruct, NULL, xgm_fla_getindex, xgm_fla_setindex, xgm_fla_convert, xgm_fla_serialize, xgm_fla_dump, NULL, NULL, NULL }}; void sgs_InitVec2( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 2, xgm_vec2_iface ); nv[ 0 ] = x; nv[ 1 ] = y; } void sgs_InitVec3( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y, XGM_VT z ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 3, xgm_vec3_iface ); nv[ 0 ] = x; nv[ 1 ] = y; nv[ 2 ] = z; } void sgs_InitVec4( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y, XGM_VT z, XGM_VT w ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 4, xgm_vec4_iface ); nv[ 0 ] = x; nv[ 1 ] = y; nv[ 2 ] = z; nv[ 3 ] = w; } void sgs_InitAABB2( SGS_CTX, sgs_Variable* var, XGM_VT x1, XGM_VT y1_shdef, XGM_VT x2, XGM_VT y2 ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 4, xgm_aabb2_iface ); nv[ 0 ] = x1; nv[ 1 ] = y1_shdef; /* shadowed declaration warning */ nv[ 2 ] = x2; nv[ 3 ] = y2; } void sgs_InitColor( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y, XGM_VT z, XGM_VT w ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 4, xgm_color_iface ); nv[ 0 ] = x; nv[ 1 ] = y; nv[ 2 ] = z; nv[ 3 ] = w; } void sgs_InitMat4( SGS_CTX, sgs_Variable* var, const XGM_VT* v16f, int transpose ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 16, xgm_mat4_iface ); if( transpose ) { nv[ 0 ] = v16f[ 0 ]; nv[ 1 ] = v16f[ 4 ]; nv[ 2 ] = v16f[ 8 ]; nv[ 3 ] = v16f[ 12 ]; nv[ 4 ] = v16f[ 1 ]; nv[ 5 ] = v16f[ 5 ]; nv[ 6 ] = v16f[ 9 ]; nv[ 7 ] = v16f[ 13 ]; nv[ 8 ] = v16f[ 2 ]; nv[ 9 ] = v16f[ 6 ]; nv[ 10 ] = v16f[ 10 ]; nv[ 11 ] = v16f[ 14 ]; nv[ 12 ] = v16f[ 3 ]; nv[ 13 ] = v16f[ 7 ]; nv[ 14 ] = v16f[ 11 ]; nv[ 15 ] = v16f[ 15 ]; } else memcpy( nv, v16f, sizeof(XGM_VT) * 16 ); } void sgs_InitFloatArray( SGS_CTX, sgs_Variable* var, const XGM_VT* vfn, sgs_SizeVal size ) { xgm_vtarray* np = (xgm_vtarray*) sgs_InitObjectIPA( C, var, sizeof(xgm_vtarray), xgm_floatarr_iface ); np->size = size; np->mem = size; np->data = size ? sgs_Alloc_n( XGM_VT, (size_t) np->mem ) : NULL; memcpy( np->data, vfn, sizeof( XGM_VT ) * (size_t) np->mem ); } void sgs_InitVec2p( SGS_CTX, sgs_Variable* var, const XGM_VT* v2f ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 2, xgm_vec2_iface ); nv[ 0 ] = v2f[ 0 ]; nv[ 1 ] = v2f[ 1 ]; } void sgs_InitVec3p( SGS_CTX, sgs_Variable* var, const XGM_VT* v3f ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 3, xgm_vec3_iface ); nv[ 0 ] = v3f[ 0 ]; nv[ 1 ] = v3f[ 1 ]; nv[ 2 ] = v3f[ 2 ]; } void sgs_InitVec4p( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 4, xgm_vec4_iface ); nv[ 0 ] = v4f[ 0 ]; nv[ 1 ] = v4f[ 1 ]; nv[ 2 ] = v4f[ 2 ]; nv[ 3 ] = v4f[ 3 ]; } void sgs_InitAABB2p( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 4, xgm_aabb2_iface ); nv[ 0 ] = v4f[ 0 ]; nv[ 1 ] = v4f[ 1 ]; nv[ 2 ] = v4f[ 2 ]; nv[ 3 ] = v4f[ 3 ]; } void sgs_InitColorp( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 4, xgm_color_iface ); nv[ 0 ] = v4f[ 0 ]; nv[ 1 ] = v4f[ 1 ]; nv[ 2 ] = v4f[ 2 ]; nv[ 3 ] = v4f[ 3 ]; } void sgs_InitColorvp( SGS_CTX, sgs_Variable* var, const XGM_VT* vf, int numfloats ) { XGM_VT* nv = (XGM_VT*) sgs_InitObjectIPA( C, var, sizeof(XGM_VT) * 4, xgm_color_iface ); if( numfloats == 0 ) nv[0] = nv[1] = nv[2] = nv[3] = 0; else if( numfloats == 1 ) nv[0] = nv[1] = nv[2] = nv[3] = vf[0]; else if( numfloats == 2 ){ nv[0] = nv[1] = nv[2] = vf[0]; nv[3] = vf[1]; } else if( numfloats == 3 ){ nv[0] = vf[0]; nv[1] = vf[1]; nv[2] = vf[2]; nv[3] = 1; } else { nv[0] = vf[0]; nv[1] = vf[1]; nv[2] = vf[2]; nv[3] = vf[3]; } } void sgs_PushVec2( SGS_CTX, XGM_VT x, XGM_VT y ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 2, xgm_vec2_iface ); nv[ 0 ] = x; nv[ 1 ] = y; } void sgs_PushVec3( SGS_CTX, XGM_VT x, XGM_VT y, XGM_VT z ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 3, xgm_vec3_iface ); nv[ 0 ] = x; nv[ 1 ] = y; nv[ 2 ] = z; } void sgs_PushVec4( SGS_CTX, XGM_VT x, XGM_VT y, XGM_VT z, XGM_VT w ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 4, xgm_vec4_iface ); nv[ 0 ] = x; nv[ 1 ] = y; nv[ 2 ] = z; nv[ 3 ] = w; } void sgs_PushAABB2( SGS_CTX, XGM_VT x1, XGM_VT y1_shdef, XGM_VT x2, XGM_VT y2 ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 4, xgm_aabb2_iface ); nv[ 0 ] = x1; nv[ 1 ] = y1_shdef; /* shadowed declaration warning */ nv[ 2 ] = x2; nv[ 3 ] = y2; } void sgs_PushColor( SGS_CTX, XGM_VT x, XGM_VT y, XGM_VT z, XGM_VT w ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 4, xgm_color_iface ); nv[ 0 ] = x; nv[ 1 ] = y; nv[ 2 ] = z; nv[ 3 ] = w; } void sgs_PushMat4( SGS_CTX, const XGM_VT* v16f, int transpose ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 16, xgm_mat4_iface ); if( transpose ) { nv[ 0 ] = v16f[ 0 ]; nv[ 1 ] = v16f[ 4 ]; nv[ 2 ] = v16f[ 8 ]; nv[ 3 ] = v16f[ 12 ]; nv[ 4 ] = v16f[ 1 ]; nv[ 5 ] = v16f[ 5 ]; nv[ 6 ] = v16f[ 9 ]; nv[ 7 ] = v16f[ 13 ]; nv[ 8 ] = v16f[ 2 ]; nv[ 9 ] = v16f[ 6 ]; nv[ 10 ] = v16f[ 10 ]; nv[ 11 ] = v16f[ 14 ]; nv[ 12 ] = v16f[ 3 ]; nv[ 13 ] = v16f[ 7 ]; nv[ 14 ] = v16f[ 11 ]; nv[ 15 ] = v16f[ 15 ]; } else memcpy( nv, v16f, sizeof(XGM_VT) * 16 ); } void sgs_PushFloatArray( SGS_CTX, const XGM_VT* vfn, sgs_SizeVal size ) { xgm_vtarray* np = (xgm_vtarray*) sgs_PushObjectIPA( C, sizeof(xgm_vtarray), xgm_floatarr_iface ); np->size = size; np->mem = size; np->data = size ? sgs_Alloc_n( XGM_VT, (size_t) np->mem ) : NULL; memcpy( np->data, vfn, sizeof( XGM_VT ) * (size_t) np->mem ); } void sgs_PushVec2p( SGS_CTX, const XGM_VT* v2f ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 2, xgm_vec2_iface ); nv[ 0 ] = v2f[ 0 ]; nv[ 1 ] = v2f[ 1 ]; } void sgs_PushVec3p( SGS_CTX, const XGM_VT* v3f ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 3, xgm_vec3_iface ); nv[ 0 ] = v3f[ 0 ]; nv[ 1 ] = v3f[ 1 ]; nv[ 2 ] = v3f[ 2 ]; } void sgs_PushVec4p( SGS_CTX, const XGM_VT* v4f ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 4, xgm_vec4_iface ); nv[ 0 ] = v4f[ 0 ]; nv[ 1 ] = v4f[ 1 ]; nv[ 2 ] = v4f[ 2 ]; nv[ 3 ] = v4f[ 3 ]; } void sgs_PushAABB2p( SGS_CTX, const XGM_VT* v4f ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 4, xgm_aabb2_iface ); nv[ 0 ] = v4f[ 0 ]; nv[ 1 ] = v4f[ 1 ]; nv[ 2 ] = v4f[ 2 ]; nv[ 3 ] = v4f[ 3 ]; } void sgs_PushColorp( SGS_CTX, const XGM_VT* v4f ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 4, xgm_color_iface ); nv[ 0 ] = v4f[ 0 ]; nv[ 1 ] = v4f[ 1 ]; nv[ 2 ] = v4f[ 2 ]; nv[ 3 ] = v4f[ 3 ]; } void sgs_PushColorvp( SGS_CTX, const XGM_VT* vf, int numfloats ) { XGM_VT* nv = (XGM_VT*) sgs_PushObjectIPA( C, sizeof(XGM_VT) * 4, xgm_color_iface ); if( numfloats == 0 ) nv[0] = nv[1] = nv[2] = nv[3] = 0; else if( numfloats == 1 ) nv[0] = nv[1] = nv[2] = nv[3] = vf[0]; else if( numfloats == 2 ){ nv[0] = nv[1] = nv[2] = vf[0]; nv[3] = vf[1]; } else if( numfloats == 3 ){ nv[0] = vf[0]; nv[1] = vf[1]; nv[2] = vf[2]; nv[3] = 1; } else { nv[0] = vf[0]; nv[1] = vf[1]; nv[2] = vf[2]; nv[3] = vf[3]; } } SGSBOOL sgs_ParseVec2P( SGS_CTX, sgs_Variable* var, XGM_VT* v2f, int strict ) { if( !strict && ( var->type == SGS_VT_INT || var->type == SGS_VT_REAL ) ) { v2f[0] = v2f[1] = (XGM_VT) sgs_GetRealP( C, var ); return 1; } if( var->type != SGS_VT_OBJECT ) return 0; if( sgs_IsObjectP( var, xgm_vec2_iface ) ) { XGM_VT* hdr = (XGM_VT*) sgs_GetObjectDataP( var ); v2f[0] = hdr[0]; v2f[1] = hdr[1]; return 1; } return 0; } SGSBOOL sgs_ParseVec3P( SGS_CTX, sgs_Variable* var, XGM_VT* v3f, int strict ) { if( !strict && ( var->type == SGS_VT_INT || var->type == SGS_VT_REAL ) ) { v3f[0] = v3f[1] = v3f[2] = (XGM_VT) sgs_GetRealP( C, var ); return 1; } if( var->type != SGS_VT_OBJECT ) return 0; if( sgs_IsObjectP( var, xgm_vec3_iface ) ) { XGM_VT* hdr = (XGM_VT*) sgs_GetObjectDataP( var ); v3f[0] = hdr[0]; v3f[1] = hdr[1]; v3f[2] = hdr[2]; return 1; } return 0; } SGSBOOL sgs_ParseVec4P( SGS_CTX, sgs_Variable* var, XGM_VT* v4f, int strict ) { if( !strict && ( var->type == SGS_VT_INT || var->type == SGS_VT_REAL ) ) { v4f[0] = v4f[1] = v4f[2] = v4f[3] = (XGM_VT) sgs_GetRealP( C, var ); return 1; } if( var->type != SGS_VT_OBJECT ) return 0; if( sgs_IsObjectP( var, xgm_vec4_iface ) || sgs_IsObjectP( var, xgm_color_iface ) ) { XGM_VT* hdr = (XGM_VT*) sgs_GetObjectDataP( var ); v4f[0] = hdr[0]; v4f[1] = hdr[1]; v4f[2] = hdr[2]; v4f[3] = hdr[3]; return 1; } return 0; } SGSBOOL sgs_ParseAABB2P( SGS_CTX, sgs_Variable* var, XGM_VT* v4f ) { if( sgs_IsObjectP( var, xgm_aabb2_iface ) ) { XGM_VT* hdr = (XGM_VT*) sgs_GetObjectDataP( var ); v4f[0] = hdr[0]; v4f[1] = hdr[1]; v4f[2] = hdr[2]; v4f[3] = hdr[3]; return 1; } return 0; } SGSBOOL sgs_ParseColorP( SGS_CTX, sgs_Variable* var, XGM_VT* v4f, int strict ) { return sgs_ParseVec4P( C, var, v4f, strict ); } SGSBOOL sgs_ParseMat4P( SGS_CTX, sgs_Variable* var, XGM_VT* v16f ) { if( sgs_IsObjectP( var, xgm_mat4_iface ) ) { XGM_VT* hdr = (XGM_VT*) sgs_GetObjectDataP( var ); memcpy( v16f, hdr, sizeof(XGM_VT) * 16 ); return 1; } return 0; } SGSBOOL sgs_ParseFloatArrayP( SGS_CTX, sgs_Variable* var, XGM_VT** v2fa, sgs_SizeVal* osz ) { if( sgs_IsObjectP( var, xgm_floatarr_iface ) ) { xgm_vtarray* data = (xgm_vtarray*) sgs_GetObjectDataP( var ); if( v2fa ) *v2fa = data->data; if( osz ) *osz = data->size; return 1; } return 0; } SGSBOOL sgs_ParseVec2( SGS_CTX, sgs_StkIdx item, XGM_VT* v2f, int strict ) { sgs_Variable tmp; return sgs_PeekStackItem( C, item, &tmp ) && sgs_ParseVec2P( C, &tmp, v2f, strict ); } SGSBOOL sgs_ParseVec3( SGS_CTX, sgs_StkIdx item, XGM_VT* v3f, int strict ) { sgs_Variable tmp; return sgs_PeekStackItem( C, item, &tmp ) && sgs_ParseVec3P( C, &tmp, v3f, strict ); } SGSBOOL sgs_ParseVec4( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f, int strict ) { sgs_Variable tmp; return sgs_PeekStackItem( C, item, &tmp ) && sgs_ParseVec4P( C, &tmp, v4f, strict ); } SGSBOOL sgs_ParseAABB2( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f ) { sgs_Variable tmp; return sgs_PeekStackItem( C, item, &tmp ) && sgs_ParseAABB2P( C, &tmp, v4f ); } SGSBOOL sgs_ParseColor( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f, int strict ) { return sgs_ParseVec4( C, item, v4f, strict ); } SGSBOOL sgs_ParseMat4( SGS_CTX, sgs_StkIdx item, XGM_VT* v16f ) { sgs_Variable tmp; return sgs_PeekStackItem( C, item, &tmp ) && sgs_ParseMat4P( C, &tmp, v16f ); } SGSBOOL sgs_ParseFloatArray( SGS_CTX, sgs_StkIdx item, XGM_VT** v2fa, sgs_SizeVal* osz ) { sgs_Variable tmp; return sgs_PeekStackItem( C, item, &tmp ) && sgs_ParseFloatArrayP( C, &tmp, v2fa, osz ); } int sgs_ArgCheck_Vec2( SGS_CTX, int argid, va_list* args, int flags ) { XGM_VT* out = NULL; XGM_VT v[2]; if( flags & SGS_LOADARG_WRITE ) out = va_arg( *args, XGM_VT* ); if( sgs_ParseVec2( C, argid, v, flags & SGS_LOADARG_STRICT ? 1 : 0 ) ) { if( out ) { out[ 0 ] = v[ 0 ]; out[ 1 ] = v[ 1 ]; } return 1; } if( flags & SGS_LOADARG_OPTIONAL ) return 1; return sgs_ArgErrorExt( C, argid, 0, "vec2", flags & SGS_LOADARG_STRICT ? "strict " : "" ); } int sgs_ArgCheck_Vec3( SGS_CTX, int argid, va_list* args, int flags ) { XGM_VT* out = NULL; XGM_VT v[3]; if( flags & SGS_LOADARG_WRITE ) out = va_arg( *args, XGM_VT* ); if( sgs_ParseVec3( C, argid, v, flags & SGS_LOADARG_STRICT ? 1 : 0 ) ) { if( out ) { out[ 0 ] = v[ 0 ]; out[ 1 ] = v[ 1 ]; out[ 2 ] = v[ 2 ]; } return 1; } if( flags & SGS_LOADARG_OPTIONAL ) return 1; return sgs_ArgErrorExt( C, argid, 0, "vec3", flags & SGS_LOADARG_STRICT ? "strict " : "" ); } static int sgs_ArgCheck_4F( SGS_CTX, int argid, va_list* args, int flags, const char* name ) { XGM_VT* out = NULL; XGM_VT v[4]; if( flags & SGS_LOADARG_WRITE ) out = va_arg( *args, XGM_VT* ); if( sgs_ParseVec4( C, argid, v, flags & SGS_LOADARG_STRICT ? 1 : 0 ) ) { if( out ) { out[ 0 ] = v[ 0 ]; out[ 1 ] = v[ 1 ]; out[ 2 ] = v[ 2 ]; out[ 3 ] = v[ 3 ]; } return 1; } if( flags & SGS_LOADARG_OPTIONAL ) return 1; return sgs_ArgErrorExt( C, argid, 0, name, flags & SGS_LOADARG_STRICT ? "strict " : "" ); } int sgs_ArgCheck_Vec4( SGS_CTX, int argid, va_list* args, int flags ) { return sgs_ArgCheck_4F( C, argid, args, flags, "vec4" ); } int sgs_ArgCheck_AABB2( SGS_CTX, int argid, va_list* args, int flags ) { XGM_VT* out = NULL; XGM_VT v[4]; if( flags & SGS_LOADARG_WRITE ) out = va_arg( *args, XGM_VT* ); if( sgs_ParseAABB2( C, argid, v ) ) { if( out ) { out[ 0 ] = v[ 0 ]; out[ 1 ] = v[ 1 ]; out[ 2 ] = v[ 2 ]; out[ 3 ] = v[ 3 ]; } return 1; } if( flags & SGS_LOADARG_OPTIONAL ) return 1; return sgs_ArgErrorExt( C, argid, 0, "aabb2", flags & SGS_LOADARG_STRICT ? "strict " : "" ); } int sgs_ArgCheck_Color( SGS_CTX, int argid, va_list* args, int flags ) { return sgs_ArgCheck_4F( C, argid, args, flags, "color" ); } int sgs_ArgCheck_Mat4( SGS_CTX, int argid, va_list* args, int flags ) { XGM_VT v[16]; if( sgs_ParseMat4( C, argid, v ) ) { if( flags & SGS_LOADARG_WRITE ) { XGM_VT* out = va_arg( *args, XGM_VT* ); memcpy( out, v, sizeof(v) ); } return 1; } if( flags & SGS_LOADARG_OPTIONAL ) return 1; return sgs_ArgErrorExt( C, argid, 0, "mat4", "" ); } int sgs_ArgCheck_FloatArray( SGS_CTX, int argid, va_list* args, int flags ) { xgm_vtarray** out = NULL; if( flags & SGS_LOADARG_WRITE ) out = va_arg( *args, xgm_vtarray** ); if( sgs_ParseFloatArray( C, argid, NULL, NULL ) ) { if( out ) *out = (xgm_vtarray*) sgs_GetObjectData( C, argid ); return 1; } if( flags & SGS_LOADARG_OPTIONAL ) return 1; return sgs_ArgErrorExt( C, argid, 0, "floatarray", "" ); } static sgs_RegFuncConst xgm_fconsts[] = { { "vec2", xgm_vec2 }, { "vec2_dot", xgm_vec2_dot }, { "vec3", xgm_vec3 }, { "vec3_dot", xgm_vec3_dot }, { "vec3_cross", xgm_vec3_cross }, { "vec4", xgm_vec4 }, { "vec4_dot", xgm_vec4_dot }, { "aabb2", xgm_aabb2 }, { "aabb2v", xgm_aabb2v }, { "aabb2_intersect", xgm_aabb2_intersect }, { "color", xgm_color }, { "mat4", xgm_mat4 }, { "floatarray_buffer", xgm_floatarray_buffer }, { "floatarray", xgm_floatarray }, { "vec2array", xgm_vec2array }, { "vec3array", xgm_vec3array }, { "vec4array", xgm_vec4array }, { "floatarray_from_int8_buffer", xgm_floatarray_from_int8_buffer }, { "floatarray_from_int16_buffer", xgm_floatarray_from_int16_buffer }, { "floatarray_from_int32_buffer", xgm_floatarray_from_int32_buffer }, { "floatarray_from_int64_buffer", xgm_floatarray_from_int64_buffer }, { "floatarray_from_uint8_buffer", xgm_floatarray_from_uint8_buffer }, { "floatarray_from_uint16_buffer", xgm_floatarray_from_uint16_buffer }, { "floatarray_from_uint32_buffer", xgm_floatarray_from_uint32_buffer }, { "floatarray_from_uint64_buffer", xgm_floatarray_from_uint64_buffer }, { "floatarray_from_float32_buffer", xgm_floatarray_from_float32_buffer }, { "floatarray_from_float64_buffer", xgm_floatarray_from_float64_buffer }, { "ray_plane_intersect", xgm_ray_plane_intersect }, }; SGS_APIFUNC int xgm_module_entry_point( SGS_CTX ) { sgs_RegFuncConsts( C, xgm_fconsts, sizeof(xgm_fconsts) / sizeof(xgm_fconsts[0]) ); sgs_RegisterType( C, "vec2", xgm_vec2_iface ); sgs_RegisterType( C, "vec3", xgm_vec3_iface ); sgs_RegisterType( C, "vec4", xgm_vec4_iface ); sgs_RegisterType( C, "aabb2", xgm_aabb2_iface ); sgs_RegisterType( C, "color", xgm_color_iface ); sgs_RegisterType( C, "vec4", xgm_vec4_iface ); sgs_RegisterType( C, "floatarray", xgm_floatarr_iface ); return SGS_SUCCESS; } #ifdef SGS_COMPILE_MODULE SGS_APIFUNC int sgscript_main( SGS_CTX ) { return xgm_module_entry_point( C ); } #endif <file_sep>/src/sgs_int.h #ifndef SGS_INT_H_INCLUDED #define SGS_INT_H_INCLUDED #include "sgscript.h" #include "sgs_util.h" /* L I M I T S ! some limits may cancel or reduce others, .. .. these are kept for the purposes of knowing the size of variables .. .. to use in various systems - number of constants in a function: 0 - 65535 - number of instructions in a function: 0 - 65535 - string size: 0 - 2^31-1 - max. jump distance: 32767 instructions - max. loop depth: 65535 nested loops (no need to test for it since instruction count .. .. effectively limits this further) - bytecode size limit: 14 - 2^32-1 - source size limit: 0 - 2^31-1 - variable size limit: string size + overhead (<=256 bytes) - item type value limits: 8 bits - identifier size: 0 - 255 - argument count: 0 - 255 - returned value count: 0 - 255 - total closure count in one function: 0 - 255 - temporary variable count (incl. args): 0 - 255 - useful line count limits in source file: 0 - 32767 - stack size: 0 - 2^31-1 - closure stack size: 0 - 2^31-1 - array size: 0 - 2^31-1 - hash table size: 0 - 2^31-1 */ #ifdef __cplusplus extern "C" { #endif #ifdef SGS_INTERNAL # define ST_NULL SGS_ST_NULL # define ST_RBRKL SGS_ST_RBRKL # define ST_RBRKR SGS_ST_RBRKR # define ST_SBRKL SGS_ST_SBRKL # define ST_SBRKR SGS_ST_SBRKR # define ST_CBRKL SGS_ST_CBRKL # define ST_CBRKR SGS_ST_CBRKR # define ST_ARGSEP SGS_ST_ARGSEP # define ST_STSEP SGS_ST_STSEP # define ST_PICKSEP SGS_ST_PICKSEP # define ST_IDENT SGS_ST_IDENT # define ST_KEYWORD SGS_ST_KEYWORD # define ST_NUMREAL SGS_ST_NUMREAL # define ST_NUMINT SGS_ST_NUMINT # define ST_STRING SGS_ST_STRING # define ST_OP_SEQ SGS_ST_OP_SEQ # define ST_OP_SNEQ SGS_ST_OP_SNEQ # define ST_OP_EQ SGS_ST_OP_EQ # define ST_OP_NEQ SGS_ST_OP_NEQ # define ST_OP_LEQ SGS_ST_OP_LEQ # define ST_OP_GEQ SGS_ST_OP_GEQ # define ST_OP_LESS SGS_ST_OP_LESS # define ST_OP_GRTR SGS_ST_OP_GRTR # define ST_OP_RWCMP SGS_ST_OP_RWCMP # define ST_OP_ADDEQ SGS_ST_OP_ADDEQ # define ST_OP_SUBEQ SGS_ST_OP_SUBEQ # define ST_OP_MULEQ SGS_ST_OP_MULEQ # define ST_OP_DIVEQ SGS_ST_OP_DIVEQ # define ST_OP_MODEQ SGS_ST_OP_MODEQ # define ST_OP_ANDEQ SGS_ST_OP_ANDEQ # define ST_OP_OREQ SGS_ST_OP_OREQ # define ST_OP_XOREQ SGS_ST_OP_XOREQ # define ST_OP_LSHEQ SGS_ST_OP_LSHEQ # define ST_OP_RSHEQ SGS_ST_OP_RSHEQ # define ST_OP_BLAEQ SGS_ST_OP_BLAEQ # define ST_OP_BLOEQ SGS_ST_OP_BLOEQ # define ST_OP_CATEQ SGS_ST_OP_CATEQ # define ST_OP_SET SGS_ST_OP_SET # define ST_OP_ERSUP SGS_ST_OP_ERSUP # define ST_OP_BLAND SGS_ST_OP_BLAND # define ST_OP_BLOR SGS_ST_OP_BLOR # define ST_OP_ADD SGS_ST_OP_ADD # define ST_OP_SUB SGS_ST_OP_SUB # define ST_OP_MUL SGS_ST_OP_MUL # define ST_OP_DIV SGS_ST_OP_DIV # define ST_OP_MOD SGS_ST_OP_MOD # define ST_OP_AND SGS_ST_OP_AND # define ST_OP_OR SGS_ST_OP_OR # define ST_OP_XOR SGS_ST_OP_XOR # define ST_OP_LSH SGS_ST_OP_LSH # define ST_OP_RSH SGS_ST_OP_RSH # define ST_OP_MMBR SGS_ST_OP_MMBR # define ST_OP_CAT SGS_ST_OP_CAT # define ST_OP_NOT SGS_ST_OP_NOT # define ST_OP_INV SGS_ST_OP_INV # define ST_OP_INC SGS_ST_OP_INC # define ST_OP_DEC SGS_ST_OP_DEC # define ST_ISOP SGS_ST_ISOP # define ST_OP_UNARY SGS_ST_OP_UNARY # define ST_OP_BINARY SGS_ST_OP_BINARY # define ST_OP_ASSIGN SGS_ST_OP_ASSIGN # define ST_OP_BINMUL SGS_ST_OP_BINMUL # define ST_OP_BINADD SGS_ST_OP_BINADD # define ST_OP_BINOPS SGS_ST_OP_BINOPS # define ST_OP_COMP SGS_ST_OP_COMP # define ST_OP_BOOL SGS_ST_OP_BOOL # define ST_ISSPEC SGS_ST_ISSPEC # define ST_READINT SGS_ST_READINT # define ST_READLN SGS_ST_READLN /* # define TokenType sgs_TokenType */ # define TokenList sgs_TokenList # define SFT_NULL SGS_SFT_NULL # define SFT_IDENT SGS_SFT_IDENT # define SFT_KEYWORD SGS_SFT_KEYWORD # define SFT_CONST SGS_SFT_CONST # define SFT_OPER SGS_SFT_OPER # define SFT_OPER_P SGS_SFT_OPER_P # define SFT_FCALL SGS_SFT_FCALL # define SFT_INDEX SGS_SFT_INDEX # define SFT_MIDXSET SGS_SFT_MIDXSET # define SFT_MPROPSET SGS_SFT_MPROPSET # define SFT_ARGMT SGS_SFT_ARGMT # define SFT_ARGLIST SGS_SFT_ARGLIST # define SFT_VARLIST SGS_SFT_VARLIST # define SFT_GVLIST SGS_SFT_GVLIST # define SFT_USELIST SGS_SFT_USELIST # define SFT_EXPLIST SGS_SFT_EXPLIST # define SFT_ARRLIST SGS_SFT_ARRLIST # define SFT_MAPLIST SGS_SFT_MAPLIST # define SFT_RETURN SGS_SFT_RETURN # define SFT_BLOCK SGS_SFT_BLOCK # define SFT_IFELSE SGS_SFT_IFELSE # define SFT_WHILE SGS_SFT_WHILE # define SFT_DOWHILE SGS_SFT_DOWHILE # define SFT_FOR SGS_SFT_FOR # define SFT_FOREACH SGS_SFT_FOREACH # define SFT_BREAK SGS_SFT_BREAK # define SFT_CONT SGS_SFT_CONT # define SFT_FUNC SGS_SFT_FUNC # define FTNode sgs_FTNode # define CompFunc sgs_CompFunc # define rcpos_t sgs_rcpos_t /* VM */ # define CONSTVAR SGS_CONSTVAR # define CONSTENC SGS_CONSTENC # define CONSTDEC SGS_CONSTDEC # define SI_NOP SGS_SI_NOP # define SI_PUSH SGS_SI_PUSH # define SI_INT SGS_SI_INT # define SI_RETN SGS_SI_RETN # define SI_JUMP SGS_SI_JUMP # define SI_JMPT SGS_SI_JMPT # define SI_JMPF SGS_SI_JMPF # define SI_CALL SGS_SI_CALL # define SI_FORPREP SGS_SI_FORPREP # define SI_FORLOAD SGS_SI_FORLOAD # define SI_FORJUMP SGS_SI_FORJUMP # define SI_LOADCONST SGS_SI_LOADCONST # define SI_GETVAR SGS_SI_GETVAR # define SI_SETVAR SGS_SI_SETVAR # define SI_GETPROP SGS_SI_GETPROP # define SI_SETPROP SGS_SI_SETPROP # define SI_GETINDEX SGS_SI_GETINDEX # define SI_SETINDEX SGS_SI_SETINDEX # define SI_GENCLSR SGS_SI_GENCLSR # define SI_PUSHCLSR SGS_SI_PUSHCLSR # define SI_MAKECLSR SGS_SI_MAKECLSR # define SI_GETCLSR SGS_SI_GETCLSR # define SI_SETCLSR SGS_SI_SETCLSR # define SI_SET SGS_SI_SET # define SI_MCONCAT SGS_SI_MCONCAT # define SI_CONCAT SGS_SI_CONCAT # define SI_NEGATE SGS_SI_NEGATE # define SI_BOOL_INV SGS_SI_BOOL_INV # define SI_INVERT SGS_SI_INVERT # define SI_INC SGS_SI_INC # define SI_DEC SGS_SI_DEC # define SI_ADD SGS_SI_ADD # define SI_SUB SGS_SI_SUB # define SI_MUL SGS_SI_MUL # define SI_DIV SGS_SI_DIV # define SI_MOD SGS_SI_MOD # define SI_AND SGS_SI_AND # define SI_OR SGS_SI_OR # define SI_XOR SGS_SI_XOR # define SI_LSH SGS_SI_LSH # define SI_RSH SGS_SI_RSH # define SI_SEQ SGS_SI_SEQ # define SI_SNEQ SGS_SI_SNEQ # define SI_EQ SGS_SI_EQ # define SI_NEQ SGS_SI_NEQ # define SI_LT SGS_SI_LT # define SI_GTE SGS_SI_GTE # define SI_GT SGS_SI_GT # define SI_LTE SGS_SI_LTE # define SI_RAWCMP SGS_SI_RAWCMP # define SI_ARRAY SGS_SI_ARRAY # define SI_DICT SGS_SI_DICT # define instr_t sgs_instr_t # define INSTR_SIZE SGS_INSTR_SIZE # define INSTR_OFF_OP SGS_INSTR_OFF_OP # define INSTR_OFF_A SGS_INSTR_OFF_A # define INSTR_OFF_B SGS_INSTR_OFF_B # define INSTR_OFF_C SGS_INSTR_OFF_C # define INSTR_OFF_E SGS_INSTR_OFF_E # define INSTR_MASK_OP SGS_INSTR_MASK_OP # define INSTR_MASK_A SGS_INSTR_MASK_A # define INSTR_MASK_B SGS_INSTR_MASK_B # define INSTR_MASK_C SGS_INSTR_MASK_C # define INSTR_MASK_E SGS_INSTR_MASK_E # define INSTR_GET_OP SGS_INSTR_GET_OP # define INSTR_GET_A SGS_INSTR_GET_A # define INSTR_GET_B SGS_INSTR_GET_B # define INSTR_GET_C SGS_INSTR_GET_C # define INSTR_GET_E SGS_INSTR_GET_E # define INSTR_MAKE_OP SGS_INSTR_MAKE_OP # define INSTR_MAKE_A SGS_INSTR_MAKE_A # define INSTR_MAKE_B SGS_INSTR_MAKE_B # define INSTR_MAKE_C SGS_INSTR_MAKE_C # define INSTR_MAKE_E SGS_INSTR_MAKE_E # define INSTR_MAKE SGS_INSTR_MAKE # define INSTR_MAKE_EX SGS_INSTR_MAKE_EX # define INSTR_RECOMB_E SGS_INSTR_RECOMB_E # define func_t sgs_iFunc # define func_consts sgs_func_consts # define func_bytecode sgs_func_bytecode # define func_c_consts sgs_func_c_consts # define func_c_bytecode sgs_func_c_bytecode # define string_t sgs_iStr # define str_cstr sgs_str_cstr # define str_c_cstr sgs_str_c_cstr # define var_cstr sgs_var_cstr # define object_t sgs_object_t # define var_destroy_object sgsVM_VarDestroyObject # define STACKFRAMESIZE SGS_STACKFRAMESIZE #endif /* Token stream <1 byte: type> <additional data> <2 bytes: line number> */ /* special id */ #define SGS_ST_NULL '\0' #define SGS_ST_RBRKL '(' #define SGS_ST_RBRKR ')' #define SGS_ST_SBRKL '[' #define SGS_ST_SBRKR ']' #define SGS_ST_CBRKL '{' #define SGS_ST_CBRKR '}' #define SGS_ST_ARGSEP ',' #define SGS_ST_STSEP ';' #define SGS_ST_PICKSEP ':' /* other id additional data */ #define SGS_ST_IDENT 'N' /* 1 byte (string size), N bytes (string), not null-terminated */ #define SGS_ST_KEYWORD 'K' /* same as IDENT */ #define SGS_ST_NUMREAL 'R' /* 8 bytes (double) */ #define SGS_ST_NUMINT 'I' /* 8 bytes (int64) */ #define SGS_ST_STRING 'S' /* 4 bytes (string size), N bytes (string), not null-terminated */ /* operators id type */ #define SGS_ST_OP_SEQ 200 /* === */ #define SGS_ST_OP_SNEQ 201 /* !== */ #define SGS_ST_OP_EQ 202 /* == */ #define SGS_ST_OP_NEQ 203 /* != */ #define SGS_ST_OP_LEQ 204 /* <= */ #define SGS_ST_OP_GEQ 205 /* >= */ #define SGS_ST_OP_LESS 206 /* < */ #define SGS_ST_OP_GRTR 207 /* > */ #define SGS_ST_OP_RWCMP 208 /* <=> */ #define SGS_ST_OP_ADDEQ 209 /* += */ #define SGS_ST_OP_SUBEQ 210 /* -= */ #define SGS_ST_OP_MULEQ 211 /* *= */ #define SGS_ST_OP_DIVEQ 212 /* /= */ #define SGS_ST_OP_MODEQ 213 /* %= */ #define SGS_ST_OP_ANDEQ 214 /* &= */ #define SGS_ST_OP_OREQ 215 /* |= */ #define SGS_ST_OP_XOREQ 216 /* ^= */ #define SGS_ST_OP_LSHEQ 217 /* <<= */ #define SGS_ST_OP_RSHEQ 218 /* >>= */ #define SGS_ST_OP_BLAEQ 219 /* &&= */ #define SGS_ST_OP_BLOEQ 220 /* ||= */ #define SGS_ST_OP_CATEQ 221 /* $= */ #define SGS_ST_OP_SET 222 /* = */ #define SGS_ST_OP_ERSUP 223 /* @ */ #define SGS_ST_OP_BLAND 224 /* && */ #define SGS_ST_OP_BLOR 225 /* || */ #define SGS_ST_OP_ADD 226 /* + */ #define SGS_ST_OP_SUB 227 /* - */ #define SGS_ST_OP_MUL 228 /* * */ #define SGS_ST_OP_DIV 229 /* / */ #define SGS_ST_OP_MOD 230 /* % */ #define SGS_ST_OP_AND 231 /* & */ #define SGS_ST_OP_OR 232 /* | */ #define SGS_ST_OP_XOR 233 /* ^ */ #define SGS_ST_OP_LSH 234 /* << */ #define SGS_ST_OP_RSH 235 /* >> */ #define SGS_ST_OP_MMBR 236 /* . */ #define SGS_ST_OP_CAT 237 /* $ */ #define SGS_ST_OP_NOT 238 /* ! */ #define SGS_ST_OP_INV 239 /* ~ */ #define SGS_ST_OP_INC 240 /* ++ */ #define SGS_ST_OP_DEC 241 /* -- */ #define SGS_ST_ISOP( chr ) ( (chr) >= 200 && (chr) <= 241 ) #define SGS_ST_OP_UNARY( chr ) ( (chr) == SGS_ST_OP_ERSUP || (chr) == SGS_ST_OP_ADD || \ (chr) == SGS_ST_OP_SUB || ( (chr) >= SGS_ST_OP_NOT && (chr) <= SGS_ST_OP_DEC ) ) #define SGS_ST_OP_BINARY( chr ) ( (chr) >= 200 && (chr) <= 237 && (chr) != 223 ) #define SGS_ST_OP_ASSIGN( chr ) ( (chr) >= 209 && (chr) <= 222 ) #define SGS_ST_OP_BINMUL( chr ) ( (chr) == SGS_ST_OP_MUL || (chr) == SGS_ST_OP_DIV || (chr) == SGS_ST_OP_MOD ) #define SGS_ST_OP_BINADD( chr ) ( (chr) == SGS_ST_OP_ADD || (chr) == SGS_ST_OP_SUB ) #define SGS_ST_OP_BINOPS( chr ) ( (chr) >= SGS_ST_OP_AND && (chr) <= SGS_ST_OP_RSH ) #define SGS_ST_OP_COMP( chr ) ( (chr) >= 200 && (chr) <= 208 ) #define SGS_ST_OP_BOOL( chr ) ( (chr) == SGS_ST_OP_BLAEQ || (chr) == SGS_ST_OP_BLOEQ || \ (chr) == SGS_ST_OP_BLAND || (chr) == SGS_ST_OP_BLOR ) #define SGS_ST_ISSPEC( chr ) isoneof( (chr), "()[]{},;:" ) #define SGS_ST_READINT( tgt, pos ) SGS_AS_INT32( tgt, pos ) #define SGS_ST_READLN( tgt, pos ) SGS_AS_( tgt, pos, sgs_LineNum ) typedef unsigned char sgs_TokenType; typedef unsigned char* sgs_TokenList; SGS_APIFUNC sgs_TokenList sgsT_Gen( SGS_CTX, const char* code, size_t length ); SGS_APIFUNC void sgsT_Free( SGS_CTX, sgs_TokenList tlist ); SGS_APIFUNC sgs_TokenList sgsT_Next( sgs_TokenList tok ); SGS_APIFUNC sgs_LineNum sgsT_LineNum( sgs_TokenList tok ); SGS_APIFUNC size_t sgsT_ListSize( sgs_TokenList tlist ); SGS_APIFUNC size_t sgsT_ListMemSize( sgs_TokenList tlist ); SGS_APIFUNC void sgsT_TokenString( SGS_CTX, sgs_MemBuf* out, sgs_TokenList tlist, sgs_TokenList tend, int xs ); SGS_APIFUNC void sgsT_DumpToken( sgs_TokenList tok ); SGS_APIFUNC void sgsT_DumpList( sgs_TokenList tlist, sgs_TokenList tend ); /* Function tree */ #define SGS_SFT_NULL 0 /* data */ #define SGS_SFT_IDENT 1 #define SGS_SFT_KEYWORD 2 #define SGS_SFT_CONST 3 /* expression parts */ #define SGS_SFT_OPER 4 #define SGS_SFT_OPER_P 5 /* post-op (inc/dec) */ #define SGS_SFT_FCALL 6 #define SGS_SFT_INDEX 7 #define SGS_SFT_MIDXSET 8 #define SGS_SFT_MPROPSET 9 /* statement data */ #define SGS_SFT_ARGMT 10 #define SGS_SFT_ARGLIST 11 #define SGS_SFT_VARLIST 12 #define SGS_SFT_GVLIST 13 #define SGS_SFT_USELIST 14 #define SGS_SFT_EXPLIST 15 #define SGS_SFT_ARRLIST 16 #define SGS_SFT_MAPLIST 17 #define SGS_SFT_RETURN 18 /* statement types */ #define SGS_SFT_BLOCK 21 #define SGS_SFT_IFELSE 22 #define SGS_SFT_WHILE 23 #define SGS_SFT_DOWHILE 24 #define SGS_SFT_FOR 25 #define SGS_SFT_FOREACH 26 #define SGS_SFT_BREAK 27 #define SGS_SFT_CONT 28 #define SGS_SFT_FUNC 30 typedef struct _sgs_FTNode sgs_FTNode; struct _sgs_FTNode { sgs_TokenList token; sgs_FTNode* next; sgs_FTNode* child; int type; }; SGS_APIFUNC void sgsFT_Destroy( SGS_CTX, sgs_FTNode* tree ); SGS_APIFUNC sgs_FTNode* sgsFT_Compile( SGS_CTX, sgs_TokenList tlist ); SGS_APIFUNC void sgsFT_Dump( sgs_FTNode* tree ); /* Intermediate function - keeps the function data between compiler stages */ typedef struct _sgs_CompFunc { sgs_MemBuf consts; sgs_MemBuf code; sgs_MemBuf lnbuf; uint8_t gotthis; /* bool */ uint8_t numargs; /* guaranteed to be <= 255 by a test in `preparse_arglist` */ uint8_t numtmp; /* reg. count (0-255, incl. numargs) - numargs (0-255) */ uint8_t numclsr; } sgs_CompFunc; /* - bytecode generator */ SGS_APIFUNC sgs_CompFunc* sgsBC_Generate( SGS_CTX, sgs_FTNode* tree ); SGS_APIFUNC void sgsBC_Dump( sgs_CompFunc* func ); SGS_APIFUNC void sgsBC_DumpEx( const char* constptr, size_t constsize, const char* codeptr, size_t codesize ); SGS_APIFUNC void sgsBC_Free( SGS_CTX, sgs_CompFunc* func ); /* Serialized bytecode */ SGS_APIFUNC int sgsBC_Func2Buf( SGS_CTX, sgs_CompFunc* func, sgs_MemBuf* outbuf ); /* assumes headers have already been validated (except size) but are still in the buffer */ SGS_APIFUNC const char* sgsBC_Buf2Func( SGS_CTX, const char* fn, const char* buf, size_t size, sgs_CompFunc** outfunc ); /* validates header size and bytes one by one (except last flag byte) -- will return header_size on success and failed byte position on failure */ SGS_APIFUNC int sgsBC_ValidateHeader( const char* buf, size_t size ); #define SGS_HEADER_SIZE 14 #define SGS_MIN_BC_SIZE 14 + SGS_HEADER_SIZE #define SGSBC_FLAG_LITTLE_ENDIAN 0x01 /* Virtual Machine */ #define SGS_CONSTVAR( x ) ((x)&0x100) #define SGS_CONSTENC( x ) ((x)|0x100) #define SGS_CONSTDEC( x ) ((x)&0xff) #define SGS_INT_ERRSUP_INC 1 #define SGS_INT_ERRSUP_DEC 2 typedef enum sgs_Instruction_e { SGS_SI_NOP = 0, SGS_SI_PUSH, /* (B:src) push register/constant */ SGS_SI_INT, /* (C:type) invoke a system state change */ SGS_SI_RETN, /* (A:N) exit current frame of execution, preserve N output arguments */ SGS_SI_JUMP, /* (E:off) add to instruction pointer */ SGS_SI_JMPT, /* (C:src, E:off) jump (add to instr.ptr.) if true */ SGS_SI_JMPF, /* (C:src, E:off) jump (add to instr.ptr.) if false */ SGS_SI_CALL, /* (A:exp, B:from, C:to) call a variable */ SGS_SI_FORPREP, /* (A:out, B:src) retrieves the iterator to work the object */ SGS_SI_FORLOAD, /* (A:iter, B:oky, C:ovl) retrieves current key & value from iterator */ SGS_SI_FORJUMP, /* (C:iter, E:off) advances and jumps if next key exists */ SGS_SI_LOADCONST,/* (C:out, E:off) load a constant to a register */ SGS_SI_GETVAR, /* (A:out, B:name) <varname> => <value> */ SGS_SI_SETVAR, /* (B:name, C:src) <varname> <value> => set <value> to <varname> */ SGS_SI_GETPROP, /* (A:out, B:var, C:name) <var> <prop> => <var> */ SGS_SI_SETPROP, /* (A:var, B:name, C:src) <var> <prop> <value> => set a <prop> of <var> to <value> */ SGS_SI_GETINDEX, /* -- || -- */ SGS_SI_SETINDEX, /* -- || -- */ /* closures */ SGS_SI_GENCLSR, /* (A:N) generates closure variables for the stack frame */ SGS_SI_PUSHCLSR, /* (A:src) pick closure variable for closure creation */ SGS_SI_MAKECLSR, /* (A:out, B:from, C:N) creates a closure object containing closure vars */ SGS_SI_GETCLSR, /* (A:out, B:which) loads data from the specified closure */ SGS_SI_SETCLSR, /* (B:which, C:src) stores data to the specified closure */ /* operators */ /* A: (A:out, B:s1, C:s2) B: (A:out, B:s1) */ SGS_SI_SET, /* B */ SGS_SI_MCONCAT, /* (A:out, B:N) */ SGS_SI_CONCAT, /* A */ SGS_SI_NEGATE, /* B */ SGS_SI_BOOL_INV, SGS_SI_INVERT, SGS_SI_INC, /* B */ SGS_SI_DEC, SGS_SI_ADD, /* A */ SGS_SI_SUB, SGS_SI_MUL, SGS_SI_DIV, SGS_SI_MOD, SGS_SI_AND, /* A */ SGS_SI_OR, SGS_SI_XOR, SGS_SI_LSH, SGS_SI_RSH, SGS_SI_SEQ, /* A */ SGS_SI_SNEQ, SGS_SI_EQ, SGS_SI_NEQ, SGS_SI_LT, SGS_SI_GTE, SGS_SI_GT, SGS_SI_LTE, SGS_SI_RAWCMP, /* specials */ SGS_SI_ARRAY, /* (A:out, B:args) */ SGS_SI_DICT, /* -- || -- */ SGS_SI_COUNT } sgs_Instruction; typedef uint32_t sgs_instr_t; /* instruction data: 32 bits OOOOOOAAAAAAAABBBBBBBBBCCCCCCCCC OOOOOOEEEEEEEEEEEEEEEEECCCCCCCCC */ #define SGS_INSTR_SIZE 4 #define SGS_INSTR_OFF_OP 0 #define SGS_INSTR_OFF_A 6 #define SGS_INSTR_OFF_B 14 #define SGS_INSTR_OFF_C 23 #define SGS_INSTR_OFF_E 6 #define SGS_INSTR_MASK_OP 0x003f /* OP: 6 bits */ #define SGS_INSTR_MASK_A 0x00ff /* A: 8 bits */ #define SGS_INSTR_MASK_B 0x01ff /* B: 9 bits */ #define SGS_INSTR_MASK_C 0x01ff /* C: 9 bits */ #define SGS_INSTR_MASK_E 0x0001ffff /* E: 17 bits */ #define SGS_INSTR_GET_OP( x ) ((int) (((x) >> SGS_INSTR_OFF_OP) & SGS_INSTR_MASK_OP)) #define SGS_INSTR_GET_A( x ) ((int) (((x) >> SGS_INSTR_OFF_A ) & SGS_INSTR_MASK_A )) #define SGS_INSTR_GET_B( x ) ((int) (((x) >> SGS_INSTR_OFF_B ) & SGS_INSTR_MASK_B )) #define SGS_INSTR_GET_C( x ) ((int) (((x) >> SGS_INSTR_OFF_C ) & SGS_INSTR_MASK_C )) #define SGS_INSTR_GET_E( x ) ((int) (((x) >> SGS_INSTR_OFF_E ) & SGS_INSTR_MASK_E )) #define SGS_INSTR_MAKE_OP( x ) ((sgs_instr_t) (((x) & SGS_INSTR_MASK_OP) << SGS_INSTR_OFF_OP)) #define SGS_INSTR_MAKE_A( x ) ((sgs_instr_t) (((x) & SGS_INSTR_MASK_A ) << SGS_INSTR_OFF_A )) #define SGS_INSTR_MAKE_B( x ) ((sgs_instr_t) (((x) & SGS_INSTR_MASK_B ) << SGS_INSTR_OFF_B )) #define SGS_INSTR_MAKE_C( x ) ((sgs_instr_t) (((x) & SGS_INSTR_MASK_C ) << SGS_INSTR_OFF_C )) #define SGS_INSTR_MAKE_E( x ) ((sgs_instr_t) (((x) & SGS_INSTR_MASK_E ) << SGS_INSTR_OFF_E )) #define SGS_INSTR_MAKE( op, a, b, c ) \ ( SGS_INSTR_MAKE_OP( op ) | SGS_INSTR_MAKE_A( a ) | SGS_INSTR_MAKE_B( b ) | SGS_INSTR_MAKE_C( c ) ) #define SGS_INSTR_MAKE_EX( op, ex, c ) \ ( SGS_INSTR_MAKE_OP( op ) | SGS_INSTR_MAKE_E( ex ) | SGS_INSTR_MAKE_C( c ) ) #define SGS_INSTR_RECOMB_E( a, b ) ( ( ( b ) << 8 ) | ( a ) ) struct _sgs_iFunc { int32_t refcount; uint32_t size; uint32_t instr_off; uint8_t gotthis; uint8_t numargs; uint8_t numtmp; uint8_t numclsr; sgs_LineNum linenum; sgs_LineNum* lineinfo; sgs_MemBuf funcname; sgs_MemBuf filename; }; SGS_CASSERT( sizeof(sgs_Variable) % 4 == 0, variable_object_chaining_issue ); SGS_CASSERT( sizeof(sgs_iFunc) % 4 == 0, ifunc_object_chaining_issue ); SGS_CASSERT( sizeof(sgs_iStr) % 8 == 0, istr_object_storage_compat_issue ); #define sgs_func_consts( pfn ) ((sgs_Variable*)SGS_ASSUME_ALIGNED(((sgs_iFunc*)(pfn))+1,16)) #define sgs_func_bytecode( pfn ) ((sgs_instr_t*)(sgs_func_consts(pfn)+pfn->instr_off/sizeof(sgs_Variable))) #define sgs_func_c_consts( pfn ) ((const sgs_Variable*)SGS_ASSUME_ALIGNED(((const sgs_iFunc*)(pfn))+1,16)) #define sgs_func_c_bytecode( pfn ) \ ((const sgs_instr_t*)(sgs_func_c_consts(pfn)+pfn->instr_off/sizeof(sgs_Variable))) #define sgs_object_t sgs_VarObj typedef struct _sgs_Closure sgs_Closure; struct _sgs_Closure { int32_t refcount; sgs_Variable var; }; /* VM interface */ void sgsVM_VarCreateString( SGS_CTX, sgs_Variable* out, const char* str, sgs_SizeVal len ); void sgsVM_VarDestroyObject( SGS_CTX, sgs_object_t* O ); size_t sgsVM_VarSize( const sgs_Variable* var ); void sgsVM_VarDump( const sgs_Variable* var ); void sgsVM_StackDump( SGS_CTX ); int sgsVM_ExecFn( SGS_CTX, int numtmp, void* code, size_t codesize, void* data, size_t datasize, int clean, uint16_t* T ); int sgsVM_VarCall( SGS_CTX, sgs_Variable* var, int args, int clsr, int expect, int gotthis ); void sgsVM_PushClosures( SGS_CTX, sgs_Closure** cls, int num ); sgs_Variable* sgsVM_VarMake_Dict(); int sgsVM_RegStdLibs( SGS_CTX ); int sgs_specfn_call( SGS_CTX ); int sgs_specfn_apply( SGS_CTX ); /* Context handling */ typedef struct _sgs_BreakInfo sgs_BreakInfo; struct _sgs_BreakInfo { sgs_BreakInfo* next; uint32_t jdoff; /* jump data offset */ uint16_t numlp; /* which loop */ uint8_t iscont; /* is a "continue"? */ }; /* register / constant position */ typedef int32_t sgs_rcpos_t; typedef struct _sgs_FuncCtx { int32_t func; sgs_rcpos_t regs, lastreg; sgs_MemBuf vars; sgs_MemBuf gvars; sgs_MemBuf clsr; int inclsr, outclsr; int32_t loops; sgs_BreakInfo* binfo; } sgs_FuncCtx; typedef struct _sgs_ObjPoolItem { sgs_VarObj* obj; uint32_t appsize; } sgs_ObjPoolItem; typedef sgs_Variable* sgs_VarPtr; struct _sgs_Context { uint32_t version; uint32_t apiversion; /* output */ sgs_OutputFunc output_fn; /* output function */ void* output_ctx; /* output context */ sgs_OutputFunc erroutput_fn; /* error output function */ void* erroutput_ctx; /* error output context */ /* info output */ int32_t minlev; int32_t apilev; sgs_MsgFunc msg_fn; /* messaging function */ void* msg_ctx; /* messaging context */ int last_errno; /* hook */ sgs_HookFunc hook_fn; void* hook_ctx; /* memory */ sgs_MemFunc memfunc; void* mfuserdata; size_t memsize; size_t numallocs; size_t numfrees; size_t numblocks; /* compilation */ uint32_t state; sgs_FuncCtx* fctx; /* ByteCodeGen */ const char* filename; /* filename of currently compiled code */ sgs_VHTable stringtable; /* string constant caching hash table */ /* virtual machine */ /* > main stack */ sgs_VarPtr stack_base; uint32_t stack_mem; sgs_VarPtr stack_off; sgs_VarPtr stack_top; /* > closure pointer stack */ sgs_Closure** clstk_base; sgs_Closure** clstk_off; sgs_Closure** clstk_top; uint32_t clstk_mem; /* > stack frame info */ sgs_StackFrame* sf_first; sgs_StackFrame* sf_last; sgs_StackFrame* sf_cached; int sf_count; /* > _G (global variable dictionary) */ sgs_VarObj* _G; /* > object info */ sgs_object_t* objs; int32_t objcount; /* >> object GC */ uint8_t redblue; sgs_VarPtr gclist; uint16_t gclist_size; uint16_t gcrun; /* >> object pool */ sgs_ObjPoolItem* objpool_data; int32_t objpool_size; /* type interface table */ sgs_VHTable typetable; }; #define SGS_STACKFRAMESIZE ((sgs_StkIdx)(C->stack_top - C->stack_off)) #ifdef SGS_INTERNAL_STRINGTABLES static const char* sgs_ErrNames[] = { "SUCCESS", "ENOTFND", "ECOMP", "ENOTOBJ", "ENOTSUP", "EBOUNDS", "EINVAL", "EINPROC" }; static const char* sgs_VarNames[] = { "null", "bool", "int", "real", "string", "function", "C function", "object", "ptr", }; static const char* sgs_OpNames[] = { "nop", "push", "int", "return", "jump", "jump_if_true", "jump_if_false", "call", "for_prep", "for_load", "for_jump", "loadconst", "getvar", "setvar", "getprop", "setprop", "getindex", "setindex", "genclsr", "pushclsr", "makeclsr", "getclsr", "setclsr", "set", "mconcat", "concat", "negate", "bool_inv", "invert", "inc", "dec", "add", "sub", "mul", "div", "mod", "and", "or", "xor", "lsh", "rsh", "seq", "sneq", "eq", "neq", "lt", "gte", "gt", "lte", "rawcmp", "array", "dict" }; #endif int sgsSTD_PostInit( SGS_CTX ); int sgsSTD_MakeArray( SGS_CTX, sgs_Variable* out, sgs_SizeVal cnt ); int sgsSTD_MakeDict( SGS_CTX, sgs_Variable* out, sgs_SizeVal cnt ); int sgsSTD_MakeMap( SGS_CTX, sgs_Variable* out, sgs_SizeVal cnt ); int sgsSTD_MakeClosure( SGS_CTX, sgs_Variable* func, uint32_t clc ); int sgsSTD_GlobalInit( SGS_CTX ); int sgsSTD_GlobalFree( SGS_CTX ); int sgsSTD_GlobalGet( SGS_CTX, sgs_Variable* out, sgs_Variable* idx ); int sgsSTD_GlobalSet( SGS_CTX, sgs_Variable* idx, sgs_Variable* val ); int sgsSTD_GlobalGC( SGS_CTX ); int sgsSTD_GlobalIter( SGS_CTX, sgs_VHTVar** outp, sgs_VHTVar** outpend ); /* STRUCTS */ typedef struct sgsstd_array_header_s { sgs_SizeVal size; sgs_SizeVal mem; sgs_Variable* data; } sgsstd_array_header_t; typedef struct sgsstd_array_iter_s { sgs_Variable ref; sgs_SizeVal size; sgs_SizeVal off; } sgsstd_array_iter_t; extern sgs_ObjInterface sgsstd_array_iface[1]; extern sgs_ObjInterface sgsstd_array_iter_iface[1]; extern sgs_ObjInterface sgsstd_dict_iface[1]; extern sgs_ObjInterface sgsstd_dict_iter_iface[1]; extern sgs_ObjInterface sgsstd_map_iface[1]; #define SGSIFACE_ARRAY SGS_IF_DLL( sgsstd_array_iface, sgs_FindType( C, "array" ) ) #define SGSIFACE_DICT SGS_IF_DLL( sgsstd_dict_iface, sgs_FindType( C, "dict" ) ) #define SGSIFACE_MAP SGS_IF_DLL( sgsstd_map_iface, sgs_FindType( C, "map" ) ) #ifdef __cplusplus } #endif #endif /* SGS_INT_H_INCLUDED */ <file_sep>/src/sgs_std.c #include <stdio.h> #include <errno.h> #define SGS_INTERNAL #define SGS_REALLY_INTERNAL #include "sgs_int.h" #define STDLIB_WARN( warn ) return sgs_Msg( C, SGS_WARNING, warn ); #define STDLIB_ERR( err ) return sgs_Msg( C, SGS_ERROR, err ); static int sgsstd_expectnum( SGS_CTX, StkIdx n ) { StkIdx ssz = sgs_StackSize( C ); if( n != ssz ) { sgs_Msg( C, SGS_WARNING, "function expects exactly %d arguments" ", %d given", n, ssz ); return FALSE; } return TRUE; } /* Containers */ /* ARRAY */ #define SGSARR_UNIT sizeof( sgs_Variable ) #define SGSARR_HDR sgsstd_array_header_t* hdr = (sgsstd_array_header_t*) data #define SGSARR_HDR_OI sgsstd_array_header_t* hdr = (sgsstd_array_header_t*) data->data #define SGSARR_HDRSIZE sizeof(sgsstd_array_header_t) #define SGSARR_ALLOCSIZE( cnt ) ((size_t)(cnt)*SGSARR_UNIT) #define SGSARR_PTR( base ) (((sgsstd_array_header_t*)base)->data) static void sgsstd_array_reserve( SGS_CTX, sgsstd_array_header_t* hdr, sgs_SizeVal size ) { if( size <= hdr->mem ) return; hdr->data = (sgs_Variable*) sgs_Realloc( C, hdr->data, SGSARR_ALLOCSIZE( size ) ); hdr->mem = size; } static void sgsstd_array_clear( SGS_CTX, sgsstd_array_header_t* hdr ) { sgs_ReleaseArray( C, SGSARR_PTR( hdr ), hdr->size ); hdr->size = 0; } /* off = offset in stack to start inserting from */ static void sgsstd_array_insert( SGS_CTX, sgsstd_array_header_t* hdr, sgs_SizeVal pos, StkIdx off ) { int i; StkIdx cnt = sgs_StackSize( C ) - off; sgs_SizeVal nsz = hdr->size + cnt; sgs_Variable* ptr = SGSARR_PTR( hdr ); if( !cnt ) return; if( nsz > hdr->mem ) { sgsstd_array_reserve( C, hdr, MAX( nsz, hdr->mem * 2 ) ); ptr = SGSARR_PTR( hdr ); } if( pos < hdr->size ) memmove( ptr + pos + cnt, ptr + pos, SGSARR_ALLOCSIZE( hdr->size - pos ) ); for( i = off; i < sgs_StackSize( C ); ++i ) { sgs_Variable* var = ptr + pos + i - off; sgs_GetStackItem( C, i, var ); } hdr->size = nsz; } static void sgsstd_array_insert_p( SGS_CTX, sgsstd_array_header_t* hdr, sgs_SizeVal pos, sgs_Variable* var ) { sgs_SizeVal nsz = hdr->size + 1; sgs_Variable* ptr = SGSARR_PTR( hdr ); if( nsz > hdr->mem ) { sgsstd_array_reserve( C, hdr, MAX( nsz, hdr->mem * 2 ) ); ptr = SGSARR_PTR( hdr ); } if( pos < hdr->size ) memmove( ptr + pos + 1, ptr + pos, SGSARR_ALLOCSIZE( hdr->size - pos ) ); ptr[ pos ] = *var; sgs_Acquire( C, var ); hdr->size = nsz; } static void sgsstd_array_erase( SGS_CTX, sgsstd_array_header_t* hdr, sgs_SizeVal from, sgs_SizeVal to ) { sgs_SizeVal i; sgs_SizeVal cnt = to - from + 1, to1 = to + 1; sgs_Variable* ptr = SGSARR_PTR( hdr ); sgs_BreakIf( from < 0 || from >= hdr->size || to < 0 || to >= hdr->size || from > to ); for( i = from; i <= to; ++i ) sgs_Release( C, ptr + i ); if( to1 < hdr->size ) memmove( ptr + from, ptr + to1, SGSARR_ALLOCSIZE( hdr->size - to1 ) ); hdr->size -= cnt; } #define SGSARR_IHDR( name ) \ sgsstd_array_header_t* hdr; \ if( !SGS_PARSE_METHOD( C, sgsstd_array_iface, hdr, array, name ) ) return 0; \ UNUSED( hdr ); static int sgsstd_arrayI_push( SGS_CTX ) { SGSARR_IHDR( push ); sgsstd_array_insert( C, hdr, hdr->size, 0 ); SGS_RETURN_THIS( C ); } static int sgsstd_arrayI_pop( SGS_CTX ) { sgs_Variable* ptr; SGSARR_IHDR( pop ); ptr = SGSARR_PTR( hdr ); if( !hdr->size ) STDLIB_WARN( "array is empty, cannot pop" ); sgs_PushVariable( C, ptr + hdr->size - 1 ); sgsstd_array_erase( C, hdr, hdr->size - 1, hdr->size - 1 ); return 1; } static int sgsstd_arrayI_shift( SGS_CTX ) { sgs_Variable* ptr; SGSARR_IHDR( shift ); ptr = SGSARR_PTR( hdr ); if( !hdr->size ) STDLIB_WARN( "array is empty, cannot shift" ); sgs_PushVariable( C, ptr ); sgsstd_array_erase( C, hdr, 0, 0 ); return 1; } static int sgsstd_arrayI_unshift( SGS_CTX ) { SGSARR_IHDR( unshift ); sgsstd_array_insert( C, hdr, 0, 0 ); SGS_RETURN_THIS( C ); } static int sgsstd_arrayI_insert( SGS_CTX ) { sgs_Int at; SGSARR_IHDR( insert ); if( !sgs_LoadArgs( C, "i?v", &at ) ) return 0; if( at < 0 ) at += hdr->size + 1; if( at < 0 || at > hdr->size ) STDLIB_WARN( "index out of bounds" ) sgsstd_array_insert( C, hdr, (sgs_SizeVal) at, 1 ); SGS_RETURN_THIS( C ); } static int sgsstd_arrayI_erase( SGS_CTX ) { int cnt = sgs_StackSize( C ); sgs_Int at, at2; SGSARR_IHDR( erase ); if( !sgs_LoadArgs( C, "i|i", &at, &at2 ) ) return 0; if( at < 0 ) at += hdr->size; if( at < 0 || at >= hdr->size ) STDLIB_WARN( "index out of bounds" ) if( cnt == 1 ) at2 = at; else { if( at2 < 0 ) at2 += hdr->size; if( at2 < 0 || at2 >= hdr->size ) STDLIB_WARN( "index out of bounds" ) if( at2 < at ) STDLIB_WARN( "after resolving," " index #1 must be smaller or equal than index #2" ) } sgsstd_array_erase( C, hdr, (sgs_SizeVal) at, (sgs_SizeVal) at2 ); SGS_RETURN_THIS( C ); } static int sgsstd_arrayI_part( SGS_CTX ) { sgs_SizeVal from, max = 0x7fffffff, to, i; SGSARR_IHDR( part ); if( !sgs_LoadArgs( C, "l|l", &from, &max ) ) return 0; if( max < 0 ) STDLIB_WARN( "argument 2 (count) cannot be negative" ) if( from < 0 ) from += hdr->size; to = from + max; if( to < from ) to = hdr->size; sgs_PushArray( C, 0 ); if( from < hdr->size && 0 < to ) { from = MAX( from, 0 ); to = MIN( to, hdr->size ); if( from < to ) { sgs_Variable *psrc, *pdst; sgs_SizeVal cnt = to - from; sgsstd_array_header_t* nhdr = (sgsstd_array_header_t*) sgs_GetObjectData( C, -1 ); sgsstd_array_reserve( C, nhdr, to - from ); nhdr->size = cnt; psrc = SGSARR_PTR( hdr ) + from; pdst = SGSARR_PTR( nhdr ); for( i = 0; i < cnt; ++i ) { pdst[ i ] = psrc[ i ]; sgs_Acquire( C, pdst + i ); } } } return 1; } static int sgsstd_arrayI_clear( SGS_CTX ) { SGSARR_IHDR( clear ); sgsstd_array_clear( C, hdr ); SGS_RETURN_THIS( C ); } static int sgsstd_arrayI_reverse( SGS_CTX ) { SGSARR_IHDR( reverse ); /* emit a warning if any arguments are passed */ if( !sgs_LoadArgs( C, "." ) ) return 0; { sgs_Variable tmp; sgs_Variable* P = SGSARR_PTR( hdr ); sgs_SizeVal i, j, hsz = hdr->size / 2; for( i = 0, j = hdr->size - 1; i < hsz; ++i, --j ) { tmp = P[ i ]; P[ i ] = P[ j ]; P[ j ] = tmp; } } SGS_RETURN_THIS( C ); } static void sgsstd_array_adjust( SGS_CTX, sgsstd_array_header_t* hdr, sgs_SizeVal cnt ) { while( hdr->size > cnt ) { sgs_Release( C, SGSARR_PTR( hdr ) + hdr->size - 1 ); hdr->size--; } while( hdr->size < cnt ) { ( SGSARR_PTR( hdr ) + (hdr->size++) )->type = SVT_NULL; } } static int sgsstd_arrayI_resize( SGS_CTX ) { sgs_SizeVal sz; SGSARR_IHDR( resize ); if( !sgs_LoadArgs( C, "l", &sz ) ) return 0; if( sz < 0 ) STDLIB_WARN( "argument 1 (size) must be bigger than or equal to 0" ) sgsstd_array_reserve( C, hdr, sz ); sgsstd_array_adjust( C, hdr, sz ); SGS_RETURN_THIS( C ); } static int sgsstd_arrayI_reserve( SGS_CTX ) { sgs_SizeVal sz; SGSARR_IHDR( reserve ); if( !sgs_LoadArgs( C, "l", &sz ) ) return 0; if( sz < 0 ) STDLIB_WARN( "argument 1 (size) must be bigger than or equal to 0" ) sgsstd_array_reserve( C, hdr, sz ); SGS_RETURN_THIS( C ); } static SGS_INLINE int sgsarrcomp_basic( const void* p1, const void* p2, void* userdata ) { SGS_CTX = (sgs_Context*) userdata; sgs_Variable v1 = *(const sgs_Variable*) p1; sgs_Variable v2 = *(const sgs_Variable*) p2; return sgs_Compare( C, &v1, &v2 ); } static SGS_INLINE int sgsarrcomp_basic_rev( const void* p1, const void* p2, void* userdata ) { return sgsarrcomp_basic( p2, p1, userdata ); } static int sgsstd_arrayI_sort( SGS_CTX ) { int rev = 0; SGSARR_IHDR( sort ); if( !sgs_LoadArgs( C, "|b", &rev ) ) return 0; /* WP: array limit */ quicksort( SGSARR_PTR( hdr ), (size_t) hdr->size, sizeof( sgs_Variable ), rev ? sgsarrcomp_basic_rev : sgsarrcomp_basic, C ); SGS_RETURN_THIS( C ); } typedef struct sgsarrcomp_cl2_s { SGS_CTX; sgs_Variable sortfunc; } sgsarrcomp_cl2; static SGS_INLINE int sgsarrcomp_custom( const void* p1, const void* p2, void* userdata ) { sgsarrcomp_cl2* u = (sgsarrcomp_cl2*) userdata; sgs_Variable v1 = *(const sgs_Variable*) p1; sgs_Variable v2 = *(const sgs_Variable*) p2; SGS_CTX = u->C; sgs_PushVariable( C, &v1 ); sgs_PushVariable( C, &v2 ); if( sgs_CallP( C, &u->sortfunc, 2, 1 ) != SGS_SUCCESS ) return 0; else { sgs_Real r = sgs_GetReal( C, -1 ); sgs_Pop( C, 1 ); return r == 0 ? 0 : ( r < 0 ? -1 : 1 ); } } static SGS_INLINE int sgsarrcomp_custom_rev( const void* p1, const void* p2, void* userdata ) { return sgsarrcomp_custom( p2, p1, userdata ); } static int sgsstd_arrayI_sort_custom( SGS_CTX ) { int rev = 0; sgsarrcomp_cl2 u; SGSARR_IHDR( sort_custom ); u.C = C; u.sortfunc.type = SVT_NULL; if( !sgs_LoadArgs( C, "?p<v|b", &u.sortfunc, &rev ) ) return 0; /* WP: array limit */ quicksort( SGSARR_PTR( hdr ), (size_t) hdr->size, sizeof( sgs_Variable ), rev ? sgsarrcomp_custom_rev : sgsarrcomp_custom, &u ); SGS_RETURN_THIS( C ); } typedef struct sgsarr_smi_s { sgs_Real value; sgs_SizeVal pos; } sgsarr_smi; static SGS_INLINE int sgsarrcomp_smi( const void* p1, const void* p2, void* userdata ) { const sgsarr_smi *v1 = (const sgsarr_smi*) p1; const sgsarr_smi *v2 = (const sgsarr_smi*) p2; if( v1->value < v2->value ) return -1; return v1->value > v2->value ? 1 : 0; } static SGS_INLINE int sgsarrcomp_smi_rev( const void* p1, const void* p2, void* userdata ) { return sgsarrcomp_smi( p2, p1, userdata ); } static int sgsstd_arrayI_sort_mapped( SGS_CTX ) { sgs_SizeVal i, asize = 0; int rev = 0; SGSARR_IHDR( sort_mapped ); if( !sgs_LoadArgs( C, "a|b", &asize, &rev ) ) return 0; if( asize != hdr->size ) STDLIB_WARN( "array sizes must match" ) { /* WP: array limit */ sgsarr_smi* smis = sgs_Alloc_n( sgsarr_smi, (size_t) asize ); for( i = 0; i < asize; ++i ) { if( sgs_PushNumIndex( C, 0, i ) ) { sgs_Dealloc( smis ); STDLIB_WARN( "error in mapping array" ) } smis[ i ].value = sgs_GetReal( C, -1 ); smis[ i ].pos = i; sgs_Pop( C, 1 ); } quicksort( smis, (size_t) asize, sizeof( sgsarr_smi ), rev ? sgsarrcomp_smi_rev : sgsarrcomp_smi, NULL ); { sgs_Variable *p1, *p2; p1 = SGSARR_PTR( hdr ); p2 = sgs_Alloc_n( sgs_Variable, (size_t) hdr->mem ); memcpy( p2, p1, SGSARR_ALLOCSIZE( hdr->mem ) ); for( i = 0; i < asize; ++i ) p1[ i ] = p2[ smis[ i ].pos ]; sgs_Dealloc( p2 ); } sgs_Dealloc( smis ); SGS_RETURN_THIS( C ); } } static int sgsstd_arrayI_find( SGS_CTX ) { sgs_Variable comp; int strict = FALSE; sgs_SizeVal off = 0; SGSARR_IHDR( find ); if( !sgs_LoadArgs( C, "v|bl", &comp, &strict, &off ) ) return 0; while( off < hdr->size ) { sgs_Variable* p = SGSARR_PTR( hdr ) + off; if( ( !strict || sgs_EqualTypes( p, &comp ) ) && sgs_Compare( C, p, &comp ) == 0 ) { sgs_PushInt( C, off ); return 1; } off++; } return 0; } static int sgsstd_arrayI_remove( SGS_CTX ) { sgs_Variable comp; int strict = FALSE, all = FALSE, rmvd = 0; sgs_SizeVal off = 0; SGSARR_IHDR( remove ); if( !sgs_LoadArgs( C, "v|bbl", &comp, &strict, &all, &off ) ) return 0; while( off < hdr->size ) { sgs_Variable* p = SGSARR_PTR( hdr ) + off; if( ( !strict || sgs_EqualTypes( p, &comp ) ) && sgs_Compare( C, p, &comp ) == 0 ) { sgsstd_array_erase( C, hdr, off, off ); rmvd++; if( !all ) break; } else off++; } sgs_PushInt( C, rmvd ); return 1; } static int _in_array( SGS_CTX, void* data, sgs_Variable* var, int strconv ) { sgs_SizeVal off = 0; SGSARR_HDR; if( !strconv ) { while( off < hdr->size ) { sgs_Variable* cur = SGSARR_PTR( hdr ) + off; if( sgs_EqualTypes( var, cur ) && sgs_Compare( C, var, cur ) == 0 ) return TRUE; off++; } return FALSE; } else { int found = 0; sgs_Variable A, B; A = *var; sgs_Acquire( C, &A ); sgs_ToStringP( C, &A ); while( off < hdr->size ) { B = SGSARR_PTR( hdr )[ off ]; sgs_Acquire( C, &B ); sgs_ToStringP( C, &B ); found = sgs_EqualTypes( &A, &B ) && sgs_Compare( C, &A, &B ) == 0; sgs_Release( C, &B ); if( found ) break; off++; } sgs_Release( C, &A ); return found; } } static int sgsstd_arrayI_unique( SGS_CTX ) { int strconv = FALSE; sgs_SizeVal off = 0, asz = 0; void* nadata; SGSARR_IHDR( unique ); if( !sgs_LoadArgs( C, "|b", &strconv ) ) return 0; sgs_PushArray( C, 0 ); nadata = sgs_GetObjectData( C, -1 ); while( off < hdr->size ) { sgs_Variable* var = SGSARR_PTR( hdr ) + off; if( !_in_array( C, nadata, var, strconv ) ) { sgsstd_array_insert_p( C, (sgsstd_array_header_t*) nadata, asz, var ); asz++; } off++; } return 1; } static int sgsstd_arrayI_random( SGS_CTX ) { sgs_SizeVal num, asz = 0; sgsstd_array_header_t* nadata; SGSARR_IHDR( random ); if( !sgs_LoadArgs( C, "l", &num ) ) return 0; if( num < 0 ) STDLIB_WARN( "argument 1 (count) cannot be negative" ) sgs_PushArray( C, 0 ); nadata = (sgsstd_array_header_t*) sgs_GetObjectData( C, -1 ); sgsstd_array_reserve( C, nadata, num ); while( num-- ) { sgsstd_array_insert_p( C, nadata, asz, SGSARR_PTR( hdr ) + ( rand() % hdr->size ) ); asz++; } return 1; } static int sgsstd_arrayI_shuffle( SGS_CTX ) { sgs_Variable tmp; sgs_SizeVal i, j; SGSARR_IHDR( shuffle ); if( !sgs_LoadArgs( C, "." ) ) return 0; for( i = hdr->size - 1; i >= 1; i-- ) { j = rand() % ( i + 1 ); tmp = SGSARR_PTR( hdr )[ i ]; SGSARR_PTR( hdr )[ i ] = SGSARR_PTR( hdr )[ j ]; SGSARR_PTR( hdr )[ j ] = tmp; } SGS_RETURN_THIS( C ); } static int sgsstd_array_getprop( SGS_CTX, void* data, sgs_Variable* key ) { char* name; SGSARR_HDR; if( sgs_ParseStringP( C, key, &name, NULL ) ) { sgs_CFunc func; if( 0 == strcmp( name, "size" ) ) { sgs_PushInt( C, hdr->size ); return SGS_SUCCESS; } else if( 0 == strcmp( name, "capacity" ) ) { sgs_PushInt( C, hdr->mem ); return SGS_SUCCESS; } else if( 0 == strcmp( name, "first" ) ) { if( hdr->size ) sgs_PushVariable( C, SGSARR_PTR( hdr ) ); else { sgs_PushNull( C ); sgs_Msg( C, SGS_WARNING, "array is empty, cannot get first item" ); } return SGS_SUCCESS; } else if( 0 == strcmp( name, "last" ) ) { if( hdr->size ) sgs_PushVariable( C, SGSARR_PTR( hdr ) + hdr->size - 1 ); else { sgs_PushNull( C ); sgs_Msg( C, SGS_WARNING, "array is empty, cannot get last item" ); } return SGS_SUCCESS; } else if( 0 == strcmp( name, "push" ) ) func = sgsstd_arrayI_push; else if( 0 == strcmp( name, "pop" ) ) func = sgsstd_arrayI_pop; else if( 0 == strcmp( name, "shift" ) ) func = sgsstd_arrayI_shift; else if( 0 == strcmp( name, "unshift" ) ) func = sgsstd_arrayI_unshift; else if( 0 == strcmp( name, "insert" ) ) func = sgsstd_arrayI_insert; else if( 0 == strcmp( name, "erase" ) ) func = sgsstd_arrayI_erase; else if( 0 == strcmp( name, "part" ) ) func = sgsstd_arrayI_part; else if( 0 == strcmp( name, "clear" ) ) func = sgsstd_arrayI_clear; else if( 0 == strcmp( name, "reverse" ) ) func = sgsstd_arrayI_reverse; else if( 0 == strcmp( name, "resize" ) ) func = sgsstd_arrayI_resize; else if( 0 == strcmp( name, "reserve" ) ) func = sgsstd_arrayI_reserve; else if( 0 == strcmp( name, "sort" ) ) func = sgsstd_arrayI_sort; else if( 0 == strcmp( name, "sort_custom" ) ) func = sgsstd_arrayI_sort_custom; else if( 0 == strcmp( name, "sort_mapped" ) ) func = sgsstd_arrayI_sort_mapped; else if( 0 == strcmp( name, "find" ) ) func = sgsstd_arrayI_find; else if( 0 == strcmp( name, "remove" ) ) func = sgsstd_arrayI_remove; else if( 0 == strcmp( name, "unique" ) ) func = sgsstd_arrayI_unique; else if( 0 == strcmp( name, "random" ) ) func = sgsstd_arrayI_random; else if( 0 == strcmp( name, "shuffle" ) ) func = sgsstd_arrayI_shuffle; else return SGS_ENOTFND; sgs_PushCFunction( C, func ); return SGS_SUCCESS; } return SGS_ENOTFND; } int sgsstd_array_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int prop ) { if( prop ) return sgsstd_array_getprop( C, data->data, key ); else { SGSARR_HDR_OI; sgs_Variable* ptr = SGSARR_PTR( hdr ); sgs_Int i = sgs_GetIntP( C, key ); if( i < 0 || i >= hdr->size ) { sgs_Msg( C, SGS_WARNING, "array index out of bounds" ); return SGS_EBOUNDS; } sgs_PushVariable( C, ptr + i ); return SGS_SUCCESS; } } static int sgsstd_array_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* val, int prop ) { if( prop ) return SGS_ENOTSUP; else { SGSARR_HDR_OI; sgs_Variable* ptr = SGSARR_PTR( hdr ); sgs_Int i = sgs_GetIntP( C, key ); if( i < 0 || i >= hdr->size ) { sgs_Msg( C, SGS_WARNING, "array index out of bounds" ); return SGS_EBOUNDS; } sgs_Assign( C, ptr + i, val ); return SGS_SUCCESS; } } static int sgsstd_array_dump( SGS_CTX, sgs_VarObj* data, int depth ) { char bfr[ 32 ]; int i, ssz = sgs_StackSize( C ); SGSARR_HDR_OI; sprintf( bfr, "array (%"PRId32")\n[", hdr->size ); sgs_PushString( C, bfr ); if( depth ) { if( hdr->size ) { for( i = 0; i < hdr->size; ++i ) { sgs_PushString( C, "\n" ); sgs_PushVariable( C, SGSARR_PTR( hdr ) + i ); if( sgs_DumpVar( C, depth ) ) return SGS_EINPROC; } if( sgs_StringConcat( C, hdr->size * 2 ) || sgs_PadString( C ) ) return SGS_EINPROC; } } else { sgs_PushString( C, "\n..." ); if( sgs_PadString( C ) ) return SGS_EINPROC; } sgs_PushString( C, "\n]" ); return sgs_StringConcat( C, sgs_StackSize( C ) - ssz ); } static int sgsstd_array_gcmark( SGS_CTX, sgs_VarObj* data ) { SGSARR_HDR_OI; return sgs_GCMarkArray( C, SGSARR_PTR( hdr ), hdr->size ); } /* iterator */ static int sgsstd_array_iter_destruct( SGS_CTX, sgs_VarObj* data ) { sgs_Release( C, &((sgsstd_array_iter_t*) data->data)->ref ); return SGS_SUCCESS; } static int sgsstd_array_iter_getnext( SGS_CTX, sgs_VarObj* data, int mask ) { sgsstd_array_iter_t* iter = (sgsstd_array_iter_t*) data->data; sgsstd_array_header_t* hdr = (sgsstd_array_header_t*) iter->ref.data.O->data; if( iter->size != hdr->size ) return SGS_EINPROC; if( !mask ) { iter->off++; return iter->off < iter->size; } else { if( mask & SGS_GETNEXT_KEY ) sgs_PushInt( C, iter->off ); if( mask & SGS_GETNEXT_VALUE ) sgs_PushVariable( C, SGSARR_PTR( hdr ) + iter->off ); return SGS_SUCCESS; } } static int sgsstd_array_iter_gcmark( SGS_CTX, sgs_VarObj* data ) { sgsstd_array_iter_t* iter = (sgsstd_array_iter_t*) data->data; sgs_GCMark( C, &iter->ref ); return SGS_SUCCESS; } sgs_ObjInterface sgsstd_array_iter_iface[1] = {{ "array_iterator", sgsstd_array_iter_destruct, sgsstd_array_iter_gcmark, NULL, NULL, NULL, NULL, NULL, sgsstd_array_iter_getnext, NULL, NULL }}; static int sgsstd_array_convert( SGS_CTX, sgs_VarObj* data, int type ) { SGSARR_HDR_OI; if( type == SGS_CONVOP_TOITER ) { sgsstd_array_iter_t* iter = (sgsstd_array_iter_t*) sgs_PushObjectIPA( C, sizeof(*iter), sgsstd_array_iter_iface ); sgs_InitObjectPtr( &iter->ref, data ); /* acquires ref */ iter->size = hdr->size; iter->off = -1; return SGS_SUCCESS; } else if( type == SVT_BOOL ) { sgs_PushBool( C, !!hdr->size ); return SGS_SUCCESS; } else if( type == SVT_STRING ) { sgs_Variable* var = SGSARR_PTR( data->data ); sgs_Variable* vend = var + hdr->size; sgs_PushString( C, "[" ); while( var < vend ) { sgs_PushVariable( C, var ); sgs_ToStringFast( C, -1 ); var++; if( var < vend ) sgs_PushString( C, "," ); } sgs_PushString( C, "]" ); return sgs_StringConcat( C, hdr->size * 2 + 1 + !hdr->size ); } else if( type == SGS_CONVOP_CLONE ) { sgsstd_array_header_t* hdr2 = (sgsstd_array_header_t*) sgs_PushObjectIPA( C, sizeof( sgsstd_array_header_t ), sgsstd_array_iface ); memcpy( hdr2, hdr, sizeof( sgsstd_array_header_t ) ); hdr2->data = sgs_Alloc_n( sgs_Variable, (size_t) hdr->mem ); memcpy( hdr2->data, hdr->data, SGSARR_ALLOCSIZE( hdr->mem ) ); { sgs_Variable* ptr = SGSARR_PTR( hdr ); sgs_Variable* pend = ptr + hdr->size; while( ptr < pend ) sgs_Acquire( C, ptr++ ); } return SGS_SUCCESS; } return SGS_ENOTSUP; } static int sgsstd_array_serialize( SGS_CTX, sgs_VarObj* data ) { int ret; sgs_Variable* pos, *posend; SGSARR_HDR_OI; pos = SGSARR_PTR( hdr ); posend = pos + hdr->size; while( pos < posend ) { sgs_PushVariable( C, pos++ ); ret = sgs_Serialize( C ); if( ret != SGS_SUCCESS ) return ret; } return sgs_SerializeObject( C, hdr->size, "array" ); } static int sgsstd_array_destruct( SGS_CTX, sgs_VarObj* data ) { SGSARR_HDR_OI; sgsstd_array_clear( C, hdr ); sgs_Dealloc( hdr->data ); return 0; } sgs_ObjInterface sgsstd_array_iface[1] = {{ "array", sgsstd_array_destruct, sgsstd_array_gcmark, sgsstd_array_getindex, sgsstd_array_setindex, sgsstd_array_convert, sgsstd_array_serialize, sgsstd_array_dump, NULL, NULL, NULL }}; static int sgsstd_array( SGS_CTX ) { int i = 0, objcnt = sgs_StackSize( C ); void* data = sgs_Malloc( C, SGSARR_ALLOCSIZE( objcnt ) ); sgs_Variable *p, *pend; sgsstd_array_header_t* hdr = (sgsstd_array_header_t*) sgs_PushObjectIPA( C, sizeof( sgsstd_array_header_t ), sgsstd_array_iface ); hdr->size = objcnt; hdr->mem = objcnt; p = hdr->data = (sgs_Variable*) data; pend = p + objcnt; while( p < pend ) sgs_GetStackItem( C, i++, p++ ); return 1; } /* VHT containers */ typedef struct _DictHdr { VHTable ht; } DictHdr; #define HTHDR DictHdr* dh = (DictHdr*) data->data; VHTable* ht = &dh->ht; static int sgsstd_vht_serialize( SGS_CTX, sgs_VarObj* data, const char* initfn ) { int ret; VHTVar *pair, *pend; HTHDR; pair = ht->vars; pend = ht->vars + vht_size( ht ); while( pair < pend ) { sgs_PushVariable( C, &pair->key ); ret = sgs_Serialize( C ); if( ret != SGS_SUCCESS ) return ret; sgs_PushVariable( C, &pair->val ); ret = sgs_Serialize( C ); if( ret != SGS_SUCCESS ) return ret; pair++; } return sgs_SerializeObject( C, vht_size( ht ) * 2, initfn ); } static int sgsstd_vht_dump( SGS_CTX, sgs_VarObj* data, int depth, const char* name ) { int ssz; char bfr[ 32 ]; VHTVar *pair, *pend; HTHDR; pair = ht->vars; pend = ht->vars + vht_size( ht ); ssz = sgs_StackSize( C ); sprintf( bfr, "%s (%"PRId32")\n{", name, vht_size( ht ) ); sgs_PushString( C, bfr ); if( depth ) { if( vht_size( ht ) ) { while( pair < pend ) { sgs_PushString( C, "\n" ); sgs_PushVariable( C, &pair->key ); if( pair->key.type == SVT_STRING ) sgs_ToPrintSafeString( C ); else { if( sgs_DumpVar( C, depth ) ) return SGS_EINPROC; } sgs_PushString( C, " = " ); sgs_PushVariable( C, &pair->val ); if( sgs_DumpVar( C, depth ) ) return SGS_EINPROC; pair++; } /* WP: stack limit */ if( sgs_StringConcat( C, (StkIdx) ( pend - ht->vars ) * 4 ) || sgs_PadString( C ) ) return SGS_EINPROC; } } else { sgs_PushString( C, "\n..." ); if( sgs_PadString( C ) ) return SGS_EINPROC; } sgs_PushString( C, "\n}" ); return sgs_StringConcat( C, sgs_StackSize( C ) - ssz ); } /* DICT */ static DictHdr* mkdict( SGS_CTX, sgs_Variable* out ) { sgs_ObjInterface* iface = SGSIFACE_DICT; if( !iface ) iface = sgsstd_dict_iface; DictHdr* dh = (DictHdr*) ( out ? sgs_InitObjectIPA( C, out, sizeof( DictHdr ), iface ) : sgs_PushObjectIPA( C, sizeof( DictHdr ), iface ) ); vht_init( &dh->ht, C, 4, 4 ); return dh; } static int sgsstd_dict_destruct( SGS_CTX, sgs_VarObj* data ) { HTHDR; vht_free( ht, C ); return SGS_SUCCESS; } static int sgsstd_dict_gcmark( SGS_CTX, sgs_VarObj* data ) { VHTVar *pair, *pend; HTHDR; pair = ht->vars; pend = ht->vars + vht_size( ht ); while( pair < pend ) { int ret = sgs_GCMark( C, &pair->key ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_GCMark( C, &pair->val ); if( ret != SGS_SUCCESS ) return ret; pair++; } return SGS_SUCCESS; } static int sgsstd_dict_dump( SGS_CTX, sgs_VarObj* data, int depth ) { return sgsstd_vht_dump( C, data, depth, "dict" ); } static int sgsstd_dict_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int prop ) { VHTVar* pair = NULL; HTHDR; if( prop && key->type == SVT_INT ) { int32_t off = (int32_t) key->data.I; if( off < 0 || off > vht_size( ht ) ) return SGS_EBOUNDS; sgs_PushVariable( C, &ht->vars[ off ].val ); return SGS_SUCCESS; } if( sgs_ParseStringP( C, key, NULL, NULL ) ) { pair = vht_get( ht, key ); if( !pair ) return SGS_ENOTFND; sgs_PushVariable( C, &pair->val ); return SGS_SUCCESS; } return SGS_EINVAL; } static int sgsstd_dict_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* val, int prop ) { char* str; HTHDR; if( sgs_ParseStringP( C, key, &str, NULL ) ) { vht_set( ht, C, key, val ); return SGS_SUCCESS; } return SGS_EINVAL; } /* iterator */ typedef struct sgsstd_dict_iter_s { sgs_Variable ref; int32_t size; int32_t off; } sgsstd_dict_iter_t; static int sgsstd_dict_iter_destruct( SGS_CTX, sgs_VarObj* data ) { sgs_Release( C, &((sgsstd_dict_iter_t*) data->data)->ref ); return SGS_SUCCESS; } static int sgsstd_dict_iter_getnext( SGS_CTX, sgs_VarObj* data, int flags ) { sgsstd_dict_iter_t* iter = (sgsstd_dict_iter_t*) data->data; VHTable* ht = (VHTable*) iter->ref.data.O->data; if( iter->size != vht_size( ht ) ) return SGS_EINVAL; if( !flags ) { iter->off++; return iter->off < iter->size; } else { if( flags & SGS_GETNEXT_KEY ) sgs_PushVariable( C, &ht->vars[ iter->off ].key ); if( flags & SGS_GETNEXT_VALUE ) sgs_PushVariable( C, &ht->vars[ iter->off ].val ); return SGS_SUCCESS; } } static int sgsstd_dict_iter_gcmark( SGS_CTX, sgs_VarObj* data ) { sgsstd_dict_iter_t* iter = (sgsstd_dict_iter_t*) data->data; sgs_GCMark( C, &iter->ref ); return SGS_SUCCESS; } sgs_ObjInterface sgsstd_dict_iter_iface[1] = {{ "dict_iterator", sgsstd_dict_iter_destruct, sgsstd_dict_iter_gcmark, NULL, NULL, NULL, NULL, NULL, sgsstd_dict_iter_getnext, NULL, NULL }}; static int sgsstd_dict_convert( SGS_CTX, sgs_VarObj* data, int type ) { HTHDR; if( type == SGS_CONVOP_TOITER ) { sgsstd_dict_iter_t* iter = (sgsstd_dict_iter_t*) sgs_PushObjectIPA( C, sizeof(*iter), sgsstd_dict_iter_iface ); sgs_InitObjectPtr( &iter->ref, data ); /* acquires ref */ iter->size = vht_size( ht ); iter->off = -1; return SGS_SUCCESS; } else if( type == SVT_BOOL ) { sgs_PushBool( C, vht_size( ht ) != 0 ); return SGS_SUCCESS; } else if( type == SVT_STRING ) { VHTVar *pair = ht->vars, *pend = ht->vars + vht_size( ht ); int cnt = 0; sgs_PushString( C, "{" ); while( pair < pend ) { if( cnt ) sgs_PushString( C, "," ); sgs_PushVariable( C, &pair->key ); sgs_PushString( C, "=" ); sgs_PushVariable( C, &pair->val ); sgs_ToStringFast( C, -1 ); cnt++; pair++; } sgs_PushString( C, "}" ); return sgs_StringConcat( C, cnt * 4 + 1 + !cnt ); } else if( type == SGS_CONVOP_CLONE ) { int i, htsize = vht_size( ht ); DictHdr* ndh = mkdict( C, NULL ); for( i = 0; i < htsize; ++i ) { vht_set( &ndh->ht, C, &ht->vars[ i ].key, &ht->vars[ i ].val ); } return SGS_SUCCESS; } return SGS_ENOTSUP; } static int sgsstd_dict_serialize( SGS_CTX, sgs_VarObj* data ) { return sgsstd_vht_serialize( C, data, "dict" ); } sgs_ObjInterface sgsstd_dict_iface[1] = {{ "dict", sgsstd_dict_destruct, sgsstd_dict_gcmark, sgsstd_dict_getindex, sgsstd_dict_setindex, sgsstd_dict_convert, sgsstd_dict_serialize, sgsstd_dict_dump, NULL, NULL, NULL }}; static int sgsstd_dict( SGS_CTX ) { DictHdr* dh; VHTable* ht; int i, objcnt = sgs_StackSize( C ); SGSFN( "dict" ); if( objcnt % 2 != 0 ) STDLIB_WARN( "function expects 0 or an even number of arguments" ) dh = mkdict( C, NULL ); ht = &dh->ht; for( i = 0; i < objcnt; i += 2 ) { sgs_Variable val; if( !sgs_ParseString( C, i, NULL, NULL ) ) return sgs_FuncArgError( C, i, SVT_STRING, 0 ); sgs_PeekStackItem( C, i + 1, &val ); vht_set( ht, C, (C->stack_off+i), &val ); } return 1; } /* MAP */ static DictHdr* mkmap( SGS_CTX, sgs_Variable* out ) { DictHdr* dh = (DictHdr*) ( out ? sgs_InitObjectIPA( C, out, sizeof( DictHdr ), SGSIFACE_MAP ) : sgs_PushObjectIPA( C, sizeof( DictHdr ), SGSIFACE_MAP ) ); vht_init( &dh->ht, C, 4, 4 ); return dh; } #define sgsstd_map_destruct sgsstd_dict_destruct #define sgsstd_map_gcmark sgsstd_dict_gcmark static int sgsstd_map_dump( SGS_CTX, sgs_VarObj* data, int depth ) { return sgsstd_vht_dump( C, data, depth, "map" ); } static int sgsstd_map_serialize( SGS_CTX, sgs_VarObj* data ) { return sgsstd_vht_serialize( C, data, "map" ); } static int sgsstd_map_convert( SGS_CTX, sgs_VarObj* data, int type ) { HTHDR; if( type == SGS_CONVOP_TOITER ) { sgsstd_dict_iter_t* iter = (sgsstd_dict_iter_t*) sgs_PushObjectIPA( C, sizeof(*iter), sgsstd_dict_iter_iface ); sgs_InitObjectPtr( &iter->ref, data ); /* acquires ref */ iter->size = vht_size( ht ); iter->off = -1; return SGS_SUCCESS; } else if( type == SVT_BOOL ) { sgs_PushBool( C, vht_size( ht ) != 0 ); return SGS_SUCCESS; } else if( type == SVT_STRING ) { VHTVar *pair = ht->vars, *pend = ht->vars + vht_size( ht ); int cnt = 0; sgs_PushString( C, "[map]{" ); while( pair < pend ) { if( cnt ) sgs_PushString( C, "," ); sgs_PushVariable( C, &pair->key ); sgs_ToStringFast( C, -1 ); sgs_PushString( C, "=" ); sgs_PushVariable( C, &pair->val ); sgs_ToStringFast( C, -1 ); cnt++; pair++; } sgs_PushString( C, "}" ); return sgs_StringConcat( C, cnt * 4 + 1 + !cnt ); } else if( type == SGS_CONVOP_CLONE ) { int i, htsize = vht_size( ht ); DictHdr* ndh = mkmap( C, NULL ); for( i = 0; i < htsize; ++i ) { vht_set( &ndh->ht, C, &ht->vars[ i ].key, &ht->vars[ i ].val ); } return SGS_SUCCESS; } return SGS_ENOTSUP; } static int sgsstd_map_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int prop ) { VHTVar* pair = NULL; HTHDR; pair = vht_get( ht, key ); if( !pair ) return SGS_ENOTFND; sgs_PushVariable( C, &pair->val ); return SGS_SUCCESS; } static int sgsstd_map_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* val, int prop ) { HTHDR; vht_set( ht, C, key, val ); return SGS_SUCCESS; } sgs_ObjInterface sgsstd_map_iface[1] = {{ "map", sgsstd_map_destruct, sgsstd_map_gcmark, sgsstd_map_getindex, sgsstd_map_setindex, sgsstd_map_convert, sgsstd_map_serialize, sgsstd_map_dump, NULL, NULL, NULL }}; static int sgsstd_map( SGS_CTX ) { DictHdr* dh; VHTable* ht; int i, objcnt = sgs_StackSize( C ); SGSFN( "map" ); if( objcnt % 2 != 0 ) STDLIB_WARN( "function expects 0 or an even number of arguments" ) dh = mkmap( C, NULL ); ht = &dh->ht; for( i = 0; i < objcnt; i += 2 ) { vht_set( ht, C, C->stack_off+i, C->stack_off+i+1 ); } return 1; } /* CLASS */ typedef struct sgsstd_class_header_s { sgs_Variable data; sgs_Variable inh; } sgsstd_class_header_t; #define SGSCLASS_HDR sgsstd_class_header_t* hdr = (sgsstd_class_header_t*) data->data; static int sgsstd_class_getmethod( SGS_CTX, sgs_VarObj* data, const char* method, sgs_Variable* out ) { int ret; sgs_Variable key; SGSCLASS_HDR; sgs_InitString( C, &key, method ); ret = sgs_GetIndexPPP( C, &hdr->inh, &key, out, TRUE ); sgs_Release( C, &key ); return ret == SGS_SUCCESS; } static int sgsstd_class_destruct( SGS_CTX, sgs_VarObj* data ) { SGSCLASS_HDR; sgs_Variable method; if( sgsstd_class_getmethod( C, data, "__destruct", &method ) ) { data->refcount++; sgs_PushObjectPtr( C, data ); sgs_ThisCallP( C, &method, 0, 0 ); sgs_Release( C, &method ); data->refcount--; } sgs_Release( C, &hdr->data ); sgs_Release( C, &hdr->inh ); return SGS_SUCCESS; } static int sgsstd_class_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int isprop ) { int ret; SGSCLASS_HDR; if( isprop && key->type == SVT_STRING && !strcmp( sgs_ToStringP( C, key ), "_super" ) ) { sgs_PushVariable( C, &hdr->inh ); return SGS_SUCCESS; } if( isprop && key->type == SVT_STRING && !strcmp( sgs_ToStringP( C, key ), "_data" ) ) { sgs_PushVariable( C, &hdr->data ); return SGS_SUCCESS; } if( SGS_SUCCEEDED( sgs_PushIndexPP( C, &hdr->data, key, isprop ) ) ) return SGS_SUCCESS; ret = sgs_PushIndexPP( C, &hdr->inh, key, isprop ); if( SGS_SUCCEEDED( ret ) ) return SGS_SUCCESS; return ret; } static int sgsstd_class_setindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, sgs_Variable* val, int isprop ) { SGSCLASS_HDR; if( isprop && key->type == SVT_STRING && !strcmp( sgs_ToStringP( C, key ), "_super" ) ) { if( val->type == SVT_OBJECT && val->data.O == data ) return SGS_EINVAL; sgs_Assign( C, &hdr->inh, val ); return SGS_SUCCESS; } if( isprop && key->type == SVT_STRING && !strcmp( sgs_ToStringP( C, key ), "_data" ) ) { if( val->type == SVT_OBJECT && val->data.O == data ) return SGS_EINVAL; sgs_Assign( C, &hdr->data, val ); return SGS_SUCCESS; } return sgs_SetIndexPPP( C, &hdr->data, key, val, isprop ); } static int sgsstd_class_dump( SGS_CTX, sgs_VarObj* data, int depth ) { SGSCLASS_HDR; sgs_PushString( C, "class\n{" ); sgs_PushString( C, "\ndata: " ); sgs_PushVariable( C, &hdr->data ); if( sgs_DumpVar( C, depth ) ) { sgs_Pop( C, 1 ); sgs_PushString( C, "<error>" ); } sgs_PushString( C, "\nsuper: " ); sgs_PushVariable( C, &hdr->inh ); if( sgs_DumpVar( C, depth ) ) { sgs_Pop( C, 1 ); sgs_PushString( C, "<error>" ); } if( sgs_StringConcat( C, 4 ) || sgs_PadString( C ) ) return SGS_EINPROC; sgs_PushString( C, "\n}" ); return sgs_StringConcat( C, 3 ); } static int sgsstd_class( SGS_CTX ); SGS_DECLARE sgs_ObjInterface sgsstd_class_iface[1]; static int sgsstd_class_convert( SGS_CTX, sgs_VarObj* data, int type ) { int otype = type; sgs_Variable method; const char* op = NULL; switch( type ) { case SVT_BOOL: op = "__tobool"; break; case SVT_INT: op = "__toint"; break; case SVT_REAL: op = "__toreal"; break; case SVT_STRING: op = "__tostr"; break; case SVT_PTR: op = "__toptr"; break; case SGS_CONVOP_CLONE: op = "__clone"; break; case SGS_CONVOP_TYPEOF: op = "__typeof"; break; } if( op == NULL ) return SGS_ENOTFND; if( sgsstd_class_getmethod( C, data, op, &method ) ) { int ret; sgs_PushObjectPtr( C, data ); ret = sgs_ThisCallP( C, &method, 0, 1 ); sgs_Release( C, &method ); return ret; } if( otype == SGS_CONVOP_CLONE ) { sgsstd_class_header_t* hdr2; SGSCLASS_HDR; hdr2 = (sgsstd_class_header_t*) sgs_PushObjectIPA( C, sizeof( sgsstd_class_header_t ), sgsstd_class_iface ); sgs_PushVariable( C, &hdr->data ); sgs_CloneItem( C, -1 ); sgs_PeekStackItem( C, -1, &hdr2->data ); hdr2->inh = hdr->inh; sgs_Acquire( C, &hdr2->data ); sgs_Acquire( C, &hdr2->inh ); sgs_SetStackSize( C, 1 ); return SGS_SUCCESS; } return SGS_ENOTSUP; } static int sgsstd_class_serialize( SGS_CTX, sgs_VarObj* data ) { int ret; SGSCLASS_HDR; sgs_PushVariable( C, &hdr->data ); ret = sgs_Serialize( C ); if( ret != SGS_SUCCESS ) return ret; sgs_PushVariable( C, &hdr->inh ); ret = sgs_Serialize( C ); if( ret != SGS_SUCCESS ) return ret; return sgs_SerializeObject( C, 2, "class" ); } static int sgsstd_class_gcmark( SGS_CTX, sgs_VarObj* data ) { int ret; SGSCLASS_HDR; ret = sgs_GCMark( C, &hdr->data ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_GCMark( C, &hdr->inh ); if( ret != SGS_SUCCESS ) return ret; return SGS_SUCCESS; } static int sgsstd_class_expr( SGS_CTX, sgs_VarObj* data, sgs_Variable* A, sgs_Variable* B, int type ) { sgs_Variable method; static const char* ops[] = { "__add", "__sub", "__mul", "__div", "__mod", "__compare", "__negate" }; if( sgsstd_class_getmethod( C, data, ops[type], &method ) ) { int ret; if( type == SGS_EOP_NEGATE ) { sgs_PushObjectPtr( C, data ); ret = sgs_FCallP( C, &method, 0, 1, 1 ); } else { sgs_PushVariable( C, A ); sgs_PushVariable( C, B ); ret = sgs_FCallP( C, &method, 2, 1, 0 ); } sgs_Release( C, &method ); return ret; } return SGS_ENOTFND; } static int sgsstd_class_call( SGS_CTX, sgs_VarObj* data ) { sgs_Variable method; if( sgsstd_class_getmethod( C, data, "__call", &method ) ) { int ret, i; sgs_PushObjectPtr( C, data ); for( i = 0; i < C->sf_last->argcount; ++i ) sgs_PushItem( C, i ); ret = sgsVM_VarCall( C, &method, C->sf_last->argcount, 0, C->sf_last->expected, TRUE ); sgs_Release( C, &method ); return ret; } return SGS_ENOTFND; } static sgs_ObjInterface sgsstd_class_iface[1] = {{ "class", sgsstd_class_destruct, sgsstd_class_gcmark, sgsstd_class_getindex, sgsstd_class_setindex, sgsstd_class_convert, sgsstd_class_serialize, sgsstd_class_dump, NULL, sgsstd_class_call, sgsstd_class_expr, }}; static int sgsstd_class( SGS_CTX ) { sgsstd_class_header_t* hdr; SGSFN( "class" ); if( !sgs_LoadArgs( C, "?v?v." ) ) return 0; hdr = (sgsstd_class_header_t*) sgs_PushObjectIPA( C, sizeof( sgsstd_class_header_t ), sgsstd_class_iface ); sgs_GetStackItem( C, 0, &hdr->data ); sgs_GetStackItem( C, 1, &hdr->inh ); return 1; } /* closure memory layout: - sgs_Variable: function - int32: closure count - sgs_Closure* x ^^: closures */ static int sgsstd_closure_destruct( SGS_CTX, sgs_VarObj* data ) { uint8_t* cl = (uint8_t*) data->data; int32_t i, cc = *(int32_t*) (void*) ASSUME_ALIGNED(cl+sizeof(sgs_Variable),sizeof(void*)); sgs_Closure** cls = (sgs_Closure**) (void*) ASSUME_ALIGNED(cl+sizeof(sgs_Variable)+sizeof(int32_t),sizeof(void*)); sgs_Release( C, (sgs_Variable*) (void*) ASSUME_ALIGNED( cl, sizeof(void*) ) ); for( i = 0; i < cc; ++i ) { if( --cls[ i ]->refcount < 1 ) { sgs_Release( C, &cls[ i ]->var ); sgs_Dealloc( cls[i] ); } } return SGS_SUCCESS; } static int sgsstd_closure_getindex( SGS_CTX, sgs_VarObj* data, sgs_Variable* key, int isprop ) { char* str; if( sgs_ParseStringP( C, key, &str, NULL ) ) { if( !strcmp( str, "call" ) ) { sgs_PushCFunction( C, sgs_specfn_call ); return SGS_SUCCESS; } if( !strcmp( str, "apply" ) ) { sgs_PushCFunction( C, sgs_specfn_apply ); return SGS_SUCCESS; } } return SGS_ENOTFND; } static int sgsstd_closure_call( SGS_CTX, sgs_VarObj* data ) { int ismethod = sgs_Method( C ), expected = C->sf_last->expected; uint8_t* cl = (uint8_t*) data->data; int32_t cc = *(int32_t*) (void*) ASSUME_ALIGNED(cl+sizeof(sgs_Variable),sizeof(void*)); sgs_Closure** cls = (sgs_Closure**) (void*) ASSUME_ALIGNED(cl+sizeof(sgs_Variable)+sizeof(int32_t),sizeof(void*)); sgsVM_PushClosures( C, cls, cc ); return sgsVM_VarCall( C, (sgs_Variable*) (void*) ASSUME_ALIGNED( cl, sizeof(void*) ), C->sf_last->argcount, cc, C->sf_last->expected, ismethod ) * expected; } static int sgsstd_closure_gcmark( SGS_CTX, sgs_VarObj* data ) { uint8_t* cl = (uint8_t*) data->data; int32_t i, cc = *(int32_t*) (void*) ASSUME_ALIGNED(cl+sizeof(sgs_Variable),sizeof(void*)); sgs_Closure** cls = (sgs_Closure**) (void*) ASSUME_ALIGNED(cl+sizeof(sgs_Variable)+sizeof(int32_t),sizeof(void*)); sgs_GCMark( C, (sgs_Variable*) (void*) ASSUME_ALIGNED( cl, sizeof(void*) ) ); for( i = 0; i < cc; ++i ) { sgs_GCMark( C, &cls[ i ]->var ); } return SGS_SUCCESS; } static int sgsstd_closure_dump( SGS_CTX, sgs_VarObj* data, int depth ) { uint8_t* cl = (uint8_t*) data->data; int32_t i, ssz, cc = *(int32_t*) (void*) ASSUME_ALIGNED(cl+sizeof(sgs_Variable),sizeof(void*)); sgs_Closure** cls = (sgs_Closure**) (void*) ASSUME_ALIGNED(cl+sizeof(sgs_Variable)+sizeof(int32_t),sizeof(void*)); sgs_PushString( C, "closure\n{" ); ssz = sgs_StackSize( C ); sgs_PushString( C, "\nfunc: " ); sgs_PushVariable( C, (sgs_Variable*) (void*) ASSUME_ALIGNED( cl, sizeof(void*) ) ); /* function */ if( sgs_DumpVar( C, depth ) ) { sgs_Pop( C, 1 ); sgs_PushString( C, "<error>" ); } for( i = 0; i < cc; ++i ) { char intro[ 64 ]; sprintf( intro, "\n#%"PRId32" (rc=%"PRId32"): ", i, cls[ i ]->refcount ); sgs_PushString( C, intro ); sgs_PushVariable( C, &cls[ i ]->var ); if( sgs_DumpVar( C, depth ) ) { sgs_Pop( C, 1 ); sgs_PushString( C, "<error>" ); } } if( sgs_StringConcat( C, sgs_StackSize( C ) - ssz ) || sgs_PadString( C ) ) return SGS_EINPROC; sgs_PushString( C, "\n}" ); return sgs_StringConcat( C, 3 ); } static sgs_ObjInterface sgsstd_closure_iface[1] = {{ "closure", sgsstd_closure_destruct, sgsstd_closure_gcmark, sgsstd_closure_getindex, NULL, NULL, NULL, sgsstd_closure_dump, NULL, sgsstd_closure_call, NULL }}; int sgsSTD_MakeClosure( SGS_CTX, sgs_Variable* func, uint32_t clc ) { /* WP: range not affected by conversion */ uint32_t i, clsz = (uint32_t) sizeof(sgs_Closure*) * clc; uint32_t memsz = clsz + (uint32_t) ( sizeof(sgs_Variable) + sizeof(int32_t) ); uint8_t* cl = (uint8_t*) sgs_PushObjectIPA( C, memsz, sgsstd_closure_iface ); memcpy( cl, func, sizeof(sgs_Variable) ); sgs_Acquire( C, func ); memcpy( cl + sizeof(sgs_Variable), &clc, sizeof(clc) ); memcpy( cl + sizeof(sgs_Variable) + sizeof(clc), C->clstk_top - clc, clsz ); for( i = 0; i < clc; ++i ) (*(C->clstk_top - clc + i))->refcount++; return SGS_SUCCESS; } /* UTILITIES */ static int sgsstd_array_filter( SGS_CTX ) { SGSBOOL cset = 0, use; sgs_SizeVal asz, off = 0, nasz = 0; void *data; sgsstd_array_header_t* nadata; SGSFN( "array_filter" ); if( !sgs_LoadArgs( C, "a|p", &asz, &cset ) ) return 0; sgs_PushArray( C, 0 ); data = sgs_GetObjectData( C, 0 ); nadata = (sgsstd_array_header_t*) sgs_GetObjectData( C, -1 ); { SGSARR_HDR; while( off < asz ) { sgs_PushVariable( C, SGSARR_PTR( hdr ) + off ); if( cset ) { sgs_PushInt( C, off ); sgs_PushItem( C, 1 ); if( sgs_Call( C, 2, 1 ) ) STDLIB_WARN( "failed to call the filter function" ) } use = sgs_GetBool( C, -1 ); sgs_Pop( C, 1 ); sgs_PushVariable( C, SGSARR_PTR( hdr ) + off ); if( use ) { sgsstd_array_insert( C, nadata, nasz, sgs_StackSize( C ) - 1 ); nasz++; } sgs_Pop( C, 1 ); off++; } } return 1; } static int sgsstd_array_process( SGS_CTX ) { sgs_SizeVal asz, off = 0; void *data; SGSFN( "array_process" ); if( !sgs_LoadArgs( C, "a?p", &asz ) ) return 0; data = sgs_GetObjectData( C, 0 ); { SGSARR_HDR; while( off < asz ) { sgs_PushVariable( C, SGSARR_PTR( hdr ) + off ); sgs_PushInt( C, off ); sgs_PushItem( C, 1 ); if( sgs_Call( C, 2, 1 ) ) STDLIB_WARN( "failed to call the processing function" ) sgs_StoreNumIndex( C, 0, off ); off++; } } sgs_SetStackSize( C, 1 ); return 1; } static int sgsstd_dict_filter( SGS_CTX ) { SGSBOOL cset = 0, use; SGSFN( "dict_filter" ); if( !sgs_LoadArgs( C, "?t|p", &cset ) ) return 0; sgs_PushDict( C, 0 ); sgs_PushIterator( C, 0 ); while( sgs_IterAdvance( C, -1 ) > 0 ) { if( sgs_IterPushData( C, -1, 1, 1 ) ) STDLIB_WARN( "failed to read iterator (was dict changed in callback?)" ) if( cset ) { sgs_PushItem( C, -1 ); sgs_PushItem( C, -3 ); sgs_PushItem( C, 1 ); if( sgs_Call( C, 2, 1 ) ) STDLIB_WARN( "failed to call the filter function" ) } use = sgs_GetBool( C, -1 ); if( cset ) sgs_Pop( C, 1 ); if( use ) { /* src-dict, ... dest-dict, iterator, key, value */ sgs_StoreIndexII( C, -4, -2, FALSE ); } sgs_Pop( C, use ? 1 : 2 ); } sgs_Pop( C, 1 ); return 1; } static int sgsstd_dict_process( SGS_CTX ) { SGSFN( "dict_process" ); if( !sgs_LoadArgs( C, "?t?p" ) ) return 0; sgs_PushIterator( C, 0 ); while( sgs_IterAdvance( C, -1 ) > 0 ) { if( sgs_IterPushData( C, -1, 1, 1 ) ) STDLIB_WARN( "failed to read iterator (was dict changed in callback?)" ) sgs_PushItem( C, -2 ); sgs_PushItem( C, 1 ); if( sgs_Call( C, 2, 1 ) ) STDLIB_WARN( "failed to call the processing function" ) /* src-dict, callable, ... iterator, key, proc.val. */ sgs_StoreIndexII( C, 0, -2, FALSE ); sgs_Pop( C, 1 ); } sgs_SetStackSize( C, 1 ); return 1; } static int sgsstd_dict_size( SGS_CTX ) { sgs_SizeVal size; SGSFN( "dict_size" ); if( !sgs_LoadArgs( C, "t.", &size ) ) return 0; sgs_PushInt( C, size ); return 1; } static int sgsstd_map_size( SGS_CTX ) { sgs_SizeVal size; SGSFN( "map_size" ); if( !sgs_LoadArgs( C, "h.", &size ) ) return 0; sgs_PushInt( C, size ); return 1; } static int sgsstd_isset( SGS_CTX ) { int ret; int32_t oldapilev; SGSFN( "isset" ); if( !sgs_LoadArgs( C, "?v?v." ) ) return 0; oldapilev = sgs_Cntl( C, SGS_CNTL_APILEV, SGS_ERROR ); ret = sgs_PushIndexII( C, 0, 1, FALSE ) == SGS_SUCCESS; sgs_Cntl( C, SGS_CNTL_APILEV, oldapilev ); sgs_PushBool( C, ret ); return 1; } static int sgsstd_unset( SGS_CTX ) { DictHdr* dh; SGSFN( "unset" ); if( !sgs_IsObject( C, 0, sgsstd_dict_iface ) && !sgs_IsObject( C, 0, sgsstd_map_iface ) ) return sgs_ArgErrorExt( C, 0, 0, "dict / map", "" ); dh = (DictHdr*) sgs_GetObjectData( C, 0 ); if( sgs_IsObject( C, 0, sgsstd_dict_iface ) ) { if( !sgs_LoadArgs( C, ">?m." ) ) return 0; } else { if( !sgs_LoadArgs( C, ">?v." ) ) return 0; } vht_unset( &dh->ht, C, (C->stack_off+1) ); return 0; } static int sgsstd_clone( SGS_CTX ) { int ret; SGSFN( "clone" ); if( !sgs_LoadArgs( C, "?v." ) ) return 0; ret = sgs_CloneItem( C, 0 ); if( ret != SGS_SUCCESS ) STDLIB_WARN( "failed to clone variable" ) return 1; } static int _foreach_lister( SGS_CTX, int vnk ) { if( !sgs_LoadArgs( C, ">." ) ) return 0; if( sgs_PushIterator( C, 0 ) != SGS_SUCCESS ) return sgs_ArgErrorExt( C, 0, 0, "iterable", "" ); sgs_PushArray( C, 0 ); /* arg1, arg1 iter, output */ while( sgs_IterAdvance( C, 1 ) > 0 ) { sgs_IterPushData( C, 1, !vnk, vnk ); sgs_ObjectAction( C, 2, SGS_ACT_ARRAY_PUSH, 1 ); } return 1; } static int sgsstd_get_keys( SGS_CTX ) { SGSFN( "get_keys" ); return _foreach_lister( C, 0 ); } static int sgsstd_get_values( SGS_CTX ) { SGSFN( "get_values" ); return _foreach_lister( C, 1 ); } static int sgsstd_get_concat( SGS_CTX ) { int i, ssz = sgs_StackSize( C ); SGSFN( "get_concat" ); if( ssz < 2 ) { return sgs_Msg( C, SGS_WARNING, "function expects at least 2 arguments, got %d", sgs_StackSize( C ) ); } sgs_PushArray( C, 0 ); for( i = 0; i < ssz; ++i ) { if( sgs_PushIterator( C, i ) != SGS_SUCCESS ) return sgs_ArgErrorExt( C, i, 0, "iterable", "" ); while( sgs_IterAdvance( C, -1 ) > 0 ) { /* ..., output, arg2 iter */ sgs_IterPushData( C, -1, FALSE, TRUE ); sgs_ObjectAction( C, -3, SGS_ACT_ARRAY_PUSH, 1 ); } sgs_Pop( C, 1 ); } return 1; } static int sgsstd__get_merged__common( SGS_CTX, sgs_SizeVal ssz ) { sgs_SizeVal i; for( i = 0; i < ssz; ++i ) { if( sgs_PushIterator( C, i ) != SGS_SUCCESS ) return sgs_ArgErrorExt( C, i, 0, "iterable", "" ); while( sgs_IterAdvance( C, -1 ) > 0 ) { int ret; /* ..., output, arg2 iter */ ret = sgs_IterPushData( C, -1, TRUE, TRUE ); if( ret != SGS_SUCCESS ) STDLIB_WARN( "failed to retrieve data from iterator" ) ret = sgs_StoreIndexII( C, -4, -2, FALSE ); if( ret != SGS_SUCCESS ) STDLIB_WARN( "failed to store data" ) sgs_Pop( C, 1 ); } sgs_Pop( C, 1 ); } return 1; } static int sgsstd_get_merged( SGS_CTX ) { sgs_SizeVal ssz = sgs_StackSize( C ); SGSFN( "get_merged" ); if( ssz < 2 ) { return sgs_Msg( C, SGS_WARNING, "function expects at least 2 arguments, got %d", sgs_StackSize( C ) ); } sgs_PushDict( C, 0 ); return sgsstd__get_merged__common( C, ssz ); } static int sgsstd_get_merged_map( SGS_CTX ) { sgs_SizeVal ssz = sgs_StackSize( C ); SGSFN( "get_merged_map" ); if( ssz < 2 ) { return sgs_Msg( C, SGS_WARNING, "function expects at least 2 arguments, got %d", sgs_StackSize( C ) ); } sgs_PushMap( C, 0 ); return sgsstd__get_merged__common( C, ssz ); } static int sgsstd_get_iterator( SGS_CTX ) { SGSFN( "get_iterator" ); if( !sgs_LoadArgs( C, "?!v" ) ) return 0; if( SGS_FAILED( sgs_PushIterator( C, 0 ) ) ) STDLIB_WARN( "failed to retrieve iterator" ); return 1; } static int sgsstd_iter_advance( SGS_CTX ) { int ret; SGSFN( "iter_advance" ); if( !sgs_LoadArgs( C, "?!v" ) ) return 0; ret = sgs_IterAdvance( C, 0 ); if( SGS_FAILED( ret ) ) STDLIB_WARN( "failed to advance iterator" ) sgs_PushBool( C, ret != 0 ); return 1; } static int sgsstd_iter_getdata( SGS_CTX ) { int ret; sgs_Bool pushkey = 0, pushval = 1; SGSFN( "iter_getdata" ); if( !sgs_LoadArgs( C, "?!v|bb", &pushkey, &pushval ) ) return 0; if( pushkey + pushval == 0 ) STDLIB_WARN( "no data requested from iterator" ); ret = sgs_IterPushData( C, 0, pushkey, pushval ); if( SGS_FAILED( ret ) ) STDLIB_WARN( "failed to retrieve data from iterator" ); return pushkey + pushval; } static int sgsstd_tobool( SGS_CTX ) { SGSFN( "tobool" ); sgs_SetStackSize( C, 1 ); sgs_ToBool( C, 0 ); return 1; } static int sgsstd_toint( SGS_CTX ) { SGSFN( "toint" ); sgs_SetStackSize( C, 1 ); sgs_ToInt( C, 0 ); return 1; } static int sgsstd_toreal( SGS_CTX ) { SGSFN( "toreal" ); sgs_SetStackSize( C, 1 ); sgs_ToReal( C, 0 ); return 1; } static int sgsstd_tostring( SGS_CTX ) { SGSFN( "tostring" ); sgs_SetStackSize( C, 1 ); sgs_ToString( C, 0 ); return 1; } static int sgsstd_toptr( SGS_CTX ) { SGSFN( "toptr" ); sgs_SetStackSize( C, 1 ); sgs_ToPtr( C, 0 ); return 1; } static int sgsstd_parseint( SGS_CTX ) { sgs_Int i; SGSFN( "parseint" ); sgs_SetStackSize( C, 1 ); if( sgs_ItemType( C, 0 ) == SVT_INT ) return 1; if( sgs_ParseInt( C, 0, &i ) ) sgs_PushInt( C, i ); else sgs_PushNull( C ); return 1; } static int sgsstd_parsereal( SGS_CTX ) { sgs_Real r; SGSFN( "parsereal" ); sgs_SetStackSize( C, 1 ); if( sgs_ItemType( C, 0 ) == SVT_REAL ) return 1; if( sgs_ParseReal( C, 0, &r ) ) sgs_PushReal( C, r ); else sgs_PushNull( C ); return 1; } static int sgsstd_typeof( SGS_CTX ) { SGSFN( "typeof" ); if( !sgsstd_expectnum( C, 1 ) ) return 0; sgs_TypeOf( C, 0 ); return 1; } static int sgsstd_typeid( SGS_CTX ) { SGSFN( "typeid" ); if( !sgsstd_expectnum( C, 1 ) ) return 0; sgs_PushInt( C, sgs_ItemType( C, 0 ) ); return 1; } static int sgsstd_typeptr( SGS_CTX ) { SGSFN( "typeptr" ); if( !sgs_LoadArgs( C, ">." ) ) return 0; if( sgs_ItemType( C, 0 ) == SVT_OBJECT ) sgs_PushPtr( C, sgs_GetObjectIface( C, 0 ) ); else sgs_PushPtr( C, NULL ); return 1; } static int sgsstd_typeptr_by_name( SGS_CTX ) { char* typename; SGSFN( "typeptr_by_name" ); if( !sgs_LoadArgs( C, "s", &typename ) ) return 0; sgs_PushPtr( C, sgs_FindType( C, typename ) ); return 1; } static int sgsstd_is_numeric( SGS_CTX ) { int res; uint32_t ty; SGSFN( "is_numeric" ); if( !sgsstd_expectnum( C, 1 ) ) return 0; ty = sgs_ItemType( C, 0 ); if( ty == SVT_NULL || ty == SVT_FUNC || ty == SVT_CFUNC || ty == SVT_OBJECT ) res = FALSE; else res = ty != SVT_STRING || sgs_IsNumericString( sgs_GetStringPtr( C, 0 ), sgs_GetStringSize( C, 0 ) ); sgs_PushBool( C, res ); return 1; } static int sgsstd_is_callable( SGS_CTX ) { SGSFN( "is_callable" ); if( !sgsstd_expectnum( C, 1 ) ) return 0; sgs_PushBool( C, sgs_IsCallable( C, 0 ) ); return 1; } static int sgsstd_is_array( SGS_CTX ) { SGSFN( "is_array" ); sgs_PushBool( C, sgs_IsObject( C, 0, sgsstd_array_iface ) ); return 1; } static int sgsstd_is_dict( SGS_CTX ) { SGSFN( "is_dict" ); sgs_PushBool( C, sgs_IsObject( C, 0, sgsstd_dict_iface ) ); return 1; } static int sgsstd_is_map( SGS_CTX ) { SGSFN( "is_map" ); sgs_PushBool( C, sgs_IsObject( C, 0, sgsstd_map_iface ) ); return 1; } static int sgsstd_is_iterable( SGS_CTX ) { SGSFN( "is_iterable" ); sgs_PushBool( C, sgs_PushIterator( C, 0 ) == SGS_SUCCESS ); return 1; } /* I/O */ static int sgsstd_print( SGS_CTX ) { StkIdx i, ssz; SGSBASEFN( "print" ); ssz = sgs_StackSize( C ); for( i = 0; i < ssz; ++i ) { sgs_SizeVal size; char* buf = sgs_ToStringBuf( C, i, &size ); /* WP: string limit */ sgs_Write( C, buf, (size_t) size ); } return 0; } static int sgsstd_println( SGS_CTX ) { SGSFN( "println" ); sgsstd_print( C ); sgs_Write( C, "\n", 1 ); return 0; } static int sgsstd_printlns( SGS_CTX ) { StkIdx i, ssz; ssz = sgs_StackSize( C ); SGSFN( "printlns" ); for( i = 0; i < ssz; ++i ) { sgs_SizeVal size; char* buf = sgs_ToStringBuf( C, i, &size ); /* WP: string limit */ sgs_Write( C, buf, (size_t) size ); sgs_Write( C, "\n", 1 ); } return 0; } static int sgsstd_errprint( SGS_CTX ) { StkIdx i, ssz; SGSBASEFN( "errprint" ); ssz = sgs_StackSize( C ); for( i = 0; i < ssz; ++i ) { sgs_SizeVal size; char* buf = sgs_ToStringBuf( C, i, &size ); /* WP: string limit */ sgs_ErrWrite( C, buf, (size_t) size ); } return 0; } static int sgsstd_errprintln( SGS_CTX ) { SGSFN( "errprintln" ); sgsstd_errprint( C ); sgs_ErrWrite( C, "\n", 1 ); return 0; } static int sgsstd_errprintlns( SGS_CTX ) { StkIdx i, ssz; ssz = sgs_StackSize( C ); SGSFN( "errprintlns" ); for( i = 0; i < ssz; ++i ) { sgs_SizeVal size; char* buf = sgs_ToStringBuf( C, i, &size ); /* WP: string limit */ sgs_ErrWrite( C, buf, (size_t) size ); sgs_ErrWrite( C, "\n", 1 ); } return 0; } static int sgsstd_printvar( SGS_CTX ) { int res; StkIdx i, ssz; ssz = sgs_StackSize( C ); SGSFN( "printvar" ); for( i = 0; i < ssz; ++i ) { sgs_PushItem( C, i ); res = sgs_DumpVar( C, 5 ); if( res == SGS_SUCCESS ) { sgs_SizeVal bsz; char* buf = sgs_ToStringBuf( C, -1, &bsz ); /* WP: string limit */ sgs_Write( C, buf, (size_t) bsz ); sgs_Write( C, "\n", 1 ); } else { char ebuf[ 64 ]; sprintf( ebuf, "unknown error while dumping variable #%d", i + 1 ); STDLIB_ERR( ebuf ); } sgs_Pop( C, 1 ); } return 0; } static int sgsstd_printvar_ext( SGS_CTX ) { sgs_Int depth = 5; SGSFN( "printvar_ext" ); if( !sgs_LoadArgs( C, ">|i.", &depth ) ) return 0; sgs_SetStackSize( C, 1 ); if( sgs_DumpVar( C, (int) depth ) == SGS_SUCCESS ) { sgs_SizeVal bsz; char* buf = sgs_ToStringBuf( C, -1, &bsz ); /* WP: string limit */ sgs_Write( C, buf, (size_t) bsz ); sgs_Write( C, "\n", 1 ); } else STDLIB_ERR( "unknown error while dumping variable" ); return 0; } static int sgsstd_read_stdin( SGS_CTX ) { MemBuf B; char bfr[ 1024 ]; int all = 0; SGSFN( "read_stdin" ); if( !sgs_LoadArgs( C, "|b", &all ) ) return 0; B = membuf_create(); while( fgets( bfr, 1024, stdin ) ) { size_t len = strlen( bfr ); membuf_appbuf( &B, C, bfr, len ); if( len && !all && bfr[ len - 1 ] == '\n' ) { B.size--; break; } } if( B.size > 0x7fffffff ) { membuf_destroy( &B, C ); STDLIB_WARN( "read more bytes than allowed to store" ); } /* WP: error condition */ sgs_PushStringBuf( C, B.ptr, (sgs_SizeVal) B.size ); membuf_destroy( &B, C ); return 1; } /* OS */ static int sgsstd_ftime( SGS_CTX ) { SGSFN( "ftime" ); sgs_PushReal( C, sgs_GetTime() ); return 1; } /* utils */ static int sgsstd_rand( SGS_CTX ) { SGSFN( "rand" ); sgs_PushInt( C, rand() ); return 1; } static int sgsstd_randf( SGS_CTX ) { SGSFN( "randf" ); sgs_PushReal( C, (double) rand() / (double) RAND_MAX ); return 1; } static int sgsstd_srand( SGS_CTX ) { uint32_t s; SGSFN( "srand" ); if( !sgs_LoadArgs( C, "+l", &s ) ) return 0; srand( s ); return 0; } static int sgsstd_hash_fnv( SGS_CTX ) { uint8_t* buf; sgs_SizeVal i, bufsize; uint32_t hv = 2166136261u; sgs_Bool as_hexstr = 0; SGSFN( "hash_fnv" ); if( !sgs_LoadArgs( C, "m|b", &buf, &bufsize, &as_hexstr ) ) return 0; for( i = 0; i < bufsize; ++i ) { hv ^= buf[ i ]; hv *= 16777619u; } if( as_hexstr ) { char hexstr[ 9 ] = {0}; sprintf( hexstr, "%08x", hv ); sgs_PushStringBuf( C, hexstr, 8 ); } else sgs_PushInt( C, hv ); return 1; } static int sgsstd_hash_crc32( SGS_CTX ) { uint8_t* buf; sgs_SizeVal bufsize; uint32_t hv; sgs_Bool as_hexstr = 0; SGSFN( "hash_crc32" ); if( !sgs_LoadArgs( C, "m|b", &buf, &bufsize, &as_hexstr ) ) return 0; hv = sgs_crc32( buf, (size_t) bufsize, 0 ); if( as_hexstr ) { char hexstr[ 9 ] = {0}; sprintf( hexstr, "%08x", hv ); sgs_PushStringBuf( C, hexstr, 8 ); } else sgs_PushInt( C, hv ); return 1; } /* internal utils */ static int sgsstd_va_get_args( SGS_CTX ) { uint8_t i, xac, pcnt; sgs_StackFrame* sf; SGSFN( "va_get_args" ); if( !C->sf_last || !C->sf_last->prev ) STDLIB_WARN( "not called from function" ) sf = C->sf_last->prev; /* WP: argument count limit */ /* accepted arguments */ pcnt = MIN( sf->argcount, sf->inexp ); for( i = 0; i < pcnt; ++i ) sgs_PushVariable( C, C->stack_base + sf->argend - pcnt + i ); /* extra arguments */ if( sf->argcount > sf->inexp ) { sgs_Variable* tpv; xac = (uint8_t)( sf->argcount - sf->inexp ); tpv = C->stack_base + sf->argbeg + xac - 1; for( i = 0; i < xac; ++i ) sgs_PushVariable( C, tpv - i ); } sgs_PushArray( C, sf->argcount ); return 1; } static int sgsstd_va_get_arg( SGS_CTX ) { sgs_Int argnum; uint8_t i, xac, pcnt; sgs_StackFrame* sf; SGSFN( "va_get_arg" ); if( !C->sf_last || !C->sf_last->prev ) STDLIB_WARN( "not called from function" ) if( !sgs_LoadArgs( C, "i", &argnum ) ) return 0; sf = C->sf_last->prev; if( argnum < 0 || argnum >= sf->argcount ) STDLIB_WARN( "argument ID out of bounds" ) /* WP: argument count limit */ i = (uint8_t) argnum; /* accepted arguments */ pcnt = MIN( sf->argcount, sf->inexp ); if( i < pcnt ) { sgs_PushVariable( C, C->stack_base + sf->argend - pcnt + i ); } else /* extra arguments */ if( sf->argcount > sf->inexp ) { sgs_Variable* tpv; i = (uint8_t)( i - pcnt ); xac = (uint8_t)( sf->argcount - sf->inexp ); tpv = C->stack_base + sf->argbeg + xac - 1; sgs_PushVariable( C, tpv - i ); } else sgs_PushNull( C ); return 1; } static int sgsstd_va_arg_count( SGS_CTX ) { SGSFN( "va_arg_count" ); if( !C->sf_last || !C->sf_last->prev ) STDLIB_WARN( "not called from function" ) sgs_PushInt( C, C->sf_last->prev->argcount ); return 1; } struct pcall_printinfo { sgs_MsgFunc pfn; void* pctx; sgs_Variable handler; int depth; }; static void sgsstd_pcall_print( void* data, SGS_CTX, int type, const char* message ) { int ret = 0; struct pcall_printinfo* P = (struct pcall_printinfo*) data; P->depth++; if( P->depth > 1 ) ret = type; /* don't handle errors thrown inside handlers */ else if( P->handler.type != SVT_NULL ) { sgs_PushInt( C, type ); sgs_PushString( C, message ); ret = sgs_CallP( C, &P->handler, 2, 1 ); if( SGS_FAILED( ret ) ) { ret = 0; P->pfn( P->pctx, C, SGS_ERROR, "Error detected while attempting to call error handler" ); } else { if( ret ) sgs_Abort( C ); ret = (int) sgs_GetInt( C, -1 ); sgs_Pop( C, 1 ); } } if( ret > 0 ) P->pfn( P->pctx, C, ret, message ); P->depth--; } static int sgsstd_pcall( SGS_CTX ) { struct pcall_printinfo P; int b = 0; SGSFN( "pcall" ); if( !sgs_LoadArgs( C, "?p|p", &b ) ) return 0; P.pfn = C->msg_fn; P.pctx = C->msg_ctx; P.handler.type = SVT_NULL; P.depth = 0; if( b ) sgs_GetStackItem( C, 1, &P.handler ); C->msg_fn = sgsstd_pcall_print; C->msg_ctx = &P; sgs_PushItem( C, 0 ); sgs_Call( C, 0, 0 ); C->msg_fn = P.pfn; C->msg_ctx = P.pctx; if( b ) sgs_Release( C, &P.handler ); return 0; } static int sgsstd_assert( SGS_CTX ) { char* str = NULL; SGSFN( "assert" ); if( !sgs_LoadArgs( C, "?v|s", &str ) ) return 0; SGSFN( NULL ); if( !sgs_GetBool( C, 0 ) ) sgs_Msg( C, SGS_ERROR, !str ? "assertion failed" : "assertion failed: %s", str ); return 0; } static int sgsstd_eval( SGS_CTX ) { char* str; sgs_SizeVal size; int rvc = 0; SGSFN( "eval" ); if( !sgs_LoadArgs( C, "m", &str, &size ) ) return 0; /* WP: string limit */ sgs_EvalBuffer( C, str, (size_t) size, &rvc ); return rvc; } static int sgsstd_eval_file( SGS_CTX ) { int ret, retcnt = 0; char* str; SGSFN( "eval_file" ); if( !sgs_LoadArgs( C, "s", &str ) ) return 0; ret = sgs_EvalFile( C, str, &retcnt ); if( ret == SGS_ENOTFND ) STDLIB_WARN( "file not found" ) return retcnt; } static void _sgsstd_compile_pfn( void* data, SGS_CTX, int type, const char* msg ) { int ret; sgs_Variable* pvar = (sgs_Variable*) data; sgs_PushVariable( C, pvar ); sgs_PushString( C, "type" ); sgs_PushInt( C, type ); sgs_PushString( C, "msg" ); sgs_PushString( C, msg ); sgs_PushDict( C, 4 ); ret = sgs_ObjectAction( C, -2, SGS_ACT_ARRAY_PUSH, 1 ); UNUSED( ret ); sgs_BreakIf( ret < 0 ); sgs_Pop( C, 1 ); } static int sgsstd_compile_sgs( SGS_CTX ) { int ret; char* buf = NULL, *outbuf = NULL; sgs_SizeVal size = 0; size_t outsize = 0; sgs_Variable var; sgs_MsgFunc oldpfn; void* oldpctx; SGSFN( "compile_sgs" ); if( !sgs_LoadArgs( C, "m", &buf, &size ) ) return 0; sgs_PushArray( C, 0 ); sgs_GetStackItem( C, -1, &var ); sgs_Pop( C, 1 ); oldpfn = C->msg_fn; oldpctx = C->msg_ctx; sgs_SetMsgFunc( C, _sgsstd_compile_pfn, &var ); SGSFN( NULL ); /* WP: string limit */ ret = sgs_Compile( C, buf, (size_t) size, &outbuf, &outsize ); SGSFN( "compile_sgs" ); C->msg_fn = oldpfn; C->msg_ctx = oldpctx; if( ret < 0 ) sgs_PushNull( C ); else { if( outsize <= 0x7fffffff ) sgs_PushStringBuf( C, outbuf, (sgs_SizeVal) outsize ); else { sgs_PushNull( C ); sgs_Msg( C, SGS_WARNING, "size of compiled code is bigger than allowed to store" ); } sgs_Dealloc( outbuf ); } sgs_PushVariable( C, &var ); sgs_Release( C, &var ); return 2; } static int sgsstd__inclib( SGS_CTX, const char* name, int override ) { char buf[ 16 ]; int ret = SGS_ENOTFND; sprintf( buf, "-%.14s", name ); if( !override && sgs_PushGlobal( C, buf ) == SGS_SUCCESS ) { sgs_Pop( C, 1 ); return SGS_SUCCESS; } if( strcmp( name, "fmt" ) == 0 ) ret = sgs_LoadLib_Fmt( C ); else if( strcmp( name, "io" ) == 0 ) ret = sgs_LoadLib_IO( C ); else if( strcmp( name, "math" ) == 0 ) ret = sgs_LoadLib_Math( C ); else if( strcmp( name, "os" ) == 0 ) ret = sgs_LoadLib_OS( C ); else if( strcmp( name, "re" ) == 0 ) ret = sgs_LoadLib_RE( C ); else if( strcmp( name, "string" ) == 0 ) ret = sgs_LoadLib_String( C ); if( ret == SGS_SUCCESS ) { sgs_PushBool( C, TRUE ); sgs_StoreGlobal( C, buf ); } return ret; } static int sgsstd__chkinc( SGS_CTX, int argid ) { sgs_PushString( C, "+" ); sgs_PushItem( C, argid ); sgs_StringConcat( C, 2 ); sgs_PushEnv( C ); if( sgs_PushIndexII( C, -1, -2, 0 ) != SGS_SUCCESS ) return FALSE; /* sgs_Pop( C, 2 ); [.., string, bool] - will return last */ return TRUE; } static void sgsstd__setinc( SGS_CTX, int argid ) { sgs_PushEnv( C ); sgs_PushString( C, "+" ); sgs_PushItem( C, argid ); sgs_StringConcat( C, 2 ); sgs_PushBool( C, TRUE ); sgs_SetIndexIII( C, -3, -2, -1, 0 ); sgs_Pop( C, 3 ); } static int sgsstd_include_library( SGS_CTX ) { int ret, over = FALSE; char* str; SGSBASEFN( "include_library" ); if( !sgs_LoadArgs( C, "s|b", &str, &over ) ) return 0; ret = sgsstd__inclib( C, str, over ); if( ret == SGS_ENOTFND ) STDLIB_WARN( "library not found" ) sgs_PushBool( C, ret == SGS_SUCCESS ); return 1; } static int sgsstd_include_file( SGS_CTX ) { int ret, over = FALSE; char* str; SGSBASEFN( "include_file" ); if( !sgs_LoadArgs( C, "s|b", &str, &over ) ) return 0; if( !over && sgsstd__chkinc( C, 0 ) ) return 1; ret = sgs_ExecFile( C, str ); if( ret == SGS_ENOTFND ) return sgs_Msg( C, SGS_WARNING, "file '%s' was not found", str ); if( ret == SGS_SUCCESS ) sgsstd__setinc( C, 0 ); sgs_PushBool( C, ret == SGS_SUCCESS ); return 1; } static int sgsstd_include_shared( SGS_CTX ) { char* fnstr; int ret, over = FALSE; sgs_CFunc func; SGSBASEFN( "include_shared" ); if( !sgs_LoadArgs( C, "s|b", &fnstr, &over ) ) return 0; if( !over && sgsstd__chkinc( C, 0 ) ) return 1; ret = sgsXPC_GetProcAddress( fnstr, SGS_LIB_ENTRY_POINT, (void**) &func ); if( ret != 0 ) { if( ret == SGS_XPC_NOFILE ) return sgs_Msg( C, SGS_WARNING, "file '%s' was not found", fnstr ); else if( ret == SGS_XPC_NOPROC ) return sgs_Msg( C, SGS_WARNING, "procedure '" SGS_LIB_ENTRY_POINT "' was not found" ); else if( ret == SGS_XPC_NOTSUP ) STDLIB_WARN( "feature is not supported on this platform" ) else STDLIB_WARN( "unknown error occured" ) } ret = func( C ); if( ret != SGS_SUCCESS ) STDLIB_WARN( "module failed to initialize" ) sgsstd__setinc( C, 0 ); sgs_PushBool( C, TRUE ); return 1; } static int _push_curdir( SGS_CTX ) { const char* file, *fend; sgs_StackFrame* sf; sf = sgs_GetFramePtr( C, 1 )->prev; if( !sf ) return 0; sgs_StackFrameInfo( C, sf, NULL, &file, NULL ); if( file ) { fend = file + strlen( file ); while( fend > file && *fend != '/' && *fend != '\\' ) fend--; if( fend == file ) { #ifdef _WIN32 sgs_PushString( C, "." ); #else if( *file == '/' ) sgs_PushString( C, "" ); else sgs_PushString( C, "." ); #endif } else { ptrdiff_t len = fend - file; if( len > 0x7fffffff ) return 0; else /* WP: error condition */ sgs_PushStringBuf( C, file, (sgs_SizeVal) len ); } return 1; } return 0; } static int _find_includable_file( SGS_CTX, MemBuf* tmp, char* ps, size_t pssize, char* fn, size_t fnsize, char* dn, size_t dnsize ) { if( ( fnsize > 2 && *fn == '.' && ( fn[1] == '/' || fn[1] == '\\' ) ) || #ifdef _WIN32 ( fnsize > 2 && fn[1] == ':' ) ) #else ( fnsize > 1 && *fn == '/' ) ) #endif { FILE* f; membuf_setstrbuf( tmp, C, fn, fnsize ); if( ( f = fopen( tmp->ptr, "rb" ) ) != NULL ) { fclose( f ); return 1; } } else { char* pse = ps + pssize; char* psc = ps; while( ps <= pse ) { if( ps == pse || *ps == ';' ) { FILE* f; membuf_resize( tmp, C, 0 ); while( psc < ps ) { if( *psc == '?' ) membuf_appbuf( tmp, C, fn, fnsize ); else if( *psc == '|' ) { if( dn ) membuf_appbuf( tmp, C, dn, dnsize ); else { psc = ps; goto notthispath; } } else membuf_appchr( tmp, C, *psc ); psc++; } membuf_appchr( tmp, C, 0 ); if( ( f = fopen( tmp->ptr, "rb" ) ) != NULL ) { fclose( f ); return 1; } notthispath: psc++; } ps++; } } return 0; } static int sgsstd_include( SGS_CTX ) { char* fnstr, *dnstr = NULL; sgs_SizeVal fnsize, dnsize = 0; int over = 0, ret; SGSFN( "include" ); if( !sgs_LoadArgs( C, "m|b", &fnstr, &fnsize, &over ) ) return 0; if( !over && sgsstd__chkinc( C, 0 ) ) goto success; ret = sgsstd__inclib( C, fnstr, over ); if( ret == SGS_SUCCESS ) goto success; else { char* ps; sgs_SizeVal pssize; sgs_CFunc func; MemBuf mb = membuf_create(); ret = sgs_PushGlobal( C, "SGS_PATH" ); if( ret != SGS_SUCCESS || ( ps = sgs_ToStringBuf( C, -1, &pssize ) ) == NULL ) { ps = SGS_INCLUDE_PATH; pssize = (sgs_SizeVal) strlen( ps ); } if( _push_curdir( C ) ) { dnstr = sgs_GetStringPtr( C, -1 ); dnsize = sgs_GetStringSize( C, -1 ); } /* WP: string limit */ ret = _find_includable_file( C, &mb, ps, (size_t) pssize, fnstr, (size_t) fnsize, dnstr, (size_t) dnsize ); if( ret == 0 || mb.size == 0 ) { membuf_destroy( &mb, C ); return sgs_Msg( C, SGS_WARNING, "could not find '%.*s' " "with include path '%.*s'", fnsize, fnstr, pssize, ps ); } sgs_PushString( C, mb.ptr ); sgs_PushString( C, " - include" ); sgs_StringConcat( C, 2 ); SGSFN( sgs_GetStringPtr( C, -1 ) ); ret = sgs_ExecFile( C, mb.ptr ); SGSFN( "include" ); if( ret == SGS_SUCCESS ) { membuf_destroy( &mb, C ); goto success; } ret = sgsXPC_GetProcAddress( mb.ptr, SGS_LIB_ENTRY_POINT, (void**) &func ); if( SGS_SUCCEEDED( ret ) ) { ret = func( C ); if( SGS_SUCCEEDED( ret ) ) { membuf_destroy( &mb, C ); goto success; } } else { membuf_destroy( &mb, C ); return sgs_Msg( C, SGS_WARNING, "failed to load native module '%.*s'", fnsize, fnstr ); } membuf_destroy( &mb, C ); } sgs_Msg( C, SGS_WARNING, "could not load '%.*s'", fnsize, fnstr ); sgs_PushBool( C, 0 ); return 1; success: sgsstd__setinc( C, 0 ); sgs_PushBool( C, 1 ); return 1; } static int sgsstd_import_cfunc( SGS_CTX ) { char* fnstr, *pnstr; int ret; sgs_CFunc func; SGSFN( "import_cfunc" ); if( !sgs_LoadArgs( C, "ss", &fnstr, &pnstr ) ) return 0; ret = sgsXPC_GetProcAddress( fnstr, pnstr, (void**) &func ); if( ret != 0 ) { if( ret == SGS_XPC_NOFILE ) return sgs_Msg( C, SGS_WARNING, "file '%s' was not found", fnstr ); else if( ret == SGS_XPC_NOPROC ) return sgs_Msg( C, SGS_WARNING, "procedure '%s' was not found", pnstr ); else if( ret == SGS_XPC_NOTSUP ) STDLIB_WARN( "feature is not supported on this platform" ) else STDLIB_WARN( "unknown error occured" ) } sgs_PushCFunction( C, func ); return 1; } static int sgsstd_sys_curfile( SGS_CTX ) { const char* file; sgs_StackFrame* sf; SGSFN( "sys_curfile" ); if( sgs_StackSize( C ) ) STDLIB_WARN( "function expects 0 arguments" ) sf = sgs_GetFramePtr( C, 1 )->prev; if( !sf ) return 0; sgs_StackFrameInfo( C, sf, NULL, &file, NULL ); if( file ) { sgs_PushString( C, file ); return 1; } return 0; } static int sgsstd_sys_curfiledir( SGS_CTX ) { SGSFN( "sys_curfiledir" ); if( sgs_StackSize( C ) ) STDLIB_WARN( "function expects 0 arguments" ) return _push_curdir( C ); } static int sgsstd_sys_backtrace( SGS_CTX ) { sgs_Bool as_errinfo = 0; SGSFN( "sys_backtrace" ); if( !sgs_LoadArgs( C, "|b", &as_errinfo ) ) return 0; if( as_errinfo ) sgs_PushErrorInfo( C, SGS_ERRORINFO_STACK, 0, NULL ); else { sgs_StkIdx sz = sgs_StackSize( C ); sgs_StackFrame* p = sgs_GetFramePtr( C, FALSE ); while( p != NULL ) { const char* file, *name; int ln; if( !p->next && !p->code ) break; sgs_StackFrameInfo( C, p, &name, &file, &ln ); sgs_PushString( C, "func" ); sgs_PushString( C, name ); sgs_PushString( C, "line" ); if( ln ) sgs_PushInt( C, ln ); else sgs_PushNull( C ); sgs_PushString( C, "file" ); sgs_PushString( C, file ); sgs_PushDict( C, 6 ); p = p->next; } sgs_PushArray( C, sgs_StackSize( C ) - sz ); } return 1; } static int sgsstd_sys_msg( SGS_CTX ) { char* errmsg; sgs_Int errcode; SGSFN( "sys_msg" ); if( !sgs_LoadArgs( C, "is", &errcode, &errmsg ) ) return 0; SGSFN( NULL ); sgs_Msg( C, (int) errcode, "%s", errmsg ); return 0; } static int sgsstd__msgwrapper( SGS_CTX, const char* fn, int code ) { char* msg; SGSFN( fn ); if( sgs_LoadArgs( C, "s", &msg ) ) { SGSFN( NULL ); sgs_Msg( C, code, "%s", msg ); } return 0; } static int sgsstd_INFO( SGS_CTX ){ return sgsstd__msgwrapper( C, "INFO", SGS_INFO ); } static int sgsstd_WARNING( SGS_CTX ){ return sgsstd__msgwrapper( C, "WARNING", SGS_WARNING ); } static int sgsstd_ERROR( SGS_CTX ){ return sgsstd__msgwrapper( C, "ERROR", SGS_ERROR ); } static int sgsstd_sys_abort( SGS_CTX ) { sgs_Abort( C ); return 0; } static int sgsstd_app_abort( SGS_CTX ){ abort(); return 0; } static int sgsstd_app_exit( SGS_CTX ) { sgs_Int ret = 0; if( !sgs_LoadArgs( C, "|i", &ret ) ) return 0; exit( (int) ret ); return 0; } static int sgsstd_sys_replevel( SGS_CTX ) { int lev = C->minlev; SGSFN( "sys_replevel" ); if( sgs_StackSize( C ) ) { sgs_Int i; if( !sgs_LoadArgs( C, "i", &i ) ) return 0; C->minlev = (int) i; return 0; } sgs_PushInt( C, lev ); return 1; } static int sgsstd_sys_stat( SGS_CTX ) { sgs_Int type; SGSFN( "sys_stat" ); if( !sgs_LoadArgs( C, "i", &type ) ) return 0; sgs_PushInt( C, sgs_Stat( C, (int) type ) ); return 1; } static int sgsstd_errno( SGS_CTX ) { int retstr = 0; SGSFN( "errno" ); if( !sgs_LoadArgs( C, "|b", &retstr ) ) return 0; if( retstr ) sgs_PushString( C, strerror( C->last_errno ) ); else sgs_PushInt( C, C->last_errno ); return 1; } static int sgsstd_errno_string( SGS_CTX ) { sgs_Int e; SGSFN( "errno_string" ); if( !sgs_LoadArgs( C, "i", &e ) ) return 0; sgs_PushString( C, strerror( (int) e ) ); return 1; } #define AE( x ) #x, (const char*) x static const char* errno_key_table[] = { AE( E2BIG ), AE( EACCES ), AE( EAGAIN ), AE( EBADF ), AE( EBUSY ), AE( ECHILD ), AE( EDEADLK ), AE( EDOM ), AE( EEXIST ), AE( EFAULT ), AE( EFBIG ), AE( EILSEQ ), AE( EINTR ), AE( EINVAL ), AE( EIO ), AE( EISDIR ), AE( EMFILE ), AE( EMLINK ), AE( ENAMETOOLONG ), AE( ENFILE ), AE( ENODEV ), AE( ENOENT ), AE( ENOEXEC ), AE( ENOLCK ), AE( ENOMEM ), AE( ENOSPC ), AE( ENOSYS ), AE( ENOTDIR ), AE( ENOTEMPTY ), AE( ENOTTY ), AE( ENXIO ), AE( EPERM ), AE( EPIPE ), AE( ERANGE ), AE( EROFS ), AE( ESPIPE ), AE( ESRCH ), AE( EXDEV ), NULL, }; #undef AE static int sgsstd_errno_value( SGS_CTX ) { const char** ekt = errno_key_table; char* str; SGSFN( "errno_value" ); if( !sgs_LoadArgs( C, "s", &str ) ) return 0; while( *ekt ) { if( strcmp( *ekt, str ) == 0 ) { sgs_PushInt( C, (int) (size_t) ekt[1] ); return 1; } ekt += 2; } sgs_Msg( C, SGS_ERROR, "this errno value is unsupported" ); return 0; } static int sgsstd_dumpvar( SGS_CTX ) { int i, ssz, res, rc = 0; ssz = sgs_StackSize( C ); SGSFN( "dumpvar" ); for( i = 0; i < ssz; ++i ) { sgs_PushItem( C, i ); res = sgs_DumpVar( C, 5 ); if( res == SGS_SUCCESS ) { sgs_PushString( C, "\n" ); rc += 2; } else { char ebuf[ 64 ]; sprintf( ebuf, "unknown error while dumping variable #%d", i + 1 ); STDLIB_ERR( ebuf ); sgs_Pop( C, 1 ); } } if( rc ) { if( sgs_StringConcat( C, rc ) != SGS_SUCCESS ) STDLIB_ERR( "failed to concatenate the output" ) return 1; } return 0; } static int sgsstd_dumpvar_ext( SGS_CTX ) { sgs_Int depth = 5; SGSFN( "dumpvar_ext" ); if( !sgs_LoadArgs( C, ">|i.", &depth ) ) return 0; sgs_SetStackSize( C, 1 ); if( sgs_DumpVar( C, (int) depth ) == SGS_SUCCESS ) return 1; else STDLIB_ERR( "unknown error while dumping variable" ); return 0; } static int sgsstd_gc_collect( SGS_CTX ) { int ret; ptrdiff_t orvc = sgs_Stat( C, SGS_STAT_OBJCOUNT ); SGSFN( "gc_collect" ); ret = sgs_GCExecute( C ); if( ret == SGS_SUCCESS ) sgs_PushInt( C, orvc - sgs_Stat( C, SGS_STAT_OBJCOUNT ) ); else sgs_PushBool( C, FALSE ); return 1; } static int sgsstd_serialize( SGS_CTX ) { int ret; SGSFN( "serialize" ); if( !sgs_LoadArgs( C, "?v." ) ) return 0; ret = sgs_Serialize( C ); if( ret == SGS_SUCCESS ) return 1; else STDLIB_ERR( "failed to serialize" ) } static int check_arrayordict_fn( SGS_CTX, int argid, va_list args, int flags ) { uint32_t ty = sgs_ItemType( C, argid ); if( ty != SVT_OBJECT || ( !sgs_IsObject( C, argid, sgsstd_array_iface ) && !sgs_IsObject( C, argid, sgsstd_dict_iface ) ) ) return sgs_ArgErrorExt( C, argid, 0, "array or dict", "" ); return 1; } static int sgsstd_unserialize( SGS_CTX ) { int ret; StkIdx ssz = sgs_StackSize( C ), dictpos; sgs_Variable env; SGSFN( "unserialize" ); if( !sgs_LoadArgs( C, "?s|x", check_arrayordict_fn ) ) return 0; if( ssz >= 2 ) { sgs_GetEnv( C, &env ); if( sgs_IsObject( C, 1, sgsstd_array_iface ) ) { dictpos = sgs_StackSize( C ); sgs_PushDict( C, 0 ); sgs_PushIterator( C, 1 ); while( sgs_IterAdvance( C, -1 ) > 0 ) { if( !sgs_IterPushData( C, -1, 0, 1 ) ) { sgs_ToString( C, -1 ); if( SGS_FAILED( sgs_PushIndexPI( C, &env, -1, 0 ) ) ) sgs_PushNull( C ); sgs_StoreIndexII( C, dictpos, -2, 0 ); sgs_Pop( C, 1 ); /* pop name */ } } sgs_Pop( C, 1 ); /* pop iterator */ } else dictpos = 1; if( SGS_FAILED( sgs_PushItem( C, dictpos ) ) || SGS_FAILED( sgs_StoreEnv( C ) ) ) { sgs_Release( C, &env ); STDLIB_ERR( "failed to change the environment" ) } sgs_PushItem( C, 0 ); } ret = sgs_Unserialize( C ); if( ssz >= 2 ) { int ret2 = sgs_SetEnv( C, &env ); sgs_Release( C, &env ); if( SGS_FAILED( ret2 ) ) STDLIB_ERR( "failed to restore the environment" ) } if( ret == SGS_SUCCESS ) return 1; else if( ret == SGS_EINPROC ) STDLIB_ERR( "error in data" ) else if( ret == SGS_ENOTFND ) STDLIB_ERR( "could not find something (like recreation function)" ) else STDLIB_ERR( "unknown error" ) } /* register all */ #define FN( name ) { #name, sgsstd_##name } static sgs_RegFuncConst regfuncs[] = { /* containers */ FN( array ), FN( dict ), FN( map ), { "class", sgsstd_class }, FN( array_filter ), FN( array_process ), FN( dict_filter ), FN( dict_process ), FN( dict_size ), FN( map_size ), FN( isset ), FN( unset ), FN( clone ), FN( get_keys ), FN( get_values ), FN( get_concat ), FN( get_merged ), FN( get_merged_map ), FN( get_iterator ), FN( iter_advance ), FN( iter_getdata ), /* types */ FN( tobool ), FN( toint ), FN( toreal ), FN( tostring ), FN( toptr ), FN( parseint ), FN( parsereal ), FN( typeof ), FN( typeid ), FN( typeptr ), FN( typeptr_by_name ), FN( is_numeric ), FN( is_callable ), FN( is_array ), FN( is_dict ), FN( is_map ), FN( is_iterable ), /* I/O */ FN( print ), FN( println ), FN( printlns ), FN( errprint ), FN( errprintln ), FN( errprintlns ), FN( printvar ), FN( printvar_ext ), FN( read_stdin ), /* OS */ FN( ftime ), /* utils */ FN( rand ), FN( randf ), FN( srand ), FN( hash_fnv ), FN( hash_crc32 ), /* internal utils */ FN( va_get_args ), FN( va_get_arg ), FN( va_arg_count ), { "sys_call", sgs_specfn_call }, { "sys_apply", sgs_specfn_apply }, FN( pcall ), FN( assert ), FN( eval ), FN( eval_file ), FN( compile_sgs ), FN( include_library ), FN( include_file ), FN( include_shared ), FN( import_cfunc ), FN( include ), FN( sys_curfile ), FN( sys_curfiledir ), FN( sys_backtrace ), FN( sys_msg ), FN( INFO ), FN( WARNING ), FN( ERROR ), FN( sys_abort ), FN( app_abort ), FN( app_exit ), FN( sys_replevel ), FN( sys_stat ), FN( errno ), FN( errno_string ), FN( errno_value ), FN( dumpvar ), FN( dumpvar_ext ), FN( gc_collect ), FN( serialize ), FN( unserialize ), }; static const sgs_RegIntConst regiconsts[] = { { "SGS_INFO", SGS_INFO }, { "SGS_WARNING", SGS_WARNING }, { "SGS_ERROR", SGS_ERROR }, { "VT_NULL", SVT_NULL }, { "VT_BOOL", SVT_BOOL }, { "VT_INT", SVT_INT }, { "VT_REAL", SVT_REAL }, { "VT_STRING", SVT_STRING }, { "VT_FUNC", SVT_FUNC }, { "VT_CFUNC", SVT_CFUNC }, { "VT_OBJECT", SVT_OBJECT }, { "VT_PTR", SVT_PTR }, { "RAND_MAX", RAND_MAX }, }; int sgsSTD_PostInit( SGS_CTX ) { int ret; ret = sgs_RegIntConsts( C, regiconsts, ARRAY_SIZE( regiconsts ) ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_RegFuncConsts( C, regfuncs, ARRAY_SIZE( regfuncs ) ); if( ret != SGS_SUCCESS ) return ret; sgs_PushString( C, SGS_INCLUDE_PATH ); ret = sgs_StoreGlobal( C, "SGS_PATH" ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_RegisterType( C, "array", sgsstd_array_iface ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_RegisterType( C, "array_iterator", sgsstd_array_iter_iface ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_RegisterType( C, "dict", sgsstd_dict_iface ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_RegisterType( C, "dict_iterator", sgsstd_dict_iter_iface ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_RegisterType( C, "map", sgsstd_map_iface ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_RegisterType( C, "class", sgsstd_class_iface ); if( ret != SGS_SUCCESS ) return ret; ret = sgs_RegisterType( C, "closure", sgsstd_closure_iface ); if( ret != SGS_SUCCESS ) return ret; return SGS_SUCCESS; } int sgsSTD_MakeArray( SGS_CTX, sgs_Variable* out, sgs_SizeVal cnt ) { StkIdx i = 0, ssz = sgs_StackSize( C ); if( ssz < cnt ) return SGS_EINVAL; else { sgs_Variable *p, *pend; void* data = sgs_Malloc( C, SGSARR_ALLOCSIZE( cnt ) ); sgsstd_array_header_t* hdr = (sgsstd_array_header_t*) sgs_InitObjectIPA( C, out, sizeof( sgsstd_array_header_t ), SGSIFACE_ARRAY ); hdr->size = cnt; hdr->mem = cnt; p = hdr->data = (sgs_Variable*) data; pend = p + cnt; while( p < pend ) sgs_GetStackItem( C, i++ - cnt, p++ ); sgs_Pop( C, cnt ); return SGS_SUCCESS; } } int sgsSTD_MakeDict( SGS_CTX, sgs_Variable* out, sgs_SizeVal cnt ) { DictHdr* dh; VHTable* ht; StkIdx i, ssz = sgs_StackSize( C ); if( cnt > ssz || cnt % 2 != 0 ) return SGS_EINVAL; dh = mkdict( C, out ); ht = &dh->ht; for( i = 0; i < cnt; i += 2 ) { if( !sgs_ParseString( C, i - cnt, NULL, NULL ) ) { sgs_Release( C, out ); return SGS_EINVAL; } vht_set( ht, C, (C->stack_top+i-cnt), (C->stack_top+i+1-cnt) ); } sgs_Pop( C, cnt ); return SGS_SUCCESS; } int sgsSTD_MakeMap( SGS_CTX, sgs_Variable* out, sgs_SizeVal cnt ) { DictHdr* dh; VHTable* ht; StkIdx i, ssz = sgs_StackSize( C ); if( cnt > ssz || cnt % 2 != 0 ) return SGS_EINVAL; dh = mkmap( C, out ); ht = &dh->ht; for( i = 0; i < cnt; i += 2 ) { vht_set( ht, C, (C->stack_top+i-cnt), (C->stack_top+i+1-cnt) ); } sgs_Pop( C, cnt ); return SGS_SUCCESS; } #define GLBP C->_G int sgsSTD_GlobalInit( SGS_CTX ) { sgs_Variable var; if( SGS_FAILED( sgsSTD_MakeDict( C, &var, 0 ) ) ) return SGS_EINPROC; GLBP = var.data.O; return SGS_SUCCESS; } int sgsSTD_GlobalFree( SGS_CTX ) { VHTVar *p, *pend; sgs_VarObj* data = GLBP; HTHDR; p = ht->vars; pend = p + vht_size( ht ); while( p < pend ) { sgs_Release( C, &p->val ); p++; } sgs_ObjRelease( C, GLBP ); GLBP = NULL; return SGS_SUCCESS; } int sgsSTD_GlobalGet( SGS_CTX, sgs_Variable* out, sgs_Variable* idx ) { VHTVar* pair; sgs_VarObj* data = GLBP; HTHDR; /* `out` is expected to point at an initialized variable */ if( idx->type != SVT_STRING ) { sgs_Release( C, out ); return SGS_ENOTSUP; } if( strcmp( str_cstr( idx->data.S ), "_G" ) == 0 ) { sgs_Release( C, out ); out->type = SVT_OBJECT; out->data.O = GLBP; sgs_Acquire( C, out ); return SGS_SUCCESS; } else if( ( pair = vht_get( ht, idx ) ) != NULL ) { sgs_Release( C, out ); *out = pair->val; sgs_Acquire( C, out ); return SGS_SUCCESS; } else { sgs_Release( C, out ); sgs_Msg( C, SGS_WARNING, "variable '%s' was not found", str_cstr( idx->data.S ) ); return SGS_ENOTFND; } } int sgsSTD_GlobalSet( SGS_CTX, sgs_Variable* idx, sgs_Variable* val ) { sgs_VarObj* data = GLBP; HTHDR; if( idx->type != SVT_STRING ) return SGS_ENOTSUP; if( strcmp( var_cstr( idx ), "_G" ) == 0 ) { int ret = sgs_SetEnv( C, val ); if( SGS_FAILED( ret ) ) sgs_Msg( C, SGS_ERROR, "_G only accepts 'dict' values" ); return ret; } vht_set( ht, C, idx, val ); return SGS_SUCCESS; } int sgsSTD_GlobalGC( SGS_CTX ) { sgs_VarObj* data = GLBP; if( data ) { if( sgs_ObjGCMark( C, data ) < 0 ) return SGS_EINPROC; } return SGS_SUCCESS; } int sgsSTD_GlobalIter( SGS_CTX, VHTVar** outp, VHTVar** outpend ) { sgs_VarObj* data = GLBP; if( data ) { HTHDR; *outp = ht->vars; *outpend = ht->vars + vht_size( ht ); return SGS_SUCCESS; } else return SGS_EINPROC; } SGSRESULT sgs_RegFuncConsts( SGS_CTX, const sgs_RegFuncConst* list, int size ) { int ret; while( size-- ) { if( !list->name ) break; sgs_PushCFunction( C, list->value ); ret = sgs_StoreGlobal( C, list->name ); if( ret != SGS_SUCCESS ) return ret; list++; } return SGS_SUCCESS; } SGSRESULT sgs_RegIntConsts( SGS_CTX, const sgs_RegIntConst* list, int size ) { int ret; while( size-- ) { if( !list->name ) break; sgs_PushInt( C, list->value ); ret = sgs_StoreGlobal( C, list->name ); if( ret != SGS_SUCCESS ) return ret; list++; } return SGS_SUCCESS; } SGSRESULT sgs_RegRealConsts( SGS_CTX, const sgs_RegRealConst* list, int size ) { int ret; while( size-- ) { if( !list->name ) break; sgs_PushReal( C, list->value ); ret = sgs_StoreGlobal( C, list->name ); if( ret != SGS_SUCCESS ) return ret; list++; } return SGS_SUCCESS; } SGSBOOL sgs_IncludeExt( SGS_CTX, const char* name, const char* searchpath ) { int ret = 0, sz; int pathrep = 0; sgs_Variable incfn; if( searchpath ) { pathrep = sgs_PushGlobal( C, "SGS_PATH" ) == SGS_SUCCESS ? 1 : 2; sgs_PushString( C, searchpath ); sgs_StoreGlobal( C, "SGS_PATH" ); } sz = sgs_StackSize( C ); sgs_PushString( C, name ); sgs_InitCFunction( &incfn, sgsstd_include ); ret = sgs_CallP( C, &incfn, 1, 1 ); if( ret == SGS_SUCCESS ) ret = sgs_GetBool( C, -1 ); else ret = 0; sgs_SetStackSize( C, sz ); if( pathrep == 1 ) sgs_StoreGlobal( C, "SGS_PATH" ); else if( pathrep == 2 ) { sgs_PushGlobal( C, "_G" ); sgs_PushString( C, "SGS_PATH" ); sgs_ObjectAction( C, -2, SGS_ACT_DICT_UNSET, -1 ); } sgs_SetStackSize( C, 0 ); return ret; } SGSMIXED sgs_ObjectAction( SGS_CTX, int item, int act, int arg ) { sgs_SizeVal i, j; switch( act ) { case SGS_ACT_ARRAY_PUSH: i = sgs_ArraySize( C, item ); j = sgs_StackSize( C ); if( i < 0 || arg > j || arg < 0 ) return SGS_EINVAL; if( arg ) { sgsstd_array_insert( C, (sgsstd_array_header_t*) sgs_GetObjectData( C, item ), i, j - arg ); sgs_Pop( C, arg ); } return SGS_SUCCESS; case SGS_ACT_ARRAY_POP: case SGS_ACT_ARRAY_POPRET: i = sgs_ArraySize( C, item ); if( i < 0 || arg > i || arg < 0 ) return SGS_EINVAL; if( arg ) { if( act == SGS_ACT_ARRAY_POPRET ) { for( j = i - arg; j < i; ++j ) sgs_PushNumIndex( C, item, j ); } sgsstd_array_erase( C, (sgsstd_array_header_t*) sgs_GetObjectData( C, item ), i - arg, i - 1 ); } return SGS_SUCCESS; case SGS_ACT_ARRAY_FIND: if( sgs_ArraySize( C, item ) < 0 ) return SGS_EINVAL; else { sgs_SizeVal off = 0; sgsstd_array_header_t* hdr = (sgsstd_array_header_t*) sgs_GetObjectData( C, item ); sgs_Variable comp; if( !sgs_PeekStackItem( C, arg, &comp ) ) return SGS_EBOUNDS; while( off < hdr->size ) { sgs_Variable* p = SGSARR_PTR( hdr ) + off; if( sgs_EqualTypes( p, &comp ) && sgs_Compare( C, p, &comp ) == 0 ) { return off; } off++; } } return SGS_ENOTFND; case SGS_ACT_ARRAY_RM_ONE: case SGS_ACT_ARRAY_RM_ALL: if( sgs_ArraySize( C, item ) < 0 ) return SGS_EINVAL; else { sgs_SizeVal off = 0, rmvd = 0; sgsstd_array_header_t* hdr = (sgsstd_array_header_t*) sgs_GetObjectData( C, item ); sgs_Variable comp; if( !sgs_PeekStackItem( C, arg, &comp ) ) return SGS_EBOUNDS; while( off < hdr->size ) { sgs_Variable* p = SGSARR_PTR( hdr ) + off; if( sgs_EqualTypes( p, &comp ) && sgs_Compare( C, p, &comp ) == 0 ) { sgsstd_array_erase( C, hdr, off, off ); rmvd++; if( act == SGS_ACT_ARRAY_RM_ONE ) break; } off++; } return rmvd; } return 0; case SGS_ACT_DICT_UNSET: if( !sgs_IsObject( C, item, sgsstd_dict_iface ) || sgs_ItemType( C, arg ) != SVT_STRING ) return SGS_EINVAL; else { sgs_Variable str; sgs_PeekStackItem( C, arg, &str ); vht_unset( &((DictHdr*)sgs_GetObjectData( C, item ))->ht, C, &str ); return SGS_SUCCESS; } case SGS_ACT_MAP_UNSET: if( !sgs_IsObject( C, item, sgsstd_map_iface ) || !sgs_IsValidIndex( C, arg ) ) return SGS_EINVAL; else { sgs_Variable key; sgs_PeekStackItem( C, arg, &key ); vht_unset( &((DictHdr*)sgs_GetObjectData( C, item ))->ht, C, &key ); return SGS_SUCCESS; } } return SGS_ENOTFND; } <file_sep>/ext/sgsmeta.c #include <sgs_int.h> int sgs_meta_globals( SGS_CTX ) { #define _META_RGS( instr ) sgs_PushInt( C, SGS_##instr ); \ sgs_StoreGlobal( C, #instr ); _META_RGS( SI_NOP ); _META_RGS( SI_PUSH ); _META_RGS( SI_RETN ); _META_RGS( SI_JUMP ); _META_RGS( SI_JMPT ); _META_RGS( SI_JMPF ); _META_RGS( SI_CALL ); _META_RGS( SI_FORPREP ); _META_RGS( SI_FORLOAD ); _META_RGS( SI_FORJUMP ); _META_RGS( SI_LOADCONST ); _META_RGS( SI_GETVAR ); _META_RGS( SI_SETVAR ); _META_RGS( SI_GETPROP ); _META_RGS( SI_SETPROP ); _META_RGS( SI_GETINDEX ); _META_RGS( SI_SETINDEX ); _META_RGS( SI_GENCLSR ); _META_RGS( SI_PUSHCLSR ); _META_RGS( SI_MAKECLSR ); _META_RGS( SI_GETCLSR ); _META_RGS( SI_SETCLSR ); _META_RGS( SI_SET ); _META_RGS( SI_MCONCAT ); _META_RGS( SI_CONCAT ); _META_RGS( SI_NEGATE ); _META_RGS( SI_BOOL_INV ); _META_RGS( SI_INVERT ); _META_RGS( SI_INC ); _META_RGS( SI_DEC ); _META_RGS( SI_ADD ); _META_RGS( SI_SUB ); _META_RGS( SI_MUL ); _META_RGS( SI_DIV ); _META_RGS( SI_MOD ); _META_RGS( SI_AND ); _META_RGS( SI_OR ); _META_RGS( SI_XOR ); _META_RGS( SI_LSH ); _META_RGS( SI_RSH ); _META_RGS( SI_SEQ ); _META_RGS( SI_SNEQ ); _META_RGS( SI_EQ ); _META_RGS( SI_NEQ ); _META_RGS( SI_LT ); _META_RGS( SI_GTE ); _META_RGS( SI_GT ); _META_RGS( SI_LTE ); _META_RGS( SI_RAWCMP ); _META_RGS( SI_ARRAY ); _META_RGS( SI_DICT ); #undef _META_RGS return 0; } static int _sgs_meta_dumpfn( SGS_CTX, sgs_iFunc* func ); static int _sgs_meta_dumpconstlist( SGS_CTX, sgs_Variable* var, size_t numvars ) { sgs_Variable* vend = var + numvars; sgs_PushArray( C, 0 ); while( var < vend ) { sgs_PushString( C, "type" ); sgs_PushInt( C, var->type ); sgs_PushString( C, "data" ); switch( var->type ) { case SGS_VT_NULL: case SGS_VT_BOOL: case SGS_VT_INT: case SGS_VT_REAL: case SGS_VT_STRING: sgs_PushVariable( C, var ); break; case SGS_VT_FUNC: if( !_sgs_meta_dumpfn( C, var->data.F ) ) return 0; break; default: return 0; } sgs_PushDict( C, 4 ); sgs_ObjectAction( C, -2, SGS_ACT_ARRAY_PUSH, 1 ); var++; } return 1; } static int _sgs_meta_dumpbclist( SGS_CTX, sgs_instr_t* data, size_t numinstr ) { sgs_instr_t* dend = data + numinstr; sgs_PushArray( C, 0 ); while( data < dend ) { sgs_instr_t i = *data++; sgs_PushString( C, "op" ); sgs_PushInt( C, SGS_INSTR_GET_OP( i ) ); sgs_PushString( C, "a" ); sgs_PushInt( C, SGS_INSTR_GET_A( i ) ); sgs_PushString( C, "b" ); sgs_PushInt( C, SGS_INSTR_GET_B( i ) ); sgs_PushString( C, "c" ); sgs_PushInt( C, SGS_INSTR_GET_C( i ) ); sgs_PushString( C, "e" ); sgs_PushInt( C, SGS_INSTR_GET_E( i ) ); sgs_PushDict( C, 10 ); sgs_ObjectAction( C, -2, SGS_ACT_ARRAY_PUSH, 1 ); } return 1; } static int _sgs_meta_dumplnlist( SGS_CTX, sgs_LineNum* data, size_t numinstr ) { sgs_LineNum* dend = data + numinstr; sgs_PushArray( C, 0 ); while( data < dend ) { sgs_PushInt( C, *data++ ); sgs_ObjectAction( C, -2, SGS_ACT_ARRAY_PUSH, 1 ); } return 1; } static int _sgs_meta_dumpfn( SGS_CTX, sgs_iFunc* func ) { int ssz = sgs_StackSize( C ); sgs_PushString( C, "consts" ); if( !_sgs_meta_dumpconstlist( C, sgs_func_consts( func ), (size_t) func->instr_off / sizeof(sgs_Variable) ) ) return 0; sgs_PushString( C, "code" ); if( !_sgs_meta_dumpbclist( C, sgs_func_bytecode( func ), (size_t) ( func->size - func->instr_off ) / sizeof(sgs_instr_t) ) ) return 0; sgs_PushString( C, "lines" ); if( !_sgs_meta_dumplnlist( C, func->lineinfo, (size_t) ( func->size - func->instr_off ) / sizeof(sgs_instr_t) ) ) return 0; sgs_PushString( C, "gotthis" ); sgs_PushBool( C, func->gotthis ); sgs_PushString( C, "numargs" ); sgs_PushInt( C, func->numargs ); sgs_PushString( C, "numtmp" ); sgs_PushInt( C, func->numtmp ); sgs_PushString( C, "numclsr" ); sgs_PushInt( C, func->numclsr ); sgs_PushString( C, "name" ); sgs_PushStringBuf( C, func->funcname.ptr, (sgs_SizeVal) func->funcname.size ); sgs_PushString( C, "line" ); sgs_PushInt( C, func->linenum ); sgs_PushDict( C, sgs_StackSize( C ) - ssz ); return 1; } static int _sgs_meta_dumpcomp( SGS_CTX, sgs_CompFunc* func ) { int ssz = sgs_StackSize( C ); sgs_PushString( C, "consts" ); if( !_sgs_meta_dumpconstlist( C, (sgs_Variable*) (void*) SGS_ASSUME_ALIGNED( func->consts.ptr, 4 ), func->consts.size / sizeof(sgs_Variable) ) ) return 0; sgs_PushString( C, "code" ); if( !_sgs_meta_dumpbclist( C, (sgs_instr_t*) (void*) SGS_ASSUME_ALIGNED( func->code.ptr, 4 ), func->code.size / sizeof(sgs_instr_t) ) ) return 0; sgs_PushString( C, "lines" ); if( !_sgs_meta_dumplnlist( C, (sgs_LineNum*) (void*) SGS_ASSUME_ALIGNED( func->lnbuf.ptr, 4 ), func->lnbuf.size / sizeof(sgs_LineNum) ) ) return 0; sgs_PushString( C, "gotthis" ); sgs_PushBool( C, func->gotthis ); sgs_PushString( C, "numargs" ); sgs_PushInt( C, func->numargs ); sgs_PushString( C, "numtmp" ); sgs_PushInt( C, func->numtmp ); sgs_PushString( C, "numclsr" ); sgs_PushInt( C, func->numclsr ); sgs_PushString( C, "name" ); sgs_PushString( C, "<main>" ); sgs_PushString( C, "line" ); sgs_PushInt( C, 0 ); sgs_PushDict( C, sgs_StackSize( C ) - ssz ); return 1; } int sgs_meta_unpack( SGS_CTX ) { int ret; char* buf; const char* bfret; sgs_SizeVal size; sgs_CompFunc* func; SGSFN( "meta_unpack" ); if( !sgs_LoadArgs( C, "m", &buf, &size ) ) return 0; ret = sgsBC_ValidateHeader( buf, (size_t) size ); if( ret < SGS_HEADER_SIZE ) return sgs_Msg( C, SGS_WARNING, "compiled code header error " "detected at position %d", ret ); bfret = sgsBC_Buf2Func( C, "", buf, (size_t) size, &func ); if( bfret ) return sgs_Msg( C, SGS_WARNING, bfret ); ret = _sgs_meta_dumpcomp( C, func ); sgsBC_Free( C, func ); if( !ret ) return sgs_Msg( C, SGS_WARNING, "internal error while converting data" ); return 1; } int sgs_meta_opname( SGS_CTX ) { const char* str; sgs_Int op; if( !sgs_LoadArgs( C, "i", &op ) ) return 0; str = sgs_CodeString( SGS_CODE_OP, (int) op ); if( str ) { sgs_PushString( C, str ); return 1; } return 0; } static sgs_RegFuncConst meta_funcs[] = { { "meta_globals", sgs_meta_globals }, { "meta_unpack", sgs_meta_unpack }, { "meta_opname", sgs_meta_opname }, SGS_RC_END() }; #ifdef SGS_COMPILE_MODULE # define meta_module_entry_point sgscript_main #endif #ifdef WIN32 __declspec(dllexport) #endif int meta_module_entry_point( SGS_CTX ) { sgs_RegFuncConsts( C, meta_funcs, -1 ); return SGS_SUCCESS; } <file_sep>/src/sgs_tok.c #include <ctype.h> #include <stdarg.h> #include <math.h> #define SGS_INTERNAL #define SGS_REALLY_INTERNAL #include "sgs_cfg.h" #include "sgs_int.h" static SGS_INLINE int detectline( const char* code, int32_t at ) { return code[ at ] == '\r' || ( code[ at ] == '\n' && ( at == 0 || code[ at - 1 ] != '\r' ) ); } static void skipcomment( SGS_CTX, MemBuf* out, LineNum* line, const char* code, int32_t* at, int32_t length ) { int32_t i = *at + 1; UNUSED( out ); if( code[ i ] == '/' ) { i++; while( i < length && code[ i ] != '\n' && code[ i ] != '\r' ) i++; if( code[ i ] == '\r' && code[ i + 1 ] == '\n' ) i++; (*line)++; *at = i; } else { LineNum init = *line; i++; while( i < length ) { if( detectline( code, i ) ) (*line)++; if( code[ i ] == '/' && i > 0 && code[ i - 1 ] == '*' ) break; else i++; } if( i == length ) { sgs_Msg( C, SGS_ERROR, "[line %d] Comment has no end", init ); *at = i - 1; } else *at = i; } } static int32_t string_inplace_fix( char* str, int32_t len ) { char *ipos = str, *opos = str, *iend = str + len; while( ipos < iend ) { if( *ipos == '\\' ) { ipos++; /* assumption that there's always a character after '\' */ if( *ipos >= '0' && *ipos <= '7' ) { int oct = *ipos++ - '0'; if( ipos < iend && *ipos >= '0' && *ipos <= '7' ){ oct *= 8; oct += *ipos++ - '0'; } if( ipos < iend && *ipos >= '0' && *ipos <= '7' ){ oct *= 8; oct += *ipos++ - '0'; } ipos--; if( oct > 0xffff ) *opos++ = (char)( oct >> 8 ); if( oct > 0xff ) *opos++ = (char)( oct >> 4 ); *opos = (char) oct; } else { switch( *ipos ) { case 'a': *opos = '\a'; break; case 'b': *opos = '\b'; break; case 'f': *opos = '\f'; break; case 'n': *opos = '\n'; break; case 'r': *opos = '\r'; break; case 't': *opos = '\t'; break; case 'v': *opos = '\v'; break; case 'x': if( ipos + 2 < iend && hexchar( ipos[1] ) && hexchar( ipos[2] ) ) { *opos = (char)( ( gethex( ipos[1] ) << 4 ) | gethex( ipos[2] ) ); ipos += 2; if( ipos + 2 < iend && hexchar( ipos[1] ) && hexchar( ipos[2] ) ) { opos++; *opos = (char)( ( gethex( ipos[1] ) << 4 ) | gethex( ipos[2] ) ); ipos += 2; } break; } /* ', ", \ too: */ default: *opos = *ipos; break; } } } else *opos = *ipos; ipos++; opos++; } /* WP: returned string can only be shorter */ return (int32_t) ( opos - str ); } static int ident_equal( const char* ptr, int size, const char* what ) { /* WP: ident limit */ int wlen = (int) strlen( what ); return size == wlen && memcmp( ptr, what, (size_t) size ) == 0; } static void readident( SGS_CTX, MemBuf* out, const char* code, int32_t* at, int32_t length ) { int32_t sz = 0; int32_t i = *at; int32_t pos_rev = (int32_t) out->size; membuf_appchr( out, C, ST_IDENT ); membuf_appchr( out, C, 0 ); while( i < length && ( isalnum( code[ i ] ) || code[ i ] == '_' ) ) { sz++; if( sz < 256 ) membuf_appchr( out, C, code[ i ] ); else if( sz == 256 ) { C->state |= SGS_HAS_ERRORS; sgs_Msg( C, SGS_ERROR, "[line %d] identifier too long", *at ); } i++; } if( sz >= 255 ) sz = 255; out->ptr[ pos_rev + 1 ] = (char) sz; if( ident_equal( out->ptr + pos_rev + 2, sz, "var" ) || ident_equal( out->ptr + pos_rev + 2, sz, "global" ) || ident_equal( out->ptr + pos_rev + 2, sz, "null" ) || ident_equal( out->ptr + pos_rev + 2, sz, "true" ) || ident_equal( out->ptr + pos_rev + 2, sz, "false" ) || ident_equal( out->ptr + pos_rev + 2, sz, "if" ) || ident_equal( out->ptr + pos_rev + 2, sz, "else" ) || ident_equal( out->ptr + pos_rev + 2, sz, "do" ) || ident_equal( out->ptr + pos_rev + 2, sz, "while" ) || ident_equal( out->ptr + pos_rev + 2, sz, "for" ) || ident_equal( out->ptr + pos_rev + 2, sz, "foreach" ) || ident_equal( out->ptr + pos_rev + 2, sz, "break" ) || ident_equal( out->ptr + pos_rev + 2, sz, "continue" ) || ident_equal( out->ptr + pos_rev + 2, sz, "function" ) || ident_equal( out->ptr + pos_rev + 2, sz, "use" ) || ident_equal( out->ptr + pos_rev + 2, sz, "return" ) || ident_equal( out->ptr + pos_rev + 2, sz, "this" ) ) { out->ptr[ pos_rev ] = ST_KEYWORD; } *at = --i; } static void readstring( SGS_CTX, MemBuf* out, LineNum* line, const char* code, int32_t* at, int32_t length ) { int32_t begln = *line; int32_t i = *at + 1; char endchr = code[ *at ]; int escaped = FALSE; if( i + 1 < length && code[i] == endchr && code[i+1] == endchr ) { /* string without escape code parsing */ int32_t beg = i + 2; i = beg + 2; while( i < length ) { char c = code[ i ]; if( detectline( code, i ) ) (*line)++; if( c == endchr && code[i-1] == endchr && code[i-2] == endchr ) { int32_t size = i - beg - 2; membuf_appchr( out, C, ST_STRING ); membuf_appbuf( out, C, (char*) &size, 4 ); membuf_appbuf( out, C, code + beg, (size_t) size ); *at = i; return; } i++; } } while( i < length ) { char c = code[ i ]; if( detectline( code, i ) ) (*line)++; if( c == '\\' ) escaped = !escaped; else if( c == endchr && !escaped ) { int32_t size = i - *at - 1, newsize; size_t numpos = out->size + 1; membuf_appchr( out, C, ST_STRING ); membuf_appbuf( out, C, (char*) &size, 4 ); membuf_appbuf( out, C, code + *at + 1, (size_t) size ); *at += size + 1; newsize = string_inplace_fix( out->ptr + numpos + 4, size ); memcpy( out->ptr + numpos, &newsize, sizeof(newsize) ); /* WP: size-newsize always non-negative */ out->size -= (size_t)( size - newsize ); return; } else escaped = FALSE; i++; } C->state |= SGS_MUST_STOP; sgs_Msg( C, SGS_ERROR, "[line %d] end of string not found", begln ); } static const char* sgs_opchars = "=<>+-*/%!~&|^.$@"; static const char* sgs_operators = "<=>;===;!==;==;!=;<=;>=;+=;-=;*=;/=;%=;&=;|=;^=;<<=;>>=;$=;" "<<;>>;&&=;||=;&&;||;<;>;=;++;--;+;-;*;/;%;&;|;^;.;$;!;~;@"; static const sgs_TokenType sgs_optable[] = { ST_OP_RWCMP, ST_OP_SEQ, ST_OP_SNEQ, ST_OP_EQ, ST_OP_NEQ, ST_OP_LEQ, ST_OP_GEQ, ST_OP_ADDEQ, ST_OP_SUBEQ, ST_OP_MULEQ, ST_OP_DIVEQ, ST_OP_MODEQ, ST_OP_ANDEQ, ST_OP_OREQ, ST_OP_XOREQ, ST_OP_LSHEQ, ST_OP_RSHEQ, ST_OP_CATEQ, ST_OP_LSH, ST_OP_RSH, ST_OP_BLAEQ, ST_OP_BLOEQ, ST_OP_BLAND, ST_OP_BLOR, ST_OP_LESS, ST_OP_GRTR, ST_OP_SET, ST_OP_INC, ST_OP_DEC, ST_OP_ADD, ST_OP_SUB, ST_OP_MUL, ST_OP_DIV, ST_OP_MOD, ST_OP_AND, ST_OP_OR, ST_OP_XOR, ST_OP_MMBR, ST_OP_CAT, ST_OP_NOT, ST_OP_INV, ST_OP_ERSUP }; static const char sgs_opsep = ';'; static int op_oneof( const char* str, const char* test, char sep, int* outlen ) { const char* pstr = str; int passed = 0, equal = 0, which = 0, len = 0; do { if( *test == sep || *test == 0 ) { if( passed == equal ) { *outlen = len; return which; } if( *test == 0 ) return -1; passed = 0; equal = 0; len = 0; pstr = str; which++; } else { len++; passed++; if( *pstr == *test ) equal++; pstr += !!*pstr; } } while( *test++ ); return -1; } static void readop( SGS_CTX, MemBuf* out, LineNum line, const char* code, int32_t* at, int32_t length ) { char opstr[ 4 ]; int32_t opsize = 0, ropsize = 0, i = *at, whichop, len = -1; memset( opstr, 0, 4 ); /* read in the operator */ while( i < length && isoneof( code[ i ], sgs_opchars ) ) { if( opsize < 3 ) opstr[ opsize++ ] = code[ i ]; ropsize++; i++; } /* test for various errors */ if( ropsize > 3 ){ *at += ropsize; goto op_read_error; } whichop = op_oneof( opstr, sgs_operators, sgs_opsep, &len ); *at += len - 1; if( whichop < 0 ) goto op_read_error; membuf_appchr( out, C, (char) sgs_optable[ whichop ] ); return; op_read_error: C->state |= SGS_HAS_ERRORS; sgs_Msg( C, SGS_ERROR, "[line %d] invalid operator found: \"%s%s\", size=%d", line, opstr, ropsize > 3 ? "..." : "", ropsize ); } TokenList sgsT_Gen( SGS_CTX, const char* code, size_t length ) { int32_t i, ilen = (int32_t) length; /* WP: code limit */ LineNum line = 1; MemBuf s = membuf_create(); membuf_reserve( &s, C, SGS_TOKENLIST_PREALLOC ); for( i = 0; i < ilen; ++i ) { LineNum tokline = line; char fc = code[ i ]; size_t isz = s.size; /* whitespace */ if( detectline( code, i ) ) line++; if( isoneof( fc, " \n\r\t" ) ) continue; /* comment */ if( fc == '/' && ( code[ i + 1 ] == '/' || code[ i + 1 ] == '*' ) ) skipcomment ( C, &s, &line, code, &i, ilen ); /* special symbol */ else if( isoneof( fc, "()[]{},;:" ) ) membuf_appchr( &s, C, fc ); /* identifier */ else if( fc == '_' || isalpha( fc ) ) readident ( C, &s, code, &i, ilen ); /* number */ else if( isdigit( fc ) ) { sgs_Int vi = 0; sgs_Real vr = 0; const char* pos = code + i; int res = util_strtonum( &pos, code + length, &vi, &vr ); if( res == 0 ) { C->state |= SGS_HAS_ERRORS; sgs_Msg( C, SGS_ERROR, "[line %d] failed to parse numeric constant", line ); } else if( res == 1 ) { membuf_appchr( &s, C, ST_NUMINT ); membuf_appbuf( &s, C, &vi, sizeof( vi ) ); } else if( res == 2 ) { membuf_appchr( &s, C, ST_NUMREAL ); membuf_appbuf( &s, C, &vr, sizeof( vr ) ); } else{ sgs_BreakIf( "Invalid return value from util_strtonum." ); } /* WP: code limit */ i = (int32_t) ( pos - code ); i--; } /* string */ else if( fc == '\'' || fc == '\"' ) readstring ( C, &s, &line, code, &i, ilen ); /* operator */ else if( isoneof( fc, sgs_opchars ) ) readop ( C, &s, line, code, &i, ilen ); /* - unexpected symbol */ else { C->state |= SGS_HAS_ERRORS; sgs_Msg( C, SGS_ERROR, "[line %d], unexpected symbol: %c", line, fc ); } if( s.size != isz ) /* write a line only if successfully wrote something (a token) */ membuf_appbuf( &s, C, &tokline, sizeof( tokline ) ); if( C->state & SGS_MUST_STOP ) break; } membuf_appchr( &s, C, ST_NULL ); return (TokenList) s.ptr; } void sgsT_Free( SGS_CTX, TokenList tlist ) { MemBuf s = membuf_partial( (char*) tlist, 0 ); membuf_destroy( &s, C ); } TokenList sgsT_Next( TokenList tok ) { sgs_BreakIf( !tok ); sgs_BreakIf( !*tok ); switch( *tok ) { case ST_IDENT: case ST_KEYWORD: return tok + tok[ 1 ] + 2 + sizeof( LineNum ); case ST_NUMREAL: case ST_NUMINT: return tok + 9 + sizeof( LineNum ); case ST_STRING: { int32_t len; ST_READINT( len, tok + 1 ); return tok + 5 + sizeof( LineNum ) + len; } default: return tok + 1 + sizeof( LineNum ); } } LineNum sgsT_LineNum( TokenList tok ) { if( !*tok ) return -1; tok = sgsT_Next( tok ); { LineNum ln; ST_READLN( ln, tok - 2 ); return ln; } } size_t sgsT_ListSize( TokenList tlist ) { size_t i = 0; while( *tlist ) { tlist = sgsT_Next( tlist ); i++; } return i; } size_t sgsT_ListMemSize( TokenList tlist ) { TokenList last = tlist; while( *last ) last = sgsT_Next( last ); return (size_t) ( last - tlist + 1 ); } static void tp_token( SGS_CTX, MemBuf* out, TokenList t ) { switch( *t ) { case ST_RBRKL: case ST_RBRKR: case ST_SBRKL: case ST_SBRKR: case ST_CBRKL: case ST_CBRKR: case ST_ARGSEP: case ST_STSEP: case ST_PICKSEP: membuf_appchr( out, C, (char) *t ); break; case ST_IDENT: case ST_KEYWORD: membuf_appbuf( out, C, t + 2, t[1] ); break; case ST_NUMREAL: { sgs_Real val; char tmp[ 1024 ]; AS_REAL( val, t+1 ); sprintf( tmp, "%g", val ); membuf_appbuf( out, C, tmp, strlen( tmp ) ); } break; case ST_NUMINT: { sgs_Int val; char tmp[ 24 ]; AS_INTEGER( val, t+1 ); sprintf( tmp, "%" PRId64, val ); membuf_appbuf( out, C, tmp, strlen( tmp ) ); } break; case ST_STRING: { int32_t i, size; ST_READINT( size, t + 1 ); TokenList buf = t + 5; for( i = 0; i < size; ++i ) { if( isgraph( buf[ i ] ) || buf[ i ] == ' ' ) membuf_appchr( out, C, (char) buf[ i ] ); else { static const char* hexdigs = "0123456789ABCDEF"; char tmp[ 4 ] = { '\\', 'x', 0, 0 }; tmp[2] = hexdigs[ (buf[i] & 0xf0) >> 4 ]; tmp[3] = hexdigs[ buf[i] & 0xf ]; membuf_appbuf( out, C, tmp, 4 ); } } } break; #define OPR( op ) membuf_appbuf( out, C, op, strlen(op) ) case ST_OP_RWCMP: OPR( "<=>" ); break; case ST_OP_SEQ: OPR( "===" ); break; case ST_OP_SNEQ: OPR( "!==" ); break; case ST_OP_EQ: OPR( "==" ); break; case ST_OP_NEQ: OPR( "!=" ); break; case ST_OP_LEQ: OPR( "<=" ); break; case ST_OP_GEQ: OPR( ">=" ); break; case ST_OP_ADDEQ: OPR( "+=" ); break; case ST_OP_SUBEQ: OPR( "-=" ); break; case ST_OP_MULEQ: OPR( "*=" ); break; case ST_OP_DIVEQ: OPR( "/=" ); break; case ST_OP_MODEQ: OPR( "%=" ); break; case ST_OP_ANDEQ: OPR( "&=" ); break; case ST_OP_OREQ: OPR( "|=" ); break; case ST_OP_XOREQ: OPR( "^=" ); break; case ST_OP_LSHEQ: OPR( "<<=" ); break; case ST_OP_RSHEQ: OPR( ">>=" ); break; case ST_OP_BLAEQ: OPR( "&&=" ); break; case ST_OP_BLOEQ: OPR( "||=" ); break; case ST_OP_CATEQ: OPR( "$=" ); break; case ST_OP_BLAND: OPR( "&&" ); break; case ST_OP_BLOR: OPR( "||" ); break; case ST_OP_LESS: OPR( "<" ); break; case ST_OP_GRTR: OPR( ">" ); break; case ST_OP_SET: OPR( "=" ); break; case ST_OP_ADD: OPR( "+" ); break; case ST_OP_SUB: OPR( "-" ); break; case ST_OP_MUL: OPR( "*" ); break; case ST_OP_DIV: OPR( "/" ); break; case ST_OP_MOD: OPR( "%" ); break; case ST_OP_AND: OPR( "&" ); break; case ST_OP_OR: OPR( "|" ); break; case ST_OP_XOR: OPR( "^" ); break; case ST_OP_LSH: OPR( "<<" ); break; case ST_OP_RSH: OPR( ">>" ); break; case ST_OP_MMBR: OPR( "." ); break; case ST_OP_CAT: OPR( "$" ); break; case ST_OP_NOT: OPR( "!" ); break; case ST_OP_INV: OPR( "~" ); break; case ST_OP_INC: OPR( "++" ); break; case ST_OP_DEC: OPR( "--" ); break; #undef OPR default: membuf_appbuf( out, C, "<error>", 7 ); break; } } static int tp_tt2i( sgs_TokenType t ) { /* 0 ident | 1 const | 2 punct | 3 op */ if( ST_ISOP( t ) ) return 3; if( t == ST_IDENT || t == ST_KEYWORD ) return 0; if( t == ST_NUMREAL || t == ST_NUMINT || t == ST_STRING ) return 1; return 2; } /* kerning table: I C P O I 1 1 0 + C 1 1 0 + P 0 0 0 + O + + + 1 */ static void tp_kerning( SGS_CTX, MemBuf* out, TokenList t1, TokenList t2, int xs ) { static const int32_t mask = 0x8033; static const int32_t maskg = 0xf8bb; int32_t m; int ty1, ty2; if( !t1 || !t2 ) return; m = xs ? maskg : mask; ty1 = tp_tt2i( *t1 ); ty2 = tp_tt2i( *t2 ); if( m & (1 << (ty1 + ty2 * 4)) ) membuf_appchr( out, C, ' ' ); } void sgsT_TokenString( SGS_CTX, MemBuf* out, TokenList tlist, TokenList tend, int xs ) { while( tlist < tend && *tlist ) { TokenList t = tlist; tlist = sgsT_Next( t ); tp_token( C, out, t ); tp_kerning( C, out, t, tlist == tend ? NULL : tlist, xs ); } } void sgsT_DumpToken( TokenList tok ) { switch( *tok ) { case ST_RBRKL: case ST_RBRKR: case ST_SBRKL: case ST_SBRKR: case ST_CBRKL: case ST_CBRKR: case ST_ARGSEP: case ST_STSEP: case ST_PICKSEP: printf( "%c", *tok ); break; case ST_IDENT: fwrite( "id(", 1, 3, stdout ); fwrite( tok + 2, 1, tok[ 1 ], stdout ); fwrite( ")", 1, 1, stdout ); break; case ST_KEYWORD: fwrite( "[", 1, 1, stdout ); fwrite( tok + 2, 1, tok[ 1 ], stdout ); fwrite( "]", 1, 1, stdout ); break; case ST_NUMREAL: { sgs_Real val; AS_REAL( val, tok + 1 ); printf( "real(%f)", val ); } break; case ST_NUMINT: { sgs_Int val; AS_INTEGER( val, tok + 1 ); printf( "int(%" PRId64 ")", val ); } break; case ST_STRING: { int32_t len; ST_READINT( len, tok + 1 ); fwrite( "str(", 1, 4, stdout ); print_safe( stdout, (const char*) tok + 5, (size_t) len ); fwrite( ")", 1, 1, stdout ); } break; #define OPR( op ) printf( "%s", op ); case ST_OP_RWCMP: OPR( "<=>" ); break; case ST_OP_SEQ: OPR( "===" ); break; case ST_OP_SNEQ: OPR( "!==" ); break; case ST_OP_EQ: OPR( "==" ); break; case ST_OP_NEQ: OPR( "!=" ); break; case ST_OP_LEQ: OPR( "<=" ); break; case ST_OP_GEQ: OPR( ">=" ); break; case ST_OP_ADDEQ: OPR( "+=" ); break; case ST_OP_SUBEQ: OPR( "-=" ); break; case ST_OP_MULEQ: OPR( "*=" ); break; case ST_OP_DIVEQ: OPR( "/=" ); break; case ST_OP_MODEQ: OPR( "%=" ); break; case ST_OP_ANDEQ: OPR( "&=" ); break; case ST_OP_OREQ: OPR( "|=" ); break; case ST_OP_XOREQ: OPR( "^=" ); break; case ST_OP_LSHEQ: OPR( "<<=" ); break; case ST_OP_RSHEQ: OPR( ">>=" ); break; case ST_OP_BLAEQ: OPR( "&&=" ); break; case ST_OP_BLOEQ: OPR( "||=" ); break; case ST_OP_CATEQ: OPR( "$=" ); break; case ST_OP_BLAND: OPR( "&&" ); break; case ST_OP_BLOR: OPR( "||" ); break; case ST_OP_LESS: OPR( "<" ); break; case ST_OP_GRTR: OPR( ">" ); break; case ST_OP_SET: OPR( "=" ); break; case ST_OP_ADD: OPR( "+" ); break; case ST_OP_SUB: OPR( "-" ); break; case ST_OP_MUL: OPR( "*" ); break; case ST_OP_DIV: OPR( "/" ); break; case ST_OP_MOD: OPR( "%" ); break; case ST_OP_AND: OPR( "&" ); break; case ST_OP_OR: OPR( "|" ); break; case ST_OP_XOR: OPR( "^" ); break; case ST_OP_LSH: OPR( "<<" ); break; case ST_OP_RSH: OPR( ">>" ); break; case ST_OP_MMBR: OPR( "." ); break; case ST_OP_ERSUP: OPR( "@" ); break; case ST_OP_CAT: OPR( "$" ); break; case ST_OP_NOT: OPR( "!" ); break; case ST_OP_INV: OPR( "~" ); break; case ST_OP_INC: OPR( "++" ); break; case ST_OP_DEC: OPR( "--" ); break; #undef OPR default: fwrite( "<invalid>", 1, 9, stdout ); break; } } void sgsT_DumpList( TokenList tlist, TokenList tend ) { printf( "\n" ); while( tlist != tend && *tlist != 0 ) { printf( " " ); sgsT_DumpToken( tlist ); tlist = sgsT_Next( tlist ); } printf( "\n\n" ); } <file_sep>/ext/sgsxgmath.h #ifndef SGSXGMATH_H #define SGSXGMATH_H #ifdef __cplusplus extern "C" { #endif #include <math.h> #include <stdarg.h> #include <sgscript.h> #ifndef XGM_VT #define XGM_VT float #endif #define XGM_SMALL_VT 0.0001f typedef struct _xgm_vtarray { XGM_VT* data; sgs_SizeVal size; sgs_SizeVal mem; } xgm_vtarray; extern sgs_ObjInterface xgm_vec2_iface[1]; extern sgs_ObjInterface xgm_vec3_iface[1]; extern sgs_ObjInterface xgm_vec4_iface[1]; extern sgs_ObjInterface xgm_aabb2_iface[1]; extern sgs_ObjInterface xgm_color_iface[1]; extern sgs_ObjInterface xgm_mat4_iface[1]; extern sgs_ObjInterface xgm_floatarr_iface[1]; SGS_APIFUNC void sgs_InitVec2( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y ); SGS_APIFUNC void sgs_InitVec3( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y, XGM_VT z ); SGS_APIFUNC void sgs_InitVec4( SGS_CTX, sgs_Variable* var, XGM_VT x, XGM_VT y, XGM_VT z, XGM_VT w ); SGS_APIFUNC void sgs_InitAABB2( SGS_CTX, sgs_Variable* var, XGM_VT x1, XGM_VT y1, XGM_VT x2, XGM_VT y2 ); SGS_APIFUNC void sgs_InitColor( SGS_CTX, sgs_Variable* var, XGM_VT r, XGM_VT g, XGM_VT b, XGM_VT a ); SGS_APIFUNC void sgs_InitMat4( SGS_CTX, sgs_Variable* var, const XGM_VT* v16f, int transpose ); SGS_APIFUNC void sgs_InitFloatArray( SGS_CTX, sgs_Variable* var, const XGM_VT* vfn, sgs_SizeVal size ); SGS_APIFUNC void sgs_InitVec2p( SGS_CTX, sgs_Variable* var, const XGM_VT* v2f ); SGS_APIFUNC void sgs_InitVec3p( SGS_CTX, sgs_Variable* var, const XGM_VT* v3f ); SGS_APIFUNC void sgs_InitVec4p( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f ); SGS_APIFUNC void sgs_InitAABB2p( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f ); SGS_APIFUNC void sgs_InitColorp( SGS_CTX, sgs_Variable* var, const XGM_VT* v4f ); SGS_APIFUNC void sgs_InitColorvp( SGS_CTX, sgs_Variable* var, const XGM_VT* vf, int numfloats ); SGS_APIFUNC void sgs_PushVec2( SGS_CTX, XGM_VT x, XGM_VT y ); SGS_APIFUNC void sgs_PushVec3( SGS_CTX, XGM_VT x, XGM_VT y, XGM_VT z ); SGS_APIFUNC void sgs_PushVec4( SGS_CTX, XGM_VT x, XGM_VT y, XGM_VT z, XGM_VT w ); SGS_APIFUNC void sgs_PushAABB2( SGS_CTX, XGM_VT x1, XGM_VT y1, XGM_VT x2, XGM_VT y2 ); SGS_APIFUNC void sgs_PushColor( SGS_CTX, XGM_VT r, XGM_VT g, XGM_VT b, XGM_VT a ); SGS_APIFUNC void sgs_PushMat4( SGS_CTX, const XGM_VT* v16f, int transpose ); SGS_APIFUNC void sgs_PushFloatArray( SGS_CTX, const XGM_VT* vfn, sgs_SizeVal size ); SGS_APIFUNC void sgs_PushVec2p( SGS_CTX, const XGM_VT* v2f ); SGS_APIFUNC void sgs_PushVec3p( SGS_CTX, const XGM_VT* v3f ); SGS_APIFUNC void sgs_PushVec4p( SGS_CTX, const XGM_VT* v4f ); SGS_APIFUNC void sgs_PushAABB2p( SGS_CTX, const XGM_VT* v4f ); SGS_APIFUNC void sgs_PushColorp( SGS_CTX, const XGM_VT* v4f ); SGS_APIFUNC void sgs_PushColorvp( SGS_CTX, const XGM_VT* vf, int numfloats ); SGS_APIFUNC SGSBOOL sgs_ParseVT( SGS_CTX, sgs_StkIdx item, XGM_VT* out ); SGS_APIFUNC SGSBOOL sgs_ParseVTP( SGS_CTX, sgs_Variable* var, XGM_VT* out ); SGS_APIFUNC SGSBOOL sgs_ParseVec2P( SGS_CTX, sgs_Variable* var, XGM_VT* v2f, int strict ); SGS_APIFUNC SGSBOOL sgs_ParseVec3P( SGS_CTX, sgs_Variable* var, XGM_VT* v3f, int strict ); SGS_APIFUNC SGSBOOL sgs_ParseVec4P( SGS_CTX, sgs_Variable* var, XGM_VT* v4f, int strict ); SGS_APIFUNC SGSBOOL sgs_ParseAABB2P( SGS_CTX, sgs_Variable* var, XGM_VT* v4f ); SGS_APIFUNC SGSBOOL sgs_ParseColorP( SGS_CTX, sgs_Variable* var, XGM_VT* v4f, int strict ); SGS_APIFUNC SGSBOOL sgs_ParseMat4P( SGS_CTX, sgs_Variable* var, XGM_VT* v16f ); SGS_APIFUNC SGSBOOL sgs_ParseFloatArrayP( SGS_CTX, sgs_Variable* var, XGM_VT** vfa, sgs_SizeVal* osz ); SGS_APIFUNC SGSBOOL sgs_ParseVec2( SGS_CTX, sgs_StkIdx item, XGM_VT* v2f, int strict ); SGS_APIFUNC SGSBOOL sgs_ParseVec3( SGS_CTX, sgs_StkIdx item, XGM_VT* v3f, int strict ); SGS_APIFUNC SGSBOOL sgs_ParseVec4( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f, int strict ); SGS_APIFUNC SGSBOOL sgs_ParseAABB2( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f ); SGS_APIFUNC SGSBOOL sgs_ParseColor( SGS_CTX, sgs_StkIdx item, XGM_VT* v4f, int strict ); SGS_APIFUNC SGSBOOL sgs_ParseMat4( SGS_CTX, sgs_StkIdx item, XGM_VT* v16f ); SGS_APIFUNC SGSBOOL sgs_ParseFloatArray( SGS_CTX, sgs_StkIdx item, XGM_VT** vfa, sgs_SizeVal* osz ); SGS_APIFUNC int sgs_ArgCheck_Vec2( SGS_CTX, int argid, va_list* args, int flags ); SGS_APIFUNC int sgs_ArgCheck_Vec3( SGS_CTX, int argid, va_list* args, int flags ); SGS_APIFUNC int sgs_ArgCheck_Vec4( SGS_CTX, int argid, va_list* args, int flags ); SGS_APIFUNC int sgs_ArgCheck_AABB2( SGS_CTX, int argid, va_list* args, int flags ); SGS_APIFUNC int sgs_ArgCheck_Color( SGS_CTX, int argid, va_list* args, int flags ); SGS_APIFUNC int sgs_ArgCheck_Mat4( SGS_CTX, int argid, va_list* args, int flags ); SGS_APIFUNC int sgs_ArgCheck_FloatArray( SGS_CTX, int argid, va_list* args, int flags ); SGS_APIFUNC int xgm_module_entry_point( SGS_CTX ); /* utility macros */ #define SGS_RETURN_VEC2( x, y ) { sgs_PushVec2( C, (XGM_VT)(x), (XGM_VT)(y) ); return SGS_SUCCESS; } #define SGS_RETURN_VEC3( x, y, z ) { sgs_PushVec3( C, (XGM_VT)(x), (XGM_VT)(y), (XGM_VT)(z) ); return SGS_SUCCESS; } #define SGS_RETURN_VEC4( x, y, z, w ) { sgs_PushVec4( C, (XGM_VT)(x), (XGM_VT)(y), (XGM_VT)(z), (XGM_VT)(w) ); return SGS_SUCCESS; } #define SGS_RETURN_AABB2( x1, y1, x2, y2 ) { sgs_PushAABB2( C, (XGM_VT)(x1), (XGM_VT)(y1), (XGM_VT)(x2), (XGM_VT)(y2) ); return SGS_SUCCESS; } #define SGS_RETURN_COLOR( r, g, b, a ) { sgs_PushColor( C, (XGM_VT)(r), (XGM_VT)(g), (XGM_VT)(b), (XGM_VT)(a) ); return SGS_SUCCESS; } #define SGS_RETURN_VEC2P( value ) { sgs_PushVec2p( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_VEC3P( value ) { sgs_PushVec3p( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_VEC4P( value ) { sgs_PushVec4p( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_AABB2P( value ) { sgs_PushAABB2p( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_COLORP( value ) { sgs_PushColorp( C, value ); return SGS_SUCCESS; } #define SGS_RETURN_MAT4( value ) { sgs_PushMat4( C, value, 0 ); return SGS_SUCCESS; } #define SGS_PARSE_VEC2( outptr, strict ) { return sgs_ParseVec2P( C, val, outptr, strict ) ? SGS_SUCCESS : SGS_EINVAL; } #define SGS_PARSE_VEC3( outptr, strict ) { return sgs_ParseVec3P( C, val, outptr, strict ) ? SGS_SUCCESS : SGS_EINVAL; } #define SGS_PARSE_VEC4( outptr, strict ) { return sgs_ParseVec4P( C, val, outptr, strict ) ? SGS_SUCCESS : SGS_EINVAL; } #define SGS_PARSE_AABB2( outptr ) { return sgs_ParseAABB2P( C, val, outptr ) ? SGS_SUCCESS : SGS_EINVAL; } #define SGS_PARSE_COLOR( outptr, strict ) { return sgs_ParseColorP( C, val, outptr, strict ) ? SGS_SUCCESS : SGS_EINVAL; } #define SGS_PARSE_MAT4( outptr ) { return sgs_ParseMat4P( C, val, outptr ) ? SGS_SUCCESS : SGS_EINVAL; } #ifdef __cplusplus } #endif #endif /* SGSXGMATH_H */ <file_sep>/ext/sgscppbctest.h #include <math.h> #include "cppbc/sgs_cppbc.h" struct Vec3 { SGS_OBJECT; Vec3( float _x, float _y, float _z ) : x(_x), y(_y), z(_z){} float _get_length(){ return (float) sqrtf(x*x+y*y+z*z); } SGS_PROPERTY float x; SGS_PROPERTY float y; SGS_PROPERTY float z; SGS_PROPERTY_FUNC( READ _get_length ) SGS_ALIAS( float length ); SGS_METHOD float getLength(){ return _get_length(); } SGS_METHOD void setLength( float len ) { if( x == 0 && y == 0 && z == 0 ) x = 1; else { float ol = _get_length(); len /= ol; } x *= len; y *= len; z *= len; } SGS_IFUNC( CONVERT ) int _convert( SGS_CTX, sgs_VarObj* data, int type ) { Vec3* V = (Vec3*) data->data; if( type == SGS_VT_STRING ) { char bfr[ 128 ]; sprintf( bfr, "Vec3(%g;%g;%g)", V->x, V->y, V->z ); sgs_PushString( C, bfr ); return SGS_SUCCESS; } return SGS_ENOTSUP; } }; <file_sep>/docs/sgscript.docs.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>SGScript documentation - v0.9.5</title> <link rel="stylesheet" type="text/css" href="docs.css"> <script type="text/javascript" src="docs.js"></script> </head><body> <h1>SGScript documentation - v0.9.5</h1><div><h2>Table of Contents</h2><ul><li><a href='#SGScript-description'>SGScript - description</a> <ul><li><a href='#Code-samples-SGScript'>Code samples - SGScript</a> </li><li><a href='#Code-samples-the-C-API'>Code samples - the C API</a> </li></ul><li><a href='#Language-reference'>Language reference</a> <ul><li><a href='#Variable-types'>Variable types</a> <ul><li><a href='#Conversion-rules'>Conversion rules</a> </li></ul><li><a href='#Code-structure'>Code structure</a> <ul><li><a href='#Constants'>Constants</a> </li><li><a href='#Identifiers'>Identifiers</a> </li><li><a href='#Expressions'>Expressions</a> </li><li><a href='#Statements'>Statements</a> </li><li><a href='#Built-in-accessors'>Built-in accessors</a> </li></ul><li><a href='#Common-constructs-in-SGScript'>Common constructs in SGScript</a> <ul><li><a href='#Basic-classes'>Basic classes</a> </li><li><a href='#Inheritance'>Inheritance</a> </li><li><a href='#Game-entities'>Game entities</a> </li></ul><li><a href='#Numeric-string-parsing-rules'>Numeric string parsing rules</a> </li></ul><li><a href='#C-API-reference'>C API reference</a> <ul><li><a href='#Constants-and-types'>Constants and types</a> <ul><li><a href='#Main-types'>Main types</a> </li><li><a href='#Error-codes'>Error codes</a> </li><li><a href='#Variable-types'>Variable types</a> </li><li><a href='#Constant-registration-types'>Constant registration types</a> </li></ul><li><a href='#Concepts-systems'>Concepts &amp; systems</a> <ul><li><a href='#Messaging-system'>Messaging system</a> </li><li><a href='#Iterator-system'>Iterator system</a> </li><li><a href='#Garbage-collection-system'>Garbage collection system</a> </li><li><a href='#Classes'>Classes</a> </li><li><a href='#Closures'>Closures</a> </li></ul><li><a href='#Functions'>Functions</a> <ul><li><a href='#Context-management'>Context management</a> </li><li><a href='#Memory-management'>Memory management</a> </li><li><a href='#Input-output'>Input / output</a> </li><li><a href='#Code-handling'>Code handling</a> </li><li><a href='#Introspection'>Introspection</a> </li><li><a href='#Execution-control'>Execution control</a> </li><li><a href='#Binding-helpers'>Binding helpers</a> </li><li><a href='#Object-type-storage'>Object type storage</a> </li><li><a href='#Variable-initialization'>Variable initialization</a> </li><li><a href='#Stack-primary-interface'>Stack primary interface</a> </li><li><a href='#Sub-item-usage'>Sub-item usage</a> </li><li><a href='#Argument-handling'>Argument handling</a> </li><li><a href='#Virtual-machine-operations'>Virtual machine operations</a> </li><li><a href='#String-helpers'>String helpers</a> </li><li><a href='#Closure-handling'>Closure handling</a> </li><li><a href='#Data-retrieval-conversion'>Data retrieval &amp; conversion</a> </li><li><a href='#Iterators'>Iterators</a> </li><li><a href='#Variable-ownership'>Variable ownership</a> </li><li><a href='#String32-optimization-interface'>String32 optimization interface</a> </li><li><a href='#Utility-functions'>Utility functions</a> </li><li><a href='#ALL-functions-A-Z'>ALL functions (A-Z)</a> </li></ul><li><a href='#Interface-implementation'>Interface implementation</a> <ul><li><a href='#C-Functions'>C Functions</a> </li><li><a href='#Object-interface'>Object interface</a> </li><li><a href='#Interaction-with-the-environment'>Interaction with the environment</a> </li></ul><li><a href='#Commonly-required-advanced-tasks'>Commonly required advanced tasks</a> </li></ul><li><a href='#Standard-library-reference'>Standard library reference</a> <ul><li><a href='#Core-library'>Core library</a> <ul><li><a href='#ALL-SGScript-core-functions-A-Z'>ALL SGScript core functions (A-Z)</a> </li></ul><li><a href='#Formatting-library-fmt'>Formatting library (&quot;fmt&quot;)</a> <ul><li><a href='#ALL-SGScript-formatting-functions-A-Z'>ALL SGScript formatting functions (A-Z)</a> </li></ul><li><a href='#I-O-library-io'>I/O library (&quot;io&quot;)</a> <ul><li><a href='#ALL-SGScript-I-O-functions-A-Z'>ALL SGScript I/O functions (A-Z)</a> </li></ul><li><a href='#Math-library-math'>Math library (&quot;math&quot;)</a> <ul><li><a href='#ALL-SGScript-math-functions-A-Z'>ALL SGScript math functions (A-Z)</a> </li></ul><li><a href='#OS-library-os'>OS library (&quot;os&quot;)</a> <ul><li><a href='#ALL-SGScript-OS-functions-A-Z'>ALL SGScript OS functions (A-Z)</a> </li></ul><li><a href='#Regular-expression-library-re'>Regular expression library (&quot;re&quot;)</a> <ul><li><a href='#ALL-SGScript-RegExp-functions-A-Z'>ALL SGScript RegExp functions (A-Z)</a> </li></ul><li><a href='#String-library-string'>String library (&quot;string&quot;)</a> <ul><li><a href='#ALL-SGScript-string-functions-A-Z'>ALL SGScript string functions (A-Z)</a> </li></ul></li></ul><li><a href='#Included-tools'>Included tools</a> <ul><li><a href='#Virtual-Machine-sgsvm'>Virtual Machine (sgsvm)</a> </li><li><a href='#Compiler-sgsc'>Compiler (sgsc)</a> </li><li><a href='#Executable-generator-for-Windows-sgsexe'>Executable generator for Windows (sgsexe)</a> </li><li><a href='#Language-test-application-sgstest'>Language test application (sgstest)</a> </li><li><a href='#API-test-application-sgsapitest'>API test application (sgsapitest)</a> </li><li><a href='#C-binding-compiler-test-application-sgscppbctest'>C++ binding compiler test application (sgscppbctest)</a> </li><li><a href='#Lightweight-C-binding-test-application-sgscppbindtest'>Lightweight C++ binding test application (sgscppbindtest)</a> </li><li><a href='#Multithreading-safety-test-application-mttest'>Multithreading safety test application (mttest)</a> </li><li><a href='#Profiler'>Profiler</a> </li><li><a href='#Interactive-debugger'>Interactive debugger</a> </li></ul><li><a href='#Additional-info'>Additional info</a> <ul><li><a href='#Serialization-in-SGScript'>Serialization in SGScript</a> </li><li><a href='#Secure-sandbox-environment'>Secure sandbox environment</a> </li></ul></li></ul></div><div> <div class='item'><a name='SGScript-description'></a><hr><h2>SGScript - description</h2><p> This is a programming language that is made to be fast, accessible and simple. </p><pre>include &quot;math&quot;; gradient = [ &quot;.&quot;, &quot;o&quot;, &quot;O&quot;, &quot;#&quot;, &quot;O&quot;, &quot;o&quot;, &quot;.&quot; ]; for( y = -7; y &lt;= 7; ++y ) { for( x = -7; x &lt;= 7; ++x ) { dst = sqrt( x * x + y * y ) * 0.9; if( dst &gt; 6 ) dst = 6; chr = gradient[ dst ]; print chr $ &#39; &#39;; } println(); }</pre><p> It is similar to many but the exact combination makes it unique in comparison to others. Thus, it might be best to describe it in comparison to others, especially the ones that heavily influenced the development of SGScript. </p><p> <table> <tr><th>language</th><th>what it DOESN&#39;T have in comparison to SGScript</th></tr> <tr><td>C</td><td>dynamic typing, built-in serialization</td></tr> <tr><td>Lua</td><td>built-in serialization, C-like syntax, proper indexing, arrays, ...</td></tr> <tr><td>PHP</td><td>consistency, lightweight design</td></tr> <tr><td>JavaScript</td><td>environmental awareness, determinism, built-in serialization, ...</td></tr> <tr><td>Python</td><td>C-like syntax, lightweight design</td></tr> </table> </p><p> With this in mind, technologies get upgraded occasionally, thus be sure to take this comparison with a grain of salt and recheck it and perhaps even report the factual errors along with the version number that marked the introduction of changes. </p><p> However, SGScript has all of the things mentioned, and some more, possibly making it one of the most balanced languages ever created. </p><p> The language supports: </p><ul><li><code>if/else</code>, <code>while</code>, <code>for</code>, <code>do/while</code>, <code>foreach</code> </li><li>9 variable types: null, bool, int, real, string, function, C function, object, pointer </li><li>Multi-level break/continue </li><li>Multiple return values </li><li>First-class functions and ability to attach variables to functions (creating closures)</li></ul><p> The standard library includes: </p><ul><li>array, dict, map, class </li><li>math, string, I/O, O/S and formatting functions </li><li><code>eval</code>, file import, DLL import</li></ul></div> <div class='item'><a name='Code-samples-SGScript'></a><hr><h2>Code samples - SGScript</h2><h4>Statements</h4><pre>print &quot;Text&quot;; println( &quot;!&quot; ); b = rand();</pre><h4>Comments</h4><pre>// this is a comment that ends with the line /* this type of comment can be more than one line long */</pre><h4>Basic calculations</h4><pre>a = 1, b = 2, c = 5; d = a + b * c - b / a; a += 3.14; c = &quot;eye&quot; $ &quot;sight&quot; // stitch (concatenate) strings together! d = &quot;Ocean&#39;s &quot; $ 11;</pre><h4>Comparison</h4><pre>if( c &gt; 5 ) print &quot;as expected&quot;; y = x &lt;= 8.8; // result of comparison can be assigned!</pre><h4>Useful shortcuts</h4><pre>a += 1; // short for a = a + 1 a++; // short for a += 1 a--; a = if( b &gt; 5, 10, 20 ); // short for if( b &gt; 5 ){ a = 10; } else { a = 20; }</pre><h4>Flow control</h4><pre>if( a &gt; b ) { print &quot;something happens only if a is greater than b&quot;; } else print &quot;...and here the opposite is true&quot;; while( a &gt; b ) { print &quot;something happens as long as a is greater than b&quot;; a--; // but not for too long, as we see } // or maybe ... do { // first we do print a; } while( a++ &lt; 10 ); // then we check</pre><h4>More useful shortcuts</h4><pre>for( i = 0; i &lt; 10; i++ ) print i; // .. is the short form for .. i = 0; while( i &lt; 10 ) { print i; i++; } for(;;) // this is not going to stop... print &quot;x&quot;;</pre><h4>More flow control</h4><pre>x = 5; for(;;) { print x; x--; if( x &lt; 0 ) break; // this says that we don&#39;t want to continue staying in the loop } // &lt;&lt; this is where &quot;break&quot; leads us, right after the loop // this goes through a list foreach( fruit : [ &quot;apple&quot;, &quot;orange&quot;, &quot;banana&quot; ] ) println( fruit ); // .. of 2 items .. list = { &quot;1&quot; = &quot;apple&quot;, &quot;2&quot; = &quot;orange&quot;, &quot;3&quot; = &quot;banana&quot; }; foreach( number, fruit : list ) println( number $ &quot;. &quot; $ fruit );</pre><h4>Functions</h4><pre>// cornerstore of reusable code function square( x ) { return x * x; } print square( 5 ); function print_quoted( text ) { print &#39;&quot;&#39; $ text $ &#39;&quot;&#39;; } print_quoted( &quot;It works!&quot; );</pre><h4>Objects</h4><pre>a = [ 1, 2, &quot;three&quot; ]; a[2] = 3; a[1]++; d = { name = &quot;test&quot;, text = &quot;hello&quot;, }; d.name = &quot;<NAME>&quot;; d.text $= &quot;, world!&quot;; println( d.text ); // hello, world!</pre><h4>Interesting stuff</h4><pre>printvar( x ); // tells you all you want to know about &quot;x&quot; // emits an error with the given message if the first argument is false assert( x &gt; 5, &quot;x must be greater than 5&quot; ); // returns the type name typeof( x ); // universal external code loader include &quot;math&quot;, &quot;string&quot;, &quot;something&quot;;</pre></div> <div class='item'><a name='Code-samples-the-C-API'></a><hr><h2>Code samples - the C API</h2><h4>Primary operations</h4><pre>// create the context sgs_Context* C = sgs_CreateEngine(); // load the built-in math library sgs_LoadLib_Math( C ); // load a file sgs_ExecFile( C, &quot;script.sgs&quot; ); // call a global function with 0 arguments, expecting 0 values returned sgs_GlobalCall( C, &quot;myFunction&quot;, 0, 0 ); // destroy the context sgs_DestroyEngine( C );</pre><h4>Data in, data out</h4><pre>sgs_Context* C = sgs_CreateEngine(); sgs_LoadLib_Math( C ); // push a variable on the stack sgs_PushReal( C, 3.14 ); // call a global function with 1 argument, expecting 1 value returned sgs_GlobalCall( C, &quot;sin&quot;, 1, 1 ); // check the returned value printf( &quot;returned value: %f\n&quot;, sgs_GetReal( C, -1 ) ); // clean the stack sgs_SetStackSize( C, 0 );</pre></div> <div class='item'><a name='Language-reference'></a><hr><h2>Language reference</h2></div> <div class='item'><a name='Variable-types'></a><hr><h2>Variable types</h2><p> SGScript has 8 primary variable types: </p><ul><li><code>null</code>: the &#39;lack of a better value&#39; type </li><li><code>bool</code>: boolean, true/false </li><li><code>int</code>: signed integer </li><li><code>real</code>: floating point number </li><li><code>string</code>: byte buffer </li><li><code>(SGS) function</code>: function that was defined in and compiled from SGScript code </li><li><code>C function</code>: function defined in C code </li><li><code>object</code>: the extension type and container for complex built-in types</li></ul><p> Extended variable types (built on <code>object</code>): </p><ul><li><code>array</code>: a dynamically allocated variable array </li><li><code>dict</code>: a map/table structure where variables are mapped to string keys </li><li><code>map</code>: a map/table structure where variables are mapped to variable keys </li><li><code>class</code>: object that uses two other objects to build its interface </li><li><code>closure</code>: a callable object consisting of another callable and several variables</li></ul></div> <div class='item'><a name='Conversion-rules'></a><hr><h2>Conversion rules</h2><p> <table> <tr><th>from \ to</th><th>bool</th><th>int</th><th>real</th><th>string</th><th>ptr</th></tr> <tr><td>null</td><td>false</td><td>0</td><td>0.0</td><td>&quot;null&quot;</td><td>NULL</td></tr> <tr><td>bool</td><td>-</td><td>0/1</td><td>0.0/1.0</td><td>&quot;false&quot;/&quot;true&quot;</td><td>NULL/0x1</td></tr> <tr><td>int</td><td>0 =&gt; false, otherwise true</td><td>-</td><td>-</td><td>-</td><td>cast</td></tr> <tr><td>real</td><td>0.0 =&gt; false, otherwise true</td><td>round to nearest</td><td>-</td><td>sprintf %g</td><td>cast</td></tr> <tr><td>string</td><td>empty =&gt; false, otherwise true</td><td>*1</td><td>*1</td><td>-</td><td>char*</td></tr> <tr><td>func</td><td>true</td><td>0</td><td>0.0</td><td>&quot;function&quot;</td><td>NULL</td></tr> <tr><td>cfunc</td><td>true</td><td>0</td><td>0.0</td><td>&quot;C function&quot;</td><td>NULL</td></tr> <tr><td>object *2</td><td>true</td><td>0</td><td>0.0</td><td>&quot;object&quot;</td><td>data ptr.</td></tr> <tr><td>ptr</td><td>NULL =&gt; false, otherwise true</td><td>cast</td><td>cast</td><td>sprintf ptr(%p)</td><td>-</td></tr> </table> </p><ul><li>&quot;-&quot; means the conversion is not necessary, does not affect data or the effect of conversion should be immediately obvious </li><li>*1) see <a href="#Numeric-string-parsing-rules">Numeric string parsing rules</a> for more info </li><li>*2) these are the default values, overrides can be provided in CONVERT function and type name for string</li></ul></div> <div class='item'><a name='Code-structure'></a><hr><h2>Code structure</h2><p> Code can contain constants, identifiers, expressions and statements. Statements usually include expressions but expressions can also include statements, specifically - function expressions. </p></div> <div class='item'><a name='Constants'></a><hr><h2>Constants</h2><p> Available constant formats: </p><p> <table> <tr><th>type</th><th>subtype</th><th>examples</th></tr> <tr><td>null</td><td>-</td><td>null</td></tr> <tr><td>bool</td><td>-</td><td>true, false</td></tr> <tr><td>int</td><td>decimal</td><td>1413, -583, 0</td></tr> <tr><td>int</td><td>binary</td><td>0b0101, 0b11</td></tr> <tr><td>int</td><td>octal</td><td>0o644, 0o1, 0o77</td></tr> <tr><td>int</td><td>hexadecimal</td><td>0x1f, 0xCA5</td></tr> <tr><td>real</td><td>basic</td><td>0.14, -25.48</td></tr> <tr><td>real</td><td>scientific</td><td>1.5e-5, 1e+10</td></tr> <tr><td>string</td><td>normal</td><td>&quot;text&quot;, &#39;1\n2&#39;</td></tr> <tr><td>string</td><td>unescaped*</td><td>&quot;&quot;&quot;text&quot;&quot;&quot;, &#39;&#39;&#39;1\2&#39;&#39;&#39;</td></tr> </table> </p><p> *) unescaped strings don&#39;t parse their contents at all, and the ending markers (&quot;&quot;&quot; or &#39;&#39;&#39;) cannot be escaped </p></div> <div class='item'><a name='Identifiers'></a><hr><h2>Identifiers</h2><p> Identifiers can contain letters (a-z, A-Z), numbers (0-9) or underscores (&quot;_&quot;) but they cannot begin with a number. </p><p> Special keywords and hardcoded constants: </p><p> <table> <tr><th>name</th><th>type</th><th>usage</th></tr> <tr><td>this</td><td>special identifier, read-only</td><td>method context retrieval</td></tr> <tr><td>_G</td><td>special identifier, read/write</td><td>global environment access</td></tr> <tr><td>null</td><td>constant</td><td>constant</td></tr> <tr><td>true</td><td>constant</td><td>constant</td></tr> <tr><td>false</td><td>constant</td><td>constant</td></tr> <tr><td>var</td><td>restricted keyword</td><td>variable declaration</td></tr> <tr><td>global</td><td>restricted keyword</td><td>variable declaration</td></tr> <tr><td>function</td><td>restricted keyword</td><td>function definition</td></tr> <tr><td>use</td><td>restricted keyword</td><td>function definition</td></tr> <tr><td>if</td><td>restricted keyword</td><td>&quot;if&quot; statement</td></tr> <tr><td>else</td><td>restricted keyword</td><td>&quot;if/else&quot; statement</td></tr> <tr><td>do</td><td>restricted keyword</td><td>&quot;do/while&quot; statement</td></tr> <tr><td>while</td><td>restricted keyword</td><td>&quot;while&quot;, &quot;do/while&quot; statements</td></tr> <tr><td>for</td><td>restricted keyword</td><td>&quot;for&quot; statement</td></tr> <tr><td>foreach</td><td>restricted keyword</td><td>&quot;foreach&quot; statement</td></tr> <tr><td>break</td><td>restricted keyword</td><td>&quot;break&quot; statement</td></tr> <tr><td>continue</td><td>restricted keyword</td><td>&quot;continue&quot; statement</td></tr> <tr><td>return</td><td>restricted keyword</td><td>&quot;return&quot; statement</td></tr> </table> </p></div> <div class='item'><a name='Expressions'></a><hr><h2>Expressions</h2><p> Expressions can be categorized in many different ways: type of action, appearance, whether it also assigns the value somewhere or if its purpose has a special meaning. </p><p> There are 5 types of action for expressions in SGScript: arithmetic, binary, boolean, comparison and special. </p><p> <table> <tr><th>expression</th><th>appearance</th><th>type of action</th><th>assign</th><th># in.</th></tr> <tr><td>add</td><td><code> A + B </code></td><td>arithmetic</td><td>no</td><td>2</td></tr> <tr><td>subtract</td><td><code> A - B </code></td><td>arithmetic</td><td>no</td><td>2</td></tr> <tr><td>multiply</td><td><code> A * B </code></td><td>arithmetic</td><td>no</td><td>2</td></tr> <tr><td>divide</td><td><code> A / B </code></td><td>arithmetic</td><td>no</td><td>2</td></tr> <tr><td>modulo</td><td><code> A % B </code></td><td>arithmetic</td><td>no</td><td>2</td></tr> <tr><td>pre-increment</td><td><code> ++ A </code></td><td>arithmetic</td><td>self</td><td>1</td></tr> <tr><td>pre-decrement</td><td><code> -- A </code></td><td>arithmetic</td><td>self</td><td>1</td></tr> <tr><td>post-increment</td><td><code> A ++ </code></td><td>arithmetic</td><td>self</td><td>1</td></tr> <tr><td>post-decrement</td><td><code> A -- </code></td><td>arithmetic</td><td>self</td><td>1</td></tr> <tr><td>add-assign</td><td><code> A += B </code></td><td>arithmetic</td><td>yes</td><td>2</td></tr> <tr><td>subtract-assign</td><td><code> A -= B </code></td><td>arithmetic</td><td>yes</td><td>2</td></tr> <tr><td>multiply-assign</td><td><code> A *= B </code></td><td>arithmetic</td><td>yes</td><td>2</td></tr> <tr><td>divide-assign</td><td><code> A /= B </code></td><td>arithmetic</td><td>yes</td><td>2</td></tr> <tr><td>modulo-assign</td><td><code> A %= B </code></td><td>arithmetic</td><td>yes</td><td>2</td></tr> <tr><td>binary AND</td><td><code> A &amp; B </code></td><td>binary</td><td>no</td><td>2</td></tr> <tr><td>binary OR</td><td><code> A | B </code></td><td>binary</td><td>no</td><td>2</td></tr> <tr><td>binary XOR</td><td><code> A ^ B </code></td><td>binary</td><td>no</td><td>2</td></tr> <tr><td>left shift</td><td><code> A &lt;&lt; B </code></td><td>binary</td><td>no</td><td>2</td></tr> <tr><td>right shift</td><td><code> A &gt;&gt; B </code></td><td>binary</td><td>no</td><td>2</td></tr> <tr><td>binary AND-assign</td><td><code> A &amp;= B </code></td><td>binary</td><td>yes</td><td>2</td></tr> <tr><td>binary OR-assign</td><td><code> A |= B </code></td><td>binary</td><td>yes</td><td>2</td></tr> <tr><td>binary XOR-assign</td><td><code> A ^= B </code></td><td>binary</td><td>yes</td><td>2</td></tr> <tr><td>left shift-assign</td><td><code> A &lt;&lt;= B </code></td><td>binary</td><td>yes</td><td>2</td></tr> <tr><td>right shift-assign</td><td><code> A &gt;&gt;= B </code></td><td>binary</td><td>yes</td><td>2</td></tr> <tr><td>binary invert</td><td><code> ~ A </code></td><td>binary</td><td>no</td><td>1</td></tr> <tr><td>boolean AND</td><td><code> A &amp;&amp; B </code></td><td>boolean</td><td>no</td><td>2</td></tr> <tr><td>boolean OR</td><td><code> A || B </code></td><td>boolean</td><td>no</td><td>2</td></tr> <tr><td>boolean AND-assign</td><td><code> A &amp;&amp;= B </code></td><td>boolean</td><td>yes</td><td>2</td></tr> <tr><td>boolean OR-assign</td><td><code> A ||= B </code></td><td>boolean</td><td>yes</td><td>2</td></tr> <tr><td>boolean invert</td><td><code> ! A </code></td><td>boolean</td><td>no</td><td>1</td></tr> <tr><td>less than</td><td><code> A &lt; B </code></td><td>comparison</td><td>no</td><td>2</td></tr> <tr><td>less than or equal</td><td><code> A &lt;= B </code></td><td>comparison</td><td>no</td><td>2</td></tr> <tr><td>greater than</td><td><code> A &gt; B </code></td><td>comparison</td><td>no</td><td>2</td></tr> <tr><td>greater than or equal</td><td><code> A &gt;= B </code></td><td>comparison</td><td>no</td><td>2</td></tr> <tr><td>equal</td><td><code> A == B </code></td><td>comparison</td><td>no</td><td>2</td></tr> <tr><td>not equal</td><td><code> A != B </code></td><td>comparison</td><td>no</td><td>2</td></tr> <tr><td>strict equality</td><td><code> A === B </code></td><td>comparison</td><td>no</td><td>2</td></tr> <tr><td>strict inequality</td><td><code> A !== B </code></td><td>comparison</td><td>no</td><td>2</td></tr> <tr><td>raw comparison</td><td><code> A &lt;=&gt; B </code></td><td>comparison</td><td>no</td><td>2</td></tr> <tr><td>error suppression</td><td><code> @ A </code></td><td>special</td><td>no</td><td>1</td></tr> <tr><td>declare-local</td><td><code> var A </code></td><td>special</td><td>maybe</td><td>any</td></tr> <tr><td>declare-global</td><td><code> global A </code></td><td>special</td><td>maybe</td><td>any</td></tr> <tr><td>array literal</td><td><code> [ A, B, .. ] </code></td><td>special</td><td>no</td><td>any</td></tr> <tr><td>dict. literal</td><td><code> {A=1,B=2,..} </code></td><td>special</td><td>no</td><td>any</td></tr> <tr><td>assign</td><td><code> A = B </code></td><td>special</td><td>yes</td><td>1</td></tr> <tr><td>concatenate</td><td><code> A $ B </code></td><td>special</td><td>no</td><td>2</td></tr> <tr><td>concatenate-assign</td><td><code> A $= B </code></td><td>special</td><td>yes</td><td>2</td></tr> <tr><td>property</td><td><code> A . B </code></td><td>special</td><td>maybe</td><td>2</td></tr> <tr><td>index</td><td><code> A [ B ] </code></td><td>special</td><td>maybe</td><td>2</td></tr> <tr><td>multi-index-assign</td><td><code> A[]&lt;dict.lit&gt;</code></td><td>special</td><td>yes</td><td>any</td></tr> <tr><td>multi-property-assign</td><td><code> A.&lt;dict.lit&gt; </code></td><td>special</td><td>yes</td><td>any</td></tr> <tr><td>function call</td><td><code> A ([B,..]) </code></td><td>special</td><td>no</td><td>&lt;=256</td></tr> <tr><td>comp. function call</td><td><code> O!A ([B,..]) </code></td><td>special</td><td>no</td><td>&lt;=256</td></tr> <tr><td>function definition</td><td><code> function A.. </code></td><td>special</td><td>maybe</td><td>0</td></tr> <tr><td>inline if</td><td><code> if(A,B,C) </code></td><td>special</td><td>no</td><td>3(2)</td></tr> <tr><td>subexpression</td><td><code> ( A[, ..] ) </code></td><td>special</td><td>maybe</td><td>any</td></tr> </table> </p><p> Some notes on the special cases: </p><ul><li>[increment,decrement] pre-increment and pre-decrement operators return the modified value, post- operators - the original one </li><li>[boolean] all boolean operators except &#39;boolean invert&#39; (which returns bool) set/return one of the two operands passed </li><li>[equality] strict (in)equality operators are the same as their non-strict counterparts with one difference: they do type checking, for example <code>5 == 5.0</code> would return &#39;true&#39; and <code>5 === 5.0</code> would return &#39;false&#39; </li><li>[declare] declarations only actually set the data if they include the assignment expression, otherwise only the type is internally noted for other references </li><li>[declare] variables can be redeclared as long as they maintain their access level </li><li>[property,index] whether property or index expressions set data depends if they&#39;re on the receiving (left) end of an assignment expression </li><li>[inline if] 3 inputs are required, 2 are actually used (as if <code>if(A){return B;}else{return C;}</code> was used) </li><li>[subexpression] subexpressions can set data if they are set up like this: &lt;subexpression&gt; = &lt;function-call&gt; - this is the way to read more than one return value from a function </li><li>[error suppression] the <code>@</code> operator disables warnings, errors and any other messages for as long as the subexpression is executed, this is mostly useful for things like reading a property or calling a function that may not exist, in cases where that isn&#39;t an error </li><li>[function] the full function definition expression syntax: <code>function &lt;name&gt; ( &lt;args&gt; ) [ use ( &lt;use-list&gt; ) ]</code>, followed by either <code>{ ... }</code> or <code>= ... ;</code>. &lt;name&gt;, &lt;args&gt; and the &#39;use&#39; block are all optional. </li><li>[multi-set] operator returns <code>A</code>, that is, the object itself</li></ul><h5>compatible function call / inheritance call / global method call (<code> O!A ([B,..]) </code>)</h5><p> CFC is created to encourage users to reduce memory usage without sacrificing clarity of code. It is a short-hand, optimized version of the .call method / sys_call function for callables. </p><p> Properties: </p><ul><li>uses the same symbol as boolean inversion operator </li><li>usage: simplified &amp; optimized calling of non-integrated compatible functions <ul><li>instead of <code>comp_func.call( object, arg1 )</code> write <code>object!comp_func( arg1 )</code> </li><li>instead of putting functions with data / class interfaces, requiring pointless memory usage, allows to easily keep them separate </li><li>simplify inheritance-like code models to the extent permitted by a dynamic language</li></ul></li></ul><p> Example WITHOUT: </p><pre>function create_object() { object = { x = 0, y = 0 }; function object.move( x, y ){ this.x = x; this.y = y; @this.move_callback(); } function object.tick( delta ){ this.move( this.x + delta, this.y ); } return object; }</pre><p> Example WITH: </p><pre>function Object_Move( x, y ){ this.x = x; this.y = y; @this.move_callback(); } function create_object() { object = { x = 0, y = 0 }; function object.tick( delta ){ this!Object_Move( this.x + delta, this.y ); } return object; }</pre><p> Now, by itself it may not mean much, however let&#39;s see what happens if the following code is used: </p><pre>for( i = 0; i &lt; 100; ++i ) objects.push( create_object() );</pre><p> Without the usage of a global method, there&#39;s a key &#39;move&#39; in each object that points to the function. In real software there may be no less than 10 such keys in many instances of many objects. And if there are no overrides planned for it, there&#39;s no need for it to be there but we can&#39;t really move it. Classes are an option that involves a few more allocations and it requires more memory to use them. Using <code>.call/sys_call</code> or replacing <code>this</code> with an argument would sacrifice readability and the option to relocate functions, as well as performance, this being a double call. This is where CFC comes in - syntax allows to clearly state the object and function used, and the required interface for the object to be compatible with said function. </p></div> <div class='item'><a name='Statements'></a><hr><h2>Statements</h2><p> There are 4 statement types in SGScript: </p><h4>Container statements</h4><p> There are two types of container statements: expression statements and block statements. </p><ul><li>Expression statements contain zero or more expressions, separated by commas (&quot;,&quot;) and ending with semicolons (&quot;;&quot;). </li><li>Block statements contain zero or more statements.</li></ul><p> Format: </p><ul><li>expression statement: <code>&lt;expression&gt;[, &lt;expression&gt;[, &lt;expression&gt; ...]] ;</code> </li><li>block statement: <code>{ [&lt;statement&gt;[, &lt;statement&gt;...]] }</code></li></ul><p> Examples: </p><pre>a = 5; a = 1, b = 2;</pre><h4>Flow control statements</h4><p> These statements decide which code gets executed when. They include loops (while, for, foreach, do/while), the if/else construct, break/continue/return. </p><p> Formats: </p><ul><li>if/else: <code>if( &lt;expression&gt; ) &lt;statement&gt; [ else &lt;statement&gt; ]</code> </li><li>while: <code>while( &lt;expression&gt; ) &lt;statement&gt;</code> </li><li>for: <code>for( &lt;expression-list&gt;; &lt;expression-list&gt;; &lt;expression-list&gt; ) &lt;statement&gt;</code> </li><li>foreach: <code>foreach( [&lt;identifier&gt;,][&lt;identifier&gt;] : &lt;expression&gt; ) &lt;statement&gt;</code> </li><li>do/while: <code>do &lt;statement&gt; while( &lt;expression&gt; )</code> </li><li>break: <code>break &lt;N&gt;;</code> </li><li>continue: <code>continue &lt;N&gt;;</code> </li><li>return: <code>return &lt;expression-list&gt;;</code></li></ul><p> Examples: </p><pre>if( a ) { print( &quot;a is true&quot; ); } else print( &quot;a is not true&quot; ); while( b &gt; 0 ) b--;</pre><h4>Declaration statements</h4><p> Statements that begin with &quot;var&quot;, &quot;global&quot; or &quot;function&quot; declare and set variables. </p><p> Examples: </p><pre>var x = 5, y = 6, z; global World = null; function fn(){ INFO( &quot;&#39;fn&#39; was called&quot; ); }</pre><h4>Function call statements</h4><p> These statements are converted directly to function calls. Currently, &#39;include&#39; and &#39;print&#39; functions are available as statements. </p><p> Formats: </p><ul><li>include: <code>include [&lt;file1&gt;[, &lt;file2&gt;...]];</code> - for each entry, a function call is generated </li><li>print: <code>print [&lt;string&gt;[, &lt;string&gt;...]];</code> - one function call is generated for all items</li></ul><p> Examples: </p><pre>include &quot;io&quot;, &quot;string&quot;; print &quot;Count: &quot;, count;</pre></div> <div class='item'><a name='Built-in-accessors'></a><hr><h2>Built-in accessors</h2><p> There are several built-in accessors for the variable types that are available. </p><p> <table> <tr><th>name</th><th>variable type</th><th>accessor type</th><th>description</th></tr> <tr><td>length</td><td>string</td><td>property</td><td>returns the length of the string, in bytes</td></tr> <tr><td>char. at</td><td>string</td><td>index</td><td>returns the character from the specified position</td></tr> <tr><td>call</td><td>any callable</td><td>property</td><td>function that allows to specify &quot;this&quot; for the call</td></tr> </table> </p></div> <div class='item'><a name='Common-constructs-in-SGScript'></a><hr><h2>Common constructs in SGScript</h2><p> This section shows some ways of implementing various often-used constructs in SGScript. Some of them (specifically the constructs coming from compiled languages) do not map directly to any set of native features and are considered solutions of lower quality. </p></div> <div class='item'><a name='Basic-classes'></a><hr><h2>Basic classes</h2><pre>global SampleClass = {}; // create a placeholder type dictionary function SampleClass.SampleMethod( a, b ) // this is the name that will show up in debug output { return a + b + this.c; // usage of &quot;this&quot; turns the function into a method } function SampleClass.SampleFunction( a, b ) { return a + b; } // Function will show up as &quot;&lt;anonymous&gt;&quot; in debug output, so avoid this kind of function declaration if possible SampleClass.SampleAnonymous = function( a, b ) { return a + b + this.c; }; // &lt;-- the semicolon is required for this notation // Giving functions a specific name: function MyCustomFunction( a, b ) { return a + b + this.c; // note that it is still possible to use &quot;this&quot; } SampleClass.Sample = MyCustomFunction; SampleClass.StaticVariable = 5; // class instantiation without custom data myclass = class( {}, SampleClass ); // class instantiation with custom data CustomData = { c = 5, d = 6 }; mydataclass = class( CustomData, SampleClass ); // static construction function function SampleClass.Create( x ) { data = { c = x }; return class( data, SampleClass ); } // make class interface into a construction function function SampleClass.__call( x ) { return SampleClass.Create( x ); } SampleClass = class( null, SampleClass ); // Be aware that this method involves some runtime overhead. // Prefer simply giving the construction function (or the interface variable) a different name: function createSampleClass( x ) { data = { c = x }; return class( data, SampleClass ); } // destructor function SampleClass.__destruct() { this.c = null; } // many more special methods are available for &#39;class&#39; objects</pre></div> <div class='item'><a name='Inheritance'></a><hr><h2>Inheritance</h2><pre>// class A - base class global A = {}; function A.func() { println( &quot;base&quot; ); } function A.create() { return class( {}, A ); } // class B - inherits from A global B = {}; function B.func() { // needless to say, this is not the preferred way to do software design in SGScript this._super._super.func.call( this ); println( &quot;override&quot; ); } A.func_A = A.func; // make a duplicate entry that will not be overridden // it is usually preferred to make the duplicates near the original entries where they&#39;re expected to be overridden function B.func() { B.func_A(); // call that entry instead of the original, obstructed entry println( &quot;override&quot; ); } function B.create() { return class( {}, class( B, A ) ); }</pre></div> <div class='item'><a name='Game-entities'></a><hr><h2>Game entities</h2><p> With game entities and objects of similar structure (just about any object) it is easier to simply define it as a key-value data map, without any classes, inheritance or anything of that kind. The nature of a dynamically typed scripting engine implies that almost everything is checked at runtime, making emulation of compiled language constructs pointless. </p><pre>entity = { x = 10, y = 20, }; function entity.tick( dt ) { this.x += dt; }</pre></div> <div class='item'><a name='Numeric-string-parsing-rules'></a><hr><h2>Numeric string parsing rules</h2><p> &quot;&gt;&gt;&gt;&quot; means &quot;until any other symbol has been found&quot; (the text is too dense for exact repetition) </p><p> The string is not a number if no numeric characters (0-9) could be parsed. (for example, &quot;+&quot; isn&#39;t a number but &quot;0x&quot; is) </p><ul><li>if string begins with 0b and has at least 3 characters, try to read a binary integer <ul><li>&gt;&gt;&gt;, 0 or 1 adds the specified bit to the integer </li></ul><li>if string begins with 0o and has at least 3 characters, try to read an octal integer <ul><li>&gt;&gt;&gt;, characters 0-7 add the specified 3 bits to the integer </li></ul><li>if string begins with 0x and has at least 3 characters, try to read a hexadecimal integer <ul><li>&gt;&gt;&gt;, characters 0-9, a-f and A-F add the specified 4 bits to the integer </li></ul><li>otherwise, try to read a decimal number <ul><li>do a test to see if the number is not an integer <ul><li>skip the sign character (+ or -) </li><li>skip the 0-9 characters </li><li>if e, E or . is found, try to read a real value <ul><li>read the sign character (+ or -) </li><li>&gt;&gt;&gt;, characters 0-9 add the specified decimal number to the whole part </li><li>if the dot character (.) is found, read the fractional part <ul><li>&gt;&gt;&gt;, characters 0-9 add the specified decimal number to the fractional part </li></ul><li>if at least 3 more characters can be found and the first is &quot;e&quot; or &quot;E&quot;, read the exponent part <ul><li>read the sign character (+ or -) </li><li>&gt;&gt;&gt;, characters 0-9 add the specified decimal number to the exponent part </li></ul></li></ul><li>otherwise, try to read the integer <ul><li>read the sign character (+ or -) </li><li>&gt;&gt;&gt;, characters 0-9 add the specified decimal number to the integer</li></ul></li></ul></li></ul></li></ul></div> <div class='item'><a name='C-API-reference'></a><hr><h2>C API reference</h2><p> The interface that it defines is one of the driving forces of SGScript. It is heavily influenced by Lua, while also adding some features of PHP (Zend Engine) and Python. </p><p> The most important difference is in error handling and triggers: errors detected in C can easily be non-fatal. Just like with PHP, minor errors are emitted as warnings that also propagate invalid (null) values throughout the system to effectively disable the subsequent calls and notify whoever is interested of the exact trail of errors. Furthermore, this behavior can be modified by using protected calls (pcall function) in SGScript and custom messaging callbacks in C. </p><p> The virtual machine supports: </p><ul><li>Operator overloading </li><li>On-demand garbage collection </li><li>Full introspection of machine state </li><li>Type registration for simplified cross-library data reuse</li></ul></div> <div class='item'><a name='Constants-and-types'></a><hr><h2>Constants and types</h2><p> This part of the documentation describes the various types and definitions used in the C API. </p></div> <div class='item'><a name='Main-types'></a><hr><h2>Main types</h2><p> Return types: </p><ul><li>SGSRESULT [int]: output code (success = 0, failure: &lt; 0 ) </li><li>SGSBOOL [int]: simplified output code (success = 1, failure = 0) </li><li>SGSMIXED [int32_t] output code / value (success + value: &gt;= 0, failure: &lt; 0)</li></ul><p> Virtual machine / language types: </p><ul><li>sgs_Bool [int32_t]: boolean value </li><li>sgs_Int [int64_t]: integer </li><li>sgs_Real [double]: real (floating point) value </li><li>sgs_SizeVal [int32_t]: size type </li><li>sgs_CFunc [int ( sgs_Context* )]: C function type </li><li>sgs_ObjInterface [struct]: object interface description </li><li>sgs_Variable [struct]: the combined variable type</li></ul><p> System types: </p><ul><li>sgs_Context [struct]: the virtual machine </li><li>sgs_StackFrame [struct]: the function call info object</li></ul><p> Interface types: </p><ul><li>sgs_MemFunc [void* ( void* userdata, void* ptr, size_t size )]: memory interface function </li><li>sgs_OutputFunc [void ( void* userdata, sgs_Context* C, const void* buf, sgs_SizeVal size )]: output function </li><li>sgs_MsgFunc [void ( void* userdata, sgs_Context* C, int code, const char* text )]: messaging function </li><li>sgs_HookFunc [void ( void*, sgs_Context*, int )]: debug hook function</li></ul></div> <div class='item'><a name='Error-codes'></a><hr><h2>Error codes</h2><p> These are the default meanings for error codes that are honored throughout the API. </p><ul><li>Generated by the C API <ul><li>SGS_SUCCESS: operation was successful </li><li>SGS_ENOTFND: item was not found </li><li>SGS_ECOMP: compile error </li><li>SGS_ENOTOBJ: argument was not an object </li><li>SGS_ENOTSUP: operation is not supported </li><li>SGS_EINVAL: invalid value was passed </li><li>SGS_EINPROC: process was interrupted</li></ul></li></ul><ul><li>Generated by SGScript VM <ul><li>SGS_INFO: information about potential issues and state of the system </li><li>SGS_WARNING: non-fatal issues </li><li>SGS_ERROR: fatal issues </li><li>any other integer may be defined and returned by other interfaces</li></ul></li></ul></div> <div class='item'><a name='Variable-types'></a><hr><h2>Variable types</h2><p> -- SGS_VT_[NULL|BOOL|INT|REAL|STRING|FUNC|CFUNC|OBJECT|PTR] </p></div> <div class='item'><a name='Constant-registration-types'></a><hr><h2>Constant registration types</h2><ul><li>struct sgs_RegFuncConst { char* name; sgs_CFunc value; } </li><li>struct sgs_RegIntConst { char* name; sgs_Int value; } </li><li>struct sgs_RegRealConst { char* name; sgs_Real value; }</li></ul></div> <div class='item'><a name='Concepts-systems'></a><hr><h2>Concepts &amp; systems</h2></div> <div class='item'><a name='Messaging-system'></a><hr><h2>Messaging system</h2><p> Messages are combinations of importance code and a null-terminated string that holds the message itself. The messaging system&#39;s purpose generally is to notify about problems and allow handling them to some extent. </p><p> The C API has a function for sending messages - <a href="#sgs-Msg-function">sgs_Msg</a> - and two for dealing with the current callback - <a href="#sgs-SetMsgFunc-function">sgs_SetMsgFunc</a> / <a href="#sgs-GetMsgFunc-function">sgs_GetMsgFunc</a>. </p><p> The <a href="#sgs-Msg-function">sgs_Msg</a> function basically generates the full string from the format string and calls the callback that is currently set. Due to the data association and accessibility, various systems can be implemented on top of it: </p><h5>Logging</h5><p> All messages can simply be logged. For the most simple approach, the <a href="#sgs-StdOutputFunc-function">sgs_StdOutputFunc</a> callback can be used with any FILE* for the data pointer. </p><h5>A limited amount of exception handling</h5><p> This system can be used to break out of any point in SGS code up until the last C function. For this, <a href="#pcall-function">pcall</a> can be used together with a callback that calls <a href="#sys-abort-function">sys_abort</a> when necessary. </p><h5>Debugging</h5><p> On each warning or error, debugging code can be triggered. It can be an interactive console debugger (as implemented in ext/sgs_idbg), it could also be code that dumps the relevant state and sends it to the developer. </p><h5>Hidden data collection</h5><p> Similarly to exception handling, <a href="#pcall-function">pcall</a> can be used also for gathering messages otherwise skipped by the system. The sub-zero importance range is generally hidden - there&#39;s 2^31 values to use to mark special messages - however, <a href="#sys-replevel-function">sys_replevel</a> or <a href="#sgs-Cntl-function">sgs_Cntl</a> with SGS_CNTL_(SET_)MINLEV must be used to enable that range. </p></div> <div class='item'><a name='Iterator-system'></a><hr><h2>Iterator system</h2><p> Iterators are objects that enable sequential, ordered traversal of object contents, allowing to read up to 2 variables at each position: the key and the value. </p><p> The C API has <a href="#Iterators">several functions</a> used to deal with iterators. There are essentially three kinds of functions: initialization ( <a href="#sgs-PushIterator-P-functions">sgs_PushIterator(P)</a>, <a href="#sgs-GetIterator-P-functions">sgs_GetIterator(P)</a> ), advancing ( <a href="#sgs-IterAdvance-P-functions">sgs_IterAdvance(P)</a> ) and data retrieval ( <a href="#sgs-IterPushData-P-functions">sgs_IterPushData(P)</a>, <a href="#sgs-IterGetData-P-functions">sgs_IterGetData(P)</a> ). </p><p> Iterator starts at the pre-first position (-1 in terms of indices), so nothing can be read initially, before the first advance. This allows to implement iterator handling with rather simple code: </p><pre>initialize; while( advance &gt; 0 ) { retrieve key and/or value; ..do something else..; } free;</pre><p> A more real example follows: </p><pre>// assuming iterable object is at the top of the stack sgs_PushIterator( C, -1 ); while( sgs_IterAdvance( C, -1 ) &gt; 0 ) { sgs_StackIdx ssz = sgs_StackSize( C ); sgs_IterPushData( C, -1, 1, 1 ); // push both key and value sgs_SetStackSize( C, ssz ); // restore stack to have iterator at -1 again } sgs_Pop( C, 1 ); // pop the iterator</pre><p> Another example using pointers: </p><pre>sgs_Variable iterator, iterable, key, value; // .. assuming iterable is initalized here .. sgs_GetIteratorP( C, &amp;iterable, &amp;iterator ); while( sgs_IterAdvanceP( C, &amp;iterator ) &gt; 0 ) { sgs_IterGetDataP( C, &amp;iterator, NULL, &amp;value ); // .. use value .. sgs_Release( C, &amp;value ); sgs_IterGetDataP( C, &amp;iterator, &amp;key, &amp;value ); // .. use key and value .. sgs_Release( C, &amp;key ); sgs_Release( C, &amp;value ); } sgs_Release( C, &amp;iterator ); // .. release the iterable or not, depending on how it was initialized ..</pre></div> <div class='item'><a name='Garbage-collection-system'></a><hr><h2>Garbage collection system</h2><p> The garbage collector currently implemented is a basic stop-the-world mark-and-sweep algorithm that goes over all objects and recursively marks them as available. </p><p> The marking is done on the variable named <code>redblue</code>, which contains 0 or 1 and in all avaiable objects is synced with the same variable for the context. On each pass, the bit is flipped for all available objects, so all objects that didn&#39;t have the bit flipped can be safely removed. </p><p> The garbage collector is invoked with <a href="#sgs-GCExecute-function">sgs_GCExecute</a> in the C API and <a href="#gc-collect-function">gc_collect</a> in SGScript. </p><p> Sub-objects are marked as available in the GCMARK callback with <a href="#sgs-GCMark-Array-function">sgs_GCMark(Array)</a> / <a href="#sgs-ObjGCMark-function">sgs_ObjGCMark</a> functions. </p></div> <div class='item'><a name='Classes'></a><hr><h2>Classes</h2><p> Classes are objects that enable operator/interface overloading and two-layer index retrieval. </p><p> Overloadable operators/interfaces: </p><ul><li>basic math: +, - (both unary and binary), *, /, % </li><li>comparison </li><li>conversions to bool, int, real, string </li><li>typeof string retrieval </li><li>cloning</li></ul><p> Two-layer index retrieval is simply trying to read the index from a different source if the first source fails to come up with something. In other languages, metatable and prototype is the name of a table that is the second source. This allows to avoid storing functions and other data that is equal to all instances of some object type. </p></div> <div class='item'><a name='Closures'></a><hr><h2>Closures</h2><p> Closures are a combination of one callable and some variables. They are meant to simplify interfaces and code around places where it was important for functions to have access to call-invariant (same on every call) data. </p><p> Closures can be created from both SGScript and the C API, though both options have their limitations. </p><ul><li>In SGScript, closures can be created by letting functions &quot;use&quot; a variable, e.g. by writing <code>function func( args ) use( closures ){ ..body.. }</code> </li><li>In the C API, closures can be created with <a href="#sgs-MakeClosure-function">sgs_MakeClosure</a>, though this requires knowledge about the receiving function&#39;s ability to use them. This means that even though there are no variable type limits, it is more practical to create closures from native functions (both plain and object interface functions) with the C API. Though <b>prefer objects for callables if function-data bindings are necessary at the native code level</b>.</li></ul><p> Closure stack in the C API is technically very similar to main stack, with one important difference - functions do not accept negative indices. </p></div> <div class='item'><a name='Functions'></a><hr><h2>Functions</h2></div> <div class='item'><a name='Context-management'></a><hr><h2>Context management</h2><ul><li><a href="#sgs-CreateEngineExt-function">sgs_CreateEngine</a> - create scripting engine context </li><li><a href="#sgs-CreateEngineExt-function">sgs_CreateEngineExt</a> - create scripting engine context and pass a custom memory function </li><li><a href="#sgs-DestroyEngine-function">sgs_DestroyEngine</a> - validate memory statistics and destroy engine context </li><li><a href="#sgs-DefaultMemFunc-function">sgs_DefaultMemFunc</a> - example memory management callback </li><li><a href="#sgs-Get-Err-OutputFunc-function">sgs_Get(Err)OutputFunc</a> - return the current output callback and its user data pointer </li><li><a href="#sgs-Set-Err-OutputFunc-function">sgs_Set(Err)OutputFunc</a> - set the output callback and its user data pointer </li><li><a href="#sgs-GetMsgFunc-function">sgs_GetMsgFunc</a> - return the current messaging callback and its user data pointer </li><li><a href="#sgs-SetMsgFunc-function">sgs_SetMsgFunc</a> - set the messaging callback and its user data pointer </li><li><a href="#sgs-Cntl-function">sgs_Cntl</a> - set and/or retrieve various states in the system</li></ul></div> <div class='item'><a name='Memory-management'></a><hr><h2>Memory management</h2><ul><li><a href="#sgs-DefaultMemFunc-function">sgs_DefaultMemFunc</a> - example memory management callback </li><li><a href="#sgs-Memory-function">sgs_Memory</a> - allocate/reallocate/free memory </li><li><a href="#Memory-allocation-macros-macros">sgs_Malloc</a> - allocate specified amount of memory </li><li><a href="#Memory-allocation-macros-macros">sgs_Free</a> - free a previously allocated memory pointer </li><li><a href="#Memory-allocation-macros-macros">sgs_Realloc</a> - allocate/reallocate/free memory (requires implicit sgs_Context* C) </li><li><a href="#Memory-allocation-macros-macros">sgs_Alloc</a> - allocate object (requires implicit sgs_Context* C) </li><li><a href="#Memory-allocation-macros-macros">sgs_Alloc_n</a> - allocate an array of objects (requires implicit sgs_Context* C) </li><li><a href="#Memory-allocation-macros-macros">sgs_Alloc_a</a> - allocate object + additional memory (requires implicit sgs_Context* C) </li><li><a href="#Memory-allocation-macros-macros">sgs_Dealloc</a> - free a previously allocated memory pointer (requires implicit sgs_Context* C)</li></ul></div> <div class='item'><a name='Input-output'></a><hr><h2>Input / output</h2><ul><li><a href="#sgs-Get-Err-OutputFunc-function">sgs_Get(Err)OutputFunc</a> - return the current output callback and its user data pointer </li><li><a href="#sgs-Set-Err-OutputFunc-function">sgs_Set(Err)OutputFunc</a> - set the output callback and its user data pointer </li><li><a href="#sgs-Err-Write-function">sgs_(Err)Write</a> - pass a character buffer to the output callback </li><li><a href="#sgs-Err-Writef-function">sgs_(Err)Writef</a> - pass a formatted string to the output callback </li><li><a href="#sgs-Err-WriteStr-function-alias">sgs_(Err)WriteStr</a> - pass a null-terminated string to the output callback </li><li><a href="#sgs-GetMsgFunc-function">sgs_GetMsgFunc</a> - return the current messaging callback and its user data pointer </li><li><a href="#sgs-SetMsgFunc-function">sgs_SetMsgFunc</a> - set the messaging callback and its user data pointer </li><li><a href="#sgs-Msg-function">sgs_Msg</a> - invoke the messaging system </li><li><a href="#sgs-WriteErrorInfo-function">sgs_WriteErrorInfo</a> - write message info to output callback </li><li><a href="#sgs-PushErrorInfo-function">sgs_PushErrorInfo</a> - push message info to stack </li><li><a href="#sgs-HasFuncName-function">sgs_HasFuncName</a> - check if current C function has a name set </li><li><a href="#sgs-FuncName-function">sgs_FuncName</a> - set current C function name </li><li><a href="#SGSFN-function-alias">SGSFN</a> - set current C function name </li><li><a href="#SGSBASEFN-function-alias">SGSBASEFN</a> - set current C function name if it&#39;s not already set </li><li><a href="#sgs-Errno-function-alias">sgs_Errno</a> - copy errno to internal errno if 2nd argument is false, otherwise clear it </li><li><a href="#sgs-SetErrno-function-alias">sgs_SetErrno</a> - set the internal errno value </li><li><a href="#sgs-GetLastErrno-function-alias">sgs_GetLastErrno</a> - return the currently set internal errno value </li><li><a href="#sgs-StdOutputFunc-function">sgs_StdOutputFunc</a> - example output callback </li><li><a href="#sgs-StdMsgFunc-NoAbort-functions">sgs_StdMsgFunc_NoAbort</a> - example messaging callback that does not abort on errors </li><li><a href="#sgs-StdMsgFunc-NoAbort-functions">sgs_StdMsgFunc</a> - example messaging callback </li><li><a href="#sgs-Cntl-function">sgs_Cntl</a> - set and/or retrieve various states in the system </li><li><a href="#sgs-ArgErrorExt-function">sgs_ArgErrorExt</a> - emit an argument type mismatch error with additional formatting options </li><li><a href="#sgs-ArgError-function">sgs_ArgError</a> - emit an argument type mismatch error </li><li><a href="#sgs-ArgError-function">sgs_FuncArgError</a> - emit an argument type mismatch error (alias for states where <code>this</code> variable is hidden) </li><li><a href="#sgs-ArgError-function">sgs_MethodArgError</a> - emit an argument type mismatch error (alias for states where <code>this</code> variable is NOT hidden)</li></ul></div> <div class='item'><a name='Code-handling'></a><hr><h2>Code handling</h2><ul><li><a href="#sgs-ExecBuffer-function-alias">sgs_ExecBuffer</a> - execute a character buffer </li><li><a href="#sgs-EvalBuffer-function">sgs_EvalBuffer</a> - execute a character buffer, keep returned variables on stack </li><li><a href="#sgs-ExecFile-function-alias">sgs_ExecFile</a> - execute a file </li><li><a href="#sgs-EvalFile-function">sgs_EvalFile</a> - execute a file, keep returned variables on stack </li><li><a href="#sgs-ExecString-function-alias">sgs_ExecString</a> - execute a null-terminated string </li><li><a href="#sgs-EvalString-function-alias">sgs_EvalString</a> - execute a null-terminated string, keep returned variables on stack </li><li><a href="#sgs-IncludeExt-function">sgs_Include</a> - include an item from the file system </li><li><a href="#sgs-IncludeExt-function">sgs_IncludeExt</a> - include an item from the file system, optionally specifying a search path </li><li><a href="#sgs-Compile-function">sgs_Compile</a> - compile character buffer to bytecode buffer </li><li><a href="#sgs-DumpCompiled-function">sgs_DumpCompiled</a> - dump bytecode/constant info from a compiled bytecode buffer</li></ul></div> <div class='item'><a name='Introspection'></a><hr><h2>Introspection</h2><ul><li><a href="#sgs-Stat-function">sgs_Stat</a> - retrieve or dump various parts of VM state </li><li><a href="#sgs-StackFrameInfo-function">sgs_StackFrameInfo</a> - retrieve preprocessed info from stack frame </li><li><a href="#sgs-GetFramePtr-function">sgs_GetFramePtr</a> - return a stack frame pointer</li></ul></div> <div class='item'><a name='Execution-control'></a><hr><h2>Execution control</h2><ul><li><a href="#sgs-FCall-P-functions">sgs_FCallP</a> - call variable as function </li><li><a href="#sgs-This-Call-P-function-aliases">sgs_CallP</a> - call variable as function without <code>this</code> passed to it </li><li><a href="#sgs-This-Call-P-function-aliases">sgs_ThisCallP</a> - call variable as function function with <code>this</code> passed to it </li><li><a href="#sgs-FCall-P-functions">sgs_FCall</a> - call the topmost stack item as function </li><li><a href="#sgs-This-Call-P-function-aliases">sgs_Call</a> - call the topmost stack item as function without <code>this</code> passed to it </li><li><a href="#sgs-This-Call-P-function-aliases">sgs_ThisCall</a> - call the topmost stack item as function with <code>this</code> passed to it </li><li><a href="#sgs-GlobalCall-function">sgs_GlobalCall</a> - call a global function </li><li><a href="#sgs-Abort-function">sgs_Abort</a> - abort the execution of the previous SGS functions up to the last C function before them </li><li><a href="#sgs-Cntl-function">sgs_Cntl</a> - set and/or retrieve various states in the system</li></ul></div> <div class='item'><a name='Binding-helpers'></a><hr><h2>Binding helpers</h2><ul><li><a href="#sgs-LoadLib-functions">sgs_LoadLib_Fmt</a> - load the formatting library </li><li><a href="#sgs-LoadLib-functions">sgs_LoadLib_IO</a> - load the input/output library </li><li><a href="#sgs-LoadLib-functions">sgs_LoadLib_Math</a> - load the math library </li><li><a href="#sgs-LoadLib-functions">sgs_LoadLib_OS</a> - load the operating system library </li><li><a href="#sgs-LoadLib-functions">sgs_LoadLib_RE</a> - load the regular expression library </li><li><a href="#sgs-LoadLib-functions">sgs_LoadLib_String</a> - load the string library </li><li><a href="#sgs-Reg-Consts-function">sgs_RegFuncConsts</a> - register a list of global C function constants </li><li><a href="#sgs-Reg-Consts-function">sgs_RegIntConsts</a> - register a list of global integer constants </li><li><a href="#sgs-Reg-Consts-function">sgs_RegRealConsts</a> - register a list of global real value constants</li></ul></div> <div class='item'><a name='Object-type-storage'></a><hr><h2>Object type storage</h2><ul><li><a href="#sgs-RegisterType-function">sgs_RegisterType</a> - register an object interface pointer by name </li><li><a href="#sgs-UnregisterType-function">sgs_UnregisterType</a> - unregister an object interface pointer by name </li><li><a href="#sgs-FindType-function">sgs_FindType</a> - find a registered object interface pointer by name </li><li><a href="#sgs-IsType-P-function-aliases">sgs_IsType</a> - check if variable on stack is of specified registered type</li></ul></div> <div class='item'><a name='Variable-initialization'></a><hr><h2>Variable initialization</h2><ul><li><a href="#sgs-Init-functions">sgs_InitNull</a> - initialize variable to a null variable </li><li><a href="#sgs-Init-functions">sgs_InitBool</a> - initialize variable to a boolean variable </li><li><a href="#sgs-Init-functions">sgs_InitInt</a> - initialize variable to an integer </li><li><a href="#sgs-Init-functions">sgs_InitReal</a> - initialize variable to a real value </li><li><a href="#sgs-Init-functions">sgs_InitStringBuf</a> - initialize variable to a new char buffer </li><li><a href="#sgs-Init-functions">sgs_InitString</a> - initialize variable to a new string </li><li><a href="#sgs-Init-functions">sgs_InitCFunction</a> - initialize variable to C function </li><li><a href="#sgs-Init-functions">sgs_InitObject</a> - initialize variable to a new object </li><li><a href="#sgs-Init-functions">sgs_InitObjectIPA</a> - initialize variable to a new object with additional memory allocated in-place for the internal data pointer </li><li><a href="#sgs-Init-functions">sgs_InitPtr</a> - initialize variable to a pointer variable </li><li><a href="#sgs-Init-functions">sgs_InitObjectPtr</a> - initialize variable to an existing object and acquire it </li><li><a href="#sgs-InitArray-function">sgs_InitArray</a> - initialize variable to a new array, optionally using the specified number of pushed items on stack </li><li><a href="#sgs-InitDict-function">sgs_InitDict</a> - initialize variable to a new dict, optionally using the specified number of pushed items on stack </li><li><a href="#sgs-InitMap-function">sgs_InitMap</a> - initialize variable to a new map, optionally using the specified number of pushed items on stack</li></ul></div> <div class='item'><a name='Stack-primary-interface'></a><hr><h2>Stack primary interface</h2><ul><li><a href="#sgs-Push-functions">sgs_PushNull</a> - push a null variable </li><li><a href="#sgs-Push-functions">sgs_PushBool</a> - push a boolean variable </li><li><a href="#sgs-Push-functions">sgs_PushInt</a> - push an integer </li><li><a href="#sgs-Push-functions">sgs_PushReal</a> - push a real value </li><li><a href="#sgs-Push-functions">sgs_PushStringBuf</a> - push a new string from char buffer </li><li><a href="#sgs-Push-functions">sgs_PushString</a> - push a new string </li><li><a href="#sgs-Push-functions">sgs_PushCFunction</a> - push a C function </li><li><a href="#sgs-Push-functions">sgs_PushObject</a> - push a new object </li><li><a href="#sgs-Push-functions">sgs_PushObjectIPA</a> - push a new object with additional memory allocated in-place for the internal data pointer </li><li><a href="#sgs-Push-functions">sgs_PushPtr</a> - push a pointer </li><li><a href="#sgs-Push-functions">sgs_PushObjectPtr</a> - push an object pointer </li><li><a href="#sgs-PushArray-function">sgs_PushArray</a> - push a new array variable, optionally using the specified number of pushed items on stack </li><li><a href="#sgs-PushDict-function">sgs_PushDict</a> - push a new dict variable, optionally using the specified number of pushed items on stack </li><li><a href="#sgs-PushMap-function">sgs_PushMap</a> - push a new map variable, optionally using the specified number of pushed items on stack </li><li><a href="#sgs-Push-functions">sgs_PushVariable</a> - push the specified variable </li><li><a href="#sgs-StoreVariable-function">sgs_StoreVariable</a> - retrieve, acquire and pop the topmost variable on stack </li><li><a href="#sgs-PushItem-function">sgs_PushItem</a> - retrieve and push the specified variable on stack </li><li><a href="#sgs-StoreItem-function">sgs_StoreItem</a> - store and pop the topmost variable to the specified position after removal in stack </li><li><a href="#sgs-InsertVariable-function">sgs_InsertVariable</a> - insert a variable on stack in the specified position </li><li><a href="#sgs-Pop-function">sgs_Pop</a> - pop the specified number of items from stack </li><li><a href="#sgs-PopSkip-function">sgs_PopSkip</a> - pop the specified number of items from stack, skipping some topmost items </li><li><a href="#sgs-StackSize-function">sgs_StackSize</a> - return the size of the current stack frame </li><li><a href="#sgs-SetStackSize-function">sgs_SetStackSize</a> - resize the current stack frame </li><li><a href="#sgs-AbsIndex-function">sgs_AbsIndex</a> - convert stack index to positive if possible (if it&#39;s &lt;0 or &gt;=StackSize, then it&#39;s invalid) </li><li><a href="#sgs-IsValidIndex-function">sgs_IsValidIndex</a> - check if specified stack index is valid </li><li><a href="#sgs-PeekStackItem-function">sgs_PeekStackItem</a> - retrieve without acquisition the specified variable on stack </li><li><a href="#sgs-GetStackItem-function">sgs_GetStackItem</a> - retrieve and acquire the specified variable on stack </li><li><a href="#sgs-SetStackItem-function">sgs_SetStackItem</a> - assign variable to the specified variable on stack </li><li><a href="#sgs-ItemType-function">sgs_ItemType</a> - return the variable type of the specified variable on stack </li><li><a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgsExtVA</a> - parse the stack as an argument list with additional options (for custom wrapper functions) </li><li><a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgsExt</a> - parse the stack as an argument list with additional options </li><li><a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgs</a> - parse the stack as an argument list </li><li><a href="#sgs-ParseMethod-function">sgs_ParseMethod</a> - the <code>this</code> object variable handling function, using the macro is preferred to this </li><li><a href="#SGS-PARSE-METHOD-function-alias">SGS_PARSE_METHOD</a> - automagically handle a <code>this</code> object variable regardless of the way its passed </li><li><a href="#sgs-Method-function">sgs_Method</a> - unhide the first variable on stack if there is a hidden <code>this</code> variable </li><li><a href="#sgs-Force-HideThis-functions">sgs_HideThis</a> - hide the first variable on stack if the stack already doesn&#39;t contain a hidden <code>this</code> variable </li><li><a href="#sgs-Force-HideThis-functions">sgs_ForceHideThis</a> - hide the first variable even if it wasn&#39;t previously hidden before unhiding</li></ul></div> <div class='item'><a name='Sub-item-usage'></a><hr><h2>Sub-item usage</h2><ul><li><a href="#sgs-GetIndex-functions">sgs_GetIndex***</a> - retrieve a sub-item </li><li><a href="#sgs-SetIndex-functions">sgs_SetIndex***</a> - set a sub-item </li><li><a href="#sgs-PushIndex-functions">sgs_PushIndex**</a> - retrieve and push a sub-item </li><li><a href="#sgs-StoreIndex-functions">sgs_StoreIndex**</a> - store and pop a sub-item </li><li><a href="#sgs-GetGlobalPP-function">sgs_GetGlobalPP</a> - retrieve a global variable </li><li><a href="#sgs-SetGlobalPP-function">sgs_SetGlobalPP</a> - set a global variable </li><li><a href="#sgs-PushProperty-function">sgs_PushProperty</a> - retrieve and push the string property of a variable on stack </li><li><a href="#sgs-StoreProperty-function">sgs_StoreProperty</a> - store and pop the topmost stack item to a string property of a variable on stack </li><li><a href="#sgs-PushNumIndex-function">sgs_PushNumIndex</a> - retrieve and push the integer index of a variable on stack </li><li><a href="#sgs-StoreNumIndex-function">sgs_StoreNumIndex</a> - store and pop the topmost stack item to an integer index of a variable on stack </li><li><a href="#sgs-PushGlobal-function">sgs_PushGlobal</a> - retrieve and push the global variable, specified by a string </li><li><a href="#sgs-StoreGlobal-function">sgs_StoreGlobal</a> - store and pop the topmost stack item as a global variable, specified by a string </li><li><a href="#sgs-GetEnv-function">sgs_GetEnv</a> - retrieve the global environment hash table (dict) </li><li><a href="#sgs-SetEnv-function">sgs_SetEnv</a> - set the variable as the global environment hash table (dict), if possible </li><li><a href="#sgs-PushEnv-function">sgs_PushEnv</a> - push the global environment hash table (dict) </li><li><a href="#sgs-StoreEnv-function">sgs_StoreEnv</a> - store and pop the topmost stack item as the global environment hash table (dict), if possible </li><li><a href="#sgs-PushPath-function">sgs_PushPath</a> - retrieve and push a variable from a path of sub-items </li><li><a href="#sgs-StorePath-function">sgs_StorePath</a> - store and pop the topmost stack item into a path of sub-items</li></ul></div> <div class='item'><a name='Argument-handling'></a><hr><h2>Argument handling</h2><ul><li><a href="#sgs-ArgErrorExt-function">sgs_ArgErrorExt</a> - emit an argument type mismatch error with additional formatting options </li><li><a href="#sgs-ArgError-function">sgs_ArgError</a> - emit an argument type mismatch error </li><li><a href="#sgs-ArgError-function">sgs_FuncArgError</a> - emit an argument type mismatch error (alias for states where <code>this</code> variable is hidden) </li><li><a href="#sgs-ArgError-function">sgs_MethodArgError</a> - emit an argument type mismatch error (alias for states where <code>this</code> variable is NOT hidden) </li><li><a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgsExtVA</a> - parse the stack as an argument list with additional options (for custom wrapper functions) </li><li><a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgsExt</a> - parse the stack as an argument list with additional options </li><li><a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgs</a> - parse the stack as an argument list </li><li><a href="#sgs-ParseMethod-function">sgs_ParseMethod</a> - the <code>this</code> object variable handling function, using the macro is preferred to this </li><li><a href="#SGS-PARSE-METHOD-function-alias">SGS_PARSE_METHOD</a> - automagically handle a <code>this</code> object variable regardless of the way its passed </li><li><a href="#sgs-Method-function">sgs_Method</a> - unhide the first variable on stack if there is a hidden <code>this</code> variable </li><li><a href="#sgs-Force-HideThis-functions">sgs_HideThis</a> - hide the first variable on stack if the stack already doesn&#39;t contain a hidden <code>this</code> variable </li><li><a href="#sgs-Force-HideThis-functions">sgs_ForceHideThis</a> - hide the first variable even if it wasn&#39;t previously hidden before unhiding</li></ul></div> <div class='item'><a name='Virtual-machine-operations'></a><hr><h2>Virtual machine operations</h2><ul><li><a href="#sgs-Assign-function">sgs_Assign</a> - release the current variable and acquire-assign to it from the source </li><li><a href="#sgs-ArithOp-function">sgs_ArithOp</a> - run an arithmetic operation (+,-,*,/,%) on two variables to generate a third one </li><li><a href="#sgs-IncDec-function">sgs_IncDec</a> - increment or decrement the specified variable </li><li><a href="#sgs-Compare-function">sgs_Compare</a> - check if both variables compare equal to each other </li><li><a href="#sgs-EqualTypes-function">sgs_EqualTypes</a> - check if both variables have the same type and object interface (if both are objects) </li><li><a href="#sgs-TypeOf-function">sgs_TypeOf</a> - convert the topmost variable on stack to a type name string </li><li><a href="#sgs-DumpVar-function">sgs_DumpVar</a> - convert the topmost variable on stack to a string that contains detailed info about its contents </li><li><a href="#sgs-GCExecute-function">sgs_GCExecute</a> - run the garbage collection system to remove all unreachable objects </li><li><a href="#sgs-StringConcat-function">sgs_StringConcat</a> - concatenate two or more variables into a string </li><li><a href="#sgs-CloneItem-function">sgs_CloneItem</a> - clone the topmost stack item if it&#39;s mutable </li><li><a href="#sgs-ObjectAction-function">sgs_ObjectAction</a> - execute actions on object variable on stack </li><li><a href="#sgs-Serialize-function">sgs_Serialize</a> - serialize the topmost variable on stack by converting it recursively to an instruction stream </li><li><a href="#sgs-SerializeObject-function">sgs_SerializeObject</a> - emit a call to the specified function to the serialized stream </li><li><a href="#sgs-Unserialize-function">sgs_Unserialize</a> - unserialize the topmost variable on stack by running its serialized instruction stream</li></ul></div> <div class='item'><a name='String-helpers'></a><hr><h2>String helpers</h2><ul><li><a href="#sgs-PadString-function">sgs_PadString</a> - return a string with two spaces appended to all newline characters </li><li><a href="#sgs-ToPrintSafeString-function">sgs_ToPrintSafeString</a> - return a string with all non-printable (except space), non-ASCII characters converted to a character hex code </li><li><a href="#sgs-StringConcat-function">sgs_StringConcat</a> - concatenate two or more variables into a string</li></ul></div> <div class='item'><a name='Closure-handling'></a><hr><h2>Closure handling</h2><ul><li><a href="#sgs-ClPushNulls-function">sgs_ClPushNulls</a> - push a number of empty closures to the closure stack </li><li><a href="#sgs-ClPushItem-function">sgs_ClPushItem</a> - push a variable on stack as a closure to the closure stack </li><li><a href="#sgs-ClPop-function">sgs_ClPop</a> - pop a number of closures from the closure stack </li><li><a href="#sgs-MakeClosure-function">sgs_MakeClosure</a> - make a callable closure object from the specified callable and number of closures on stack </li><li><a href="#sgs-ClGetItem-function">sgs_ClGetItem</a> - retrieve the variable from a closure on stack </li><li><a href="#sgs-ClSetItem-function">sgs_ClSetItem</a> - set the variable to a closure on stack</li></ul></div> <div class='item'><a name='Data-retrieval-conversion'></a><hr><h2>Data retrieval &amp; conversion</h2><ul><li><a href="#sgs-Get-functions">sgs_GetBoolP</a> - return the boolean version of the variable </li><li><a href="#sgs-Get-functions">sgs_GetIntP</a> - return the integer version of the variable </li><li><a href="#sgs-Get-functions">sgs_GetRealP</a> - return the real value version of the variable </li><li><a href="#sgs-Get-functions">sgs_GetPtrP</a> - return the pointer version of the variable </li><li><a href="#sgs-To-functions">sgs_ToBoolP</a> - convert variable to a boolear value and return it </li><li><a href="#sgs-To-functions">sgs_ToIntP</a> - convert variable to an integer and return it </li><li><a href="#sgs-To-functions">sgs_ToRealP</a> - convert variable to a real value and return it </li><li><a href="#sgs-To-functions">sgs_ToPtrP</a> - convert variable to a pointer and return it </li><li><a href="#sgs-ToStringBuf-Fast-P-functions">sgs_ToStringBufP</a> - convert variable to a string, returning size </li><li><a href="#sgs-ToString-Fast-P-function-aliases">sgs_ToStringP</a> - convert variable to a string </li><li><a href="#sgs-ToStringBuf-Fast-P-functions">sgs_ToStringBufFastP</a> - convert variable to a string, preventing possible recursion and returning size </li><li><a href="#sgs-ToString-Fast-P-function-aliases">sgs_ToStringFastP</a> - convert variable to a string, preventing possible recursion </li><li><a href="#sgs-IsObject-P-functions">sgs_IsObjectP</a> - check if variable is an object and has the specified interface pointer </li><li><a href="#sgs-IsType-P-function-aliases">sgs_IsTypeP</a> - check if variable is of specified registered type </li><li><a href="#sgs-IsCallable-P-functions">sgs_IsCallableP</a> - check if variable is callable (SGS function, C function or object with CALL impl.) </li><li><a href="#sgs-Parse-functions">sgs_ParseBoolP</a> - validate conversion, optionally return boolean value from variable, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParseIntP</a> - validate conversion, optionally return integer value from variable, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParseRealP</a> - validate conversion, optionally return real value from variable, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParseStringP</a> - validate conversion, optionally return string or buffer from variable, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParseObjectPtrP</a> - validate conversion, optionally return object pointer from variable, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParsePtrP</a> - validate conversion, optionally return pointer from variable, if possible </li><li><a href="#sgs-ArraySize-P-functions">sgs_ArraySizeP</a> - retrieve size of array variable, if possible </li><li><a href="#sgs-Get-functions">sgs_GetBool</a> - return the boolean version of the variable on stack </li><li><a href="#sgs-Get-functions">sgs_GetInt</a> - return the integer version of the variable on stack </li><li><a href="#sgs-Get-functions">sgs_GetReal</a> - return the real value version of the variable on stack </li><li><a href="#sgs-Get-functions">sgs_GetPtr</a> - return the pointer version of the variable on stack </li><li><a href="#sgs-To-functions">sgs_ToBool</a> - convert variable on stack to a boolear value and return it </li><li><a href="#sgs-To-functions">sgs_ToInt</a> - convert variable on stack to an integer and return it </li><li><a href="#sgs-To-functions">sgs_ToReal</a> - convert variable on stack to a real value and return it </li><li><a href="#sgs-To-functions">sgs_ToPtr</a> - convert variable on stack to a pointer and return it </li><li><a href="#sgs-ToStringBuf-Fast-P-functions">sgs_ToStringBuf</a> - convert variable on stack to a string, returning size </li><li><a href="#sgs-ToString-Fast-P-function-aliases">sgs_ToString</a> - convert variable on stack to a string </li><li><a href="#sgs-ToStringBuf-Fast-P-functions">sgs_ToStringBufFast</a> - convert variable on stack to a string, preventing possible recursion and returning size </li><li><a href="#sgs-ToString-Fast-P-function-aliases">sgs_ToStringFast</a> - convert variable on stack to a string, preventing possible recursion </li><li><a href="#sgs-IsObject-P-functions">sgs_IsObject</a> - check if variable on stack is an object and has the specified interface pointer </li><li><a href="#sgs-IsType-P-function-aliases">sgs_IsType</a> - check if variable on stack is of specified registered type </li><li><a href="#sgs-IsCallable-P-functions">sgs_IsCallable</a> - check if variable on stack is callable (SGS function, C function or object with CALL impl.) </li><li><a href="#sgs-Parse-functions">sgs_ParseBool</a> - validate conversion, optionally return boolean value from variable on stack, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParseInt</a> - validate conversion, optionally return integer value from variable on stack, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParseReal</a> - validate conversion, optionally return real value from variable on stack, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParseString</a> - validate conversion, optionally return string or buffer from variable on stack, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParseObjectPtr</a> - validate conversion, optionally return object pointer from variable on stack, if possible </li><li><a href="#sgs-Parse-functions">sgs_ParsePtr</a> - validate conversion, optionally return pointer from variable on stack, if possible </li><li><a href="#sgs-ArraySize-P-functions">sgs_ArraySize</a> - retrieve size of array variable on stack, if possible </li><li><a href="#sgs-Global-functions">sgs_GlobalBool</a> - retrieve global by name as bool </li><li><a href="#sgs-Global-functions">sgs_GlobalInt</a> - retrieve global by name as integer </li><li><a href="#sgs-Global-functions">sgs_GlobalReal</a> - retrieve global by name as real </li><li><a href="#sgs-Global-functions">sgs_GlobalStringBuf</a> - retrieve global by name as string buffer </li><li><a href="#sgs-Global-functions">sgs_GlobalString</a> - retrieve global by name as string </li><li><a href="#sgs-GetStringPtr-P-functions">sgs_GetStringPtrP</a> - get string pointer from variable pointer </li><li><a href="#sgs-GetStringSize-P-functions">sgs_GetStringSizeP</a> - get string size from variable pointer </li><li><a href="#sgs-GetObjectStruct-P-functions">sgs_GetObjectStructP</a> - get object pointer from variable pointer </li><li><a href="#sgs-GetObjectData-P-functions">sgs_GetObjectDataP</a> - get data pointer of object variable pointer </li><li><a href="#sgs-GetObjectIface-P-functions">sgs_GetObjectIfaceP</a> - get interface pointer of object variable pointer </li><li><a href="#sgs-SetObjectData-P-functions">sgs_SetObjectDataP</a> - set data pointer of object variable pointer </li><li><a href="#sgs-SetObjectIface-P-functions">sgs_SetObjectIfaceP</a> - set interface pointer of object variable pointer </li><li><a href="#sgs-GetStringPtr-P-functions">sgs_GetStringPtr</a> - get string pointer from variable on stack </li><li><a href="#sgs-GetStringSize-P-functions">sgs_GetStringSize</a> - get string size from variable on stack </li><li><a href="#sgs-GetObjectStruct-P-functions">sgs_GetObjectStruct</a> - get object pointer from variable on stack </li><li><a href="#sgs-GetObjectData-P-functions">sgs_GetObjectData</a> - get data pointer of object variable on stack </li><li><a href="#sgs-GetObjectIface-P-functions">sgs_GetObjectIface</a> - get interface pointer of object variable on stack </li><li><a href="#sgs-SetObjectData-P-functions">sgs_SetObjectData</a> - set data pointer of object variable on stack </li><li><a href="#sgs-SetObjectIface-P-functions">sgs_SetObjectIface</a> - set interface pointer of object variable on stack</li></ul></div> <div class='item'><a name='Iterators'></a><hr><h2>Iterators</h2><ul><li>see <a href="#Iterator-system">Iterator system</a> for info on how these functions are to be used</li></ul><ul><li><a href="#sgs-PushIterator-P-functions">sgs_PushIteratorP</a> - create and push iterator from variable pointer </li><li><a href="#sgs-GetIterator-P-functions">sgs_GetIteratorP</a> - create iterator from variable pointer </li><li><a href="#sgs-IterAdvance-P-functions">sgs_IterAdvanceP</a> - advance iterator, specified by its variable pointer </li><li><a href="#sgs-IterPushData-P-functions">sgs_IterPushDataP</a> - extract and push data of current iteration of the iterator, specified by its variable pointer </li><li><a href="#sgs-IterGetData-P-functions">sgs_IterGetDataP</a> - extract data of current iteration of the iterator, specified by its variable pointer </li><li><a href="#sgs-PushIterator-P-functions">sgs_PushIterator</a> - create and push iterator from variable on stack </li><li><a href="#sgs-GetIterator-P-functions">sgs_GetIterator</a> - create iterator from variable on stack </li><li><a href="#sgs-IterAdvance-P-functions">sgs_IterAdvance</a> - advance iterator, specified by its stack index </li><li><a href="#sgs-IterPushData-P-functions">sgs_IterPushData</a> - extract and push data of current iteration of the iterator variable on stack </li><li><a href="#sgs-IterGetData-P-functions">sgs_IterGetData</a> - extract data of current iteration of the iterator variable on stack</li></ul></div> <div class='item'><a name='Variable-ownership'></a><hr><h2>Variable ownership</h2><ul><li><a href="#sgs-Acquire-Array-function">sgs_Acquire</a> - increment reference count of a variable if the type implements reference counting </li><li><a href="#sgs-Acquire-Array-function">sgs_AcquireArray</a> - acquire an array of variables </li><li><a href="#sgs-Release-Array-function">sgs_Release</a> - decrement reference count and possibly destroy a variable if the type implements ref.counting </li><li><a href="#sgs-Release-Array-function">sgs_ReleaseArray</a> - release an array of variables </li><li><a href="#sgs-GCMark-Array-function">sgs_GCMark</a> - mark a variable as available to prevent GC from removing it </li><li><a href="#sgs-GCMark-Array-function">sgs_GCMarkArray</a> - mark an array of variables as available </li><li><a href="#sgs-ObjAcquire-function">sgs_ObjAcquire</a> - acquire an object variable by its sgs_VarObj pointer </li><li><a href="#sgs-ObjRelease-function">sgs_ObjRelease</a> - release an object variable by its sgs_VarObj pointer </li><li><a href="#sgs-ObjGCMark-function">sgs_ObjGCMark</a> - mark an object variable by its sgs_VarObj pointer </li><li><a href="#sgs-ObjAssign-function">sgs_ObjAssign</a> - assign object pointer, handling acquisition/release properly </li><li><a href="#sgs-ObjCallDtor-function">sgs_ObjCallDtor</a> - call the destruction function of an object variable if it&#39;s defined</li></ul></div> <div class='item'><a name='String32-optimization-interface'></a><hr><h2>String32 optimization interface</h2><ul><li><a href="#sgs-PushStringBuf32-function">sgs_PushStringBuf32</a> - initialize and push string32 object on stack </li><li><a href="#sgs-PushString32-function">sgs_PushString32</a> - initialize and push string32 object on stack </li><li><a href="#sgs-CheckString32-function">sgs_CheckString32</a> - trigger a breakpoint if string32 object is not freed </li><li><a href="#sgs-IsFreedString32-function">sgs_IsFreedString32</a> - check if string32 object is freed</li></ul></div> <div class='item'><a name='Utility-functions'></a><hr><h2>Utility functions</h2><ul><li><a href="#sgs-CodeString-function">sgs_CodeString</a> - retrieve a name string for the specified constant </li><li><a href="#sgs-IsNumericString-function">sgs_IsNumericString</a> - check if string is going to be parsed as a number by the internal parser</li></ul></div> <div class='item'><a name='ALL-functions-A-Z'></a><hr><h2>ALL functions (A-Z)</h2><ul><li><a href="#SGSBASEFN-function-alias">SGSBASEFN [function alias]</a> </li><li><a href="#SGSFN-function-alias">SGSFN [function alias]</a> </li><li><a href="#SGS-PARSE-METHOD-function-alias">SGS_PARSE_METHOD [function alias]</a> </li><li><a href="#sgs-Err-Write-function">sgs_(Err)Write [function]</a> </li><li><a href="#sgs-Err-WriteStr-function-alias">sgs_(Err)WriteStr [function alias]</a> </li><li><a href="#sgs-Err-Writef-function">sgs_(Err)Writef [function]</a> </li><li><a href="#sgs-Force-HideThis-functions">sgs_(Force)HideThis [functions]</a> </li><li><a href="#sgs-This-Call-P-function-aliases">sgs_(This)Call(P) [function aliases]</a> </li><li><a href="#sgs-ArgError-function-aliases">sgs_***ArgError [function aliases]</a> </li><li><a href="#sgs-Abort-function">sgs_Abort [function]</a> </li><li><a href="#sgs-AbsIndex-function">sgs_AbsIndex [function]</a> </li><li><a href="#sgs-Acquire-Array-function">sgs_Acquire(Array) [function]</a> </li><li><a href="#sgs-ArgError-function">sgs_ArgError [function]</a> </li><li><a href="#sgs-ArgErrorExt-function">sgs_ArgErrorExt [function]</a> </li><li><a href="#sgs-ArithOp-function">sgs_ArithOp [function]</a> </li><li><a href="#sgs-ArraySize-P-functions">sgs_ArraySize(P) [functions]</a> </li><li><a href="#sgs-Assign-function">sgs_Assign [function]</a> </li><li><a href="#sgs-CheckString32-function">sgs_CheckString32 [function]</a> </li><li><a href="#sgs-ClGetItem-function">sgs_ClGetItem [function]</a> </li><li><a href="#sgs-ClPop-function">sgs_ClPop [function]</a> </li><li><a href="#sgs-ClPushItem-function">sgs_ClPushItem [function]</a> </li><li><a href="#sgs-ClPushNulls-function">sgs_ClPushNulls [function]</a> </li><li><a href="#sgs-ClSetItem-function">sgs_ClSetItem [function]</a> </li><li><a href="#sgs-CloneItem-function">sgs_CloneItem [function]</a> </li><li><a href="#sgs-Cntl-function">sgs_Cntl [function]</a> </li><li><a href="#sgs-CodeString-function">sgs_CodeString [function]</a> </li><li><a href="#sgs-Compare-function">sgs_Compare [function]</a> </li><li><a href="#sgs-Compile-function">sgs_Compile [function]</a> </li><li><a href="#sgs-CreateEngine-function-alias">sgs_CreateEngine [function alias]</a> </li><li><a href="#sgs-CreateEngineExt-function">sgs_CreateEngineExt [function]</a> </li><li><a href="#sgs-DefaultMemFunc-function">sgs_DefaultMemFunc [function]</a> </li><li><a href="#sgs-DestroyEngine-function">sgs_DestroyEngine [function]</a> </li><li><a href="#sgs-DumpCompiled-function">sgs_DumpCompiled [function]</a> </li><li><a href="#sgs-DumpVar-function">sgs_DumpVar [function]</a> </li><li><a href="#sgs-EqualTypes-function">sgs_EqualTypes [function]</a> </li><li><a href="#sgs-Errno-function-alias">sgs_Errno [function alias]</a> </li><li><a href="#sgs-EvalBuffer-function">sgs_EvalBuffer [function]</a> </li><li><a href="#sgs-EvalFile-function">sgs_EvalFile [function]</a> </li><li><a href="#sgs-EvalString-function-alias">sgs_EvalString [function alias]</a> </li><li><a href="#sgs-ExecBuffer-function-alias">sgs_ExecBuffer [function alias]</a> </li><li><a href="#sgs-ExecFile-function-alias">sgs_ExecFile [function alias]</a> </li><li><a href="#sgs-ExecString-function-alias">sgs_ExecString [function alias]</a> </li><li><a href="#sgs-FCall-P-functions">sgs_FCall(P) [functions]</a> </li><li><a href="#sgs-FindType-function">sgs_FindType [function]</a> </li><li><a href="#sgs-FuncName-function">sgs_FuncName [function]</a> </li><li><a href="#sgs-GCExecute-function">sgs_GCExecute [function]</a> </li><li><a href="#sgs-GCMark-Array-function">sgs_GCMark(Array) [function]</a> </li><li><a href="#sgs-Get-Err-OutputFunc-function">sgs_Get(Err)OutputFunc [function]</a> </li><li><a href="#sgs-Get-functions">sgs_Get*** [functions]</a> </li><li><a href="#sgs-GetEnv-function">sgs_GetEnv [function]</a> </li><li><a href="#sgs-GetFramePtr-function">sgs_GetFramePtr [function]</a> </li><li><a href="#sgs-GetGlobalPP-function">sgs_GetGlobalPP [function]</a> </li><li><a href="#sgs-GetHookFunc-function">sgs_GetHookFunc [function]</a> </li><li><a href="#sgs-GetIndex-functions">sgs_GetIndex*** [functions]</a> </li><li><a href="#sgs-GetIterator-P-functions">sgs_GetIterator(P) [functions]</a> </li><li><a href="#sgs-GetLastErrno-function-alias">sgs_GetLastErrno [function alias]</a> </li><li><a href="#sgs-GetMsgFunc-function">sgs_GetMsgFunc [function]</a> </li><li><a href="#sgs-GetObjectData-P-functions">sgs_GetObjectData(P) [functions]</a> </li><li><a href="#sgs-GetObjectIface-P-functions">sgs_GetObjectIface(P) [functions]</a> </li><li><a href="#sgs-GetObjectStruct-P-functions">sgs_GetObjectStruct(P) [functions]</a> </li><li><a href="#sgs-GetStackItem-function">sgs_GetStackItem [function]</a> </li><li><a href="#sgs-GetStringPtr-P-functions">sgs_GetStringPtr(P) [functions]</a> </li><li><a href="#sgs-GetStringSize-P-functions">sgs_GetStringSize(P) [functions]</a> </li><li><a href="#sgs-Global-functions">sgs_Global*** [functions]</a> </li><li><a href="#sgs-GlobalCall-function">sgs_GlobalCall [function]</a> </li><li><a href="#sgs-HasFuncName-function">sgs_HasFuncName [function]</a> </li><li><a href="#sgs-IncDec-function">sgs_IncDec [function]</a> </li><li><a href="#sgs-Include-function-alias">sgs_Include [function alias]</a> </li><li><a href="#sgs-IncludeExt-function">sgs_IncludeExt [function]</a> </li><li><a href="#sgs-Init-functions">sgs_Init*** [functions]</a> </li><li><a href="#sgs-InitArray-function">sgs_InitArray [function]</a> </li><li><a href="#sgs-InitDict-function">sgs_InitDict [function]</a> </li><li><a href="#sgs-InitMap-function">sgs_InitMap [function]</a> </li><li><a href="#sgs-InsertVariable-function">sgs_InsertVariable [function]</a> </li><li><a href="#sgs-IsCallable-P-functions">sgs_IsCallable(P) [functions]</a> </li><li><a href="#sgs-IsFreedString32-function">sgs_IsFreedString32 [function]</a> </li><li><a href="#sgs-IsNumericString-function">sgs_IsNumericString [function]</a> </li><li><a href="#sgs-IsObject-P-functions">sgs_IsObject(P) [functions]</a> </li><li><a href="#sgs-IsType-P-function-aliases">sgs_IsType(P) [function aliases]</a> </li><li><a href="#sgs-IsValidIndex-function">sgs_IsValidIndex [function]</a> </li><li><a href="#sgs-ItemType-function">sgs_ItemType [function]</a> </li><li><a href="#sgs-IterAdvance-P-functions">sgs_IterAdvance(P) [functions]</a> </li><li><a href="#sgs-IterGetData-P-functions">sgs_IterGetData(P) [functions]</a> </li><li><a href="#sgs-IterPushData-P-functions">sgs_IterPushData(P) [functions]</a> </li><li><a href="#sgs-LoadArgs-function-alias">sgs_LoadArgs [function alias]</a> </li><li><a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgsExt(VA) [function]</a> </li><li><a href="#sgs-LoadLib-functions">sgs_LoadLib_*** [functions]</a> </li><li><a href="#sgs-MakeClosure-function">sgs_MakeClosure [function]</a> </li><li><a href="#sgs-Memory-function">sgs_Memory [function]</a> </li><li><a href="#sgs-Method-function">sgs_Method [function]</a> </li><li><a href="#sgs-Msg-function">sgs_Msg [function]</a> </li><li><a href="#sgs-ObjAcquire-function">sgs_ObjAcquire [function]</a> </li><li><a href="#sgs-ObjAssign-function">sgs_ObjAssign [function]</a> </li><li><a href="#sgs-ObjCallDtor-function">sgs_ObjCallDtor [function]</a> </li><li><a href="#sgs-ObjGCMark-function">sgs_ObjGCMark [function]</a> </li><li><a href="#sgs-ObjRelease-function">sgs_ObjRelease [function]</a> </li><li><a href="#sgs-ObjectAction-function">sgs_ObjectAction [function]</a> </li><li><a href="#sgs-PadString-function">sgs_PadString [function]</a> </li><li><a href="#sgs-Parse-functions">sgs_Parse*** [functions]</a> </li><li><a href="#sgs-ParseMethod-function">sgs_ParseMethod [function]</a> </li><li><a href="#sgs-PeekStackItem-function">sgs_PeekStackItem [function]</a> </li><li><a href="#sgs-Pop-function">sgs_Pop [function]</a> </li><li><a href="#sgs-PopSkip-function">sgs_PopSkip [function]</a> </li><li><a href="#sgs-Push-functions">sgs_Push*** [functions]</a> </li><li><a href="#sgs-PushArray-function">sgs_PushArray [function]</a> </li><li><a href="#sgs-PushDict-function">sgs_PushDict [function]</a> </li><li><a href="#sgs-PushEnv-function">sgs_PushEnv [function]</a> </li><li><a href="#sgs-PushErrorInfo-function">sgs_PushErrorInfo [function]</a> </li><li><a href="#sgs-PushGlobal-function">sgs_PushGlobal [function]</a> </li><li><a href="#sgs-PushIndex-functions">sgs_PushIndex** [functions]</a> </li><li><a href="#sgs-PushItem-function">sgs_PushItem [function]</a> </li><li><a href="#sgs-PushIterator-P-functions">sgs_PushIterator(P) [functions]</a> </li><li><a href="#sgs-PushMap-function">sgs_PushMap [function]</a> </li><li><a href="#sgs-PushNumIndex-function">sgs_PushNumIndex [function]</a> </li><li><a href="#sgs-PushPath-function">sgs_PushPath [function]</a> </li><li><a href="#sgs-PushProperty-function">sgs_PushProperty [function]</a> </li><li><a href="#sgs-PushString32-function">sgs_PushString32 [function]</a> </li><li><a href="#sgs-PushStringBuf32-function">sgs_PushStringBuf32 [function]</a> </li><li><a href="#sgs-Reg-Consts-function">sgs_Reg***Consts [function]</a> </li><li><a href="#sgs-RegisterType-function">sgs_RegisterType [function]</a> </li><li><a href="#sgs-Release-Array-function">sgs_Release(Array) [function]</a> </li><li><a href="#sgs-Serialize-function">sgs_Serialize [function]</a> </li><li><a href="#sgs-SerializeObject-function">sgs_SerializeObject [function]</a> </li><li><a href="#sgs-Set-Err-OutputFunc-function">sgs_Set(Err)OutputFunc [function]</a> </li><li><a href="#sgs-SetEnv-function">sgs_SetEnv [function]</a> </li><li><a href="#sgs-SetErrno-function-alias">sgs_SetErrno [function alias]</a> </li><li><a href="#sgs-SetGlobalPP-function">sgs_SetGlobalPP [function]</a> </li><li><a href="#sgs-SetHookFunc-function">sgs_SetHookFunc [function]</a> </li><li><a href="#sgs-SetIndex-functions">sgs_SetIndex*** [functions]</a> </li><li><a href="#sgs-SetMsgFunc-function">sgs_SetMsgFunc [function]</a> </li><li><a href="#sgs-SetObjectData-P-functions">sgs_SetObjectData(P) [functions]</a> </li><li><a href="#sgs-SetObjectIface-P-functions">sgs_SetObjectIface(P) [functions]</a> </li><li><a href="#sgs-SetStackItem-function">sgs_SetStackItem [function]</a> </li><li><a href="#sgs-SetStackSize-function">sgs_SetStackSize [function]</a> </li><li><a href="#sgs-StackFrameInfo-function">sgs_StackFrameInfo [function]</a> </li><li><a href="#sgs-StackSize-function">sgs_StackSize [function]</a> </li><li><a href="#sgs-Stat-function">sgs_Stat [function]</a> </li><li><a href="#sgs-StdMsgFunc-NoAbort-functions">sgs_StdMsgFunc(_NoAbort) [functions]</a> </li><li><a href="#sgs-StdOutputFunc-function">sgs_StdOutputFunc [function]</a> </li><li><a href="#sgs-StoreEnv-function">sgs_StoreEnv [function]</a> </li><li><a href="#sgs-StoreGlobal-function">sgs_StoreGlobal [function]</a> </li><li><a href="#sgs-StoreIndex-functions">sgs_StoreIndex** [functions]</a> </li><li><a href="#sgs-StoreItem-function">sgs_StoreItem [function]</a> </li><li><a href="#sgs-StoreNumIndex-function">sgs_StoreNumIndex [function]</a> </li><li><a href="#sgs-StorePath-function">sgs_StorePath [function]</a> </li><li><a href="#sgs-StoreProperty-function">sgs_StoreProperty [function]</a> </li><li><a href="#sgs-StoreVariable-function">sgs_StoreVariable [function]</a> </li><li><a href="#sgs-StringConcat-function">sgs_StringConcat [function]</a> </li><li><a href="#sgs-To-functions">sgs_To*** [functions]</a> </li><li><a href="#sgs-ToPrintSafeString-function">sgs_ToPrintSafeString [function]</a> </li><li><a href="#sgs-ToString-Fast-P-function-aliases">sgs_ToString(Fast)(P) [function aliases]</a> </li><li><a href="#sgs-ToStringBuf-Fast-P-functions">sgs_ToStringBuf(Fast)(P) [functions]</a> </li><li><a href="#sgs-TypeOf-function">sgs_TypeOf [function]</a> </li><li><a href="#sgs-UnregisterType-function">sgs_UnregisterType [function]</a> </li><li><a href="#sgs-Unserialize-function">sgs_Unserialize [function]</a> </li><li><a href="#sgs-WriteErrorInfo-function">sgs_WriteErrorInfo [function]</a></li></ul></div> <div class='item'><a name='sgs-CreateEngine-function-alias'></a><hr><h2>sgs_CreateEngine [function alias]</h2><h3>sgs_Context* sgs_CreateEngine()</h3><h4>returns a new scripting engine context</h4><ul><li>alias to <code>sgs_CreateEngineExt( sgs_DefaultMemFunc, NULL )</code></li></ul></div> <div class='item'><a name='sgs-CreateEngineExt-function'></a><hr><h2>sgs_CreateEngineExt [function]</h2><h3>sgs_Context* sgs_CreateEngineExt( sgs_MemFunc memfunc, void* mfuserdata )</h3><h4>returns a new scripting engine context, attached to the specified allocator</h4></div> <div class='item'><a name='sgs-DestroyEngine-function'></a><hr><h2>sgs_DestroyEngine [function]</h2><h3>sgs_DestroyEngine( sgs_Context* C )</h3><h4>destroys the passed context and frees all memory associated to it</h4></div> <div class='item'><a name='sgs-ExecString-function-alias'></a><hr><h2>sgs_ExecString [function alias]</h2><h3>SGSRESULT sgs_ExecString( sgs_Context* C, const char* str )</h3><h4>compiles and executes a string of text</h4><ul><li>leaves the stack the same as it was before the call </li><li>alias to <code>sgs_ExecBuffer( C, str, SGS_STRINGLENGTHFUNC( str ) )</code> </li><li>theoretically bytecode is supported but it will most probably be trimmed by the string length function, unless a different string termination mark is used, and a different string length function to detect it is set</li></ul><h4>error codes</h4><ul><li>SGS_ECOMP: compiler error </li><li>SGS_EINVAL: passed data was not recognized</li></ul></div> <div class='item'><a name='sgs-ExecBuffer-function-alias'></a><hr><h2>sgs_ExecBuffer [function alias]</h2><h3>SGSRESULT sgs_ExecBuffer( sgs_Context* C, const char* buf, sgs_SizeVal size )</h3><h4>compiles and executes a buffer of text or bytecode</h4><ul><li>leaves the stack the same as it was before the call </li><li>alias to <code>sgs_EvalBuffer( C, buf, size, NULL )</code></li></ul><h4>error codes</h4><ul><li>SGS_ECOMP: compiler error </li><li>SGS_EINVAL: passed data was not recognized</li></ul></div> <div class='item'><a name='sgs-EvalString-function-alias'></a><hr><h2>sgs_EvalString [function alias]</h2><h3>SGSRESULT sgs_EvalString( sgs_Context* C, const char* str, int* rvc )</h3><h4>compiles and executes a string of text, optionally leaving the return values on stack and returning the number of values via <code>rvc</code></h4><ul><li>if <code>rvc</code> is not set (NULL), return values are removed - the stack is the same as it was before the call </li><li>alias to sgs_EvalBuffer( C, str, SGS_STRINGLENGTHFUNC( str ), rvc )</li></ul><h4>error codes</h4><ul><li>SGS_ECOMP: compiler error </li><li>SGS_EINVAL: passed data was not recognized</li></ul></div> <div class='item'><a name='sgs-EvalBuffer-function'></a><hr><h2>sgs_EvalBuffer [function]</h2><h3>SGSRESULT sgs_EvalBuffer( sgs_Context* C, const char* buf, sgs_SizeVal size, int* rvc )</h3><h4>compiles and executes a buffer of text or bytecode, optionally leaving the return values on stack and returning the number of values via <code>rvc</code></h4><ul><li>if <code>rvc</code> is not set (NULL), return values are removed - the stack is the same as it was before the call</li></ul><h4>error codes</h4><ul><li>SGS_ECOMP: compiler error </li><li>SGS_EINVAL: passed data was not recognized</li></ul></div> <div class='item'><a name='sgs-ExecFile-function-alias'></a><hr><h2>sgs_ExecFile [function alias]</h2><h3>SGSRESULT sgs_ExecFile( sgs_Context* C, const char* filename )</h3><h4>compiles and executes a file containing script text or bytecode</h4><ul><li>leaves the stack the same as it was before the call </li><li>alias to <code>sgs_EvalFile( C, filename, NULL )</code></li></ul><h4>error codes</h4><ul><li>SGS_ECOMP: compiler error </li><li>SGS_EINVAL: passed data was not recognized</li></ul></div> <div class='item'><a name='sgs-EvalFile-function'></a><hr><h2>sgs_EvalFile [function]</h2><h3>SGSRESULT sgs_EvalFile( sgs_Context* C, const char* filename, int* rvc )</h3><h4>compiles and executes a file containing script text or bytecode, optionally leaving the return values on stack and returning the number of values via <code>rvc</code></h4><ul><li>if <code>rvc</code> is not set (NULL), return values are removed - the stack is the same as it was before the call</li></ul><h4>error codes</h4><ul><li>SGS_ECOMP: compiler error </li><li>SGS_EINVAL: passed data was not recognized</li></ul></div> <div class='item'><a name='sgs-Include-function-alias'></a><hr><h2>sgs_Include [function alias]</h2><h3>SGSBOOL sgs_Include( sgs_Context* C, const char* name )</h3><h4>includes an item by the specified name, returning if completed successfully</h4><ul><li>a C version of the <code>include</code> SGS function </li><li>alias to <code>sgs_IncludeExt( C, name, NULL )</code></li></ul></div> <div class='item'><a name='sgs-IncludeExt-function'></a><hr><h2>sgs_IncludeExt [function]</h2><h3>SGSBOOL sgs_IncludeExt( sgs_Context* C, const char* name, const char* searchpath )</h3><h4>includes an item by the specified name, optionally looking in the places specified by the search path, returning if completed successfully</h4><ul><li>a C version of the <a href="#include-function">include</a> SGS function </li><li><code>searchpath</code> overrides SGS_PATH for the time of execution</li></ul></div> <div class='item'><a name='sgs-Compile-function'></a><hr><h2>sgs_Compile [function]</h2><h3>SGSRESULT sgs_Compile( sgs_Context* C, const char* buf, size_t size, char** outbuf, size_t* outsize )</h3><h4>compile a buffer of SGScript code, returning the compiled code buffer on success</h4><ul><li>a C version of <a href="#compile-sgs-function">compile_sgs</a> SGS function </li><li><code>outbuf</code> must be freed after usage with one of the relevant memory handling functions </li><li><code>outbuf</code> and <code>outsize</code> will only contain valid buffer (pointer and size) on success </li><li>all info/warning/error messages are passed to the <a href="#Messaging-system">Messaging system</a></li></ul><h4>error codes</h4><ul><li>SGS_ECOMP: compiler error </li><li>SGS_EINVAL: passed data was too big </li><li>SGS_EINPROC: failed to serialize bytecode</li></ul></div> <div class='item'><a name='sgs-DumpCompiled-function'></a><hr><h2>sgs_DumpCompiled [function]</h2><h3>SGSRESULT sgs_DumpCompiled( sgs_Context* C, const char* buf, size_t size )</h3><h4>dump compiled bytecode or SGScript code buffer to stdout</h4><ul><li>code is compiled before dumping if SGScript code is passed <ul><li>in that case, all info/warning/error messages are passed to the <a href="#Messaging-system">Messaging system</a></li></ul></li></ul><h4>error codes</h4><ul><li>SGS_ECOMP: compiler error </li><li>SGS_EINVAL: passed data was too big</li></ul></div> <div class='item'><a name='sgs-LoadLib-functions'></a><hr><h2>sgs_LoadLib_*** [functions]</h2><h3>SGSRESULT sgs_LoadLib_Fmt( sgs_Context* C )</h3><h3>SGSRESULT sgs_LoadLib_IO( sgs_Context* C )</h3><h3>SGSRESULT sgs_LoadLib_Math( sgs_Context* C )</h3><h3>SGSRESULT sgs_LoadLib_OS( sgs_Context* C )</h3><h3>SGSRESULT sgs_LoadLib_RE( sgs_Context* C )</h3><h3>SGSRESULT sgs_LoadLib_String( sgs_Context* C )</h3><h4>loads the library into the specified context</h4><ul><li>it is generally unnecessary to check for these error codes</li></ul><h4>error codes</h4><ul><li>SGS_E****: first error encountered (operation stopped somewhere in the middle)</li></ul></div> <div class='item'><a name='sgs-Reg-Consts-function'></a><hr><h2>sgs_Reg***Consts [function]</h2><h3>SGSRESULT sgs_RegFuncConsts( sgs_Context* C, const sgs_RegFuncConst* list, int size )</h3><h3>SGSRESULT sgs_RegIntConsts( sgs_Context* C, const sgs_RegIntConst* list, int size )</h3><h3>SGSRESULT sgs_RegRealConsts( sgs_Context* C, const sgs_RegRealConst* list, int size )</h3><h4>loads the specified list of constants in the context</h4><ul><li>the end of list can be specified in two ways <ul><li>set the size to <code>sizeof(list)/sizeof(list[0])</code> </li><li>set the size to -1 and end the list with <code>SGS_RC_END()</code> </li><li>using both at the same time should be reserved to special cases only</li></ul></li></ul><h4>error codes</h4><ul><li>SGS_E****: first error encountered (operation stopped somewhere in the middle)</li></ul></div> <div class='item'><a name='sgs-Init-functions'></a><hr><h2>sgs_Init*** [functions]</h2><h3>void sgs_InitNull( sgs_Variable* out )</h3><h3>void sgs_InitBool( sgs_Variable* out, sgs_Bool value )</h3><h3>void sgs_InitInt( sgs_Variable* out, sgs_Int value )</h3><h3>void sgs_InitReal( sgs_Variable* out, sgs_Real value )</h3><h3>void sgs_InitStringBuf( sgs_Context* C, sgs_Variable* out, const char* str, sgs_SizeVal size )</h3><h3>void sgs_InitString( sgs_Context* C, sgs_Variable* out, const char* str )</h3><h3>void sgs_InitCFunction( sgs_Variable* out, sgs_CFunc func )</h3><h3>void sgs_InitObject( sgs_Context* C, sgs_Variable* out, void* data, sgs_ObjInterface* iface )</h3><h3>void* sgs_InitObjectIPA( sgs_Context* C, sgs_Variable* out, sgs_SizeVal added, sgs_ObjInterface* iface )</h3><h3>void sgs_InitPtr( sgs_Variable* out, void* ptr )</h3><h3>void sgs_InitObjectPtr( sgs_Variable* out, sgs_VarObj* obj )</h3><ul><li>sgs_Bool is transformed to 0/1 before pushing, everything else is unchanged </li><li>sgs_InitStringBuf( C, NULL, size ) would allocate an uninitialized buffer <ul><li>it is accessible immediately by <a href="#sgs-GetStringPtr-P-functions">sgs_GetStringPtrP</a> / <a href="#sgs-GetStringSize-P-functions">sgs_GetStringSizeP</a> </li></ul><li>sgs_InitObjectIPA stands for &quot;initialize object, allocate memory in-place&quot; <ul><li>it means that the <code>added</code> memory space will be appended to the end of object allocation </li><li>this allows to allocate all object data for most objects with just one allocation, instead of two </li><li>the allocated memory will be returned and also available via <a href="#sgs-GetObjectData-P-functions">sgs_GetObjectDataP</a></li></ul></li></ul></div> <div class='item'><a name='sgs-InitArray-function'></a><hr><h2>sgs_InitArray [function]</h2><h3>SGSRESULT sgs_InitArray( sgs_Context* C, sgs_Variable* out, sgs_SizeVal numitems )</h3><h4>creates an array at <code>out</code> from <code>numitems</code> last items on the stack, pops those items</h4><h4>error codes</h4><ul><li>SGS_EINVAL: more items are selected than exist in the current stack frame</li></ul></div> <div class='item'><a name='sgs-InitDict-function'></a><hr><h2>sgs_InitDict [function]</h2><h3>SGSRESULT sgs_InitDict( sgs_Context* C, sgs_Variable* out, sgs_SizeVal numitems )</h3><h4>creates a dict at <code>out</code> from <code>numitems</code> last items on the stack, pops those items</h4><ul><li><code>numitems</code> can be even or 0, since all odd arguments are keys and all even arguments are values</li></ul><h4>error codes</h4><ul><li>SGS_EINVAL: more items are selected than exist in the current stack frame or <code>numitems</code> wasn&#39;t even or 0</li></ul></div> <div class='item'><a name='sgs-InitMap-function'></a><hr><h2>sgs_InitMap [function]</h2><h3>SGSRESULT sgs_InitMap( sgs_Context* C, sgs_Variable* out, sgs_SizeVal numitems )</h3><h4>creates a map at <code>out</code> from <code>numitems</code> last items on the stack, pops those items</h4><ul><li><code>numitems</code> can be even or 0, since all odd arguments are keys and all even arguments are values</li></ul><h4>error codes</h4><ul><li>SGS_EINVAL: more items are selected than exist in the current stack frame or <code>numitems</code> wasn&#39;t even or 0</li></ul></div> <div class='item'><a name='sgs-Push-functions'></a><hr><h2>sgs_Push*** [functions]</h2><h3>void sgs_PushNull( sgs_Context* C )</h3><h3>void sgs_PushBool( sgs_Context* C, sgs_Bool value )</h3><h3>void sgs_PushInt( sgs_Context* C, sgs_Int value )</h3><h3>void sgs_PushReal( sgs_Context* C, sgs_Real value )</h3><h3>void sgs_PushStringBuf( sgs_Context* C, const char* str, sgs_SizeVal size )</h3><h3>void sgs_PushString( sgs_Context* C, const char* str )</h3><h3>void sgs_PushCFunction( sgs_Context* C, sgs_CFunc func )</h3><h3>void sgs_PushObject( sgs_Context* C, void* data, sgs_ObjInterface* iface )</h3><h3>void* sgs_PushObjectIPA( sgs_Context* C, sgs_SizeVal added, sgs_ObjInterface* iface )</h3><h3>void sgs_PushPtr( sgs_Context* C, void* ptr )</h3><h3>void sgs_PushObjectPtr( sgs_Context* C, sgs_VarObj* obj )</h3><h3>SGSRESULT sgs_PushVariable( sgs_Context* C, sgs_Variable* var )</h3><h4>pushes the data on the stack, as a new entry, appended to the end</h4><ul><li>sgs_Bool is transformed to 0/1 before pushing, everything else is unchanged </li><li>sgs_PushStringBuf( C, NULL, size ) would allocate an uninitialized buffer <ul><li>it is accessible immediately by <a href="#sgs-GetStringPtr-P-functions">sgs_GetStringPtr( C, -1 )</a> / <a href="#sgs-GetStringSize-P-functions">sgs_GetStringSize( C, -1 )</a> </li></ul><li>sgs_PushObjectIPA stands for &quot;push object, allocate memory in-place&quot; <ul><li>it means that the <code>added</code> memory space will be appended to the end of object allocation </li><li>this allows to allocate all object data for most objects with just one allocation, instead of two </li><li>the allocated memory will be returned and also available via <a href="#sgs-GetObjectData-P-functions">sgs_GetObjectData( C, -1 )</a> </li></ul><li>sgs_PushVariable will increment the reference count of strings, SGS functions and objects <ul><li>it will also return EINVAL if type of variable isn&#39;t one of the allowed types </li></ul><li>these functions do not throw an error when the stack is full since there is no way to handle that</li></ul></div> <div class='item'><a name='sgs-StoreVariable-function'></a><hr><h2>sgs_StoreVariable [function]</h2><h3>SGSRESULT sgs_StoreVariable( sgs_Context* C, sgs_Variable* var )</h3><h4>copy the topmost item of the current stack frame to the specified place, acquire it and pop it</h4><h4>error codes</h4><ul><li>SGS_ENOTFND: stack frame is empty</li></ul></div> <div class='item'><a name='sgs-Pop-function'></a><hr><h2>sgs_Pop [function]</h2><h3>SGSRESULT sgs_Pop( sgs_Context* C, int count )</h3><h4>pops <code>count</code> variables off the current frame of the stack</h4><h4>error codes</h4><ul><li>SGS_EINVAL: <code>count</code> was bigger than the number of items in the current stack frame or <code>count</code> is less than 0</li></ul></div> <div class='item'><a name='sgs-PopSkip-function'></a><hr><h2>sgs_PopSkip [function]</h2><h3>SGSRESULT sgs_PopSkip( sgs_Context* C, int count, int skip )</h3><h4>pops <code>count</code> variables off the current frame of the stack, skipping the last <code>skip</code> elements</h4><h4>error codes</h4><ul><li>SGS_EINVAL: <code>count+skip</code> was bigger than the number of items in the current stack frame or <code>count</code> is less than 0 or <code>skip</code> is less than 0</li></ul></div> <div class='item'><a name='sgs-InsertVariable-function'></a><hr><h2>sgs_InsertVariable [function]</h2><h3>SGSRESULT sgs_InsertVariable( sgs_Context* C, int pos, sgs_Variable* var )</h3><h4>inserts a variable <code>var</code> at a given index <code>pos</code> of the current stack frame, increasing its reference count</h4><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds</li></ul></div> <div class='item'><a name='sgs-PushArray-function'></a><hr><h2>sgs_PushArray [function]</h2><h3>SGSRESULT sgs_PushArray( sgs_Context* C, sgs_SizeVal numitems )</h3><h4>creates an array from <code>numitems</code> last items on the stack, pops those items and pushes the array</h4><h4>error codes</h4><ul><li>SGS_EINVAL: more items are selected than exist in the current stack frame</li></ul></div> <div class='item'><a name='sgs-PushDict-function'></a><hr><h2>sgs_PushDict [function]</h2><h3>SGSRESULT sgs_PushDict( sgs_Context* C, sgs_SizeVal numitems )</h3><h4>creates a dict from <code>numitems</code> last items on the stack, pops those items and pushes the dict</h4><ul><li><code>numitems</code> can be even or 0, since all odd arguments are keys and all even arguments are values</li></ul><h4>error codes</h4><ul><li>SGS_EINVAL: more items are selected than exist in the current stack frame or <code>numitems</code> wasn&#39;t even or 0</li></ul></div> <div class='item'><a name='sgs-PushMap-function'></a><hr><h2>sgs_PushMap [function]</h2><h3>SGSRESULT sgs_PushMap( sgs_Context* C, sgs_SizeVal numitems )</h3><h4>creates a map from <code>numitems</code> last items on the stack, pops those items and pushes the map</h4><ul><li><code>numitems</code> can be even or 0, since all odd arguments are keys and all even arguments are values</li></ul><h4>error codes</h4><ul><li>SGS_EINVAL: more items are selected than exist in the current stack frame or <code>numitems</code> wasn&#39;t even or 0</li></ul></div> <div class='item'><a name='sgs-PushItem-function'></a><hr><h2>sgs_PushItem [function]</h2><h3>SGSRESULT sgs_PushItem( sgs_Context* C, sgs_StkIdx item )</h3><h4>copy an item from the current stack frame and append it to the end of the stack</h4><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds</li></ul></div> <div class='item'><a name='sgs-StoreItem-function'></a><hr><h2>sgs_StoreItem [function]</h2><h3>SGSRESULT sgs_StoreItem( sgs_Context* C, sgs_StkIdx item )</h3><h4>copy last item in current stack frame to index <code>item</code> and pop it</h4><ul><li><code>item</code> refers to a position after the pop operation, therefore -1 means one element before the last etc.</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds</li></ul></div> <div class='item'><a name='sgs-GetIndex-functions'></a><hr><h2>sgs_GetIndex*** [functions]</h2><h3>SGSRESULT sgs_GetIndexPPP( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, sgs_Variable* out, int isprop )</h3><h3>SGSRESULT sgs_GetIndexIPP( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, sgs_Variable* out, int isprop )</h3><h3>SGSRESULT sgs_GetIndexPIP( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, sgs_Variable* out, int isprop )</h3><h3>SGSRESULT sgs_GetIndexIIP( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, sgs_Variable* out, int isprop )</h3><h3>SGSRESULT sgs_GetIndexPPI( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, sgs_StkIdx out, int isprop )</h3><h3>SGSRESULT sgs_GetIndexIPI( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, sgs_StkIdx out, int isprop )</h3><h3>SGSRESULT sgs_GetIndexPII( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, sgs_StkIdx out, int isprop )</h3><h3>SGSRESULT sgs_GetIndexIII( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, sgs_StkIdx out, int isprop )</h3><h4>retrieve index/property <code>idx</code> from the specified variable <code>obj</code> to the position <code>out</code>, specifying retrieval type via <code>isprop</code></h4><ul><li>last 3 letters in function name determines the type for parameters 2, 3 and 4: P for pointers, I for stack indices</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: something was not pointing inside the current stack frame </li><li>SGS_ENOTFND: index/property was not found </li><li>other codes may appear if returned by custom objects</li></ul></div> <div class='item'><a name='sgs-SetIndex-functions'></a><hr><h2>sgs_SetIndex*** [functions]</h2><h3>SGSRESULT sgs_SetIndexPPP( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, sgs_Variable* val, int isprop )</h3><h3>SGSRESULT sgs_SetIndexIPP( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, sgs_Variable* val, int isprop )</h3><h3>SGSRESULT sgs_SetIndexPIP( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, sgs_Variable* val, int isprop )</h3><h3>SGSRESULT sgs_SetIndexIIP( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, sgs_Variable* val, int isprop )</h3><h3>SGSRESULT sgs_SetIndexPPI( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, sgs_StkIdx val, int isprop )</h3><h3>SGSRESULT sgs_SetIndexIPI( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, sgs_StkIdx val, int isprop )</h3><h3>SGSRESULT sgs_SetIndexPII( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, sgs_StkIdx val, int isprop )</h3><h3>SGSRESULT sgs_SetIndexIII( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, sgs_StkIdx val, int isprop )</h3><h4>set index/property <code>idx</code> in the specified variable <code>obj</code> to the value <code>val</code>, specifying type via <code>isprop</code></h4><ul><li>last 3 letters in function name determines the type for parameters 2, 3 and 4: P for pointers, I for stack indices</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: something was not pointing inside the current stack frame </li><li>SGS_ENOTFND: index/property was not found </li><li>SGS_EINVAL: specified value could not be used </li><li>other codes may appear if returned by custom objects</li></ul></div> <div class='item'><a name='sgs-PushIndex-functions'></a><hr><h2>sgs_PushIndex** [functions]</h2><h3>SGSRESULT sgs_PushIndexPP( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, int isprop )</h3><h3>SGSRESULT sgs_PushIndexIP( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, int isprop )</h3><h3>SGSRESULT sgs_PushIndexPI( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, int isprop )</h3><h3>SGSRESULT sgs_PushIndexII( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, int isprop )</h3><h4>retrieve and push index/property <code>idx</code> from the specified variable <code>obj</code>, specifying retrieval type via <code>isprop</code></h4><ul><li>last 2 letters in function name determines the type for parameters 2 and 3: P for pointers, I for stack indices</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: something was not pointing inside the current stack frame </li><li>SGS_ENOTFND: index/property was not found </li><li>other codes may appear if returned by custom objects</li></ul></div> <div class='item'><a name='sgs-StoreIndex-functions'></a><hr><h2>sgs_StoreIndex** [functions]</h2><h3>SGSRESULT sgs_StoreIndexPP( sgs_Context* C, sgs_Variable* obj, sgs_Variable* idx, int isprop )</h3><h3>SGSRESULT sgs_StoreIndexIP( sgs_Context* C, sgs_StkIdx obj, sgs_Variable* idx, int isprop )</h3><h3>SGSRESULT sgs_StoreIndexPI( sgs_Context* C, sgs_Variable* obj, sgs_StkIdx idx, int isprop )</h3><h3>SGSRESULT sgs_StoreIndexII( sgs_Context* C, sgs_StkIdx obj, sgs_StkIdx idx, int isprop )</h3><h4>set index/property <code>idx</code> in the specified variable <code>obj</code> to the topmost variable in stack, specifying type via <code>isprop</code>, then pop the topmost variable in stack if successful</h4><ul><li>last 2 letters in function name determines the type for parameters 2 and 3: P for pointers, I for stack indices</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: something was not pointing inside the current stack frame </li><li>SGS_ENOTFND: index/property was not found </li><li>SGS_EINVAL: specified value could not be used </li><li>SGS_EINPROC: current stack frame is empty </li><li>other codes may appear if returned by custom objects</li></ul></div> <div class='item'><a name='sgs-GetGlobalPP-function'></a><hr><h2>sgs_GetGlobalPP [function]</h2><h3>SGSRESULT sgs_GetGlobalPP( SGS_CTX, sgs_Variable* idx, sgs_Variable* out )</h3><h4>retrieve a global variable by index <code>idx</code> to position <code>out</code></h4><h4>error codes</h4><ul><li>SGS_ENOTSUP: <code>idx</code> was not a string </li><li>SGS_ENOTFND: index was not found</li></ul></div> <div class='item'><a name='sgs-SetGlobalPP-function'></a><hr><h2>sgs_SetGlobalPP [function]</h2><h3>SGSRESULT sgs_SetGlobalPP( SGS_CTX, sgs_Variable* idx, sgs_Variable* val )</h3><h4>set a global variable <code>val</code> to index <code>idx</code></h4><h4>error codes</h4><ul><li>SGS_ENOTSUP: <code>idx</code> was not a string / <code>idx</code> was _G and <code>val</code> was not a dict</li></ul></div> <div class='item'><a name='sgs-PushProperty-function'></a><hr><h2>sgs_PushProperty [function]</h2><h3>SGSRESULT sgs_PushProperty( sgs_Context* C, sgs_StkIdx obj, const char* name )</h3><h4>load and push the property of the item <code>obj</code> in the current stack frame</h4><h4>error codes</h4><ul><li>SGS_EBOUNDS: <code>obj</code> was not pointing inside the current stack frame </li><li>SGS_EINPROC: current stack frame is empty </li><li>SGS_ENOTFND: property was not found </li><li>other codes may appear if returned by custom objects</li></ul></div> <div class='item'><a name='sgs-StoreProperty-function'></a><hr><h2>sgs_StoreProperty [function]</h2><h3>SGSRESULT sgs_StoreProperty( sgs_Context* C, sgs_StkIdx obj, const char* name )</h3><h4>copy and pop the topmost item of the current stack frame to the property <code>name</code> of variable <code>obj</code></h4><h4>error codes</h4><ul><li>SGS_EBOUNDS: <code>obj</code> was not pointing inside the current stack frame </li><li>SGS_ENOTFND: property was not found </li><li>other codes may appear if returned by custom objects</li></ul></div> <div class='item'><a name='sgs-PushNumIndex-function'></a><hr><h2>sgs_PushNumIndex [function]</h2><h3>SGSRESULT sgs_PushNumIndex( sgs_Context* C, sgs_StkIdx obj, sgs_Int idx )</h3><h4>load and push the integer index <code>idx</code> of the variable <code>obj</code></h4><h4>error codes:</h4><ul><li>SGS_EBOUNDS: <code>obj</code> was not pointing inside the current stack frame / array index out of bounds </li><li>SGS_ENOTFND: index was not found </li><li>other codes may appear if returned by custom objects</li></ul></div> <div class='item'><a name='sgs-StoreNumIndex-function'></a><hr><h2>sgs_StoreNumIndex [function]</h2><h3>SGSRESULT sgs_StoreNumIndex( sgs_Context* C, sgs_StkIdx obj, sgs_Int idx )</h3><h4>copy and pop the topmost item of the current stack to the integer index <code>idx</code> of variable <code>obj</code></h4><h4>error codes</h4><ul><li>SGS_EBOUNDS: <code>obj</code> was not pointing inside the current stack frame / array index out of bounds </li><li>SGS_ENOTFND: index was not found </li><li>other codes may appear if returned by custom objects</li></ul></div> <div class='item'><a name='sgs-PushGlobal-function'></a><hr><h2>sgs_PushGlobal [function]</h2><h3>SGSRESULT sgs_PushGlobal( sgs_Context* C, const char* name )</h3><h4>push the global variable <code>name</code> on the stack</h4><h4>error codes</h4><ul><li>SGS_ENOTFND: variable was not found</li></ul></div> <div class='item'><a name='sgs-StoreGlobal-function'></a><hr><h2>sgs_StoreGlobal [function]</h2><h3>SGSRESULT sgs_StoreGlobal( sgs_Context* C, const char* name )</h3><h4>copy and pop the topmost stack item to the global variable <code>name</code></h4><ul><li>_G is the environment table (a superglobal, list of global variable names and values)</li></ul><h4>error codes</h4><ul><li>SGS_EINPROC: current stack frame was empty </li><li>SGS_ENOTSUP: variable was not a dict (_G only accepts dict values)</li></ul></div> <div class='item'><a name='sgs-GetEnv-function'></a><hr><h2>sgs_GetEnv [function]</h2><h3>void sgs_GetEnv( SGS_CTX, sgs_Variable* out )</h3><h4>retrieve the global environment dict variable (_G)</h4></div> <div class='item'><a name='sgs-SetEnv-function'></a><hr><h2>sgs_SetEnv [function]</h2><h3>SGSRESULT sgs_SetEnv( SGS_CTX, sgs_Variable* var )</h3><h4>set a global environment dict variable from the variable <code>var</code></h4><h4>error codes</h4><ul><li>SGS_ENOTSUP: variable was not a dict (_G only accepts dict values)</li></ul></div> <div class='item'><a name='sgs-PushEnv-function'></a><hr><h2>sgs_PushEnv [function]</h2><h3>void sgs_PushEnv( SGS_CTX )</h3><h4>retrieve and push the global environment dict variable (_G)</h4></div> <div class='item'><a name='sgs-StoreEnv-function'></a><hr><h2>sgs_StoreEnv [function]</h2><h3>SGSRESULT sgs_StoreEnv( SGS_CTX )</h3><h4>set a global environment dict variable from the topmost stack item, then pop it if successful</h4><h4>error codes</h4><ul><li>SGS_EINPROC: current stack frame was empty </li><li>SGS_ENOTSUP: variable was not a dict (_G only accepts dict values)</li></ul></div> <div class='item'><a name='sgs-PushPath-function'></a><hr><h2>sgs_PushPath [function]</h2><h3>SGSRESULT sgs_PushPath( sgs_Context* C, sgs_StkIdx item, const char* path, ... )</h3><h4>push the variable specified by starting point <code>item</code> and traversal path <code>path</code></h4><p> <em class='notice-bgr'>The safety of this function is similar to that of the printf family of functions. Be explicit in what types you pass to the variable argument list to avoid errors.</em> </p><ul><li>the syntax of <code>path</code>: <ul><li>a list of letters, specifying a sub-variable to request (o,p,s,i,k,n)</li></ul></li></ul><h5>table of accepted letters</h5><p> <table> <tr><th>letter</th><th>property?</th><th>variable arguments</th><th>virtual machine access mode / description</th></tr> <tr><td>o</td><td>yes</td><td>SizeVal</td><td>integer property</td></tr> <tr><td>p</td><td>yes</td><td>C string</td><td>string property</td></tr> <tr><td>s</td><td>yes</td><td>SizeVal, buffer</td><td>special string property</td></tr> <tr><td>i</td><td>no</td><td>SizeVal</td><td>integer index</td></tr> <tr><td>k</td><td>no</td><td>C string</td><td>string index</td></tr> <tr><td>n</td><td>no</td><td>SizeVal, buffer</td><td>special string index</td></tr> </table> </p><ul><li>legend: <ul><li>SizeVal: sgs_SizeVal / int32_t </li><li>C string: null-terminated char* string </li><li>buffer: char* byte array, size is specified in the previous argument </li><li>property?: if yes, property access is used (object.property), otherwise index access is used (object[index])</li></ul></li></ul><h4>error codes</h4><ul><li>SGS_EINVAL: invalid symbol found in path / corresponding variable arguments had an invalid value </li><li>other errors, as returned by <a href="#sgs-PushIndex-functions">sgs_PushIndex***()</a></li></ul></div> <div class='item'><a name='sgs-StorePath-function'></a><hr><h2>sgs_StorePath [function]</h2><h3>SGSRESULT sgs_StorePath( sgs_Context* C, sgs_StkIdx item, const char* path, ... )</h3><h4>copy and pop the topmost item on stack to variable specified by starting point <code>item</code> and traversal path <code>path</code></h4><p> <em class='notice-bgr'>The safety of this function is similar to that of the printf family of functions. Be explicit in what types you pass to the variable argument list to avoid errors.</em> </p><ul><li>the syntax of <code>path</code> is the same as with <a href="#sgs-PushPath-function">sgs_PushPath</a> </li><li>the last item on the path (or in the case of an empty path, the starting point) is accessed with a store operation, the rest - with a push operation</li></ul><h4>error codes</h4><ul><li>SGS_EINVAL: invalid symbol found in path / corresponding variable arguments had an invalid value </li><li>SGS_EINPROC: current stack frame is empty </li><li>other errors, as returned by <a href="#sgs-PushIndex-functions">sgs_PushIndex***</a> or <a href="#sgs-StoreIndex-functions">sgs_StoreIndex***</a></li></ul></div> <div class='item'><a name='sgs-ArgErrorExt-function'></a><hr><h2>sgs_ArgErrorExt [function]</h2><h3>int sgs_ArgErrorExt( sgs_Context* C, int argid, int method, const char* expect, const char* expfx )</h3><h4>prints the argument type mismatch error</h4><ul><li><code>expfx</code> - prefix of <code>expect</code>, put exactly before this for things like &#39;strict &#39; </li><li>always returns 0 so it can be used to return and print an error in the same statement</li></ul></div> <div class='item'><a name='sgs-ArgError-function'></a><hr><h2>sgs_ArgError [function]</h2><h3>int sgs_ArgError( sgs_Context* C, int argid, int expect, int is_strict )</h3><h4>prints the argument type mismatch error</h4><ul><li>always returns 0 so it can be used to return and print an error in the same statement</li></ul></div> <div class='item'><a name='sgs-ArgError-function-aliases'></a><hr><h2>sgs_***ArgError [function aliases]</h2><h3>int sgs_FuncArgError( sgs_Context* C, int argid, int expect, int is_strict )</h3><h3>int sgs_MethodArgError( sgs_Context* C, int argid, int expect, int is_strict )</h3><h4>prints the argument type mismatch error</h4><ul><li>always returns 0 so it can be used to return and print an error in the same statement </li><li>alias to <code>sgs_ArgError( C, argid, Func/Method =&gt; 0/1, expect, is_strict )</code></li></ul></div> <div class='item'><a name='sgs-LoadArgsExt-VA-function'></a><hr><h2>sgs_LoadArgsExt(VA) [function]</h2><h3>SGSMIXED sgs_LoadArgsExt( sgs_Context* C, int from, const char* cmd, ... )</h3><h3>SGSMIXED sgs_LoadArgsExtVA( sgs_Context* C, int from, const char* cmd, va_list* args )</h3><h4>parse the stack items and retrieve their data according to <code>cmd</code>, starting from item <code>from</code></h4><ul><li>for anything function requires, pass the value; for anything it returns - the pointer to the value </li><li><code>cmd</code> is a string consisting of one-character commands </li><li>the commands are grouped into two kinds: control commands and parsing commands </li><li>function returns whether all required arguments have been parsed successfully <ul><li>thus, if function returns &lt; 1, state of outputs is somewhat unknown unless filled with defaults </li><li>it is guaranteed that all arguments will be parsed from first (specified) forward, not in any other way </li></ul><li><code>null</code> values in optional arguments are skipped (this may not apply to custom checking functions)</li></ul><p> <em class='notice-bgr'>unlike sgs_LoadArgs, it returns <code>SGSMIXED</code> and must be checked differently (&quot;ret.val. &gt; 0&quot;, if same output needed)</em> </p><h5>control commands</h5><ul><li><code>?</code> -- only check, do not write the result and do not require a pointer to write the data to </li><li><code>!</code> -- enable strict parsing for the next item (requires exactly the type specified </li><li><code>-</code>,<code>+</code> -- enable (-) or disable (+) treating integers as signed (default = true) </li><li><code>|</code> -- mark the point where required arguments end and optional arguments begin </li><li><code>#</code> -- do range checking on integer arguments (min/max of the required types) </li><li><code>^</code> -- clamp the argument to the range of the required type </li><li><code>~</code> -- ignore ranges and chop out-of-range integers (default) </li><li><code>&lt;</code> -- move argument pointer 1 item back (cannot move it before 0) </li><li><code>&gt;</code> -- move argument pointer 1 item forward </li><li><code>@</code> -- specify that this is a method (argument 0 = &#39;this&#39;; shifts argument indices on error printing by -1) </li><li><code>.</code> -- specify the end of argument list (how many arguments are expected)</li></ul><h5>parsing commands</h5><ul><li><code>n</code> -- check for <code>null</code> (returns SGSBOOL = 1, always strict) </li><li><code>b</code> -- check for <code>bool</code> (returns sgs_Bool) </li><li><code>c</code> -- check for <code>int</code> (returns int8_t or uint8_t, depending on sign settings, may check ranges) </li><li><code>w</code> -- check for <code>int</code> (returns int16_t or uint16_t, depending on sign settings, may check ranges) </li><li><code>l</code> -- check for <code>int</code> (returns int32_t or uint32_t, depending on sign settings, may check ranges) </li><li><code>q</code> -- check for <code>int</code> (returns int64_t or uint64_t, depending on sign settings, may check ranges) </li><li><code>i</code> -- check for <code>int</code> (returns sgs_Int, may check ranges) </li><li><code>f</code> -- check for <code>real</code> (returns float) </li><li><code>d</code> -- check for <code>real</code> (returns double) </li><li><code>r</code> -- check for <code>real</code> (returns sgs_Real) </li><li><code>s</code> -- check for <code>string</code> (returns char*) </li><li><code>m</code> -- check for <code>string</code> (returns char* string and sgs_SizeVal size) </li><li><code>p</code> -- check for <code>func/cfunc/object with CALL</code> (callables) (returns SGSBOOL = 1) </li><li><code>a</code> -- check for <code>array</code> (returns sgs_SizeVal size, use -1 as starting value to check optional arguments) </li><li><code>t</code> -- check for <code>dict</code> (returns sgs_SizeVal size, use -1 as starting value to check optional arguments) </li><li><code>h</code> -- check for <code>map</code> (returns sgs_SizeVal size, use -1 as starting value to check optional arguments) </li><li><code>o</code> -- check for <code>object</code> (requires void** interface, returns &lt;type&gt;* data - the data pointer) </li><li><code>&amp;</code> -- check for <code>pointer</code> (returns void* data - the pointer) </li><li><code>v</code> -- check for any (non-null if strict, returns sgs_Variable data) </li><li><code>x</code> -- call a custom checking function (requires sgs_ArgCheckFunc, everything else depends on function)</li></ul><h4>error codes</h4><ul><li>SGS_EINVAL: error in <code>cmd</code> (wrong character/argument pointer moved before 0)</li></ul></div> <div class='item'><a name='sgs-LoadArgs-function-alias'></a><hr><h2>sgs_LoadArgs [function alias]</h2><h3>SGSBOOL sgs_LoadArgs( sgs_Context* C, const char* cmd, ... )</h3><h4>parse the stack items and retrieve their data according to <code>cmd</code>, starting from item 0</h4><p> <em class='notice-bgr'>unlike <a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgsExt(VA)</a>, it returns <code>bool</code> - whether all required arguments have been successfully parsed</em> </p><ul><li>for more info on syntax and usage, refer to <a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgsExt(VA)</a> </li><li>alias to <code>sgs_LoadArgsExt( C, 0, cmd, ... )&gt;0</code></li></ul></div> <div class='item'><a name='sgs-ParseMethod-function'></a><hr><h2>sgs_ParseMethod [function]</h2></div> <div class='item'><a name='SGS-PARSE-METHOD-function-alias'></a><hr><h2>SGS_PARSE_METHOD [function alias]</h2></div> <div class='item'><a name='sgs-Method-function'></a><hr><h2>sgs_Method [function]</h2><h3>SGSBOOL sgs_Method( sgs_Context* C )</h3><h4>unlock the &#39;this&#39; variable, return if the function was called as a method (and thus variable was unlocked)</h4><ul><li>method calls look like this: &quot;object.method(...)&quot;</li></ul></div> <div class='item'><a name='sgs-Force-HideThis-functions'></a><hr><h2>sgs_(Force)HideThis [functions]</h2><h3>SGSBOOL sgs_HideThis( sgs_Context* C )</h3><h3>SGSBOOL sgs_ForceHideThis( sgs_Context* C )</h3><h4>hide the &#39;this&#39; variable, return if successful</h4><ul><li>sgs_ForceHideThis attempts to hide the first item on stack even if it didn&#39;t belong to the call, sgs_HideThis only does it if it belongs to the call and was hidden before </li><li>the hiding method is stack offset pointer shift</li></ul></div> <div class='item'><a name='sgs-FCall-P-functions'></a><hr><h2>sgs_FCall(P) [functions]</h2><h3>SGSRESULT sgs_FCall( sgs_Context* C, int args, int expect, int gotthis )</h3><h4>call the topmost variable on stack with the arguments before it, returning the expected number of variables on stack</h4><h3>SGSRESULT sgs_FCallP( sgs_Context* C, sgs_Variable* var, int args, int expect, int gotthis )</h3><h4>call the variable with the arguments on stack, returning the expected number of variables on stack</h4><ul><li><code>var</code>: the callable variable to call as a function </li><li><code>args</code>: the primary variables to be passed to the function, in the same order they are in the stack </li><li><code>expect</code>: the number of variables to be left after a successful call </li><li><code>gotthis</code>: whether the function is a method and an additional argument needs to be passed as the &#39;this&#39; value before others</li></ul><p> After a successful call, all arguments and the function will be popped off the stack and the expected number of variables will appear in their place. If the underlying callable does not return enough arguments, &#39;null&#39; variables will be pushed instead. If the number of returned values is bigger than expected, only the first expected return values will stay on the stack. </p><ul><li>expected stack structure: <ul><li>(if gotthis != 0) [this] </li><li>[argument] x <code>args</code> </li><li>[callable]</li></ul></li></ul><ul><li>a callable is one of the following: <ul><li>SGS function </li><li>C function </li><li>object with CALL interface function defined</li></ul></li></ul><p> <em class='notice-bgr'>Stack is returned to the expected state only if the return value implies success (&gt;= 0) or is equal to SGS_EINPROC. Otherwise, it&#39;s left exactly as it was before the call.</em> </p><p> <em class='notice-bgr'>The return value <code>1</code> is returned if function call was aborted.</em> </p><h4>error codes</h4><ul><li>SGS_EINPROC: topmost item on stack was not callable </li><li>SGS_EINVAL: not enough values in current stack frame (must have at least <code>args + (gotthis?1:0) + (is_sgs_FCallP?0:1)</code>)</li></ul></div> <div class='item'><a name='sgs-This-Call-P-function-aliases'></a><hr><h2>sgs_(This)Call(P) [function aliases]</h2><h3>SGSRESULT sgs_Call( sgs_Context* C, int args, int expect )</h3><h3>SGSRESULT sgs_ThisCall( sgs_Context* C, int args, int expect )</h3><h4>call the topmost variable on stack with the arguments before it, returning the expected number of variables on stack</h4><h3>SGSRESULT sgs_Call( sgs_Context* C, sgs_Variable* var, int args, int expect )</h3><h3>SGSRESULT sgs_ThisCall( sgs_Context* C, sgs_Variable* var, int args, int expect )</h3><h4>call the variable with the arguments on stack, returning the expected number of variables on stack</h4><ul><li>aliases to <a href="#sgs-FCall-P-functions">sgs_FCall(P)</a>, for the first function of each group <code>gotthis = 0</code>, for the second <code>gotthis = 1</code>.</li></ul></div> <div class='item'><a name='sgs-GlobalCall-function'></a><hr><h2>sgs_GlobalCall [function]</h2><h3>SGSRESULT sgs_GlobalCall( sgs_Context* C, const char* name, int args, int expect )</h3><h4>call the global variable <code>name</code> as a function</h4><ul><li>combination of global function retrieval and function call; see <a href="#sgs-PushGlobal-function">sgs_PushGlobal</a> and <a href="#sgs-FCall-P-functions">sgs_FCall(P)</a> for more info on behavior</li></ul><h4>error codes</h4><ul><li>SGS_ENOTFND: global variable was not found </li><li>SGS_EINPROC: item found was not callable </li><li>SGS_EINVAL: not enough values in current stack frame (must have at least <code>args + (gotthis?1:0)</code>)</li></ul></div> <div class='item'><a name='sgs-TypeOf-function'></a><hr><h2>sgs_TypeOf [function]</h2><h3>SGSRESULT sgs_TypeOf( sgs_Context* C )</h3><h4>return the type name string of topmost variable in current stack frame</h4><ul><li>if the object does not support the specific part of the conversion interface function, a string of format &quot;object (%p)&quot; is returned to ensure expected type name comparison capabilities</li></ul><h4>error codes</h4><ul><li>SGS_EINPROC: current stack frame was empty</li></ul></div> <div class='item'><a name='sgs-DumpVar-function'></a><hr><h2>sgs_DumpVar [function]</h2><h3>SGSRESULT sgs_DumpVar( sgs_Context* C, int maxdepth )</h3><h4>convert the topmost variable of current stack frame to a highly informative string that should display the contents of the variable, up to <code>maxdepth</code> depth</h4><ul><li>if object does not have the DUMP interface function implemented, only its pointer in memory and reference count are displayed</li></ul><h4>error codes</h4><ul><li>SGS_EINPROC: current stack frame was empty </li><li>SGS_EINVAL: invalid base variable type found in variable (not really expected to happen unless custom variable creation is done)</li></ul></div> <div class='item'><a name='sgs-GCExecute-function'></a><hr><h2>sgs_GCExecute [function]</h2><h3>SGSRESULT sgs_GCExecute( sgs_Context* C )</h3><h4>call the garbage collector on the VM</h4><ul><li>this procedure may take some time if the object graph is big </li><li>during the procedure, the GCMARK interface functions of objects are invoked for the objects visible from entry points (like stack and global table) </li><li>aborting the procedure via error codes could lead the system into an unrecoverable state</li></ul><h4>error codes</h4><ul><li>any code can be returned by GCMARK and DESTRUCT functions, doing so would abort the process if the code is not either SGS_SUCCESS or SGS_ENOTFND</li></ul></div> <div class='item'><a name='sgs-PadString-function'></a><hr><h2>sgs_PadString [function]</h2><h3>SGSRESULT sgs_PadString( sgs_Context* C )</h3><h4>replace the topmost variable of current stack frame with a string variable where two spaces are appended after every newline</h4><h4>error codes</h4><ul><li>SGS_EINPROC: current stack frame is empty or output string size exceeds limit </li><li>SGS_EINVAL: topmost variable is not a string</li></ul></div> <div class='item'><a name='sgs-ToPrintSafeString-function'></a><hr><h2>sgs_ToPrintSafeString [function]</h2><h3>SGSRESULT sgs_ToPrintSafeString( sgs_Context* C )</h3><h4>replace the topmost variable of current stack frame with a string where all non-printable (except space), non-ASCII characters converted to a character hex code</h4><h4>error codes</h4><ul><li>SGS_EINPROC: current stack frame is empty or output string size exceeds limit</li></ul></div> <div class='item'><a name='sgs-StringConcat-function'></a><hr><h2>sgs_StringConcat [function]</h2><h3>SGSRESULT sgs_StringConcat( sgs_Context* C, int args )</h3><h4>concatenate the <code>args</code> number of topmost string variables in the current stack frame</h4><h4>error codes</h4><ul><li>SGS_EINVAL: not enough (less than <code>args</code>) variables were found in the current stack frame</li></ul></div> <div class='item'><a name='sgs-ClPushNulls-function'></a><hr><h2>sgs_ClPushNulls [function]</h2><h3>SGSRESULT sgs_ClPushNulls( sgs_Context* C, sgs_StkIdx num )</h3><h4>push <code>num</code> empty closures to the closure stack</h4><h4>error codes</h4><ul><li>SGS_EINVAL: <code>num</code> was less than 0</li></ul></div> <div class='item'><a name='sgs-ClPushItem-function'></a><hr><h2>sgs_ClPushItem [function]</h2><h3>SGSRESULT sgs_ClPushItem( sgs_Context* C, sgs_StkIdx item )</h3><h4>push a variable <code>item</code> on stack as a closure to the closure stack</h4><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds</li></ul></div> <div class='item'><a name='sgs-ClPop-function'></a><hr><h2>sgs_ClPop [function]</h2><h3>SGSRESULT sgs_ClPop( sgs_Context* C, sgs_StkIdx num )</h3><h4>pop <code>num</code> closures from the closure stack</h4><h4>error codes</h4><ul><li>SGS_EINPROC: attempted to pop more closures than there are on the stack</li></ul></div> <div class='item'><a name='sgs-MakeClosure-function'></a><hr><h2>sgs_MakeClosure [function]</h2><h3>SGSRESULT sgs_MakeClosure( sgs_Context* C, sgs_Variable* func, sgs_StkIdx clcount, sgs_Variable* out )</h3><h4>make a callable closure object from the specified callable <code>func</code> and <code>clcount</code> closures on stack, return it at position <code>out</code></h4><h4>error codes</h4><ul><li>SGS_EINPROC: attempted to use more closures than there are on the stack</li></ul></div> <div class='item'><a name='sgs-ClGetItem-function'></a><hr><h2>sgs_ClGetItem [function]</h2><h3>SGSRESULT sgs_ClGetItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* out )</h3><h4>retrieve the variable from a closure <code>item</code> on stack</h4><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds</li></ul></div> <div class='item'><a name='sgs-ClSetItem-function'></a><hr><h2>sgs_ClSetItem [function]</h2><h3>SGSRESULT sgs_ClSetItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* var )</h3><h4>set the variable <code>var</code> to a closure <code>item</code> on stack</h4><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds</li></ul></div> <div class='item'><a name='sgs-CloneItem-function'></a><hr><h2>sgs_CloneItem [function]</h2><h3>SGSRESULT sgs_CloneItem( sgs_Context* C, sgs_StkIdx item )</h3><h4>push a copy of the specified stack item</h4><p> <em class='notice-bgr'>Even though operations with functions and strings succeed, functions and strings are not actually cloned since they are immutable.</em> </p><h4>error codes</h4><ul><li>SGS_EBOUNDS: stack item index was out of bounds </li><li>SGS_ENOTFND: the object does not support cloning</li></ul></div> <div class='item'><a name='sgs-ObjectAction-function'></a><hr><h2>sgs_ObjectAction [function]</h2><h3>SGSMIXED sgs_ObjectAction( sgs_Context* C, sgs_StkIdx item, int action, int arg )</h3><h4>execute an action on the specified stack item</h4><h4>actions</h4><ul><li>SGS_ACT_ARRAY_PUSH <ul><li>append the last <code>arg</code> items on stack to the array </li><li>error codes <ul><li>SGS_EINVAL: <code>item</code> was not an array, <code>arg</code> was negative or bigger than stack frame </li></ul></li></ul><li>SGS_ACT_ARRAY_POP <ul><li>remove the last <code>arg</code> items from the end of the array </li><li>error codes <ul><li>SGS_EINVAL: <code>item</code> was not an array, <code>arg</code> was negative or bigger than size of array </li></ul></li></ul><li>SGS_ACT_ARRAY_POPRET <ul><li>remove the last <code>arg</code> items from the end of the array and return them in the order they were stored (last items on array are last on stack) </li><li>error codes <ul><li>SGS_EINVAL: <code>item</code> was not an array, <code>arg</code> was negative or bigger than size of array </li></ul></li></ul><li>SGS_ACT_ARRAY_FIND <ul><li>find and return the index of variable specified in <code>arg</code> </li><li>error codes <ul><li>SGS_EINVAL: <code>item</code> was not an array </li><li>SGS_EBOUNDS: <code>arg</code> was out of bounds </li><li>SGS_ENOTFND: <code>arg</code> was not found inside item </li></ul></li></ul><li>SGS_ACT_ARRAY_RM_ONE <ul><li>find and remove only the first copy of variable specified in <code>arg</code>, return if found and removed </li><li>error codes <ul><li>SGS_EINVAL: <code>item</code> was not an array </li><li>SGS_EBOUNDS: <code>arg</code> was out of bounds </li></ul></li></ul><li>SGS_ACT_ARRAY_RM_ALL <ul><li>find and remove all copies of variable specified in <code>arg</code>, return how many were found and removed </li><li>error codes <ul><li>SGS_EINVAL: <code>item</code> was not an array </li><li>SGS_EBOUNDS: <code>arg</code> was out of bounds </li></ul></li></ul><li>SGS_ACT_DICT_UNSET <ul><li>unset a key-value pair from a dict </li><li>error codes <ul><li>SGS_EINVAL: <code>item</code> was not a dict, <code>arg</code> was not pointing to a stack item of <code>string</code> type </li></ul></li></ul><li>SGS_ACT_MAP_UNSET <ul><li>unset a key-value pair from a map </li><li>error codes <ul><li>SGS_EINVAL: <code>item</code> was not a map, <code>arg</code> was out of bounds</li></ul></li></ul></li></ul><h4>error codes</h4><ul><li>SGS_E****: action-specific </li><li>SGS_ENOTFND: action was not found</li></ul></div> <div class='item'><a name='sgs-Serialize-function'></a><hr><h2>sgs_Serialize [function]</h2><h3>SGSRESULT sgs_Serialize( sgs_Context* C )</h3><h4>serialize the topmost variable of the current stack frame (convert to a binary recreation instruction stream)</h4><ul><li>the following variable types can be serialized: <ul><li>null, bool, int, real, string, func (SGS function) </li><li>objects with the SERIALIZE interface function defined</li></ul></li></ul><ul><li>serialized data has the following format: <ul><li>a list of &#39;P&#39; or &#39;C&#39; commands </li><li>&#39;P&#39; (push) command: byte - variable type; variable data <ul><li>variable data: nothing for null, byte for bool, int64 for int, double for real, int32 + char[] for string </li></ul><li>&#39;C&#39; (call) command: int32 - number of arguments; byte - function name size; char[] - function name</li></ul></li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: current stack frame was empty </li><li>SGS_EINVAL: an unserializable topmost variable was found (function) </li><li>SGS_EINPROC: unknown memory error</li></ul></div> <div class='item'><a name='sgs-SerializeObject-function'></a><hr><h2>sgs_SerializeObject [function]</h2><h3>SGSRESULT sgs_SerializeObject( sgs_Context* C, int args, const char* func )</h3><h4>write the serialized code for an object&#39;s unserializing function</h4><h4>error codes</h4><ul><li>SGS_EINVAL: function name was too long (255 characters or more) </li><li>SGS_EINPROC: function was used outside serialization interface function</li></ul></div> <div class='item'><a name='sgs-Unserialize-function'></a><hr><h2>sgs_Unserialize [function]</h2><h3>SGSRESULT sgs_Unserialize( sgs_Context* C )</h3><h4>unserialize the topmost string variable of the current stack frame (run the binary recreation instruction stream)</h4><p> <em class='notice-bgr'>Be mindful of the data sources you use - calls to any global function can be placed in the instruction stream.</em> </p></div> <div class='item'><a name='sgs-Assign-function'></a><hr><h2>sgs_Assign [function]</h2><h3>void sgs_Assign( sgs_Context* C, sgs_Variable* var_to, sgs_Variable* var_from )</h3><h4>release <code>var_to</code>, copy <code>var_from</code> to <code>var_to</code>, acquire the new value</h4></div> <div class='item'><a name='sgs-ArithOp-function'></a><hr><h2>sgs_ArithOp [function]</h2><h3>SGSRESULT sgs_ArithOp( sgs_Context* C, sgs_Variable* out, sgs_Variable* A, sgs_Variable* B, int op )</h3><h4>perform the specified operation on variables A and B, returning the value on <code>out</code></h4><p> <em class='notice-bgr'>this function prints errors, exactly like VM would (internally there are the same functions)</em> </p><ul><li>this function can perform 5 operations, which are specified by passing the following values to <code>op</code>: <ul><li>SGS_EOP_ADD: + </li><li>SGS_EOP_SUB: - (binary) </li><li>SGS_EOP_MUL: * </li><li>SGS_EOP_DIV: / </li><li>SGS_EOP_MOD: % </li><li>SGS_EOP_NEGATE: - (unary, uses only <code>A</code>)</li></ul></li></ul><h4>error codes</h4><ul><li>SGS_ENOTSUP: operation not supported (invalid operation ID) </li><li>SGS_EINVAL: specified arithmetic operation is not supported by the given set of arguments </li><li>SGS_EINPROC: division by 0</li></ul></div> <div class='item'><a name='sgs-IncDec-function'></a><hr><h2>sgs_IncDec [function]</h2><h3>SGSRESULT sgs_IncDec( SGS_CTX, sgs_Variable* out, sgs_Variable* A, int inc )</h3><h4>increment or decrement the specified variable <code>A</code> to the output <code>out</code></h4><p> <em class='notice-bgr'>this function prints errors, exactly like VM would (internally there are the same functions)</em> </p><ul><li>if inc is non-zero, variable is incremented; otherwise it is decremented</li></ul><h4>error codes</h4><ul><li>SGS_EINVAL: variable was not int or real</li></ul></div> <div class='item'><a name='sgs-Compare-function'></a><hr><h2>sgs_Compare [function]</h2><h3>int sgs_Compare( sgs_Context* C, sgs_Variable* v1, sgs_Variable* v2 )</h3><h4>return the difference between variables, as int -1/0/1</h4></div> <div class='item'><a name='sgs-EqualTypes-function'></a><hr><h2>sgs_EqualTypes [function]</h2><h3>SGSBOOL sgs_EqualTypes( sgs_Variable* v1, sgs_Variable* v2 )</h3><h4>return if types of both variables are exactly equal</h4><ul><li>both type variables and interface pointers (only if both variables are objects) are checked for equality</li></ul></div> <div class='item'><a name='sgs-Get-functions'></a><hr><h2>sgs_Get*** [functions]</h2><h3>sgs_Bool sgs_GetBool( sgs_Context* C, sgs_StkIdx item )</h3><h3>sgs_Int sgs_GetInt( sgs_Context* C, sgs_StkIdx item )</h3><h3>sgs_Real sgs_GetReal( sgs_Context* C, sgs_StkIdx item )</h3><h3>void* sgs_GetPtr( sgs_Context* C, sgs_StkIdx item )</h3><h4>return an item from the current stack frame, converted to the specified type</h4><h3>sgs_Bool sgs_GetBoolP( sgs_Context* C, sgs_Variable* var )</h3><h3>sgs_Int sgs_GetIntP( sgs_Context* C, sgs_Variable* var )</h3><h3>sgs_Real sgs_GetRealP( sgs_Context* C, sgs_Variable* var )</h3><h3>void* sgs_GetPtrP( sgs_Context* C, sgs_Variable* var )</h3><h4>return the value of the specified variable, converted to the specified type</h4><ul><li>if <code>item</code> is out of bounds, 0 is returned</li></ul></div> <div class='item'><a name='sgs-To-functions'></a><hr><h2>sgs_To*** [functions]</h2><h3>sgs_Bool sgs_ToBool( sgs_Context* C, sgs_StkIdx item )</h3><h3>sgs_Int sgs_ToInt( sgs_Context* C, sgs_StkIdx item )</h3><h3>sgs_Real sgs_ToReal( sgs_Context* C, sgs_StkIdx item )</h3><h3>void* sgs_ToPtr( sgs_Context* C, sgs_StkIdx item )</h3><h4>return an item from the current stack frame, converted in-place to the specified type</h4><h3>sgs_Bool sgs_ToBoolP( sgs_Context* C, sgs_Variable* var )</h3><h3>sgs_Int sgs_ToIntP( sgs_Context* C, sgs_Variable* var )</h3><h3>sgs_Real sgs_ToRealP( sgs_Context* C, sgs_Variable* var )</h3><h3>void* sgs_GetPtrP( sgs_Context* C, sgs_Variable* var )</h3><h4>return the value of the specified variable, converted in-place to the specified type</h4><ul><li>in ***P functions previous variable is properly released before conversion takes place and reacquired afterwards </li><li>in-place conversion means that if the function succeeds, the variable will have the requested type</li></ul></div> <div class='item'><a name='sgs-ToStringBuf-Fast-P-functions'></a><hr><h2>sgs_ToStringBuf(Fast)(P) [functions]</h2><h3>char* sgs_ToStringBuf( sgs_Context* C, sgs_StkIdx item, sgs_SizeVal* outsize )</h3><h3>char* sgs_ToStringBufFast( sgs_Context* C, sgs_StkIdx item, sgs_SizeVal* outsize )</h3><h4>return an item from the current stack frame, converted in-place to string</h4><h3>char* sgs_ToStringBufP( sgs_Context* C, sgs_Variable* var, sgs_SizeVal* outsize )</h3><h3>char* sgs_ToStringBufFastP( sgs_Context* C, sgs_Variable* var, sgs_SizeVal* outsize )</h3><h4>return the value of the specified variable, converted in-place to string</h4><ul><li>in ***P functions previous variable is properly released before conversion takes place and reacquired afterwards </li><li>if <code>item</code> is out of bounds or conversion fails, NULL is returned </li><li>the &#39;fast&#39; version uses type name conversion on object, instead of string conversion - this is to avoid recursion while generating a short description about object contents </li><li>length of string is returned to the value that <code>outsize</code> points to</li></ul></div> <div class='item'><a name='sgs-ToString-Fast-P-function-aliases'></a><hr><h2>sgs_ToString(Fast)(P) [function aliases]</h2><h3>char* sgs_ToString( sgs_Context* C, sgs_StkIdx item )</h3><h3>char* sgs_ToStringFast( sgs_Context* C, sgs_StkIdx item )</h3><h4>return an item from the current stack frame, converted in-place to string</h4><h3>char* sgs_ToStringP( sgs_Context* C, sgs_Variable* var )</h3><h3>char* sgs_ToStringFastP( sgs_Context* C, sgs_Variable* var )</h3><h4>return the value of the specified variable, converted in-place to string</h4><ul><li>in ***P functions previous variable is properly released before conversion takes place and reacquired afterwards </li><li>these are aliases of <a href="#sgs-ToStringBuf-Fast-P-functions">sgs_ToStringBuf(Fast)(P)</a> with the third argument set to NULL</li></ul></div> <div class='item'><a name='sgs-RegisterType-function'></a><hr><h2>sgs_RegisterType [function]</h2><h3>SGSRESULT sgs_RegisterType( sgs_Context* C, const char* name, sgs_ObjInterface* iface )</h3><h4>register a type interface by mapping it to a name</h4><h4>error codes</h4><ul><li>SGS_EINVAL: iface was NULL </li><li>SGS_EINPROC: the name is already used</li></ul></div> <div class='item'><a name='sgs-UnregisterType-function'></a><hr><h2>sgs_UnregisterType [function]</h2><h3>SGSRESULT sgs_UnregisterType( sgs_Context* C, const char* name )</h3><h4>unregister a type interface by its name</h4><h4>error codes</h4><ul><li>SGS_ENOTFND: the specified type name was not mapped to any interface</li></ul></div> <div class='item'><a name='sgs-FindType-function'></a><hr><h2>sgs_FindType [function]</h2><h3>sgs_ObjInterface* sgs_FindType( sgs_Context* C, const char* name )</h3><h4>finds the type interface that is mapped to the specified name or returns NULL if that type name cannot be found</h4></div> <div class='item'><a name='sgs-IsObject-P-functions'></a><hr><h2>sgs_IsObject(P) [functions]</h2><h3>SGSBOOL sgs_IsObject( sgs_Context* C, sgs_StkIdx item, sgs_ObjInterface* iface )</h3><h4>returns whether the specified stack item <code>item</code> is an object with the interface pointer <code>iface</code></h4><ul><li>if <code>item</code> is out of bounds or not an object or doesn&#39;t have the specified interface, 0 is returned</li></ul><h3>SGSBOOL sgs_IsObjectP( sgs_Context* C, sgs_Variable* var, sgs_ObjInterface* iface )</h3><h4>returns whether the specified variable <code>var</code> is an object with the interface pointer <code>iface</code></h4></div> <div class='item'><a name='sgs-IsType-P-function-aliases'></a><hr><h2>sgs_IsType(P) [function aliases]</h2><h3>SGSBOOL sgs_IsType( sgs_Context* C, sgs_StkIdx item, const char* type )</h3><h4>returns whether the specified stack item <code>item</code> is an object of the specified type</h4><ul><li>alias of <code>sgs_IsObject( C, item, sgs_FindType( C, type ) )</code></li></ul><h3>SGSBOOL sgs_IsTypeP( sgs_Context* C, sgs_Variable* var, const char* type )</h3><h4>returns whether the specified variable <code>var</code> is an object of the specified type</h4><ul><li>alias of <code>sgs_IsObjectP( C, var, sgs_FindType( C, type ) )</code></li></ul></div> <div class='item'><a name='sgs-IsCallable-P-functions'></a><hr><h2>sgs_IsCallable(P) [functions]</h2><h3>SGSBOOL sgs_IsCallable( sgs_Context* C, sgs_StkIdx item )</h3><h4>returns whether the specified stack item <code>item</code> is callable</h4><ul><li>if <code>item</code> is out of bounds, 0 is returned</li></ul><h3>SGSBOOL sgs_IsCallableP( sgs_Context* C, sgs_Variable* var )</h3><h4>returns whether the specified variable <code>var</code> is callable</h4><ul><li>callable variables are either SGS functions or C functions or objects with the CALL interface implemented</li></ul></div> <div class='item'><a name='sgs-IsNumericString-function'></a><hr><h2>sgs_IsNumericString [function]</h2><h3>SGSBOOL sgs_IsNumericString( const char* str, sgs_SizeVal size )</h3><h4>checks if the string is convertible to an integer/real</h4><ul><li>more info at @&lt;Numeric string parsing rules&gt;</li></ul></div> <div class='item'><a name='sgs-Parse-functions'></a><hr><h2>sgs_Parse*** [functions]</h2><h3>SGSBOOL sgs_ParseBool( sgs_Context* C, sgs_StkIdx item, sgs_Bool* out )</h3><h3>SGSBOOL sgs_ParseInt( sgs_Context* C, sgs_StkIdx item, sgs_Int* out )</h3><h3>SGSBOOL sgs_ParseReal( sgs_Context* C, sgs_StkIdx item, sgs_Real* out )</h3><h3>SGSBOOL sgs_ParseString( sgs_Context* C, sgs_StkIdx item, char** out, sgs_SizeVal* size )</h3><h3>SGSBOOL sgs_ParseObjectPtr( sgs_Context* C, sgs_StkIdx item, sgs_ObjInterface* iface, sgs_VarObj** out, int strict )</h3><h3>SGSBOOL sgs_ParsePtr( sgs_Context* C, sgs_StkIdx item, void** out )</h3><h4>attempts to parse the specified item of the current stack frame, returning whether parsing was successful</h4><h3>SGSBOOL sgs_ParseBoolP( sgs_Context* C, sgs_Variable* var, sgs_Bool* out )</h3><h3>SGSBOOL sgs_ParseIntP( sgs_Context* C, sgs_Variable* var, sgs_Int* out )</h3><h3>SGSBOOL sgs_ParseRealP( sgs_Context* C, sgs_Variable* var, sgs_Real* out )</h3><h3>SGSBOOL sgs_ParseStringP( sgs_Context* C, sgs_Variable* var, char** out, sgs_SizeVal* size )</h3><h3>SGSBOOL sgs_ParseObjectPtrP( sgs_Context* C, sgs_Variable* var, sgs_ObjInterface* iface, sgs_VarObj** out, int strict )</h3><h3>SGSBOOL sgs_ParsePtrP( sgs_Context* C, sgs_Variable* var, void** out )</h3><h4>attempts to parse the specified varuabke, returning whether parsing was successful</h4><ul><li>the parsing rules: <ul><li>for <code>sgs_ParsePtr</code>/<code>sgs_ParsePtrP</code>, unlike every other parsing function, only null/ptr types are considered valid </li><li>for <code>sgs_ParseObjectPtr</code>/<code>sgs_ParseObjectPtrP</code>, only objects with the specified interface <code>iface</code> are valid unless strict = 0, then <code>null</code> is valid too </li><li>if <code>item</code> is out of bounds, fail </li><li>if item has the type <code>null</code>, <code>func</code> or <code>cfunc</code>, fail </li><li>if item is of <code>string</code> type and <code>bool</code> is requested, fail </li><li>if item is of <code>string</code> type and <code>int</code>/<code>real</code> is requested, try to convert </li><li>everything else succeeds</li></ul></li></ul></div> <div class='item'><a name='sgs-Global-functions'></a><hr><h2>sgs_Global*** [functions]</h2><h3>sgs_Bool sgs_GlobalBool( SGS_CTX, const char* name )</h3><h3>sgs_Int sgs_GlobalInt( SGS_CTX, const char* name )</h3><h3>sgs_Real sgs_GlobalReal( SGS_CTX, const char* name )</h3><h3>char* sgs_GlobalStringBuf( SGS_CTX, const char* name, sgs_SizeVal* outsize )</h3><h3>char* sgs_GlobalString( SGS_CTX, const char* name )</h3><h4>retrieve a global variable, converted to the specified type</h4><p> <em class='notice-bgr'>sgs_GlobalString[Buf] <b>pushes the variable on the stack</b> to be able to reliably return the string pointer</em> </p><ul><li>if variable is not found, 0 / NULL is returned </li><li>if string cannot be parsed (variable is null or a function), NULL is returned <ul><li>this is done because converting these values does not yield useful results with global variables</li></ul></li></ul></div> <div class='item'><a name='sgs-PushIterator-P-functions'></a><hr><h2>sgs_PushIterator(P) [functions]</h2><h3>SGSRESULT sgs_PushIterator( sgs_Context* C, sgs_StkIdx item )</h3><h4>create and push an iterator from the specified item of the current stack frame</h4><h3>SGSRESULT sgs_PushIteratorP( sgs_Context* C, sgs_Variable* var )</h3><h4>create and push an iterator from the specified variable</h4><ul><li>see <a href="#Iterator-system">Iterator system</a> for more info about iterators</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds </li><li>SGS_ENOTSUP: variable type does not support iterators (only objects support them) </li><li>SGS_ENOTFND: object type does not support iterators (iterator conversion request failed) </li><li>any other code can be returned by the object</li></ul></div> <div class='item'><a name='sgs-GetIterator-P-functions'></a><hr><h2>sgs_GetIterator(P) [functions]</h2><h3>SGSRESULT sgs_GetIterator( sgs_Context* C, sgs_StkIdx item, sgs_Variable* out )</h3><h4>create an iterator from the specified item of the current stack frame</h4><h3>SGSRESULT sgs_GetIteratorP( sgs_Context* C, sgs_Variable* var, sgs_Variable* out )</h3><h4>create an iterator from the specified variable</h4><ul><li>see <a href="#Iterator-system">Iterator system</a> for more info about iterators</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds </li><li>SGS_ENOTSUP: variable type does not support iterators (only objects support them) </li><li>SGS_ENOTFND: object type does not support iterators (iterator conversion request failed) </li><li>any other code can be returned by the object</li></ul></div> <div class='item'><a name='sgs-IterAdvance-P-functions'></a><hr><h2>sgs_IterAdvance(P) [functions]</h2><h3>SGSMIXED sgs_IterAdvance( sgs_Context* C, sgs_StkIdx item )</h3><h3>SGSMIXED sgs_IterAdvanceP( sgs_Context* C, sgs_Variable* var )</h3><h4>advance the iterator to the next position, returning if the current position is still in range or an error code on failure</h4><ul><li>this is the way it&#39;s expected to be usually called: <code>while( sgs_IterAdvance( C, item ) &gt; 0 ){ ... sgs_IterPushData ... }</code> </li><li>see <a href="#Iterator-system">Iterator system</a> for more info about iterators</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds </li><li>SGS_EINVAL: iterated object changed in a way that iterator does not support (currently a size equality test) </li><li>SGS_EINPROC: internal failure in the object interface</li></ul></div> <div class='item'><a name='sgs-IterPushData-P-functions'></a><hr><h2>sgs_IterPushData(P) [functions]</h2><h3>SGSRESULT sgs_IterPushData( sgs_Context* C, sgs_StkIdx item, int key, int value )</h3><h3>SGSRESULT sgs_IterPushDataP( sgs_Context* C, sgs_Variable* var, int key, int value )</h3><h4>load and push data associated with the current position</h4><ul><li><code>key</code> and <code>value</code> are booleans that specify if the respective value should be returned </li><li>first the key is pushed, then the value </li><li>if neither <code>key</code> nor <code>value</code> are expected, the call succeeds and doesn&#39;t push anything </li><li>see <a href="#Iterator-system">Iterator system</a> for more info about iterators</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds </li><li>SGS_EINVAL: iterated object changed in a way that iterator does not support </li><li>SGS_EINPROC: internal failure in the object interface</li></ul></div> <div class='item'><a name='sgs-IterGetData-P-functions'></a><hr><h2>sgs_IterGetData(P) [functions]</h2><h3>SGSRESULT sgs_IterGetData( sgs_Context* C, sgs_StkIdx item, sgs_Variable* key, sgs_Variable* value )</h3><h3>SGSRESULT sgs_IterGetDataP( sgs_Context* C, sgs_Variable* var, sgs_Variable* key, sgs_Variable* value )</h3><h4>load data associated with the current position</h4><ul><li><code>key</code> and <code>value</code> are variables where the data is written if the pointer is not NULL </li><li>if neither <code>key</code> nor <code>value</code> are expected, the call succeeds and doesn&#39;t retrieve anything </li><li>see <a href="#Iterator-system">Iterator system</a> for more info about iterators</li></ul><h4>error codes</h4><ul><li>SGS_EBOUNDS: index out of bounds </li><li>SGS_EINVAL: iterated object changed in a way that iterator does not support </li><li>SGS_EINPROC: internal failure in the object interface</li></ul></div> <div class='item'><a name='sgs-ArraySize-P-functions'></a><hr><h2>sgs_ArraySize(P) [functions]</h2><h3>SGSMIXED sgs_ArraySize( sgs_Context* C, sgs_StkIdx item )</h3><h3>SGSMIXED sgs_ArraySizeP( sgs_Context* C, sgs_Variable* var )</h3><h4>check if the specified stack item or variable is an array and return its size or error code on failure</h4><h4>error codes</h4><ul><li>SGS_EINVAL: index out of bounds / variable was not an array</li></ul></div> <div class='item'><a name='sgs-StackSize-function'></a><hr><h2>sgs_StackSize [function]</h2><h3>sgs_StkIdx sgs_StackSize( sgs_Context* C )</h3><h4>return the size of the current stack frame</h4></div> <div class='item'><a name='sgs-SetStackSize-function'></a><hr><h2>sgs_SetStackSize [function]</h2><h3>SGSRESULT sgs_SetStackSize( sgs_Context* C, sgs_StkIdx size )</h3><h4>resizes the current stack frame to fit the specified amount of items</h4><ul><li>if the current number of items is less than needed, stack is null-variable-padded at the end </li><li>if the current number of items is more than needed, the unnecessary amount of items is popped</li></ul></div> <div class='item'><a name='sgs-AbsIndex-function'></a><hr><h2>sgs_AbsIndex [function]</h2><h3>sgs_StkIdx sgs_AbsIndex( sgs_Context* C, sgs_StkIdx item )</h3><h4>attempt to convert a negative stack index into a positive one</h4><p> <em class='notice-bgr'>this function can still return negative values - make sure that valid values are passed to it or check if the returned value is in the range [ 0; stack_frame_size )</em> </p></div> <div class='item'><a name='sgs-IsValidIndex-function'></a><hr><h2>sgs_IsValidIndex [function]</h2><h3>SGSBOOL sgs_IsValidIndex( sgs_Context* C, sgs_StkIdx item )</h3><h4>return whether the specified stack index points to an item in the current stack frame</h4><ul><li>both positive (first = 0) and negative (last = -1) indices are supported</li></ul></div> <div class='item'><a name='sgs-PeekStackItem-function'></a><hr><h2>sgs_PeekStackItem [function]</h2><h3>SGSBOOL sgs_PeekStackItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* out )</h3><h4>write the data of the specified stack variable if the index is valid</h4><p> <em class='notice-bgr'>this function does not acquire the variable and thus CANNOT be used in functions that modify it, such as <a href="#sgs-Assign-function">sgs_Assign</a> or <a href="#sgs-To-functions">sgs_To***;</a> to acquire variable on retrieval, see <a href="#sgs-GetStackItem-function">sgs_GetStackItem</a> or <a href="#sgs-Acquire-Array-function">sgs_Acquire</a></em> </p><ul><li>function returns whether the stack index was valid</li></ul></div> <div class='item'><a name='sgs-GetStackItem-function'></a><hr><h2>sgs_GetStackItem [function]</h2><h3>SGSBOOL sgs_GetStackItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* out )</h3><h4>write the data of the specified stack variable and increments its reference count if the index is valid</h4><ul><li>function returns whether the stack index was valid</li></ul></div> <div class='item'><a name='sgs-SetStackItem-function'></a><hr><h2>sgs_SetStackItem [function]</h2><h3>SGSRESULT sgs_SetStackItem( sgs_Context* C, sgs_StkIdx item, sgs_Variable* val )</h3><h4>copy the specified variable to the specified position in stack</h4><h4>error codes</h4><ul><li>SGS_EINVAL: invalid variable type detected (corrupted data) </li><li>SGS_EBOUNDS: index out of bounds</li></ul></div> <div class='item'><a name='sgs-ItemType-function'></a><hr><h2>sgs_ItemType [function]</h2><h3>uint32_t sgs_ItemType( sgs_Context* C, sgs_StkIdx item )</h3><h4>return the type ID of the specified stack item</h4><ul><li>return value will be equal to one of the SGS_VT_* macro </li><li>if index is invalid, return value will be 0 (SGS_VT_NULL)</li></ul></div> <div class='item'><a name='sgs-Acquire-Array-function'></a><hr><h2>sgs_Acquire(Array) [function]</h2><h3>void sgs_Acquire( sgs_Context* C, sgs_Variable* var )</h3><h3>void sgs_AcquireArray( sgs_Context* C, sgs_Variable* var, sgs_SizeVal count )</h3><h4>increment the reference count of the specified variables (if they count references)</h4></div> <div class='item'><a name='sgs-Release-Array-function'></a><hr><h2>sgs_Release(Array) [function]</h2><h3>void sgs_Release( sgs_Context* C, sgs_Variable* var )</h3><h3>void sgs_ReleaseArray( sgs_Context* C, sgs_Variable* var, sgs_SizeVal count )</h3><h4>decrement and possibly deallocate the reference count of the specified variables (if they count references)</h4><ul><li>works differently while GC is running: doesn&#39;t delete objects of same context in destructor</li></ul></div> <div class='item'><a name='sgs-GCMark-Array-function'></a><hr><h2>sgs_GCMark(Array) [function]</h2><h3>SGSRESULT sgs_GCMark( sgs_Context* C, sgs_Variable* var )</h3><h3>SGSRESULT sgs_GCMarkArray( sgs_Context* C, sgs_Variable* var, sgs_SizeVal count )</h3><h4>mark the specified variables as reachable for the garbage collector</h4><ul><li>to be called in the GCMARK object callback</li></ul></div> <div class='item'><a name='sgs-ObjAcquire-function'></a><hr><h2>sgs_ObjAcquire [function]</h2><h3>void sgs_ObjAcquire( sgs_Context* C, sgs_VarObj* obj )</h3><h4>increment reference count of the specified object</h4></div> <div class='item'><a name='sgs-ObjRelease-function'></a><hr><h2>sgs_ObjRelease [function]</h2><h3>void sgs_ObjRelease( sgs_Context* C, sgs_VarObj* obj )</h3><h4>decrement reference count and possibly delete the specified object</h4></div> <div class='item'><a name='sgs-ObjGCMark-function'></a><hr><h2>sgs_ObjGCMark [function]</h2><h3>SGSRESULT sgs_ObjGCMark( sgs_Context* C, sgs_VarObj* obj )</h3><h4>mark the specified object as accessible to avoid its destruction by the <a href="#Garbage-collection-system">Garbage collection system</a></h4><ul><li>to be called in the GCMARK object callback</li></ul></div> <div class='item'><a name='sgs-ObjAssign-function'></a><hr><h2>sgs_ObjAssign [function]</h2><h3>void sgs_ObjAssign( sgs_Context* C, sgs_VarObj** dest, sgs_VarObj* src )</h3><h4>assign object pointer, handling acquisition/release properly</h4><ul><li><code>*dest</code> and <code>src</code> must be NULL or valid pointers to objects </li><li>if <code>src</code> is not NULL, it is acquired </li><li>if <code>*dest</code> is not NULL, it is released </li><li>after the function call, <code>*dest</code> is equal to <code>src</code></li></ul></div> <div class='item'><a name='sgs-ObjCallDtor-function'></a><hr><h2>sgs_ObjCallDtor [function]</h2><h3>void sgs_ObjCallDtor( sgs_Context* C, sgs_VarObj* obj )</h3><h4>call the DESTRUCT object callback</h4><ul><li>this function is to be used in cases where objects are owned by a single entity but have handles all over the place - calling this function would not delete the object but would free its resources, thus leaving handles intact, with their states updated</li></ul></div> <div class='item'><a name='sgs-GetStringPtr-P-functions'></a><hr><h2>sgs_GetStringPtr(P) [functions]</h2><h3>char* sgs_GetStringPtr( sgs_Context* C, sgs_StkIdx item )</h3><h4>return the string data pointer of the specified stack item</h4><h3>char* sgs_GetStringPtrP( sgs_Context* C, sgs_Variable* var )</h3><h4>return the string data pointer of the specified variable</h4><ul><li>if item is out of bounds or not a string, NULL will be returned and ... <ul><li>in a debug build, one of the BreakIf macros will go off and stop the action</li></ul></li></ul></div> <div class='item'><a name='sgs-GetStringSize-P-functions'></a><hr><h2>sgs_GetStringSize(P) [functions]</h2><h3>sgs_SizeVal sgs_GetStringSize( sgs_Context* C, sgs_StkIdx item )</h3><h4>return the string size of the specified stack item</h4><h3>sgs_SizeVal sgs_GetStringSizeP( sgs_Context* C, sgs_Variable* var )</h3><h4>return the string size of the specified variable</h4><ul><li>if item is out of bounds or not a string, 0 will be returned and ... <ul><li>in a debug build, one of the BreakIf macros will go off and stop the action</li></ul></li></ul></div> <div class='item'><a name='sgs-GetObjectStruct-P-functions'></a><hr><h2>sgs_GetObjectStruct(P) [functions]</h2><h3>sgs_VarObj* sgs_GetObjectStruct( sgs_Context* C, sgs_StkIdx item )</h3><h4>return the object&#39;s internal data pointer of the specified stack item</h4><h3>sgs_VarObj* sgs_GetObjectStructP( sgs_Context* C, sgs_Variable* var )</h3><h4>return the object&#39;s internal data pointer of the specified variable</h4><ul><li>if item is out of bounds or not an object, NULL will be returned and ... <ul><li>in a debug build, one of the BreakIf macros will go off and stop the action</li></ul></li></ul></div> <div class='item'><a name='sgs-GetObjectData-P-functions'></a><hr><h2>sgs_GetObjectData(P) [functions]</h2><h3>void* sgs_GetObjectData( sgs_Context* C, sgs_StkIdx item )</h3><h4>return the object data pointer of the specified stack item</h4><h3>void* sgs_GetObjectDataP( sgs_Context* C, sgs_Variable* var )</h3><h4>return the object data pointer of the specified variable</h4><ul><li>if item is out of bounds or not an object, NULL will be returned and ... <ul><li>in a debug build, one of the BreakIf macros will go off and stop the action</li></ul></li></ul></div> <div class='item'><a name='sgs-GetObjectIface-P-functions'></a><hr><h2>sgs_GetObjectIface(P) [functions]</h2><h3>sgs_ObjInterface* sgs_GetObjectIface( sgs_Context* C, sgs_StkIdx item )</h3><h4>return the object interface pointer of the specified stack item</h4><h3>sgs_ObjInterface* sgs_GetObjectIfaceP( sgs_Context* C, sgs_Variable* var )</h3><h4>return the object interface pointer of the specified variable</h4><ul><li>if item is out of bounds or not an object, NULL will be returned and ... <ul><li>in a debug build, one of the BreakIf macros will go off and stop the action</li></ul></li></ul></div> <div class='item'><a name='sgs-SetObjectData-P-functions'></a><hr><h2>sgs_SetObjectData(P) [functions]</h2><h3>int sgs_SetObjectData( sgs_Context* C, sgs_StkIdx item, void* data )</h3><h4>set the object data pointer of the specified stack item</h4><h3>int sgs_SetObjectDataP( sgs_Context* C, sgs_Variable* var, void* data )</h3><h4>set the object data pointer of the specified variable</h4><ul><li>if item is out of bounds or not an object, pointer will not be set, 0 will be returned and ... <ul><li>in a debug build, one of the BreakIf macros will go off and stop the action</li></ul></li></ul></div> <div class='item'><a name='sgs-SetObjectIface-P-functions'></a><hr><h2>sgs_SetObjectIface(P) [functions]</h2><h3>int sgs_SetObjectIface( sgs_Context* C, sgs_StkIdx item, sgs_ObjInterface* iface )</h3><h4>set the object interface pointer of the specified stack item</h4><h3>int sgs_SetObjectIfaceP( sgs_Context* C, sgs_Variable* var, sgs_ObjInterface* iface )</h3><h4>set the object interface pointer of the specified variable</h4><ul><li>if item is out of bounds or not an object, pointer will not be set, 0 will be returned and ... <ul><li>in a debug build, one of the BreakIf macros will go off and stop the action</li></ul></li></ul></div> <div class='item'><a name='sgs-StdOutputFunc-function'></a><hr><h2>sgs_StdOutputFunc [function]</h2><h3>void sgs_StdOutputFunc( void* userdata, sgs_Context* C, const void* ptr, size_t size )</h3><h4>standard output function assumes userdata to be FILE* type and writes the passed buffer to it</h4></div> <div class='item'><a name='sgs-Get-Err-OutputFunc-function'></a><hr><h2>sgs_Get(Err)OutputFunc [function]</h2><h3>void sgs_GetOutputFunc( sgs_Context* C, sgs_OutputFunc* outfunc, void** outuserdata )</h3><h3>void sgs_GetErrOutputFunc( sgs_Context* C, sgs_OutputFunc* outfunc, void** outuserdata )</h3><h4>retrieves the currently set (error) output function</h4><ul><li>validity of the returned function pointer is assured as long as engine internals are not touched anywhere</li></ul></div> <div class='item'><a name='sgs-Set-Err-OutputFunc-function'></a><hr><h2>sgs_Set(Err)OutputFunc [function]</h2><h3>void sgs_SetOutputFunc( sgs_Context* C, sgs_OutputFunc func, void* userdata )</h3><h3>void sgs_SetErrOutputFunc( sgs_Context* C, sgs_OutputFunc func, void* userdata )</h3><h4>sets the function used in &#39;print&#39;/&#39;errprint&#39; function family</h4><ul><li>default output function can be set by passing SGSOUTPUTFN_DEFAULT to func with userdata as FILE*, allocated using the same C runtime that SGScript uses </li><li>default implementation - <a href="#sgs-StdOutputFunc-function">sgs_StdOutputFunc</a> - copies data to FILE* stream, specified in userdata <ul><li>to use this function with non-default (stderr) stream, pass it explicity due to the possibility of having different runtime libraries linked to different binaries</li></ul></li></ul></div> <div class='item'><a name='sgs-Err-Write-function'></a><hr><h2>sgs_(Err)Write [function]</h2><h3>void sgs_Write( sgs_Context* C, const void* ptr, sgs_SizeVal size )</h3><h3>void sgs_ErrWrite( sgs_Context* C, const void* ptr, sgs_SizeVal size )</h3><h4>passes the specified data to the (error) output function</h4><ul><li>the default output function prints the data to the specified FILE* stream (stdout/stderr by default)</li></ul></div> <div class='item'><a name='sgs-Err-WriteStr-function-alias'></a><hr><h2>sgs_(Err)WriteStr [function alias]</h2><h3>void sgs_WriteStr( sgs_Context* C, const char* str )</h3><h3>void sgs_ErrWriteStr( sgs_Context* C, const char* str )</h3><h4>passes the specified string to the (error) output function</h4><ul><li>alias to <code>sgs_(Err)Write( C, str, SGS_STRINGLENGTHFUNC( str ) )</code></li></ul></div> <div class='item'><a name='sgs-Err-Writef-function'></a><hr><h2>sgs_(Err)Writef [function]</h2><h3>void sgs_Writef( sgs_Context* C, const char* what, ... )</h3><h4>passes the arguments through a vsprintf-like function to expand the data and passes it to the specified output function</h4><ul><li>printf rules apply here</li></ul></div> <div class='item'><a name='sgs-StdMsgFunc-NoAbort-functions'></a><hr><h2>sgs_StdMsgFunc(_NoAbort) [functions]</h2><h3>void sgs_StdMsgFunc( void* ctx, sgs_Context* C, int type, const char* msg )</h3><h3>void sgs_StdMsgFunc_NoAbort( void* ctx, sgs_Context* C, int type, const char* msg )</h3><h4>writes error info with <a href="#sgs-WriteErrorInfo-function">sgs_WriteErrorInfo</a> to userdata with fprintf, assuming userdata is FILE*</h4></div> <div class='item'><a name='sgs-GetMsgFunc-function'></a><hr><h2>sgs_GetMsgFunc [function]</h2><h3>void sgs_GetMsgFunc( sgs_Context* C, sgs_MsgFunc* outfunc, void** outuserdata )</h3><h4>retrieves the currently set messaging function</h4><ul><li>info about the system is at the <a href="#Messaging-system">Messaging system</a> page </li><li>validity of the returned function pointer is assured as long as engine internals are not touched anywhere</li></ul></div> <div class='item'><a name='sgs-SetMsgFunc-function'></a><hr><h2>sgs_SetMsgFunc [function]</h2><h3>void sgs_SetMsgFunc( sgs_Context* C, sgs_MsgFunc func, void* userdata )</h3><h4>sets the function that handles and prints messages (more commonly, warnings and errors), while still being physically in that context</h4><ul><li>info about the system is at the <a href="#Messaging-system">Messaging system</a> page </li><li>both subtypes of the default messaging function can be set by passing these flags for <code>func</code> <ul><li>&#39;SGSMSGFN_DEFAULT&#39; - default behavior (write stack frame, write error, abort on SGS_ERROR) </li><li>&#39;SGSMSGFN_DEFAULT_NOABORT&#39; - default behavior without the abort-on-errors feature </li></ul><li>default implementations - <a href="#sgs-StdMsgFunc-NoAbort-functions">sgs_StdMsgFunc(_NoAbort)</a> passes error and stack trace to @sgs_ErrWrite&lt;sgs_(Err)Write)</li></ul></div> <div class='item'><a name='sgs-Msg-function'></a><hr><h2>sgs_Msg [function]</h2><h3>int sgs_Msg( sgs_Context* C, int type, const char* what, ... )</h3><h4>prepares and prints the error specified</h4><ul><li>info about the system is at the <a href="#Messaging-system">Messaging system</a> page </li><li><code>type</code> is the output code (SGS_WARNING, SGS_ERROR etc.) </li><li><code>what</code> is the error text <ul><li>additional function name prefix can be specified with <a href="#sgs-FuncName-function">sgs_FuncName</a> or the SGSFN/SGSBASEFN macros </li></ul><li><code>what</code>, the function name prefix (if set) and the variable arguments are passed to a vsprintf-like function so printf syntax rules apply </li><li>function always returns 0 to be compatible with most error handling cases in C functions: &quot;return sgs_Msg( ... );&quot;</li></ul></div> <div class='item'><a name='sgs-WriteErrorInfo-function'></a><hr><h2>sgs_WriteErrorInfo [function]</h2><h3>void sgs_WriteErrorInfo( sgs_Context* C, int flags, sgs_ErrorOutputFunc func, void* ctx, int type, const char* msg )</h3><h4>writes error info using the error output function specified</h4><p> the error output function type has the following definition: </p><pre>typedef int (*sgs_ErrorOutputFunc) ( void*, const char*, ... );</pre><ul><li>error output function has the same type as fprintf, sgs_Writef and sgs_ErrWritef </li><li><code>type</code> and <code>msg</code> should be passed from the messaging callback - they are the same type number / error message </li><li><code>flags</code> should be one of SGS_ERRORINFO_STACK, SGS_ERRORINFO_ERROR, SGS_ERRORINFO_FULL <ul><li>SGS_ERRORINFO_STACK only writes the stack frame </li><li>SGS_ERRORINFO_ERROR only writes the error message </li><li>SGS_ERRORINFO_FULL writes both</li></ul></li></ul></div> <div class='item'><a name='sgs-PushErrorInfo-function'></a><hr><h2>sgs_PushErrorInfo [function]</h2><h3>void sgs_PushErrorInfo( sgs_Context* C, int flags, int type, const char* msg )</h3><h4>pushes a string generated from error info</h4><ul><li><code>type</code> and <code>msg</code> should be passed from the messaging callback - they are the same type number / error message </li><li><code>flags</code> should be one of SGS_ERRORINFO_STACK, SGS_ERRORINFO_ERROR, SGS_ERRORINFO_FULL <ul><li>SGS_ERRORINFO_STACK only writes the stack frame </li><li>SGS_ERRORINFO_ERROR only writes the error message </li><li>SGS_ERRORINFO_FULL writes both</li></ul></li></ul></div> <div class='item'><a name='sgs-HasFuncName-function'></a><hr><h2>sgs_HasFuncName [function]</h2><h3>int sgs_HasFuncName( sgs_Context* C )</h3><h4>checks if the currently executed function (last stack frame) has a name literal set</h4></div> <div class='item'><a name='sgs-FuncName-function'></a><hr><h2>sgs_FuncName [function]</h2><h3>void sgs_FuncName( sgs_Context* C, const char* fnliteral )</h3><h4>sets the function name string for the currently executed function (last stack frame)</h4><ul><li>the argument is expected to stay alive for the duration of the function call <ul><li>this makes string literals safe for the call, everything else should be avoided</li></ul></li></ul></div> <div class='item'><a name='SGSFN-function-alias'></a><hr><h2>SGSFN [function alias]</h2><h3>void SGSFN( const char* fnliteral )</h3><h4>sets the function name string, more info at <a href="#sgs-FuncName-function">sgs_FuncName</a></h4><ul><li>alias for <code>sgs_FuncName( &lt;implicit&gt; C, fnliteral )</code></li></ul></div> <div class='item'><a name='SGSBASEFN-function-alias'></a><hr><h2>SGSBASEFN [function alias]</h2><h3>void SGSBASEFN( const char* fnliteral )</h3><h4>sets the function name string if it hasn&#39;t already been set for the function</h4><ul><li>alias for <code>if( !sgs_HasFuncName( &lt;implicit&gt; C ) ) sgs_FuncName( &lt;implicit&gt; C, x )</code></li></ul></div> <div class='item'><a name='sgs-SetHookFunc-function'></a><hr><h2>sgs_SetHookFunc [function]</h2><h3>void sgs_SetHookFunc( sgs_Context* C, sgs_HookFunc func, void* ctx )</h3><h4>sets the hook function and user data pointer</h4><ul><li>hook function is called on function entry, exit and instruction change events </li><li>setting a new hook function disables the one that was set before (if any)</li></ul></div> <div class='item'><a name='sgs-GetHookFunc-function'></a><hr><h2>sgs_GetHookFunc [function]</h2><h3>SGSBOOL sgs_GetHookFunc( sgs_Context* C, sgs_HookFunc* outfunc, void** outctx )</h3><h4>writes the hook function and user data pointer that was set (if any), returns whether anything was written</h4></div> <div class='item'><a name='sgs-DefaultMemFunc-function'></a><hr><h2>sgs_DefaultMemFunc [function]</h2><h3>void* sgs_DefaultMemFunc( void* userdata, void* ptr, size_t size )</h3><h4>the default memory allocation function</h4><p> expected behavior: same as for <a href="#sgs-Memory-function">sgs_Memory</a> </p><p> sample implementation (same as in sgscript.h): </p><pre>if( ptr &amp;&amp; size ) return realloc( ptr, size ); else if( size ) return malloc( size ); if( ptr ) free( ptr ); return NULL;</pre></div> <div class='item'><a name='sgs-Memory-function'></a><hr><h2>sgs_Memory [function]</h2><h3>void sgs_Memory( sgs_Context* C, void* ptr, size_t size )</h3><h4>allocates and frees memory, as specified in arguments</h4><ul><li>there are four possible cases that are handled by the function: <ul><li><code>ptr</code> != NULL, <code>size</code> != 0: <code>ptr</code> is reallocated with new size, keeping as much data as possible, new block of memory is returned </li><li><code>ptr</code> != NULL, <code>size</code> == 0: <code>ptr</code> is freed, NULL is returned </li><li><code>ptr</code> == NULL, <code>size</code> != 0: a new block of memory is allocated and returned </li><li><code>ptr</code> == NULL, <code>size</code> == 0: nothing is done, NULL is returned</li></ul></li></ul></div> <div class='item'><a name='Memory-allocation-macros-macros'></a><hr><h2>Memory allocation macros [macros]</h2><h3>Memory allocation macros</h3><h4>these macros allow slightly simplified handling of memory</h4><ul><li><code>sgs_Malloc( C, size )</code>: allocates the memory (alias to <code>sgs_Memory( C, NULL, size )</code>) </li><li><code>sgs_Free( C, ptr )</code>: frees the memory (alias to <code>sgs_Memory( C, ptr, 0 )</code>) </li><li>sgs_Realloc: alias to sgs_Memory </li><li>the following macros expect that the variable sgs_Context* C is in the scope <ul><li><code>sgs_Alloc( what )</code>: allocates enough memory to fit the specified type <code>what</code> </li><li><code>sgs_Alloc_n( what, n )</code>: allocates enough memory to fit <code>n</code> instances of the specified type <code>what</code> </li><li><code>sgs_Alloc_a( what, app )</code>: allocates enough memory to fit the specified type <code>what</code> and <code>app</code> more bytes </li><li><code>sgs_Dealloc( ptr )</code>: frees the memory </li></ul><li>all of these functions, including sgs_Memory, work on the same heap, thus they are interchangeable</li></ul></div> <div class='item'><a name='sgs-CodeString-function'></a><hr><h2>sgs_CodeString [function]</h2><h3>const char* sgs_CodeString( int type, int val )</h3><h4>returns a string for the enumeration <code>type</code> value <code>val</code></h4><ul><li>there are 4 enumerations to have value names returned for: <ul><li>SGS_CODE_ER: error codes (SGS_ERROR, SGS_WARNING, ...) </li><li>SGS_CODE_VT: variable types (SGS_VT_BOOL, SGS_VT_FUNC, ...) </li><li>SGS_CODE_OP: VM instructions (SGS_SI_PUSH, SGS_SI_FORPREP, ... [internal])</li></ul></li></ul></div> <div class='item'><a name='sgs-Abort-function'></a><hr><h2>sgs_Abort [function]</h2><h3>SGSRESULT sgs_Abort( sgs_Context* C )</h3><h4>stops execution of current SGS functions up to the last C function in the stack, excluding the current</h4><h4>error codes</h4><ul><li>SGS_ENOTFND: last or next to last function in the stack was not a SGS function</li></ul></div> <div class='item'><a name='sgs-Stat-function'></a><hr><h2>sgs_Stat [function]</h2><h3>ptrdiff_t sgs_Stat( sgs_Context* C, int type )</h3><h4>returns or prints information about state of SGScript VM</h4><ul><li>the following <code>type</code> values are supported: <ul><li>SGS_STAT_VERSION: returns the version number of the VM </li><li>SGS_STAT_APIVERSION: returns the API version numver of the VM </li><li>SGS_STAT_OBJCOUNT: returns the number of objects created in the VM </li><li>SGS_STAT_MEMSIZE: returns the number of bytes allocated through this SGScript context </li><li>SGS_STAT_NUMALLOCS: returns the number of memory allocations (incremented on each alloc/realloc) </li><li>SGS_STAT_NUMFREES: returns the number of memory frees (incremented on each free/realloc) </li><li>SGS_STAT_NUMBLOCKS: number of memory blocks currently allocated (incremented on alloc, decremented on free) </li><li>SGS_STAT_DUMP_STACK: prints all of the variables in the stack </li><li>SGS_STAT_DUMP_GLOBALS: prints all variables in the global dictionary </li><li>SGS_STAT_DUMP_OBJECTS: prints all objects in the context </li><li>SGS_STAT_DUMP_FRAMES: prints all functions in the call stack </li><li>SGS_STAT_DUMP_STATS: dump some info about memory and objects </li><li>SGS_STAT_XDUMP_STACK: verbosely dumps all of the variables in the stack (extended info, may be much longer)</li></ul></li></ul><ul><li>tips: <ul><li>compare return value of SGS_STAT_VERSION against SGS_VERSION_INT if the code is version-sensitive </li><li>compare return value of SGS_STATE_APIVERSION against SGS_API_VERSION if dynamic loading is used and multiple versions should be supported</li></ul></li></ul></div> <div class='item'><a name='sgs-Cntl-function'></a><hr><h2>sgs_Cntl [function]</h2><h3>int32_t sgs_Cntl( sgs_Context* C, int what, int32_t val )</h3><h4>modifies the state of the VM or returns info about it</h4><ul><li>the following <code>what</code> values are supported: <ul><li>SGS_CNTL_STATE: sets the new compilation state from <code>val</code>, returns the previous value </li><li>SGS_CNTL_GET_STATE: returns the currently set compilation state </li><li>SGS_CNTL_MINLEV: sets the new minimum error level from <code>val</code>, returns the previous value </li><li>SGS_CNTL_GET_MINLEV: returns the currently set minimum error level </li><li>SGS_CNTL_ERRNO: if <code>val</code> is true, sets internal errno to 0, otherwise - to <code>errno</code>, returns the previous value </li><li>SGS_CNTL_SET_ERRNO: sets internal errno to <code>val</code>, returns the previous value </li><li>SGS_CNTL_GET_ERRNO: returns the currently set internal errno </li><li>SGS_CNTL_ERRSUP: sets error suppression lock count to <code>val</code>, returns the previous value </li><li>SGS_CNTL_GET_ERRSUP: returns the currently set error suppression lock count for the last stack frame </li></ul><li>everything else does nothing and returns 0</li></ul></div> <div class='item'><a name='sgs-StackFrameInfo-function'></a><hr><h2>sgs_StackFrameInfo [function]</h2><h3>void sgs_StackFrameInfo( sgs_Context* C, sgs_StackFrame* frame, const char** name, const char** file, int* line )</h3><h4>helps to retrieve file name, function name and line number of the specified stack frame</h4><ul><li>each non-NULL pointer is initialized with valid data; even if it may not be very helpful (for example, all anonymous functions get the same name - &quot;&lt;anonymous function&gt;&quot;)</li></ul></div> <div class='item'><a name='sgs-GetFramePtr-function'></a><hr><h2>sgs_GetFramePtr [function]</h2><h3>sgs_StackFrame* sgs_GetFramePtr( sgs_Context* C, int end )</h3><h4>returns a call stack frame pointer</h4><ul><li>if <code>end</code> is not 0, pointer to topmost frame is returned, otherwise a pointer to first frame is returned</li></ul></div> <div class='item'><a name='sgs-Errno-function-alias'></a><hr><h2>sgs_Errno [function alias]</h2><h3>int sgs_Errno( sgs_Context* C, int clear )</h3><h4>copies errno to internal errno value if <code>clear</code> is not 0, otherwise internal errno value is set to 0, returns <code>clear</code></h4><ul><li>used with a boolean expression and chaining to set errno if the expression returned false, like this: <ul><li><code>sgs_PushBool( C, sgs_Errno( C, rename( a, b ) == 0 ) )</code></li></ul></li></ul></div> <div class='item'><a name='sgs-SetErrno-function-alias'></a><hr><h2>sgs_SetErrno [function alias]</h2><h3>int sgs_SetErrno( sgs_Context* C, int err )</h3><h4>sets a specific value <code>err</code> to the internal errno variable</h4><ul><li>alias to <code>sgs_Cntl( C, SGS_CNTL_SET_ERRNO, err )</code></li></ul></div> <div class='item'><a name='sgs-GetLastErrno-function-alias'></a><hr><h2>sgs_GetLastErrno [function alias]</h2><h3>int sgs_GetLastErrno( sgs_Context* C )</h3><h4>returns the currently set internal errno variable</h4><ul><li>alias to <code>sgs_Cntl( C, SGS_CNTL_GET_ERRNO, 0 )</code></li></ul></div> <div class='item'><a name='sgs-PushStringBuf32-function'></a><hr><h2>sgs_PushStringBuf32 [function]</h2><h3>void sgs_PushStringBuf32( sgs_Context* C, sgs_String32* S, const char* str, sgs_SizeVal len )</h3><h4>pushes a temporary string variable from the specified buffer, allocated in the <code>sgs_String32</code> object</h4><ul><li>string buffer must be freed from all contexts before the memory it&#39;s allocated on is released </li><li><code>len</code> is limited to 31 character</li></ul></div> <div class='item'><a name='sgs-PushString32-function'></a><hr><h2>sgs_PushString32 [function]</h2><h3>void sgs_PushString32( sgs_Context* C, sgs_String32* S, const char* str )</h3><h4>pushes a temporary string variable from the specified string, allocated in the <code>sgs_String32</code> object</h4><ul><li>string buffer must be freed from all contexts before the memory it&#39;s allocated on is released </li><li>alias to <code>sgs_PushStringBuf32( C, S, str, SGS_STRINGLENGTHFUNC(str) )</code></li></ul></div> <div class='item'><a name='sgs-CheckString32-function'></a><hr><h2>sgs_CheckString32 [function]</h2><h3>void sgs_CheckString32( sgs_String32* S )</h3><h4>attempts to trigger a debug breakpoint if the specified temporary string object is not freed from all contexts</h4><ul><li>internal function <code>sgs_BreakIf</code> is used</li></ul></div> <div class='item'><a name='sgs-IsFreedString32-function'></a><hr><h2>sgs_IsFreedString32 [function]</h2><h3>SGSBOOL sgs_IsFreedString32( sgs_String32* S )</h3><h4>returns whether the specified temporary string object is freed from all contexts</h4><ul><li>for usage with custom error outputs / assertion systems</li></ul></div> <div class='item'><a name='Interface-implementation'></a><hr><h2>Interface implementation</h2></div> <div class='item'><a name='C-Functions'></a><hr><h2>C Functions</h2><p> A C function has the type <code>int CFunc( sgs_Context* )</code>. It receives the context that called it and must return the number of return values pushed on stack. </p><h4>Conventions</h4><p> There are no forced courses of action beyond this point. However, to simplify development, some conventions were established and are used throughout the standard library and are suggested to follow. </p><h5>General structure</h5><ul><li>the usage of SGS_CTX in argument list is suggested to enable the use of certain macros that assume the availability of <code>sgs_Context* C</code> </li><li>there are no restrictions on function names, however it helps to mark the scripting engine functions with a common prefix and if they wrap a native function, including the name of the wrapped function is suggested</li></ul><h5>Argument loading</h5><ul><li>prefer using <a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgs</a>, followed by <a href="#sgs-LoadArgsExt-VA-function">sgs_LoadArgsExt</a>, followed by the sgs_Parse***/sgs_Is***/sgs_ItemType(Ext)/... functions together with ArgError function family for error handling</li></ul><h5>Error handling</h5><ul><li>it is preferred to do most of it at the beginning, before custom allocations (VM stack doesn&#39;t count here), where it is possible to just <code>return sgs_Msg( C, SGS_WARNING, &quot;Error message&quot; )</code> </li><li>SGS_WARNING is for non-fatal errors, SGS_ERROR is for errors that make it impossible to continue (severe, undoubted logical errors fall into this category) </li><li>on error, functions should return nothing or null</li></ul><p> A typical function </p><pre>int sgsfunc_sample( SGS_CTX ) { sgs_Int num; char* str; char* buf; sgs_SizeVal bufsize; if( !sgs_LoadArgs( C, &quot;ism&quot;, &amp;num, &amp;str, &amp;buf, &amp;bufsize ) ) return 0; if( bufsize == 0 ) return sgs_Msg( C, SGS_WARNING, &quot;buffer cannot be empty&quot; ); // sgs_Msg always returns 0 // .. do something with the passed arguments .. // anything can be returned .. // .. but in this case, we want to say .. // .. that the action was successful sgs_PushBool( C, 1 ); return 1; }</pre></div> <div class='item'><a name='Object-interface'></a><hr><h2>Object interface</h2><p> Every interface function has the type <code>int ObjCallback ( sgs_Context* C, sgs_VarObj* data, ... )</code>. Not every of them has to be implemented (none of them are required) but for all non-pointer objects it helps to have at least one of them. </p><p> Interface is a structure that contains of an array and 10 function pointers in the following order: destruct, gcmark, getindex, setindex, convert, serialize, dump, getnext, call, expr. This is how interfaces are usually defined in code: </p><pre>sgs_ObjInterface object_interface[1] = {{ &quot;object_type_name&quot;, object_destruct, NULL, /* destruct, gcmark */ object_getindex, NULL, /* getindex, setindex */ NULL, NULL, NULL, NULL, /* convert, serialize, dump, getnext */ NULL, NULL /* call, expr */ }};</pre><p> The interface is defined as an array with size=1 to later be able to use it in code without prepending &quot;&amp;&quot; to the name. </p><h4>DESTRUCT - destruction callback</h4><h5>When called:</h5><ul><li>Before the object is about to be destroyed. </li><li>On <a href="#sgs-ObjCallDtor-function">sgs_ObjCallDtor</a></li></ul><h5>Additional arguments:</h5><p> None. </p><h5>Stack frame:</h5><p> Empty. </p><h5>Return values:</h5><p> Non-negative value if successful, negative on error. </p><h5>Additional notes:</h5><p> It is important to minimize the possibility of failure here. The system cannot help in any way if memory or ownership states are corrupted. </p><h4>GETINDEX - index/property retrieval callback</h4><h5>When called:</h5><ul><li>On A[B] (index) and A.B (property) reads in SGScript. </li><li>Index/Property/Path function families in the C API.</li></ul><h5>Additional arguments:</h5><ul><li>sgs_Variable* key -- key variable to be used to find a sub-item </li><li>int isprop -- (0/1) whether this is a property read (1) or index read (0)</li></ul><h5>Stack frame:</h5><p> Empty at beginning. Expected to have at least one item on stack after a successful index/property read. The topmost one is used. </p><h5>Return values:</h5><ul><li>Non-negative value if successful, negative on error. </li><li>Use SGS_ENOTFND if the specified index/property was not found.</li></ul><h5>Additional notes:</h5><p> It is safe to use conversion functions on the key variable. </p><h4>SETINDEX - index/property setting callback</h4><h5>When called:</h5><ul><li>On A[B] (index) and A.B (property) writes in SGScript. </li><li>Index/Property/Path function families in the C API.</li></ul><h5>Additional arguments:</h5><ul><li>sgs_Variable* key -- key variable to be used to find a sub-item </li><li>sgs_Variable* value -- value variable to be used in setting the value of the sub-item </li><li>int isprop -- (0/1) whether this is a property read (1) or index read (0)</li></ul><h5>Stack frame:</h5><p> Empty. </p><h5>Return values:</h5><ul><li>Non-negative value if successful, negative on error. </li><li>Use SGS_ENOTFND if the specified index/property was not found. </li><li>Use SGS_EINVAL if the given value could not be used.</li></ul><h5>Additional notes:</h5><p> It is safe to use conversion functions on both variables. </p><h4>CONVERT - conversion callback</h4><h5>When called:</h5><p> Depending on the argument, it is called by different sources: </p><ul><li>type conversion: to*** function families and other conversion triggers (like operators) in SGScript and the Get/To/Parse function families in the C API. </li><li>SGS_CONVOP_CLONE: called on <a href="#clone-function">clone</a> / <a href="#sgs-CloneItem-function">sgs_Clone</a> </li><li>SGS_CONVOP_TYPEOF: called on <a href="#typeof-function">typeof</a> / <a href="#sgs-TypeOf-function">sgs_TypeOf</a> </li><li>SGS_CONVOP_TOITER: called on foreach / <a href="#sgs-PushIterator-P-functions">sgs_PushIterator(P)</a> / <a href="#sgs-GetIterator-P-functions">sgs_GetIterator(P)</a></li></ul><h5>Additional arguments:</h5><ul><li>int type -- one of SGS_VT_[BOOL|INT|REAL|STRING|PTR] or SGS_CONVOP_CLONE / SGS_CONVOP_TYPEOF / SGS_CONVOP_TOITER</li></ul><h5>Stack frame:</h5><p> Empty at beginning. Expected to have at least one item on stack after a successful conversion. The topmost one is used. </p><p> Depending on the argument, it requires different variable types on stack: </p><ul><li>type conversions require a value of the right type. </li><li>SGS_CONVOP_CLONE should return an exact copy of the same object </li><li>SGS_CONVOP_TYPEOF should return a string containing the type name </li><li>SGS_CONVOP_TOITER should return an object with a GETNEXT callback</li></ul><h5>Return values:</h5><ul><li>Non-negative value if successful, negative on error. </li><li>Use SGS_ENOTSUP if specified conversion is not supported.</li></ul><h5>Additional notes:</h5><ul><li>It should be safe to give the wrong variable type but errors may not be triggered in such cases.</li></ul><h4>SERIALIZE - serialization callback</h4><h5>When called:</h5><ul><li><a href="#serialize-function">serialize</a> in SGScript. </li><li><a href="#sgs-Serialize-function">sgs_Serialize</a> in the C API.</li></ul><h5>Additional arguments:</h5><p> None. </p><h5>Stack frame:</h5><p> Empty. </p><h5>Return values:</h5><ul><li>Non-negative value if successful, negative on error.</li></ul><h5>Additional notes:</h5><p> Callback requires no data but expects that <a href="#sgs-Serialize-function">sgs_Serialize</a> / <a href="#sgs-SerializeObject-function">sgs_SerializeObject</a> is successfully called once. In the case of sgs_SerializeObject, the necessary number (equal to argument count, passed to the function) of sgs_Serialize calls must be made before it. </p><h4>DUMP - debug dump callback</h4><h5>When called:</h5><ul><li><a href="#printvar-function">printvar</a>, <a href="#dumpvar-function">dumpvar</a>, <a href="#printvar-ext-function">printvar_ext</a>, <a href="#dumpvar-ext-function">dumpvar_ext</a> in SGScript. </li><li><a href="#sgs-DumpVar-function">sgs_DumpVar</a> in the C API.</li></ul><h5>Additional arguments:</h5><ul><li>int maxdepth -- remaining recursion depth of dump to be passed on to <a href="#sgs-DumpVar-function">sgs_DumpVar</a> calls.</li></ul><h5>Stack frame:</h5><p> Empty at beginning. Expected to have at least one item on stack after a successful conversion. The topmost one is used. </p><h5>Return values:</h5><ul><li>Non-negative value if successful, negative on error.</li></ul><h5>Additional notes:</h5><ul><li>Callback expects a string variable on the top of the stack. </li><li><a href="#sgs-DumpVar-function">sgs_DumpVar</a> with maxdepth &lt;= 0 returns &quot;...&quot;, so it is not necessary to handle such cases beyond passing the parameter.</li></ul><h4>GCMARK - garbage collector marking callback</h4><h5>When called:</h5><ul><li><a href="#gc-collect-function">gc_collect</a> in SGScript. </li><li><a href="#sgs-GCMark-Array-function">sgs_GCMark</a> / <a href="#sgs-GCExecute-function">sgs_GCExecute</a> in the C API.</li></ul><h5>Additional arguments:</h5><p> None. </p><h5>Stack frame:</h5><p> Empty. </p><h5>Return values:</h5><ul><li>Non-negative value if successful, negative on error.</li></ul><h5>Additional notes:</h5><ul><li>Callback expects that sgs_GCMark is called on all of the owned variables. </li><li>It is important to minimize the possibility of failure here. The system cannot help in any way if memory or ownership states are corrupted.</li></ul><h4>GETNEXT - iterator control callback</h4><h5>When called:</h5><ul><li>foreach in SGScript. </li><li><a href="#sgs-IterAdvance-P-functions">sgs_IterAdvance(P)</a> / <a href="#sgs-IterPushData-P-functions">sgs_IterPushData(P)</a> / <a href="#sgs-IterGetData-P-functions">sgs_IterGetData(P)</a></li></ul><h5>Additional arguments:</h5><ul><li>int act -- specifies the actions that should be taken in this call. <ul><li>if argument == 0, iterator&#39;s position must be increased by one step and the return value must contain whether iterator has not reached end (positive value if so, otherwise - 0) or an error if callback has failed </li><li>otherwise, callback must push the data required (if SGS_GETNEXT_KEY is set, the key, and if SGS_GETNEXT_VALUE is set - the value, in exactly that order)</li></ul></li></ul><h5>Stack frame:</h5><p> Empty at beginning. Expects at least one (if either flag is set, but not both) or two (if both flags are set) variables on success. Key first, value second. </p><h5>Return values:</h5><ul><li>Non-negative value if successful, negative on error. </li><li>if argument == 0, must return whether iterator has not reached end (positive value if so, otherwise - 0)</li></ul><h5>Additional notes:</h5><p> None. </p><h4>CALL - the &quot;function call&quot; callback</h4><h5>When called:</h5><ul><li>when an object is used like a function <ul><li><code>object_variable( .. )</code> in SGScript </li><li>Call function family in the C API</li></ul></li></ul><h5>Additional arguments:</h5><p> None. </p><h5>Stack frame:</h5><p> Contains all the same things as any C function call would: optional <code>this</code> variable and optional argument list. Expects at least the returned number of items after the call to be used as return values. </p><h5>Return values:</h5><ul><li>Non-negative value if successful, negative on error. </li><li>On success, the number returned is the number of variables returned by the function.</li></ul><h5>Additional notes:</h5><p> None. </p><h4>EXPR - expression callback</h4><h4>When called:</h4><ul><li>On arithmetic operations with the object as one or both operands in SGScript. </li><li>On <a href="#sgs-ArithOp-function">sgs_ArithOp</a> in the C API.</li></ul><h5>Additional arguments:</h5><ul><li>sgs_Variable* A - the first (left side) operand or the only one in case of SGS_EOP_NEGATE </li><li>sgs_Variable* B - the second (right side) operand or NULL in case of SGS_EOP_NEGATE </li><li>int op - operation type, one of SGS_EOP_[ADD|SUB|MUL|DIV|MOD|COMPARE|NEGATE]</li></ul><h5>Stack frame:</h5><p> Empty at beginning. Expects at least one variable on success (the topmost one will be used). </p><h5>Return values:</h5><ul><li>Non-negative value if successful, negative on error.</li></ul><h5>Additional notes:</h5><ul><li>SGS_EOP_COMPARE expects int/real value: &gt;0 if A &gt; B, &lt;0 if A &lt; B, =0 if A = B</li></ul><p> The full list of operators triggering the operations: </p><ul><li>SGS_EOP_ADD: binary +, += </li><li>SGS_EOP_SUB: binary -, -= </li><li>SGS_EOP_MUL: *, *= </li><li>SGS_EOP_DIV: /, /= </li><li>SGS_EOP_MOD: %, %= </li><li>SGS_EOP_COMPARE: &lt;, &lt;=, &gt;, &gt;=, ==, !=, ===, !== </li><li>SGS_EOP_NEGATE: unary -</li></ul></div> <div class='item'><a name='Interaction-with-the-environment'></a><hr><h2>Interaction with the environment</h2><p> Most operations are directed towards the scripting engine, that is - environment makes a function call and scripting engine handles it. For everything else, there are callbacks. </p><h4>Memory allocation</h4><ul><li>sgs_MemFunc must be specified in creation of the scripting engine context </li><li>sgs_MemFunc (re)allocates and frees memory </li><li>unlike realloc, if size = 0, this function must return NULL </li><li><a href="#sgs-DefaultMemFunc-function">sgs_DefaultMemFunc</a> is the sample implementation </li><li>the expected behavior is same as for <a href="#sgs-Memory-function">sgs_Memory</a></li></ul><h4>Output</h4><ul><li>sgs_MsgFunc and sgs_OutputFunc are responsible for piping the outputs to their destinations </li><li>they can be set at any moment after the creation of the scripting engine context </li><li>sgs_MsgFunc takes the following arguments: <ul><li>void* data - the user data pointer </li><li>sgs_Context* C - the scripting engine context </li><li>int type - the debug type (SGS_INFO, SGS_WARNING etc.) </li><li>const char* message - the debug message </li><li><a href="#sgs-StdMsgFunc-NoAbort-functions">sgs_StdMsgFunc(_NoAbort)</a> are the sample implementations </li></ul><li>sgs_OutputFunc takes the following arguments: <ul><li>void* data - the user data pointer </li><li>sgs_Context* C - the scripting engine context </li><li>const void* ptr - the data to write </li><li>sgs_SizeVal size - the size of data to write </li><li><a href="#sgs-StdOutputFunc-function">sgs_StdOutputFunc</a> is the sample implementation</li></ul></li></ul><h4>Execution notifications</h4><ul><li>sgs_HookFunc must be set to retrieve events of that kind </li><li>it can be set at any moment after the creation of the scripting engine context </li><li>sgs_HookFunc takes the following arguments: <ul><li>void* data - the user data pointer </li><li>sgs_Context* C - the scripting engine context </li><li>int event - the event that occured, can be one of these values: <ul><li>SGS_HOOK_ENTER - function was entered </li><li>SGS_HOOK_EXIT - function was exited </li><li>SGS_HOOK_STEP - instruction is about to be executed</li></ul></li></ul></li></ul></div> <div class='item'><a name='Commonly-required-advanced-tasks'></a><hr><h2>Commonly required advanced tasks</h2><h4>Method handling</h4><ul><li>the preferred way to handle methods with a specific object type for <code>this</code>:</li></ul><pre>ObjectDataStruct* data; if( !SGS_PARSE_METHOD( C, Object_interface_pointer, data, Object_name, Method_name ) ) return 0;</pre><ul><li>the OLD way, version 1:</li></ul><pre>sgs_FuncName( C, &quot;&lt;object&gt;.&lt;method&gt;&quot; ); if( !sgs_Method( C ) || !sgs_IsObject( C, 0, Object_interface_pointer ) ) return sgs_ArgErrorExt( C, 0, 1, &quot;&lt;object&gt;&quot;, &quot;&quot; ); ObjectDataStruct* data = (ObjectDataStruct*) sgs_GetObjectData( C, 0 ); sgs_HideThis( C );</pre><ul><li>the OLD way, version 2: Method + function handling (function that can be called as a method too)</li></ul><pre>int method_call = sgs_Method( C ); sgs_FuncName( C, method_call ? &quot;&lt;object&gt;.&lt;method&gt;&quot; : &quot;&lt;object_function&gt;&quot; ); if( !sgs_IsObject( C, 0, Object_interface_pointer ) ) return sgs_ArgErrorExt( C, 0, method_call, &quot;&lt;object&gt;&quot;, &quot;&quot; ); ObjectDataStruct* data = (ObjectDataStruct*) sgs_GetObjectData( C, 0 ); sgs_ForceHideThis( C );</pre><ul><li>the reason why the first method is preferred to others is: it&#39;s shorter, does pretty much the same thing and resolves to <a href="#sgs-ParseMethod-function">sgs_ParseMethod</a>, which allows sharing more code and rebuilding the <a href="#SGS-PARSE-METHOD-function-alias">SGS_PARSE_METHOD</a> macro abstraction, if necessary</li></ul></div> <div class='item'><a name='Standard-library-reference'></a><hr><h2>Standard library reference</h2></div> <div class='item'><a name='Core-library'></a><hr><h2>Core library</h2><p> This library is loaded on initialization and contains the functions and constants necessary to do primary actions: </p><ul><li>execution of additional scripts </li><li>creating and using array, class, dict, map, closure </li><li>converting between variables </li><li>serialization / deserialization </li><li>operation control </li><li>error handling and throwing </li><li>global environment modification </li><li>standard input / output </li><li>data debugging</li></ul><h4>Functions:</h4><ul><li>containers <ul><li><a href="#array-function">array</a> - returns an array containing the specified variables </li><li><a href="#dict-function">dict</a> - returns a key-value map object (string keys) containing the specified variables </li><li><a href="#map-function">map</a> - returns a key-value map object (many key types) containing the specified variables </li><li><a href="#class-function">class</a> - returns an index fallback / overloading object, linking both specified variables </li><li><a href="#array-filter-function">array_filter</a> - returns an array that is filtered with a truth test or the specified function </li><li><a href="#array-process-function">array_process</a> - convert all array elements by a function </li><li><a href="#dict-filter-function">dict_filter</a> - returns a dict object that is filtered with a truth test or the specified function </li><li><a href="#dict-process-function">dict_process</a> - convert all dictionary elements by a function </li><li><a href="#dict-size-function">dict_size</a> - returns the number of items in a dict </li><li><a href="#map-size-function">map_size</a> - returns the number of items in a map </li><li><a href="#isset-function">isset</a> - checks if the specified property is available </li><li><a href="#unset-function">unset</a> - unsets the specified property (only for dict/map objects) </li><li><a href="#clone-function">clone</a> - returns the cloned variable or the same if immutable </li><li><a href="#get-keys-function">get_keys</a> - returns an array of keys from an iterable </li><li><a href="#get-values-function">get_values</a> - returns an array of values from an iterable </li><li><a href="#get-concat-function">get_concat</a> - returns an array with all values from all iterables concatenated together in order </li><li><a href="#get-merged-function">get_merged</a> - returns a dict with all mappings merged </li><li><a href="#get-merged-map-function">get_merged_map</a> - returns a map with all mappings merged </li><li><a href="#get-iterator-function">get_iterator</a> - returns an iterator from the passed object, if it has one </li><li><a href="#iter-advance-function">iter_advance</a> - advances an iterator to the next position, returning if there is any more data to read </li><li><a href="#iter-getdata-function">iter_getdata</a> - returns key/value data from iterator </li></ul><li>type info and conversion <ul><li><a href="#tobool-function">tobool</a> - returns a variable, converted to boolean </li><li><a href="#toint-function">toint</a> - returns a variable, converted to an integer </li><li><a href="#toreal-function">toreal</a> - returns a variable, converted to a real value </li><li><a href="#tostring-function">tostring</a> - returns a variable, converted to a string </li><li><a href="#toptr-function">toptr</a> - returns a variable, converted to pointer </li><li><a href="#parseint-function">parseint</a> - try to parse a variable as integer, return the value or null on failure </li><li><a href="#parsereal-function">parsereal</a> - try to parse a variable as string, return the value or null on failure </li><li><a href="#typeof-function">typeof</a> - returns the type string of a variable </li><li><a href="#typeid-function">typeid</a> - returns type ID of a variable </li><li><a href="#typeptr-function">typeptr</a> - returns type interface pointer from object variables </li><li><a href="#typeptr-by-name-function">typeptr_by_name</a> - returns type interface pointer by its name </li><li><a href="#is-numeric-function">is_numeric</a> - returns if variable is a numeric type </li><li><a href="#is-callable-function">is_callable</a> - returns if variable can be called as a function </li><li><a href="#is-array-function">is_array</a> - returns if variable is an array </li><li><a href="#is-dict-function">is_dict</a> - returns if variable is a dict </li><li><a href="#is-map-function">is_map</a> - returns if variable is a map </li><li><a href="#is-iterable-function">is_iterable</a> - returns if variable is iterable </li></ul><li>input/output <ul><li><a href="#print-println-printlns-errprint-errprintln-errprintlns-functions">print, println, printlns, errprint, errprintln, errprintlns</a> - write variables to output callback/stream </li><li><a href="#printvar-function">printvar</a> - write variable dumps to output callback/stream </li><li><a href="#printvar-ext-function">printvar_ext</a> - write variable dump to output callback/stream, optionally specifying max. recursion depth </li><li><a href="#read-stdin-function">read_stdin</a> - attempt to read from standard input file (stdin) </li></ul><li>operating system <ul><li><a href="#ftime-function">ftime</a> - returns an always increasing time value, in seconds, as a real value </li></ul><li>utilities <ul><li><a href="#rand-function">rand</a> - returns a random integer between 0 and RAND_MAX </li><li><a href="#randf-function">randf</a> - returns a random real value between 0 and 1 </li><li><a href="#srand-function">srand</a> - reseed random number generator </li><li><a href="#hash-fnv-function">hash_fnv</a> - generate a hash using the FNV-1a algorithm </li><li><a href="#hash-crc32-function">hash_crc32</a> - generate a hash/checksum using the crc32 algorithm </li></ul><li>SGS-specific utilities <ul><li><a href="#va-get-args-function">va_get_args</a> - returns an array of all arguments passed to calling function </li><li><a href="#va-get-arg-function">va_get_arg</a> - returns one of the arguments passed to calling function </li><li><a href="#va-arg-count-function">va_arg_count</a> - returns the number of all arguments passed to calling function </li><li><a href="#sys-call-function">sys_call</a> - call a function/callable dynamically (function and <code>this</code> specified at runtime) </li><li><a href="#sys-apply-function">sys_apply</a> - call a function/callable even more dynamically (argument count also specified at runtime) </li><li><a href="#pcall-function">pcall</a> - do a protected call by trapping all internal messages in the specified callback </li><li><a href="#assert-function">assert</a> - emit an error if a condition does not evaluate to <code>true</code> </li><li><a href="#eval-function">eval</a> - compile and run script code, retrieve return values </li><li><a href="#eval-file-function">eval_file</a> - compile and rune script file, retrieve return values </li><li><a href="#compile-sgs-function">compile_sgs</a> - compile script code </li><li><a href="#include-library-function">include_library</a> - load a built-in library </li><li><a href="#include-file-function">include_file</a> - load a script file </li><li><a href="#include-shared-function">include_shared</a> - load a dynamically linked library / shared object (.DLL/.SO) </li><li><a href="#import-cfunc-function">import_cfunc</a> - load a C function from .DLL/.SO </li><li><a href="#include-function">include</a> - load many types of files </li><li><a href="#sys-curfile-function">sys_curfile</a> - returns the origin file of the calling function </li><li><a href="#sys-curfiledir-function">sys_curfiledir</a> - returns the directory of the origin file of the calling function </li><li><a href="#sys-backtrace-function">sys_backtrace</a> - returns call stack info </li><li><a href="#sys-msg-function">sys_msg</a> - emit a system message </li><li><a href="#INFO-function">INFO</a> - emit an INFO message </li><li><a href="#WARNING-function">WARNING</a> - emit a WARNING message </li><li><a href="#ERROR-function">ERROR</a> - emit an ERROR message </li><li><a href="#sys-abort-function">sys_abort</a> - stop the execution of the calling SGS function </li><li><a href="#app-abort-function">app_abort</a> - abort execution of application (exit application immediately with an error) </li><li><a href="#app-exit-function">app_exit</a> - exit application immediately </li><li><a href="#sys-replevel-function">sys_replevel</a> - change the minimum message reporting level </li><li><a href="#sys-stat-function">sys_stat</a> - write info about system state </li><li><a href="#errno-function">errno</a> - return current errno value as number or string </li><li><a href="#errno-string-function">errno_string</a> - return specified or current errno value as string </li><li><a href="#errno-value-function">errno_value</a> - return the errno value corresponding to the name </li><li><a href="#dumpvar-function">dumpvar</a> - returns the dump string of variables </li><li><a href="#dumpvar-ext-function">dumpvar_ext</a> - returns the dump string of a variable, optionally specifying max. recursion depth </li><li><a href="#gc-collect-function">gc_collect</a> - run the garbage collector to remove inaccessible objects </li><li><a href="#serialize-function">serialize</a> - returns a byte buffer containing info necessary to later recreate variable structure </li><li><a href="#unserialize-function">unserialize</a> - recreate variable structure from a byte buffer</li></ul></li></ul><h4>Objects and their methods:</h4><ul><li><a href="#array-object">array</a> <ul><li><a href="#array-push-method">push</a> </li><li><a href="#array-pop-method">pop</a> </li><li><a href="#array-shift-method">shift</a> </li><li><a href="#array-unshift-method">unshift</a> </li><li><a href="#array-insert-method">insert</a> </li><li><a href="#array-erase-method">erase</a> </li><li><a href="#array-part-method">part</a> </li><li><a href="#array-clear-method">clear</a> </li><li><a href="#array-reverse-method">reverse</a> </li><li><a href="#array-resize-method">resize</a> </li><li><a href="#array-reserve-method">reserve</a> </li><li><a href="#array-sort-method">sort</a> </li><li><a href="#array-sort-custom-method">sort_custom</a> </li><li><a href="#array-sort-mapped-method">sort_mapped</a> </li><li><a href="#array-find-method">find</a> </li><li><a href="#array-remove-method">remove</a> </li><li><a href="#array-unique-method">unique</a> </li><li><a href="#array-random-method">random</a> </li><li><a href="#array-shuffle-method">shuffle</a> </li></ul><li><a href="#dict-object">dict</a> </li><li><a href="#map-object">map</a> </li><li><a href="#class-object">class</a></li></ul><h4>Constants:</h4><ul><li><a href="#SGS-constants">SGS_***</a> - error levels </li><li><a href="#VT-constants">VT_***</a> - variable type IDs </li><li><a href="#RAND-MAX-constant">RAND_MAX</a> - maximum value that can be returned by <a href="#rand-function">rand</a></li></ul><h4>Other:</h4><ul><li><a href="#G-superglobal">_G</a> - environment superglobal, a dict containing all global variable names and values; can be changed</li></ul></div> <div class='item'><a name='array-function'></a><hr><h2>array [function]</h2><h3>array( ... )</h3><h4>returns an <a href="#array-object">array</a>, containing the arguments</h4><ul><li>similar to the array literal, though somewhat limited</li></ul><pre>array( &quot;5&quot;, 6, 7.0 ) // same as [&quot;5&quot;,6,7.0]</pre></div> <div class='item'><a name='dict-function'></a><hr><h2>dict [function]</h2><h3>dict( [key, value, ...] )</h3><h4>returns a &#39;<a href="#dict-object">dict</a>&#39; (dictionary/hash table) object, containing the even arguments mapped to respective previous arguments</h4><ul><li>if no arguments are passed, an empty dictionary is returned </li><li>if an even number of arguments is passed, function returns null and emits a warning </li><li>all even arguments must be strings or convertible to strings</li></ul><pre>dict( &quot;name&quot;, &quot;John&quot;, &quot;phone&quot;, 1234567890 ); // same as { name = &quot;John&quot;, phone = 1234567890 }</pre></div> <div class='item'><a name='map-function'></a><hr><h2>map [function]</h2><h3>map( [key, value, ...] )</h3><h4>returns a &#39;<a href="#map-object">map</a>&#39; (map/hash table) object, containing the even arguments mapped to respective previous arguments</h4><ul><li>if no arguments are passed, an empty map is returned </li><li>if an even number of arguments is passed, function returns null and emits a warning</li></ul><pre>map( &quot;John&quot;, &quot;name&quot;, 1234567890, &quot;phone&quot; ); // useful for mapping additional data to variables or making sets</pre></div> <div class='item'><a name='class-function'></a><hr><h2>class [function]</h2><h3>class( first, second )</h3><h4>returns a <a href="#class-object">class</a> object with <code>first</code> set as the primary data source and <code>second</code> set as the secondary/backup data source</h4><ul><li>both arguments accept all kinds of variables but it&#39;s generally preferred to use only dicts / maps / special objects </li><li>refer to <a href="#Classes">Classes</a> for more information on how class objects work and how to use them</li></ul><pre>someCommonInterface = { printdata = function(){ print( this.data ); } }; c = class( { data = &quot;5&quot; }, someCommonInterface ); c.data = &quot;6&quot;; c.printdata(); // prints 6</pre></div> <div class='item'><a name='array-filter-function'></a><hr><h2>array_filter [function]</h2><h3>array_filter( array[, callable] )</h3><h4>return an array with the items that convert to boolean &#39;true&#39;, optionally preprocessed by a callable</h4><ul><li>two arguments are passed to the callable: value, index</li></ul><pre>array_filter([ 0, 1, 2, 3 ]); // returns [1,2,3]</pre></div> <div class='item'><a name='array-process-function'></a><hr><h2>array_process [function]</h2><h3>array_process( array, callable )</h3><h4>return an array with the items passed through a callable</h4><ul><li>two arguments are passed to the callable: value, index</li></ul></div> <div class='item'><a name='dict-filter-function'></a><hr><h2>dict_filter [function]</h2><h3>dict_filter( dict[, callable] )</h3><h4>return a dict with the items that convert to boolean &#39;true&#39;, optionally preprocessed by a callable</h4><ul><li>two arguments are passed to the callable: value, key</li></ul><pre>dict_filter({ a = 0, b = 1 }); // returns {b=1}</pre></div> <div class='item'><a name='dict-process-function'></a><hr><h2>dict_process [function]</h2><h3>dict_process( dict, callable )</h3><h4>return a dict with the items passed through a callable</h4><ul><li>two arguments are passed to the callable: value, key</li></ul></div> <div class='item'><a name='dict-size-function'></a><hr><h2>dict_size [function]</h2><h3>dict_size( dict )</h3><h4>return the number of entries in the dict object</h4><pre>x = { a = 5, b = 123 }; dict_size( x ); // returns 2</pre></div> <div class='item'><a name='map-size-function'></a><hr><h2>map_size [function]</h2><h3>map_size( dict )</h3><h4>return the number of entries in the map object</h4><pre>x = map( 5, &quot;a&quot;, 123, &quot;b&quot; ); map_size( x ); // returns 2</pre></div> <div class='item'><a name='isset-function'></a><hr><h2>isset [function]</h2><h3>isset( var, key )</h3><h4>returns whether a property <code>key</code> is readable (exists) in variable <code>var</code></h4><pre>x = { a = 5 }; isset( x, &quot;a&quot; ); // returns &#39;true&#39; isset( x, &quot;b&quot; ); // returns &#39;false&#39; isset( print, &quot;call&quot; ); // returns &#39;true&#39; -- works with built-in special properties too</pre></div> <div class='item'><a name='unset-function'></a><hr><h2>unset [function]</h2><h3>unset( dict|map var, (string) key )</h3><h4>removes an entry named <code>key</code> from the dictionary <code>var</code></h4><ul><li><code>key</code> is only required to be of <code>string</code> type if a <code>dict</code> is passed</li></ul></div> <div class='item'><a name='clone-function'></a><hr><h2>clone [function]</h2><h3>clone( var )</h3><h4>creates a one-reference copy of the variable <code>var</code> or returns null and emits a warning on failure</h4><ul><li>variables that are passed by value (null, bool, int, real, cfunc) or strings/functions are returned as-is, since for value types all copies are same and strings/functions are immutable</li></ul><pre>x = { a = 5 }; y = clone( x ); z = x; x.a = 6; print( y.a ); // prints &quot;5&quot; print( z.a ); // prints &quot;6&quot;</pre></div> <div class='item'><a name='get-keys-function'></a><hr><h2>get_keys [function]</h2><h3>get_keys( iterable var )</h3><h4>returns an array of keys found in the iterable object <code>var</code> or returns null and emits a warning on failure</h4><ul><li><code>var</code> must be an iterable object (has interface OP_CONVERT defined and successfully handles a CONVOP_TOITER request) - such objects are <code>array</code>, <code>dict</code>, <code>map</code> and <code>io_dir</code></li></ul><pre>get_keys( [5,7,0] ); // returns [0,1,2] get_keys( {b=5,a=2} ); // returns [&quot;b&quot;,&quot;a&quot;]</pre></div> <div class='item'><a name='get-values-function'></a><hr><h2>get_values [function]</h2><h3>get_values( iterable var )</h3><h4>returns an array of values found in the iterable object <code>var</code> or returns null and emits a warning on failure</h4><ul><li><code>var</code> must be an iterable object (has interface OP_CONVERT defined and successfully handles a CONVOP_TOITER request) - such objects are <code>array</code>, <code>dict</code>, <code>map</code> and <code>io_dir</code></li></ul><pre>get_values( [5,7,0] ); // returns [5,7,0] get_values( {b=5,a=2} ); // returns [5,2]</pre></div> <div class='item'><a name='get-concat-function'></a><hr><h2>get_concat [function]</h2><h3>get_concat( iterable var, iterable var1, ... )</h3><h4>returns an array of values found in all iterable objects passed to the function or returns null and emits a warning on failure</h4><pre>get_concat( [1,2], {a=&quot;5&quot;,b=8} ); // returns [1,2,&quot;5&quot;,8]</pre></div> <div class='item'><a name='get-merged-function'></a><hr><h2>get_merged [function]</h2><h3>get_merged( iterable var, iterable var1, ... )</h3><h4>returns a dict of all key-value pairs found in all iterable objects passed to the function or returns null and emits a warning on failure</h4><pre>get_merged( [1,2], [3], {a=&quot;4&quot;} ); // return {0=3,1=2,a=&quot;4&quot;}</pre></div> <div class='item'><a name='get-merged-map-function'></a><hr><h2>get_merged_map [function]</h2><h3>get_merged_map( iterable var, iterable var1, ... )</h3><h4>returns a map of all key-value pairs found in all iterable objects passed to the function or returns null and emits a warning on failure</h4><pre>get_merged_map( [1,2], map(5,6), {a=&quot;4&quot;} ); // return {0=3,1=2,int(5)=6,a=&quot;4&quot;}</pre></div> <div class='item'><a name='get-iterator-function'></a><hr><h2>get_iterator [function]</h2><h3>get_iterator( iterable var )</h3><h4>returns an iterator from the passed object, if it has one</h4><ul><li>More info about iterators: <a href="#Iterator-system">Iterator system</a></li></ul><pre>get_iterator( [ 5 ] ); // returns array iterator for the specified array</pre></div> <div class='item'><a name='iter-advance-function'></a><hr><h2>iter_advance [function]</h2><h3>iter_advance( iterator var )</h3><h4>advances an iterator to the next position, returning if there is any more data to read</h4><ul><li>More info about iterators: <a href="#Iterator-system">Iterator system</a></li></ul><pre>it = get_iterator( [ 5 ] ); // retrieves iterator from array [5] iter_advance( it ); // returns true, indicating that the current position is still a valid one</pre></div> <div class='item'><a name='iter-getdata-function'></a><hr><h2>iter_getdata [function]</h2><h3>iter_getdata( iterator var, bool pushkey = false, bool pushvalue = true )</h3><h4>returns key/value data from iterator</h4><ul><li>if key is requested, it is returned first </li><li>if neither key not value are requested, <code>null</code> is returned and a warning is emitted</li></ul><ul><li>More info about iterators: <a href="#Iterator-system">Iterator system</a></li></ul><pre>it = get_iterator( [ 5 ] ); // retrieves iterator from array [5] iter_advance( it ); // returns true, indicating that the current position is still a valid one (key,value) = iter_getdata( it, true ); // returns 0, 5 -- key, value</pre></div> <div class='item'><a name='tobool-function'></a><hr><h2>tobool [function]</h2><h3>tobool( var )</h3><h4>returns a boolean, generated from variable <code>var</code> using the <a href="#Conversion-rules">Conversion rules</a></h4><ul><li>this function is equivalent to <a href="#sgs-Get-functions">sgs_GetBool</a> / <a href="#sgs-To-functions">sgs_ToBool</a> in the C API</li></ul><pre>tobool( 5 ); // returns &#39;true&#39; tobool( &quot;&quot; ); // returns &#39;false&#39;</pre></div> <div class='item'><a name='toint-function'></a><hr><h2>toint [function]</h2><h3>toint( var )</h3><h4>returns an integer, generated from variable <code>var</code> using the <a href="#Conversion-rules">Conversion rules</a></h4><ul><li>this function is equivalent to <a href="#sgs-Get-functions">sgs_GetInt</a> / <a href="#sgs-To-functions">sgs_ToInt</a> in the C API</li></ul><pre>toint( 5.4 ); // returns 5 toint( &quot;0xff&quot; ); // returns 255</pre></div> <div class='item'><a name='toreal-function'></a><hr><h2>toreal [function]</h2><h3>toreal( var )</h3><h4>returns a real value, generated from variable <code>var</code> using the <a href="#Conversion-rules">Conversion rules</a></h4><ul><li>this function is equivalent to <a href="#sgs-Get-functions">sgs_GetReal</a> / <a href="#sgs-To-functions">sgs_ToReal</a> in the C API</li></ul><pre>toreal( 5 ); // returns 5.0 toreal( &quot;3e+2&quot; ); // returns 300.0 toreal( &quot;0xff&quot; ); // returns 255.0</pre></div> <div class='item'><a name='tostring-function'></a><hr><h2>tostring [function]</h2><h3>tostring( var )</h3><h4>returns a string value, generated from variable <code>var</code> using the <a href="#Conversion-rules">Conversion rules</a></h4><ul><li>this function is equivalent to <a href="#sgs-To-functions">sgs_ToString</a> in the C API</li></ul><pre>tostring( 5 ); // returns &quot;5&quot; tostring( { &quot;a&quot; = &quot;b&quot; } ); // returns &quot;{a=b}&quot;</pre></div> <div class='item'><a name='toptr-function'></a><hr><h2>toptr [function]</h2><h3>toptr( var )</h3><h4>returns a pointer value, generated from variable <code>var</code> using the <a href="#Conversion-rules">Conversion rules</a></h4><ul><li>this function is equivalent to <a href="#sgs-Get-functions">sgs_GetPtr</a> / <a href="#sgs-To-functions">sgs_ToPtr</a> in the C API</li></ul><pre>toptr( 5 ); // returns 5 toptr( &quot;3e+2&quot; ); // returns address of the string toptr( [] ); // returns address of array data</pre></div> <div class='item'><a name='parseint-function'></a><hr><h2>parseint [function]</h2><h3>parseint( var )</h3><h4>returns an integer, generated from variable <code>var</code> using the <a href="#Conversion-rules">Conversion rules</a> or returns <code>null</code> on failure</h4><ul><li>this function is equivalent to <a href="#sgs-Parse-functions">sgs_ParseInt</a> in the C API</li></ul><pre>parseint( 5.4 ); // returns 5 parseint( &quot;0xff&quot; ); // returns 255 parseint( parseint ); // returns null</pre></div> <div class='item'><a name='parsereal-function'></a><hr><h2>parsereal [function]</h2><h3>parsereal( var )</h3><h4>returns a real value, generated from variable <code>var</code> using the <a href="#Conversion-rules">Conversion rules</a> or returns <code>null</code> on failure</h4><ul><li>this function is equivalent to <a href="#sgs-Parse-functions">sgs_ParseReal</a> in the C API</li></ul><pre>parsereal( 5 ); // returns 5.0 parsereal( &quot;3e+2&quot; ); // returns 300.0 parsereal( &quot;0xff&quot; ); // returns 255.0 parsereal( parsereal ); // returns null</pre></div> <div class='item'><a name='typeof-function'></a><hr><h2>typeof [function]</h2><h3>typeof( var )</h3><h4>returns the type name of variable <code>var</code>, as string</h4><ul><li>this function is equivalent to <a href="#sgs-TypeOf-function">sgs_TypeOf</a> in the C API</li></ul><pre>typeof( 5 ); // returns &quot;real&quot; typeof( [] ); // returns &quot;array&quot;</pre></div> <div class='item'><a name='typeid-function'></a><hr><h2>typeid [function]</h2><h3>typeid( var )</h3><h4>returns the first 4 bits of the variable <code>var</code> type flags, as <code>int</code></h4><ul><li>returns one of the values mapped to VT_NULL/VT_BOOL/VT_INT/VT_REAL/VT_STRING/VT_FUNC/VT_CFUNC/VT_OBJECT/VT_PTR </li><li>this function is equivalent to <a href="#sgs-ItemType-function">sgs_ItemType</a> in the C API</li></ul><pre>typeid( 5 ) == VT_INT; // returns &#39;true&#39; typeid( [] ); // returns 7 / VT_OBJECT</pre></div> <div class='item'><a name='typeptr-function'></a><hr><h2>typeptr [function]</h2><h3>typeptr( var )</h3><h4>returns type interface pointer from object variables or null pointer from other variables</h4><pre>typeptr( 5 ); // returns ptr(0) typeptr( [] ); // returns ptr(...), NOT ptr(0)</pre></div> <div class='item'><a name='typeptr-by-name-function'></a><hr><h2>typeptr_by_name [function]</h2><h3>typeptr_by_name( string name )</h3><h4>returns type interface pointer by its name or null pointer if name is not assigned to a pointer</h4><ul><li>equivalent to <a href="#sgs-FindType-function">sgs_FindType</a> in the C API</li></ul><pre>typeptr_by_name( &quot;array&quot; ); // returns ptr(...) typeptr_by_name( &quot;array&quot; ) == typeptr( [] ); // returns &#39;true&#39;</pre></div> <div class='item'><a name='is-numeric-function'></a><hr><h2>is_numeric [function]</h2><h3>is_numeric( var )</h3><h4>returns whether the variable <code>var</code> is numeric - one of bool/int/real or a numeric string</h4><ul><li>all types that can always be converted to numbers are considered numeric, with two exceptions: <ul><li>convertible objects are not numeric since validation requires an interface call and unnecessary interface calls cannot be made </li><li>null value is considered to be the lack of a better value, thus it cannot be considered valid, even though it always maps implicitly to the integer 0</li></ul></li></ul><pre>is_numeric( 12.124 ); // returns true is_numeric( &quot;what&quot; ); // returns false</pre></div> <div class='item'><a name='is-callable-function'></a><hr><h2>is_callable [function]</h2><h3>is_callable( var )</h3><h4>returns whether the variable <code>var</code> is callable - a function (func/cfunc) or an object with OP_CALL defined</h4><ul><li>this function is equivalent to <a href="#sgs-IsCallable-P-functions">sgs_IsCallable</a> in the C API</li></ul><pre>is_callable( print ); // returns &#39;true&#39; is_callable( function(){} ); // returns &#39;true&#39; is_callable( 5 ); // returns &#39;false&#39;</pre></div> <div class='item'><a name='is-array-function'></a><hr><h2>is_array [function]</h2><h3>is_array( var )</h3><h4>returns if variable is an array</h4><pre>is_array( print ); // returns &#39;false&#39; is_array( [] ); // returns &#39;true&#39;</pre></div> <div class='item'><a name='is-dict-function'></a><hr><h2>is_dict [function]</h2><h3>is_dict( var )</h3><h4>returns if variable is a dict</h4><pre>is_dict( 5 ); // returns &#39;false&#39; is_dict( [] ); // returns &#39;false&#39; is_dict( {} ); // returns &#39;true&#39;</pre></div> <div class='item'><a name='is-map-function'></a><hr><h2>is_map [function]</h2><h3>is_map( var )</h3><h4>returns if variable is a map</h4><pre>is_map( &quot;map&quot; ); // returns &#39;false&#39; is_map( {} ); // returns &#39;false&#39; is_map( map() ); // returns &#39;true&#39;</pre></div> <div class='item'><a name='is-iterable-function'></a><hr><h2>is_iterable [function]</h2><h3>is_iterable( var )</h3><h4>returns if variable is iterable</h4><pre>is_iterable( print ); // returns &#39;false&#39; is_iterable( [] ); // returns &#39;true&#39; is_iterable( {} ); // returns &#39;true&#39;</pre></div> <div class='item'><a name='print-println-printlns-errprint-errprintln-errprintlns-functions'></a><hr><h2>print, println, printlns, errprint, errprintln, errprintlns [functions]</h2><h3>print( ... ), println( ... ), printlns( ... ),</h3><h3>errprint( ... ), errprintln( ... ), errprintlns( ... ),</h3><h4>passes all arguments, converted to strings, to the (error) output callback</h4><ul><li>(err)print passes arguments without modifications </li><li>(err)println passes a newline character after all variables </li><li>(err)printlns passes a newline character after each variable</li></ul><pre>print( 5, &quot;x&quot; ); // prints &quot;5x&quot; println( 5, &quot;x&quot; ); // prints &quot;5x\n&quot; printlns( 5, &quot;x&quot; ); // prints &quot;5\nx\n&quot; errprint( 5, &quot;x&quot; ); // prints &quot;5x&quot; to error output stream errprintln( 5, &quot;x&quot; ); // prints &quot;5x\n&quot; to error output stream errprintlns( 5, &quot;x&quot; ); // prints &quot;5\nx\n&quot; to error output stream</pre></div> <div class='item'><a name='printvar-ext-function'></a><hr><h2>printvar_ext [function]</h2><h3>printvar_ext( var, int maxdepth = 5 )</h3><h4>passes a dump of the variable (informative string version) to the output callback, allowing to optionally specify the maximum depth of the dump (how deep it is allowed to look for sub-variables)</h4><pre>printvar_ext( 5 ); // prints &quot;real (5)&quot; printvar_ext( &quot;wat&quot; ); // prints &quot;string [3] &quot;wat&quot;&quot; printvar_ext( [{a=[{}]}], 2 ); /* prints: object (003C5F90) [0] array (1) [ object (003C60A8) [1] dict (1) { ... } ] */</pre></div> <div class='item'><a name='printvar-function'></a><hr><h2>printvar [function]</h2><h3>printvar( var, ... )</h3><h4>same as a list of printvar(var); calls for each argument</h4><ul><li>refer to <a href="#printvar-ext-function">printvar_ext</a> for more info</li></ul></div> <div class='item'><a name='read-stdin-function'></a><hr><h2>read_stdin [function]</h2><h3>read_stdin( bool all = false )</h3><h4>reads from the standard input</h4><ul><li>if <code>all</code> is set to &#39;true&#39;, all standard input is read up to EOF (useful for piped input) </li><li>if <code>all</code> is set to &#39;false&#39; or not set at all, input is read up to (and excluding) the next newline character</li></ul><pre>print &quot;Name: &quot;; name = read_stdin(); // waits for user input process( read_stdin(true) ); // loads all piped input</pre></div> <div class='item'><a name='ftime-function'></a><hr><h2>ftime [function]</h2><h3>ftime()</h3><h4>returns a value that is increased by a total of 1 each second (time), as real</h4><ul><li>guaranteed to offer sub-second precision unless stated otherwise for any specific platform</li></ul><pre>start = ftime(); do_something_big(); println( &quot;That took &quot; $ ftime() - start $ &quot; seconds.&quot; );</pre></div> <div class='item'><a name='rand-function'></a><hr><h2>rand [function]</h2><h3>rand()</h3><h4>returns a random &#39;int&#39; value in the range [0;RAND_MAX] - from 0, inclusive, to RAND_MAX, inclusive</h4></div> <div class='item'><a name='randf-function'></a><hr><h2>randf [function]</h2><h3>randf()</h3><h4>returns a random &#39;real&#39; value in the range [0;1] - from 0, inclusive, to 1, inclusive</h4></div> <div class='item'><a name='srand-function'></a><hr><h2>srand [function]</h2><h3>srand( int seed )</h3><h4>specify a different seed value for the built-in pseudo-random number generator</h4><pre>srand( 5 ); // restart the generator with the value specified srand( ftime() ); // restart the generator depending on the second the code was executed</pre></div> <div class='item'><a name='hash-fnv-function'></a><hr><h2>hash_fnv [function]</h2><h3>hash_fnv( string buf, bool as_hexstring = false )</h3><h4>generate a hash, using the FNV-1a algorithm</h4><ul><li>if <code>as_hexstring</code> is true, an 8 characters long string containing the hexadecimal fixed-length hash value is returned, otherwise the value is returned as integer</li></ul></div> <div class='item'><a name='hash-crc32-function'></a><hr><h2>hash_crc32 [function]</h2><h3>hash_crc32( string buf, bool as_hexstring = false )</h3><h4>generate a hash/checksum, using the CRC32 algorithm</h4><ul><li>if <code>as_hexstring</code> is true, an 8 characters long string containing the hexadecimal fixed-length hash/checksum value is returned, otherwise the value is returned as integer</li></ul></div> <div class='item'><a name='va-get-args-function'></a><hr><h2>va_get_args [function]</h2><h3>va_get_args()</h3><h4>return an array containing all arguments passed to the calling function</h4></div> <div class='item'><a name='va-get-arg-function'></a><hr><h2>va_get_arg [function]</h2><h3>va_get_arg()</h3><h4>returns one of the arguments passed to calling function</h4></div> <div class='item'><a name='va-arg-count-function'></a><hr><h2>va_arg_count [function]</h2><h3>va_arg_count()</h3><h4>return the number of arguments passed to the calling function</h4></div> <div class='item'><a name='sys-call-function'></a><hr><h2>sys_call [function]</h2><h3>sys_call( func, this[, args..] )</h3><h4>calls the specified function with the specified <code>this</code> value and argument list</h4><p> <em class='notice-bgr'>if argument count is only known at runtime, see <a href="#sys-apply-function">sys_apply</a></em> </p><ul><li>C functions, SGS functions, closure objects and real closures have this function under the &quot;call&quot; property</li></ul></div> <div class='item'><a name='sys-apply-function'></a><hr><h2>sys_apply [function]</h2><h3>sys_apply( func, this, args )</h3><h4>calls the specified function with the specified <code>this</code> value and argument array</h4><p> <em class='notice-bgr'>if argument count is known at compile time, prefer <a href="#sys-call-function">sys_call</a> to this function</em> </p><ul><li>C functions, SGS functions, closure objects and real closures have this function under the &quot;apply&quot; property</li></ul></div> <div class='item'><a name='pcall-function'></a><hr><h2>pcall [function]</h2><h3>pcall( callable func[, callable errh ])</h3><h4>calls the callable <code>func</code>, hiding internal errors from the caller or optionally passing them to callable <code>errh</code></h4><ul><li><code>errh</code> error handler is called with two arguments - <code>int error_type, string message</code> - and expected to return 0-1 arguments ([int]) </li><li>error handler must return 0/null/nothing if the error has been successfully processed or the new error type otherwise <ul><li>errors thrown inside the handler will not be caught so any error can be transformed to any other </li><li>an empty function behaves the same way as <code>pcall</code> without function</li></ul></li></ul><pre>include &quot;string&quot;; function handler( type, msg ) { if( string_find( msg, &quot;not found&quot; ) !== null ) sys_msg( type, &quot;nooooooooooo&quot; ); } function handler2( type, msg ) { if( string_find( msg, &quot;not found&quot; ) !== null ) return SGS_ERROR; } pcall(function(){ print x; }); // nothing pcall(function(){ print x; }, handler ); // renamed warning pcall(function(){ print x; }, handler2 ); // changed type to error</pre></div> <div class='item'><a name='assert-function'></a><hr><h2>assert [function]</h2><h3>assert( var condition[, string message] )</h3><h4>if condition evaluates to &#39;false&#39;, emits an error &quot;assertion failed&quot; or if message is defined, &quot;assertion failed: &lt;message&gt;&quot;</h4><pre>assert( text, &quot;text was not defined&quot; );</pre></div> <div class='item'><a name='eval-function'></a><hr><h2>eval [function]</h2><h3>eval( string code )</h3><h4>returns the result of evaluating the passed <code>code</code> string as SGScript code</h4><ul><li>this function is equivalent to <a href="#sgs-EvalBuffer-function">sgs_EvalBuffer</a> / <a href="#sgs-EvalString-function-alias">sgs_EvalString</a> in the C API</li></ul><pre>eval(&quot;print 5;&quot;); // prints 5</pre></div> <div class='item'><a name='eval-file-function'></a><hr><h2>eval_file [function]</h2><h3>eval_file( string filename )</h3><h4>returns the result of evaluating the file pointed to by <code>filename</code> as SGScript code</h4><ul><li>this function is equivalent to <a href="#sgs-EvalFile-function">sgs_EvalFile</a> in the C API</li></ul><pre>eval_file(&quot;myfile.sgs&quot;); // ???</pre></div> <div class='item'><a name='compile-sgs-function'></a><hr><h2>compile_sgs [function]</h2><h3>compile_sgs( string code )</h3><h4>returns the generated bytecode or null + error info</h4><ul><li>this function is equivalent to <a href="#sgs-Compile-function">sgs_Compile</a> in the C API</li></ul><pre>compile_sgs( io_file_read( &quot;myfile.sgs&quot; ) ); // ???</pre></div> <div class='item'><a name='include-library-function'></a><hr><h2>include_library [function]</h2><h3>include_library( string lib[, bool override ] )</h3><h4>loads the global variables of the specific library <code>lib</code> in the state, returns success, as <code>bool</code>, emits a warning on failure</h4><ul><li>lib must be one of &#39;fmt&#39;, &#39;io&#39;, &#39;math&#39;, &#39;os&#39;, &#39;string&#39; </li><li>if <code>override</code> is specified, library will be reloaded even if it was already loaded before </li><li>this function is equivalent to the sgs_LoadLib_* functions in the C API</li></ul><pre>printvar( sin ); // warning, null include_library( &quot;math&quot; ); printvar( sin ); // C function</pre></div> <div class='item'><a name='include-file-function'></a><hr><h2>include_file [function]</h2><h3>include_file( string file[, bool override ] )</h3><h4>executes the file pointed to by <code>file</code>, returns success, as <code>bool</code>, emits a warning on failure</h4><ul><li>this function does NOT check include paths (SGS_PATH) </li><li>if <code>override</code> is specified, file will be reloaded even if it was already loaded before </li><li>this function is equivalent to <a href="#sgs-ExecFile-function-alias">sgs_ExecFile</a> in the C API</li></ul><pre>include_file( &quot;something.sgs&quot; ); // loads something include_file( &quot;something.sgs&quot; ); // does not load it again include_file( &quot;something.sgs&quot;, true ); // loads it again</pre></div> <div class='item'><a name='include-shared-function'></a><hr><h2>include_shared [function]</h2><h3>include_shared( string file[, bool override ] )</h3><h4>runs the shared library pointed to by <code>file</code>, returns success, as <code>bool</code>, emits a warning on failure</h4><ul><li><code>file</code> must be available according to the platform-specific rules of dynamic libraries (shared objects) </li><li>the library must contain a &#39;sgscript_main&#39; function that will be called on initialization </li><li>if <code>override</code> is specified, file will be reloaded even if it was already loaded before</li></ul><pre>include_shared( &quot;sgsjson.dll&quot; ); // load the JSON library DLL on Windows</pre></div> <div class='item'><a name='include-function'></a><hr><h2>include [function]</h2><h3>include( string file[, bool override ] )</h3><h4>tries to load a library or a file according to the include path</h4><ul><li>the order of actions: <ul><li>first, a library load is attempted </li><li>on failure, a file is looked for by every entry of the sys_include_path variable (? - the file replacement symbol, | - file directory replacement symbol, ; - separator) </li><li>if file is not found, everything stops </li><li>if file is found, first - a library load is attempted, on failure - bytecode &amp; source code loading </li></ul><li>this function is also available as a replicating statement &#39;include&#39; (ex. &#39;include &quot;fmt&quot;, &quot;io&quot;;&#39; works the same way as include(&quot;fmt&quot;); include(&quot;io&quot;);)</li></ul></div> <div class='item'><a name='import-cfunc-function'></a><hr><h2>import_cfunc [function]</h2><h3>import_cfunc( string file, string funcname )</h3><h4>retrieves the <code>funcname</code> function of the shared library <code>file</code>, returns success, as <code>bool</code>, emits a warning on failure</h4><p> <em class='notice-bgr'>Do not call &#39;sgscript_main&#39; using this function! That function has different return value semantics so at best, something will work, a warning could be emitted and the worst case is that something will crash.</em> </p><ul><li><code>file</code> must be available according to the platform-specific rules of dynamic libraries (shared objects)</li></ul><pre>import_cfunc( &quot;mydll.dll&quot;, &quot;someSGScriptFunc&quot; )();</pre></div> <div class='item'><a name='sys-curfile-function'></a><hr><h2>sys_curfile [function]</h2><h3>sys_curfile()</h3><h4>returns the path of the file (as passed on load) that contains the currently executed code or <code>null</code> if the file cannot be determined (eval, C functions)</h4><pre>// a.sgs print( sys_curfile() ); // prints &quot;a.sgs&quot; // b.sgs include &quot;a.sgs&quot;;</pre></div> <div class='item'><a name='sys-curfiledir-function'></a><hr><h2>sys_curfiledir [function]</h2><h3>sys_curfiledir()</h3><h4>returns the directory path of the file (as passed on load) that contains the currently executed code or <code>null</code> if the file cannot be determined (eval, C functions)</h4><pre>// ext/a.sgs print( sys_curfiledir() ); // prints &quot;ext&quot; // a.sgs print( sys_curfiledir() ); // prints &quot;.&quot; // b.sgs include &quot;ext/a.sgs&quot;, &quot;a.sgs&quot;;</pre></div> <div class='item'><a name='sys-backtrace-function'></a><hr><h2>sys_backtrace [function]</h2><h3>sys_backtrace( bool as_string = false )</h3><h4>returns the call stack function/line/file list, either as array of dicts, or as a string, formatted exactly like in error messages (via <a href="#sgs-PushErrorInfo-function">sgs_PushErrorInfo)</a></h4><ul><li>in the dict, there are three keys: <ul><li>func (string) </li><li>line (null/int) </li><li>file (string)</li></ul></li></ul><pre>errprint( sys_backtrace( true ) ); // print backtrace to stderr println( sys_backtrace().last.func ); // print name of current function</pre></div> <div class='item'><a name='sys-msg-function'></a><hr><h2>sys_msg [function]</h2><h3>sys_msg( int code, string message )</h3><h4>passes a message to the internal messaging system (one that&#39;s commonly used to report errors and warnings)</h4><p> <em class='notice-bgr'>Different codes can be handled differently by the system. By default, SGS_ERROR code will stop execution and return to C code as soon as possible.</em> </p><ul><li><code>code</code> is the code to use to pass the message (ex. SGS_INFO, SGS_WARNING, SGS_ERROR)</li></ul></div> <div class='item'><a name='INFO-function'></a><hr><h2>INFO [function]</h2><h3>INFO( string message )</h3><h4>passes a message to the internal messaging system</h4><ul><li>the name of this function is written in all caps to avoid shadowing by a common variable name </li><li>works exactly like <code>sys_msg( SGS_INFO, message )</code></li></ul></div> <div class='item'><a name='WARNING-function'></a><hr><h2>WARNING [function]</h2><h3>WARNING( string message )</h3><h4>passes a message to the internal messaging system</h4><ul><li>the name of this function is written in all caps for consistency with the other two </li><li>works exactly like <code>sys_msg( SGS_INFO, message )</code></li></ul></div> <div class='item'><a name='ERROR-function'></a><hr><h2>ERROR [function]</h2><h3>ERROR( string message )</h3><h4>passes a message to the internal messaging system</h4><p> <em class='notice-bgr'>By default, SGS_ERROR code (the one this function uses internally) will stop execution and return to C code as soon as possible.</em> </p><ul><li>the name of this function is written in all caps to avoid shadowing by a common variable name </li><li>works exactly like <code>sys_msg( SGS_INFO, message )</code></li></ul></div> <div class='item'><a name='sys-abort-function'></a><hr><h2>sys_abort [function]</h2><h3>sys_abort()</h3><h4>stops execution and returns to C code as soon as possible</h4><ul><li>this function is equivalent to <a href="#sgs-Abort-function">sgs_Abort</a> in the C API</li></ul><pre>sys_abort(); print( 5 ); // this line is not reached</pre></div> <div class='item'><a name='app-abort-function'></a><hr><h2>app_abort [function]</h2><h3>app_abort()</h3><h4>calls the abort() function of the C standard library (crashes the application)</h4></div> <div class='item'><a name='app-exit-function'></a><hr><h2>app_exit [function]</h2><h3>app_exit( code = 0 )</h3><h4>calls the exit() function of the C standard library (exits the application)</h4></div> <div class='item'><a name='sys-replevel-function'></a><hr><h2>sys_replevel [function]</h2><h3>sys_replevel([ level ])</h3><h4>returns the current reported error level and optionally sets a new one</h4><p> <em class='notice-bgr'>The effects of this function are not reverted automatically at any moment (unless implemented manually with hooks).</em> </p><pre>old_level = sys_replevel( SGS_ERROR ); // report only errors or worse magic = calculate_magic(); // any warnings are never processed at this point sys_replevel( old_level ); // restore the old reported level</pre></div> <div class='item'><a name='sys-stat-function'></a><hr><h2>sys_stat [function]</h2><h3>sys_stat( code )</h3><h4>prints info about virtual machine state, everything is implementation-defined</h4><ul><li>accepted codes are the same as for <a href="#sgs-Stat-function">sgs_Stat</a>, which this function is equivalent to</li></ul><pre>sys_stat( 11 ); // dumps all globals</pre></div> <div class='item'><a name='errno-function'></a><hr><h2>errno [function]</h2><h3>errno( as_string = false )</h3><h4>returns the last relevant error number for the C standard library, as an integer or a string if <code>as_string</code> is set</h4><ul><li>last relevant error number is defined by <a href="#sgs-Errno-function-alias">sgs_Errno</a> / <a href="#sgs-SetErrno-function-alias">sgs_SetErrno</a> C API functions</li></ul><pre>data = io_file_read( &quot;doesnotexist&quot; ); // file that does not exist print errno(); // prints 2 print errno(true); // prints &quot;No such file or directory&quot; on Windows</pre></div> <div class='item'><a name='errno-string-function'></a><hr><h2>errno_string [function]</h2><h3>errno_string( int code )</h3><h4>returns the error string for the given code</h4><ul><li>errno_string(errno()) is equivalent to errno(true)</li></ul><pre>print errno_string(2); // prints &quot;No such file or directory&quot; on Windows</pre></div> <div class='item'><a name='errno-value-function'></a><hr><h2>errno_value [function]</h2><h3>errno_value( string key )</h3><h4>returns the number for the error key (for &quot;ENOENT&quot; it would return 2)</h4><ul><li>this function might be a bit slow considering that it currently does not use any extended lookup systems, such as hash tables</li></ul><pre>data = io_file_read( &quot;doesnotexist&quot; ); if( errno() == error_string(&quot;ENOENT&quot;) ) println( &quot;file does not exist&quot; );</pre></div> <div class='item'><a name='dumpvar-ext-function'></a><hr><h2>dumpvar_ext [function]</h2><h3>dumpvar_ext( var, int depth = 5 )</h3><h4>similar to <a href="#printvar-ext-function">printvar_ext()</a> but returns the dump instead of printing it</h4><ul><li>this function is equivalent to <a href="#sgs-DumpVar-function">sgs_DumpVar</a> in the C API</li></ul><pre>sys_error( SGS_INFO, &quot;Extended variable info:\n&quot; $ dumpvar(data) );</pre></div> <div class='item'><a name='dumpvar-function'></a><hr><h2>dumpvar [function]</h2><h3>dumpvar( ... )</h3><h4>similar to <a href="#printvar-function">printvar()</a> but returns the dumps, concatenated, instead of printing them</h4></div> <div class='item'><a name='gc-collect-function'></a><hr><h2>gc_collect [function]</h2><h3>gc_collect()</h3><h4>runs the garbage collector on the virtual machine, waiting until it has finished</h4><ul><li>returns the reduction in objects or false on failure</li></ul><pre>a = []; a.push(a); // creates a circular dependency a = null; // a is not actually freed gc_collect(); // a is freed now</pre></div> <div class='item'><a name='serialize-function'></a><hr><h2>serialize [function]</h2><h3>serialize( var )</h3><h4>converts the variable to a byte buffer (string), containing the serialized data that can be recreated with <a href="#unserialize-function">unserialize()</a> or returns null and emits a warning on failure</h4><ul><li>C functions and objects without OP_SERIALIZE implemented cannot be serialized</li></ul><pre>data = serialize({ name = &quot;A&quot;, info = &quot;B&quot; }); print data; // prints random-looking, yet deterministic garbage print unserialize(data); // prints {name=A,info=B}</pre></div> <div class='item'><a name='unserialize-function'></a><hr><h2>unserialize [function]</h2><h3>unserialize( string data[, array|dict funcs ])</h3><h4>recreates a variable from the buffer with serialized data or returns null and emits a warning on failure</h4><ul><li>this function will internally call global object creation functions specified in the data, so they must be defined and the state could change in the process </li><li>the list of allowed functions can be optionally specified in the second parameter <ul><li>if array is passed, all functions with the specified names are loaded from global environment </li><li>if dict is passed, it is expected to be a map to be set as the temporary global environment </li></ul><li>for more info on serialization in SGScript, refer to <a href="#Serialization-in-SGScript">Serialization in SGScript</a></li></ul><pre>data = serialize({ name = &quot;A&quot;, info = &quot;B&quot; }); print data; // prints random-looking, yet deterministic garbage print unserialize(data); // prints {name=A,info=B}</pre></div> <div class='item'><a name='SGS-constants'></a><hr><h2>SGS_*** [constants]</h2><h3>SGS_INFO, SGS_WARNING, SGS_ERROR</h3><h4>defined to the values of the C macros, respectively 100, 200 and 300</h4></div> <div class='item'><a name='VT-constants'></a><hr><h2>VT_*** [constants]</h2><h3>VT_NULL, VT_BOOL, VT_INT, VT_REAL, VT_STRING, VT_FUNC, VT_CFUNC, VT_OBJECT, VT_PTR</h3><h4>these constants are defined to the values of the C macros (with the prefix &quot;SGS_VT_&quot; in C) and can be compared with the values returned in <a href="#typeid-function">typeid()</a></h4></div> <div class='item'><a name='RAND-MAX-constant'></a><hr><h2>RAND_MAX [constant]</h2><h3>RAND_MAX</h3><h4>the maximum number that can be returned by <a href="#rand-function">rand()</a></h4></div> <div class='item'><a name='G-superglobal'></a><hr><h2>_G [superglobal]</h2><h3>A hard-coded global value that points to the global dictionary. Can be used to access non-identifier globals and change the global dictionary.</h3><pre>_G[&quot;$diff&quot;] = 5; // no way to access this via usual globals _G = {}; // global value dictionary is changed, previous functions are lost unless stored somewhere</pre></div> <div class='item'><a name='array-object'></a><hr><h2>array [object]</h2><ul><li>methods <ul><li><a href="#array-push-method">push</a> </li><li><a href="#array-pop-method">pop</a> </li><li><a href="#array-shift-method">shift</a> </li><li><a href="#array-unshift-method">unshift</a> </li><li><a href="#array-insert-method">insert</a> </li><li><a href="#array-erase-method">erase</a> </li><li><a href="#array-part-method">part</a> </li><li><a href="#array-clear-method">clear</a> </li><li><a href="#array-reverse-method">reverse</a> </li><li><a href="#array-resize-method">resize</a> </li><li><a href="#array-reserve-method">reserve</a> </li><li><a href="#array-sort-method">sort</a> </li><li><a href="#array-sort-custom-method">sort_custom</a> </li><li><a href="#array-sort-mapped-method">sort_mapped</a> </li><li><a href="#array-find-method">find</a> </li><li><a href="#array-remove-method">remove</a> </li><li><a href="#array-unique-method">unique</a> </li><li><a href="#array-random-method">random</a> </li><li><a href="#array-shuffle-method">shuffle</a> </li></ul><li>read-only properties <ul><li>[int] size </li><li>[int] capacity </li><li>[var] first (valid if array is not empty, otherwise a warning is thrown and &#39;null&#39; is returned) </li><li>[var] last (similar to &#39;first&#39;) </li></ul><li>other features: <ul><li>read/write integer index </li><li>full content dump </li><li>tostring = quick content dump </li><li>tobool = size != 0 </li><li>iterator </li><li>cloning </li><li>serialization </li><li>GC-safe</li></ul></li></ul></div> <div class='item'><a name='array-push-method'></a><hr><h2>array.push [method]</h2><h3>array.push( ... )</h3><h4>appends the variables passed to the end of array in the same order, returns the array for chaining</h4><pre>a = [ 5 ]; a.push( 6, 7 ).push( 8 ); // a = [5,6,7,8]</pre></div> <div class='item'><a name='array-pop-method'></a><hr><h2>array.pop [method]</h2><h3>array.pop()</h3><h4>removes one item from the end of array or emits a warning if there are no items in the array, returns the removed item</h4><pre>a = [ 5 ]; a.pop(); // array is empty now a.pop(); // warning: &quot;array is empty, cannot pop&quot;</pre></div> <div class='item'><a name='array-shift-method'></a><hr><h2>array.shift [method]</h2><h3>array.shift()</h3><h4>removes one item from the beginning of array or emits a warning if there are no items in the array, returns the removed item</h4><pre>a = [ 5, 6 ]; a.shift(); // a = [6], returned 5</pre></div> <div class='item'><a name='array-unshift-method'></a><hr><h2>array.unshift [method]</h2><h3>array.unshift( ... )</h3><h4>prepends the variables passed to the beginning of array in the same order, returns the array for chaining</h4><pre>a = [ 5 ]; a.unshift( 6, 7 ); // a = [6,7,5] now</pre></div> <div class='item'><a name='array-insert-method'></a><hr><h2>array.insert [method]</h2><h3>array.insert( int pos, ... )</h3><h4>inserts the variables passed (all arguments after first) to the position specified in the array or emits a warning on failure (index out of bounds), returns the array for chaining</h4><ul><li><code>pos</code> accepts both positive and negative values, the meaning is &quot;which value to insert before&quot; <ul><li>negative values are converted to positive ones by adding (&lt;size&gt; + 1) to them </li><li>beginning of array can be inserted to using position 0 or (- &lt;size&gt; - 1) </li><li>end of array can be inserted to using position &lt;size&gt; or -1</li></ul></li></ul><pre>a = [ 5, 7 ]; a.insert( 1, 6 ); // inserts 6 at position 1 (before item with index 1) a.insert( -1, 8 ); // appends to the end of array, a = [5,6,7,8] now</pre></div> <div class='item'><a name='array-erase-method'></a><hr><h2>array.erase [method]</h2><h3>array.erase( int[, int] )</h3><h4>erases item or a range of items from the array, depending on the arguments passed or emits a warning on failure, returns the array for chaining</h4><ul><li>both arguments have same index processing rules as <a href="#array-object">array</a>.insert(), but with one difference - if both arguments are passed, after resolving (converting negative indices to positive ones, if there are any), first must be smaller than second</li></ul><pre>a = [ 5, 6, 7, 8 ]; a.erase( 1, 2 ); // erases all items between position 1 and 2, including; gives a = [5,8] a.erase( 0 ); // a = [8]</pre></div> <div class='item'><a name='array-part-method'></a><hr><h2>array.part [method]</h2><h3>array.part( int from[, int max ] )</h3><h4>returns a new array starting from index <code>from</code>, with the max. size <code>max</code></h4><ul><li>if <code>from</code> is negative, it is subtracted from the end of array </li><li><code>max</code> cannot be negative, everything else is allowed</li></ul><pre>a = [ 5, 6, 7, 8 ]; a.part( 1, 2 ); // returns [6,7] a.part( -5, 2 ); // returns [5] a.part( 3 ); // returns [8]</pre></div> <div class='item'><a name='array-clear-method'></a><hr><h2>array.clear [method]</h2><h3>array.clear()</h3><h4>erases all items from the array, returns the array for chaining</h4><pre>a = [ 1, &quot;asd&quot;, 8 ]; a.clear(); // a = []</pre></div> <div class='item'><a name='array-reverse-method'></a><hr><h2>array.reverse [method]</h2><h3>array.reverse()</h3><h4>reverses the order of items in the original array, returns the original array for chaining</h4><pre>a = [ 1, 2, 3 ]; b = a; a.reverse(); // a = [3,2,1] print( b ); // prints [3,2,1]</pre></div> <div class='item'><a name='array-resize-method'></a><hr><h2>array.resize [method]</h2><h3>array.resize( int size )</h3><h4>changes the size of the array, returns the array for chaining</h4><ul><li><code>size</code> must be larger than or equal to 0 </li><li>if previous size was less than passed to the method, null variables are appended </li><li>if previous size was more than passed to the method, items are popped from the end of the array </li><li>if size was not changed, nothing else will change</li></ul><pre>a = [ 5, 6, 7 ]; a.resize( 5 ); // a = [5,6,7,null,null] a.resize( 2 ); // a = [5,6]</pre></div> <div class='item'><a name='array-reserve-method'></a><hr><h2>array.reserve [method]</h2><h3>array.reserve( int capacity )</h3><h4>reserves the space for the requested number of elements in the array, returns the array for chaining</h4><ul><li><code>capacity</code> must be larger than or equal to 0 </li><li>if previous capacity was less than passed to the method, capacity will be increased to the requested amount </li><li>if previous capacity was more than or equal to what was passed to the method, nothing will change</li></ul><pre>a = [ 5, 6, 7 ]; a.capacity( 1 ); // nothing happens a.capacity( 5 ); // a.capacity = 5 and two variable additions can now happen without reallocations</pre></div> <div class='item'><a name='array-sort-method'></a><hr><h2>array.sort [method]</h2><h3>array.sort([ bool reverse ])</h3><h4>sorts the array using the <a href="#sgs-Compare-function">sgs_Compare</a> C API function for comparisons, returns the array for chaining</h4><ul><li>if <code>reverse</code> is true, array is sorted in the reverse order</li></ul><pre>a = [ 6, 8, 7, 5 ]; a.sort(); // a = [5,6,7,8]</pre></div> <div class='item'><a name='array-sort-custom-method'></a><hr><h2>array.sort_custom [method]</h2><h3>array.sort_custom( callable[, bool reverse ] )</h3><h4>sorts the array using the callable for comparisons, returns the array for chaining</h4><p> <em class='notice-bgr'>This function is considerably slower than <a href="#array-object">array</a>.sort or <a href="#array-object">array</a>.sort_mapped so prefer those if performance matters.</em> </p><ul><li>callable must return a number, specifying the relative order of the two passed arguments: less than 0 if first variable should be placed before second, greater than 0 if first variable should be placed after second, or 0 if it doesn&#39;t matter </li><li>if <code>reverse</code> is true, array is sorted in the reverse order</li></ul><pre>a = [ 6, 8, 7, 5 ]; // this code will sort numbers into odd/even ones and in ascending order a.sort_custom( function(a,b){return a-b+(b%2-a%2)*1000; } ); // a = [5,7,6,8]</pre></div> <div class='item'><a name='array-sort-mapped-method'></a><hr><h2>array.sort_mapped [method]</h2><h3>array.sort_mapped( array map[, bool reverse ] );</h3><h4>sorts the array by sorting the passed array and applying the index map to the first one, returns the array for chaining</h4><ul><li>both arrays must have the same size, otherwise a warning is emitted </li><li>all variables in the mapping array are interpreted as &#39;real&#39; values </li><li>if <code>reverse</code> is true, array is sorted in the reverse order</li></ul><pre>a = [ 5, 6, 7, 8 ]; b = [ 3, 1, 4, 2 ]; a.sort_mapped( b ); // a = [6,8,5,7]</pre></div> <div class='item'><a name='array-find-method'></a><hr><h2>array.find [method]</h2><h3>array.find( var item[, bool strict[, int from ]] )</h3><h4>attempts to find <code>item</code> in array, starting from 0 or the index passed with <code>from</code>, if it exists, using basic or strict equality comparisons (depending on <code>strict</code>), returning the index or &#39;null&#39; if item was not found</h4><ul><li>if strict comparisons are enabled, variable types are also checked for equality</li></ul><pre>a = [ 5, 6, 7, 8 ]; a.find( &quot;7&quot; ); // returns 2 a.find( &quot;7&quot;, true ); // returns null</pre></div> <div class='item'><a name='array-remove-method'></a><hr><h2>array.remove [method]</h2><h3>array.remove( var item[, bool strict[, bool all[, int from ]]] )</h3><h4>attepts to find and remove first or all <code>item</code> variables in array (depending on <code>all</code>), according to the rules specified in <a href="#array-object">array</a>.find(), returning the number of removed items</h4><pre>a = [ 5, 2, 6, 7, 8, 2 ]; a.remove( &quot;7&quot; ); // returns 1; a = [5,2,6,8,2] a.remove( &quot;6&quot;, true ); // returns 0; a remains unchanged a.remove( 2, false, true ); // returns 2; a = [5,6,8]</pre></div> <div class='item'><a name='array-unique-method'></a><hr><h2>array.unique [method]</h2><h3>array.unique( bool strconv = false )</h3><h4>returns an array without duplicates, where a duplicate is a strictly equal variable or a string conversion match</h4><ul><li>if <code>strconv</code> is true, items are converted to strings before comparison</li></ul><pre>a = [ 5, 3, 2, 3, 2, &quot;3&quot; ]; a.unique(); // returns [5,3,2,&quot;3&quot;] a.unique( true ); // returns [5,3,2]</pre></div> <div class='item'><a name='array-random-method'></a><hr><h2>array.random [method]</h2><h3>array.random( int num )</h3><h4>return <code>num</code> randomly chosen items from the array</h4><ul><li>to retrieve a part of the array in random order without duplicates, <a href="#array-object">array</a>.shuffle can be used </li><li>items after RAND_MAX will currently not be returned</li></ul></div> <div class='item'><a name='array-shuffle-method'></a><hr><h2>array.shuffle [method]</h2><h3>array.shuffle()</h3><h4>change the order of items in the array</h4></div> <div class='item'><a name='dict-object'></a><hr><h2>dict [object]</h2><ul><li>features: <ul><li>read/write string index </li><li>read/write string properties and integer index-via-property </li><li>full content dump </li><li>tostring = quick content dump </li><li>tobool = size != 0 </li><li>iterator </li><li>cloning </li><li>serialization </li><li>GC-safe </li><li>type identification (returns the string &quot;dict&quot;)</li></ul></li></ul></div> <div class='item'><a name='map-object'></a><hr><h2>map [object]</h2><ul><li>features: <ul><li>read/write index </li><li>read/write properties </li><li>full content dump </li><li>tostring = quick content dump </li><li>tobool = size != 0 </li><li>iterator </li><li>cloning </li><li>serialization </li><li>GC-safe </li><li>type identification (returns the string &quot;map&quot;)</li></ul></li></ul></div> <div class='item'><a name='class-object'></a><hr><h2>class [object]</h2><ul><li>read/write properties <ul><li>[var] _super </li></ul><li>other features <ul><li>read/write pass-through index </li><li>read/write pass-through properties (except string &quot;_super&quot;) </li><li>full content dump </li><li>tobool = ENOTSUP, overridable via &quot;__tobool&quot; </li><li>toint = ENOTSUP, overridable via &quot;__toint&quot; </li><li>toreal = ENOTSUP, overridable via &quot;__toreal&quot; </li><li>tostring = &quot;class&quot;, overridable via &quot;__tostring&quot; </li><li>cloning, overridable via &quot;__clone&quot; </li><li>type identification (returns the string &quot;class&quot;, overridable via &quot;__typeof&quot;) </li><li>overridable arithmetic/comparison operations </li><li>overridable object call </li><li>serialization </li><li>GC-safe</li></ul></li></ul></div> <div class='item'><a name='ALL-SGScript-core-functions-A-Z'></a><hr><h2>ALL SGScript core functions (A-Z)</h2><ul><li><a href="#ERROR-function">ERROR [function]</a> </li><li><a href="#INFO-function">INFO [function]</a> </li><li><a href="#WARNING-function">WARNING [function]</a> </li><li><a href="#app-abort-function">app_abort [function]</a> </li><li><a href="#app-exit-function">app_exit [function]</a> </li><li><a href="#array-function">array [function]</a> </li><li><a href="#array-filter-function">array_filter [function]</a> </li><li><a href="#array-process-function">array_process [function]</a> </li><li><a href="#assert-function">assert [function]</a> </li><li><a href="#class-function">class [function]</a> </li><li><a href="#clone-function">clone [function]</a> </li><li><a href="#compile-sgs-function">compile_sgs [function]</a> </li><li><a href="#dict-function">dict [function]</a> </li><li><a href="#dict-filter-function">dict_filter [function]</a> </li><li><a href="#dict-process-function">dict_process [function]</a> </li><li><a href="#dict-size-function">dict_size [function]</a> </li><li><a href="#dumpvar-function">dumpvar [function]</a> </li><li><a href="#dumpvar-ext-function">dumpvar_ext [function]</a> </li><li><a href="#errno-function">errno [function]</a> </li><li><a href="#errno-string-function">errno_string [function]</a> </li><li><a href="#errno-value-function">errno_value [function]</a> </li><li><a href="#eval-function">eval [function]</a> </li><li><a href="#eval-file-function">eval_file [function]</a> </li><li><a href="#ftime-function">ftime [function]</a> </li><li><a href="#gc-collect-function">gc_collect [function]</a> </li><li><a href="#get-concat-function">get_concat [function]</a> </li><li><a href="#get-iterator-function">get_iterator [function]</a> </li><li><a href="#get-keys-function">get_keys [function]</a> </li><li><a href="#get-merged-function">get_merged [function]</a> </li><li><a href="#get-merged-map-function">get_merged_map [function]</a> </li><li><a href="#get-values-function">get_values [function]</a> </li><li><a href="#hash-crc32-function">hash_crc32 [function]</a> </li><li><a href="#hash-fnv-function">hash_fnv [function]</a> </li><li><a href="#import-cfunc-function">import_cfunc [function]</a> </li><li><a href="#include-function">include [function]</a> </li><li><a href="#include-file-function">include_file [function]</a> </li><li><a href="#include-library-function">include_library [function]</a> </li><li><a href="#include-shared-function">include_shared [function]</a> </li><li><a href="#is-array-function">is_array [function]</a> </li><li><a href="#is-callable-function">is_callable [function]</a> </li><li><a href="#is-dict-function">is_dict [function]</a> </li><li><a href="#is-iterable-function">is_iterable [function]</a> </li><li><a href="#is-map-function">is_map [function]</a> </li><li><a href="#is-numeric-function">is_numeric [function]</a> </li><li><a href="#isset-function">isset [function]</a> </li><li><a href="#iter-advance-function">iter_advance [function]</a> </li><li><a href="#iter-getdata-function">iter_getdata [function]</a> </li><li><a href="#map-function">map [function]</a> </li><li><a href="#map-size-function">map_size [function]</a> </li><li><a href="#parseint-function">parseint [function]</a> </li><li><a href="#parsereal-function">parsereal [function]</a> </li><li><a href="#pcall-function">pcall [function]</a> </li><li><a href="#print-println-printlns-errprint-errprintln-errprintlns-functions">print, println, printlns, errprint, errprintln, errprintlns [functions]</a> </li><li><a href="#printvar-function">printvar [function]</a> </li><li><a href="#printvar-ext-function">printvar_ext [function]</a> </li><li><a href="#rand-function">rand [function]</a> </li><li><a href="#randf-function">randf [function]</a> </li><li><a href="#read-stdin-function">read_stdin [function]</a> </li><li><a href="#serialize-function">serialize [function]</a> </li><li><a href="#srand-function">srand [function]</a> </li><li><a href="#sys-abort-function">sys_abort [function]</a> </li><li><a href="#sys-apply-function">sys_apply [function]</a> </li><li><a href="#sys-backtrace-function">sys_backtrace [function]</a> </li><li><a href="#sys-call-function">sys_call [function]</a> </li><li><a href="#sys-curfile-function">sys_curfile [function]</a> </li><li><a href="#sys-curfiledir-function">sys_curfiledir [function]</a> </li><li><a href="#sys-msg-function">sys_msg [function]</a> </li><li><a href="#sys-replevel-function">sys_replevel [function]</a> </li><li><a href="#sys-stat-function">sys_stat [function]</a> </li><li><a href="#tobool-function">tobool [function]</a> </li><li><a href="#toint-function">toint [function]</a> </li><li><a href="#toptr-function">toptr [function]</a> </li><li><a href="#toreal-function">toreal [function]</a> </li><li><a href="#tostring-function">tostring [function]</a> </li><li><a href="#typeid-function">typeid [function]</a> </li><li><a href="#typeof-function">typeof [function]</a> </li><li><a href="#typeptr-function">typeptr [function]</a> </li><li><a href="#typeptr-by-name-function">typeptr_by_name [function]</a> </li><li><a href="#unserialize-function">unserialize [function]</a> </li><li><a href="#unset-function">unset [function]</a> </li><li><a href="#va-arg-count-function">va_arg_count [function]</a> </li><li><a href="#va-get-arg-function">va_get_arg [function]</a> </li><li><a href="#va-get-args-function">va_get_args [function]</a></li></ul></div> <div class='item'><a name='Formatting-library-fmt'></a><hr><h2>Formatting library (&quot;fmt&quot;)</h2><p> This library includes functions and objects for parsing binary and text buffers. </p><ul><li>binary format -- <a href="#fmt-pack-function">fmt_pack</a>, <a href="#fmt-unpack-function">fmt_unpack</a>, <a href="#fmt-pack-count-function">fmt_pack_count</a>, <a href="#fmt-pack-size-function">fmt_pack_size</a> </li><li>base64 format -- <a href="#fmt-base64-encode-function">fmt_base64_encode</a>, <a href="#fmt-base64-decode-function">fmt_base64_decode</a> </li><li>text format -- <a href="#fmt-parser-object">fmt_parser</a>, <a href="#fmt-text-function">fmt_text</a>, <a href="#fmt-charcc-function">fmt_charcc</a></li></ul><h4>Functions:</h4><ul><li><a href="#fmt-pack-function">fmt_pack</a> - pack variables into a byte buffer, according to the format string </li><li><a href="#fmt-unpack-function">fmt_unpack</a> - unpack byte buffer to an array of variables, according to the format string </li><li><a href="#fmt-pack-count-function">fmt_pack_count</a> - returns the number of items found in a packing format string </li><li><a href="#fmt-pack-size-function">fmt_pack_size</a> - returns the number of bytes found in a packing format string </li><li><a href="#fmt-base64-encode-function">fmt_base64_encode</a> - encodes a byte buffer in base64 character buffer (A-Za-z0-9+/) </li><li><a href="#fmt-base64-decode-function">fmt_base64_decode</a> - decodes a base64 character buffer (A-Za-z0-9+/) to a byte buffer </li><li><a href="#fmt-text-function">fmt_text</a> - formats specified variables according to the format string </li><li><a href="#fmt-parser-object">fmt_parser</a> - creates a text parser object with the specified stream reading function </li><li><a href="#fmt-string-parser-function">fmt_string_parser</a> - creates a text parser object that reads from the specified string </li><li><a href="#fmt-file-parser-function">fmt_file_parser</a> - creates a text parser object that reads from the specified file </li><li><a href="#fmt-charcc-function">fmt_charcc</a> - checks if a character is in the character class</li></ul><h4>Objects and their methods:</h4><ul><li><a href="#fmt-parser-object">fmt_parser</a> - formatted text string-parsing object <ul><li><a href="#fmt-parser-read-method">read</a> - read the specified number of characters from the stream </li><li><a href="#fmt-parser-getchar-method">getchar</a> - read one character from the stream </li><li><a href="#fmt-parser-readcc-method">readcc</a> - read characters while they match the specified class </li><li><a href="#fmt-parser-skipcc-method">skipcc</a> - skip characters while they match the specified class </li><li><a href="#fmt-parser-read-real-method">read_real</a> - read with the real value character class, optionally return real </li><li><a href="#fmt-parser-read-int-method">read_int</a> - read with the integer value character class, optionally return integer </li><li><a href="#fmt-parser-read-binary-int-method">read_binary_int</a> - read with the binary integer character class, optionally -return integer </li><li><a href="#fmt-parser-read-octal-int-method">read_octal_int</a> - read with the octal integer character class, optionally return -integer </li><li><a href="#fmt-parser-read-decimal-int-method">read_decimal_int</a> - read with the decimal integer character class, optionally -return integer </li><li><a href="#fmt-parser-read-hex-int-method">read_hex_int</a> - read with the hexadecimal integer character class, optionally return -integer </li><li><a href="#fmt-parser-check-method">check</a> - check for presence of a string in stream</li></ul></li></ul></div> <div class='item'><a name='fmt-pack-function'></a><hr><h2>fmt_pack [function]</h2><h3>fmt_pack( string fmt, ... )</h3><h4>packs the given arguments using the format <code>fmt</code> and returns the byte buffer or returns null and emits a warning on failure</h4><ul><li>the format: character command list <ul><li>0-9: add a digit to multiplier </li><li>=/&lt;/&gt;/@: &quot;=&quot; sets host byte order, &quot;&lt;&quot; - little endian byte order, &quot;&gt;&quot; - big endian, &quot;@&quot; - inverted </li><li>+/-: &quot;+&quot; - unsigned integers, &quot;-&quot; - signed integers </li><li>c/w/l/q/p: integers (c - char, 1 byte, w - word, 2 bytes, l - long, 4 bytes, q - quad-word, 8 bytes, p - pointer/size, platform-specific size of 4/8 bytes, usually) </li><li>f/d: floating-point numbers: &quot;f&quot; - single precision, &quot;d&quot; - double precision </li><li>s: string, multiplier sets length instead of count, as with other items </li><li>x: padding byte (does not get read or written, can be used to advance the pointer) </li><li>space/tab/CR/LF: invisible to the parser </li><li>everything else resets multiplier, does nothing </li></ul><li>sign modifiers do nothing in fmt_pack, refer to <a href="#fmt-unpack-function">fmt_unpack()</a> for their usage info</li></ul><pre>printvar( fmt_pack( &quot;3cf&quot;, 0, 1, 2, 3 ) ); // prints &#39;string [7] &quot;\x00\x01\x02\x00\x00@@&quot;&#39;</pre></div> <div class='item'><a name='fmt-unpack-function'></a><hr><h2>fmt_unpack [function]</h2><h3>fmt_unpack( string fmt, string data )</h3><h4>unpacks the byte buffer <code>data</code> using the format <code>fmt</code>, returns unpacked items (possibly in an array)</h4><ul><li>if &#39;#&#39; can be found in the format string, all data is returned in, otherwise </li><li>unpacks c/w/l/q/p to integers, f/d to floats, s to strings </li><li>if signed numbers are expected (as set by the &quot;-&quot; modifier), the sign bit of the expected type is extended to the end of the native integer type, this makes the loaded integer signed </li><li>refer to <a href="#fmt-pack-function">fmt_pack()</a> for more info about the format</li></ul><pre>print fmt_unpack( &quot;3ld&quot;, fmt_pack( &quot;3ld&quot;, 0, 1, 2, 3 ) ); // prints [0,1,2,3]</pre></div> <div class='item'><a name='fmt-pack-count-function'></a><hr><h2>fmt_pack_count [function]</h2><h3>fmt_pack_count( string fmt )</h3><h4>calculates the number of items to be expected in an unpacked array / required to make a successful fmt_pack call</h4><ul><li>refer to <a href="#fmt-pack-function">fmt_pack()</a> for more info about the format</li></ul><pre>print fmt_pack_count( &quot;3ld&quot; ); // prints 4</pre></div> <div class='item'><a name='fmt-pack-size-function'></a><hr><h2>fmt_pack_size [function]</h2><h3>fmt_pack_size( string fmt )</h3><h4>calculates the number of bytes generated by a successful fmt_pack call / required to successfully unpack data using the given format</h4><ul><li>refer to <a href="#fmt-pack-function">fmt_pack()</a> for more info about the format</li></ul><pre>print fmt_pack_size( &quot;3ld&quot; ); // prints 20</pre></div> <div class='item'><a name='fmt-base64-encode-function'></a><hr><h2>fmt_base64_encode [function]</h2><h3>fmt_base64_encode( string data )</h3><h4>encodes data to produce base64 text data</h4><ul><li>encoding is done using the following table (shortened): &quot;A-Za-z0-9+/&quot;</li></ul><pre>print fmt_base64_encode( &quot;hello world&quot; ); // prints &quot;aGVsbG8gd29ybGQ=&quot;</pre></div> <div class='item'><a name='fmt-base64-decode-function'></a><hr><h2>fmt_base64_decode [function]</h2><h3>fmt_base64_decode( string b64text )</h3><h4>decodes base64 text data</h4><ul><li>decoding is done using the table mentioned in <a href="#fmt-base64-encode-function">fmt_base64_encode()</a></li></ul><pre>fmt_base64_decode( fmt_base64_encode( &quot;hello world&quot; ) ) == &quot;hello world&quot; // returns true</pre></div> <div class='item'><a name='fmt-text-function'></a><hr><h2>fmt_text [function]</h2><h3>fmt_text( [int prealloc,] string text, ... )</h3><h4>parses all format specifiers in <code>text</code> and returns the result</h4><p> <em class='notice-bgr'>see <a href="#string-format-function">string_format</a> if you need position (argument index) specifications in the format string</em> </p><ul><li><code>prealloc</code> specifies number of bytes to be preallocated on the buffer to avoid continuous reallocations during string generation </li><li>the general format of a format specifier is as follows: {fmt[size][.prec][r][p&lt;char&gt;]} <ul><li>fmt: one-character output type (b-binary, o-octal, d-decimal, x/X-hexadecimal, f-floating-point, g/G-compact floating-point, e/E-scientific floating-point, s-valid string, c-always converted to string) </li><li>size: minimum number of characters to print </li><li>prec: precision of floating-point variables, string length limit </li><li>r: add &quot;r&quot; to right-pad (left-justify) </li><li>p&lt;char&gt;: add &quot;p&quot; and any character to set that character as the padding character (default: space/0x20) </li></ul><li>if anything unexpected happens, this function will emit a warning and put &quot;#error#&quot; in the place of a format specifier</li></ul><pre>print fmt_text( &quot;{d} -&gt; {x}&quot;, 1337, 1337 ); // prints &quot;1337 -&gt; 539&quot; print fmt_text( &quot;null: {d}, {s}, {c}&quot;, null, null, null ); // prints &quot;null: #error#, #error#, null&quot; and emits two warnings for item 1 and item 2 print fmt_text( &quot;pi: {f10.10r} {g10r} {E10r}&quot;, M_PI, M_PI, M_PI ); // &quot;pi: 3.1415926536 3.14159 3.141593E+000&quot;</pre></div> <div class='item'><a name='fmt-parser-function'></a><hr><h2>fmt_parser [function]</h2><h3>fmt_parser( callable[, buffersize ] )</h3><h4>creates a <a href="#fmt-parser-object">fmt_parser</a> object, connected to the callable</h4><ul><li>the callable is a function that returns at most the number of bytes requested from the stream <ul><li>if previous request reached end, subsequent requests must return &#39;null&#39;</li></ul></li></ul><pre>f = io_file( &quot;test.txt&quot;, FILE_READ ); // usually it is easier to use @fmt_file_parser instead of the next line of code p = fmt_parser( function( num ) use( file ){ if( file.eof() ) return null; return file.read( num ); } );</pre></div> <div class='item'><a name='fmt-string-parser-function'></a><hr><h2>fmt_string_parser [function]</h2><h3>fmt_string_parser( string, offset = 0[, buffersize ] )</h3><h4>creates a <a href="#fmt-parser-object">fmt_parser</a> object, connected to a string reader object, initialized to the given offset and buffer size</h4><pre>p = fmt_string_parser( &quot;this is a test&quot; ); p.readcc( &quot;a-z&quot; ); // returns &quot;this&quot;</pre></div> <div class='item'><a name='fmt-file-parser-function'></a><hr><h2>fmt_file_parser [function]</h2><h3>fmt_file_parser( file[, buffersize ] )</h3><h4>creates a <a href="#fmt-parser-object">fmt_parser</a> object, connected to a file reader object, initialized to the given buffer size</h4><pre>p = fmt_file_parser( io_file( &quot;something.txt&quot;, FILE_READ ) ); p.readcc( &quot;a-z&quot; ); // returns something</pre></div> <div class='item'><a name='fmt-charcc-function'></a><hr><h2>fmt_charcc [function]</h2><h3>fmt_charcc( string char, string class )</h3><h4>checks if the first character of string <code>char</code> is included in the character class <code>class</code></h4><ul><li>character class is a regex-like list of specific symbols and ranges (its low and high symbols separated by &quot;-&quot;), optionally prepended by &quot;^&quot; that inverts the scope of the class</li></ul><pre>fmt_charcc( &quot;.&quot;, &quot;a-zA-Z0-9&quot; ); // returns false fmt_charcc( &quot;x&quot;, &quot;a-zA-Z0-9&quot; ); // returns true</pre></div> <div class='item'><a name='fmt-parser-object'></a><hr><h2>fmt_parser [object]</h2><ul><li>methods <ul><li><a href="#fmt-parser-read-method">read</a> </li><li><a href="#fmt-parser-getchar-method">getchar</a> </li><li><a href="#fmt-parser-readcc-method">readcc</a> </li><li><a href="#fmt-parser-skipcc-method">skipcc</a> </li><li><a href="#fmt-parser-read-real-method">read_real</a> </li><li><a href="#fmt-parser-read-int-method">read_int</a> </li><li><a href="#fmt-parser-read-binary-int-method">read_binary_int</a> </li><li><a href="#fmt-parser-read-octal-int-method">read_octal_int</a> </li><li><a href="#fmt-parser-read-decimal-int-method">read_decimal_int</a> </li><li><a href="#fmt-parser-read-hex-int-method">read_hex_int</a> </li><li><a href="#fmt-parser-check-method">check</a> </li></ul><li>read-only properties <ul><li>[bool] at_end </li><li>[bool] stream_offset </li></ul><li>other features: <ul><li>GC-safe</li></ul></li></ul></div> <div class='item'><a name='fmt-parser-read-method'></a><hr><h2>fmt_parser.read [method]</h2><h3>fmt_parser.read( int num )</h3><h4>reads at most <code>num</code> bytes from stream and returns them as string</h4><ul><li>if 0 bytes are returned, it&#39;s quite safe to assume that the function has reached the end of file but check the at_end property to be sure </li><li>may return null and emit a warning on unexpected read errors</li></ul><pre>stream = fmt_string_parser( &quot;action&quot; ); stream.read( 5 ); // returns &quot;actio&quot;</pre></div> <div class='item'><a name='fmt-parser-getchar-method'></a><hr><h2>fmt_parser.getchar [method]</h2><h3>fmt_parser.getchar( bool peek = false, bool as_int = false )</h3><h4>returns a character from stream</h4><ul><li>if <code>peek</code> is true, stream is not advanced (next read operation will also work on the same character) </li><li>if <code>as_int</code> is true, character is returned as integer (as one-character string otherwise) </li><li>may return null and emit a warning on unexpected read errors</li></ul><pre>stream = fmt_string_parser( &quot;action&quot; ); stream.read( true ); // returns &quot;a&quot; stream.read( true, true ); // returns 97 stream.read(); // returns &quot;a&quot; stream.read(); // returns &quot;c&quot;</pre></div> <div class='item'><a name='fmt-parser-readcc-method'></a><hr><h2>fmt_parser.readcc [method]</h2><h3>fmt_parser.readcc( string class, int num = 2^31-1 (0x7fffffff) )</h3><h4>reads and returns at most <code>num</code> bytes that match the character class <code>class</code></h4><ul><li>returns null and emits a warning if the class is empty/only contains the inversion symbol &quot;^&quot; </li><li>may return null and emit a warning on unexpected read errors</li></ul><pre>stream = fmt_string_parser( &quot;what is this&quot; ); stream.readcc( &quot;a-z&quot; ); // returns &quot;what&quot; stream.readcc( &quot;^a-z&quot; ); // returns &quot; &quot;</pre></div> <div class='item'><a name='fmt-parser-skipcc-method'></a><hr><h2>fmt_parser.skipcc [method]</h2><h3>fmt_parser.skipcc( string class, int num = 2^31-1 (0x7fffffff) )</h3><h4>skips at most <code>num</code> bytes that match the character class <code>class</code> and returns the number of bytes skipped</h4><ul><li>returns null and emits a warning if the class is empty/only contains the inversion symbol &quot;^&quot; </li><li>may return null and emit a warning on unexpected read errors</li></ul><pre>stream = fmt_string_parser( &quot;what is this&quot; ); stream.skipcc( &quot;a-z&quot; ); // returns 4 stream.skipcc( &quot;^a-z&quot; ); // returns 1</pre></div> <div class='item'><a name='fmt-parser-read-real-method'></a><hr><h2>fmt_parser.read_real [method]</h2><h3>fmt_parser.read_real( bool as_real = true )</h3><h4>returns characters read with the character class &quot;-+0-9.eE&quot;, optionally returned as a real value</h4></div> <div class='item'><a name='fmt-parser-read-int-method'></a><hr><h2>fmt_parser.read_int [method]</h2><h3>fmt_parser.read_int( bool as_int = true )</h3><h4>returns characters read with the character class &quot;-+0-9A-Fa-fxob&quot;, optionally returned as an int value</h4></div> <div class='item'><a name='fmt-parser-read-binary-int-method'></a><hr><h2>fmt_parser.read_binary_int [method]</h2><h3>fmt_parser.read_binary_int( bool as_int = true )</h3><h4>returns characters read with the character class &quot;0-1&quot;, optionally returned as an int value</h4></div> <div class='item'><a name='fmt-parser-read-octal-int-method'></a><hr><h2>fmt_parser.read_octal_int [method]</h2><h3>fmt_parser.read_octal_int( bool as_int = true )</h3><h4>returns characters read with the character class &quot;0-7&quot;, optionally returned as an int value</h4></div> <div class='item'><a name='fmt-parser-read-decimal-int-method'></a><hr><h2>fmt_parser.read_decimal_int [method]</h2><h3>fmt_parser.read_decimal_int( bool as_int = true )</h3><h4>returns characters read with the character class &quot;-+0-9&quot;, optionally returned as an int value</h4></div> <div class='item'><a name='fmt-parser-read-hex-int-method'></a><hr><h2>fmt_parser.read_hex_int [method]</h2><h3>fmt_parser.read_hex_int( bool as_int = true )</h3><h4>returns characters read with the character class &quot;0-9a-fA-F&quot;, optionally returned as an int value</h4></div> <div class='item'><a name='fmt-parser-check-method'></a><hr><h2>fmt_parser.check [method]</h2><h3>fmt_parser.check( string str, bool ci = false, bool partial = false )</h3><h4>returns whether the specified string was found at the current position</h4><ul><li><code>ci</code> makes matching case-insensitive </li><li>if <code>partial</code> is true, function returns the number of characters successfully matched instead of whether everything has been matched</li></ul></div> <div class='item'><a name='ALL-SGScript-formatting-functions-A-Z'></a><hr><h2>ALL SGScript formatting functions (A-Z)</h2><ul><li><a href="#fmt-base64-decode-function">fmt_base64_decode [function]</a> </li><li><a href="#fmt-base64-encode-function">fmt_base64_encode [function]</a> </li><li><a href="#fmt-charcc-function">fmt_charcc [function]</a> </li><li><a href="#fmt-file-parser-function">fmt_file_parser [function]</a> </li><li><a href="#fmt-pack-function">fmt_pack [function]</a> </li><li><a href="#fmt-pack-count-function">fmt_pack_count [function]</a> </li><li><a href="#fmt-pack-size-function">fmt_pack_size [function]</a> </li><li><a href="#fmt-parser-function">fmt_parser [function]</a> </li><li><a href="#fmt-string-parser-function">fmt_string_parser [function]</a> </li><li><a href="#fmt-text-function">fmt_text [function]</a> </li><li><a href="#fmt-unpack-function">fmt_unpack [function]</a></li></ul></div> <div class='item'><a name='I-O-library-io'></a><hr><h2>I/O library (&quot;io&quot;)</h2><p> This library contains the functions necessary to work with the file system (files and directories). </p><h4>Functions:</h4><ul><li><a href="#io-setcwd-function">io_setcwd</a> - set the current working directory </li><li><a href="#io-getcwd-function">io_getcwd</a> - returns the current working directory </li><li><a href="#io-getexecpath-function">io_getexecpath</a> - returns the absolute executable path </li><li><a href="#io-rename-function">io_rename</a> - rename or move a file system item </li><li><a href="#io-file-exists-function">io_file_exists</a> - returns whether the specified file exists and is accessible </li><li><a href="#io-dir-exists-function">io_dir_exists</a> - returns whether the specified directory exists and is accessible </li><li><a href="#io-stat-function">io_stat</a> - returns information about a file system item </li><li><a href="#io-dir-create-function">io_dir_create</a> - create a directory </li><li><a href="#io-dir-delete-function">io_dir_delete</a> - remove a directory </li><li><a href="#io-file-delete-function">io_file_delete</a> - deletes a file </li><li><a href="#io-file-write-method">io_file_write</a> - writes byte buffer to file, creating or overwriting it, as necessary </li><li><a href="#io-file-read-method">io_file_read</a> - reads byte buffer from a file </li><li><a href="#io-file-object">io_file</a> - creates a <a href="#io-file-object">io_file</a> object, optionally opening it </li><li><a href="#io-dir-function">io_dir</a> - creates a <a href="#io-dir-function">io_dir</a> directory iterator object, set to read a specific directory</li></ul><h4>Objects and their methods:</h4><ul><li><a href="#io-file-object">io_file</a> - file object <ul><li><a href="#io-file-open-method">open</a> - open a file </li><li><a href="#io-file-close-method">close</a> - close the currently open file (if any) </li><li><a href="#io-file-read-method">read</a> - read from the open file </li><li><a href="#io-file-write-method">write</a> - write to the open file </li><li><a href="#io-file-seek-method">seek</a> - change read/write position in file </li><li><a href="#io-file-flush-method">flush</a> - flush the write buffer </li><li><a href="#io-file-setbuf-method">setbuf</a> - change the size and flush trigger of the write buffer or disables it </li></ul><li><a href="#io-dir-function">io_dir</a> - directory iterator object, for use in &quot;foreach&quot;</li></ul><h4>Constants:</h4><ul><li><a href="#FILE-constants">FILE_***</a> - mode constants for <a href="#io-file-object">io_file</a>.open / <a href="#io-file-function">io_file [function]</a> </li><li><a href="#SEEK-constants">SEEK_***</a> - mode constants for <a href="#io-file-object">io_file</a>.seek </li><li><a href="#FST-constants">FST_***</a> - file system item type constants for <a href="#io-stat-function">io_stat</a></li></ul></div> <div class='item'><a name='io-setcwd-function'></a><hr><h2>io_setcwd [function]</h2><h3>io_setcwd( string cwd )</h3><h4>sets the current working directory, returns bool/sets errno</h4></div> <div class='item'><a name='io-getcwd-function'></a><hr><h2>io_getcwd [function]</h2><h3>io_getcwd()</h3><h4>returns the current working directory or null, if for some reason an error occured</h4><ul><li>in case of failure, function will set errno</li></ul></div> <div class='item'><a name='io-getexecpath-function'></a><hr><h2>io_getexecpath [function]</h2><h3>io_getexecpath()</h3><h4>returns the path of the executable file the script is executed in</h4><ul><li>in case of failure, function will set errno</li></ul></div> <div class='item'><a name='io-rename-function'></a><hr><h2>io_rename [function]</h2><h3>io_rename( string path, string newpath )</h3><h4>attempts to rename the file, returns bool/sets errno</h4><ul><li>wraps the C library function rename </li><li>to avoid moving the file/directory, make sure both paths are of the same origin</li></ul></div> <div class='item'><a name='io-file-exists-function'></a><hr><h2>io_file_exists [function]</h2><h3>io_file_exists( string file )</h3><h4>checks if file exists and is accessible by the process at the moment, returns true on success, false otherwise</h4><ul><li>uses the C library functions fopen/fclose</li></ul></div> <div class='item'><a name='io-dir-exists-function'></a><hr><h2>io_dir_exists [function]</h2><h3>io_dir_exists( string dir )</h3><h4>checks if directory exists and is accessible by the process at the moment, returns true on success, false otherwise</h4><ul><li>uses the C library functions opendir,closedir where supported properly, Windows API Find*** functions otherwise</li></ul></div> <div class='item'><a name='io-stat-function'></a><hr><h2>io_stat [function]</h2><h3>io_stat( string fsitem )</h3><h4>returns info about the file system item <code>fsitem</code>, as dict</h4><ul><li>the returned object contains the following properties: <ul><li>atime: last access time </li><li>ctime: creation time </li><li>mtime: last modification time </li><li>type: enum (one of FST_DIR/FST_FILE/FST_UNKNOWN) </li><li>size: size of item </li></ul><li>uses the C library function stat/_stat</li></ul></div> <div class='item'><a name='io-dir-create-function'></a><hr><h2>io_dir_create [function]</h2><h3>io_dir_create( string path, int mode = 0o777 )</h3><h4>attempts to create a directory at the specified path, with the specified access mode <code>mode</code>, returns bool/sets errno</h4><ul><li><code>mode</code> is ignored on Windows </li><li>uses the C library function mkdir/_mkdir</li></ul></div> <div class='item'><a name='io-dir-delete-function'></a><hr><h2>io_dir_delete [function]</h2><h3>io_dir_delete( string path )</h3><h4>attempts to delete a directory at the specified path, returns bool/sets errno</h4><ul><li>uses the C library function rmdir/_rmdir</li></ul></div> <div class='item'><a name='io-file-delete-function'></a><hr><h2>io_file_delete [function]</h2><h3>io_file_delete( string path )</h3><h4>attempts to delete a file at the specified path, returns bool/sets errno</h4><ul><li>uses the C library function remove</li></ul></div> <div class='item'><a name='io-file-write-function'></a><hr><h2>io_file_write [function]</h2><h3>io_file_write( string path, string data )</h3><h4>writes the byte buffer <code>data</code> to the file pointed to by <code>path</code>, returns bool/sets errno</h4></div> <div class='item'><a name='io-file-read-function'></a><hr><h2>io_file_read [function]</h2><h3>io_file_read( string path )</h3><h4>reads the byte buffer from file at <code>path</code>, returns buffer as string or null/sets errno</h4></div> <div class='item'><a name='io-file-object'></a><hr><h2>io_file [object]</h2><ul><li>methods <ul><li><a href="#io-file-open-method">open</a> </li><li><a href="#io-file-close-method">close</a> </li><li><a href="#io-file-read-method">read</a> </li><li><a href="#io-file-write-method">write</a> </li><li><a href="#io-file-seek-method">seek</a> </li><li><a href="#io-file-flush-method">flush</a> </li><li><a href="#io-file-setbuf-method">setbuf</a> </li></ul><li>read-only properties <ul><li>[int] offset </li><li>[int] size </li><li>[bool] error </li><li>[bool] eof </li></ul><li>other features: <ul><li>tobool = returns whether file is open or not </li><li>GC-safe</li></ul></li></ul></div> <div class='item'><a name='io-file-open-method'></a><hr><h2>io_file.open [method]</h2><h3>io_file.open( string name, int mode )</h3><h4>closes the previously open file if any, opens the file <code>name</code> for operation mode <code>mode</code>, returns bool/sets errno</h4><ul><li><code>mode</code> must be one of FILE_READ, FILE_WRITE or FILE_READ|FILE_WRITE </li><li>file is always opened in binary mode</li></ul><pre>f = io_file(); f.open( &quot;file&quot; ); // returns true or false, sets errno accordingly</pre></div> <div class='item'><a name='io-file-close-method'></a><hr><h2>io_file.close [method]</h2><h3>io_file.close()</h3><h4>closes the previously open file, if any, returns whether the file was open or not</h4><pre>f = io_file( &quot;file.txt&quot; ); f.close(); // returns true if the file existed f.close(); // returns false</pre></div> <div class='item'><a name='io-file-read-method'></a><hr><h2>io_file.read [method]</h2><h3>io_file.read( int num )</h3><h4>reads and returns at most <code>num</code> bytes from file, sets errno</h4></div> <div class='item'><a name='io-file-write-method'></a><hr><h2>io_file.write [method]</h2><h3>io_file.write( string data )</h3><h4>writes the byte buffer <code>data</code> to the file, sets errno</h4></div> <div class='item'><a name='io-file-seek-method'></a><hr><h2>io_file.seek [method]</h2><h3>io_file.seek( int off, int mode )</h3><h4>sets the offset in file, returns bool/sets errno</h4><ul><li><code>mode</code> must be one of SEEK_SET (sets as-is), SEEK_CUR (sets relative to current), SEEK_END (sets relative to end)</li></ul></div> <div class='item'><a name='io-file-flush-method'></a><hr><h2>io_file.flush [method]</h2><h3>io_file.flush()</h3><h4>flushes a buffered file, returns bool</h4></div> <div class='item'><a name='io-file-setbuf-method'></a><hr><h2>io_file.setbuf [method]</h2><h3>io_file.setbuf( int size )</h3><h4>sets the size of file buffer (0 to disable buffering), returns bool</h4><ul><li>buffering allows to avoid committing each write immediately to disk, resulting in a performance gain, however it may introduce issues if application is expected to fail at any moment, resulting in some data not being written in such cases</li></ul></div> <div class='item'><a name='io-file-function'></a><hr><h2>io_file [function]</h2><h3>io_file([ string name, int mode ])</h3><h4>creates and returns a file, optionally allowing to open it on creation</h4><ul><li>see <a href="#io-file-object">io_file</a>.open() for more info on opening the file</li></ul></div> <div class='item'><a name='io-dir-directory-iterator-object'></a><hr><h2>io_dir (directory_iterator) [object]</h2><ul><li>features: <ul><li>tostring = &quot;directory_iterator&quot; </li><li>iterator interface (key = whether real item, value = item name) <ul><li>real items are all except &quot;.&quot; and &quot;..&quot; </li></ul><li>returns self as iterator </li><li>GC-safe </li><li>type identification (returns the string &quot;directory_iterator&quot;)</li></ul></li></ul></div> <div class='item'><a name='io-dir-function'></a><hr><h2>io_dir [function]</h2><h3>io_dir( string dir )</h3><h4>creates a directory iterator for the directory <code>dir</code>, sets errno, returns null and emits a warning on failure</h4></div> <div class='item'><a name='FILE-constants'></a><hr><h2>FILE_*** [constants]</h2><h3>FILE_READ, FILE_WRITE</h3><h4>mode constants for <a href="#io-file-object">io_file</a>.open / <a href="#io-file-function">io_file [function]</a></h4></div> <div class='item'><a name='SEEK-constants'></a><hr><h2>SEEK_*** [constants]</h2><h3>SEEK_SET, SEEK_CUR, SEEK_END</h3><h4>mode constants for <a href="#io-file-object">io_file</a>.seek</h4></div> <div class='item'><a name='FST-constants'></a><hr><h2>FST_*** [constants]</h2><h3>FST_UNKNOWN, FST_FILE, FST_DIR</h3><h4>file system item type constants for <a href="#io-stat-function">io_stat</a></h4></div> <div class='item'><a name='ALL-SGScript-I-O-functions-A-Z'></a><hr><h2>ALL SGScript I/O functions (A-Z)</h2><ul><li><a href="#io-dir-function">io_dir [function]</a> </li><li><a href="#io-dir-create-function">io_dir_create [function]</a> </li><li><a href="#io-dir-delete-function">io_dir_delete [function]</a> </li><li><a href="#io-dir-exists-function">io_dir_exists [function]</a> </li><li><a href="#io-file-function">io_file [function]</a> </li><li><a href="#io-file-delete-function">io_file_delete [function]</a> </li><li><a href="#io-file-exists-function">io_file_exists [function]</a> </li><li><a href="#io-file-read-function">io_file_read [function]</a> </li><li><a href="#io-file-write-function">io_file_write [function]</a> </li><li><a href="#io-getcwd-function">io_getcwd [function]</a> </li><li><a href="#io-getexecpath-function">io_getexecpath [function]</a> </li><li><a href="#io-rename-function">io_rename [function]</a> </li><li><a href="#io-setcwd-function">io_setcwd [function]</a> </li><li><a href="#io-stat-function">io_stat [function]</a></li></ul></div> <div class='item'><a name='Math-library-math'></a><hr><h2>Math library (&quot;math&quot;)</h2><p> This library contains the basic math functions for processing real values. </p><h4>Functions:</h4><ul><li><a href="#abs-function">abs</a> - returns the absolute value of x </li><li><a href="#floor-function">floor</a> - returns rounded-down value of x </li><li><a href="#ceil-function">ceil</a> - returns the rounded-up value of x </li><li><a href="#round-function">round</a> - returns the rounded-to-nearest-integer value of x </li><li><a href="#pow-function">pow</a> - returns x to the power of y </li><li><a href="#sqrt-function">sqrt</a> - returns a square root of x </li><li><a href="#log-function">log</a> - returns the logarithm (power) of x for base y </li><li><a href="#sin-function">sin</a> - returns the sine of x </li><li><a href="#cos-function">cos</a> - returns the cosine of x </li><li><a href="#tan-function">tan</a> - returns the tangent of x </li><li><a href="#asin-function">asin</a> - returns arcsine (angle for sine value) of x </li><li><a href="#acos-function">acos</a> - returns arccosine (angle for cosine value) of x </li><li><a href="#atan-function">atan</a> - returns arctangent (angle for tangent value) of x </li><li><a href="#atan2-function">atan2</a> - returns arctangent of x and y, using both values to extend the range of returned value </li><li><a href="#deg2rad-function">deg2rad</a> - returns x degrees as radians </li><li><a href="#rad2deg-function">rad2deg</a> - returns x radians as degrees</li></ul><h4>Constants:</h4><ul><li><a href="#Main-types">M_***</a> - mathematical constants</li></ul></div> <div class='item'><a name='abs-function'></a><hr><h2>abs [function]</h2><h3>abs( x )</h3><h4>returns the absolute value of <code>x</code>, as <code>real</code></h4><pre>abs( 2.2 ); // real (2.2) abs( -3.1 ); // real (3.1)</pre></div> <div class='item'><a name='floor-function'></a><hr><h2>floor [function]</h2><h3>floor( x )</h3><h4>returns the largest integer that is not bigger than <code>x</code>, as <code>real</code></h4><pre>floor( 3.4 ); // real (3) floor( 3.8 ); // real (3) floor( 4.2 ); // real (4) floor( -3.1 ); // real (-4)</pre></div> <div class='item'><a name='ceil-function'></a><hr><h2>ceil [function]</h2><h3>ceil( x )</h3><h4>returns the smallest integer that is not smaller than <code>x</code>, as <code>real</code></h4><pre>ceil( 3.4 ); // real (4) ceil( 3.8 ); // real (4) ceil( 4.2 ); // real (5) ceil( -3.1 ); // real (-3)</pre></div> <div class='item'><a name='round-function'></a><hr><h2>round [function]</h2><h3>round( x )</h3><h4>returns the closest integer to <code>x</code>, as <code>real</code></h4><pre>round( 3.4 ); // real (3) round( 3.8 ); // real (4) round( 4.2 ); // real (4) round( -3.1 ); // real (-3)</pre></div> <div class='item'><a name='pow-function'></a><hr><h2>pow [function]</h2><h3>pow( x, y )</h3><h4>returns <code>x</code> raised to the power <code>y</code>, as <code>real</code></h4><ul><li>If base (<code>x</code>) is negative and exponent (<code>y</code>) is not an integral value, or if base is zero and exponent is negative, function returns <code>null</code> and emits a warning message.</li></ul><pre>pow( 2, 5 ); // real (32) pow( 9, 0.5 ); // real (3) pow( -1, 0.5 ); // null; Warning: pow(): mathematical error</pre></div> <div class='item'><a name='sqrt-function'></a><hr><h2>sqrt [function]</h2><h3>sqrt( x )</h3><h4>returns the square root of <code>x</code>, as <code>real</code></h4><ul><li>If <code>x</code> is negative, function returns <code>null</code> and emits a warning message.</li></ul><pre>sqrt( 16 ); // real (4) sqrt( -1 ); // null; Warning: sqrt(): mathematical error</pre></div> <div class='item'><a name='log-function'></a><hr><h2>log [function]</h2><h3>log( x, y )</h3><h4>returns the base-`y` logarithm of <code>x</code>, as <code>real</code></h4><ul><li>If <code>x &lt;= 0</code> or <code>b &lt;= 0</code> or <code>b = 1</code>, function returns <code>null</code> and emits a warning message.</li></ul><pre>log( 9, 3 ); // real (2) log( -1, 3 ); // .. or .. log( 3, 0 ); // .. or .. log( 3, 1 ); // null; Warning: log(): mathematical error</pre></div> <div class='item'><a name='sin-function'></a><hr><h2>sin [function]</h2><h3>sin( x )</h3><h4>returns the sine of angle <code>x</code> in radians, as <code>real</code></h4><pre>sin( 0 ); // real (0) sin( M_PI / 2 ); // real (1) sin( M_PI / 4 ); // real (0.707107)</pre></div> <div class='item'><a name='cos-function'></a><hr><h2>cos [function]</h2><h3>cos( x )</h3><h4>returns the cosine of angle <code>x</code> in radians, as <code>real</code></h4><pre>sin( 0 ); // real (1) sin( M_PI ); // real (-1) sin( M_PI / 4 ); // real (0.707107)</pre></div> <div class='item'><a name='tan-function'></a><hr><h2>tan [function]</h2><h3>tan( x )</h3><h4>returns the tangent of angle <code>x</code> in radians, as <code>real</code></h4><pre>tan( 0 ); // real (0) tan( 1 ); // real (1.55741) tan( M_PI / 4 ); // real (1)</pre></div> <div class='item'><a name='asin-function'></a><hr><h2>asin [function]</h2><h3>asin( x )</h3><h4>returns the arcsine of <code>x</code> (angle in radians), as <code>real</code></h4><ul><li>If <code>x</code> is outside the [-1,1] range, function returns <code>null</code> and emits a warning message</li></ul><pre>asin( -1 ); // real (-1.5708) asin( 0 ); // real (0) asin( 2 ); // null; Warning: asin(): mathematical error</pre></div> <div class='item'><a name='acos-function'></a><hr><h2>acos [function]</h2><h3>acos( x )</h3><h4>returns the arccosine of <code>x</code> (angle in radians), as <code>real</code></h4><ul><li>If <code>x</code> is outside the [-1,1] range, function returns <code>null</code> and emits a warning message</li></ul><pre>acos( -1 ); // real (3.14159) acos( 0 ); // real (1.5708) acos( 2 ); // null; Warning: acos(): mathematical error</pre></div> <div class='item'><a name='atan-function'></a><hr><h2>atan [function]</h2><h3>atan( x )</h3><h4>returns the arctangent of <code>x</code> (angle in radians), as <code>real</code></h4><pre>atan( 0 ); // real (0) atan( 1 ); // real (0.785398) atan( 9999999 ); // real (1.5708)</pre></div> <div class='item'><a name='atan2-function'></a><hr><h2>atan2 [function]</h2><h3>atan2( y, x )</h3><h4>returns the extended arctangent of y/x (angle in radians), as <code>real</code></h4><ul><li>Signs of <code>x</code> and <code>y</code> are used to determine the quadrant, thus <code>y</code> is expected to be the sine of the angle to be returned (the <code>y</code> coordinate of a point) and <code>x</code> - the cosine (the <code>x</code> coordinate).</li></ul><p> <em class='notice-bgr'>Due to the common requirement to use this function to determine the angle between two somewhat random points (usually from a simulation), it will not emit a warning when both arguments are 0 - it will return 0 instead.</em> </p><pre>atan2( 0, 1 ); // real (0) atan2( 1, 0 ); // real (1.5708) atan2( -1, -1 ); // real (-2.35619) atan2( 0, 0 ); // real (0)</pre></div> <div class='item'><a name='deg2rad-function'></a><hr><h2>deg2rad [function]</h2><h3>deg2rad( x )</h3><h4>returns angle, converted from degrees to radians, as <code>real</code></h4><pre>deg2rad( 0 ); // real (0) deg2rad( 180 ); // real (3.14159) deg2rad( -90 ); // real (-1.5708)</pre></div> <div class='item'><a name='rad2deg-function'></a><hr><h2>rad2deg [function]</h2><h3>rad2deg( x )</h3><h4>returns angle, converted from radians to degrees, as <code>real</code></h4><pre>rad2deg( 0 ); // real (0) rad2deg( M_PI ); // real (180) rad2deg( -M_PI / 2 ); // real (-90)</pre></div> <div class='item'><a name='M-constants'></a><hr><h2>M_*** [constants]</h2><h3>M_PI</h3><h4>the ratio of circumference of a circle to its diameter (pi)</h4><ul><li>the value of this constant is <code>3.14159265358979323846</code></li></ul><h3>M_E</h3><h4>the natural logarithmic base (e)</h4><ul><li>the value of this constant is <code>2.7182818284590452354</code></li></ul></div> <div class='item'><a name='ALL-SGScript-math-functions-A-Z'></a><hr><h2>ALL SGScript math functions (A-Z)</h2><ul><li><a href="#abs-function">abs [function]</a> </li><li><a href="#acos-function">acos [function]</a> </li><li><a href="#asin-function">asin [function]</a> </li><li><a href="#atan-function">atan [function]</a> </li><li><a href="#atan2-function">atan2 [function]</a> </li><li><a href="#ceil-function">ceil [function]</a> </li><li><a href="#cos-function">cos [function]</a> </li><li><a href="#deg2rad-function">deg2rad [function]</a> </li><li><a href="#floor-function">floor [function]</a> </li><li><a href="#log-function">log [function]</a> </li><li><a href="#pow-function">pow [function]</a> </li><li><a href="#rad2deg-function">rad2deg [function]</a> </li><li><a href="#round-function">round [function]</a> </li><li><a href="#sin-function">sin [function]</a> </li><li><a href="#sqrt-function">sqrt [function]</a> </li><li><a href="#tan-function">tan [function]</a></li></ul></div> <div class='item'><a name='OS-library-os'></a><hr><h2>OS library (&quot;os&quot;)</h2><ul><li>environment variables </li><li>time and date </li><li>locale / regional settings</li></ul><h4>Functions:</h4><ul><li><a href="#os-gettype-function">os_gettype</a> - returns the name of closest known OS type match, defined at compile time </li><li><a href="#os-command-function">os_command</a> - pass command to OS command processor </li><li><a href="#os-getenv-function">os_getenv</a> - returns the value of the specified environment variable </li><li><a href="#os-putenv-function">os_putenv</a> - set an environment variable </li><li><a href="#os-time-function">os_time</a> - returns the time in seconds, optionally from a different time zone </li><li><a href="#os-get-timezone-function">os_get_timezone</a> - returns the time zone set in OS, optionally as string </li><li><a href="#os-date-string-function">os_date_string</a> - format a time value into a string </li><li><a href="#os-parse-time-function">os_parse_time</a> - split time value into components </li><li><a href="#os-make-time-function">os_make_time</a> - make a time value from components </li><li><a href="#os-get-locale-function">os_get_locale</a> - returns current locale of the specified category </li><li><a href="#os-set-locale-function">os_set_locale</a> - set locale for the specified category </li><li><a href="#os-get-locale-format-function">os_get_locale_format</a> - returns locale formatting info </li><li><a href="#os-locale-strcmp-function">os_locale_strcmp</a> - compare two strings using locale</li></ul><h4>Constants:</h4><ul><li><a href="#LC-constants">LC_***</a> - locale categories</li></ul></div> <div class='item'><a name='os-gettype-function'></a><hr><h2>os_gettype [function]</h2><h3>os_gettype()</h3><h4>returns the name of the closest known match for the operating system type, defined at library compile time</h4><ul><li>the function can detect and return the following OSes at the moment (with the preprocessor define in braces): <ul><li>&quot;Windows&quot; (_WIN32/__WIN32__/__WINDOWS__) </li><li>&quot;Mac OS X&quot; (__APPLE__) </li><li>&quot;Android&quot; (__ANDROID__) </li><li>&quot;Linux&quot; (__linux/__linux__) </li><li>&quot;Unix&quot; (__unix/__unix__) </li><li>&quot;POSIX&quot; (__posix) </li><li>&quot;Unknown&quot; (..any other)</li></ul></li></ul></div> <div class='item'><a name='os-command-function'></a><hr><h2>os_command [function]</h2><h3>os_command( string cmd )</h3><h4>passes a command to the OS command processor, returns the integer return value</h4><p> <em class='notice-bgr'>this function can be extremely unsafe in multithreaded/incontrollable environments due to the completely undefined outcome of the call</em> </p><ul><li>uses the C library function &#39;system&#39;</li></ul></div> <div class='item'><a name='os-getenv-function'></a><hr><h2>os_getenv [function]</h2><h3>os_getenv( string var )</h3><h4>returns the value for the environment variable <code>var</code> or null, if there is no such value</h4></div> <div class='item'><a name='os-putenv-function'></a><hr><h2>os_putenv [function]</h2><h3>os_putenv( string cmd )</h3><h4>sets the value for the environment variable specified in command <code>cmd</code>, returns success as bool</h4><ul><li><code>cmd</code> has the format &quot;&lt;name&gt;=&lt;value&gt;&quot;</li></ul></div> <div class='item'><a name='os-time-function'></a><hr><h2>os_time [function]</h2><h3>os_time( real tz = &lt;local&gt; )</h3><h4>returns the time in seconds, as integer, optionally from a different time zone <code>tz</code></h4></div> <div class='item'><a name='os-get-timezone-function'></a><hr><h2>os_get_timezone [function]</h2><h3>os_get_timezone( bool as_string = false )</h3><h4>returns the time zone set in the operating system, optionally as string in the format &quot;(+/-)HH:MM&quot;</h4></div> <div class='item'><a name='os-date-string-function'></a><hr><h2>os_date_string [function]</h2><h3>os_date_string( string fmt, int time = os_time() )</h3><h4>returns the date/time string in the format <code>fmt</code>, optionally for a different time <code>time</code></h4><ul><li>the following item specifiers are supported (*-local-specific): <ul><li>%a: abbreviated weekday name * </li><li>%A: full weekday name * </li><li>%b: abbreviated month name * </li><li>%B: full month name * </li><li>%c: full date/time * </li><li>%x: full date * </li><li>%X: full time * </li><li>%Z: timezone name/abbreviation (could be an empty string) * </li><li>%U: week number with first Sunday as the first day of week one * </li><li>%W: week number with first Monday as the first day of week one * </li><li>%C: year/100, as integer </li><li>%d: zero-padded day of the month (01-31) </li><li>%e: space-padded day of the month ( 1-31) </li><li>%F: date, shortcut of &quot;%Y-%m-%d&quot; </li><li>%H: hour in 24h format (00-23) </li><li>%I: hour in 12h format (01-12) </li><li>%j: day of the year (001-366) </li><li>%m: month number (01-12) </li><li>%M: minute (00-59) </li><li>%p: AM or PM </li><li>%R: hour/minute time, shortcut to %H:%M </li><li>%s: second (00-61) </li><li>%T: time, shortcut to %H:%M:%S </li><li>%u: weekday with Sunday as 0 </li><li>%w: weekday with Monday as 1 </li><li>%y: 2-digit year (00-99) </li><li>%Y: year </li><li>%f: file-safe full time, shortcut to %Y-%m-%d_%H-%M-%S </li><li>%t: the UNIX timestamp </li><li>%%: prints &quot;%&quot; </li><li>%&lt;any other&gt;: prints both characters</li></ul></li></ul></div> <div class='item'><a name='os-parse-time-function'></a><hr><h2>os_parse_time [function]</h2><h3>os_parse_time( int time = os_time() )</h3><h4>returns <code>time</code> split into parts, as dict</h4><ul><li>the returned dict contains the following properties (all are integers): <ul><li>year (1900-????) </li><li>month (1-12) </li><li>day (1-31) </li><li>weekday (1-7) </li><li>yearday (1-366) </li><li>hours (0-23) </li><li>minutes (0-59) </li><li>seconds (0-61)</li></ul></li></ul></div> <div class='item'><a name='os-make-time-function'></a><hr><h2>os_make_time [function]</h2><h3>os_make_time( int sec, int min = 0, int hour = 0, int mday = 0, int mon = 0, int year = 0 )</h3><h4>returns time as UNIX timestamp, generated from the arguments, using them as hints (under-/overflows may have some unexpected behavior)</h4></div> <div class='item'><a name='os-get-locale-function'></a><hr><h2>os_get_locale [function]</h2><h3>os_get_locale( int which )</h3><h4>returns the currently set locale for the specified category</h4><ul><li><code>which</code> must be one of the LC_ constants </li><li>the returned string is platform-specific </li><li>wraps the C library function setlocale</li></ul></div> <div class='item'><a name='os-set-locale-function'></a><hr><h2>os_set_locale [function]</h2><h3>os_set_locale( int which, string locale )</h3><h4>sets the locale for the specified category, returning whether the call was successful</h4><ul><li><code>which</code> must be one of the LC_ constants </li><li>the available locale strings are platform-specific </li><li>wraps the C library function setlocale</li></ul></div> <div class='item'><a name='os-get-locale-format-function'></a><hr><h2>os_get_locale_format [function]</h2><h3>os_get_locale_format()</h3><h4>retrieve the formatting info of the currently set locale as a dict</h4><ul><li>wraps the C library function localeconv </li><li>the returned data is identical to pre-C99 format of struct lconv</li></ul></div> <div class='item'><a name='os-locale-strcmp-function'></a><hr><h2>os_locale_strcmp [function]</h2><h3>os_locale_strcmp( string a, string b )</h3><h4>compare two strings using locale to return correct sign for inequalities (good for language-correct sorting)</h4><ul><li>expected encoding depends on the platform and the locale that is currently set </li><li>wraps the C library function strcoll</li></ul></div> <div class='item'><a name='LC-constants'></a><hr><h2>LC_*** [constants]</h2><p> These constants specify the categories for which locale can be changed. </p><ul><li>LC_ALL affects every locale-related function </li><li>LC_COLLATE: os_locale_strcmp </li><li>LC_MONETARY: os_get_locale_format </li><li>LC_NUMERIC: os_get_locale_format </li><li>LC_TIME: os_date_string</li></ul></div> <div class='item'><a name='ALL-SGScript-OS-functions-A-Z'></a><hr><h2>ALL SGScript OS functions (A-Z)</h2><ul><li><a href="#os-command-function">os_command [function]</a> </li><li><a href="#os-date-string-function">os_date_string [function]</a> </li><li><a href="#os-get-locale-function">os_get_locale [function]</a> </li><li><a href="#os-get-locale-format-function">os_get_locale_format [function]</a> </li><li><a href="#os-get-timezone-function">os_get_timezone [function]</a> </li><li><a href="#os-getenv-function">os_getenv [function]</a> </li><li><a href="#os-gettype-function">os_gettype [function]</a> </li><li><a href="#os-locale-strcmp-function">os_locale_strcmp [function]</a> </li><li><a href="#os-make-time-function">os_make_time [function]</a> </li><li><a href="#os-parse-time-function">os_parse_time [function]</a> </li><li><a href="#os-putenv-function">os_putenv [function]</a> </li><li><a href="#os-set-locale-function">os_set_locale [function]</a> </li><li><a href="#os-time-function">os_time [function]</a></li></ul></div> <div class='item'><a name='Regular-expression-library-re'></a><hr><h2>Regular expression library (&quot;re&quot;)</h2><p> This library includes regular expression match &amp; replace functions. </p><h4>Functions:</h4><ul><li><a href="#re-match-function">re_match</a> - check for first match in string for pattern </li><li><a href="#re-match-all-function">re_match_all</a> - check for all matches in string for pattern </li><li><a href="#re-replace-function">re_replace</a> - replace all matches in string for pattern with the specified string</li></ul><h4>Constants:</h4><ul><li><a href="#RE-RETURN-constants">RE_RETURN_***</a> - flag constants for <a href="#re-match-function">re_match</a> / <a href="#re-match-all-function">re_match_all</a></li></ul></div> <div class='item'><a name='re-match-function'></a><hr><h2>re_match [function]</h2><h3>re_match( string str, string pattern, int flags = 0, int offset = 0 )</h3><h4>check for matches in string <code>str</code> for <code>pattern</code>, returning whether a match was found or details of the first match, as specified in <code>flags</code></h4><ul><li><code>offset</code> specifies the character to start matching from, negative offset is subtracted from the end </li><li><code>flags</code> expect RE_RETURN_CAPTURED, RE_RETURN_OFFSETS or RE_RETURN_BOTH, which is a combination of the previous two <ul><li>if <code>flags</code> is one of the special values, function returns an array of captured ranges <ul><li>each entry is either a string (on RE_RETURN_CAPTURED) or an array of beginning and end offsets (at positions 0 and 1, respectively, on RE_RETURN_OFFSETS) or an array of a string and the beginning and end offsets (on RE_RETURN_BOTH) </li></ul></li></ul><li>the first character in the pattern specifies a delimiter that separates the pattern from modifiers <ul><li>example pattern strings: &quot;/^[a-z]+/mi&quot;, &quot;#[a-z0-9_]+.*?#s&quot; </li></ul><li>more info about the supported features and modifiers at https://github.com/snake5/sgregex</li></ul></div> <div class='item'><a name='re-match-all-function'></a><hr><h2>re_match_all [function]</h2><h3>re_match_all( string str, string pattern, int flags = 0, int offset = 0 )</h3><h4>check for matches in string <code>str</code> for <code>pattern</code>, returning the number of matches or details of all matches, as specified in <code>flags</code></h4><ul><li>similar to <a href="#re-match-function">re_match</a>, only difference is in the return value: <ul><li>if <code>flags</code> is one of the special values, function returns an array of matches where each match is an array of captured ranges <ul><li>each entry is same as in <a href="#re-match-function">re_match</a></li></ul></li></ul></li></ul></div> <div class='item'><a name='re-replace-function'></a><hr><h2>re_replace [function]</h2><h3>re_replace( string str, string pattern, string replacement )</h3><h4>find and replace all occurrences of <code>pattern</code> in string <code>str</code> with the <code>replacement</code> string</h4><ul><li>replacement string can contain backreferences in the forms &quot;$[0-9]&quot; or &quot;\[0-9]&quot; (in a string constant, a double backslash is required due to rules in SGScript) <ul><li>there can be up to 10 backreferences, 0-9, 0 being the whole match</li></ul></li></ul></div> <div class='item'><a name='RE-RETURN-constants'></a><hr><h2>RE_RETURN_*** [constants]</h2><p> These constants are used in <a href="#re-match-function">re_match</a> / <a href="#re-match-all-function">re_match_all</a> to specify the format of the return value. </p><p> If none of these are specified (<code>flags</code> = 0), only the success state is returned (true/false/match count). </p><ul><li>RE_RETURN_CAPTURED - return the captured string </li><li>RE_RETURN_OFFSETS - return array of start/end offsets </li><li>RE_RETURN_BOTH - return both the captured string and the start/end offsets in an array</li></ul></div> <div class='item'><a name='ALL-SGScript-RegExp-functions-A-Z'></a><hr><h2>ALL SGScript RegExp functions (A-Z)</h2><ul><li><a href="#re-match-function">re_match [function]</a> </li><li><a href="#re-match-all-function">re_match_all [function]</a> </li><li><a href="#re-replace-function">re_replace [function]</a></li></ul></div> <div class='item'><a name='String-library-string'></a><hr><h2>String library (&quot;string&quot;)</h2><p> This library contains the string handling functions. In all functions, except the utf-8 ones, it is assumed that strings are byte buffers where each byte is one character. If correct indices are applied, many of them will work with multibyte strings. </p><h4>Objects:</h4><ul><li><a href="#string-utf8-iterator-object">string_utf8_iterator</a> - UTF-8 code point iterator</li></ul><h4>Functions:</h4><ul><li><a href="#string-cut-function">string_cut</a> - extract a substring from a string from the specified beginning / end offsets </li><li><a href="#string-part-function">string_part</a> - extract a substring from a string from the specified offset and length </li><li><a href="#string-reverse-function">string_reverse</a> - reverse the order of bytes in a string </li><li><a href="#string-pad-function">string_pad</a> - pad one or both sides of a string with a pattern string up to the specified length </li><li><a href="#string-repeat-function">string_repeat</a> - concatenate several copies of the specified string </li><li><a href="#string-count-function">string_count</a> - count occurences of a substring in a string </li><li><a href="#string-find-function">string_find</a> - find first substring in the string, optionally after the specified position </li><li><a href="#string-find-rev-function">string_find_rev</a> - find a substring by walking the string backwards, optionally before the specified position </li><li><a href="#string-replace-function">string_replace</a> - replace parts of string according to match / replacement strings or arrays </li><li><a href="#string-translate-function">string_translate</a> - replace parts of string according to the provided match -&gt; replacement mapping dict </li><li><a href="#string-trim-function">string_trim</a> - trim one or both sides of string, removing the specified or default character set </li><li><a href="#string-toupper-function">string_toupper</a> - convert all ASCII lowercase characters into uppercase equivalents </li><li><a href="#string-tolower-function">string_tolower</a> - convert all ASCII uppercase characters into lowercase equivalents </li><li><a href="#string-compare-function">string_compare</a> - compare strings as byte arrays </li><li><a href="#string-implode-function">string_implode</a> - combine an array of strings, putting a separator string between each two consecutive strings </li><li><a href="#string-explode-function">string_explode</a> - split string into parts, separated by the specified separator string </li><li><a href="#string-charcode-function">string_charcode</a> - get the character code (byte value, as integer) from the specified position in string </li><li><a href="#string-frombytes-function">string_frombytes</a> - make a string from an array of integer values, interpreted as bytes </li><li><a href="#string-utf8-decode-function">string_utf8_decode</a> - decode a UTF-8 string into an array of code points </li><li><a href="#string-utf8-encode-function">string_utf8_encode</a> - encode an array of code points into a UTF-8 string </li><li><a href="#string-utf8-offset-function">string_utf8_offset</a> - get byte offset of a specific character </li><li><a href="#string-utf8-length-function">string_utf8_length</a> - get UTF-8 length of string or its part </li><li><a href="#string-utf8-iterator-function">string_utf8_iterator</a> - create an iterator for UTF-8 code points in a string </li><li><a href="#string-format-function">string_format</a> - format variables according to the specified format string</li></ul><h4>Constants:</h4><ul><li>STRING_NO_REV_INDEX - used by <a href="#string-cut-function">string_cut</a> / <a href="#string-part-function">string_part</a> - disable handling of negative indices </li><li>STRING_STRICT_RANGES - used by <a href="#string-cut-function">string_cut</a> / <a href="#string-part-function">string_part</a> - disable handling of out-of-bounds indices </li><li>STRING_TRIM_LEFT, STRING_TRIM_RIGHT - used by <a href="#string-trim-function">string_trim</a> - specify sides to be trimmed </li><li>STRING_PAD_LEFT, STRING_PAD_RIGHT - used by <a href="#string-pad-function">string_pad</a> - specify sides to be padded</li></ul></div> <div class='item'><a name='string-utf8-iterator-object'></a><hr><h2>string_utf8_iterator [object]</h2><ul><li>read/write properties: <ul><li>[int] offset - returns the point in string from which last character was retrieved, can set point in string from which next character will be retrieved </li></ul><li>read-only properties: <ul><li>[string] string - returns the string currently being iterated on </li></ul><li>other features: <ul><li>iterator (self) </li><li>cloning </li><li>serialization </li><li>GC-safe</li></ul></li></ul></div> <div class='item'><a name='string-cut-function'></a><hr><h2>string_cut [function]</h2><h3>string_cut( string str, int from[, int to[, int flags]] )</h3><h4>returns a part of string <code>str</code>, <code>from</code> and <code>to</code> being positions of the first and last character returned, respectively</h4><ul><li>if <code>to</code> is not specified, <code>to</code> is assumed to be the position of the last character in string <code>str</code> </li><li>if <code>from</code> or <code>to</code> are negative, they point to characters before the end of string (-1 being the last one) </li><li>available values for <code>flags</code>: <ul><li><code>STRING_NO_REV_INDEX</code> - emit warnings on negative indices, instead of handling them </li><li><code>STRING_STRICT_RANGES</code> - emit warnings on out of bounds <code>from</code>/<code>to</code> values instead of silently ignoring the outside characters</li></ul></li></ul><pre>string_cut( &quot;01234567&quot;, 3, 5 ); // string [3] &quot;345&quot;</pre></div> <div class='item'><a name='string-part-function'></a><hr><h2>string_part [function]</h2><h3>string_part( string str, int from[, int len[, int flags]] )</h3><h4>returns a part of string <code>str</code>, starting at <code>from</code>, at most <code>len</code> characters</h4><ul><li>if <code>len</code> is not specified, <code>len</code> is assumed to be the number of characters between <code>from</code> and the end of string <code>str</code> </li><li>if <code>from</code> is negative, it points to characters before the end of string (-1 being the last one) </li><li>if <code>len</code> is negative, the maximum length of returned string is the sum of <code>len</code> and string <code>str</code> length </li><li>available values for <code>flags</code>: <ul><li><code>STRING_NO_REV_INDEX</code> - emit warnings on negative indices, instead of handling them </li><li><code>STRING_STRICT_RANGES</code> - emit warnings on out of bounds <code>from</code>/<code>len</code> values instead of silently ignoring the outside characters</li></ul></li></ul><pre>string_part( &quot;01234567&quot;, 3, 3 ); // string [3] &quot;345&quot;</pre></div> <div class='item'><a name='string-reverse-function'></a><hr><h2>string_reverse [function]</h2><h3>string_reverse( string str )</h3><h4>returns <code>str</code> with all the bytes in reversed order</h4><p> <em class='notice-bgr'>This function will not work correctly with multibyte-encoded strings.</em> </p><pre>string_reverse( &quot;noitca&quot; ); // string [6] &quot;action&quot;</pre></div> <div class='item'><a name='string-pad-function'></a><hr><h2>string_pad [function]</h2><h3>string_pad( string str, int tgtsize, string padstr = &quot; &quot;, int flags = STRING_PAD_RIGHT )</h3><h4>return the string <code>str</code>, padded from template <code>padstr</code> up to the size <code>tgtsize</code> according to <code>flags</code></h4><ul><li>if <code>str</code> is longer than <code>tgtsize</code>, it is returned without changes </li><li>available values for <code>flags</code>: <ul><li><code>STRING_PAD_LEFT</code> - pad the string at the left side </li><li><code>STRING_PAD_RIGHT</code> - pad the string at the right side </li><li>if both flags are OR&#39;ed together, the string <code>str</code> is centered </li><li>at least one of the flags must be specified if the argument is passed for the function to work</li></ul></li></ul><pre>string_pad( &quot;padded&quot;, 10 ); // string [10] &quot;padded &quot; string_pad( &quot;center&quot;, 10, &quot;_&quot;, STRING_PAD_LEFT | STRING_PAD_RIGHT ); // string [10] &quot;__center__&quot;</pre></div> <div class='item'><a name='string-repeat-function'></a><hr><h2>string_repeat [function]</h2><h3>string_repeat( string str, int count )</h3><h4>return the string <code>str</code>, appended to itself `count`-1 times or an empty string if <code>count</code> is equal to 0</h4><ul><li><code>count</code> must be greater than or equal to 0</li></ul><pre>string_repeat( &quot;na&quot;, 6 ); // string [12] &quot;nananananana&quot; string_repeat( &quot;none&quot;, 0 ); // string [0] &quot;&quot;</pre></div> <div class='item'><a name='string-count-function'></a><hr><h2>string_count [function]</h2><h3>string_count( string str, string substr, bool overlap = false )</h3><h4>returns the number of substrings <code>substr</code> found in string <code>str</code></h4><ul><li>if <code>overlap</code> is true, function does not skip substrings when they are found</li></ul><pre>string_count( &quot;abababa&quot;, &quot;aba&quot; ); // int 2 string_count( &quot;abababa&quot;, &quot;aba&quot;, true ); // int 3</pre></div> <div class='item'><a name='string-find-function'></a><hr><h2>string_find [function]</h2><h3>string_find( string str, string substr, int offset = 0 )</h3><h4>returns the position of first found substring <code>substr</code> in string <code>str</code>, starting at <code>offset</code></h4><ul><li>if <code>substr</code> was not found, &#39;null&#39; is returned </li><li>if <code>offset</code> is less than 0, it specifies offset from the end</li></ul><pre>string_find( &quot;what hat&quot;, &quot;hat&quot; ); // int 1 string_find( &quot;what&quot;, &quot;hat&quot;, 2 ); // null</pre></div> <div class='item'><a name='string-find-rev-function'></a><hr><h2>string_find_rev [function]</h2><h3>string_find_rev( string str, string substr, int offset = 0 )</h3><h4>returns the position of last found substring <code>substr</code> in string <code>str</code>, starting at <code>offset</code></h4><ul><li>if <code>substr</code> was not found, &#39;null&#39; is returned </li><li>if <code>offset</code> is less than 0, it specifies offset from the end</li></ul><pre>string_find_rev( &quot;what hat&quot;, &quot;hat&quot; ); // int 5 string_find_rev( &quot;what&quot;, &quot;hat&quot;, 2 ); // int 1</pre></div> <div class='item'><a name='string-replace-function'></a><hr><h2>string_replace [function]</h2><h3>string_replace( string str, string from, string to )</h3><h3>string_replace( string str, array from, string to )</h3><h3>string_replace( string str, array from, array to )</h3><h4>replaces parts of string <code>str</code>, specified in <code>from</code>, to the respective values passed in <code>to</code></h4><ul><li>the respective replacement is picked by taking the substring index and performing modulo operation with the number of replacement strings</li></ul><pre>string_replace( &quot;loaded %num files&quot;, &quot;%num&quot;, 5 ); // string [14] &quot;loaded 5 files&quot; string_replace( &quot;abcd&quot;, [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;], [1,2,3,4] ); // string [4] &quot;1234&quot; string_replace( &quot;1234&quot;, [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;], [&quot;x&quot;,&quot;y&quot;] ); // string [4] &quot;xyxy&quot;</pre></div> <div class='item'><a name='string-translate-function'></a><hr><h2>string_translate [function]</h2><h3>string_translate( string str, iterable repmap )</h3><h4>replaces parts of string <code>str</code>, specified in the keys of <code>repmap</code>, to the matching values of the same iterable</h4><pre>string_translate( &quot;found %a files and %b folders&quot;, {&quot;%a&quot; = 5, &quot;%b&quot; = 17} ); // string [28] &quot;found 5 files and 17 folders&quot;</pre></div> <div class='item'><a name='string-trim-function'></a><hr><h2>string_trim [function]</h2><h3>string_trim( string str, string chars = &quot; \t\r\n&quot;, int flags = STRING_TRIM_LEFT | STRING_TRIM_RIGHT )</h3><h4>removes the specified characters from the specified sides of the string</h4><ul><li>available values for <code>flags</code>: <ul><li><code>STRING_TRIM_LEFT</code> - trim the string from the left side </li><li><code>STRING_TRIM_RIGHT</code> - trim the string from the right side</li></ul></li></ul><pre>string_trim( &quot; space &quot; ); // string [5] &quot;space&quot; string_trim( &quot;..something!..&quot;, &quot;.!&quot;, STRING_TRIM_RIGHT ); // string [11] &quot;..something&quot;</pre></div> <div class='item'><a name='string-toupper-function'></a><hr><h2>string_toupper [function]</h2><h3>string_toupper( string str )</h3><h4>converts all ASCII lowercase letter characters of the string to uppercase</h4><pre>string_toupper( &quot;Test&quot; ); // string [4] &quot;TEST&quot;</pre></div> <div class='item'><a name='string-tolower-function'></a><hr><h2>string_tolower [function]</h2><h3>string_tolower( string str )</h3><h4>converts all ASCII uppercase letter characters of the string to lowercase</h4><pre>string_toupper( &quot;Test&quot; ); // string [4] &quot;test&quot;</pre></div> <div class='item'><a name='string-compare-function'></a><hr><h2>string_compare [function]</h2><h3>string_compare( string str1, string str2, int max = 0, int from = 0 )</h3><h4>compares the two strings or the specified portions of them</h4><pre>string_compare( &quot;what&quot;, &quot;whaT&quot; ); // int 1 string_compare( &quot;what&quot;, &quot;whaT&quot;, 3 ); // int 0 string_compare( &quot;file.txt&quot;, &quot;.txt&quot;, 0, -4 ); // int 0</pre></div> <div class='item'><a name='string-implode-function'></a><hr><h2>string_implode [function]</h2><h3>string_implode( array items, string sep )</h3><h4>concatenates the string representations of array <code>items</code> values, putting a string <code>sep</code> between each two</h4><pre>string_implode( [&quot;one&quot;,&quot;two&quot;,&quot;three&quot;], &quot;, &quot; ); // string [15] &quot;one, two, three&quot;</pre></div> <div class='item'><a name='string-explode-function'></a><hr><h2>string_explode [function]</h2><h3>string_explode( string str, string sep )</h3><h4>splits the string <code>str</code> into an array of substrings, separated by string <code>sep</code></h4><pre>string_explode( &quot;www.example.com&quot;, &quot;.&quot; ); // [&quot;www&quot;,&quot;example&quot;,&quot;com&quot;] string_explode( &quot;x&quot;, &quot;-&quot; ); // [&quot;x&quot;] string_explode( &quot;/some//data&quot;, &quot;/&quot; ); // [&quot;&quot;,&quot;some&quot;,&quot;&quot;,&quot;data&quot;]</pre></div> <div class='item'><a name='string-charcode-function'></a><hr><h2>string_charcode [function]</h2><h3>string_charcode( string str, int offset = 0 )</h3><h4>returns the byte value / ASCII character code of the specified byte in the string</h4><pre>string_charcode( &quot;Test&quot; ); // int 84 string_charcode( &quot;Test&quot;, 3 ); // int 116</pre></div> <div class='item'><a name='string-frombytes-function'></a><hr><h2>string_frombytes [function]</h2><h3>string_frombytes( int byteval )</h3><h3>string_frombytes( array bytes )</h3><h4>returns a string, created from either one byte value (overload #1) or an array of byte values (overload #2)</h4><ul><li>byte values must be in the range [0-255]</li></ul><pre>string_frombytes( 53 ); // string [1] &quot;5&quot; string_frombytes([ 84, 101, 115, 116 ]); // string [4] &quot;Test&quot;</pre></div> <div class='item'><a name='string-utf8-decode-function'></a><hr><h2>string_utf8_decode [function]</h2><h3>string_utf8_decode( string ustr )</h3><h4>returns an array of Unicode code points, decoded from the UTF-8 string <code>ustr</code></h4><ul><li>invalid byte sequences will add 0xFFFD to the array</li></ul><pre>string_utf8_decode( &quot;pie&quot; ); // [112,105,101] string_utf8_decode( &quot;код&quot; ); // [1082,1086,1076] string_utf8_decode( &quot;標準&quot; ); // [27161,28310]</pre></div> <div class='item'><a name='string-utf8-encode-function'></a><hr><h2>string_utf8_encode [function]</h2><h3>string_utf8_encode( array cplist )</h3><h4>returns a UTF-8 string, composed from the Unicode code point list <code>cplist</code></h4><h3>string_utf8_encode([ int cp0[, int cp1, ... ]])</h3><h4>returns a UTF-8 string, composed from the Unicode code point list passed in argument list</h4><p> <em class='notice-bgr'>Without proper terminal software UTF-8 strings will not be displayed correctly (as is the case on Windows).</em> </p><ul><li>invalid code points will add &quot;\xEF\xBF\xBD&quot; (0xFFFD code point as UTF-8) to the string</li></ul><pre>string_utf8_encode( [112,105,101] ); // string [3] &quot;pie&quot; string_utf8_decode( [1082,1086,1076] ); // string [6] &quot;код&quot; string_utf8_decode( [27161,28310] ); // string [6] &quot;標準&quot;</pre></div> <div class='item'><a name='string-utf8-offset-function'></a><hr><h2>string_utf8_offset [function]</h2><h3>string_utf8_offset( string ustr, int charnum[, int byteoff ])</h3><h4>returns byte offset of character in UTF-8 string, optionally skipping the specified number of bytes</h4><ul><li>valid character numbers are 0 to actual number of characters from specified byte offset </li><li>valid byte offsets are 0 to ustr.length</li></ul><pre>string_utf8_offset( &quot;標準&quot;, 2 ); // returns 6</pre></div> <div class='item'><a name='string-utf8-length-function'></a><hr><h2>string_utf8_length [function]</h2><h3>string_utf8_length( string ustr, int byteoff = 0[, int numbytes[, int flags ]])</h3><h4>returns length of UTF-8 string or the specified part of it</h4><pre>string_utf8_length( &quot;標準&quot;, 3 ); // returns 1</pre></div> <div class='item'><a name='string-utf8-iterator-function'></a><hr><h2>string_utf8_iterator [function]</h2><h3>string_utf8_iterator( string ustr, int byteoff = 0 )</h3><h4>creates a UTF-8 code point iterator object</h4><pre>it = string_utf8_iterator( &quot;標準&quot; ); // returns string_utf8_iterator object iter_advance( it ); // go to position 0 iter_getdata( it ); // returns 27161</pre></div> <div class='item'><a name='string-format-function'></a><hr><h2>string_format [function]</h2><h3>string_format( [int prealloc,] string text, ... )</h3><h4>parses all format specifiers in <code>text</code> and returns the result</h4><p> <em class='notice-bgr'>see <a href="#fmt-text-function">fmt_text</a> if you don&#39;t need the position (argument index) specifications</em> </p><ul><li><code>prealloc</code> specifies number of bytes to be preallocated on the buffer to avoid continuous reallocations during string generation </li><li>the format specifier has the form {&lt;id&gt;:&lt;specifier&gt;} where &quot;id&quot; is the argument index to use and specifier is a <a href="#fmt-text-function">fmt_text</a> specifier </li><li>argument indices to be used in specifiers start from 1</li></ul><pre>print string_format( &quot;{1:d} -&gt; {1:x}&quot;, 1337 ); // prints &quot;1337 -&gt; 539&quot;</pre></div> <div class='item'><a name='ALL-SGScript-string-functions-A-Z'></a><hr><h2>ALL SGScript string functions (A-Z)</h2><ul><li><a href="#string-charcode-function">string_charcode [function]</a> </li><li><a href="#string-compare-function">string_compare [function]</a> </li><li><a href="#string-count-function">string_count [function]</a> </li><li><a href="#string-cut-function">string_cut [function]</a> </li><li><a href="#string-explode-function">string_explode [function]</a> </li><li><a href="#string-find-function">string_find [function]</a> </li><li><a href="#string-find-rev-function">string_find_rev [function]</a> </li><li><a href="#string-format-function">string_format [function]</a> </li><li><a href="#string-frombytes-function">string_frombytes [function]</a> </li><li><a href="#string-implode-function">string_implode [function]</a> </li><li><a href="#string-pad-function">string_pad [function]</a> </li><li><a href="#string-part-function">string_part [function]</a> </li><li><a href="#string-repeat-function">string_repeat [function]</a> </li><li><a href="#string-replace-function">string_replace [function]</a> </li><li><a href="#string-reverse-function">string_reverse [function]</a> </li><li><a href="#string-tolower-function">string_tolower [function]</a> </li><li><a href="#string-toupper-function">string_toupper [function]</a> </li><li><a href="#string-translate-function">string_translate [function]</a> </li><li><a href="#string-trim-function">string_trim [function]</a> </li><li><a href="#string-utf8-decode-function">string_utf8_decode [function]</a> </li><li><a href="#string-utf8-encode-function">string_utf8_encode [function]</a> </li><li><a href="#string-utf8-iterator-function">string_utf8_iterator [function]</a> </li><li><a href="#string-utf8-length-function">string_utf8_length [function]</a> </li><li><a href="#string-utf8-offset-function">string_utf8_offset [function]</a></li></ul></div> <div class='item'><a name='Included-tools'></a><hr><h2>Included tools</h2><h4>Executables</h4><ul><li><a href="#Virtual-Machine-sgsvm">Virtual Machine (sgsvm)</a> </li><li><a href="#Compiler-sgsc">Compiler (sgsc)</a> </li><li><a href="#Executable-generator-for-Windows-sgsexe">Executable generator for Windows (sgsexe)</a> </li><li><a href="#Language-test-application-sgstest">Language test application (sgstest)</a> </li><li><a href="#API-test-application-sgsapitest">API test application (sgsapitest)</a> </li><li><a href="#C-binding-compiler-test-application-sgscppbctest">C++ binding compiler test application (sgscppbctest)</a> </li><li><a href="#Lightweight-C-binding-test-application-sgscppbindtest">Lightweight C++ binding test application (sgscppbindtest)</a> </li><li><a href="#Multithreading-safety-test-application-mttest">Multithreading safety test application (mttest)</a></li></ul><h4>Extensions</h4><ul><li><a href="#Profiler">Profiler</a> </li><li><a href="#Interactive-debugger">Interactive debugger</a></li></ul></div> <div class='item'><a name='Virtual-Machine-sgsvm'></a><hr><h2>Virtual Machine (sgsvm)</h2><p> This is the default standalone environment for SGScript, useful for running scripts in a portable way. </p><h4>Command line syntax</h4><pre>sgsvm [files|options] sgsvm [options] -p|--program &lt;srcname&gt;[, &lt;arguments&gt;]</pre><h4>Options</h4><ul><li><code>-h</code>, <code>--help</code>: print help text, displaying command line syntax </li><li><code>-v</code>, <code>--version</code>: print version info </li><li><code>-s</code>, <code>--separate</code>: restart the engine between scripts </li><li><code>-d</code>, <code>--debug</code>: enable interactive debugging on errors </li><li><code>-p</code>, <code>--program</code>: translate the following arguments into a SGS program call </li><li><code>--stats</code>: print VM stats after running the scripts <ul><li>prints number of allocations, frees, memory blocks and size, object count, GC state </li></ul><li><code>--profile</code>: enable profiling by collecting call stack timings </li><li><code>--profile-ops</code>: enable low-level VM instruction profiling </li><li><code>--profile-mem</code>: enable memory usage profiling</li></ul><h4>Example usage</h4><ul><li><code>sgsvm -d -p appMain param=1</code> - run application <code>appMain</code> with debugging, passing argument &#39;param=1&#39; </li><li><code>sgsvm one.sgs two.sgs</code> - run file <code>one.sgs</code>, followed by <code>two.sgs</code>, in the same environment</li></ul><h4>Additional info</h4><ul><li>Program mode defines global <code>argc</code> and <code>argv</code> variables, generated from arguments after the flag. </li><li>It is possible to execute multiple files, this is so that environment could be prepared by one file and used by another one. </li><li>Profilers dump their data to standard output before freeing the engine (after end of each separately executed script or at the end of all scripts).</li></ul></div> <div class='item'><a name='Compiler-sgsc'></a><hr><h2>Compiler (sgsc)</h2><p> This is the standalone script compiler and instruction listing generator for SGScript. </p><h4>Command line syntax</h4><pre>sgsc [file|options]</pre><h4>Additional info</h4><ul><li><code>-h</code>: print help info </li><li><code>-c</code>: compile the file </li><li><code>-d</code>: dump bytecode to standard output </li><li><code>-o</code>: specify bytecode output file (default: remove .sgs on end, add .sgc)</li></ul><h4>Example usage</h4><ul><li><code>sgsc -c src.sgs</code> - compile <code>src.sgs</code> to <code>src.sgc</code> </li><li><code>sgsc -d src.sgs</code> - compile <code>src.sgs</code>, dump generated bytecode</li></ul></div> <div class='item'><a name='Executable-generator-for-Windows-sgsexe'></a><hr><h2>Executable generator for Windows (sgsexe)</h2><p> Utility to combine a single script with the virtual machine. After compilation, the executable passes all input arguments as-is as <code>argc</code> and <code>argv</code> to the script. </p><h4>Command line syntax</h4><pre>sgsexe &lt;output-file&gt; &lt;script-file&gt;</pre></div> <div class='item'><a name='Language-test-application-sgstest'></a><hr><h2>Language test application (sgstest)</h2><p> The application runs all test scripts in <code>./tests</code> directory. File handling rules are as follows: </p><ul><li>Ignore files with <code>!_</code> prefix. </li><li>Require compilation success for tests with <code>s_</code> prefix. </li><li>Require compilation failure for tests with <code>f_</code> prefix. </li><li>If there is no prefix, require that the system does not crash. </li><li>If a file name as <code>TF</code> in it, use the advanced testing framework. </li><li>Files are sorted according to the logical order of testing: requirements grow with test file number: <ul><li>first sort by whether testing framework (TF) is required (files that don&#39;t need it go first); </li><li>then sort by whether compilation success is required (files that do need it go first); </li><li>finally, sort by whether compilation state is expected (files that do need it go first);</li></ul></li></ul><p> The sort order broken down: </p><ul><li>1. <code>s_</code> tests without <code>TF</code> </li><li>2. <code>f_</code> tests without <code>TF</code> </li><li>3. tests without prefix and <code>TF</code> </li><li>4. <code>s_</code> tests with <code>TF</code> </li><li>5. <code>f_</code> tests with <code>TF</code> (none such tests exist because it would make no sense to have them) </li><li>6. tests without prefix but with <code>TF</code></li></ul><p> The application <code>sgstest</code> must be run from root, like so: <code>bin/sgstest</code>. It generates two log files: <code>./tests-errors.log</code> and <code>./tests-output.log</code>. </p></div> <div class='item'><a name='API-test-application-sgsapitest'></a><hr><h2>API test application (sgsapitest)</h2><p> This application tests the core programming interface. It generates two log files: <code>./apitests-errors.log</code> and <code>./apitests-output.log</code>. </p></div> <div class='item'><a name='C-binding-compiler-test-application-sgscppbctest'></a><hr><h2>C++ binding compiler test application (sgscppbctest)</h2><p> This application tests the C++ programming interface that utilizes the <a href="sgs.cppbc.docs.htm" target="_blank">binding compiler</a>. </p></div> <div class='item'><a name='Lightweight-C-binding-test-application-sgscppbindtest'></a><hr><h2>Lightweight C++ binding test application (sgscppbindtest)</h2><p> This application tests the C++ programming interface that utilizes the lightweight binding extension. </p></div> <div class='item'><a name='Multithreading-safety-test-application-mttest'></a><hr><h2>Multithreading safety test application (mttest)</h2><p> This application tests the SGScript engine&#39;s ability to work with more than one thread (different instances for each) at the same time. </p></div> <div class='item'><a name='Profiler'></a><hr><h2>Profiler</h2><p> This is an engine profiler hook extension. It supports three processing modes. </p><h4>Modes</h4><ul><li>Function timing profiler: use SGS_PROF_FUNCTIME to initialize </li><li>Instruction timing profiler: use SGS_PROF_OPTIME to initialize </li><li>Memory usage profiler: use SGS_PROF_MEMUSAGE to initialize</li></ul><h4>Functions</h4><ul><li>SGSBOOL sgs_ProfInit( SGS_CTX, SGS_PROF, int mode ) - initialize the profiler </li><li>SGSBOOL sgs_ProfClose( SGS_PROF ) - free the profiler </li><li>SGSBOOL sgs_ProfDump( SGS_PROF ) - dump the data</li></ul><h4>Usage example</h4><pre>sgs_Prof profiler; // keep this allocated while it is linked to engine // initialize and attach the profiler sgs_ProfInit( contextPtr, &amp;profiler, [SGS_PROF_FUNCTIME|SGS_PROF_OPTIME|SGS_PROF_MEMUSAGE] ); // ...do things with the engine... sgs_ProfDump( &amp;profiler ); // dump the data (done through @sgs_Write* functions) // free the profiler - must be done before freeing the engine sgs_ProfClose( &amp;profiler );</pre></div> <div class='item'><a name='Interactive-debugger'></a><hr><h2>Interactive debugger</h2><p> This is an engine debugging hook extension. It provides the opportunity to interactively introspect the engine state on each message (info/warning/error). </p><h4>Functions</h4><ul><li>int sgs_InitIDbg( SGS_CTX, SGS_IDBG ) - initialize the debugger </li><li>int sgs_CloseIDbg( SGS_CTX, SGS_IDBG ) - free the debugger</li></ul><h4>Usage example</h4><pre>sgs_IDbg debugger; // keep this allocated while it is linked to engine // initialize and attach the debugger sgs_InitIDbg( contextPtr, &amp;debugger ); // ...do things with the engine... // free the debugger sgs_CloseIDbg( contextPtr, &amp;debugger );</pre></div> <div class='item'><a name='Additional-info'></a><hr><h2>Additional info</h2></div> <div class='item'><a name='Serialization-in-SGScript'></a><hr><h2>Serialization in SGScript</h2><p> In SGScript, serialization is conversion to a binary stream of a specific format. Serialization in the language API is done by calling the &quot;<a href="#serialize-function">serialize</a>&quot; function and deserialization is done with &quot;<a href="#unserialize-function">unserialize</a>&quot;. The C API has similar functions: <a href="#sgs-Serialize-function">sgs_Serialize</a> / <a href="#sgs-SerializeObject-function">sgs_SerializeObject</a> and <a href="#sgs-Unserialize-function">sgs_Unserialize</a>, respectively. </p><p> <em class='notice-bgr'>check the &quot;Possible gotchas&quot; part of this page if it is intended to trust the end user with access to serialized data</em> </p><h4>The format</h4><ul><li>a list of operations </li><li>each operation consists of a &#39;type&#39; byte and additional data <ul><li>a &quot;push&quot; operation has the byte &#39;P&#39;, the data consists of the type to push (a byte consisting of one base flag from SGS_VT_*) and the binary data of the type </li><li>a &quot;call&quot; operation has the byte &#39;C&#39;, the data consists of the number of arguments (4 bytes), function name length (1 byte) and the null-terminated function name itself (&lt;length&gt;+1 bytes)</li></ul></li></ul><h4>Serialization</h4><ul><li>&quot;<a href="#serialize-function">serialize</a>&quot; is called </li><li>&quot;<a href="#sgs-Serialize-function">sgs_Serialize</a>&quot; is called internally </li><li>type of variable is determined and the data is written <ul><li>C functions cannot be serialized (obviously) and whenever encountered, will abort the action </li><li>objects will have SERIALIZE operation called <ul><li>if operation is not defined, everything will stop </li><li>if object is an array, all variables in it will be serialized using <a href="#sgs-Serialize-function">sgs_Serialize</a> and <a href="#sgs-SerializeObject-function">sgs_SerializeObject</a> will generate a call to &#39;array&#39; </li><li>if object is a &#39;dict&#39; or a &#39;map&#39;, all keys and values in it will be serialized using <a href="#sgs-Serialize-function">sgs_Serialize</a> and <a href="#sgs-SerializeObject-function">sgs_SerializeObject</a> will generate a call to &#39;dict&#39;</li></ul></li></ul></li></ul><h4>Deserialization</h4><ul><li>&quot;<a href="#unserialize-function">unserialize</a>&quot; is called <ul><li>the global environment could be changed </li></ul><li>&quot;<a href="#sgs-Unserialize-function">sgs_Unserialize</a>&quot; is called internally </li><li>&quot;push&quot; and &quot;call&quot; operations are executed, thus regenerating the data <ul><li>&quot;push&quot; operation pushes a variable on the stack </li><li>&quot;call&quot; operation calls the specified function</li></ul></li></ul><h4>Possible gotchas</h4><ul><li>unserialization is not by default safe in the sense that any function can be executed with a carefully crafted byte buffer; this can be prevented by specifying the second parameter to the &quot;unserialize&quot; function. the behavior can be reproduced with the C API but it will take a bit more effort or calling the &quot;unserialize&quot; function from it </li><li><a href="#sgs-Serialize-function">sgs_Serialize</a> overrides the output function so any output done via &quot;print&quot; or &quot;sgs_Write*&quot; functions during serialization will corrupt the stream </li><li>if environment overrides are used on deserialization, remember to add &quot;array&quot;, &quot;dict&quot; and &quot;map&quot; to the list if you use them, they are not added automatically </li><li>serialization will not preserve any variable reuse relationships so after deserialization the structure could use more memory than before; if more efficient behavior is desired, it is suggested to serialize an array of unique items and a structure of indices to those items</li></ul></div> <div class='item'><a name='Secure-sandbox-environment'></a><hr><h2>Secure sandbox environment</h2><p> To ensure safety of the underlying environment, there are functions that need to be protected or disabled. </p><h3>Critical (access to file system, possibility of taking control of the machine):</h3><ul><li>core functions: <ul><li><a href="#include-library-function">include_library</a> - access to file system, can load other libraries </li><li><a href="#include-shared-function">include_shared</a> - access to file system, can run some library code </li><li><a href="#include-file-function">include_file</a> - access to file system, can run script files </li><li><a href="#include-function">include</a> - access to file system, can load other libraries, can run script files or some library code </li><li><a href="#import-cfunc-function">import_cfunc</a> - access to file system, can run some library code </li><li><a href="#eval-file-function">eval_file</a> - access to file system, can run script files </li></ul><li><a href="#I-O-library-io">All functions in I/O library</a> - access to file system </li><li><a href="#OS-library-os">OS library</a>: <ul><li><a href="#os-command-function">os_command</a> - can run any terminal command</li></ul></li></ul><h3>Information control (access to data about the system</h3><ul><li><a href="#OS-library-os">Most functions in OS library</a> - access to environment variables, system date/time info / process locale info. </li><li>core functions: <ul><li><a href="#printvar-function">printvar</a>, <a href="#printvar-ext-function">printvar_ext</a>, <a href="#dumpvar-function">dumpvar</a>, <a href="#dumpvar-ext-function">dumpvar_ext</a>, <a href="#sys-stat-function">sys_stat</a>, <a href="#toptr-function">toptr</a> - access to memory layout of engine objects</li></ul></li></ul><h3>Sandbox example</h3><pre>restrict = function( name ) { println( &quot;==\n= The use of &#39;&quot; $ name $ &quot;&#39; is restricted!\n==&quot; ); }; closure = function( clbl, data ) { return function() use( clbl, data ) { args = va_get_args(); args.unshift( data ); sys_apply( clbl, this, args ); }; }; safe_include_lib = function( data, libname ) { libname = tostring( libname ); if( [&quot;string&quot;,&quot;math&quot;,&quot;re&quot;,&quot;fmt&quot;,&quot;os&quot;].find( libname ) === null ) { println( &quot;info: cannot include files and system access libraries here&quot; ); return; } data( libname ); if( libname == &quot;os&quot; ) { unset( _G, &quot;os_command&quot; ); unset( _G, &quot;os_getenv&quot; ); unset( _G, &quot;os_putenv&quot; ); } }; safe_include = function( libname ) { return include_library( libname ); }; global include_library = closure( safe_include_lib, include_library ); global include = safe_include; global include_shared = closure( restrict, &quot;include_shared&quot; ); global import_cfunc = closure( restrict, &quot;import_cfunc&quot; ); global include_file = closure( restrict, &quot;include_file&quot; ); global eval_file = closure( restrict, &quot;eval_file&quot; ); include &quot;string&quot;, &quot;math&quot;, &quot;re&quot;, &quot;fmt&quot;, &quot;os&quot;;</pre></div> </div> </body></html> <file_sep>/src/sgs_bcg.c #define SGS_INTERNAL #define SGS_REALLY_INTERNAL #include "sgs_int.h" static int is_keyword( TokenList tok, const char* text ) { return *tok == ST_KEYWORD && tok[ 1 ] == strlen( text ) && strncmp( (const char*) tok + 2, text, tok[ 1 ] ) == 0; } #define over_limit( x, lim ) ((x)>(lim)||(x)<(-lim)) /* register allocation */ static SGS_INLINE rcpos_t comp_reg_alloc( SGS_CTX ) { rcpos_t out = C->fctx->regs++; if( out > 0xff ) { C->state |= SGS_HAS_ERRORS | SGS_MUST_STOP; sgs_Msg( C, SGS_ERROR, "Max. register count exceeded" ); } return out; } static SGS_INLINE rcpos_t comp_reg_alloc_n( SGS_CTX, int n ) { rcpos_t out; sgs_BreakIf( n < 1 ); out = comp_reg_alloc( C ); n--; while( n --> 0 ) { if( HAS_FLAG( C->state, SGS_MUST_STOP ) ) break; comp_reg_alloc( C ); } return out; } static SGS_INLINE void comp_reg_unwind( SGS_CTX, rcpos_t pos ) { if( C->fctx->regs > C->fctx->lastreg ) C->fctx->lastreg = C->fctx->regs; C->fctx->regs = pos; } static sgs_CompFunc* make_compfunc( SGS_CTX ) { sgs_CompFunc* func = sgs_Alloc( sgs_CompFunc ); func->consts = membuf_create(); func->code = membuf_create(); func->lnbuf = membuf_create(); func->gotthis = FALSE; func->numargs = 0; func->numtmp = 0; func->numclsr = 0; return func; } static void fctx_binfo_add( SGS_CTX, sgs_FuncCtx* fctx, uint32_t ioff, uint16_t loop, uint8_t iscont ) { sgs_BreakInfo* binfo = sgs_Alloc( sgs_BreakInfo ); binfo->jdoff = ioff; binfo->numlp = loop; binfo->iscont = iscont; binfo->next = fctx->binfo; fctx->binfo = binfo; } static void fctx_binfo_rem( SGS_CTX, sgs_FuncCtx* fctx, sgs_BreakInfo* prev ) { sgs_BreakInfo* pn; if( prev ) { pn = prev->next; prev->next = prev->next->next; sgs_Dealloc( pn ); } else { pn = fctx->binfo; fctx->binfo = fctx->binfo->next; sgs_Dealloc( pn ); } } static sgs_FuncCtx* fctx_create( SGS_CTX ) { sgs_FuncCtx* fctx = sgs_Alloc( sgs_FuncCtx ); fctx->func = TRUE; fctx->regs = 0; fctx->lastreg = -1; fctx->vars = membuf_create(); fctx->gvars = membuf_create(); fctx->clsr = membuf_create(); fctx->inclsr = 0; fctx->outclsr = 0; fctx->loops = 0; fctx->binfo = NULL; membuf_appbuf( &fctx->gvars, C, "_G=", 3 ); return fctx; } static void fctx_destroy( SGS_CTX, sgs_FuncCtx* fctx ) { while( fctx->binfo ) fctx_binfo_rem( C, fctx, NULL ); membuf_destroy( &fctx->vars, C ); membuf_destroy( &fctx->gvars, C ); membuf_destroy( &fctx->clsr, C ); sgs_Dealloc( fctx ); } #if SGS_DUMP_BYTECODE || ( SGS_DEBUG && SGS_DEBUG_DATA ) static void fctx_dumpvarlist( MemBuf* mb ) { char* p = mb->ptr, *pend = mb->ptr + mb->size; while( p < pend ) { if( *p == '=' ) { if( p < pend - 1 ) printf( ", " ); } else putchar( *p ); p++; } } static void fctx_dump( sgs_FuncCtx* fctx ) { printf( "Type: %s\n", fctx->func ? "Function" : "Main code" ); printf( "Globals: " ); fctx_dumpvarlist( &fctx->gvars ); printf( "\n" ); printf( "Variables: " ); fctx_dumpvarlist( &fctx->vars ); printf( "\n" ); printf( "Closures in=%d out=%d : ", fctx->inclsr, fctx->outclsr ); fctx_dumpvarlist( &fctx->clsr ); printf( "\n" ); } #endif static void dump_rcpos( int arg ) { char rc = CONSTVAR( arg ) ? 'C' : 'R'; arg = CONSTDEC( arg ); printf( "%c%d", rc, arg ); } static void dump_opcode_a( const char* name, instr_t I ) { printf( "%s R%"PRId32" <= ", name, INSTR_GET_A( I ) ); dump_rcpos( INSTR_GET_B( I ) ); printf( ", " ); dump_rcpos( INSTR_GET_C( I ) ); } static void dump_opcode_b( const char* name, instr_t I ) { printf( "%s R%"PRId32" <= ", name, INSTR_GET_A( I ) ); dump_rcpos( INSTR_GET_B( I ) ); } static void dump_opcode_b1( const char* name, instr_t I ) { printf( "%s ", name ); dump_rcpos( INSTR_GET_B( I ) ); printf( " <= " ); dump_rcpos( INSTR_GET_C( I ) ); } static void dump_opcode( const instr_t* ptr, size_t count ) { const instr_t* pend = ptr + count; const instr_t* pbeg = ptr; while( ptr < pend ) { instr_t I = *ptr++; int op = INSTR_GET_OP( I ), argA = INSTR_GET_A( I ), argB = INSTR_GET_B( I ), argC = INSTR_GET_C( I ), argE = INSTR_GET_E( I ); printf( "\t%04d | ", (int)( ptr - pbeg - 1 ) ); switch( op ) { #define DOP_A( wat ) case SI_##wat: dump_opcode_a( #wat, I ); break; #define DOP_B( wat ) case SI_##wat: dump_opcode_b( #wat, I ); break; case SI_NOP: printf( "NOP " ); break; case SI_PUSH: printf( "PUSH " ); dump_rcpos( argB ); break; case SI_INT: printf( "INT %d", argC ); break; case SI_RETN: printf( "RETURN %d", argA ); break; case SI_JUMP: printf( "JUMP %d", (int) (int16_t) argE ); break; case SI_JMPT: printf( "JMP_T " ); dump_rcpos( argC ); printf( ", %d", (int) (int16_t) argE ); break; case SI_JMPF: printf( "JMP_F " ); dump_rcpos( argC ); printf( ", %d", (int) (int16_t) argE ); break; case SI_CALL: printf( "CALL args: %d - %d expect: %d%s", argB & 0xff, argC, argA, ( argB & 0x100 ) ? ", method" : "" ); break; case SI_FORPREP: printf( "FOR_PREP " ); dump_rcpos( argA ); printf( " <= " ); dump_rcpos( argB ); break; case SI_FORLOAD: printf( "FOR_LOAD " ); dump_rcpos( argA ); printf( " => " ); dump_rcpos( argB ); printf( ", " ); dump_rcpos( argC ); break; case SI_FORJUMP: printf( "FOR_JUMP " ); dump_rcpos( argC ); printf( ", %d", (int) (int16_t) argE ); break; case SI_LOADCONST: printf( "LOADCONST " ); dump_rcpos( argC ); printf( " <= C%d", argE ); break; DOP_B( GETVAR ); case SI_SETVAR: dump_opcode_b1( "SETVAR", I ); break; DOP_A( GETPROP ); DOP_A( SETPROP ); DOP_A( GETINDEX ); DOP_A( SETINDEX ); case SI_GENCLSR: printf( "GEN_CLSR %d", argA ); break; case SI_PUSHCLSR: printf( "PUSH_CLSR %d", argA ); break; case SI_MAKECLSR: printf( "MAKE_CLSR " ); dump_rcpos( argA ); printf( " <= " ); dump_rcpos( argB ); printf( " [%d]", argC ); break; case SI_GETCLSR: printf( "GET_CLSR " ); dump_rcpos( argA ); printf( " <= CL%d", argB ); break; case SI_SETCLSR: printf( "SET_CLSR CL%d <= ", argB ); dump_rcpos( argC ); break; DOP_B( SET ); case SI_MCONCAT: printf( "MCONCAT " ); dump_rcpos( argA ); printf( " [%d]", argB ); break; DOP_A( CONCAT ); DOP_B( NEGATE ); DOP_B( BOOL_INV ); DOP_B( INVERT ); DOP_B( INC ); DOP_B( DEC ); DOP_A( ADD ); DOP_A( SUB ); DOP_A( MUL ); DOP_A( DIV ); DOP_A( MOD ); DOP_A( AND ); DOP_A( OR ); DOP_A( XOR ); DOP_A( LSH ); DOP_A( RSH ); DOP_A( SEQ ); DOP_A( EQ ); DOP_A( LT ); DOP_A( LTE ); DOP_A( SNEQ ); DOP_A( NEQ ); DOP_A( GT ); DOP_A( GTE ); DOP_A( RAWCMP ); #undef DOP_A #undef DOP_B case SI_ARRAY: printf( "ARRAY args:%d output:", argB ); dump_rcpos( argA ); break; case SI_DICT: printf( "DICT args:%d output:", argB ); dump_rcpos( argA ); break; default: printf( "<error> \t\t(op=%d A=%d B=%d C=%d E=%d)", op, argA, argB, argC, argE ); break; } printf( "\n" ); } } static int find_var( MemBuf* S, char* str, unsigned len ) { char* ptr = S->ptr; char* pend = ptr + S->size; const char* cstr = str; int difs = 0, at = 0; unsigned left = len; while( ptr < pend ) { if( *ptr == '=' ) { if( difs == 0 && !left ) return at; difs = 0; cstr = str; left = len; ptr++; at++; } else { difs += abs( *cstr - *ptr ); ptr += *ptr != '='; cstr += ( left -= 1 ) > 0; } } return -1; } static int find_nth_var( MemBuf* S, int which, char** outstr, unsigned* outlen ) { char* ptr = S->ptr; char* pend = ptr + S->size; while( which > 0 ) { while( ptr < pend && *ptr != '=' ) ptr++; ptr++; which--; } if( ptr >= pend ) return 0; *outstr = ptr; while( ptr < pend && *ptr != '=' ) ptr++; /* WP: ptr always bigger or equal to *outstr, difference cannot exceed 255 */ *outlen = (unsigned) ( ptr - *outstr ); return 1; } static int add_var( MemBuf* S, SGS_CTX, char* str, unsigned len ) { int pos = find_var( S, str, len ); if( pos < 0 ) { membuf_appbuf( S, C, str, len ); membuf_appchr( S, C, '=' ); return TRUE; } return FALSE; } #define find_varT( S, tok ) \ find_var( S, (char*) (tok) + 2, tok[1] ) #define add_varT( S, C, tok ) \ add_var( S, C, (char*) (tok) + 2, tok[1] ) static int preadd_thisvar( MemBuf* S, SGS_CTX ) { int pos = find_var( S, "this", 4 ); if( pos < 0 ) { membuf_insbuf( S, C, 0, "this=", 5 ); return TRUE; } return FALSE; } /* simplifies writing code */ static void add_instr( sgs_CompFunc* func, SGS_CTX, FTNode* node, instr_t I ) { sgs_LineNum ln = sgsT_LineNum( node->token ); membuf_appbuf( &func->lnbuf, C, &ln, sizeof( ln ) ); membuf_appbuf( &func->code, C, &I, sizeof( I ) ); } #define INSTR_N( i, n ) add_instr( func, C, n, i ) #define INSTR( i ) INSTR_N( i, node ) #define INSTR_WRITE( op, a, b, c ) INSTR( INSTR_MAKE( op, a, b, c ) ) #define INSTR_WRITE_EX( op, ex, c ) INSTR( INSTR_MAKE_EX( op, ex, c ) ) #define INSTR_WRITE_PCH() INSTR_WRITE( 63, 0, 0, 0 ) #define QPRINT( str ) sgs_Msg( C, SGS_ERROR, "[line %d] " str, sgsT_LineNum( node->token ) ) static int preparse_varlists( SGS_CTX, sgs_CompFunc* func, FTNode* node ); static int preparse_varlist( SGS_CTX, sgs_CompFunc* func, FTNode* node ) { int ret = TRUE; node = node->child; while( node ) { if( node->type != SFT_IDENT && node->type != SFT_KEYWORD && node->type != SFT_ARGMT ) goto cont; /* compatibility with explists */ if( find_varT( &C->fctx->clsr, node->token ) >= 0 ) goto cont; /* closure */ if( find_varT( &C->fctx->gvars, node->token ) >= 0 ) { QPRINT( "Variable storage redefined: global -> local" ); return FALSE; } if( add_varT( &C->fctx->vars, C, node->token ) ) comp_reg_alloc( C ); if( node->child ) ret &= preparse_varlists( C, func, node ); cont: node = node->next; } return ret; } static int preparse_gvlist( SGS_CTX, sgs_CompFunc* func, FTNode* node ) { int ret = TRUE; node = node->child; while( node ) { if( find_varT( &C->fctx->clsr, node->token ) >= 0 ) { QPRINT( "Variable storage redefined: closure -> global" ); return FALSE; } if( find_varT( &C->fctx->vars, node->token ) >= 0 ) { QPRINT( "Variable storage redefined: local -> global" ); return FALSE; } add_varT( &C->fctx->gvars, C, node->token ); if( node->child ) ret &= preparse_varlists( C, func, node ); node = node->next; } return ret; } static int preparse_varlists( SGS_CTX, sgs_CompFunc* func, FTNode* node ) { int ret = 1; if( node->type == SFT_VARLIST ) ret &= preparse_varlist( C, func, node ); else if( node->type == SFT_GVLIST ) ret &= preparse_gvlist( C, func, node ); else if( node->type == SFT_KEYWORD && node->token && is_keyword( node->token, "this" ) ) { func->gotthis = TRUE; if( preadd_thisvar( &C->fctx->vars, C ) ) comp_reg_alloc( C ); } else if( node->type == SFT_OPER ) { if( ST_OP_ASSIGN( *node->token ) && node->child ) { if( node->child->type == SFT_IDENT ) { /* add_var calls find_var internally but - GVARS vs VARS - note the difference */ if( find_varT( &C->fctx->gvars, node->child->token ) == -1 && find_varT( &C->fctx->clsr, node->child->token ) == -1 && add_varT( &C->fctx->vars, C, node->child->token ) ) comp_reg_alloc( C ); } if( node->child->type == SFT_EXPLIST ) ret &= preparse_varlist( C, func, node->child ); } ret &= preparse_varlists( C, func, node->child ); } else if( node->type == SFT_FOREACH ) { if( find_varT( &C->fctx->gvars, node->token ) >= 0 ) { QPRINT( "Variable storage redefined (foreach key variable cannot be global): global -> local" ); ret = FALSE; } else { if( node->child->type != SFT_NULL && add_varT( &C->fctx->vars, C, node->child->token ) ) comp_reg_alloc( C ); if( node->child->next->type != SFT_NULL && add_varT( &C->fctx->vars, C, node->child->next->token ) ) comp_reg_alloc( C ); } ret &= preparse_varlists( C, func, node->child->next ); } else if( node->type == SFT_FUNC ) { FTNode* N = node->child->next->next->next; if( N && N->type == SFT_IDENT ) { if( find_varT( &C->fctx->gvars, N->token ) == -1 && /* if the variable hasn't been .. */ find_varT( &C->fctx->clsr, N->token ) == -1 && /* .. created before */ /* if it was successfully added */ add_varT( C->fctx->func ? &C->fctx->vars : &C->fctx->gvars, C, N->token ) && C->fctx->func ) /* and if it was added as a local variable */ comp_reg_alloc( C ); /* add a register for it */ } } else if( node->child ) ret &= preparse_varlists( C, func, node->child ); if( node->next ) ret &= preparse_varlists( C, func, node->next ); return ret; } static int preparse_closures( SGS_CTX, sgs_CompFunc* func, FTNode* node, int decl ) { int ret; node = node->child; while( node ) { ret = add_varT( &C->fctx->clsr, C, node->token ); if( !ret && decl ) { QPRINT( "Cannot redeclare used variables with the same name" ); return 0; } if( ret ) { C->fctx->outclsr++; if( decl ) C->fctx->inclsr++; } node = node->next; } return 1; } static int preparse_clsrlists( SGS_CTX, sgs_CompFunc* func, FTNode* node ) { int ret = 1; if( node->type == SFT_FUNC ) ret &= preparse_closures( C, func, node->child->next, 0 ); else if( node->child ) ret &= preparse_clsrlists( C, func, node->child ); if( node->next ) ret &= preparse_clsrlists( C, func, node->next ); return ret; } static int preparse_arglist( SGS_CTX, sgs_CompFunc* func, FTNode* node ) { node = node->child; while( node ) { if( func->numargs == 255 ) { QPRINT( "Argument count exceeded (max. 255 arguments)" ); return 0; } if( !add_var( &C->fctx->vars, C, (char*) node->token + 2, node->token[ 1 ] ) ) { QPRINT( "Cannot redeclare arguments with the same name" ); return 0; } comp_reg_alloc( C ); func->numargs++; node = node->next; } return 1; } #define add_const_HDR \ sgs_Variable* vbeg = (sgs_Variable*) (void*) ASSUME_ALIGNED( func->consts.ptr, 4 ); \ sgs_Variable* vend = (sgs_Variable*) (void*) ASSUME_ALIGNED( func->consts.ptr + func->consts.size, 4 ); \ sgs_Variable* var = vbeg; \ sgs_Variable nvar; static rcpos_t add_const_null( SGS_CTX, sgs_CompFunc* func ) { add_const_HDR; while( var < vend ) { if( var->type == SGS_VT_NULL ) return (rcpos_t) ( var - vbeg ); /* WP: const limit */ var++; } nvar.type = SGS_VT_NULL; membuf_appbuf( &func->consts, C, &nvar, sizeof( nvar ) ); return (rcpos_t) ( vend - vbeg ); /* WP: const limit */ } static rcpos_t add_const_b( SGS_CTX, sgs_CompFunc* func, sgs_Bool bval ) { add_const_HDR; while( var < vend ) { if( var->type == SGS_VT_BOOL && var->data.B == bval ) return (rcpos_t) ( var - vbeg ); /* WP: const limit */ var++; } nvar.type = SGS_VT_BOOL; nvar.data.B = bval; membuf_appbuf( &func->consts, C, &nvar, sizeof( nvar ) ); return (rcpos_t) ( vend - vbeg ); /* WP: const limit */ } static rcpos_t add_const_i( SGS_CTX, sgs_CompFunc* func, sgs_Int ival ) { add_const_HDR; while( var < vend ) { if( var->type == SGS_VT_INT && var->data.I == ival ) return (rcpos_t) ( var - vbeg ); /* WP: const limit */ var++; } nvar.type = SGS_VT_INT; nvar.data.I = ival; membuf_appbuf( &func->consts, C, &nvar, sizeof( nvar ) ); return (rcpos_t) ( vend - vbeg ); /* WP: const limit */ } static rcpos_t add_const_r( SGS_CTX, sgs_CompFunc* func, sgs_Real rval ) { add_const_HDR; while( var < vend ) { if( var->type == SGS_VT_REAL && var->data.R == rval ) return (rcpos_t) ( var - vbeg ); /* WP: const limit */ var++; } nvar.type = SGS_VT_REAL; nvar.data.R = rval; membuf_appbuf( &func->consts, C, &nvar, sizeof( nvar ) ); return (rcpos_t) ( vend - vbeg ); /* WP: const limit */ } static rcpos_t add_const_s( SGS_CTX, sgs_CompFunc* func, uint32_t len, const char* str ) { add_const_HDR; while( var < vend ) { if( var->type == SGS_VT_STRING && var->data.S->size == len && memcmp( var_cstr( var ), str, len ) == 0 ) return (rcpos_t) ( var - vbeg ); /* WP: const limit */ var++; } sgs_BreakIf( len > 0x7fffffff ); sgsVM_VarCreateString( C, &nvar, str, (int32_t) len ); membuf_appbuf( &func->consts, C, &nvar, sizeof( nvar ) ); return (rcpos_t) ( vend - vbeg ); /* WP: const limit */ } static rcpos_t add_const_f( SGS_CTX, sgs_CompFunc* func, sgs_CompFunc* nf, const char* funcname, size_t fnsize, LineNum lnum ) { sgs_Variable nvar; rcpos_t pos; func_t* F = sgs_Alloc_a( func_t, nf->consts.size + nf->code.size ); F->refcount = 1; /* WP: const/instruction limits */ F->size = (uint32_t) ( nf->consts.size + nf->code.size ); F->instr_off = (uint32_t) nf->consts.size; F->gotthis = nf->gotthis; F->numargs = nf->numargs; F->numtmp = nf->numtmp; F->numclsr = nf->numclsr; { size_t lnc = nf->lnbuf.size / sizeof( sgs_LineNum ); F->lineinfo = sgs_Alloc_n( sgs_LineNum, lnc ); memcpy( F->lineinfo, nf->lnbuf.ptr, nf->lnbuf.size ); } F->funcname = membuf_create(); if( funcname ) membuf_setstrbuf( &F->funcname, C, funcname, fnsize ); F->linenum = lnum; F->filename = membuf_create(); if( C->filename ) membuf_setstr( &F->filename, C, C->filename ); memcpy( func_consts( F ), nf->consts.ptr, nf->consts.size ); memcpy( func_bytecode( F ), nf->code.ptr, nf->code.size ); membuf_destroy( &nf->consts, C ); membuf_destroy( &nf->code, C ); membuf_destroy( &nf->lnbuf, C ); sgs_Dealloc( nf ); /* WP: const limit */ pos = (rcpos_t) ( func->consts.size / sizeof( nvar ) ); nvar.type = SGS_VT_FUNC; nvar.data.F = F; membuf_appbuf( &func->consts, C, &nvar, sizeof( nvar ) ); return pos; } #define INTERNAL_ERROR( loff ) sgs_Msg( C, SGS_ERROR, "INTERNAL ERROR occured in file %s [%d]", __FILE__, __LINE__ - (loff) ) static int op_pick_opcode( int oper, int binary ) { if( !binary ) { if( oper == ST_OP_ADD ) return 0; if( oper == ST_OP_SUB ) return SI_NEGATE; if( oper == ST_OP_NOT ) return SI_BOOL_INV; if( oper == ST_OP_INV ) return SI_INVERT; } switch( oper ) { case ST_OP_ADD: case ST_OP_ADDEQ: return SI_ADD; case ST_OP_SUB: case ST_OP_SUBEQ: return SI_SUB; case ST_OP_MUL: case ST_OP_MULEQ: return SI_MUL; case ST_OP_DIV: case ST_OP_DIVEQ: return SI_DIV; case ST_OP_MOD: case ST_OP_MODEQ: return SI_MOD; case ST_OP_AND: case ST_OP_ANDEQ: return SI_AND; case ST_OP_OR: case ST_OP_OREQ: return SI_OR; case ST_OP_XOR: case ST_OP_XOREQ: return SI_XOR; case ST_OP_LSH: case ST_OP_LSHEQ: return SI_LSH; case ST_OP_RSH: case ST_OP_RSHEQ: return SI_RSH; case ST_OP_CAT: case ST_OP_CATEQ: return SI_CONCAT; case ST_OP_SEQ: return SI_SEQ; case ST_OP_SNEQ: return SI_SNEQ; case ST_OP_EQ: return SI_EQ; case ST_OP_NEQ: return SI_NEQ; case ST_OP_LESS: return SI_LT; case ST_OP_LEQ: return SI_LTE; case ST_OP_GRTR: return SI_GT; case ST_OP_GEQ: return SI_GTE; case ST_OP_RWCMP: return SI_RAWCMP; default: return 0; } } static SGSBOOL compile_node( SGS_CTX, sgs_CompFunc* func, FTNode* node ); static SGSBOOL compile_node_r( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* out ); static SGSBOOL compile_node_w( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t src ); static SGSBOOL compile_node_rrw( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t dst ); static SGSBOOL compile_oper( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* arg, int out, int expect ); static rcpos_t const_maybeload( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t cid ) { if( cid > 65535 ) { QPRINT( "Maximum number of constants exceeded" ); C->state |= SGS_MUST_STOP; return 0; } if( cid < 256 ) return CONSTENC( cid ); else { rcpos_t out = comp_reg_alloc( C ); INSTR_WRITE_EX( SI_LOADCONST, cid, out ); return out; } } #define BC_CONSTENC( cid ) const_maybeload( C, func, node, cid ) static void compile_ident( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* out ) { rcpos_t pos = add_const_s( C, func, node->token[ 1 ], (const char*) node->token + 2 ); *out = BC_CONSTENC( pos ); } static SGSBOOL compile_ident_r( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* out ) { rcpos_t pos; if( is_keyword( node->token, "null" ) ) { pos = add_const_null( C, func ); *out = BC_CONSTENC( pos ); return 1; } if( is_keyword( node->token, "true" ) ) { pos = add_const_b( C, func, TRUE ); *out = BC_CONSTENC( pos ); return 1; } if( is_keyword( node->token, "false" ) ) { pos = add_const_b( C, func, FALSE ); *out = BC_CONSTENC( pos ); return 1; } if( *node->token == ST_KEYWORD ) { if( is_keyword( node->token, "this" ) ) { if( func->gotthis ) { *out = 0; return 1; } else { QPRINT( "This function is not a method, cannot use 'this'" ); return 0; } } QPRINT( "Cannot read from specified keyword" ); return 0; } /* closures */ if( ( pos = find_var( &C->fctx->clsr, (char*) node->token + 2, node->token[1] ) ) >= 0 ) { *out = comp_reg_alloc( C ); INSTR_WRITE( SI_GETCLSR, *out, pos, 0 ); return 1; } if( C->fctx->func ) { rcpos_t gpos = find_var( &C->fctx->gvars, (char*) node->token + 2, node->token[ 1 ] ); if( gpos >= 0 ) pos = -1; else { pos = find_var( &C->fctx->vars, (char*) node->token + 2, node->token[ 1 ] ); if( pos < 0 ) pos = -1; /* read from globals by default */ } } else { pos = find_var( &C->fctx->vars, (char*) node->token + 2, node->token[ 1 ] ); } if( pos >= 0 ) { *out = pos; } else { *out = comp_reg_alloc( C ); compile_ident( C, func, node, &pos ); INSTR_WRITE( SI_GETVAR, *out, pos, 0 ); } return 1; } static SGSBOOL compile_ident_w( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t src ) { rcpos_t pos; if( *node->token == ST_KEYWORD ) { QPRINT( "Cannot write to reserved keywords" ); return 0; } if( ( pos = find_var( &C->fctx->clsr, (char*) node->token + 2, node->token[1] ) ) >= 0 ) { INSTR_WRITE( SI_SETCLSR, 0, pos, src ); return 1; } if( C->fctx->func ) { rcpos_t gpos = find_var( &C->fctx->gvars, (char*) node->token + 2, node->token[ 1 ] ); if( gpos >= 0 ) pos = -1; else { add_var( &C->fctx->vars, C, (char*) node->token + 2, node->token[ 1 ] ); pos = find_var( &C->fctx->vars, (char*) node->token + 2, node->token[ 1 ] ); } } else { pos = find_var( &C->fctx->vars, (char*) node->token + 2, node->token[ 1 ] ); } if( pos >= 0 ) { /* optimization */ if( pos != src ) { INSTR_WRITE( SI_SET, pos, src, 0 ); } } else { compile_ident( C, func, node, &pos ); INSTR_WRITE( SI_SETVAR, 0, pos, src ); } return 1; } static SGSBOOL compile_const( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* opos ) { if( *node->token == ST_NUMINT ) { sgs_Int val; AS_INTEGER( val, node->token + 1 ); *opos = BC_CONSTENC( add_const_i( C, func, val ) ); } else if( *node->token == ST_NUMREAL ) { sgs_Real val; AS_REAL( val, node->token + 1 ); *opos = BC_CONSTENC( add_const_r( C, func, val ) ); } else if( *node->token == ST_STRING ) { uint32_t val; AS_UINT32( val, node->token + 1 ); *opos = BC_CONSTENC( add_const_s( C, func, val, (const char*) node->token + 5 ) ); } else { QPRINT( "INTERNAL ERROR: constant doesn't have a token of type int/real/string attached" ); return 0; } return 1; } static SGSBOOL compile_regcopy( SGS_CTX, sgs_CompFunc* func, FTNode* node, size_t from, rcpos_t srcpos, rcpos_t dstpos ) { INSTR_WRITE( SI_SET, dstpos, srcpos, 0 ); return 1; } static SGSBOOL compile_fcall( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* out, int expect ) { int i = 0, gotthis = 0; /* IF (ternary-like) */ if( is_keyword( node->child->token, "if" ) ) { FTNode* n = node->child->next->child; int argc = 0; size_t csz1, csz2, csz3; rcpos_t exprpos = -1, srcpos = -1, retpos = -1; if( expect > 1 ) { QPRINT( "'if' pseudo-function cannot be used as input for expression writes with multiple outputs" ); return 0; } while( n ) { argc++; n = n->next; } if( argc != 3 ) { QPRINT( "'if' pseudo-function requires exactly 3 arguments" ); return 0; } if( expect ) retpos = comp_reg_alloc( C ); n = node->child->next->child; FUNC_ENTER; if( !compile_node_r( C, func, n, &exprpos ) || exprpos < 0 ) return 0; n = n->next; INSTR_WRITE_PCH(); csz1 = func->code.size; if( !compile_node_r( C, func, n, &srcpos ) || !compile_regcopy( C, func, n, csz1, srcpos, retpos ) ) return 0; n = n->next; INSTR_WRITE_PCH(); csz2 = func->code.size; if( !compile_node_r( C, func, n, &srcpos ) || !compile_regcopy( C, func, n, csz2, srcpos, retpos ) ) return 0; csz3 = func->code.size; INSTR_WRITE_EX( SI_NOP, 0, 0 ); /* harmful optimization prevention hack */ { uint32_t instr1, instr2; instr1 = INSTR_MAKE_EX( SI_JMPF, ( csz2 - csz1 ) / INSTR_SIZE, exprpos ); instr2 = INSTR_MAKE_EX( SI_JUMP, ( csz3 - csz2 ) / INSTR_SIZE, 0 ); memcpy( func->code.ptr + csz1 - 4, &instr1, sizeof(instr1) ); memcpy( func->code.ptr + csz2 - 4, &instr2, sizeof(instr2) ); } *out = retpos; return 1; } else { FTNode* n; int regc = 0; rcpos_t argpos, funcpos; /* count the required number of registers */ if( node->child->type == SFT_OPER && ( *node->child->token == ST_OP_MMBR || *node->child->token == ST_OP_NOT ) ) { gotthis = 1; regc++; } n = node->child->next->child; while( n ) { regc++; n = n->next; } regc++; /* function register */ if( out && regc < expect ) regc = expect; argpos = comp_reg_alloc_n( C, regc ); funcpos = argpos + regc - 1; /* return register positions for expected data */ if( out ) *out = argpos; /* load function (for properties, object too) */ if( node->child->type == SFT_OPER && ( *node->child->token == ST_OP_MMBR || *node->child->token == ST_OP_NOT ) ) { /* object pos. (this) = argpos + 0 */ FTNode* ncc = node->child->child; rcpos_t proppos = -1; FUNC_ENTER; if( !compile_node_rrw( C, func, ncc, argpos ) ) return 0; if( *node->child->token == ST_OP_MMBR ) { if( ncc->next->type == SFT_IDENT ) compile_ident( C, func, ncc->next, &proppos ); else { FUNC_ENTER; if( !compile_node_r( C, func, ncc->next, &proppos ) ) return 0; } INSTR_WRITE( SI_GETPROP, funcpos, argpos, proppos ); } else { FUNC_ENTER; if( !compile_node_rrw( C, func, ncc->next, funcpos ) ) return 0; } } else { FUNC_ENTER; if( !compile_node_rrw( C, func, node->child, funcpos ) ) return 0; } /* load arguments */ i = 0; { /* passing objects where the call is formed appropriately */ n = node->child->next->child; while( n ) { FUNC_ENTER; if( !compile_node_rrw( C, func, n, argpos + i + gotthis ) ) return 0; i++; n = n->next; } } /* compile call */ INSTR_WRITE( SI_CALL, expect, gotthis ? argpos | 0x100 : argpos, funcpos ); comp_reg_unwind( C, argpos + expect ); return 1; } } static SGSBOOL compile_index_r( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* out ) { rcpos_t var, name, opos = comp_reg_alloc( C ); rcpos_t regpos = C->fctx->regs; FUNC_ENTER; if( !compile_node_r( C, func, node->child, &var ) ) return 0; FUNC_ENTER; if( !compile_node_r( C, func, node->child->next, &name ) ) return 0; INSTR_WRITE( SI_GETINDEX, opos, var, name ); comp_reg_unwind( C, regpos ); if( out ) *out = opos; return 1; } static SGSBOOL compile_index_w( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t src ) { rcpos_t var, name; rcpos_t regpos = C->fctx->regs; FUNC_ENTER; if( !compile_node_r( C, func, node->child, &var ) ) return 0; FUNC_ENTER; if( !compile_node_r( C, func, node->child->next, &name ) ) return 0; if( CONSTVAR( var ) ) { QPRINT( "Cannot set indexed value of a constant" ); return 0; } INSTR_WRITE( SI_SETINDEX, var, name, src ); comp_reg_unwind( C, regpos ); return 1; } static SGSBOOL compile_midxset( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* out, int isprop ) { FTNode* mapi; rcpos_t var, name, src; rcpos_t regpos = C->fctx->regs, regpos2; FUNC_ENTER; if( !compile_node_r( C, func, node->child, &var ) ) return 0; regpos2 = C->fctx->regs; mapi = node->child->next->child; while( mapi ) { if( *mapi->token == ST_STRING ) { uint32_t string_len; AS_UINT32( string_len, mapi->token + 1 ); name = BC_CONSTENC( add_const_s( C, func, string_len, (const char*) mapi->token + 5 ) ); } else { compile_ident( C, func, mapi, &name ); } mapi = mapi->next; FUNC_ENTER; if( !compile_node_r( C, func, mapi, &src ) ) return 0; mapi = mapi->next; INSTR_WRITE( isprop ? SI_SETPROP : SI_SETINDEX, var, name, src ); comp_reg_unwind( C, regpos2 ); } if( out ) *out = var; else comp_reg_unwind( C, regpos ); return 1; } static SGSBOOL try_optimize_last_instr_out( SGS_CTX, sgs_CompFunc* func, FTNode* node, size_t ioff, rcpos_t* out ) { rcpos_t pos = -1; FUNC_BEGIN; UNUSED( C ); if( ( node->type != SFT_IDENT && node->type != SFT_ARGMT ) || *node->token != ST_IDENT ) goto cannot; /* moved offset 4 to other side of equation to prevent unsigned underflow */ if( ioff + 4 > func->code.size ) goto cannot; ioff = func->code.size - 4; /* check if closure variable */ pos = find_varT( &C->fctx->clsr, node->token ); if( pos >= 0 ) goto cannot; /* find the variable output register */ if( C->fctx->func ) { rcpos_t gpos = find_varT( &C->fctx->gvars, node->token ); if( gpos >= 0 ) pos = -1; else { add_varT( &C->fctx->vars, C, node->token ); pos = find_varT( &C->fctx->vars, node->token ); } } else { pos = find_varT( &C->fctx->vars, node->token ); } /* global variable */ if( pos < 0 ) goto cannot; { instr_t I; AS_( I, func->code.ptr + ioff, instr_t ); int op = INSTR_GET_OP( I ), argB = INSTR_GET_B( I ), argC = INSTR_GET_C( I ); switch( op ) { case SI_GETVAR: case SI_GETPROP: case SI_GETINDEX: case SI_SET: case SI_CONCAT: case SI_NEGATE: case SI_BOOL_INV: case SI_INVERT: case SI_ADD: case SI_SUB: case SI_MUL: case SI_DIV: case SI_MOD: case SI_AND: case SI_OR: case SI_XOR: case SI_LSH: case SI_RSH: case SI_SEQ: case SI_EQ: case SI_LT: case SI_LTE: case SI_SNEQ: case SI_NEQ: case SI_GT: case SI_GTE: case SI_RAWCMP: case SI_ARRAY: case SI_DICT: { char* dummy0 = NULL; unsigned dummy1 = 0; if( find_nth_var( &C->fctx->vars, INSTR_GET_A( I ), &dummy0, &dummy1 ) ) goto cannot; } I = INSTR_MAKE( op, pos, argB, argC ); memcpy( func->code.ptr + ioff, &I, sizeof(I) ); if( out ) *out = pos; break; default: goto cannot; } } FUNC_END; return 1; cannot: FUNC_END; return 0; } static SGSBOOL try_optimize_set_op( SGS_CTX, sgs_CompFunc* func, size_t ioff, rcpos_t ireg ) { FUNC_BEGIN; UNUSED( C ); /* moved offset 4 to other side of equation to prevent unsigned underflow */ if( ioff + 4 > func->code.size ) goto cannot; ioff = func->code.size - 4; { instr_t I; AS_( I, func->code.ptr + ioff, instr_t ); int op = INSTR_GET_OP( I ), argB = INSTR_GET_B( I ), argC = INSTR_GET_C( I ); switch( op ) { case SI_GETVAR: case SI_GETPROP: case SI_GETINDEX: case SI_SET: case SI_CONCAT: case SI_NEGATE: case SI_BOOL_INV: case SI_INVERT: case SI_ADD: case SI_SUB: case SI_MUL: case SI_DIV: case SI_MOD: case SI_AND: case SI_OR: case SI_XOR: case SI_LSH: case SI_RSH: case SI_SEQ: case SI_EQ: case SI_LT: case SI_LTE: case SI_SNEQ: case SI_NEQ: case SI_GT: case SI_GTE: case SI_RAWCMP: case SI_ARRAY: case SI_DICT: { char* dummy0 = NULL; unsigned dummy1 = 0; if( find_nth_var( &C->fctx->vars, INSTR_GET_A( I ), &dummy0, &dummy1 ) ) goto cannot; } I = INSTR_MAKE( op, ireg, argB, argC ); memcpy( func->code.ptr + ioff, &I, sizeof(I) ); break; default: goto cannot; } } FUNC_END; return 1; cannot: FUNC_END; return 0; } static SGSBOOL compile_node_rrw( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t dst ) { rcpos_t ireg = -1, bkup = C->fctx->regs; size_t newcodestart = func->code.size; FUNC_ENTER; if( !compile_node_r( C, func, node, &ireg ) ) return 0; FUNC_ENTER; if( !try_optimize_set_op( C, func, newcodestart, dst ) ) { /* just set the contents */ FUNC_ENTER; INSTR_WRITE( SI_SET, dst, ireg, 0 ); } comp_reg_unwind( C, bkup ); return 1; } static SGSBOOL compile_oper( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* arg, int out, int expect ) { int assign = ST_OP_ASSIGN( *node->token ); FUNC_BEGIN; /* Error suppression op */ if( *node->token == ST_OP_ERSUP ) { size_t csz; INSTR_WRITE( SI_INT, 0, 0, SGS_INT_ERRSUP_INC ); csz = func->code.size; if( out && expect ) { FUNC_ENTER; if( !compile_node_r( C, func, node->child, arg ) ) goto fail; } else { FUNC_ENTER; if( !compile_node( C, func, node->child ) ) goto fail; } if( func->code.size > csz ) { /* write INT ERRSUP_DEC if any code was written */ INSTR_WRITE( SI_INT, 0, 0, SGS_INT_ERRSUP_DEC ); } else { /* otherwise, remove the already written IN ERRSUP_INC */ func->code.size -= 4; } return 1; } /* Boolean ops */ else if( ST_OP_BOOL( *node->token ) ) { int jin; rcpos_t ireg1, ireg2, oreg = 0; size_t csz, csz2; if( !assign ) oreg = comp_reg_alloc( C ); if( C->state & SGS_MUST_STOP ) goto fail; /* get source data register */ FUNC_ENTER; if( !compile_node_r( C, func, node->child, &ireg1 ) ) goto fail; /* write cond. jump */ jin = ( *node->token == ST_OP_BLAND || *node->token == ST_OP_BLAEQ ) ? SI_JMPT : SI_JMPF; INSTR_WRITE_PCH(); csz = func->code.size; /* compile write of value 1 */ if( assign ) { FUNC_ENTER; if( !compile_node_w( C, func, node->child, ireg1 ) ) goto fail; } else { INSTR_WRITE( SI_SET, oreg, ireg1, 0 ); } INSTR_WRITE_PCH(); csz2 = func->code.size; /* fix-up jump 1 */ { instr_t instr; /* WP: instruction limit */ ptrdiff_t jmp_off = (ptrdiff_t) ( func->code.size - csz ) / INSTR_SIZE; instr = INSTR_MAKE_EX( jin, jmp_off, ireg1 ); memcpy( func->code.ptr + csz - 4, &instr, sizeof(instr) ); } /* get source data register 2 */ FUNC_ENTER; if( !compile_node_r( C, func, node->child->next, &ireg2 ) ) goto fail; /* compile write of value 2 */ if( assign ) { FUNC_ENTER; if( !compile_node_w( C, func, node->child, ireg2 ) ) goto fail; } else { INSTR_WRITE( SI_SET, oreg, ireg2, 0 ); } INSTR_WRITE( SI_NOP, 0, 0, 0 ); /* fix-up jump 2 */ { instr_t instr; /* WP: instruction limit */ ptrdiff_t jmp_off = (ptrdiff_t) ( func->code.size - csz2 ) / INSTR_SIZE; instr = INSTR_MAKE_EX( SI_JUMP, jmp_off, 0 ); memcpy( func->code.ptr + csz2 - 4, &instr, sizeof(instr) ); } /* re-read from assignments */ if( arg ) { if( assign ) { FUNC_ENTER; if( !compile_node_r( C, func, node->child, arg ) ) goto fail; } else *arg = oreg; } } else /* Increment / decrement */ if( *node->token == ST_OP_INC || *node->token == ST_OP_DEC ) { rcpos_t ireg, oreg; /* register with input data */ FUNC_ENTER; if( !compile_node_r( C, func, node->child, &ireg ) ) goto fail; /* output register selection */ oreg = expect && node->type == SFT_OPER_P ? comp_reg_alloc( C ) : ireg; if( C->state & SGS_MUST_STOP ) goto fail; if( oreg != ireg ) { INSTR_WRITE( SI_SET, oreg, ireg, 0 ); } /* check for errors if this operator generates output */ if( expect ) { if( expect != 1 ) { QPRINT( "Too many expected outputs for operator" ); goto fail; } } /* write bytecode */ INSTR_WRITE( *node->token == ST_OP_INC ? SI_INC : SI_DEC, ireg, ireg, 0 ); if( arg ) *arg = oreg; /* compile writeback */ FUNC_ENTER; if( !compile_node_w( C, func, node->child, ireg ) ) goto fail; } /* Assignment */ else if( assign ) { /* 1 operand */ if( *node->token == ST_OP_SET ) { rcpos_t ireg; size_t isb = func->code.size; if( node->child->type == SFT_EXPLIST ) { FTNode* n; int i, xpct = 0; int32_t bkup; rcpos_t freg; if( node->child->next->type != SFT_FCALL ) { QPRINT( "Expression writes only allowed with function call reads" ); goto fail; } /* multiwrite */ n = node->child->child; while( n ) { xpct++; n = n->next; } if( !compile_fcall( C, func, node->child->next, &freg, xpct ) ) goto fail; bkup = C->fctx->regs; n = node->child->child; for( i = 0; i < xpct; ++i ) { FUNC_ENTER; if( !compile_node_w( C, func, n, freg + i ) ) goto fail; comp_reg_unwind( C, bkup ); n = n->next; } } else { /* get source data register */ FUNC_ENTER; if( !compile_node_r( C, func, node->child->next, &ireg ) ) goto fail; FUNC_ENTER; if( !try_optimize_last_instr_out( C, func, node->child, isb, arg ) ) { /* just set the contents */ FUNC_ENTER; if( !compile_node_w( C, func, node->child, ireg ) ) goto fail; } if( arg ) { FUNC_ENTER; if( !compile_node_r( C, func, node->child, arg ) ) goto fail; } } } /* 3+ operands (MCONCAT only) */ else if( *node->token == ST_OP_CATEQ && node->child && node->child->next && node->child->next->next ) { int numch = 0; FTNode* cur = node->child; rcpos_t ireg, oreg = comp_reg_alloc( C ); if( C->state & SGS_MUST_STOP ) goto fail; /* get source data registers */ while( cur ) { int32_t bkup = C->fctx->regs; FUNC_ENTER; if( !compile_node_r( C, func, cur, &ireg ) ) goto fail; INSTR_WRITE( SI_PUSH, 0, ireg, 0 ); numch++; cur = cur->next; comp_reg_unwind( C, bkup ); } INSTR_WRITE( SI_MCONCAT, oreg, numch, 0 ); if( arg ) *arg = oreg; /* compile write */ FUNC_ENTER; if( !compile_node_w( C, func, node->child, oreg ) ) goto fail; } /* 2 operands */ else { int op; size_t isb = func->code.size; rcpos_t ireg1, ireg2, oreg = comp_reg_alloc( C ); if( C->state & SGS_MUST_STOP ) goto fail; /* get source data registers */ FUNC_ENTER; if( !compile_node_r( C, func, node->child, &ireg1 ) ) goto fail; FUNC_ENTER; if( !compile_node_r( C, func, node->child->next, &ireg2 ) ) goto fail; /* compile op */ op = op_pick_opcode( *node->token, 1 ); INSTR_WRITE( op, oreg, ireg1, ireg2 ); FUNC_ENTER; if( !try_optimize_last_instr_out( C, func, node->child, isb, arg ) ) { /* just set the contents */ FUNC_ENTER; if( !compile_node_w( C, func, node->child, oreg ) ) goto fail; } if( arg ) { FUNC_ENTER; if( !compile_node_r( C, func, node->child, arg ) ) goto fail; } } } /* Any other */ else { rcpos_t ireg1, ireg2, oreg; if( expect > 1 ) { QPRINT( "Too many expected outputs for operator" ); goto fail; } if( /* no operands, unary used as binary, binary used as unary */ ( !node->child ) || ( ST_OP_UNARY( *node->token ) && !ST_OP_BINARY( *node->token ) && node->child->next ) || ( !ST_OP_UNARY( *node->token ) && ST_OP_BINARY( *node->token ) && !node->child->next ) ) { QPRINT( "Invalid expression" ); goto fail; } if( *node->token == ST_OP_MMBR ) { /* oreg points to output register if "out", source register otherwise */ if( out ) { oreg = comp_reg_alloc( C ); if( C->state & SGS_MUST_STOP ) goto fail; if( arg ) *arg = oreg; } else oreg = *arg; /* get source data registers */ FUNC_ENTER; if( !compile_node_r( C, func, node->child, &ireg1 ) ) goto fail; if( node->child->next->type == SFT_IDENT ) compile_ident( C, func, node->child->next, &ireg2 ); else { FUNC_ENTER; if( !compile_node_r( C, func, node->child->next, &ireg2 ) ) goto fail; } /* compile op */ if( out ) INSTR_WRITE( SI_GETPROP, oreg, ireg1, ireg2 ); else { if( CONSTVAR( ireg1 ) ) { QPRINT( "Cannot set property of a constant" ); goto fail; } INSTR_WRITE( SI_SETPROP, ireg1, ireg2, oreg ); } } /* 3+ operands (MCONCAT only) */ else if( *node->token == ST_OP_CAT && node->child && node->child->next && node->child->next->next ) { int numch = 0; FTNode* cur = node->child; rcpos_t ireg; oreg = comp_reg_alloc( C ); if( C->state & SGS_MUST_STOP ) goto fail; /* get source data registers */ while( cur ) { int32_t bkup = C->fctx->regs; FUNC_ENTER; if( !compile_node_r( C, func, cur, &ireg ) ) goto fail; INSTR_WRITE( SI_PUSH, 0, ireg, 0 ); numch++; cur = cur->next; comp_reg_unwind( C, bkup ); } if( arg ) *arg = oreg; /* compile op */ INSTR_WRITE( SI_MCONCAT, oreg, numch, 0 ); } else { int op; oreg = comp_reg_alloc( C ); if( C->state & SGS_MUST_STOP ) goto fail; /* get source data registers */ FUNC_ENTER; if( !compile_node_r( C, func, node->child, &ireg1 ) ) goto fail; if( node->child->next ) { FUNC_ENTER; if( !compile_node_r( C, func, node->child->next, &ireg2 ) ) goto fail; } if( arg ) *arg = oreg; /* compile op */ op = op_pick_opcode( *node->token, !!node->child->next ); if( !op ) INSTR_WRITE( SI_SET, oreg, ireg1, 0 ); else if( node->child->next ) INSTR_WRITE( op, oreg, ireg1, ireg2 ); else INSTR_WRITE( op, oreg, ireg1, 0 ); } } FUNC_END; return 1; fail: C->state |= SGS_HAS_ERRORS; FUNC_END; return 0; } static SGSBOOL compile_breaks( SGS_CTX, sgs_CompFunc* func, FTNode* node, uint8_t iscont ) { sgs_BreakInfo* binfo = C->fctx->binfo, *prev = NULL; while( binfo ) { if( binfo->numlp == C->fctx->loops && binfo->iscont == iscont ) { /* WP: jump limit */ ptrdiff_t off = (ptrdiff_t) ( func->code.size - binfo->jdoff ) / INSTR_SIZE - 1; if( over_limit( off, 32767 ) ) { QPRINT( "Max. jump limit exceeded (32767 instructions) @ break/continue; reduce size of loops" ); return 0; } instr_t instr = INSTR_MAKE_EX( SI_JUMP, off, 0 ); memcpy( func->code.ptr + binfo->jdoff, &instr, sizeof(instr) ); binfo = binfo->next; fctx_binfo_rem( C, C->fctx, prev ); } else { prev = binfo; binfo = binfo->next; } } return 1; } static void rpts( MemBuf* out, SGS_CTX, FTNode* root ) { switch( root->type ) { case SFT_IDENT: membuf_appbuf( out, C, root->token + 2, root->token[1] ); break; case SFT_OPER: switch( *root->token ) { case ST_OP_MMBR: rpts( out, C, root->child ); membuf_appchr( out, C, '.' ); rpts( out, C, root->child->next ); break; } break; } } static void prefix_bytecode( SGS_CTX, sgs_CompFunc* func, int args ) { MemBuf ncode = membuf_create(); MemBuf nlnbuf = membuf_create(); if( C->fctx->outclsr > C->fctx->inclsr ) { int i; instr_t I = INSTR_MAKE( SI_GENCLSR, C->fctx->outclsr - C->fctx->inclsr, 0, 0 ); uint16_t ln = 0; membuf_appbuf( &ncode, C, &I, sizeof( I ) ); membuf_appbuf( &nlnbuf, C, &ln, sizeof( ln ) ); for( i = 0; i < args; ++i ) { char* varstr = NULL; unsigned varstrlen; int result, which; result = find_nth_var( &C->fctx->vars, i, &varstr, &varstrlen ); sgs_BreakIf( !result ); if( !result ) continue; which = find_var( &C->fctx->clsr, varstr, varstrlen ); if( which < 0 ) continue; I = INSTR_MAKE( SI_SETCLSR, 0, which, i ); membuf_appbuf( &ncode, C, &I, sizeof( I ) ); membuf_appbuf( &nlnbuf, C, &ln, sizeof( ln ) ); } } membuf_appbuf( &ncode, C, func->code.ptr, func->code.size ); membuf_appbuf( &nlnbuf, C, func->lnbuf.ptr, func->lnbuf.size ); membuf_destroy( &func->code, C ); membuf_destroy( &func->lnbuf, C ); /* WP: both lastreg and args cannot exceed 255, lastreg includes args */ func->numtmp = (uint8_t) ( C->fctx->lastreg - args ); func->code = ncode; func->lnbuf = nlnbuf; } static SGSBOOL compile_func( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* out ) { sgs_FuncCtx* fctx = fctx_create( C ), *bkfctx = C->fctx; sgs_CompFunc* nf = make_compfunc( C ); int args = 0, clsrcnt = 0; FTNode* n_arglist = node->child; FTNode* n_uselist = n_arglist->next; FTNode* n_body = n_uselist->next; FTNode* n_name = n_body->next; /* pre-context-change closure-apply */ FUNC_ENTER; if( !preparse_closures( C, func, n_uselist, 0 ) ) { goto fail; } C->fctx = fctx; FUNC_ENTER; if( !preparse_closures( C, nf, n_uselist, 1 ) ) { goto fail; } FUNC_ENTER; if( !preparse_arglist( C, nf, n_arglist ) ) { goto fail; } args = fctx->regs; FUNC_ENTER; if( !preparse_clsrlists( C, nf, n_body ) ) { goto fail; } FUNC_ENTER; if( !preparse_varlists( C, nf, n_body ) ) { goto fail; } args += nf->gotthis; FUNC_ENTER; if( !compile_node( C, nf, n_body ) ) { goto fail; } comp_reg_unwind( C, 0 ); if( C->fctx->lastreg > 0xff ) { QPRINT( "Max. register count exceeded" ); goto fail; } if( C->fctx->inclsr > 0xff ) { QPRINT( "Max. closure count exceeded" ); goto fail; } prefix_bytecode( C, nf, args ); /* WP: closure limit */ nf->numclsr = (uint8_t) ( clsrcnt = C->fctx->inclsr ); #if SGS_DUMP_BYTECODE || ( SGS_DEBUG && SGS_DEBUG_DATA ) fctx_dump( fctx ); sgsBC_Dump( nf ); #endif C->fctx = bkfctx; { MemBuf ffn = membuf_create(); if( n_name ) rpts( &ffn, C, n_name ); *out = BC_CONSTENC( add_const_f( C, func, nf, ffn.ptr, ffn.size, sgsT_LineNum( node->token ) ) ); membuf_destroy( &ffn, C ); if( clsrcnt > 0 ) { int i; rcpos_t ro = comp_reg_alloc( C ); FTNode* uli = n_uselist->child; for( i = 0; i < clsrcnt; ++i ) { INSTR_WRITE( SI_PUSHCLSR, find_varT( &bkfctx->clsr, uli->token ), 0, 0 ); uli = uli->next; } INSTR_WRITE( SI_MAKECLSR, ro, *out, clsrcnt ); *out = ro; } } fctx_destroy( C, fctx ); return 1; fail: sgsBC_Free( C, nf ); C->fctx = bkfctx; fctx_destroy( C, fctx ); C->state |= SGS_HAS_ERRORS; return 0; } static SGSBOOL compile_node_w( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t src ) { FUNC_BEGIN; switch( node->type ) { case SFT_IDENT: case SFT_KEYWORD: FUNC_HIT( "W_IDENT" ); if( !compile_ident_w( C, func, node, src ) ) goto fail; break; case SFT_CONST: FUNC_HIT( "W_CONST" ); QPRINT( "Cannot write to constants" ); goto fail; case SFT_FUNC: FUNC_HIT( "W_FUNC" ); QPRINT( "Cannot write to constants" ); goto fail; case SFT_ARRLIST: FUNC_HIT( "W_ARRLIST" ); QPRINT( "Cannot write to constants" ); goto fail; case SFT_MAPLIST: FUNC_HIT( "W_MAPLIST" ); QPRINT( "Cannot write to constants" ); goto fail; case SFT_OPER: case SFT_OPER_P: FUNC_HIT( "W_OPER" ); if( !compile_oper( C, func, node, &src, 0, 1 ) ) goto fail; break; case SFT_FCALL: FUNC_HIT( "W_FCALL" ); if( !compile_fcall( C, func, node, NULL, 0 ) ) goto fail; break; case SFT_INDEX: FUNC_HIT( "W_INDEX" ); if( !compile_index_w( C, func, node, src ) ) goto fail; break; case SFT_MIDXSET: FUNC_HIT( "MIDXSET" ); QPRINT( "Cannot write to multi-index-set expression" ); break; case SFT_MPROPSET: FUNC_HIT( "MPROPSET" ); QPRINT( "Cannot write to multi-property-set expression" ); break; case SFT_EXPLIST: FUNC_HIT( "W_EXPLIST" ); QPRINT( "Expression writes only allowed with function call reads" ); goto fail; default: sgs_Msg( C, SGS_ERROR, "Unexpected tree node [uncaught/internal BcG/w error]" ); goto fail; } FUNC_END; return 1; fail: FUNC_END; return 0; } static SGSBOOL compile_node_r( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* out ) { FUNC_BEGIN; switch( node->type ) { case SFT_IDENT: case SFT_KEYWORD: FUNC_HIT( "R_IDENT" ); if( !compile_ident_r( C, func, node, out ) ) goto fail; break; case SFT_CONST: FUNC_HIT( "R_CONST" ); if( !compile_const( C, func, node, out ) ) goto fail; break; case SFT_FUNC: FUNC_HIT( "R_FUNC" ); if( !compile_func( C, func, node, out ) ) goto fail; break; case SFT_ARRLIST: FUNC_HIT( "R_ARRLIST" ); { rcpos_t pos = 0; int args = 0; FTNode* n = node->child; while( n ) { int32_t bkup = C->fctx->regs; pos = 0; FUNC_ENTER; if( !compile_node_r( C, func, n, &pos ) ) goto fail; INSTR_WRITE( SI_PUSH, 0, pos, 0 ); comp_reg_unwind( C, bkup ); args++; n = n->next; } pos = comp_reg_alloc( C ); INSTR_WRITE( SI_ARRAY, pos, args, 0 ); *out = pos; } break; case SFT_MAPLIST: FUNC_HIT( "R_MAPLIST" ); { rcpos_t pos = 0; int args = 0; FTNode* n = node->child; while( n ) { rcpos_t bkup = C->fctx->regs; pos = 0; if( args % 2 == 0 ) { if( *n->token == ST_STRING ) { uint32_t string_len; AS_UINT32( string_len, n->token + 1 ); pos = BC_CONSTENC( add_const_s( C, func, string_len, (const char*) n->token + 5 ) ); } else compile_ident( C, func, n, &pos ); } else { FUNC_ENTER; if( !compile_node_r( C, func, n, &pos ) ) goto fail; } INSTR_WRITE( SI_PUSH, 0, pos, 0 ); comp_reg_unwind( C, bkup ); args++; n = n->next; } pos = comp_reg_alloc( C ); INSTR_WRITE( SI_DICT, pos, args, 0 ); *out = pos; } break; case SFT_OPER: case SFT_OPER_P: FUNC_HIT( "R_OPER" ); if( !compile_oper( C, func, node, out, 1, 1 ) ) goto fail; break; case SFT_FCALL: FUNC_HIT( "R_FCALL" ); if( !compile_fcall( C, func, node, out, 1 ) ) goto fail; break; case SFT_INDEX: FUNC_HIT( "R_INDEX" ); if( !compile_index_r( C, func, node, out ) ) goto fail; break; case SFT_MIDXSET: FUNC_HIT( "MIDXSET" ); if( !compile_midxset( C, func, node, out, 0 ) ) goto fail; break; case SFT_MPROPSET: FUNC_HIT( "MPROPSET" ); if( !compile_midxset( C, func, node, out, 1 ) ) goto fail; break; case SFT_EXPLIST: FUNC_HIT( "R_EXPLIST" ); { FTNode* n = node->child; if( !n ) { QPRINT( "Empty expression found" ); goto fail; } while( n ) { FUNC_ENTER; if( !compile_node_r( C, func, n, out ) ) goto fail; n = n->next; } } break; default: sgs_Msg( C, SGS_ERROR, "Unexpected tree node [uncaught/internal BcG/r error]" ); goto fail; } FUNC_END; return 1; fail: FUNC_END; return 0; } static SGSBOOL compile_for_explist( SGS_CTX, sgs_CompFunc* func, FTNode* node, rcpos_t* out ) { FTNode* n; FUNC_BEGIN; if( node->type != SFT_EXPLIST ) { sgs_Msg( C, SGS_ERROR, "Unexpected tree node [uncaught/internal BcG/r[fe] error]" ); goto fail; } FUNC_HIT( "Rs_EXPLIST" ); n = node->child; while( n ) { FUNC_ENTER; if( !compile_node_r( C, func, n, out ) ) goto fail; n = n->next; } FUNC_END; return 1; fail: FUNC_END; return 0; } static SGSBOOL compile_node( SGS_CTX, sgs_CompFunc* func, FTNode* node ) { FUNC_BEGIN; switch( node->type ) { /* ignore these items if they're leading in statements */ case SFT_IDENT: case SFT_KEYWORD: case SFT_CONST: case SFT_ARRLIST: case SFT_MAPLIST: break; case SFT_OPER: case SFT_OPER_P: FUNC_HIT( "OPERATOR" ); if( !compile_oper( C, func, node, NULL, 1, 0 ) ) goto fail; break; case SFT_INDEX: FUNC_HIT( "INDEX" ); if( !compile_index_r( C, func, node, NULL ) ) goto fail; break; case SFT_MIDXSET: FUNC_HIT( "MIDXSET" ); if( !compile_midxset( C, func, node, NULL, 0 ) ) goto fail; break; case SFT_MPROPSET: FUNC_HIT( "MPROPSET" ); if( !compile_midxset( C, func, node, NULL, 1 ) ) goto fail; break; case SFT_FCALL: FUNC_HIT( "FCALL" ); if( !compile_fcall( C, func, node, NULL, 0 ) ) goto fail; break; case SFT_EXPLIST: FUNC_HIT( "EXPLIST" ); { FTNode* n = node->child; while( n ) { FUNC_ENTER; if( !compile_node( C, func, n ) ) goto fail; n = n->next; } } break; case SFT_RETURN: FUNC_HIT( "RETURN" ); { rcpos_t regstate = C->fctx->regs; int num = 0; FTNode* n = node->child; while( n ) { rcpos_t arg = 0; FUNC_ENTER; if( !compile_node_r( C, func, n, &arg ) ) goto fail; INSTR_WRITE( SI_PUSH, 0, arg, 0 ); n = n->next; num++; } INSTR_WRITE( SI_RETN, num, 0, 0 ); comp_reg_unwind( C, regstate ); } break; case SFT_BLOCK: FUNC_HIT( "BLOCK" ); node = node->child; while( node ) { rcpos_t regstate = C->fctx->regs; FUNC_ENTER; if( !compile_node( C, func, node ) ) goto fail; node = node->next; comp_reg_unwind( C, regstate ); } break; case SFT_IFELSE: FUNC_HIT( "IF/ELSE" ); { rcpos_t arg = 0; rcpos_t regstate = C->fctx->regs; FUNC_ENTER; if( !compile_node_r( C, func, node->child, &arg ) ) goto fail; comp_reg_unwind( C, regstate ); INSTR_WRITE_PCH(); { size_t jp1, jp2 = 0, jp3 = 0; jp1 = func->code.size; regstate = C->fctx->regs; FUNC_ENTER; if( !compile_node( C, func, node->child->next ) ) goto fail; comp_reg_unwind( C, regstate ); if( node->child->next->next ) { INSTR_WRITE_PCH(); jp2 = func->code.size; { instr_t instr; /* WP: jump limit */ ptrdiff_t jmp_off = (ptrdiff_t) ( jp2 - jp1 ) / INSTR_SIZE; if( over_limit( jmp_off, 32767 ) ) { QPRINT( "Max. jump limit exceeded (32767 instructions) @ if/else; reduce size of construct" ); goto fail; } instr = INSTR_MAKE_EX( SI_JMPF, jmp_off, arg ); memcpy( func->code.ptr + jp1 - 4, &instr, sizeof(instr) ); } regstate = C->fctx->regs; FUNC_ENTER; if( !compile_node( C, func, node->child->next->next ) ) goto fail; jp3 = func->code.size; { instr_t instr; /* WP: jump limit */ ptrdiff_t jmp_off = (ptrdiff_t) ( jp3 - jp2 ) / INSTR_SIZE; if( over_limit( jmp_off, 32767 ) ) { QPRINT( "Max. jump limit exceeded (32767 instructions) @ if/else; reduce size of construct" ); goto fail; } instr = INSTR_MAKE_EX( SI_JUMP, jmp_off, 0 ); memcpy( func->code.ptr + jp2 - 4, &instr, sizeof(instr) ); } comp_reg_unwind( C, regstate ); } else { instr_t instr; /* WP: jump limit */ ptrdiff_t jmp_off = (ptrdiff_t) ( func->code.size - jp1 ) / INSTR_SIZE; if( over_limit( jmp_off, 32767 ) ) { QPRINT( "Max. jump limit exceeded (32767 instructions) @ if/else; reduce size of construct" ); goto fail; } instr = INSTR_MAKE_EX( SI_JMPF, jmp_off, arg ); memcpy( func->code.ptr + jp1 - 4, &instr, sizeof(instr) ); } } } break; case SFT_WHILE: FUNC_HIT( "WHILE" ); { size_t codesize; rcpos_t arg = -1; rcpos_t regstate = C->fctx->regs; C->fctx->loops++; codesize = func->code.size; FUNC_ENTER; if( !compile_node_r( C, func, node->child, &arg ) ) goto fail; /* test */ comp_reg_unwind( C, regstate ); INSTR_WRITE_PCH(); { ptrdiff_t off; size_t jp1, jp2 = 0; jp1 = func->code.size; regstate = C->fctx->regs; FUNC_ENTER; if( !compile_node( C, func, node->child->next ) ) goto fail; /* while */ comp_reg_unwind( C, regstate ); if( !compile_breaks( C, func, node, 1 ) ) goto fail; jp2 = func->code.size; /* WP: jump limit */ off = (ptrdiff_t) ( codesize - jp2 ) / INSTR_SIZE - 1; if( over_limit( off, 32767 ) ) { QPRINT( "Max. jump limit exceeded (32767 instructions) @ while; reduce size of loop" ); goto fail; } INSTR_WRITE_EX( SI_JUMP, off, 0 ); { instr_t instr; instr = INSTR_MAKE_EX( SI_JMPF, ( jp2 - jp1 ) / INSTR_SIZE + 1, arg ); memcpy( func->code.ptr + jp1 - 4, &instr, sizeof(instr) ); } } if( !compile_breaks( C, func, node, 0 ) ) goto fail; C->fctx->loops--; } break; case SFT_DOWHILE: FUNC_HIT( "DO/WHILE" ); { size_t codesize; rcpos_t regstate = C->fctx->regs; rcpos_t arg = -1; ptrdiff_t off; C->fctx->loops++; codesize = func->code.size; { FUNC_ENTER; if( !compile_node( C, func, node->child->next ) ) goto fail; /* while */ comp_reg_unwind( C, regstate ); if( !compile_breaks( C, func, node, 1 ) ) goto fail; } FUNC_ENTER; if( !compile_node_r( C, func, node->child, &arg ) ) goto fail; /* test */ comp_reg_unwind( C, regstate ); /* WP: jump limit */ off = (ptrdiff_t) ( codesize - func->code.size ) / INSTR_SIZE - 1; if( over_limit( off, 32767 ) ) { QPRINT( "Max. jump limit exceeded (32767 instructions) @ do/while; reduce size of loop" ); goto fail; } INSTR_WRITE_EX( SI_JMPT, off, arg ); if( !compile_breaks( C, func, node, 0 ) ) goto fail; C->fctx->loops--; } break; case SFT_FOR: FUNC_HIT( "FOR" ); { size_t codesize; rcpos_t regstate = C->fctx->regs; rcpos_t arg = -1; C->fctx->loops++; FUNC_ENTER; if( !compile_node( C, func, node->child ) ) goto fail; /* init */ comp_reg_unwind( C, regstate ); codesize = func->code.size; FUNC_ENTER; if( !compile_for_explist( C, func, node->child->next, &arg ) ) goto fail; /* test */ comp_reg_unwind( C, regstate ); if( arg != -1 ) { INSTR_WRITE_PCH(); } { ptrdiff_t off; size_t jp1, jp2 = 0; jp1 = func->code.size; FUNC_ENTER; if( !compile_node( C, func, node->child->next->next->next ) ) goto fail; /* block */ comp_reg_unwind( C, regstate ); if( !compile_breaks( C, func, node, 1 ) ) goto fail; FUNC_ENTER; if( !compile_node( C, func, node->child->next->next ) ) goto fail; /* incr */ comp_reg_unwind( C, regstate ); jp2 = func->code.size; /* WP: jump limit */ off = (ptrdiff_t) ( codesize - jp2 ) / INSTR_SIZE - 1; if( over_limit( off, 32767 ) ) { QPRINT( "Max. jump limit exceeded (32767 instructions) @ for; reduce size of loop" ); goto fail; } INSTR_WRITE_EX( SI_JUMP, off, 0 ); if( arg != -1 ) { instr_t instr; instr = INSTR_MAKE_EX( SI_JMPF, ( jp2 - jp1 ) / INSTR_SIZE + 1, arg ); memcpy( func->code.ptr + jp1 - 4, &instr, sizeof(instr) ); } } if( !compile_breaks( C, func, node, 0 ) ) goto fail; C->fctx->loops--; } break; case SFT_FOREACH: FUNC_HIT( "FOREACH" ); { size_t codesize, jp1, jp2; rcpos_t var, iter, key = -1, val = -1; rcpos_t regstate, regstate2; regstate2 = C->fctx->regs; /* init */ var = -1; FUNC_ENTER; if( !compile_node_r( C, func, node->child->next->next, &var ) ) goto fail; /* get variable */ iter = comp_reg_alloc( C ); if( node->child->type != SFT_NULL ) key = comp_reg_alloc( C ); if( node->child->next->type != SFT_NULL ) val = comp_reg_alloc( C ); regstate = C->fctx->regs; C->fctx->loops++; INSTR_WRITE( SI_FORPREP, iter, var, 0 ); comp_reg_unwind( C, regstate ); /* iterate */ codesize = func->code.size; INSTR_WRITE_PCH(); jp1 = func->code.size; INSTR_WRITE( SI_FORLOAD, iter, key, val ); { ptrdiff_t off = 0; /* write to key variable */ if( node->child->type != SFT_NULL && !compile_ident_w( C, func, node->child, key ) ) goto fail; /* write to value variable */ if( node->child->next->type != SFT_NULL && !compile_ident_w( C, func, node->child->next, val ) ) goto fail; FUNC_ENTER; if( !compile_node( C, func, node->child->next->next->next ) ) goto fail; /* block */ comp_reg_unwind( C, regstate ); if( !compile_breaks( C, func, node, 1 ) ) goto fail; jp2 = func->code.size; /* WP: jump limit */ off = (ptrdiff_t) ( codesize - jp2 ) / INSTR_SIZE - 1; if( over_limit( off, 32767 ) ) { QPRINT( "Max. jump limit exceeded (32767 instructions) @ foreach; reduce size of loop" ); goto fail; } INSTR_WRITE_EX( SI_JUMP, off, 0 ); { instr_t instr; instr = INSTR_MAKE_EX( SI_FORJUMP, ( func->code.size - jp1 ) / INSTR_SIZE, iter ); memcpy( func->code.ptr + jp1 - 4, &instr, sizeof(instr) ); } } if( !compile_breaks( C, func, node, 0 ) ) goto fail; C->fctx->loops--; comp_reg_unwind( C, regstate2 ); } break; case SFT_BREAK: FUNC_HIT( "BREAK" ); { TokenList tl = sgsT_Next( node->token ); int32_t blev = 1; if( *tl == ST_NUMINT ) { sgs_Int tint; AS_INTEGER( tint, tl + 1 ); if( tint < 1 || tint > 0xffff ) { QPRINT( "Invalid break level" ); goto fail; } blev = (int32_t) tint; } if( blev > C->fctx->loops ) { if( C->fctx->loops ) QPRINT( "Break level too high" ); else QPRINT( "Attempted to break while not in a loop" ); goto fail; } /* WP: instruction limit, max loop depth */ fctx_binfo_add( C, C->fctx, (uint32_t) func->code.size, (uint16_t)( C->fctx->loops + 1 - blev ), FALSE ); INSTR_WRITE_PCH(); } break; case SFT_CONT: FUNC_HIT( "CONTINUE" ); { TokenList tl = sgsT_Next( node->token ); int32_t blev = 1; if( *tl == ST_NUMINT ) { sgs_Int tint; AS_INTEGER( tint, tl + 1 ); if( tint < 1 || tint > 0xffff ) { QPRINT( "Invalid continue level" ); goto fail; } blev = (int32_t) tint; } if( blev > C->fctx->loops ) { if( C->fctx->loops ) QPRINT( "Continue level too high" ); else QPRINT( "Attempted to continue while not in a loop" ); goto fail; } /* WP: instruction limit, max loop depth */ fctx_binfo_add( C, C->fctx, (uint32_t) func->code.size, (uint16_t)( C->fctx->loops + 1 - blev ), TRUE ); INSTR_WRITE_PCH(); } break; case SFT_FUNC: FUNC_HIT( "FUNC" ); { rcpos_t pos; FUNC_ENTER; if( !compile_func( C, func, node, &pos ) ) goto fail; if( node->child->next->next->next ) { FUNC_ENTER; if( !compile_node_w( C, func, node->child->next->next->next, pos ) ) goto fail; } } break; case SFT_VARLIST: case SFT_GVLIST: FUNC_HIT( node->type == SFT_VARLIST ? "VARLIST" : "GLOBALVARLIST" ); { rcpos_t regstate = C->fctx->regs; FTNode* pp = node->child; while( pp ) { if( pp->child ) { rcpos_t arg = -1; size_t lastsize = func->code.size; if( !compile_node_r( C, func, pp->child, &arg ) ) goto fail; if( !pp->token || *pp->token != ST_IDENT ) goto fail; if( node->type != SFT_VARLIST || !try_optimize_last_instr_out( C, func, pp, lastsize, NULL ) ) { compile_ident_w( C, func, pp, arg ); } comp_reg_unwind( C, regstate ); } pp = pp->next; } } break; default: sgs_Msg( C, SGS_ERROR, "Unexpected tree node [uncaught/internal BcG error]" ); goto fail; } FUNC_END; return 1; fail: FUNC_END; return 0; } sgs_CompFunc* sgsBC_Generate( SGS_CTX, FTNode* tree ) { sgs_CompFunc* func = make_compfunc( C ); sgs_FuncCtx* fctx = fctx_create( C ); fctx->func = FALSE; C->fctx = fctx; if( !preparse_clsrlists( C, func, tree ) ) goto fail; if( !preparse_varlists( C, func, tree ) ) goto fail; if( !compile_node( C, func, tree ) ) goto fail; comp_reg_unwind( C, 0 ); if( C->fctx->lastreg > 0xff ) { sgs_Msg( C, SGS_ERROR, "[line %d] Maximum register count exceeded", sgsT_LineNum( tree->token ) ); goto fail; } prefix_bytecode( C, func, 0 ); C->fctx = NULL; #if SGS_DUMP_BYTECODE || ( SGS_DEBUG && SGS_DEBUG_DATA ) fctx_dump( fctx ); #endif fctx_destroy( C, fctx ); return func; fail: sgsBC_Free( C, func ); C->fctx = NULL; fctx_destroy( C, fctx ); C->state |= SGS_HAS_ERRORS; return NULL; } void sgsBC_Dump( sgs_CompFunc* func ) { sgsBC_DumpEx( func->consts.ptr, func->consts.size, func->code.ptr, func->code.size ); } void sgsBC_DumpEx( const char* constptr, size_t constsize, const char* codeptr, size_t codesize ) { const sgs_Variable* vbeg = (const sgs_Variable*) (const void*) ASSUME_ALIGNED( constptr, 4 ); const sgs_Variable* vend = (const sgs_Variable*) (const void*) ASSUME_ALIGNED( constptr + constsize, 4 ); const sgs_Variable* var = vbeg; printf( "{\n" ); printf( "> constants:\n" ); while( var < vend ) { printf( "%4d = ", (int) ( var - vbeg ) ); sgsVM_VarDump( var ); printf( "\n" ); var++; } printf( "> code:\n" ); dump_opcode( (const instr_t*) (const void*) ASSUME_ALIGNED( codeptr, 4 ), codesize / sizeof( instr_t ) ); printf( "}\n" ); } void sgsBC_Free( SGS_CTX, sgs_CompFunc* func ) { sgs_Variable* vbeg = (sgs_Variable*) (void*) ASSUME_ALIGNED( func->consts.ptr, 4 ); sgs_Variable* vend = (sgs_Variable*) (void*) ASSUME_ALIGNED( func->consts.ptr + func->consts.size, 4 ); sgs_Variable* var = vbeg; while( var < vend ) { sgs_Release( C, var ); var++; } membuf_destroy( &func->code, C ); membuf_destroy( &func->consts, C ); membuf_destroy( &func->lnbuf, C ); sgs_Dealloc( func ); } /* bytecode serialization */ #define esi16( x ) ( (((x)&0xff)<<8) | (((x)>>8)&0xff) ) #define esi32( x ) (\ (((x)&0xff)<<24) | (((x)&0xff00)<<8) |\ (((x)>>8)&0xff00) | (((x)>>24)&0xff) ) typedef struct decoder_s { SGS_CTX; const char* buf, *start; char convend; const char* filename; size_t filename_len; } decoder_t; static void esi32_array( uint32_t* data, unsigned cnt ) { unsigned i; for( i = 0; i < cnt; ++i ) { data[ i ] = (uint32_t) esi32( data[ i ] ); } } /* i32 size byte[size] data */ static void bc_write_sgsstring( string_t* S, SGS_CTX, MemBuf* outbuf ) { membuf_appbuf( outbuf, C, &S->size, sizeof( int32_t ) ); membuf_appbuf( outbuf, C, str_cstr( S ), S->size ); } static void bc_read_sgsstring( decoder_t* D, sgs_Variable* var ) { const char* buf = D->buf; int32_t len; AS_INT32( len, buf ); if( D->convend ) len = esi32( len ); buf += 4; sgsVM_VarCreateString( D->C, var, buf, len ); D->buf = buf + len; } /* byte type --if type = NULL: --if type = BOOL: byte value --if type = INT: integer value --if type = REAL: real value --if type = STRING: stringdata data --if type = FUNC: funcdata data */ static int bc_write_sgsfunc( func_t* F, SGS_CTX, MemBuf* outbuf ); static int bc_write_var( sgs_Variable* var, SGS_CTX, MemBuf* outbuf ) { uint8_t vt = (uint8_t) var->type; /* WP: don't care about the sign when serializing bitfield */ membuf_appchr( outbuf, C, (char) vt ); switch( vt ) { case SVT_NULL: break; /* WP: var->data.B can only store 0/1 */ case SVT_BOOL: membuf_appchr( outbuf, C, (char) var->data.B ); break; case SVT_INT: membuf_appbuf( outbuf, C, &var->data.I, sizeof( sgs_Int ) ); break; case SVT_REAL: membuf_appbuf( outbuf, C, &var->data.R, sizeof( sgs_Real ) ); break; case SVT_STRING: bc_write_sgsstring( var->data.S, C, outbuf ); break; case SVT_FUNC: if( !bc_write_sgsfunc( var->data.F, C, outbuf ) ) return 0; break; default: return 0; } return 1; } static const char* bc_read_sgsfunc( decoder_t* D, sgs_Variable* var ); static const char* bc_read_var( decoder_t* D, sgs_Variable* var ) { uint8_t vt = (uint8_t) *D->buf++; var->type = vt; switch( vt ) { case SVT_NULL: break; case SVT_BOOL: var->data.B = *D->buf++; break; case SVT_INT: AS_INTEGER( var->data.I, D->buf ); D->buf += sizeof( sgs_Int ); break; case SVT_REAL: AS_REAL( var->data.R, D->buf ); D->buf += sizeof( sgs_Real ); break; case SVT_STRING: bc_read_sgsstring( D, var ); break; case SVT_FUNC: return bc_read_sgsfunc( D, var ); default: var->type = SVT_NULL; return "invalid variable type found"; } return NULL; } /* var[cnt] varlist */ static int bc_write_varlist( sgs_Variable* vlist, SGS_CTX, int cnt, MemBuf* outbuf ) { int i; for( i = 0; i < cnt; ++i ) { if( !bc_write_var( vlist + i, C, outbuf ) ) return 0; } return 1; } static const char* bc_read_varlist( decoder_t* D, sgs_Variable* vlist, int cnt ) { int i; for( i = 0; i < cnt; ++i ) { const char* ret = bc_read_var( D, vlist + i ); if( ret ) { cnt = i; for( i = 0; i < cnt; ++i ) sgs_Release( D->C, vlist + i ); return ret; } } return NULL; } /* i16 constcount i16 instrcount byte gotthis byte numargs byte numtmp byte numclsr i16 linenum i16[instrcount] lineinfo i32 funcname_size byte[funcname_size] funcname varlist consts instr[instrcount] instrs */ static int bc_write_sgsfunc( func_t* F, SGS_CTX, MemBuf* outbuf ) { size_t size = F->funcname.size; uint16_t cc, ic; uint8_t gntc[4] = { F->gotthis, F->numargs, F->numtmp, F->numclsr }; /* WP: const/instruction limits */ cc = (uint16_t)( F->instr_off / sizeof( sgs_Variable ) ); ic = (uint16_t)( ( F->size - F->instr_off ) / sizeof( instr_t ) ); membuf_appbuf( outbuf, C, &cc, sizeof( cc ) ); membuf_appbuf( outbuf, C, &ic, sizeof( ic ) ); membuf_appbuf( outbuf, C, gntc, 4 ); membuf_appbuf( outbuf, C, &F->linenum, sizeof( LineNum ) ); membuf_appbuf( outbuf, C, F->lineinfo, sizeof( uint16_t ) * ic ); membuf_appbuf( outbuf, C, &size, sizeof( size ) ); membuf_appbuf( outbuf, C, F->funcname.ptr, F->funcname.size ); if( !bc_write_varlist( func_consts( F ), C, cc, outbuf ) ) return 0; membuf_appbuf( outbuf, C, func_bytecode( F ), sizeof( instr_t ) * ic ); return 1; } static void bc_read_membuf( decoder_t* D, MemBuf* out ) { const char* buf = D->buf; uint32_t len; AS_UINT32( len, buf ); if( D->convend ) len = (uint32_t) esi32( len ); buf += 4; membuf_setstrbuf( out, D->C, buf, len ); D->buf = buf + len; } static const char* bc_read_sgsfunc( decoder_t* D, sgs_Variable* var ) { func_t* F; uint32_t coff, ioff, size; uint16_t cc, ic; const char* ret; SGS_CTX = D->C; AS_UINT16( cc, D->buf ); AS_UINT16( ic, D->buf + 2 ); if( D->convend ) { /* WP: int promotion will not affect the result */ cc = (uint16_t) esi16( cc ); ic = (uint16_t) esi16( ic ); } /* WP: const/instruction limits */ ioff = (uint32_t) sizeof( sgs_Variable ) * cc; coff = (uint32_t) sizeof( instr_t ) * ic; size = ioff + coff; F = sgs_Alloc_a( func_t, size ); F->refcount = 1; F->size = size; F->instr_off = ioff; AS_UINT8( F->gotthis, D->buf + 4 ); AS_UINT8( F->numargs, D->buf + 5 ); AS_UINT8( F->numtmp, D->buf + 6 ); AS_UINT8( F->numclsr, D->buf + 7 ); AS_INT16( F->linenum, D->buf + 8 ); if( D->convend ) F->linenum = (sgs_LineNum) esi16( F->linenum ); F->lineinfo = sgs_Alloc_n( sgs_LineNum, ic ); D->buf += 10; memcpy( F->lineinfo, D->buf, sizeof( sgs_LineNum ) * ic ); D->buf += sizeof( sgs_LineNum ) * ic; F->funcname = membuf_create(); bc_read_membuf( D, &F->funcname ); F->filename = membuf_create(); membuf_setstrbuf( &F->filename, C, D->filename, D->filename_len ); /* the main data */ ret = bc_read_varlist( D, func_consts( F ), cc ); if( ret ) goto fail; memcpy( func_bytecode( F ), D->buf, coff ); if( D->convend ) esi32_array( func_bytecode( F ), coff / sizeof( instr_t ) ); D->buf += coff; var->data.F = F; return NULL; fail: sgs_Dealloc( F->lineinfo ); membuf_destroy( &F->funcname, C ); membuf_destroy( &F->filename, C ); sgs_Dealloc( F ); return ret; } /* -- header -- 14 bytes -- seq "SGS\0" byte version_major byte version_minor byte version_incr byte integer_size byte real_size byte flags u32 filesize -- header end -- i16 constcount i16 instrcount byte gotthis byte numargs byte numtmp byte numclsr -- -- -- -- -- 8 bytes in the previous section varlist consts i32[instrcount] instrs linenum[instrcount] lines */ int sgsBC_Func2Buf( SGS_CTX, sgs_CompFunc* func, MemBuf* outbuf ) { char header_bytes[ 14 ] = { 'S', 'G', 'S', 0, SGS_VERSION_MAJOR, SGS_VERSION_MINOR, SGS_VERSION_INCR, sizeof( sgs_Int ), sizeof( sgs_Real ), 0, 0, 0, 0, 0 }; header_bytes[ 9 ] = ( O32_HOST_ORDER == O32_LITTLE_ENDIAN ) ? SGSBC_FLAG_LITTLE_ENDIAN : 0; membuf_resize( outbuf, C, 0 ); membuf_reserve( outbuf, C, 1000 ); membuf_appbuf( outbuf, C, header_bytes, 14 ); { uint16_t cc, ic; uint8_t gntc[4] = { func->gotthis, func->numargs, func->numtmp, func->numclsr }; /* max. count: 65535, max. variable size: 16 bytes */ cc = (uint16_t) func->consts.size / sizeof( sgs_Variable ); ic = (uint16_t) func->code.size / sizeof( instr_t ); membuf_appbuf( outbuf, C, &cc, sizeof( cc ) ); membuf_appbuf( outbuf, C, &ic, sizeof( ic ) ); membuf_appbuf( outbuf, C, gntc, 4 ); sgs_BreakIf( outbuf->size != 22 ); if( !bc_write_varlist( (sgs_Variable*) (void*) ASSUME_ALIGNED( func->consts.ptr, 4 ), C, cc, outbuf ) ) return 0; membuf_appbuf( outbuf, C, func->code.ptr, sizeof( instr_t ) * ic ); membuf_appbuf( outbuf, C, func->lnbuf.ptr, sizeof( LineNum ) * ic ); { /* WP: bytecode size limit */ uint32_t outbufsize = (uint32_t) outbuf->size; memcpy( outbuf->ptr + 10, &outbufsize, sizeof(uint32_t) ); } return 1; } } const char* sgsBC_Buf2Func( SGS_CTX, const char* fn, const char* buf, size_t size, sgs_CompFunc** outfunc ) { char flags = buf[ 9 ]; uint32_t sz; AS_UINT32( sz, buf + 10 ); decoder_t D; { D.C = C; D.buf = NULL; D.start = buf; D.convend = ( O32_HOST_ORDER == O32_LITTLE_ENDIAN ) != ( ( flags & SGSBC_FLAG_LITTLE_ENDIAN ) != 0 ); D.filename = fn; D.filename_len = strlen( fn ); } if( D.convend ) sz = esi32( sz ); if( (size_t) sz != size ) return "incomplete file"; { const char* ret; uint16_t cc, ic; sgs_CompFunc* func = make_compfunc( C ); AS_UINT16( cc, buf + 14 ); AS_UINT16( ic, buf + 16 ); AS_UINT8( func->gotthis, buf + 18 ); AS_UINT8( func->numargs, buf + 19 ); AS_UINT8( func->numtmp, buf + 20 ); AS_UINT8( func->numclsr, buf + 21 ); D.buf = buf + 22; if( D.convend ) { /* WP: int promotion will not affect the result */ cc = (uint16_t) esi16( cc ); ic = (uint16_t) esi16( ic ); } membuf_resize( &func->consts, C, sizeof( sgs_Variable ) * cc ); membuf_resize( &func->code, C, sizeof( instr_t ) * ic ); membuf_resize( &func->lnbuf, C, sizeof( LineNum ) * ic ); ret = bc_read_varlist( &D, (sgs_Variable*) (void*) ASSUME_ALIGNED( func->consts.ptr, 4 ), cc ); if( ret ) { sgsBC_Free( C, func ); return ret; } memcpy( func->code.ptr, D.buf, sizeof( instr_t ) * ic ); if( D.convend ) esi32_array( (instr_t*) (void*) ASSUME_ALIGNED( func->code.ptr, 4 ), ic ); D.buf += sizeof( instr_t ) * ic; memcpy( func->lnbuf.ptr, D.buf, sizeof( LineNum ) * ic ); *outfunc = func; return NULL; } } int sgsBC_ValidateHeader( const char* buf, size_t size ) { int i; char validate_bytes[ 9 ] = { 'S', 'G', 'S', 0, SGS_VERSION_MAJOR, SGS_VERSION_MINOR, SGS_VERSION_INCR, sizeof( sgs_Int ), sizeof( sgs_Real ) }; if( size < SGS_MIN_BC_SIZE ) return -1; for( i = 0; i < 9; ++i ) { if( buf[ i ] != validate_bytes[ i ] ) return i; } return SGS_HEADER_SIZE; } <file_sep>/ext/sgs_idbg.h #ifndef SGS_IDBG_H_INCLUDED #define SGS_IDBG_H_INCLUDED #include <sgscript.h> #include <sgs_util.h> typedef struct _sgs_IDbg { SGS_CTX; sgs_MsgFunc pfn; void* pctx; sgs_MemBuf input; char iword[ 32 ]; int inside; ptrdiff_t stkoff; ptrdiff_t stksize; int minlev; } sgs_IDbg; #define SGS_IDBG sgs_IDbg* D int sgs_InitIDbg( SGS_CTX, SGS_IDBG ); int sgs_CloseIDbg( SGS_CTX, SGS_IDBG ); #endif <file_sep>/ext/cpp/cppbind_example.cpp #include <stdio.h> #include <string> #include "cppbind.h" class Account { public: int coins; int numtransactions; std::string name; Account() : coins( 0 ), numtransactions( 0 ) { printf( "Created a new account!\n" ); } ~Account() { printf( "Deleted the account.\n" ); } int getter_coins( SGS_CTX ){ sgs_PushInt( C, coins ); return SGS_SUCCESS; } int Add( SGS_CTX ) { int orig = coins; sgs_Int I; if( !sgs_LoadArgs( C, "i", &I ) ) return 0; coins += (int) I; numtransactions++; printf( "Transaction #%04d | before=%d after=%d\n", numtransactions, orig, coins ); return 0; } }; #define SGS_CLASS Account SGS_DECLARE_IFACE; SGS_METHOD_WRAPPER( Add ); SGS_BEGIN_GENERIC_GETINDEXFUNC SGS_GIF_METHOD( Add ) SGS_GIF_GETTER( coins ) SGS_GIF_CUSTOM( name, sgs_PushString(C,item->name.c_str()) ) SGS_GIF_CUSTOM( transaction_count, sgs_PushInt(C,item->numtransactions) ) SGS_END_GENERIC_GETINDEXFUNC; SGS_BEGIN_GENERIC_SETINDEXFUNC SGS_GIF_CUSTOM( name, char* name; sgs_SizeVal namelen; if( !sgs_ParseStringP( C, val, &name, &namelen ) ) return SGS_EINVAL; item->name.assign( name, (size_t) namelen ); ) SGS_END_GENERIC_SETINDEXFUNC; SGS_GENERIC_DESTRUCTOR; SGS_DEFINE_IFACE "Account", SGS_IFACE_DESTRUCT, NULL, SGS_IFACE_GETINDEX, SGS_IFACE_SETINDEX, NULL, NULL, NULL, NULL, NULL, NULL SGS_DEFINE_IFACE_END; SGS_DEFINE_EMPTY_CTORFUNC; #undef SGS_CLASS const char* code = "\n\ a = Account();\n\ a.Add( 1337 );\n\ print 'reading from property: ' $ a.coins $ '\\n';\n\ a.name = 'special';\n\ printvar( a.name, a.transaction_count, a.coins );\n\ "; int main( int argc, char* argv[] ) { printf( "\n//\n/// SGScript / CPPBIND test\n//\n" ); SGS_CTX = sgs_CreateEngine(); SGS_REGISTER( Account ); sgs_ExecString( C, code ); sgs_DestroyEngine( C ); return 0; } <file_sep>/src/sgs_util.h #ifndef SGS_UTIL_H_INCLUDED #define SGS_UTIL_H_INCLUDED #include <stdlib.h> #include <string.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif #ifdef SGS_INTERNAL # ifdef SGS_REALLY_INTERNAL # ifndef TRUE # define TRUE sgs_TRUE # endif # ifndef FALSE # define FALSE sgs_FALSE # endif # define MIN sgs_MIN # define MAX sgs_MAX # define ARRAY_SIZE sgs_ARRAY_SIZE # define HAS_FLAG sgs_HAS_FLAG # define HAS_ANY_FLAG sgs_HAS_ANY_FLAG # endif # define LineNum sgs_LineNum # define isoneof sgs_isoneof # define hexchar sgs_hexchar # define gethex sgs_gethex # define decchar sgs_decchar # define getdec sgs_getdec # define octchar sgs_octchar # define getoct sgs_getoct # define binchar sgs_binchar # define getbin sgs_getbin # define AS_ SGS_AS_ # define AS_INT8 SGS_AS_INT8 # define AS_UINT8 SGS_AS_UINT8 # define AS_INT16 SGS_AS_INT16 # define AS_UINT16 SGS_AS_UINT16 # define AS_INT32 SGS_AS_INT32 # define AS_UINT32 SGS_AS_UINT32 # define AS_INT64 SGS_AS_INT64 # define AS_UINT64 SGS_AS_UINT64 # define AS_FLOAT SGS_AS_FLOAT # define AS_DOUBLE SGS_AS_DOUBLE # define AS_INTEGER SGS_AS_INTEGER # define AS_REAL SGS_AS_REAL # define ASSUME_ALIGNED SGS_ASSUME_ALIGNED # define FUNC_HIT SGS_FUNC_HIT # define FUNC_ENTER SGS_FUNC_ENTER # define FUNC_BEGIN SGS_FUNC_BEGIN # define FUNC_END SGS_FUNC_END # define MemBuf sgs_MemBuf # define membuf_create sgs_membuf_create # define membuf_destroy sgs_membuf_destroy # define membuf_partial sgs_membuf_partial # define membuf_reserve sgs_membuf_reserve # define membuf_resize sgs_membuf_resize # define membuf_resize_opt sgs_membuf_resize_opt # define membuf_insbuf sgs_membuf_insbuf # define membuf_erase sgs_membuf_erase # define membuf_appbuf sgs_membuf_appbuf # define membuf_setstr sgs_membuf_setstr # define membuf_setstrbuf sgs_membuf_setstrbuf # define membuf_appchr sgs_membuf_appchr # define VHTIdx sgs_VHTIdx # define VHTVar sgs_VHTVar # define VHTable sgs_VHTable # define vht_init sgs_vht_init # define vht_free sgs_vht_free # define vht_get sgs_vht_get # define vht_get_str sgs_vht_get_str # define vht_set sgs_vht_set # define vht_unset sgs_vht_unset # define vht_size sgs_vht_size # define print_safe sgs_print_safe # define util_strtonum sgs_util_strtonum # define util_atoi sgs_util_atoi # define util_atof sgs_util_atof # define quicksort sgs_quicksort #endif #include "sgscript.h" /* useful shortcut definitions */ #define sgs_TRUE 1 #define sgs_FALSE 0 #define sgs_MAX( a, b ) ((a)>(b)?(a):(b)) #define sgs_MIN( a, b ) ((a)<(b)?(a):(b)) #define sgs_ARRAY_SIZE( a ) (sizeof(a)/sizeof(a[0])) #define sgs_HAS_FLAG( val, flag ) (((val)&(flag))==(flag)) #define sgs_HAS_ANY_FLAG( val, flag ) (((val)&(flag))!=0) #define SGS_GLUE(a,b) __SGS_GLUE(a,b) #define __SGS_GLUE(a,b) a ## b #define SGS_CASSERT(expr, msg) typedef char SGS_GLUE (compiler_verify_, msg) [(expr) ? (+1) : (-1)] #define sgs_isoneof( chr, str ) (!!strchr( str, chr )) typedef int16_t sgs_LineNum; SGS_APIFUNC void sgs_BreakIfFunc( const char* code, const char* file, int line ); #if SGS_DEBUG && SGS_DEBUG_VALIDATE # define sgs_BreakIf( expr ) { if( expr ){ sgs_BreakIfFunc( #expr, __FILE__, __LINE__ ); } } #else # define sgs_BreakIf( expr ) #endif /* conversions */ static SGS_INLINE int sgs_hexchar( char c ) { return ( (c) >= '0' && (c) <= '9' ) || ( (c) >= 'a' && (c) <= 'f' ) || ( (c) >= 'A' && (c) <= 'F' ); } static SGS_INLINE int sgs_gethex( char c ) { return ( (c) >= '0' && (c) <= '9' ) ? ( (c) - '0' ) : ( ( (c) >= 'a' && (c) <= 'f' ) ? ( (c) - 'a' + 10 ) : ( (c) - 'A' + 10 ) ); } static SGS_INLINE int sgs_decchar( char c ){ return c >= '0' && c <= '9'; } static SGS_INLINE int sgs_getdec( char c ){ return c - '0'; } static SGS_INLINE int sgs_octchar( char c ){ return c >= '0' && c <= '7'; } static SGS_INLINE int sgs_getoct( char c ){ return c - '0'; } static SGS_INLINE int sgs_binchar( char c ){ return c == '0' || c == '1'; } static SGS_INLINE int sgs_getbin( char c ){ return c - '0'; } #define SGS_AS_( tgt, ptr, wat ) do{ memcpy( &(tgt), (ptr), sizeof(wat) ); }while(0) #define SGS_AS_INT8( tgt, ptr ) SGS_AS_( tgt, ptr, int8_t ) #define SGS_AS_UINT8( tgt, ptr ) SGS_AS_( tgt, ptr, uint8_t ) #define SGS_AS_INT16( tgt, ptr ) SGS_AS_( tgt, ptr, int16_t ) #define SGS_AS_UINT16( tgt, ptr ) SGS_AS_( tgt, ptr, uint16_t ) #define SGS_AS_INT32( tgt, ptr ) SGS_AS_( tgt, ptr, int32_t ) #define SGS_AS_UINT32( tgt, ptr ) SGS_AS_( tgt, ptr, uint32_t ) #define SGS_AS_INT64( tgt, ptr ) SGS_AS_( tgt, ptr, int64_t ) #define SGS_AS_UINT64( tgt, ptr ) SGS_AS_( tgt, ptr, uint64_t ) #define SGS_AS_FLOAT( tgt, ptr ) SGS_AS_( tgt, ptr, float ) #define SGS_AS_DOUBLE( tgt, ptr ) SGS_AS_( tgt, ptr, double ) #define SGS_AS_INTEGER( tgt, ptr ) SGS_AS_( tgt, ptr, sgs_Int ) #define SGS_AS_REAL( tgt, ptr ) SGS_AS_( tgt, ptr, sgs_Real ) /* flow/data debugging */ #if SGS_DEBUG && SGS_DEBUG_FLOW # define SGS_FUNC_HIT( what ) \ printf( "Hit \"%s\" line %d in function \"%s\"\n", what, __LINE__, __FUNCTION__ ); # define SGS_FUNC_ENTER \ printf( "Entering a function from \"%s\" at line %d\n", __FUNCTION__, __LINE__ ); # define SGS_FUNC_BEGIN \ printf( "Inside \"%s\"\n", __FUNCTION__ ); # define SGS_FUNC_END \ printf( "Out of \"%s\" at line %d\n", __FUNCTION__, __LINE__ ); #else # define SGS_FUNC_HIT( what ) # define SGS_FUNC_ENTER # define SGS_FUNC_BEGIN # define SGS_FUNC_END #endif SGS_APIFUNC void sgs_print_safe( FILE* fp, const char* buf, size_t size ); /* string buffer */ typedef struct _sgs_MemBuf { char* ptr; size_t size; size_t mem; } sgs_MemBuf; /* data buffer */ SGS_APIFUNC sgs_MemBuf sgs_membuf_create( void ); SGS_APIFUNC void sgs_membuf_destroy( sgs_MemBuf* sb, SGS_CTX ); SGS_APIFUNC sgs_MemBuf sgs_membuf_partial( char* ch, size_t size ); SGS_APIFUNC void sgs_membuf_reserve( sgs_MemBuf* mb, SGS_CTX, size_t size ); SGS_APIFUNC void sgs_membuf_resize( sgs_MemBuf* mb, SGS_CTX, size_t size ); SGS_APIFUNC void sgs_membuf_resize_opt( sgs_MemBuf* mb, SGS_CTX, size_t size ); SGS_APIFUNC void sgs_membuf_insbuf( sgs_MemBuf* mb, SGS_CTX, size_t pos, const void* buf, size_t size ); SGS_APIFUNC void sgs_membuf_erase( sgs_MemBuf* mb, size_t from, size_t to ); SGS_APIFUNC void sgs_membuf_appbuf( sgs_MemBuf* mb, SGS_CTX, const void* buf, size_t size ); static SGS_INLINE void sgs_membuf_setstr( sgs_MemBuf* mb, SGS_CTX, const char* str ) { mb->size = 0; sgs_membuf_appbuf( mb, C, str, strlen( str ) + 1 ); mb->size--; } static SGS_INLINE void sgs_membuf_setstrbuf( sgs_MemBuf* mb, SGS_CTX, const char* str, size_t size ) { sgs_membuf_reserve( mb, C, size + 1 ); mb->size = 0; sgs_membuf_appbuf( mb, C, str, size ); mb->ptr[ mb->size ] = 0; } static SGS_INLINE void sgs_membuf_appchr( sgs_MemBuf* mb, SGS_CTX, char chr ) { sgs_membuf_appbuf( mb, C, &chr, 1 ); } /* hashing functions */ typedef uint32_t sgs_Hash; SGS_APIFUNC sgs_Hash sgs_HashFunc( const char* str, size_t size ); #define SGS_HASH_COMPUTED( h ) ((h) != 0) SGS_APIFUNC sgs_Hash sgs_HashVar( const sgs_Variable* v ); /* hash table */ typedef sgs_SizeVal sgs_VHTIdx; #define SGS_VHTIDX_EMPTY -1 #define SGS_VHTIDX_REMOVED -2 typedef struct _sgs_VHTVar { sgs_Variable key; sgs_Variable val; sgs_Hash hash; } sgs_VHTVar; typedef struct _sgs_VHTable { sgs_VHTIdx* pairs; sgs_VHTVar* vars; sgs_VHTIdx pair_mem; sgs_VHTIdx var_mem; sgs_VHTIdx size; sgs_VHTIdx num_rem; } sgs_VHTable; SGS_APIFUNC void sgs_vht_init( sgs_VHTable* T, SGS_CTX, int32_t initial_pair_mem, int32_t initial_var_mem ); SGS_APIFUNC void sgs_vht_free( sgs_VHTable* T, SGS_CTX ); SGS_APIFUNC sgs_VHTIdx sgs_vht_pair_id( sgs_VHTable* T, sgs_Variable* K, sgs_Hash hash ); SGS_APIFUNC sgs_VHTVar* sgs_vht_get( sgs_VHTable* T, sgs_Variable* K ); SGS_APIFUNC sgs_VHTVar* sgs_vht_get_str( sgs_VHTable* T, const char* str, uint32_t size, sgs_Hash hash ); SGS_APIFUNC sgs_VHTVar* sgs_vht_set( sgs_VHTable* T, SGS_CTX, sgs_Variable* K, sgs_Variable* V ); SGS_APIFUNC void sgs_vht_unset( sgs_VHTable* T, SGS_CTX, sgs_Variable* K ); #define sgs_vht_size( T ) ((T)->size) SGS_APIFUNC double sgs_GetTime(); /* returns 0 on failure, 1/2 on integer/real */ SGS_APIFUNC int sgs_util_strtonum( const char** at, const char* end, sgs_Int* outi, sgs_Real* outf ); SGS_APIFUNC sgs_Int sgs_util_atoi( const char* str, size_t len ); SGS_APIFUNC sgs_Real sgs_util_atof( const char* str, size_t len ); /* crc32 */ SGS_APIFUNC uint32_t sgs_crc32( const void* buf, size_t len, uint32_t in_crc ); SGS_APIFUNC void sgs_quicksort( void *array, size_t length, size_t size, int(*compare)(const void *, const void *, void*), void* userdata); /* UNICODE helper functions - utf8_decode: returns number of bytes parsed (negated if input was invalid) - utf8_encode: returns number of bytes written (up to 4, make sure there's space) */ #define SGS_UNICODE_INVCHAR 0xfffd #define SGS_UNICODE_INVCHAR_STR "\xef\xbf\xbd" #define SGS_UNICODE_INVCHAR_LEN 3 SGS_APIFUNC int sgs_utf8_decode( char* buf, size_t size, uint32_t* outchar ); SGS_APIFUNC int sgs_utf8_encode( uint32_t ch, char* out ); #ifdef __cplusplus } #endif #endif /* SGS_UTIL_H_INCLUDED */ <file_sep>/src/sgs_cfg.h #ifndef SGS_CFG_H_INCLUDED #define SGS_CFG_H_INCLUDED /* global debug switch */ #ifndef SGS_DEBUG # ifdef _DEBUG # define SGS_DEBUG 1 # else # define SGS_DEBUG 0 # endif #endif /* stage output dumps */ #ifndef SGS_DEBUG_DATA # define SGS_DEBUG_DATA 0 #endif /* function entry/exit tagging */ #ifndef SGS_DEBUG_FLOW # define SGS_DEBUG_FLOW 0 #endif /* instruction logging */ #ifndef SGS_DEBUG_INSTR # define SGS_DEBUG_INSTR 0 #endif /* stack dump before execution of each instruction */ #ifndef SGS_DEBUG_STATE # define SGS_DEBUG_STATE 0 #endif /* break-if */ #ifndef SGS_DEBUG_VALIDATE # define SGS_DEBUG_VALIDATE 1 #endif /* extensive buffer overflow tests */ #ifndef SGS_DEBUG_EXTRA # define SGS_DEBUG_EXTRA 0 #endif /* checks for having more memory allocated with.. ..the context memory functions than freed very fast, runs only in sgs_DestroyEngine */ #ifndef SGS_DEBUG_LEAKS # define SGS_DEBUG_LEAKS 1 #endif /* profiling */ #ifndef SGS_DUMP_BYTECODE # define SGS_DUMP_BYTECODE 0 #endif /* bytes reserved initially for token storage used to prevent multiple reallocations in the beginning */ #define SGS_TOKENLIST_PREALLOC 1024 /* maximum length for a string to be included in the string table */ #define SGS_STRINGTABLE_MAXLEN -1 /* 16 */ /* max. length of the call stack */ #define SGS_MAX_CALL_STACK_SIZE 256 /* the size of the stack buffer for temporary vsprintf'ed text if predicted text length is longer than that, the memory is allocated using the context allocator */ #define SGS_OUTPUT_STACKBUF_SIZE 128 /* postfix for function names in C functions EXTRABYTES should be set to the length of EXTRASTRING */ #define SGS_MSG_EXTRASTRING "(): " #define SGS_MSG_EXTRABYTES 4 /* object pool settings - size of object pool (max. number of items) - max. appended memory size for pool usage */ #define SGS_OBJPOOL_SIZE 64 #define SGS_OBJPOOL_MAX_APPMEM 256 /* inclusion system settings: - name of entry point function to look for - the default include path */ #define SGS_LIB_ENTRY_POINT "sgscript_main" #define SGS_INCLUDE_PATH "|/?;|/?" SGS_MODULE_EXT ";|/?.sgc;|/?.sgs;?;?" SGS_MODULE_EXT ";?.sgc;?.sgs" /* per-platform switches */ #ifdef SGS_PF_ANDROID #define SGS_INVALID_LCONV /* disables os_locale_format */ #endif #endif /* SGS_CFG_H_INCLUDED */ <file_sep>/ext/cppbc/sgs_cppbc.h #ifndef __SGS_CPPBC_H__ #define __SGS_CPPBC_H__ #include <sgscript.h> #include <new> #include <assert.h> #ifdef SGS_CPPBC_WITH_STD_STRING # include <string> #endif #ifndef SGS_CPPBC_PROCESS # define SGS_OBJECT_LITE \ static int _sgs_destruct( SGS_CTX, sgs_VarObj* obj ); \ static int _sgs_convert( SGS_CTX, sgs_VarObj* obj, int type ); \ static int _sgs_getindex( SGS_CTX, sgs_VarObj* obj, sgs_Variable* key, int isprop ); \ static int _sgs_setindex( SGS_CTX, sgs_VarObj* obj, sgs_Variable* key, sgs_Variable* val, int isprop ); \ static sgs_ObjInterface _sgs_interface[1]; # define SGS_OBJECT \ SGS_OBJECT_LITE \ sgs_VarObj* m_sgsObject; \ SGS_CTX; # define SGS_METHOD # define SGS_MULTRET int # define SGS_PROPERTY # define SGS_PROPERTY_FUNC( funcs ) # define VARNAME # define READ # define WRITE # define READ_CALLBACK # define WRITE_CALLBACK # define SGS_IFUNC( type ) static # define SGS_ALIAS( func ) #define SGS_DEFAULT_LITE_OBJECT_INTERFACE( name ) \ template<> inline void sgs_PushVar<name>( SGS_CTX, const name& v ){ sgs_PushLiteClassFrom( C, &v ); } \ template<> struct sgs_GetVar<name> { name operator () ( SGS_CTX, sgs_StkIdx item ){ \ if( sgs_IsObject( C, item, name::_sgs_interface ) ) return *(name*)sgs_GetObjectData( C, -1 ); return name(); }}; \ template<> struct sgs_GetVarP<name> { name operator () ( SGS_CTX, sgs_Variable* val ){ \ if( sgs_IsObjectP( val, name::_sgs_interface ) ) return *(name*)sgs_GetObjectDataP( val ); return name(); }}; #endif template< class T > class sgsMaybe /* nullable PODs */ { public: sgsMaybe() : isset(false) {}; sgsMaybe( const T& val ) : data(val), isset(true) {} void set( const T& val ){ data = val; isset = true; } void unset(){ isset = false; } T data; bool isset; }; template< class OwningClass > class sgsArrayIterator { public: sgsArrayIterator( OwningClass* owner ) : m_owner(owner), m_origsize(owner->size()), m_offset(-1){ sgs_ObjAcquire( m_owner->C, m_owner->m_sgsObject ); } sgsArrayIterator( const sgsArrayIterator& other ) : m_owner(other.m_owner), m_origsize(other.m_origsize), m_offset(other.m_offset){ sgs_ObjAcquire( m_owner->C, m_owner->m_sgsObject ); } const sgsArrayIterator& operator = ( const sgsArrayIterator& other ) { sgs_ObjRelease( m_owner->C, m_owner->m_sgsObject ); m_owner = other.m_owner; m_origsize = other.m_origsize; m_offset = other.m_offset; sgs_ObjAcquire( m_owner->C, m_owner->m_sgsObject ); } ~sgsArrayIterator(){ sgs_ObjRelease( m_owner->C, m_owner->m_sgsObject ); } int gcmark(){ return sgs_ObjGCMark( m_owner->C, m_owner->m_sgsObject ); } int convert( SGS_CTX, sgs_VarObj* obj, int to ) { if( to == SGS_CONVOP_TOITER ){ sgs_PushObjectPtr( C, obj ); return SGS_SUCCESS; } if( to == SGS_CONVOP_CLONE ){ sgs_PushLiteClassFrom( C, this ); return SGS_SUCCESS; } return SGS_ENOTSUP; } int getnext( SGS_CTX, int mode ) { if( m_origsize != m_owner->size() ) return SGS_EINPROC; if( !mode ) // incr { m_offset++; return m_offset >= 0 && m_offset < m_origsize; } if( mode & SGS_GETNEXT_KEY ) sgs_PushInt( C, m_offset ); if( mode & SGS_GETNEXT_VALUE ) sgs_PushVar( C, (*m_owner)[ m_offset ] ); return SGS_SUCCESS; } static int _sgs_destruct( SGS_CTX, sgs_VarObj* obj ){ ((sgsArrayIterator*)obj->data)->~sgsArrayIterator(); return SGS_SUCCESS; } static int _sgs_gcmark( SGS_CTX, sgs_VarObj* obj ){ return ((sgsArrayIterator*)obj->data)->gcmark(); } static int _sgs_convert( SGS_CTX, sgs_VarObj* obj, int type ){ return ((sgsArrayIterator*)obj->data)->convert( C, obj, type ); } static int _sgs_getnext( SGS_CTX, sgs_VarObj* obj, int type ){ return ((sgsArrayIterator*)obj->data)->getnext( C, type ); } static sgs_ObjInterface _sgs_interface[1]; OwningClass* m_owner; sgs_SizeVal m_origsize, m_offset; }; template< class OwningClass > sgs_ObjInterface sgsArrayIterator<OwningClass>::_sgs_interface[1] = { OwningClass::IteratorTypeName, sgsArrayIterator::_sgs_destruct, sgsArrayIterator::_sgs_gcmark, NULL, NULL, sgsArrayIterator::_sgs_convert, NULL, NULL, sgsArrayIterator::_sgs_getnext, NULL, NULL }; template< class T > class sgsHandle { public: sgsHandle() : object(NULL), C(NULL) {}; sgsHandle( const sgsHandle& h ) : object(h.object), C(h.C) { if( object ) _acquire(); } sgsHandle( sgs_Context* c, sgs_VarObj* obj ) : object(NULL), C(NULL) { if( obj && obj->iface == T::_sgs_interface ) { object = obj; C = c; _acquire(); } } sgsHandle( sgs_Context* c, sgs_StkIdx item ) : object(NULL), C(c) { if( sgs_IsObject( C, item, T::_sgs_interface ) ) { object = sgs_GetObjectStruct( C, item ); _acquire(); } } sgsHandle( sgs_Context* c, sgs_Variable* var ) : object(NULL), C(c) { if( sgs_IsObjectP( var, T::_sgs_interface ) ) { object = var->data.O; _acquire(); } } explicit sgsHandle( T* obj ) : object(NULL), C(NULL) { if( obj ) { object = obj->m_sgsObject; C = obj->C; _acquire(); } } ~sgsHandle(){ _release(); } const sgsHandle& operator = ( const sgsHandle& h ) { if( object != h.object ) { _release(); if( h.object && h.object->iface == T::_sgs_interface ) { object = h.object; C = h.C; _acquire(); } } return *this; } operator T*(){ return object ? static_cast<T*>( object->data ) : NULL; } operator const T*() const { return object ? static_cast<T*>( object->data ) : NULL; } T* operator -> (){ return object ? static_cast<T*>( object->data ) : NULL; } const T* operator -> () const { return object ? static_cast<T*>( object->data ) : NULL; } bool operator < ( const sgsHandle& h ) const { return object < h.object; } bool operator == ( const sgsHandle& h ) const { return object == h.object; } bool operator != ( const sgsHandle& h ) const { return object != h.object; } SGSRESULT gcmark() const { if( !object ){ return SGS_SUCCESS; } return sgs_ObjGCMark( C, object ); } void push( sgs_Context* c = NULL ) const { if( C ){ c = C; assert( C ); } else { assert( c ); } sgs_Variable v; v.type = object ? SGS_VT_OBJECT : SGS_VT_NULL; v.data.O = object; sgs_PushVariable( c, &v ); } bool not_null(){ return !!object; } class sgsVariable get_variable(); sgs_VarObj* object; SGS_CTX; void _acquire(){ if( object ) sgs_ObjAcquire( C, object ); } void _release(){ if( object ){ sgs_ObjRelease( C, object ); object = NULL; } } }; class sgsString { public: sgsString() : str(NULL), C(NULL) {}; sgsString( const sgsString& h ) : str(h.str), C(h.C) { _acquire(); } sgsString( sgs_Context* c, sgs_iStr* s ) : str(s), C(c) { _acquire(); } sgsString( sgs_Context* c, sgs_StkIdx item ) : str(NULL), C(c) { if( sgs_ParseString( C, item, NULL, NULL ) ) { sgs_Variable v; sgs_GetStackItem( C, item, &v ); str = v.data.S; } } sgsString( sgs_Context* c, sgs_Variable* var ) : str(NULL), C(c) { if( sgs_ParseStringP( C, var, NULL, NULL ) ) { str = var->data.S; _acquire(); } } sgsString( sgs_Context* c, const char* s, size_t sz ) : str(NULL), C(c) { assert( sz <= 0x7fffffff ); sgs_Variable v; sgs_InitStringBuf( C, &v, s, (sgs_SizeVal) sz ); str = v.data.S; } sgsString( sgs_Context* c, const char* s ) : str(NULL), C(c) { sgs_Variable v; sgs_InitString( C, &v, s ); str = v.data.S; } ~sgsString(){ _release(); } const sgsString& operator = ( const sgsString& s ) { if( !same_as( s ) ) { _release(); if( s.str ) { str = s.str; C = s.C; _acquire(); } } return *this; } const char* c_str() const { return str ? sgs_str_cstr( str ) : NULL; } size_t size() const { return str ? (size_t) str->size : 0; } #ifdef SGS_CPPBC_WITH_STD_STRING bool get_string( std::string& out ){ if( str ){ out = std::string( sgs_str_cstr( str ), str->size ); return true; } return false; } #endif int compare( const sgsString& s ) const { int null1 = str == NULL; int null2 = s.str == NULL; if( null1 || null2 ) return null2 - null1; int cmp = memcmp( sgs_str_cstr( str ), sgs_str_cstr( s.str ), str->size < s.str->size ? str->size : s.str->size ); if( cmp ) return cmp; return str->size == s.str->size ? 0 : ( str->size < s.str->size ? -1 : 1 ); } bool operator < ( const sgsString& s ) const { return compare( s ) < 0; } bool operator == ( const sgsString& s ) const { return compare( s ) == 0; } bool operator != ( const sgsString& s ) const { return compare( s ) != 0; } bool same_as( const sgsString& s ) const { return str == s.str; } void push( sgs_Context* c = NULL ) const { if( C ){ c = C; assert( C ); } else { assert( c ); } sgs_Variable v; v.type = str ? SGS_VT_STRING : SGS_VT_NULL; v.data.S = str; sgs_PushVariable( c, &v ); } bool not_null(){ return !!str; } class sgsVariable get_variable(); sgs_iStr* str; SGS_CTX; void _acquire(){ if( str ){ sgs_Variable v; v.type = SGS_VT_STRING; v.data.S = str; sgs_Acquire( C, &v ); } } void _release(){ if( str ){ sgs_Variable v; v.type = SGS_VT_STRING; v.data.S = str; sgs_Release( C, &v ); str = NULL; } } }; class sgsVariable { public: sgsVariable() : C(NULL) { var.type = SGS_VT_NULL; }; sgsVariable( const sgsVariable& h ) : var(h.var), C(h.C) { if( h.var.type != SGS_VT_NULL ) { var = h.var; C = h.C; _acquire(); } } sgsVariable( sgs_Context* c ) : C(c) { var.type = SGS_VT_NULL; } sgsVariable( sgs_Context* c, sgs_StkIdx item ) : C(c) { var.type = SGS_VT_NULL; sgs_PeekStackItem( C, item, &var ); _acquire(); } sgsVariable( sgs_Context* c, sgs_Variable* v ) : C(c) { if( v && v->type != SGS_VT_NULL ) { var = *v; _acquire(); } } ~sgsVariable(){ _release(); } const sgsVariable& operator = ( const sgsVariable& h ) { if( *this != h ) { _release(); if( h.var.type != SGS_VT_NULL ) { var = h.var; C = h.C; _acquire(); } } return *this; } bool operator < ( const sgsVariable& h ) const { return var.type < h.var.type || var.data.I < h.var.data.I; } bool operator == ( const sgsVariable& h ) const { return var.type == h.var.type && var.data.I == h.var.data.I; } bool operator != ( const sgsVariable& h ) const { return var.type != h.var.type || var.data.I != h.var.data.I; } void push( sgs_Context* c = NULL ) const { if( C ){ c = C; assert( C ); } else { assert( c ); } sgs_PushVariable( c, const_cast<sgs_Variable*>( &var ) ); } SGSRESULT gcmark() { if( !C ) return SGS_SUCCESS; return sgs_GCMark( C, &var ); } bool not_null(){ return var.type != SGS_VT_NULL; } bool is_object( sgs_ObjInterface* iface ){ return sgs_IsObjectP( &var, iface ); } template< class T > bool is_handle(){ return sgs_IsObjectP( &var, T::_sgs_interface ); } template< class T > T* get_object_data(){ return (T*) sgs_GetObjectDataP( &var ); } template< class T > sgsHandle<T> get_handle(){ return sgsHandle<T>( &var ); } bool is_string(){ return var.type == SGS_VT_STRING; } sgsString get_string(){ return is_string() ? sgsString( C, var.data.S ) : sgsString(); } sgs_Variable var; SGS_CTX; void _acquire(){ if( C ){ sgs_Acquire( C, &var ); } } void _release(){ if( C ){ sgs_Release( C, &var ); var.type = SGS_VT_NULL; } } }; template<class T> inline sgsVariable sgsHandle<T>::get_variable() { sgs_Variable v; v.type = object ? SGS_VT_OBJECT : SGS_VT_NULL; v.data.O = object; return sgsVariable( C, &v ); } inline sgsVariable sgsString::get_variable() { sgs_Variable v; v.type = str ? SGS_VT_STRING : SGS_VT_NULL; v.data.S = str; return sgsVariable( C, &v ); } /* PushVar [stack] */ template< class T > void sgs_PushVar( SGS_CTX, const T& ); template< class T > inline void sgs_PushVar( SGS_CTX, T* v ){ sgs_PushClass( C, v ); } template< class T > inline void sgs_PushVar( SGS_CTX, sgsMaybe<T> v ){ if( v.isset ) sgs_PushVar( C, v.data ); else sgs_PushNull( C ); } template< class T > inline void sgs_PushVar( SGS_CTX, sgsHandle<T> v ){ v.push( C ); } template<> inline void sgs_PushVar<sgsVariable>( SGS_CTX, const sgsVariable& v ){ v.push( C ); } #define SGS_DECL_PUSHVAR( type, parsefn ) template<> inline void sgs_PushVar<type>( SGS_CTX, const type& v ){ parsefn( C, v ); } SGS_DECL_PUSHVAR( bool, sgs_PushBool ); #define SGS_DECL_PUSHVAR_INT( type ) template<> inline void sgs_PushVar<type>( SGS_CTX, const type& v ){ sgs_PushInt( C, (sgs_Int) v ); } SGS_DECL_PUSHVAR_INT( signed char ); SGS_DECL_PUSHVAR_INT( unsigned char ); SGS_DECL_PUSHVAR_INT( signed short ); SGS_DECL_PUSHVAR_INT( unsigned short ); SGS_DECL_PUSHVAR_INT( signed int ); SGS_DECL_PUSHVAR_INT( unsigned int ); SGS_DECL_PUSHVAR_INT( signed long ); SGS_DECL_PUSHVAR_INT( unsigned long ); SGS_DECL_PUSHVAR_INT( signed long long ); SGS_DECL_PUSHVAR_INT( unsigned long long ); SGS_DECL_PUSHVAR( float, sgs_PushReal ); SGS_DECL_PUSHVAR( double, sgs_PushReal ); template<> inline void sgs_PushVar<sgsString>( SGS_CTX, const sgsString& v ){ v.push( C ); } SGS_DECL_PUSHVAR( sgs_CFunc, sgs_PushCFunction ); #ifdef SGS_CPPBC_WITH_STD_STRING template<> inline void sgs_PushVar<std::string>( SGS_CTX, const std::string& v ){ sgs_PushStringBuf( C, v.c_str(), (sgs_SizeVal) v.size() ); } #endif /* GETVAR [stack] */ template< class T > struct sgs_GetVar { T operator () ( SGS_CTX, sgs_StkIdx item ); }; template< class T > struct sgs_GetVarObj { T* operator () ( SGS_CTX, sgs_StkIdx item ) { if( sgs_IsObject( C, item, T::_sgs_interface ) ) return static_cast<T*>( sgs_GetObjectData( C, item ) ); return NULL; }}; template<> struct sgs_GetVar<bool> { bool operator () ( SGS_CTX, sgs_StkIdx item ) { sgs_Bool v; if( sgs_ParseBool( C, item, &v ) ) return v; return false; }}; #define SGS_DECL_GETVAR_INT( type ) \ template<> struct sgs_GetVar<type> { type operator () ( SGS_CTX, sgs_StkIdx item ){ \ sgs_Int v; if( sgs_ParseInt( C, item, &v ) ) return (type) v; return 0; }}; SGS_DECL_GETVAR_INT( signed char ); SGS_DECL_GETVAR_INT( unsigned char ); SGS_DECL_GETVAR_INT( signed short ); SGS_DECL_GETVAR_INT( unsigned short ); SGS_DECL_GETVAR_INT( signed int ); SGS_DECL_GETVAR_INT( unsigned int ); SGS_DECL_GETVAR_INT( signed long ); SGS_DECL_GETVAR_INT( unsigned long ); SGS_DECL_GETVAR_INT( signed long long ); template<> struct sgs_GetVar<float> { float operator () ( SGS_CTX, sgs_StkIdx item ){ sgs_Real v; if( sgs_ParseReal( C, item, &v ) ) return (float) v; return 0; }}; template<> struct sgs_GetVar<double> { double operator () ( SGS_CTX, sgs_StkIdx item ){ sgs_Real v; if( sgs_ParseReal( C, item, &v ) ) return (double) v; return 0; }}; template<> struct sgs_GetVar<char*> { char* operator () ( SGS_CTX, sgs_StkIdx item ){ char* str = NULL; sgs_ParseString( C, item, &str, NULL ); return str; }}; template<> struct sgs_GetVar<sgsString> { sgsString operator () ( SGS_CTX, sgs_StkIdx item ){ return sgsString( C, item ); }}; #ifdef SGS_CPPBC_WITH_STD_STRING template<> struct sgs_GetVar<std::string> { std::string operator () ( SGS_CTX, sgs_StkIdx item ){ char* str; sgs_SizeVal size; if( sgs_ParseString( C, item, &str, &size ) ) return std::string( str, (size_t) size ); return std::string(); }}; #endif template< class O > struct sgs_GetVar< sgsMaybe<O> > { sgsMaybe<O> operator () ( SGS_CTX, sgs_StkIdx item ) const { if( sgs_ItemType( C, item ) != SGS_VT_NULL ) return sgsMaybe<O>( sgs_GetVar<O>()( C, item ) ); return sgsMaybe<O>(); } }; template< class O > struct sgs_GetVar< sgsHandle<O> > { sgsHandle<O> operator () ( SGS_CTX, sgs_StkIdx item ) const { return sgsHandle<O>( C, item ); } }; template<> struct sgs_GetVar< sgsVariable > { sgsVariable operator () ( SGS_CTX, sgs_StkIdx item ) const { return sgsVariable( C, item ); } }; /* GETVARP [pointer] */ template< class T > struct sgs_GetVarP { T operator () ( SGS_CTX, sgs_Variable* var ); }; template< class T > struct sgs_GetVarObjP { T* operator () ( SGS_CTX, sgs_Variable* var ) { if( sgs_IsObjectP( var, T::_sgs_interface ) ) return static_cast<T*>( sgs_GetObjectDataP( var ) ); return NULL; }}; template<> struct sgs_GetVarP<bool> { bool operator () ( SGS_CTX, sgs_Variable* var ) { sgs_Bool v; if( sgs_ParseBoolP( C, var, &v ) ) return v; return false; }}; #define SGS_DECL_GETVARP_INT( type ) \ template<> struct sgs_GetVarP<type> { type operator () ( SGS_CTX, sgs_Variable* var ){ \ sgs_Int v; if( sgs_ParseIntP( C, var, &v ) ) return (type) v; return 0; }}; SGS_DECL_GETVARP_INT( signed char ); SGS_DECL_GETVARP_INT( unsigned char ); SGS_DECL_GETVARP_INT( signed short ); SGS_DECL_GETVARP_INT( unsigned short ); SGS_DECL_GETVARP_INT( signed int ); SGS_DECL_GETVARP_INT( unsigned int ); SGS_DECL_GETVARP_INT( signed long ); SGS_DECL_GETVARP_INT( unsigned long ); SGS_DECL_GETVARP_INT( signed long long ); template<> struct sgs_GetVarP<float> { float operator () ( SGS_CTX, sgs_Variable* var ){ sgs_Real v; if( sgs_ParseRealP( C, var, &v ) ) return (float) v; return 0; }}; template<> struct sgs_GetVarP<double> { double operator () ( SGS_CTX, sgs_Variable* var ){ sgs_Real v; if( sgs_ParseRealP( C, var, &v ) ) return (double) v; return 0; }}; template<> struct sgs_GetVarP<char*> { char* operator () ( SGS_CTX, sgs_Variable* var ){ char* str = NULL; sgs_ParseStringP( C, var, &str, NULL ); return str; }}; template<> struct sgs_GetVarP<sgsString> { sgsString operator () ( SGS_CTX, sgs_Variable* var ){ sgsString S; if( sgs_ParseStringP( C, var, NULL, NULL ) ) S = sgsString( C, var->data.S ); return S; }}; #ifdef SGS_CPPBC_WITH_STD_STRING template<> struct sgs_GetVarP<std::string> { std::string operator () ( SGS_CTX, sgs_Variable* var ){ char* str; sgs_SizeVal size; if( sgs_ParseStringP( C, var, &str, &size ) ) return std::string( str, (size_t) size ); return std::string(); }}; #endif template< class O > struct sgs_GetVarP< sgsMaybe<O> > { sgsMaybe<O> operator () ( SGS_CTX, sgs_Variable* var ) const { if( var->type != SGS_VT_NULL ) return sgsMaybe<O>( sgs_GetVarP<O>()( C, var ) ); return sgsMaybe<O>(); } }; template< class O > struct sgs_GetVarP< sgsHandle<O> > { sgsHandle<O> operator () ( SGS_CTX, sgs_Variable* var ) const { return sgsHandle<O>( C, var ); } }; template<> struct sgs_GetVarP< sgsVariable > { sgsVariable operator () ( SGS_CTX, sgs_Variable* var ) const { return sgsVariable( C, var ); } }; template< class T > void sgs_PushClass( SGS_CTX, T* inst ) { sgs_PushObject( C, inst, T::_sgs_interface ); inst->m_sgsObject = sgs_GetObjectStruct( C, -1 ); inst->C = C; } template< class T > T* sgs_PushClassIPA( SGS_CTX ) { T* data = static_cast<T*>( sgs_PushObjectIPA( C, (sgs_SizeVal) sizeof(T), T::_sgs_interface ) ); data->m_sgsObject = sgs_GetObjectStruct( C, -1 ); data->C = C; return data; } template< class T> T* sgs_InitPushedClass( T* inst, SGS_CTX ) { inst->C = C; inst->m_sgsObject = sgs_GetObjectStruct( C, -1 ); return inst; } #define SGS_PUSHCLASS( C, name, args ) sgs_InitPushedClass(new (sgs_PushClassIPA< name >( C )) name args, C ) template< class T > T* sgs_PushClassFrom( SGS_CTX, T* inst ) { T* data = SGS_PUSHCLASS( C, T, ( *inst ) ); return sgs_InitPushedClass( data, C ); } template< class T > void sgs_PushLiteClass( SGS_CTX, T* inst ){ sgs_PushObject( C, inst, T::_sgs_interface ); } template< class T > T* sgs_PushLiteClassIPA( SGS_CTX ){ return static_cast<T*>( sgs_PushObjectIPA( C, (sgs_SizeVal) sizeof(T), T::_sgs_interface ) ); } #define SGS_PUSHLITECLASS( C, name, args ) (new (sgs_PushLiteClassIPA< name >( C )) name args ) template< class T > T* sgs_PushLiteClassFrom( SGS_CTX, const T* inst ) { T* data = SGS_PUSHLITECLASS( C, T, ( *inst ) ); return data; } #endif // __SGS_CPPBC_H__ <file_sep>/src/sgs_ctx.c #include <stdarg.h> #include <ctype.h> #include <errno.h> #define SGS_INTERNAL #define SGS_REALLY_INTERNAL #define SGS_INTERNAL_STRINGTABLES #include "sgs_int.h" #if SGS_DEBUG && SGS_DEBUG_FLOW # define DBGINFO( text ) sgs_Msg( C, SGS_INFO, text ) #else # define DBGINFO( text ) #endif static const char* g_varnames[] = { "null", "bool", "int", "real", "string", "func", "cfunc", "obj", "ptr" }; static void ctx_init( SGS_CTX ) { C->version = SGS_VERSION_INT; C->apiversion = SGS_API_VERSION; C->output_fn = sgs_StdOutputFunc; C->output_ctx = stdout; C->erroutput_fn = sgs_StdOutputFunc; C->erroutput_ctx = stderr; C->minlev = SGS_INFO; C->apilev = SGS_ERROR + 1; C->msg_fn = sgs_StdMsgFunc; C->msg_ctx = stderr; C->last_errno = 0; C->hook_fn = NULL; C->hook_ctx = NULL; C->state = 0; C->fctx = NULL; C->filename = NULL; vht_init( &C->stringtable, C, 256, 256 ); C->stack_mem = 32; C->stack_base = sgs_Alloc_n( sgs_Variable, C->stack_mem ); C->stack_off = C->stack_base; C->stack_top = C->stack_base; C->clstk_mem = 32; C->clstk_base = sgs_Alloc_n( sgs_Closure*, C->clstk_mem ); C->clstk_off = C->clstk_base; C->clstk_top = C->clstk_base; C->sf_first = NULL; C->sf_last = NULL; C->sf_cached = NULL; C->sf_count = 0; C->objs = NULL; C->objcount = 0; C->redblue = 0; C->gclist = NULL; C->gclist_size = 0; C->gcrun = FALSE; #if SGS_OBJPOOL_SIZE > 0 C->objpool_data = sgs_Alloc_n( sgs_ObjPoolItem, SGS_OBJPOOL_SIZE ); #else C->objpool_data = NULL; #endif C->objpool_size = 0; vht_init( &C->typetable, C, 32, 32 ); } sgs_Context* sgs_CreateEngineExt( sgs_MemFunc memfunc, void* mfuserdata ) { SGS_CTX = (sgs_Context*) memfunc( mfuserdata, NULL, sizeof( sgs_Context ) ); C->memsize = sizeof( sgs_Context ); C->numallocs = 1; C->numblocks = 1; C->numfrees = 0; C->memfunc = memfunc; C->mfuserdata = mfuserdata; ctx_init( C ); sgsSTD_GlobalInit( C ); sgsSTD_PostInit( C ); return C; } void sgs_DestroyEngine( SGS_CTX ) { sgs_StackFrame* sf = C->sf_cached, *sfn; /* clear the stack */ while( C->stack_base != C->stack_top ) { C->stack_top--; sgs_Release( C, C->stack_top ); } while( C->clstk_base != C->clstk_top ) { C->clstk_top--; if( --(*C->clstk_top)->refcount < 1 ) { sgs_Release( C, &(*C->clstk_top)->var ); sgs_Dealloc( *C->clstk_top ); } } sgsSTD_GlobalFree( C ); sgs_GCExecute( C ); sgs_BreakIf( C->objs || C->objcount ); sgs_Dealloc( C->stack_base ); sgs_Dealloc( C->clstk_base ); vht_free( &C->typetable, C ); { VHTVar* p = C->stringtable.vars; VHTVar* pend = p + C->stringtable.size; while( p < pend ) { string_t* st = p->key.data.S; st->refcount--; sgs_BreakIf( st->refcount > 0 ); sgs_BreakIf( st->refcount < 0 ); sgs_Dealloc( st ); p++; } } vht_free( &C->stringtable, C ); /* free the call stack */ while( sf ) { sfn = sf->cached; sgs_Dealloc( sf ); sf = sfn; } C->sf_cached = NULL; #if SGS_OBJPOOL_SIZE > 0 { int32_t i; for( i = 0; i < C->objpool_size; ++i ) sgs_Dealloc( C->objpool_data[ i ].obj ); sgs_Dealloc( C->objpool_data ); } #endif #ifdef SGS_DEBUG_LEAKS sgs_BreakIf( C->memsize > sizeof( sgs_Context ) ); sgs_BreakIf( C->memsize < sizeof( sgs_Context ) ); #endif C->msg_fn = NULL; C->msg_ctx = NULL; C->memfunc( C->mfuserdata, C, 0 ); } const char* sgs_CodeString( int type, int val ) { if( type == SGS_CODE_ER ) { if( val < SGS_EINPROC ) return "UNKNOWN ERROR"; if( val > SGS_SUCCESS ) val = 0; return sgs_ErrNames[ - val ]; } else if( type == SGS_CODE_VT ) { if( val < 0 || val >= SGS_VT__COUNT ) return NULL; return sgs_VarNames[ val ]; } else if( type == SGS_CODE_OP ) { if( val < 0 || val >= SGS_SI_COUNT ) return NULL; return sgs_OpNames[ val ]; } else return NULL; } void sgs_GetOutputFunc( SGS_CTX, sgs_OutputFunc* outf, void** outc ) { *outf = C->output_fn; *outc = C->output_ctx; } void sgs_SetOutputFunc( SGS_CTX, sgs_OutputFunc func, void* ctx ) { sgs_BreakIf( func == NULL ); if( func == SGSOUTPUTFN_DEFAULT ) func = sgs_StdOutputFunc; if( !ctx && func == sgs_StdOutputFunc ) ctx = stdout; C->output_fn = func; C->output_ctx = ctx; } void sgs_Write( SGS_CTX, const void* ptr, size_t size ) { C->output_fn( C->output_ctx, C, ptr, size ); } SGSBOOL sgs_Writef( SGS_CTX, const char* what, ... ) { char buf[ SGS_OUTPUT_STACKBUF_SIZE ]; MemBuf info = membuf_create(); int cnt; va_list args; char* ptr = buf; va_start( args, what ); cnt = SGS_VSPRINTF_LEN( what, args ); va_end( args ); if( cnt < 0 ) return FALSE; if( cnt >= SGS_OUTPUT_STACKBUF_SIZE ) { /* WP: false alarm */ membuf_resize( &info, C, (size_t) cnt + 1 ); ptr = info.ptr; } va_start( args, what ); vsprintf( ptr, what, args ); va_end( args ); ptr[ cnt ] = 0; sgs_WriteStr( C, ptr ); membuf_destroy( &info, C ); return TRUE; } void sgs_GetErrOutputFunc( SGS_CTX, sgs_OutputFunc* outf, void** outc ) { *outf = C->erroutput_fn; *outc = C->erroutput_ctx; } void sgs_SetErrOutputFunc( SGS_CTX, sgs_OutputFunc func, void* ctx ) { sgs_BreakIf( func == NULL ); if( func == SGSOUTPUTFN_DEFAULT ) func = sgs_StdOutputFunc; if( !ctx && func == sgs_StdOutputFunc ) ctx = stderr; C->erroutput_fn = func; C->erroutput_ctx = ctx; } void sgs_ErrWrite( SGS_CTX, const void* ptr, size_t size ) { C->erroutput_fn( C->erroutput_ctx, C, ptr, size ); } SGSBOOL sgs_ErrWritef( SGS_CTX, const char* what, ... ) { char buf[ SGS_OUTPUT_STACKBUF_SIZE ]; MemBuf info = membuf_create(); int cnt; va_list args; char* ptr = buf; va_start( args, what ); cnt = SGS_VSPRINTF_LEN( what, args ); va_end( args ); if( cnt < 0 ) return FALSE; if( cnt >= SGS_OUTPUT_STACKBUF_SIZE ) { /* WP: false alarm */ membuf_resize( &info, C, (size_t) cnt + 1 ); ptr = info.ptr; } va_start( args, what ); vsprintf( ptr, what, args ); va_end( args ); ptr[ cnt ] = 0; sgs_ErrWriteStr( C, ptr ); membuf_destroy( &info, C ); return TRUE; } void sgs_GetMsgFunc( SGS_CTX, sgs_MsgFunc* outf, void** outc ) { *outf = C->msg_fn; *outc = C->msg_ctx; } void sgs_SetMsgFunc( SGS_CTX, sgs_MsgFunc func, void* ctx ) { sgs_BreakIf( func == NULL ); if( func == SGSMSGFN_DEFAULT ) func = sgs_StdMsgFunc; else if( func == SGSMSGFN_DEFAULT_NOABORT ) func = sgs_StdMsgFunc_NoAbort; if( !ctx && ( func == sgs_StdMsgFunc || func == sgs_StdMsgFunc_NoAbort ) ) ctx = NULL; C->msg_fn = func; C->msg_ctx = ctx; } int sgs_Msg( SGS_CTX, int type, const char* what, ... ) { char buf[ SGS_OUTPUT_STACKBUF_SIZE ]; MemBuf info = membuf_create(); int off = 0, cnt = 0, slen = 0; va_list args; char* ptr = buf; /* error level filter */ if( type < C->minlev ) return 0; /* error suppression */ if( C->sf_last && C->sf_last->errsup > 0 ) return 0; va_start( args, what ); cnt = SGS_VSPRINTF_LEN( what, args ); va_end( args ); sgs_BreakIf( cnt < 0 ); if( cnt < 0 ) { C->msg_fn( C->msg_ctx, C, SGS_ERROR, "sgs_Msg ERROR: failed to print the message" ); return 0; } if( C->sf_last && C->sf_last->nfname ) { /* WP: it is expected that native functions .. .. will not set names of more than 2GB length */ slen = (int) strlen( C->sf_last->nfname ); off = slen + SGS_MSG_EXTRABYTES; cnt += off; } if( cnt >= SGS_OUTPUT_STACKBUF_SIZE ) { /* WP: cnt is never negative */ membuf_resize( &info, C, (size_t) cnt + 1 ); ptr = info.ptr; } if( C->sf_last && C->sf_last->nfname ) { /* WP: slen is generated from size_t, thus is never negative */ memcpy( ptr, C->sf_last->nfname, (size_t) slen ); memcpy( ptr + slen, SGS_MSG_EXTRASTRING, SGS_MSG_EXTRABYTES ); } va_start( args, what ); vsprintf( ptr + off, what, args ); va_end( args ); ptr[ cnt ] = 0; C->msg_fn( C->msg_ctx, C, type, ptr ); membuf_destroy( &info, C ); return 0; } void sgs_WriteErrorInfo( SGS_CTX, int flags, sgs_ErrorOutputFunc func, void* ctx, int type, const char* msg ) { if( flags & SGS_ERRORINFO_STACK ) { sgs_StackFrame* p = sgs_GetFramePtr( C, FALSE ); UNUSED( ctx ); while( p != NULL ) { const char* file, *name; int ln; if( !p->next && !p->code ) break; sgs_StackFrameInfo( C, p, &name, &file, &ln ); if( ln ) func( ctx, "- \"%s\" in %s, line %d\n", name, file, ln ); else func( ctx, "- \"%s\" in %s\n", name, file ); p = p->next; } } if( flags & SGS_ERRORINFO_ERROR ) { static const char* errpfxs[ 3 ] = { "Info", "Warning", "Error" }; type = type / 100 - 1; if( type < 0 ) type = 0; if( type > 2 ) type = 2; func( ctx, "%s: %s\n", errpfxs[ type ], msg ); } } static void serialize_output_func( void* ud, SGS_CTX, const void* ptr, size_t datasize ) { MemBuf* B = (MemBuf*) ud; membuf_appbuf( B, C, ptr, datasize ); } void sgs_PushErrorInfo( SGS_CTX, int flags, int type, const char* msg ) { sgs_OutputFunc oldfn = C->output_fn; void* oldctx = C->output_ctx; MemBuf B = membuf_create(); C->output_fn = serialize_output_func; C->output_ctx = &B; sgs_WriteErrorInfo( C, flags, (sgs_ErrorOutputFunc) sgs_Writef, C, type, msg ); /* WP: hopefully the error messages will not be more than 2GB long */ sgs_PushStringBuf( C, B.ptr, (sgs_SizeVal) B.size ); membuf_destroy( &B, C ); C->output_fn = oldfn; C->output_ctx = oldctx; } SGSBOOL sgs_GetHookFunc( SGS_CTX, sgs_HookFunc* outf, void** outc ) { if( C->hook_fn ) { *outf = C->hook_fn; *outc = C->hook_ctx; return 1; } return 0; } void sgs_SetHookFunc( SGS_CTX, sgs_HookFunc func, void* ctx ) { C->hook_fn = func; C->hook_ctx = ctx; } void* sgs_Memory( SGS_CTX, void* ptr, size_t size ) { void* p; if( size ) { size += 16; C->memsize += size; C->numallocs++; C->numblocks++; } if( ptr ) { ptr = ((char*)ptr) - 16; C->memsize -= *(size_t*)ptr; C->numfrees++; C->numblocks--; } p = C->memfunc( C->mfuserdata, ptr, size ); if( p ) { memcpy( p, &size, sizeof(size_t) ); p = ((char*)p) + 16; } return p; } static int ctx_decode( SGS_CTX, const char* buf, size_t size, sgs_CompFunc** out ) { sgs_CompFunc* func = NULL; if( sgsBC_ValidateHeader( buf, size ) < SGS_HEADER_SIZE ) { /* invalid / unsupported / unrecognized file */ return 0; } { const char* ret; ret = sgsBC_Buf2Func( C, C->filename ? C->filename : "", buf, size, &func ); if( ret ) { /* just invalid, error! */ sgs_Msg( C, SGS_ERROR, "Failed to read bytecode file (%s)", ret ); return -1; } } *out = func; return 1; } static int ctx_compile( SGS_CTX, const char* buf, size_t size, sgs_CompFunc** out ) { sgs_CompFunc* func = NULL; TokenList tlist = NULL; FTNode* ftree = NULL; C->state = 0; DBGINFO( "...running the tokenizer" ); tlist = sgsT_Gen( C, buf, size ); if( !tlist || C->state & SGS_HAS_ERRORS ) goto error; #if SGS_DEBUG && SGS_DEBUG_DATA sgsT_DumpList( tlist, NULL ); #endif DBGINFO( "...running the function tree builder" ); ftree = sgsFT_Compile( C, tlist ); if( !ftree || C->state & SGS_HAS_ERRORS ) goto error; #if SGS_DEBUG && SGS_DEBUG_DATA sgsFT_Dump( ftree ); #endif DBGINFO( "...generating the opcode" ); func = sgsBC_Generate( C, ftree ); if( !func || C->state & SGS_HAS_ERRORS ) goto error; DBGINFO( "...cleaning up tokens/function tree" ); sgsFT_Destroy( C, ftree ); ftree = NULL; sgsT_Free( C, tlist ); tlist = NULL; #if SGS_DUMP_BYTECODE || ( SGS_DEBUG && SGS_DEBUG_DATA ) sgsBC_Dump( func ); #endif *out = func; return 1; error: if( func ) sgsBC_Free( C, func ); if( ftree ) sgsFT_Destroy( C, ftree ); if( tlist ) sgsT_Free( C, tlist ); return 0; } static SGSRESULT ctx_execute( SGS_CTX, const char* buf, size_t size, int clean, int* rvc ) { int returned, rr; ptrdiff_t oo; sgs_CompFunc* func; oo = C->stack_off - C->stack_base; if( !( rr = ctx_decode( C, buf, size, &func ) ) && !ctx_compile( C, buf, size, &func ) ) return SGS_ECOMP; if( rr < 0 ) return SGS_EINVAL; DBGINFO( "...executing the generated function" ); C->stack_off = C->stack_top; C->gclist = (sgs_Variable*) (void*) ASSUME_ALIGNED( func->consts.ptr, 4 ); /* WP: const limit */ C->gclist_size = (uint16_t) func->consts.size / sizeof( sgs_Variable ); returned = sgsVM_ExecFn( C, func->numtmp, func->code.ptr, func->code.size, func->consts.ptr, func->consts.size, clean, (uint16_t*) (void*) ASSUME_ALIGNED( func->lnbuf.ptr, 4 ) ); if( rvc ) *rvc = returned; C->gclist = NULL; C->gclist_size = 0; C->stack_off = C->stack_base + oo; DBGINFO( "...cleaning up bytecode/constants" ); sgsBC_Free( C, func ); DBGINFO( "...finished!" ); return SGS_SUCCESS; } SGSRESULT sgs_EvalBuffer( SGS_CTX, const char* buf, size_t size, int* rvc ) { DBGINFO( "sgs_EvalBuffer called!" ); if( size > 0x7fffffff ) return SGS_EINVAL; return ctx_execute( C, buf, size, !rvc, rvc ); } SGSRESULT sgs_EvalFile( SGS_CTX, const char* file, int* rvc ) { int ret; long len; size_t ulen; FILE* f; char* data; const char* ofn; unsigned char magic[4]; DBGINFO( "sgs_EvalFile called!" ); f = fopen( file, "rb" ); if( !f ) { sgs_Errno( C, 0 ); return SGS_ENOTFND; } fseek( f, 0, SEEK_END ); len = ftell( f ); if( len < 0 ) { sgs_Errno( C, 0 ); return SGS_EINPROC; } fseek( f, 0, SEEK_SET ); if( len > 4 ) { if( fread( magic, 1, 4, f ) != 4 ) { sgs_Errno( C, 0 ); fclose( f ); return SGS_EINPROC; } if( ( magic[0] == 0x7f && magic[1] == 'E' && magic[2] == 'L' && magic[3] == 'F' ) /* ELF binary */ || ( magic[0] == 'M' && magic[1] == 'Z' ) /* DOS binary / DOS stub for PE binary */ || ( magic[0] == 0xCA && magic[1] == 0xFE && magic[2] == 0xBA && magic[3] == 0xBE ) /* Mach-O binary 1 */ || ( magic[0] == 0xCE && magic[1] == 0xFA && magic[2] == 0xED && magic[3] == 0xFE ) /* Mach-O binary 2 */ || ( magic[0] == 0xCF && magic[1] == 0xFA && magic[2] == 0xED && magic[3] == 0xFE ) /* Mach-O binary 3 */ ) { sgs_Errno( C, 1 ); fclose( f ); return SGS_EINVAL; } fseek( f, 0, SEEK_SET ); } /* WP: len is always in the range of size_t */ ulen = (size_t) len; data = sgs_Alloc_n( char, ulen ); if( fread( data, 1, ulen, f ) != ulen ) { sgs_Errno( C, 0 ); fclose( f ); sgs_Dealloc( data ); return SGS_EINPROC; } fclose( f ); ofn = C->filename; C->filename = file; ret = ctx_execute( C, data, ulen, rvc ? FALSE : TRUE, rvc ); C->filename = ofn; sgs_Dealloc( data ); return ret; } SGSRESULT sgs_Compile( SGS_CTX, const char* buf, size_t size, char** outbuf, size_t* outsize ) { MemBuf mb; sgs_CompFunc* func; if( size > 0x7fffffff ) return SGS_EINVAL; if( !ctx_compile( C, buf, size, &func ) ) return SGS_ECOMP; mb = membuf_create(); if( !sgsBC_Func2Buf( C, func, &mb ) ) { membuf_destroy( &mb, C ); return SGS_EINPROC; } *outbuf = mb.ptr; *outsize = mb.size; sgsBC_Free( C, func ); return SGS_SUCCESS; } static void _recfndump( const char* constptr, size_t constsize, const char* codeptr, size_t codesize, int gt, int args, int tmp, int clsr ) { const sgs_Variable* var = (const sgs_Variable*) (const void*) ASSUME_ALIGNED( constptr, 4 ); const sgs_Variable* vend = (const sgs_Variable*) (const void*) ASSUME_ALIGNED( constptr + constsize, 4 ); while( var < vend ) { if( var->type == SGS_VT_FUNC ) { _recfndump( (const char*) func_consts( var->data.F ), var->data.F->instr_off, (const char*) func_bytecode( var->data.F ), var->data.F->size - var->data.F->instr_off, var->data.F->gotthis, var->data.F->numargs, var->data.F->numtmp, var->data.F->numclsr ); } var++; } printf( "\nFUNC: type=%s args=%d tmp=%d closures=%d\n", gt ? "method" : "function", args, tmp, clsr ); sgsBC_DumpEx( constptr, constsize, codeptr, codesize ); } SGSRESULT sgs_DumpCompiled( SGS_CTX, const char* buf, size_t size ) { int rr; sgs_CompFunc* func; if( size > 0x7fffffff ) return SGS_EINVAL; if( !( rr = ctx_decode( C, buf, size, &func ) ) && !ctx_compile( C, buf, size, &func ) ) return SGS_ECOMP; if( rr < 0 ) return SGS_EINVAL; _recfndump( func->consts.ptr, func->consts.size, func->code.ptr, func->code.size, func->gotthis, func->numargs, func->numtmp, func->numclsr ); sgsBC_Free( C, func ); return SGS_SUCCESS; } SGSRESULT sgs_Abort( SGS_CTX ) { sgs_StackFrame* sf = C->sf_last; if( sf && !sf->iptr ) sf = sf->prev; /* should be able to use this inside a C function */ if( !sf || !sf->iptr ) return SGS_ENOTFND; while( sf && sf->iptr ) { sf->iptr = sf->iend; sf->flags |= SGS_SF_ABORTED; sf = sf->prev; } return SGS_SUCCESS; } static void ctx_print_safe( SGS_CTX, const char* str, size_t size ) { const char* strend = str + size; while( str < strend ) { if( *str == ' ' || isgraph( *str ) ) sgs_Write( C, str, 1 ); else { static const char* hexdigs = "0123456789ABCDEF"; char buf[ 4 ] = { '\\', 'x', 0, 0 }; { buf[2] = hexdigs[ (*str & 0xf0) >> 4 ]; buf[3] = hexdigs[ *str & 0xf ]; } sgs_Write( C, buf, 4 ); } str++; } } static void dumpobj( SGS_CTX, sgs_VarObj* p ) { sgs_Writef( C, "OBJECT %p refcount=%d data=%p iface=%p prev=%p next=%p redblue=%s", p, p->refcount, p->data, p->iface, p->prev, p->next, p->redblue ? "R" : "B" ); } /* g_varnames ^^ */ static void dumpvar( SGS_CTX, sgs_Variable* var ) { if( var->type > SVT_PTR ) { sgs_Writef( C, "INVALID TYPE %d\n", (int) var->type ); return; } /* WP: var->type base type info uses bits 1-8 */ sgs_Writef( C, "%s (size:%d)", g_varnames[ var->type ], sgsVM_VarSize( var ) ); switch( var->type ) { case SVT_NULL: break; case SVT_BOOL: sgs_Writef( C, " = %s", var->data.B ? "true" : "false" ); break; case SVT_INT: sgs_Writef( C, " = %" PRId64, var->data.I ); break; case SVT_REAL: sgs_Writef( C, " = %f", var->data.R ); break; case SVT_STRING: sgs_Writef( C, " [rc:%d] = \"", var->data.S->refcount ); ctx_print_safe( C, var_cstr( var ), MIN( var->data.S->size, 16 ) ); sgs_Writef( C, var->data.S->size > 16 ? "...\"" : "\"" ); break; case SVT_FUNC: sgs_Writef( C, " [rc:%d] '%s'[%d]%s tmp=%d clsr=%d", var->data.F->refcount, var->data.F->funcname.ptr ? var->data.F->funcname.ptr : "<anonymous>", (int) var->data.F->numargs, var->data.F->gotthis ? " (method)" : "", (int) var->data.F->numtmp, (int) var->data.F->numclsr ); break; case SVT_CFUNC: sgs_Writef( C, " = %p", var->data.C ); break; case SVT_OBJECT: sgs_Writef( C, " = " ); dumpobj( C, var->data.O ); break; case SVT_PTR: sgs_Writef( C, " = %p", var->data.P ); break; } } ptrdiff_t sgs_Stat( SGS_CTX, int type ) { switch( type ) { /* WP: not important */ case SGS_STAT_VERSION: return (ptrdiff_t) C->version; case SGS_STAT_APIVERSION: return (ptrdiff_t) C->apiversion; case SGS_STAT_OBJCOUNT: return (ptrdiff_t) C->objcount; case SGS_STAT_MEMSIZE: return (ptrdiff_t) C->memsize; case SGS_STAT_NUMALLOCS: return (ptrdiff_t) C->numallocs; case SGS_STAT_NUMFREES: return (ptrdiff_t) C->numfrees; case SGS_STAT_NUMBLOCKS: return (ptrdiff_t) C->numblocks; case SGS_STAT_DUMP_STACK: { sgs_Variable* p = C->stack_base; sgs_WriteStr( C, "\nVARIABLE -- ---- STACK ---- BASE ----\n" ); while( p < C->stack_top ) { if( p == C->stack_off ) { sgs_WriteStr( C, "VARIABLE -- ---- STACK ---- OFFSET ----\n" ); } sgs_Writef( C, "VARIABLE %02d ", p - C->stack_base ); dumpvar( C, p ); sgs_WriteStr( C, "\n" ); p++; } sgs_WriteStr( C, "VARIABLE -- ---- STACK ---- TOP ----\n" ); } return SGS_SUCCESS; case SGS_STAT_DUMP_GLOBALS: { VHTVar *p, *pend; sgsSTD_GlobalIter( C, &p, &pend ); sgs_WriteStr( C, "\nGLOBAL ---- LIST ---- START ----\n" ); while( p < pend ) { sgs_iStr* str = p->key.data.S; sgs_WriteStr( C, "GLOBAL '" ); ctx_print_safe( C, str_cstr( str ), str->size ); sgs_WriteStr( C, "' = " ); dumpvar( C, &p->val ); sgs_WriteStr( C, "\n" ); p++; } sgs_WriteStr( C, "GLOBAL ---- LIST ---- END ----\n" ); } return SGS_SUCCESS; case SGS_STAT_DUMP_OBJECTS: { object_t* p = C->objs; sgs_WriteStr( C, "\nOBJECT ---- LIST ---- START ----\n" ); while( p ) { dumpobj( C, p ); sgs_WriteStr( C, "\n" ); p = p->next; } sgs_WriteStr( C, "OBJECT ---- LIST ---- END ----\n" ); } return SGS_SUCCESS; case SGS_STAT_DUMP_FRAMES: { sgs_StackFrame* p = sgs_GetFramePtr( C, FALSE ); sgs_WriteStr( C, "\nFRAME ---- LIST ---- START ----\n" ); while( p != NULL ) { const char* file, *name; int ln; sgs_StackFrameInfo( C, p, &name, &file, &ln ); sgs_Writef( C, "FRAME \"%s\" in %s, line %d\n", name, file, ln ); p = p->next; } sgs_WriteStr( C, "FRAME ---- LIST ---- END ----\n" ); } return SGS_SUCCESS; case SGS_STAT_DUMP_STATS: { sgs_WriteStr( C, "\nSTATS ---- ---- ----\n" ); sgs_Writef( C, "# allocs: %d\n", C->numallocs ); sgs_Writef( C, "# frees: %d\n", C->numfrees ); sgs_Writef( C, "# mem blocks: %d\n", C->numblocks ); sgs_Writef( C, "# mem bytes: %d\n", C->memsize ); sgs_Writef( C, "# objects: %d\n", C->objcount ); sgs_Writef( C, "GC state: %s\n", C->redblue ? "red" : "blue" ); sgs_WriteStr( C, "---- ---- ---- -----\n" ); } return SGS_SUCCESS; case SGS_STAT_XDUMP_STACK: { ptrdiff_t i = 0, ssz = C->stack_top - C->stack_base; sgs_WriteStr( C, "\nVARIABLE -- ---- STACK ---- BASE ----\n" ); while( i < ssz ) { sgs_Variable* p = C->stack_base + i; if( p == C->stack_off ) { sgs_WriteStr( C, "VARIABLE -- ---- STACK ---- OFFSET ----\n" ); } sgs_Writef( C, "VARIABLE %02d ", (int) i ); dumpvar( C, p ); sgs_WriteStr( C, "\n" ); sgs_PushVariable( C, p ); if( SGS_SUCCEEDED( sgs_DumpVar( C, 6 ) ) ) { sgs_WriteStr( C, sgs_ToString( C, -1 ) ); sgs_Pop( C, 1 ); sgs_WriteStr( C, "\n" ); } i++; } sgs_WriteStr( C, "VARIABLE -- ---- STACK ---- TOP ----\n" ); } return SGS_SUCCESS; default: return SGS_EINVAL; } } int32_t sgs_Cntl( SGS_CTX, int what, int32_t val ) { int32_t x; switch( what ) { /* WP: last bit of C->state is not used */ case SGS_CNTL_STATE: x = (int32_t) C->state; C->state = (uint32_t) val; return x; case SGS_CNTL_GET_STATE: return (int32_t) C->state; case SGS_CNTL_MINLEV: x = C->minlev; C->minlev = val; return x; case SGS_CNTL_GET_MINLEV: return C->minlev; case SGS_CNTL_APILEV: x = C->apilev; C->apilev = val; return x; case SGS_CNTL_GET_APILEV: return C->apilev; case SGS_CNTL_ERRNO: x = C->last_errno; C->last_errno = val ? 0 : errno; return x; case SGS_CNTL_SET_ERRNO: x = C->last_errno; C->last_errno = val; return x; case SGS_CNTL_GET_ERRNO: return C->last_errno; case SGS_CNTL_ERRSUP: if( C->sf_last ) { x = C->sf_last->errsup; C->sf_last->errsup = (int16_t) val; return x; } return 0; case SGS_CNTL_GET_ERRSUP: return C->sf_last ? C->sf_last->errsup : 0; } return 0; } void sgs_StackFrameInfo( SGS_CTX, sgs_StackFrame* frame, const char** name, const char** file, int* line ) { int L = 0; const char* N = "<non-callable type>"; const char* F = "<buffer>"; UNUSED( C ); if( !frame->func ) { N = "<main>"; L = frame->lntable[ frame->lptr - frame->code ]; if( frame->filename ) F = frame->filename; } else if( frame->func->type == SGS_VT_FUNC ) { N = "<anonymous function>"; if( frame->func->data.F->funcname.size ) N = frame->func->data.F->funcname.ptr; L = !frame->func->data.F->lineinfo ? 1 : frame->func->data.F->lineinfo[ frame->lptr - frame->code ]; if( frame->func->data.F->filename.size ) F = frame->func->data.F->filename.ptr; else if( frame->filename ) F = frame->filename; } else if( frame->func->type == SGS_VT_CFUNC ) { N = frame->nfname ? frame->nfname : "[C function]"; F = "[C code]"; } else if( frame->func->type == SGS_VT_OBJECT ) { sgs_VarObj* O = frame->func->data.O; N = O->iface->name ? O->iface->name : "<object>"; F = "[C code]"; } if( name ) *name = N; if( file ) *file = F; if( line ) *line = L; } sgs_StackFrame* sgs_GetFramePtr( SGS_CTX, int end ) { return end ? C->sf_last : C->sf_first; } SGSRESULT sgs_RegisterType( SGS_CTX, const char* name, sgs_ObjInterface* iface ) { size_t len; VHTVar* p; if( !iface ) return SGS_EINVAL; len = strlen( name ); if( len > 0x7fffffff ) return SGS_EINVAL; /* WP: error condition */ p = vht_get_str( &C->typetable, name, (uint32_t) len, sgs_HashFunc( name, len ) ); if( p ) return SGS_EINPROC; { sgs_Variable tmp; tmp.type = SVT_PTR; tmp.data.P = iface; sgs_PushStringBuf( C, name, (sgs_SizeVal) len ); vht_set( &C->typetable, C, C->stack_top-1, &tmp ); sgs_Pop( C, 1 ); } return SGS_SUCCESS; } SGSRESULT sgs_UnregisterType( SGS_CTX, const char* name ) { size_t len = strlen( name ); if( len > 0x7fffffff ) return SGS_EINVAL; /* WP: error condition */ VHTVar* p = vht_get_str( &C->typetable, name, (uint32_t) len, sgs_HashFunc( name, len ) ); if( !p ) return SGS_ENOTFND; vht_unset( &C->typetable, C, &p->key ); return SGS_SUCCESS; } sgs_ObjInterface* sgs_FindType( SGS_CTX, const char* name ) { size_t len = strlen( name ); if( len > 0x7fffffff ) return NULL; /* WP: error condition */ VHTVar* p = vht_get_str( &C->typetable, name, (uint32_t) len, sgs_HashFunc( name, len ) ); if( p ) return (sgs_ObjInterface*) p->val.data.P; return NULL; } void sgs_FuncName( SGS_CTX, const char* fnliteral ) { if( C->sf_last ) C->sf_last->nfname = fnliteral; } int sgs_HasFuncName( SGS_CTX ) { return !!C->sf_last && !!C->sf_last->nfname; } void sgs_InitStringBuf32( sgs_Variable* var, sgs_String32* S, const char* str, size_t len ) { sgs_BreakIf( len > 31 ); S->data.refcount = 1; /* WP: range of len: 0-31 */ S->data.size = (uint32_t) len; S->data.hash = sgs_HashFunc( str, len ); S->data.isconst = 0; memcpy( S->buf, str, len ); S->buf[ len ] = 0; var->type = SGS_VT_STRING; var->data.S = &S->data; } void sgs_PushStringBuf32( SGS_CTX, sgs_String32* S, const char* str, size_t len ) { sgs_Variable var; sgs_InitStringBuf32( &var, S, str, len ); sgs_PushVariable( C, &var ); } void sgs_CheckString32( sgs_String32* S ) { sgs_BreakIf( !sgs_IsFreedString32( S ) ); } SGSBOOL sgs_IsFreedString32( sgs_String32* S ) { return S->data.refcount == 1; } <file_sep>/readme.txt --- SGScript v0.9.5 --- usage: - MinGW users: * compile the makefile (add mode=release to get the release build) * link with -lsgscript from the bin/ directory (-Lbin) - VC10/11 users: project file is in build/vc10/SGScript - Code::Blocks users: project file is in build/codeblocks - XCode users: project file is in build/xcode - include src/sgscript.h in your project and link with libsgscript.a sample code and documentation ... is in tests/ and docs/ directories as you'll probably see, it's not that different from many other languages. there'll be no specification until the language survives a few iterations. after that, we'll see if it's necessary. --- features: - a C-like syntax - the usual stuff (while/do-while/for/foreach, expressions, variables etc.) - highly optimized, register-based virtual machine - mixed memory management (ref.counting + GC) - extensive native debugging features - ** interactive debug inspector add-on ** - 8 data types (with lots of space for extensions): null, bool, int, real, string, function, C function, object - tests * testing framework is in ext/sgstest.c => bin/sgstest ("make test" to run) - object-oriented constructs (dict, class, closure, overloadable operators) bugs: ! if you think you've found a bug, pop me an email to snake5creator [at] GMail * don't forget to include a test sample, as small as possible! future: - more extensions, fully featured API - got a suggestion? write some sample code (in the form of a test) and send it credits: - developer: <NAME> (snake5) * I can be reached at snake5creator [at] GMail - XCode project contributed by <NAME> change log: 0.9.5 (2014/05/25, updated 2014/07/11): - full Mac OS X support - bugfixes: lots of those (regex is finally stable) - memory usage profiler - map object - syntax/VM upgrades (multi-index/property set, compatible call, unescaped strings, ... ... error suppression, named anonymous and short functions, var.arg. support) - stdlib upgrades (core, utf8, io) - xgmath (floatarray, matrix), sockets module upgrades - C API upgrades (major refactor for variable pointer support, output system) - almost fully documented the whole system, upgraded documentation system - cppbc upgraded and fully tested with heavy C++ projects (sgs-box2d) + documented - sgs2c experimental script developed to maximum bytecode compatibility - code is mostly warning-free on all supported platforms 0.9.0 (2013/11/10): - bugfixes: empty subexpr, unary op chaining, expression writes - implemented hooks interface - created two kinds of profilers - major internal refactoring (object interface & C-side handling) - major stdlib upgrades (OS, date, I/O, formatting, iterables, system, regex) - serialization - the meta-global, environment switching - unoptimized pseudo-empty statements due to possible side effects (1+funccall("x") etc.) - documented stdlib / C API - multiple return value capture via expression writes - if(cond,true,false) pseudo-function (ternary op substitute) - real closures 0.8.5 (2013/05/01): sorted MANY things out (lots of fixes and API changes) utf8<->utf32, big math/type lib. changes, debug inspector, json addon DLL, upgraded the test framework, created the monkey test, doc.gen. from MD 0.8.2 (2013/04/15): implicit "this", bytecode serialization, upgraded AST code, DLL loading system (Windows-only ATM), core I/O API, variable cloning, extended array API that is made to be sequencing-friendly, int/int=>real 0.8.1 (2013/04/04): important stability and main API improvements the engine is finally tested to be production-code-ready 0.8 (2013/03/29): most of string API, type API, closures, API test framework, improved debugging, fixed: boolean logic, div/0 error and other things 0.7 (2013/01/28): object orientation (w/ operator overloading), do-while, optimizations, classes, eval, foreach, fixed comparisons 0.6 - skipped 0.5 (2013/01/06): cleanup, lambdas, literals, "dict" container 0.4 (2012/12/26): the initial release <file_sep>/makefile # SGScript makefile # Additional compilation info: # CC (compiler) can be specified in the `make` command # For Android, together with some android-*** target, pass this: # CC="<some-prebuilt-gcc/clang> --sysroot=NDK_ROOT\platforms\<platform>\<arch>" # MAKE comma := , space := space += # BASIC VARIABLES ifeq ($(CC),cc) # no such compiler on Windows CC= endif ifeq ($(CC),) CC=gcc endif ifeq ($(CXX),) CXX=g++ endif ifeq ($(OUTDIR),) OUTDIR=bin endif # UTILITIES cOS=os_unknown cARCH=arch_unknown cCOMPILER=compiler_unknown ifeq ($(OS),Windows_NT) fnREMOVE_ALL = del /F /S /Q fnCOPY_FILE = copy fnFIX_PATH = $(subst /,\,$1) cOS=windows ifeq ($(PROCESSOR_ARCHITECTURE),x86) cARCH=x86 endif ifeq ($(PROCESSOR_ARCHITECTURE),AMD64) cARCH=x64 endif else fnREMOVE_ALL = rm -rf fnCOPY_FILE = cp fnFIX_PATH = $1 UNAME_S := $(shell uname -s) ifeq ($(UNAME_S),Linux) cOS=linux endif ifeq ($(UNAME_S),Darwin) cOS=osx endif UNAME_P := $(shell uname -p) ifneq ($(filter %86,$(UNAME_P)),) cARCH=x86 endif ifeq ($(UNAME_P),x86_64) cARCH=x64 endif ifneq ($(filter arm%,$(UNAME_P)),) cARCH=arm endif endif CC_V := $(shell $(CC) -v 2>&1) ifneq ($(findstring clang,$(CC_V)),) cCOMPILER=clang endif ifneq ($(findstring gcc,$(CC_V)),) cCOMPILER=gcc endif cOS_ARCH=$(cOS)-$(cARCH) ifeq ($(target),) target=$(cOS_ARCH) endif target_os=$(word 1,$(subst -, ,$(target))) target_arch=$(word 2,$(subst -, ,$(target))) ifeq ($(target_os),) $(error Target OS not specified (windows/linux/osx)) endif ifeq ($(target_arch),) $(error Target CPU type not specified (x86/x64/arm/..)) endif cIF_RELEASE=$(findstring release,$(mode)) fnIF_RELEASE=$(if $(cIF_RELEASE),$1,$2) fnIF_OS=$(if $(findstring $1,$(target_os)),$2,$3) fnIF_ARCH=$(if $(findstring $1,$(target_arch)),$2,$3) fnIF_OS_ARCH=$(if $(findstring $1,$(target)),$2,$3) fnIF_COMPILER=$(if $(findstring $1,$(cCOMPILER)),$2,$3) # PLATFORM SPECIFICS ifeq ($(target_os),windows) BINEXT=.exe LIBPFX= LIBEXT=.dll else BINEXT= LIBPFX=lib LIBEXT=.so endif # APP FLAGS OUTFILE_STATIC=lib/libsgscript.a OUTFILE_DYNAMIC=$(OUTDIR)/$(LIBPFX)sgscript$(LIBEXT) OUTFLAGS_STATIC=-Llib -lsgscript OUTFLAGS_DYNAMIC=-L$(OUTDIR) -lsgscript ifneq ($(static),) PREFLAGS=-DBUILDING_SGS=1 OUTFILE=$(OUTFILE_STATIC) OUTFLAGS=$(OUTFLAGS_STATIC) else PREFLAGS=-DBUILDING_SGS=1 -DSGS_DLL=1 OUTFILE=$(OUTFILE_DYNAMIC) OUTFLAGS=$(OUTFLAGS_DYNAMIC) endif CFLAGS=-fwrapv -Wall -Wconversion -Wshadow -Wpointer-arith -Wcast-qual -Wcast-align \ $(call fnIF_RELEASE,-O3,-D_DEBUG -g) $(call fnIF_COMPILER gcc,-static-libgcc,) \ $(call fnIF_ARCH,x86,-m32,$(call fnIF_ARCH,x64,-m64,)) -Isrc \ $(call fnIF_OS,windows,,-fPIC -D_FILE_OFFSET_BITS=64) \ $(call fnIF_OS,android,-DSGS_PF_ANDROID,) COMFLAGS=$(CFLAGS) BINFLAGS=$(CFLAGS) $(OUTFLAGS) -lm \ $(call fnIF_OS,android,-ldl -Wl$(comma)-rpath$(comma)'$$ORIGIN' -Wl$(comma)-z$(comma)origin,) \ $(call fnIF_OS,windows,-lkernel32,) \ $(call fnIF_OS,osx,-ldl -Wl$(comma)-rpath$(comma)'@executable_path/.',) \ $(call fnIF_OS,linux,-ldl -lrt -Wl$(comma)-rpath$(comma)'$$ORIGIN' -Wl$(comma)-z$(comma)origin,) MODULEFLAGS=-DSGS_COMPILE_MODULE $(BINFLAGS) -shared EXEFLAGS=$(BINFLAGS) THREADLIBS=$(call fnIF_OS,windows,,$(call fnIF_OS,android,,-lpthread)) SGS_INSTALL_TOOL = $(call fnIF_OS,osx,install_name_tool \ -change $(OUTDIR)/libsgscript.so @rpath/libsgscript.so $1,) # BUILD INFO ifneq ($(MAKECMDGOALS),clean) ifneq ($(MAKECMDGOALS),clean_obj) ifneq ($(MAKECMDGOALS),clean_objbin) $(info -------------------) $(info SGScript build info) $(info -------------------) $(info OS - $(cOS)) $(info ARCH - $(cARCH)) $(info COMPILER - $(cCOMPILER)) $(info TARGET - $(target_os)/$(target_arch)) $(info MODE - $(call fnIF_RELEASE,release,debug)) $(info OUT.LIB. - $(OUTFILE)) $(info TODO - $(MAKECMDGOALS)) $(info -------------------) endif endif endif # TARGETS ## the library (default target) .PHONY: make make: $(OUTFILE) DEPS = $(patsubst %,src/%.h,sgs_cfg sgs_int sgs_regex sgs_util sgs_xpc sgscript) OBJ = $(patsubst %,obj/sgs_%.o,bcg ctx fnt proc regex std stdL tok util xpc) lib/libsgscript.a: $(OBJ) ar rcs $@ $(OBJ) $(OUTDIR)/$(LIBPFX)sgscript$(LIBEXT): $(OBJ) $(CC) $(PREFLAGS) -o $@ $(OBJ) $(CFLAGS) -shared -lm obj/%.o: src/%.c $(DEPS) $(CC) $(PREFLAGS) -c -o $@ $< $(COMFLAGS) ## the libraries $(OUTDIR)/sgsxgmath$(LIBEXT): ext/sgsxgmath.c ext/sgsxgmath.h $(OUTFILE) $(CC) -o $@ $< $(MODULEFLAGS) $(call SGS_INSTALL_TOOL,$@) $(OUTDIR)/sgsjson$(LIBEXT): ext/sgsjson.c $(OUTFILE) $(CC) -o $@ $< $(MODULEFLAGS) $(call SGS_INSTALL_TOOL,$@) $(OUTDIR)/sgspproc$(LIBEXT): ext/sgspproc.c $(OUTFILE) $(CC) -o $@ $< $(MODULEFLAGS) $(THREADLIBS) $(call SGS_INSTALL_TOOL,$@) $(OUTDIR)/sgssockets$(LIBEXT): ext/sgssockets.c $(OUTFILE) $(CC) -o $@ $< $(MODULEFLAGS) $(call fnIF_OS,windows,-lws2_32,) $(call SGS_INSTALL_TOOL,$@) $(OUTDIR)/sgsmeta$(LIBEXT): ext/sgsmeta.c $(OUTFILE) $(CC) -o $@ $< $(MODULEFLAGS) $(call SGS_INSTALL_TOOL,$@) ## the tools $(OUTDIR)/sgstest$(BINEXT): ext/sgstest.c $(OUTFILE) $(CC) -o $@ $< $(EXEFLAGS) $(call SGS_INSTALL_TOOL,$@) $(OUTDIR)/sgsapitest$(BINEXT): ext/sgsapitest.c $(OUTFILE) $(CC) -o $@ $< $(EXEFLAGS) $(call SGS_INSTALL_TOOL,$@) $(OUTDIR)/sgsvm$(BINEXT): ext/sgsvm.c ext/sgs_idbg.c ext/sgs_prof.c $(OUTFILE) $(CC) -o $@ $(subst $(OUTFILE),,$^) $(EXEFLAGS) $(call SGS_INSTALL_TOOL,$@) $(OUTDIR)/sgsc$(BINEXT): ext/sgsc.c $(OUTFILE) $(CC) -o $@ $< $(EXEFLAGS) $(call SGS_INSTALL_TOOL,$@) ## library/tool aliases .PHONY: xgmath .PHONY: json .PHONY: pproc .PHONY: sockets .PHONY: meta .PHONY: build_test .PHONY: build_apitest .PHONY: vm .PHONY: c .PHONY: test .PHONY: apitest xgmath: $(OUTDIR)/sgsxgmath$(LIBEXT) json: $(OUTDIR)/sgsjson$(LIBEXT) pproc: $(OUTDIR)/sgspproc$(LIBEXT) sockets: $(OUTDIR)/sgssockets$(LIBEXT) meta: $(OUTDIR)/sgsmeta$(LIBEXT) build_test: $(OUTDIR)/sgstest$(BINEXT) json xgmath build_apitest: $(OUTDIR)/sgsapitest$(BINEXT) vm: $(OUTDIR)/sgsvm$(BINEXT) c: $(OUTDIR)/sgsc$(BINEXT) # test tool aliases test: build_test $(OUTDIR)/sgstest apitest: build_apitest $(OUTDIR)/sgsapitest .PHONY: tools tools: xgmath json pproc sockets meta build_test build_apitest vm c ## other stuff ## - cppbc testing .PHONY: cppbctest .PHONY: build_cppbctest build_cppbctest: $(OUTDIR)/sgscppbctest$(BINEXT) cppbctest: build_cppbctest $(OUTDIR)/sgscppbctest $(OUTDIR)/sgscppbctest$(BINEXT): ext/sgscppbctest.cpp obj/cppbc_test.cpp ext/sgscppbctest.h ext/cppbc/sgs_cppbc.h $(OUTFILE) $(CXX) -o $@ $< $(word 2,$^) $(EXEFLAGS) -I. $(call SGS_INSTALL_TOOL,$@) obj/cppbc_test.cpp: ext/sgscppbctest.h $(OUTDIR)/sgsvm -p ext/cppbc/cppbc.sgs $< $@ ## - cppbind testing .PHONY: cppbindtest .PHONY: build_cppbindtest build_cppbindtest: $(OUTDIR)/sgscppbindtest$(BINEXT) cppbindtest: build_cppbindtest $(OUTDIR)/sgscppbindtest $(OUTDIR)/sgscppbindtest$(BINEXT): ext/cpp/cppbind_example.cpp $(OUTFILE) $(CXX) -o $@ $< $(EXEFLAGS) $(call SGS_INSTALL_TOOL,$@) ## - multithreaded testing .PHONY: mttest .PHONY: build_mttest build_mttest: $(OUTDIR)/sgstest_mt$(BINEXT) mttest: build_mttest $(OUTDIR)/sgstest_mt $(OUTDIR)/sgstest_mt$(BINEXT): examples/sgstest_mt.c $(OUTFILE) $(CC) -o $@ $^ $(EXEFLAGS) $(THREADLIBS) $(call SGS_INSTALL_TOOL,$@) ## - sgs2exe tool .PHONY: sgsexe sgsexe: ext/sgsexe.c $(OUTFILE_STATIC) $(CC) -o $(OUTDIR)/sgsexe.exe $^ $(CFLAGS) -lm copy /B $(OUTDIR)\sgsexe.exe + ext\stubapp.bin $(OUTDIR)\sgsexe.tmp del /Q $(OUTDIR)\sgsexe.exe cmd /c move /Y $(OUTDIR)\sgsexe.tmp $(OUTDIR)\sgsexe.exe ## - binary archive preparation .PHONY: binarch binarch: vm bin/sgsvm build/prep.sgs ## clean build data .PHONY: clean_obj clean_obj: $(fnREMOVE_ALL) $(call fnFIX_PATH,obj/*.o) .PHONY: clean_objbin clean_objbin: $(fnREMOVE_ALL) $(call fnFIX_PATH,obj/*.o $(OUTDIR)/sgs* $(OUTDIR)/libsgs*) .PHONY: clean clean: $(fnREMOVE_ALL) $(call fnFIX_PATH,obj/*.o lib/*.a lib/*.lib $(OUTDIR)/sgs* $(OUTDIR)/libsgs*) <file_sep>/ext/cpp/cppbind.h #pragma once #include <sgscript.h> #define SGS_VDECL( var ) extern var #define SGS_VDEF( var ) var #define SGS_IFN( name ) sgsiface_##name #define SGS_METHODNAME( obj, funcname ) SGS_IFN( obj##_##funcname ) #define SGS_GETINDEXNAME( obj ) SGS_IFN(obj##GetIndex) #define SGS_SETINDEXNAME( obj ) SGS_IFN(obj##SetIndex) #define SGS_CTORNAME( obj ) SGS_IFN(obj##Create) #define SGS_DTORNAME( obj ) SGS_IFN(obj##Destroy) #define SGS_DECLARE_IFACE_O( obj ) SGS_VDECL( sgs_ObjInterface SGS_IFN(obj)[1] ); #define SGS_DEFINE_IFACE_O( obj ) SGS_VDEF( sgs_ObjInterface SGS_IFN(obj)[1] ) = {{ #define SGS_DEFINE_IFACE_END }}; #define SGS_IFACE_GETINDEX_O( obj ) SGS_GETINDEXNAME(obj) #define SGS_IFACE_SETINDEX_O( obj ) SGS_SETINDEXNAME(obj) #define SGS_IFACE_DESTRUCT_O( obj ) SGS_DTORNAME(obj) #define SGS_IFNHDR( obj, funcname ) \ obj* item; if( !SGS_PARSE_METHOD( C, SGS_IFN(obj), item, #obj, #funcname ) ) return 0; #define SGS_METHOD_WRAPPER_O( obj, funcname ) \ int SGS_METHODNAME(obj,funcname)(SGS_CTX){SGS_IFNHDR(obj,funcname) \ return item->funcname(C);} #define SGS_DEFINE_GETINDEXFUNC_O( obj ) int SGS_GETINDEXNAME(obj) \ (SGS_CTX,sgs_VarObj*data,sgs_Variable*key,int isprop) #define SGS_BEGIN_GENERIC_GETINDEXFUNC_O( obj ) SGS_DEFINE_GETINDEXFUNC_O(obj){\ char* str;obj*item = (obj*) data->data;(void)item;if(sgs_ParseStringP(C,key,&str,NULL)){ #define SGS_END_GENERIC_GETINDEXFUNC } return SGS_ENOTFND; } #define SGS_GIF_CUSTOM( ename, code ) \ if(strcmp(str,#ename)==0){code;return SGS_SUCCESS;} #define SGS_GIF_METHOD_O( obj, funcname ) SGS_GIF_CUSTOM(funcname, \ sgs_PushCFunction(C,SGS_METHODNAME(obj,funcname))) #define SGS_GIF_GETTER( name ) SGS_GIF_CUSTOM(name, \ return item->getter_##name(C); ) #define SGS_DEFINE_SETINDEXFUNC( obj ) int SGS_SETINDEXNAME(obj) \ (SGS_CTX,sgs_VarObj*data,sgs_Variable*key,sgs_Variable*val,int isprop) #define SGS_BEGIN_GENERIC_SETINDEXFUNC_O( obj ) SGS_DEFINE_SETINDEXFUNC(obj){\ char* str;obj*item = (obj*) data->data;(void)item;if(sgs_ParseStringP(C,key,&str,NULL)){ #define SGS_END_GENERIC_SETINDEXFUNC } return SGS_ENOTFND; } #define SGS_GIF_SETTER( name ) SGS_GIF_CUSTOM(name, \ return item->setter_##name(C,val); ) #define SGS_GENERIC_DESTRUCTOR_O( obj ) \ int SGS_DTORNAME(obj)(SGS_CTX,sgs_VarObj*data) \ { ((obj*) data->data)->~obj(); return SGS_SUCCESS; } #define SGS_GENERIC_IFPUSH( obj ) new (sgs_PushObjectIPA( C, (uint32_t) sizeof(obj), SGS_IFN(obj) )) obj #define SGS_DEFINE_CTORFUNC_O( obj ) int SGS_CTORNAME(obj)(SGS_CTX) #define SGS_DEFINE_EMPTY_CTORFUNC_O( obj ) SGS_DEFINE_CTORFUNC_O(obj) \ { SGS_GENERIC_IFPUSH( obj ); return 1; } #define SGS_REGISTER_C( C, obj ) do{\ sgs_PushCFunction(C,SGS_CTORNAME(obj));sgs_StoreGlobal(C,#obj);}while(0) #define SGS_REGISTER( obj ) SGS_REGISTER_C( C, obj ) #define SGS_DECLARE_IFACE SGS_DECLARE_IFACE_O(SGS_CLASS) #define SGS_DEFINE_IFACE SGS_DEFINE_IFACE_O(SGS_CLASS) #define SGS_METHOD_WRAPPER( funcname ) \ SGS_METHOD_WRAPPER_O(SGS_CLASS,funcname) #define SGS_BEGIN_GENERIC_GETINDEXFUNC \ SGS_BEGIN_GENERIC_GETINDEXFUNC_O(SGS_CLASS) #define SGS_GIF_METHOD( funcname ) SGS_GIF_METHOD_O(SGS_CLASS,funcname) #define SGS_BEGIN_GENERIC_SETINDEXFUNC \ SGS_BEGIN_GENERIC_SETINDEXFUNC_O(SGS_CLASS) #define SGS_GENERIC_DESTRUCTOR SGS_GENERIC_DESTRUCTOR_O(SGS_CLASS) #define SGS_DEFINE_CTORFUNC SGS_DEFINE_CTORFUNC_O(SGS_CLASS) #define SGS_DEFINE_EMPTY_CTORFUNC SGS_DEFINE_EMPTY_CTORFUNC_O(SGS_CLASS) #define SGS_IFACE_GETINDEX SGS_IFACE_GETINDEX_O(SGS_CLASS) #define SGS_IFACE_SETINDEX SGS_IFACE_SETINDEX_O(SGS_CLASS) #define SGS_IFACE_DESTRUCT SGS_IFACE_DESTRUCT_O(SGS_CLASS) <file_sep>/ext/sgs_prof.h #ifndef SGS_PROF_H_INCLUDED #define SGS_PROF_H_INCLUDED #include <sgscript.h> #include <sgs_util.h> typedef struct _sgs_Prof { SGS_CTX; sgs_HookFunc hfn; void* hctx; int mode; /* mode 1 / 3 */ sgs_MemBuf keytmp; sgs_MemBuf timetmp; sgs_VHTable timings; /* mode 2 */ int prev; double* ictrs; uint32_t* iexcs; int32_t instr; double starttime; } sgs_Prof; #define SGS_PROF sgs_Prof* P #define SGS_PROF_FUNCTIME 1 #define SGS_PROF_OPTIME 2 #define SGS_PROF_MEMUSAGE 3 SGSBOOL sgs_ProfInit( SGS_CTX, SGS_PROF, int mode ); SGSBOOL sgs_ProfClose( SGS_PROF ); SGSBOOL sgs_ProfDump( SGS_PROF ); #endif <file_sep>/ext/sgs_prof.c #include <math.h> #include <sgs_int.h> #include "sgs_prof.h" static void mode1hook( void* userdata, SGS_CTX, int evid ) { SGS_PROF = (sgs_Prof*) userdata; double TM = sgs_GetTime(); if( P->hfn ) P->hfn( P->hctx, C, evid ); if( evid == SGS_HOOK_ENTER ) { sgs_membuf_appbuf( &P->timetmp, C, &TM, sizeof(TM) ); } else if( evid == SGS_HOOK_EXIT ) { double prevTM; sgs_VHTVar* pair; sgs_StackFrame* sf = sgs_GetFramePtr( C, 0 ); sgs_membuf_resize( &P->keytmp, C, 0 ); while( sf ) { const char* fname = "<error>"; sgs_StackFrameInfo( C, sf, &fname, NULL, NULL ); sgs_membuf_appbuf( &P->keytmp, C, fname, strlen( fname ) ); sgs_membuf_appchr( &P->keytmp, C, 0 ); sf = sf->next; } SGS_AS_DOUBLE( prevTM, P->timetmp.ptr + P->timetmp.size - sizeof(double) ); pair = sgs_vht_get_str( &P->timings, P->keytmp.ptr, (uint32_t) P->keytmp.size, sgs_HashFunc( P->keytmp.ptr, P->keytmp.size ) ); if( pair ) { pair->val.data.R += TM - prevTM; } else { sgs_Variable val; sgs_InitReal( &val, TM - prevTM ); sgs_PushStringBuf( C, P->keytmp.ptr, (sgs_SizeVal) P->keytmp.size ); sgs_vht_set( &P->timings, C, C->stack_top-1, &val ); sgs_Pop( C, 1 ); } sgs_membuf_resize( &P->timetmp, C, P->timetmp.size - sizeof(TM) ); } } static int initProfMode1( SGS_PROF ) { P->keytmp = sgs_membuf_create(); P->timetmp = sgs_membuf_create(); sgs_vht_init( &P->timings, P->C, 128, 128 ); sgs_SetHookFunc( P->C, mode1hook, P ); return 1; } static void freeProfMode1( SGS_PROF ) { sgs_membuf_destroy( &P->keytmp, P->C ); sgs_membuf_destroy( &P->timetmp, P->C ); sgs_vht_free( &P->timings, P->C ); } static int dpm1sf( const void* p1, const void* p2 ) { const sgs_VHTVar* v1 = (const sgs_VHTVar*) p1; const sgs_VHTVar* v2 = (const sgs_VHTVar*) p2; const sgs_iStr* str1 = v1->key.data.S; const sgs_iStr* str2 = v2->key.data.S; uint32_t cmpsz = str1->size < str2->size ? str1->size : str2->size; int ret = memcmp( sgs_str_c_cstr( str1 ), sgs_str_c_cstr( str2 ), cmpsz ); if( !ret ) ret = (int)( str1->size - str2->size ); return ret; } static int dumpProfMode1( SGS_PROF ) { int i; sgs_VHTVar* pbuf = (sgs_VHTVar*) sgs_Malloc( P->C, sizeof(sgs_VHTVar) * (size_t) P->timings.size ); memcpy( pbuf, P->timings.vars, sizeof(sgs_VHTVar) * (size_t) P->timings.size ); qsort( pbuf, (size_t) P->timings.size, sizeof(sgs_VHTVar), dpm1sf ); sgs_Writef( P->C, "--- Time by call stack frame ---\n" ); for( i = 0; i < P->timings.size; ++i ) { const char *s, *send; sgs_VHTVar* p = pbuf + i; s = sgs_var_cstr( &p->key ); send = s + p->key.data.S->size; while( s < send ) { if( s != sgs_var_cstr( &p->key ) ) sgs_Writef( P->C, "::" ); sgs_Writef( P->C, "%s", s ); s += strlen( s ) + 1; } sgs_Writef( P->C, " - %f\n", p->val.data.R ); } sgs_Writef( P->C, "---\n" ); sgs_Free( P->C, pbuf ); return 1; } #define TOPCNT (SGS_SI_COUNT+1) static void mode2hook( void* userdata, SGS_CTX, int evid ) { SGS_PROF = (sgs_Prof*) userdata; double TM = sgs_GetTime(); if( P->hfn ) P->hfn( P->hctx, C, evid ); if( P->instr >= 0 ) { double dif = TM - P->starttime; P->ictrs[ P->instr ] += dif >= 0 ? dif : 0; P->instr = -1; } if( evid == SGS_HOOK_STEP ) { sgs_StackFrame* sf = sgs_GetFramePtr( C, 1 ); P->instr = SGS_INSTR_GET_OP( *sf->iptr ); P->iexcs[ P->instr ]++; P->starttime = TM; } else { if( P->prev != SGS_HOOK_STEP ) { double dif = TM - P->starttime; P->ictrs[ SGS_SI_COUNT ] += dif >= 0 ? dif : 0; } P->starttime = TM; } P->prev = evid; } static int initProfMode2( SGS_PROF ) { int i; P->instr = -1; P->ictrs = (double*) sgs_Malloc( P->C, sizeof( double ) * TOPCNT ); P->iexcs = (uint32_t*) sgs_Malloc( P->C, sizeof( uint32_t ) * TOPCNT ); for( i = 0; i < TOPCNT; ++i ) { P->ictrs[ i ] = 0; P->iexcs[ i ] = 0; } sgs_SetHookFunc( P->C, mode2hook, P ); return 1; } static void freeProfMode2( SGS_PROF ) { sgs_Free( P->C, P->ictrs ); sgs_Free( P->C, P->iexcs ); } typedef struct { int i; uint32_t c; double t; } icts; static int its_sort( const void* p1, const void* p2 ) { const icts* t1 = (const icts*) p1; const icts* t2 = (const icts*) p2; if( t1->t != t2->t ) return t1->t > t2->t ? -1 : 1; else if( t1->c != t2->c ) return t1->c > t2->c ? -1 : 1; return 0; } static int dumpProfMode2( SGS_PROF ) { int i; icts* temp; uint32_t totalcnt = 0, c; double total = 0, t; sgs_Writef( P->C, "--- Time by VM instruction ---\n" ); sgs_Writef( P->C, "| NAME | TIME | COUNT |\n" ); temp = (icts*) sgs_Malloc( P->C, sizeof( icts ) * TOPCNT ); for( i = 0; i < TOPCNT; ++i ) { t = P->ictrs[ i ]; c = P->iexcs[ i ]; total += t; totalcnt += c; temp[ i ].t = t; temp[ i ].i = i; temp[ i ].c = c; } qsort( temp, TOPCNT, sizeof( icts ), its_sort ); for( i = 0; i < TOPCNT; ++i ) { const char* str = temp[ i ].i == SGS_SI_COUNT ? "! native code" : sgs_CodeString( SGS_CODE_OP, temp[ i ].i ); sgs_Writef( P->C, "| %14s - %12f - %11d |\n", str, temp[ i ].t, temp[ i ].c ); } sgs_Free( P->C, temp ); sgs_Writef( P->C, "///\n| %14s - %12f - %11d |\n---\n", "Total", total, totalcnt ); return 1; } typedef struct _mode3data { size_t numallocs; size_t numfrees; size_t numblocks; double szdelta; } mode3data; static void mode3hook( void* userdata, SGS_CTX, int evid ) { SGS_PROF = (sgs_Prof*) userdata; mode3data CD = { C->numallocs, C->numfrees, C->numblocks, (double) C->memsize }; if( P->hfn ) P->hfn( P->hctx, C, evid ); if( evid == SGS_HOOK_ENTER ) { sgs_membuf_appbuf( &P->timetmp, C, &CD, sizeof(CD) ); } else if( evid == SGS_HOOK_EXIT ) { mode3data prevCD, *PD; sgs_VHTVar* pair; sgs_StackFrame* sf = sgs_GetFramePtr( C, 0 ); sgs_membuf_resize( &P->keytmp, C, 0 ); while( sf ) { const char* fname = "<error>"; sgs_StackFrameInfo( C, sf, &fname, NULL, NULL ); sgs_membuf_appbuf( &P->keytmp, C, fname, strlen( fname ) ); sgs_membuf_appchr( &P->keytmp, C, 0 ); sf = sf->next; } memcpy( &prevCD, P->timetmp.ptr + P->timetmp.size - sizeof(CD), sizeof(CD) ); pair = sgs_vht_get_str( &P->timings, P->keytmp.ptr, (uint32_t) P->keytmp.size, sgs_HashFunc( P->keytmp.ptr, P->keytmp.size ) ); if( pair ) { PD = (mode3data*) pair->val.data.P; } else { sgs_Variable val; val.type = SGS_VT_PTR; val.data.P = PD = (mode3data*) sgs_Malloc( C, sizeof(CD) ); memset( PD, 0, sizeof(*PD) ); sgs_PushStringBuf( C, P->keytmp.ptr, (sgs_SizeVal) P->keytmp.size ); sgs_vht_set( &P->timings, C, C->stack_top-1, &val ); sgs_Pop( C, 1 ); } PD->numallocs += CD.numallocs - prevCD.numallocs; PD->numfrees += CD.numfrees - prevCD.numfrees; PD->numblocks += CD.numblocks - prevCD.numblocks; PD->szdelta += CD.szdelta - prevCD.szdelta; sgs_membuf_resize( &P->timetmp, C, P->timetmp.size - sizeof(CD) ); } } static int initProfMode3( SGS_PROF ) { initProfMode1( P ); sgs_SetHookFunc( P->C, mode3hook, P ); return 1; } static int freeProfMode3( SGS_PROF ) { sgs_SizeVal i; for( i = 0; i < P->timings.size; ++i ) { sgs_Free( P->C, P->timings.vars[ i ].val.data.P ); } freeProfMode1( P ); return 1; } static int dpm3sf( const void* p1, const void* p2 ) { const sgs_VHTVar* v1 = (const sgs_VHTVar*) p1; const sgs_VHTVar* v2 = (const sgs_VHTVar*) p2; const sgs_iStr* str1 = v1->key.data.S; const sgs_iStr* str2 = v2->key.data.S; const mode3data* D1 = (const mode3data*) v1->val.data.P; const mode3data* D2 = (const mode3data*) v2->val.data.P; size_t cmpsz = str1->size < str2->size ? str1->size : str2->size; int ret = (int)( ( D2->numallocs + D2->numfrees ) - ( D1->numallocs + D1->numfrees ) ); if( !ret ) { double abs1 = fabs( D2->szdelta ); double abs2 = fabs( D1->szdelta ); ret = abs1 == abs2 ? 0 : ( abs1 < abs2 ? -1 : 1 ); } if( !ret ) ret = memcmp( sgs_str_c_cstr( str1 ), sgs_str_c_cstr( str2 ), cmpsz ); if( !ret ) ret = (int)( str1->size - str2->size ); return ret; } static int dumpProfMode3( SGS_PROF ) { int i; sgs_VHTVar* pbuf = (sgs_VHTVar*) sgs_Malloc( P->C, sizeof(sgs_VHTVar) * (size_t) P->timings.size ); memcpy( pbuf, P->timings.vars, sizeof(sgs_VHTVar) * (size_t) P->timings.size ); qsort( pbuf, (size_t) P->timings.size, sizeof(sgs_VHTVar), dpm3sf ); sgs_Writef( P->C, "--- Memory usage by call stack frame ---\n" ); for( i = 0; i < P->timings.size; ++i ) { const char *s, *send; sgs_VHTVar* p = pbuf + i; mode3data* PD = (mode3data*) p->val.data.P; s = sgs_var_cstr( &p->key ); send = s + p->key.data.S->size; while( s < send ) { if( s != sgs_var_cstr( &p->key ) ) sgs_Writef( P->C, "::" ); sgs_Writef( P->C, "%s", s ); s += strlen( s ) + 1; } sgs_Writef( P->C, " - %d allocs, %d frees, %d delta blocks, %.3f delta memory (kB)\n", PD->numallocs, PD->numfrees, PD->numblocks, PD->szdelta / 1024.0 ); } sgs_Writef( P->C, "---\n" ); sgs_Free( P->C, pbuf ); return 1; } SGSBOOL sgs_ProfInit( SGS_CTX, SGS_PROF, int mode ) { P->hfn = NULL; P->hctx = NULL; sgs_GetHookFunc( C, &P->hfn, &P->hctx ); P->C = C; P->mode = mode; P->prev = 0; P->ictrs = NULL; P->iexcs = NULL; if( mode == SGS_PROF_FUNCTIME ) return initProfMode1( P ); else if( mode == SGS_PROF_OPTIME ) return initProfMode2( P ); else if( mode == SGS_PROF_MEMUSAGE ) return initProfMode3( P ); return 0; } SGSBOOL sgs_ProfClose( SGS_PROF ) { if( P->mode == SGS_PROF_FUNCTIME ) freeProfMode1( P ); else if( P->mode == SGS_PROF_OPTIME ) freeProfMode2( P ); else if( P->mode == SGS_PROF_MEMUSAGE ) freeProfMode3( P ); sgs_SetHookFunc( P->C, P->hfn, P->hctx ); return 1; } SGSBOOL sgs_ProfDump( SGS_PROF ) { if( P->mode == SGS_PROF_FUNCTIME ) return dumpProfMode1( P ); else if( P->mode == SGS_PROF_OPTIME ) return dumpProfMode2( P ); else if( P->mode == SGS_PROF_MEMUSAGE ) return dumpProfMode3( P ); return 0; } <file_sep>/src/sgs_xpc.h #ifndef SGS_XPC_H_INCLUDED #define SGS_XPC_H_INCLUDED #ifdef _MSC_VER # pragma warning( disable: 4996 ) # if _MSC_VER >= 1600 # include <stdint.h> # else typedef __int8 int8_t; typedef __int16 int16_t; typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; # endif # define SGS_INLINE # define PRId32 "d" # define PRId64 "lld" # define snprintf _snprintf # define SGS_VSPRINTF_LEN( str, args ) _vscprintf( str, args ) #else # include <inttypes.h> # define SGS_INLINE inline # define SGS_VSPRINTF_LEN( str, args ) vsnprintf( NULL, 0, str, args ) #endif #define UNUSED( x ) (void)(x) #if defined(__GNUC__) && ( __GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 7 ) ) # define SGS_ASSUME_ALIGNED __builtin_assume_aligned #else # define SGS_ASSUME_ALIGNED( x, a ) (x) #endif #ifdef __cplusplus #define SGS_DECLARE extern #else #define SGS_DECLARE static #endif #if SGS_DLL && !defined( __GNUC__ ) # if BUILDING_SGS # define SGS_APIFUNC __declspec(dllexport) # else # define SGS_APIFUNC __declspec(dllimport) # endif #else # define SGS_APIFUNC #endif #if SGS_DLL # define SGS_IF_DLL( dll, nodll ) dll #else # define SGS_IF_DLL( dll, nodll ) nodll #endif #ifdef SGS_USE_FILESYSTEM # include <sys/types.h> # include <sys/stat.h> # ifdef _WIN32 # include <direct.h> # define getcwd _getcwd # define mkdir _mkdir # define rmdir _rmdir # define stat _stat # include "../ext/msvc/dirent.h" # else # include <unistd.h> # include <dirent.h> # endif #endif #ifdef _WIN32 # define SGS_MODULE_EXT ".dll" #else # define SGS_MODULE_EXT ".so" #endif /* basic platform info */ #if _WIN32 || __WIN32__ || __WINDOWS__ # define SGS_OS_TYPE "Windows" #elif __APPLE__ # define SGS_OS_TYPE "Mac OS X" #elif __ANDROID__ # define SGS_OS_TYPE "Android" #elif __linux || __linux__ # define SGS_OS_TYPE "Linux" #elif __unix || __unix__ # define SGS_OS_TYPE "Unix" #elif __posix # define SGS_OS_TYPE "POSIX" #else # define SGS_OS_TYPE "Unknown" #endif /* simplified architecture info */ #if defined __arm__ || defined __thumb__ || defined _M_ARM || defined _M_ARMT # define SGS_ARCH_ARM 1 #endif #if defined i386 || defined __i386 || defined __i386 || defined _M_IX86 || defined _X86_ || defined __X86__ # define SGS_ARCH_X86 1 #endif #if defined __amd64__ || defined __amd64 || defined __x86_64__ || defined __x86_64 || defined _M_X64 || defined _M_AMD64 # define SGS_ARCH_AMD64 1 #endif #if defined __ia64__ || defined _IA64 || defined __IA64__ || defined _M_IA64 # define SGS_ARCH_IA64 1 #endif #if defined __powerpc || defined __powerpc__ || defined __powerpc64__ || \ defined __ppc__ || defined __ppc64 || defined _M_PPC || defined _XENON # define SGS_ARCH_PPC 1 #endif /* http://stackoverflow.com/a/2103095/1648140 */ enum { O32_LITTLE_ENDIAN = 0x03020100ul, O32_BIG_ENDIAN = 0x00010203ul }; static const union { unsigned char bytes[4]; uint32_t value; } o32_host_order = { { 0, 1, 2, 3 } }; #define O32_HOST_ORDER (o32_host_order.value) #ifdef __cplusplus extern "C" { #endif #define SGS_XPC_NOFILE -1 #define SGS_XPC_NOPROC -2 #define SGS_XPC_NOTSUP -3 #define SGS_XPC_NOTLIB -4 #define SGS_XPC_LDFAIL -5 int sgsXPC_GetProcAddress( const char* file, const char* proc, void** out ); char* sgsXPC_GetCurrentDirectory(); int sgsXPC_SetCurrentDirectory( char* path ); char* sgsXPC_GetModuleFileName(); #ifdef __cplusplus } #endif #endif /* SGS_XPC_H_INCLUDED */
5294a28e27e4b5ccaf8297dfb17593451d48d593
[ "HTML", "Makefile", "Text", "C", "C++" ]
26
C
elnormous/sgscript
97a5676239a3e1ebad082829e62460f8cd02bcc6
2bb8a1286f777d39267e0bc22e82eb473a0ec1e6
refs/heads/master
<repo_name>r4stered/AppletQuiz<file_sep>/index.js $(document).ready(function () { var allCorrect = true; console.log('Configuring Dragula for containers w/ d.gebt'); var drake = dragula( [ document.getElementById('options'), document.getElementById('catA'), document.getElementById('catB'), document.getElementById('catC'), document.getElementById('catD'), ] ); allCorrect = false; drake.on('drop', function(el, target, source, sibling){ console.log("Dropped:", el); var optionsLeft = $('#options .option').length; console.log('Options left:', optionsLeft); var catAChildren = $("#catA").children(); console.log('Children of catA:', catAChildren); allCorrect = true; if(optionsLeft > 0) { allCorrect = false; } $("#catC").children().each(function(i, e){ if(!$(e).hasClass('catC')){ allCorrect = false; } }); $("#catD").children().each(function(i, e){ if(!$(e).hasClass('catD')){ allCorrect = false; } }); $("#catA").children().each(function(i, e){ if(!$(e).hasClass('catA')){ allCorrect = false; } }); $("#catB").children().each(function(i, e){ if(!$(e).hasClass('catB')){ allCorrect = false; } }); console.log("allCorrect", allCorrect); /* for(i = 0; i < quad1Children.length; i++) { console.log('loop'); if(quad1Children[i].attrib('id') == 'catC') { console.log('correct!'); } } */ }) $('#checkButton').click(function() { if(allCorrect == true) { alert("Nice job! You got all of the quadrants correct!"); } else { alert("Sorry, try again!"); } }); });
7e9fb2d391425f2501798bad957f3c7d5d92b9b4
[ "JavaScript" ]
1
JavaScript
r4stered/AppletQuiz
1811f03053496f2f728d0acca0fd56ce5f813d63
3ab4c67fc760891751ceed37ac21d1d161066910
refs/heads/master
<file_sep>/* ------------------------------------------------------------------ * node-gotapi - http-server.js * * Copyright (c) 2017, <NAME>, All rights reserved. * Released under the MIT license * Date: 2017-01-03 * ---------------------------------------------------------------- */ 'use strict'; let mFs = require('fs'); let mPath = require('path'); let mIPRest = require('./ip-address-restriction.js'); /* ------------------------------------------------------------------ * Constructor: HttpServer(config) * ---------------------------------------------------------------- */ let HttpServer = function(config) { this.config = config; this.ext_mime_type_map = {}; this.directory_index = ['index.html', 'index.htm']; }; /* ------------------------------------------------------------------ * Method: start() * ---------------------------------------------------------------- */ HttpServer.prototype.start = function() { var promise = new Promise((resolve, reject) => { // Load the data of mime types this.mime_type_ext_map = require('./mime-types.js'); for(let mime in this.mime_type_ext_map) { this.mime_type_ext_map[mime].forEach((ext) => { this.ext_mime_type_map[ext] = mime; }); } // Start the HTTP server for web apps try { let server = null; let port = 0; if(this.config['ssl_engine'] === true) { let https = require("https"); server = https.createServer({ key : this.config['ssl_key_data'], cert : this.config['ssl_crt_data'], ca : this.config['ssl_ca_data'] }); port = this.config['https_server_port']; } else { let http = require('http'); server = http.createServer(); port = this.config['http_server_port']; } server.listen(port, () => { server.on('request', (req, res) => { this._receiveRequest(req, res); }); resolve(); }); } catch(error) { reject(error); } }); return promise; }; HttpServer.prototype._fileExists = function(path) { let flag = false; try { mFs.statSync(path); flag = true; } catch(e) { } return flag; }; /* ------------------------------------------------------------------ * Method: _receiveRequest(req, res) * ---------------------------------------------------------------- */ HttpServer.prototype._receiveRequest = function(req, res) { let ip_allowed = mIPRest.isArrowed(req.connection.remoteAddress, this.config['allowed_address_list']); if(!ip_allowed) { res.writeHead(403, {'Content-Type': 'text/plain'}); res.write('403 Forbidden'); res.end(); return; } let path = req.url.replace(/\?.*$/, ''); if(path.match(/[^a-zA-Z\d\_\-\.\/]/)) { this._response404(req.url, res); return; } let fpath = this.config['http_server_document_root'] + path; fpath = mPath.normalize(fpath); // Check if the file path is in the document root if(fpath.indexOf(this.config['http_server_document_root']) !== 0) { this._response404(req.url, res); return; } // Check whther the target of the file path is a file or a directory this._determineFileTarget([fpath], (target_fpath) => { mFs.readFile(target_fpath, 'utf-8', (err, data) => { if(err) { this._response404(req.url, res); } else { let ctype = this._getContentType(target_fpath); res.writeHead(200, {'Content-Type': ctype}); res.write(data); res.end(); } }); }); }; HttpServer.prototype._determineFileTarget = function(fpath_list, callback) { let fpath = fpath_list.shift(); if(!fpath) { callback(''); return; } mFs.stat(fpath, (err, stats) => { if(err) { if(fpath_list.length > 0) { this._determineFileTarget(fpath_list, callback); } else { callback(''); } } else if(stats.isFile()) { callback(fpath); } else if(stats.isDirectory()) { this.directory_index.forEach((f) => { let new_fpath = mPath.normalize(mPath.join(fpath, f)); fpath_list.unshift(new_fpath); }); this._determineFileTarget(fpath_list, callback); } }); }; HttpServer.prototype._getContentType = function(fpath) { let ext = fpath.split('.').pop().toLowerCase(); let ctype = this.ext_mime_type_map[ext]; if(!ctype) { ctype = 'application/octet-stream'; } return ctype; } HttpServer.prototype._response404 = function(url, res) { res.writeHead(404, {'Content-Type': 'text/plain'}); res.write('404 Not Found: ' + url); res.end(); } module.exports = HttpServer;<file_sep>/* ------------------------------------------------------------------ * node-gotapi - gotapi-interface-1.js * * Copyright (c) 2017, <NAME>, All rights reserved. * Released under the MIT license * Date: 2017-03-30 * ---------------------------------------------------------------- */ 'use strict'; let mOs = require('os'); let mCrypto = require('crypto'); let mIPRest = require('./ip-address-restriction.js'); /* ------------------------------------------------------------------ * Constructor: GotapiInterface1(config, sendToGotapiServer) * ---------------------------------------------------------------- */ let GotapiInterface1 = function(config, sendToGotapiServer) { this.config = config; this.sendToGotapiServer = sendToGotapiServer; this.local_address_list = ['localhost']; this.requests = {}; this.http_request_timeout = 60; // Seconds this.port = 0; this.server = null; this.status_codes = null; if(this.config['ssl_engine'] === true) { let https = require("https"); this.server = https.createServer({ key : this.config['ssl_key_data'], cert : this.config['ssl_crt_data'], ca : this.config['ssl_ca_data'] }); this.port = this.config['gotapi_if_ssl_port']; let http = require('http'); this.status_codes = http.STATUS_CODES; } else { let http = require('http'); this.server = http.createServer(); this.port = this.config['gotapi_if_port']; this.status_codes = http.STATUS_CODES; } this.oncommunication = null; }; /* ------------------------------------------------------------------ * Method: start() * ---------------------------------------------------------------- */ GotapiInterface1.prototype.start = function() { let promise = new Promise((resolve, reject) => { // Get the local IP addresses let netifs = mOs.networkInterfaces(); for(let dev in netifs) { netifs[dev].forEach((info) => { this.local_address_list.push(info.address); }); } // Start the HTTP server for the GotAPI-1 Interface try { this.server.listen(this.port, () => { this.server.on('request', (req, res) => { this._monitorIncoming(req); this._receiveRequestFromApp(req, res); }); resolve(); }); } catch(error) { reject(error); } // Start to watch http connections this._watchHttpConnections(); }); return promise; }; GotapiInterface1.prototype._monitorIncoming = function(req) { if(!this.oncommunication) { return; } this.oncommunication({ type : 1, dir : 1, url : req.url, method : req.method, headers: req.headers }); }; GotapiInterface1.prototype._monitorOutgoing = function(m) { if(!this.oncommunication) { return; } this.oncommunication({ type : 1, dir : 2, code : m['code'], headers : m['headers'], data : m['data'] }); }; GotapiInterface1.prototype._watchHttpConnections = function() { let now = Date.now(); Object.keys(this.requests).forEach((request_id) => { let request = this.requests[request_id]; if(now - request['ctime'] > this.http_request_timeout * 1000) { this._returnErrorToApp(request_id, 408, 'The GotAPI Server did not respond.'); } }); setTimeout(() => { this._watchHttpConnections(); }, 1000); }; GotapiInterface1.prototype._receiveRequestFromApp = function(req, res) { let ip_allowed = mIPRest.isArrowed(req.connection.remoteAddress, this.config['allowed_address_list']); if(ip_allowed) { if(this._checkOrigin(req)) { let method = req.method.toLowerCase(); if(method === 'options') { this._retunForPreflightRequestToApp(req, res); } else if(method.match(/^(get|post|put|delete)$/)) { this._handleRequestFromApp(req, res); } else { this._retun403ToApp(req, res, 'The HTTP method `' + method + '` is not allowed.'); } } else { this._retun403ToApp(req, res, 'The access from the origin `' + req.headers['origin'] + '` is not allowed.'); } } else { this._retun403ToApp(req, res, 'The access from the IP address `' + req.connection.remoteAddress + '` is not allowed.'); } }; GotapiInterface1.prototype._checkOrigin = function(req) { if(this.config['disable_auth']) { return true; } let origin = req.headers['origin']; let scheme = ''; let port = 0; if(this.config['ssl_engine'] === true) { scheme = 'https:'; port = this.config['https_server_port']; } else { scheme = 'http:'; port = this.config['http_server_port']; } let allowed = false; for(let i=0; i<this.local_address_list.length; i++) { let addr = this.local_address_list[i]; if(req.headers['origin'] === scheme + '//' + addr + ':' + port) { allowed = true; break; } } if(allowed === true) { return allowed; } let allowed_origin_list = this.config['allowed_origin_list']; if(allowed_origin_list && Array.isArray(allowed_origin_list) && allowed_origin_list.length > 0) { for(let i=0; i<allowed_origin_list.length; i++) { if(req.headers['origin'] === allowed_origin_list[i]) { allowed = true; break; } } } return allowed; }; GotapiInterface1.prototype._retun403ToApp = function(req, res, err_message) { let code = 403; let headers = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': req.headers['origin'] }; res.writeHead(code, headers); let data = { result : code, errorCode : code, errorText : this.status_codes[code] || 'Unknown Error', errorMessage : err_message }; res.write(JSON.stringify(data)); res.end(); this._monitorOutgoing({code: code, data: data, headers: headers}); }; GotapiInterface1.prototype._retunForPreflightRequestToApp = function(req, res) { let headers = { 'Content-Type' : 'application/json', 'Access-Control-Allow-Origin' : req.headers['origin'], 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE' }; res.writeHead(200, headers); res.write(''); res.end(); this._monitorOutgoing({code: 200, data: null, headers: headers}); }; GotapiInterface1.prototype._handleRequestFromApp = function(req, res) { let method = req.method.toLowerCase(); let request_id = this._createNewRequestId(); let url_path_parts = (req.url.split('?'))[0].split('/'); let params_parse_result = this._parseQueryString(req.url); this.requests[request_id] = { req : req, res : res, ctime : Date.now(), message: { if_type : 1, request_id : request_id, request_url : req.url, params : params_parse_result['result'], package : this.config['disable_auth'] ? 'dummy' : req.headers['origin'], api : url_path_parts[1], profile : url_path_parts[2] || '', attribute : url_path_parts[3] || '', method : req.method.toLowerCase() } }; if(params_parse_result['error']) { this._returnErrorToApp(request_id, 400, 'The specified parameters could not been parsed: ' + params_parse_result['error']); return; } if(url_path_parts[1] === 'gotapi') { this.sendToGotapiServer(this.requests[request_id]['message']); } else { this._returnErrorToApp(request_id, 404, 'The URL of the request is invalid.'); } }; GotapiInterface1.prototype._createNewRequestId = function() { let id = ''; id += mCrypto.randomBytes(32).toString('hex') + '_'; id += Date.now(); let sha256 = mCrypto.createHash('sha256'); sha256.update(id); id = sha256.digest('hex'); return id; }; GotapiInterface1.prototype._returnErrorToApp = function(request_id, code, error_message) { let request = this.requests[request_id]; if(!request || !request['message']) { return; } let message = request['message']; message['result'] = code; message['errorCode'] = code; message['errorText'] = this.status_codes[code] || 'Plug-In Error', message['errorMessage'] = error_message; this._returnResponseToApp(message); }; GotapiInterface1.prototype._parseQueryString = function(url) { let parts = url.split('?'); let q = parts[1]; let p = {}; if(!q) { return { result: p }; } let kv_list = q.split('&'); let error = ''; kv_list.forEach((kv) => { let pair = kv.split('='); try { p[pair[0]] = decodeURIComponent(pair[1]); } catch(e) { error = e.message; } }); return { result: p, error: error }; }; GotapiInterface1.prototype._returnResponseToApp = function(data) { let request_id = data['request_id']; let request = this.requests[request_id]; if(!request || !request['req'] || !request['res']) { delete this.requests[request_id]; return; } let status_code = 200; if(data['result'] === 0) { data['errorCode'] = 0; data['errorText'] = ''; data['errorMessage'] = ''; } else { status_code = data['errorCode']; data['errorText'] = this.status_codes[status_code] || 'Unknown Error'; if(!data['errorMessage']) { data['errorMessage'] = data['errorText']; } } let nonce = data['params']['nonce']; let key = ''; if(data['_client']) { key = data['_client']['key']; } if(nonce && key) { data['hmac'] = mCrypto.createHmac('sha256', key).update(nonce).digest('hex');; } data['serviceId'] = ('params' in data) ? data['params']['serviceId'] : ''; // Delete the properties used internally if(!(data['profile'] === 'authorization' && data['attribute'] === 'grant')) { delete data['clientId']; } delete data['if_type']; delete data['package']; delete data['request_id']; delete data['action']; delete data['params']; delete data['request_url']; delete data['api']; delete data['receiver']; delete data['_client']; delete data['method']; delete data['_plugin_id_list']; let res = request['res']; let req = request['req']; let headers = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': req.headers['origin'] }; res.writeHead(status_code, headers); res.write(JSON.stringify(data)); res.end(); this._monitorOutgoing({code: status_code, data: data, headers: headers}); delete this.requests[request_id]; }; /* ------------------------------------------------------------------ * Method: postMessage(data) * This method is just an alias of the `_returnResponseToApp()` method, * which is exposed to the GotAPI Server. * When this method is called by the GotAPI Server, this method will * pass the message to the web app on the GotAPI-1 Interface. * ---------------------------------------------------------------- */ GotapiInterface1.prototype.postMessage = GotapiInterface1.prototype._returnResponseToApp; module.exports = GotapiInterface1;<file_sep>node-gotapi Changelog ====================== ## 0.1.8 (2017-03-30) - Fixed the bug in the debug mode. If there is no query string in the request URL, then the node-gotapi died. Now this bug is fixed. ## 0.1.7 (2017-03-29) - Fixed the bug which the node-gotapi prosess was down if the query string in the request URL includes non-UTF-8 characters. Now the node-gotapi returns an error. ## 0.1.6 (2017-03-29) - Fixed the bug which Plug-Ins could not set a custom error code to the `result` property in a response. ## 0.1.5 (2017-03-07) - Fixed the bug which any accesses on the GotAPI-1 Interface are allowed in the production mode if the `allowed_address_list` is empty in the `config.js`. - Changed the error message reported when the access from the front-end application on the GotAPI-1 Interface is denied, so that you can get the reason why the access was denied: the IP address or the origin. ## 0.1.4 (2017-03-06) - Fixed the bug which the GotAPI-1 Interface always denied any accesses from the localhost in some Linux environments in the production mode (not the debug mode). ## 0.1.3 (2017-03-05) - Changed line break from CRLF to LF in some files. ## 0.1.2 (2017-03-04) - Removed the script `start-gotapi-debug.js` which starts the node-gotapi for debugging. Instead, `start-gotapi.js` supports some command options for debugging. ## 0.1.1 (2017-02-26) - Changed the WebSocket module from the [websocket.io](https://github.com/LearnBoost/websocket.io) to the [WebSocket-Node](https://github.com/theturtle32/WebSocket-Node). The reason for this is that the [websocket.io](https://github.com/LearnBoost/websocket.io) has not been updated for a few years and it does not support Node 6 for now. ## 0.1.0 (2017-02-18) - Added a debug mode - The `start-gotapi-debug.js` now supports a mode which ignores the grant and access token mechanism. In this mode, you can debug Plug-Ins easily. - Extended the name space of property names for response from Plug-Ins - The property name for response for Plug-Ins was limited to `data`, now any property names are allowed except the prohibited property names for response. - Disabled the `console.log()`, `console.dir()` and `console.error()` methods in the `start-gotapi.js` - If you want to check the outputs generated by the GotAPI Server and the Plug-Ins on your shell, use the `start-gotapi-debug.js` instead of the `start-gotapi.js`.
0f2d7238c76890efb1bbd257b83caecd9c8d84e2
[ "JavaScript", "Markdown" ]
3
JavaScript
TakayukiHoshi1984/node-gotapi
e2535257280500d25a802d9cd79083b1f0eb7605
f66c009caa31490c63b355cb0e85c9d3c570f00e
refs/heads/master
<file_sep>module Cenit module BuildInApps module OauthHelpers def self.included(m) m.controller do def if_can?(action, model = nil) error_description = nil if (auth_header = request.headers['Authorization']) auth_header = auth_header.to_s.squeeze(' ').strip.split(' ') if auth_header.length == 2 access_token = Cenit::OauthAccessToken.where(token_type: auth_header[0], token: auth_header[1]).first if access_token&.alive? if (user = access_token.user) User.current = user if access_token.set_current_tenant! access_grant = Cenit::OauthAccessGrant.where(application_id: access_token.application_id).first if access_grant oauth_scope = access_grant.oauth_scope if oauth_scope.can?(action, model) yield if block_given? else error_description = 'The requested action is out of the access token scope' end else error_description = 'Access grant revoked or moved outside token tenant' end end else error_description = 'The token owner is no longer an active user' end else error_description = 'Access token is expired or malformed' end else error_description = 'Malformed authorization header' end end if error_description response.headers['WWW-Authenticate'] = %(Bearer realm="example",error="insufficient_scope",error_description=#{error_description}) render json: { error: 'insufficient_scope', error_description: error_description }, status: :forbidden end end end end end end end<file_sep>module Cenit module BuildInApps module AppBuilder extend self attr_reader :app_id def controller_defs @controller_defs ||= [] end def document_types_defs @document_types_defs ||= {} end def file_types_defs @file_types_defs ||= {} end def types_options @types_options ||= {} end def custom_layout(*args) if args.length > 0 layout = args[0] @custom_layout = if layout.is_a?(String) args[0] elsif layout controller_prefix else nil end end @custom_layout end def initializers unless @initializers @initializers = [] end @initializers end def on_initialize(&block) initializers << block end def installers unless @installers @installers = [] install do ::Setup::Namespace.find_or_create_by(name: to_s).update(slug: app_key) end end @installers end def install(&block) installers << block end def default_redirect_uris @default_redirect_uris ||= [ -> { "#{Cenit.homepage}/oauth/callback" } ] end def setups unless @setups @setups = [] setup do app = self.app config = app.configuration redirect_uris = config.redirect_uris || [] default_redirect_uris.each do |uri| next unless uri uri = uri.call unless uri.is_a?(String) next if redirect_uris.include?(uri) redirect_uris << uri puts "OAuth callback URI added: #{uri}" end config.redirect_uris = redirect_uris app.save puts("#{self}:redirect_uris", JSON.pretty_generate(app.configuration.redirect_uris)) end end @setups end def setup(&block) setups << block end def document_type(name, options = nil, &block) fail "#{name} already defined as a file" if file_types_defs.key?(name) types_options[name] = options if options document_types_defs[name] = block end def file_type(name, options = nil, &block) fail "#{name} already defined as a document" if document_types_defs.key?(name) types_options[name] = options if options file_types_defs[name] = block end def controller(&block) controller_defs << block end def controller? controller_defs.any? end def short_name to_s.split('::').last end def app_key(*args) if args.length == 0 @app_key || short_name.underscore else @app_key = args[0].to_s end end def app_name(*args) if args.length == 0 @app_name || short_name else @app_name = args[0].to_s end end def app Cenit::BuildInApp.find(app_id) end def controller_prefix(*args) @controller_prefix = args[0] if args.length > 0 @controller_prefix ||= begin tokens = to_s.split('::').map(&:underscore) tokens.pop tokens << app_key tokens.join('/') end end end end end<file_sep>require 'cenit/build_in_apps/version' require 'cenit/build_in_apps/error' require 'cenit/build_in_apps/app_builder' require 'cenit/build_in_apps/oauth_helpers' module Cenit module BuildInApps def self.included(m) m.extend(AppBuilder) apps_modules << m # Create app engine engine = Class.new(::Rails::Engine) m.const_set('Engine', engine) # Fixing engine dir called location (check ::Rails::Engine#inerited for details) call_stack = if Kernel.respond_to?(:caller_locations) caller_locations.map { |l| l.absolute_path || l.path } else # Remove the line number from backtraces making sure we don't leave anything behind caller.map { |p| p.sub(/:\d+.*/, '') } end engine_dir = File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] }) engine.called_from = engine_dir assets_dir = engine_dir.split('/') assets_dir.pop(2) assets_dir = "#{assets_dir.join('/')}/app/assets" assets = [] %w(javascripts stylesheets images).each do |dir| dir = "#{assets_dir}/#{dir}" Dir["#{dir}/**/*"].each do |file| next unless File.file?(file) if file.ends_with?('.scss') file = file[0..(file.length - 6)] end assets << file[(dir.length + 1)..file.length] end end unless assets.empty? engine.initializer :assets do Rails.application.config.assets.precompile += assets end end end module_function def apps_modules @apps_modules ||= [] end def controllers @controllers ||= {} end def build_controllers_from(parent) apps_modules.each do |app_module| controller = Class.new(parent) controller.instance_variable_set(:@app_module, app_module) app_module.controller_defs.each do |controller_def| controller.class_eval(&controller_def) end key = app_module.app_key app_module.const_set('MainController', controller) if app_module.custom_layout controller.class_eval <<-RUBY layout '#{app_module.custom_layout}' RUBY end controller.class_eval <<-RUBY def self.local_prefixes ['#{app_module.controller_prefix}'] end RUBY controllers[key] = controller end end end end <file_sep>RSpec.describe Cenit::BuildInApps do it "has a version number" do expect(Cenit::BuildInApps::VERSION).not_to be nil end end <file_sep>require_relative 'lib/cenit/build_in_apps/version' Gem::Specification.new do |spec| spec.name = "cenit-build_in_apps" spec.version = Cenit::BuildInApps.version spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = %q{Support for Cenit Build-In Apps.} spec.description = %q{Basic functionality to create a build-in app for Cenit.} spec.homepage = "https://cenit.io" spec.license = "MIT" end
3fa4e4cedaaef33ac3e5e4ad9e66b787ddd1bd6b
[ "Ruby" ]
5
Ruby
cenit-io/cenit-build_in_apps
31369fdcaf871938f4178d311a2230f760afc5cc
286427eaba2674d8179a32f6cffb3a4803bba71d
refs/heads/master
<file_sep>const {sequelize} = require('../../../core/db') const {Sequelize, Model} = require('sequelize') const ObituaryAlive = require('../../models/obituary/ObituaryAlive') const ObituaryLonely = require('../../models/obituary/ObituaryLonely') const ObituaryInfernal = require('../../models/obituary/ObituaryInfernal') class ObituaryDel extends Model{ static async getObituaryList(current=1, size=10, name='', genre='', type=''){ const data = await ObituaryDel.findAndCountAll({ where:{ name: { $like: `%${name}%`, }, }, limit: size * 1, offset: size * (current - 1), }) return data } // 根据id查询 static async getItemInfo(id){ const data = await ObituaryDel.findOne({ where:{ id:id } }) return data } //恢复 static async deleteItem(id){ return sequelize.transaction(t => { return ObituaryDel.findOne({ where:{ id:id } }, {transaction: t}).then(user => { return ObituaryDel.destroy({ where:{id:user.id}, force:true },{transaction: t}).then(row=>{ if(user.status===1){ return ObituaryAlive.create(user, {transaction: t}) }else if(user.status===2){ return ObituaryLonely.create(user, {transaction: t}) }else if(user.status===3){ return ObituaryInfernal.create(user, {transaction: t}) } }); }); }).then(result => { }).catch(err => { console.log('事件已回滚') throw new global.errors.NotFound() }); } } ObituaryDel.init({ id:{ type:Sequelize.INTEGER, primaryKey:true, autoIncrement:true, }, name:{ type:Sequelize.STRING, allowNull:false }, status:{ type:Sequelize.INTEGER, defaultValue:1 // 1阳寿未尽 2孤魂野鬼 3地府鬼魂 4已删除 }, sex:{ type:Sequelize.INTEGER, defaultValue:1 //1男 2女 }, life:{//寿命 type:Sequelize.INTEGER, }, genre:{ type:Sequelize.INTEGER, defaultValue:1 //1:人 2:动物 3:植物 }, Infernal:{//第几层地狱 type:Sequelize.INTEGER, }, type:{ type:Sequelize.INTEGER, defaultValue:1 //1:善终 2:病死 3:意外死亡 4:被害 5:自杀 }, area:Sequelize.STRING,//地区 birthday:Sequelize.STRING },{sequelize}) module.exports = ObituaryDel<file_sep>const RequireDirectory = require('require-directory') const Router = require('koa-router') class initManager { static initCore(app){ // 入口方法 initManager.app = app initManager.initLoadRouters() initManager.initError() initManager.loadConfig() } static initLoadRouters(){ const path = `${process.cwd()}/app/api` RequireDirectory(module,path,{ visit : whenLoadMoudle }) function whenLoadMoudle(obj){ if(obj instanceof Router){ initManager.app.use(obj.routes()) } } } static initError(){ const error = require('./http-exception') global.errors = error } static loadConfig (path='') { const configPath = path || `${process.cwd()}/config/config.js` const config = require(configPath) global.config = config } } module.exports = initManager<file_sep>const Router = require('koa-router') const bcrypt = require('bcryptjs') const router = new Router({ prefix:'/v1/user' }) const { RegisterException } = require('../../validators/validator') const User = require('../../models/user') router.post('/register',async (ctx,next)=>{ let v = await new RegisterException().validate(ctx) const user = { phone:v.get('body.phone'), password:<PASSWORD>('<PASSWORD>'), nickname:v.get('body.nickname'), auth:v.get('body.auth') } await User.create(user) throw new global.errors.Success() }) module.exports = router<file_sep>const Router = require('koa-router') const router = new Router({ prefix:'/v1/obituary' }) const ReaponseBase = require('../../lib/ReaponseBase') const reaponseBase = new ReaponseBase() const ObituaryAlive = require('../../models/obituary/obituaryAlive') const ObituaryLonely = require('../../models/obituary/obituaryLonely') const ObituaryInfernal = require('../../models/obituary/obituaryInfernal') const ObituaryDel = require('../../models/obituary/obituaryDel') const { ObituaryValidator, ObituaryDeleteValidator } = require('../../validators/validator') // status:1阳寿未尽 2孤魂野鬼 3地府鬼魂 4已删除 router.post('/getList',async(ctx, next)=>{ const v = await new ObituaryValidator().validate(ctx) const body = v.get('body') const {status,current,size,name,genre,type} = body let getList = getObituaryList(status) const data = await getList(current,size,name,genre,type) const reaponseBody = { list:data.rows, total:data.count } ctx.body = reaponseBase.success('',reaponseBody) }) router.get('/getInfoById',async(ctx, next)=>{ let v = await new ObituaryDeleteValidator().validate(ctx) const query = v.get('query') const {id,status} = query let getInfo = getInfoById(status) const data = await getInfo(id) ctx.body = reaponseBase.success('',data) }) router.delete('/deleteById', async(ctx, next)=>{ const v = await new ObituaryDeleteValidator().validate(ctx) const query = v.get('query') const {id,status} = query let deleteFun = deleteItem(status) await deleteFun(id) ctx.body = reaponseBase.success('删除成功') }) router.put('/update', async(ctx, next)=>{ const v = await new ObituaryValidator().validate(ctx) const body = v.get('body') const id = v.get('query.id') let updateFun = updateItem(body.status) const data = await updateFun(body,id) ctx.body = reaponseBase.success('修改成功') }) function getObituaryList(status){ switch (status) { case 1: return ObituaryAlive.getObituaryList break; case 2: return ObituaryLonely.getObituaryList break; case 3: return ObituaryInfernal.getObituaryList break; case 4: return ObituaryDel.getObituaryList break; default: throw new global.errors.ParameterException() break; } } function getInfoById(status){ switch (status) { case 1: return ObituaryAlive.getItemInfo break; case 2: return ObituaryLonely.getItemInfo break; case 3: return ObituaryInfernal.getItemInfo break; case 4: return ObituaryDel.getItemInfo break; default: throw new global.errors.ParameterException() break; } } function deleteItem(status){ switch (status) { case 1: return ObituaryAlive.deleteItem break; case 2: return ObituaryLonely.deleteItem break; case 3: return ObituaryInfernal.deleteItem break; case 4: return ObituaryDel.deleteItem break; default: throw new global.errors.ParameterException() break; } } function updateItem(status){ switch (status) { case 1: return ObituaryAlive.updateItem break; case 2: return ObituaryLonely.updateItem break; case 3: return ObituaryInfernal.updateItem break; case 4: return ObituaryDel.updateItem break; default: throw new global.errors.ParameterException() break; } } module.exports = router<file_sep>const Router = require('koa-router') const router = new Router({ prefix:'/v1/token' }) const {LoginType} = require('../../lib/enum') const User = require('../../models/user') const { TokenException } = require('../../validators/validator') const { generateToken } = require('../../../core/util') router.post('/',async (ctx)=>{ let v = await new TokenException().validate(ctx) let token; switch (v.get('body.type')) { case LoginType.USER_ACCOUNT: token = await accountLogin(v.get('body.account'),v.get('body.password')) break; case LoginType.USER_MOBILE: //验证手机验证码 break; default: throw new global.errors.ParameterException('没有相应的处理函数') break; } ctx.body = { token } }) async function accountLogin(account,password){ const user = await User.verifyAccountPassword(account,password) return token = generateToken(user.id, user.auth) } module.exports = router<file_sep>const {sequelize} = require('../../../core/db') const {Sequelize, Model} = require('sequelize') const ObituaryDel = require('../../models/obituary/obituaryDel') const Op = Sequelize.Op; class obituaryInfernal extends Model{ static async getObituaryList(current=1, size=10, name='', genre='', type=''){ const data = await obituaryInfernal.findAndCountAll({ where:{ name: { [Op.like]: `%${name}%` }, genre:{ [Op.like]: `%${genre}%` }, type:{ [Op.like]: `%${type}%` } }, limit: size * 1, offset: size * (current - 1), }) return data } // 根据id查询 static async getItemInfo(id){ const data = await obituaryInfernal.findOne({ where:{ id:id } }) return data } //删除 static async deleteItem(id){ return sequelize.transaction(t => { return obituaryInfernal.findOne({ where:{ id:id } }, {transaction: t}).then(user => { return ObituaryDel.create(user, {transaction: t}).then(user=>{ return obituaryInfernal.destroy({ where:{id:user.id}, force:true },{transaction: t}); }); }); }).then(result => { }).catch(err => { throw new global.errors.NotFound() }); } //更新 static async updateItem(params,id){ const data = await obituaryInfernal.update(params,{ where:{ id:id } }) return data } } obituaryInfernal.init({ id:{ type:Sequelize.INTEGER, primaryKey:true, autoIncrement:true, }, status:{ type:Sequelize.INTEGER, defaultValue:3 // 1阳寿未尽 2孤魂野鬼 3地府鬼魂 4已删除 }, name:{ type:Sequelize.STRING, allowNull:false }, sex:{ type:Sequelize.INTEGER, defaultValue:1 //1男 2女 }, life:{//寿命 type:Sequelize.INTEGER, }, genre:{ type:Sequelize.INTEGER, defaultValue:1 //1:人 2:动物 3:植物 }, Infernal:{//第几层地狱 type:Sequelize.INTEGER, }, type:{ type:Sequelize.INTEGER, defaultValue:1 //1:善终 2:病死 3:意外死亡 4:被害 5:自杀 }, area:Sequelize.STRING,//地区 birthday:Sequelize.STRING },{sequelize}) module.exports = obituaryInfernal<file_sep>const {LinValidator, Rule} = require('../../core/lin-validator-v2') const User = require('../models/user') const { LoginType } = require('../lib/enum') class PositiveIntegerValidator extends LinValidator{ constructor(){ super() this.id = [ new Rule('isInt','需要是正整数',{min:1}) ] } } class RegisterException extends LinValidator{ constructor(){ super() this.phone = [ new Rule('matches','不符合手机号规范',"^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[1,3,5,8,9])\\d{8}$") ] this.password = [ new Rule('isLength','密码至少6个字符,最多32个字符',{min:6,max:32}), new Rule('matches','密码不符合规范',"(?=.*([a-zA-Z].*))(?=.*[0-9].*)[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,32}$") ] this.nickname = [ new Rule('isLength','昵称长度不符合规范',{min:1,max:16}) ] } async validatePhone(vals){ const phone = vals.body.phone const user = await User.findOne({ where:{ phone:phone } }) if (user) { throw new Error('该手机号已注册') } } } class TokenException extends LinValidator{ constructor(){ super() this.account = [ new Rule('matches','不符合手机号规范',"^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[1,3,5,8,9])\\d{8}$") ] this.password = [ new Rule('isOptional'), new Rule('isLength','密码至少6个字符,最多32个字符',{min:6,max:32}), ] } validateType(vals){ if(!vals.body.type){ throw new Error('type是必填参数') } if(!LoginType.isThisType(vals.body.type)){ throw new Error('type参数不合法') } } } class ObituaryValidator extends LinValidator{ constructor(){ super() this.status = [ new Rule('isInt','传入正确的状态'), new Rule('isLength', '请传入状态', {min: 1}) ] } } class IdValidator extends LinValidator{ constructor(){ super() this.id = [ new Rule('isLength', '请传入id', {min: 1}) ] } } class ObituaryDeleteValidator extends LinValidator{ constructor(){ super() this.id = [ new Rule('isLength', '请传入id', {min: 1}) ] this.status = [ new Rule('isInt','传入正确的状态'), new Rule('isLength', '请传入状态', {min: 1}) ] } } module.exports = { PositiveIntegerValidator, RegisterException, TokenException, ObituaryValidator, IdValidator, ObituaryDeleteValidator }<file_sep># underground-serve-node 地府后台管理系统的服务端(node实现) <file_sep>module.exports = { environment:'dev', // environment:'prod', database: { dbName: 'underground', host: 'localhost', port: '3306', user: 'root', password:'<PASSWORD>' }, security: { secretKey: 'abcdefg', expiresIn: 60*60 } }<file_sep>class ReaponseBase{ constructor(error_code=0,message='',data={}){ this.error_code = error_code this.message = message this.data = data } success(message='',data={}){ return { error_code: 0, message, data } } } module.exports = ReaponseBase
3ad1eab732a1ae7cfc74d968dde09d67d6085f25
[ "JavaScript", "Markdown" ]
10
JavaScript
wangtiant/underground-serve-node
06ab9b5107101243887a5f6da4c81ec337d46cc0
4e04750d84f4f56e572bdcdfd1db4291b4d8baea
refs/heads/master
<file_sep>//<NAME> //8606 package userApplication; import java.io.*; import java.util.Scanner; import java.util.ArrayList; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.File; import java.io.FileOutputStream; import ithakimodem.Modem; import java.lang.*; public class userApplication { public static void main(String[] args) { for (;;) { // menu epilogis Scanner input = new Scanner(System.in); System.out.println("hello! please select one of the options below"); System.out.println("for downloading echo pachet press 1"); System.out.println("for downloading image with no error press 2"); System.out.println("for downloading image with error press 3"); System.out.println("for downloading gps info press 4"); System.out.println("for ARQ packages press 5"); System.out.println("for exiting userApplication press 6"); try { int choice = input.nextInt(); switch (choice) { case 1: new userApplication().getEchoPackets(); continue; case 2: new userApplication().getImage(0); continue; case 3: new userApplication().getImage(1); continue; case 4: new userApplication().getGPS(); continue; case 5: new userApplication().ARQ(); continue; case 6: break; } } catch (Exception e) { System.out.println("sorry,you didnt give a right choice"); } } } public Modem createModem() { int data = 0; Modem modem; modem = new Modem(); modem.setSpeed(82000); modem.setTimeout(20000); modem.write("atd2310ithaki\r".getBytes()); for (;;) { try { data = modem.read(); if (data == -1) break; System.out.print((char) data); } catch (Exception x) { break; } } return modem; } public void getEchoPackets() { String code; int preData = 0, afterData = 0;// metavlites apothikefsis dedomenwn int numOfPackets = 0;// arithmos paketwn pou elifthisan double startTime = 0, endTime = 0, totalTime = 0, startDL = 0, endDL = 0, avgTime = 0; Scanner input = new Scanner(System.in); ArrayList<String> DLinfo = new ArrayList<String>();// apothikefsi pliroforiwn lipsis System.out.println("please instert the code for recieving packet in the form:XXXX"); code = input.nextLine(); Modem modem; modem = createModem(); startDL = System.nanoTime(); while (endDL < 4 * 60 * 1000) { modem.write(("E" + code + "\r").getBytes()); numOfPackets++; startTime = System.nanoTime(); for (;;) { try { preData = afterData; afterData = modem.read(); System.out.print((char) afterData); if (((char) preData == 'O') && ((char) afterData == 'P')) { endTime = (System.nanoTime() - startTime) / 1000000; break; } } catch (Exception e) { System.out.println("packet download wasn't successfull"); } } DLinfo.add(String.valueOf(endTime)); totalTime += endTime; endDL = (System.nanoTime() - startDL) / 1000000; System.out.println(" "); } avgTime = totalTime / numOfPackets; DLinfo.add("Total time of download:" + String.valueOf(totalTime) + "milisec"); System.out.println("Total time of download:" + String.valueOf(totalTime) + "milisec"); DLinfo.add("Total time of Comunication with server:" + String.valueOf(endDL) + "milisec"); System.out.println("Total time of Comunication with server:" + String.valueOf(endDL) + "milisec"); DLinfo.add("Number of packets downloaded: " + String.valueOf(numOfPackets)); System.out.println("Number of packets downloaded: " + String.valueOf(numOfPackets)); DLinfo.add("Average time for packet download : " + String.valueOf(avgTime) + "milisec"); System.out.println("Average time for packet download : " + String.valueOf(avgTime) + "milisec"); BufferedWriter BW = null; try { File echofile = new File("C:\\Users\\ypatiapd\\Desktop\\δικτυα\\Echo" + code + ".txt"); BW = new BufferedWriter( new FileWriter(("C:\\Users\\ypatiapd\\Desktop\\δικτυα\\Echo" + code + ".txt"), true)); if (!echofile.exists()) { echofile.createNewFile(); } for (int i = 0; i < DLinfo.size(); i++) { BW.write(String.valueOf(DLinfo.get(i))); BW.newLine(); } BW.newLine(); } catch (Exception e) { System.out.println("couldn't write a echofile"); } finally { try { if (BW != null) BW.close(); } catch (Exception e) { System.out.println("couldn't close the BufferedWriter" + e); } } } public void getImage(int er) { ArrayList<Integer> Image = new ArrayList<Integer>(); // apothikevetai i eikona san ascii String type = " "; String code = " "; String fileName = " "; int preData = 0, afterData = 0; Scanner input = new Scanner(System.in); if (er == 0) type = "M"; else type = "G"; System.out.println("please insert the code for downloading image in form XXXX"); code = input.nextLine(); Modem modem; modem = createModem(); modem.write((type + code + "\r").getBytes()); for (;;) { try { preData = afterData; afterData = modem.read(); System.out.println(afterData); Image.add(afterData); if ((preData == 255) && (afterData == 217)) break; } catch (Exception e) { System.out.println("couldnt download image"); } } if (er == 0) fileName = ("C:\\Users\\ypatiapd\\Desktop\\δικτυα\\imageNoError" + code + ".jpeg"); else fileName = ("C:\\Users\\ypatiapd\\Desktop\\δικτυα\\imageError" + code + ".jpeg"); try { FileOutputStream imageFile = new FileOutputStream(fileName); for (int i = 0; i < Image.size(); i++) { imageFile.write(Image.get(i)); } imageFile.close(); } catch (Exception e) { System.out.println(" couldnt create file"); } System.out.println(" "); System.out.println("image download was successfull"); modem.close(); } public void getGPS() { String Tpar = new String();// apothikefsi Tparametrou se morfi string int[] gpsUnit = new int[80];// apothikefsi dedomenwn tis kathe enotitas se int pinaka int[][] latlong = new int[2][10];// apomonosi g.mikous kai g.platous se disdiastato pinaka String[] TparApparts = new String[6];// pinakas pou apothikevei ta stoixeia tis T parametrou prin enopoihthoun // se ena string ArrayList<String> Tparameters = new ArrayList<String>();// arraylist pou apothikevei oles tis Tparametrous ArrayList<Integer> Image = new ArrayList<Integer>();// arraylist pou apothikevei ta dedomena tis eikonas gps float[] latInfo = new float[6];// stoixeia g.platous float[] longInfo = new float[6];// stoixeia g.mikous float[] latDigInfo = new float[6];// stoixeia gwnias g.platous float[] longDigInfo = new float[6];// stoixeia gwnias g.mikous String fileName = " "; String code = " "; int pointer = 0;// metritis gia ton pinaka gpsUnit int preData = 0, afterData = 0; Scanner input = new Scanner(System.in); System.out.println("please insert the code for downloading gps units"); code = input.nextLine(); Modem modem; modem = createModem(); modem.write(("P" + code + "R=1000199" + "\r").getBytes()); for (;;) { try { preData = afterData; afterData = modem.read(); gpsUnit[pointer] = afterData; System.out.print((char) gpsUnit[pointer]); pointer++; if (((char) preData == 'N') && ((char) afterData == 'G'))// ews ayto to simeio tis enotitas ta dedomena // den mas aforoun continue; if (((char) preData == 'O') && ((char) afterData == 'P'))// sto telos i kathe enotita exei STOP break; if ((preData == 13) && (afterData == 10)) { for (int i = 0; i < 10; i++) { latlong[0][i] = gpsUnit[i + 18];// apo ayta ta simeia tis gpsUnit apomonwnoume g.platos kai // g.mikos kai ta apothikevoume ston pinaka latlong latlong[1][i] = gpsUnit[i + 30]; // System.out.print((char)latlong[0][i]); } // afairoume 48 apo tin kathe timi tou pinaka gia na paroume tin arithmitiki // timi kai // analoga me ti thesi tou psifeiou diairoume me katallili dynami tou 10 // etsi wste me tin prosthesi aytwn se mia metavliti na prokypsei o arithmos tou // mikous kai tou platous antistoixa latInfo[0] = (float) (latlong[0][2] - 48) / 10; latInfo[1] = (float) (latlong[0][3] - 48) / 100; latInfo[2] = (float) (latlong[0][5] - 48) / 1000; latInfo[3] = (float) (latlong[0][6] - 48) / 10000; latInfo[4] = (float) (latlong[0][7] - 48) / 100000; latInfo[5] = (float) (latlong[0][8] - 48) / 1000000; longInfo[0] = (float) (latlong[1][3] - 48) / 10; longInfo[1] = (float) (latlong[1][4] - 48) / 100; longInfo[2] = (float) (latlong[1][6] - 48) / 1000; longInfo[3] = (float) (latlong[1][7] - 48) / 10000; longInfo[4] = (float) (latlong[1][8] - 48) / 100000; longInfo[5] = (float) (latlong[1][9] - 48) / 1000000; // paromoia diadikasia gia tis gwnies latDigInfo[0] = (float) (latlong[0][0] - 48) * 10; latDigInfo[1] = (float) (latlong[0][1] - 48); longDigInfo[0] = (float) (latlong[1][1] - 48) * 10; longDigInfo[1] = (float) (latlong[1][2] - 48); // stis metavlites aytes apothikevontai oi arithmitikes times pou prokyptoun apo // tin // parapanw diadikasia kai tha symptyxthoun gia na dimiourgisoun tin T parametro float lattitudeMins = 0, longtitudeMins = 0, lattitudeSec = 0, longtitudeSec = 0; float latDigrees = 0, longDigrees = 0; for (int i = 0; i < 6; i++) { lattitudeMins += latInfo[i]; longtitudeMins += longInfo[i]; } for (int j = 0; j < 2; j++) { latDigrees += latDigInfo[j]; longDigrees += longDigInfo[j]; } System.out.print(latDigrees + "latDig"); System.out.print(longDigrees + "longDig"); lattitudeMins *= 100.0; longtitudeMins *= 100.0; longtitudeSec = (longtitudeMins % 1) * 60; lattitudeSec = (lattitudeMins % 1) * 60; System.out.print(lattitudeMins + "latMins"); System.out.print(longtitudeMins + "longMins"); System.out.print(lattitudeSec + "latsec"); System.out.print(longtitudeSec + "longSec"); // apothikefsi ston pinaka TparApparts twn timwn se string morfi TparApparts[0] = String.valueOf(longDigrees); TparApparts[1] = String.valueOf(longtitudeMins); TparApparts[2] = String.valueOf(longtitudeSec); TparApparts[3] = String.valueOf(latDigrees); TparApparts[4] = String.valueOf(lattitudeMins); TparApparts[5] = String.valueOf(lattitudeSec); for (int j = 0; j < 6; j++) { TparApparts[j] = TparApparts[j].substring(0, 2); // apomonwsi twn 2 prwtwn psifeiwn apo kathe // timi } String Tparameter = new String(); Tparameter = (TparApparts[0] + TparApparts[1] + TparApparts[2] + TparApparts[3] + TparApparts[4] + TparApparts[5]); // synenwsi twn string timwn tou pinaka TparApparts se ena string // Tparameter pointer = 0; Tparameters.add(Tparameter);// apothikefsi sto arraylist twn T parametrwn } } catch (Exception e) { System.out.println("couldnt download gps info"); } } modem.close(); System.out.println("please insert the code for downloading gps image"); code = input.nextLine(); modem = createModem(); modem.write(("P" + code + "T=" + Tparameters.get(1) + "T=" + Tparameters.get(30) + "T=" + Tparameters.get(60) + "T=" + Tparameters.get(90) + "\r").getBytes()); for (;;) { try { preData = afterData; afterData = modem.read(); System.out.println(afterData); Image.add(afterData); if ((preData == 255) && (afterData == 217)) { break; } } catch (Exception e) { System.out.println("couldnt download gps image"); } } fileName = ("C:\\Users\\ypatiapd\\Desktop\\δικτυα\\imageGps.jpg"); try { FileOutputStream imageFile = new FileOutputStream(fileName); for (int j = 0; j < Image.size(); j++) { imageFile.write(Image.get(j)); } imageFile.close(); } catch (Exception e) { System.out.println(" couldnt create file"); } System.out.println(" "); System.out.println("image download was successfull"); modem.close(); } void ARQ() { String Acode = " ", Ncode = " "; int nack = 0;// an ginei 1 dilwnei oti egine to prwto error request opote i metavliti // numOfErrors ananewnetai mono otan bei gia prwti fora ston deytero vroxo while // i roi int xor = 0;// apothikefsi tou xor tis symvoloseiras int fcs = 0;// apothikefsi tou fcs float ber = 0;// apothikefsi tou bit error rate int preData = 0, afterData = 0, numOfPackets = 0; int numOfErrors = 0;// arithmos paketwn pou stalthikan me error(xwris tis epanapostoles) int counter = 0;// metritis gia ton pinaka numOfTries int[] numOfTries = new int[10];// kathe thesi tou pinaka dilwnei tis fores epanapostolis pou xreiazontai gia // kathe paketo for (int i = 0; i < 10; i++) { numOfTries[i] = 0; } double startDL = 0, endDL = 0, startTime = 0, endTime = 0, totalTime = 0; Scanner input = new Scanner(System.in); ArrayList<String> DLinfo = new ArrayList<String>(); System.out.println("please insert ack code"); Acode = input.nextLine(); System.out.println("please insert nack code"); Ncode = input.nextLine(); Modem modem; modem = createModem(); startDL = System.nanoTime(); while (endDL < 4 * 60 * 1000) { modem.write(("Q" + Acode + "\r").getBytes()); numOfPackets++; startTime = System.nanoTime(); for (;;) { try { preData = afterData; afterData = modem.read(); System.out.print((char) afterData); if (preData == '<') { while (afterData != '>') { xor = xor ^ (char) afterData; afterData = modem.read();// apothikevoume tin symvoloseira kai kanoume to diadoxiko xor System.out.print((char) afterData); } System.out.print("xor=" + xor); } if ((preData == '>') && (afterData == ' ')) {// apothikevoume to fcs afterData = modem.read(); fcs = Character.getNumericValue((char) afterData) * 100; afterData = modem.read(); fcs = fcs + Character.getNumericValue((char) afterData) * 10; afterData = modem.read(); fcs = fcs + Character.getNumericValue((char) afterData); System.out.print("fcs=" + fcs); } if (((char) preData == 'O') && ((char) afterData == 'P')) { System.out.println(" "); break; } } catch (Exception e) { System.out.println("couldnt download packet"); } } counter = 0; nack = 0; while (xor != fcs) {// an den einai isa mpainoume se allo vroxo while opou zitame epanapostoli mexri // to // xor na isoutai me to fcs kai na epistrepsoume ston arxiko vroxo if (nack == 0) numOfErrors++; nack = 1;// to numOfErrors ananewnetai mono tin prwti fora pou bainoume sto vroxo xor = 0; fcs = 0; modem.write(("R" + Ncode + "\r").getBytes()); counter++;// o counter ayksanetai analoga tis epanapostoles for (;;) { try { preData = afterData; afterData = modem.read(); System.out.print((char) afterData); if (preData == '<') { while (afterData != '>') { xor = xor ^ (char) afterData; afterData = modem.read(); System.out.print((char) afterData); } System.out.print("xor=" + xor); } if ((preData == '>') && (afterData == ' ')) { afterData = modem.read(); fcs = Character.getNumericValue((char) afterData) * 100; afterData = modem.read(); fcs = fcs + Character.getNumericValue((char) afterData) * 10; afterData = modem.read(); fcs = fcs + Character.getNumericValue((char) afterData); System.out.print("fcs=" + fcs + " err"); } if (((char) preData == 'O') && ((char) afterData == 'P')) { System.out.println(" "); break; } } catch (Exception e) { System.out.println("couldnt download packet"); } } } numOfTries[counter] = numOfTries[counter] + 1;// prosthetoume ena sti thesi tou pinaka isi me ton // counter,diladi ton arithmo epanapostolwn endTime = (System.nanoTime() - startTime) / 1000000; totalTime += endTime; // System.out.print("Time to recieve packet was"+ endTime +"milisec"); DLinfo.add(String.valueOf(endTime)); endDL = (System.nanoTime() - startDL) / 1000000; } ber = (float) numOfErrors / (numOfPackets * 59);// bit error rate System.out.print("\n\nNumber of packets recieved was " + numOfPackets + "\n"); System.out.print("Total time of communication : " + (totalTime / 60) / 1000 + " minutes\n"); System.out.print( "Average time to recieve one packet : " + ((totalTime / 60) / numOfPackets) / 1000 + "minutes \n"); System.out.print("The number of errors in " + numOfPackets + " was " + numOfErrors + " \n"); System.out.print("Total time of downloading : " + (endDL / 60) / 1000 + " minutes \n"); System.out.print("Bit error rate : " + ber + "\n"); DLinfo.add("\n\nNumber of packets recieved was " + numOfPackets + "\n"); DLinfo.add("Total time of communication : " + (totalTime / 60) / 1000 + " minutes\n"); DLinfo.add("Average time to recieve one packet : " + ((totalTime) / numOfPackets) / 1000 + "minutes \n"); DLinfo.add("The number of errors in " + numOfPackets + "packets was " + numOfErrors + " \n"); DLinfo.add("Total time of downloading " + (endDL / 60) / 1000 + "minutes \n"); DLinfo.add("Bit error rate : " + ber); DLinfo.add("\n"); for (int i = 0; i < 10; i++) { System.out.print(numOfTries[i] + "packets needed " + i + "requests\n"); DLinfo.add(numOfTries[i] + "packets needed " + i + "requests\n"); } BufferedWriter BW = null; try { File ARQfile = new File("C:\\Users\\ypatiapd\\Desktop\\δικτυα\\ARQ.txt"); BW = new BufferedWriter(new FileWriter(("C:\\Users\\ypatiapd\\Desktop\\δικτυα\\ARQ.txt"), true)); if (!ARQfile.exists()) { ARQfile.createNewFile(); } for (int i = 0; i < DLinfo.size(); i++) { BW.write(String.valueOf(DLinfo.get(i))); BW.newLine(); } BW.newLine(); } catch (Exception e) { System.out.println("couldn't write an ARQ file"); } finally { try { if (BW != null) BW.close(); } catch (Exception e) { System.out.println("couldn't close the BufferedWriter" + e); } } modem.close(); } }
002b4c35bf67576072692f7d19370d8b3fffee0e
[ "Java" ]
1
Java
ypatiapd/Networks
0fd04a9889a0865675dd5ade4c3b6bb102c5961f
46c1448e8dc0a4aa24f33b49b8b4de6326a4d9e1
refs/heads/master
<repo_name>EliasFerguson/MKS21X-LinkedList<file_sep>/LinkedList.java class MyLinkedList { private int size; private Node start,end; public MyLinkedList() { size = 0; } public int size() { return size; } public boolean add(Integer value) { if (size == 0) { start = new Node(value); end = start; } else { end = new Node(value); size++; } return true; } public String toString() { Node current = start; String output = "["; while (current != null) { output += current.toString() + ", "; current = current.next(); } return output + "]"; } private class Node { private int data; private Node next,prev; private Node(int num) { data = num; } private Node next() { return next; } private Node prev() { return prev; } private void setNext(Node other) { next = other; } private void setPrev(Node other) { prev = other; } private Integer getData() { return data; } private Integer setData(Integer i) { Integer old = data; data = i; return old; } public String toString() { return "" + getData(); } } }
473f7e766fda433fe2d446944e8fc3dee2045c1c
[ "Java" ]
1
Java
EliasFerguson/MKS21X-LinkedList
b64fe7a512f68189d5ab7eea8329ced8065bc39d
ed6781395a43a21accca108eb760bde68800d36a
refs/heads/main
<repo_name>cgomezm/APIWorkshop<file_sep>/Controllers/TokenController.cs using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; namespace APIWorkshop.Controllers { [ApiController] [Route("[controller]")] public class TokenController : ControllerBase { private IConfiguration configuration; public TokenController(IConfiguration configuration) { this.configuration = configuration; } [HttpGet] public IActionResult GenerateToken(string username, string password) { // if (username != "admin") // return Unauthorized(); var authClaims = new List<Claim>(){ new Claim(ClaimTypes.Role, username) }; var token = new JwtSecurityToken( issuer: configuration.GetValue<string>("JwtOptions:Issuer"), audience: configuration.GetValue<string>("JwtOptions:Audience"), expires: DateTime.UtcNow.AddMinutes(5), claims: authClaims, signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials( new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue<string>("JwtOptions:SecureKey"))), SecurityAlgorithms.HmacSha256Signature) ); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiresIn = 5 }); } } }<file_sep>/Models/Album.cs using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Models { public class Album { [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] [Required(ErrorMessage = "Album Id is required")] public int Id { get; set; } public string Name { get; set; } public int Year { get; set; } //[ForeignKey("ArtistId")] public int ArtistId { get; set; } public Artist Artist { get; set; } } }<file_sep>/DataAccess/MusicDBContext.cs using Microsoft.EntityFrameworkCore; using Models; namespace APIWorkshop.DataAccess { public class MusicDBContext : DbContext { public MusicDBContext() { } public MusicDBContext(DbContextOptions<MusicDBContext> options) : base(options) { } public DbSet<Album> Albums { get; set; } public DbSet<Artist> Artists { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Artist>() .ToTable("Artist"); modelBuilder.Entity<Album>() .HasOne(p => p.Artist) .WithMany(b => b.Albums) .HasForeignKey(p => p.ArtistId); } } }<file_sep>/Models/HasScopeRequirement.cs using Microsoft.AspNetCore.Authorization; namespace Models { public class HasScopeRequirement : IAuthorizationRequirement { public string Scope { get; set; } public HasScopeRequirement(string scope) { this.Scope = scope; } } }<file_sep>/Startup.cs using System.Text; using APIWorkshop.DataAccess; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using Models; namespace myfirstapi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<MusicDBContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters{ ValidIssuer = "ddsdfs",//Configuration.GetValue<string>("JwtOptions:Issuer"), ValidateIssuer = true, ValidAudience = Configuration.GetValue<string>("JwtOptions:Audience"), ValidateAudience = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue<string>("JwtOptions:SecureKey"))), }; }); // services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) // .AddJwtBearer(options => { // options.Authority = "your auth server url"; // options.Audience = "netcommapi"; // }); // services.AddAuthorization(options =>{ // options.AddPolicy("super", policy => // policy.Requirements.Add(new HasScopeRequirement("super"))); // }); services.AddSingleton<IAuthorizationHandler, HasScopeHandler>(); services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "myfirstapi", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "myfirstapi v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>/Controllers/ArtistController.cs using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Models; using System.Linq; using APIWorkshop.DataAccess; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Authorization; namespace myfirstapi.Controllers { [ApiController] [Route("[controller]")] public class ArtistController : ControllerBase { private MusicDBContext _dBContext { get; set; } public ArtistController(MusicDBContext dBContext) { _dBContext = dBContext; } [HttpGet] public List<Artist> Get() { /* EAGER LOADING */ return _dBContext.Set<Artist>() .Include(artist => artist.Albums) .ToList(); /* EXPLICIT LOADING */ // var all = _dBContext.Artists; // var a = all // .Single(b => b.Id == 4); // _dBContext.Entry(a) // .Collection(b => b.Albums) // .Load(); // return all.ToList(); } [HttpPost] [Authorize(Policy = "super")] public List<Artist> Post(Artist artist) { var artists = new List<Artist>(); if (ModelState.IsValid) { _dBContext.Set<Artist>().Add(artist); _dBContext.SaveChanges(); artists = _dBContext.Set<Artist>().ToList(); } else { artists = new List<Artist>(); } return artists; } [HttpDelete] public List<Artist> Delete(int id) { var artists = new List<Artist>(); ; var artist = _dBContext.Find<Artist>(id); _dBContext.Set<Artist>().Remove(artist); _dBContext.SaveChanges(); artists = _dBContext.Set<Artist>().ToList(); return artists; } [HttpPut] public List<Artist> Put(Artist artist) { var artists = new List<Artist>(); _dBContext.Set<Artist>().Update(artist); foreach (var item in artist.Albums) { if(_dBContext.Set<Album>().Any(a => a.Id == item.Id)){ _dBContext.Entry(item).State = EntityState.Modified; // added row } else{ _dBContext.Entry(item).State = EntityState.Added; // added row _dBContext.Set<Album>().Add(item); } } _dBContext.SaveChanges(); artists = _dBContext.Set<Artist>().ToList(); return artists; } } }
37fabe30198b9695663ca49353795bf8644d30dd
[ "C#" ]
6
C#
cgomezm/APIWorkshop
0f1c96fdf039cbe659e030946b6ff5bca6e130a2
30b63a177807a45305d86ecb51bd9cf1956fa936
refs/heads/master
<repo_name>darthyody/generator-yody<file_sep>/README.md # Yeoman Generator - yody ## Installation 1. Install Yeoman 2. Copy this repo 3. Run: 'yo yody' to initialize. ## Features * Jade * Sass * Bootstrap * jQuery * grunt <file_sep>/generators/app/index.js var generators = require('yeoman-generator'); /* static functions * all library code should be put here. */ var YodyGenerator = generators.Base.extend({ userInput: function() { var done = this.async(); var prompts = [{ type: 'input', name: 'name', message: 'Input the name of your webapp', default: this.appname },{ type: 'checkbox', name: 'modules', message: 'Select which libraries you want included:', choices: [ "Sass", "Jade", "Boostrap", "jQuery" ] }]; this.prompt(prompts,function(answers) { this.log(answers.modules); done(); }.bind(this)); }, installBootstrap: function() { } }); /* Steps of the Generator. * all functions here should be called from above. */ module.exports = YodyGenerator.extend({ initializing: function () { }, prompting: function() { this.userInput(); }, configuring: function() { }, default: function() {}, writing: function() {}, conflicts: function() {}, install: function() {}, end: function() {} });
a40e6705cebd2c35077a1450600ccebc545b98c4
[ "Markdown", "JavaScript" ]
2
Markdown
darthyody/generator-yody
d394c7a704d1e54b4db113333096f9494f4cd994
a5bad7726b52a8cbe7a932a2cad9f92afd5be3bf
refs/heads/master
<repo_name>SSKJ-Android/SSKJ-Java<file_sep>/app/src/main/java/com/sskj/hub/utils/PopUtil.java package com.sskj.hub.utils; import android.Manifest; import android.app.Activity; import android.graphics.drawable.ColorDrawable; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; import com.luck.picture.lib.PictureSelector; import com.luck.picture.lib.config.PictureConfig; import com.luck.picture.lib.config.PictureMimeType; import com.sskj.hub.R; import com.tbruyelle.rxpermissions2.RxPermissions; /** * Created by lv on 18-6-8. */ public class PopUtil { private Activity context; private View mView; private PopupWindow popupWindow; public PopUtil(Activity context) { this.context = context; } public void showPhoto() { if (popupWindow == null) { mView = LayoutInflater.from(context).inflate(R.layout.pop_xinxibianjirenzheng, null); View takephoto = mView.findViewById(R.id.take_photo); View getphoto = mView.findViewById(R.id.get_photo); View cancel = mView.findViewById(R.id.cancel); ClickUtil.click(takephoto, () -> { new RxPermissions(context) .request(Manifest.permission.CAMERA) .subscribe(isGrant -> { if (isGrant) { popupWindow.dismiss(); PictureSelector.create(context).openCamera(PictureMimeType.ofImage()) .forResult(PictureConfig.CHOOSE_REQUEST); } else { PermissionTipUtil.tip(context, "相机"); } }); }); ClickUtil.click(getphoto, () -> { new RxPermissions(context) .request(Manifest.permission.WRITE_EXTERNAL_STORAGE) .subscribe(isGrant -> { if (isGrant) { popupWindow.dismiss(); PictureSelector.create(context) .openGallery(PictureMimeType.ofImage()) .compress(true) .selectionMode(PictureConfig.SINGLE) .minimumCompressSize(100) .forResult(PictureConfig.CHOOSE_REQUEST); } else { PermissionTipUtil.tip(context, "存储"); } }); }); ClickUtil.click(cancel, () -> popupWindow.dismiss()); popupWindow = new PopupWindow(mView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); popupWindow.setFocusable(false); popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000)); } popupWindow.showAtLocation(mView, Gravity.BOTTOM, 0, 0); } } <file_sep>/app/src/main/java/com/sskj/hub/mvchelper/Rx2DataSource.java package com.sskj.hub.mvchelper; import com.shizhefei.mvc.IAsyncDataSource; import com.shizhefei.mvc.RequestHandle; import com.shizhefei.mvc.ResponseSender; import io.reactivex.Flowable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.DisposableSubscriber; /** * Created by LuckyJayce on 2016/7/21. */ public abstract class Rx2DataSource<DATA> implements IAsyncDataSource<DATA> { @Override public final RequestHandle refresh(final ResponseSender<DATA> sender) throws Exception { return load(sender, refreshRX()); } @Override public final RequestHandle loadMore(ResponseSender<DATA> sender) throws Exception { return load(sender, loadMoreRX()); } protected abstract Flowable<DATA> refreshRX() throws Exception; protected abstract Flowable<DATA> loadMoreRX() throws Exception; private RequestHandle load(final ResponseSender<DATA> sender, final Flowable<DATA> flowable) { DisposableSubscriber<DATA> subscriber = new DisposableSubscriber<DATA>() { @Override public void onNext(DATA data) { sender.sendData(data); } @Override public void onError(Throwable e) { sender.sendError(new Exception(e)); } @Override public void onComplete() { } }; flowable.subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber); return new RequestHandle() { @Override public void cancle() { if (!subscriber.isDisposed()) { subscriber.dispose(); } } @Override public boolean isRunning() { return false; } }; } } <file_sep>/app/src/main/java/com/sskj/hub/utils/ClickUtil.java package com.sskj.hub.utils; import android.view.View; import com.jakewharton.rxbinding2.view.RxView; import java.util.concurrent.TimeUnit; /** * @author吕志豪 . * @date 17-12-12 上午10:10. * Github :https://github.com/lvzhihao100 * E-Mail:<EMAIL> * 简书 :http://www.jianshu.com/u/6e525b929aac * 设置点击事件,防重复点击,可设置时间 */ public class ClickUtil { public static void click(View view, Click click) { RxView.clicks(view) .throttleFirst(1, TimeUnit.SECONDS) .subscribe(aVoid -> click.click()); } public static void click(long time,View view, Click click) { RxView.clicks(view) .throttleFirst(time, TimeUnit.MILLISECONDS) .subscribe(aVoid -> click.click()); } public interface Click { void click(); } } <file_sep>/app/src/main/java/com/sskj/hub/rxbus2/NetSubScriber.java package com.sskj.hub.rxbus2; import io.reactivex.subscribers.DisposableSubscriber; /** * Created by Administrator on 2018/4/20. */ public abstract class NetSubScriber<T> extends DisposableSubscriber<T> { @Override public void onNext(T t) { onSuccess(t); } @Override public void onError(Throwable t) { onFailure(t); t.printStackTrace(); } @Override public void onComplete() { } public abstract void onSuccess(T t); public void onFailure(Throwable t){}; } <file_sep>/provider/src/main/java/com/sskj/provider/http/observer/HttpRxCallback.java package com.sskj.provider.http.observer; import android.text.TextUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import com.sskj.provider.http.entity.ResponseEnrtity; import com.sskj.provider.http.exception.ApiException; import com.sskj.provider.http.exception.ExceptionEngine; import com.sskj.provider.http.helper.ParseHelper; import com.sskj.provider.http.retrofit.HttpRequestListener; import com.sskj.provider.http.retrofit.RxActionManagerImpl; import com.sskj.provider.http.util.DateDeserializer; import com.sskj.provider.http.util.DateSerializer; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.text.DateFormat; import io.reactivex.Observer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; /** * 适用Retrofit网络请求Observer(监听者) * 备注: * 1.重写onSubscribe,添加请求标识 * 2.重写onError,封装错误/异常处理,移除请求 * 3.重写onNext,移除请求 * 4.重写cancel,取消请求 * * @author ZhongDaFeng */ public abstract class HttpRxCallback<T> implements Observer<ResponseEnrtity>, HttpRequestListener { private String mTag;//请求标识 private ParseHelper parseHelper;//数据解析 public HttpRxCallback() { } public HttpRxCallback(String tag) { this.mTag = tag; } @Override public void onError(Throwable e) { RxActionManagerImpl.getInstance().remove(mTag); if (e instanceof ApiException) { ApiException exception = (ApiException) e; int code = exception.getCode(); String msg = exception.getMsg(); if (code == 1001) { //系统公告(示例) //此处在UI主线程 } else if (code == 1002) {//token失效 //处理对应的逻辑 } else {//其他错误回调 onError(code, msg); } } else { onError(ExceptionEngine.UN_KNOWN_ERROR, "未知错误"); } } @Override public void onComplete() { } @Override public void onNext(ResponseEnrtity responseEnrtity) { if (responseEnrtity != null) { T data = null; try { GsonBuilder gb = new GsonBuilder(); gb.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG); gb.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG); Gson gson = gb.create(); Type genericSuperclass = getClass().getGenericSuperclass(); Type type = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0]; data = gson.fromJson((String) responseEnrtity.getBody(), type); onSuccess(data, responseEnrtity.getMsg()); } catch (JsonSyntaxException e) { e.printStackTrace(); onError(e); } } } @Override public void onSubscribe(@NonNull Disposable d) { if (!TextUtils.isEmpty(mTag)) { RxActionManagerImpl.getInstance().add(mTag, d); } } @Override public void cancel() { if (!TextUtils.isEmpty(mTag)) { RxActionManagerImpl.getInstance().cancel(mTag); } } /** * 是否已经处理 * * @author ZhongDaFeng */ public boolean isDisposed() { if (TextUtils.isEmpty(mTag)) { return true; } return RxActionManagerImpl.getInstance().isDisposed(mTag); } /** * 设置解析回调 * * @param parseHelper */ public void setParseHelper(ParseHelper parseHelper) { this.parseHelper = parseHelper; } /** * 成功回调 * * @param data */ public void onSuccess(T data, String message) { onSuccess(data); } public void onSuccess(T data) { } /** * 失败回调 * * @param code * @param desc */ public abstract void onError(int code, String desc); } <file_sep>/app/src/main/java/com/sskj/hub/rxbus2/RxBus.java package com.sskj.hub.rxbus2; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.Subject; /**改造版本,适用,多code,单方法 * Created by lvzhihao on 17-7-25. */ public class RxBus { public static final String LOG_BUS = "RXBUS_LOG"; private static volatile RxBus defaultInstance; private Map<Class, List<Disposable>> subscriptionsByEventType = new HashMap(); private Map<Object, List<Class>> eventTypesBySubscriber = new HashMap(); private Map<Class, List<SubscriberMethod>> subscriberMethodByEventType = new HashMap(); private final Subject<Object> bus = PublishSubject.create().toSerialized(); private RxBus() { } public static RxBus getDefault() { RxBus rxBus = defaultInstance; if (defaultInstance == null) { Class var1 = RxBus.class; synchronized (RxBus.class) { rxBus = defaultInstance; if (defaultInstance == null) { rxBus = new RxBus(); defaultInstance = rxBus; } } } return rxBus; } private <T> Flowable<T> toObservable(Class<T> eventType) { return this.bus.toFlowable(BackpressureStrategy.BUFFER).ofType(eventType); } private <T> Flowable<T> toObservable(final int code, final Class<T> eventType) { return this.bus.toFlowable(BackpressureStrategy.BUFFER) .ofType(Message.class) .filter(o -> o.getCode() == code && eventType.isInstance(o.getObject())) .map(Message::getObject) .cast(eventType); } public void register(Object subscriber) { Class subClass = subscriber.getClass(); Method[] methods = subClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { Method method = methods[i]; if (method.isAnnotationPresent(Subscribe.class)) { Class[] parameterType = method.getParameterTypes(); Class eventType; Subscribe sub; int[] codes; int codeOrigin; ThreadMode threadMode; SubscriberMethod subscriberMethod; if (parameterType != null && parameterType.length == 1) { eventType = parameterType[0]; this.addEventTypeToMap(subscriber, eventType); sub = method.getAnnotation(Subscribe.class); codes = sub.codes(); codeOrigin = sub.code(); threadMode = sub.threadMode(); if (codeOrigin != -1) { subscriberMethod = new SubscriberMethod(subscriber, method, eventType, codeOrigin, threadMode); this.addSubscriberToMap(eventType, subscriberMethod); this.addSubscriber(subscriberMethod); } else { for (int code : codes) { subscriberMethod = new SubscriberMethod(subscriber, method, eventType, code, threadMode); this.addSubscriberToMap(eventType, subscriberMethod); this.addSubscriber(subscriberMethod); } } } else if (parameterType == null || parameterType.length == 0) { eventType = BusData.class; this.addEventTypeToMap(subscriber, eventType); sub = method.getAnnotation(Subscribe.class); codes = sub.codes(); codeOrigin = sub.code(); threadMode = sub.threadMode(); if (codeOrigin != -1) { subscriberMethod = new SubscriberMethod(subscriber, method, eventType, codeOrigin, threadMode); this.addSubscriberToMap(eventType, subscriberMethod); this.addSubscriber(subscriberMethod); } else { for (int code : codes) { subscriberMethod = new SubscriberMethod(subscriber, method, eventType, code, threadMode); this.addSubscriberToMap(eventType, subscriberMethod); this.addSubscriber(subscriberMethod); } } } } } } private void addEventTypeToMap(Object subscriber, Class eventType) { Object eventTypes = this.eventTypesBySubscriber.get(subscriber); if (eventTypes == null) { eventTypes = new ArrayList(); this.eventTypesBySubscriber.put(subscriber, (List<Class>) eventTypes); } if (!((List) eventTypes).contains(eventType)) { ((List) eventTypes).add(eventType); } } private void addSubscriberToMap(Class eventType, SubscriberMethod subscriberMethod) { Object subscriberMethods = this.subscriberMethodByEventType.get(eventType); if (subscriberMethods == null) { subscriberMethods = new ArrayList(); this.subscriberMethodByEventType.put(eventType, (List<SubscriberMethod>) subscriberMethods); } if (!((List) subscriberMethods).contains(subscriberMethod)) { ((List) subscriberMethods).add(subscriberMethod); } } private void addSubscriptionToMap(Class eventType, Disposable disposable) { Object disposables = this.subscriptionsByEventType.get(eventType); if (disposables == null) { disposables = new ArrayList(); this.subscriptionsByEventType.put(eventType, (List<Disposable>) disposables); } if (!((List) disposables).contains(disposable)) { ((List) disposables).add(disposable); } } private void addSubscriber(final SubscriberMethod subscriberMethod) { Flowable flowable; if (subscriberMethod.code == -1) { flowable = this.toObservable(subscriberMethod.eventType); } else { flowable = this.toObservable(subscriberMethod.code, subscriberMethod.eventType); } Disposable subscription = this.postToObservable(flowable, subscriberMethod).subscribe( o -> RxBus.this.callEvent(subscriberMethod, o)); this.addSubscriptionToMap(subscriberMethod.subscriber.getClass(), subscription); } private Flowable postToObservable(Flowable observable, SubscriberMethod subscriberMethod) { Scheduler scheduler; switch (subscriberMethod.threadMode.ordinal()) { case 1: scheduler = AndroidSchedulers.mainThread(); break; case 2: scheduler = Schedulers.newThread(); break; case 3: scheduler = Schedulers.trampoline(); break; default: throw new IllegalStateException("Unknown thread mode: " + subscriberMethod.threadMode); } return observable.observeOn(scheduler); } private void callEvent(SubscriberMethod method, Object object) { method.invoke(object); } public synchronized boolean isRegistered(Object subscriber) { return this.eventTypesBySubscriber.containsKey(subscriber); } public void unregister(Object subscriber) { List subscribedTypes = this.eventTypesBySubscriber.get(subscriber); if (subscribedTypes != null) { Iterator var3 = subscribedTypes.iterator(); while (var3.hasNext()) { Class eventType = (Class) var3.next(); this.unSubscribeByEventType(subscriber.getClass()); this.unSubscribeMethodByEventType(subscriber, eventType); } this.eventTypesBySubscriber.remove(subscriber); } } private void unSubscribeByEventType(Class eventType) { List disposables = this.subscriptionsByEventType.get(eventType); if (disposables != null) { Iterator iterator = disposables.iterator(); while (iterator.hasNext()) { Disposable disposable = (Disposable) iterator.next(); if (disposable != null && !disposable.isDisposed()) { disposable.dispose(); iterator.remove(); } } } } private void unSubscribeMethodByEventType(Object subscriber, Class eventType) { List subscriberMethods = this.subscriberMethodByEventType.get(eventType); if (subscriberMethods != null) { Iterator iterator = subscriberMethods.iterator(); while (iterator.hasNext()) { SubscriberMethod subscriberMethod = (SubscriberMethod) iterator.next(); if (subscriberMethod.subscriber.equals(subscriber)) { iterator.remove(); } } } } public void send(int code, Object o) { this.bus.onNext(new Message(code, o)); } public void post(Object o) { this.bus.onNext(o); } public void send(int code) { this.bus.onNext(new Message(code, new BusData())); } private class Message { private int code; private Object object; private Message(int code, Object o) { this.code = code; this.object = o; } private int getCode() { return this.code; } public void setCode(int code) { this.code = code; } private Object getObject() { return this.object; } public void setObject(Object object) { this.object = object; } } } <file_sep>/app/src/main/java/com/sskj/hub/model/main/entity/SelfSelectEntity.java package com.sskj.hub.model.main.entity; /** * Created by Administrator on 2018/1/12. */ public class SelfSelectEntity { private Object id; private String code; private String type; private String name; private String engName; private String price; private String volume; private Object nowCount; private String openPrice; private String closePrice; private String high; private String low; private String change; private String changeRate; private Object date; private String mggs; private String jggd; private int goingLongStatus; private int shortSellingStatus; private Object createTime; private Object status; private Object topChoice; private Object timestamp; public Object getId() { return id; } public void setId(Object id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEngName() { return engName; } public void setEngName(String engName) { this.engName = engName; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getVolume() { return volume; } public void setVolume(String volume) { this.volume = volume; } public Object getNowCount() { return nowCount; } public void setNowCount(Object nowCount) { this.nowCount = nowCount; } public String getOpenPrice() { return openPrice; } public void setOpenPrice(String openPrice) { this.openPrice = openPrice; } public String getClosePrice() { return closePrice; } public void setClosePrice(String closePrice) { this.closePrice = closePrice; } public String getHigh() { return high; } public void setHigh(String high) { this.high = high; } public String getLow() { return low; } public void setLow(String low) { this.low = low; } public String getChange() { return change; } public void setChange(String change) { this.change = change; } public String getChangeRate() { return changeRate; } public void setChangeRate(String changeRate) { this.changeRate = changeRate; } public Object getDate() { return date; } public void setDate(Object date) { this.date = date; } public String getMggs() { return mggs; } public void setMggs(String mggs) { this.mggs = mggs; } public String getJggd() { return jggd; } public void setJggd(String jggd) { this.jggd = jggd; } public int getGoingLongStatus() { return goingLongStatus; } public void setGoingLongStatus(int goingLongStatus) { this.goingLongStatus = goingLongStatus; } public int getShortSellingStatus() { return shortSellingStatus; } public void setShortSellingStatus(int shortSellingStatus) { this.shortSellingStatus = shortSellingStatus; } public Object getCreateTime() { return createTime; } public void setCreateTime(Object createTime) { this.createTime = createTime; } public Object getStatus() { return status; } public void setStatus(Object status) { this.status = status; } public Object getTopChoice() { return topChoice; } public void setTopChoice(Object topChoice) { this.topChoice = topChoice; } public Object getTimestamp() { return timestamp; } public void setTimestamp(Object timestamp) { this.timestamp = timestamp; } } <file_sep>/provider/src/main/java/com/sskj/provider/http/entity/ResponseEnrtity.java package com.sskj.provider.http.entity; /** * ProjectName: * DESC: 返回实体类,包含data,和msg * Created by lez on 2018/6/8 8:46 * updateName: * updateTime: * updateDesc: */ public class ResponseEnrtity { private Object body; @Override public String toString() { return "ResponseEnrtity{" + "body=" + body + ", msg='" + msg + '\'' + '}'; } public ResponseEnrtity() { } public ResponseEnrtity(Object body, String msg) { this.body = body; this.msg = msg; } public Object getBody() { return body; } public void setBody(Object body) { this.body = body; } public String getMsg() { return msg == null ? "" : msg; } public void setMsg(String msg) { this.msg = msg; } private String msg; } <file_sep>/app/src/main/java/com/sskj/hub/model/main/entity/SingleStock.java package com.sskj.hub.model.main.entity; /** * <pre> * author : wk_math * e-mail : <EMAIL> * time : 2018/01/02 * desc : 单个商品信息 * version: 1.0 * </pre> */ public class SingleStock { public SingleStock() { } @Override public String toString() { return "SingleStock{" + "id='" + id + '\'' + ", code='" + code + '\'' + ", type='" + type + '\'' + ", name='" + name + '\'' + ", engName='" + engName + '\'' + ", price='" + price + '\'' + ", volume='" + volume + '\'' + ", nowCount='" + nowCount + '\'' + ", openPrice='" + openPrice + '\'' + ", closePrice='" + closePrice + '\'' + ", prevClose='" + prevClose + '\'' + ", high='" + high + '\'' + ", low='" + low + '\'' + ", change='" + change + '\'' + ", changeRate='" + changeRate + '\'' + ", date='" + date + '\'' + ", mggs='" + mggs + '\'' + ", jggd='" + jggd + '\'' + ", goingLongStatus=" + goingLongStatus + ", shortSellingStatus=" + shortSellingStatus + ", createTime='" + createTime + '\'' + ", status='" + status + '\'' + ", dealFee='" + dealFee + '\'' + ", topChoice='" + topChoice + '\'' + ", timestamp='" + timestamp + '\'' + ", dealMoney='" + dealMoney + '\'' + ", spotSpread='" + spotSpread + '\'' + ", stopProfit='" + stopProfit + '\'' + ", stopLoss='" + stopLoss + '\'' + ", cashDeposit='" + cashDeposit + '\'' + ", floatMoney='" + floatMoney + '\'' + ", contractMax=" + contractMax + ", contractKind='" + contractKind + '\'' + ", closeSpotKind='" + closeSpotKind + '\'' + '}'; } private String id; public SingleStock(String id, String code, String type, String name, String engName, String price, String volume, String nowCount, String openPrice, String closePrice, String prevClose, String high, String low, String change, String changeRate, String date, String mggs, String jggd, int goingLongStatus, int shortSellingStatus, String createTime, String status, String dealFee, String topChoice, String timestamp, String dealMoney, String spotSpread, String stopProfit, String stopLoss, String cashDeposit, String floatMoney, int contractMax, String contractKind, String closeSpotKind) { this.id = id; this.code = code; this.type = type; this.name = name; this.engName = engName; this.price = price; this.volume = volume; this.nowCount = nowCount; this.openPrice = openPrice; this.closePrice = closePrice; this.prevClose = prevClose; this.high = high; this.low = low; this.change = change; this.changeRate = changeRate; this.date = date; this.mggs = mggs; this.jggd = jggd; this.goingLongStatus = goingLongStatus; this.shortSellingStatus = shortSellingStatus; this.createTime = createTime; this.status = status; this.dealFee = dealFee; this.topChoice = topChoice; this.timestamp = timestamp; this.dealMoney = dealMoney; this.spotSpread = spotSpread; this.stopProfit = stopProfit; this.stopLoss = stopLoss; this.cashDeposit = cashDeposit; this.floatMoney = floatMoney; this.contractMax = contractMax; this.contractKind = contractKind; this.closeSpotKind = closeSpotKind; } public String getId() { return id == null ? "" : id; } public void setId(String id) { this.id = id; } public String getCode() { return code == null ? "" : code; } public void setCode(String code) { this.code = code; } public String getType() { return type == null ? "" : type; } public void setType(String type) { this.type = type; } public String getName() { return name == null ? "" : name; } public void setName(String name) { this.name = name; } public String getEngName() { return engName == null ? "" : engName; } public void setEngName(String engName) { this.engName = engName; } public String getPrice() { return price == null ? "" : price; } public void setPrice(String price) { this.price = price; } public String getVolume() { return volume == null ? "" : volume; } public void setVolume(String volume) { this.volume = volume; } public String getNowCount() { return nowCount == null ? "" : nowCount; } public void setNowCount(String nowCount) { this.nowCount = nowCount; } public String getOpenPrice() { return openPrice == null ? "" : openPrice; } public void setOpenPrice(String openPrice) { this.openPrice = openPrice; } public String getClosePrice() { return closePrice == null ? "" : closePrice; } public void setClosePrice(String closePrice) { this.closePrice = closePrice; } public String getPrevClose() { return prevClose == null ? "" : prevClose; } public void setPrevClose(String prevClose) { this.prevClose = prevClose; } public String getHigh() { return high == null ? "" : high; } public void setHigh(String high) { this.high = high; } public String getLow() { return low == null ? "" : low; } public void setLow(String low) { this.low = low; } public String getChange() { return change == null ? "" : change; } public void setChange(String change) { this.change = change; } public String getChangeRate() { return changeRate == null ? "" : changeRate; } public void setChangeRate(String changeRate) { this.changeRate = changeRate; } public String getDate() { return date == null ? "" : date; } public void setDate(String date) { this.date = date; } public String getMggs() { return mggs == null ? "" : mggs; } public void setMggs(String mggs) { this.mggs = mggs; } public String getJggd() { return jggd == null ? "" : jggd; } public void setJggd(String jggd) { this.jggd = jggd; } public int getGoingLongStatus() { return goingLongStatus; } public void setGoingLongStatus(int goingLongStatus) { this.goingLongStatus = goingLongStatus; } public int getShortSellingStatus() { return shortSellingStatus; } public void setShortSellingStatus(int shortSellingStatus) { this.shortSellingStatus = shortSellingStatus; } public String getCreateTime() { return createTime == null ? "" : createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getStatus() { return status == null ? "" : status; } public void setStatus(String status) { this.status = status; } public String getDealFee() { return dealFee == null ? "" : dealFee; } public void setDealFee(String dealFee) { this.dealFee = dealFee; } public String getTopChoice() { return topChoice == null ? "" : topChoice; } public void setTopChoice(String topChoice) { this.topChoice = topChoice; } public String getTimestamp() { return timestamp == null ? "" : timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getDealMoney() { return dealMoney == null ? "" : dealMoney; } public void setDealMoney(String dealMoney) { this.dealMoney = dealMoney; } public String getSpotSpread() { return spotSpread == null ? "" : spotSpread; } public void setSpotSpread(String spotSpread) { this.spotSpread = spotSpread; } public String getStopProfit() { return stopProfit == null ? "" : stopProfit; } public void setStopProfit(String stopProfit) { this.stopProfit = stopProfit; } public String getStopLoss() { return stopLoss == null ? "" : stopLoss; } public void setStopLoss(String stopLoss) { this.stopLoss = stopLoss; } public String getCashDeposit() { return cashDeposit == null ? "" : cashDeposit; } public void setCashDeposit(String cashDeposit) { this.cashDeposit = cashDeposit; } public String getFloatMoney() { return floatMoney == null ? "" : floatMoney; } public void setFloatMoney(String floatMoney) { this.floatMoney = floatMoney; } public int getContractMax() { return contractMax; } public void setContractMax(int contractMax) { this.contractMax = contractMax; } public String getContractKind() { return contractKind == null ? "" : contractKind; } public void setContractKind(String contractKind) { this.contractKind = contractKind; } public String getCloseSpotKind() { return closeSpotKind == null ? "" : closeSpotKind; } public void setCloseSpotKind(String closeSpotKind) { this.closeSpotKind = closeSpotKind; } private String code; private String type; private String name; private String engName; private String price; private String volume; private String nowCount; private String openPrice; private String closePrice; private String prevClose; private String high; private String low; private String change; private String changeRate; private String date; private String mggs; private String jggd; private int goingLongStatus; private int shortSellingStatus; private String createTime; private String status; private String dealFee; private String topChoice; private String timestamp; private String dealMoney; private String spotSpread; private String stopProfit; private String stopLoss; private String cashDeposit; private String floatMoney; private int contractMax; private String contractKind; private String closeSpotKind; } <file_sep>/app/src/main/java/com/sskj/hub/model/main/entity/Commodity.java package com.sskj.hub.model.main.entity; import android.os.Parcel; import android.os.Parcelable; /** * ProjectName:HUB * DESC: HUB实体类 * Created by lez on 2018/5/29 16:53 * updateName: * updateTime: * updateDesc: */ public class Commodity implements Parcelable{ private String code; private String name; private String date; private String time; private String dateTime; private String price; private String change; private String ampRate; private String changeRate; private String period; private String openPrice; private String closePrice; private String high; private String low; private String volume; public String getDateTime() { return dateTime == null ? "" : dateTime; } public void setDateTime(String dateTime) { this.dateTime = dateTime; } public String getAmpRate() { return ampRate == null ? "" : ampRate; } public void setAmpRate(String ampRate) { this.ampRate = ampRate; } private String amount; private String timestamp; private int isDeal;//是否正在交易 private boolean isLight=false; public String getPeriod() { return period == null ? "" : period; } public void setPeriod(String period) { this.period = period; } public String getAmount() { return amount == null ? "" : amount; } public void setAmount(String amount) { this.amount = amount; } public String getTimestamp() { return timestamp == null ? "" : timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public Commodity() { } public int getIsDeal() { return isDeal; } public void setIsDeal(int isDeal) { this.isDeal = isDeal; } public boolean isLight() { return isLight; } public void setLight(boolean light) { isLight = light; } public String getName() { return name; } public String getCode() { return code; } public String getOpenPrice() { return openPrice; } public String getClosePrice() { return closePrice; } public String getHigh() { return high; } public String getLow() { return low; } public String getVolume() { return volume; } public String getDate() { return date; } public String getChange() { return change; } public String getChangeRate() { return changeRate; } public String getPrice() { return price; } public String getTime() { return time; } public void setName(String name) { this.name = name; } public void setCode(String code) { this.code = code; } public void setOpenPrice(String openPrice) { this.openPrice = openPrice; } public void setClosePrice(String closePrice) { this.closePrice = closePrice; } public void setHigh(String high) { this.high = high; } public void setLow(String low) { this.low = low; } public void setVolume(String volume) { this.volume = volume; } public void setDate(String date) { this.date = date; } public void setChange(String change) { this.change = change; } public void setChangeRate(String changeRate) { this.changeRate = changeRate; } public void setPrice(String price) { this.price = price; } public void setTime(String time) { this.time = time; } @Override public int describeContents() { return 0; } @Override public String toString() { return "Commodity{" + "code='" + code + '\'' + ", name='" + name + '\'' + ", date='" + date + '\'' + ", time='" + time + '\'' + ", dateTime='" + dateTime + '\'' + ", price='" + price + '\'' + ", change='" + change + '\'' + ", ampRate='" + ampRate + '\'' + ", changeRate='" + changeRate + '\'' + ", period='" + period + '\'' + ", openPrice='" + openPrice + '\'' + ", closePrice='" + closePrice + '\'' + ", high='" + high + '\'' + ", low='" + low + '\'' + ", volume='" + volume + '\'' + ", amount='" + amount + '\'' + ", timestamp='" + timestamp + '\'' + ", isDeal=" + isDeal + ", isLight=" + isLight + '}'; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.name); dest.writeString(this.code); dest.writeString(this.openPrice); dest.writeString(this.closePrice); dest.writeString(this.high); dest.writeString(this.low); dest.writeString(this.change); dest.writeString(this.changeRate); dest.writeString(this.price); dest.writeString(this.volume); dest.writeString(this.date); dest.writeString(this.time); dest.writeInt(this.isDeal); dest.writeString(this.amount); dest.writeString(this.period); dest.writeString(this.timestamp); } protected Commodity(Parcel in) { this.name = in.readString(); this.code = in.readString(); this.openPrice = in.readString(); this.closePrice = in.readString(); this.high = in.readString(); this.low = in.readString(); this.change = in.readString(); this.changeRate = in.readString(); this.price = in.readString(); this.volume = in.readString(); this.date = in.readString(); this.time = in.readString(); this.isDeal = in.readInt(); this.amount = in.readString(); this.period = in.readString(); this.timestamp = in.readString(); } public static final Creator<Commodity> CREATOR = new Creator<Commodity>() { @Override public Commodity createFromParcel(Parcel in) { return new Commodity(in); } @Override public Commodity[] newArray(int size) { return new Commodity[size]; } }; } <file_sep>/app/src/main/java/com/sskj/hub/model/main/presenter/MinePresenter.java package com.sskj.hub.model.main.presenter; import com.sskj.hub.base.BasePresenter; import com.sskj.hub.model.main.fragment.MineFragment; public class MinePresenter extends BasePresenter<MineFragment, MineFragment> { public MinePresenter(MineFragment baseFragment, MineFragment fragment) { super(baseFragment, fragment); } } <file_sep>/app/src/main/java/com/sskj/hub/model/main/entity/UpdateBean.java package com.sskj.hub.model.main.entity; /** * ProjectName: * DESC: 版本升级 * Created by lez on 2018/5/29 16:55 * updateName: * updateTime: * updateDesc: */ public class UpdateBean { private String id; private String title; private String appVersion; private String versionName; private String createTime; private String upState; private String downUrl; private String appSys; private String details; public String getVersionName() { return versionName == null ? "" : versionName; } public void setVersionName(String versionName) { this.versionName = versionName; } public UpdateBean() { } public UpdateBean(String id, String title, String appVersion, String versionName, String createTime, String upState, String downUrl, String appSys, String details) { this.id = id; this.title = title; this.appVersion = appVersion; this.versionName = versionName; this.createTime = createTime; this.upState = upState; this.downUrl = downUrl; this.appSys = appSys; this.details = details; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAppVersion() { return appVersion; } public void setAppVersion(String appVersion) { this.appVersion = appVersion; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpState() { return upState; } public void setUpState(String upState) { this.upState = upState; } public String getDownUrl() { return downUrl; } public void setDownUrl(String downUrl) { this.downUrl = downUrl; } public String getAppSys() { return appSys; } public void setAppSys(String appSys) { this.appSys = appSys; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } } <file_sep>/provider/src/main/java/com/sskj/provider/widget/RLoadingDialog.java package com.sskj.provider.widget; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.widget.TextView; import com.sskj.provider.R; import com.wang.avi.AVLoadingIndicatorView; /** * 自定义Loading弹窗 * * @author ZhongDafeng */ public class RLoadingDialog extends Dialog { AVLoadingIndicatorView loadingView; TextView loadingText; private Builder mBuilder; public RLoadingDialog(Builder builder) { super(builder.mContext, R.style.custom_dialog); mBuilder = builder; setCancelable(mBuilder.mCancelable); setCanceledOnTouchOutside(mBuilder.mCanceledOnTouchOutside); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog); initView(); } private void initView() { loadingView = findViewById(R.id.loadingView); loadingText = findViewById(R.id.loadingText); setOnDismissListener(dialog -> { dialog.dismiss(); loadingView.smoothToHide(); }); } @Override public void show() { super.show(); loadingView.smoothToShow(); loadingText.setText(mBuilder.mLoadText); } public Builder getBuilder() { return mBuilder; } public static class Builder { private Context mContext; private int mDelay = 80; private CharSequence mLoadText; private boolean mCancelable = true; private boolean mCanceledOnTouchOutside = true; public Builder(Context context) { mContext = context; } public Builder delay(int delay) { mDelay = delay; return this; } public Builder loadText(CharSequence loadText) { mLoadText = loadText; return this; } public Builder loadText(int resId) { mLoadText = mContext.getString(resId); return this; } public Builder cancelable(boolean cancelable) { mCancelable = cancelable; mCanceledOnTouchOutside = cancelable; return this; } public Builder canceledOnTouchOutside(boolean canceledOnTouchOutside) { mCanceledOnTouchOutside = canceledOnTouchOutside; return this; } public RLoadingDialog build() { return new RLoadingDialog(this); } public RLoadingDialog show() { RLoadingDialog dialog = build(); dialog.show(); return dialog; } } } <file_sep>/provider/src/main/java/com/sskj/provider/http/retrofit/HttpRequest.java package com.sskj.provider.http.retrofit; import com.sskj.provider.http.allapi.Api; import com.sskj.provider.http.observer.HttpRxCallback; import com.sskj.provider.http.observer.HttpRxObservable; import com.trello.rxlifecycle2.LifecycleProvider; import com.trello.rxlifecycle2.android.ActivityEvent; import com.trello.rxlifecycle2.android.FragmentEvent; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.Observable; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; /** * Http请求类 * * @author ZhongDaFeng */ public class HttpRequest { /** * ApiUrl key 开发者可自定义 */ public static final String API_URL = "API_URL"; public enum Method { GET, POST, FILE } /** * 发送请求 * 备注:不管理生命周期 * * @param method 请求方式 * @param prams 参数集合 * @param callback 回调 */ public void request(Method method, TreeMap<String, Object> prams,String token,String account, HttpRxCallback callback) { Observable<HttpResponse> apiObservable = handleRequest(method, prams,token,account); HttpRxObservable.getObservable(apiObservable).subscribe(callback); } /** * 发送请求 * 备注:自动管理生命周期 * * @param method 请求方式 * @param lifecycle 实现RxActivity/RxFragment 参数为空不管理生命周期 * @param prams 参数集合 * @param callback 回调 */ public void request(Method method, TreeMap<String, Object> prams,String token,String account, LifecycleProvider lifecycle, HttpRxCallback callback) { Observable<HttpResponse> apiObservable = handleRequest(method, prams,token,account); HttpRxObservable.getObservable(apiObservable, lifecycle).subscribe(callback); } /** * 发送请求 * 备注:自动管理生命周期 * * @param * @param method 请求方式 * @param prams 参数集合 * @param lifecycle 实现RxActivity/RxFragment 参数为空不管理生命周期 */ public Flowable request(Method method, TreeMap<String, Object> prams,String token,String account, LifecycleProvider lifecycle) { Observable<HttpResponse> apiObservable = handleRequest(method, prams,token,account); return HttpRxObservable.getObservable(apiObservable, lifecycle).toFlowable(BackpressureStrategy.BUFFER); } /** * 发送请求 * 备注:手动指定生命周期-Activity * * @param method 请求方式 * @param lifecycle 实现RxActivity * @param event 指定生命周期 * @param prams 参数集合 * @param callback 回调 */ public void request(Method method, TreeMap<String, Object> prams,String token,String account, LifecycleProvider<ActivityEvent> lifecycle, ActivityEvent event, HttpRxCallback callback) { Observable<HttpResponse> apiObservable = handleRequest(method, prams,token,account); HttpRxObservable.getObservable(apiObservable, lifecycle, event).subscribe(callback); } /** * 发送请求 * 备注:手动指定生命周期-Fragment * * @param method 请求方式 * @param lifecycle 实现RxFragment * @param event 指定生命周期 * @param prams 参数集合 * @param callback 回调 */ public void request(Method method, TreeMap<String, Object> prams,String token,String account, LifecycleProvider<FragmentEvent> lifecycle, FragmentEvent event, HttpRxCallback callback) { Observable<HttpResponse> apiObservable = handleRequest(method, prams,token,account); HttpRxObservable.getObservable(apiObservable, lifecycle, event).subscribe(callback); } /** * 发送请求 * 备注:手动指定生命周期-Fragment * * @param method 请求方式 * @param lifecycle 实现RxFragment * @param prams 参数集合 * @param callback 回调 */ public void requestFile(Method method, TreeMap<String, Object> prams,String token,String account, Map<String, File> fileMap, LifecycleProvider<FragmentEvent> lifecycle, HttpRxCallback callback) { Observable<HttpResponse> apiObservable = handleRequestFile(method, prams,token,account, fileMap); HttpRxObservable.getObservable(apiObservable, lifecycle).subscribe(callback); } /** * 预处理请求 * * @param method 请求方法 * @param prams 参数集合 * @return */ private Observable<HttpResponse> handleRequest(Method method, TreeMap<String, Object> prams,String token,String account) { //获取基础参数 TreeMap<String, Object> request = getBaseRequest(); //添加业务参数 request.putAll(prams); //获取apiUrl String apiUrl = ""; if (request.containsKey(API_URL)) { apiUrl = String.valueOf(request.get(API_URL)); //移除apiUrl参数(此参数不纳入业务参数) request.remove(API_URL); } Observable<HttpResponse> apiObservable; switch (method) { case GET: apiObservable = RetrofitUtils.get(token,account).retrofit().create(Api.class).get(apiUrl, request); break; case POST: apiObservable = RetrofitUtils.get(token,account).retrofit().create(Api.class).post(apiUrl, request); break; default: apiObservable = RetrofitUtils.get(token,account).retrofit().create(Api.class).post(apiUrl, request); break; } return apiObservable; } /** * 预处理请求 * * @param method 请求方法 * @param prams 参数集合 * @return */ private Observable<HttpResponse> handleRequestFile(Method method, TreeMap<String, Object> prams,String token,String account, Map<String, File> fileMap) { TreeMap<String, Object> request = getBaseRequest(); request.putAll(prams); String apiUrl = ""; if (request.containsKey(API_URL)) { apiUrl = String.valueOf(request.get(API_URL)); request.remove(API_URL); } Iterator<Map.Entry<String, Object>> iterator1 = request.entrySet().iterator(); HashMap<String, String> requestMap = new HashMap<>(); ArrayList<MultipartBody.Part> parts = new ArrayList<>(); while (iterator1.hasNext()) { Map.Entry<String, Object> next = iterator1.next(); requestMap.put(next.getKey(), next.getValue().toString()); MultipartBody.Part formData = MultipartBody.Part.createFormData(next.getKey(), next.getValue().toString()); parts.add(formData); } Iterator<Map.Entry<String, File>> iterator = fileMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, File> next = iterator.next(); RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), next.getValue()); MultipartBody.Part filePart = MultipartBody.Part.createFormData(next.getKey(), next.getValue().getName(), requestBody); parts.add(filePart); } Observable<HttpResponse> apiObservable; switch (method) { case GET: apiObservable = RetrofitUtils.get(token,account).retrofit().create(Api.class).get(apiUrl, request); break; case POST: apiObservable = RetrofitUtils.get(token,account).retrofit().create(Api.class).post(apiUrl, request); break; case FILE: apiObservable = RetrofitUtils.get(token,account).retrofit().create(Api.class).postFile(apiUrl, parts); break; default: apiObservable = RetrofitUtils.get(token,account).retrofit().create(Api.class).post(apiUrl, request); break; } return apiObservable; } /** * 获取基础request参数 */ private TreeMap<String, Object> getBaseRequest() { TreeMap<String, Object> map = new TreeMap<>(); return map; } } <file_sep>/app/src/main/java/com/sskj/hub/rxbus2/Subscribe.java package com.sskj.hub.rxbus2; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by lvzhihao on 17-7-25. * 注解在RxBus消息的处理方法上 * 当使用codes时,表示处理红点 * 使用code时,与红点逻辑无关 */ @Documented @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Subscribe { int[] codes() default {-1}; int code() default -1; ThreadMode threadMode() default ThreadMode.CURRENT_THREAD; } <file_sep>/app/src/main/java/com/sskj/hub/utils/ImageUtil.java package com.sskj.hub.utils; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.widget.ImageView; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.transition.Transition; import com.sskj.hub.R; import com.sskj.hub.base.GlideApp; import com.sskj.provider.utils.App; /** * Created by vzhihao on 2016/7/29. * 图片加载工具,可以设置圆形,圆角,正常,模糊图片,现在使用Glide加载 */ public class ImageUtil { private static RequestOptions optionsRound; private static RequestOptions optionsNormal; private static RequestOptions optionsCircle; static { optionsRound = new RequestOptions() .placeholder(R.mipmap.ic_launcher) .error(R.mipmap.ic_launcher) .transform(new GlideRoundTransformCenterCrop(20)); } static { optionsCircle = new RequestOptions() .circleCrop() .placeholder(R.mipmap.ic_launcher) .error(R.mipmap.ic_launcher); } static { optionsNormal = new RequestOptions() .placeholder(R.mipmap.ic_launcher) .error(R.mipmap.ic_launcher); } /** * 设置圆形图片 * * @param url * @param imageView */ public static void setCircleImage(Object url, ImageView imageView) { GlideApp.with(App.INSTANCE).load(url).apply(optionsCircle).into(imageView); } /** * 返回圆形图片Drawable * * @param url * @param drawableBack */ public static void setCircleImageReady(Object url, DrawableBack drawableBack) { GlideApp.with(App.INSTANCE).load(url).apply(optionsCircle).into(new SimpleTarget<Drawable>() { @Override public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) { drawableBack.back(resource); } }); } /** * 设置图片 * * @param url * @param imageView */ public static void setImage(Object url, ImageView imageView) { GlideApp.with(App.INSTANCE).load(url).apply(optionsNormal).into(imageView); } /** * 设置圆角矩形图片 * * @param url * @param imageView */ public static void setRoundImage(Object url, ImageView imageView) { GlideApp.with(App.INSTANCE).load(url).apply(optionsRound).into(imageView); } // /** // * 模糊图片 // * @param url // * @param imageView // * @param radius // */ // public static void flurImage(Object url, ImageView imageView, int radius) { // GlideApp.with(App.INSTANCE).load(url) // .apply(bitmapTransform(new BlurTransformation(radius))) // .into(imageView); // } /** * 返回圆形图片Bitmap * * @param url * @param bitmapBack */ public static void bitmapCircle(Object url, BitmapBack bitmapBack) { GlideApp.with(App.INSTANCE) .asBitmap() .load(url) .apply(optionsCircle) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) { bitmapBack.back(resource); } }); } public interface BitmapBack { void back(Bitmap bitmap); } public interface DrawableBack { void back(Drawable drawable); } } <file_sep>/app/src/main/java/com/sskj/hub/rxbus2/SubscriberMethod.java package com.sskj.hub.rxbus2; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Created by lvzhihao on 17-7-25. */ public class SubscriberMethod { public Method method; public ThreadMode threadMode; public Class<?> eventType; public Object subscriber; public int code; public SubscriberMethod(Object subscriber, Method method, Class<?> eventType, int code, ThreadMode threadMode) { this.method = method; this.threadMode = threadMode; this.eventType = eventType; this.subscriber = subscriber; this.code = code; } public void invoke(Object o) { try { Class[] e = this.method.getParameterTypes(); if (e != null && e.length == 1) { this.method.invoke(this.subscriber, o); } else if (e == null || e.length == 0) { this.method.invoke(this.subscriber); } } catch (IllegalAccessException var3) { var3.printStackTrace(); } catch (InvocationTargetException var4) { var4.printStackTrace(); } } } <file_sep>/app/src/main/java/com/sskj/hub/base/BaseRecyclerViewAdapter.java package com.sskj.hub.base; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; /** * ProjectName: * DESC: RecyclerView基类 * Created by lez on 2018/9/28 13:32 * updateName: * updateTime: * updateDesc: */ abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> { ArrayList<T> mData; //数据 IRecyclerItemChangeListener mListener; //回调接口 //设置数据的方法 public void setData(ArrayList<T> data){ this.mData = data; } //获取显示数量 @Override public int getItemCount() { return mData != null ? mData.size() : 0; } //设置点击事件接口回调r public void setListener(IRecyclerItemChangeListener listener){ mListener = listener; } //设置一个回调的接口 interface IRecyclerItemChangeListener { void onitemListener(View v, int postion); } //返回Item显示的不同布局 @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //抽象方法,子类出具体实现 return getLayout(parent,viewType); } //对Item的数据进行赋值 @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { //抽象方法子类去具体实现 setItemData(holder,position); //设置Item的点击事件 holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //点击事件回调到Activity if (mListener != null){ mListener.onitemListener(v,position); } } }); } //抽象方法,子类实现具体操作 protected abstract void setItemData(RecyclerView.ViewHolder holder, int position); protected abstract RecyclerView.ViewHolder getLayout(ViewGroup parent, int viewType); } <file_sep>/provider/src/main/java/com/sskj/provider/http/allapi/Api.java package com.sskj.provider.http.allapi; import com.sskj.provider.http.retrofit.HttpResponse; import java.util.List; import java.util.TreeMap; import io.reactivex.Observable; import okhttp3.MultipartBody; import okhttp3.ResponseBody; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.QueryMap; import retrofit2.http.Streaming; import retrofit2.http.Url; /** * Api接口 * * @author ZhongDaFeng */ public interface Api { /** * GET请求 * * @param url api接口url * @param request 请求参数map * @return */ @GET Observable<HttpResponse> get(@Url String url, @QueryMap TreeMap<String, Object> request); /** * POST请求 * * @param url api接口url * @param request 请求参数map * @return */ @FormUrlEncoded @POST Observable<HttpResponse> post(@Url String url, @FieldMap TreeMap<String, Object> request); /** * POST请求上传文件 * * @param url api接口url * @param * @return */ @Multipart @POST Observable<HttpResponse> postFile(@Url() String url, @Part() List<MultipartBody.Part> parts ); @Streaming @GET Observable<ResponseBody> executeDownload(@Header("Range") String range, @Url() String url); } <file_sep>/app/src/main/java/com/sskj/hub/rxbus2/ThreadMode.java package com.sskj.hub.rxbus2; /** * Created by lvzhihao on 17-7-25. */ public enum ThreadMode { CURRENT_THREAD, MAIN, NEW_THREAD; ThreadMode() { } } <file_sep>/app/src/main/java/com/sskj/hub/model/main/biz/SelfSelectFragmentBiz.java package com.sskj.hub.model.main.biz; import com.sskj.hub.base.BaseBiz; import com.sskj.provider.http.constant.ProviderConstant; import com.sskj.provider.http.constant.Url; import com.sskj.provider.http.observer.HttpRxCallback; import com.sskj.provider.http.retrofit.HttpRequest; import com.sskj.provider.utils.SPUtil; import com.trello.rxlifecycle2.LifecycleProvider; import java.util.TreeMap; /** * ProjectName: * DESC: 自选业务逻辑 * Created by lez on 2018/6/7 18:03 * updateName: * updateTime: * updateDesc: */ public class SelfSelectFragmentBiz extends BaseBiz { /** * 基本Url */ private final String BASE_API = Url.APP_URL; /** * 获取自选相关数据 * @param lifecycle * @param callback */ public void requestCommodity(String codeList,LifecycleProvider lifecycle, HttpRxCallback callback) { /** * 构建请求参数 */ TreeMap<String, Object> request = new TreeMap<>(); request.put("app", "app"); request.put("action", "oneStockInfo"); request.put("stockCode", codeList); request.put(HttpRequest.API_URL, BASE_API); /** * 发送请求 */ getRequest().request(HttpRequest.Method.GET, request, SPUtil.get(ProviderConstant.TOKEN,""),SPUtil.get(ProviderConstant.ACCOUNT,""), lifecycle, callback); } } <file_sep>/provider/src/main/java/com/sskj/provider/widget/NoticeDialog.java package com.sskj.provider.widget; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.sskj.provider.R; /** * Created by Administrator on 2018/1/3. */ public class NoticeDialog extends Dialog implements View.OnClickListener { private static final String TAG = "NoticeDialog"; private Context context; private TextView tv_1; public NoticeDialog(Context context) { super(context); this.context = context; } protected NoticeDialog(Context context, int themeResId) { super(context, themeResId); } private void init() { //设置dialog位置 Window win = getWindow(); WindowManager.LayoutParams lp = win.getAttributes(); lp.gravity = Gravity.CENTER; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; lp.width = WindowManager.LayoutParams.MATCH_PARENT; win.setAttributes(lp); //设置背景透明 win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_notice_dialog); init(); initView(); } private void initView() { tv_1 = findViewById(R.id.tv_1); findViewById(R.id.tv_cancel).setOnClickListener(this); findViewById(R.id.tv_confirm).setOnClickListener(this); } public void setData(String noticeContent) { if (!TextUtils.isEmpty(noticeContent)) { //保证\n换行,去掉头部尾部的双引号 noticeContent=noticeContent.replace("\\n", "\n"); if(noticeContent.startsWith("\"")){ noticeContent=noticeContent.replaceFirst("\"",""); } if(noticeContent.endsWith("\"")){ noticeContent=noticeContent.substring(0,noticeContent.length()-1); } tv_1.setText(noticeContent); } } @Override public void onClick(View v) { int id=v.getId(); //取消 if(id == R.id.tv_cancel){ noticeListener.cancel(); }else if(id == R.id.tv_confirm){ noticeListener.ensure(); } } /** * 缓存公告信息 */ private void confirmInfo() { } public void setNoticeListener(NoticeListener noticeListener){ this.noticeListener = noticeListener; } private NoticeListener noticeListener; public interface NoticeListener{ void cancel(); void ensure(); } } <file_sep>/app/src/main/java/com/sskj/hub/model/main/entity/Config.java package com.sskj.hub.model.main.entity; /** * author : lez * time : 2018/04/02 * desc : 配置信息 * version: 1.0 */ public class Config { private String closeOutRate;//强平比例 private String goodsCheckFullStop;//商品股止盈止损点位% private int goodsMinBuyHand;//商品最小买入手数 private String hkChargeMin;//港股最低手续费 private String hkChargeRate;//港股手续费‰ private String hkCheckFullStop;//港股止盈止损点位% private int hkMinBuyHand;//港股最小买入手数 private int hkNightLever;//港股隔夜杠杆 默认5倍 private int hkNormalLever;//港股正常杠杆 默认10倍 private String hkOverFeeRate;//港股递延费 ‰ private int id; private String inRate;//入金汇率(美元转人民币) private int maxCountDay;//最大持仓天数 private String maxCountMoney;//最大持仓金额 private String maxOutCharge;//最大出金 private String maxPriceFloatRate;//最大浮动比例 private String minDealMoney;//最小交易金额100美金 private String minInCharge;//最小入金 private String outRate;//出金汇率(美元转人民币) private String serviceCharge;//交易手续费 private String usChargeMin;//美股最低手续费 private String usChargeRate;//美股手续费比例 每股 0.003美元 private String usCheckFullStop;//美股止盈止损点位% private int usMinBuyHand;//美股最小买入手数 private int usNightLever;//美股隔夜杠杆 private String minOutCharge;//最小出金 private String hkNightStrat; private String hkNightEnd; private String virtualCoinEnd; private String virtualCoinStart; private String hkHSIFStart; public String getHkHSIFStart() { return hkHSIFStart; } public void setHkHSIFStart(String hkHSIFStart) { this.hkHSIFStart = hkHSIFStart; } public String getVirtualCoinEnd() { return virtualCoinEnd; } public Config setVirtualCoinEnd(String virtualCoinEnd) { this.virtualCoinEnd = virtualCoinEnd; return this; } public String getVirtualCoinStart() { return virtualCoinStart; } public Config setVirtualCoinStart(String virtualCoinStart) { this.virtualCoinStart = virtualCoinStart; return this; } public String getHkNightStrat() { return hkNightStrat; } public Config setHkNightStrat(String hkNightStrat) { this.hkNightStrat = hkNightStrat; return this; } public String getHkNightEnd() { return hkNightEnd; } public Config setHkNightEnd(String hkNightEnd) { this.hkNightEnd = hkNightEnd; return this; } public String getDealFee() { return dealFee == null ? "" : dealFee; } public void setDealFee(String dealFee) { this.dealFee = dealFee; } private int usNormalLever;//美股正常杠杆 10倍 private String usOverFeeRate;//美股递延费‰ private String payType; private String hkUsRate; private String hkAmStart; private String hkAmEnd; private String hkPmStart; private String hkPmEnd; private String usStart; private String usEnd; public String getStopProfit() { return stopProfit == null ? "" : stopProfit; } public void setStopProfit(String stopProfit) { this.stopProfit = stopProfit; } public String getStopLoss() { return stopLoss == null ? "" : stopLoss; } public void setStopLoss(String stopLoss) { this.stopLoss = stopLoss; } private String concGlncSLNCStart; private String concGlncSLNCEnd; public String getConcGlncSLNCStart() { return concGlncSLNCStart; } public Config setConcGlncSLNCStart(String concGlncSLNCStart) { this.concGlncSLNCStart = concGlncSLNCStart; return this; } public String getConcGlncSLNCEnd() { return concGlncSLNCEnd; } public Config setConcGlncSLNCEnd(String concGlncSLNCEnd) { this.concGlncSLNCEnd = concGlncSLNCEnd; return this; } private String goodsStart; private String goodsEnd; private String outMoneyFee;//出金费率 private String dealFee;//手续费 private String stopProfit;//止盈 private String stopLoss;//止损 public String getCloseOutRate() { return closeOutRate == null ? "" : closeOutRate; } public void setCloseOutRate(String closeOutRate) { this.closeOutRate = closeOutRate; } public String getMinOutCharge() { return minOutCharge == null ? "" : minOutCharge; } public void setMinOutCharge(String minOutCharge) { this.minOutCharge = minOutCharge; } public String getGoodsCheckFullStop() { return goodsCheckFullStop == null ? "" : goodsCheckFullStop; } public void setGoodsCheckFullStop(String goodsCheckFullStop) { this.goodsCheckFullStop = goodsCheckFullStop; } public int getGoodsMinBuyHand() { return goodsMinBuyHand; } public void setGoodsMinBuyHand(int goodsMinBuyHand) { this.goodsMinBuyHand = goodsMinBuyHand; } public String getHkChargeMin() { return hkChargeMin == null ? "" : hkChargeMin; } public void setHkChargeMin(String hkChargeMin) { this.hkChargeMin = hkChargeMin; } public String getHkChargeRate() { return hkChargeRate == null ? "" : hkChargeRate; } public void setHkChargeRate(String hkChargeRate) { this.hkChargeRate = hkChargeRate; } public String getHkCheckFullStop() { return hkCheckFullStop == null ? "" : hkCheckFullStop; } public void setHkCheckFullStop(String hkCheckFullStop) { this.hkCheckFullStop = hkCheckFullStop; } public int getHkMinBuyHand() { return hkMinBuyHand; } public void setHkMinBuyHand(int hkMinBuyHand) { this.hkMinBuyHand = hkMinBuyHand; } public int getHkNightLever() { return hkNightLever; } public void setHkNightLever(int hkNightLever) { this.hkNightLever = hkNightLever; } public int getHkNormalLever() { return hkNormalLever; } public void setHkNormalLever(int hkNormalLever) { this.hkNormalLever = hkNormalLever; } public String getHkOverFeeRate() { return hkOverFeeRate == null ? "" : hkOverFeeRate; } public void setHkOverFeeRate(String hkOverFeeRate) { this.hkOverFeeRate = hkOverFeeRate; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getInRate() { return inRate == null ? "" : inRate; } public void setInRate(String inRate) { this.inRate = inRate; } public int getMaxCountDay() { return maxCountDay; } public void setMaxCountDay(int maxCountDay) { this.maxCountDay = maxCountDay; } public String getMaxCountMoney() { return maxCountMoney == null ? "" : maxCountMoney; } public void setMaxCountMoney(String maxCountMoney) { this.maxCountMoney = maxCountMoney; } public String getMaxOutCharge() { return maxOutCharge == null ? "" : maxOutCharge; } public void setMaxOutCharge(String maxOutCharge) { this.maxOutCharge = maxOutCharge; } public String getMaxPriceFloatRate() { return maxPriceFloatRate == null ? "" : maxPriceFloatRate; } public void setMaxPriceFloatRate(String maxPriceFloatRate) { this.maxPriceFloatRate = maxPriceFloatRate; } public String getMinDealMoney() { return minDealMoney == null ? "" : minDealMoney; } public void setMinDealMoney(String minDealMoney) { this.minDealMoney = minDealMoney; } public String getMinInCharge() { return minInCharge == null ? "" : minInCharge; } public void setMinInCharge(String minInCharge) { this.minInCharge = minInCharge; } public String getOutRate() { return outRate == null ? "" : outRate; } public void setOutRate(String outRate) { this.outRate = outRate; } public String getServiceCharge() { return serviceCharge == null ? "" : serviceCharge; } public void setServiceCharge(String serviceCharge) { this.serviceCharge = serviceCharge; } public String getUsChargeMin() { return usChargeMin == null ? "" : usChargeMin; } public void setUsChargeMin(String usChargeMin) { this.usChargeMin = usChargeMin; } public String getUsChargeRate() { return usChargeRate == null ? "" : usChargeRate; } public void setUsChargeRate(String usChargeRate) { this.usChargeRate = usChargeRate; } public String getUsCheckFullStop() { return usCheckFullStop == null ? "" : usCheckFullStop; } public void setUsCheckFullStop(String usCheckFullStop) { this.usCheckFullStop = usCheckFullStop; } public int getUsMinBuyHand() { return usMinBuyHand; } public void setUsMinBuyHand(int usMinBuyHand) { this.usMinBuyHand = usMinBuyHand; } public int getUsNightLever() { return usNightLever; } public void setUsNightLever(int usNightLever) { this.usNightLever = usNightLever; } public int getUsNormalLever() { return usNormalLever; } public void setUsNormalLever(int usNormalLever) { this.usNormalLever = usNormalLever; } public String getUsOverFeeRate() { return usOverFeeRate == null ? "" : usOverFeeRate; } public void setUsOverFeeRate(String usOverFeeRate) { this.usOverFeeRate = usOverFeeRate; } public String getPayType() { return payType == null ? "" : payType; } public void setPayType(String payType) { this.payType = payType; } public String getHkUsRate() { return hkUsRate == null ? "" : hkUsRate; } public void setHkUsRate(String hkUsRate) { this.hkUsRate = hkUsRate; } public String getHkAmStart() { return hkAmStart == null ? "" : hkAmStart; } public void setHkAmStart(String hkAmStart) { this.hkAmStart = hkAmStart; } public String getHkAmEnd() { return hkAmEnd == null ? "" : hkAmEnd; } public void setHkAmEnd(String hkAmEnd) { this.hkAmEnd = hkAmEnd; } public String getHkPmStart() { return hkPmStart == null ? "" : hkPmStart; } public void setHkPmStart(String hkPmStart) { this.hkPmStart = hkPmStart; } public String getHkPmEnd() { return hkPmEnd == null ? "" : hkPmEnd; } public void setHkPmEnd(String hkPmEnd) { this.hkPmEnd = hkPmEnd; } public String getUsStart() { return usStart == null ? "" : usStart; } public void setUsStart(String usStart) { this.usStart = usStart; } public String getUsEnd() { return usEnd == null ? "" : usEnd; } public void setUsEnd(String usEnd) { this.usEnd = usEnd; } public String getGoodsStart() { return goodsStart == null ? "" : goodsStart; } public void setGoodsStart(String goodsStart) { this.goodsStart = goodsStart; } public String getGoodsEnd() { return goodsEnd == null ? "" : goodsEnd; } @Override public String toString() { return "Config{" + "closeOutRate='" + closeOutRate + '\'' + ", goodsCheckFullStop='" + goodsCheckFullStop + '\'' + ", goodsMinBuyHand=" + goodsMinBuyHand + ", hkChargeMin='" + hkChargeMin + '\'' + ", hkChargeRate='" + hkChargeRate + '\'' + ", hkCheckFullStop='" + hkCheckFullStop + '\'' + ", hkMinBuyHand=" + hkMinBuyHand + ", hkNightLever=" + hkNightLever + ", hkNormalLever=" + hkNormalLever + ", hkOverFeeRate='" + hkOverFeeRate + '\'' + ", id=" + id + ", inRate='" + inRate + '\'' + ", maxCountDay=" + maxCountDay + ", maxCountMoney='" + maxCountMoney + '\'' + ", maxOutCharge='" + maxOutCharge + '\'' + ", maxPriceFloatRate='" + maxPriceFloatRate + '\'' + ", minDealMoney='" + minDealMoney + '\'' + ", minInCharge='" + minInCharge + '\'' + ", outRate='" + outRate + '\'' + ", serviceCharge='" + serviceCharge + '\'' + ", usChargeMin='" + usChargeMin + '\'' + ", usChargeRate='" + usChargeRate + '\'' + ", usCheckFullStop='" + usCheckFullStop + '\'' + ", usMinBuyHand=" + usMinBuyHand + ", usNightLever=" + usNightLever + ", minOutCharge='" + minOutCharge + '\'' + ", usNormalLever=" + usNormalLever + ", usOverFeeRate='" + usOverFeeRate + '\'' + ", payType='" + payType + '\'' + ", hkUsRate='" + hkUsRate + '\'' + ", hkAmStart='" + hkAmStart + '\'' + ", hkAmEnd='" + hkAmEnd + '\'' + ", hkPmStart='" + hkPmStart + '\'' + ", hkPmEnd='" + hkPmEnd + '\'' + ", usStart='" + usStart + '\'' + ", usEnd='" + usEnd + '\'' + ", goodsStart='" + goodsStart + '\'' + ", goodsEnd='" + goodsEnd + '\'' + ", outMoneyFee='" + outMoneyFee + '\'' + ", dealFee='" + dealFee + '\'' + '}'; } public void setGoodsEnd(String goodsEnd) { this.goodsEnd = goodsEnd; } public String getOutMoneyFee() { return outMoneyFee == null ? "" : outMoneyFee; } public void setOutMoneyFee(String outMoneyFee) { this.outMoneyFee = outMoneyFee; } } <file_sep>/app/src/main/java/com/sskj/hub/utils/SpanUtil.java package com.sskj.hub.utils; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.text.style.RelativeSizeSpan; /** * Created by lv on 18-5-31. */ public class SpanUtil { public static SpannableStringBuilder getSmall(String content, String split, float size) { SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content); spannableStringBuilder.setSpan(new RelativeSizeSpan(size), content.indexOf(split) + 1, content.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); return spannableStringBuilder; } public static SpannableStringBuilder getColor(String content, String split, int color) { SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content); spannableStringBuilder.setSpan(new ForegroundColorSpan(color), content.indexOf(split) + 1, content.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); return spannableStringBuilder; } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' def releaseTime() { return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC")) } android { compileSdkVersion 27 defaultConfig { applicationId "com.sskj.hub" multiDexEnabled true minSdkVersion 17 targetSdkVersion 27 versionCode 4 versionName "1.3" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } android.applicationVariants.all { variant -> variant.outputs.all { outputFileName = "HUB_${releaseTime()}_${defaultConfig.versionCode}.apk" } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support.constraint:constraint-layout:1.1.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.jakewharton:butterknife:8.6.0' /*动态权限*/ implementation 'com.bulong.rudeness:rudeness:0.1.4@aar' /*######################指示器#################*/ implementation 'com.flyco.tablayout:FlycoTabLayout_Lib:2.1.2@aar' implementation 'com.android.support:recyclerview-v7:27.0.1' /*######################图片加载框架#################*/ implementation 'com.github.bumptech.glide:glide:4.3.1' annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1' implementation 'com.github.bumptech.glide:okhttp3-integration:4.3.1' /*###################上拉加载下拉刷新##################*/ implementation 'com.shizhefei:MVCHelper-Library:1.3.1' implementation 'com.shizhefei:MVCHelper-CoolRefresh:1.3.1' implementation 'com.shizhefei:CoolRefreshView:1.0.1' implementation 'com.contrarywind:Android-PickerView:4.1.6' implementation 'com.zhy:okhttputils:2.6.2' implementation 'com.tencent.bugly:crashreport:2.6.6' implementation 'com.github.LuckSiege.PictureSelector:picture_library:v2.2.3' implementation 'cn.bingoogolapple:bga-qrcode-zxing:1.2.1' implementation 'com.github.yoojia:next-inputs-android:1.7.2' //底部导航 implementation 'com.ashokvarma.android:bottom-navigation-bar:2.0.5' implementation project(':provider') annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0' } <file_sep>/app/src/main/java/com/sskj/hub/manager/MyApplication.java package com.sskj.hub.manager; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.support.multidex.MultiDex; import com.blankj.utilcode.util.Utils; import com.bulong.rudeness.RudenessScreenHelper; import com.shizhefei.mvc.MVCHelper; import com.sskj.hub.base.BaseActivityLifecycleCallbacks; import com.sskj.hub.mvchelper.LoadViewFactory; import com.zhy.http.okhttp.OkHttpUtils; import java.util.LinkedList; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; /** * ProjectName: * DESC: * Created by lez on 2018/9/13 9:58 * updateName: * updateTime: * updateDesc: */ public class MyApplication extends Application { private static MyApplication mAppInstance; /** * 链表Activity集合 */ private LinkedList<Activity> mActivityList = new LinkedList<Activity>(); @Override public void onCreate() { super.onCreate(); // 应用启动 , 在此初始化数据 单例application mAppInstance = this; OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10000L, TimeUnit.MILLISECONDS) .readTimeout(10000L, TimeUnit.MILLISECONDS) .build(); registerActivityLifecycleCallbacks(new BaseActivityLifecycleCallbacks()); /** 屏幕适配设置屏幕宽度*/ new RudenessScreenHelper(this, 750).activate(); OkHttpUtils.initClient(okHttpClient); Utils.init(this); /**设置全局加载更多及数据加载各状态界面*/ MVCHelper.setLoadViewFractory(new LoadViewFactory()); SharedPreferences mySharedPreferences = getSharedPreferences("userdata", Activity.MODE_PRIVATE); if (!mySharedPreferences.contains("language")) { //实例化SharedPreferences.Editor对象(第二步) SharedPreferences.Editor editor = mySharedPreferences.edit(); //用putString的方法保存数据 editor.putInt("language", 0); //提交当前数据 editor.commit(); } } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } public static MyApplication getInstance() { return mAppInstance; } @Override // 建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗 public void onTerminate() { // 应用结束 在此保存数据 // ...在此写代码 super.onTerminate(); } @Override public void onLowMemory() { // 系统内存过低,在此部署一些内存回收策略 super.onLowMemory(); } /** * 退出系统 */ public void exit() { for (Activity activity : mActivityList) { activity.finish(); } System.exit(0); } } <file_sep>/app/src/main/java/com/sskj/hub/model/main/biz/MainBiz.java package com.sskj.hub.model.main.biz; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; import com.sskj.hub.base.BaseBiz; import com.sskj.hub.utils.DownloadIntentService; import com.sskj.provider.http.constant.ProviderConstant; import com.sskj.provider.http.constant.Url; import com.sskj.provider.http.observer.HttpRxCallback; import com.sskj.provider.http.retrofit.HttpRequest; import com.sskj.provider.utils.SPUtil; import com.trello.rxlifecycle2.LifecycleProvider; import java.util.List; import java.util.TreeMap; /** * ProjectName: * DESC:主页面业务 * Created by lez on 2018/6/6 9:18 * updateName: * updateTime: * updateDesc: */ public class MainBiz extends BaseBiz { /** * 版本更新请求 */ public void requestVersionUpdate(LifecycleProvider lifecycle, HttpRxCallback callback){ /** * 构建请求参数 */ TreeMap<String, Object> request = new TreeMap<>(); request.put(HttpRequest.API_URL, Url.APP_UPDATE); /** * 发送请求 */ getRequest().request(HttpRequest.Method.GET, request, SPUtil.get(ProviderConstant.TOKEN,""),SPUtil.get(ProviderConstant.ACCOUNT,""), lifecycle, callback); } /** * 下载APK */ public void downloadAPK(Context context,String url){ if (isServiceRunning(context,DownloadIntentService.class.getName())) { Toast.makeText(context, "正在下载", Toast.LENGTH_SHORT).show(); return; } // url = "http://sqdd.myapp.com/myapp/qqteam/tim/down/tim.apk"; Intent intent = new Intent(context, DownloadIntentService.class); Bundle bundle = new Bundle(); bundle.putString("download_url", url); bundle.putInt("download_id", 1); bundle.putString("download_file", url.substring(url.lastIndexOf('/') + 1)); intent.putExtras(bundle); context.startService(intent); } /** * 用来判断服务是否运行. * * @param className 判断的服务名字 * @return true 在运行 false 不在运行 */ private boolean isServiceRunning(Context context,String className) { boolean isRunning = false; ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningServiceInfo> serviceList = activityManager .getRunningServices(Integer.MAX_VALUE); if (!(serviceList.size() > 0)) { return false; } for (int i = 0; i < serviceList.size(); i++) { if (serviceList.get(i).service.getClassName().equals(className) == true) { isRunning = true; break; } } return isRunning; } } <file_sep>/app/src/main/java/com/sskj/hub/model/main/iface/ISplashView.java package com.sskj.hub.model.main.iface; import com.sskj.hub.base.IBaseView; /** * ProjectName: * DESC: 启动页View * Created by lez on 2018/5/30 8:38 * updateName: * updateTime: * updateDesc: */ public interface ISplashView extends IBaseView { //显示结果 void showResult(String msg); } <file_sep>/provider/src/main/java/com/sskj/provider/widget/UpdateDialog.java package com.sskj.provider.widget; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.sskj.provider.R; /** * ProjectName: * DESC: 版本更新弹窗 * Created by lez on 2018/6/29 16:55 * updateName: * updateTime: * updateDesc: */ public class UpdateDialog extends Dialog implements View.OnClickListener{ private String updateFlag;//是否是强制更新 private TextView contentTxt; private TextView titleTxt; private TextView submitTxt; private TextView cancelTxt; private Context mContext; private String content; private OnCloseListener listener; private String positiveName; private String negativeName; private String title; public UpdateDialog(Context context) { super(context); this.mContext = context; } public UpdateDialog(Context context, int themeResId, String content) { super(context, themeResId); this.mContext = context; this.content = content; } public UpdateDialog(Context context, String updateFlag, int themeResId, String content, OnCloseListener listener) { super(context, themeResId); this.mContext = context; this.updateFlag = updateFlag; this.content = content; this.listener = listener; } protected UpdateDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); this.mContext = context; } public UpdateDialog setTitle(String title){ this.title = title; return this; } public UpdateDialog setPositiveButton(String name){ this.positiveName = name; return this; } public UpdateDialog setNegativeButton(String name){ this.negativeName = name; return this; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.version_update_dialog_layout); setCanceledOnTouchOutside(false); initView(); } private void initView(){ contentTxt = findViewById(R.id.update_content); titleTxt = findViewById(R.id.update_title); submitTxt = findViewById(R.id.update_submit); submitTxt.setOnClickListener(this); cancelTxt = findViewById(R.id.update_cancel); cancelTxt.setOnClickListener(this); if("1".equals(updateFlag)){ cancelTxt.setTextColor(Color.GRAY); cancelTxt.setClickable(false); } contentTxt.setText(content); if(!TextUtils.isEmpty(positiveName)){ submitTxt.setText(positiveName); } if(!TextUtils.isEmpty(negativeName)){ cancelTxt.setText(negativeName); } if(!TextUtils.isEmpty(title)){ titleTxt.setText(title); } } @Override public void onClick(View v) { int id = v.getId(); if(id == R.id.update_cancel){ if(listener != null){ listener.onClick(this, false); dismiss(); } }else if(id == R.id.update_submit){ if(listener != null){ listener.onClick(this, true); } } } public interface OnCloseListener{ void onClick(Dialog dialog, boolean confirm); } }<file_sep>/app/src/main/java/com/sskj/hub/mvchelper/ModelRx2DataSource.java package com.sskj.hub.mvchelper; import java.util.List; import io.reactivex.Flowable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; /** * Created by lvzhihao on 17-3-30. */ public class ModelRx2DataSource<T> extends Rx2DataSource<List<T>> { private int pageSize=20; private boolean isMore = false; public int mPage = 1; OnLoadSource onLoadSource; public ModelRx2DataSource(OnLoadSource onLoadSource,int pageSize) { this.pageSize=pageSize; this.onLoadSource=onLoadSource; } public ModelRx2DataSource(OnLoadSource onLoadSource) { this.onLoadSource=onLoadSource; } public interface OnLoadSource<T>{ Flowable<List<T>> loadSource(final int page); } private Flowable load(final int page) throws Exception { return onLoadSource.loadSource(page) .flatMap(new Function<List<T>, Flowable<List<T>>>() { @Override public Flowable<List<T>> apply(@NonNull List<T> s) throws Exception { if (s!=null&&s.size()==pageSize){ isMore=true; }else { isMore=false; } return Flowable.just(s); } }); } @Override public boolean hasMore() { return isMore; } @Override public Flowable<List<T>> refreshRX() throws Exception { mPage = 1; return load(mPage); } @Override public Flowable<List<T>> loadMoreRX() throws Exception { return load(++mPage); } }<file_sep>/app/src/main/java/com/sskj/hub/model/main/presenter/QuotationMainPresenter.java package com.sskj.hub.model.main.presenter; import android.text.TextUtils; import android.util.Log; import com.sskj.hub.base.BasePresenter; import com.sskj.hub.model.main.biz.QuotationMainBiz; import com.sskj.hub.model.main.entity.NoticeEntity; import com.sskj.hub.model.main.iface.IQuotationMainView; import com.sskj.hub.model.main.fragment.QuotationFragment; import com.sskj.provider.http.observer.HttpRxCallback; /** * ProjectName: * DESC: 行情主页面Presenter * Created by lez on 2018/5/30 8:37 * updateName: * updateTime: * updateDesc: */ public class QuotationMainPresenter extends BasePresenter<IQuotationMainView,QuotationFragment> { public QuotationMainPresenter(IQuotationMainView view, QuotationFragment quotationFragment) { super(view, quotationFragment); } //获取公告 public void requestNotice(){ //请求 new QuotationMainBiz().requestNotice(getActivity(),new HttpRxCallback<NoticeEntity>() { @Override public void onSuccess(NoticeEntity noticeEntity,String msg) { String noticeId = noticeEntity.getId()+""; if (TextUtils.isEmpty(noticeId) || "null".equals(noticeId)) { return; } if (getView() != null) { getView().showNotice(noticeEntity); } } @Override public void onError(int code, String desc) { Log.i("info",desc); } }); } } <file_sep>/app/src/main/java/com/sskj/hub/model/main/entity/NoticeEntity.java package com.sskj.hub.model.main.entity; /** * ProjectName: * DESC: * Created by lez on 2018/6/5 12:34 * updateName: * updateTime: * updateDesc: */ public class NoticeEntity { @Override public String toString() { return "NoticeEntity{" + "id=" + id + ", createTime='" + createTime + '\'' + ", timestamp='" + timestamp + '\'' + ", title='" + title + '\'' + ", details='" + details + '\'' + '}'; } public NoticeEntity(int id, String createTime, String timestamp, String title, String details) { this.id = id; this.createTime = createTime; this.timestamp = timestamp; this.title = title; this.details = details; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCreateTime() { return createTime == null ? "" : createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getTimestamp() { return timestamp == null ? "" : timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getTitle() { return title == null ? "" : title; } public void setTitle(String title) { this.title = title; } public String getDetails() { return details == null ? "" : details; } public void setDetails(String details) { this.details = details; } private int id; private String createTime; private String timestamp; private String title; private String details; }
b85a9b0a2fa1b2d98d3e407900d18ce06a341dbe
[ "Java", "Gradle" ]
32
Java
SSKJ-Android/SSKJ-Java
31f5fcd9fdee3dd08fa246ca2563b111f57df158
b0cc032b97a2288b4f5b75d221349b67384c3400
refs/heads/master
<file_sep>/* Hamming and parity calculations */ /* Copyright 2015 <NAME> <<EMAIL>> */ unsigned char hamming84(unsigned char d) { unsigned char d1 = d&1; unsigned char d2 = (d>>1)&1; unsigned char d3 = (d>>2)&1; unsigned char d4 = (d>>3)&1; unsigned char p1 = (1 + d1 + d3 + d4) & 1; unsigned char p2 = (1 + d1 + d2 + d4) & 1; unsigned char p3 = (1 + d1 + d2 + d3) & 1; unsigned char p4 = (1 + p1 + d1 + p2 + d2 + p3 + d3 + d4) & 1; return (p1 | (d1<<1) | (p2<<2) | (d2<<3) | (p3<<4) | (d3<<5) | (p4<<6) | (d4<<7)); } unsigned char parity(unsigned char d) { d &= 0x7f; unsigned char p = 1; unsigned char t = d; int i; for (i=0; i<7; i++) { p += t&1; t = t>>1; } p &= 1; return d|(p<<7); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <time.h> #include <assert.h> #include <unistd.h> #include <sys/time.h> #include "bcm_host.h" #include "hamming.h" #ifndef ALIGN_UP #define ALIGN_UP(x,y) ((x + (y)-1) & ~((y)-1)) #endif typedef struct { DISPMANX_DISPLAY_HANDLE_T display; DISPMANX_MODEINFO_T info; void *image; DISPMANX_UPDATE_HANDLE_T update; DISPMANX_RESOURCE_HANDLE_T resource; DISPMANX_ELEMENT_HANDLE_T element; uint32_t vc_image_ptr; } RECT_VARS_T; static RECT_VARS_T gRectVars; #define RGB565(r,g,b) (((r)>>3)<<11 | ((g)>>2)<<5 | (b)>>3) static unsigned short pal[256] = { RGB565(0,0,0), RGB565(255,255,255), }; int main(void) { RECT_VARS_T *vars; uint32_t screen = 0; int ret; VC_RECT_T src_rect; VC_RECT_T dst_rect; VC_IMAGE_TYPE_T type = VC_IMAGE_8BPP; VC_DISPMANX_ALPHA_T alpha = { DISPMANX_FLAGS_ALPHA_FROM_SOURCE | DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS, 255, /*alpha 0->255*/ 0 }; unsigned char packet[45] = {0x55, 0x55, 0x27}; // mrag packet[3] = hamming84(1); packet[4] = hamming84(0); // page-subpage packet[5] = hamming84(0); packet[6] = hamming84(0); packet[7] = hamming84(0); packet[8] = hamming84(0); packet[9] = hamming84(0); packet[10] = hamming84(0); packet[11] = hamming84(0); packet[12] = hamming84(0); vars = &gRectVars; bcm_host_init(); printf("Open display[%i]...\n", screen ); vars->display = vc_dispmanx_display_open( screen ); ret = vc_dispmanx_display_get_info( vars->display, &vars->info); assert(ret == 0); printf( "Display is %d x %d\n", vars->info.width, vars->info.height ); int width = 360; int height = 1; int pitch = ALIGN_UP(width, 32); //int aligned_height = ALIGN_UP(height, 16); vars->image = calloc( 1, pitch * height ); assert(vars->image); vars->resource = vc_dispmanx_resource_create( type, width, height, &vars->vc_image_ptr ); assert( vars->resource ); ret = vc_dispmanx_resource_set_palette( vars->resource, pal, 0, sizeof pal ); assert( ret == 0 ); vc_dispmanx_rect_set( &dst_rect, 0, 0, width, height); ret = vc_dispmanx_resource_write_data( vars->resource, type, pitch, vars->image, &dst_rect ); assert( ret == 0 ); vars->update = vc_dispmanx_update_start( 10 ); assert( vars->update ); vc_dispmanx_rect_set( &src_rect, 0, 0, width << 16, height << 16 ); vc_dispmanx_rect_set( &dst_rect, 10, 0, 700, 64 ); vars->element = vc_dispmanx_element_add( vars->update, vars->display, 2000, // layer &dst_rect, vars->resource, &src_rect, DISPMANX_PROTECTION_NONE, &alpha, NULL, // clamp VC_IMAGE_ROT0 ); ret = vc_dispmanx_update_submit_sync( vars->update ); assert( ret == 0 ); while(1) { time_t rawtime; struct tm *info; char buffer[32]; time( &rawtime ); info = localtime( &rawtime ); strftime(buffer,32,"RaspberryPi %a %d %b %H:%M/%S", info); int z; for (z=0; z<32;z++) packet[13+z] = parity(buffer[z]); int x, xx, n=0; unsigned char b; for(x = 0;x < 45; x+=1) { b = packet[x]; for (xx = 0; xx < 8; xx++) { ((unsigned char *)(vars->image))[n++] = (b&1); b = b>>1; } } vc_dispmanx_rect_set( &dst_rect, 0, 0, width, height); ret = vc_dispmanx_resource_write_data( vars->resource, type, pitch, vars->image, &dst_rect ); assert( ret == 0 ); sleep(1); } vars->update = vc_dispmanx_update_start( 10 ); assert( vars->update ); ret = vc_dispmanx_element_remove( vars->update, vars->element ); assert( ret == 0 ); ret = vc_dispmanx_update_submit_sync( vars->update ); assert( ret == 0 ); ret = vc_dispmanx_resource_delete( vars->resource ); assert( ret == 0 ); ret = vc_dispmanx_display_close( vars->display ); assert( ret == 0 ); return 0; } <file_sep>unsigned char hamming84 (unsigned char); unsigned char parity (unsigned char);
f34b09185b397708aade83f32cfd830855922c8f
[ "C" ]
3
C
yaba/raspi-teletext
ad1dc176f21c52a27ee58c6b25ef53a0a812e07a
31979623c8ed19fa58e8c7e74bfebd95f1ab50c9
refs/heads/main
<file_sep>package com.bank.cqrs.command.aggregate; import java.math.BigDecimal; import org.axonframework.commandhandling.CommandHandler; import org.axonframework.eventsourcing.EventSourcingHandler; import org.axonframework.modelling.command.AggregateIdentifier; import org.axonframework.modelling.command.AggregateLifecycle; import org.axonframework.spring.stereotype.Aggregate; import com.bank.cqrs.command.CreateAccountCommand; import com.bank.cqrs.command.DepositMoneyCommand; import com.bank.cqrs.command.WithdrawMoneyCommand; import com.bank.cqrs.common.event.AccountActivatedEvent; import com.bank.cqrs.common.event.AccountCreatedEvent; import com.bank.cqrs.common.event.AccountCreditedEvent; import com.bank.cqrs.common.event.AccountDebitedEvent; import lombok.extern.slf4j.Slf4j; @Aggregate @Slf4j public class AccountAggregate { @AggregateIdentifier private String accountId ; private BigDecimal amount ; private String status ; public AccountAggregate() { } @CommandHandler public AccountAggregate(CreateAccountCommand createAccountCommand) { System.out.println("CreateAccountCommand received."); AggregateLifecycle.apply(new AccountCreatedEvent(createAccountCommand.getId(), createAccountCommand.getBalance())); } @EventSourcingHandler public void on(AccountCreatedEvent accountCreatedEvent) { System.out.println("AccountCreatedEvent received."); this.accountId= accountCreatedEvent.getId(); this.amount = accountCreatedEvent.getBalance(); this.status ="CREATED"; AggregateLifecycle.apply(new AccountActivatedEvent(accountCreatedEvent.getId() ,"ACTIVATED")); } @EventSourcingHandler public void on(AccountActivatedEvent accountActivatedEvent) { System.out.println("An AccountActivatedEvent occurred."); this.status = accountActivatedEvent.getStatus(); } @CommandHandler public AccountAggregate(DepositMoneyCommand depositeMoneyCommand) { System.out.println("DepositMoneyCommand received."); AggregateLifecycle.apply(new AccountCreditedEvent(depositeMoneyCommand.getId(), depositeMoneyCommand.getBalance())); } @EventSourcingHandler public void on(AccountCreditedEvent accountCreditedEvent) { System.out.println("AccountCreditedEvent occured."); this.accountId= accountCreditedEvent.getId(); //this.amount = accountCreditedEvent.getAmount(); this.amount = this.amount.add(accountCreditedEvent.getAmount()); } @CommandHandler public AccountAggregate(WithdrawMoneyCommand withdrawMoneyCommand) { System.out.println("WithdrawMoneyCommand received."); AggregateLifecycle.apply(new AccountDebitedEvent(withdrawMoneyCommand.getId(), withdrawMoneyCommand.getBalance())); } @EventSourcingHandler public void on(AccountDebitedEvent accountDebitedEvent) { System.out.println("AccountDebitedEvent occured."); this.accountId =accountDebitedEvent.getId(); this.amount = this.amount.subtract(accountDebitedEvent.getAmount()); } } <file_sep>package com.bank.cqrs.query.query; import lombok.Data; @Data public class FindAccountByIdQuery { private String accountId; public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public FindAccountByIdQuery(String accountId) { super(); this.accountId = accountId; } } <file_sep>package com.bank.cqrs.query.repository; import org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension; import org.springframework.stereotype.Repository; import com.bank.cqrs.query.entity.Account; import org.springframework.data.jpa.repository.JpaRepository; @Repository public interface AccountRepository extends JpaRepository<Account, String>{ } <file_sep>package com.bank.cqrs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BankManagementDemoApplication { public static void main(String[] args) { SpringApplication.run(BankManagementDemoApplication.class, args); } } <file_sep>axon.serializer.general=jackson axon.serializer.events=jackson axon.serializer.messages=jackson
ec9535b1b6d872c30338536087238ee5b7d2ab44
[ "Java", "INI" ]
5
Java
m-elbastawisi/bank-management
e96a42884d5177e43440d6ce1864ddd3b5e05078
55bb1f3215110dec392073c90d67114d6c8e76c1
refs/heads/master
<file_sep># When done, submit this entire file to the autograder. # Part 1 def sum arr # YOUR CODE HERE arr.inject(0, :+) end def max_2_sum arr # YOUR CODE HERE arr.sort.last(2).inject(0, :+) end def sum_to_n? arr, n # YOUR CODE HERE arr.permutation(2).to_a.any? { |x| x.inject(0, :+) == n } end # Part 2 def hello(name) # YOUR CODE HERE "Hello, #{name}" end def starts_with_consonant? s # YOUR CODE HERE !!(s[0] =~ /[bcdfghjklmnprstvwxyz]+/i) end def binary_multiple_of_4? s # YOUR CODE HERE # A multiple of 4 in binary is any binary number that ends with 00 return true if s == "0" /^[10]*00$/.match(s) != nil end # Part 3 class BookInStock # YOUR CODE HERE def initialize(isbn, price) raise ArgumentError.new("ISBN is an empty string!") if isbn.empty? raise ArgumentError.new("Price should be greater than zero") if price <= 0 @isbn = isbn @price = price end attr_reader :isbn, :price def isbn=(isbn) raise ArgumentError.new("ISBN is an empty string!") if isbn.empty? @isbn = isbn end def price=(price) raise ArgumentError.new("Price should be greater than zero") if price <= 0 @price = price end def price_as_string format '$%.2f', @price end end
53f4213e80119313d0dd775a3acb3c453f1ec037
[ "Ruby" ]
1
Ruby
Abishalini/hw-ruby-intro
76ab6f0640c2c2760ea58f86b2cc4c03968fc872
48b219b91ec65df8bb96e2113b88a57bfa89b7c7
refs/heads/main
<repo_name>alsrua7222/SeleniumNaverCafeWrite<file_sep>/1.0.1/run.py from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys import pyperclip import time class Naver(): def __init__(self, mode = False): option = Options() if mode: option.add_argument('--headless') option.add_argument('window-size=1920x1080') option.add_argument("lang=ko_KR") option.add_argument("disable-gpu") # if mode: # self.add_argument('--headless') # self.add_argument('window-size=1920x1080') # self.add_argument("lang=ko_KR") # self.add_argument("disable-gpu") driver_dlr = 'module/chromedriver' self.driver = webdriver.Chrome(executable_path=driver_dlr, chrome_options=option) self.n_id = "" self.n_pw = "" self.title = "" self.content = "" self.sleep_sec = 0.5 # 19543191 = lol kor self.cafeID = 19543191 # 2 = 자유 게시판 self.menuID = 2 self.HeadlessMode = mode self.imgUrl = "" self.writerUrl = 'https://cafe.naver.com/ArticleWrite.nhn?m=write&clubid={0}&menuid={1}' self.login_err_dic = { # xPath 'Auth2' : '//*[@id="call_success"]/div[1]/label', 'Capture' : '//*[@id="captcha"]' } self.old_editor_iframe = 'cafe_main' def __del__(self): self.driver.close() self.driver.quit() def run(self, func): def wrapper(*args, **kwargs): try: print("Log: %s Started" % func.__name__) func(*args, **kwargs) except: print("Log: %s Error" % func.__name__) finally: self.sleep() return wrapper def sleep(self): time.sleep(self.sleep_sec) def has_xpath(self, xpath): try: self.driver.find_element_by_xpath(xpath) return True except: return False def login_err_chk(self): for i in self.login_err_dic: if self.has_xpath(self.login_err_dic[i]): print("login_err_chk: {}".format(i)) exit() def login(self): self.driver.get('https://nid.naver.com/nidlogin.login') self.sleep() e_id = self.driver.find_element_by_id('id') e_pw = self.driver.find_element_by_id('pw') e_id.clear() e_pw.clear() if self.HeadlessMode: # Headless Mode - 유료, 배포 전용 print("Headless mode 지원 불가") exit() else: # Not Headless Mode - 무료, 오픈 소스 전용 e_id.click() self.clipboard_input(self.n_id) e_pw.click() self.clipboard_input(self.n_pw) self.driver.find_element_by_class_name('btn_global').click() self.login_err_chk() def write(self): # 메인으로 작용할 함수. # 접속하려는 url에 cafeID와 menuID 포맷. url = 'https://cafe.naver.com/ArticleWrite.nhn?m=write&clubid={0}&menuid={1}'.format(self.cafeID, self.menuID) self.driver.get(url) self.sleep() # cafe_main iframe를 찾고 제목, 콘텐트를 설정한다. # self.driver.switch_to.frame(self.driver.find_element_by_id('cafe_main')) o_title = self.driver.find_element_by_id('subject') o_title.clear() o_title.send_keys(self.title) # How to use it? # 1. Smart Editor 2.0으로 만든 content(HTML)를 불러온다. # 2. innerHTML에 content를 넣어 추가한다. # 3. 대표 이미지를 설정하고 싶다면 사진 업로드를 추가해야 한다. self.driver.execute_script(self.innerHTML(self.content)) self.driver.switch_to.default_content() self.insertRPimg() self.submit() def submit(self): self.driver.switch_to.default_content() # self.driver.switch_to.frame(self.driver.find_element_by_id('cafe_main')) self.driver.find_element_by_id('cafewritebtn').click() def getIframes2Pagesource(self): iframes = self.driver.find_elements_by_css_selector('iframe') for i, iframe in enumerate(iframes): try: self.driver.switch_to.frame(iframes[i]) print("iframes[%d]'s has data" % i) print(self.driver.page_source) self.driver.switch_to.default_content() except: self.driver.switch_to.default_content() print("iframes[%d]'s None" % i) pass def clipboard_input(self, user_input): temp_copy = pyperclip.paste() pyperclip.copy(user_input) ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform() pyperclip.copy(temp_copy) # @run # def S2C(self, content = "Hello World"): # # String to Content(HTML) # tmp = "" # return tmp def innerHTML(self, content: str): iframe = self.driver.find_element_by_css_selector('iframe') self.Check_iframe() self.driver.switch_to.frame(iframe) time.sleep(1) # 평균 1초로 잡아줌. base = "document.getElementsByTagName('body')[0].innerHTML = \'{}\'".format(content) return base def insertRPimg(self): if not self.imgUrl: return self.driver.find_element_by_xpath('//*[@id="iImage"]/a').click() self.sleep() self.driver.switch_to.window(self.driver.window_handles[-1]) self.sleep() self.driver.find_element_by_xpath('//*[@id="pc_image_file"]').send_keys(self.imgUrl) self.sleep() self.driver.find_element_by_xpath('/html/body/div[3]/header/div[2]/button').click() self.driver.switch_to.window(self.driver.window_handles[0]) def Check_iframe(self): iframes = self.driver.find_elements_by_css_selector('iframe') for i, iframe in enumerate(iframes): try: print('%d번째 iframe 입니다.' % i) self.driver.switch_to.frame(iframes[i]) print(self.driver.page_source) self.driver.switch_to.default_content() except: self.driver.switch_to.default_content() print('pass by except: iframes[%d' % i) pass def main(self): self.login() self.driver.get_screenshot_as_file("capture.png") self.write() time.sleep(1) # self.run(self.login) # self.run(self.write)<file_sep>/run.py import selenium from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select import pyperclip import time from pyvirtualdisplay import Display option = Options() option.add_argument('window-size=1920x1080') option.add_argument('--headless') option.add_argument("lang=ko_KR") option.add_argument("disable-gpu") # display = Display(visible=0, size=(1920, 1080)) # display.start() chrome_dir = 'module/chromedriver' # driver = webdriver.Chrome(executable_path=chrome_dir, chrome_options=option) driver = webdriver.Chrome(executable_path=chrome_dir) # driver.implicitly_wait(2) driver.get('https://www.naver.com/') driver.get_screenshot_as_file('capture0.png') def sleep(s=0.5): time.sleep(s) def has_xpath(xpath): try: driver.find_element_by_xpath(xpath) return True except: return False id1 = 'alsrua7222' pw1 = '******' url_cafe = 'https://cafe.naver.com/******' login_err = { 'Auth2': '//*[@id="call_success"]/div[1]/label', 'Capture': '//*[@id="captcha"]' } login_btn = driver.find_element_by_class_name('link_login') login_btn.click() sleep() tag_id = driver.find_element_by_id('id') tag_pw = driver.find_element_by_id('pw') tag_id.clear() tag_id.click() pyperclip.copy(id1) #tag_id.send_keys(pyperclip.paste()) 캡챠 방지 ㅆㅂ # tag_id.send_keys(Keys.CONTROL, 'v') ActionChains(driver).key_down(Keys.CONTROL).send_keys('V').key_up(Keys.CONTROL).perform() sleep() driver.get_screenshot_as_file('capture11.png') tag_pw.click() pyperclip.copy(pw1) #tag_pw.send_keys(pyperclip.paste()) 캡챠 방지 ㅆㅂ # tag_pw.send_keys(Keys.CONTROL, 'v') ActionChains(driver).key_down(Keys.CONTROL).send_keys('V').key_up(Keys.CONTROL).perform() sleep(3) login_btn = driver.find_element_by_class_name('btn_global') login_btn.click() sleep() print("Login Before") if has_xpath(login_err['Auth2']) == True: print("2차 인증 걸려있습니다.") exit() if has_xpath(login_err['Capture']) == True: print("캡챠 방지 걸려있습니다.") exit() # 카폐에 들어가서 글쓰기 버튼 누르기 # driver.get(url_cafe) # write_btn = driver.find_element_by_xpath('//*[@id="cafe-info-data"]/div[4]/a') # write_btn.click() # sleep() # 글쓰기 화면 탭으로 전환하기 # last_tap = driver.window_handles[-1] # driver.switch_to.window(window_name=last_tap) # #driver.close() # sleep() #iframe 값을 전혀 알 수 없음 #출처: https://dejavuqa.tistory.com/198 # iframes = driver.find_elements_by_css_selector('iframe') # print("iframes: {}".format(len(iframes))) # for i, iframe in enumerate(iframes): # try: # print('%d번째 iframe 입니다.' % i) # driver.switch_to.frame(iframes[i]) # print(driver.page_source) # driver.switch_to.default_content() # except: # driver.switch_to.default_content() # print('pass by except: iframes[%d' % i) # pass print("Login After") driver.get('https://cafe.naver.com/******?iframe_url=%2FArticleWrite.nhn%3Fclubid%3D19543191%26m%3Dwrite') sleep() driver.get_screenshot_as_file('capture2.png') # oEditor = driver.find_element_by_xpath('//*[@id="app"]/div/div/section/div/div[1]/div/div/button[2]') # oEditor.send_keys(Keys.ENTER) # oEditor_goto = driver.find_element_by_xpath('//*[@id="app"]/div/div/section/div/div[3]/div[6]/div/div/div[2]/div[2]/a') # oEditor_goto.send_keys(Keys.ENTER) # sleep() # 구버전 프레임 번호 print("Access Cafe Write") print(driver.window_handles) iframes = driver.find_elements_by_css_selector('iframe') print("iframes: {}".format(len(iframes))) for i, iframe in enumerate(iframes): try: print('%d번째 iframe 입니다.' % i) driver.switch_to.frame(iframes[i]) print(driver.page_source) driver.switch_to.default_content() except: driver.switch_to.default_content() print('pass by except: iframes[%d' % i) pass driver.switch_to.frame(driver.find_element_by_id('cafe_main')) # driver.switch_to.frame('cafe_main') # 구버전 글쓰기 메뉴 카테고리 print("Category") menu = Select(driver.find_element_by_id('boardCategory')) menu.select_by_visible_text('자유 게시판') # 구버전 글쓰기 제목 print("Title init") title = driver.find_element_by_xpath('//*[@id="subject"]') title.clear() title.send_keys('Hello World') sleep() #직접 내용 쓰고 싶으면 써라 def innerHTML(exStr): base = "document.getElementsByTagName('body')[0].innerHTML = \'{}\'".format(exStr) return base def image(): print("ImageButton") Image = driver.find_element_by_xpath('//*[@id="iImage"]/a') Image.click() sleep() # driver.get_screenshot_as_file('capture1.png') print("windowHandler") last_tap = driver.window_handles[-1] driver.switch_to.window(window_name=last_tap) # driver.get_screenshot_as_file('capture2.png') sleep() print("urlImg") urlimg = "C:\\Usr\\selenium\\images0.png" driver.find_element_by_xpath('//*[@id="pc_image_file"]').send_keys(urlimg) sleep() #나는 이미지를 본문에 삽입하기로 함. image() driver.find_element_by_xpath('/html/body/div[3]/header/div[2]/button').click() sleep(2) # driver.close() driver.switch_to.window(driver.window_handles[0]) driver.switch_to.frame(driver.find_element_by_id('cafe_main')) sleep() # driver.get_screenshot_as_file('capture3.png') print(driver.window_handles) driver.find_element_by_xpath('//*[@id="cafewritebtn"]').click() sleep(1) driver.close() driver.quit() # display.stop() # driver.switch_to.frame(driver.find_element_by_id('cafe_main')) # driver.find_element_by_xpath('//*[@id="cafewritebtn"]').click() # iframes = driver.find_element_by_css_selector('iframe') # driver.switch_to.frame(iframes) # content = driver.find_element_by_id('textbox') # driver.execute_script(innerHTML('Hello World')) # content = driver.find_element_by_id('textbox') # pyperclip.copy("Test") # content.send_keys(Keys.CONTROL, 'V') # #driver.get_screenshot_as_file('capture.png') # list_btn = driver.find_element_by_xpath('//*[@id="app"]/div/div/section/div/div[2]/div[1]/div[1]/div[1]/div[1]/div/div[1]/button') # #드랍다운 메뉴 버튼일 경우, click() 호출하면 안된다. # #즉, send_keys(Keys.ENTER)로 호출한다. # #출처: https://wkdtjsgur100.github.io/selenium-does-not-work-to-click/ # list_btn.send_keys(Keys.ENTER) # sleep() # # list_items = driver.find_element_by_xpath('//*[@id="app"]/div/div/section/div/div[2]/div[1]/div[1]/div[1]/div[1]/div/div[2]/ul/li[9]/button') # list_items.click() # sleep() # # title = driver.find_element_by_xpath('//*[@id="app"]/div/div/section/div/div[2]/div[1]/div[1]/div[2]/div/textarea') # title.send_keys(Keys.ENTER) # pyperclip.copy('Test') # title.send_keys(Keys.CONTROL, 'V') # sleep() # title.send_keys(Keys.TAB, Keys.CONTROL, 'V') # driver.switch_to.frame(iframes[4]) # content = driver.find_element_by_xpath('/html/body') # pyperclip.copy('Hello World') # driver.execute_script("document.querySelector('div.se-module-text').textContent = 'sdfsadfsadfsfdgsdf'") # sleep() # driver.switch_to.default_content() #driver.switch_to.frame(driver.find_element_by_id('SmartEditor')) # context = driver.find_element_by_xpath('//*[@id="SE-ee59c2c0-a40e-4ca4-9f63-be316b9f084a"]/div[1]/div/div[1]/div[2]/section/div[1]') # context.click() # pyperclip.copy('Python Selenium Test') # context.send_keys(Keys.CONTROL, 'V') # sleep() # # send_btn = driver.find_element_by_xpath('//*[@id="app"]/div/div/section/div/div[1]/div/a') # send_btn.click() # sleep()<file_sep>/README.md # SeleniumNaverCafeWrite(네이버카페에서 자동 글쓰기(Not Headless)) ![logo](./title.png/) ___ ## _Warning!_ > 재미로 즐기는 것이므로, 악질적인 홍보와 같은 광고 산업에 악용하면 안됨. > 개인 책임임. > 코드는 얘를 싸지른거마냥 복잡하게 구성되었음. ## _Modules_ > ### _Terminal_ > ```pip3 install pyperclip ``` > ```pip3 install selenium ``` ## _How to use it?_ > run.py를 직접 수정하면 된다. > 각 소스 코드마다 주석처리 되어 있으니, 참고 바람 > 각 버전 main.py 참고 > #### 1.0.1 > > ```naver = Naver()``` Not Headless node > > ```naver = Naver(True)``` Headless mode > > ```naver.n_id = "INPUT_YOUR_ID_STR"``` 네이버 아이디 > > ```naver.n_pw = "INPUT_YOUR_PW_STR"``` 네이버 비밀번호 > > ```naver.cafeID = INPUT_CAFE_ID_INT``` 가입된 카페 번호 > > ```naver.menuID = INPUT_MENU_ID_INT``` 가입된 카페의 메뉴 번호 > > ```naver.title = "INPUT_TITLE_STR"``` 글쓰기 제목 > > ```naver.content = "INPUT_CONTENT_HTML_STR"``` 글쓰기 본문(내용) > > ```naver.imgUrl = "INPUT_YOUR_IMAGE_STR"``` 대표 이미지 설정 (절대 경로만 가능. Ex) "C:\\Users\\Project_selenium\\sample.png") > > ```naver.sleep_sec = INPUT_SLEEP_INT``` 지연 시간(똥컴은 3초, 보통컴은 0.5 ~ 1초, 쩌는 컴은 0.1 ~ 0.5초 추천), Default값은 0.5초로 되어 있음. > > ```naver.main()``` 앱 실행 함수 > #### 1.0.2 > > ```naver.BTime = "INPUT_YOU_WANT_TIME"``` 예약 시간 Ex) "" 예약X, "23:53:52" 예약됨. 반드시 ':' 넣어서 시간 구분해야 함 > #### _Chorme Current Version(2020/12/26)_ > > Driver.exe 파일은 현재 파일에 module 폴더에 넣어야 함. > > Ex) ../selenium/module/ 에 넣기. > > driver.exe 파일 명을 바꾸면 안돼요. (Don't renaming the driver.exe) > > 버전에 맞는 각 브라우저 드라이버를 설치 필요.(ex: Chrome) > > ![](./ver.PNG) > > ```Current Version: 87.0.4280.88``` > #### _How to Content(HTML) Create_ > > content를 HTML양식으로 꾸미고 싶다면? > > 카페 글쓰기 본문 내용을 제대로 꾸미고 싶다면? > > [SmartEditor 2.0 Demo]에 들어가서 본문 내용을 마음대로 적고 > > 복사하고 content 변수의 ""(큰따옴표)안에 붙여넣으면 된다. > > 오른쪽 밑을 보면 [Editor] | HTML | TEXT가 보일 것이다. > > Editor에서 마음대로 작성한 후에, HTML 모드로 바꾸면 내용들이 HTML 양식대로 변환한다. ## _Comment_ > 요즘 들어서 더럽히는 불법 광고들이 판치기 때문에 신버전에 대한 소스 코드를 공개하지 않습니다. ## _Links_ > [SmartEditor 2.0](https://github.com/naver/smarteditor2) > [SmartEditor 2.0 Demo](http://naver.github.io/smarteditor2/demo/) ## _update_ > #### 1.0.0(2020/12/25) > > 애새끼마냥 싸지러놓음 코드가 복잡함. > #### 1.0.1(2020/12/27) > > 클래스로 싹다 정리한 후, 가이드 라인을 추가함. > #### 1.0.2(2020/12/27) > > Timer기능 추가 > #### 1.0.3(2021/01/15) > > 곧 스마트에디터 2.0 서비스 종료한다. > > 3.0에 맞는 코드를 정리. > > 근데 정보가 별로 없어서 업로드 하지 않고 개인으로 가지고 있음. > > 추가 코멘트에 확인 부탁. ## _Donate_ > Headless 기능을 쓸 수 있습니다. > Headless 기능: 백그라운드에서 실행하기 때문에, 실행 도중에 다른 작업을 수행할 수 있습니다. 속도가 빠릅니다. (그래픽 처리 같은게 필요없어져서 그런 듯) <file_sep>/1.0.1/main.py from run import Naver if __name__ == '__main__': # 객체 선언 naver = Naver() # 필요 정보 설정 naver.n_id = "naver0123" naver.n_pw = "<PASSWORD>" naver.cafeID = 12345 # 카폐 번호 naver.menuID = 1 # 게시판(메뉴) 번호 naver.title = "[Title] Selenium Test" naver.content = "[Content] Selenium Test<p>Hello World</p><p>CUCUUC</p>" # imgUrl 필요 하면 무조건 절대경로 삽입 # naver.imgUrl = "C:\\Users\\selenium\\sample.png" # imgUrl 필요하지 않으면 ""로 처리 naver.imgUrl = "" naver.sleep_sec = 1 # 똥컴 = 1 ~ 3초, 보통 = 0.5 ~ 1초, 짱 = 0.1 ~ 0.5 # 실행 # (총 걸리는 시간) = (함수 호출 횟수) x (sleep_sec)ms naver.main()
a751fccf84131bdde4cf50f08db94456c4a47e99
[ "Markdown", "Python" ]
4
Python
alsrua7222/SeleniumNaverCafeWrite
63cfc5df0c9487048e50fef9dbc9d8e67071e75b
924d954df8e6c8469044357fe321283e615a4706
refs/heads/master
<repo_name>dferguso/ExData_Plotting1<file_sep>/plot1.R rm(list=ls()) ## memory estimation assuming all 9 columns are numeric ## this estimate is not very accurate based on results from object.size() fLines = 2075259 ## Number of rows fCol = 9 ## Number of columns ByteSize = 8 ## 8bytes /numeric bYtesperMB = 1024*1024 ## byts per MegaByte memSize = fLines*fCol*ByteSize/bYtesperMB cat("Memory size required = ", memSize, "MB") ## Read in the first few lines of the table to determine the ## classes for each column library(sqldf) ## Need this for read.csv.sql used below tabROws <- read.table("data/household_power_consumption.txt", header = TRUE, sep=";" , nrow=5) ## pull in a small number of rows to check the variable class classes <-sapply(tabROws, class) ## Variables defining the class for each column ## read subset of tabAll<-read.csv.sql("data/household_power_consumption.txt", header=TRUE, sep=";", colClasses=classes, sql="Select * from file where Date = '1/2/2007' OR Date = '2/2/2007'") closeAllConnections() tabAll[as.character(tabAll)=="?"]<-NA dt=paste(tabAll$Date, tabAll$Time) dateTime <- strptime(dt, format="%d/%m/%Y %H:%M:%S") pData<-cbind(dateTime, tabAll) rm(tabROws, tabAll, classes) ## Plot 1 hist(pData$Global_active_power, breaks = 14, col = "red", xlab="Global Active Power (kilowatts)", main="Global Active Power") dev.copy(png, filename = "Plot1.png", width = 480, height = 480, units = "px", pointsize = 12) dev.off() dev.off()<file_sep>/plot4.R rm(list=ls()) ## memory estimation assuming all 9 columns are numeric ## this estimate is not very accurate based on results from object.size() fLines = 2075259 ## Number of rows fCol = 9 ## Number of columns ByteSize = 8 ## 8bytes /numeric bYtesperMB = 1024*1024 ## byts per MegaByte memSize = fLines*fCol*ByteSize/bYtesperMB cat("Memory size required = ", memSize, "MB") ## Read in the first few lines of the table to determine the ## classes for each column library(sqldf) ## Need this for read.csv.sql used below tabROws <- read.table("data/household_power_consumption.txt", header = TRUE, sep=";" , nrow=5) ## pull in a small number of rows to check the variable class classes <-sapply(tabROws, class) ## Variables defining the class for each column ## read subset of tabAll<-read.csv.sql("data/household_power_consumption.txt", header=TRUE, sep=";", colClasses=classes, sql="Select * from file where Date = '1/2/2007' OR Date = '2/2/2007'") closeAllConnections() tabAll[as.character(tabAll)=="?"]<-NA dt=paste(tabAll$Date, tabAll$Time) dateTime <- strptime(dt, format="%d/%m/%Y %H:%M:%S") pData<-cbind(dateTime, tabAll) rm(tabROws, tabAll, classes) ## Plot 4 par(mfrow=c(2,2)) par(mar=c(4,4,2,2)); # Plot 1 plot(pData$dateTime, pData$Global_active_power, type="l", xlab="", ylab="Global Active Power") # Plot 2 plot(pData$dateTime, pData$Voltage, type="l", xlab="datetime", ylab="Voltage", col="black") # Plot 3 plot(pData$dateTime, pData$Sub_metering_1, type="l", xlab="", ylab="Energy sub metering", col="black") lines(pData$dateTime, pData$Sub_metering_2, type="l", xlab="", ylab="", col="red") lines(pData$dateTime, pData$Sub_metering_3, type="l", xlab="", ylab="", col="blue") #legend(pData$dateTime[2000], 38, legend("topright", inset=0.1, lty = 1, col=c("black", "red", "blue"), bty = "n", cex = 0.65, legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")) # Plot 4 plot(pData$dateTime, pData$Global_reactive_power, type="l", xlab="datetime", ylab="Global_reactive_power", col="black") dev.copy(png, filename = "Plot4.png", width = 480, height = 480, units = "px", pointsize = 12) dev.off() dev.off()
2bdb60f717762605529899c473cb4a839f2ec1e8
[ "R" ]
2
R
dferguso/ExData_Plotting1
e21f292cb21c5e930c1bcd665296721a6233852e
f8a4a3d20ac9c5aa561d779e118afef38d64de0d
refs/heads/master
<file_sep>package com.tencent.nemo; import com.sun.javafx.util.Logging; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.filters.Watermark; import net.coobird.thumbnailator.geometry.Positions; import javax.imageio.ImageIO; import javax.imageio.stream.ImageOutputStream; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.*; public class PicMain extends HttpServlet { private static final String TAG = "PicMain"; @Override public void init() throws ServletException { super.init(); Logging.getJavaFXLogger().info(TAG + "[init()]"); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); Logging.getJavaFXLogger().info(TAG + "[init(ServletConfig config)]"); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Logging.getJavaFXLogger().info(TAG + "[service]"); ServletContext context = getServletContext(); BufferedImage oriImg = ImageIO.read(req.getInputStream()); File dir = new File(context.getRealPath("WEB-INF").concat("/pics/ori/")); if(!dir.exists()){ dir.mkdir(); } File originalFile = new File(context.getRealPath("WEB-INF").concat("/pics/ori/" + System.currentTimeMillis() + ".png")); if(!originalFile.exists()){ originalFile.createNewFile(); } FileOutputStream fOut = new FileOutputStream(originalFile); ImageIO.write(oriImg,"png",fOut); String waterMarkPicPath = context.getRealPath("WEB-INF").concat("/pics/google.png"); BufferedImage bImg = ImageIO.read(new FileInputStream(waterMarkPicPath)); Watermark wm = new Watermark(Positions.BOTTOM_CENTER, bImg, 0.5f); BufferedImage oriPicsWithWatermark = Thumbnails.of(oriImg) .watermark(wm) .size(oriImg.getWidth(), oriImg.getHeight()) .asBufferedImage(); OutputStream out = resp.getOutputStream(); byte[] temp = toByteArray(getImageStream(oriPicsWithWatermark)); out.write(temp); fOut.close(); out.flush(); out.close(); } public static byte[] toByteArray(InputStream in) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int readSize; byte[] data = new byte[2 * 1024]; while ((readSize = in.read(data)) != -1) { buffer.write(data, 0, readSize); } buffer.flush(); return buffer.toByteArray(); } public InputStream getImageStream(BufferedImage bimage) { InputStream is = null; ByteArrayOutputStream bs = new ByteArrayOutputStream(); ImageOutputStream imOut; try { imOut = ImageIO.createImageOutputStream(bs); ImageIO.write(bimage, "png", imOut); is = new ByteArrayInputStream(bs.toByteArray()); } catch (IOException e) { e.printStackTrace(); } return is; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); Logging.getJavaFXLogger().info(TAG + "[doGet]"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); Logging.getJavaFXLogger().info(TAG + "[doPost]"); } } <file_sep>package com.tencent.nemo; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class Test { static final String URL = "http://localhost:8080/first_w_war_exploded/aa"; public static void uploadPic(){ try { URL url = new URL(URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.addRequestProperty("User-Agent", "UnionSDK"); conn.addRequestProperty("Content-Type", "application/octet-stream"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
809eda9f154ec7ce9dd8ac41b08f3ccdcc1bc94e
[ "Java" ]
2
Java
hitYOUcry/litelite
b3e05da26e2dcdc2155d86dc91879abe0639f962
43418cc73363856e07b10f02f1f88eb856dedb05
refs/heads/master
<repo_name>numb3rcruncher52/GettingAndCleaningDataCourseProject<file_sep>/run_analysis.R ## run_analysis.R ## ## Author: Max ## Date: 4/14/2016 ## ## This script downloads accelerometer data from the Samsung Galaxy S ## smartphone and cleans it up for analysis for the Getting and Cleaning ## data course project from Coursera library(dplyr) ## Load the subject, activity, and feature data for both the test and training ## data sets from the UCI HAR Dataset in the project directory test_features <- read.table("./UCI HAR Dataset/test/X_test.txt") test_activities <- read.table("./UCI HAR Dataset/test/y_test.txt") test_subject <- read.table("./UCI HAR Dataset/test/subject_test.txt") test <- cbind(test_subject,test_activities,test_features) train_features <- read.table("./UCI HAR Dataset/train/X_train.txt") train_activities <- read.table("./UCI HAR Dataset/train/y_train.txt") train_subject <- read.table("./UCI HAR Dataset/train/subject_train.txt") train <- cbind(train_subject,train_activities,train_features) feature_names <- as.character(read.table("./UCI HAR Dataset/features.txt")$V2) feature_names <- c("subject","activity",feature_names) ## Merge training and test sets to get one dataframe data <- rbind(train,test) ## Extract only mean and standard deviation for each measurement final_features <- grep("-mean\\(|-std\\(|^subject$|^activity$",feature_names) data <- data[,final_features] ## Relabel the variables to be descriptive feature_names <- feature_names[final_features] # replace 't' with time and 'f' with fourier feature_names <- gsub("^t","time",feature_names) feature_names <- gsub("^f","fourier",feature_names) # replace 'Acc' with accelerometer and 'Gyro' with gyroscope feature_names <- gsub("Acc", "Accelerometer", feature_names) feature_names <- gsub("Gyro", "Gyroscope", feature_names) # replace 'Mag' with magnitude feature_names <- gsub("Mag", "Magnitude", feature_names) # remove hyphens from variable names feature_names <- gsub("-mean\\(\\)-?", "Mean", feature_names) feature_names <- gsub("-std\\(\\)-?", "StandardDeviation", feature_names) names(data) <- feature_names ## Change activity names to be more descriptive activity_names <- read.table("./UCI HAR Dataset/activity_labels.txt") data <- left_join(data,activity_names, by = c("activity" = "V1")) data <- data %>% mutate(activity = V2) %>% select(-V2) ## Create another tidy data set with the average of each variable for each ## activity and subject tidy <- data %>% group_by(activity, subject) %>% summarise_each(funs(mean)) <file_sep>/README.md # Course Project for the Coursera Getting and Cleaning Data Course This Github repo houses the data and scripts necessary to complete the Coursera "Getting and Cleaning Data" Course Project. The following files are included in the repo: README.md: The instruction file you are currently reading CodeBook.Rmd: A code book explaining the data used in this project and the transformations used to tidy it run_analysis.R: The single script that was run to clean the data UCI HAR Dataset: A collection of training and test data from the accelerometer of a Samsung Galaxy S used while various subjects performed different activities with the smartphone on their person <file_sep>/CodeBook.Rmd --- title: "CodeBook" author: "Max" date: "April 14, 2016" output: html_document --- This is a codebook that describes the variables, the data, and any transformations or work performed while cleaning up the Samsung Galaxy S smartphone accelerometer data for the Getting and Cleaning Data Course Project #From the README included with the dataset: The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, we captured 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers was selected for generating the training data and 30% the test data. The sensor signals (accelerometer and gyroscope) were pre-processed by applying noise filters and then sampled in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window). The sensor acceleration signal, which has gravitational and body motion components, was separated using a Butterworth low-pass filter into body acceleration and gravity. The gravitational force is assumed to have only low frequency components, therefore a filter with 0.3 Hz cutoff frequency was used. From each window, a vector of features was obtained by calculating variables from the time and frequency domain. See 'features_info.txt' for more details. For each record it is provided: ====================================== - Triaxial acceleration from the accelerometer (total acceleration) and the estimated body acceleration. - Triaxial Angular velocity from the gyroscope. - A 561-feature vector with time and frequency domain variables. - Its activity label. - An identifier of the subject who carried out the experiment. The dataset includes the following files: ========================================= - 'README.txt' - 'features_info.txt': Shows information about the variables used on the feature vector. - 'features.txt': List of all features. - 'activity_labels.txt': Links the class labels with their activity name. - 'train/X_train.txt': Training set. - 'train/y_train.txt': Training labels. - 'test/X_test.txt': Test set. - 'test/y_test.txt': Test labels. The following files are available for the train and test data. Their descriptions are equivalent. - 'train/subject_train.txt': Each row identifies the subject who performed the activity for each window sample. Its range is from 1 to 30. - 'train/Inertial Signals/total_acc_x_train.txt': The acceleration signal from the smartphone accelerometer X axis in standard gravity units 'g'. Every row shows a 128 element vector. The same description applies for the 'total_acc_x_train.txt' and 'total_acc_z_train.txt' files for the Y and Z axis. - 'train/Inertial Signals/body_acc_x_train.txt': The body acceleration signal obtained by subtracting the gravity from the total acceleration. - 'train/Inertial Signals/body_gyro_x_train.txt': The angular velocity vector measured by the gyroscope for each window sample. The units are radians/second. Notes: ====== - Features are normalized and bounded within [-1,1]. - Each feature vector is a row on the text file. For more information about this dataset contact: <EMAIL> #The features selected by the run_analysis.R script: [1] "activity" - name of activity subject performed [2] "subject" - the subject in the study [3] "timeBodyAccelerometerMeanX" [4] "timeBodyAccelerometerMeanY" [5] "timeBodyAccelerometerMeanZ" [6] "timeBodyAccelerometerStandardDeviationX" [7] "timeBodyAccelerometerStandardDeviationY" [8] "timeBodyAccelerometerStandardDeviationZ" [9] "timeGravityAccelerometerMeanX" [10] "timeGravityAccelerometerMeanY" [11] "timeGravityAccelerometerMeanZ" [12] "timeGravityAccelerometerStandardDeviationX" [13] "timeGravityAccelerometerStandardDeviationY" [14] "timeGravityAccelerometerStandardDeviationZ" [15] "timeBodyAccelerometerJerkMeanX" [16] "timeBodyAccelerometerJerkMeanY" [17] "timeBodyAccelerometerJerkMeanZ" [18] "timeBodyAccelerometerJerkStandardDeviationX" [19] "timeBodyAccelerometerJerkStandardDeviationY" [20] "timeBodyAccelerometerJerkStandardDeviationZ" [21] "timeBodyGyroscopeMeanX" [22] "timeBodyGyroscopeMeanY" [23] "timeBodyGyroscopeMeanZ" [24] "timeBodyGyroscopeStandardDeviationX" [25] "timeBodyGyroscopeStandardDeviationY" [26] "timeBodyGyroscopeStandardDeviationZ" [27] "timeBodyGyroscopeJerkMeanX" [28] "timeBodyGyroscopeJerkMeanY" [29] "timeBodyGyroscopeJerkMeanZ" [30] "timeBodyGyroscopeJerkStandardDeviationX" [31] "timeBodyGyroscopeJerkStandardDeviationY" [32] "timeBodyGyroscopeJerkStandardDeviationZ" [33] "timeBodyAccelerometerMagnitudeMean" [34] "timeBodyAccelerometerMagnitudeStandardDeviation" [35] "timeGravityAccelerometerMagnitudeMean" [36] "timeGravityAccelerometerMagnitudeStandardDeviation" [37] "timeBodyAccelerometerJerkMagnitudeMean" [38] "timeBodyAccelerometerJerkMagnitudeStandardDeviation" [39] "timeBodyGyroscopeMagnitudeMean" [40] "timeBodyGyroscopeMagnitudeStandardDeviation" [41] "timeBodyGyroscopeJerkMagnitudeMean" [42] "timeBodyGyroscopeJerkMagnitudeStandardDeviation" [43] "fourierBodyAccelerometerMeanX" [44] "fourierBodyAccelerometerMeanY" [45] "fourierBodyAccelerometerMeanZ" [46] "fourierBodyAccelerometerStandardDeviationX" [47] "fourierBodyAccelerometerStandardDeviationY" [48] "fourierBodyAccelerometerStandardDeviationZ" [49] "fourierBodyAccelerometerJerkMeanX" [50] "fourierBodyAccelerometerJerkMeanY" [51] "fourierBodyAccelerometerJerkMeanZ" [52] "fourierBodyAccelerometerJerkStandardDeviationX" [53] "fourierBodyAccelerometerJerkStandardDeviationY" [54] "fourierBodyAccelerometerJerkStandardDeviationZ" [55] "fourierBodyGyroscopeMeanX" [56] "fourierBodyGyroscopeMeanY" [57] "fourierBodyGyroscopeMeanZ" [58] "fourierBodyGyroscopeStandardDeviationX" [59] "fourierBodyGyroscopeStandardDeviationY" [60] "fourierBodyGyroscopeStandardDeviationZ" [61] "fourierBodyAccelerometerMagnitudeMean" [62] "fourierBodyAccelerometerMagnitudeStandardDeviation" [63] "fourierBodyBodyAccelerometerJerkMagnitudeMean" [64] "fourierBodyBodyAccelerometerJerkMagnitudeStandardDeviation" [65] "fourierBodyBodyGyroscopeMagnitudeMean" [66] "fourierBodyBodyGyroscopeMagnitudeStandardDeviation" [67] "fourierBodyBodyGyroscopeJerkMagnitudeMean" [68] "fourierBodyBodyGyroscopeJerkMagnitudeStandardDeviation" # Transformations done in the run_analysis.R script: 1. Combining the X_test.txt and X_train.txt files to get one comprehensive set of data 2. Extracted only the accelerometer and gyroscope mean and standard deviation measurements 3. Changed the variable names of each measurement to be more descriptive and to remove any special characters 4. Replaced the activity code with a descriptive activity name 5. Created an additional tidy data set that calculates the mean of each measurement for each activity-subject combination
42baa975cefff2ac6d5e85fb65c406e6050c9610
[ "Markdown", "R", "RMarkdown" ]
3
R
numb3rcruncher52/GettingAndCleaningDataCourseProject
b6d2ad176d1d5bf18630301762c536dc07c8780e
7444fa9dab37349159534a47ea6d6d7f0cbaef02
refs/heads/master
<repo_name>Justduma/Trattoria<file_sep>/build/js/main.js // open/close popup var catch_event = document.querySelector('.slaider'), popup = document.querySelector('.popup'), popup_close_btn = document.querySelector('.popup__close-btn'); var temp_popup_class = ''; catch_event.addEventListener('click', function(event) { temp_popup_class = event.target.name; if (event.target.name && event.target.tagName == 'BUTTON') { event.preventDefault(); popup.classList.add(event.target.name); } }); popup_close_btn.addEventListener('click', function(event) { popup.classList.remove(temp_popup_class); }); //slaider var slaider = document.querySelector('.slaider'), radio_left = document.querySelector('.slaider__radio--left input'), radio_right = document.querySelector('.slaider__radio--right input'), field = document.querySelector('.slaider__list'); function addClass(cls) { field.classList.remove('slaider-1', 'slaider-2', 'slaider-tb-1', 'slaider-tb-2', 'slaider-tb-3', 'slaider-mb-1', 'slaider-mb-2', 'slaider-mb-3', 'slaider-mb-4', 'slaider-mb-5', 'slaider-mb-6'); field.classList.add(cls); } slaider.addEventListener('click', function(event) { var number = event.target.getAttribute('data-number'); if (!number) return; var field_width = parseInt(getComputedStyle(slaider).width); if (field_width > 900) { if (number == 11 || number == 21) { addClass('slaider-1') radio_left.checked = true; } if (number == 12 || number == 22) { addClass('slaider-2') radio_right.checked = true; } return } if (field_width <= 900 && field_width > 680) { if (number == 11) { if (field.classList[1].slice(-1) == 1) return addClass('slaider-tb-' + (+field.classList[1].slice(-1) - 1)) } if (number == 12) { if (field.classList[1].slice(-1) == 3) return addClass('slaider-tb-' + (+field.classList[1].slice(-1) + 1)) } return } if (field_width <= 680) { if (number == 11) { if (field.classList[1].slice(-1) == 1) return addClass('slaider-mb-' + (+field.classList[1].slice(-1) - 1)) } if (number == 12) { if (field.classList[1].slice(-1) == 6) return addClass('slaider-mb-' + (+field.classList[1].slice(-1) + 1)) } return } }); <file_sep>/gulpfile.js var gulp = require('gulp'), sass = require('gulp-sass'), browserSync = require('browser-sync'), autoprefixer = require('gulp-autoprefixer'), cssmin = require('gulp-cssmin'); var path = { src: { html: 'dev/*.html', js: 'dev/js/main.js', style: 'dev/scss/style.scss', img: 'dev/img/**/*.*', fonts: 'dev/fonts/**/*.*' }, build: { html: 'build', js: 'build/js/', css: 'build/css/', img: 'build/img/', fonts: 'build/fonts/' }, watch: { html: 'dev/**/*.html', js: 'dev/js/**/*.js', style: 'dev/scss/**/*.scss', img: 'dev/img/**/*.*', fonts: 'dev/fonts/**/*.*' } }; gulp.task('html', function() { gulp.src(path.src.html) .pipe(gulp.dest(path.build.html)) .pipe(browserSync.reload({ stream: true })) }); gulp.task('sass', function() { return gulp.src(path.src.style) .pipe(sass()) .pipe(gulp.dest(path.build.css)) .pipe(browserSync.reload({ stream: true })) }); gulp.task('jscript', function() { gulp.src(path.src.js) .pipe(gulp.dest(path.build.js)) .pipe(browserSync.reload({ stream: true })) }); gulp.task('watch', ['browserSync', 'sass', 'html', 'jscript'], function() { gulp.watch(path.watch.html, ['html']); gulp.watch(path.watch.style, ['sass']); gulp.watch(path.watch.js, ['jscript']); }) gulp.task('browserSync', function() { browserSync({ server: { baseDir: 'build' }, }) });
bd6db15887dd724f6b6b630e196bd6885f5f5e1e
[ "JavaScript" ]
2
JavaScript
Justduma/Trattoria
3d9f72aeb15179bdd0ad11aa19decafd6519b453
c47f594a9f32b30d35592c006bf4e978e61180cc
refs/heads/master
<repo_name>DineshShelke/LoginSignupFragment<file_sep>/README.md #Login-and-Signup-in-Android **Description**: I have developed below three modules in android: - User Signup - User Login - Initial Setup (Welcome Screen) The User Signup module creates a new user in the SQLite database. Once registered, users can login with their credentials. After the user logs in, he will be redirected to the initial setup page. I have made use of following components while developing this project (as per the requirement): - Toast messages – Used toast messages to display errors (like ‘username and/or password don’t match’, ‘All fields are required’) and success messages like ‘Registration success!!’. - TextViews – Used text views as an input fields for Email, Password, Full Name, age and telephone number. - ImageButtonView – On click of this component, user gets option to add his recurring bills) please note that storing this bills data in the database is a future scope ). - Buttons – Use standard buttons that enables user to sign up, log me and logout from the application. - Dialogs- User gets an alert dialog box when the logout button is pressed. On clicking ‘yes’, user is logged out from application. - Action Bar – The logout button is placed over the action bar using menu inflater. - Fragments – Used fragment to provide a lightweight UI throughout the application (explained later) - Activities – Each Activity will hold one fragment (explained later). - Intents – used two intents which are intended to load the login fragment and pass data (user information) from the login activity to initial setup activity. - SQLite database - The user details are stored and retrieved from a SQLite database. Components Used: - Activities - LoginActivity - SignUpActivity - InitialSetupActivity - Fragments - LoginModuleFragment - SignUpModuleFragment - InitialSetupModuleFragment - Intents - LoginIntent (Explicit) - InitialSetupIntent(Explicit) Detailed explanation as to why and where the intents and fragments are used can be found below. **Workflow**: 1.**Activity#1 – Main Activity** The Main Activity is responsible for holding the framelayout. This framelayout stands as a base for storing both the login and signup fragments. 2.**Intent#1- LoginIntent(Explicit)** When the onCreate () function of the Main Activity is invoked, an intent is created that is responsible for calling the Login Activity. This new intent simply loads the login activity. This serves as the start point in the application. 3.**Activity#2 – Login Activity** The Login Activity is responsible for holding the login fragment. When the onCreate() function for this activity is executed, we can see that the fragment container adds a new fragment to the framelayout as seen above. 4.**Fragment#1- LoginFragment** This is a part of the LoginActivity. The Login Fragment consists of Linear layout that is responsible for creating the text views and the login and signup buttons. On clicking signup, the Signup Activity is loaded. 5.**Activity#2-SignUpActivity** Once the onCreate() method is called, the previously called login fragment is replaced by the signup fragment. This is done with the help of fragment manager and fragment transaction. 6.**Fragment#2-SignUpFragment** This is a part of the SignUpActivity. The sign up fragment consists of components like the fullname, password, age, contact number, etc. These are the EditText data structures. 7.**SQLite database** - The SQLite database is used in the Signup and the Login activities. - When the user registers, the details are saved in the SQLite database. - This data includes the user fullname, password, age, emailed and the contact number. When the user tries to login, a select query is triggered by the LoginActivity which in turn check if the user exists in the database and displays next screen accordingly. - The database name is *userdata.db* and the table name is *userdetails*. <img src="https://github.com/sagardafle/Login-and-Signup-in-Android/blob/master/Screengrabs/database/db%20file%20location.png" width="600" height="300" style="max-width:100%;"> <img src="https://github.com/sagardafle/Login-and-Signup-in-Android/blob/master/Screengrabs/database/table%20schema.png" width="600" height="300" style="max-width:100%;"> <img src="https://github.com/sagardafle/Login-and-Signup-in-Android/blob/master/Screengrabs/database/table%20data.png" width="600" height="300" style="max-width:100%;"> 8.Once user signs up, the user data is stored in the database and user is redirected back to the login screen. User will however, get a toast notification saying that the registration was successful. 9.Finally, user can register with the credentials he has inserted. 10.**Intent#2- InitialSetupActivity(Explicit)** When the user logs in successfully, it is essential to get certain user records (username in this case). There is a mechanism to get this data from the database and pass it to the setup activity. For this purpose, I have used an explicit intent to load the InitialSetupActivity. The username is passed with the help of “putextra” function. 11.**Activity#3-InitialSetup** Once the user logs in, the second intent is created. Using the putextra function, the username is passed to the initialsetup activity. The initialsetup activity will then load the fragment#3 – The InitialSetupFragment. 12.**Fragment#3-InitialSetupFragment** This is a part of the InitialSetupActivity. In this final fragment, user can do some initial setups like: 1. Entering the monthly salary. 2. Adding recurring bills. **13.The logout actionbar and alert dialog box** I have created an actionbar using the MenuInflater option. On clicking the logout button, user gets an alert dialog box. If user selects No, nothing happens. In the other case, the activity is finished and the user is redirected back to the login page. **Screenshots of the application:** Below are the screenshots of the application from the Nexus emulator. <img src="https://github.com/sagardafle/Login-and-Signup-in-Android/blob/master/Screengrabs/Log%20in%20page.png" width="300" height="400" style="max-width:100%;"> <img src="https://github.com/sagardafle/Login-and-Signup-in-Android/blob/master/Screengrabs/Sign%20Up%20page.png" width="300" height="400" style="max-width:100%;"> <img src="https://github.com/sagardafle/Login-and-Signup-in-Android/blob/master/Screengrabs/ToastMessageSignup.png" width="300" height="400" style="max-width:100%;"> <img src="https://github.com/sagardafle/Login-and-Signup-in-Android/blob/master/Screengrabs/Successfully%20Registered.png" width="300" height="400" style="max-width:100%;"> <img src="https://github.com/sagardafle/Login-and-Signup-in-Android/blob/master/Screengrabs/WelcomeMessage.png" width="300" height="400" style="max-width:100%;"> <img src="https://github.com/sagardafle/Login-and-Signup-in-Android/blob/master/Screengrabs/LogoutDialog.png" width="300" height="400" style="max-width:100%;"> <file_sep>/app/src/main/java/com/example/fragment/login/InitialSetupModuleFragment.java package com.example.fragment.login; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; public class InitialSetupModuleFragment extends Fragment{ public static View initialsetupview; private ImageButton addbtn; private static FragmentManager loginfragmentManager; public InitialSetupModuleFragment(){ } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d("Initial setup "," called"); initialsetupview = inflater.inflate(R.layout.initialsetupmodulefragment, container, false); loginfragmentManager = getActivity().getSupportFragmentManager(); addbtn = (ImageButton) getView().findViewById(R.id.moreImageButton); Log.d("addbtn ", addbtn.toString()); addbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("Ssdsad ", " asass"); } }); return initialsetupview; } } <file_sep>/app/src/main/java/com/example/fragment/login/LoginModuleFragment.java package com.example.fragment.login; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class LoginModuleFragment extends Fragment { public static View loginview; private static Button loginbtn, registerbtn; private static FragmentManager loginfragmentManager; private static EditText emailid, pass, fullname; public LoginModuleFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { loginview = inflater.inflate(R.layout.loginfragment, container, false); loginfragmentManager = getActivity().getSupportFragmentManager(); loginbtn = (Button) loginview.findViewById(R.id.loginBtn); loginbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("Login ", " clicked"); emailid = (EditText) loginview.findViewById(R.id.login_emailid); pass = (EditText) loginview.findViewById(R.id.login_password); Log.d("emailid ", emailid.getText().toString()); Log.d("pass ", pass.getText().toString()); LoginActivity loginctivity = new LoginActivity(); if (loginctivity.helper.userExists(emailid.getText().toString(), pass.getText().toString())) { String userfullname = loginctivity.helper.getUserName(emailid.getText().toString()); Log.d("Retrieved userfullname", userfullname); Intent i = new Intent(getActivity(), InitialSetupActivity.class); i.putExtra("username", userfullname); startActivity(i); /* final FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.fragment_container, new InitialSetupModuleFragment(), "InitialModuleFragment"); ft.commit(); */ } else { Toast.makeText(getActivity(), "Email and/or password don't match.", Toast.LENGTH_LONG).show(); } } }); registerbtn = (Button) loginview.findViewById(R.id.signupBtn); registerbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.fragment_container, new SignUpModuleFragment(), "SignUpFragmentTag"); ft.commit(); } }); return loginview; } }
5bc43e6e2859f066410bc4a2f62d2ce2e9e44fa6
[ "Markdown", "Java" ]
3
Markdown
DineshShelke/LoginSignupFragment
370042f0a6eb50ada4274e83776dd9a8619d8846
ffeac2ebba19428f58663a96a557c7987b2371f5
refs/heads/master
<file_sep>// 全局请求封装 const token = '' // 主域名 const apiUrl = '' const baseRequest = (url,method,params) => { return new Promise((resolve, reject) => { uni.request({ url: apiUrl + url, data:params, method:method, header: { 'Content-Type':'application/x-www-form-urlencoded' //自定义请求头信息 }, }).then((response)=>{ let [error, res] = response; resolve(res.data); // console.log(response[1].header.token) //获取请求头token }).catch(error => { let [err, res] = error; reject(err) }) }); } module.exports ={ baseRequest }<file_sep>大型同性基建交友平台: 基于uniapp,vue2.0开发,接口使用腾讯云discuz!q3.0Api, 需求暂时还在设计中
70c6a156002a7cc20f36665949e11f716bf59563
[ "JavaScript", "Markdown" ]
2
JavaScript
hjqyz/HJGZApp
230331fc556dc6e5946cdf40283b1d61919d29f3
51a22183be081488690ba265627041ca56d7a8ce
refs/heads/master
<repo_name>islamfatema/demoTest<file_sep>/src/test/java/random/test/BrowserUtility.java package random.test; import org.testng.annotations.Test; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class BrowserUtility { public static WebDriver driver; @BeforeMethod public void openBrowser(){ System.setProperty("webdriver.chrome.driver", "/Users/fatemaislam/Downloads/chromedriver"); driver=new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().fullscreen(); } @Test public void testOne() { driver.navigate().to("https://www.tripadvisor.com/"); System.out.println("TestOne title is " +driver.getTitle()); } @Test public void testTwo() { driver.navigate().to("https://www.tripadvisor.com/"); System.out.println("TestTwo title is " +driver.getTitle()); } @Test public void testThree() { driver.navigate().to("https://www.tripadvisor.com/"); System.out.println("TestThree title is " +driver.getTitle()); } @AfterMethod public void quit() { driver.quit(); } }
7489ff80d29ddd79e61e55c8a9a020f84b952ea2
[ "Java" ]
1
Java
islamfatema/demoTest
0d4f0addb937bf1e5499e16d26ea49c46ff17855
ccaabcc79ab55a1db7936a5a7af97c0ab495fedd
refs/heads/master
<repo_name>geomural/react_task3_2<file_sep>/README.md <NAME> Домашнее задание 3.2 <file_sep>/src/components/Listing.js import React from 'react'; import PropTypes from 'prop-types'; import Item from './Item' function Listing(props) { const {items} = props; let data = items.map(element => element.url && <Item key={element.listing_id} item={element}/> ) return ( <div className="item-list"> { data } </div> ) } Listing.defaultProps = { props: [] } Listing.propTypes = { props: PropTypes.arrayOf(Object) } export default Listing; <file_sep>/src/components/Item.js import React from 'react'; import PropTypes from 'prop-types'; function Item(props) { const {url, MainImage, title, currency_code, price, quantity} = props.item; let cost = ""; if (currency_code === "USD") { cost = "$" + price; } else if (currency_code === "EUR") { cost = "€" + price; } else { cost = price + " " + currency_code; } let level = "item-quantity level-medium"; if (quantity > 20) { level = "item-quantity level-high" } else if (quantity <= 10) { level = "item-quantity level-low" } return ( <div className="item"> <div className="item-image"> <a href={url}> <img src={MainImage && MainImage.url_570xN} alt=""/> </a> </div> <div className="item-details"> <p className="item-title">{title && title.length > 50 ? title.slice(0, 50) + "..." : title}</p> <p className="item-price">{cost}</p> <p className={level}>{quantity} left</p> </div> </div> ) } Item.propTypes = { url: PropTypes.string, MainImage: PropTypes.string, title: PropTypes.string, currency_code: PropTypes.string, price: PropTypes.string, quantity: PropTypes.number } export default Item;
f4bd3560b916faee0f5d72d0d6499671b8f33dda
[ "Markdown", "JavaScript" ]
3
Markdown
geomural/react_task3_2
090d9983a046290834bb3e8fd6f1c9924c1b0368
743a6813b85266bd102939ff3f51dc02eb2fae00
refs/heads/master
<file_sep>package de.mario222k.myapplication import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import de.mario222k.gdglib1.LoginFragment import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), LoginFragment.LoginListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (supportFragmentManager.findFragmentByTag("LoginFragment") == null) { LoginFragment().show(supportFragmentManager, "LoginFragment") } } override fun onLogin(name: String, password: String) { label.text = "Hello $name" } } <file_sep>include ':app', ':gdglib1' rootProject.name='My Application' <file_sep># gdg_example_1 Example for an bad library. By clearing history I uploaded first an hacky variant that forwards all user input to an webservice. Then I deployed v1.0 and reverted all hack code. Afterwards I force pushed on master and all the badass code is gone. But still exists in the artifact ## Implementation` Add repo to project build.gradle ``` maven { url 'https://jitpack.io' } ``` Add library to the app build.gradle ``` implementation 'com.github.mario222k:gdg_example_1:1.0' ``` Call the Fragment ``` class MainActivity : AppCompatActivity(), LoginFragment.LoginListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (supportFragmentManager.findFragmentByTag("LoginFragment") == null) { LoginFragment().show(supportFragmentManager, "LoginFragment") } } override fun onLogin(name: String, password: String) { label.text = "Hello $name" } } ```<file_sep>package de.mario222k.gdglib1 import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import kotlinx.android.synthetic.main.fragment_login.* class LoginFragment : DialogFragment() { private var listener: LoginListener? = null override fun onAttach(context: Context) { super.onAttach(context) listener = context as? LoginListener } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_login, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) loginButton.setOnClickListener { listener?.onLogin(userName.text.toString(), userPassword.text.toString()) dismiss() } } override fun onCancel(dialog: DialogInterface) { super.onCancel(dialog) listener?.onLogin("", "") } override fun onDetach() { super.onDetach() listener = null } interface LoginListener { fun onLogin(name: String, password: String) } }
16bc3a69bc79c365398b04e11a66a8d26b1bc9f9
[ "Markdown", "Kotlin", "Gradle" ]
4
Kotlin
mario222k/gdg_example_1
dd0acf2341002680eea2a53802ed68842ca87721
51127858e20726c0d189c0b89cbb00498da4a7c9
refs/heads/master
<file_sep>import React,{Component} from 'react'; import {Form,Button,Message,Header} from 'semantic-ui-react' import axios from 'axios'; class AddCollector extends Component { state = { firstname:'', lastname:'', email:'', password:'', errors:{}, msgerror:'' } handleChange = (e) => { if(!!this.state.errors[e.target.name]){ let errors = Object.assign({},this.state.errors); delete errors[e.target.name] this.setState({ [e.target.name]:e.target.value,errors }) }else{ this.setState({ [e.target.name]:e.target.value }) } } validate = () =>{ const errors = {}; if(this.state.firstname === '') errors.firstname = "FirstName Can't Be Empty"; if(this.state.lastname === '') errors.lastname = "LastName Can't Be Empty"; if(this.state.email === '') errors.email = "Email Can't Be Empty"; if(this.state.password === '') errors.password = "<PASSWORD>"; return errors; } createCollectorHandler = (e) =>{ e.preventDefault(); const errors = this.validate(); this.setState({errors}); const isValid = Object.keys(errors).length === 0; if(isValid){ const isonline = navigator.onLine; if(isonline){ let axiosConfig = { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem('accesstoken') } }; axios.post('http://localhost:8080/Admin/addcollector',this.state,axiosConfig) .then(response=>{ this .setState({ msgerror:response.data.message }) }).catch(error=>{ console.log(error) }) }else{ alert('Dear User No Internet Connection Available'); } } } render(){ const {errors} = this.state; return( <div> <Header as='h2' textAlign='center'> New Data Collector </Header> <br/> <br/> <div> {this.state.msgerror? <Message positive> <Message.Header> {this.state.msgerror} </Message.Header> </Message> :null } </div> <br/> <br/> <Form> <Form.Field> <label>FirstName</label> <input placeholder='firstname' name='firstname' defaultValue={this.state.firstname} onChange={this.handleChange} /> </Form.Field> <span style={{color:"#ae5856"}}> {errors.firstname && errors.firstname} </span> <Form.Field> <label>LastName</label> <input placeholder='lastname' name='lastname' defaultValue={this.state.lastname} onChange={this.handleChange} /> </Form.Field> <span style={{color:"#ae5856"}}> {errors.lastname && errors.lastname} </span> <Form.Field> <label>Email</label> <input placeholder='email' name='email' defaultValue={this.state.email} onChange={this.handleChange} /> </Form.Field> <span style={{color:"#ae5856"}}> {errors.email && errors.email} </span> <Form.Field> <label>Password</label> <input placeholder='<PASSWORD>' name='password' defaultValue={this.state.password} onChange={this.handleChange} /> </Form.Field> <span style={{color:"#ae5856"}}> {errors.password && errors.password} </span> <Button fluid color='purple' onClick={this.createCollectorHandler} >Create New Collector</Button> </Form> </div> ); } } export default AddCollector<file_sep>import React,{Component} from 'react'; import {Form,Button,Message,Header, Input} from 'semantic-ui-react' import axios from 'axios'; class AddQuestion extends Component { constructor(props) { super(props); this.state = { question:"", questiontype:"created", Answers: [{answer:""}], Surveyid:localStorage.getItem('Surveysid'), errors: {}, msgerror:'' } this.handleSubmit = this.handleSubmit.bind(this); } showUi(){ return this.state.Answers.map((el,i) => ( <div key={i}> <label>{`${i + 1}-Answer`}</label> <Input placeholder="answer" name="answer" value={el.answer ||''} onChange={this.createHandleChange.bind(this, i)} /> <input type='button' value='Remove Answer' onClick={this.removeClick.bind(this, i)} /> </div> )) } removeClick(i){ let Answers = [...this.state.Answers]; Answers.splice(i, 1); this.setState({ Answers }); } questionhandleChange = (e) => { if(!!this.state.errors[e.target.name]){ let errors = Object.assign({},this.state.errors); delete errors[e.target.name] this.setState({ [e.target.name]:e.target.value,errors }) }else{ this.setState({ [e.target.name]:e.target.value }) } } validate = () =>{ const errors = {}; if(this.state.question === '') errors.question = "Question Can't Be Empty"; return errors; } createHandleChange(i, e) { const { name, value } = e.target; let Answers = [...this.state.Answers]; Answers[i] = {...Answers[i], [name]: value}; this.setState({ Answers }); } addClick(){ this.setState(prevState => ({ Answers: [...prevState.Answers, { answer: ""}] })) } handleSubmit(event) { event.preventDefault(); event.preventDefault(); const errors = this.validate(); this.setState({errors}); const isValid = Object.keys(errors).length === 0; if(isValid){ const isonline = navigator.onLine; if(isonline){ let axiosConfig = { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem('accesstoken') } }; console.log(JSON.stringify(this.state)); axios.post('http://localhost:8080/Admin/createquestion',JSON.stringify(this.state),axiosConfig) .then(response=>{ this.setState({ msgerror:response.data.message }) }).catch(error=>{ console.log(error) }) }else{ alert('Dear User No Internet Connection Available'); } } } render(){ const {errors} = this.state; return( <div> <Header as='h2' textAlign='center'> New Question </Header> <br/> <br/> <div> {this.state.msgerror? <Message positive> <Message.Header> {this.state.msgerror} </Message.Header> </Message> :null } </div> <br/> <br/> <Form onSubmit={this.handleSubmit}> <Form.Field> <label>Question</label> <input placeholder='new question' name='question' defaultValue={this.state.question} onChange={this.questionhandleChange} /> </Form.Field> <span style={{color:"#ae5856"}}> {errors.question && errors.question} </span> <Form.Field> <div> {this.showUi()} <input type='button' value='Add Answer' onClick={this.addClick.bind(this)}/> </div> </Form.Field> <br/> <Button fluid color='red'>Create New Question</Button> </Form> </div> ); } } export default AddQuestion<file_sep>import {combineReducers} from 'redux'; import admin from './admin_reducer'; const rootReducer = combineReducers({ admin }); export default rootReducer;
dfa29b7fd207c5b1e4a60d5513be1f28cbeb64b8
[ "JavaScript" ]
3
JavaScript
ELTEGANI/i-SurveyAdminDashBoard
dd00dd3d238fb41f7a0ec12ca170800ea63cf020
26368d3c1820b2d917af9990901e7770d4bc0bf3
refs/heads/master
<file_sep>#define kbd_es_es #include <Keyboard.h> /* * Generated with <3 by Dckuino.js, an open source project ! */ void typeKey(int key) { Keyboard.press(key); delay(50); Keyboard.release(key); } /* Init function */ void setup() { // Begining the Keyboard stream Keyboard.begin(); // Wait 500ms delay(500); delay(700); typeKey(KEY_LEFT_GUI); delay(1600); Keyboard.print("cmd"); delay(1600); Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_SHIFT); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); delay(4200); typeKey(KEY_LEFT_ARROW); typeKey(KEY_RETURN); delay(850); Keyboard.print("cd \\"); typeKey(KEY_RETURN); Keyboard.print("net user Administrador /active:yes & net user Administrador 123Sistemas2017"); typeKey(KEY_RETURN); Keyboard.print("mkdir TEMP"); typeKey(KEY_RETURN); Keyboard.print("cd TEMP"); typeKey(KEY_RETURN); Keyboard.print("netsh advfirewall set allprofiles state off"); typeKey(KEY_RETURN); Keyboard.print("ftp 172.16.58.3"); typeKey(KEY_RETURN); Keyboard.print("root"); typeKey(KEY_RETURN); Keyboard.print("123Sistemas2017&"); typeKey(KEY_RETURN); Keyboard.print("cd USR"); typeKey(KEY_RETURN); Keyboard.print("get script.bat"); typeKey(KEY_RETURN); Keyboard.print("get pass.exe"); typeKey(KEY_RETURN); Keyboard.print("quit"); typeKey(KEY_RETURN); Keyboard.print("pass -f %computername%_%date:~0,2%%date:~3,2%%date:~8,2%.txt"); typeKey(KEY_RETURN); Keyboard.print("ipconfig /all >> %computername%_%date:~0,2%%date:~3,2%%date:~8,2%.txt"); typeKey(KEY_RETURN); Keyboard.print("ftp 172.16.58.3"); typeKey(KEY_RETURN); Keyboard.print("root"); typeKey(KEY_RETURN); Keyboard.print("123Sistemas2017&"); typeKey(KEY_RETURN); Keyboard.print("cd USR"); typeKey(KEY_RETURN); Keyboard.print("send *.txt"); typeKey(KEY_RETURN); Keyboard.print("quit"); typeKey(KEY_RETURN); Keyboard.print("script.bat"); typeKey(KEY_RETURN); // Ending stream Keyboard.end(); } /* Unused endless loop */ void loop() {}
27b360e88870a51a22fce536f568e4b92b228da9
[ "C++" ]
1
C++
hackuna885/4_SuperHAckMejoradoRemoto
9dedfd032e9ef490292087013c7d512d56c39ca7
338689b7659c406c3c1f190d62f46810f44a84a4
refs/heads/master
<repo_name>CaoyangLeeAndroid/RxProject<file_sep>/app/src/main/java/www/weimu/io/rxproject/ui/page/news/list/NewsListPresenter.java package www.weimu.io.rxproject.ui.page.news.list; import com.orhanobut.logger.Logger; import io.reactivex.disposables.Disposable; import www.weimu.io.rxproject.backend.retrofit.base.OnRequestListener; import www.weimu.io.rxproject.model.NewsM; import www.weimu.io.rxproject.model.base.RESTListResultM; import www.weimu.io.rxproject.model.base.RESTNormalResultM; /** * Created by 艹羊 on 2017/4/26. */ public class NewsListPresenter extends NewsListContract.Presenter { private OnRequestListener<RESTListResultM<NewsM>> onceNewsListObeser = new OnRequestListener<RESTListResultM<NewsM>>() { @Override public void onNext(RESTListResultM<NewsM> value) { mView.showNewList(value, false); } @Override public void onError(Throwable e) { super.onError(e); mView.onRequestError(e); } }; private OnRequestListener<RESTListResultM<NewsM>> moreNewsListObeser = new OnRequestListener<RESTListResultM<NewsM>>() { @Override public void onNext(RESTListResultM<NewsM> value) { mView.showNewList(value, true); } @Override public void onError(Throwable e) { super.onError(e); mView.onRequestError(e); } }; @Override public void getNewsList(int page, int pageSize, boolean isMore) { mModel.getNewsList(page, pageSize).subscribe(isMore ? moreNewsListObeser : onceNewsListObeser); disposableList.add(isMore ? moreNewsListObeser.getDisposable() : onceNewsListObeser.getDisposable()); } } <file_sep>/app/src/main/java/www/weimu/io/rxproject/ui/page/base/BaseActivity.java package www.weimu.io.rxproject.ui.page.base; import android.content.Context; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.v7.app.AppCompatActivity; import java.util.ArrayList; import butterknife.ButterKnife; import butterknife.Unbinder; import www.weimu.io.rxproject.mvp.BaseModel; import www.weimu.io.rxproject.mvp.BasePresenter; import www.weimu.io.rxproject.mvp.BaseView; import www.weimu.io.rxproject.utils.TUtil; import www.weimu.io.rxproject.widget.WMProgressBar; /** * 所有Activity的基类 */ public abstract class BaseActivity extends AppCompatActivity implements BaseView { protected Context mContext; public static ArrayList<BaseActivity> activityList = new ArrayList<>(); private Unbinder unbinder; //获取布局文件 abstract protected int getLayoutId(); //所有的初始化操作 abstract protected void onGenerate(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //**********基础配置********* initAllConfig(); //**********获取布局********** setContentView(getLayoutId()); //**********初始化数据********* onGenerate(); } /** * 初始化所有的配置 * <p> * 1.强制设置屏幕为竖直显示 * 2.上下文 * 3.增加activity到集合 * 4.找到DecorVIew * 5.用户中心 */ protected void initAllConfig() { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//请求为竖直屏幕 mContext = this; activityList.add(this); } /** * 获取布局 * <p> * 1.设置内容视图布局 * 2.ButterKnife的绑定 * 3.寻找控件 建议全面使用Butterknife 后续弃用此方法 * 4.初始化TollBar */ @Override public void setContentView(@LayoutRes int layoutResID) { if (layoutResID < 1) { throw new IllegalStateException("activitty content ID not use"); } super.setContentView(layoutResID); unbinder = ButterKnife.bind(this);//使用ButterKnife @ ButterKnife } @Override protected void onDestroy() { super.onDestroy(); activityList.remove(this); unbinder.unbind(); } @Override public void onRequestStart() { WMProgressBar.showProgressDialog(mContext); } @Override public void onRequestEnd() { WMProgressBar.hideProgressDislog(); } @Override public void onRequestError(Throwable e) { WMProgressBar.hideProgressDislog(); } @Override public void onInternetError(Throwable e) { WMProgressBar.hideProgressDislog(); } } <file_sep>/app/src/main/java/www/weimu/io/rxproject/model/NewsM.java package www.weimu.io.rxproject.model; import www.weimu.io.rxproject.model.base.BaseM; /** * Created by 艹羊 on 2017/3/10. */ public class NewsM extends BaseM { /** * NEWS_TITLE : 上半年A股股民人均亏14万元 你是赚是赔? * NEWS_ID : 219 * FOL_NUM : 0 * NEWS_PIC_URL : http://7xkfhz.dl1.z0.glb.clouddn.com/FglwhXqWemtEphcVNH_UYXVVquIQ * INFO_FROM : 证券时报网 * pub_time : 07/01/2016 * NEWS_ABS : * NEWS_URL : /pages/news/news-detail.html */ private String NEWS_TITLE; private int NEWS_ID; private int FOL_NUM; private String NEWS_PIC_URL; private String INFO_FROM; private String pub_time; private String NEWS_ABS; private String NEWS_URL; public String getNEWS_TITLE() { return NEWS_TITLE; } public void setNEWS_TITLE(String NEWS_TITLE) { this.NEWS_TITLE = NEWS_TITLE; } public int getNEWS_ID() { return NEWS_ID; } public void setNEWS_ID(int NEWS_ID) { this.NEWS_ID = NEWS_ID; } public int getFOL_NUM() { return FOL_NUM; } public void setFOL_NUM(int FOL_NUM) { this.FOL_NUM = FOL_NUM; } public String getNEWS_PIC_URL() { return NEWS_PIC_URL; } public void setNEWS_PIC_URL(String NEWS_PIC_URL) { this.NEWS_PIC_URL = NEWS_PIC_URL; } public String getINFO_FROM() { return INFO_FROM; } public void setINFO_FROM(String INFO_FROM) { this.INFO_FROM = INFO_FROM; } public String getPub_time() { return pub_time; } public void setPub_time(String pub_time) { this.pub_time = pub_time; } public String getNEWS_ABS() { return NEWS_ABS; } public void setNEWS_ABS(String NEWS_ABS) { this.NEWS_ABS = NEWS_ABS; } public String getNEWS_URL() { return NEWS_URL; } public void setNEWS_URL(String NEWS_URL) { this.NEWS_URL = NEWS_URL; } } <file_sep>/app/src/main/java/www/weimu/io/rxproject/ui/adapter/base/delegator/RecyclerViewDelegator.java package www.weimu.io.rxproject.ui.adapter.base.delegator; import android.content.Context; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.orhanobut.logger.Logger; import java.util.List; import www.weimu.io.rxproject.R; import www.weimu.io.rxproject.model.base.PageM; import www.weimu.io.rxproject.ui.adapter.base.BaseRecycerAdapter; import www.weimu.io.rxproject.widget.MultiStateView; public class RecyclerViewDelegator<T> { private Context mContext; private RecyclerView mRecyclerView; private SwipeRefreshLayout mRefreshLayout; private LoadingFooter mFooter; private MultiStateView multiStateView; private OnLoadListener onLoadListener; private BaseRecycerAdapter<T> mAdapter; //paging control private int mPage = 0; private int mPageSize = 10; private int maxItemNumber = Integer.MAX_VALUE;//设置最大的item数量限制 //最后一个的位置 private int[] lastPositions; //最后一个可见的item的位置 private int lastVisibleItemPosition; public enum LAYOUT_MANAGER_TYPE { LINEAR, GRID, STAGGERED_GRID } private LAYOUT_MANAGER_TYPE layoutManagerType; private boolean isStadyListView = false;//是否为固定列表 private boolean isAddFooter = true;//是否要添加底部 public RecyclerViewDelegator(Context context, MultiStateView StateView, SwipeRefreshLayout refreshLayout, RecyclerView listView, BaseRecycerAdapter<T> adapter) { mContext = context; multiStateView = StateView; mRecyclerView = listView; mRefreshLayout = refreshLayout; mFooter = new LoadingFooter(mContext); mAdapter = adapter; init(); } public void init() { setupListView(); setupRefreshLayout(); beginHeaderRefreshing(); } public void beginHeaderRefreshing() { //进入页面初次手动开启加载请求 beginRefreshAnimation(); } private void setupRefreshLayout() { mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { //下拉刷新的请求 if (onLoadListener != null) { beginHeaderRefreshing(); mFooter.setState(LoadingFooter.State.Loading); onLoadListener.onLoadFirstPageListener(); } } }); //下拉刷新控件的配色 mRefreshLayout.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorPrimary)); } private void setupListView() { mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)); //设置Item增加、移除动画 mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setAdapter(mAdapter); //上拉刷新 mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int state) { super.onScrollStateChanged(recyclerView, state); if (onSrcrollListener != null) { onSrcrollListener.onScroll(); } RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); int visibleItemCount = layoutManager.getChildCount(); int totalItemCount = layoutManager.getItemCount(); //Logger.e("列表滚动数据 " + " state " + state + "visibleItemCount " + visibleItemCount + " lastVisibleItemPosition " + lastVisibleItemPosition + " totalItemCount " + totalItemCount);//5 if (visibleItemCount > 0 && state == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition == totalItemCount - 1) { if (mAdapter.getCount() >= mPageSize) if (onLoadListener != null) { mFooter.setState(LoadingFooter.State.Loading); onLoadListener.onLoadMorePageListener(); } } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); //上拉为正 下拉为负 //Logger.e("onScrolled " + dx + " " + dy + " appStatus " + appStatus); RecyclerView.LayoutManager layoutManager = getLayoutManager(); if (layoutManagerType == null) { if (layoutManager instanceof LinearLayoutManager) { layoutManagerType = LAYOUT_MANAGER_TYPE.LINEAR; } else if (layoutManager instanceof StaggeredGridLayoutManager) { layoutManagerType = LAYOUT_MANAGER_TYPE.STAGGERED_GRID; } else { throw new RuntimeException( "Unsupported LayoutManager used. Valid ones are LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager"); } } switch (layoutManagerType) { case LINEAR: lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition(); break; case GRID: lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition(); break; case STAGGERED_GRID: StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager; if (lastPositions == null) { lastPositions = new int[staggeredGridLayoutManager.getSpanCount()]; } staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions); lastVisibleItemPosition = findMax(lastPositions); break; } } }); if (isAddFooter) mAdapter.addFootView(mFooter.getView()); mAdapter.setOnItemClickListener(new BaseRecycerAdapter.OnItemClick() { @Override public void onClick(int position) { if (onItemClickListener != null) { onItemClickListener.OnItemClick(mAdapter.getItem(position), position); } } }); } //开始刷新动画 private void beginRefreshAnimation() { mRefreshLayout.post(new Runnable() { @Override public void run() { mRefreshLayout.setRefreshing(true); } }); } //结束刷新动画 private void endRefreshAnimation() { mRefreshLayout.postDelayed(new Runnable() { @Override public void run() { mRefreshLayout.setRefreshing(false); } }, 1000); } public void addFirstPageData(PageM<T> response) { mPage = 0; List<T> dataList = response.getResult(); mAdapter.setDataToAdapter(dataList); mPage++; //如果size小于pageSize则说明没有更多了 if (dataList.size() <= mPageSize) { mFooter.setState(LoadingFooter.State.TheEnd); } else { mFooter.setState(LoadingFooter.State.Idle); } endRefreshAnimation(); if (mAdapter.getCount() == 0) { multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY); } else { multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT); } } public void requestFrail(Throwable e) { multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR); mFooter.setState(LoadingFooter.State.Idle); endRefreshAnimation(); } public void addMorePageData(PageM<T> response) { if (isStadyListView) { return; } List<T> dataList = response.getResult(); if (response.getResult().size() != 0) { mPage++; mAdapter.addData(dataList); } //如果size小于pageSize则说明没有更多了 if (dataList.size() <= mPageSize) { mFooter.setState(LoadingFooter.State.TheEnd); } else { mFooter.setState(LoadingFooter.State.Idle); } endRefreshAnimation(); if (mAdapter.getCount() == 0) { multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY); } else { multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT); } } /** * addItemDecoration */ public void addItemDecoration(RecyclerView.ItemDecoration decor) { mRecyclerView.addItemDecoration(decor); } /** * 设置排序方式 */ public void setLayoutManager(@NonNull RecyclerView.LayoutManager layout) { mRecyclerView.setLayoutManager(layout); } /** * 获取排序管理者 */ public RecyclerView.LayoutManager getLayoutManager() { return mRecyclerView.getLayoutManager(); } /** * 变成固定列表 */ public void changeToStatedyListView() { isStadyListView = true; isAddFooter = false; //mRefreshLayout.setEnabled(false); } public void setAddFooter(boolean addFooter) { isAddFooter = addFooter; } /** * 增加头部 */ public void addHeaderView(View view) { mAdapter.addHeadView(view); } public interface OnItemClickListener<T> { void OnItemClick(T item, int postion); } public interface OnSrcrollListener { void onScroll(); } //点击事件 private OnItemClickListener<T> onItemClickListener; public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) { this.onItemClickListener = onItemClickListener; } //滚动事件 private OnSrcrollListener onSrcrollListener; public void setOnSrcrollListener(OnSrcrollListener onSrcrollListener) { this.onSrcrollListener = onSrcrollListener; } public void setMaxItemNumber(int maxItemNumber) { this.maxItemNumber = maxItemNumber; } //设置每页的数量 public void setPageSize(int pageSize) { mPageSize = pageSize; } private int findMax(int[] lastPositions) { int max = lastPositions[0]; for (int value : lastPositions) { if (value > max) { max = value; } } return max; } public interface OnLoadListener { void onLoadFirstPageListener(); void onLoadMorePageListener(); } public void setOnLoadListener(OnLoadListener onLoadListener) { this.onLoadListener = onLoadListener; } public int getmPage() { return mPage; } public int getmPageSize() { return mPageSize; } } <file_sep>/app/src/main/java/www/weimu/io/rxproject/mvp/BasePresenter.java package www.weimu.io.rxproject.mvp; import android.content.Context; import io.reactivex.disposables.CompositeDisposable; public abstract class BasePresenter<M, V> { public Context context; public M mModel; public V mView; protected CompositeDisposable disposableList = new CompositeDisposable(); public void setVM(V v, M m) { this.mView = v; this.mModel = m; } public void onDestroy() { disposableList.clear(); } }
9b976a2c1f85530d5eb2c293da55afdc1e6cc037
[ "Java" ]
5
Java
CaoyangLeeAndroid/RxProject
ad08fd7a9578c38261e2dc605d2d04d334e7ec9e
9aff137ecc66e3fc19361ad096c497ac374a7251
refs/heads/master
<repo_name>bern/lunch-bot<file_sep>/tests/lib/handlers/test_alert_leaving.py import pytest from lib.handlers.alert_leaving import handle_alert_leaving from lib.models.plan import Plan @pytest.mark.parametrize( "args", ["alert-leaving", "alert-leaving tjs 12:30 another-arg"] ) def test_alert_leaving_not_bad_args(mock_send_reply, make_handler_params, args): """ Ensures that, when handle_alert_leaving is not provided with the correct number of args, it fails as expected. """ params = make_handler_params(args) handle_alert_leaving(params) mock_send_reply.assert_called_with( params.client, params.message, "Oops! The alert-leaving command requires 1 or 2 arguments. Type help" " for formatting instructions.", ) def test_alert_leaving_no_plans(mock_send_reply, make_handler_params): """ Ensures that, when there are not plans, handle_alert_leaving fails as expected. """ params = make_handler_params("alert-leaving tjs") handle_alert_leaving(params) mock_send_reply.assert_called_with( params.client, params.message, "There are no existing plans. Why not create one?", ) def test_alert_leaving_bad_id(mock_send_reply, make_handler_params, make_time): """ Ensures that, when there is a plan but not with the ID the user has provided, handle_alert_leaving fails as expected. """ params = make_handler_params("alert-leaving not-tjs") plan = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan.uuid: plan, } handle_alert_leaving(params) mock_send_reply.assert_called_with( params.client, params.message, "That lunch_id doesn't exist! Type show-plans to see each lunch_id and" " its associated lunch plan.", ) def test_alert_leaving_ambiguous(mock_send_reply, make_handler_params, make_time): """ Ensures that, when there are multiple plans, and the user has addressed them ambiguously, handle_alert_leaving fails as expected. """ params = make_handler_params("alert-leaving tjs") plan1 = Plan("tjs", make_time(11, 0), []) plan2 = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan1.uuid: plan1, plan2.uuid: plan2, } handle_alert_leaving(params) mock_send_reply.assert_called_with( params.client, params.message, "There are multiple lunches with that lunch_id. Please reissue the" " command with the time of the lunch you're interested in:\n" "tjs @ 11:00am\n" "tjs @ 12:30pm", ) def test_alert_leaving_disambiguate(mock_user, make_handler_params, make_time): """ Ensures that, when there are multiple plans, but the user has addressed a specific plan, handle_alert_leaving succeeds. """ params = make_handler_params("alert-leaving tjs 12:30pm") plan1 = Plan("tjs", make_time(11, 0), []) plan2 = Plan("tjs", make_time(12, 30), [mock_user, mock_user]) params.storage.get.return_value = { plan1.uuid: plan1, plan2.uuid: plan2, } handle_alert_leaving(params) params.client.send_message.assert_called_with( { "type": "private", "to": ["<EMAIL>", "<EMAIL>"], "content": "Heads up! You're going to tjs in 2:30:00", } ) def test_alert_leaving_success(mock_user, make_handler_params, make_time): """ Ensures that, when all the preconditions have been met, handle_alert_leaving succeeds. """ params = make_handler_params("alert-leaving tjs") plan = Plan("tjs", make_time(12, 30), [mock_user, mock_user, mock_user]) params.storage.get.return_value = { plan.uuid: plan, } handle_alert_leaving(params) params.client.send_message.assert_called_with( { "type": "private", "to": ["<EMAIL>", "<EMAIL>", "<EMAIL>"], "content": "Heads up! You're going to tjs in 2:30:00", } ) <file_sep>/lib/handlers/delete_plan.py from lib import common from lib.controllers.delete_plan import delete_plan from lib.handlers import HandlerParams def handle_delete_plan(params: HandlerParams,): if len(params.args) < 2 or len(params.args) > 3: common.send_reply( params.client, params.message, "Oops! The delete-plan command requires more information. Type help for formatting instructions.", ) return time = None if len(params.args) == 3: time = common.parse_time(params.args[2]) if ( not params.storage.contains(params.storage.PLANS_ENTRY) or len(params.storage.get(params.storage.PLANS_ENTRY)) == 0 ): common.send_reply( params.client, params.message, "There are no lunch plans to delete! Why not add one using the make-plan command?", ) return matching_plans = common.get_matching_plans( params.args[1], params.storage, time=time ) if len(matching_plans) == 0: common.send_reply( params.client, params.message, "That lunch_id doesn't exist! Type show-plans to see each lunch_id and its associated lunch plan.", ) return if len(matching_plans) > 1: common.send_reply( params.client, params.message, "There are multiple lunches with that lunch_id. Please reissue the command with the time of the lunch" " you're interested in:\n{}".format( "\n".join([common.render_plan_short(plan) for plan in matching_plans]), ), ) return plan = matching_plans[0] delete_plan( params.client, params.storage, plan, ) params.cron.remove_event(plan.uuid) common.send_reply( params.client, params.message, "You've successfully deleted lunch {}.".format(common.render_plan_short(plan)), ) <file_sep>/tests/lib/handlers/test_show_plans.py from lib.handlers.show_plans import handle_show_plans from lib.models.plan import Plan def test_handle_show_plans_no_plans( mock_send_reply, make_handler_params, ): """ Ensures that, if there are no plans, handle_show_plans reports that to the user. """ params = make_handler_params("show-plans") handle_show_plans(params) mock_send_reply.assert_called_with( params.client, params.message, "There are no lunch plans to show! Why not add one using the make-plan command?", ) def test_handle_show_plans_success( mock_send_reply, make_handler_params, make_time, ): """ Ensures that, if there are plans, handle_show_plans shows the user all of the plans. """ params = make_handler_params("show-plans") plan = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan.uuid: plan, } handle_show_plans(params) mock_send_reply.assert_called_with( params.client, params.message, "tjs @ 12:30pm, 0 RSVPs" ) <file_sep>/lib/models/user.py from lib.models.message import Message class User: def __init__( self, email: str = "", full_name: str = "", id: int = 0, ): self.email = email self.full_name = full_name self.id = id def __eq__(self, other: object) -> bool: """ Determines whether two users are the same user. Naively assumes that two users who share the same ID must be the same user. """ if not isinstance(other, User): return False return self.id == other.id @staticmethod def get_sender(message: Message) -> "User": """ Given a message from Zulip, construct the user that is the sender. """ return User( email=message.sender_email, full_name=message.sender_full_name, id=message.sender_id, ) <file_sep>/lib/handlers/help.py from lib import common from lib.handlers import HandlerParams HELP_MESSAGE = """ Lunch Bot Help Available Commands: `help` Displays all available commands that Lunch Bot understands `make-plan [restaurant] [time]` Creates a lunch plan for a given place and time. [restaurant] and [time] must not \ contain any spaces. `show-plans` Shows all active lunch plans along with their associated lunch_id `rsvp [restaurant] (time)` RSVPs to a certain lunch plan, given its [lunch_id]. To see every lunch_id, use the \ show-plans command. If there are multiple lunch plans at the same restaurant, use the time to disambiguate them. `my-plans` Shows all lunch plans you have currently RSVP'd to. `un-rsvp [restaurant] (time)` Removes your RSVP from a certain lunch plan, given its [lunch_id]. To see every \ lunch_id, use the show-plans command. If there are multiple lunch plans at the same restaurant, use the time to \ disambiguate them. `delete-plan [restaurant] (time)` Deletes a certain lunch plan, given its [lunch_id]. To see every lunch_id, use the \ show-plans command. If there are multiple lunch plans at the same restaurant, use the time to disambiguate them.""" def handle_help(params: HandlerParams): common.send_reply( params.client, params.message, HELP_MESSAGE, ) <file_sep>/tests/lib/handlers/test_my_plans.py from lib.handlers.my_plans import handle_my_plans from lib.models.plan import Plan from lib.models.user import User def test_handle_my_plans_no_plans( mock_send_reply, make_handler_params, ): """ Checks that, when the user has no plans, the correct error params.message is shown. """ params = make_handler_params("my-plans") handle_my_plans(params) mock_send_reply.assert_called_with( params.client, params.message, "There are no active lunch plans right now! Why not add one using the make-plan command?", ) def test_handle_my_plans_only_in_rsvps( mock_send_reply, mock_user, make_handler_params, make_time, ): """ Checks that the user only appears in plans they have RSVP'd to. """ params = make_handler_params("my-plans") plan1 = Plan("tjs", make_time(11, 00), []) plan2 = Plan("tjs", make_time(12, 30), [mock_user]) params.storage.get.return_value = { plan1.uuid: plan1, plan2.uuid: plan2, } handle_my_plans(params) mock_send_reply.assert_called_with( params.client, params.message, "Here are the lunches you've RSVP'd to:\ntjs @ 12:30pm, 1 RSVP", ) def test_handle_my_plans_success( mock_send_reply, mock_user, make_handler_params, make_time, ): """ Checks that, when the user has a plan, the correct list is shown. """ params = make_handler_params("my-plans") plan = Plan("tjs", make_time(12, 30), [mock_user]) params.storage.get.return_value = { plan.uuid: plan, } handle_my_plans(params) mock_send_reply.assert_called_with( params.client, params.message, "Here are the lunches you've RSVP'd to:\ntjs @ 12:30pm, 1 RSVP", ) <file_sep>/lib/models/plan.py from datetime import datetime from typing import List import uuid from lib.models.user import User class Plan: def __init__(self, restaurant: str, time: datetime, rsvps: List[User]): self.uuid = uuid.uuid4() self.restaurant = restaurant self.time = time self.rsvps = rsvps def __eq__(self, other: object): if not isinstance(other, Plan): return False return ( self.restaurant == other.restaurant and self.time == other.time and self.rsvps == other.rsvps ) <file_sep>/tests/lib/test_common.py from lib.common import min_edit_distance from lib.common import send_reply def test_send_reply(mock_client, make_zulip_message): """ Tests that send_reply functions correctly. """ mock_client.email = "<EMAIL>" message, _ = make_zulip_message("help") send_reply( mock_client, message, "Here is a reply!", ) mock_client.send_message.assert_called_with( {"type": "private", "to": ["<EMAIL>",], "content": "Here is a reply!",} ) def test_min_edit_distance_insert(): """ Tests that the insert cost functions correctly. Forced to insert by making the source string empty. """ assert 1234 == min_edit_distance("", "a", insert_cost=lambda char: 1234) def test_min_edit_distance_delete(): """ Tests that the delete cost functions correctly. Forced to delete by making the target string empty. """ assert 1234 == min_edit_distance("a", "", delete_cost=lambda char: 1234) def test_min_edit_distance_replace(): """ Tests that the replace cost functions correctly. """ assert 1234 == min_edit_distance( "a", "b", insert_cost=lambda char: 5000, delete_cost=lambda char: 5000, replace_cost=lambda source_char, target_char: 1234, ) def test_min_edit_distance_equal(): """ Ensures that when two strings are the same, the min edit distance metric has a cost of 0. """ assert 0 == min_edit_distance("same_string", "same_string") assert 0 == min_edit_distance("abc", "abc") def test_min_edit_distance(): """ General test cases for min edit distance between two words. """ assert 1 == min_edit_distance("cat", "cats") assert 4 == min_edit_distance("door", "gore") <file_sep>/lib/lunch_bot.py from typing import Any from typing import Dict from typing import Callable import zulip from lib import state_handler from lib.cron import PersistentCron from lib.handlers import HandlerParams from lib.handlers.alert_leaving import handle_alert_leaving from lib.handlers.delete_plan import handle_delete_plan from lib.handlers.help import handle_help from lib.handlers.make_plan import handle_make_plan from lib.handlers.my_plans import handle_my_plans from lib.handlers.not_a_command import handle_not_a_command from lib.handlers.reset import handle_reset from lib.handlers.rsvp import handle_rsvp from lib.handlers.show_plans import handle_show_plans from lib.handlers.un_rsvp import handle_un_rsvp from lib.models.message import Message class LunchBotHandler(object): """ Let's get lunch! """ def __init__( self, client: zulip.Client, cron: PersistentCron, storage: state_handler.StateHandler, ): self.client = client self.cron = cron self.storage = storage self.default_handler: Callable[[HandlerParams], None] = handle_not_a_command self.handlers: Dict[str, Callable[[HandlerParams], None]] = { "alert-leaving": handle_alert_leaving, "delete-plan": handle_delete_plan, "help": handle_help, "make-plan": handle_make_plan, "my-plans": handle_my_plans, "reset": handle_reset, "rsvp": handle_rsvp, "show-plans": handle_show_plans, "un-rsvp": handle_un_rsvp, } def usage(self): return """ lunch-bot is a bot that helps Recursers organize groups to get lunch! Type help to get started. """ def safe_handle_message(self, message: Dict[str, Any]): """ A safe wrapper around handle_message that logs all errors, instead of crashing the bot. Useful for running in production where bugs aren't a problem, they're just log entries! """ try: self.handle_message(message) except KeyboardInterrupt as e: raise e except Exception as e: print(e) def handle_message(self, message: Dict[str, Any]): """ Handles messages from users on Zulip. Handles the provided command, and responds with the appropriate message. Delegates responsibilities to handlers defined in lib.handlers.* """ # If the bot was the sender of the message, then skip processing the # message. parsed_message = Message.parse_zulip_message(message) args = parsed_message.content.split() if parsed_message.sender_email == self.client.email or len(args) == 0: return self.handlers.get(args[0], self.default_handler)( HandlerParams( args=args, client=self.client, cron=self.cron, message=parsed_message, storage=self.storage, ), ) <file_sep>/lib/handlers/un_rsvp.py from lib import common from lib.handlers import HandlerParams from lib.models.user import User def handle_un_rsvp(params: HandlerParams): if len(params.args) < 2 or len(params.args) > 3: common.send_reply( params.client, params.message, "Oops! The un-rsvp command requires more information. Type help for formatting instructions.", ) return time = None if len(params.args) == 3: time = common.parse_time(params.args[2]) if ( not params.storage.contains(params.storage.PLANS_ENTRY) or len(params.storage.get(params.storage.PLANS_ENTRY)) == 0 ): common.send_reply( params.client, params.message, "There are no lunch plans to remove your RSVP from! Why not add one using the make-plan command?", ) return plans = params.storage.get(params.storage.PLANS_ENTRY) matching_plans = common.get_matching_plans( params.args[1], params.storage, time=time ) if len(matching_plans) == 0: common.send_reply( params.client, params.message, "That lunch_id doesn't exist! Type show-plans to see each lunch_id and its associated lunch plan.", ) return if len(matching_plans) > 1: common.send_reply( params.client, params.message, "There are multiple lunches with that lunch_id. Please reissue the command with the time of the lunch" " you're interested in:\n{}".format( "\n".join([common.render_plan_short(plan) for plan in matching_plans]), ), ) return user = User.get_sender(params.message) selected_plan = matching_plans[0] if user not in selected_plan.rsvps: common.send_reply( params.client, params.message, "Oops! It looks like you haven't RSVP'd to this lunch_id!", ) return selected_plan.rsvps.remove(user) plans[selected_plan.uuid] = selected_plan params.storage.put(params.storage.PLANS_ENTRY, plans) common.send_reply( params.client, params.message, "You've successful un-RSVP'd to lunch at {}.".format(selected_plan.restaurant), ) <file_sep>/tests/lib/handlers/test_not_a_command.py from lib.handlers.not_a_command import handle_not_a_command def test_handle_not_a_command_success( mock_send_reply, make_handler_params, ): """ Ensures that the handle_not_a_command handler provides the correct response when an incorrect command is issued. """ params = make_handler_params("blargh") handle_not_a_command(params) mock_send_reply.assert_called_with( params.client, params.message, "Oops! 'blargh' is not a valid lunch-bot command! Type help for a list of commands I understand :-)", ) <file_sep>/lib/handlers/show_plans.py from lib import common from lib.handlers import HandlerParams def handle_show_plans(params: HandlerParams): if ( not params.storage.contains(params.storage.PLANS_ENTRY) or len(params.storage.get(params.storage.PLANS_ENTRY)) == 0 ): common.send_reply( params.client, params.message, "There are no lunch plans to show! Why not add one using the make-plan command?", ) return plans = params.storage.get(params.storage.PLANS_ENTRY) common.send_reply( params.client, params.message, "\n".join([common.render_plan(plan) for _, plan in plans.items()]), ) <file_sep>/lib/cron.py import sched import threading import time from typing import Callable from typing import Dict from typing import Optional import uuid import zulip from lib import common from lib.events import EventGenerator from lib.state_handler import StateHandler class Cron: """ Provides a cron-like interface for other classes to use. Wraps around sched to provide a more user-friendly interface to schedule and execute events. """ def __init__(self): self.scheduler = sched.scheduler(time.time, time.sleep) self.scheduled_events: Dict[uuid.UUID, sched.Event] = {} self.scheduler_thread = threading.Thread(daemon=True, target=self._event_loop,) self.scheduler_thread.start() def _event_loop(self): """ Runs in the background in self.scheduler_thread to run Callables when they're scheduled. """ while True: self.scheduler.run(blocking=True) time.sleep(1) def add_event( self, event_time: float, event_action: Callable, event_id: Optional[uuid.UUID] = None, ) -> uuid.UUID: """ Adds an event to the queue at a given time. """ if event_id is None: event_id = uuid.uuid4() self.scheduled_events[event_id] = self.scheduler.enterabs( event_time, 0, event_action, ) return event_id def remove_event(self, event_id: uuid.UUID) -> bool: """ Given an event's ID, removes it from the queue. Returns True iff the the event ID exists in the queue. """ if event_id not in self.scheduled_events: return False try: self.scheduler.cancel(self.scheduled_events[event_id]) except ValueError: return False self.scheduled_events.pop(event_id) return True class CronEvent: """ Serializable representation of an event that may be scheduled. """ def __init__( self, *, event_generator: EventGenerator, event_id: uuid.UUID, event_time: float, ): self.event_generator = event_generator self.event_id = event_id self.event_time = event_time def __eq__(self, other: object) -> bool: if not isinstance(other, CronEvent): return False return ( self.event_generator == other.event_generator and self.event_id == other.event_id and self.event_time == other.event_time ) class PersistentCron: """ A persistent form of Cron that automatically saves queued events to disk. Reloads them when starting up, so that events can be rescheduled after a restart. """ def __init__(self, client: zulip.Client, storage: StateHandler): self.cron = Cron() self.client = client self.storage = storage events = self._get_persistent_events() rm_events = [] now = common.get_now().timestamp() for event_id, event in events.items(): if event.event_time < now: rm_events.append(event_id) continue self.cron.add_event( event.event_time, event.event_generator.generate_action(self.client, self.storage), event.event_id, ) # Removing events outside of the earlier for loop so we don't break the # iterator. for rm_event_id in rm_events: events.pop(rm_event_id) self.storage.put(StateHandler.EVENTS_ENTRY, events) def _get_persistent_events(self) -> Dict[uuid.UUID, CronEvent]: """ Gets the persisted copy of events from the database. If it doesn't exist, create it. """ if not self.storage.contains(StateHandler.EVENTS_ENTRY): self.storage.put(StateHandler.EVENTS_ENTRY, {}) return self.storage.get(StateHandler.EVENTS_ENTRY) def add_event( self, event_time: float, event_generator: EventGenerator, event_id: Optional[uuid.UUID] = None, ) -> uuid.UUID: """ Adds an event to the queue, and persists it to disk so that it can be reloaded later. """ event_id = self.cron.add_event( event_time, event_generator.generate_action(self.client, self.storage), event_id, ) events = self._get_persistent_events() events[event_id] = CronEvent( event_generator=event_generator, event_id=event_id, event_time=event_time, ) self.storage.put(StateHandler.EVENTS_ENTRY, events) return event_id def remove_event(self, event_id: uuid.UUID) -> bool: """ Removes an event from the queue, and """ events = self._get_persistent_events() persistent_removed = False if event_id in events: persistent_removed = True events.pop(event_id) queue_removed = self.cron.remove_event(event_id) return persistent_removed or queue_removed <file_sep>/lib/handlers/alert_leaving.py from lib import common from lib.controllers.alert_leaving import alert_leaving from lib.handlers import HandlerParams def handle_alert_leaving(params: HandlerParams): """ Alerts members of a plan about when their plan is going to leave. """ if len(params.args) < 2 or len(params.args) > 3: common.send_reply( params.client, params.message, "Oops! The alert-leaving command requires 1 or 2 arguments. Type" " help for formatting instructions.", ) return time = None if len(params.args) == 3: time = common.parse_time(params.args[2]) if ( not params.storage.contains(params.storage.PLANS_ENTRY) or len(params.storage.get(params.storage.PLANS_ENTRY)) == 0 ): common.send_reply( params.client, params.message, "There are no existing plans. Why not create one?", ) return matching_plans = common.get_matching_plans( params.args[1], params.storage, time=time ) if len(matching_plans) == 0: common.send_reply( params.client, params.message, "That lunch_id doesn't exist! Type show-plans to see each lunch_id" " and its associated lunch plan.", ) return if len(matching_plans) > 1: common.send_reply( params.client, params.message, "There are multiple lunches with that lunch_id. Please reissue the" " command with the time of the lunch you're interested in:\n" "{}".format( "\n".join([common.render_plan_short(plan) for plan in matching_plans]), ), ) return alert_leaving(params.client, matching_plans[0]) <file_sep>/requirements.txt pytest==5.3.2 pytest-mock==2.0.0 zulip==0.6.3 <file_sep>/lib/handlers/my_plans.py from lib import common from lib.handlers import HandlerParams from lib.models.user import User def handle_my_plans(params: HandlerParams): if ( not params.storage.contains(params.storage.PLANS_ENTRY) or len(params.storage.get(params.storage.PLANS_ENTRY)) == 0 ): common.send_reply( params.client, params.message, "There are no active lunch plans right now! Why not add one using the make-plan command?", ) return plans = params.storage.get(params.storage.PLANS_ENTRY) user = User.get_sender(params.message) common.send_reply( params.client, params.message, "Here are the lunches you've RSVP'd to:\n{}".format( "\n".join( [ common.render_plan(plan) for _, plan in plans.items() if user in plan.rsvps ] ) ), ) <file_sep>/tests/lib/handlers/test_rsvp.py from lib.handlers.rsvp import handle_rsvp from lib.models.plan import Plan from lib.models.user import User def test_handle_rsvp_bad_args( mock_send_reply, make_handler_params, ): """ Ensures that the RSVP handler will fail as expected when we provide an incorrect number of arguments. """ params = make_handler_params("rsvp tjs 12:30 fasdf") handle_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "Oops! The rsvp command requires more information. Type help for formatting instructions.", ) def test_handle_rsvp_no_plans( mock_send_reply, make_handler_params, ): """ Ensures that handle_rsvp fails as expected when there are no plans. """ params = make_handler_params("rsvp tjs") handle_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "There are no lunch plans to RSVP to! Why not add one using the make-plan command?", ) def test_handle_rsvp_bad_id( mock_send_reply, make_handler_params, make_time, ): """ Ensures that handle_rsvp failes correctly when the plan ID is not malformed but does not correspond to a plan. """ params = make_handler_params("rsvp not-tjs") plan = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = {plan.uuid: plan} handle_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "That lunch_id doesn't exist! Type show-plans to see each lunch_id and its associated lunch plan.", ) def test_handle_rsvp_already_rsvpd( mock_send_reply, mock_user, make_handler_params, make_time, ): """ Ensures handle_rsvp fails correctly when the user is already RSVP'd to the event to which they're trying to rsvp. """ params = make_handler_params("rsvp tjs") plan = Plan("tjs", make_time(12, 30), [mock_user]) params.storage.get.return_value = {plan.uuid: plan} handle_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "You've already RSVP'd to this lunch_id! Type my-plans to show all of your current lunch plans.", ) def test_handle_rsvp_ambiguous( mock_send_reply, make_handler_params, make_time, ): """ Ensures that, when the query is ambiguous, handle_rsvp alerts the user and asks them to disambiguate with a time. """ params = make_handler_params("rsvp tjs") plan1 = Plan("tjs", make_time(11, 00), []) plan2 = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan1.uuid: plan1, plan2.uuid: plan2, } handle_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, """There are multiple lunches with that lunch_id. Please reissue the command with the time of the lunch you're interested in: tjs @ 11:00am tjs @ 12:30pm""", ) def test_handle_rsvp_disambiguate( mock_send_reply, mock_user, make_handler_params, make_time, ): """ Ensures that, when there are multiple lunches, the user can construct a query to disambiguate between them. """ params = make_handler_params("rsvp tjs 12:30") plan1 = Plan("tjs", make_time(11, 00), []) plan2 = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan1.uuid: plan1, plan2.uuid: plan2, } handle_rsvp(params) params.storage.put.assert_called_with( params.storage.PLANS_ENTRY, {plan1.uuid: plan1, plan2.uuid: Plan("tjs", make_time(12, 30), [mock_user])}, ) mock_send_reply.assert_called_with( params.client, params.message, "Thanks for RSVPing to lunch at tjs! Enjoy your food, Test Sender!", ) def test_handle_rsvp_success( mock_send_reply, mock_user, make_handler_params, make_time, ): """ Ensures that handle_rsvp functions correctly when the preconditions are met. """ params = make_handler_params("rsvp tjs") plan = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan.uuid: plan, } handle_rsvp(params) params.storage.put.assert_called_with( params.storage.PLANS_ENTRY, {plan.uuid: Plan("tjs", make_time(12, 30), [mock_user])}, ) mock_send_reply.assert_called_with( params.client, params.message, "Thanks for RSVPing to lunch at tjs! Enjoy your food, Test Sender!", ) <file_sep>/lib/controllers/alert_leaving.py import zulip from lib import common from lib.models.plan import Plan def alert_leaving(client: zulip.Client, plan: Plan): """ Controller for alert_leaving. Executes if everything else goes well. """ now = common.get_now() client.send_message( { "type": "private", "to": [user.email for user in plan.rsvps], "content": "Heads up! You're going to {} in {}".format( plan.restaurant, str(plan.time - now), ), } ) <file_sep>/main.py import os from os import path import sys from typing import List import zulip from lib import lunch_bot from lib import state_handler from lib.cron import PersistentCron ZULIPRC_FILE_NAME = ".zuliprc" def main(args: List[str]): client = zulip.Client( config_file=path.join(path.abspath(os.getcwd()), ZULIPRC_FILE_NAME) ) try: with state_handler.StateHandler() as storage: cron = PersistentCron(client, storage) bot = lunch_bot.LunchBotHandler(client, cron, storage) client.call_on_each_message(bot.safe_handle_message) except KeyboardInterrupt: pass print() if __name__ == "__main__": main(sys.argv) <file_sep>/README.md # lunch-bot Managing lunch plans at the [Recurse Center](https://recurse.com) (RC)! At the time of development RC uses a bunch of laminated pieces of paper to plan lunch groups. We thought: "Hey, we're all programmers, why are we _getting out of our chairs_ and like, _using physical media_ when we could type on [Zulip](https://zulip.com/) instead?" Lunch Bot solves that problem! ## Interface There's a really high chance that this README isn't updated when we add new features (you know how it do), so if you're using Lunch Bot, then please just use the `help` command. The available commands are: * `help` - Displays all available commands that Lunch Bot understands * `make-plan [restaurant] [time]` - Creates a lunch plan for a given place and time. [restaurant] and [time] must not contain any spaces. * `show-plans` - Shows all active lunch plans along with their associated lunch_id * `rsvp [lunch_id]` - RSVPs to a certain lunch plan, given its [lunch_id]. To see every lunch_id, use the show-plans command. * `my-plans` - Shows all lunch plans you have currently RSVP'd to. * `un-rsvp [lunch_id]` - Removes your RSVP from a certain lunch plan, given its [lunch_id]. To see every lunch_id, use the show-plans command. * `delete-plan [lunch_id]` - Deletes a certain lunch plan, given its [lunch_id]. To see every lunch_id, use the show-plans command. ## Contributing If you're interested in contributing to Lunch Bot: great! We only have one request: use [pre-commit](https://pre-commit.com/). Once it's set up, it will run [black](https://github.com/psf/black) and [mypy](http://mypy-lang.org/) every time to commit. ```bash # Install pre-commit $ brew install pre-commit # On mac $ pip install pre-commit # Everywhere else # Register pre-commit in the repo $ pre-commit install ``` ### Tasks If something should be done, you don't want to do it now, just make an issue and leave a TODO. In this repo, it's good practice to: 1. Create an issue with the appropriate tag (e.g. "enhancement," "bug," etc.) and assign it to the "Lunch Bot" project. 2. Leave a TODO in your code that looks like `# TODO (#<issue number>): Description` ## License MIT licensed. Refer to `LICENSE` document. <file_sep>/lib/handlers/rsvp.py from lib import common from lib.handlers import HandlerParams from lib.models.user import User def handle_rsvp(params: HandlerParams): if len(params.args) < 2 or len(params.args) > 3: common.send_reply( params.client, params.message, "Oops! The rsvp command requires more information. Type help for formatting instructions.", ) return time = None if len(params.args) == 3: time = common.parse_time(params.args[2]) if ( not params.storage.contains(params.storage.PLANS_ENTRY) or len(params.storage.get(params.storage.PLANS_ENTRY)) == 0 ): common.send_reply( params.client, params.message, "There are no lunch plans to RSVP to! Why not add one using the make-plan command?", ) return plans = params.storage.get(params.storage.PLANS_ENTRY) matching_plans = common.get_matching_plans( params.args[1], params.storage, time=time ) if len(matching_plans) == 0: common.send_reply( params.client, params.message, "That lunch_id doesn't exist! Type show-plans to see each lunch_id and its associated lunch plan.", ) return if len(matching_plans) > 1: common.send_reply( params.client, params.message, "There are multiple lunches with that lunch_id. Please reissue the command with the time of the lunch" " you're interested in:\n{}".format( "\n".join([common.render_plan_short(plan) for plan in matching_plans]), ), ) return user = User.get_sender(params.message) selected_plan = matching_plans[0] if user in selected_plan.rsvps: common.send_reply( params.client, params.message, "You've already RSVP'd to this lunch_id! Type my-plans to show all of your current lunch plans.", ) return selected_plan.rsvps.append(user) plans[selected_plan.uuid] = selected_plan params.storage.put(params.storage.PLANS_ENTRY, plans) common.send_reply( params.client, params.message, "Thanks for RSVPing to lunch at {}! Enjoy your food, {}!".format( selected_plan.restaurant, user.full_name, ), ) <file_sep>/lib/models/message.py from typing import Any from typing import Dict from typing import List # For reference, this is an example of a raw Zulip message. If you need more # fields, then you can add any included here into the Message constructor. # # { # "id": 1234, # "sender_id": 5678, # "content": contents, # "recipient_id": 1337, # "timestamp": int(time.time()), # "client": "website", # "subject": "", # "subject_links": [], # "is_me_message": False, # "reactions": [], # "submessages": [], # "sender_full_name": "<NAME>", # "sender_short_name": "tester", # "sender_email": "<EMAIL>", # "sender_realm_str": "recurse", # "display_recipient": [ # { # "email": "<EMAIL>", # "full_name": "<NAME>", # "short_name": "tester", # "id": 5678, # "is_mirror_dummy": False, # }, # { # "id": 1337, # "email": "<EMAIL>", # "full_name": "<NAME>", # "short_name": "lunch-bot-bot", # "is_mirror_dummy": False, # }, # ], # "type": "private", # "avatar_url": "https://fakeurl.com/fake_picture.png", # "content_type": "text/x-markdown", # } class DisplayRecipient: def __init__( self, email: str = "", full_name: str = "", id: int = 0, is_mirror_dummy: bool = False, short_name: str = "", ): self.email = email self.full_name = full_name self.id = (id,) self.is_mirror_dummy = is_mirror_dummy self.short_name = short_name @staticmethod def parse_display_recipient( display_recipient: Dict[str, Any] ) -> "DisplayRecipient": """ Parses an individual display recipient. Should NOT be called on the list of display recipients entitled 'display_recipient'. """ return DisplayRecipient( display_recipient["email"], display_recipient["full_name"], display_recipient["id"], display_recipient["is_mirror_dummy"], display_recipient["short_name"], ) @staticmethod def parse_display_recipients( display_recipients: List[Dict[str, Any]] ) -> List["DisplayRecipient"]: """ Parses a list of display recipients. Should be used on the entire list of display recipients entired 'display_recipient'. """ return [ DisplayRecipient.parse_display_recipient(display_recipient) for display_recipient in display_recipients ] class Message: def __init__( self, content: str = "", display_recipient: List[DisplayRecipient] = [], sender_email: str = "", sender_full_name: str = "", sender_id: int = 0, ): self.content = content self.display_recipient = display_recipient self.sender_email = sender_email self.sender_full_name = sender_full_name self.sender_id = sender_id @staticmethod def parse_zulip_message(zulip_message: Dict[str, Any]) -> "Message": """ Parses out a complete Zulip message into a well structured object. Assumes that all normal fields are present, and does not attempt to do any error checking. """ return Message( content=zulip_message["content"], display_recipient=DisplayRecipient.parse_display_recipients( zulip_message["display_recipient"], ), sender_email=zulip_message["sender_email"], sender_full_name=zulip_message["sender_full_name"], sender_id=zulip_message["sender_id"], ) <file_sep>/tests/lib/handlers/test_make_plan.py import uuid from lib.handlers.make_plan import handle_make_plan from lib.models.plan import Plan from lib.models.user import User def test_handle_make_plan_bad_args( mock_send_reply, make_handler_params, ): """ Ensures that, when we provide handle_make_plan with an improper number of arugments, it does not execute and provides us with the correct error params.message. """ params = make_handler_params("make-plan tjs 12:30 and-another-arg") handle_make_plan(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "Oops! The make-plan command requires more information. Type help for formatting instructions.", ) def test_handle_make_plan_existing_plan( mock_send_reply, make_handler_params, make_time, ): """ Ensures that, when there is already an existing plan with the intended name, we prevent the user from making another one. """ params = make_handler_params("make-plan tjs 12:30") plan = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = {plan.uuid: plan} handle_make_plan(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "Sorry, there is already a plan with that name and time. How about you RSVP instead?", ) def test_handle_make_plan_success( mocker, mock_send_reply, mock_user, make_handler_params, make_time, ): """ Ensures that make_plan correctly inserts a plan when the arguments are correct. """ params = make_handler_params("make-plans tjs 12:30") mocker.patch("uuid.uuid4", return_value="test_uuid") params.storage.get.return_value = {} handle_make_plan(params) params.storage.put.assert_called_with( params.storage.PLANS_ENTRY, {"test_uuid": Plan("tjs", make_time(12, 30), [mock_user])}, ) params.cron.add_event.assert_called() mock_send_reply.assert_called_with( params.client, params.message, "I have added your plan! Enjoy lunch, Test Sender!", ) <file_sep>/tests/lib/test_cron.py import uuid from lib.cron import CronEvent from lib.cron import PersistentCron from lib.events import AlertLeavingGenerator from lib.models.plan import Plan from lib.state_handler import StateHandler def test_persistent_cron_add_event(mock_client, mock_storage, mock_user, make_time): mock_storage.get.return_value = {} cron = PersistentCron(mock_client, mock_storage) leaving_generator = AlertLeavingGenerator( Plan("tjs", make_time(12, 30), [mock_user],) ) event_id = cron.add_event(1337, leaving_generator) cron.storage.put.assert_called_with( StateHandler.EVENTS_ENTRY, { event_id: CronEvent( event_generator=leaving_generator, event_id=event_id, event_time=1337, ) }, ) def test_persistent_cron_remove_event(mock_client, mock_storage, mock_user, make_time): event_id = uuid.uuid4() leaving_generator = AlertLeavingGenerator( Plan("tjs", make_time(12, 30), [mock_user]) ) cron_event = CronEvent( event_generator=leaving_generator, event_id=event_id, event_time=make_time(12, 15).timestamp(), ) mock_storage.get.return_value = { event_id: cron_event, } cron = PersistentCron(mock_client, mock_storage) assert cron.remove_event(event_id) <file_sep>/lib/common.py from datetime import datetime from collections import defaultdict import re from typing import Callable from typing import Dict from typing import Optional from typing import List import zulip from lib.state_handler import StateHandler from lib.models.message import Message from lib.models.plan import Plan def send_reply(client: zulip.Client, message: Message, reply: str): """ Given an message object, send a string reply. Uses the metadata from the original message to determine to whom the response should be addressed. """ client.send_message( { "type": "private", "to": [ recipient.email for recipient in message.display_recipient if client.email != recipient.email ], "content": reply, } ) def render_plan(plan: Plan, short: bool = False) -> str: """ Standard function to render a Plan so that it's uniform across all handlers. """ return "{} @ {}, {} RSVP{}".format( plan.restaurant, render_plan_time(plan), len(plan.rsvps), "s" if len(plan.rsvps) != 1 else "", ) def render_plan_short(plan: Plan) -> str: """ Rendering a plan without the RSVP information. """ return "{} @ {}".format(plan.restaurant, render_plan_time(plan)) def render_plan_time(plan: Plan) -> str: """ Renders the time of a plan as we would want it to appear to the user. """ return plan.time.strftime("%I:%M%p").lower() def get_now() -> datetime: """ Returns the current time. Exactly equivalent to datetime.now(). This function only exists because it can be mocked, but datetime.now() cannot. """ return datetime.now() def min_edit_distance( source: str, target: str, insert_cost: Callable[[str], int] = lambda char: 1, delete_cost: Callable[[str], int] = lambda char: 1, replace_cost: Callable[[str, str], int] = lambda source_char, target_char: 0 if source_char == target_char else 2, ) -> int: """ Returns the minimum edit distance from between two strings. Allows the user to customize the functions used to calculate insert, delete, and replacement costs. """ costs: Dict[int, Dict[int, int]] = defaultdict(lambda: defaultdict(lambda: 0)) for i in range(len(source)): costs[i + 1][0] = costs[i][0] + delete_cost(source[i]) for j in range(len(target)): costs[0][j + 1] = costs[0][j] + insert_cost(target[j]) for j, target_char in enumerate(target): for i, source_char in enumerate(source): costs[i + 1][j + 1] = min( costs[i][j + 1] + delete_cost(target_char), costs[i + 1][j] + insert_cost(source_char), costs[i][j] + replace_cost(source_char, target_char), ) return costs[len(source)][len(target)] def parse_time(date_str: str) -> datetime: """ Parses out a string-formatted date into a well-structured datetime in UTC. Supports any of the following formats: - hh:mm In this format, we treat the value of the hh section to be 24hr format. If a user types in 1:00, it will be interpreted as 1am, not 1pm. - hh:mm(am|pm) In this format, we treat the value of the hh section to be 12hr format, and we rely on the am/pm flag to determine whether it is in the morning or the afternoon. """ match = re.match(r"(\d?\d):(\d\d)(am|pm)?", date_str) if match is None: raise ValueError() groups = match.groups() hour = int(groups[0]) minute = int(groups[1]) if groups[2] == "pm" and hour < 12: hour += 12 now = get_now() time = datetime( year=now.year, month=now.month, day=now.day, hour=hour, minute=minute, second=0, microsecond=0, ) return time def get_matching_plans( restaurant: str, storage: StateHandler, time: Optional[datetime] = None, ) -> List[Plan]: """ Returns a list of matching plans, given a restaurant name and an optional time. """ matching_plans = [] plans = storage.get(StateHandler.PLANS_ENTRY) for _, plan in plans.items(): if plan.restaurant == restaurant and (time is None or plan.time == time): matching_plans.append(plan) return matching_plans <file_sep>/tests/lib/handlers/test_delete_plan.py from lib.handlers.delete_plan import handle_delete_plan from lib.models.plan import Plan def test_handle_delete_plan_bad_args( mock_send_reply, make_handler_params, ): """ Ensures that, when handle_delete_plan is provided with too few or too many arguments, it does not perform any action, and that it sends the correct response. """ params = make_handler_params("delete-plan") handle_delete_plan(params) mock_send_reply.assert_called_with( params.client, params.message, "Oops! The delete-plan command requires more information. Type help for formatting instructions.", ) def test_handle_delete_plan_no_plans( mock_send_reply, make_handler_params, ): """ Ensures that handle_delete_plan functions correctly when the StateHandler has no plans available to use. """ params = make_handler_params("delete-plan tjs") handle_delete_plan(params) mock_send_reply.assert_called_with( params.client, params.message, "There are no lunch plans to delete! Why not add one using the make-plan command?", ) def test_handle_delete_plan_bad_id( mock_send_reply, make_handler_params, make_time, ): """ Ensures that handle_delete_plan functions correctly when the user provides an integer ID that does not correspond to a plan. """ params = make_handler_params("delete-plan not-tjs") plan = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = {plan.uuid: plan} handle_delete_plan(params) mock_send_reply.assert_called_with( params.client, params.message, "That lunch_id doesn't exist! Type show-plans to see each lunch_id and its associated lunch plan.", ) def test_handle_delete_plan_ambiguous( mock_send_reply, make_handler_params, make_time, ): """ Tests that when there are multiple plans with the same name, delete_plan prompts the user to disambiguate a lunch. """ params = make_handler_params("delete-plan tjs") plan1 = Plan("tjs", make_time(11, 00), []) plan2 = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan1.uuid: plan1, plan2.uuid: plan2, } handle_delete_plan(params) mock_send_reply.assert_called_with( params.client, params.message, "There are multiple lunches with that lunch_id. Please reissue the command with the time of the lunch you're" " interested in:\n" "tjs @ 11:00am\n" "tjs @ 12:30pm", ) def test_handle_delete_plan_disambiguate( mock_send_reply, make_handler_params, make_time, ): """ Tests that when there are multiple plans with the same name, delete_plan lets the user disambiguate with a time. """ params = make_handler_params("delete-plan tjs 12:30") plan1 = Plan("tjs", make_time(11, 00), []) plan2 = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan1.uuid: plan1, plan2.uuid: plan2, } handle_delete_plan(params) params.storage.put.assert_called_with( params.storage.PLANS_ENTRY, {plan1.uuid: plan1} ) params.cron.remove_event.assert_called_with(plan2.uuid) mock_send_reply.assert_called_with( params.client, params.message, "You've successfully deleted lunch tjs @ 12:30pm.", ) def test_handle_delete_plan_success( mock_send_reply, make_handler_params, make_time, ): params = make_handler_params("delete-plan tjs") plan = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = {plan.uuid: plan} handle_delete_plan(params) params.storage.put.assert_called_with(params.storage.PLANS_ENTRY, {}) params.cron.remove_event.assert_called_with(plan.uuid) mock_send_reply.assert_called_with( params.client, params.message, "You've successfully deleted lunch tjs @ 12:30pm.", ) <file_sep>/tests/lib/handlers/test_reset.py from lib.handlers.reset import handle_reset def test_handle_reset_success( mock_send_reply, make_handler_params, ): """ Ensures that, when asked to reset, Lunch Bot will only do so when confirmed. """ params = make_handler_params("reset") handle_reset(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "This will wipe all current lunches from my records. If you wish to continue, please type 'reset confirm'.", ) def test_handle_rest_confirm_success( mock_send_reply, make_handler_params, ): """ Ensures that, when asked to reset, Lunch Bot will only do so when confirmed. """ params = make_handler_params("reset confirm") handle_reset(params) params.storage.put.assert_called_with(params.storage.PLANS_ENTRY, {}) mock_send_reply.assert_not_called() <file_sep>/lib/handlers/make_plan.py from datetime import timedelta from lib import common from lib import events from lib.handlers import HandlerParams from lib.models.plan import Plan from lib.models.user import User def handle_make_plan(params: HandlerParams): if len(params.args) != 3: common.send_reply( params.client, params.message, "Oops! The make-plan command requires more information. Type help for formatting instructions.", ) return try: plan_time = common.parse_time(params.args[2]) except ValueError: common.send_reply( params.client, params.message, "Sorry, the time you entered could not be used because it is not a valid date format.", ) return now = common.get_now() if plan_time < now: common.send_reply( params.client, params.message, "Sorry, you can't plan for a lunch before the current time.", ) return if not params.storage.contains(params.storage.PLANS_ENTRY): params.storage.put(params.storage.PLANS_ENTRY, {}) plans = params.storage.get(params.storage.PLANS_ENTRY) for _, plan in plans.items(): if plan.restaurant == params.args[1] and plan.time == plan_time: common.send_reply( params.client, params.message, "Sorry, there is already a plan with that name and time. How about you RSVP instead?", ) return user = User.get_sender(params.message) plan = Plan(params.args[1], plan_time, [user]) plans = params.storage.get(params.storage.PLANS_ENTRY) plans[plan.uuid] = plan params.storage.put(params.storage.PLANS_ENTRY, plans) common.send_reply( params.client, params.message, "I have added your plan! Enjoy lunch, {}!".format(user.full_name), ) params.cron.add_event( (plan.time - timedelta(minutes=15)).timestamp(), events.AlertLeavingGenerator(plan), plan.uuid, ) params.cron.add_event( plan.time.timestamp(), events.DeletePlanGenerator(plan), ) <file_sep>/lib/controllers/delete_plan.py import zulip from lib.models.plan import Plan from lib.state_handler import StateHandler def delete_plan(client: zulip.Client, storage: StateHandler, plan: Plan): """ Backend for deleting a plan from the database. """ plans = storage.get(StateHandler.PLANS_ENTRY) if plan.uuid in plans: del plans[plan.uuid] storage.put(storage.PLANS_ENTRY, plans) <file_sep>/lib/handlers/__init__.py from typing import List import zulip from lib.cron import PersistentCron from lib.models.message import Message from lib.state_handler import StateHandler class HandlerParams: """ A struct that represents the arguments a handler can receive. Used to extend the possible arguments without having to rewrite each of the function definitions each time. """ def __init__( self, *, args: List[str], client: zulip.Client, cron: PersistentCron, message: Message, storage: StateHandler, ): self.args = args self.client = client self.cron = cron self.message = message self.storage = storage <file_sep>/lib/handlers/reset.py from lib import common from lib.handlers import HandlerParams def handle_reset(params: HandlerParams): if len(params.args) == 2 and params.args[1] == "confirm": params.storage.put(params.storage.PLANS_ENTRY, {}) return common.send_reply( params.client, params.message, "This will wipe all current lunches from my records. If you wish to continue, please type 'reset confirm'.", ) <file_sep>/lib/handlers/not_a_command.py from lib import common from lib.handlers import HandlerParams def handle_not_a_command(params: HandlerParams): common.send_reply( params.client, params.message, "Oops! '{}' is not a valid lunch-bot command! Type help for a list of commands I understand :-)".format( params.args[0], ), ) <file_sep>/tests/lib/handlers/test_un_rsvp.py from lib.handlers.un_rsvp import handle_un_rsvp from lib.models.plan import Plan from lib.models.user import User def test_handle_un_rsvp_bad_args( mock_send_reply, make_handler_params, ): """ Ensures that handle_un_rsvp fails as expected when we don't provide the correct number of arguments. """ params = make_handler_params("un-rsvp tjs adfg as") handle_un_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "Oops! The un-rsvp command requires more information. Type help for formatting instructions.", ) def test_handle_un_rsvp_no_lunches( mock_send_reply, make_handler_params, ): """ Ensures that handle_un_rsvp fails as expected when there are not lunches to un-rsvp from. """ params = make_handler_params("un-rsvp tjs") handle_un_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "There are no lunch plans to remove your RSVP from! Why not add one using the make-plan command?", ) def test_handle_un_rsvp_bad_id( mock_send_reply, mock_user, make_handler_params, make_time, ): """ Ensures that handle_un_rsvp fails as expected when the user provides an id that is out of range of our available lunches. """ params = make_handler_params("un-rsvp not-tjs") plan = Plan("tjs", make_time(12, 30), [mock_user]) params.storage.get.return_value = { plan.uuid: plan, } handle_un_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "That lunch_id doesn't exist! Type show-plans to see each lunch_id and its associated lunch plan.", ) def test_handle_un_rsvp_not_rsvpd( mock_send_reply, make_handler_params, make_time, ): """ Ensures that handle_un_rsvp fails as expected when the user is not already RSVP'd to the event. """ params = make_handler_params("un-rsvp tjs") plan = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan.uuid: plan, } handle_un_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, "Oops! It looks like you haven't RSVP'd to this lunch_id!", ) def test_handle_un_rsvp_ambiguous( mock_send_reply, make_handler_params, make_time, ): """ Ensures that, when the user has provided an ambiguous query, handle_un_rsvp prompts them to disambiguate. """ params = make_handler_params("un-rsvp tjs") plan1 = Plan("tjs", make_time(11, 00), []) plan2 = Plan("tjs", make_time(12, 30), []) params.storage.get.return_value = { plan1.uuid: plan1, plan2.uuid: plan2, } handle_un_rsvp(params) params.storage.put.assert_not_called() mock_send_reply.assert_called_with( params.client, params.message, """There are multiple lunches with that lunch_id. Please reissue the command with the time of the lunch you're interested in: tjs @ 11:00am tjs @ 12:30pm""", ) def test_handle_un_rsvp_disambiguate( mock_send_reply, mock_user, make_handler_params, make_time, ): """ Ensures that, when the user has provided an ambiguous query, handle_un_rsvp prompts them to disambiguate. """ params = make_handler_params("un-rsvp tjs 12:30") plan1 = Plan("tjs", make_time(11, 00), []) plan2 = Plan("tjs", make_time(12, 30), [mock_user]) params.storage.get.return_value = { plan1.uuid: plan1, plan2.uuid: plan2, } handle_un_rsvp(params) params.storage.put.assert_called_with( params.storage.PLANS_ENTRY, {plan1.uuid: plan1, plan2.uuid: Plan("tjs", make_time(12, 30), []),}, ) mock_send_reply.assert_called_with( params.client, params.message, "You've successful un-RSVP'd to lunch at tjs." ) def test_handle_un_rsvp_success( mock_send_reply, mock_user, make_handler_params, make_time, ): """ Ensures that handle_un_rsvp succeeds when the required preconditions are met. """ params = make_handler_params("un-rsvp tjs") plan = Plan("tjs", make_time(12, 30), [mock_user]) params.storage.get.return_value = { plan.uuid: plan, } handle_un_rsvp(params) params.storage.put_assert_called_with( params.storage.PLANS_ENTRY, Plan("tjs", make_time(12, 30), []) ) mock_send_reply.assert_called_with( params.client, params.message, "You've successful un-RSVP'd to lunch at tjs." ) <file_sep>/tests/conftest.py from datetime import datetime from typing import List from typing import Tuple import pytest from lib import common from lib.handlers import HandlerParams from lib.models.message import DisplayRecipient from lib.models.message import Message from lib.models.user import User @pytest.fixture(autouse=True) def mock_time(mocker): mocker.patch( "lib.common.get_now", return_value=datetime(year=2020, month=1, day=24, hour=10, minute=0, second=0,), ) @pytest.fixture def mock_client(mocker): return mocker.patch("zulip.Client") @pytest.fixture def mock_cron(mocker): return mocker.patch("lib.cron.Cron") @pytest.fixture def mock_storage(mocker): return mocker.patch("lib.state_handler.StateHandler") @pytest.fixture def mock_send_reply(mocker): return mocker.patch("lib.common.send_reply") @pytest.fixture def mock_user(): return User(email="<EMAIL>", full_name="<NAME>", id=5678) @pytest.fixture def make_zulip_message(mock_user: User): def _make_zulip_message(contents: str) -> Tuple[Message, List[str]]: message = Message( content=contents, display_recipient=[ DisplayRecipient( email=mock_user.email, full_name=mock_user.full_name, is_mirror_dummy=False, id=mock_user.id, short_name="tester", ), DisplayRecipient( email="<EMAIL>", full_name="Lunch Bot", id=1337, is_mirror_dummy=False, short_name="lunch-bot-bot", ), ], sender_email=mock_user.email, sender_full_name=mock_user.full_name, sender_id=mock_user.id, ) args = contents.split() return message, args return _make_zulip_message @pytest.fixture def make_handler_params(mock_client, mock_cron, mock_storage, make_zulip_message): def _make_handler_params(contents: str): message, args = make_zulip_message(contents) return HandlerParams( args=args, client=mock_client, cron=mock_cron, message=message, storage=mock_storage, ) return _make_handler_params @pytest.fixture def make_time(): def _make_time(hour: int, minute: int) -> datetime: now = common.get_now() return datetime( year=now.year, month=now.month, day=now.day, hour=hour, minute=minute, second=0, microsecond=0, ) return _make_time <file_sep>/lib/events.py from typing import Callable import zulip from lib.controllers.alert_leaving import alert_leaving from lib.controllers.delete_plan import delete_plan from lib.models.plan import Plan from lib.state_handler import StateHandler class EventGenerator: """ Interface of a serializable object that generates the actions we store in PersistentCron. Used to that we can pickle these objects. """ def __init__(self): pass def generate_action(self, client: zulip.Client, storage: StateHandler) -> Callable: raise NotImplementedError() class AlertLeavingGenerator(EventGenerator): """ Generates a call to lib.controllers.alert_leaving. """ def __init__(self, plan: Plan): self.plan = plan def __eq__(self, other: object) -> bool: if not isinstance(other, AlertLeavingGenerator): return False return self.plan == other.plan def generate_action(self, client: zulip.Client, storage: StateHandler) -> Callable: return lambda: alert_leaving(client, self.plan) class DeletePlanGenerator(EventGenerator): """ Generates a call to lib.controllers.delete_plan. """ def __init__(self, plan: Plan): self.plan = plan def __eq__(self, other: object) -> bool: if not isinstance(other, DeletePlanGenerator): return False return self.plan == other.plan def generate_action(self, client: zulip.Client, storage: StateHandler) -> Callable: return lambda: delete_plan(client, storage, self.plan) <file_sep>/lib/state_handler.py import shelve from typing import Any class StateHandler: """ Custom shim that implements Zulip's StateHandler class, but with some changes to better suit our use case! """ SHELVE_DB_FILE = "lunch-bot.db" OPEN_ERROR = ValueError("StateHandler must not be open") NOT_OPEN_ERROR = ValueError("StateHandler must be open") EVENTS_ENTRY = "events" PLANS_ENTRY = "lunches" def __init__(self): self._db = None def __enter__(self): return self.open() pass def __exit__(self, type, value, traceback): self.close() def open(self) -> "StateHandler": if self.is_open(): raise self.OPEN_ERROR self._db = shelve.open(self.SHELVE_DB_FILE, writeback=True) return self def is_open(self) -> bool: return self._db is not None def close(self): if not self.is_open(): raise self.NOT_OPEN_ERROR self._db.close() def put(self, key: str, value: Any): if not self.is_open(): raise self.NOT_OPEN_ERROR self._db[key] = value def get(self, key: str) -> Any: if not self.is_open(): raise self.NOT_OPEN_ERROR return self._db[key] def contains(self, key: str) -> bool: if not self.is_open(): raise self.NOT_OPEN_ERROR return key in self._db
879f3e396e2beb97cfc51a8841febfdcf21ad70e
[ "Markdown", "Python", "Text" ]
36
Python
bern/lunch-bot
8770bac9e7a824d9ed75e7aa3abcc112be840509
7293bd104d1be2a5ddd6572177c2bec800870466
refs/heads/master
<repo_name>jlrickert/clipvault<file_sep>/clipvault/cmd/__init__.py import sys from ..vault import vault as vault_ from .snag import SnagCli from .vault import VaultCli def snag(): args = sys.argv cli = SnagCli(args, vault_) sys.exit(cli.run()) def vault(): args = sys.argv cli = VaultCli(args, vault_) sys.exit(cli.run()) <file_sep>/README.rst Clip Vault ========== A quick and simple way to manage passwords for web pages. Installation ------------ ``` python setup.py install ``` Example Usage ---------------------- Registering for a new website: - copy the URL from a website you would like to create a password for - type `snag` into a terminal - copy new random password into the password field - profit Login into an existing site: - copy URL of website - type `snag` into a terminal - copy password into the password field - profit Modifying existing passwords for a website: - copy URL of website into terminal - type `vault` - enter in new password (the new password will also be put into your clipboard) - profit <file_sep>/setup.py import os import re import sys from setuptools import find_packages, setup min_version = (3, 6) if sys.version_info < (3, 6): raise Exception("Clipvault requires Python %s,%s or higher" % min_version) version_file = os.path.join( os.path.dirname(__file__), 'clipvault', '__init__.py') with open(version_file, 'r') as f: version = re.compile( r".*__version__ = '(.*?)'", re.S ).match(f.read()).group(1) readme_file = os.path.join(os.path.dirname(__file__), 'README.rst') with open(readme_file, 'r') as f: readme = f.read() setup( name='clipvault', version=version, description="a more secure way to manage passwords", long_description=readme, author="<NAME>", author_email="<EMAIL>", url='https://github.com/jlrickert/clipvault/', include_package_data=True, packages=find_packages(), setup_requires=['pytest-runner'], install_requires=[ 'keyring==10.4.0', 'pyperclip==1.5.27', 'rfc3987==1.3.7', ] + (['secretstorage==2.3.1'] if "linux" in sys.platform else []), entry_points={ 'console_scripts': [ 'snag = clipvault.cmd:snag', 'vault = clipvault.cmd:vault', ], }, tests_require=['pytest>=2.5.2'], classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Topic :: Database :: Front-Ends", "Operating System :: OS Independent", ], platforms='any', zip_safe=False) <file_sep>/clipvault/cmd/snag.py import random import pyperclip from termcolor import colored, cprint from rfc3987 import parse from .cli import AbstractCli class SnagCli(AbstractCli): """Snag description """ name = 'snag' def random_password(length): return ''.join(random.choice( 'abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + '<PASSWORD>' + '!@#$%^&*()') for i in range(length)) def command(self, args): key = self.__process_key(args.key) value, text = self.__fetch_value(key) self.vault.set_password(key, value) pyperclip.copy(value) cprint(text) def _setup_parser(self, parser): parser.add_argument( 'key', nargs='?', type=str, help='key to fetch from vault') def __process_key(self, key): if key is None: key = pyperclip.paste() try: tmp_key = key uri = parse(tmp_key) if uri['authority'] is not None: key = uri['authority'] except ValueError: pass return key def __fetch_value(self, key): try: value = self.vault[key] text = colored('"{} copied to clipboard!"'.format( key), 'green') except self.vault.KeyError: value = SnagCli.random_password(16) text = colored( '"Generated random value for {}"'.format(key), 'red') return value, text <file_sep>/clipvault/vault.py from getpass import getpass import keyring class __Vault(object): class KeyError(Exception): pass def __init__(self): self.service = 'Clip Vault' def __setitem__(self, key, item): self.set_password(key, item) def __getitem__(self, key, prompt_on_error=False): try: value = self.get_password(key) except vault.KeyError: if prompt_on_error: value = self.set_password_by_input( key, msg='Please input passphrase', hidden=True) else: raise vault.KeyError return value def get_password(self, key): value = keyring.get_password(self.service, key) if value is None: raise vault.KeyError(self.service, key) return value def set_password(self, key, password): keyring.set_password(self.service, key, password) def set_password_by_input(self, key, msg=None, hidden=True): password = None confirm = None if not msg: msg = 'Please Enter in a value for {}: '.format(key) while (password != confirm) or (password is None): if hidden: password = getpass(prompt=msg) confirm = getpass('Please confirm: ') else: password = input(msg) confirm = password self.set_password(key, password) return password vault = __Vault() <file_sep>/Pipfile [[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [packages] keyring = "*" secretstorage = "*" pyperclip = "*" termcolor = "*" "rfc3987" = "*" [dev-packages] pytest = "*"<file_sep>/clipvault/__main__.py import argparse import sys import pyperclip from termcolor import colored, cprint from .cli import Cli from .vault import vault def usage(): print('Missing key') def copy_key(key, timeout=5): try: value = vault[key] pyperclip.copy(value) text = colored( '"{} copied to clipboard for {} minutes!"'.format(key, timeout), 'green') except vault.KeyError: text = colored( '"{} has no associated value"'.format(key, timeout), 'red') cprint(text) def set_key(key, value): vault[key] = value text = colored( 'Value for {} has been set!'.format(key), 'green') cprint(text) def main() -> None: cli = Cli(sys.argv, vault) return cli.run() # args = sys.argv # parser = argparse.ArgumentParser(description='') # subparsers = parser.add_subparser() # subparsers.require = True # subparsers.dest = 'command' # get_parser = subparsers.add_parser('get') # set_parser = subparsers.add_parser('set') # # parser.add_argument('command') # if len(args) == 2: # copy_key(args[1]) # elif len(args) >= 3: # set_key(args[1], args[2]) # else: # usage() if __name__ == '__main__': sys.exit(main()) <file_sep>/clipvault/cmd/cli.py import argparse class AbstractCli(object): """AbstractCli """ def __init__(self, args, vault): self.args = args self.vault = vault self.parser = argparse.ArgumentParser( prog=self.name, description=self.__doc__) def print_usage(self): print(self.__doc__) def _setup_parser(self, parser): pass def command(self, args): pass def run(self): self._setup_parser(self.parser) self.parser.parse_args() args = self.parser.parse_args() self.command(args) <file_sep>/clipvault/cmd/vault.py import pyperclip from termcolor import colored, cprint from rfc3987 import parse from .cli import AbstractCli class VaultCli(AbstractCli): """Vault description """ name = 'vault' def command(self, args): key, fromCb = self.__process_key(args.key) if key and not fromCb: value = pyperclip.paste() self.vault[key] = value else: value = self.vault.set_password_by_input(key) pyperclip.copy(value) text = colored( 'Value for {} has been set and is now in your clipboard!'.format( key), 'green') cprint(text) def _setup_parser(self, parser): parser.add_argument( 'key', nargs='?', type=str, help='Key to store contents of clipboard into') def __process_key(self, key): fromCb = False if key is None: key = pyperclip.paste() fromCb = True try: tmp_key = key uri = parse(tmp_key) if uri['authority'] is not None: key = uri['authority'] except ValueError: pass return key, fromCb def __process_value(self): return pyperclip.paste(), True
fa8e5ecf0a861125881f22a579ccadbec9608cf8
[ "TOML", "Python", "reStructuredText" ]
9
Python
jlrickert/clipvault
37eeba923b095873085049b0547cbc1de0b9897d
00f397b8dca82f140956bf3c8d1beea0150f89cf
refs/heads/master
<repo_name>C0dak/amass<file_sep>/amass/activecert.go // Copyright 2017 <NAME>. All rights reserved. // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. package amass import ( "crypto/tls" "fmt" "strconv" "strings" "time" ) type ActiveCertService struct { BaseAmassService // Queue for requests queue []*AmassRequest // Ensures that the same IP is not used twice filter map[string]struct{} } func NewActiveCertService(in, out chan *AmassRequest, config *AmassConfig) *ActiveCertService { acs := &ActiveCertService{filter: make(map[string]struct{})} acs.BaseAmassService = *NewBaseAmassService("Active Certificate Service", config, acs) acs.input = in acs.output = out return acs } func (acs *ActiveCertService) OnStart() error { acs.BaseAmassService.OnStart() go acs.processRequests() return nil } func (acs *ActiveCertService) OnStop() error { acs.BaseAmassService.OnStop() return nil } func (acs *ActiveCertService) processRequests() { t := time.NewTicker(10 * time.Second) defer t.Stop() pull := time.NewTicker(1 * time.Second) defer pull.Stop() loop: for { select { case req := <-acs.Input(): if req.activeCertOnly { go acs.add(req) } case <-pull.C: next := acs.next() if next != nil { go acs.handleRequest(next) } case <-t.C: acs.SetActive(false) case <-acs.Quit(): break loop } } } func (acs *ActiveCertService) add(req *AmassRequest) { acs.Lock() defer acs.Unlock() acs.queue = append(acs.queue, req) } func (acs *ActiveCertService) next() *AmassRequest { acs.Lock() defer acs.Unlock() var next *AmassRequest if len(acs.queue) == 1 { next = acs.queue[0] acs.queue = []*AmassRequest{} } else if len(acs.queue) > 1 { next = acs.queue[0] acs.queue = acs.queue[1:] } return next } // Returns true if the IP is a duplicate entry in the filter. // If not, the IP is added to the filter func (acs *ActiveCertService) duplicate(ip string) bool { acs.Lock() defer acs.Unlock() if _, found := acs.filter[ip]; found { return true } acs.filter[ip] = struct{}{} return false } func (acs *ActiveCertService) handleRequest(req *AmassRequest) { acs.SetActive(true) // Which type of request is this? if req.Address != "" && !acs.duplicate(req.Address) { acs.pullCertificate(req.Address) } else if req.Netblock != nil { ips := hosts(req.Netblock) for _, ip := range ips { acs.add(&AmassRequest{ Address: ip, Netblock: req.Netblock, ASN: req.ASN, ISP: req.ISP, }) } } } // pullCertificate - Attempts to pull a cert from several ports on an IP func (acs *ActiveCertService) pullCertificate(addr string) { var roots []string var requests []*AmassRequest // Check hosts for certificates that contain subdomain names for _, port := range acs.Config().Ports { strPort := strconv.Itoa(port) cfg := tls.Config{InsecureSkipVerify: true} conn, err := tls.Dial("tcp", addr+":"+strPort, &cfg) if err != nil { continue } certChain := conn.ConnectionState().PeerCertificates cert := certChain[0] var cn string for _, name := range cert.Subject.Names { oid := name.Type if len(oid) == 4 && oid[0] == 2 && oid[1] == 5 && oid[2] == 4 { if oid[3] == 3 { cn = fmt.Sprintf("%s", name.Value) break } } } root := removeAsteriskLabel(cn) roots = append(roots, root) var subdomains []string for _, name := range cert.DNSNames { subdomains = append(subdomains, removeAsteriskLabel(name)) } subdomains = NewUniqueElements([]string{}, subdomains...) for _, name := range subdomains { requests = append(requests, &AmassRequest{ Name: name, Domain: root, Tag: "cert", Source: "Active Cert", }) } for _, ip := range cert.IPAddresses { acs.add(&AmassRequest{Address: ip.String()}) } } // Add the new root domain names to our Config acs.Config().Domains = UniqueAppend(acs.Config().Domains, roots...) // Send all the new requests out for _, req := range requests { acs.SendOut(req) } } func removeAsteriskLabel(s string) string { var index int labels := strings.Split(s, ".") for i := len(labels) - 1; i >= 0; i-- { if strings.TrimSpace(labels[i]) == "*" { break } index = i } if index == len(labels)-1 { return "" } return strings.Join(labels[index:], ".") }
fb1e70a1ca7356e81b23e7485a2c45708401db65
[ "Go" ]
1
Go
C0dak/amass
1e8d79e659075594c5fb7790a5bc9ed38bad204b
412bbc4be74f8f87820b6f3759d1a90ee93c4c8b
refs/heads/master
<file_sep>[![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/) ##Lab for RequireJS + grunt-contrib-requirejs + AlmondJS #### Resources: * http://requirejs.org/ * http://requirejs.org/docs/optimization.html * https://github.com/gruntjs/grunt-contrib-requirejs * http://gregfranko.com/requirejs-talk/ #### TODO: * Using RequireJS; * Using RequireJS with Grunt; * Using RequireJS with Almond (For optimization); <file_sep>'use strict'; module.exports = function(grunt) { // Load tasks require('load-grunt-tasks')(grunt); // Project configuration grunt.initConfig({ // Read package.json file pkg: grunt.file.readJSON('package.json'), // Define paths meta: { srcPathSass: 'app/src/sass/', srcPathJS: 'app/src/js/', buildPathCSS: 'app/build/css/', buildPathJS: 'app/build/js/' }, // Compass compass: { dist: { options: { require: 'susy', sassDir: 'app/src/sass', cssDir: 'app/build/css', environment: 'production' } } }, // TODO: Make RequireJS work properly // RequireJS requirejs: { prod: { options: { baseUrl: ".", mainConfigFile: "app/config/requireconfig.js", deps: ['app/src/js/main'], insertRequire: ['app/src/js/main'], name: "bower/almond/almond", out: "app/build/js/main.min.js", optimize: 'uglify2', preserveLicenseComments: false // done: function(done, output) { // var duplicates = require('rjs-build-analysis').duplicates(output); // if (duplicates.length > 0) { // grunt.log.subhead('Duplicates found....'); // grunt.log.warn(duplicates); // done(new Error('r.js built duplicate modules, please check the excludes option.')); // } // done(); // } } } }, // Connect connect: { options: { port: 9000, hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true } } }, // Watch watch: { compass: { files: ['<% meta.srcPathSass %>**/*.{scss,sass}'], tasks: ['compass'] }, html: { files: '*.html' }, options: { livereload: '<%= connect.options.livereload %>' } } }); grunt.registerTask('default', ['connect', 'watch']); }<file_sep>require(["app/src/js/wtf/app"], function(app) { });
c99e8b3fdd37d54895f74a852e5a77ae7f4dbf95
[ "Markdown", "JavaScript" ]
3
Markdown
AgtLucas/require
2f5f7ac75df5c7d239ffdad2b4664e675d273a6a
e3299ef44470721d74ee66dda38461e20bd7dd00
refs/heads/master
<file_sep>var flowFile = session.get(); if (flowFile !== null) { var StreamCallback = Java.type("org.apache.nifi.processor.io.StreamCallback"); var IOUtils = Java.type("org.apache.commons.io.IOUtils"); var StandardCharsets = Java.type("java.nio.charset.StandardCharsets"); flowFile = session.write(flowFile, new StreamCallback(function (inputStream, outputStream) { // Read input FlowFile content var inputText = IOUtils.toString(inputStream, StandardCharsets.UTF_8); var inputObj = JSON.parse(inputText); var outputObj = { electricity: parseFloat(inputObj.electricity), furnace: parseFloat(inputObj.furnace), entrance: parseFloat(inputObj.entrance), exit: parseFloat(inputObj.exit), exhaust: parseFloat(inputObj.exhaust), e103: parseFloat(inputObj.e103), e106: parseFloat(inputObj.e106), e108: parseFloat(inputObj.e108), create_time: (new Date()).getTime() }; // Write output content outputStream.write(JSON.stringify(outputObj, null, "\t").getBytes(StandardCharsets.UTF_8)); })); // Finish by transferring the FlowFile to an output relationship session.transfer(flowFile, REL_SUCCESS); }<file_sep>put nifi extension .nar file on here<file_sep># nifi docker compose 1. clone this project 2. `docker-compose up -d`
ad70af0dd9b6fe46393a4828ae91f15ac27ecc8f
[ "JavaScript", "Markdown" ]
3
JavaScript
chnbohwr/nifi_compose
04787d2ed723ddbc322d36d8f6869a813db5c1b7
a90404b21082d745b0cab4611d03a6c8e7b95442
refs/heads/master
<repo_name>brendannee/bikesy-native<file_sep>/app/services/weather.ts import config from '../../config.json'; import CoordinateType from '../types/coordinate'; // Only fetch weather info every 5 minutes const cacheWindow = 5 * 60 * 60 * 1000; let weatherFetchTime; let weatherResults; export const getWeather = async (coord: CoordinateType) => { if (weatherFetchTime && weatherFetchTime + cacheWindow > Date.now()) { return weatherResults; } const url = `https://api.openweathermap.org/data/2.5/weather?lat=${coord.latitude}&lon=${coord.longitude}&units=imperial&appid=${config.openWeatherMapApiKey}`; weatherFetchTime = Date.now(); const response = await fetch(url); weatherResults = response.json(); return weatherResults; }; <file_sep>/app/services/api.ts import _ from 'lodash'; import config from '../../config.json'; import CoordinateType from '../types/coordinate'; const scenarios = { '1': { hills: '1', bikeLanes: '3', }, '2': { hills: '2', bikeLanes: '3', }, '3': { hills: '3', bikeLanes: '3', }, '4': { hills: '1', bikeLanes: '2', }, '5': { hills: '2', bikeLanes: '2', }, '6': { hills: '3', bikeLanes: '2', }, '7': { hills: '1', bikeLanes: '1', }, '8': { hills: '2', bikeLanes: '1', }, '9': { hills: '3', bikeLanes: '1', }, }; const componentsToScenario = (components: object) => { return _.findKey(scenarios, scenario => _.isMatch(scenario, components)); }; export const getRoute = async (startLocation: CoordinateType, endLocation: CoordinateType, bikeLanes: string, hills: string) => { const scenario = componentsToScenario({ hills, bikeLanes }); const parameters = `/?lat1=${startLocation.latitude}&lng1=${startLocation.longitude}&lat2=${endLocation.latitude}&lng2=${endLocation.longitude}&scenario=${scenario}`; const response = await fetch(`${config.bikeMapperApiUrl}${parameters}`); const route = await response.json(); if (route.error) { throw new Error(route.error); } return route; }; export const reverseGeocode = async (coordinate: CoordinateType) => { const parameters = `${coordinate.longitude},${coordinate.latitude}.json?types=address&access_token=${config.mapboxAccessToken}`; const response = await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${parameters}`); const result = await response.json(); if (!result || !result.features || !result.features.length) { throw new Error('No matching features found'); } const address = result.features[0].place_name.replace(', United States', ''); return address; }; export const geocode = async (address: string) => { const parameters = `${address}.json?bbox=${config.boundsLeft},${config.boundsBottom},${config.boundsRight},${config.boundsTop}&access_token=${config.mapboxAccessToken}`; const response = await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${parameters}`); const result = await response.json(); if (!result || !result.features || !result.features.length) { throw new Error('No matching features found'); } const coordinate = { latitude: result.features[0].center[1], longitude: result.features[0].center[0], }; return coordinate; }; <file_sep>/app/services/map-utils.ts import config from '../../config.json'; import turfBBox from '@turf/bbox'; import turfLength from '@turf/length'; import turfDistance from '@turf/distance'; interface Point { latitude: number; longitude: number; } interface Region { latitude: number; latitudeDelta: number; longitude: number; longitudeDelta: number; } const polylineToGeoJSON = (polyline: Array<[number, number]>) => ({ geometry: { coordinates: polyline, type: 'LineString', }, properties: {}, type: 'Feature', }); export const getRegion = (polyline: Array<[number, number]>) => { const bbox = turfBBox(polylineToGeoJSON(polyline)); const paddingPercent = 0.15; const region = { latitude: (bbox[2] - bbox[0]) / 2 + bbox[0], latitudeDelta: (bbox[2] - bbox[0]) * (1 + paddingPercent * 3), longitude: (bbox[3] - bbox[1]) / 2 + bbox[1], longitudeDelta: (bbox[3] - bbox[1]) * (1 + paddingPercent), }; return region; }; export const getDistanceMi = (polyline: Array<[number, number]>) => { return turfLength(polylineToGeoJSON(polyline), { units: 'miles' }); }; export const regionContainsPoint = (region: Region, point: Point) => { return ( point.latitude > region.latitude - region.latitudeDelta && point.latitude < region.latitude + region.latitudeDelta && point.longitude > region.longitude - region.longitudeDelta && point.longitude < region.longitude + region.longitudeDelta ); }; export const isWithinMapBoundaries = (point: Point) => { return ( point.latitude < config.boundsTop && point.latitude > config.boundsBottom && point.longitude > config.boundsLeft && point.longitude < config.boundsRight ); }; export const getMapBoundariesCenter = () => { return { latitude: config.boundsBottom + (config.boundsTop - config.boundsBottom) / 2, longitude: config.boundsLeft + (config.boundsRight - config.boundsLeft) / 2, }; }; export const getMapBoundariesRadius = () => { const diagonalDistance = turfDistance( [config.boundsLeft, config.boundsTop], [config.boundsRight, config.boundsBottom], { units: 'meters', } ); return diagonalDistance / 2; }; <file_sep>/app/services/airquality.ts import config from '../../config.json'; import CoordinateType from '../types/coordinate'; // Only fetch air quality info every 5 minutes const cacheWindow = 5 * 60 * 60 * 1000; let dataFetchTime; let dataResults; export const getAirQuality = async (coord: CoordinateType) => { if (dataFetchTime && (dataFetchTime + cacheWindow > Date.now())) { return dataResults; } const url = `https://bikesy.com/airquality.php?format=application/json&latitude=${coord.latitude}&longitude=${coord.longitude}&distance=5&API_KEY=${config.airNowApiKey}`; dataFetchTime = Date.now(); const response = await fetch(url); dataResults = response.json(); return dataResults; }; <file_sep>/README.md # Bikesy Native A react native app for bikesy.com. It is an iOS and Android app for finding bike directions. ![bikesy-mobile-2](https://user-images.githubusercontent.com/96217/109886177-84051000-7c34-11eb-9134-0a4921059a74.jpg) It uses routes based on open street maps and served from the Bikesy Server. It allows users to specify a start and end point to a route along with a hill tolerance (from avoiding hills to not weighting hills much at all). It allows users to choose between three different scenarios of bike facilities from mainly bike lanes and bike routes to a very direct route. Try it out: [Bikesy on iOS](https://apps.apple.com/us/app/bikesy/id1459787289) [Bikesy on Android](https://play.google.com/store/apps/details?id=com.blinktaginc.bikesy&hl=en_US) A web-based version is available at http://bikesy.com. ## Bikesy API Bikesy Native pulls route data from the [Bikesy API](https://bikesy.com/bikesy-api). The assumptions that go into the routes provided by the Bikesy API are documented on the Bikesy API page. ## Running ### `yarn start` Runs your app in development mode. Open it in the [Expo app](https://expo.io) on your phone to view it. It will reload if you save edits to your files, and you will see build errors and logs in the terminal. Sometimes you may need to reset or clear the React Native packager's cache. To do so, you can pass the `--reset-cache` flag to the start script: ``` yarn start --reset-cache ``` #### `yarn test` Runs the [jest](https://github.com/facebook/jest) test runner on your tests. <file_sep>/app/services/formatters.ts import config from '../../config.json'; export const metersToFeet = (meters: number) => meters * 3.28084; export const metersToMiles = (meters: number) => meters * 0.000621371; const hoursToMinutes = (hours: number) => hours * 60; export const formatTime = (miles: number) => { const lowEstimate = miles / config.highBikeSpeedMph; const highEstimate = miles / config.lowBikeSpeedMph; let formattedTime; if (highEstimate < 1) { formattedTime = `${hoursToMinutes(lowEstimate).toFixed()} to ${hoursToMinutes(highEstimate).toFixed()} min`; } else { formattedTime = `${lowEstimate.toFixed(1)} to ${highEstimate.toFixed(1)} hours`; } return formattedTime; }; export const formatDistance = (distance: number) => distance.toFixed(1); export const getElevationGain = (profile: number[]) => { let totalElevGain = 0; profile.forEach((p, idx) => { if (idx < profile.length - 1 && profile[idx][1] < profile[idx + 1][1]) { totalElevGain += profile[idx + 1][1] - profile[idx][1]; } }); return totalElevGain; }; export const formatElevation = (elevation: number) => { return `${metersToFeet(elevation).toFixed()} ft`; }; export const formatAddressLines = (address: string) => { if (!address) { return ''; } const addressComponents = address.split(','); return addressComponents[0]; };
81abaa5520b9c90ceae7a3d7573c8ee0a16a0c21
[ "Markdown", "TypeScript" ]
6
TypeScript
brendannee/bikesy-native
6d10183f4a5f38ac6846fa0fd2c730f68dea02b4
14851393dda2be911c722beabe6a7073c5e0b868
refs/heads/main
<file_sep>import React, { useCallback, useState } from 'react'; import { styled } from '@material-ui/core/styles'; import { AppBar } from '../AppBar'; import { CatGrid } from './CatGrid' const HomeContainer = styled('div')({ flexGrow: 1, display: 'flex', flexDirection: 'column' }); const Home = () => { const [selectedCats, setSelectedCats] = useState({}) const cartCallback = useCallback((cat) => { setSelectedCats((sCats) => { return { ...sCats, ...{ [cat.id]: cat } } }) return }, []) const clearCart = useCallback(() => { setSelectedCats({}) }, []) return ( <HomeContainer> <AppBar clearCart={clearCart} selectedCats={selectedCats} cartCallback={cartCallback} /> <CatGrid cartCallback={cartCallback} /> </HomeContainer> ); } export default Home; <file_sep>import React from 'react'; import { styled, makeStyles } from '@material-ui/core/styles'; import IconButton from '@material-ui/core/IconButton'; import MenuItem from '@material-ui/core/MenuItem'; import Menu from '@material-ui/core/Menu'; import AccountCircle from '@material-ui/icons/AccountCircle'; import MuiAppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import ShoppingCartIcon from '@material-ui/icons/ShoppingCart'; const Title = styled(Typography)({ flexGrow: 1 }); const ShoppingCart = ({ selectedCats, clearCart }) => { const [anchorEl, setAnchorEl] = React.useState(null); function handleProfileMenuOpen(event) { setAnchorEl(event.currentTarget); } function handleMenuClose() { setAnchorEl(null); } return ( <React.Fragment> <IconButton edge="end" aria-label="account of current user" aria-controls="appbar-account-menu" aria-haspopup="true" onClick={handleProfileMenuOpen} color="inherit" > <ShoppingCartIcon /> </IconButton> <Menu id="appbar-account-menu" anchorEl={anchorEl} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'right' }} open={Boolean(anchorEl)} onClose={handleMenuClose} > {Object.keys(selectedCats).map(catId => (<MenuItem key={catId}>{selectedCats[catId].name} {selectedCats[catId].price}</MenuItem>))} <MenuItem onClick={clearCart}>Clear Cart</MenuItem> </Menu> </React.Fragment> ); } export const AppBar = ({ selectedCats, clearCart }) => { return ( <MuiAppBar color="primary" position="static"> <Toolbar> <Title variant="h6">Cat App</Title> <ShoppingCart selectedCats={selectedCats} clearCart={clearCart} /> </Toolbar> </MuiAppBar> ); } <file_sep>import { Router } from 'express'; const router = Router(); const catFile = require('../catfile.json'); router.use('/cats', (req, res) => { res.status(200).json(catFile) return }) router.use('/cats-filtered', (req, res) => { const gte = parseInt(req.query.gte) const lte = parseInt(req.query.lte) res.status(200).json(catFile.filter(cat => !gte || parseInt(cat.price) >= gte).filter(cat => !lte || parseInt(cat.price) <= lte)) return }) router.use('/', (req, res, next) => { return res.render('index'); }); export { router }; <file_sep>import React, { useEffect, useState } from 'react'; import { styled } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid' import Paper from '@material-ui/core/Paper' import Button from '@material-ui/core/Button' import { makeStyles } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import axios from 'axios'; const useStyles = makeStyles((theme) => ({ paper: { padding: theme.spacing(1), color: theme.palette.text.secondary, height: 200 }, image: { width: 128, height: 128, 'object-fit': 'cover', 'border-radius': '50%' } })); const Container = styled('div')({ marginTop: 16, flexGrow: 1, display: 'flex', flexDirection: 'column' }); const RowContainer = styled('div')({ display: 'flex', flexDirection: 'row', height: '100%' }); const ColumnContainer = styled('div')({ paddingLeft: 16, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', height: '100%' }); const CatData = styled('div')({ display: 'flex', flexDirection: 'column', }); export const CatGrid = ({ cartCallback }) => { const [cats, setCats] = useState([]) useEffect(async () => { const result = await axios('/cats') setCats(result.data) }, []) const classes = useStyles(); const handleClick = (cat) => { return (e) => { cartCallback(cat) } } return ( <Container> <Grid container spacing={1}> {cats.map((cat) => <Grid key={cat.id} item xs={4}> <Paper className={classes.paper}> <RowContainer> <img className={classes.image} src={cat.image} /> <ColumnContainer> <CatData> <Typography variant="h6">{cat.name}</Typography> <Typography variant="subtitle2">{cat.price}</Typography> </CatData> <Button onClick={handleClick(cat)} color="primary">Add To Cart</Button> </ColumnContainer> </RowContainer> </Paper> </Grid>)} </Grid> </Container> ) }
051271f4ba6e9f01b76ffd83bc3b4ec6f5f02b9e
[ "JavaScript" ]
4
JavaScript
Radzell/probable-cat
4a80ed0e85849b0f85997d9851d8cc1ab09a0a3e
419ad8be612fda726950b023a6e3d38d6c8b9626
refs/heads/master
<file_sep>(function () { require('angular-translate'); angular.module('app.translate', ['pascalprecht.translate']) .config(config) .factory('translateService', translateService); /* @ngInject */ function translateService($translate) { var service = { changeLang: function () { var current = $translate.use(), toSelect = current === 'en' ? 'es' : 'en'; $translate.use(toSelect); }, currentLang: function () { return $translate.use(); } }; return service; } /* @ngInject */ function config($translateProvider) { $translateProvider.translations('en', { 'HOME': 'Home', 'EVENTS': 'Events', 'ACCOUNT': 'Account', 'SETTINGS': 'Settings', 'TAB_STATUS_DAILY': 'Daily', 'TAB_STATUS_MONTHLY': 'Monthly', 'DATA_TRANSFER': 'Data Transfer', 'AUDIO': 'Audio', 'VIDEO': 'Video', 'PHOTO': 'Photo', 'UPLOAD_FILES': 'Upload Files', 'SHARE_LINK': 'Share Link', 'BACKUP': 'Backup', 'FILES': 'files', 'EMAIL': 'Email', 'SUBJECT': 'Subject', 'MESSAGE': 'Message', 'SEND_EMAIL': 'Send Email', 'NEW_EMAIL':'New Email', 'SENT_EMAILS':'Sent Emails' }); $translateProvider.translations('es', { 'HOME': 'Inicio', 'EVENTS': 'Eventos', 'ACCOUNT': 'Cuenta', 'SETTINGS': 'Ajustes', 'TAB_STATUS_DAILY': 'Diario', 'TAB_STATUS_MONTHLY': 'Mensual', 'DATA_TRANSFER': 'Transferencia de Datos', 'AUDIO': 'Audio', 'VIDEO': 'Video', 'PHOTO': 'Foto', 'UPLOAD_FILES': 'Subir Archivos', 'SHARE_LINK': 'Compartir Enlace', 'BACKUP': 'Copia Respaldo', 'FILES': 'archivos', 'EMAIL': 'Email', 'SUBJECT': 'Asunto', 'MESSAGE': 'Mensaje', 'SEND_EMAIL': 'Enviar Email', 'NEW_EMAIL':'Nuevo Email', 'SENT_EMAILS':'Email Enviados' }); $translateProvider.preferredLanguage('en'); } }());<file_sep>(function () { 'use strict'; angular .module('app.widgets') .directive('cimSentItems', cimSentItems); function cimSentItems() { var directive = { scope:{ items:'=' }, controller: SentItemsController, controllerAs: 'vm', link: link, replace: true, templateUrl: 'views/widgets/cimSentItems.html', restrict: 'AE' }; return directive; /* @ngInject */ function SentItemsController(dataservice){ var vm = this; dataservice.getSentEmails().then(function (data) { vm.sentItems = data; }); } function link(scope, element, attrs) {} } })();<file_sep># C - I'M Demo page: [http://plentycode.com/CIM](http://cim-plentycode.herokuapp.com/). ## Getting Started #### Prerequisites You will need **git** to clone the repository. You can get git from [http://git-scm.com/](http://git-scm.com/). You must have node.js and its package manager (npm) installed. You can get them from [http://nodejs.org/](http://nodejs.org/). #### Clone PL_CIM To get started, please clone the repository: ``` git clone https://github.com/civanm/PL_CIM.git cd PL_CIM ``` If you just want to start a new project: ```bash git clone --depth=1 https://github.com/civanm/PL_CIM.git <your-project-name> ``` #### Install Dependencies ``` npm install ``` #### Build the app After installing the package dependencies, it's time to build our application, do it running the gulps tasks: ``` gulp build ``` and then to uglify and minify release files, run: ``` gulp release ``` ### Running the App Install a node.js tool called http-server. You can install http-server globally: ``` sudo npm install -g http-server ``` Then you can start your own development web server to serve static files from a folder by running: ``` cd release http-server -a localhost -p 8000 ``` Then you can browse localhost:8000 in your preferred browser and see the site running. <file_sep>(function () { angular.module('app.router', ['ui.router']) .config(config); /* @ngInject */ function config($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: '/home', templateUrl: 'views/pages/home.html' }) .state('events', { url: '/events', templateUrl: 'views/pages/events.html' }) .state('account', { url: '/account', templateUrl: 'views/pages/account.html' }) .state('settings', { url: '/settings', templateUrl: 'views/pages/settings.html' }); $urlRouterProvider.otherwise('/home'); } }());<file_sep>(function () { 'use strict'; angular.module('app.services', []) .factory('dataservice', dataservice); /* @ngInject */ function dataservice($http) { var service = { sentItems: [], getProfileInfo: getProfileInfo, getStatistics: getStatistics, getSentEmails: getSentEmails, addSentEmail: addSentEmail }; return service; function getProfileInfo() { return $http.get('API/profile/get-info.json').then(function (response) { return response.data[0]; }) .catch(function () { console.error('Error trying to fetch profile'); }); } function getStatistics() { return $http.get('API/statistics/get-data-transfer.json').then(function (response) { return response.data[0]; }) .catch(function () { console.error('Error trying to fetch statistics'); }); } function addSentEmail(email){ /*jshint validthis:true */ var self= this; self.sentItems.unshift(email); } function getSentEmails() { /*jshint validthis:true */ var self= this; return $http.get('API/email/get-sent-items.json').then(function (response) { self.sentItems= response.data; return response.data; }) .catch(function () { console.error('Error trying to fetch sent items'); }); } } }());<file_sep>(function () { angular.module('app.widgets', []); //loads files for the module require('./cimProfileCard'); require('./cimTopNav'); require('./cimChartTabs'); require('./cimForm'); require('./cimSentItems'); }());<file_sep> require('angular'); require('angular-mocks'); require('./dataservice'); describe('dataservice', function () { 'use strict'; var dataservice; beforeEach(function () { angular.mock.module('app.services'); inject(function ($q) { deferred = $q; }); //injects angular scopes to the controller inject(function (_dataservice_) { dataservice = _dataservice_; }); }); describe('service function definitions', function () { it('should have getProfileInfo function', function () { expect(dataservice.getProfileInfo).toBeDefined(); }); it('should have getStatistics function', function(){ expect(dataservice.getStatistics).toBeDefined(); }); it('should have getSentEmails function', function(){ expect(dataservice.getSentEmails).toBeDefined(); }); }); describe('send email', function () { it('should have a send email func', function () { expect(dataservice.addSentEmail).toBeDefined(); }); it('should add an email to the sent email list', function () { dataservice.sentItems = []; var email = { to: '<EMAIL>', subject: 'subject', message: 'message' }; expect(dataservice.sentItems.length).toEqual(0); //callls the main func dataservice.addSentEmail(email); expect(dataservice.sentItems.length).toEqual(1); }); }); });<file_sep>(function () { 'use strict'; angular .module('app.widgets') .directive('cimChartTabs', cimChartTabs); function cimChartTabs() { var directive = { scope: true, controller: ChartController, controllerAs: 'vm', link: link, replace: true, templateUrl: 'views/widgets/cimChartTabs.html', restrict: 'AE' }; return directive; /* @ngInject */ function ChartController(dataservice){ var chart = this; dataservice.getStatistics().then(function (data) { chart.daily = data.day; chart.monthly = data.month; }); } function link(scope, element, attrs) {} } })();<file_sep> require('angular'); require('angular-mocks'); require('angular-translate'); require('./translate'); describe('translateService', function () { 'use strict'; var service; beforeEach(function () { //injects the module angular.mock.module('app.translate'); //injects angular scopes to the controller angular.mock.inject(function (translateService) { service = translateService; }); }); describe('service function definitions', function () { it('should have a func to change the language', function () { expect(service.changeLang).toBeDefined(); }); it('should have a func to get the current Lang', function () { expect(service.currentLang).toBeDefined(); }); it('should have the current lang in english', function () { expect(service.currentLang()).toBe('en'); }); it('should toggle the language to spanish', function () { expect(service.currentLang()).toBe('en'); service.changeLang(); expect(service.currentLang()).toBe('es'); }); }); });<file_sep>require('angular'); require('angular-mocks'); require('angular-material'); require('./layout.module'); require('./shell'); var mocks = require('../../mocks/mocks'); describe('Layout Shell', function () { 'use strict'; var deferred, scope, shell, translateServiceMock, dataservice; beforeEach(function () { angular.mock.module('app.layout'); inject(function ($q) { deferred = $q; }); var mockedDeferred = deferred(function (resolve, reject) { resolve({}); }); //override mocks services with fake deferreds mocks.dataservice = { getProfileInfo: function () { return mockedDeferred; }, getStatistics: function () { return mockedDeferred; }, getSentEmails: function () { return mockedDeferred; } }; //injects angular scopes to the controller inject(function ($controller, $rootScope) { scope = $rootScope.$new(); shell = $controller('Shell', { $scope: scope, $mdSidenav: mocks.$mdSidenav, translateService: mocks.translateService, dataservice: mocks.dataservice }); }); }); describe('language', function () { it('should have a toggle lang func', function () { expect(shell.toggleLang).toBeDefined(); }); it('should get the current language', function () { spyOn(mocks.translateService, 'currentLang'); shell.toggleLang(); expect(mocks.translateService.currentLang).toHaveBeenCalled(); }); it('should call the changeLang fucnt when toggle', function () { spyOn(mocks.translateService, 'changeLang'); shell.toggleLang(); expect(mocks.translateService.changeLang).toHaveBeenCalled(); }); }); });
761be43fb9b5eb0528828a1a0067a574004b3f3d
[ "JavaScript", "Markdown" ]
10
JavaScript
civanm/PL_CIM
1ccc1b2d7762f3342a5d988b5b50bade932c71af
015d5e083862050db59f11fdbbf439f7f36e1577
refs/heads/master
<repo_name>maximebj/wp.theme.oop<file_sep>/header.php <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <?php wp_body_open(); ?> <header class="header"> <div class="container"> <a href="<?php echo home_url( '/' ); ?>"><?php _e( 'Hello there !', 'dysign' ); ?></a> <?php wp_nav_menu( array( 'theme_location' => 'main', 'container' => 'ul', 'menu_class' => 'header__menu' ) ); ?> </div> </header> <file_sep>/single.php <?php get_header(); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="section blog"> <div class="wrapper flex-container"> <div class="f3 blog__posts"> <div class="post"> <h1 class="blog__title"><?php the_title(); ?></h1> <div class="post__meta"> <span class="post__date"><?php _e('Le', 'smoothie'); ?> <?php the_time('d F Y'); ?></span> <span>&bullet;</span> <span class="post__categories"><?php _e('Thème :', 'smoothie'); ?> <?php the_category(); ?></span> <span>&bullet;</span> <span class="post__tags"><?php _e('Mots-Clés :', 'smoothie'); ?> <?php the_tags('',' ',''); ?></span> </div> <div class="post__thumbnail"> <?php the_post_thumbnail(); ?> </div> <div class="post__content content"> <?php the_content(); ?> </div> </div> <div class="flex-container singlenav"> <div class="f1 singlenav__next"> <?php _e('« Article suivant', 'smoothie'); ?><br> <?php next_post_link('%link'); ?> </div> <div class="f1 singlenav__prev"> <?php _e('Article précédent »', 'smoothie'); ?><br> <?php previous_post_link('%link'); ?> </div> </div> </div> <div class="f1 blog__sidebar"> <?php dynamic_sidebar('Blog'); ?> </div> </div> </div> <?php endwhile; endif; get_footer(); ?> <file_sep>/taxonomy.php <?php // search for a archive-[custom-type].php instead of trying to load taxonomy-[taxo].php and if not found, goes to standard archive.php // this code check if a archive-[custom-type].php exists where [custom-type] is the type which [taxo] belongs to. // get queried object $queried_object = $wp_query->get_queried_object(); // get actual taxonomy from object $taxonomy = $queried_object->taxonomy; // all taxonomy datas $tax_object = get_taxonomy($taxonomy); // among the datas, the custom type $custom_type = $tax_object->object_type[0]; // check if archive type template exists, else go to standard archive if (locate_template('archive-'.$custom_type.'.php') != '') { get_template_part('archive-'.$custom_type); } else { get_template_part('archive'); }<file_sep>/archive.php <?php get_header(); // case : display a category if (is_category()) { $title = "Catégorie &bullet; ".single_tag_title( '', false); } // case : display a tag elseif (is_tag()) { $title = "Mot clé &bullet; ".single_tag_title( '', false); } // case : display a tag elseif (is_search()) { $title = "Recherche &bullet; ".get_search_query(); } else { $title = 'Le Blog &bullet; dernières actus'; } ?> <div class="section blog"> <div class="wrapper flex-container"> <div class="f3 blog__posts"> <h1 class="blog__title"><?php echo $title; ?></h1> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="post"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <div class="post__meta"> <span class="post__date">Le <?php the_time('d F Y'); ?></span> <span>&bullet;</span> <span class="post__categories">Thème : <?php the_category(); ?></span> <span>&bullet;</span> <span class="post__tags"> Tags : <?php the_tags('',' ',''); ?></span> </div> <div class="post__thumbnail"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> </div> <div class="post__content"> <?php the_excerpt(); ?> <p class="right"><a href="<?php the_permalink(); ?>" class="button--type1 button--small button--bold">Lire l'article</a></p> </div> </div> <?php endwhile; endif; ?> <div class="blog__navigation"> <?php global $wp_query; $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages ) ); ?> </div> </div> <div class="f1 blog__sidebar"> <?php dynamic_sidebar('Blog'); ?> </div> </div> </div> <?php get_footer(); ?> <file_sep>/front-page.php <?php get_header(); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> <p class="date"><?php the_date(); ?></p> <p class="thumb"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></p> <?php the_excerpt(); ?> <p><?php the_tags('',', ','') ?></p> <p><?php the_category(); ?></p> <?php endwhile; endif; ?> <?php get_template_part('parts/navigation'); ?> <?php get_footer(); ?> <file_sep>/parts/article.php <div class="post"> <div class="post__thumbnail"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> <div class="post__date">Le <?php the_time('d M Y'); ?></div> </div> <div class="post__meta"> <?php the_category(); ?> <?php the_tags('',', ',''); ?> </div> <div class="post__content"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_content(); ?> <p><a href="<?php the_permalink(); ?>" class="button--main">Lire l'article</a></p> </div> </div> <file_sep>/footer.php <footer class="footer"> <div class="container"> <?php wp_nav_menu( array( 'theme_location' => 'footer', 'container' => 'ul', 'menu_class' => 'footer__menu' ) ); ?> </div> </footer> <?php wp_footer(); ?> <!-- Google Analytics --> </body> </html> <file_sep>/parts/navigation.php <?php // trick for custom queries // default wp query - call this page with : get_template_part( 'parts/navigation' ); // wp_query - call this page with : $custom = true; get_template_part( 'parts/navigation' ); global $custom, $my_query; $max_pages = ($custom) ? $my_query->max_num_pages : 0; ?> <nav class="navigation"> <div class="prev"> <?php previous_posts_link('Articles plus récents', $max_pages); ?> </div> <div class="next"> <?php next_posts_link('Articles plus anciens', $max_pages); ?> </div> </nav> <file_sep>/parts/searchform.php <form method="get" id="searchform" action="<?php bloginfo('url') ?>"> <div> <input class="text" type="text" placeholder="recherche" value="" name="s" id="s" /> <input type="submit" class="submit" name="Submit" value="s" /> </div> </form>
860350f71a68037a85304dd6688510144e4b811f
[ "PHP" ]
9
PHP
maximebj/wp.theme.oop
4f8d71d9740c8057241d8d6b969cc8c4621e5ad8
aaf6d3398cf81e721f6e59aa534b1a3936526f11
refs/heads/master
<file_sep>using UnityEngine; using UnityEditor; using System.Collections.Generic; using System; namespace FluxEditor { public class FSettings : ScriptableObject { [MenuItem(FSequenceEditorWindow.MENU_PATH + FSequenceEditorWindow.PRODUCT_NAME + "/Create Flux Settings", false, 101)] public static void CreateColorSettings() { string settingsPath = FluxEditor.FUtility.GetFluxEditorPath() + "FluxSettings.asset"; if (AssetDatabase.LoadMainAssetAtPath(settingsPath) != null) { if (!EditorUtility.DisplayDialog("Warning", "Flux Settings already exist, are you sure you want to replace them?", "Replace", "Cancel")) return; } FSettings settings = CreateInstance<FSettings>(); AssetDatabase.CreateAsset(settings, settingsPath); } [SerializeField] private List<FColorSetting> _eventColors = new List<FColorSetting>(); public List<FColorSetting> EventColors { get { return _eventColors; } } private Dictionary<string, FColorSetting> _eventColorsHash = null; [SerializeField] private List<FColorSetting> _defaultContainers = new List<FColorSetting>(); public List<FColorSetting> DefaultContainers { get { return _defaultContainers; } } [SerializeField] private List<FContainerSetting> _containerType = new List<FContainerSetting>(); public List<FContainerSetting> ContainerType { get { return _containerType; } } public void Init() { if (_eventColorsHash == null) _eventColorsHash = new Dictionary<string, FColorSetting>(); else _eventColorsHash.Clear(); foreach (FColorSetting colorSetting in _eventColors) { if (string.IsNullOrEmpty(colorSetting._str)) return; if (_eventColorsHash.ContainsKey(colorSetting._str)) return; // can't add duplicates! _eventColorsHash.Add(colorSetting._str, colorSetting); } Type containerType = typeof(Flux.FContainerEnum); var fields = Enum.GetValues(containerType); List<FContainerSetting> cset = new List<FContainerSetting>(ContainerType); ContainerType.Clear(); for (int i = 0; i < fields.Length; i++) { Flux.FContainerEnum e = (Flux.FContainerEnum)Enum.Parse(containerType, fields.GetValue(i).ToString()); if (e == Flux.FContainerEnum.FContainer) continue; string title = "-"; foreach (var pair in Flux.FContainer.ContainerMap) { if (pair.Value == e) { title = pair.Key; break; } } if (title.Equals("-")) continue; int index = cset.FindIndex(m => m._type == e); if (index < 0) { FContainerSetting container = new FContainerSetting(e, title, new List<string>()); ContainerType.Add(container); } else { cset[index]._name = title; ContainerType.Add(cset[index]); } } } public Color GetEventColor(string str) { if (_eventColorsHash == null) Init(); // Debug.Log ( eventTypeStr ); FColorSetting c; if (!_eventColorsHash.TryGetValue(str, out c)) return FGUI.GetEventColor(); return c._color; } } [System.Serializable] public class FColorSetting { public string _str; public Color _color; public FColorSetting(string str, Color color) { _str = str; _color = color; } } [System.Serializable] public class FContainerSetting { public Flux.FContainerEnum _type; public string _name; public List<string> _list; public FContainerSetting(Flux.FContainerEnum type, string name, List<string> list) { _type = type; _name = name; _list = list; } } } <file_sep>using UnityEngine; using System.Collections; using XmlCfg.Skill; namespace Flux { [FEvent("碰撞检测")] public class FHitCheck : FEvent { [SerializeField, HideInInspector] private Transform _target;//碰撞绑定对象 [SerializeField, HideInInspector] private bool _isDynamic = false; [SerializeField, HideInInspector] private FHitZone _zone; [SerializeField, HideInInspector] private FSequence _sequence; public override string Text { get { return string.Format("区域{0}", _zone == null ? "?" : _zone.ZoneID.ToString()); } set { } } private TransformSnapshot _targetSnapshot; protected static bool HitCube(FHitZone zone) { return false; } protected static bool HitSphere(FHitZone zone) { return false; } protected static bool HitCylinder(FHitZone zone) { return false; } protected static bool CheckHit(FHitZone zone) { bool result = false; switch (zone.SharpType) { case HitSharpType.Cube: result = HitCube(zone); break; case HitSharpType.Sphere: result = HitSphere(zone); break; case HitSharpType.Cylinder: result = HitCylinder(zone); break; default: break; } return result; } protected bool HasData() { bool hasZone = _zone != null; if (!hasZone) Debug.LogError("未配置碰撞区域数据"); bool hasSequence = _sequence != null; if (!hasSequence) Debug.LogError("未配置序列信息"); bool hasTarget = _target != null; if (!hasTarget) Debug.LogError("未配置目标对象"); return hasZone && hasSequence && hasTarget; } protected override void SetDefaultValues() { base.SetDefaultValues(); _target = transform; _targetSnapshot = new TransformSnapshot(_target, false); } protected override void OnUpdateEvent(float timeSinceTrigger) { base.OnUpdateEvent(timeSinceTrigger); if (!HasData()) return; if (CheckHit(_zone) && Sequence.IsPlaying) _sequence.Play(_sequence.InverseFrameRate + timeSinceTrigger); } protected override void OnPause() { base.OnPause(); if (!HasData()) return; _sequence.Pause(); } protected override void OnResume() { base.OnResume(); if (!HasData()) return; _sequence.Resume(); } protected override void OnStop() { base.OnStop(); if (!HasData()) return; _sequence.Stop(); _targetSnapshot.Restore(); } protected override void OnFinish() { base.OnFinish(); if (!HasData()) return; _sequence.Pause(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.AllType { public enum CardElement { Attack = 0, Extract = 1, Renounce = 2, Armor = 3, Control = 4, Cure = 5, Oneself = 6, Hand = 7, Brary = 8, Handack = 9, } } <file_sep>using System.Collections.Generic; using UnityEditor; public partial class ExportResource { static Dictionary<string, string> assetAvatars = new Dictionary<string, string>(); static void GetAvatarAssets() { assetAvatars.Clear(); GetAssetsRecursively("Assets/Avatar", "*.prefab", "avatar/", "ar", ref assetAvatars); } static void ExportSelectedAvatars(BuildTarget target) { GetAvatarAssets(); UnityEngine.Object[] selection = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets); if (selection.Length > 0) { var assets = GetSelectedAssets(assetAvatars, selection); SetAssetBundleName(assets, new string[] { EXT_SHADER }, SHADER_FOLDER); SetAssetBundleName(assets); BuildAssetBundles(target); } } static void ExportAllAvatars(BuildTarget target) { GetAvatarAssets(); SetAssetBundleName(assetAvatars, new string[] { EXT_SHADER }, SHADER_FOLDER); SetAssetBundleName(assetAvatars); BuildAssetBundles(target); } [MenuItem("Assets/Build Selected for Windows/Avatar")] static void ExportSelectedAvatarsForWindows() { ExportSelectedAvatars(BuildTarget.StandaloneWindows); } [MenuItem("Assets/Build Selected for Android/Avatar")] static void ExportSelectedAvatarsForAndroid() { //ForAndroidSfxProcessBug(BuildTarget.Android); ExportSelectedAvatars(BuildTarget.Android); } [MenuItem("Assets/Build Selected for iOS/Avatar")] static void ExportSelectedAvatarsForiOS() { ExportSelectedAvatars(BuildTarget.iOS); } [MenuItem("Build Windows/Build Avatars for Windows")] static void ExportAllAvatarsForWindows() { ExportAllAvatars(BuildTarget.StandaloneWindows); } [MenuItem("Build Android/Build Avatars for Android")] static void ExportAllAvatarsForAndroid() { //ForAndroidSfxProcessBug(BuildTarget.Android); ExportAllAvatars(BuildTarget.Android); } [MenuItem("Build iOS/Build Avatars for iOS")] static void ExportAllAvatarsForiOS() { ExportAllAvatars(BuildTarget.iOS); } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public enum LockObjectType { /// <summary> /// 不需要目标 /// <summary> None = 0, /// <summary> /// 敌方目标 /// <summary> Enemy = 1, /// <summary> /// 己方目标 /// <summary> Teammate = 2, /// <summary> /// 自己 /// <summary> Self = 3, /// <summary> /// 中立方 /// <summary> Other = 4, } } <file_sep>public static class UObjectExtention { // 说明:lua侧判Object为空全部使用这个函数 public static bool IsNull(this UnityEngine.Object o) { return o == null; } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Flux { public class FEventField : PropertyAttribute { public string Name; public string Tip; public FEventField(string name, string tip) { Name = name; Tip = tip; } public FEventField(string name) { Name = name; Tip = ""; } } } <file_sep>using UnityEngine; using UnityEditor; using Flux; namespace FluxEditor { [CustomEditor(typeof(FVolumeAudioEvent))] public class FVolumeAudioEventInspector : FTweenEventInspector { private FVolumeAudioEvent _audioEvt; private SerializedProperty _source; private GUIContent _sourceUI = new GUIContent("音频源"); private AudioSource[] _sources; private GUIContent[] _sourceNames; private int _selectedIndex; protected override void OnEnable() { base.OnEnable(); _audioEvt = (FVolumeAudioEvent)target; _source = serializedObject.FindProperty("_source"); _sources = FUtility.FindObjects<AudioSource>(); _sourceNames = new GUIContent[_sources.Length]; for (int i = 0; i < _sources.Length; i++) _sourceNames[i] = new GUIContent(_sources[i].name); if (_sources.Length > 0) _source.objectReferenceValue = _sources[_selectedIndex]; serializedObject.ApplyModifiedProperties(); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); EditorGUI.BeginChangeCheck(); int index = EditorGUILayout.Popup(_sourceUI, _selectedIndex, _sourceNames); if (EditorGUI.EndChangeCheck()) { _selectedIndex = index; _source.objectReferenceValue = _sources[index]; } serializedObject.ApplyModifiedProperties(); } } } <file_sep>/******************************************************************** created: 2016-07-13 author: zhangjialing description: Copyright (C) - All Rights Reserved *********************************************************************/ using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Game { public class AnimationClipObject { public static float CacheTime = 10; public AnimationClip clip; //public AssetBundle ab; public int refcount ; //ÒýÓüÆÊý public float lastusetime; public AnimationClipObject(AnimationClip clip) { this.clip = clip; //this.ab = ab; this.refcount = 0; this.lastusetime = Time.time; } public AnimationClip GetAnimtionClip() { lastusetime = Time.time; return clip; } public bool CanRelease() { return refcount <=0 && Time.time - lastusetime > CacheTime ; } public void Release() { //Util.LogColor("red", "AudioPool:Release " + path + Time.time); //Object.DestroyImmediate(clip,true); Resources.UnloadAsset(clip); //ab.Unload(false); clip = null; //ab = null; } } public class AnimationClipPool { static Dictionary<int, AnimationClipObject> Pool = new Dictionary<int, AnimationClipObject>(); static float _cleanupLastTime = 0; public static bool Contains(int hashclip) { return Pool.ContainsKey(hashclip); } public static AnimationClip Get(int hashclip) { if (Pool.ContainsKey(hashclip)) { return Pool[hashclip].GetAnimtionClip(); } return null; } public static void AddClipRef(int hashclip) { if (Pool.ContainsKey(hashclip)) { Pool[hashclip].refcount++; } } public static void RemoveClipRef(int hashclip) { if (Pool.ContainsKey(hashclip)) { Pool[hashclip].refcount--; } } public static void AddClipRef(string clip) { AddClipRef(Animator.StringToHash(clip)); } public static void RemoveClipRef(string clip) { RemoveClipRef(Animator.StringToHash(clip)); } public static void Put(int hashclip,AnimationClip clip) { if (clip == null) { Debug.LogError("Load Clip Error! clip == null :" + LuaHelper.hash_name_map[hashclip]); return; } if (!Pool.ContainsKey(hashclip)) { Pool[hashclip] = new AnimationClipObject(clip); } Pool[hashclip].lastusetime = Time.time; } public static void CleanupInterval() { const float interval = 30; if (Time.realtimeSinceStartup > _cleanupLastTime + interval) { CleanupNow(); } if (Input.GetKeyDown(KeyCode.Q)) { //Util.LogColor("cyan", "PoolCount:" + Pool.Count); foreach (var pair in Pool) { if (pair.Value.refcount <= 0) { //Util.LogColor("red", LuaHelper.hash_name_map[pair.Key] + " : " + pair.Value.refcount); } else { //Util.LogColor("cyan", LuaHelper.hash_name_map[pair.Key] + " : " + pair.Value.refcount); } } } } public static void CleanupNow() { _cleanupLastTime = Time.realtimeSinceStartup; var unusedanimationclips = new List<int>(); foreach (var pair in Pool) { if (pair.Value.CanRelease()) { unusedanimationclips.Add(pair.Key); } } foreach (var hashclip in unusedanimationclips) { Pool[hashclip].Release(); //Util.LogColor("red", "AnimationClipPool Remove:" + LuaHelper.hash_name_map[hashclip]); Pool.Remove(hashclip); } } public static void ReleaseAll() { foreach (var kv in Pool) { kv.Value.Release(); } Pool.Clear(); } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Flux { public class FFindPathBtn : PropertyAttribute { public FFindPathBtn() { } } }<file_sep>--手写枚举定义 local CtrlNames = { Prompt = "PromptCtrl", Message = "MessageCtrl" } local PanelNames = { "PromptPanel", "MessagePanel", } --协议类型-- local ProtocalType = { BINARY = 0, PB_LUA = 1, PBC = 2, SPROTO = 3, } --当前使用的协议类型-- local TestProtoType = ProtocalType.BINARY; return { CtrlNames, PanelNames, ProtocalType, TestProtoType, } <file_sep>using UnityEngine; using System.Collections; using System; namespace Flux { [FEvent("控制器/对象替换", isSingle: true)] public class FReplaceObject : FController { [SerializeField, HideInInspector] [FEventField("新对象"), FFindPathBtn] private string _newObject; [SerializeField, HideInInspector] [FEventField("相对位置")] private Vector3 _offset; [SerializeField, HideInInspector] [FEventField("相对旋转")] private Vector3 _eulerAngles; private bool _iniState; private GameObject _oldObj; private GameObject _newObj; private TransformSnapshot _newSnapshot; public override string Text { get { string[] oldNodes = _path == null ? null : _path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string[] newNodes = _path == null ? null : _newObject.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string tip = "Miss"; if (oldNodes != null && oldNodes.Length > 0 && newNodes != null && newNodes.Length > 0) { string oldObj = oldNodes[oldNodes.Length - 1]; string newObj = newNodes[newNodes.Length - 1]; tip = string.Format("{0}->{1}", oldObj, newObj); } return tip; } set { } } protected override void OnInit() { base.OnInit(); _oldObj = FUtility.FindGameObject(_path); _newObj = FUtility.FindGameObject(_newObject); } protected override void OnTrigger(float timeSinceTrigger) { base.OnTrigger(timeSinceTrigger); if (_newObj != null) _newSnapshot = new TransformSnapshot(_newObj.transform, false); if (_oldObj != null) _oldObj.SetActive(false); if (_newObj != null) { _newObj.transform.parent = _oldObj.transform.parent; _newObj.transform.localPosition = _offset; _newObj.transform.localEulerAngles = _eulerAngles; } } protected override void OnStop() { base.OnStop(); if (_oldObj != null) _oldObj.SetActive(true); if (_newSnapshot != null) _newSnapshot.Restore(); } } } <file_sep>using UnityEngine; using UnityEditor; using Sirenix; [CustomEditor(typeof(MecanimControl))] public class MecanimControlEditor : Editor { bool mEndHorizontal = false; public bool DrawHeader(string text, bool forceOn) { string key = text; bool minimalistic = !forceOn; bool state = EditorPrefs.GetBool(key, true); if (!minimalistic) GUILayout.Space(3f); if (!forceOn && !state) GUI.backgroundColor = new Color(0.8f, 0.8f, 0.8f); GUILayout.BeginHorizontal(); GUI.changed = false; if (minimalistic) { if (state) text = "\u25BC" + (char)0x200a + text; else text = "\u25BA" + (char)0x200a + text; GUILayout.BeginHorizontal(); GUI.contentColor = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.7f) : new Color(0f, 0f, 0f, 0.7f); if (!GUILayout.Toggle(true, text, "PreToolbar2", GUILayout.MinWidth(20f))) state = !state; GUI.contentColor = Color.white; GUILayout.EndHorizontal(); } else { text = "<b><size=11>" + text + "</size></b>"; if (state) text = "\u25BC " + text; else text = "\u25BA " + text; if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) state = !state; } if (GUI.changed) EditorPrefs.SetBool(key, state); if (!minimalistic) GUILayout.Space(2f); GUILayout.EndHorizontal(); GUI.backgroundColor = Color.white; if (!forceOn && !state) GUILayout.Space(3f); return state; } public void BeginContents(bool minimalistic) { if (!minimalistic) { mEndHorizontal = true; GUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal(EditorStyles.textArea, GUILayout.MinHeight(10f)); } else { mEndHorizontal = false; EditorGUILayout.BeginHorizontal(EditorStyles.textArea, GUILayout.MinHeight(10f)); GUILayout.Space(10f); } GUILayout.BeginVertical(); GUILayout.Space(2f); } public void EndContents() { GUILayout.Space(3f); GUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); if (mEndHorizontal) { GUILayout.Space(3f); GUILayout.EndHorizontal(); } GUILayout.Space(3f); } public override void OnInspectorGUI() { EditorGUIUtility.labelWidth = 200f; MecanimControl mc = target as MecanimControl; GUILayout.Space(6f); EditorGUILayout.LabelField("Model Name", mc.modelName); mc.debugMode = EditorGUILayout.Toggle("Debug Mode", mc.debugMode); mc.alwaysPlay = EditorGUILayout.Toggle("Always Play", mc.alwaysPlay); mc.playOnStart = EditorGUILayout.Toggle("Play On Start", mc.playOnStart); mc.overrideRootMotion = EditorGUILayout.Toggle("Override Root Motion", mc.overrideRootMotion); mc.defaultTransitionDuration = EditorGUILayout.FloatField("Default Transition Duration", mc.defaultTransitionDuration); mc.defaultWrapMode = (WrapMode)EditorGUILayout.EnumPopup("Default Wrap Mode", mc.defaultWrapMode); if (DrawHeader("Default Animation", true)) { BeginContents(false); EditorGUILayout.BeginVertical(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Clip", GUILayout.MinWidth(150), GUILayout.Height(50)); EditorGUILayout.LabelField("Name", GUILayout.MinWidth(150), GUILayout.Height(50)); EditorGUILayout.LabelField("Speed", GUILayout.Width(50), GUILayout.Height(50)); EditorGUILayout.LabelField("Transition\nDuration", GUILayout.Width(60), GUILayout.Height(50)); EditorGUILayout.LabelField("Wrap\nMode", GUILayout.Width(50), GUILayout.Height(50)); EditorGUILayout.LabelField("Apply\nRoot\nMotion", GUILayout.Width(50), GUILayout.Height(50)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); var clip = mc.defaultAnimationData.clip; clip = EditorGUILayout.ObjectField(clip, typeof(AnimationClip), false, GUILayout.MinWidth(150)) as AnimationClip; mc.defaultAnimationData.clipName = EditorGUILayout.TextField(mc.defaultAnimationData.clipName, GUILayout.MinWidth(150)); mc.defaultAnimationData.speed = EditorGUILayout.FloatField(mc.defaultAnimationData.speed, GUILayout.Width(50)); mc.defaultAnimationData.transitionDuration = EditorGUILayout.FloatField(mc.defaultAnimationData.transitionDuration, GUILayout.Width(50)); mc.defaultAnimationData.wrapMode = (WrapMode)EditorGUILayout.EnumPopup(mc.defaultAnimationData.wrapMode, GUILayout.Width(50)); mc.defaultAnimationData.applyRootMotion = EditorGUILayout.Toggle(mc.defaultAnimationData.applyRootMotion, GUILayout.Width(50)); if (clip != mc.defaultAnimationData.clip) { mc.defaultAnimationData.clip = clip; mc.defaultAnimationData.clipName = clip.name; mc.defaultAnimationData.speed = 1; mc.defaultAnimationData.transitionDuration = -1; mc.defaultAnimationData.wrapMode = clip.wrapMode; mc.defaultAnimationData.applyRootMotion = false; } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); EndContents(); } if (DrawHeader("Animations", true)) { BeginContents(false); EditorGUILayout.BeginVertical(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Clip", GUILayout.MinWidth(150), GUILayout.Height(50)); EditorGUILayout.LabelField("Name", GUILayout.MinWidth(150), GUILayout.Height(50)); EditorGUILayout.LabelField("Speed", GUILayout.Width(50), GUILayout.Height(50)); EditorGUILayout.LabelField("Transition\nDuration", GUILayout.Width(60), GUILayout.Height(50)); EditorGUILayout.LabelField("Wrap\nMode", GUILayout.Width(50), GUILayout.Height(50)); EditorGUILayout.LabelField("Apply\nRoot\nMotion", GUILayout.Width(50), GUILayout.Height(50)); EditorGUILayout.EndHorizontal(); EditorGUI.BeginDisabledGroup(true); foreach (var pairs in mc.animations) { var animData = pairs.Value; EditorGUILayout.BeginHorizontal(); var clip = animData.clip; clip = EditorGUILayout.ObjectField(clip, typeof(AnimationClip), false, GUILayout.MinWidth(150)) as AnimationClip; animData.clipName = EditorGUILayout.TextField(animData.clipName, GUILayout.MinWidth(150)); animData.speed = EditorGUILayout.FloatField(animData.speed, GUILayout.Width(50)); animData.transitionDuration = EditorGUILayout.FloatField(animData.transitionDuration, GUILayout.Width(50)); animData.wrapMode = (WrapMode)EditorGUILayout.EnumPopup(animData.wrapMode, GUILayout.Width(50)); animData.applyRootMotion = EditorGUILayout.Toggle(animData.applyRootMotion, GUILayout.Width(50)); EditorGUILayout.EndHorizontal(); } EditorGUI.EndDisabledGroup(); EditorGUILayout.EndVertical(); EndContents(); } } } <file_sep>using System; using System.Collections.Generic; using UnityEngine; public static class ExtendedAnimator { public static float Bake(this Animator animator, string action) { if(!string.IsNullOrEmpty(action)) { animator.Rebind(); animator.StopPlayback(); animator.recorderStartTime = 0; // 这里可以在指定的时间触发新的动画状态 animator.Play(action); AnimatorStateInfo info = animator.GetCurrentAnimatorStateInfo(0); //const float frameRate = 30f; //int frameCount = (int)((Duration * frameRate) + 2); // 开始记录指定的帧数 animator.StartRecording(0); while (info.normalizedTime < 1f) { // 记录每一帧 animator.Update(1.0f / 30); info = animator.GetCurrentAnimatorStateInfo(0); //Debug.Log(info.length); //Debug.Log(info.normalizedTime); if (info.length <= 0) { return 0; } } // 完成记录 animator.StopRecording(); // 开启回放模式 animator.StartPlayback(); return info.length; } return 0; } public static float BakeCurrent(this Animator animator) { animator.Rebind(); animator.StopPlayback(); animator.recorderStartTime = 0; // 这里可以在指定的时间触发新的动画状态 AnimatorStateInfo info = animator.GetCurrentAnimatorStateInfo(0); //const float frameRate = 30f; //int frameCount = (int)((Duration * frameRate) + 2); // 开始记录指定的帧数 animator.StartRecording(0); while (info.normalizedTime < 1f) { // 记录每一帧 animator.Update(1.0f / 30); info = animator.GetCurrentAnimatorStateInfo(0); //Debug.Log(info.length); //Debug.Log(info.normalizedTime); } // 完成记录 animator.StopRecording(); // 开启回放模式 animator.StartPlayback(); return info.length; } //public static UnityEditorInternal.State GetDefaultState(this Animator animator) //{ // // Get a reference to the Animator Controller: // UnityEditorInternal.AnimatorController ac = animator.runtimeAnimatorController as UnityEditorInternal.AnimatorController; // if(ac != null) // { // UnityEditorInternal.AnimatorControllerLayer layer = ac.GetLayer(0); // UnityEditorInternal.StateMachine sm = layer.stateMachine; // return sm.defaultState; // } // return null; //} //public static string GetDefaultStateName(this Animator animator) //{ // UnityEditorInternal.State state = animator.GetDefaultState(); // if (state != null) // { // return state.name; // } // return string.Empty; //} public static float GetCurrentStateLength(this Animator animator) { if (animator != null) { AnimatorStateInfo info = animator.GetCurrentAnimatorStateInfo(0); return info.length; } return 0; } public static void Sample(this Animator animator, float time) { if (animator != null) { animator.playbackTime = time; animator.Update(0); } } } <file_sep>using UnityEngine; using UnityEditor; using UnityEditor.Animations; //using UnityEditorInternal; using System.Collections.Generic; using Flux; using FluxEditor; namespace FluxEditor { [CustomEditor(typeof(FAnimationTrack))] public class FAnimationTrackInspector : FTrackInspector { // private const string ADVANCE_TRIGGER = "FAdvanceTrigger"; private const string FLUX_STATE_MACHINE_NAME = "FluxStateMachine"; private FAnimationTrack _animTrack = null; private SerializedProperty _owner = null; private SerializedProperty _layerName = null; private SerializedProperty _layerId = null; private GUIContent _ownerUI; public override void OnEnable() { base.OnEnable(); if (target == null) { DestroyImmediate(this); return; } _animTrack = (FAnimationTrack)target; _owner = serializedObject.FindProperty("_owner"); _layerName = serializedObject.FindProperty("_layerName"); _layerId = serializedObject.FindProperty("_layerId"); _ownerUI = new GUIContent("角色"); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(_owner, _ownerUI); if (EditorGUI.EndChangeCheck()) { _animTrack.ClearCache(); _animTrack.AnimatorController = null; serializedObject.ApplyModifiedProperties(); SetAnimator(_animTrack); } } public void UpdateLayer(AnimatorControllerLayer layer) { if (layer == null) { _layerName.stringValue = null; _layerId.intValue = -1; } else { AnimatorController controller = (AnimatorController)_animTrack.AnimatorController; for (int i = 0; i != controller.layers.Length; ++i) { if (controller.layers[i].name == layer.name) { _layerName.stringValue = layer.name; _layerId.intValue = i; return; } } // shouldn't get here.. Debug.LogError("Trying to set a layer that doesn't belong to the controller"); UpdateLayer(null); } } public static void SetAnimator(FAnimationTrack animTrack) { if (animTrack.Owner.GetComponent<Animator>() == null) { Animator animator = animTrack.Owner.gameObject.AddComponent<Animator>(); Undo.RegisterCreatedObjectUndo(animator, string.Empty); } if (animTrack.AnimatorController == null) { var temp = FUtility.GetFluxAssets<UnityEditor.Animations.AnimatorController>("EditorAnimatorController.controller"); var animatorController = Instantiate(temp); animTrack.LayerId = 0; animTrack.LayerName = "Base Layer"; var layers = animatorController.layers; layers[animTrack.LayerId].name = animTrack.LayerName; layers[animTrack.LayerId].stateMachine.name = animTrack.LayerName; animatorController.layers = layers; animTrack.AnimatorController = animatorController; FAnimationTrackInspector.RebuildStateMachine(animTrack); } } public static void RebuildStateMachine(FAnimationTrack track) { if (track.AnimatorController == null || track.LayerId == -1) return; bool isPreviewing = track.HasCache; if (isPreviewing) track.ClearCache(); Animator animator = track.Owner.GetComponent<Animator>(); animator.runtimeAnimatorController = null; AnimatorController controller = (AnimatorController)track.AnimatorController; track.UpdateEventIds(); AnimatorControllerLayer layer = FindLayer(controller, track.LayerName); if (layer == null) { controller.AddLayer(track.LayerName); layer = FindLayer(controller, track.LayerName); } AnimatorStateMachine fluxSM = FindStateMachine(layer.stateMachine, FLUX_STATE_MACHINE_NAME); if (fluxSM == null) { fluxSM = layer.stateMachine.AddStateMachine(FLUX_STATE_MACHINE_NAME); ChildAnimatorStateMachine[] stateMachines = layer.stateMachine.stateMachines; for (int i = 0; i != stateMachines.Length; ++i) { if (stateMachines[i].stateMachine == fluxSM) { stateMachines[i].position = layer.stateMachine.entryPosition + new Vector3(300, 0, 0); break; } } layer.stateMachine.stateMachines = stateMachines; } List<FEvent> events = track.Events; if (fluxSM.states.Length > events.Count) { for (int i = events.Count; i < fluxSM.states.Length; ++i) fluxSM.RemoveState(fluxSM.states[i].state); } else if (fluxSM.states.Length < events.Count) { for (int i = fluxSM.states.Length; i < events.Count; ++i) fluxSM.AddState(i.ToString()); } AnimatorState lastState = null; Vector3 pos = fluxSM.entryPosition + new Vector3(300, 0, 0); Vector3 statePosDelta = new Vector3(0, 80, 0); ChildAnimatorState[] states = fluxSM.states; for (int i = 0; i != events.Count; ++i) { FPlayAnimationEvent animEvent = (FPlayAnimationEvent)events[i]; if (animEvent._animationClip == null) // dump events without animations continue; states[i].position = pos; AnimatorState state = states[i].state; state.name = i.ToString(); pos += statePosDelta; state.motion = animEvent._animationClip; animEvent._stateHash = Animator.StringToHash(state.name); if (lastState) { AnimatorStateTransition[] lastStateTransitions = lastState.transitions; if (animEvent.IsBlending()) { AnimatorStateTransition transition = null; for (int j = lastStateTransitions.Length - 1; j > 0; --j) { lastState.RemoveTransition(lastStateTransitions[j]); } transition = lastStateTransitions.Length == 1 ? lastStateTransitions[0] : lastState.AddTransition(state); transition.offset = (animEvent._startOffset / animEvent._animationClip.frameRate) / animEvent._animationClip.length; FPlayAnimationEvent prevAnimEvent = (FPlayAnimationEvent)events[i - 1]; int offsetFrame = Mathf.RoundToInt(transition.offset * animEvent._animationClip.length * animEvent._animationClip.frameRate); animEvent._startOffset = Mathf.Clamp(offsetFrame, 0, animEvent.GetMaxStartOffset()); transition.offset = (animEvent._startOffset / animEvent._animationClip.frameRate) / animEvent._animationClip.length; EditorUtility.SetDirty(animEvent); float blendSeconds = animEvent._blendLength / prevAnimEvent._animationClip.frameRate; transition.duration = blendSeconds; transition.hasExitTime = true; float p = blendSeconds / prevAnimEvent._animationClip.length; transition.exitTime = p > 1f ? 1f : 1f - Mathf.Clamp01(blendSeconds / prevAnimEvent._animationClip.length); for (int j = transition.conditions.Length - 1; j >= 0; --j) { transition.RemoveCondition(transition.conditions[j]); } // AnimatorCondition condition = transition.conditions[0]; // condition.threshold = 0; } else // animations not blending, needs hack for animation previewing { for (int j = lastStateTransitions.Length - 1; j >= 0; --j) { lastState.RemoveTransition(lastStateTransitions[j]); } } } lastState = state; } fluxSM.states = states; if (fluxSM.states.Length > 0) layer.stateMachine.defaultState = fluxSM.states[0].state; animator.runtimeAnimatorController = controller; if (isPreviewing) track.CreateCache(); } public static AnimatorStateTransition GetTransitionTo(FPlayAnimationEvent animEvt) { FAnimationTrack animTrack = (FAnimationTrack)animEvt.Track; if (animTrack.AnimatorController == null) return null; AnimatorController controller = (AnimatorController)animTrack.AnimatorController; AnimatorState animState = null; AnimatorControllerLayer layer = FindLayer(controller, ((FAnimationTrack)animEvt.Track).LayerName); if (layer == null) return null; if (layer.stateMachine.stateMachines.Length == 0) return null; ChildAnimatorStateMachine fluxSM = layer.stateMachine.stateMachines[0]; AnimatorStateMachine stateMachine = fluxSM.stateMachine; for (int i = 0; i != stateMachine.states.Length; ++i) { if (stateMachine.states[i].state.nameHash == animEvt._stateHash) { animState = stateMachine.states[i].state; break; } } if (animState == null) { // Debug.LogError("Couldn't find state " + animEvt._animationClip ); return null; } for (int i = 0; i != stateMachine.states.Length; ++i) { AnimatorState state = stateMachine.states[i].state; AnimatorStateTransition[] transitions = state.transitions; for (int j = 0; j != transitions.Length; ++j) { if (transitions[j].destinationState == animState) { return transitions[j]; } } } return null; } private static AnimatorControllerParameter FindParameter(AnimatorController controller, string paramName) { foreach (AnimatorControllerParameter p in controller.parameters) { if (p.name == paramName) return p; } return null; } private static AnimatorControllerLayer FindLayer(AnimatorController controller, string layerName) { foreach (AnimatorControllerLayer layer in controller.layers) { if (layer.name == layerName) return layer; } return null; } private static AnimatorStateMachine FindStateMachine(AnimatorStateMachine stateMachine, string stateMachineName) { foreach (ChildAnimatorStateMachine sm in stateMachine.stateMachines) { if (sm.stateMachine.name == stateMachineName) return sm.stateMachine; } return null; } } } <file_sep> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Game { public class AudioObject { public static float CacheTime = 10; public static float IntervalTime = 0.2f; public float lastusetime; public string path; public AudioClip clip; public AssetBundle ab; public bool CanPlay() { return Time.time - lastusetime > IntervalTime; } public bool CanRelease() { return Time.time - lastusetime > clip.length + CacheTime; } public void Release() { //Util.LogColor("red", "AudioPool:Release " + path + Time.time); //Object.DestroyImmediate(clip,true); Resources.UnloadAsset(clip); ab.Unload(false); } } public class AudioPool { static readonly int MaxPoolCount = 10; static Dictionary<string, AudioObject> Pool = new Dictionary<string, AudioObject>(); static float _cleanupLastTime = 0; public static string GetStandardlize(string path) { return path.Replace(@"\", @"/").ToLower(); } public static bool Contains(string ipath) { var path = GetStandardlize(ipath); return Pool.ContainsKey(path); } public static bool CanPlay(string ipath) { var path = GetStandardlize(ipath); if (!Pool.ContainsKey(path)) { return true; } AudioObject ao = Pool.Get(path); return ao.CanPlay(); } public static AudioClip Get(string ipath) { var path = GetStandardlize(ipath); if (Pool.ContainsKey(path)) { Pool[path].lastusetime = Time.time; return Pool[path].clip; } return null; } public static void Put(string ipath, AudioClip clip,AssetBundle ab) { var path = GetStandardlize(ipath); if (Pool.ContainsKey(path)) { if (Pool[path].ab != ab) { ab.Unload(false); } Pool[path].lastusetime = Time.time; } else { AudioObject newclipobject = new AudioObject(); newclipobject.path = path; newclipobject.lastusetime = Time.time; newclipobject.clip = clip; newclipobject.ab = ab; Pool[path] = newclipobject; //Util.LogColor("green", "AudioPool:New " + path + Time.time); } } public static void CleanupInterval() { const float interval = 30; if (Time.realtimeSinceStartup > _cleanupLastTime + interval) { CleanupNow(); } } public static void CleanupNow() { if (Pool.Count > MaxPoolCount) { var unusedeffectpools = new List<AudioObject>(); foreach (var pair in Pool) { if (pair.Value.CanRelease()) { unusedeffectpools.Add(pair.Value); } } unusedeffectpools.Sort((x, y) => { return x.lastusetime.CompareTo(y.lastusetime); }); for (int index = 0; index < Mathf.Min(Pool.Count - MaxPoolCount, unusedeffectpools.Count); index++) { unusedeffectpools[index].Release(); Pool.Remove(unusedeffectpools[index].path); } } } public static void ReleaseAll() { foreach (var kv in Pool) { kv.Value.Release(); } Pool.Clear(); } } } <file_sep>namespace CS.ActorConfig { using System; using System.IO; using System.Collections.Generic; using UnityEngine; using UnityEditor; using Sirenix.Utilities; using Sirenix.OdinInspector; using Sirenix.Utilities.Editor; using XmlCfg.Skill; using Cfg.Character; using Cfg; using Vec3 = UnityEngine.Vector3; using Flux; [GlobalConfig("ActorDesigner/ModelEditor/Editor", UseAsset = true)] internal class ActionHomeConfig : GlobalConfig<ActionHomeConfig> { /// <summary> /// 分类名称 /// </summary> public static readonly Dictionary<GroupType, string> MenuItems = new Dictionary<GroupType, string>() { {GroupType.None, "主页" }, {GroupType.Base, "基础类型" }, {GroupType.Player, "玩家" }, {GroupType.Monster, "怪物" }, {GroupType.NPC, "NPC" }, }; public static string[] MenuItemNames = { "主页", "基础类型", "玩家", "怪物", "NPC" }; [FolderPath(RequireExistingPath = true), BoxGroup("Config", showLabel: false)] [LabelText("Xml存储目录"), PropertyOrder(-100)] public string ActionConfigPath; [FolderPath(RequireExistingPath = true), BoxGroup("Config", showLabel: false)] [LabelText("Csv存储目录"), PropertyOrder(-99)] public string ConfigRelativeDir = ""; [FolderPath(RequireExistingPath = true), BoxGroup("Config", showLabel: false)] [LabelText("角色资源目录"), PropertyOrder(-98)] public string CharacterRelativeDir = ""; [FolderPath(RequireExistingPath = true), BoxGroup("Config", showLabel: false)] [LabelText("Avatar资源目录"), PropertyOrder(-98)] public string AvatarRelativeDir = ""; [FolderPath(RequireExistingPath = true), BoxGroup("Config", showLabel: false)] [LabelText("特效资源目录"), PropertyOrder(-98)] public string EffectRelativeDir = ""; [FolderPath(RequireExistingPath = true), BoxGroup("Config", showLabel: false)] [LabelText("碰撞体资源目录"), PropertyOrder(-98)] public string ColliderRelativeDir = ""; } [Serializable] internal class HomeConfig { private static HomeConfig _instance; public static HomeConfig Instance { get { if (_instance == null) _instance = new HomeConfig(); return _instance; } } private ActionHomeConfig _config; #region 界面设计 [FolderPath(RequireExistingPath = true), BoxGroup("Config", showLabel: false)] [ShowInInspector, ReadOnly, LabelText("Xml存储目录"), PropertyOrder(-100)] private string ActionConfigPath { get { return string.Format("{0}/../{1}/", Application.dataPath, _config.ActionConfigPath); } } [FolderPath(RequireExistingPath = true), BoxGroup("Config", showLabel: false)] [ShowInInspector, ReadOnly, LabelText("Csv存储目录"), PropertyOrder(-99)] private string ConfigDir { get { return string.Format("{0}/../{1}/", Application.dataPath, _config.ConfigRelativeDir); } } [ButtonGroup("Config/Btns")] [Button("加载所有动作", ButtonSizes.Large)] public void LoadAll() { ClearAll(); _config = ActionHomeConfig.Instance; CfgManager.ConfigDir = ConfigDir; CfgManager.LoadAll(); //--初始化资源路径 EUtil.GetAssetsInSubFolderRecursively(_config.CharacterRelativeDir, "*.prefab", ref AllCharacters); EUtil.GetAssetsInSubFolderRecursively(_config.AvatarRelativeDir, "*.prefab", ref AllAvatars); EUtil.GetAssetsInSubFolderRecursively(_config.EffectRelativeDir, "*.prefab", ref AllEffects); foreach (var item in AllCharacters) { string searchDir = item.Value.Substring(0, item.Value.LastIndexOf(@"/prefab")) + "/clips"; var selfClips = new Dictionary<string, string>(); EUtil.GetAssetsInSubFolderRecursively(searchDir, "*.anim", ref selfClips); AllCharacterClips[item.Key] = selfClips; } //--初始化资源 SequenceRoot = ActorHelper.CreateGameObject("---行为序列---"); RuntimeAssetRoot = ActorHelper.CreateGameObject("---运行时资源---"); CharacterDir = ActorHelper.CreateGameObject("Characters", "/---运行时资源---/"); EffectDir = ActorHelper.CreateGameObject("Effects", "/---运行时资源---/"); OtherDir = ActorHelper.CreateGameObject("Others", "/---运行时资源---/"); //--加载行为配置 foreach (var model in CfgManager.Model) { var modelName = model.Key; string path = string.Format("{0}/{1}.xml", ActionConfigPath, modelName); if (!File.Exists(path)) { var config = new ActorConfig() { ModelName = modelName }; string savePath = string.Format("{0}/{1}.xml", ActionHomeConfig.Instance.ActionConfigPath, modelName); var actor = new ActorConfigEditor(savePath, config); actor.Save(true); Debug.LogFormat("<color=orange>新建Actor - {0}</color>", modelName); } } string[] files = Directory.GetFiles(ActionConfigPath, "*.xml", SearchOption.TopDirectoryOnly); foreach (var path in files) { var actor = new ActorConfigEditor(path); AddActor(actor); } foreach (var item in _modelDict) item.Value.InitBaseModelAction(); var window = ActorCfgWindow.GetWindow<ActorCfgWindow>(); window.RefreshTree(); IsInit = true; Debug.Log("加载所有动作 完毕!"); } [ButtonGroup("Config/Btns")] [Button("保存所有配置", ButtonSizes.Large)] public void SaveAll() { foreach (var group in ModelGroupDict) { float count = 0; foreach (var cfg in group.Value) { try { if (group.Key != GroupType.None) cfg.Save(); } catch (Exception) { Debug.LogErrorFormat("{0} 数据异常,无法正常存储!", cfg.ModelName); } EditorUtility.DisplayProgressBar("导出所有配置>" + cfg.Group, cfg.Path, count / group.Value.Count); } } EditorUtility.ClearProgressBar(); Debug.Log("所有配置保存完毕~~"); } [Title("辅助功能区"), OnInspectorGUI, PropertyOrder(0)] void OnGUI_Func() { EditorGUILayout.BeginHorizontal(); GUIHelper.PushGUIPositionOffset(UnityEngine.Vector2.up * -2); if (GUILayout.Button("设置受击对象", GUILayout.Width(150))) { SimplePopupCreator.ShowDialog(new List<string>(CfgManager.Model.Keys), (name) => { _targetDisplayName = name; ActorConfigEditor actor = GetActorEditor(name); LoadTarget(actor); }); } GUIHelper.PopGUIPositionOffset(); EditorGUILayout.LabelField(_targetDisplayName, EditorStyles.textArea); EditorGUILayout.EndHorizontal(); } private string _targetDisplayName = ""; [HorizontalGroup("Separator", Order = 100)] [BoxGroup("Separator/Left", ShowLabel = false), SerializeField] [LabelText("显示打击框"), OnValueChanged("OnShowHitBox")] public bool _showHitBox = false; [BoxGroup("Separator/Left", ShowLabel = false), SerializeField] [LabelText("显示碰撞体"), OnValueChanged("OnShowCollider")] private bool _showCollider = false; [BoxGroup("Separator/Right", ShowLabel = false), SerializeField] [LabelText("显示攻击范围"), OnValueChanged("OnShowAttackRange")] private bool _showAttackRange = false; [BoxGroup("Separator/Right", ShowLabel = false), SerializeField] [LabelText("显示受击对象"), OnValueChanged("OnShowTarget")] private bool _showTarget = false; [Button("LoadAsset", ButtonSizes.Large)] void LoadAssetByPath() { _targetCollider = LoadCollider(_charColliderName); var collider = PrefabUtility.InstantiatePrefab(_targetCollider) as GameObject; collider.transform.parent = RuntimeAssetRoot.transform; Debug.LogError(collider.name); } private void OnShowHitBox() { if (Self != null) { var range = Self.GetComponentInChildren<SelfRange>(); range.SetRangeActive(_showHitBox); } if (Target != null) { var range = Target.GetComponentInChildren<SelfRange>(); range.SetRangeActive(_showHitBox); } } private void OnShowCollider() { //if (_targetCollider != null) // _targetCollider.SetActive(_showCollider); } private void OnShowAttackRange() { if (_attackRangeOb != null) _attackRangeOb.SetActive(_showAttackRange); } private void OnShowTarget() { if (Target != null) Target.gameObject.SetActive(_showTarget); } #endregion /// <summary> /// 剪切板 /// </summary> private List<ModelActionEditor> _clipboard = new List<ModelActionEditor>(); /// <summary> /// 所有模型数据 key-模型名称 value-模型编辑器 /// </summary> private Dictionary<string, ActorConfigEditor> _modelDict = new Dictionary<string, ActorConfigEditor>(); /// <summary> /// 模型分组信息 key-分组类型 value-模型行为编辑器 /// </summary> private Dictionary<GroupType, List<ActorConfigEditor>> _modelGroupDict = new Dictionary<GroupType, List<ActorConfigEditor>>(); private Dictionary<string, string> AllCharacters = new Dictionary<string, string>(); private Dictionary<string, string> AllAvatars = new Dictionary<string, string>(); private Dictionary<string, string> AllEffects = new Dictionary<string, string>(); public bool IsInit { get; private set; } public Dictionary<GroupType, List<ActorConfigEditor>> ModelGroupDict { get { if (_config == null) LoadAll(); return _modelGroupDict; } } public Dictionary<string, Dictionary<string, string>> AllCharacterClips = new Dictionary<string, Dictionary<string, string>>(); public void AddActor(ActorConfigEditor model) { if (ModelGroupDict.ContainsKey(model.GroupType)) ModelGroupDict[model.GroupType].Add(model); else { ModelGroupDict.Add(model.GroupType, new List<ActorConfigEditor>()); ModelGroupDict[model.GroupType].Add(model); } if (!_modelDict.ContainsKey(model.ModelName)) _modelDict.Add(model.ModelName, model); } public void RemoveActor(ActorConfigEditor model) { if (!ModelGroupDict.ContainsKey(model.GroupType)) { Debug.LogError("未定义组类型 " + model.GroupType); return; } if (!ModelGroupDict[model.GroupType].Remove(model)) Debug.LogErrorFormat("{0} 无法从分组中移除", model.MenuItemName); if (_modelDict.ContainsKey(model.ModelName)) _modelDict.Remove(model.ModelName); } public ActorConfigEditor GetActorEditor(string modelName) { if (_modelDict.ContainsKey(modelName)) return _modelDict[modelName]; Debug.LogErrorFormat("[读取配置]{0} 模型配置不存在!", modelName); return null; } public List<string> GetAllActorList() { return new List<string>(_modelDict.Keys); } public void Destroy() { //保存所有配置 SaveAll(); ClearAll(); _instance = null; } private void ClearAll() { IsInit = false; _modelGroupDict.Clear(); CfgManager.Clear(); _clipboard.Clear(); _modelDict.Clear(); AllCharacters.Clear(); AllAvatars.Clear(); AllCharacterClips.Clear(); AllEffects.Clear(); UnityEngine.Object.DestroyImmediate(SequenceRoot); UnityEngine.Object.DestroyImmediate(RuntimeAssetRoot); Resources.UnloadUnusedAssets(); } #region 辅助功能区 public GameObject SequenceRoot { get; private set; } public GameObject RuntimeAssetRoot { get; private set; } public GameObject CharacterDir { get; private set; } public GameObject EffectDir { get; private set; } public GameObject OtherDir { get; private set; } public GameObject Self { get; private set; } public GameObject Target { get; set; } public bool ShowHitBox { get { return _showHitBox; } } public bool ShowCollider { get { return _showCollider; } } public bool ShowAttackRange { get { return _showAttackRange; } } public bool ShowTarget { get { return _showTarget; } } public float AttackRange { get { return _attackRange; } set { _attackRange = value; LoadAttackRange(); } } private string _charColliderName = "cylinder360"; private string _attackRangeObName = "攻击区域"; private GameObject _targetCollider; private FSequence _sequence; private GameObject _attackRangeOb; private float _attackRange = 1; private List<GameObject> _hitBoxs = new List<GameObject>(); public void OpenSequence(ActorConfigEditor actor, ModelActionEditor action) { LoadSelf(actor); string targetName = _targetDisplayName; if (string.IsNullOrEmpty(targetName)) targetName = actor.ModelName; LoadTarget(actor); //_sequence = FSequence.CreateSequence(SequenceRoot); //FluxEditor.FSequenceEditorWindow.Open(_sequence); } public void CloseSequence() { var seq = SequenceRoot.GetComponent<FSequence>(); UnityEngine.Object.DestroyImmediate(seq); foreach (var item in _hitBoxs) UnityEngine.Object.DestroyImmediate(item); _hitBoxs.Clear(); } //-- 加载角色行为时加载资源 private void LoadSelf(ActorConfigEditor actor) { string modelName = CfgManager.Model[actor.ModelName].ModelPath; if (Self != null && Self.name.Equals(modelName)) return; if (Self != null) UnityEngine.Object.DestroyImmediate(Self); Self = ActorHelper.Instantiate(actor); Self.transform.parent = CharacterDir.transform; Self.transform.position = Vec3.forward * 10; Self.transform.forward = -Vec3.forward; //if (_showCollider) //{ // var ctrl = Self.GetComponent<CharacterController>(); // if (ctrl != null) // { // var collider = LoadCollider(_charColliderName); // collider.transform.localScale = Vec3.one * ctrl.radius; // } //} } private void LoadTarget(ActorConfigEditor actor) { string modelName = CfgManager.Model[actor.ModelName].ModelPath; if (Target != null && Target.name.Equals(modelName)) return; if (Target != null) UnityEngine.Object.DestroyImmediate(Target); Target = ActorHelper.Instantiate(actor); Target.transform.parent = CharacterDir.transform; Target.transform.position = Vec3.forward * -10; Target.transform.forward = Vec3.forward; var cap = Target.GetComponent<CapsuleCollider>(); if (cap != null) { var collider = LoadCollider(_charColliderName, Target); collider.SetActive(_showCollider); float size = cap.radius; collider.transform.localScale = Vec3.one * size; } else { Debug.LogErrorFormat("{0} 角色没有渲染组件!", Target.name); } } private void LoadAttackRange() { var attackRange = Self.transform.Find(_attackRangeObName); GizmosCircle circle = null; if (attackRange == null) { _attackRangeOb = ActorHelper.CreateGameObject(_attackRangeObName); _attackRangeOb.transform.parent = Self.transform; circle = _attackRangeOb.AddComponent<GizmosCircle>(); } else { circle = _attackRangeOb.GetComponent<GizmosCircle>(); } circle.m_Radius = AttackRange; _attackRangeOb.SetActive(_showAttackRange); } public GameObject LoadCollider(string collider, GameObject parent = null) { string path = string.Format("{0}/{1}.fbx", _config.ColliderRelativeDir, collider); GameObject col = ActorHelper.Instantiate(path, parent); col.GetComponent<Renderer>().material = new Material(Shader.Find("Transparent/Diffuse")); return col; } public string GetCharacterPath(string name) { string path = string.Empty; AllCharacters.TryGetValue(name, out path); return path; } public string GetAvatarPath(string name) { string path = string.Empty; AllAvatars.TryGetValue(name, out path); return path; } public string GetEffectPath(string name) { string path = string.Empty; AllEffects.TryGetValue(name, out path); return path; } #endregion public void CheckAll() { foreach (var item in _modelDict) { Debug.LogErrorFormat("{0} : Is dirty>{1}", item.Key, item.Value.IsDirty); } } public void UpdateClipbord(List<ModelActionEditor> editors) { _clipboard = editors; } /// <summary> /// 创建角色动作行为配置文本 /// 每个角色只能有一套配置 /// </summary> /// <returns></returns> private void Create() { ActorConfigEditor model = null; var models = CfgManager.Model.Keys; SimplePopupCreator.ShowDialog(new List<string>(models), (name) => { var config = new ActorConfig() { ModelName = name }; string path = string.Format("{0}/{1}.xml", ActionHomeConfig.Instance.ActionConfigPath, name); model = new ActorConfigEditor(path, config); model.Save(); }); } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class ActorConfig : XmlObject { /// <summary> /// 模型名称 /// <summary> public string ModelName = ""; /// <summary> /// 基础模型名称 /// <summary> public string BaseModelName = ""; /// <summary> /// 普通动作 /// <summary> public Dictionary<string, GeneralAction> GeneralActions = new Dictionary<string, GeneralAction>(); /// <summary> /// 技能动作 /// <summary> public Dictionary<string, SkillAction> SkillActions = new Dictionary<string, SkillAction>(); public override void Write(TextWriter _1) { Write(_1, "ModelName", this.ModelName); Write(_1, "BaseModelName", this.BaseModelName); Write(_1, "GeneralActions", this.GeneralActions); Write(_1, "SkillActions", this.SkillActions); } public override void Read(XmlNode _1) { foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "ModelName": this.ModelName = ReadString(_2); break; case "BaseModelName": this.BaseModelName = ReadString(_2); break; case "GeneralActions": GetChilds(_2).ForEach (_3 => this.GeneralActions.Add(ReadString(GetOnlyChild(_3, "Key")), ReadObject<XmlCfg.Skill.GeneralAction>(GetOnlyChild(_3, "Value"), "XmlCfg.Skill.GeneralAction"))); break; case "SkillActions": GetChilds(_2).ForEach (_3 => this.SkillActions.Add(ReadString(GetOnlyChild(_3, "Key")), ReadDynamicObject<XmlCfg.Skill.SkillAction>(GetOnlyChild(_3, "Value"), "XmlCfg.Skill"))); break; } } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class CastObject : XmlCfg.Skill.Controller { /// <summary> /// 是否追踪目标 /// <summary> public bool IsTraceTarget; /// <summary> /// 飞行参数ID,数据有配置表 /// <summary> public int CurveId; /// <summary> /// 是否穿透 /// <summary> public bool PassBody; /// <summary> /// 投射起始偏移 /// <summary> public XmlCfg.Vector3 Position; /// <summary> /// 投射起始旋转角度 /// <summary> public XmlCfg.Vector3 EulerAngles; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "IsTraceTarget", this.IsTraceTarget); Write(_1, "CurveId", this.CurveId); Write(_1, "PassBody", this.PassBody); Write(_1, "Position", this.Position); Write(_1, "EulerAngles", this.EulerAngles); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "IsTraceTarget": this.IsTraceTarget = ReadBool(_2); break; case "CurveId": this.CurveId = ReadInt(_2); break; case "PassBody": this.PassBody = ReadBool(_2); break; case "Position": this.Position = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; case "EulerAngles": this.EulerAngles = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; } } } } <file_sep>namespace AssetManager { using System; using UnityEngine; using System.Collections.Generic; using Sirenix.OdinInspector; using UnityEditor; using System.IO; using System.Text; [Serializable] public class ModelImportSetting : AssetOption { [ShowInInspector, ReadOnly, PropertyOrder(-1)] public override string Path { get { return base.Path; } set { base.Path = value; } } bool AddCollider = false; bool KeepQuads = false; [FoldoutGroup("导入设置")] public ModelImporterMeshCompression MeshCompress = ModelImporterMeshCompression.Off; [FoldoutGroup("导入设置")] public bool IsReadable = false; [FoldoutGroup("导入设置")] public bool OptimizeMesh = true; [FoldoutGroup("导入设置")] public bool ImportBlendShapes = false; [FoldoutGroup("导入设置")] public bool GenerateLightMapUV = false; [FoldoutGroup("导入设置")] public ModelImporterNormals ImportNormals = ModelImporterNormals.Import; [FoldoutGroup("导入设置")] public ModelImporterTangents ImportTangents = ModelImporterTangents.CalculateMikk; [FoldoutGroup("导入设置")] public bool ImportMaterials = true; [FoldoutGroup("导入设置")] public ModelImporterMaterialName MaterialName = ModelImporterMaterialName.BasedOnTextureName; [FoldoutGroup("导入设置")] public ModelImporterMaterialSearch MaterialSearch = ModelImporterMaterialSearch.RecursiveUp; [FoldoutGroup("导入设置")] public ModelImporterAnimationType AnimationType = ModelImporterAnimationType.Generic; [FoldoutGroup("导入设置")] public bool ImportAnimation = true; [Serializable] class AssetInfo { [TableColumnWidth(280), ReadOnly] public string FileName; [TableColumnWidth(90), ReadOnly] public bool IsReadable; [TableColumnWidth(90), ReadOnly] public bool OptimizeMesh; [TableColumnWidth(90), ReadOnly] public bool ImpShapes; [TableColumnWidth(90), ReadOnly] public bool LightMapUV; [TableColumnWidth(90), ReadOnly] public bool ImpMaterials; [TableColumnWidth(90), ReadOnly] public bool ImpAnimation; [TableColumnWidth(100), ReadOnly] public ModelImporterAnimationType AnimationType; [ReadOnly] public string Other; } /// <summary> /// 按照配置重新导入资源 /// </summary> public override void ReimportAsset() { base.ReimportAsset(); ClearAsset(); List<string> files = new List<string>(Directory.GetFiles(Path, "*.fbx", SearchOption.AllDirectories)); for (int i = 0; i < files.Count; i++) { string refPath = files[i].Replace(Application.dataPath, "Assets").Replace("\\", "/"); ModelImporter importer = ModelImporter.GetAtPath(refPath) as ModelImporter; ModelImporterMeshCompression meshCompress = importer.meshCompression; importer.meshCompression = MeshCompress; importer.isReadable = IsReadable; importer.optimizeMesh = OptimizeMesh; importer.importBlendShapes = ImportBlendShapes; importer.generateSecondaryUV = GenerateLightMapUV; importer.importNormals = ImportNormals; importer.importTangents = ImportTangents; importer.importMaterials = ImportMaterials; importer.materialName = MaterialName; importer.materialSearch = MaterialSearch; importer.animationType = AnimationType; importer.importAnimation = ImportAnimation; importer.addCollider = AddCollider; SerializedObject serialized = new SerializedObject(importer); var keepQuade = serialized.FindProperty("keepQuads"); keepQuade.boolValue = KeepQuads; serialized.ApplyModifiedProperties(); importer.SaveAndReimport(); EditorUtility.DisplayProgressBar("按配置导入模型", refPath, (i + 1f) / files.Count); } EditorUtility.UnloadUnusedAssetsImmediate(); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } } }<file_sep>local lower = string.lower local setmetatable = setmetatable local tonumber = tonumber local lines = io.lines local split = string.split local format= string.format local root = CSUtil.DataPath local Stream = {} Stream.__index = Stream Stream.name = "Stream" local out = '' local Split = function (line) return split(line, '▃') end function Stream.new(dataFile) local o = {} setmetatable(o, Stream) o.dataFile = dataFile o.GetLine = lines(format('%sConfig/%s', root, dataFile)) o.idx = 0 o.line = 0 return o end function Stream:Count() return #self.columns end function Stream:NextRow() local line = self.GetLine() if line == nil or #line == 0 then return false end self.columns = Split(line) self.idx = 1 self.line = self.line + 1 return true end function Stream:NextColum() if self.idx > #self.columns then local status = self:NextRow() if not status then self.hasNext = false return nil end end local result = self.columns[self.idx] out = out .. '▃' .. result self.idx = self.idx + 1 return result end function Stream:GetInt() local next = self:NextColum() return tonumber(next) end function Stream:GetLong() local next = self:NextColum() return tonumber(next) end function Stream:GetFloat() local next = self:NextColum() return tonumber(next) end function Stream:GetBool() local next = lower(self:NextColum()) if next == '0' then return false else return true end end function Stream:GetString() return self:NextColum() end function Stream:GetList(type) local result = {} local length = self:GetInt() local method = self['Get' .. type] for i = 1, length do result[i] = method(self) end return result end function Stream:GetDict(key, value) local result = {} local optKey = self['Get' .. key] local optValue = self['Get' .. value] local length = self:GetInt() for i = 1, length do result[optKey(self)] = optValue(self) end return result end function Stream:GetObject(name) local getter = self['Get' .. name] return getter(self) end return Stream <file_sep>using UnityEngine; using System.Collections; namespace Flux { [FEvent("播放器/音频音量")] public class FVolumeAudioEvent : FTweenEvent<FTweenFloat> { [SerializeField, HideInInspector] private AudioSource _source; public override string Text { get { return _source== null? "Miss" : _source.name; } set { } } protected override void ApplyProperty(float t) { if (_source == null) return; _source.volume = _tween.GetValue(t); } } } <file_sep>using UnityEngine; using System; namespace Game.Platform { public class CustomInterface : Interface { public override void Init() { } public override void Release() { } public override void OpenUrl(string url) { } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class SphereZone : XmlCfg.Skill.HitZone { /// <summary> /// 球半径 /// <summary> public float Radius; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Radius", this.Radius); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Radius": this.Radius = ReadFloat(_2); break; } } } } <file_sep>using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; public partial class ExportResource { const string EXT_SHADER = ".shader"; const string EXT_PNG = ".png"; const string EXT_TGA = ".tga"; const string EXT_MP3 = ".mp3"; const string EXT_OGG = ".ogg"; const string UI_FOLDER = "ui/"; const string SHADER_FOLDER = "shaders/"; const string DEPTEX_FOLDER = "texture/t_"; const string AUDIO_FOLDER = "audio/a_"; static BuildAssetBundleOptions options = BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.ForceRebuildAssetBundle; /// <summary> /// 平台文件目录名 /// </summary> /// <param name="target"></param> /// <returns></returns> static string GetPlatfomrPath(BuildTarget target) { string platformPath = string.Empty; switch (target) { case BuildTarget.Android: platformPath = "Dist/Android"; break; case BuildTarget.iOS: platformPath = "Dist/IOS"; break; default: { platformPath = "GamePlayer"; } break; } return platformPath; } /// <summary> /// AB包路径 /// </summary> /// <param name="target">平台</param> /// <param name="relativePath">平台内部相对路径</param> /// <returns></returns> public static string GetBundleSavePath(BuildTarget target, string relativePath) { string path; switch (target) { case BuildTarget.Android: case BuildTarget.iOS: path = string.Format("{0}/../../{1}/{2}", Application.dataPath, GetPlatfomrPath(target), relativePath); break; default: path = string.Format("{0}/../../{1}/Data/{2}", Application.dataPath, GetPlatfomrPath(target), relativePath); break; } return path; } /// <summary> /// 对应分类资源目录 /// </summary> /// <param name="target"></param> /// <returns></returns> public static string GetBundleSaveDir(BuildTarget target) { return string.Format("{0}/../../{1}/", Application.dataPath, GetPlatfomrPath(target)); } /// <summary> /// 设置主体资源AB包名及依赖资源包名;[分离依赖单独打包] /// </summary> /// <param name="assets">资源</param> /// <param name="depFormats">依赖资源格式,此格式单独打AB包</param> /// <param name="depPath">依赖存储相对路径</param> /// <param name="bPrefix">是否修正前缀</param> static void SetAssetBundleName(Dictionary<string, string> assets, string[] depFormats, string depPath) { AssetImporter importer = null; foreach (KeyValuePair<string, string> pair in assets) { string[] dependencies = AssetDatabase.GetDependencies(pair.Key); foreach (string sdep in dependencies) { string dep = sdep.ToLower(); foreach (string format in depFormats) { if (dep.EndsWith(format)) { importer = AssetImporter.GetAtPath(dep); string newName = string.Format("{0}{1}.bundle", depPath, Path.GetFileNameWithoutExtension(dep)); newName = newName.Replace(" ", ""); newName = newName.ToLower(); if (importer.assetBundleName == null || importer.assetBundleName != newName) { importer.assetBundleName = newName; } } } } importer = AssetImporter.GetAtPath(pair.Key); if (importer == null) { Debug.LogError("未发现资源: " + pair.Key); } if (importer.assetBundleName == null || importer.assetBundleName != pair.Value) { importer.assetBundleName = pair.Value; } } } /// <summary> /// 设置AB包名,无依赖资源 /// </summary> /// <param name="assets">资源</param> static void SetAssetBundleName(Dictionary<string, string> assets) { AssetImporter importer = null; foreach (KeyValuePair<string, string> pair in assets) { importer = AssetImporter.GetAtPath(pair.Key); if (importer.assetBundleName == null || importer.assetBundleName != pair.Value) { importer.assetBundleName = pair.Value; } } } /// <summary> /// 构建AB包 /// </summary> static void BuildAssetBundles(BuildTarget target) { string dir = GetBundleSaveDir(target); Directory.CreateDirectory(Path.GetDirectoryName(dir)); BuildPipeline.BuildAssetBundles(dir, options, target); string[] allNames = AssetDatabase.GetAllAssetBundleNames(); for (int i = 0; i < allNames.Length; i++) { AssetDatabase.RemoveAssetBundleName(allNames[i], true); } } /// <summary> /// 标准化路径,'\'转化'/' /// </summary> /// <param name="obj">资源对象</param> /// <returns></returns> static string StandardlizePath(UnityEngine.Object obj) { return StandardlizePath(AssetDatabase.GetAssetPath(obj)); } /// <summary> /// 标准化路径,'\'转化'/' /// </summary> /// <param name="path">资源路径</param> /// <returns></returns> public static string StandardlizePath(string path) { string pathReplace = path.Replace(@"\", @"/"); string pathLower = pathReplace.ToLower(); return pathLower; } /// <summary> /// 限定选择的资源必须在指定范围内 /// </summary> /// <param name="allassets">所有资源</param> /// <param name="selection">选择的资源</param> /// <returns></returns> static Dictionary<string, string> GetSelectedAssets(Dictionary<string, string> allassets, Object[] selection) { Dictionary<string, string> assets = new Dictionary<string, string>(); for (int i = 0; i < selection.Length; ++i) { var assetpath = AssetDatabase.GetAssetPath(selection[i]); var assetstandardlizepath = StandardlizePath(selection[i]); if (allassets.ContainsKey(assetpath)) { assets[assetpath] = allassets[assetpath]; } else if (allassets.ContainsKey(assetstandardlizepath)) { assets[assetstandardlizepath] = allassets[assetstandardlizepath]; } } return assets; } /// <summary> /// 获取目录下指定格式资源,包含子目录 /// </summary> /// <param name="srcFolder"></param> /// <param name="searchPattern"></param> /// <param name="dstFolder"></param> /// <param name="prefix"></param> /// <param name="assets"></param> static void GetAssetsRecursively(string srcFolder, string searchPattern, string dstFolder, string prefix, ref Dictionary<string, string> assets) { string searchFolder = StandardlizePath(srcFolder); if (!Directory.Exists(searchFolder)) return; string suffix = "bundle"; string srcDir = searchFolder; string[] files = Directory.GetFiles(srcDir, searchPattern); foreach (string oneFile in files) { string srcFile = StandardlizePath(oneFile); if (!File.Exists(srcFile)) continue; string dstFile; if (string.IsNullOrEmpty(prefix)) { dstFile = Path.Combine(dstFolder, string.Format("{0}.{1}", Path.GetFileNameWithoutExtension(srcFile), suffix)); } else { dstFile = Path.Combine(dstFolder, string.Format("{0}_{1}.{2}", prefix, Path.GetFileNameWithoutExtension(srcFile), suffix)); } dstFile = StandardlizePath(dstFile); assets[srcFile] = dstFile; //UnityEngine.Debug.Log("srcFile: " + srcFile + " => dstFile: " + dstFile); } string[] dirs = Directory.GetDirectories(searchFolder); foreach (string oneDir in dirs) { GetAssetsRecursively(oneDir, searchPattern, dstFolder, prefix, ref assets); } } /// <summary> /// Android平台时,图集更换材质 /// </summary> static void ReplaceDefaultMatAndShaders() { } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class DynamicHit : XmlCfg.Skill.StaticHit { /// <summary> /// 碰撞体绑定对象路径 /// <summary> public string Target = ""; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Target", this.Target); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Target": this.Target = ReadString(_2); break; } } } } <file_sep>using UnityEngine; using System.Collections.Generic; namespace Flux { public enum FContainerEnum { FContainer, FCfgContainer,//基础配置 FTimelineContainer,//时间事件 } public class FContainer : FObject { public static readonly Color DEFAULT_COLOR = new Color(0.14f, 0.14f, 0.14f, 0.7f); /// <summary> /// 容器类型,用于区别处理数据 /// </summary> [HideInInspector] public FContainerEnum ConatinerType = FContainerEnum.FContainer; [HideInInspector] public int ContainerNo = 0; public static readonly Dictionary<string, FContainerEnum> ContainerMap = new Dictionary<string, FContainerEnum>() { {"Default", FContainerEnum.FContainer}, {"基础配置", FContainerEnum.FCfgContainer}, {"时间事件", FContainerEnum.FTimelineContainer}, }; [SerializeField] [HideInInspector] private FSequence _sequence = null; [SerializeField] [HideInInspector] private Color _color; public Color Color { get { return _color; } set { _color = value; } } [SerializeField] private List<FTrack> _tracks = new List<FTrack>(); public List<FTrack> Tracks { get { return _tracks; } } public override FSequence Sequence { get { return _sequence; } } public override Transform Owner { get { return null; } } public static FContainer Create(string name, Color color) { GameObject go = new GameObject(name); FContainer container = go.AddComponent<FContainer>(); container.Color = color; container.ConatinerType = ContainerMap[name]; return container; } internal void SetSequence(FSequence sequence) { _sequence = sequence; if (_sequence) transform.parent = _sequence.Content; else transform.parent = null; } public override void Init() { foreach (FTrack track in _tracks) { track.Init(); } } public override void Stop() { foreach (FTrack track in _tracks) { track.Stop(); } } public void Resume() { foreach (FTrack track in _tracks) { track.Resume(); } } public void Pause() { foreach (FTrack track in _tracks) { track.Pause(); } } public bool IsEmpty() { foreach (FTrack track in _tracks) { if (!track.IsEmpty()) { return false; } } return true; } public void UpdateTracks(int frame, float time) { for (int i = 0; i != _tracks.Count; ++i) { if (!_tracks[i].enabled) continue; _tracks[i].UpdateEvents(frame, time); } } public void UpdateTracksEditor(int frame, float time) { for (int i = 0; i != _tracks.Count; ++i) { if (!_tracks[i].enabled) continue; _tracks[i].UpdateEventsEditor(frame, time); } } public FTrack Add<T>(FrameRange range) where T : FEvent { FTrack track = FTrack.Create<T>(); Add(track); FEvent evt = FEvent.Create<T>(range); track.Add(evt); return track; } /// @brief Adds new timeline at the end of the list. /// @param timeline New timeline. public void Add(FTrack track) { int id = _tracks.Count; _tracks.Add(track); track.SetId(id); // timeline.SetSequence( this ); track.SetContainer(this); } /// @brief Removes timeline and updates their ids. /// @param timeline CTimeline to remove. /// @note After calling this function, the ids of the timelines after this /// one in the list will have an id smaller by 1. public void Remove(FTrack track) { for (int i = 0; i != _tracks.Count; ++i) { if (_tracks[i] == track) { Remove(i); break; } } } /// @brief Removes timeline with id. /// @oaram id Id of the CTimeline to remove. /// @note After calling this function, the ids of the timelines after this /// one in the list will have an id smaller by 1. /// @warning Does not check if id is valid (i.e. between -1 & GetTimelines().Count) public void Remove(int id) { FTrack track = _tracks[id]; _tracks.RemoveAt(id); track.SetContainer(null); UpdateTrackIds(); } public void Rebuild() { _tracks.Clear(); Transform t = transform; for (int i = 0; i != t.childCount; ++i) { FTrack track = t.GetChild(i).GetComponent<FTrack>(); if (track != null) { _tracks.Add(track); track.SetContainer(this); track.Rebuild(); } } UpdateTrackIds(); } // Updates the ids of the tracks private void UpdateTrackIds() { for (int i = 0; i != _tracks.Count; ++i) _tracks[i].SetId(i); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class ActorConfig : CfgObject { /// <summary> /// 模型名称 /// <summary> public readonly string ModelName; /// <summary> /// 基础模型名称 /// <summary> public readonly string BaseModelName; /// <summary> /// 普通动作 /// <summary> public readonly Dictionary<string, GeneralAction> GeneralActions = new Dictionary<string, GeneralAction>(); /// <summary> /// 技能动作 /// <summary> public readonly Dictionary<string, SkillAction> SkillActions = new Dictionary<string, SkillAction>(); public ActorConfig(DataStream data) { this.ModelName = data.GetString(); this.BaseModelName = data.GetString(); for (int n = data.GetInt(); n-- > 0;) { string k = data.GetString(); this.GeneralActions[k] = (GeneralAction)data.GetObject(data.GetString()); } for (int n = data.GetInt(); n-- > 0;) { string k = data.GetString(); this.SkillActions[k] = (SkillAction)data.GetObject(data.GetString()); } } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public enum BindType { /// <summary> /// 无 /// <summary> None = 0, /// <summary> /// 身体 /// <summary> Body = 1, /// <summary> /// 头 /// <summary> Head = 2, /// <summary> /// 脚 /// <summary> Foot = 3, } } <file_sep>#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using System; using System.Collections.Generic; using System.Reflection; namespace XLua.CSObjectWrap { public class XLua_Gen_Initer_Register__ { static void wrapInit0(LuaEnv luaenv, ObjectTranslator translator) { translator.DelayWrapLoader(typeof(object), SystemObjectWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Object), UnityEngineObjectWrap.__Register); translator.DelayWrapLoader(typeof(UObjectExtention), UObjectExtentionWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Vector2), UnityEngineVector2Wrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Vector3), UnityEngineVector3Wrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Vector4), UnityEngineVector4Wrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Quaternion), UnityEngineQuaternionWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Color), UnityEngineColorWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Ray), UnityEngineRayWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Bounds), UnityEngineBoundsWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Ray2D), UnityEngineRay2DWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Mathf), UnityEngineMathfWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Time), UnityEngineTimeWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.GL), UnityEngineGLWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Input), UnityEngineInputWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Screen), UnityEngineScreenWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Physics), UnityEnginePhysicsWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Graphics), UnityEngineGraphicsWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Resources), UnityEngineResourcesWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Application), UnityEngineApplicationWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.SleepTimeout), UnityEngineSleepTimeoutWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Collider), UnityEngineColliderWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.BoxCollider), UnityEngineBoxColliderWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.MeshCollider), UnityEngineMeshColliderWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.SphereCollider), UnityEngineSphereColliderWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.CharacterController), UnityEngineCharacterControllerWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.CapsuleCollider), UnityEngineCapsuleColliderWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.WWW), UnityEngineWWWWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Behaviour), UnityEngineBehaviourWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.MonoBehaviour), UnityEngineMonoBehaviourWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.GameObject), UnityEngineGameObjectWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Texture), UnityEngineTextureWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Texture2D), UnityEngineTexture2DWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.AudioClip), UnityEngineAudioClipWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.AssetBundle), UnityEngineAssetBundleWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.AsyncOperation), UnityEngineAsyncOperationWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Animator), UnityEngineAnimatorWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Animation), UnityEngineAnimationWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.AnimationClip), UnityEngineAnimationClipWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.AnimationState), UnityEngineAnimationStateWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Shader), UnityEngineShaderWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Renderer), UnityEngineRendererWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.MeshRenderer), UnityEngineMeshRendererWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.TrackedReference), UnityEngineTrackedReferenceWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.SkinnedMeshRenderer), UnityEngineSkinnedMeshRendererWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.ParticleSystem), UnityEngineParticleSystemWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.QualitySettings), UnityEngineQualitySettingsWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.RenderSettings), UnityEngineRenderSettingsWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.RenderTexture), UnityEngineRenderTextureWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.LightType), UnityEngineLightTypeWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.CameraClearFlags), UnityEngineCameraClearFlagsWrap.__Register); } static void wrapInit1(LuaEnv luaenv, ObjectTranslator translator) { translator.DelayWrapLoader(typeof(UnityEngine.KeyCode), UnityEngineKeyCodeWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Space), UnityEngineSpaceWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.AnimationBlendMode), UnityEngineAnimationBlendModeWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.QueueMode), UnityEngineQueueModeWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.PlayMode), UnityEnginePlayModeWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.WrapMode), UnityEngineWrapModeWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.BlendWeights), UnityEngineBlendWeightsWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.RectTransform), UnityEngineRectTransformWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.UI.Text), UnityEngineUITextWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.UI.Image), UnityEngineUIImageWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.UI.Button), UnityEngineUIButtonWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.UI.RawImage), UnityEngineUIRawImageWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.Debug), UnityEngineDebugWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.EventSystems.EventTrigger), UnityEngineEventSystemsEventTriggerWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.EventSystems.BaseEventData), UnityEngineEventSystemsBaseEventDataWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.EventSystems.AxisEventData), UnityEngineEventSystemsAxisEventDataWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.EventSystems.PointerEventData), UnityEngineEventSystemsPointerEventDataWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.EventSystems.EventTriggerType), UnityEngineEventSystemsEventTriggerTypeWrap.__Register); translator.DelayWrapLoader(typeof(Game.Util), GameUtilWrap.__Register); translator.DelayWrapLoader(typeof(Game.AppConst), GameAppConstWrap.__Register); translator.DelayWrapLoader(typeof(Game.LuaHelper), GameLuaHelperWrap.__Register); translator.DelayWrapLoader(typeof(Game.GameManager), GameGameManagerWrap.__Register); translator.DelayWrapLoader(typeof(Game.LuaManager), GameLuaManagerWrap.__Register); translator.DelayWrapLoader(typeof(Game.ResourceManager), GameResourceManagerWrap.__Register); translator.DelayWrapLoader(typeof(Game.ResourceLoadType), GameResourceLoadTypeWrap.__Register); translator.DelayWrapLoader(typeof(Game.SoundManager), GameSoundManagerWrap.__Register); translator.DelayWrapLoader(typeof(Game.NetworkManager), GameNetworkManagerWrap.__Register); translator.DelayWrapLoader(typeof(Game.Platform.CustomInterface), GamePlatformCustomInterfaceWrap.__Register); translator.DelayWrapLoader(typeof(Game.Platform.Interface), GamePlatformInterfaceWrap.__Register); translator.DelayWrapLoader(typeof(LuaBehaviour), LuaBehaviourWrap.__Register); translator.DelayWrapLoader(typeof(XLuaTest.Pedding), XLuaTestPeddingWrap.__Register); translator.DelayWrapLoader(typeof(XLuaTest.MyStruct), XLuaTestMyStructWrap.__Register); translator.DelayWrapLoader(typeof(XLuaTest.MyEnum), XLuaTestMyEnumWrap.__Register); translator.DelayWrapLoader(typeof(XLuaTest.NoGc), XLuaTestNoGcWrap.__Register); translator.DelayWrapLoader(typeof(UnityEngine.WaitForSeconds), UnityEngineWaitForSecondsWrap.__Register); translator.DelayWrapLoader(typeof(BaseTest), BaseTestWrap.__Register); translator.DelayWrapLoader(typeof(Foo1Parent), Foo1ParentWrap.__Register); translator.DelayWrapLoader(typeof(Foo2Parent), Foo2ParentWrap.__Register); translator.DelayWrapLoader(typeof(Foo1Child), Foo1ChildWrap.__Register); translator.DelayWrapLoader(typeof(Foo2Child), Foo2ChildWrap.__Register); translator.DelayWrapLoader(typeof(Foo), FooWrap.__Register); translator.DelayWrapLoader(typeof(FooExtension), FooExtensionWrap.__Register); } static void Init(LuaEnv luaenv, ObjectTranslator translator) { wrapInit0(luaenv, translator); wrapInit1(luaenv, translator); translator.AddInterfaceBridgeCreator(typeof(InvokeLua.ICalc), InvokeLuaICalcBridge.__Create); translator.AddInterfaceBridgeCreator(typeof(XLuaTest.IExchanger), XLuaTestIExchangerBridge.__Create); } static XLua_Gen_Initer_Register__() { XLua.LuaEnv.AddIniter(Init); } } } namespace XLua { public partial class ObjectTranslator { static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ s_gen_reg_dumb_obj = new XLua.CSObjectWrap.XLua_Gen_Initer_Register__(); static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ gen_reg_dumb_obj {get{return s_gen_reg_dumb_obj;}} } internal partial class InternalGlobals { static InternalGlobals() { extensionMethodMap = new Dictionary<Type, IEnumerable<MethodInfo>>() { }; genTryArrayGetPtr = StaticLuaCallbacks.__tryArrayGet; genTryArraySetPtr = StaticLuaCallbacks.__tryArraySet; } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class PlaySound : Cfg.Skill.Timeline { /// <summary> /// 音效资源路径 /// <summary> public readonly string Path; /// <summary> /// 音量 /// <summary> public readonly float Volume; public PlaySound(DataStream data) : base(data) { this.Path = data.GetString(); this.Volume = data.GetFloat(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class Move : Cfg.Skill.Controller { /// <summary> /// 移动方式:0向目标移动 1按指定方向移动 /// <summary> public readonly int Type; /// <summary> /// 是否相对于自己移动 /// <summary> public readonly bool IsRelateSelf; /// <summary> /// 起始位置相对目标偏移 /// <summary> public Cfg.Vector3 Offset; /// <summary> /// Y轴顺时针旋转角度 /// <summary> public readonly float Angle; /// <summary> /// 位移速度m/s /// <summary> public readonly float Speed; public Move(DataStream data) : base(data) { this.Type = data.GetInt(); this.IsRelateSelf = data.GetBool(); this.Offset = new Vector3(data); this.Angle = data.GetFloat(); this.Speed = data.GetFloat(); } } } <file_sep>#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class UnityEngineTrackedReferenceWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(UnityEngine.TrackedReference); Utils.BeginObjectRegister(type, L, translator, 1, 2, 0, 0); Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__eq", __EqMeta); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Equals", _m_Equals); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetHashCode", _m_GetHashCode); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { return LuaAPI.luaL_error(L, "UnityEngine.TrackedReference does not have a constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __EqMeta(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if (translator.Assignable<UnityEngine.TrackedReference>(L, 1) && translator.Assignable<UnityEngine.TrackedReference>(L, 2)) { UnityEngine.TrackedReference leftside = (UnityEngine.TrackedReference)translator.GetObject(L, 1, typeof(UnityEngine.TrackedReference)); UnityEngine.TrackedReference rightside = (UnityEngine.TrackedReference)translator.GetObject(L, 2, typeof(UnityEngine.TrackedReference)); LuaAPI.lua_pushboolean(L, leftside == rightside); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to right hand of == operator, need UnityEngine.TrackedReference!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Equals(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.TrackedReference gen_to_be_invoked = (UnityEngine.TrackedReference)translator.FastGetCSObj(L, 1); { object _o = translator.GetObject(L, 2, typeof(object)); bool gen_ret = gen_to_be_invoked.Equals( _o ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetHashCode(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); UnityEngine.TrackedReference gen_to_be_invoked = (UnityEngine.TrackedReference)translator.FastGetCSObj(L, 1); { int gen_ret = gen_to_be_invoked.GetHashCode( ); LuaAPI.xlua_pushinteger(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } } } <file_sep>using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Reflection; using System; using Flux; namespace FluxEditor { [FEditor(typeof(FAnimationTrack))] public class FAnimationTrackEditor : FTrackEditor { protected override void OnEnable() { base.OnEnable(); } protected override void OnDestroy() { base.OnDestroy(); //SceneView.onSceneGUIDelegate -= OnSceneGUI; FAnimationTrack animTrack = (FAnimationTrack)Obj; DestroyImmediate(animTrack.AnimatorController); animTrack.AnimatorController = null; Resources.UnloadUnusedAssets(); //if (SyncWithAnimationWindow) // SyncWithAnimationWindow = false; } public override void Init(FObject obj, FEditor owner) { base.Init(obj, owner); FAnimationTrackInspector.SetAnimator((FAnimationTrack)Track); } public override void OnTrackChanged() { FAnimationTrack animTrack = (FAnimationTrack)Track; FAnimationTrackInspector.RebuildStateMachine(animTrack); FAnimationTrackInspector.SetAnimator(animTrack); } public override void Render(Rect rect, float headerWidth) { base.Render(rect, headerWidth); switch (Event.current.type) { case EventType.DragUpdated: if (rect.Contains(Event.current.mousePosition)) { int numAnimationsDragged = FAnimationEventInspector.NumAnimationsDragAndDrop(Track.Sequence.FrameRate); int frame = SequenceEditor.GetFrameForX(Event.current.mousePosition.x); DragAndDrop.visualMode = numAnimationsDragged > 0 && Track.CanAddAt(frame) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected; Event.current.Use(); } break; case EventType.DragPerform: if (rect.Contains(Event.current.mousePosition)) { AnimationClip animClip = FAnimationEventInspector.GetAnimationClipDragAndDrop(Track.Sequence.FrameRate); if (animClip && Mathf.Approximately(animClip.frameRate, Track.Sequence.FrameRate)) { int frame = SequenceEditor.GetFrameForX(Event.current.mousePosition.x); int maxLength; if (Track.CanAddAt(frame, out maxLength)) { FPlayAnimationEvent animEvt = FEvent.Create<FPlayAnimationEvent>(new FrameRange(frame, frame + Mathf.Min(maxLength, Mathf.RoundToInt(animClip.length * animClip.frameRate)))); Track.Add(animEvt); FAnimationEventInspector.SetAnimationClip(animEvt, animClip); DragAndDrop.AcceptDrag(); } } Event.current.Use(); } break; } } public override void UpdateEventsEditor(int frame, float time) { if (Track.RequiresEditorCache && !Track.HasCache && Track.CanCreateCache()) { OnToggle(true); } base.UpdateEventsEditor(frame, time); //if (_syncWithAnimationWindow) //{ // FEvent[] evts = new FEvent[2]; // int numEvts = Track.GetEventsAt(frame, evts); // if (numEvts > 0) // { // if (numEvts == 1) // { // _previousEvent = evts[0]; // } // else if (numEvts == 2) // { // if (_previousEvent != evts[0] && _previousEvent != evts[1]) // { // _previousEvent = evts[1]; // } // } // FPlayAnimationEvent animEvt = (FPlayAnimationEvent)_previousEvent; // if (animEvt._animationClip != AnimationWindowProxy.GetSelectedAnimationClip()) // { // AnimationWindowProxy.SelectAnimationClip(animEvt._animationClip); // } // AnimationWindowProxy.SetCurrentFrame(frame - animEvt.Start, time - animEvt.StartTime); // } //} } } } <file_sep>namespace CS.ActorConfig { using System; using UnityEngine; using UnityEditor; using Sirenix.Utilities; using Sirenix.Utilities.Editor; using Sirenix.OdinInspector.Editor; using System.Collections.Generic; internal class ActionWindow : OdinEditorWindow { public static void Init(ActorConfigEditor actorEditor, ModelActionEditor modelAction, bool isAddAction, Action<ModelActionEditor> result = null) { var window = GetWindow<ActionWindow>(true, "行为配置窗口", true); window.position = GUIHelper.GetEditorWindowRect().AlignCenter(400, 250); window.minSize = new Vector2(400, 250); window.maxSize = new Vector2(400, 250); window._nameStyle = SirenixGUIStyles.BoldTitleCentered; window._nameStyle.fontSize = 30; window._nameStyle.fontStyle = FontStyle.Bold; window._nameStyle.normal.textColor = Color.white; window._isAddAction = isAddAction; window._selfActorEditor = actorEditor; window._modelAction = modelAction; window._actionName = modelAction.ActionName; window._clipName = modelAction.ActionClip; window._otherModelName = modelAction.OtherModelName; window._result = result; if (!modelAction.IsFromOther) window.LoadSelfAction(); else window.LoadOtherAction(modelAction.OtherModelName); } GUIStyle _nameStyle; ActorConfigEditor _otherActorEditor; ActorConfigEditor _selfActorEditor; Action<ModelActionEditor> _result; ModelActionEditor _modelAction; string _actionName = string.Empty; string _clipName = string.Empty; string _otherModelName = string.Empty; bool _isAddAction = false; List<string> _actClipList; bool IsFromOther { get { return _modelAction.IsFromOther; } } private void LoadSelfAction() { _otherModelName = string.Empty; _otherActorEditor = null; _actClipList = _selfActorEditor.GetActionClips(); } private void LoadOtherAction(string name) { _otherModelName = name; _otherActorEditor = HomeConfig.Instance.GetActorEditor(name); _actClipList = _otherActorEditor.GetActionClips(); } protected override void OnGUI() { base.OnGUI(); if (EditorApplication.isCompiling) { Debug.Log("[行为窗口]脚本正在编译,所以自动关闭窗口!"); Close(); return; } SirenixEditorGUI.BeginBox(); { SirenixEditorGUI.BeginBoxHeader(); GUILayout.Label(_selfActorEditor.ModelName, _nameStyle); SirenixEditorGUI.EndBoxHeader(); bool isNew = _modelAction.ActState == ModelActionEditor.ActionState.New; if (!isNew) GUIHelper.PushGUIEnabled(false); _actionName = EditorGUILayout.TextField("动作行为", _actionName); if (!isNew) GUIHelper.PushGUIEnabled(true); EditorGUILayout.BeginHorizontal(); { GUILayout.Label("其他角色", SirenixGUIStyles.BoldLabel, GUILayout.Width(142)); if (GUILayout.Button(_otherModelName, EditorStyles.textField)) { var list = HomeConfig.Instance.GetAllActorList(); list.Remove(_selfActorEditor.ModelName); SimplePopupCreator.ShowDialog(list, (name) => LoadOtherAction(name)); } if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(20), GUILayout.Height(EditorGUIUtility.singleLineHeight))) { LoadSelfAction(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); { GUILayout.Label("动画文件", SirenixGUIStyles.BoldLabel, GUILayout.Width(142)); if (GUILayout.Button(_clipName, SirenixGUIStyles.Popup)) SimplePopupCreator.ShowDialog(_actClipList, (name) => _clipName = name); if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(20), GUILayout.Height(EditorGUIUtility.singleLineHeight))) _clipName = string.Empty; } EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); { if (GUILayout.Button("修改行为", GUILayout.Height(50))) { if (_isAddAction) { bool hasSame = false; if (!_modelAction.IsSkillAction) hasSame = _selfActorEditor.GeneralActions.Exists(a => a.ActionName.Equals(_actionName)); else hasSame = _selfActorEditor.SkillActions.Exists(a => a.ActionName.Equals(_actionName)); if (!hasSame) { _modelAction.ActionName = _actionName; _modelAction.ActionClip = _clipName; _modelAction.OtherModelName = _otherModelName; _selfActorEditor.SetChildAction(_modelAction); if (_result != null) _result(_modelAction); Close(); } else { EditorUtility.DisplayDialog("动作配置错误", "动作名重复,请重新配置!!!", "确定"); } } else { _modelAction.ActionName = _actionName; _modelAction.ActionClip = _clipName; _modelAction.OtherModelName = _otherModelName; if (_result != null) _result(_modelAction); Close(); } } } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndHorizontal(); } protected override void OnDestroy() { _modelAction = null; _selfActorEditor = null; _otherActorEditor = null; _result = null; _actClipList = null; } } }<file_sep>/******************************************************************** description: * 特效缓存池(对象级) * 每种特效最多实例化5个特效 * 也可以以特效池为模板克隆(EffectPool.GetEffectClone),但是返回的特效不由池管理 * 缓存池最多保留10种特效,多出的无用特效(游戏中已经没有在用的特效)删除 *********************************************************************/ using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Game { public class EffectPoolItem { public static int MaxCount = 5; public static float CacheTime = 100; public EffectPoolItem(string path,GameObject originaleffect) { this.path = path; this.originaleffect = originaleffect; this.originaleffect.SetActive(false); this.lastusetime = Time.time; GameObject.DontDestroyOnLoad(this.originaleffect); } public float lastusetime = 0; public string path; public GameObject originaleffect; ObjectPool<GameObject> effectpool = new ObjectPool<GameObject>(MaxCount, false); HashSet<GameObject> usingeffects = new HashSet<GameObject>(); public bool IsFull() { return effectpool.Count + usingeffects.Count >= MaxCount; } public bool HasEffect() { return effectpool.Count > 0 || !IsFull(); } public GameObject Clone() { var effect = Util.Copy(originaleffect); GameObject.DontDestroyOnLoad(effect); return effect; } // public GameObject Get() { if (!HasEffect()) { return null; } var effect = effectpool.Get(); if (effect == null) { effect = Clone(); } usingeffects.Add(effect); //Util.LogColor("green", "EffectPoolItem:Get " + path+Time.time); return effect; } public void Put(GameObject effect) { if (usingeffects.Contains(effect)) { effectpool.Put(effect); usingeffects.Remove(effect); lastusetime = Time.time; //Util.LogColor("white", "EffectPoolItem:Put " + path + Time.time); } } public bool IsUnused() { return usingeffects.Count == 0 && Time.time - lastusetime > CacheTime; } public void Release() { var del = effectpool.Get(); while (del != null) { Object.Destroy(del); del = effectpool.Get(); } Object.Destroy(originaleffect); //Util.LogColor("red", "EffectPoolItem:Release " + path + Time.time); } } public class EffectPool { static int MaxCount = 10; static Dictionary<string, EffectPoolItem> CachedEffect= new Dictionary<string, EffectPoolItem>(); static float _cleanupLastTime = 0; public static string GetStandardlize(string path) { return path.Replace(@"\", @"/").ToLower(); } //是否有特效缓存 public static bool HasEffectPoolItem(string path) { return CachedEffect.ContainsKey(GetStandardlize(path)); } public static EffectPoolItem GetEffectPoolItem(string path) { return CachedEffect[GetStandardlize(path)]; } public static void AddEffectPoolItem(string path, GameObject assetobj) { if (!HasEffectPoolItem(path)) { var standardlizepath = GetStandardlize(path); var effect = Util.Instantiate(assetobj, standardlizepath); EffectPoolItem item = new EffectPoolItem(standardlizepath, effect); CachedEffect[standardlizepath] = item; //Util.LogColor("cyan", "EffectPool:AddCachedEffect " + path + CachedEffect.Count); } } public static void DestroyEffectPoolItem(string path) { if (HasEffectPoolItem(path)) { var item = GetEffectPoolItem(path); item.Release(); CachedEffect.Remove(item.path); } } public static bool HasEffect(string path) { return GetEffectPoolItem(path).HasEffect(); } public static GameObject GetEffect(string path) { return GetEffectPoolItem(path).Get(); } public static void PutEffect(string path, GameObject effect) { GetEffectPoolItem(path).Put(effect); } public static GameObject GetEffectClone(string path) { return GetEffectPoolItem(path).Clone(); } public static void ReleaseAll() { foreach (var pairs in CachedEffect) { pairs.Value.Release(); } CachedEffect.Clear(); } public static void CleanupInterval() { const float interval = 30; if (Time.realtimeSinceStartup > _cleanupLastTime + interval) { CleanupNow(); } } public static void CleanupNow() { if (CachedEffect.Count > MaxCount) { var unusedeffectpools = new List<EffectPoolItem>(); foreach (var pair in CachedEffect) { if (pair.Value.IsUnused()) { unusedeffectpools.Add(pair.Value); } } unusedeffectpools.Sort((x, y) => { return x.lastusetime.CompareTo(y.lastusetime); }); for (int index = 0; index < Mathf.Min(CachedEffect.Count - MaxCount, unusedeffectpools.Count); index++) { DestroyEffectPoolItem(unusedeffectpools[index].path); } } } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg { public class Vector3 : CfgObject { /// <summary> /// /// <summary> public readonly float X; /// <summary> /// /// <summary> public readonly float Y; /// <summary> /// /// <summary> public readonly float Z; public Vector3(DataStream data) { this.X = data.GetFloat(); this.Y = data.GetFloat(); this.Z = data.GetFloat(); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using XLua; namespace Game { public class LuaManager : IManager { public static LuaManager Instance { get { if (_instance == null) _instance = new LuaManager(); return _instance; } } static LuaManager _instance; protected LuaManager() { } //lua逻辑代码目录 #if UNITY_EDITOR string LUA_DIR { get { return Util.DataPath + "../Code/Scripts"; } } #else string LUA_DIR { get { return Util.DataPath + "Scripts"; } } #endif const string _luaMain = "Main"; LuaEnv _luaEnv; public LuaEnv LuaEnv { get { return _luaEnv; } } public void Init() { _luaEnv = new LuaEnv(); _luaEnv.AddLoader(CustomLoader); LuaHelper.Init(); } public void Dispose() { if (_luaEnv != null) { try { _luaEnv.Dispose(); _luaEnv = null; _instance = null; } catch (Exception e) { Debug.LogError(string.Format("xLua exception : {0}\n {1}", e.Message, e.StackTrace)); } } } private byte[] CustomLoader(ref string filePath) { string fullPath = string.Format("{0}/{1}.lua", LUA_DIR, filePath.Replace(".", "/")); if (File.Exists(fullPath)) return File.ReadAllBytes(fullPath); return null; } public void Start() { _luaEnv.DoString(string.Format("require '{0}'", _luaMain), _luaMain); _luaEnv.DoString(string.Format("{0}.Init()", _luaMain), _luaMain); Main.Instance.Updater += _luaEnv.Global.GetInPath<UpdateFunc>(_luaMain + ".Update"); Main.Instance.LateUpdater += _luaEnv.Global.GetInPath<LateUpdateFunc>(_luaMain + ".LateUpdate"); Main.Instance.FixedUpdater += _luaEnv.Global.GetInPath<FixedUpdateFunc>(_luaMain + ".FixedUpdate"); } public void Tick() { if (_luaEnv != null && Time.frameCount % 100 == 0) { _luaEnv.GC(); _luaEnv.FullGc(); } } } } <file_sep>Shader = CS.UnityEngine.Shader Animator = CS.UnityEngine.Animator Animation = CS.UnityEngine.Animation AnimationClip = CS.UnityEngine.AnimationClip AnimationEvent = CS.UnityEngine.AnimationEvent AnimationState = CS.UnityEngine.AnimationState AudioClip = CS.UnityEngine.AudioClip AudioSource = CS.UnityEngine.AudioSource Physics = CS.UnityEngine.Physics GameObject = CS.UnityEngine.GameObject Transform = CS.UnityEngine.Transform Application = CS.UnityEngine.Application SystemInfo = CS.UnityEngine.SystemInfo Screen = CS.UnityEngine.Screen Camera = CS.UnityEngine.Camera Material = CS.UnityEngine.Material Renderer = CS.UnityEngine.Renderer WWW = CS.UnityEngine.WWW Input = CS.UnityEngine.Input KeyCode = CS.UnityEngine.KeyCode CharacterController = CS.UnityEngine.CharacterController SkinnedMeshRenderer = CS.UnityEngine.SkinnedMeshRenderer CSUtil = CS.Game.Util AppConst = CS.Game.AppConst LuaHelper = CS.Game.LuaHelper Interface = CS.Game.Platform.Interface ResMgr = CS.Game.ResourceManager.Instance SoundMgr = CS.Game.SoundManager.Instance NetworkMgr = CS.Game.NetworkManager.Instance EasyTouch = CS.HedgehogTeam.EasyTouch.EasyTouch Gesture = CS.HedgehogTeam.EasyTouch.Gesture ECTInput = CS.HedgehogTeam.EasyTouch.ECTInput local require = require require 'System.string' require 'System.table' Mathf = require "UnityEngine.Mathf" Vector3 = require "UnityEngine.Vector3" Quaternion = require "UnityEngine.Quaternion" Vector2 = require "UnityEngine.Vector2" Vector4 = require "UnityEngine.Vector4" Color = require "UnityEngine.Color" Ray = require "UnityEngine.Ray" Bounds = require "UnityEngine.Bounds" RaycastHit = require "UnityEngine.RaycastHit" Touch = require "UnityEngine.Touch" LayerMask = require "UnityEngine.LayerMask" Plane = require "UnityEngine.Plane" Time = require "UnityEngine.Time" Profiler = require 'System.profiler' Memory = require 'System.memory' require 'System.coroutine' require "Local" ----------------------------------------------------------- require 'Function' Define = require "Define" Class = require "Common.Class" Util = require "Common.Util" List = require 'Common.List' Queue = require "Common.Queue" Stack = require "Common.Stack" Event = require "Common.Event" Easing = require "Common.Easing" GameEvent = require "Common.GameEvent" <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public enum ShakeType { /// <summary> /// 水平 /// <summary> Horizontal = 0, /// <summary> /// 垂直 /// <summary> Vertical = 1, /// <summary> /// 混合 /// <summary> Mix = 2, } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class CylinderZone : Cfg.Skill.HitZone { /// <summary> /// 圆半径 /// <summary> public readonly float Radius; /// <summary> /// 圆柱高度 /// <summary> public readonly float Height; /// <summary> /// 打击区域绕y轴旋转角度(顺时针:左手定则),构成扇形 /// <summary> public readonly float Angle; public CylinderZone(DataStream data) : base(data) { this.Radius = data.GetFloat(); this.Height = data.GetFloat(); this.Angle = data.GetFloat(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class GeneralAction : CfgObject { /// <summary> /// 行为名称 /// <summary> public readonly string ActionName; /// <summary> /// 其他模型名称,用于套用其他模型动作 /// <summary> public readonly string OtherModelName; /// <summary> /// 绑定的动作名称 /// <summary> public readonly string ActionClip; /// <summary> /// 前摇动作名称 /// <summary> public readonly string PreActionFile; /// <summary> /// 后摇动作名称 /// <summary> public readonly string PostActionFile; /// <summary> /// 动作播放速率 /// <summary> public readonly float ActionSpeed; /// <summary> /// 动作循环次数 /// <summary> public readonly int LoopTimes; /// <summary> /// 时间事件列表 /// <summary> public readonly List<Timeline> Timelines = new List<Timeline>(); public GeneralAction(DataStream data) { this.ActionName = data.GetString(); this.OtherModelName = data.GetString(); this.ActionClip = data.GetString(); this.PreActionFile = data.GetString(); this.PostActionFile = data.GetString(); this.ActionSpeed = data.GetFloat(); this.LoopTimes = data.GetInt(); for (int n = data.GetInt(); n-- > 0; ) { this.Timelines.Add((Timeline)data.GetObject(data.GetString())); } } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class HitZone : XmlObject { /// <summary> /// 打击区域id /// <summary> public int Id; /// <summary> /// 打击范围的形态,0:方盒,1:圆柱,2:球 /// <summary> public XmlCfg.Skill.HitSharpType Sharp; /// <summary> /// 坐标偏移量 /// <summary> public XmlCfg.Vector3 Offset; /// <summary> /// 最大数量 /// <summary> public int MaxNum; public override void Write(TextWriter _1) { Write(_1, "Id", this.Id); Write(_1, "Sharp", (int)this.Sharp); Write(_1, "Offset", this.Offset); Write(_1, "MaxNum", this.MaxNum); } public override void Read(XmlNode _1) { foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Id": this.Id = ReadInt(_2); break; case "Sharp": this.Sharp = (XmlCfg.Skill.HitSharpType)ReadInt(_2); break; case "Offset": this.Offset = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; case "MaxNum": this.MaxNum = ReadInt(_2); break; } } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.AllType { public class SingleClass : CfgObject { /// <summary> /// Var1 /// <summary> public readonly string Var1; /// <summary> /// Var2 /// <summary> public readonly float Var2; public SingleClass(DataStream data) { this.Var1 = data.GetString(); this.Var2 = data.GetFloat(); } } } <file_sep>using System.Collections.Generic; using System.IO; using UnityEditor; public partial class ExportResource { //特效图集在Android平台需要分离A通道 //TODO static Dictionary<string, string> assetScenes = new Dictionary<string, string>(); static void GetSceneAssets() { assetScenes.Clear(); GetAssetsRecursively("Assets/Environment/Scene/", "*.unity", "scene/", "se", ref assetScenes); } static void ExportAllScenes(BuildTarget target) { GetSceneAssets(); SetAssetBundleName(assetScenes, new string[] { EXT_PNG, EXT_TGA }, DEPTEX_FOLDER); SetAssetBundleName(assetScenes, new string[] { EXT_MP3, EXT_OGG }, AUDIO_FOLDER); SetAssetBundleName(assetScenes, new string[] { EXT_SHADER }, SHADER_FOLDER); BuildAssetBundles(target); } static void ExportSelectedScenes(BuildTarget target) { UnityEngine.Object[] selection = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets); if (selection.Length > 0) { GetSceneAssets(); var assets = GetSelectedAssets(assetScenes, selection); SetAssetBundleName(assets, new string[] { EXT_PNG, EXT_TGA }, DEPTEX_FOLDER); SetAssetBundleName(assets, new string[] { EXT_MP3, EXT_OGG }, AUDIO_FOLDER); SetAssetBundleName(assets, new string[] { EXT_SHADER }, SHADER_FOLDER); BuildAssetBundles(target); } } [MenuItem("Assets/Build Selected for Windows/Scene")] static void ExportSceneForWindows() { ExportSelectedScenes(BuildTarget.StandaloneWindows); } [MenuItem("Assets/Build Selected for iOS/Scene")] static void ExportSceneForiOS() { ExportSelectedScenes(BuildTarget.iOS); } [MenuItem("Assets/Build Selected for Android/Scene")] static void ExportSceneForAndroid() { //ForAndroidSfxProcessBug(BuildTarget.Android); ExportSelectedScenes(BuildTarget.Android); } [MenuItem("Build Windows/Build Scenes for Windows")] static void ExportAllScenesForWindows() { ExportAllScenes(BuildTarget.StandaloneWindows); } [MenuItem("Build Android/Build Scenes for Android")] static void ExportAllScenesForAndroid() { //ForAndroidSfxProcessBug(BuildTarget.Android); ExportAllScenes(BuildTarget.Android); } [MenuItem("Build iOS/Build Scenes for iOS")] static void ExportAllScenesForiOS() { ExportAllScenes(BuildTarget.iOS); } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class HitZone : CfgObject { /// <summary> /// 打击区域id /// <summary> public readonly int Id; /// <summary> /// 打击范围的形态,0:方盒,1:圆柱,2:球 /// <summary> public readonly int Sharp; /// <summary> /// 坐标偏移量 /// <summary> public Cfg.Vector3 Offset; /// <summary> /// 最大数量 /// <summary> public readonly int MaxNum; public HitZone(DataStream data) { this.Id = data.GetInt(); this.Sharp = data.GetInt(); this.Offset = new Vector3(data); this.MaxNum = data.GetInt(); } } } <file_sep>namespace AssetManager { using System; using System.IO; using UnityEngine; using UnityEditor; using System.Linq; using Sirenix.OdinInspector; using System.Collections.Generic; using Sirenix.Utilities.Editor; [Serializable] public class RoleMeshCheckerInfo : CheckerInfo { [ShowInInspector, BoxGroup("限制条件"), PropertyOrder(-100)] [FolderPath(RequireValidPath = true), LabelText("角色网格目录")] public override string Path { get { return base.Path; } set { base.Path = value; } } [BoxGroup("限制条件"), Range(3, 60000)] public int LimitVerts = 2500; [BoxGroup("限制条件"), Range(1, 5)] public int LimitSubmesh = 1; [BoxGroup("限制条件"), Range(1, 5)] public int LimitSkin = 1; [BoxGroup("限制条件")] public ChannelType Channel = ChannelType.UV; [Flags] public enum ChannelType { None = 0, UV = 1 << 1, UV2 = 1 << 3, UV3 = 1 << 4, UV4 = 1 << 5, Color = 1 << 6, } class MeshInfo { public string Path; public int Verts; public int SubmeshNum; public int SkinNum; public ChannelType Channel; } [OnInspectorGUI] void OnInspectorGUI() { if (_meshInfos != null) SirenixEditorGUI.MessageBox(string.Format("异常文件数量{0}个", _meshInfos.Count), MessageType.Info); SirenixEditorGUI.BeginHorizontalToolbar(); GUILayout.Label("文件名", SirenixGUIStyles.BoldLabel, GUILayout.Width(650)); GUILayout.Label("顶点数量", SirenixGUIStyles.BoldLabel, GUILayout.Width(60)); GUILayout.Label("子网格数", SirenixGUIStyles.BoldLabel, GUILayout.Width(60)); GUILayout.Label("蒙皮数量", SirenixGUIStyles.BoldLabel, GUILayout.Width(60)); GUILayout.Label("通道", SirenixGUIStyles.BoldLabelCentered); SirenixEditorGUI.EndHorizontalToolbar(); if (_meshInfos == null) return; GUILayout.Space(-5); SirenixEditorGUI.BeginBox(); for (int i = 0; i < _meshInfos.Count; i++) { var item = _meshInfos[i]; EditorGUILayout.BeginHorizontal(); GUILayout.Label(item.Path, SirenixGUIStyles.Label, GUILayout.Width(650)); GUILayout.Label(item.Verts.ToString(), SirenixGUIStyles.LabelCentered, GUILayout.Width(50)); GUILayout.Label(item.SubmeshNum.ToString(), SirenixGUIStyles.LabelCentered, GUILayout.Width(56)); GUILayout.Label(item.SkinNum.ToString(), SirenixGUIStyles.LabelCentered, GUILayout.Width(60)); GUILayout.Label(item.Channel.ToString(), SirenixGUIStyles.LabelCentered); EditorGUILayout.EndHorizontal(); if (i + 1 != _meshInfos.Count) { GUILayout.Space(3); SirenixEditorGUI.HorizontalLineSeparator(); } } SirenixEditorGUI.EndBox(); } public RoleMeshCheckerInfo(string name) : base(name) { } List<MeshInfo> _meshInfos = new List<MeshInfo>(); public override void CheckAsset() { base.CheckAsset(); ClearAsset(); float count = 0; string[] files = Directory.GetFiles(GetAbsPath(Path), "*.fbx", SearchOption.AllDirectories); foreach (var f in files) { string path = GetUnityPath(f); EditorUtility.DisplayProgressBar("角色网格信息检查", path, ++count / files.Length); GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path); SkinnedMeshRenderer[] skins = go.GetComponentsInChildren<SkinnedMeshRenderer>(); if (skins.Length == 0) { EditorUtility.DisplayDialog("网格检查", path + " 资源无蒙皮信息!", "确定"); continue; } int verts = 0; int submeshs = 0; ChannelType channel = ChannelType.None; for (int i = 0; i < skins.Length; i++) { Mesh mesh = skins[i].sharedMesh; verts += mesh.vertexCount; submeshs += mesh.subMeshCount; if ((ChannelType.Color & Channel) == 0 && mesh.colors.Length > 0) channel |= ChannelType.Color; if ((ChannelType.UV & Channel) == 0 && mesh.uv.Length > 0) channel |= ChannelType.UV; if ((ChannelType.UV2 & Channel) == 0 && mesh.uv2.Length > 0) channel |= ChannelType.UV2; if ((ChannelType.UV3 & Channel) == 0 && mesh.uv3.Length > 0) channel |= ChannelType.UV3; if ((ChannelType.UV4 & Channel) == 0 && mesh.uv4.Length > 0) channel |= ChannelType.UV4; } int skinNum = skins.Length; bool isMultiSkin = skins.Length > 1; if (verts > LimitVerts || submeshs > LimitSubmesh || skinNum > LimitSkin || channel != ChannelType.None) { MeshInfo info = new MeshInfo(); info.Path = path; info.Verts = verts; info.SubmeshNum = submeshs; info.SkinNum = skinNum; info.Verts = verts; info.Channel = channel; _meshInfos.Add(info); } } EditorUtility.UnloadUnusedAssetsImmediate(); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } public override void ClearAsset() { base.ClearAsset(); if (_meshInfos == null) _meshInfos = new List<MeshInfo>(); _meshInfos.Clear(); } } }<file_sep>local require = require require "Global" local modules = require "Modules" local gameEvent = GameEvent local LogError = LogError local Time = Time Main = {} local function InitModule() for _, name in ipairs(modules) do local module = require(name) if module then module.Init() else LogError("module %s init fail!", name) end end end function Main.Init() InitModule() print('lua framework init successful.') end --逻辑update function Main.Update(deltaTime, unscaledDeltaTime) Time:SetDeltaTime(deltaTime, unscaledDeltaTime) gameEvent.UpdateEvent:Trigger() end function Main.LateUpdate() gameEvent.LateUpdateEvent:Trigger() end --物理update function Main.FixedUpdate(fixedDeltaTime) Time:SetFixedDelta(fixedDeltaTime) gameEvent.FixedUpdateEvent:Trigger() end -------------------------------------------------------- ---------------------- 测试 ---------------------------- function TEST() --local CfgMgr = require('Manager.CfgManager') --printt(CfgMgr.NameTable, 'NameTable') --local queue = Queue:new() --queue:Enqueue('1') --queue:Enqueue('2') --print("Queue Count:", queue:Count()) --print("Queue Dequeue:", queue:Dequeue()) --print("Queue Count:", queue:Count()) --print("Queue Dequeue:", queue:Dequeue()) --print("Queue Count:", queue:Count()) end<file_sep>local List = List local Class = Class ---@class Queue:List local Queue = Class:new(List) function Queue:Enqueue(item) self:push(item) end function Queue:Peek() return self:head() end function Queue:Dequeue() return self:shift() end function Queue:Clear() self:clear() end function Queue:Count() return self.length end function Queue:Contains(item) local node = self:find(item) return node ~= nil end function Queue:Clone(item) self:clone() end function Queue:MoveNext() return self:movenext() end function Queue:Current() return self:current() end function Queue:InitEnumerator() self:initenumerator() end function Queue:ToTable() return self:totable() end return Queue<file_sep>using System; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Xml.Serialization; using System.IO; public class XmlUtil { /// <summary> /// Xml序列化 /// </summary> public static void Serialize(string filePath, object sourceObj) { if (!string.IsNullOrEmpty(filePath) && filePath.Length != 0 && sourceObj != null) { File.Delete(filePath); Type type = sourceObj.GetType(); using (StreamWriter streamWriter = new StreamWriter(filePath)) { XmlSerializer xmlSerializer = new XmlSerializer(type); xmlSerializer.Serialize(streamWriter, sourceObj); } } } /// <summary> /// Xml反序列化 /// </summary> public static object Deserialize(string filePath, Type type) { object result = null; if (File.Exists(filePath)) { try { using (StreamReader streamReader = new StreamReader(filePath)) { result = new XmlSerializer(type).Deserialize(streamReader); } } catch (Exception e) { string txt = File.ReadAllText(filePath); if (string.IsNullOrEmpty(txt)) { File.Delete(filePath); UnityEngine.Debug.LogError(filePath + "空文件!"); } UnityEngine.Debug.LogErrorFormat("{2}\nActor Xml Exception: {0}\n{1}", e.Message, e.StackTrace, filePath); } } return result; } } <file_sep>using System.Collections.Generic; using System.IO; using UnityEditor; public partial class ExportResource { static Dictionary<string, string> assetAudios = new Dictionary<string, string>(); static void ExportSelectedAudios(BuildTarget target) { UnityEngine.Object[] selections = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets); if (selections.Length > 0) { assetAudios.Clear(); GetAssetsRecursively("Assets/audio/music", "*.mp3", "audio/", "a", ref assetAudios); GetAssetsRecursively("Assets/audio/sound", "*.ogg", "audio/", "a", ref assetAudios); var assets = GetSelectedAssets(assetAudios, selections); SetAssetBundleName(assets); BuildAssetBundles(target); } } static void ExportAllAudios(BuildTarget target) { assetAudios.Clear(); GetAssetsRecursively("Assets/audio/music", "*.mp3", "audio/", "a", ref assetAudios); GetAssetsRecursively("Assets/audio/sound", "*.ogg", "audio/", "a", ref assetAudios); SetAssetBundleName(assetAudios); BuildAssetBundles(target); } [MenuItem("Assets/Build Selected for Windows/Audio")] static void ExportAudioForWindows() { ExportSelectedAudios(BuildTarget.StandaloneWindows); } [MenuItem("Assets/Build Selected for iOS/Audio")] static void ExportAudioForiOS() { ExportSelectedAudios(BuildTarget.iOS); } [MenuItem("Assets/Build Selected for Android/Audio")] static void ExportAudioForAndroid() { ExportSelectedAudios(BuildTarget.Android); } [MenuItem("Build Windows/Build Audios for Windows")] static void ExportAllAudiosForWindows() { ExportAllAudios(BuildTarget.StandaloneWindows); } [MenuItem("Build Android/Build Audios for Android")] static void ExportAllAudiosForAndroid() { ExportAllAudios(BuildTarget.Android); } [MenuItem("Build iOS/Build Audios for iOS")] static void ExportAllAudiosForiOS() { ExportAllAudios(BuildTarget.iOS); } } <file_sep>using System.Collections.Generic; using UnityEditor; public partial class ExportResource { static Dictionary<string, string> assetCharacters = new Dictionary<string, string>(); static void GetCharacterAssets() { assetCharacters.Clear(); GetAssetsRecursively("Assets/Character", "*.prefab", "character/", "c", ref assetAvatars); } static void ExportSelectedChars(BuildTarget target) { UnityEngine.Object[] selection = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets); if (selection.Length > 0) { GetCharacterAssets(); var assets = GetSelectedAssets(assetCharacters, selection); SetAssetBundleName(assets, new string[] { ".shader" }, "shaders/"); BuildAssetBundles(target); } } static void ExportAllChars(BuildTarget target) { GetCharacterAssets(); SetAssetBundleName(assetCharacters, new string[] { ".shader" }, "shaders/"); BuildAssetBundles(target); } [MenuItem("Assets/Build Selected for Windows/Character")] static void ExportSelectCharacterForWindows() { ExportSelectedChars(BuildTarget.StandaloneWindows); } [MenuItem("Assets/Build Selected for Android/Character")] static void ExportSelectCharacterForAndroid() { //ForAndroidSfxProcessBug(BuildTarget.Android); ExportSelectedChars(BuildTarget.Android); } [MenuItem("Assets/Build Selected for iOS/Character")] static void ExportSelectCharacterForiOS() { ExportSelectedChars(BuildTarget.iOS); } [MenuItem("Build Windows/Build Characters for Windows")] static void ExportAllCharactersForWindows() { ExportAllChars(BuildTarget.StandaloneWindows); } [MenuItem("Build Android/Build Characters for Android")] static void ExportAllCharactersForAndroid() { //ForAndroidSfxProcessBug(BuildTarget.Android); ExportAllChars(BuildTarget.Android); } [MenuItem("Build iOS/Build Characters for iOS")] static void ExportAllCharactersForiOS() { ExportAllChars(BuildTarget.iOS); } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public enum HitSharpType { /// <summary> /// 立方体 /// <summary> Cube = 0, /// <summary> /// 球 /// <summary> Sphere = 1, /// <summary> /// 圆柱形 /// <summary> Cylinder = 2, } } <file_sep>using UnityEngine; using System.Collections.Generic; using UnityEditor; namespace Flux { /** * @brief Runtime Utility class for Flux */ public class FUtility { public const int FLUX_VERSION = 210; public const string ResourceName = "-----Resources-----"; public static bool IsAnimationEditable(AnimationClip clip) { //return clip == null || ( ((clip.hideFlags & HideFlags.NotEditable) == 0) && !clip.isLooping); return false; } public static void ResizeAnimationCurve(AnimationCurve curve, float newLength) { float frameRate = 60; float oldLength = curve.length == 0 ? 0 : curve.keys[curve.length - 1].time; // float newLength = newLength; if (oldLength == 0) { // handle no curve curve.AddKey(0, 1); curve.AddKey(newLength, 1); return; } float ratio = newLength / oldLength; float inverseRatio = 1f / ratio; int start = 0; int limit = curve.length; int increment = 1; if (ratio > 1) { start = limit - 1; limit = -1; increment = -1; } for (int i = start; i != limit; i += increment) { Keyframe newKeyframe = new Keyframe(Mathf.RoundToInt(curve.keys[i].time * ratio * frameRate) / frameRate, curve.keys[i].value, curve.keys[i].inTangent * inverseRatio, curve.keys[i].outTangent * inverseRatio); newKeyframe.tangentMode = curve.keys[i].tangentMode; curve.MoveKey(i, newKeyframe); } } /// <summary> /// 一般在激活状态下使用 /// 资源路径均采用相对路径来处理. /// 保证场景资源与项目资源相对路径一致. /// </summary> public static GameObject FindGameObject(string path) { GameObject resources = GameObject.Find(ResourceName); if (resources == null) resources = new GameObject(ResourceName); GameObject go = GameObject.Find(path);//这里的对象可以是任意节点下的对象 if (go == null) { go = AssetDatabase.LoadAssetAtPath<GameObject>(path); if (go == null) { Debug.LogError("资源不存在" + path); return null; } go.transform.parent = resources.transform; go.transform.localPosition = Vector3.zero; go.transform.localEulerAngles = Vector3.zero; } return go; } } } <file_sep>using System; using System.IO; using System.Text; using System.Collections.Generic; namespace Cfg { public class CfgManager { /// <summary> /// 配置文件文件夹路径 /// <summary> public static string ConfigDir; public static readonly Dictionary<int, Cfg.AllType.AllClass> AllClass = new Dictionary<int, Cfg.AllType.AllClass>(); public static readonly Dictionary<string, Cfg.Character.Model> Model = new Dictionary<string, Cfg.Character.Model>(); public static readonly Dictionary<string, Cfg.Skill.ActorConfig> ActorConfig = new Dictionary<string, Cfg.Skill.ActorConfig>(); private static int _row; /// <summary> /// constructor参数为指定类型的构造函数 /// <summary> public static List<T> Load<T>(string path, Func<DataStream, T> constructor) { if (!File.Exists(path)) { UnityEngine.Debug.LogError(path + "配置路径不存在"); return new List<T>(); } DataStream data = new DataStream(path, Encoding.UTF8); List<T> list = new List<T>(); for (int i = 0; i < data.Count; i++) { _row = i; list.Add(constructor(data)); } return list; } public static void LoadAll() { string path = "Data Path Empty"; try { path = ConfigDir + "AllType/AllClass.data"; var allclasss = Load(path, (d) => new AllType.AllClass(d)); allclasss.ForEach(v => AllClass.Add(v.ID, v)); path = ConfigDir + "Character/Model.data"; var models = Load(path, (d) => new Character.Model(d)); models.ForEach(v => Model.Add(v.Name, v)); path = ConfigDir + "Skill/ActorConfig.data"; var actorconfigs = Load(path, (d) => new Skill.ActorConfig(d)); actorconfigs.ForEach(v => ActorConfig.Add(v.ModelName, v)); } catch (Exception e) { UnityEngine.Debug.LogErrorFormat("{0}[r{3}]\n{1}\n{2}", path, e.Message, e.StackTrace, _row); } } public static void Clear() { AllClass.Clear(); Model.Clear(); ActorConfig.Clear(); } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class ShakeScreen : XmlCfg.Skill.Timeline { /// <summary> /// 震屏方式:0水平 1垂直 2混合 /// <summary> public XmlCfg.Skill.ShakeType Type; /// <summary> /// 每秒震动的次数 /// <summary> public int Frequency; /// <summary> /// 初始频率维持时间 /// <summary> public float FrequencyDuration; /// <summary> /// 频率衰减 /// <summary> public float FrequencyAtten; /// <summary> /// 单次振幅 /// <summary> public float Amplitude; /// <summary> /// 单次震动的衰减幅度 /// <summary> public float AmplitudeAtten; /// <summary> /// 最小完整影响范围 /// <summary> public float MinRange; /// <summary> /// 最大影响范围 /// <summary> public float MaxRange; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Type", (int)this.Type); Write(_1, "Frequency", this.Frequency); Write(_1, "FrequencyDuration", this.FrequencyDuration); Write(_1, "FrequencyAtten", this.FrequencyAtten); Write(_1, "Amplitude", this.Amplitude); Write(_1, "AmplitudeAtten", this.AmplitudeAtten); Write(_1, "MinRange", this.MinRange); Write(_1, "MaxRange", this.MaxRange); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Type": this.Type = (XmlCfg.Skill.ShakeType)ReadInt(_2); break; case "Frequency": this.Frequency = ReadInt(_2); break; case "FrequencyDuration": this.FrequencyDuration = ReadFloat(_2); break; case "FrequencyAtten": this.FrequencyAtten = ReadFloat(_2); break; case "Amplitude": this.Amplitude = ReadFloat(_2); break; case "AmplitudeAtten": this.AmplitudeAtten = ReadFloat(_2); break; case "MinRange": this.MinRange = ReadFloat(_2); break; case "MaxRange": this.MaxRange = ReadFloat(_2); break; } } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public enum EffectAlignType { None = 0, LeftTop = 1, Left = 2, LeftBottom = 3, Top = 4, Center = 5, Bottom = 6, RightTop = 7, Right = 8, RightBottom = 9, } } <file_sep>using UnityEngine; using System.Collections; [ExecuteInEditMode] public class SelfRange : MonoBehaviour { public float BodyRadius = 0; public float BodyHeight = 0; public float Scale = 1; public Transform CharacterTransform; public Animator Animator; public MeshCollider mc = null; public float HitTime = -1; private Renderer _renderer; void Start () { _renderer = GetComponent<Renderer>(); mc = GetComponent<MeshCollider>(); if (mc == null) { mc = gameObject.AddComponent<MeshCollider>(); mc.convex = true; mc.isTrigger = true; Rigidbody rb = gameObject.AddComponent<Rigidbody>(); rb.useGravity = false; rb.isKinematic = true; } CharacterTransform = transform.parent; var scale = Scale == 0 ? 1 : Scale; transform.localScale = new Vector3(BodyRadius * 2/ scale, BodyHeight/ scale, BodyRadius * 2/ scale); transform.position = new Vector3(CharacterTransform.position.x, CharacterTransform.position.y + BodyHeight / 2, CharacterTransform.position.z); Animator = CharacterTransform.GetComponent<Animator>(); SetColor(Color.yellow); } public void SetRangeActive(bool state) { _renderer.enabled = state; } public void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "WeaponCollider") { //CinemaDirector.RangeAttack ra = other.gameObject.GetComponent<CinemaDirector.RangeAttack>(); //if (ra != null) //{ // if (!ra.Attacked(gameObject)) // { // ra.AddBeAttacker(gameObject); // Debug.Log(string.Format("OnTriggerEnter ~~~~~~~~~~~~~~~{0} is be attack!", other.gameObject.name)); // if (Animator != null) // { // Animator.Play("hit"); // } // SetColor(Color.red); // BeAttackEffectManager.Instance.Add(ra.m_BeAttackEffectItem); // HitTime = Time.time; // } //} } } //public void OnTriggerExit(Collider other) //{ // if (other.gameObject.tag == "WeaponCollider") // { // Debug.Log(string.Format("OnTriggerExit ~~~~~~~~~~~~~~~{0}!", other.gameObject.name)); // SetColor(Color.yellow); // } //} public void SetColor(Color color) { //Debug.Log("SetColor" + color); color.a = 0.3f; //gameObject.renderer.material.color = color; if (gameObject.GetComponent<Renderer>().sharedMaterial.HasProperty("_Color")) { gameObject.GetComponent<Renderer>().sharedMaterial.SetColor("_Color", color); } } } <file_sep>local Stream = require("Cfg.DataStruct") local cfgs = {} for _, s in ipairs({ { name = 'AllClass', method = 'GetCfgAllTypeAllClass', index = 'ID', output = 'AllType/AllClass.data' }, { name = 'Model', method = 'GetCfgCharacterModel', index = 'Name', output = 'Character/Model.data' }, { name = 'ActorConfig', method = 'GetCfgSkillActorConfig', index = 'ModelName', output = 'Skill/ActorConfig.data' }, }) do local data = Stream.new(s.output) local cfg = {} while data:NextRow() do local value = data[s.method](data) local key = value[s.index] cfg[key] = value end cfgs[s.name] = cfg end return cfgs <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; public partial class ExportResource { //需要角色动作配置器 //依据配置器来决定需要打包哪些Clip static Dictionary<string, string> assetAnimationClips = new Dictionary<string, string>(); //static void AddAssetAnimationClip(SkillConfig.ActionHost host, ModelActionBase action, string animname) //{ // var clippath = ActionSettings.GetClipPath(host, action, animname); // if (!clippath.IsNullOrEmpty() && !assetAnimationClips.ContainsKey(clippath)) // { // assetAnimationClips[clippath] = ActionSettings.GetAnimationClipBundleName(host, action, animname); // } //} //static void GetAnimationClipAssets() //{ // EditorUtility.DisplayProgressBar("Init Animator Config", "Please wait ...", 0.3f); // ActionSettings.ReLoadAll(); // EditorUtility.DisplayProgressBar("Init Animator Config", "Please wait ...", 0.7f); // assetAnimationClips.Clear(); // foreach (var host in ActionSettings.AllHosts) // { // if (host.Model.modeltype != cfg.character.ModelType.Base && // host.Model.modeltype != cfg.character.ModelType.Template) // { // var allactions = host.AllActions; // foreach (var action in allactions) // { // AddAssetAnimationClip(host, action, action.foreactionfile); // AddAssetAnimationClip(host, action, action.actionfile); // AddAssetAnimationClip(host, action, action.succactionfile); // } // } // } // EditorUtility.DisplayProgressBar("Init Animator Config", "Please wait ...", 1f); //} static void ExportAllAnimationClips(BuildTarget target) { //GetAnimationClipAssets(); SetAssetBundleName(assetAnimationClips); BuildAssetBundles(target); } static void ExportSelectedAnimationClips(BuildTarget target) { UnityEngine.Object[] selection = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets); if (selection.Length > 0) { //GetAnimationClipAssets(); var assets = GetSelectedAssets(assetAnimationClips, selection); SetAssetBundleName(assets); BuildAssetBundles(target); } } [MenuItem("Assets/Build Selected for Windows/AnimationClip")] static void ExportSelectAnimationClipForWindows() { ExportSelectedAnimationClips(BuildTarget.StandaloneWindows); } [MenuItem("Assets/Build Selected for Android/AnimationClip")] static void ExportSelectAnimationClipForAndroid() { ExportSelectedAnimationClips(BuildTarget.Android); } [MenuItem("Assets/Build Selected for iOS/AnimationClip")] static void ExportSelectAnimationClipForiOS() { ExportSelectedAnimationClips(BuildTarget.iOS); } [MenuItem("Build Windows/Build AnimationClips for Windows")] static void ExportAllAnimationClipsForWindows() { ExportAllAnimationClips(BuildTarget.StandaloneWindows); } [MenuItem("Build Android/Build AnimationClips for Android")] static void ExportAllAnimationClipsForAndroid() { ExportAllAnimationClips(BuildTarget.Android); } [MenuItem("Build iOS/Build AnimationClips for iOS")] static void ExportAllAnimationClipsForiOS() { ExportAllAnimationClips(BuildTarget.iOS); } } <file_sep>/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using XLua; using System; using System.Linq; using UnityEngine; using System.Reflection; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; using Game; public static class ExportConfig { [LuaCallCSharp] public static List<Type> LuaCallCSharp = new List<Type>() { typeof(Action), typeof(Action<int>), typeof(Action<string>), typeof(Predicate<int>), typeof(Comparison<int>), typeof(Func<int, int>), typeof(System.Object), typeof(UnityEngine.Object), typeof(UObjectExtention), typeof(Vector2), typeof(Vector3), typeof(Vector4), typeof(Quaternion), typeof(Color), typeof(Ray), typeof(Bounds), typeof(Ray2D), typeof(Mathf), typeof(Time), typeof(GL), typeof(Input), typeof(Screen), typeof(Physics), typeof(Graphics), typeof(Resources), typeof(Application), typeof(SleepTimeout), typeof(Collider), typeof(BoxCollider), typeof(MeshCollider), typeof(SphereCollider), typeof(CharacterController), typeof(CapsuleCollider), typeof(WWW), typeof(Behaviour), typeof(MonoBehaviour), typeof(GameObject), typeof(Texture), typeof(Texture2D), typeof(AudioClip), typeof(AssetBundle), typeof(AsyncOperation), typeof(Animator), typeof(Animation), typeof(AnimationClip), typeof(AnimationState), typeof(Shader), typeof(Renderer), typeof(MeshRenderer), typeof(TrackedReference), typeof(SkinnedMeshRenderer), typeof(ParticleSystem), typeof(QualitySettings), typeof(RenderSettings), typeof(RenderTexture), typeof(LightType), typeof(CameraClearFlags), typeof(KeyCode), typeof(Space), typeof(AnimationBlendMode), typeof(QueueMode), typeof(PlayMode), typeof(WrapMode), typeof(BlendWeights), typeof(RectTransform), typeof(Text), typeof(Image), typeof(Button), typeof(RawImage), typeof(UnityEngine.Debug), typeof(EventTrigger), typeof(BaseEventData), typeof(AxisEventData), typeof(PointerEventData), typeof(EventTriggerType), typeof(UnityEngine.Events.UnityAction), typeof(Util), typeof(AppConst), typeof(LuaHelper), typeof(GameManager), typeof(LuaManager), typeof(ResourceManager), typeof(ResourceLoadType), typeof(SoundManager), typeof(NetworkManager), typeof(Game.Platform.CustomInterface), typeof(Game.Platform.Interface), }; //自动把LuaCallCSharp涉及到的delegate加到CSharpCallLua列表,后续可以直接用lua函数做callback [CSharpCallLua] public static List<Type> CSharpCallLua { get { var lua_call_csharp = LuaCallCSharp; var delegate_types = new List<Type>(); var flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly; foreach (var field in (from type in lua_call_csharp select type).SelectMany(type => type.GetFields(flag))) { if (typeof(Delegate).IsAssignableFrom(field.FieldType)) { delegate_types.Add(field.FieldType); } } foreach (var method in (from type in lua_call_csharp select type).SelectMany(type => type.GetMethods(flag))) { if (typeof(Delegate).IsAssignableFrom(method.ReturnType)) { delegate_types.Add(method.ReturnType); } foreach (var param in method.GetParameters()) { var paramType = param.ParameterType.IsByRef ? param.ParameterType.GetElementType() : param.ParameterType; if (typeof(Delegate).IsAssignableFrom(paramType)) { delegate_types.Add(paramType); } } } return delegate_types.Distinct().ToList(); } } //黑名单 [BlackList] public static List<List<string>> BlackList = new List<List<string>>() { new List<string>(){"System.Xml.XmlNodeList", "ItemOf"}, new List<string>(){"UnityEngine.WWW", "movie"}, #if UNITY_WEBGL new List<string>(){"UnityEngine.WWW", "threadPriority"}, #endif new List<string>(){"UnityEngine.Texture2D", "alphaIsTransparency"}, new List<string>(){"UnityEngine.Security", "GetChainOfTrustValue"}, new List<string>(){"UnityEngine.CanvasRenderer", "onRequestRebuild"}, new List<string>(){"UnityEngine.Light", "areaSize"}, new List<string>(){"UnityEngine.Light", "lightmapBakeType"}, new List<string>(){"UnityEngine.WWW", "MovieTexture"}, new List<string>(){"UnityEngine.WWW", "GetMovieTexture"}, new List<string>(){"UnityEngine.AnimatorOverrideController", "PerformOverrideClipListCleanup"}, #if !UNITY_WEBPLAYER new List<string>(){"UnityEngine.Application", "ExternalEval"}, #endif new List<string>(){"UnityEngine.GameObject", "networkView"}, //4.6.2 not support new List<string>(){"UnityEngine.Component", "networkView"}, //4.6.2 not support new List<string>(){"System.IO.FileInfo", "GetAccessControl", "System.Security.AccessControl.AccessControlSections"}, new List<string>(){"System.IO.FileInfo", "SetAccessControl", "System.Security.AccessControl.FileSecurity"}, new List<string>(){"System.IO.DirectoryInfo", "GetAccessControl", "System.Security.AccessControl.AccessControlSections"}, new List<string>(){"System.IO.DirectoryInfo", "SetAccessControl", "System.Security.AccessControl.DirectorySecurity"}, new List<string>(){"System.IO.DirectoryInfo", "CreateSubdirectory", "System.String", "System.Security.AccessControl.DirectorySecurity"}, new List<string>(){"System.IO.DirectoryInfo", "Create", "System.Security.AccessControl.DirectorySecurity"}, new List<string>(){"UnityEngine.MonoBehaviour", "runInEditMode"}, }; } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class GeneralAction : XmlObject { /// <summary> /// 行为名称 /// <summary> public string ActionName = ""; /// <summary> /// 其他模型名称,用于套用其他模型动作 /// <summary> public string OtherModelName = ""; /// <summary> /// 绑定的动作名称 /// <summary> public string ActionClip = ""; /// <summary> /// 前摇动作名称 /// <summary> public string PreActionFile = ""; /// <summary> /// 后摇动作名称 /// <summary> public string PostActionFile = ""; /// <summary> /// 动作播放速率 /// <summary> public float ActionSpeed; /// <summary> /// 动作循环次数 /// <summary> public int LoopTimes; /// <summary> /// 时间事件列表 /// <summary> public List<Timeline> Timelines = new List<Timeline>(); public override void Write(TextWriter _1) { Write(_1, "ActionName", this.ActionName); Write(_1, "OtherModelName", this.OtherModelName); Write(_1, "ActionClip", this.ActionClip); Write(_1, "PreActionFile", this.PreActionFile); Write(_1, "PostActionFile", this.PostActionFile); Write(_1, "ActionSpeed", this.ActionSpeed); Write(_1, "LoopTimes", this.LoopTimes); Write(_1, "Timelines", this.Timelines); } public override void Read(XmlNode _1) { foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "ActionName": this.ActionName = ReadString(_2); break; case "OtherModelName": this.OtherModelName = ReadString(_2); break; case "ActionClip": this.ActionClip = ReadString(_2); break; case "PreActionFile": this.PreActionFile = ReadString(_2); break; case "PostActionFile": this.PostActionFile = ReadString(_2); break; case "ActionSpeed": this.ActionSpeed = ReadFloat(_2); break; case "LoopTimes": this.LoopTimes = ReadInt(_2); break; case "Timelines": GetChilds(_2).ForEach (_3 => this.Timelines.Add(ReadObject<XmlCfg.Skill.Timeline>(_3, "XmlCfg.Skill.Timeline"))); break; } } } } <file_sep>using System.Collections.Generic; using UnityEngine; namespace Game { public class ObjectPool<T> where T : class, new() { private int maxNum = 5; private bool createWhenIsFull = true; private readonly Queue<T> objects = new Queue<T>(); public int Count { get { return objects == null ? 0 : objects.Count; } } public bool IsFull { get { return objects.Count >= maxNum; } } public ObjectPool() { Queue<T> queue = new Queue<T>(maxNum); createWhenIsFull = true; } public ObjectPool(int maxNum, bool createWhenIsFull = true) { Queue<T> queue = new Queue<T>(maxNum); this.maxNum = maxNum; this.createWhenIsFull = createWhenIsFull; } public T Get() { if (objects.Count > 0) { T item = objects.Dequeue(); if (item != null) return item; } if (createWhenIsFull) { return new T(); } return null; } public void Put(T item) { if (item == null) { Debug.LogError("Trying to release null to pool"); return; } if (objects.Count > 0 && ReferenceEquals(objects.Peek(), item)) Debug.LogError("Internal error. Trying to destroy object that is already released to pool."); objects.Enqueue(item); if (objects.Count > maxNum) Debug.LogWarningFormat("Warning! Class {0}'s pool is full.", typeof(T).ToString()); } } } <file_sep>using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace FluxEditor { [CustomEditor(typeof(FSettings))] public class FSettingsInspector : Editor { private FSettings _fluxSettings = null; private Texture2D _plusTexture = null; private Texture2D _minusTexture = null; private const string EVENT_COLOR_MSG = "The name you associate with the color needs to be the full " + "path of the event type, i.e. Namespace.EventType, e.g. Flux.FPlayAnimationEvent"; private const string CONTAINER_COLOR_MSG = "Default containers can be added by right clicking the add " + "container button in the Flux editor window."; void OnEnable() { _fluxSettings = (FSettings)target; _plusTexture = FUtility.GetFluxTexture("Plus.png"); _minusTexture = FUtility.GetFluxTexture("Minus.png"); } public override void OnInspectorGUI() { GUIStyle centeredLabel = new GUIStyle(EditorStyles.largeLabel); centeredLabel.alignment = TextAnchor.MiddleCenter; GUILayout.Label("Flux Color Settings", centeredLabel); EditorGUI.BeginChangeCheck(); RenderColorList("Event Colors", _fluxSettings.EventColors, "<Flux.EventType>", FGUI.GetEventColor(), EVENT_COLOR_MSG); GUILayout.Space(10); RenderColorList("Default Containers", _fluxSettings.DefaultContainers, "<Container Name>", Flux.FContainer.DEFAULT_COLOR, CONTAINER_COLOR_MSG); foreach (var item in _fluxSettings.ContainerType) { GUILayout.Space(10); RenderContainerList(item._name, item._list); } if (EditorGUI.EndChangeCheck()) { RebuildSettingsCache(); } } private void RenderColorList(string title, List<FColorSetting> colors, string defaultName, Color defaultColor, string helpStr) { EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginVertical("box"); EditorGUILayout.BeginHorizontal(); GUIContent label = new GUIContent(title, helpStr); GUILayout.Label(label); if (GUILayout.Button(_plusTexture, GUILayout.Width(40), GUILayout.Height(16))) colors.Add(new FColorSetting(defaultName, defaultColor)); EditorGUILayout.EndHorizontal(); for (int i = 0; i != colors.Count; ++i) { EditorGUILayout.BeginHorizontal(); colors[i]._str = EditorGUILayout.TextField(colors[i]._str); colors[i]._color = EditorGUILayout.ColorField(colors[i]._color); if (GUILayout.Button(_minusTexture, GUILayout.Width(40), GUILayout.Height(16))) { colors.RemoveAt(i); RebuildSettingsCache(); EditorGUIUtility.ExitGUI(); } EditorGUILayout.EndHorizontal(); } // EditorGUILayout.HelpBox( helpStr, MessageType.Info ); EditorGUILayout.EndVertical(); if (EditorGUI.EndChangeCheck()) EditorUtility.SetDirty(_fluxSettings); } private void RenderContainerList(string title, List<string> tracks) { EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginVertical("box"); EditorGUILayout.BeginHorizontal(); GUIContent label = new GUIContent(title); GUILayout.Label(label); if (GUILayout.Button(_plusTexture, GUILayout.Width(40), GUILayout.Height(16))) tracks.Add("Flux.FEvent"); EditorGUILayout.EndHorizontal(); for (int i = 0; i != tracks.Count; ++i) { EditorGUILayout.BeginHorizontal(); tracks[i] = EditorGUILayout.TextField(tracks[i]); if (GUILayout.Button(_minusTexture, GUILayout.Width(40), GUILayout.Height(16))) { tracks.RemoveAt(i); RebuildSettingsCache(); EditorGUIUtility.ExitGUI(); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndVertical(); if (EditorGUI.EndChangeCheck()) EditorUtility.SetDirty(_fluxSettings); } private void RebuildSettingsCache() { _fluxSettings.Init(); if (FSequenceEditorWindow.instance != null) FSequenceEditorWindow.instance.Repaint(); } } } <file_sep>namespace AssetManager { using System; using UnityEngine; using System.Collections; using Sirenix.Utilities; using Sirenix.OdinInspector; using System.Collections.Generic; using System.IO; using UnityEditor; using Sirenix.Serialization; using Sirenix.OdinInspector.Editor; //ScriptableObject [GlobalConfig("Editor/AssetManager/Config", UseAsset = true)] public class ImporterConfig : GlobalConfig<ImporterConfig> { [BoxGroup("路径配置组"), ListDrawerSettings(IsReadOnly = true)] public List<TextureImpConfig> TextureConfigs = new List<TextureImpConfig>(); [BoxGroup("路径配置组"), ListDrawerSettings(IsReadOnly = true)] public List<ModelImpConfig> ModelConfigs = new List<ModelImpConfig>(); [BoxGroup("路径配置组"), ListDrawerSettings(IsReadOnly = true)] public List<AudioClipImpConfig> AudioClipConfigs = new List<AudioClipImpConfig>(); [Button("Clear Invalid Path", ButtonSizes.Large)] public void ClearInvalidPath() { TextureConfigs = InvalidPath(TextureConfigs); ModelConfigs = InvalidPath(ModelConfigs); AudioClipConfigs = InvalidPath(AudioClipConfigs); } [Button("Clear All", ButtonSizes.Large)] private void ClearAll() { TextureConfigs.Clear(); ModelConfigs.Clear(); AudioClipConfigs.Clear(); } private List<T> InvalidPath<T>(List<T> list) where T : AssetImpConfig { var newList = new List<T>(); for (int i = 0; i < list.Count; i++) { if (list[i] == null) continue; string path = list[i].GetAbsPath(); if (string.IsNullOrEmpty(list[i].FolderPath) || !Directory.Exists(path)) continue; newList.Add(list[i]); } return newList; } private void LoadConfig<T>(OdinMenuTree tree, AssetImpConfig cfg, ref List<T> setting, string tabName) where T : AssetOption, new() { if (!Directory.Exists(cfg.GetAbsPath())) return; UpdateConfig<T>(cfg, ref setting); for (int i = 0; i < setting.Count; i++) { var imp = setting[i] as T; tree.AddObjectAtPath(string.Format("{0}/{1}", tabName, imp.Name), imp).SortMenuItemsByName(); EditorUtility.DisplayProgressBar(tabName, setting[i].Path, (i + 1f) / setting.Count); } EditorUtility.ClearProgressBar(); } private void UpdateConfig<T>(AssetImpConfig cfg, ref List<T> Setting) where T : AssetOption, new() { string absFolderPath = cfg.GetAbsPath(); string[] dirs = null; if (cfg.FlattenSubFolder) {//多项 SearchOption option = cfg.IncludeSubFolder ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; dirs = Directory.GetDirectories(absFolderPath, "*", option); List<T> newImports = new List<T>(); if (dirs.Length == 0) { string path = AssetOption.GetUnityPath(absFolderPath); T newImp = new T(); newImp.Path = path; newImports.Add(newImp); } else for (int i = 0; i < dirs.Length; i++) { string path = AssetOption.GetUnityPath(dirs[i]); T oldImp = Setting.Find(imp => imp.Path.Equals(path)) as T; if (oldImp != null) { newImports.Add(oldImp); } else { T newImp = new T(); newImp.Path = path; newImports.Add(newImp); } } Setting = newImports; } else { string path = AssetOption.GetUnityPath(absFolderPath); T impSet = Setting.Find(imp => imp.Path.Equals(path)) as T; if (impSet == null) { impSet = new T(); impSet.Path = path; } Setting.Clear(); Setting.Add(impSet); } } //--资源配数据加载 public void LoadTexture(OdinMenuTree tree, string tabName) { for (int i = 0; i < TextureConfigs.Count; i++) { if (TextureConfigs[i] == null) continue; LoadConfig(tree, TextureConfigs[i], ref TextureConfigs[i].Setting, tabName); } } public void LoadModel(OdinMenuTree tree, string tabName) { for (int i = 0; i < ModelConfigs.Count; i++) { if (ModelConfigs[i] == null) continue; LoadConfig(tree, ModelConfigs[i], ref ModelConfigs[i].Setting, tabName); } } public void LoadAudioClip(OdinMenuTree tree, string tabName) { for (int i = 0; i < AudioClipConfigs.Count; i++) { if (AudioClipConfigs[i] == null) continue; LoadConfig(tree, AudioClipConfigs[i], ref AudioClipConfigs[i].Setting, tabName); } } } class AssetImpCfgOverview<T> where T : AssetImpConfig, new() { [ListDrawerSettings(ShowItemCount = true), LabelText("配置列表"), OnValueChanged("OnValueChanged")] public List<AssetImpConfig> Configs; private List<T> _configs; public AssetImpCfgOverview(List<T> configs) { Configs = new List<AssetImpConfig>(); configs.ForEach(cfg => Configs.Add(cfg)); _configs = configs; } private void OnValueChanged() { _configs.Clear(); Configs.ForEach(cfg => { T item = new T(); item.FolderPath = cfg.FolderPath; item.IncludeSubFolder = cfg.IncludeSubFolder; item.FlattenSubFolder = cfg.FlattenSubFolder; _configs.Add(item); }); AssetImporter.Instance.RefreshTree(); } } [Serializable] public class AssetImpConfig { [HorizontalGroup("Spilt"), HideLabel, OnValueChanged("OnValueChanged")] [FolderPath(ParentFolder = "Assets", RequireValidPath = true)] public string FolderPath; [HorizontalGroup("Spilt"), LabelWidth(120), ToggleLeft, LabelText("包含子目录"), OnValueChanged("OnValueChanged")] public bool IncludeSubFolder = false; [HorizontalGroup("Spilt"), LabelWidth(120), ToggleLeft, LabelText("作为同级目录显示"), OnValueChanged("OnValueChanged")] public bool FlattenSubFolder = false; private void OnValueChanged() { AssetImporter.Instance.RefreshTree(); } public string GetAbsPath() { return string.Format("{0}/{1}", Application.dataPath, FolderPath); } } [Serializable] public class TextureImpConfig : AssetImpConfig { [SerializeField] public List<TextureImportSetting> Setting = new List<TextureImportSetting>(); } [Serializable] public class ModelImpConfig : AssetImpConfig { [SerializeField] public List<ModelImportSetting> Setting = new List<ModelImportSetting>(); } [Serializable] public class AudioClipImpConfig : AssetImpConfig { [SerializeField] public List<AudioClipImportSetting> Setting = new List<AudioClipImportSetting>(); } }<file_sep>--[[ -- table扩展工具类,对table不支持的功能执行扩展 -- 注意: -- 1、所有参数带hashtable的函数,将把table当做哈希表对待 -- 2、所有参数带array的函数,将把table当做可空值数组对待 -- 3、所有参数带t的函数,对表通用,不管是哈希表还是数组 --]] local type = type local pairs = pairs local ipairs = ipairs local rep = string.rep local tostring = tostring local getmetatable = getmetatable local insert = table.insert local floor = math.floor local sort = table.sort local concat = table.concat local getmetatable = getmetatable local setmetatable = setmetatable local format = string.format -- 计算哈希表长度 local function count(hashtable) local count = 0 for _, _ in pairs(hashtable) do count = count + 1 end return count end -- 计算数据长度 local function length(array) if array.n ~= nil then return array.n end local count = 0 for i, _ in pairs(array) do if count < i then count = i end end return count end -- 设置数组长度 local function setlen(array, n) array.n = n end -- 获取哈希表所有键 local function keys(hashtable) local keys = {} for k, v in pairs(hashtable) do keys[#keys + 1] = k end return keys end -- 获取哈希表所有值 local function values(hashtable) local values = {} for k, v in pairs(hashtable) do values[#values + 1] = v end return values end -- 合并哈希表:将src_hashtable表合并到dest_hashtable表,相同键值执行覆盖 local function merge(src_hashtable, dest_hashtable) for k, v in pairs(src_hashtable) do dest_hashtable[k] = v end end -- 合并数组:将src_array数组从begin位置开始插入到dest_array数组 -- 注意:begin <= 0被认为没有指定起始位置,则将两个数组执行拼接 local function insertarray(src_array, dest_array, begin) assert(begin == nil or type(begin) == "number") if begin == nil or begin <= 0 then begin = #dest_array + 1 end local src_len = #src_array for i = 0, src_len - 1 do dest_array[i + begin] = src_array[i + 1] end end -- 从数组中查找指定值,返回其索引,没找到返回false local function indexof(array, value, begin) for i = begin or 1, #array do if array[i] == value then return i end end return false end -- 从哈希表查找指定值,返回其键,没找到返回nil -- 注意: -- 1、containskey用hashtable[key] ~= nil快速判断 -- 2、containsvalue由本函数返回结果是否为nil判断 local function keyof(hashtable, value) for k, v in pairs(hashtable) do if v == value then return k end end return nil end -- 从数组中删除指定值,返回删除的值的个数 local function removebyvalue(array, value, removeall) local remove_count = 0 for i = #array, 1, -1 do if array[i] == value then table.remove(array, i) remove_count = remove_count + 1 if not removeall then break end end end return remove_count end -- 筛选符合条件的项:不对原表执行操作 local function filter(hashtable, condition) local filter = {} for k, v in pairs(hashtable) do if not condition(k, v) then filter[k] = v end end return filter end -- dump table local function dump(hashtable, max_level) local limit = max_level or 3 local _dump = nil _dump = function(t, level) if level >= limit then return end local code = { "{\n" } local tab = rep("\t", level) for k, v in pairs(t) do if type(v) == "number" then insert(code, format("%s\t<color=orange>[%s]</color> = %s,\n",tab, k, v)) elseif type(v) == "string" then insert(code, format("%s\t<color=orange>%s</color> = %s,\n",tab, k, v)) elseif type(v) == "table" then insert(code, format("%s\t<color=orange>%s</color> = %s,\n",tab, k, _dump(v, level + 1) or '')) end end insert(code, tab .. "}") return concat(code) end return _dump(hashtable, 0) end -- 清理表 local function clear(t) if t == nil then return end for k, _ in pairs(t) do t[k] = nil end end -- 深复制表,但不包含function类型 local function deepcopyto(src, dst) for k, v in pairs(src) do if type(v) ~= "table" then dst[k] = v else dst[k] = dst[k] or {} deepcopyto(v, dst[k]) end end end -- 浅复制表,只取第一层基础类型 local function shallowcopyto(src, dst) for k, v in pairs(src) do dst[k] = v end end -- 自身完全复制;注意死循环 local function clone(src) local dst = {} for k, v in pairs(src) do if type(v) == "table" then dst[k] = clone(v) else dst[k] = v end end local mt = getmetatable(src) setmetatable(dst, mt) return dst end --二分法查找 local function binsearch(array, v) local from, to from = 1 to = #array while from <= to do local mid = floor(from / 2 + to / 2) -- PrintYellow(from,to,mid) if array[mid] > v then to = mid - 1 elseif array[mid] < v then from = mid + 1 else return array[mid] end end return nil end -- 数组对比 local function swap(t, a, b) local temp = t[a] t[a] = t[b] t[b] = temp end local function mysort(t, cmp) for i = 1, #t do for j = #t, i + 1, -1 do if not cmp(t[j - 1], t[j]) then swap(t, j, j - 1) end end end end local function compare(array1, array2, cmp) if array1 == array2 then return true else if nil == array1 or nil == array2 then return false elseif #array1 ~= #array2 then return false else if cmp then mysort(array1, cmp) mysort(array2, cmp) else sort(array1) sort(array2) end for i, value in ipairs(array1) do if value ~= array2[i] then print(format("[table.compare] array1[%s]=[%s] while array2[%s]=[%s], return false!", i, value, i, array2[i])) return false end end return true end end end table.count = count table.length = length table.setlen = setlen table.keys = keys table.values = values table.merge = merge table.insertarray = insertarray table.indexof = indexof table.keyof = keyof table.removebyvalue = removebyvalue table.filter = filter table.dump = dump table.clear = clear table.deepcopyto = deepcopyto table.shallowcopyto = shallowcopyto table.clone = clone table.binsearch = binsearch table.compare = compare -- dump表 -- local function dump(t, dump_metatable, max_level) -- local lookup_table = {} -- local level = 0 -- local dump_metatable = dump_metatable -- local max_level = max_level or 1 -- local function _dump(t, level) -- local str = "\n" .. rep("\t", level) .. "{\n" -- for k, v in pairs(t) do -- local k_is_str = type(k) == "string" and 1 or 0 -- local v_is_str = type(v) == "string" and 1 or 0 -- str = str .. rep("\t", level + 1) .. "[" .. rep("\"", k_is_str) .. (tostring(k) or type(k)) .. rep("\"", k_is_str) .. "]" .. " = " -- if type(v) == "table" then -- if not lookup_table[v] and ((not max_level) or level < max_level) then -- lookup_table[v] = true -- str = str .. _dump(v, level + 1, dump_metatable) .. "\n" -- else -- str = str .. (tostring(v) or type(v)) .. ",\n" -- end -- else -- str = str .. rep("\"", v_is_str) .. (tostring(v) or type(v)) .. rep("\"", v_is_str) .. ",\n" -- end -- end -- if dump_metatable then -- local mt = getmetatable(t) -- if mt ~= nil and type(mt) == "table" then -- str = str .. rep("\t", level + 1) .. "[\"__metatable\"]" .. " = " -- if not lookup_table[mt] and ((not max_level) or level < max_level) then -- lookup_table[mt] = true -- str = str .. _dump(mt, level + 1, dump_metatable) .. "\n" -- else -- str = str .. (tostring(v) or type(v)) .. ",\n" -- end -- end -- end -- str = str .. rep("\t", level) .. "}," -- return str -- end -- return _dump(t, level) -- end<file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg { public class Vector3 : XmlObject { /// <summary> /// /// <summary> public float X; /// <summary> /// /// <summary> public float Y; /// <summary> /// /// <summary> public float Z; public override void Write(TextWriter _1) { Write(_1, "X", this.X); Write(_1, "Y", this.Y); Write(_1, "Z", this.Z); } public override void Read(XmlNode _1) { foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "X": this.X = ReadFloat(_2); break; case "Y": this.Y = ReadFloat(_2); break; case "Z": this.Z = ReadFloat(_2); break; } } } } <file_sep>namespace AssetManager { using UnityEditor; using UnityEngine; using Sirenix.OdinInspector.Editor; using Sirenix.Utilities.Editor; using Sirenix.Utilities; using System.Linq; public class AssetChecker : OdinMenuEditorWindow { [MenuItem("Assets/资源检查器", false, 2000)] private static void Open() { var window = GetWindow<AssetChecker>("资源检查器"); window.position = GUIHelper.GetEditorWindowRect().AlignCenter(1200, 600); CheckerConfig.LoadInstanceIfAssetExists(); window._check = new GUIContent(EditorIcons.Refresh.Raw); } const string TAB_ATLAS_WITHOUT_SPRITE = "未打入图集中的精灵"; const string TAB_ROLE_MESH = "角色网格"; const string TAB_FILE_NAME = "非法文件命名"; const string TAB_TEXTURE_STRETCH = "图片拉伸模糊"; GUIContent _check; protected override OdinMenuTree BuildMenuTree() { var tree = new OdinMenuTree(false); tree.Config.DrawSearchToolbar = true; if (CheckerConfig.Instance.BitmapChecker == null) CheckerConfig.Instance.BitmapChecker = new BitmapCheckerInfo(TAB_ATLAS_WITHOUT_SPRITE); tree.AddObjectAtPath(TAB_ATLAS_WITHOUT_SPRITE, CheckerConfig.Instance.BitmapChecker); if (CheckerConfig.Instance.RoleMeshChecker == null) CheckerConfig.Instance.RoleMeshChecker = new RoleMeshCheckerInfo(TAB_ROLE_MESH); tree.AddObjectAtPath(TAB_ROLE_MESH, CheckerConfig.Instance.RoleMeshChecker); if (CheckerConfig.Instance.FileNameChecker == null) CheckerConfig.Instance.FileNameChecker = new FileNameCheckerInfo(TAB_FILE_NAME); tree.AddObjectAtPath(TAB_FILE_NAME, CheckerConfig.Instance.FileNameChecker); if (CheckerConfig.Instance.TextureStretchChecker == null) CheckerConfig.Instance.TextureStretchChecker = new TextureStretchCheckerInfo(TAB_TEXTURE_STRETCH); tree.AddObjectAtPath(TAB_TEXTURE_STRETCH, CheckerConfig.Instance.TextureStretchChecker); return tree; } protected override void OnBeginDrawEditors() { var selected = this.MenuTree.Selection.FirstOrDefault(); var toolbarHeight = this.MenuTree.Config.SearchToolbarHeight; if (selected == null) return; SirenixEditorGUI.BeginHorizontalToolbar(toolbarHeight); { if (selected != null) { GUILayout.Label(selected.Name); } if (SirenixEditorGUI.ToolbarButton(_check)) { (selected.ObjectInstance as CheckerInfo).CheckAsset(); } } SirenixEditorGUI.EndHorizontalToolbar(); } protected override void OnDestroy() { base.OnDestroy(); EditorUtility.SetDirty(CheckerConfig.Instance); EditorUtility.UnloadUnusedAssetsImmediate(); AssetDatabase.Refresh(); } } } <file_sep>using Game.Platform; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Profiling; using XLua; namespace Game { [CSharpCallLua] public delegate void UpdateFunc(float deltaTime, float unscaledDeltaTime); [CSharpCallLua] public delegate void LateUpdateFunc(); [CSharpCallLua] public delegate void FixedUpdateFunc(float fixedDeltaTime); public class Main : MonoBehaviour { public static Main Instance { get; private set; } public UpdateFunc Updater; public LateUpdateFunc LateUpdater; public FixedUpdateFunc FixedUpdater; List<IManager> _managers = new List<IManager>() { LuaManager.Instance, ResourceManager.Instance, GameManager.Instance, }; void Awake() { Instance = this; var uiRoot = GameObject.Find("/UIRoot"); var eSystem = GameObject.Find("/EventSystem"); DontDestroyOnLoad(gameObject); DontDestroyOnLoad(uiRoot); DontDestroyOnLoad(eSystem); for (int i = 0; i < _managers.Count; i++) _managers[i].Init(); Util.SetResolution(AppConst.Resolution); Application.targetFrameRate = AppConst.FrameRate; QualitySettings.blendWeights = BlendWeights.TwoBones; Screen.sleepTimeout = SleepTimeout.NeverSleep; Interface.Create(); Interface.Instance.Init(); } IEnumerator Start() { yield return GameManager.Instance.InitSDK(); yield return GameManager.Instance.DowmloadUnZip(); yield return GameManager.Instance.UnZipFile(); yield return GameManager.Instance.UpdateAppVersion(); yield return GameManager.Instance.UpdateResVersion(); yield return GameManager.Instance.GetServerList(); yield return GameManager.Instance.LoadResource(); GameManager.Instance.StartGame(); } void Update() { LuaManager.Instance.Tick(); if (AppConst.EnableProfile) Profiler.BeginSample("Client.Updater"); if (Updater != null) Updater(Time.deltaTime, Time.unscaledDeltaTime); if (AppConst.EnableProfile) Profiler.EndSample(); } void LateUpdate() { if (AppConst.EnableProfile) Profiler.BeginSample("Client.LateUpdater"); if (Updater != null) LateUpdater(); if (AppConst.EnableProfile) Profiler.EndSample(); } void FixedUpdate() { if (AppConst.EnableProfile) Profiler.BeginSample("Client.FixedUpdater"); if (Updater != null) FixedUpdater(Time.fixedDeltaTime); if (AppConst.EnableProfile) Profiler.EndSample(); } void OnApplicationQuit() { Updater = null; LateUpdater = null; FixedUpdater = null; for (int i = 0; i < _managers.Count; i++) _managers[i].Dispose(); _managers.Clear(); Instance = null; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using XLua; using Object = UnityEngine.Object; public class ManagedResource : MonoBehaviour { public string bundlename; public void OnDestroy() { //Util.LogColor("green", "~~~ OnDestroy : " + bundlename); Game.ResourceManager.Instance.RemoveRefCount(bundlename); } } namespace Game { public enum ResourceLoadType { Default = 0, // 资源已加载,直接取资源 Persistent = 1 << 0, // 永驻内存的资源 Cache = 1 << 1, // Asset需要缓存 UnLoad = 1 << 4, // 利用www加载并且处理后是否立即unload ab,如不卸载,则在指定时间后清理 Immediate = 1 << 5, // 需要立即加载 // 加载方式 LoadBundleFromFile = 1 << 6, // 利用AssetBundle.LoadFromFile加载 LoadBundleFromWWW = 1 << 7, // 利用WWW 异步加载 AssetBundle ReturnAssetBundle = 1 << 8, // 返回scene AssetBundle,默认unload ab } class CacheObject { public Object obj; public float lastUseTime; } class AssetLoadTask { public uint id; public List<uint> parentTaskIds; public int loadType; public string path; public Action<Object> actions; public List<string> dependencies; public int loadedDependenciesCount = 0; public void Reset() { id = 0; parentTaskIds = null; path = string.Empty; actions = null; dependencies = null; loadedDependenciesCount = 0; } } /// <summary> /// AssetBundle加载完毕,后续处理 /// </summary> class LoadTask { public AssetLoadTask task; public AssetBundle bundle; } public class ResourceManager : IManager { public static ResourceManager Instance { get { if (_instance == null) _instance = new ResourceManager(); return _instance; } } static ResourceManager _instance; protected ResourceManager() { } //资源存储策略 private Dictionary<string, Object> persistantObjects = new Dictionary<string, Object>(); //key-依赖路径 private Dictionary<string, CacheObject> cacheObjects = new Dictionary<string, CacheObject>(); //加载的AB资源包 private Dictionary<string, AssetBundle> dependenciesObj = new Dictionary<string, AssetBundle>(); //key-依赖路径 //加载任务 private Dictionary<string, AssetLoadTask> loadingFiles = new Dictionary<string, AssetLoadTask>();//key-文件名 private Dictionary<uint, AssetLoadTask> loadingTasks = new Dictionary<uint, AssetLoadTask>(); //key-任务ID private ObjectPool<AssetLoadTask> assetLoadTaskPool = new ObjectPool<AssetLoadTask>(); //加载资源的相关信息 private Queue<AssetLoadTask> delayAssetLoadTask = new Queue<AssetLoadTask>(); private ObjectPool<LoadTask> loadTaskPool = new ObjectPool<LoadTask>(); private Queue<LoadTask> delayLoadTask = new Queue<LoadTask>(); private bool canStartCleanupMemeory = true; private const float cleanupMemInterval = 180; private const float cleanupCacheInterval = 120; private const float cleanupDepInterval = 30; private string preloadListPath = "config/preloadlist.txt"; private List<string> preloadList = new List<string>(); private Dictionary<string, int> refCount = new Dictionary<string, int>(); private Dictionary<string, float> refDelTime = new Dictionary<string, float>(); private int currentTaskCount = 0; private const int defaultMaxTaskCount = 10; private float cleanupMemoryLastTime; private float cleanupCacheBundleLastTime; private float cleanupDependenciesLastTime; private AssetBundleManifest manifest; private static uint nextTaskId; public int MaxTaskCount { get; set; } /// <summary> /// 初始化 /// </summary> public void Init() { int memorySize = 1024 * 1024; //内存大小1GB if (memorySize <= 1024 * 1024) { MaxTaskCount = 5; } byte[] stream = null; #if UNITY_EDITOR string path = GetResPath("GamePlayer"); #elif UNITY_ANDROID string path = GetResPath("Android"); #elif UNITY_IOS string path = GetResPath("IOS"); #endif if (!File.Exists(path)) return; stream = File.ReadAllBytes(path); var assetbundle = AssetBundle.LoadFromMemory(stream); manifest = assetbundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest"); } public void Start() { //获取预加载资源列表 //加载预加载资源 //TODO } public bool IsLoading(uint taskId) { return loadingTasks.ContainsKey(taskId); } public void RemoveTask(uint taskId, Action<Object> action) { if (IsLoading(taskId)) { AssetLoadTask oldTask = null; if (loadingTasks.TryGetValue(taskId, out oldTask)) { if (null != action) { oldTask.actions -= action; } } } } public uint AddTask(string file, LuaFunction action, int loadType = (int)ResourceLoadType.LoadBundleFromFile) { return AddTask(file, o => action.Call(o), loadType, 0); } public uint AddTask(string file, Action<Object> action, int loadType = (int)ResourceLoadType.LoadBundleFromFile) { return AddTask(file, action, loadType, 0); } private uint AddTask(string file, Action<Object> action, int loadType, uint parentTaskId) { if (string.IsNullOrEmpty(file)) { return 0; } string fileReplace = file.Replace(@"\", @" / "); string lowerFile = fileReplace.ToLower(); Object obj; if (persistantObjects.TryGetValue(lowerFile, out obj)) { action(obj); return 0; } CacheObject cacheObject; if (cacheObjects.TryGetValue(lowerFile, out cacheObject)) { cacheObject.lastUseTime = Time.realtimeSinceStartup; action(cacheObject.obj); return 0; } AssetLoadTask oldTask; if (loadingFiles.TryGetValue(lowerFile, out oldTask)) {//资源加载任务-正在进行中 if (action != null) { oldTask.actions += action; } if ((loadType & (int)ResourceLoadType.Persistent) > 0) { oldTask.loadType |= (int)ResourceLoadType.Persistent; } if (parentTaskId != 0) { if (oldTask.parentTaskIds == null) { oldTask.parentTaskIds = new List<uint>(); Debug.LogErrorFormat("resource path {0} type is mixed, dependency resource or not ", oldTask.path); } oldTask.parentTaskIds.Add(parentTaskId); } return 0; } //加载资源到内存 uint id = ++nextTaskId; List<uint> ptList = null; if (parentTaskId != 0) { ptList = new List<uint>(); ptList.Add(parentTaskId); } string[] deps = manifest.GetAllDependencies(lowerFile); var task = assetLoadTaskPool.Get(); { task.id = id; task.parentTaskIds = ptList; task.path = lowerFile; task.loadType = loadType; task.actions = action; task.dependencies = deps == null ? null : new List<string>(deps); task.loadedDependenciesCount = 0; }; loadingFiles[lowerFile] = task; loadingTasks[id] = task; if (dependenciesObj.ContainsKey(task.path)) {//依赖资源已被加载 AddRefCount(task.path); } //任务数量达最大时,延迟加载资源[需要排队] if (currentTaskCount < MaxTaskCount) DoTask(task); else delayAssetLoadTask.Enqueue(task); return id; } public void AddRefCount(string bundlename) { string[] dependencies = manifest.GetAllDependencies(bundlename); if (dependencies != null && dependencies.Length > 0) { for (int i = 0; i < dependencies.Length; i++) { string depname = dependencies[i]; if (!persistantObjects.ContainsKey(depname)) { if (!refCount.ContainsKey(depname)) { refCount[depname] = 0; } refCount[depname]++; } } } } public void RemoveRefCount(string bundlename) { string[] dependencies = manifest.GetAllDependencies(bundlename); if (dependencies != null && dependencies.Length > 0) { for (int i = 0; i < dependencies.Length; i++) { string depname = dependencies[i]; if (refCount.ContainsKey(depname)) { refCount[depname]--; if (refCount[depname] <= 0) { refDelTime[depname] = Time.realtimeSinceStartup; } } } } } private void DoTask(AssetLoadTask task) { if (task.dependencies == null) { DoImmediateTask(task); } else { if (task.loadedDependenciesCount >= task.dependencies.Count) { DoImmediateTask(task); } else { int i = task.loadedDependenciesCount; for (; i < task.dependencies.Count; ++i) { if (dependenciesObj.ContainsKey(task.dependencies[i]) || persistantObjects.ContainsKey(task.dependencies[i])) { task.loadedDependenciesCount += 1; if (task.loadedDependenciesCount >= task.dependencies.Count) { DoImmediateTask(task); return; } } else { AddTask(task.dependencies[i], null, task.loadType, task.id); } } } } } private void DoImmediateTask(AssetLoadTask task) { currentTaskCount += 1; if ((task.loadType & (int)ResourceLoadType.LoadBundleFromWWW) != 0) { Main.Instance.StartCoroutine(LoadBundleFromWWW(task)); } else if ((task.loadType & (int)ResourceLoadType.LoadBundleFromFile) != 0) { LoadBundleFromFile(task); } else { currentTaskCount -= 1; Debug.LogErrorFormat("Unknown task loadtype:{0} path:{1}", task.loadType, task.path); } } private IEnumerator LoadBundleFromWWW(AssetLoadTask task) { string path = GetResPath(task.path); var www = new WWW(path); yield return www; if (null != www.error) Debug.LogErrorFormat("LoadBundleAsync: {0} failed! www error:{1}", task.path, www.error); OnBundleLoaded(task, www.assetBundle); www.Dispose(); } private void LoadBundleFromFile(AssetLoadTask task) { string path = GetResPath(task.path); AssetBundle ab = AssetBundle.LoadFromFile(path); OnBundleLoaded(task, ab); } //AssetBundle加载完毕 private void OnBundleLoaded(AssetLoadTask task, AssetBundle ab) { currentTaskCount -= 1; Object obj = null; if (ab == null) { Debug.LogErrorFormat("LoadBundle: {0} failed! assetBundle == NULL!", task.path); OnAseetsLoaded(task, ab, obj); } else { var loadTask = loadTaskPool.Get(); loadTask.task = task; loadTask.bundle = ab; delayLoadTask.Enqueue(loadTask); } } void Update() { CleanupCacheBundle(); CleanupMemoryInterval(); CleanupDependenciesInterval(); //执行延迟加载任务 DoDelayTasks(); } private void DoDelayTasks() { if (delayAssetLoadTask.Count > 0) { while (delayAssetLoadTask.Count > 0 && currentTaskCount < MaxTaskCount) { AssetLoadTask task = delayAssetLoadTask.Dequeue(); DoTask(task); } } if (delayLoadTask.Count > 0) { var maxLoadTime = 0.02f; var startTime = Time.realtimeSinceStartup; while (delayLoadTask.Count > 0 && Time.realtimeSinceStartup - startTime < maxLoadTime) { LoadTask loadTask = delayLoadTask.Dequeue(); var task = loadTask.task; var bundle = loadTask.bundle; Object obj = null; if (bundle != null) { if (!bundle.isStreamedSceneAssetBundle) { var objs = bundle.LoadAllAssets(); if (objs.Length > 0) obj = objs[0]; if (obj == null) { Debug.LogErrorFormat("LoadBundle: {0} ! No Assets in Bundle!", task.path); } } } OnAseetsLoaded(task, bundle, obj); loadTaskPool.Put(loadTask); } } } //Asset加载完毕,可能是依赖资源,也可能是主资源 private void OnAseetsLoaded(AssetLoadTask task, AssetBundle ab, Object obj) { string[] dependencies = manifest.GetAllDependencies(task.path); if (dependencies == null || dependencies.Length == 0) { RemoveRefCount(task.path); } loadingFiles.Remove(task.path); loadingTasks.Remove(task.id); //主资源加载完毕 if (task.actions != null && task.parentTaskIds == null) { Delegate[] delegates = task.actions.GetInvocationList(); foreach (var dele in delegates) { var action = (Action<Object>)dele; try { if ((task.loadType & (int)ResourceLoadType.ReturnAssetBundle) > 0) { action(ab); } else { action(obj); } } catch (Exception e) { Debug.LogErrorFormat("Load Bundle {0} DoAction Exception: {1}", task.path, e); } } } //缓存加载的资源对象[非AB] if (ab != null && task.parentTaskIds == null) { if ((task.loadType & (int)ResourceLoadType.Persistent) > 0) { persistantObjects[task.path] = obj; if ((task.loadType & (int)ResourceLoadType.UnLoad) > 0) { ab.Unload(false); } } else { if ((task.loadType & (int)ResourceLoadType.Cache) > 0) { var cacheObject = new CacheObject { lastUseTime = Time.realtimeSinceStartup, obj = obj }; cacheObjects[task.path] = cacheObject; } if ((task.loadType & (int)ResourceLoadType.ReturnAssetBundle) == 0) { ab.Unload(false); } } } //依赖资源加载完毕 if (task.parentTaskIds != null) { dependenciesObj[task.path] = ab; for (int i = 0; i < task.parentTaskIds.Count; ++i) { uint taskid = task.parentTaskIds[i]; AssetLoadTask pt = null; if (loadingTasks.TryGetValue(taskid, out pt)) { pt.loadedDependenciesCount += 1; if (pt.loadedDependenciesCount >= pt.dependencies.Count) { DoTask(pt); } } } } task.Reset(); assetLoadTaskPool.Put(task); } public string GetResPath(string relative) { relative = Util.StandardlizePath(relative); string fullPath = Util.DataPath + relative; if (!File.Exists(fullPath)) fullPath = Util.StreamingPath + relative; return fullPath; } //定时清理功能 //-内存清理 public void CleanupMemoryInterval() { if (Time.realtimeSinceStartup > cleanupMemoryLastTime + cleanupMemInterval) { CleanupMemoryNow(); } } public void CleanupMemoryNow() { if (canStartCleanupMemeory) { canStartCleanupMemeory = false; cleanupMemoryLastTime = Time.realtimeSinceStartup; Main.Instance.StartCoroutine(CleanupMemoryAsync()); } } private IEnumerator CleanupMemoryAsync() { yield return Resources.UnloadUnusedAssets(); GC.Collect(); canStartCleanupMemeory = true; cleanupMemoryLastTime = Time.realtimeSinceStartup; } //-缓存包清理 private void CleanupCacheBundle() { if (cacheObjects.Count <= 0) return; if (!(Time.realtimeSinceStartup > cleanupCacheBundleLastTime + 10)) return; var now = cleanupCacheBundleLastTime = Time.realtimeSinceStartup; var tempList = new List<string>(); foreach (var pair in cacheObjects) { if (now > pair.Value.lastUseTime + cleanupCacheInterval) { tempList.Add(pair.Key); if (null != pair.Value.obj) { //Debug.LogError(" try to destroy object: " + pair.Key); if (pair.Value.obj is GameObject) { UnityEngine.Object.DestroyImmediate(pair.Value.obj, true); } else { Resources.UnloadAsset(pair.Value.obj); } } } } foreach (var bundle in tempList) { cacheObjects.Remove(bundle); } } //-依赖包清理 public void CleanupDependenciesInterval() { if (Time.realtimeSinceStartup > cleanupDependenciesLastTime + cleanupDepInterval) { CleanupDependenciesNow(); } } public void CleanupDependenciesNow() { if (refCount == null || refDelTime == null || dependenciesObj == null) { return; } cleanupDependenciesLastTime = Time.realtimeSinceStartup; List<string> refCountToRemove = new List<string>(); foreach (var pairs in refCount) { if (pairs.Value <= 0) { if (dependenciesObj.ContainsKey(pairs.Key) && refDelTime.ContainsKey(pairs.Key) && Time.realtimeSinceStartup - refDelTime[pairs.Key] > 60) { if (dependenciesObj.ContainsKey(pairs.Key)) { if (dependenciesObj[pairs.Key] != null) dependenciesObj[pairs.Key].Unload(false); dependenciesObj[pairs.Key] = null; dependenciesObj.Remove(pairs.Key); } refDelTime.Remove(pairs.Key); refCountToRemove.Add(pairs.Key); } } } foreach (var remove in refCountToRemove) { refCount.Remove(remove); } } //其他操作 public void Dispose() { if (manifest != null) manifest = null; foreach (KeyValuePair<string, Object> pair in persistantObjects) { if (pair.Value != null) { if (pair.Value is GameObject) { UnityEngine.Object.DestroyImmediate(pair.Value, true); } else { Resources.UnloadAsset(pair.Value); } } } persistantObjects.Clear(); foreach (var pair in dependenciesObj) { if (pair.Value != null) { pair.Value.Unload(true); } } dependenciesObj.Clear(); foreach (var pair in cacheObjects) { if (pair.Value != null && pair.Value.obj != null) { if (pair.Value.obj is GameObject) { UnityEngine.Object.DestroyImmediate(pair.Value.obj, true); } else { Resources.UnloadAsset(pair.Value.obj); } } } cacheObjects.Clear(); Debug.Log("~ResourceManager was destroy!"); } } } <file_sep>#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class GameUtilWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(Game.Util); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 13, 4, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "md5", _m_md5_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "md5file", _m_md5file_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "StandardlizePath", _m_StandardlizePath_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "SetResolution", _m_SetResolution_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "ClearChild", _m_ClearChild_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "Log", _m_Log_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "LogWarning", _m_LogWarning_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "LogError", _m_LogError_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "ReadDict", _m_ReadDict_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "ReadList", _m_ReadList_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "WriteDict", _m_WriteDict_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_IDX, "WriteList", _m_WriteList_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "DataPath", _g_get_DataPath); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "StreamingPath", _g_get_StreamingPath); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "NetAvailable", _g_get_NetAvailable); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "IsWifi", _g_get_IsWifi); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { Game.Util gen_ret = new Game.Util(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to Game.Util constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_md5_xlua_st_(RealStatePtr L) { try { { string _source = LuaAPI.lua_tostring(L, 1); string gen_ret = Game.Util.md5( _source ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_md5file_xlua_st_(RealStatePtr L) { try { { string _file = LuaAPI.lua_tostring(L, 1); string gen_ret = Game.Util.md5file( _file ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_StandardlizePath_xlua_st_(RealStatePtr L) { try { { string _path = LuaAPI.lua_tostring(L, 1); string gen_ret = Game.Util.StandardlizePath( _path ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_SetResolution_xlua_st_(RealStatePtr L) { try { { int _resolution = LuaAPI.xlua_tointeger(L, 1); Game.Util.SetResolution( _resolution ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_ClearChild_xlua_st_(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); { UnityEngine.Transform _go = (UnityEngine.Transform)translator.GetObject(L, 1, typeof(UnityEngine.Transform)); Game.Util.ClearChild( _go ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Log_xlua_st_(RealStatePtr L) { try { { string _str = LuaAPI.lua_tostring(L, 1); Game.Util.Log( _str ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_LogWarning_xlua_st_(RealStatePtr L) { try { { string _str = LuaAPI.lua_tostring(L, 1); Game.Util.LogWarning( _str ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_LogError_xlua_st_(RealStatePtr L) { try { { string _str = LuaAPI.lua_tostring(L, 1); Game.Util.LogError( _str ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_ReadDict_xlua_st_(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); { string _filePath = LuaAPI.lua_tostring(L, 1); System.Collections.Generic.Dictionary<string, string> gen_ret = Game.Util.ReadDict( _filePath ); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_ReadList_xlua_st_(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); { string _filePath = LuaAPI.lua_tostring(L, 1); System.Collections.Generic.List<string> gen_ret = Game.Util.ReadList( _filePath ); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_WriteDict_xlua_st_(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); { string _filePath = LuaAPI.lua_tostring(L, 1); System.Collections.Generic.Dictionary<string, string> _dict = (System.Collections.Generic.Dictionary<string, string>)translator.GetObject(L, 2, typeof(System.Collections.Generic.Dictionary<string, string>)); Game.Util.WriteDict( _filePath, _dict ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_WriteList_xlua_st_(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); { string _filePath = LuaAPI.lua_tostring(L, 1); System.Collections.Generic.List<string> _list = (System.Collections.Generic.List<string>)translator.GetObject(L, 2, typeof(System.Collections.Generic.List<string>)); Game.Util.WriteList( _filePath, _list ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_DataPath(RealStatePtr L) { try { LuaAPI.lua_pushstring(L, Game.Util.DataPath); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_StreamingPath(RealStatePtr L) { try { LuaAPI.lua_pushstring(L, Game.Util.StreamingPath); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_NetAvailable(RealStatePtr L) { try { LuaAPI.lua_pushboolean(L, Game.Util.NetAvailable); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_IsWifi(RealStatePtr L) { try { LuaAPI.lua_pushboolean(L, Game.Util.IsWifi); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class CylinderZone : XmlCfg.Skill.HitZone { /// <summary> /// 圆半径 /// <summary> public float Radius; /// <summary> /// 圆柱高度 /// <summary> public float Height; /// <summary> /// 打击区域绕y轴旋转角度(顺时针:左手定则),构成扇形 /// <summary> public float Angle; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Radius", this.Radius); Write(_1, "Height", this.Height); Write(_1, "Angle", this.Angle); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Radius": this.Radius = ReadFloat(_2); break; case "Height": this.Height = ReadFloat(_2); break; case "Angle": this.Angle = ReadFloat(_2); break; } } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class SkillAction : XmlCfg.Skill.GeneralAction { /// <summary> /// 默认后续技能使用期限,用于单个技能多段输出 /// <summary> public const float EXPIRE_TIME = 1f; /// <summary> /// 后续技能使用期限,用于单个技能多段输出 /// <summary> public float SkillExpireTime; /// <summary> /// 技能结束时间 /// <summary> public float SkillEndTime; /// <summary> /// 是否可被打断 /// <summary> public bool CanInterrupt; /// <summary> /// 技能锁定对象类型(0不需要目标 1敌方目标 ,2己方目标 3自己 4中立方) /// <summary> public XmlCfg.Skill.LockObjectType LockType; /// <summary> /// 技能作用范围[半径] /// <summary> public float SkillRange; /// <summary> /// 是否显示技能范围 /// <summary> public bool CanShowSkillRange; /// <summary> /// 放技能时人是否可以转动 /// <summary> public bool CanRotate; /// <summary> /// 放技能时人是否可以移动 /// <summary> public bool CanMove; /// <summary> /// 序列字典集合 /// <summary> public Dictionary<int, Sequence> SequenceDict = new Dictionary<int, Sequence>(); public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "SkillExpireTime", this.SkillExpireTime); Write(_1, "SkillEndTime", this.SkillEndTime); Write(_1, "CanInterrupt", this.CanInterrupt); Write(_1, "LockType", (int)this.LockType); Write(_1, "SkillRange", this.SkillRange); Write(_1, "CanShowSkillRange", this.CanShowSkillRange); Write(_1, "CanRotate", this.CanRotate); Write(_1, "CanMove", this.CanMove); Write(_1, "SequenceDict", this.SequenceDict); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "SkillExpireTime": this.SkillExpireTime = ReadFloat(_2); break; case "SkillEndTime": this.SkillEndTime = ReadFloat(_2); break; case "CanInterrupt": this.CanInterrupt = ReadBool(_2); break; case "LockType": this.LockType = (XmlCfg.Skill.LockObjectType)ReadInt(_2); break; case "SkillRange": this.SkillRange = ReadFloat(_2); break; case "CanShowSkillRange": this.CanShowSkillRange = ReadBool(_2); break; case "CanRotate": this.CanRotate = ReadBool(_2); break; case "CanMove": this.CanMove = ReadBool(_2); break; case "SequenceDict": GetChilds(_2).ForEach (_3 => this.SequenceDict.Add(ReadInt(GetOnlyChild(_3, "Key")), ReadObject<XmlCfg.Skill.Sequence>(GetOnlyChild(_3, "Value"), "XmlCfg.Skill.Sequence"))); break; } } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class ReplaceObject : XmlCfg.Skill.Controller { /// <summary> /// 新对象 /// <summary> public string NewObject = ""; /// <summary> /// 相对位置 /// <summary> public XmlCfg.Vector3 Offset; /// <summary> /// 相对旋转 /// <summary> public XmlCfg.Vector3 EulerAngles; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "NewObject", this.NewObject); Write(_1, "Offset", this.Offset); Write(_1, "EulerAngles", this.EulerAngles); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "NewObject": this.NewObject = ReadString(_2); break; case "Offset": this.Offset = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; case "EulerAngles": this.EulerAngles = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; } } } } <file_sep>#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class GamePlatformInterfaceWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(Game.Platform.Interface); Utils.BeginObjectRegister(type, L, translator, 0, 44, 0, 0); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Init", _m_Init); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Release", _m_Release); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetAvailableMemory", _m_GetAvailableMemory); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Install", _m_Install); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetSDKPlatform", _m_GetSDKPlatform); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetSDKPlatformName", _m_GetSDKPlatformName); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetNetWorkMode", _m_GetNetWorkMode); Utils.RegisterFunc(L, Utils.METHOD_IDX, "InitSDK", _m_InitSDK); Utils.RegisterFunc(L, Utils.METHOD_IDX, "EscapeSDK", _m_EscapeSDK); Utils.RegisterFunc(L, Utils.METHOD_IDX, "IsSDKFinished", _m_IsSDKFinished); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Login", _m_Login); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Logout", _m_Logout); Utils.RegisterFunc(L, Utils.METHOD_IDX, "SubmitUserInfo", _m_SubmitUserInfo); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Pay", _m_Pay); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetLoginStatus", _m_GetLoginStatus); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetUserId", _m_GetUserId); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetUserName", _m_GetUserName); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetToken", _m_GetToken); Utils.RegisterFunc(L, Utils.METHOD_IDX, "SetToken", _m_SetToken); Utils.RegisterFunc(L, Utils.METHOD_IDX, "SetUserInfo", _m_SetUserInfo); Utils.RegisterFunc(L, Utils.METHOD_IDX, "CheckGuestAccount", _m_CheckGuestAccount); Utils.RegisterFunc(L, Utils.METHOD_IDX, "ChangeAccount", _m_ChangeAccount); Utils.RegisterFunc(L, Utils.METHOD_IDX, "StartAccountHome", _m_StartAccountHome); Utils.RegisterFunc(L, Utils.METHOD_IDX, "StartForum", _m_StartForum); Utils.RegisterFunc(L, Utils.METHOD_IDX, "ShowToolBar", _m_ShowToolBar); Utils.RegisterFunc(L, Utils.METHOD_IDX, "HideToolBar", _m_HideToolBar); Utils.RegisterFunc(L, Utils.METHOD_IDX, "IsCydia", _m_IsCydia); Utils.RegisterFunc(L, Utils.METHOD_IDX, "IsPad", _m_IsPad); Utils.RegisterFunc(L, Utils.METHOD_IDX, "IsHdVersion", _m_IsHdVersion); Utils.RegisterFunc(L, Utils.METHOD_IDX, "StartWebView", _m_StartWebView); Utils.RegisterFunc(L, Utils.METHOD_IDX, "OpenUrl", _m_OpenUrl); Utils.RegisterFunc(L, Utils.METHOD_IDX, "SendWeibo", _m_SendWeibo); Utils.RegisterFunc(L, Utils.METHOD_IDX, "SendWeChat", _m_SendWeChat); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetMemInfo", _m_GetMemInfo); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetUDID", _m_GetUDID); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Voice_GetFileLength", _m_Voice_GetFileLength); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Voice_GetVolume", _m_Voice_GetVolume); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Voice_Start", _m_Voice_Start); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Voice_Stop", _m_Voice_Stop); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Voice_GetAsrText", _m_Voice_GetAsrText); Utils.RegisterFunc(L, Utils.METHOD_IDX, "InitLogSystem", _m_InitLogSystem); Utils.RegisterFunc(L, Utils.METHOD_IDX, "MonitorBatteryState", _m_MonitorBatteryState); Utils.RegisterFunc(L, Utils.METHOD_IDX, "OpenAlbum", _m_OpenAlbum); Utils.RegisterFunc(L, Utils.METHOD_IDX, "StartScanCode", _m_StartScanCode); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 1, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "Create", _m_Create_xlua_st_); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "Instance", _g_get_Instance); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { return LuaAPI.luaL_error(L, "Game.Platform.Interface does not have a constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Create_xlua_st_(RealStatePtr L) { try { { Game.Platform.Interface.Create( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Init(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Init( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Release(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Release( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetAvailableMemory(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { int gen_ret = gen_to_be_invoked.GetAvailableMemory( ); LuaAPI.xlua_pushinteger(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Install(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _file = LuaAPI.lua_tostring(L, 2); string gen_ret = gen_to_be_invoked.Install( _file ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetSDKPlatform(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { int gen_ret = gen_to_be_invoked.GetSDKPlatform( ); LuaAPI.xlua_pushinteger(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetSDKPlatformName(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string gen_ret = gen_to_be_invoked.GetSDKPlatformName( ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetNetWorkMode(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { Game.Platform.NetworkMode gen_ret = gen_to_be_invoked.GetNetWorkMode( ); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_InitSDK(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.InitSDK( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_EscapeSDK(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { bool gen_ret = gen_to_be_invoked.EscapeSDK( ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_IsSDKFinished(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { bool gen_ret = gen_to_be_invoked.IsSDKFinished( ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Login(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Login( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Logout(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Logout( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_SubmitUserInfo(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _type = LuaAPI.lua_tostring(L, 2); string _roleid = LuaAPI.lua_tostring(L, 3); string _rolename = LuaAPI.lua_tostring(L, 4); string _level = LuaAPI.lua_tostring(L, 5); int _zoneid = LuaAPI.xlua_tointeger(L, 6); string _zonename = LuaAPI.lua_tostring(L, 7); string _createtime = LuaAPI.lua_tostring(L, 8); gen_to_be_invoked.SubmitUserInfo( _type, _roleid, _rolename, _level, _zoneid, _zonename, _createtime ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Pay(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _roleid = LuaAPI.lua_tostring(L, 2); string _rolename = LuaAPI.lua_tostring(L, 3); string _level = LuaAPI.lua_tostring(L, 4); string _vip = LuaAPI.lua_tostring(L, 5); string _orderId = LuaAPI.lua_tostring(L, 6); int _serverid = LuaAPI.xlua_tointeger(L, 7); string _servername = LuaAPI.lua_tostring(L, 8); int _cash = LuaAPI.xlua_tointeger(L, 9); string _pid = LuaAPI.lua_tostring(L, 10); string _desc = LuaAPI.lua_tostring(L, 11); gen_to_be_invoked.Pay( _roleid, _rolename, _level, _vip, _orderId, _serverid, _servername, _cash, _pid, _desc ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetLoginStatus(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { int gen_ret = gen_to_be_invoked.GetLoginStatus( ); LuaAPI.xlua_pushinteger(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetUserId(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { long gen_ret = gen_to_be_invoked.GetUserId( ); LuaAPI.lua_pushint64(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetUserName(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string gen_ret = gen_to_be_invoked.GetUserName( ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetToken(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string gen_ret = gen_to_be_invoked.GetToken( ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_SetToken(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _token = LuaAPI.lua_tostring(L, 2); int _deadline = LuaAPI.xlua_tointeger(L, 3); gen_to_be_invoked.SetToken( _token, _deadline ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_SetUserInfo(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _userId = LuaAPI.lua_tostring(L, 2); string _userName = LuaAPI.lua_tostring(L, 3); gen_to_be_invoked.SetUserInfo( _userId, _userName ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_CheckGuestAccount(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.CheckGuestAccount( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_ChangeAccount(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.ChangeAccount( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_StartAccountHome(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.StartAccountHome( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_StartForum(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.StartForum( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_ShowToolBar(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.ShowToolBar( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_HideToolBar(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.HideToolBar( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_IsCydia(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { bool gen_ret = gen_to_be_invoked.IsCydia( ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_IsPad(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { bool gen_ret = gen_to_be_invoked.IsPad( ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_IsHdVersion(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { bool gen_ret = gen_to_be_invoked.IsHdVersion( ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_StartWebView(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _strURL = LuaAPI.lua_tostring(L, 2); gen_to_be_invoked.StartWebView( _strURL ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_OpenUrl(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _url = LuaAPI.lua_tostring(L, 2); gen_to_be_invoked.OpenUrl( _url ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_SendWeibo(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _content = LuaAPI.lua_tostring(L, 2); gen_to_be_invoked.SendWeibo( _content ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_SendWeChat(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _content = LuaAPI.lua_tostring(L, 2); gen_to_be_invoked.SendWeChat( _content ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetMemInfo(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { long gen_ret = gen_to_be_invoked.GetMemInfo( ); LuaAPI.lua_pushint64(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetUDID(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string gen_ret = gen_to_be_invoked.GetUDID( ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Voice_GetFileLength(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { int gen_ret = gen_to_be_invoked.Voice_GetFileLength( ); LuaAPI.xlua_pushinteger(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Voice_GetVolume(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { int gen_ret = gen_to_be_invoked.Voice_GetVolume( ); LuaAPI.xlua_pushinteger(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Voice_Start(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { bool _record = LuaAPI.lua_toboolean(L, 2); string _filename = LuaAPI.lua_tostring(L, 3); bool _recognize = LuaAPI.lua_toboolean(L, 4); bool gen_ret = gen_to_be_invoked.Voice_Start( _record, _filename, _recognize ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Voice_Stop(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Voice_Stop( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Voice_GetAsrText(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string gen_ret = gen_to_be_invoked.Voice_GetAsrText( ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_InitLogSystem(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _filename = LuaAPI.lua_tostring(L, 2); gen_to_be_invoked.InitLogSystem( _filename ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_MonitorBatteryState(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.MonitorBatteryState( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_OpenAlbum(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { string _fileNameBig = LuaAPI.lua_tostring(L, 2); string _fileNameSmall = LuaAPI.lua_tostring(L, 3); int _scaleFactorBig = LuaAPI.xlua_tointeger(L, 4); int _scaleFactorSmall = LuaAPI.xlua_tointeger(L, 5); string _resultCode = LuaAPI.lua_tostring(L, 6); gen_to_be_invoked.OpenAlbum( _fileNameBig, _fileNameSmall, _scaleFactorBig, _scaleFactorSmall, _resultCode ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_StartScanCode(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.Platform.Interface gen_to_be_invoked = (Game.Platform.Interface)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.StartScanCode( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_Instance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); translator.Push(L, Game.Platform.Interface.Instance); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } } } <file_sep>namespace AssetManager { using System; using System.IO; using UnityEngine; using UnityEditor; using System.Linq; using Sirenix.OdinInspector; using System.Collections.Generic; using Sirenix.Utilities.Editor; using System.Text.RegularExpressions; using System.Text; [Serializable] public class FileNameCheckerInfo : CheckerInfo { [LabelText("检查目录列表")] public List<Folder> PathList = new List<Folder>(); [Serializable] public class Folder { [FolderPath(RequireValidPath = true)] public string Path; } class IllegalFile { public string Path; public bool HasEmpty;//包含空字符 public StringBuilder IllegalFlag; //非法字符 } [OnInspectorGUI] void OnInspectorGUI() { GUILayout.Space(15f); if (_illegalFileInfos != null) SirenixEditorGUI.MessageBox(string.Format("异常文件数量{0}个", _illegalFileInfos.Count), MessageType.Info); SirenixEditorGUI.BeginHorizontalToolbar(); GUILayout.Label("文件名", SirenixGUIStyles.BoldLabel, GUILayout.Width(650)); GUILayout.Label("包含空字符", SirenixGUIStyles.BoldLabel); GUILayout.Label("非法字符", SirenixGUIStyles.BoldLabel); SirenixEditorGUI.EndHorizontalToolbar(); if (_illegalFileInfos == null) return; GUILayout.Space(-5); SirenixEditorGUI.BeginBox(); for (int i = 0; i < _illegalFileInfos.Count; i++) { var item = _illegalFileInfos[i]; EditorGUILayout.BeginHorizontal(); GUILayout.Label(item.Path, SirenixGUIStyles.Label, GUILayout.Width(650)); GUILayout.Label(item.HasEmpty.ToString(), SirenixGUIStyles.LabelCentered, GUILayout.Width(50)); GUILayout.Label(item.IllegalFlag.ToString(), SirenixGUIStyles.LabelCentered); EditorGUILayout.EndHorizontal(); if (i + 1 != _illegalFileInfos.Count) { GUILayout.Space(3); SirenixEditorGUI.HorizontalLineSeparator(); } } SirenixEditorGUI.EndBox(); } public FileNameCheckerInfo(string name) : base(name) { } const string _regex1 = @"[\s]"; const string _regex2 = @"[^A-Za-z_0-9]"; List<IllegalFile> _illegalFileInfos = new List<IllegalFile>(); public override void CheckAsset() { ClearAsset(); List<string> files = new List<string>(); for (int i = 0; i < PathList.Count; i++) { string path = GetAbsPath(PathList[i].Path); if (!Directory.Exists(path)) continue; files.AddRange(Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)); EditorUtility.DisplayProgressBar("获取文件", PathList[i].Path, (i + 1f) / PathList.Count); } files.RemoveAll(f => f.EndsWith(".meta")); float count = 0; foreach (var f in files) { string fileName = System.IO.Path.GetFileNameWithoutExtension(f); EditorUtility.DisplayProgressBar("文件命名检查", fileName, ++count / files.Count); var resutlt1 = Regex.Matches(fileName, _regex1); var resutlt2 = Regex.Matches(fileName, _regex2); if (resutlt1.Count == 0 && resutlt2.Count == 0) continue; IllegalFile illegal = new IllegalFile(); illegal.Path = GetUnityPath(f); illegal.HasEmpty = resutlt1.Count > 0; foreach (var item in resutlt2) { if (illegal.IllegalFlag == null) { illegal.IllegalFlag = new StringBuilder(); illegal.IllegalFlag.AppendFormat("{0}", item); } else { illegal.IllegalFlag.AppendFormat(" {0}", item); } } _illegalFileInfos.Add(illegal); } EditorUtility.UnloadUnusedAssetsImmediate(); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } public override void ClearAsset() { base.ClearAsset(); if (_illegalFileInfos == null) _illegalFileInfos = new List<IllegalFile>(); _illegalFileInfos.Clear(); } } }<file_sep>using UnityEngine; using UnityEditor; using System.Collections.Generic; using Flux; using System; namespace FluxEditor { public class FEventEditor : FEditor { public FTrackEditor TrackEditor { get { return (FTrackEditor)Owner; } } public FEvent Evt { get { return (FEvent)Obj; } } private int _mouseOffsetFrames; private bool _isSingleFrame = false; private GUIStyle _singleFrameStyle = null; private Vector2 _singleSize; protected Rect _eventRect; public override FSequenceEditor SequenceEditor { get { return TrackEditor != null ? TrackEditor.SequenceEditor : null; } } public override float Height { get { return FTrackEditor.DEFAULT_TRACK_HEIGHT; } } public override void Init(FObject obj, FEditor owner) { base.Init(obj, owner); Type evtType = obj.GetType(); object[] customAttributes = evtType.GetCustomAttributes(typeof(FEventAttribute), false); if (customAttributes.Length > 0) _isSingleFrame = ((FEventAttribute)customAttributes[0]).isSingleFrame; if (_isSingleFrame && Evt.FrameRange.Length != 1) { FrameRange range = Evt.FrameRange; range.Length = 1; Evt.FrameRange = range; } if (_singleFrameStyle == null) _singleFrameStyle = FUtility.GetFluxSkin().GetStyle("SingleFrame"); GUIContent singleWidth = new GUIContent(FUtility.GetFluxTexture("SingleFrame_Active.png")); _singleSize = _singleFrameStyle.CalcSize(singleWidth); } public override void Render(Rect rect, float headerWidth) { } // pixelsPerFrame can be calculated from rect and viewRange, but being cached on a higher level public void Render(Rect rect, FrameRange viewRange, float pixelsPerFrame, FrameRange validKeyframeRange) { Rect = rect; _eventRect = rect; int eventStartFrame = Mathf.Max(Evt.Start, viewRange.Start); int eventEndFrame = Mathf.Min(Evt.End, viewRange.End); // _eventRect.xMin = Evt.Start * pixelsPerFrame; // _eventRect.xMax = Evt.End * pixelsPerFrame; _eventRect.xMin = SequenceEditor.GetXForFrame(eventStartFrame); _eventRect.xMax = SequenceEditor.GetXForFrame(eventEndFrame); // _eventRect.xMin += (eventStartFrame-viewRange.Start) * pixelsPerFrame; // first set the start // _eventRect.xMax = _eventRect.xMin + Mathf.Max( 4, (eventEndFrame-eventStartFrame) * pixelsPerFrame ); // then width if (_eventRect.Contains(Event.current.mousePosition)) SequenceEditor.SetMouseHover(Event.current.mousePosition.x, this); RenderEvent(viewRange, validKeyframeRange); } private int _leftHandleGuiId = 0; private int _rightHandleGuiId = 0; public override void ReserveGuiIds() { base.ReserveGuiIds(); _leftHandleGuiId = EditorGUIUtility.GetControlID(FocusType.Passive); _rightHandleGuiId = EditorGUIUtility.GetControlID(FocusType.Passive); } protected virtual void RenderEvent(FrameRange viewRange, FrameRange validKeyframeRange) { if (_isSingleFrame) SingleFrameRender(viewRange, validKeyframeRange); else RangeFrameRender(viewRange, validKeyframeRange); } private void RangeFrameRender(FrameRange viewRange, FrameRange validKeyframeRange) { bool leftHandleVisible = viewRange.Contains(Evt.Start); bool rightHandleVisible = viewRange.Contains(Evt.End); Rect leftHandleRect = _eventRect; leftHandleRect.width = 4; Rect rightHandleRect = _eventRect; rightHandleRect.xMin = rightHandleRect.xMax - 4; if (leftHandleVisible && IsSelected) EditorGUIUtility.AddCursorRect(leftHandleRect, MouseCursor.ResizeHorizontal, _leftHandleGuiId); if (rightHandleVisible && IsSelected) EditorGUIUtility.AddCursorRect(rightHandleRect, MouseCursor.ResizeHorizontal, _rightHandleGuiId); // if( SequenceEditor.EditorDragged == this ) // { // Rect editorDraggedRect = _eventRect; // editorDraggedRect.y = -Offset.value.y; // // SequenceEditor.EditorDraggedRect = editorDraggedRect; // // SequenceEditor.Repaint(); // } switch (Event.current.type) { case EventType.Repaint: if (!viewRange.Overlaps(Evt.FrameRange)) { break; } GUIStyle evtStyle = GetEventStyle(); GUI.backgroundColor = GetColor(); evtStyle.Draw(_eventRect, _isSelected, _isSelected, false, false); string text = Evt.Text; if (text != null) { GUIStyle style = GetTextStyle(); Vector2 size = style.CalcSize(new GUIContent(text)); Rect rect = _eventRect; rect.size = size; GUI.Label(rect, text, GetTextStyle()); } break; case EventType.MouseDown: if (EditorGUIUtility.hotControl == 0 && IsSelected && !Event.current.control && !Event.current.shift) { Vector2 mousePos = Event.current.mousePosition; if (Event.current.button == 0) // left click? { if (rightHandleVisible && rightHandleRect.Contains(mousePos)) { EditorGUIUtility.hotControl = _rightHandleGuiId; // keyframeOnSelect = evt.Start; Event.current.Use(); } else if (leftHandleVisible && leftHandleRect.Contains(mousePos)) { EditorGUIUtility.hotControl = _leftHandleGuiId; // keyframeOnSelect = evt.End; Event.current.Use(); } else if (_eventRect.Contains(mousePos)) { EditorGUIUtility.hotControl = GuiId; _mouseOffsetFrames = SequenceEditor.GetFrameForX(mousePos.x) - Evt.Start; if (IsSelected) { if (Event.current.control) { SequenceEditor.Deselect(this); } } else { if (Event.current.shift) SequenceEditor.Select(this); else if (!Event.current.control) SequenceEditor.SelectExclusive(this); } Event.current.Use(); } } else if (Event.current.button == 1 && _eventRect.Contains(Event.current.mousePosition)) // right click? { CreateEventContextMenu().ShowAsContext(); Event.current.Use(); } } break; case EventType.MouseUp: if (EditorGUIUtility.hotControl != 0) { if (EditorGUIUtility.hotControl == GuiId || EditorGUIUtility.hotControl == _leftHandleGuiId || EditorGUIUtility.hotControl == _rightHandleGuiId) { EditorGUIUtility.hotControl = 0; Event.current.Use(); SequenceEditor.Repaint(); FinishMovingEventEditors(); } } break; case EventType.MouseDrag: if (EditorGUIUtility.hotControl != 0) { if (EditorGUIUtility.hotControl == GuiId) { // if( !TrackEditor.Rect.Contains( Event.current.mousePosition ) ) // { // SequenceEditor.StartDraggingEditor( this ); // } // else { int t = SequenceEditor.GetFrameForX(Event.current.mousePosition.x) - _mouseOffsetFrames; int delta = t - Evt.Start; SequenceEditor.MoveEvents(delta); } Event.current.Use(); } else if (EditorGUIUtility.hotControl == _leftHandleGuiId || EditorGUIUtility.hotControl == _rightHandleGuiId) { int leftLimit = 0; int rightLimit = 0; bool draggingStart = EditorGUIUtility.hotControl == _leftHandleGuiId; if (draggingStart) { leftLimit = validKeyframeRange.Start; rightLimit = Evt.End - 1; } else { leftLimit = Evt.Start + 1; rightLimit = validKeyframeRange.End; } int t = SequenceEditor.GetFrameForX(Event.current.mousePosition.x); t = Mathf.Clamp(t, leftLimit, rightLimit); int delta = t - (draggingStart ? Evt.Start : Evt.End); if (draggingStart) { int newLength = Evt.Length - delta; if (newLength < Evt.GetMinLength()) { delta += newLength - Evt.GetMinLength(); } if (newLength > Evt.GetMaxLength()) { delta += newLength - Evt.GetMaxLength(); } } else { int newLength = Evt.Length + delta; if (newLength < Evt.GetMinLength()) { delta -= newLength - Evt.GetMinLength(); } if (newLength > Evt.GetMaxLength()) { delta -= newLength - Evt.GetMaxLength(); } } if (delta != 0) { if (draggingStart) SequenceEditor.ResizeEventsLeft(delta); else SequenceEditor.ResizeEventsRight(delta); } Event.current.Use(); } } break; case EventType.Ignore: if (EditorGUIUtility.hotControl == GuiId || EditorGUIUtility.hotControl == _leftHandleGuiId || EditorGUIUtility.hotControl == _rightHandleGuiId) { EditorGUIUtility.hotControl = 0; SequenceEditor.Repaint(); FinishMovingEventEditors(); } break; } } private void SingleFrameRender(FrameRange viewRange, FrameRange validKeyframeRange) { Rect rect = _eventRect; rect.width = 15; rect.x = SequenceEditor.PixelsPerFrame * Evt.Start; FrameRange range = Evt.FrameRange; range.Start = SequenceEditor.GetFrameForX(rect.x); range.End = range.Start + 1 + _mouseOffsetFrames + SequenceEditor.GetFrameForX(rect.width); Evt.FrameRange = range; switch (Event.current.type) { case EventType.Repaint: { if (!viewRange.Overlaps(Evt.FrameRange)) break; _mouseOffsetFrames = 0; GUIStyle evtStyle = _singleFrameStyle; GUI.backgroundColor = Color.white; Rect renderRect = rect; renderRect.x -= 2.5f; evtStyle.Draw(renderRect, _isSelected, _isSelected, false, false); string text = Evt.Text; if (text != null) { GUIStyle style = GetTextStyle(); Vector2 size = style.CalcSize(new GUIContent(text)); rect.size = size; GUI.Label(rect, text, GetTextStyle()); } break; } case EventType.MouseDown: if (EditorGUIUtility.hotControl == 0 && IsSelected && !Event.current.control && !Event.current.shift) { Vector2 mousePos = Event.current.mousePosition; if (Event.current.button == 0) { if (rect.Contains(mousePos)) { EditorGUIUtility.hotControl = GuiId; _mouseOffsetFrames = SequenceEditor.GetFrameForX(mousePos.x) - Evt.Start; if (IsSelected) { if (Event.current.control) { SequenceEditor.Deselect(this); } } else { if (Event.current.shift) SequenceEditor.Select(this); else if (!Event.current.control) SequenceEditor.SelectExclusive(this); } Event.current.Use(); } } else if (Event.current.button == 1 && rect.Contains(Event.current.mousePosition)) // right click? { CreateEventContextMenu().ShowAsContext(); Event.current.Use(); } } break; case EventType.MouseUp: if (EditorGUIUtility.hotControl == GuiId) { EditorGUIUtility.hotControl = 0; Event.current.Use(); SequenceEditor.Repaint(); FinishMovingEventEditors(); } break; case EventType.MouseDrag: if (EditorGUIUtility.hotControl == GuiId) { int t = SequenceEditor.GetFrameForX(Event.current.mousePosition.x) - _mouseOffsetFrames; int delta = t - Evt.Start; if (t < viewRange.Start) t = viewRange.Start; else if (t > viewRange.End - 1) t = viewRange.End - 1; Evt.SingleFrame = t + 1; SequenceEditor.MoveEvents(delta); Event.current.Use(); } break; case EventType.Ignore: if (EditorGUIUtility.hotControl == GuiId) { EditorGUIUtility.hotControl = 0; SequenceEditor.Repaint(); FinishMovingEventEditors(); } break; } } public virtual void OnEventMoved(FrameRange oldFrameRange) { AddEventEditorBeingMoved(this, oldFrameRange); } public virtual void OnEventFinishedMoving(FrameRange oldFrameRange) { } public virtual Color GetColor() { return FluxEditor.FUtility.GetEventColor(Evt.GetType().ToString()); } public virtual GUIStyle GetEventStyle() { return FUtility.GetEventStyle(); } public virtual GUIStyle GetTextStyle() { return EditorStyles.label; } protected virtual GenericMenu CreateEventContextMenu() { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("复制"), false, Copy); menu.AddItem(new GUIContent("剪切"), false, Cut); menu.AddItem(new GUIContent("删除"), false, Delete); return menu; } private void Copy() { SequenceEditor.CopyEditor(this); } private void Cut() { SequenceEditor.CutEditor(this); } private void Delete() { List<FEventEditor> eventEditors = new List<FEventEditor>(); eventEditors.Add(this); SequenceEditor.DestroyEvents(eventEditors); } #region Event editors being moved // holds the event editors being moved / resized, so that we can call a function at the end of the move // with the full change and not just the delta each update. Useful when you have other assets that have // to be changed but you only want to do it at the end (e.g. resize animations, to minimize errors) private static Dictionary<FEventEditor, FrameRange> _eventEditorsBeingMoved = new Dictionary<FEventEditor, FrameRange>(); private static void AddEventEditorBeingMoved(FEventEditor evtEditor, FrameRange oldFrameRange) { if (!_eventEditorsBeingMoved.ContainsKey(evtEditor)) { _eventEditorsBeingMoved.Add(evtEditor, oldFrameRange); } } public static void FinishMovingEventEditors() { Dictionary<FEventEditor, FrameRange>.Enumerator e = _eventEditorsBeingMoved.GetEnumerator(); while (e.MoveNext()) { e.Current.Key.OnEventFinishedMoving(e.Current.Value); } _eventEditorsBeingMoved.Clear(); } #endregion } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class ReplaceObject : Cfg.Skill.Controller { /// <summary> /// 新对象 /// <summary> public readonly string NewObject; /// <summary> /// 相对位置 /// <summary> public Cfg.Vector3 Offset; /// <summary> /// 相对旋转 /// <summary> public Cfg.Vector3 EulerAngles; public ReplaceObject(DataStream data) : base(data) { this.NewObject = data.GetString(); this.Offset = new Vector3(data); this.EulerAngles = new Vector3(data); } } } <file_sep>local allCfgs = nil local CfgManager = {} -- 配置名列表 -- CfgManager.NameTable={} function CfgManager.Init() allCfgs = require "Cfg.Config" for k, _ in pairs(allCfgs) do CfgManager.NameTable[k] = k end end function CfgManager.GetConfig(cfgName) if allCfgs then return allCfgs[cfgName] end return nil end return CfgManager<file_sep>#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using System; namespace XLua { public partial class ObjectTranslator { class IniterAdderXLuaTestPedding { static IniterAdderXLuaTestPedding() { LuaEnv.AddIniter(Init); } static void Init(LuaEnv luaenv, ObjectTranslator translator) { translator.RegisterPushAndGetAndUpdate<XLuaTest.Pedding>(translator.PushXLuaTestPedding, translator.Get, translator.UpdateXLuaTestPedding); translator.RegisterPushAndGetAndUpdate<XLuaTest.MyStruct>(translator.PushXLuaTestMyStruct, translator.Get, translator.UpdateXLuaTestMyStruct); translator.RegisterPushAndGetAndUpdate<PushAsTableStruct>(translator.PushPushAsTableStruct, translator.Get, translator.UpdatePushAsTableStruct); translator.RegisterPushAndGetAndUpdate<UnityEngine.Vector2>(translator.PushUnityEngineVector2, translator.Get, translator.UpdateUnityEngineVector2); translator.RegisterPushAndGetAndUpdate<UnityEngine.Vector3>(translator.PushUnityEngineVector3, translator.Get, translator.UpdateUnityEngineVector3); translator.RegisterPushAndGetAndUpdate<UnityEngine.Vector4>(translator.PushUnityEngineVector4, translator.Get, translator.UpdateUnityEngineVector4); translator.RegisterPushAndGetAndUpdate<UnityEngine.Color>(translator.PushUnityEngineColor, translator.Get, translator.UpdateUnityEngineColor); translator.RegisterPushAndGetAndUpdate<UnityEngine.Quaternion>(translator.PushUnityEngineQuaternion, translator.Get, translator.UpdateUnityEngineQuaternion); translator.RegisterPushAndGetAndUpdate<UnityEngine.Ray>(translator.PushUnityEngineRay, translator.Get, translator.UpdateUnityEngineRay); translator.RegisterPushAndGetAndUpdate<UnityEngine.Bounds>(translator.PushUnityEngineBounds, translator.Get, translator.UpdateUnityEngineBounds); translator.RegisterPushAndGetAndUpdate<UnityEngine.Ray2D>(translator.PushUnityEngineRay2D, translator.Get, translator.UpdateUnityEngineRay2D); translator.RegisterPushAndGetAndUpdate<UnityEngine.LightType>(translator.PushUnityEngineLightType, translator.Get, translator.UpdateUnityEngineLightType); translator.RegisterPushAndGetAndUpdate<UnityEngine.CameraClearFlags>(translator.PushUnityEngineCameraClearFlags, translator.Get, translator.UpdateUnityEngineCameraClearFlags); translator.RegisterPushAndGetAndUpdate<UnityEngine.KeyCode>(translator.PushUnityEngineKeyCode, translator.Get, translator.UpdateUnityEngineKeyCode); translator.RegisterPushAndGetAndUpdate<UnityEngine.Space>(translator.PushUnityEngineSpace, translator.Get, translator.UpdateUnityEngineSpace); translator.RegisterPushAndGetAndUpdate<UnityEngine.AnimationBlendMode>(translator.PushUnityEngineAnimationBlendMode, translator.Get, translator.UpdateUnityEngineAnimationBlendMode); translator.RegisterPushAndGetAndUpdate<UnityEngine.QueueMode>(translator.PushUnityEngineQueueMode, translator.Get, translator.UpdateUnityEngineQueueMode); translator.RegisterPushAndGetAndUpdate<UnityEngine.PlayMode>(translator.PushUnityEnginePlayMode, translator.Get, translator.UpdateUnityEnginePlayMode); translator.RegisterPushAndGetAndUpdate<UnityEngine.WrapMode>(translator.PushUnityEngineWrapMode, translator.Get, translator.UpdateUnityEngineWrapMode); translator.RegisterPushAndGetAndUpdate<UnityEngine.BlendWeights>(translator.PushUnityEngineBlendWeights, translator.Get, translator.UpdateUnityEngineBlendWeights); translator.RegisterPushAndGetAndUpdate<UnityEngine.EventSystems.EventTriggerType>(translator.PushUnityEngineEventSystemsEventTriggerType, translator.Get, translator.UpdateUnityEngineEventSystemsEventTriggerType); translator.RegisterPushAndGetAndUpdate<Game.ResourceLoadType>(translator.PushGameResourceLoadType, translator.Get, translator.UpdateGameResourceLoadType); translator.RegisterPushAndGetAndUpdate<XLuaTest.MyEnum>(translator.PushXLuaTestMyEnum, translator.Get, translator.UpdateXLuaTestMyEnum); } } static IniterAdderXLuaTestPedding s_IniterAdderXLuaTestPedding_dumb_obj = new IniterAdderXLuaTestPedding(); static IniterAdderXLuaTestPedding IniterAdderXLuaTestPedding_dumb_obj {get{return s_IniterAdderXLuaTestPedding_dumb_obj;}} int XLuaTestPedding_TypeID = -1; public void PushXLuaTestPedding(RealStatePtr L, XLuaTest.Pedding val) { if (XLuaTestPedding_TypeID == -1) { bool is_first; XLuaTestPedding_TypeID = getTypeId(L, typeof(XLuaTest.Pedding), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 1, XLuaTestPedding_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for XLuaTest.Pedding ,value="+val); } } public void Get(RealStatePtr L, int index, out XLuaTest.Pedding val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != XLuaTestPedding_TypeID) { throw new Exception("invalid userdata for XLuaTest.Pedding"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for XLuaTest.Pedding"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (XLuaTest.Pedding)objectCasters.GetCaster(typeof(XLuaTest.Pedding))(L, index, null); } } public void UpdateXLuaTestPedding(RealStatePtr L, int index, XLuaTest.Pedding val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != XLuaTestPedding_TypeID) { throw new Exception("invalid userdata for XLuaTest.Pedding"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for XLuaTest.Pedding ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int XLuaTestMyStruct_TypeID = -1; public void PushXLuaTestMyStruct(RealStatePtr L, XLuaTest.MyStruct val) { if (XLuaTestMyStruct_TypeID == -1) { bool is_first; XLuaTestMyStruct_TypeID = getTypeId(L, typeof(XLuaTest.MyStruct), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 25, XLuaTestMyStruct_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for XLuaTest.MyStruct ,value="+val); } } public void Get(RealStatePtr L, int index, out XLuaTest.MyStruct val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != XLuaTestMyStruct_TypeID) { throw new Exception("invalid userdata for XLuaTest.MyStruct"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for XLuaTest.MyStruct"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (XLuaTest.MyStruct)objectCasters.GetCaster(typeof(XLuaTest.MyStruct))(L, index, null); } } public void UpdateXLuaTestMyStruct(RealStatePtr L, int index, XLuaTest.MyStruct val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != XLuaTestMyStruct_TypeID) { throw new Exception("invalid userdata for XLuaTest.MyStruct"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for XLuaTest.MyStruct ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int PushAsTableStruct_TypeID = -1; public void PushPushAsTableStruct(RealStatePtr L, PushAsTableStruct val) { if (PushAsTableStruct_TypeID == -1) { bool is_first; PushAsTableStruct_TypeID = getTypeId(L, typeof(PushAsTableStruct), out is_first); } var translator = this; LuaAPI.xlua_pushcstable(L, 2, PushAsTableStruct_TypeID); LuaAPI.xlua_pushasciistring(L, "x"); LuaAPI.xlua_pushinteger(L, val.x); LuaAPI.lua_rawset(L, -3); LuaAPI.xlua_pushasciistring(L, "y"); LuaAPI.xlua_pushinteger(L, val.y); LuaAPI.lua_rawset(L, -3); } public void Get(RealStatePtr L, int index, out PushAsTableStruct val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != PushAsTableStruct_TypeID) { throw new Exception("invalid userdata for PushAsTableStruct"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for PushAsTableStruct"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (PushAsTableStruct)objectCasters.GetCaster(typeof(PushAsTableStruct))(L, index, null); } } public void UpdatePushAsTableStruct(RealStatePtr L, int index, PushAsTableStruct val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TTABLE) { return; } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineVector2_TypeID = -1; public void PushUnityEngineVector2(RealStatePtr L, UnityEngine.Vector2 val) { if (UnityEngineVector2_TypeID == -1) { bool is_first; UnityEngineVector2_TypeID = getTypeId(L, typeof(UnityEngine.Vector2), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 8, UnityEngineVector2_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for UnityEngine.Vector2 ,value="+val); } } public void Get(RealStatePtr L, int index, out UnityEngine.Vector2 val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineVector2_TypeID) { throw new Exception("invalid userdata for UnityEngine.Vector2"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for UnityEngine.Vector2"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (UnityEngine.Vector2)objectCasters.GetCaster(typeof(UnityEngine.Vector2))(L, index, null); } } public void UpdateUnityEngineVector2(RealStatePtr L, int index, UnityEngine.Vector2 val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineVector2_TypeID) { throw new Exception("invalid userdata for UnityEngine.Vector2"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for UnityEngine.Vector2 ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineVector3_TypeID = -1; public void PushUnityEngineVector3(RealStatePtr L, UnityEngine.Vector3 val) { if (UnityEngineVector3_TypeID == -1) { bool is_first; UnityEngineVector3_TypeID = getTypeId(L, typeof(UnityEngine.Vector3), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 12, UnityEngineVector3_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for UnityEngine.Vector3 ,value="+val); } } public void Get(RealStatePtr L, int index, out UnityEngine.Vector3 val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineVector3_TypeID) { throw new Exception("invalid userdata for UnityEngine.Vector3"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for UnityEngine.Vector3"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (UnityEngine.Vector3)objectCasters.GetCaster(typeof(UnityEngine.Vector3))(L, index, null); } } public void UpdateUnityEngineVector3(RealStatePtr L, int index, UnityEngine.Vector3 val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineVector3_TypeID) { throw new Exception("invalid userdata for UnityEngine.Vector3"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for UnityEngine.Vector3 ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineVector4_TypeID = -1; public void PushUnityEngineVector4(RealStatePtr L, UnityEngine.Vector4 val) { if (UnityEngineVector4_TypeID == -1) { bool is_first; UnityEngineVector4_TypeID = getTypeId(L, typeof(UnityEngine.Vector4), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 16, UnityEngineVector4_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for UnityEngine.Vector4 ,value="+val); } } public void Get(RealStatePtr L, int index, out UnityEngine.Vector4 val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineVector4_TypeID) { throw new Exception("invalid userdata for UnityEngine.Vector4"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for UnityEngine.Vector4"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (UnityEngine.Vector4)objectCasters.GetCaster(typeof(UnityEngine.Vector4))(L, index, null); } } public void UpdateUnityEngineVector4(RealStatePtr L, int index, UnityEngine.Vector4 val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineVector4_TypeID) { throw new Exception("invalid userdata for UnityEngine.Vector4"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for UnityEngine.Vector4 ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineColor_TypeID = -1; public void PushUnityEngineColor(RealStatePtr L, UnityEngine.Color val) { if (UnityEngineColor_TypeID == -1) { bool is_first; UnityEngineColor_TypeID = getTypeId(L, typeof(UnityEngine.Color), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 16, UnityEngineColor_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for UnityEngine.Color ,value="+val); } } public void Get(RealStatePtr L, int index, out UnityEngine.Color val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineColor_TypeID) { throw new Exception("invalid userdata for UnityEngine.Color"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for UnityEngine.Color"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (UnityEngine.Color)objectCasters.GetCaster(typeof(UnityEngine.Color))(L, index, null); } } public void UpdateUnityEngineColor(RealStatePtr L, int index, UnityEngine.Color val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineColor_TypeID) { throw new Exception("invalid userdata for UnityEngine.Color"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for UnityEngine.Color ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineQuaternion_TypeID = -1; public void PushUnityEngineQuaternion(RealStatePtr L, UnityEngine.Quaternion val) { if (UnityEngineQuaternion_TypeID == -1) { bool is_first; UnityEngineQuaternion_TypeID = getTypeId(L, typeof(UnityEngine.Quaternion), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 16, UnityEngineQuaternion_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for UnityEngine.Quaternion ,value="+val); } } public void Get(RealStatePtr L, int index, out UnityEngine.Quaternion val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineQuaternion_TypeID) { throw new Exception("invalid userdata for UnityEngine.Quaternion"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for UnityEngine.Quaternion"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (UnityEngine.Quaternion)objectCasters.GetCaster(typeof(UnityEngine.Quaternion))(L, index, null); } } public void UpdateUnityEngineQuaternion(RealStatePtr L, int index, UnityEngine.Quaternion val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineQuaternion_TypeID) { throw new Exception("invalid userdata for UnityEngine.Quaternion"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for UnityEngine.Quaternion ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineRay_TypeID = -1; public void PushUnityEngineRay(RealStatePtr L, UnityEngine.Ray val) { if (UnityEngineRay_TypeID == -1) { bool is_first; UnityEngineRay_TypeID = getTypeId(L, typeof(UnityEngine.Ray), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 24, UnityEngineRay_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for UnityEngine.Ray ,value="+val); } } public void Get(RealStatePtr L, int index, out UnityEngine.Ray val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineRay_TypeID) { throw new Exception("invalid userdata for UnityEngine.Ray"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for UnityEngine.Ray"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (UnityEngine.Ray)objectCasters.GetCaster(typeof(UnityEngine.Ray))(L, index, null); } } public void UpdateUnityEngineRay(RealStatePtr L, int index, UnityEngine.Ray val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineRay_TypeID) { throw new Exception("invalid userdata for UnityEngine.Ray"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for UnityEngine.Ray ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineBounds_TypeID = -1; public void PushUnityEngineBounds(RealStatePtr L, UnityEngine.Bounds val) { if (UnityEngineBounds_TypeID == -1) { bool is_first; UnityEngineBounds_TypeID = getTypeId(L, typeof(UnityEngine.Bounds), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 24, UnityEngineBounds_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for UnityEngine.Bounds ,value="+val); } } public void Get(RealStatePtr L, int index, out UnityEngine.Bounds val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineBounds_TypeID) { throw new Exception("invalid userdata for UnityEngine.Bounds"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for UnityEngine.Bounds"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (UnityEngine.Bounds)objectCasters.GetCaster(typeof(UnityEngine.Bounds))(L, index, null); } } public void UpdateUnityEngineBounds(RealStatePtr L, int index, UnityEngine.Bounds val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineBounds_TypeID) { throw new Exception("invalid userdata for UnityEngine.Bounds"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for UnityEngine.Bounds ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineRay2D_TypeID = -1; public void PushUnityEngineRay2D(RealStatePtr L, UnityEngine.Ray2D val) { if (UnityEngineRay2D_TypeID == -1) { bool is_first; UnityEngineRay2D_TypeID = getTypeId(L, typeof(UnityEngine.Ray2D), out is_first); } IntPtr buff = LuaAPI.xlua_pushstruct(L, 16, UnityEngineRay2D_TypeID); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail fail for UnityEngine.Ray2D ,value="+val); } } public void Get(RealStatePtr L, int index, out UnityEngine.Ray2D val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineRay2D_TypeID) { throw new Exception("invalid userdata for UnityEngine.Ray2D"); } IntPtr buff = LuaAPI.lua_touserdata(L, index);if (!CopyByValue.UnPack(buff, 0, out val)) { throw new Exception("unpack fail for UnityEngine.Ray2D"); } } else if (type ==LuaTypes.LUA_TTABLE) { CopyByValue.UnPack(this, L, index, out val); } else { val = (UnityEngine.Ray2D)objectCasters.GetCaster(typeof(UnityEngine.Ray2D))(L, index, null); } } public void UpdateUnityEngineRay2D(RealStatePtr L, int index, UnityEngine.Ray2D val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineRay2D_TypeID) { throw new Exception("invalid userdata for UnityEngine.Ray2D"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, val)) { throw new Exception("pack fail for UnityEngine.Ray2D ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineLightType_TypeID = -1; int UnityEngineLightType_EnumRef = -1; public void PushUnityEngineLightType(RealStatePtr L, UnityEngine.LightType val) { if (UnityEngineLightType_TypeID == -1) { bool is_first; UnityEngineLightType_TypeID = getTypeId(L, typeof(UnityEngine.LightType), out is_first); if (UnityEngineLightType_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.LightType)); UnityEngineLightType_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEngineLightType_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEngineLightType_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.LightType ,value="+val); } LuaAPI.lua_getref(L, UnityEngineLightType_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.LightType val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineLightType_TypeID) { throw new Exception("invalid userdata for UnityEngine.LightType"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.LightType"); } val = (UnityEngine.LightType)e; } else { val = (UnityEngine.LightType)objectCasters.GetCaster(typeof(UnityEngine.LightType))(L, index, null); } } public void UpdateUnityEngineLightType(RealStatePtr L, int index, UnityEngine.LightType val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineLightType_TypeID) { throw new Exception("invalid userdata for UnityEngine.LightType"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.LightType ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineCameraClearFlags_TypeID = -1; int UnityEngineCameraClearFlags_EnumRef = -1; public void PushUnityEngineCameraClearFlags(RealStatePtr L, UnityEngine.CameraClearFlags val) { if (UnityEngineCameraClearFlags_TypeID == -1) { bool is_first; UnityEngineCameraClearFlags_TypeID = getTypeId(L, typeof(UnityEngine.CameraClearFlags), out is_first); if (UnityEngineCameraClearFlags_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.CameraClearFlags)); UnityEngineCameraClearFlags_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEngineCameraClearFlags_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEngineCameraClearFlags_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.CameraClearFlags ,value="+val); } LuaAPI.lua_getref(L, UnityEngineCameraClearFlags_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.CameraClearFlags val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineCameraClearFlags_TypeID) { throw new Exception("invalid userdata for UnityEngine.CameraClearFlags"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.CameraClearFlags"); } val = (UnityEngine.CameraClearFlags)e; } else { val = (UnityEngine.CameraClearFlags)objectCasters.GetCaster(typeof(UnityEngine.CameraClearFlags))(L, index, null); } } public void UpdateUnityEngineCameraClearFlags(RealStatePtr L, int index, UnityEngine.CameraClearFlags val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineCameraClearFlags_TypeID) { throw new Exception("invalid userdata for UnityEngine.CameraClearFlags"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.CameraClearFlags ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineKeyCode_TypeID = -1; int UnityEngineKeyCode_EnumRef = -1; public void PushUnityEngineKeyCode(RealStatePtr L, UnityEngine.KeyCode val) { if (UnityEngineKeyCode_TypeID == -1) { bool is_first; UnityEngineKeyCode_TypeID = getTypeId(L, typeof(UnityEngine.KeyCode), out is_first); if (UnityEngineKeyCode_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.KeyCode)); UnityEngineKeyCode_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEngineKeyCode_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEngineKeyCode_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.KeyCode ,value="+val); } LuaAPI.lua_getref(L, UnityEngineKeyCode_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.KeyCode val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineKeyCode_TypeID) { throw new Exception("invalid userdata for UnityEngine.KeyCode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.KeyCode"); } val = (UnityEngine.KeyCode)e; } else { val = (UnityEngine.KeyCode)objectCasters.GetCaster(typeof(UnityEngine.KeyCode))(L, index, null); } } public void UpdateUnityEngineKeyCode(RealStatePtr L, int index, UnityEngine.KeyCode val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineKeyCode_TypeID) { throw new Exception("invalid userdata for UnityEngine.KeyCode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.KeyCode ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineSpace_TypeID = -1; int UnityEngineSpace_EnumRef = -1; public void PushUnityEngineSpace(RealStatePtr L, UnityEngine.Space val) { if (UnityEngineSpace_TypeID == -1) { bool is_first; UnityEngineSpace_TypeID = getTypeId(L, typeof(UnityEngine.Space), out is_first); if (UnityEngineSpace_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.Space)); UnityEngineSpace_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEngineSpace_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEngineSpace_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.Space ,value="+val); } LuaAPI.lua_getref(L, UnityEngineSpace_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.Space val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineSpace_TypeID) { throw new Exception("invalid userdata for UnityEngine.Space"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.Space"); } val = (UnityEngine.Space)e; } else { val = (UnityEngine.Space)objectCasters.GetCaster(typeof(UnityEngine.Space))(L, index, null); } } public void UpdateUnityEngineSpace(RealStatePtr L, int index, UnityEngine.Space val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineSpace_TypeID) { throw new Exception("invalid userdata for UnityEngine.Space"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.Space ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineAnimationBlendMode_TypeID = -1; int UnityEngineAnimationBlendMode_EnumRef = -1; public void PushUnityEngineAnimationBlendMode(RealStatePtr L, UnityEngine.AnimationBlendMode val) { if (UnityEngineAnimationBlendMode_TypeID == -1) { bool is_first; UnityEngineAnimationBlendMode_TypeID = getTypeId(L, typeof(UnityEngine.AnimationBlendMode), out is_first); if (UnityEngineAnimationBlendMode_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.AnimationBlendMode)); UnityEngineAnimationBlendMode_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEngineAnimationBlendMode_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEngineAnimationBlendMode_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.AnimationBlendMode ,value="+val); } LuaAPI.lua_getref(L, UnityEngineAnimationBlendMode_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.AnimationBlendMode val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineAnimationBlendMode_TypeID) { throw new Exception("invalid userdata for UnityEngine.AnimationBlendMode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.AnimationBlendMode"); } val = (UnityEngine.AnimationBlendMode)e; } else { val = (UnityEngine.AnimationBlendMode)objectCasters.GetCaster(typeof(UnityEngine.AnimationBlendMode))(L, index, null); } } public void UpdateUnityEngineAnimationBlendMode(RealStatePtr L, int index, UnityEngine.AnimationBlendMode val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineAnimationBlendMode_TypeID) { throw new Exception("invalid userdata for UnityEngine.AnimationBlendMode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.AnimationBlendMode ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineQueueMode_TypeID = -1; int UnityEngineQueueMode_EnumRef = -1; public void PushUnityEngineQueueMode(RealStatePtr L, UnityEngine.QueueMode val) { if (UnityEngineQueueMode_TypeID == -1) { bool is_first; UnityEngineQueueMode_TypeID = getTypeId(L, typeof(UnityEngine.QueueMode), out is_first); if (UnityEngineQueueMode_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.QueueMode)); UnityEngineQueueMode_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEngineQueueMode_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEngineQueueMode_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.QueueMode ,value="+val); } LuaAPI.lua_getref(L, UnityEngineQueueMode_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.QueueMode val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineQueueMode_TypeID) { throw new Exception("invalid userdata for UnityEngine.QueueMode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.QueueMode"); } val = (UnityEngine.QueueMode)e; } else { val = (UnityEngine.QueueMode)objectCasters.GetCaster(typeof(UnityEngine.QueueMode))(L, index, null); } } public void UpdateUnityEngineQueueMode(RealStatePtr L, int index, UnityEngine.QueueMode val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineQueueMode_TypeID) { throw new Exception("invalid userdata for UnityEngine.QueueMode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.QueueMode ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEnginePlayMode_TypeID = -1; int UnityEnginePlayMode_EnumRef = -1; public void PushUnityEnginePlayMode(RealStatePtr L, UnityEngine.PlayMode val) { if (UnityEnginePlayMode_TypeID == -1) { bool is_first; UnityEnginePlayMode_TypeID = getTypeId(L, typeof(UnityEngine.PlayMode), out is_first); if (UnityEnginePlayMode_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.PlayMode)); UnityEnginePlayMode_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEnginePlayMode_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEnginePlayMode_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.PlayMode ,value="+val); } LuaAPI.lua_getref(L, UnityEnginePlayMode_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.PlayMode val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEnginePlayMode_TypeID) { throw new Exception("invalid userdata for UnityEngine.PlayMode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.PlayMode"); } val = (UnityEngine.PlayMode)e; } else { val = (UnityEngine.PlayMode)objectCasters.GetCaster(typeof(UnityEngine.PlayMode))(L, index, null); } } public void UpdateUnityEnginePlayMode(RealStatePtr L, int index, UnityEngine.PlayMode val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEnginePlayMode_TypeID) { throw new Exception("invalid userdata for UnityEngine.PlayMode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.PlayMode ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineWrapMode_TypeID = -1; int UnityEngineWrapMode_EnumRef = -1; public void PushUnityEngineWrapMode(RealStatePtr L, UnityEngine.WrapMode val) { if (UnityEngineWrapMode_TypeID == -1) { bool is_first; UnityEngineWrapMode_TypeID = getTypeId(L, typeof(UnityEngine.WrapMode), out is_first); if (UnityEngineWrapMode_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.WrapMode)); UnityEngineWrapMode_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEngineWrapMode_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEngineWrapMode_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.WrapMode ,value="+val); } LuaAPI.lua_getref(L, UnityEngineWrapMode_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.WrapMode val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineWrapMode_TypeID) { throw new Exception("invalid userdata for UnityEngine.WrapMode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.WrapMode"); } val = (UnityEngine.WrapMode)e; } else { val = (UnityEngine.WrapMode)objectCasters.GetCaster(typeof(UnityEngine.WrapMode))(L, index, null); } } public void UpdateUnityEngineWrapMode(RealStatePtr L, int index, UnityEngine.WrapMode val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineWrapMode_TypeID) { throw new Exception("invalid userdata for UnityEngine.WrapMode"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.WrapMode ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineBlendWeights_TypeID = -1; int UnityEngineBlendWeights_EnumRef = -1; public void PushUnityEngineBlendWeights(RealStatePtr L, UnityEngine.BlendWeights val) { if (UnityEngineBlendWeights_TypeID == -1) { bool is_first; UnityEngineBlendWeights_TypeID = getTypeId(L, typeof(UnityEngine.BlendWeights), out is_first); if (UnityEngineBlendWeights_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.BlendWeights)); UnityEngineBlendWeights_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEngineBlendWeights_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEngineBlendWeights_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.BlendWeights ,value="+val); } LuaAPI.lua_getref(L, UnityEngineBlendWeights_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.BlendWeights val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineBlendWeights_TypeID) { throw new Exception("invalid userdata for UnityEngine.BlendWeights"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.BlendWeights"); } val = (UnityEngine.BlendWeights)e; } else { val = (UnityEngine.BlendWeights)objectCasters.GetCaster(typeof(UnityEngine.BlendWeights))(L, index, null); } } public void UpdateUnityEngineBlendWeights(RealStatePtr L, int index, UnityEngine.BlendWeights val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineBlendWeights_TypeID) { throw new Exception("invalid userdata for UnityEngine.BlendWeights"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.BlendWeights ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int UnityEngineEventSystemsEventTriggerType_TypeID = -1; int UnityEngineEventSystemsEventTriggerType_EnumRef = -1; public void PushUnityEngineEventSystemsEventTriggerType(RealStatePtr L, UnityEngine.EventSystems.EventTriggerType val) { if (UnityEngineEventSystemsEventTriggerType_TypeID == -1) { bool is_first; UnityEngineEventSystemsEventTriggerType_TypeID = getTypeId(L, typeof(UnityEngine.EventSystems.EventTriggerType), out is_first); if (UnityEngineEventSystemsEventTriggerType_EnumRef == -1) { Utils.LoadCSTable(L, typeof(UnityEngine.EventSystems.EventTriggerType)); UnityEngineEventSystemsEventTriggerType_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, UnityEngineEventSystemsEventTriggerType_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, UnityEngineEventSystemsEventTriggerType_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for UnityEngine.EventSystems.EventTriggerType ,value="+val); } LuaAPI.lua_getref(L, UnityEngineEventSystemsEventTriggerType_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out UnityEngine.EventSystems.EventTriggerType val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineEventSystemsEventTriggerType_TypeID) { throw new Exception("invalid userdata for UnityEngine.EventSystems.EventTriggerType"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for UnityEngine.EventSystems.EventTriggerType"); } val = (UnityEngine.EventSystems.EventTriggerType)e; } else { val = (UnityEngine.EventSystems.EventTriggerType)objectCasters.GetCaster(typeof(UnityEngine.EventSystems.EventTriggerType))(L, index, null); } } public void UpdateUnityEngineEventSystemsEventTriggerType(RealStatePtr L, int index, UnityEngine.EventSystems.EventTriggerType val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != UnityEngineEventSystemsEventTriggerType_TypeID) { throw new Exception("invalid userdata for UnityEngine.EventSystems.EventTriggerType"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for UnityEngine.EventSystems.EventTriggerType ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int GameResourceLoadType_TypeID = -1; int GameResourceLoadType_EnumRef = -1; public void PushGameResourceLoadType(RealStatePtr L, Game.ResourceLoadType val) { if (GameResourceLoadType_TypeID == -1) { bool is_first; GameResourceLoadType_TypeID = getTypeId(L, typeof(Game.ResourceLoadType), out is_first); if (GameResourceLoadType_EnumRef == -1) { Utils.LoadCSTable(L, typeof(Game.ResourceLoadType)); GameResourceLoadType_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, GameResourceLoadType_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, GameResourceLoadType_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for Game.ResourceLoadType ,value="+val); } LuaAPI.lua_getref(L, GameResourceLoadType_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out Game.ResourceLoadType val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != GameResourceLoadType_TypeID) { throw new Exception("invalid userdata for Game.ResourceLoadType"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for Game.ResourceLoadType"); } val = (Game.ResourceLoadType)e; } else { val = (Game.ResourceLoadType)objectCasters.GetCaster(typeof(Game.ResourceLoadType))(L, index, null); } } public void UpdateGameResourceLoadType(RealStatePtr L, int index, Game.ResourceLoadType val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != GameResourceLoadType_TypeID) { throw new Exception("invalid userdata for Game.ResourceLoadType"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for Game.ResourceLoadType ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } int XLuaTestMyEnum_TypeID = -1; int XLuaTestMyEnum_EnumRef = -1; public void PushXLuaTestMyEnum(RealStatePtr L, XLuaTest.MyEnum val) { if (XLuaTestMyEnum_TypeID == -1) { bool is_first; XLuaTestMyEnum_TypeID = getTypeId(L, typeof(XLuaTest.MyEnum), out is_first); if (XLuaTestMyEnum_EnumRef == -1) { Utils.LoadCSTable(L, typeof(XLuaTest.MyEnum)); XLuaTestMyEnum_EnumRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); } } if (LuaAPI.xlua_tryget_cachedud(L, (int)val, XLuaTestMyEnum_EnumRef) == 1) { return; } IntPtr buff = LuaAPI.xlua_pushstruct(L, 4, XLuaTestMyEnum_TypeID); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail fail for XLuaTest.MyEnum ,value="+val); } LuaAPI.lua_getref(L, XLuaTestMyEnum_EnumRef); LuaAPI.lua_pushvalue(L, -2); LuaAPI.xlua_rawseti(L, -2, (int)val); LuaAPI.lua_pop(L, 1); } public void Get(RealStatePtr L, int index, out XLuaTest.MyEnum val) { LuaTypes type = LuaAPI.lua_type(L, index); if (type == LuaTypes.LUA_TUSERDATA ) { if (LuaAPI.xlua_gettypeid(L, index) != XLuaTestMyEnum_TypeID) { throw new Exception("invalid userdata for XLuaTest.MyEnum"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); int e; if (!CopyByValue.UnPack(buff, 0, out e)) { throw new Exception("unpack fail for XLuaTest.MyEnum"); } val = (XLuaTest.MyEnum)e; } else { val = (XLuaTest.MyEnum)objectCasters.GetCaster(typeof(XLuaTest.MyEnum))(L, index, null); } } public void UpdateXLuaTestMyEnum(RealStatePtr L, int index, XLuaTest.MyEnum val) { if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) { if (LuaAPI.xlua_gettypeid(L, index) != XLuaTestMyEnum_TypeID) { throw new Exception("invalid userdata for XLuaTest.MyEnum"); } IntPtr buff = LuaAPI.lua_touserdata(L, index); if (!CopyByValue.Pack(buff, 0, (int)val)) { throw new Exception("pack fail for XLuaTest.MyEnum ,value="+val); } } else { throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); } } // table cast optimze } public partial class StaticLuaCallbacks { internal static bool __tryArrayGet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int index) { if (type == typeof(XLuaTest.Pedding[])) { XLuaTest.Pedding[] array = obj as XLuaTest.Pedding[]; translator.PushXLuaTestPedding(L, array[index]); return true; } else if (type == typeof(XLuaTest.MyStruct[])) { XLuaTest.MyStruct[] array = obj as XLuaTest.MyStruct[]; translator.PushXLuaTestMyStruct(L, array[index]); return true; } else if (type == typeof(PushAsTableStruct[])) { PushAsTableStruct[] array = obj as PushAsTableStruct[]; translator.PushPushAsTableStruct(L, array[index]); return true; } else if (type == typeof(UnityEngine.Vector2[])) { UnityEngine.Vector2[] array = obj as UnityEngine.Vector2[]; translator.PushUnityEngineVector2(L, array[index]); return true; } else if (type == typeof(UnityEngine.Vector3[])) { UnityEngine.Vector3[] array = obj as UnityEngine.Vector3[]; translator.PushUnityEngineVector3(L, array[index]); return true; } else if (type == typeof(UnityEngine.Vector4[])) { UnityEngine.Vector4[] array = obj as UnityEngine.Vector4[]; translator.PushUnityEngineVector4(L, array[index]); return true; } else if (type == typeof(UnityEngine.Color[])) { UnityEngine.Color[] array = obj as UnityEngine.Color[]; translator.PushUnityEngineColor(L, array[index]); return true; } else if (type == typeof(UnityEngine.Quaternion[])) { UnityEngine.Quaternion[] array = obj as UnityEngine.Quaternion[]; translator.PushUnityEngineQuaternion(L, array[index]); return true; } else if (type == typeof(UnityEngine.Ray[])) { UnityEngine.Ray[] array = obj as UnityEngine.Ray[]; translator.PushUnityEngineRay(L, array[index]); return true; } else if (type == typeof(UnityEngine.Bounds[])) { UnityEngine.Bounds[] array = obj as UnityEngine.Bounds[]; translator.PushUnityEngineBounds(L, array[index]); return true; } else if (type == typeof(UnityEngine.Ray2D[])) { UnityEngine.Ray2D[] array = obj as UnityEngine.Ray2D[]; translator.PushUnityEngineRay2D(L, array[index]); return true; } else if (type == typeof(UnityEngine.LightType[])) { UnityEngine.LightType[] array = obj as UnityEngine.LightType[]; translator.PushUnityEngineLightType(L, array[index]); return true; } else if (type == typeof(UnityEngine.CameraClearFlags[])) { UnityEngine.CameraClearFlags[] array = obj as UnityEngine.CameraClearFlags[]; translator.PushUnityEngineCameraClearFlags(L, array[index]); return true; } else if (type == typeof(UnityEngine.KeyCode[])) { UnityEngine.KeyCode[] array = obj as UnityEngine.KeyCode[]; translator.PushUnityEngineKeyCode(L, array[index]); return true; } else if (type == typeof(UnityEngine.Space[])) { UnityEngine.Space[] array = obj as UnityEngine.Space[]; translator.PushUnityEngineSpace(L, array[index]); return true; } else if (type == typeof(UnityEngine.AnimationBlendMode[])) { UnityEngine.AnimationBlendMode[] array = obj as UnityEngine.AnimationBlendMode[]; translator.PushUnityEngineAnimationBlendMode(L, array[index]); return true; } else if (type == typeof(UnityEngine.QueueMode[])) { UnityEngine.QueueMode[] array = obj as UnityEngine.QueueMode[]; translator.PushUnityEngineQueueMode(L, array[index]); return true; } else if (type == typeof(UnityEngine.PlayMode[])) { UnityEngine.PlayMode[] array = obj as UnityEngine.PlayMode[]; translator.PushUnityEnginePlayMode(L, array[index]); return true; } else if (type == typeof(UnityEngine.WrapMode[])) { UnityEngine.WrapMode[] array = obj as UnityEngine.WrapMode[]; translator.PushUnityEngineWrapMode(L, array[index]); return true; } else if (type == typeof(UnityEngine.BlendWeights[])) { UnityEngine.BlendWeights[] array = obj as UnityEngine.BlendWeights[]; translator.PushUnityEngineBlendWeights(L, array[index]); return true; } else if (type == typeof(UnityEngine.EventSystems.EventTriggerType[])) { UnityEngine.EventSystems.EventTriggerType[] array = obj as UnityEngine.EventSystems.EventTriggerType[]; translator.PushUnityEngineEventSystemsEventTriggerType(L, array[index]); return true; } else if (type == typeof(Game.ResourceLoadType[])) { Game.ResourceLoadType[] array = obj as Game.ResourceLoadType[]; translator.PushGameResourceLoadType(L, array[index]); return true; } else if (type == typeof(XLuaTest.MyEnum[])) { XLuaTest.MyEnum[] array = obj as XLuaTest.MyEnum[]; translator.PushXLuaTestMyEnum(L, array[index]); return true; } return false; } internal static bool __tryArraySet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int array_idx, int obj_idx) { if (type == typeof(XLuaTest.Pedding[])) { XLuaTest.Pedding[] array = obj as XLuaTest.Pedding[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(XLuaTest.MyStruct[])) { XLuaTest.MyStruct[] array = obj as XLuaTest.MyStruct[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(PushAsTableStruct[])) { PushAsTableStruct[] array = obj as PushAsTableStruct[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.Vector2[])) { UnityEngine.Vector2[] array = obj as UnityEngine.Vector2[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.Vector3[])) { UnityEngine.Vector3[] array = obj as UnityEngine.Vector3[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.Vector4[])) { UnityEngine.Vector4[] array = obj as UnityEngine.Vector4[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.Color[])) { UnityEngine.Color[] array = obj as UnityEngine.Color[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.Quaternion[])) { UnityEngine.Quaternion[] array = obj as UnityEngine.Quaternion[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.Ray[])) { UnityEngine.Ray[] array = obj as UnityEngine.Ray[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.Bounds[])) { UnityEngine.Bounds[] array = obj as UnityEngine.Bounds[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.Ray2D[])) { UnityEngine.Ray2D[] array = obj as UnityEngine.Ray2D[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.LightType[])) { UnityEngine.LightType[] array = obj as UnityEngine.LightType[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.CameraClearFlags[])) { UnityEngine.CameraClearFlags[] array = obj as UnityEngine.CameraClearFlags[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.KeyCode[])) { UnityEngine.KeyCode[] array = obj as UnityEngine.KeyCode[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.Space[])) { UnityEngine.Space[] array = obj as UnityEngine.Space[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.AnimationBlendMode[])) { UnityEngine.AnimationBlendMode[] array = obj as UnityEngine.AnimationBlendMode[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.QueueMode[])) { UnityEngine.QueueMode[] array = obj as UnityEngine.QueueMode[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.PlayMode[])) { UnityEngine.PlayMode[] array = obj as UnityEngine.PlayMode[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.WrapMode[])) { UnityEngine.WrapMode[] array = obj as UnityEngine.WrapMode[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.BlendWeights[])) { UnityEngine.BlendWeights[] array = obj as UnityEngine.BlendWeights[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(UnityEngine.EventSystems.EventTriggerType[])) { UnityEngine.EventSystems.EventTriggerType[] array = obj as UnityEngine.EventSystems.EventTriggerType[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(Game.ResourceLoadType[])) { Game.ResourceLoadType[] array = obj as Game.ResourceLoadType[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } else if (type == typeof(XLuaTest.MyEnum[])) { XLuaTest.MyEnum[] array = obj as XLuaTest.MyEnum[]; translator.Get(L, obj_idx, out array[array_idx]); return true; } return false; } } }<file_sep>using UnityEngine; using UnityEditor; using Flux; using System.Collections.Generic; namespace FluxEditor { [CustomEditor(typeof(Flux.FSequenceTrack), true)] public class FSequenceTrackInspector : FTrackInspector { private SerializedProperty _ownerSequence = null; private GUIContent _ownerSequenceUI = new GUIContent("序列"); private List<FSequence> _sequences; private GUIContent[] _sequenceNames; private int _selectedSequenceIndex; public override void OnEnable() { base.OnEnable(); if (target == null) { DestroyImmediate(this); return; } var sequenceTrack = (FSequenceTrack)target; _ownerSequence = serializedObject.FindProperty("_ownerSequence"); _sequences = new List<FSequence>(FUtility.FindObjects<FSequence>()); _sequences.Remove(sequenceTrack.Sequence); _sequences.Sort(delegate (FSequence x, FSequence y) { return x.name.CompareTo(y.name); }); _selectedSequenceIndex = _sequences.FindIndex((select) => select.name == _ownerSequence.objectReferenceValue.name); _sequenceNames = new GUIContent[_sequences.Count]; for (int i = 0; i != _sequences.Count; ++i) { _sequenceNames[i] = new GUIContent(_sequences[i].name); } } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); EditorGUI.BeginChangeCheck(); int index = EditorGUILayout.Popup(_ownerSequenceUI, _selectedSequenceIndex, _sequenceNames); if (EditorGUI.EndChangeCheck()) { _selectedSequenceIndex = index; _ownerSequence.objectReferenceValue = _sequences[index]; } serializedObject.ApplyModifiedProperties(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class StaticHit : Cfg.Skill.Timeline { /// <summary> /// 碰撞区域 /// <summary> public Cfg.Skill.HitZone Zone; /// <summary> /// 触发序列容器ID /// <summary> public readonly int SequeueID; public StaticHit(DataStream data) : base(data) { this.Zone = (Skill.HitZone)data.GetObject(data.GetString()); this.SequeueID = data.GetInt(); } } } <file_sep>namespace AssetManager { using System; using UnityEngine; using System.Collections; using System.Collections.Generic; using Sirenix.OdinInspector; using UnityEditor; using System.IO; using System.Text; using System.Linq; [Serializable] public class AudioClipImportSetting : AssetOption { [ShowInInspector, ReadOnly, PropertyOrder(-1)] public override string Path { get { return base.Path; } set { base.Path = value; } } const string OGG = ".ogg"; const string MP3 = ".mp3"; readonly string PLATFORM = BuildTarget.StandaloneWindows.ToString(); [FoldoutGroup("导入设置")] public AudioClipLoadType LoadType = AudioClipLoadType.DecompressOnLoad; [FoldoutGroup("导入设置")] public bool PreloadAudioData = true; [FoldoutGroup("导入设置")] public AudioCompressionFormat CompressionFormat = AudioCompressionFormat.Vorbis; [FoldoutGroup("导入设置"), Range(0, 100)] public int Quality = 100; [FoldoutGroup("导入设置")] public AudioSampleRateSetting SampleRateSetting = AudioSampleRateSetting.PreserveSampleRate; [Serializable] class AssetInfo { [TableColumnWidth(280), ReadOnly] public string FileName; [TableColumnWidth(150), ReadOnly] public AudioClipLoadType LoadType; [TableColumnWidth(100), ReadOnly] public string PreloadData; [TableColumnWidth(120), ReadOnly] public AudioCompressionFormat CompressFormat; [TableColumnWidth(70), ReadOnly] public string Quality; [TableColumnWidth(150), ReadOnly] public AudioSampleRateSetting SampleSetting; [ReadOnly] public string Other; } /// <summary> /// 按照配置重新导入资源 /// </summary> public override void ReimportAsset() { base.ReimportAsset(); ClearAsset(); List<string> files = new List<string>(Directory.GetFiles(Path, "*.*", SearchOption.AllDirectories) .Where(f => f.EndsWith(OGG) || f.EndsWith(MP3))); for (int i = 0; i < files.Count; i++) { string refPath = files[i].Replace(Application.dataPath, "Assets").Replace("\\", "/"); AudioImporter importer = AudioImporter.GetAtPath(refPath) as AudioImporter; AudioImporterSampleSettings aiss = importer.GetOverrideSampleSettings(PLATFORM); aiss.loadType = LoadType; importer.preloadAudioData = PreloadAudioData; aiss.compressionFormat = CompressionFormat; aiss.quality = Quality / 100f; aiss.sampleRateSetting = SampleRateSetting; importer.SetOverrideSampleSettings(BuildTarget.StandaloneWindows.ToString(), aiss); importer.SetOverrideSampleSettings(BuildTarget.Android.ToString(), aiss); importer.SetOverrideSampleSettings(BuildTarget.iOS.ToString(), aiss); importer.SaveAndReimport(); EditorUtility.DisplayProgressBar("按配置导入音频", refPath, (i + 1f) / files.Count); } EditorUtility.UnloadUnusedAssetsImmediate(); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } } }<file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class CastObject : Cfg.Skill.Controller { /// <summary> /// 是否追踪目标 /// <summary> public readonly bool IsTraceTarget; /// <summary> /// 飞行参数ID,数据有配置表 /// <summary> public readonly int CurveId; /// <summary> /// 是否穿透 /// <summary> public readonly bool PassBody; /// <summary> /// 投射起始偏移 /// <summary> public Cfg.Vector3 Position; /// <summary> /// 投射起始旋转角度 /// <summary> public Cfg.Vector3 EulerAngles; public CastObject(DataStream data) : base(data) { this.IsTraceTarget = data.GetBool(); this.CurveId = data.GetInt(); this.PassBody = data.GetBool(); this.Position = new Vector3(data); this.EulerAngles = new Vector3(data); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class PlayParticle : Cfg.Skill.Timeline { /// <summary> /// 粒子资源的路径 /// <summary> public readonly string Path; /// <summary> /// 是否相对于自己移动 /// <summary> public readonly bool IsRelateSelf; /// <summary> /// 特效是否始终跟随目标对象方向变化 /// <summary> public readonly bool FollowDir; /// <summary> /// 节点名称,如果有配置则绑定到节点局部空间;反之绑定世界空间 /// <summary> public readonly string NodeName; /// <summary> /// 特效结点偏移;特效世界偏移 /// <summary> public Cfg.Vector3 Position; /// <summary> /// 特效结点旋转;特效世界旋转 /// <summary> public Cfg.Vector3 EulerAngles; /// <summary> /// 整体缩放大小 /// <summary> public Cfg.Vector3 Scale; /// <summary> /// 屏幕对齐类型 /// <summary> public readonly int AlignType; public PlayParticle(DataStream data) : base(data) { this.Path = data.GetString(); this.IsRelateSelf = data.GetBool(); this.FollowDir = data.GetBool(); this.NodeName = data.GetString(); this.Position = new Vector3(data); this.EulerAngles = new Vector3(data); this.Scale = new Vector3(data); this.AlignType = data.GetInt(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class DynamicHit : Cfg.Skill.StaticHit { /// <summary> /// 碰撞体绑定对象路径 /// <summary> public readonly string Target; public DynamicHit(DataStream data) : base(data) { this.Target = data.GetString(); } } } <file_sep>using System.Collections.Generic; using UnityEditor; public partial class ExportResource { static Dictionary<string, string> assetTextures = new Dictionary<string, string>(); static void GetTexturesAssets() { assetTextures.Clear(); GetAssetsRecursively("Assets/Texture/", "*.png", "texture/", "t", ref assetTextures); GetAssetsRecursively("Assets/Texture/", "*.tga", "texture/", "t", ref assetTextures); } static void ExportSelectedTextures(BuildTarget target) { UnityEngine.Object[] selection = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets); if (selection.Length > 0) { GetTexturesAssets(); var assets = GetSelectedAssets(assetTextures, selection); SetAssetBundleName(assets); BuildAssetBundles(target); } } static void ExportAllTextures(BuildTarget target) { GetTexturesAssets(); SetAssetBundleName(assetTextures); BuildAssetBundles(target); } [MenuItem("Assets/Build Selected for Windows/Texture")] static void ExportSelectedTexturesForWindows() { ExportSelectedTextures(BuildTarget.StandaloneWindows); } [MenuItem("Assets/Build Selected for Android/Texture")] static void ExportSelectedTexturesForAndroid() { ExportSelectedTextures(BuildTarget.Android); } [MenuItem("Assets/Build Selected for iOS/Texture")] static void ExportSelectedTexturesForiOS() { ExportSelectedTextures(BuildTarget.iOS); } [MenuItem("Build Windows/Build Textures for Windows")] static void ExportAllTexturesForWindows() { ExportAllTextures(BuildTarget.StandaloneWindows); } [MenuItem("Build Android/Build Textures for Android")] static void ExportAllTexturesForAndroid() { ExportAllTextures(BuildTarget.Android); } [MenuItem("Build iOS/Build Textures for iOS")] static void ExportAllTexturesForiOS() { ExportAllTextures(BuildTarget.iOS); } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class Controller : XmlCfg.Skill.Timeline { /// <summary> /// 资源对象路径 /// <summary> public string Path = ""; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Path", this.Path); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Path": this.Path = ReadString(_2); break; } } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public enum MoveType { /// <summary> /// 向目标移动 /// <summary> MoveToTarget = 0, /// <summary> /// 按当前方向移动 /// <summary> MoveInDirection = 1, } } <file_sep>using UnityEngine; using System.Collections; using XmlCfg.Skill; using System; namespace Flux { [FEvent("控制器/激活隐藏", isSingle: true)] public class FActive : FController { [SerializeField, HideInInspector] [FEventField("是否激活")] private bool _enable; private bool _iniState; private GameObject _targetObj; protected override void OnInit() { base.OnInit(); _targetObj = FUtility.FindGameObject(_path); if (_targetObj != null) _iniState = _targetObj.activeSelf; } protected override void OnTrigger(float timeSinceTrigger) { base.OnTrigger(timeSinceTrigger); if (_targetObj != null) _targetObj.SetActive(_enable); } protected override void OnStop() { base.OnStop(); if (_targetObj != null) _targetObj.SetActive(_iniState); } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class Buff : XmlCfg.Skill.PlayParticle { /// <summary> /// Buff参数集合ID /// <summary> public int Id; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Id", this.Id); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Id": this.Id = ReadInt(_2); break; } } } } <file_sep>namespace AssetManager { using UnityEditor; using UnityEngine; using Sirenix.OdinInspector.Editor; using Sirenix.Utilities.Editor; using Sirenix.Utilities; using System.Collections.Generic; using System.Linq; public class AssetRefCounter : OdinMenuEditorWindow { [MenuItem("Assets/资源引用统计", false, 2002)] private static void Open() { var window = GetWindow<AssetRefCounter>("资源引用统计"); window.position = GUIHelper.GetEditorWindowRect().AlignCenter(800, 500); RefCounterConfig.LoadInstanceIfAssetExists(); window._refresh = new GUIContent(EditorIcons.Refresh.Raw); //初始化引用基础数据 //TODO } const string TAB_ATLASSPRITE = "界面精灵"; const string TAB_TEXTUREUI = "界面图片"; const string TAB_TEXTURESFX = "特效图片"; const string TAB_TEXTURECHARACTER = "角色贴图"; const string TAB_ANIMATIONCLIP = "动画剪辑"; const string TAB_AUDIOCLIP = "音频剪辑"; GUIContent _refresh; GUIContent _sortName = new GUIContent("名称排序"); GUIContent _sortNum = new GUIContent("数量排序"); GUIContent _sortSize = new GUIContent("大小排序"); protected override OdinMenuTree BuildMenuTree() { var tree = new OdinMenuTree(false); tree.Config.DrawSearchToolbar = true; CreateListItem(tree, TAB_ATLASSPRITE, RefCounterConfig.Instance.AtlasSprite); CreateListItem(tree, TAB_TEXTUREUI, RefCounterConfig.Instance.TextureUI); CreateListItem(tree, TAB_TEXTURESFX, RefCounterConfig.Instance.TextureSFX); CreateListItem(tree, TAB_TEXTURECHARACTER, RefCounterConfig.Instance.TextureCharacter); CreateListItem(tree, TAB_ANIMATIONCLIP, RefCounterConfig.Instance.AnimationClip); CreateListItem(tree, TAB_AUDIOCLIP, RefCounterConfig.Instance.AudioClip); return tree; } private void CreateListItem(OdinMenuTree tree, string tabName, RefCounterInfo refCounter) { if (refCounter == null) refCounter = new RefCounterInfo(tabName); tree.AddObjectAtPath(tabName, refCounter); } protected override void OnBeginDrawEditors() { var selected = this.MenuTree.Selection.FirstOrDefault(); var toolbarHeight = this.MenuTree.Config.SearchToolbarHeight; if (selected == null) return; SirenixEditorGUI.BeginHorizontalToolbar(toolbarHeight); { if (selected != null) { GUILayout.Label(selected.Name); } if (SirenixEditorGUI.ToolbarButton(_sortName)) { (selected.ObjectInstance as RefCounterInfo).SortName(); } if (SirenixEditorGUI.ToolbarButton(_sortNum)) { (selected.ObjectInstance as RefCounterInfo).SortRefNum(); } if (SirenixEditorGUI.ToolbarButton(_sortSize)) { (selected.ObjectInstance as RefCounterInfo).SortSize(); } if (SirenixEditorGUI.ToolbarButton(EditorIcons.X)) { (selected.ObjectInstance as RefCounterInfo).ClearAsset(); } if (SirenixEditorGUI.ToolbarButton(_refresh)) { switch (selected.Name) { case TAB_ATLASSPRITE: RefCounterInfo.CountAtlasSprite(selected.ObjectInstance as RefCounterInfo); break; case TAB_TEXTUREUI: RefCounterInfo.CountTextureUI(selected.ObjectInstance as RefCounterInfo); break; case TAB_TEXTURESFX: RefCounterInfo.CountTextureSFX(selected.ObjectInstance as RefCounterInfo); break; case TAB_TEXTURECHARACTER: RefCounterInfo.CountTextureCharacter(selected.ObjectInstance as RefCounterInfo); break; case TAB_ANIMATIONCLIP: RefCounterInfo.CountAnimationClip(selected.ObjectInstance as RefCounterInfo); break; case TAB_AUDIOCLIP: RefCounterInfo.CountAudioClip(selected.ObjectInstance as RefCounterInfo); break; default: break; } } } SirenixEditorGUI.EndHorizontalToolbar(); } protected override void OnDestroy() { base.OnDestroy(); RefCounterConfig.Instance.ClearAll(); RefCounterConfig.Instance.ClearInvalidPath(); EditorUtility.SetDirty(RefCounterConfig.Instance); EditorUtility.UnloadUnusedAssetsImmediate(); AssetDatabase.Refresh(); } } } <file_sep>namespace Game { public interface IManager { void Init(); void Dispose(); } } <file_sep>namespace AssetManager { using System; using System.IO; using System.Text; using UnityEditor; using UnityEngine; using Sirenix.Utilities; using Sirenix.OdinInspector; using System.Collections.Generic; using Sirenix.Utilities.Editor; [GlobalConfig("Editor/AssetManager/Config", UseAsset = true)] public class RefCounterConfig : GlobalConfig<RefCounterConfig> { public RefCounterInfo AtlasSprite; public RefCounterInfo TextureUI; public RefCounterInfo TextureSFX; public RefCounterInfo TextureCharacter; public RefCounterInfo AnimationClip; public RefCounterInfo AudioClip; private List<RefCounterInfo> _list { get { List<RefCounterInfo> list = new List<RefCounterInfo>(); list.Add(AtlasSprite); list.Add(TextureUI); list.Add(TextureSFX); list.Add(TextureCharacter); list.Add(AnimationClip); list.Add(AudioClip); return list; } } [Button("Clear Invalid Path", ButtonSizes.Large)] public void ClearInvalidPath() { for (int i = 0; i < _list.Count; i++) { if (!Directory.Exists(_list[i].Path)) { _list[i].ClearAsset(); _list[i].Path = string.Empty; _list[i].OptPath = string.Empty; _list[i].OnlyShowZeroRef = false; } } } [Button("Clear All", ButtonSizes.Large)] public void ClearAll() { for (int i = 0; i < _list.Count; i++) { _list[i].ClearAsset(); } } } [Serializable] public class RefCounterInfo : AssetOption { [ShowInInspector, PropertyOrder(-100), OnValueChanged("OnValueChanged"), LabelText("路径")] [FolderPath(RequireValidPath = true)] public override string Path { get { return base.Path; } set { base.Path = value; } } [FolderPath(RequireValidPath = true), HorizontalGroup("Option"), LabelText("额外路径")] public string OptPath; [HorizontalGroup("Option", 20, 10), LabelText("仅显示0引用"), ToggleLeft, LabelWidth(50)] public bool OnlyShowZeroRef; [HideInInspector] public string Description = string.Empty; List<RefCounter> _refInfoList = new List<RefCounter>(); private void OnValueChanged() { _refInfoList = new List<RefCounter>(); } [OnInspectorGUI] private void OnInspectorGUI() { if (!string.IsNullOrEmpty(Description)) SirenixEditorGUI.MessageBox(Description, MessageType.Info); SirenixEditorGUI.BeginHorizontalToolbar(); GUILayout.Label("文件名", SirenixGUIStyles.BoldLabel); GUILayout.Label("引用数量", SirenixGUIStyles.BoldLabel, GUILayout.Width(90)); GUILayout.Label("内存大小", SirenixGUIStyles.BoldLabel, GUILayout.Width(70)); SirenixEditorGUI.EndHorizontalToolbar(); if (_refInfoList == null) return; GUILayout.Space(-5); SirenixEditorGUI.BeginBox(); for (int i = 0; i < _refInfoList.Count; i++) { var item = _refInfoList[i]; if (OnlyShowZeroRef && item.RefNum != 0) continue; EditorGUILayout.BeginHorizontal(); GUILayout.Label(item.FileName, SirenixGUIStyles.Label); GUILayout.Label(item.RefNum.ToString(), SirenixGUIStyles.Label, GUILayout.Width(70)); GUILayout.Label(EditorUtility.FormatBytes(item.Size), SirenixGUIStyles.Label, GUILayout.Width(70)); EditorGUILayout.EndHorizontal(); if (i + 1 != _refInfoList.Count) { GUILayout.Space(3); SirenixEditorGUI.HorizontalLineSeparator(); } } SirenixEditorGUI.EndBox(); } public override void ClearAsset() { _refInfoList.Clear(); Description = string.Empty; } public RefCounterInfo(string name) { _name = name; } [Serializable] class RefCounter { [FilePath(RequireValidPath = true), ReadOnly] public string FileName; [ReadOnly] public int RefNum; [ReadOnly] public int Size; } public void SortName() { int count = 0; int all = (int)(_refInfoList.Count * Mathf.Log(_refInfoList.Count, 2)) + _refInfoList.Count; _refInfoList.Sort((a, b) => { EditorUtility.DisplayProgressBar("按照名称排序", count.ToString(), (++count * 1f) / all); return string.Compare(a.FileName, b.FileName); }); EditorUtility.ClearProgressBar(); } public void SortRefNum() { int count = 0; int all = (int)(_refInfoList.Count * Mathf.Log(_refInfoList.Count, 2)) + _refInfoList.Count; _refInfoList.Sort((a, b) => { EditorUtility.DisplayProgressBar("按照引用数量排序", count.ToString(), (++count * 1f) / all); return a.RefNum - b.RefNum; }); EditorUtility.ClearProgressBar(); } public void SortSize() { int count = 0; int all = (int)(_refInfoList.Count * Mathf.Log(_refInfoList.Count, 2)) + _refInfoList.Count; _refInfoList.Sort((a, b) => { EditorUtility.DisplayProgressBar("按照内存大小排序", count.ToString(), (++count * 1f) / all); return a.Size - b.Size; }); EditorUtility.ClearProgressBar(); } //StringBuilder builder = new StringBuilder(); //Transform parent = sprite.transform.parent; //string nodePtah = string.Format("{0}/{1}", parent.name, sprite.name); //while (parent.parent != null) //{ // parent = parent.parent; // nodePtah = string.Format("{0}/{1}", parent.name, nodePtah); //} //builder.AppendFormat("预制节点路径:{0} 图集图片:{1}\n", nodePtah, file); //Profiler.GetRuntimeMemorySize(sprite.mainTexture);内存大小 //---------各种资源的统计方法 public static void CountAtlasSprite(RefCounterInfo atlasSprite) { atlasSprite._refInfoList.Clear(); Dictionary<string, RefCounter> pairs = new Dictionary<string, RefCounter>(); HashSet<string> atlasHash = new HashSet<string>(); HashSet<string> spriteHash = new HashSet<string>(); string path = GetAbsPath(atlasSprite.Path); string optPath = GetAbsPath(atlasSprite.OptPath); string[] atlasFile = Directory.GetFiles(optPath, "*.prefab", SearchOption.AllDirectories); string[] uiFile = Directory.GetFiles(path, "*.prefab", SearchOption.AllDirectories); #if ASSET_MGR_NGUI foreach (var file in atlasFile) { GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(GetUnityPath(file)); UIAtlas atlas = prefab.GetComponent<UIAtlas>(); foreach (var sprite in atlas.spriteList) { string fileName = string.Format("{0}/{1}", atlas.name, sprite.name); RefCounter counter = new RefCounter(); counter.FileName = fileName; counter.RefNum = 0; counter.Size = 0; pairs.Add(fileName, counter); } } for (int i = 0; i < uiFile.Length; i++) { path = GetUnityPath(uiFile[i]); GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path); if (prefab == null) continue; UISprite[] sprites = prefab.GetComponentsInChildren<UISprite>(); for (int j = 0; j < sprites.Length; j++) { UISprite sprite = sprites[j]; if (sprite.atlas == null) continue; if (!atlasHash.Contains(sprite.atlas.name)) atlasHash.Add(sprite.atlas.name); if (!spriteHash.Contains(sprite.name)) spriteHash.Add(sprite.name); string file = string.Format("{0}/{1}", sprite.atlas.name, sprite.spriteName); if (pairs.ContainsKey(file)) { pairs[file].RefNum++; } } EditorUtility.DisplayProgressBar("解析预制", path, (i * 1f) / uiFile.Length); } #elif ASSET_MGR_UGUI #endif EditorUtility.ClearProgressBar(); atlasSprite.Description = string.Format("图集预制总数:{0}\t 图集预制实际引用数:{1}\t 图集精灵总数量:{2}", atlasFile.Length, atlasHash.Count, spriteHash.Count); atlasSprite._refInfoList.AddRange(pairs.Values); atlasSprite.SortRefNum(); EditorUtility.UnloadUnusedAssetsImmediate(); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } public static void CountTextureUI(RefCounterInfo atlasSprite) { } public static void CountTextureSFX(RefCounterInfo atlasSprite) { } public static void CountTextureCharacter(RefCounterInfo atlasSprite) { } public static void CountAnimationClip(RefCounterInfo atlasSprite) { } public static void CountAudioClip(RefCounterInfo atlasSprite) { } } }<file_sep>using UnityEngine; using System.Collections; using UnityEditor; using UnityEditor.VersionControl; using System.Collections.Generic; using System.Text; using System.IO; using UnityEngine.UI; public class LabelTextTool : EditorWindow { [MenuItem("Tools/FindReplaceTool")] static void ReplaceTool() { var window = GetWindow<LabelTextTool>("预制Label查找工具"); } Object _asset; string _find = ""; string _src = ""; string _dst = ""; void OnGUI() { GUILayout.BeginHorizontal(); GUILayout.Label("选择资源", GUILayout.Width(60)); _asset = EditorGUILayout.ObjectField(_asset, typeof(Object)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); _find = GUILayout.TextField(_find); if (GUILayout.Button("查找", GUILayout.Width(60)) && !string.IsNullOrEmpty(_find) && _asset != null) { Debug.LogError("----------------------查找----------------------"); List<GameObject> ls = GetGameObjects(); for (int i = 0; i < ls.Count; i++) { string title = string.Format("查找-{0}[{1}/{2}]", _find, i + 1, ls.Count); Find(ls[i].transform, _find, title); EditorUtility.DisplayProgressBar(title, ls[i].name, (i + 1f) / ls.Count); } EditorUtility.ClearProgressBar(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); _src = GUILayout.TextField(_src); GUILayout.Label("->", GUILayout.Width(20)); _dst = GUILayout.TextField(_dst); if (GUILayout.Button("替换", GUILayout.Width(60)) && _asset != null && !string.IsNullOrEmpty(_src) && !string.IsNullOrEmpty(_dst)) { Debug.LogError("----------------------替换----------------------"); List<GameObject> ls = GetGameObjects(); for (int i = 0; i < ls.Count; i++) { string title = string.Format("替换-{0}:{1}[{2}/{3}]", _src, _dst, i + 1, ls.Count); Replace(ls[i], _src, _dst, title); EditorUtility.DisplayProgressBar(title, ls[i].name, (i + 1f) / ls.Count); } EditorUtility.ClearProgressBar(); } GUILayout.EndHorizontal(); } List<GameObject> GetGameObjects() { List<GameObject> ls = new List<GameObject>(); if (typeof(DefaultAsset) == _asset.GetType()) { string path = AssetDatabase.GetAssetPath(_asset).Replace("Assets", Application.dataPath); string[] files = Directory.GetFiles(path, "*.prefab", SearchOption.AllDirectories); foreach (var f in files) { string refPath = f.Replace(Application.dataPath, "Assets"); ls.Add(AssetDatabase.LoadAssetAtPath<GameObject>(refPath)); } } else if (typeof(GameObject) == _asset.GetType()) ls.Add(_asset as GameObject); return ls; } string GetPath(Transform t) { StringBuilder builder = new StringBuilder(t.name); while (t.parent != null) { t = t.parent; builder.Insert(0, t.name + "\\"); } return builder.ToString(); } void Find(Transform t, string str, string title) { StringBuilder builder = new StringBuilder(); //var labels = t.GetComponentsInChildren<UILabel>(); var labels = t.GetComponentsInChildren<Text>(); for (int i = 0; i < labels.Length; i++) { var l = labels[i]; string path = GetPath(l.transform); if (l.text.IndexOf(str) > -1) builder.AppendLine(path); else { char[] chars = str.ToCharArray(); bool isContain = true; for (int j = 0; j < chars.Length; j++) { isContain &= l.text.IndexOf(chars[j]) != -1; if (!isContain) break; } if (isContain) Debug.LogError("可能需要替换:" + path); } } string log = builder.ToString(); if (!string.IsNullOrEmpty(log)) Debug.LogError(log); } void Replace(GameObject go, string a, string b, string title) { StringBuilder builder = new StringBuilder(); var ins = PrefabUtility.InstantiatePrefab(go) as GameObject; //var labels = ins.transform.GetComponentsInChildren<UILabel>(true); var labels = ins.transform.GetComponentsInChildren<Text>(true); bool needReplace = false; for (int i = 0; i < labels.Length; i++) { var l = labels[i]; if (l.text.IndexOf(a) > -1) { builder.AppendLine(GetPath(l.transform)); l.text = l.text.Replace(a, b); needReplace = true; } } if (needReplace) PrefabUtility.ReplacePrefab(ins, go, ReplacePrefabOptions.ConnectToPrefab); DestroyImmediate(ins); AssetDatabase.Refresh(); string log = builder.ToString(); if (!string.IsNullOrEmpty(log)) Debug.LogError(log); } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Character { public class Model : XmlObject { /// <summary> /// 模型名称 /// <summary> public string Name = ""; /// <summary> /// 模型分组类型 /// <summary> public XmlCfg.Character.GroupType GroupType; /// <summary> /// 模型路径 /// <summary> public string ModelPath = ""; /// <summary> /// Avatar路径 /// <summary> public string AvatarPath = ""; /// <summary> /// 模型缩放 /// <summary> public float ModelScale; public override void Write(TextWriter _1) { Write(_1, "Name", this.Name); Write(_1, "GroupType", (int)this.GroupType); Write(_1, "ModelPath", this.ModelPath); Write(_1, "AvatarPath", this.AvatarPath); Write(_1, "ModelScale", this.ModelScale); } public override void Read(XmlNode _1) { foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Name": this.Name = ReadString(_2); break; case "GroupType": this.GroupType = (XmlCfg.Character.GroupType)ReadInt(_2); break; case "ModelPath": this.ModelPath = ReadString(_2); break; case "AvatarPath": this.AvatarPath = ReadString(_2); break; case "ModelScale": this.ModelScale = ReadFloat(_2); break; } } } } <file_sep>using UnityEngine; using UnityEditor; using System.Collections.Generic; using Flux; namespace FluxEditor { [FEditor(typeof(FSequenceTrack))] public class FSequenceTrackEditor : FTrackEditor { private FSequenceEditor _sequenceEditor = null; public override void Init(FObject obj, FEditor owner) { base.Init(obj, owner); FSequenceTrack sequenceTrack = (FSequenceTrack)Obj; if (sequenceTrack.OwnerSequence == null) { FSequence newSequence = FSequenceEditorWindow.CreateSequence(); newSequence.transform.parent = sequenceTrack.transform; sequenceTrack.OwnerSequence = newSequence; foreach (FPlaySequenceEvent evt in sequenceTrack.Events) { evt.Init(); } } if (_sequenceEditor == null) { _sequenceEditor = FSequenceEditor.CreateInstance<FSequenceEditor>(); _sequenceEditor.Init((Editor)null/*SequenceEditor*/ ); _sequenceEditor.OpenSequence(sequenceTrack.OwnerSequence); // if( Track.PreviewDirtiesScene && !Track.HasCache ) // { // _sequenceEditor.TurnOnAllPreviews( false ); // } } } public override void UpdateEventsEditor(int frame, float time) { base.UpdateEventsEditor(frame, time); FEvent[] evts = new FEvent[2]; int numEvents = Track.GetEventsAt(frame, evts); if (numEvents > 0) { int startOffset = ((FPlaySequenceEvent)evts[0]).StartOffset; _sequenceEditor.SetCurrentFrame(startOffset + frame - evts[0].Start); /// @TODO handle offset if (numEvents > 1) { startOffset = ((FPlaySequenceEvent)evts[1]).StartOffset; _sequenceEditor.SetCurrentFrame(startOffset + frame - evts[1].Start); } } } } } <file_sep>using System.Collections.Generic; using UnityEditor; public partial class ExportResource { //冗余资源:Texture,Audio,VFX:图集[RGB|A] //上述资源,在每次打包UI时,需要重新打包 //Android 平台特效有待继续处理 static string uiPrefabsFolder = "Assets/Interface/Prefabs"; static string atlasAssetFolder = "Assets/Interface/Atlas"; static Dictionary<string, string> assetAtlas = new Dictionary<string, string>(); static Dictionary<string, string> assetFonts = new Dictionary<string, string>(); static Dictionary<string, string> assetUIs = new Dictionary<string, string>(); static void ExportSelectedUIs(BuildTarget target) { UnityEngine.Object[] selection = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets); if (selection.Length > 0) { assetAtlas.Clear(); GetAssetsRecursively(atlasAssetFolder, "*.spriteatlas", "ui/atlas/", null, ref assetAtlas); SetAssetBundleName(assetAtlas); GetUIPrefabAssets(); var assets = GetSelectedAssets(assetUIs, selection); CombineAssets(new Dictionary<string, string>[] { assetFonts, assetUIs }, ref assets); SetAssetBundleName(assets, new string[] { EXT_PNG, EXT_TGA, }, DEPTEX_FOLDER); SetAssetBundleName(assets, new string[] { EXT_SHADER }, SHADER_FOLDER); SetAssetBundleName(assets, new string[] { EXT_OGG, EXT_MP3 }, AUDIO_FOLDER); BuildAssetBundles(target); } } static void ExportAllUIs(BuildTarget target) { assetAtlas.Clear(); GetAssetsRecursively(atlasAssetFolder, "*.spriteatlas", "ui/atlas/", null, ref assetAtlas); SetAssetBundleName(assetAtlas); GetUIPrefabAssets(); CombineAssets(new Dictionary<string, string>[] { assetFonts }, ref assetUIs); SetAssetBundleName(assetUIs, new string[] { EXT_PNG, EXT_TGA, }, DEPTEX_FOLDER); SetAssetBundleName(assetUIs, new string[] { EXT_SHADER }, SHADER_FOLDER); SetAssetBundleName(assetUIs, new string[] { EXT_OGG, EXT_MP3 }, AUDIO_FOLDER); BuildAssetBundles(target); } static void GetUIPrefabAssets() { assetUIs.Clear(); GetAssetsRecursively(uiPrefabsFolder, "*.prefab", "ui/", null, ref assetUIs); } static void CombineAssets(Dictionary<string, string>[] dics, ref Dictionary<string, string> assets) { for (int i = 0; i < dics.Length; ++i) { Dictionary<string, string> dic = dics[i]; foreach (KeyValuePair<string, string> pair in dic) { assets[pair.Key] = pair.Value; } } } [MenuItem("Assets/Build Selected for Windows/UI")] static void ExportSelectedUIsForWindows() { ExportSelectedUIs(BuildTarget.StandaloneWindows); } [MenuItem("Assets/Build Selected for Android/UI")] static void ExportSelectedUIsForAndroid() { //ForAndroidSfxProcessBug(BuildTarget.Android); ExportSelectedUIs(BuildTarget.Android); } [MenuItem("Assets/Build Selected for iOS/UI")] static void ExportSelectedUIsForiOS() { ExportSelectedUIs(BuildTarget.iOS); } [MenuItem("Build Windows/Build UIs for Windows")] static void ExportAllUIsForWindows() { ExportAllUIs(BuildTarget.StandaloneWindows); } [MenuItem("Build Android/Build UIs for Android")] static void ExportAllUIsForAndroid() { //ForAndroidSfxProcessBug(BuildTarget.Android); ExportAllUIs(BuildTarget.Android); } [MenuItem("Build iOS/Build UIs for iOS")] static void ExportAllUIsForiOS() { ExportAllUIs(BuildTarget.iOS); } } <file_sep>using UnityEngine; using System.Collections; namespace Flux { public class FCharacterTrack : FTrack { public override void Init() { base.Init(); //Sequence. SetOwner(null); } } } <file_sep>local unpack = unpack or table.unpack local insert = table.insert local find = string.find local format = string.format local gsub = string.gsub -- 字符串分割 -- @str:被分割的字符串 -- @sep:分隔符 local function split(str, sep) local fields = {} local flag = "(.-)" .. sep local last_end = 1 local s, e, cap = str:find(flag, 1) while s do if s ~= 1 or cap ~= "" then insert(fields, cap) end last_end = e + 1 s, e, cap = str:find(flag, last_end) end if last_end <= #str then cap = str:sub(last_end) insert(fields, cap) end return fields end -- 字符串连接 local function join(join_table, joiner) if #join_table == 0 then return "" end local fmt = "%s" for i = 2, #join_table do fmt = fmt .. joiner .. "%s" end return format(fmt, unpack(join_table)) end -- 是否包含 -- 注意:plain为true时,关闭模式匹配机制,此时函数仅做直接的 “查找子串”的操作 local function contains(target_string, pattern, plain) plain = plain or true local find_pos_begin, find_pos_end = find(target_string, pattern, 1, plain) return find_pos_begin ~= nil end -- 以某个字符串开始 local function startswith(target_string, start_pattern, plain) plain = plain or true local find_pos_begin, find_pos_end = find(target_string, start_pattern, 1, plain) return find_pos_begin == 1 end -- 以某个字符串结尾 local function endswith(target_string, start_pattern, plain) plain = plain or true local find_pos_begin, find_pos_end = find(target_string, start_pattern, -#start_pattern, plain) return find_pos_end == #target_string end local function trim(target_string) return gsub(target_string, "^%s*(.-)%s*$", "%1") end string.split = split string.join = join string.contains = contains string.startswith = startswith string.endswith = endswith string.trim = endswith <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class Timeline : CfgObject { /// <summary> /// 起始帧 /// <summary> public readonly int Start; /// <summary> /// 结束帧 /// <summary> public readonly int End; public Timeline(DataStream data) { this.Start = data.GetInt(); this.End = data.GetInt(); } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class Move : XmlCfg.Skill.Controller { /// <summary> /// 移动方式:0向目标移动 1按指定方向移动 /// <summary> public XmlCfg.Skill.MoveType Type; /// <summary> /// 是否相对于自己移动 /// <summary> public bool IsRelateSelf; /// <summary> /// 起始位置相对目标偏移 /// <summary> public XmlCfg.Vector3 Offset; /// <summary> /// Y轴顺时针旋转角度 /// <summary> public float Angle; /// <summary> /// 位移速度m/s /// <summary> public float Speed; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Type", (int)this.Type); Write(_1, "IsRelateSelf", this.IsRelateSelf); Write(_1, "Offset", this.Offset); Write(_1, "Angle", this.Angle); Write(_1, "Speed", this.Speed); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Type": this.Type = (XmlCfg.Skill.MoveType)ReadInt(_2); break; case "IsRelateSelf": this.IsRelateSelf = ReadBool(_2); break; case "Offset": this.Offset = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; case "Angle": this.Angle = ReadFloat(_2); break; case "Speed": this.Speed = ReadFloat(_2); break; } } } } <file_sep>#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class GameGameManagerWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(Game.GameManager); Utils.BeginObjectRegister(type, L, translator, 0, 10, 0, 0); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Init", _m_Init); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Dispose", _m_Dispose); Utils.RegisterFunc(L, Utils.METHOD_IDX, "InitSDK", _m_InitSDK); Utils.RegisterFunc(L, Utils.METHOD_IDX, "DowmloadUnZip", _m_DowmloadUnZip); Utils.RegisterFunc(L, Utils.METHOD_IDX, "UnZipFile", _m_UnZipFile); Utils.RegisterFunc(L, Utils.METHOD_IDX, "UpdateAppVersion", _m_UpdateAppVersion); Utils.RegisterFunc(L, Utils.METHOD_IDX, "UpdateResVersion", _m_UpdateResVersion); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetServerList", _m_GetServerList); Utils.RegisterFunc(L, Utils.METHOD_IDX, "LoadResource", _m_LoadResource); Utils.RegisterFunc(L, Utils.METHOD_IDX, "StartGame", _m_StartGame); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 1, 1, 0); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "Instance", _g_get_Instance); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { return LuaAPI.luaL_error(L, "Game.GameManager does not have a constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Init(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Init( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Dispose(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Dispose( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_InitSDK(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { System.Collections.IEnumerator gen_ret = gen_to_be_invoked.InitSDK( ); translator.PushAny(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_DowmloadUnZip(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { System.Collections.IEnumerator gen_ret = gen_to_be_invoked.DowmloadUnZip( ); translator.PushAny(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_UnZipFile(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { System.Collections.IEnumerator gen_ret = gen_to_be_invoked.UnZipFile( ); translator.PushAny(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_UpdateAppVersion(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { System.Collections.IEnumerator gen_ret = gen_to_be_invoked.UpdateAppVersion( ); translator.PushAny(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_UpdateResVersion(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { System.Collections.IEnumerator gen_ret = gen_to_be_invoked.UpdateResVersion( ); translator.PushAny(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetServerList(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { System.Collections.IEnumerator gen_ret = gen_to_be_invoked.GetServerList( ); translator.PushAny(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_LoadResource(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { System.Collections.IEnumerator gen_ret = gen_to_be_invoked.LoadResource( ); translator.PushAny(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_StartGame(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.GameManager gen_to_be_invoked = (Game.GameManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.StartGame( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_Instance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); translator.Push(L, Game.GameManager.Instance); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class StaticHit : XmlCfg.Skill.Timeline { /// <summary> /// 碰撞区域 /// <summary> public XmlCfg.Skill.HitZone Zone; /// <summary> /// 触发序列容器ID /// <summary> public int SequeueID; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Zone", this.Zone); Write(_1, "SequeueID", this.SequeueID); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Zone": this.Zone = ReadObject<XmlCfg.Skill.HitZone>(_2, "XmlCfg.Skill.HitZone"); break; case "SequeueID": this.SequeueID = ReadInt(_2); break; } } } } <file_sep>namespace AssetManager { using System; using System.IO; using UnityEngine; using UnityEditor; using System.Linq; using Sirenix.OdinInspector; using System.Collections.Generic; using Sirenix.Utilities.Editor; [Serializable] public class BitmapCheckerInfo : CheckerInfo { [ShowInInspector, PropertyOrder(-100)] [FolderPath(RequireValidPath = true), LabelText("图集路径")] public override string Path { get { return base.Path; } set { base.Path = value; } } #if ASSET_MGR_NGUI [FolderPath(RequireValidPath = true)] [ShowInInspector, PropertyOrder(-99), LabelText("位图路径")] public string BitmapPath; #endif class BitmapDelete { public string Path; public bool AtlasExist; /// <summary> /// 移出项目 /// </summary> public void Delete() { string srcPath = GetAbsPath(Path); string dstPath = srcPath.Replace(Application.dataPath, CheckerConfig.Instance.AssetMoveToPath); CreateFolder(dstPath); if (AtlasExist && File.Exists(srcPath)) { if (File.Exists(dstPath)) File.Delete(dstPath); File.Move(srcPath, dstPath); } if (!AtlasExist && Directory.Exists(srcPath)) { if (Directory.Exists(dstPath)) Directory.Delete(dstPath); Directory.Move(srcPath, dstPath); } Path = null; } } //[ButtonGroup("Delete", -80), Button(ButtonSizes.Medium)] //public void SelectedDelete() //{ // for (int i = 0; i < spriteBitmaps.Count; i++) // { // BitmapDelete delete = spriteBitmaps[i]; // if (!delete.AtlasExist && delete.IsDeletable) // delete.Delete(); // if (delete.AtlasExist && delete.IsDeletable) // delete.Delete(); // } // RefreshAsset(); // AssetDatabase.Refresh(); //} [ButtonGroup("Delete", -80), Button(ButtonSizes.Medium), LabelText("删除文件")] public void DeleteFileImmediate() { for (int i = 0; i < _spriteBitmaps.Count; i++) { BitmapDelete delete = _spriteBitmaps[i]; if (delete.AtlasExist) delete.Delete(); } RefreshAsset(); AssetDatabase.Refresh(); } [ButtonGroup("Delete", -80), Button(ButtonSizes.Medium), LabelText("删除文件夹")] public void DeleteFolderImmediate() { for (int i = 0; i < _spriteBitmaps.Count; i++) { BitmapDelete delete = _spriteBitmaps[i]; if (!delete.AtlasExist) delete.Delete(); } RefreshAsset(); AssetDatabase.Refresh(); } List<BitmapDelete> _spriteBitmaps = new List<BitmapDelete>(); [OnInspectorGUI] void OnInspectorGUI() { if (_spriteBitmaps != null) SirenixEditorGUI.MessageBox(string.Format("异常文件数量{0}个", _spriteBitmaps.Count), MessageType.Info); SirenixEditorGUI.BeginHorizontalToolbar(); GUILayout.Label("文件名", SirenixGUIStyles.BoldLabel); GUILayout.Label("图集是否存在", SirenixGUIStyles.BoldLabel, GUILayout.Width(90)); GUILayout.Label("操作", SirenixGUIStyles.BoldLabelCentered, GUILayout.Width(70)); SirenixEditorGUI.EndHorizontalToolbar(); if (_spriteBitmaps == null) return; GUILayout.Space(-5); SirenixEditorGUI.BeginBox(); for (int i = 0; i < _spriteBitmaps.Count; i++) { var item = _spriteBitmaps[i]; EditorGUILayout.BeginHorizontal(); GUILayout.Label(item.Path, SirenixGUIStyles.Label); GUIHelper.PushColor(item.AtlasExist ? Color.green : Color.red); GUILayout.Label(item.AtlasExist ? "有" : "无", SirenixGUIStyles.Label, GUILayout.Width(70)); GUIHelper.PopColor(); GUILayout.Space(-9); GUILayout.Button("删除", SirenixGUIStyles.Button, GUILayout.Width(70)); EditorGUILayout.EndHorizontal(); if (i + 1 != _spriteBitmaps.Count) { GUILayout.Space(3); SirenixEditorGUI.HorizontalLineSeparator(); } } SirenixEditorGUI.EndBox(); } public BitmapCheckerInfo(string name) : base(name) { } public override void CheckAsset() { base.CheckAsset(); #if ASSET_MGR_NGUI if (!Directory.Exists(BitmapPath)) EditorUtility.DisplayDialog("错误", "位图目录路径不存在", "确定"); ClearAsset(); Dictionary<string, HashSet<string>> pairs = new Dictionary<string, HashSet<string>>(); string[] prefabs = Directory.GetFiles(GetAbsPath(Path), "*.prefab"); foreach (var file in prefabs) { string unityPath = GetUnityPath(file); GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(unityPath); UIAtlas atlas = go.GetComponent<UIAtlas>(); var sprites = atlas.GetListOfSprites(); pairs.Add(atlas.name, new HashSet<string>(sprites.ToArray())); } string[] bitmaps = Directory.GetDirectories(GetAbsPath(BitmapPath)); foreach (var item in bitmaps) { List<string> sprites = new List<string>(Directory.GetFiles(item, "*.*", SearchOption.AllDirectories) .Where(f => f.EndsWith(".png"))); string atlasName = System.IO.Path.GetFileName(item); if (!pairs.ContainsKey(atlasName)) { BitmapDelete delete = new BitmapDelete(); delete.Path = GetUnityPath(item); delete.AtlasExist = false; _spriteBitmaps.Add(delete); } else { HashSet<string> atlas = pairs[atlasName]; foreach (var sprite in sprites) { string name = System.IO.Path.GetFileNameWithoutExtension(sprite); if (!atlas.Contains(name)) { BitmapDelete delete = new BitmapDelete(); delete.Path = GetUnityPath(sprite); delete.AtlasExist = true; _spriteBitmaps.Add(delete); } } } } #elif ASSET_MGR_UGUI #endif EditorUtility.UnloadUnusedAssetsImmediate(); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } public override void ClearAsset() { base.ClearAsset(); if (_spriteBitmaps == null) _spriteBitmaps = new List<BitmapDelete>(); _spriteBitmaps.Clear(); } } }<file_sep>namespace AssetManager { using System; using System.IO; using UnityEngine; using UnityEditor; using Sirenix.OdinInspector; using System.Collections.Generic; using Sirenix.Utilities.Editor; using System.Drawing; [Serializable] public class TextureStretchCheckerInfo : CheckerInfo { [LabelText("检查目录列表")] public List<Folder> PathList = new List<Folder>(); [Serializable] public class Folder { [FolderPath(RequireValidPath = true)] public string Path; } class TextureInfo { public string Path; public string Before; public string After; } [OnInspectorGUI] void OnInspectorGUI() { GUILayout.Space(15f); if (_textureInfos != null) SirenixEditorGUI.MessageBox(string.Format("异常文件数量{0}个", _textureInfos.Count), MessageType.Info); SirenixEditorGUI.BeginHorizontalToolbar(); GUILayout.Label("文件名", SirenixGUIStyles.BoldLabel, GUILayout.Width(650)); GUILayout.Label("原始像素尺寸", SirenixGUIStyles.BoldLabel); GUILayout.Label("Unity像素尺寸", SirenixGUIStyles.BoldLabel); SirenixEditorGUI.EndHorizontalToolbar(); if (_textureInfos == null) return; GUILayout.Space(-5); SirenixEditorGUI.BeginBox(); for (int i = 0; i < _textureInfos.Count; i++) { var item = _textureInfos[i]; EditorGUILayout.BeginHorizontal(); GUILayout.Label(item.Path, SirenixGUIStyles.Label, GUILayout.Width(650)); GUILayout.Label(item.Before, SirenixGUIStyles.Label); GUILayout.Label(item.After, SirenixGUIStyles.Label); EditorGUILayout.EndHorizontal(); if (i + 1 != _textureInfos.Count) { GUILayout.Space(3); SirenixEditorGUI.HorizontalLineSeparator(); } } SirenixEditorGUI.EndBox(); } public TextureStretchCheckerInfo(string name) : base(name) { } static string[] _pattern = { "*.png", "*.jpg", "*.tga" }; List<TextureInfo> _textureInfos = new List<TextureInfo>(); public override void CheckAsset() { ClearAsset(); List<string> files = new List<string>(); for (int j = 0; j < PathList.Count; j++) { string path = GetAbsPath(PathList[j].Path); if (!Directory.Exists(path)) continue; for (int i = 0; i < _pattern.Length; i++) { files.AddRange(Directory.GetFiles(path, _pattern[i], SearchOption.AllDirectories)); } EditorUtility.DisplayProgressBar("获取文件", PathList[j].Path, (j + 1f) / _pattern.Length); } float count = 0; foreach (var f in files) { string path = GetUnityPath(f); EditorUtility.DisplayProgressBar("图片拉伸检查", path, ++count / files.Count); int bWidth, bHeight, aWidth, aHeight; using (FileStream fs = new FileStream(f, FileMode.Open, FileAccess.Read)) { Image image = Image.FromStream(fs); bWidth = image.Width; bHeight = image.Height; Texture texture = AssetDatabase.LoadAssetAtPath<Texture>(path); aWidth = texture.width; aHeight = texture.height; if (bHeight > aHeight || bWidth > aWidth) { var info = new TextureInfo(); info.Path = path; info.Before = string.Format("{0}x{1}", bWidth, bHeight); info.After = string.Format("{0}x{1}", aWidth, aHeight); _textureInfos.Add(info); } } } EditorUtility.UnloadUnusedAssetsImmediate(); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } public override void ClearAsset() { base.ClearAsset(); if (_textureInfos == null) _textureInfos = new List<TextureInfo>(); _textureInfos.Clear(); } } }<file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public enum ActionSourceType { /// <summary> /// 自己模型 /// <summary> SelfModel = 0, /// <summary> /// 其他模型 /// <summary> OtherModel = 1, } } <file_sep>local Mathf = Mathf local function Linear(from, to, t) to = to - from return to * t + from end local function Clerp(from, to, t) local min = 0 local max = 360 local half = Mathf.Abs((max - min) * 0.5) local retval = 0 local diff = 0 if (from - to) < -half then diff = (max - from + to) * t retval = from + diff elseif (to - from) > half then diff = -((max - to) + from) * t retval = from + diff else retval = from + (to - from) * t end return retval end local function Spring(from, to, t) t = Mathf.Clamp01(t) t = (Mathf.Sin(t * Mathf.PI * (0.2 + 2.5 * t * t * t)) * Mathf.Pow(1 - t, 2.2) + t) * (1 + (1.2 * (1 - t))) return from + (to - from) * t end local function EaseInQuad(from, to, t) to = to - from return to * t * t + from end local function EaseOutQuad(from, to, t) to = to - from return -to * t * (t - 2) + from end local function EaseInOutQuad(from, to, t) t = t / 0.5 to = to - from if t < 1 then return to * 0.5 * t * t + from end t = t - 1 return -to * 0.5 * (t * (t - 2) - 1) + from end local function EaseInCubic(from, to, t) to = to - from return to * t * t * t + from end local function EaseOutCubic(from, to, t) t = t - 1 to = to - from return to * (t * t * t + 1) + from end local function EaseInOutCubic(from, to, t) t = t / 0.5 to = to - from if t < 1 then return to * 0.5 * t * t * t + from end t = t - 2 return to * 0.5 * (t * t * t + 2) + from end local function EaseInQuart(from, to, t) to = to - from return to * t * t * t * t + from end local function EaseOutQuart(from, to, t) t = t - 1 to = to - from return -to * (t * t * t * t - 1) + from end local function EaseInOutQuart(from, to, t) t = t / 0.5 to = to - from if t < 1 then return to * 0.5 * t * t * t * t + from end t = t - 2 return -to * 0.5 * (t * t * t * t - 2) + from end local function EaseInQuint(from, to, t) to = to - from return to * t * t * t * t * t + from end local function EaseOutQuint(from, to, t) t = t - 1 to = to - from return to * (t * t * t * t * t + 1) + from end local function EaseInOutQuint(from, to, t) t = t / 0.5 to = to - from if t < 1 then return to * 0.5 * t * t * t * t * t + from end t = t - 2 return to * 0.5 * (t * t * t * t * t + 2) + from end local function EaseInSine(from, to, t) to = to - from return -to * Mathf.Cos(t * (Mathf.PI * 0.5)) + to + from end local function EaseOutSine(from, to, t) to = to - from return to * Mathf.Sin(t * (Mathf.PI * 0.5)) + from end local function EaseInOutSine(from, to, t) to = to - from return -to * 0.5 * (Mathf.Cos(Mathf.PI * t) - 1) + from end local function EaseInExpo(from, to, t) to = to - from return to * Mathf.Pow(2, 10 * (t - 1)) + from end local function EaseOutExpo(from, to, t) to = to - from return to * (-Mathf.Pow(2, -10 * t) + 1) + from end local function EaseInOutExpo(from, to, t) t = t / 0.5 to = to - from if t < 1 then return to * 0.5 * Mathf.Pow(2, 10 * (t - 1)) + from end t = t - 1 return to * 0.5 * (-Mathf.Pow(2, -10 * t) + 2) + from end local function EaseInCirc(from, to, t) to = to - from return -to * (Mathf.Sqrt(1 - t * t) - 1) + from end local function EaseOutCirc(from, to, t) t = t - 1 to = to - from return to * Mathf.Sqrt(1 - t * t) + from end local function EaseInOutCirc(from, to, t) t = t / 0.5 to = to - from if t < 1 then return -to * 0.5 * (Mathf.Sqrt(1 - t * t) - 1) + from end t = t - 2 return to * 0.5 * (Mathf.Sqrt(1 - t * t) + 1) + from end local function EaseOutBounce(from, to, t) t = t / 1 to = to - from if t < (1 / 2.75) then return to * (7.5625 * t * t) + from elseif t < (2 / 2.75) then t = t - 1.5 / 2.75 return to * (7.5625 * (t) * t + 0.75) + from elseif t < (2.5 / 2.75) then t = t - 2.25 / 2.75 return to * (7.5625 * t * t + 0.9375) + from else t = t - 2.625 / 2.75 return to * (7.5625 * t * t + 0.984375) + from end end local function EaseInBounce(from, to, t) to = to - from local d = 1 return to - EaseOutBounce(0, to, d - t) + from end local function EaseInOutBounce(from, to, t) to = to - from local d = 1 if t < (d * 0.5) then return EaseInBounce(0, to, t * 2) * 0.5 + from else return EaseOutBounce(0, to, t * 2 - d) * 0.5 + to * 0.5 + from end end local function EaseInBack(from, to, t) to = to - from t = t / 1 local s = 1.70158 return to * t * t * ((s + 1) * t - s) + from end local function EaseOutBack(from, to, t) local s = 1.70158 to = to - from t = t - 1 return to * (t * t * ((s + 1) * t + s) + 1) + from end local function EaseInOutBack(from, to, t) local s = 1.70158 to = to - from t = t / 0.5 if t < 1 then s = s * 1.525 return to * 0.5 * (t * t * ((s + 1) * t - s)) + from end t = t - 2 s = s * 1.525 return to * 0.5 * ((t) * t * (((s) + 1) * t + s) + 2) + from end local function EaseInElastic(from, to, t) to = to - from local d = 1 local p = d * 0.3 local s = 0 local a = 0 if (t == 0) then return from end t = t / d if t == 1 then return from + to end if a == 0 or a < Mathf.Abs(to) then a = to s = p / 4 else s = p / (2 * Mathf.PI) * Mathf.Asin(to / a) end t = t - 1 return -(a * Mathf.Pow(2, 10 * t) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p)) + from end local function EaseOutElastic(from, to, t) to = to - from local d = 1 local p = d * 0.3 local s = 0 local a = 0 if t == 0 then return from end t = t / d if t == 1 then return from + to end if a == 0 or a < Mathf.Abs(to) then a = to s = p * 0.25 else s = p / (2 * Mathf.PI) * Mathf.Asin(to / a) end return (a * Mathf.Pow(2, -10 * t) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p) + to + from) end local function EaseInOutElastic(from, to, t) to = to - from local d = 1 local p = d * 0.3 local s = 0 local a = 0 if t == 0 then return from end t = t / d * 0.5 if t == 2 then return from + to end if (a == 0 or a < Mathf.Abs(to)) then a = to s = p / 4 else s = p / (2 * Mathf.PI) * Mathf.Asin(to / a) end if (t < 1) then t = t - 1 return -0.5 * (a * Mathf.Pow(2, 10 * t) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p)) + from end t = t - 1 return a * Mathf.Pow(2, -10 * t) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p) * 0.5 + to + from end local function Punch(amplitude, t) local s = 9 if t == 0 or t == 1 then return 0 end local period = 1 * 0.3 s = period / (2 * Mathf.PI) * Mathf.Asin(0) return amplitude * Mathf.Pow(2, -10 * t) * Mathf.Sin((t * 1 - s) * (2 * Mathf.PI) / period) end return { Linear = Linear, Clerp = Clerp, Spring = Spring, EaseInQuad = EaseInQuad, EaseOutQuad = EaseOutQuad, EaseInOutQuad = EaseInOutQuad, EaseInCubic = EaseInCubic, EaseOutCubic = EaseOutCubic, EaseInOutCubic = EaseInOutCubic, EaseInQuart = EaseInQuart, EaseOutQuart = EaseOutQuart, EaseInOutQuart = EaseInOutQuart, EaseInQuint = EaseInQuint, EaseOutQuint = EaseOutQuint, EaseInOutQuint = EaseInOutQuint, EaseInSine = EaseInSine, EaseOutSine = EaseOutSine, EaseInOutSine = EaseInOutSine, EaseInExpo = EaseInExpo, EaseOutExpo = EaseOutExpo, EaseInOutExpo = EaseInOutExpo, EaseInCirc = EaseInCirc, EaseOutCirc = EaseOutCirc, EaseInOutCirc = EaseInOutCirc, EaseInBounce = EaseInBounce, EaseOutBounce = EaseOutBounce, EaseInOutBounce = EaseInOutBounce, EaseInBack = EaseInBack, EaseOutBack = EaseOutBack, EaseInOutBack = EaseInOutBack, EaseInElastic = EaseInElastic, EaseOutElastic = EaseOutElastic, EaseInOutElastic = EaseInOutElastic, }<file_sep>namespace CS.ActorConfig { using System; using XmlCfg.Skill; using Sirenix.OdinInspector; using Sirenix.Utilities.Editor; using System.Collections.Generic; using UnityEngine; using UnityEditor; using Flux; [Serializable] public class ModelActionEditor { public enum ActionState { New, Inherit, Override, } public const int INHERIT_WIDTH = 50; public const int ACT_NAME_WIDTH = 100; public const int ACT_SRC_WIDTH = 100; public const int ACT_CLIP_WIDTH = 100; [HideInInspector] public readonly GeneralAction ModelAction; [HideInInspector] public readonly bool IsSkillAction = false; private ActorConfigEditor _actorEditor; [OnInspectorGUI] private void OnGUI() { EditorGUILayout.BeginHorizontal(); Color color = Color.green; string actState = "新建"; switch (ActState) { case ActionState.New: break; case ActionState.Inherit: color = Color.yellow; actState = "继承"; break; case ActionState.Override: color = Color.red; actState = "重写"; break; } GUIHelper.PushColor(color); GUILayout.Label(actState, SirenixGUIStyles.LabelCentered, GUILayout.Width(INHERIT_WIDTH)); GUIHelper.PopColor(); GUILayout.Label(ActionName, SirenixGUIStyles.LabelCentered, GUILayout.Width(ACT_NAME_WIDTH)); GUILayout.Label(IsFromOther ? "其他" : "自己", SirenixGUIStyles.LabelCentered, GUILayout.Width(ACT_SRC_WIDTH)); bool isClipMiss = string.IsNullOrEmpty(ActionClip); GUIHelper.PushColor(isClipMiss ? Color.red : Color.green); GUILayout.Label(isClipMiss ? "Error" : ActionClip, SirenixGUIStyles.LabelCentered, GUILayout.Width(ACT_CLIP_WIDTH)); GUIHelper.PopColor(); GUIHelper.PushGUIPositionOffset(Vector2.up * -4f); if (GUILayout.Button("加载", SirenixGUIStyles.ButtonLeft)) { LoadSequence(); } bool canOverride = ActState == ActionState.Inherit; if (GUILayout.Button(canOverride? "重写" : "修改", SirenixGUIStyles.ButtonRight)) { Modifier(); } bool isSelected = IsSelected; if (isSelected) GUIHelper.PushColor(Color.green); if (GUILayout.Button("选择", SirenixGUIStyles.Button, GUILayout.Width(40))) { IsSelected = !IsSelected; } if (isSelected) GUIHelper.PopColor(); GUIHelper.PopGUIPositionOffset(); if (ActState != ActionState.Inherit) { if (SirenixEditorGUI.IconButton(EditorIcons.X)) { if (ActState == ActionState.Override) { ActState = ActionState.Inherit; var baseEditor = HomeConfig.Instance.GetActorEditor(_actorEditor.BaseName); ModelActionEditor action = null; if (IsSkillAction) action = baseEditor.SkillActions.Find(a => a.ActionName.Equals(ActionName)); else action = baseEditor.GeneralActions.Find(a => a.ActionName.Equals(ActionName)); OtherModelName = action.OtherModelName; ActionClip = action.ActionClip; } else { if (IsSkillAction) _actorEditor.SkillActions.Remove(this); else _actorEditor.GeneralActions.Remove(this); } } } else { GUILayout.Label("", GUILayout.Width(18), GUILayout.Height(18)); } EditorGUILayout.EndHorizontal(); } private void LoadSequence() { HomeConfig.Instance.OpenSequence(_actorEditor, this); } private void Modifier() { ActionWindow.Init(_actorEditor, this, false, (a) => { if (a.ActState == ActionState.Inherit) a.ActState = ActionState.Override; OnCfgChange(); }); } public ActionState ActState { get; set; } public ModelActionEditor() { } public ModelActionEditor(ActorConfigEditor actorEditor, GeneralAction modelAction, bool isSkill) { ModelAction = modelAction; IsSkillAction = isSkill; _actorEditor = actorEditor; } public void ResetActorEditor(ActorConfigEditor actorEditor) { _actorEditor = actorEditor; OnCfgChange(); } public override bool Equals(object obj) { ModelActionEditor other = obj as ModelActionEditor; if (other == null) return false; bool result = other.IsFromOther.Equals(IsFromOther); result &= other.OtherModelName.Equals(OtherModelName); result &= other.ActionClip.Equals(ActionClip); return result; } public bool IsFromOther { get { return !string.IsNullOrEmpty(ModelAction.OtherModelName); } } [OnValueChanged("OnCfgChange")] public string ActionName { get { return string.IsNullOrEmpty(ModelAction.ActionName) ? string.Empty : ModelAction.ActionName; } set { ModelAction.ActionName = value; } } [OnValueChanged("OnCfgChange")] public string OtherModelName { get { return string.IsNullOrEmpty(ModelAction.OtherModelName) ? string.Empty : ModelAction.OtherModelName; } set { ModelAction.OtherModelName = value; } } [OnValueChanged("OnCfgChange")] public string ActionClip { get { return string.IsNullOrEmpty(ModelAction.ActionClip) ? string.Empty : ModelAction.ActionClip; } set { ModelAction.ActionClip = value; } } public bool IsSelected { get; set; } private void OnCfgChange() { _actorEditor.OnCfgChange(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.AllType { public class M1 : Cfg.AllType.SingleClass { /// <summary> /// 继承1 /// <summary> public readonly long V3; public M1(DataStream data) : base(data) { this.V3 = data.GetLong(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.AllType { public class M2 : Cfg.AllType.SingleClass { /// <summary> /// 继承2 /// <summary> public readonly bool V4; public M2(DataStream data) : base(data) { this.V4 = data.GetBool(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class SkillAction : Cfg.Skill.GeneralAction { /// <summary> /// 默认后续技能使用期限,用于单个技能多段输出 /// <summary> public const float EXPIRE_TIME = 1f; /// <summary> /// 后续技能使用期限,用于单个技能多段输出 /// <summary> public readonly float SkillExpireTime; /// <summary> /// 技能结束时间 /// <summary> public readonly float SkillEndTime; /// <summary> /// 是否可被打断 /// <summary> public readonly bool CanInterrupt; /// <summary> /// 技能锁定对象类型(0不需要目标 1敌方目标 ,2己方目标 3自己 4中立方) /// <summary> public readonly int LockType; /// <summary> /// 技能作用范围[半径] /// <summary> public readonly float SkillRange; /// <summary> /// 是否显示技能范围 /// <summary> public readonly bool CanShowSkillRange; /// <summary> /// 放技能时人是否可以转动 /// <summary> public readonly bool CanRotate; /// <summary> /// 放技能时人是否可以移动 /// <summary> public readonly bool CanMove; /// <summary> /// 序列字典集合 /// <summary> public readonly Dictionary<int, Sequence> SequenceDict = new Dictionary<int, Sequence>(); public SkillAction(DataStream data) : base(data) { this.SkillExpireTime = data.GetFloat(); this.SkillEndTime = data.GetFloat(); this.CanInterrupt = data.GetBool(); this.LockType = data.GetInt(); this.SkillRange = data.GetFloat(); this.CanShowSkillRange = data.GetBool(); this.CanRotate = data.GetBool(); this.CanMove = data.GetBool(); for (int n = data.GetInt(); n-- > 0;) { int k = data.GetInt(); this.SequenceDict[k] = new Sequence(data); } } } } <file_sep>using UnityEngine; using System.Collections; using System; namespace Flux { public abstract class FController : FEvent { [SerializeField, HideInInspector] [FEventField("资源路径"), FFindPathBtn] protected string _path; public override string Text { get { string[] nodes = _path == null ? null : _path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string tip = "Miss"; if (nodes != null && nodes.Length > 0) tip = nodes[nodes.Length - 1]; return tip; } set { } } } } <file_sep>namespace AssetManager { using UnityEditor; using UnityEngine; using Sirenix.OdinInspector.Editor; using Sirenix.Utilities.Editor; using Sirenix.Utilities; using System.Collections.Generic; using System.Linq; public class AssetImporter : OdinMenuEditorWindow { [MenuItem("Assets/资源导入设置", false, 2001)] private static void Open() { Instance = GetWindow<AssetImporter>("资源导入设置"); Instance.position = GUIHelper.GetEditorWindowRect().AlignCenter(800, 500); ImporterConfig.LoadInstanceIfAssetExists(); Instance._import = new GUIContent(EditorIcons.Refresh.Raw); Instance._importAll = new GUIContent("导入当前配置"); } public static AssetImporter Instance; public void RefreshTree() { OdinMenuTree MenuTree = Instance.MenuTree; var items = MenuTree.MenuItems; for (int i = 0; i < items.Count; i++) { items[i].ChildMenuItems.Clear(); } SetMenuTree(MenuTree); MenuTree.UpdateMenuTree(); } readonly HashSet<string> settings = new HashSet<string>() { TAB_TEXTURE, TAB_MODEL, TAB_AUDIO }; const string TAB_TEXTURE = "#贴图配置"; const string TAB_MODEL = "#模型配置"; const string TAB_AUDIO = "#音效配置"; GUIContent _import; GUIContent _importAll; protected override OdinMenuTree BuildMenuTree() { var tree = new OdinMenuTree(false); tree.Config.DrawSearchToolbar = true; SetMenuTree(tree); EditorUtility.ClearProgressBar(); return tree; } public void SetMenuTree(OdinMenuTree tree) { var texConfigs = ImporterConfig.Instance.TextureConfigs; ImporterConfig.Instance.LoadTexture(tree, TAB_TEXTURE); var texOverView = new AssetImpCfgOverview<TextureImpConfig>(texConfigs); tree.Add(TAB_TEXTURE, texOverView, EditorIcons.SettingsCog); var modelConfigs = ImporterConfig.Instance.ModelConfigs; ImporterConfig.Instance.LoadModel(tree, TAB_MODEL); var modelOverview = new AssetImpCfgOverview<ModelImpConfig>(modelConfigs); tree.Add(TAB_MODEL, modelOverview, EditorIcons.SettingsCog); var audioClipConfigs = ImporterConfig.Instance.AudioClipConfigs; ImporterConfig.Instance.LoadAudioClip(tree, TAB_AUDIO); var audioClipOverview = new AssetImpCfgOverview<AudioClipImpConfig>(audioClipConfigs); tree.Add(TAB_AUDIO, audioClipOverview, EditorIcons.SettingsCog); } private void ClearTree() { var items = MenuTree.MenuItems; for (int i = 0; i < items.Count; i++) { items[i].ChildMenuItems.Clear(); } } protected override void OnBeginDrawEditors() { var selected = MenuTree.Selection.FirstOrDefault(); var toolbarHeight = this.MenuTree.Config.SearchToolbarHeight; if (selected == null) return; // Draws a toolbar with the name of the currently selected menu item. SirenixEditorGUI.BeginHorizontalToolbar(toolbarHeight); { if (selected != null) { GUILayout.Label(selected.Name); } if (!settings.Contains(selected.SmartName)) { if (SirenixEditorGUI.ToolbarButton(_import)) { (selected.ObjectInstance as AssetOption).ReimportAsset(); } } else { if (SirenixEditorGUI.ToolbarButton(_importAll)) { var child = selected.ChildMenuItems; for (int i = 0; i < child.Count; i++) (child[i].ObjectInstance as AssetOption).ReimportAsset(); } } } SirenixEditorGUI.EndHorizontalToolbar(); } protected override void OnDestroy() { base.OnDestroy(); ImporterConfig.Instance.ClearInvalidPath(); EditorUtility.SetDirty(ImporterConfig.Instance); EditorUtility.UnloadUnusedAssetsImmediate(); AssetDatabase.Refresh(); } } } <file_sep>using UnityEngine; using UnityEditor; using UnityEditorInternal; using System; using System.Collections.Generic; using System.Reflection; using Flux; namespace FluxEditor { [CustomEditor(typeof(Flux.FEvent), true)] [CanEditMultipleObjects] public class FEventInspector : Editor { private const string FRAMERANGE_START_FIELD_ID = "FrameRange.Start"; private FEvent _evt; private bool _allEventsSameType = true; private bool _isSingleFrame = false; // protected SerializedProperty _script; protected SerializedProperty _triggerOnSkip; protected SerializedProperty _singleFrame; protected GUIContent _singleFrameUI = new GUIContent("单帧:"); private List<FieldDraw> _fields = new List<FieldDraw>(); class FieldDraw { public GUIContent DisplayName; public SerializedProperty Property; public bool AddFindBtn; } protected virtual void OnEnable() { if (target == null) { DestroyImmediate(this); return; } _evt = (Flux.FEvent)target; Type evtType = _evt.GetType(); for (int i = 0; i != targets.Length; ++i) { FEvent evt = (FEvent)targets[i]; if (evtType != evt.GetType()) { _allEventsSameType = false; break; } } // _script = serializedObject.FindProperty("m_Script"); _singleFrame = serializedObject.FindProperty("_singleFrame"); if (_allEventsSameType) { _triggerOnSkip = serializedObject.FindProperty("_triggerOnSkip"); } _fields.Clear(); var fields = evtType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); foreach (var f in fields) { //if (!f.DeclaringType.Equals(evtType)) continue; if (!typeof(FEvent).IsAssignableFrom(evtType)) continue; var attributes0 = f.GetCustomAttributes(typeof(FEventField), false); if (attributes0 != null && attributes0.Length > 0) { string alias = (attributes0[0] as FEventField).Name; string tip = (attributes0[0] as FEventField).Tip; SerializedProperty property = serializedObject.FindProperty(f.Name); bool needAddBtn = false; var attributes1 = f.GetCustomAttributes(typeof(FFindPathBtn), false); if (attributes1 != null && attributes1.Length > 0) needAddBtn = true; _fields.Add(new FieldDraw() { DisplayName = new GUIContent(alias, tip), Property = property, AddFindBtn = needAddBtn }); } } object[] customAttributes = evtType.GetCustomAttributes(typeof(FEventAttribute), false); if (customAttributes.Length > 0) _isSingleFrame = ((FEventAttribute)customAttributes[0]).isSingleFrame; } public override void OnInspectorGUI() { // EditorGUILayout.PropertyField( _script ); if (_allEventsSameType) { serializedObject.Update(); EditorGUILayout.PropertyField(_triggerOnSkip, new GUIContent("跳过触发器")); } else { bool triggerOnSkipMatch = true; for (int i = 0; i != targets.Length; ++i) { if (((FEvent)targets[i]).TriggerOnSkip != _evt.TriggerOnSkip) { triggerOnSkipMatch = false; break; } } EditorGUI.BeginChangeCheck(); bool triggerOnSkip = EditorGUILayout.Toggle("跳过触发器", _evt.TriggerOnSkip, triggerOnSkipMatch ? EditorStyles.toggle : "ToggleMixed"); if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(targets, " Inspector"); for (int i = 0; i != targets.Length; ++i) { FEvent evt = (FEvent)targets[i]; evt.TriggerOnSkip = triggerOnSkip; } } } // EditorGUILayout.IntField( "Instance ID", _evt.GetInstanceID() ); FrameRange validRange = _evt.Track != null ? _evt.Track.GetValidRange(_evt) : new FrameRange(_evt.Start, _evt.End); if (!_isSingleFrame) { float startFrame = _evt.Start; float endFrame = _evt.End; EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("范围"); GUILayout.Label("开始:", EditorStyles.label); GUI.SetNextControlName(FRAMERANGE_START_FIELD_ID); startFrame = EditorGUILayout.IntField(_evt.Start); GUILayout.Label("结束:", EditorStyles.label); endFrame = EditorGUILayout.IntField(_evt.End); EditorGUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) { bool changedStart = GUI.GetNameOfFocusedControl() == FRAMERANGE_START_FIELD_ID; for (int i = 0; i != targets.Length; ++i) { FEvent evt = (FEvent)targets[i]; FrameRange newFrameRange = evt.FrameRange; if (changedStart) { if (startFrame <= newFrameRange.End) newFrameRange.Start = (int)startFrame; } else if (endFrame >= newFrameRange.Start) newFrameRange.End = (int)endFrame; if (newFrameRange.Length >= evt.GetMinLength() && newFrameRange.Length <= evt.GetMaxLength()) { FSequenceEditorWindow.instance.GetSequenceEditor().MoveEvent(evt, newFrameRange); FEventEditor.FinishMovingEventEditors(); // FUtility.Resize( evt, newFrameRange ); } } } if (targets.Length == 1) { EditorGUI.BeginChangeCheck(); EditorGUILayout.BeginHorizontal(); GUILayout.Space(EditorGUIUtility.labelWidth); float sliderStartFrame = startFrame; float sliderEndFrame = endFrame; EditorGUILayout.MinMaxSlider(ref sliderStartFrame, ref sliderEndFrame, validRange.Start, validRange.End); EditorGUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) { FrameRange newFrameRange = new FrameRange((int)sliderStartFrame, (int)sliderEndFrame); if (newFrameRange.Length < _evt.GetMinLength()) { if (sliderStartFrame != startFrame) // changed start newFrameRange.Start = newFrameRange.End - _evt.GetMinLength(); else newFrameRange.Length = _evt.GetMinLength(); } // FUtility.Resize( _evt, newFrameRange ); FSequenceEditorWindow.instance.GetSequenceEditor().MoveEvent(_evt, newFrameRange); FEventEditor.FinishMovingEventEditors(); } } } else { EditorGUI.BeginChangeCheck(); EditorGUILayout.IntSlider(_singleFrame, validRange.Start + 1, validRange.End, _singleFrameUI); if (EditorGUI.EndChangeCheck()) { _evt.SingleFrame = _singleFrame.intValue; FrameRange newFrameRange = _evt.FrameRange; newFrameRange.Start = _evt.SingleFrame - 1; newFrameRange.End = _evt.SingleFrame; FSequenceEditorWindow.instance.GetSequenceEditor().MoveEvent(_evt, newFrameRange); FEventEditor.FinishMovingEventEditors(); } } if (_allEventsSameType) { serializedObject.ApplyModifiedProperties(); base.OnInspectorGUI(); serializedObject.Update(); foreach (var field in _fields) { if (field.AddFindBtn) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(field.Property, field.DisplayName); if (GUILayout.Button("F", GUILayout.Width(30))) { UnityEngine.Object obj = Selection.activeObject; string path = AssetDatabase.GetAssetPath(obj); if (obj != null && string.IsNullOrEmpty(path)) { path = GetSceneNodePath((obj as GameObject).transform); field.Property.stringValue = path; } else if (!string.IsNullOrEmpty(path)) field.Property.stringValue = path; } EditorGUILayout.EndHorizontal(); } else EditorGUILayout.PropertyField(field.Property, field.DisplayName); } serializedObject.ApplyModifiedProperties(); } } private string GetSceneNodePath(Transform node) { string path = node.name; while (node.parent != null) { path = string.Format("{0}/{1}", node.parent.name, path); node = node.parent; } return "/" + path; } public static void OnInspectorGUIGeneric(List<FEvent> evts) { if (evts.Count == 0) return; bool triggerOnSkipMatch = true; int startFrame = evts[0].Start; int endFrame = evts[0].End; bool startFrameMatch = true; bool endFrameMatch = true; for (int i = 1; i < evts.Count; ++i) { if (evts[i].TriggerOnSkip != evts[0].TriggerOnSkip) { triggerOnSkipMatch = false; } if (evts[i].Start != startFrame) { startFrameMatch = false; } if (evts[i].End != endFrame) { endFrameMatch = false; } } EditorGUI.BeginChangeCheck(); bool triggerOnSkip = EditorGUILayout.Toggle("跳过触发器", evts[0].TriggerOnSkip, triggerOnSkipMatch ? EditorStyles.toggle : "ToggleMixed"); if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(evts.ToArray(), "Inspector"); for (int i = 0; i < evts.Count; ++i) { evts[i].TriggerOnSkip = triggerOnSkip; EditorUtility.SetDirty(evts[i]); } } // FrameRange validRange = _evt.GetTrack().GetValidRange( _evt ); EditorGUI.BeginChangeCheck(); // foreach( GUIStyle style in GUI.skin.customStyles ) // { //// if( style.name.ToLower().Contains( "" ) ) // Debug.Log( style.name ); // } EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("范围"); GUILayout.Label("开始:", EditorStyles.label); GUI.SetNextControlName(FRAMERANGE_START_FIELD_ID); startFrame = EditorGUILayout.IntField(startFrame, startFrameMatch ? EditorStyles.numberField : "PR TextField"); GUILayout.Label("结束:", EditorStyles.label); endFrame = EditorGUILayout.IntField(endFrame, endFrameMatch ? EditorStyles.numberField : "PR TextField"); EditorGUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) { // bool changedStart = GUI.GetNameOfFocusedControl() == FRAMERANGE_START_FIELD_ID; // for( int i = 0; i != targets.Length; ++i ) // { // FEvent evt = (FEvent)targets[i]; // // FrameRange newFrameRange = evt.FrameRange; // if( changedStart ) // { // if( startFrame <= newFrameRange.End ) // newFrameRange.Start = (int)startFrame; // } // else if( endFrame >= newFrameRange.Start ) // newFrameRange.End = (int)endFrame; // // if( newFrameRange.Length >= evt.GetMinLength() && newFrameRange.Length <= evt.GetMaxLength() ) // { // FSequenceEditorWindow.instance.GetSequenceEditor().MoveEvent( evt, newFrameRange ); // // FUtility.Resize( evt, newFrameRange ); // } // } } } } } <file_sep>using UnityEngine; using UnityEditor; using UnityEditor.Animations; //using UnityEditorInternal; using System.Collections.Generic; using Flux; using FluxEditor; namespace FluxEditor { public abstract class FOwnerTrackInspector : FTrackInspector { private SerializedProperty _owner = null; private GUIContent _ownerUI; protected virtual string OwnerName { get { return "角色"; } } public override void OnEnable() { base.OnEnable(); if (target == null) { DestroyImmediate(this); return; } _owner = serializedObject.FindProperty("_owner"); _ownerUI = new GUIContent(OwnerName); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(_owner, _ownerUI); if (EditorGUI.EndChangeCheck()) OnChangeCharacter(); } protected virtual void OnChangeCharacter() { } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Game { public class AppConst { public const bool DebugMode = false; //是否为调试模式 public const bool EnableProfile = false; //是否激活Profile功能 public const int FrameRate = 30; //游戏帧率 #if UNITY_IPHONE public const int Resolution = 1080; //分辨率配置 #else public const int Resolution = 810; //分辨率配置 #endif } } <file_sep>local insert = table.insert local concat = table.concat local schar = string.char local sbyte = string.byte local find = string.find local sub = string.sub local pairs = pairs local ipairs = ipairs local math = math local traceback = debug.traceback local xpcall = xpcall local LogError = LogError local Util = {} local this = Util --错误处理机制 function Util.ErrHandler(e) LogError(traceback()) end function Util.Myxpcall(func, data) return xpcall(function() func(data) end, this.ErrHandler) end --字符串转整数 function Util.ToLong(s) local n = 0 for i = #s, 1, -1 do n = n * 256 + sbyte(s, i) end return n end function Util.BytesToString(bytes) local d = {} for i = 1, bytes.Length do local x = bytes[i] insert(d, schar(x >= 0 and x or x + 256)) end return concat(d) end --获取或创建类表 function Util.GetOrCreate(namespace) local t = _G local idx = 1 while true do local start, ends = find(namespace, ".", idx, true) local subname = sub(namespace, idx, start and start - 1) local subt = t[subname] if not subt then subt = {} t[subname] = subt end t = subt if start then idx = ends + 1 else return t end end end function Util.InsidePolygon(polygon, p) local N = #polygon local counter = 0 local i local xinters local p1 local p2 p1 = polygon[1] for i = 2, (N + 1) do if (i % N == 0) then p2 = polygon[i] else p2 = polygon[i % N] end if (p.z > math.min(p1.z, p2.z)) then if (p.z <= math.max(p1.z, p2.z)) then if (p.x <= math.max(p1.x, p2.x)) then if (p1.z ~= p2.z) then xinters = (p.z - p1.z) * (p2.x - p1.x) / (p2.z - p1.z) + p1.x if ((p1.x == p2.x) or (p.x <= xinters)) then counter = counter + 1 end end end end end p1 = p2 end if (counter % 2 == 0) then return false else return true end end --判断一个点是否在一个任意多边形内 function Util.InsideAnyPolygon(polygon, p) local count = 0 local n = #polygon local a local b a = polygon[1] for i = 2, n + 1 do if (i % n == 0) then b = polygon[i] else b = polygon[i % n] end if ((a.x <= p.x and p.x <= b.x) or (b.x <= p.x and p.x <= a.x)) then local r = (p.x - a.x) * (a.z - b.z) - (p.z - a.z) * (a.x - b.x) if (r == 0) then -- 在边上 if (a.x ~= p.x or p.x ~= b.x or (a.z <= p.z and p.z <= b.z) or (b.z <= p.z and p.z <= a.z)) then return true end elseif (r / (a.x - b.x) > 0) then count = count + 1 end end a = b end return (count % 2 == 1) end --获取枚举名 function Util.GetEnumName(enumtype, enumvalue) for name, value in pairs(enumtype) do if value == enumvalue then return name end end return "" end --设置粒子特效scale function Util.SetParticleSystemScale(gameObject, scale) if not gameObject or not scale or scale <= 0 or scale == 1 then return end local allParticleSystem = gameObject:GetComponentsInChildren(CS.UnityEngine.ParticleSystem, true) for i = 1, allParticleSystem.Length do local particleSystem = allParticleSystem[i] if particleSystem then particleSystem.startSize = particleSystem.startSize * scale particleSystem.startSpeed = particleSystem.startSpeed * scale end end end --获取默认组件 function Util.GetDefaultComponent(go, com) if go then local component = go:GetComponent(com) if not component then component = go:AddComponent(com) end return component end return nil end function Util.IsChinese(val) --4e00-u9fa5 local ret = val >= 0x4E00 and val <= 0x9FA5 if ret then printcolor("IsChinese") end return ret end --对应ACSII表 local ExpCharacters = { 91, 93, 62, 60, 63, 92, 47, 46, 44, 42, 35, 33, 38, 40, 41, 96, 58, 61, 59 } function Util.IsInExpCharacters(c) for _, char in ipairs(ExpCharacters) do if c == char then return true end end return false end function Util.IsCharacter(bt) local ret = (bt >= 48 and bt <= 57) or (bt >= 65 and bt <= 90) or (bt >= 97 and bt <= 122) or this.IsInExpCharacters(bt) if ret then printcolor("IsCharacter") end return ret end return Util --local exceptions_mask --local masks = { 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC } --local value_masks = { 0x7F, 0x1F, 0x0F, 0x07, 0x03, 0x01 } -- --function Util.IsExsception(val) -- if not exceptions_mask then -- exceptions_mask = {} -- local path = LuaHelper.GetPath("config/encode.txt") -- local file = io.open(path, "r") -- if file then -- while true do -- local num = file:read("*number") -- if not num then -- break -- end -- -- printcolor("num = ",num,#exceptions_mask+1) -- table.insert(exceptions_mask, num) -- end -- file:close() -- end -- end -- local ret = this.BinSearch(exceptions_mask, val) -- if ret then -- printcolor("IsExsception") -- end -- return ret --bin_search(exceptions_mask,val) --end --function Util.GetBytesValue(bytes, len) -- local ret = 0 -- local msk = 0x3F -- ret = Bit.band(bytes[1], value_masks[len]) -- for i = 2, len do -- ret = Bit.lshift(ret, 6) -- ret = Bit.bor(ret, Bit.band(bytes[i], msk)) -- end -- return ret --end --function Util.CheckName(name) -- name = string.gsub(name, "%[%a%]", "") -- name = string.gsub(name, "%[%a%a%]", "") -- name = string.gsub(name, "%[%x%x%x%x%x%x%]", "") -- -- read exceptions mask -- local errmgr = require "assistant.errormanager" -- -- local len = 0 -- local k = 1 -- while (k <= #name) do -- local bt = string.byte(name, k) -- if not bt then -- break -- end -- if len == 6 then -- exceptions_mask = nil -- return false, errmgr.GetErrorText(2803) -- end -- if this.IsCharacter(bt) then -- len = len + 1 -- else -- local code_len = 0 -- for i = 6, 1, -1 do -- if Bit.band(masks[i], bt) == masks[i] then -- code_len = i -- break -- end -- end -- local bytes = { bt } -- if code_len > 0 then -- -- printcolor("code_len",code_len) -- for i = 2, code_len do -- local sbt = string.byte(name, k + i - 1) -- table.insert(bytes, sbt) -- end -- local val = this.GetBytesValue(bytes, code_len) -- -- printcolor("val = ",val) -- if this.IsChinese(val) or this.IsExsception(val) then -- k = k + code_len - 1 -- len = len + 1 -- else -- exceptions_mask = nil -- return false, LocalString.ERR_ILLEAGE_NAME -- end -- else -- exceptions_mask = nil -- return false, LocalString.ERR_WRONG_NAME -- end -- end -- k = k + 1 -- end -- exceptions_mask = nil -- return true, name --end<file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Character { public class Model : CfgObject { /// <summary> /// 模型名称 /// <summary> public readonly string Name; /// <summary> /// 模型分组类型 /// <summary> public readonly int GroupType; /// <summary> /// 模型路径 /// <summary> public readonly string ModelPath; /// <summary> /// Avatar路径 /// <summary> public readonly string AvatarPath; /// <summary> /// 碰撞体半径 /// <summary> public readonly float BodyRadius; /// <summary> /// 碰撞体高度 /// <summary> public readonly float BodyHeight; /// <summary> /// 模型缩放 /// <summary> public readonly float ModelScale; public Model(DataStream data) { this.Name = data.GetString(); this.GroupType = data.GetInt(); this.ModelPath = data.GetString(); this.AvatarPath = data.GetString(); this.BodyRadius = data.GetFloat(); this.BodyHeight = data.GetFloat(); this.ModelScale = data.GetFloat(); } } } <file_sep>namespace AssetManager { using System; using UnityEngine; using Sirenix.OdinInspector; using System.Collections.Generic; using UnityEditor; using System.IO; using System.Text; using System.Linq; [Serializable] public class TextureImportSetting : AssetOption { [ShowInInspector, ReadOnly, LabelText("路径"), PropertyOrder(-1)] public override string Path { get { return base.Path; } set { base.Path = value; } } readonly int[] MAX_SIZE = { 32, 64, 128, 256, 512, 1024, 2048, 4096 }; readonly string[] PLATFORM = { "Window", "Android", "IOS" }; [BoxGroup("导入设置")] public TextureImporterType ImportType = TextureImporterType.Default; [BoxGroup("导入设置")] public TextureImporterNPOTScale TextureNPOT = TextureImporterNPOTScale.ToNearest; [BoxGroup("导入设置"), LabelText("Read/Write Enabled")] public bool IsReadable = false; [BoxGroup("导入设置")] public bool IsTransparency = false; [BoxGroup("导入设置")] public bool GenerateMipmap = false; [BoxGroup("导入设置")] public TextureWrapMode WrapMode = TextureWrapMode.Clamp; [BoxGroup("导入设置")] public FilterMode Filter = FilterMode.Bilinear; [BoxGroup("导入设置"), Range(0, 16)] public int AnisoLevel = 1; //---Window [TabGroup("导入设置/Platform", "Window"), ValueDropdown("MAX_SIZE"), LabelText("MaxSize")] public int WindowMaxSize = 1024; [TabGroup("导入设置/Platform", "Window"), LabelText("Format")] public TextureImporterFormat WindowImporterFormat = TextureImporterFormat.RGBA32; //---Android [TabGroup("导入设置/Platform", "Android"), ValueDropdown("MAX_SIZE"), LabelText("MaxSize")] public int AndroidMaxSize = 1024; [TabGroup("导入设置/Platform", "Android"), LabelText("Format")] public TextureImporterFormat AndroidImporterFormat = TextureImporterFormat.RGBA32; //---IOS [TabGroup("导入设置/Platform", "IOS"), ValueDropdown("MAX_SIZE"), LabelText("MaxSize")] public int IOSMaxSize = 1024; [TabGroup("导入设置/Platform", "IOS"), LabelText("Format")] public TextureImporterFormat IOSImporterFormat = TextureImporterFormat.RGBA32; /// <summary> /// 按照配置重新导入资源 /// </summary> public override void ReimportAsset() { base.ReimportAsset(); ClearAsset(); List<string> files = new List<string>(Directory.GetFiles(Path, "*.*", SearchOption.AllDirectories) .Where(f => f.EndsWith(".png") || f.EndsWith(".jpg") || f.EndsWith(".tga") || f.EndsWith(".psd"))); for (int i = 0; i < files.Count; i++) { string refPath = files[i].Replace(Application.dataPath, "Assets").Replace("\\", "/"); UnityEditor.TextureImporter importer = UnityEditor.TextureImporter.GetAtPath(refPath) as UnityEditor.TextureImporter; importer.textureType = ImportType; importer.npotScale = TextureNPOT; importer.isReadable = IsReadable; importer.alphaIsTransparency = IsTransparency; importer.mipmapEnabled = GenerateMipmap; importer.wrapMode = WrapMode; importer.filterMode = Filter; importer.anisoLevel = AnisoLevel; importer.SetPlatformTextureSettings(BuildTarget.StandaloneWindows.ToString(), WindowMaxSize, WindowImporterFormat); importer.SetPlatformTextureSettings(BuildTarget.Android.ToString(), AndroidMaxSize, AndroidImporterFormat, true); importer.SetPlatformTextureSettings(BuildTarget.iOS.ToString(), IOSMaxSize, IOSImporterFormat); importer.SaveAndReimport(); EditorUtility.DisplayProgressBar("按配置导入纹理", refPath, (i + 1f) / files.Count); } EditorUtility.UnloadUnusedAssetsImmediate(); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } } }<file_sep>using UnityEngine; using UnityEditor; using System; using System.IO; using System.Collections.Generic; using Flux; using Object = UnityEngine.Object; namespace FluxEditor { public enum TimeFormat { Frames = 0, Seconds, SecondsFormatted } public class FSequenceEditorWindow : EditorWindow { public const string MENU_PATH = ""; public const string PRODUCT_NAME = "Flux"; #region Menus [MenuItem(MENU_PATH + PRODUCT_NAME + "/Open Editor %&c", false, 0)] public static void Open() { FSequenceEditorWindow window = GetWindow<FSequenceEditorWindow>(); window.Show(); window.titleContent = new GUIContent(PRODUCT_NAME); window.Update(); } public static void Open(FSequence sequence) { Open(); instance._sequenceEditor.OpenSequence(sequence); } [MenuItem(MENU_PATH + PRODUCT_NAME + "/Create Sequence", false, 100)] public static FSequence CreateSequence(string seqName = null) { // find new name & priority for sequence string sequenceNameFormat = "Sequence_{0}"; int sequenceId = 0; string sequenceName = string.IsNullOrEmpty(seqName) ? string.Format(sequenceNameFormat, sequenceId.ToString("000")) : seqName; FSequence[] sequences = FindObjectsOfType<FSequence>(); for (int i = 0, limit = sequences.Length; i != limit; ++i) { if (sequences[i].name == sequenceName) { // try new name ++sequenceId; sequenceName = string.Format(sequenceNameFormat, sequenceId.ToString("000")); i = -1; // restart search } } FSequence sequence = FSequence.CreateSequence(); sequence.name = sequenceName; sequence.FrameRate = FUtility.FrameRate; sequence.Length = sequence.FrameRate * FSequence.DEFAULT_LENGTH; Undo.RegisterCreatedObjectUndo(sequence.gameObject, "Create Sequence"); return sequence; } //[MenuItem(MENU_PATH + PRODUCT_NAME + "/Website", false, 200)] //public static void OpenWebsite() //{ // Application.OpenURL("http://www.fluxeditor.com"); //} //[MenuItem(MENU_PATH + PRODUCT_NAME + "/Contact Support", false, 201)] //public static void ContactSupport() //{ // Application.OpenURL("mailto:<EMAIL>"); //} #endregion public static FSequenceEditorWindow instance = null; // size of the whole window, cached to determine if it was resized private Rect _windowRect; // rect used for the header at the top of the window private Rect _windowHeaderRect; // header private FSequenceWindowHeader _windowHeader; // toolbar private FSequenceWindowToolbar _toolbar; // area for the toolbar private Rect _toolbarRect; [SerializeField] private FSequenceEditor _sequenceEditor; void OnEnable() { instance = this; wantsMouseMove = true; minSize = new Vector2(450, 300); _windowHeader = new FSequenceWindowHeader(this); _toolbar = new FSequenceWindowToolbar(this); _windowRect = new Rect(); FUtility.LoadPreferences(); } void OnSelectionChange() { if (!FUtility.OpenSequenceOnSelect) return; FSequence sequence = Selection.activeGameObject == null || PrefabUtility.GetPrefabType(Selection.activeGameObject) == PrefabType.Prefab ? null : Selection.activeGameObject.GetComponent<FSequence>(); if (sequence != null) { Open(sequence); } } public FSequenceEditor GetSequenceEditor() { return _sequenceEditor; } void OnDestroy() { if (_sequenceEditor != null) { _sequenceEditor.Stop(); DestroyImmediate(_sequenceEditor); } } void OnLostFocus() { } #region Editor state changes hookups private void OnDidOpenScene() { if (_sequenceEditor) _sequenceEditor.OpenSequence(null); } #endregion public bool IsPlaying { get { return _sequenceEditor.IsPlaying; } } void Update() { #if FLUX_PROFILE Profiler.BeginSample("flux Update"); #endif if (_sequenceEditor == null) { _sequenceEditor = FSequenceEditor.CreateInstance<FSequenceEditor>(); _sequenceEditor.Init(this); } FSequence sequence = _sequenceEditor.Sequence; if (Application.isPlaying && sequence != null && FUtility.RenderOnEditorPlay) { Repaint(); } _sequenceEditor.Update(); #if FLUX_PROFILE Profiler.EndSample(); #endif } public void Play(bool restart) { _sequenceEditor.IsPlayingForward = true; _sequenceEditor.Play(restart); } public void PlayBackwards(bool restart) { _sequenceEditor.IsPlayingForward = false; _sequenceEditor.Play(restart); } public void Pause() { _sequenceEditor.Pause(); } public void Stop() { _sequenceEditor.Stop(); } private void RebuildLayout() { _windowRect = position; _windowRect.x = 0; _windowRect.y = 0; _windowHeaderRect = _windowRect; _windowHeaderRect.height = FSequenceWindowHeader.HEIGHT; _windowHeader.RebuildLayout(_windowHeaderRect); _toolbarRect = _windowRect; _toolbarRect.yMin = _toolbarRect.yMax - FSequenceWindowToolbar.HEIGHT; _toolbar.RebuildLayout(_toolbarRect); Rect timelineViewRect = _windowRect; timelineViewRect.yMin += FSequenceWindowHeader.HEIGHT; timelineViewRect.yMax -= FSequenceWindowToolbar.HEIGHT; _sequenceEditor.RebuildLayout(timelineViewRect); Repaint(); } public void Refresh() { if (_sequenceEditor != null) { _sequenceEditor.OpenSequence(_sequenceEditor.Sequence); } Repaint(); } public static void RefreshIfOpen() { if (instance != null) instance.Refresh(); } void OnGUI() { #if FLUX_PROFILE Profiler.BeginSample("Flux OnGUI"); #endif if (_sequenceEditor == null) return; Rect currentWindowRect = position; currentWindowRect.x = 0; currentWindowRect.y = 0; if (currentWindowRect != _windowRect) { RebuildLayout(); } if (!FUtility.RenderOnEditorPlay && EditorApplication.isPlaying && !EditorApplication.isPaused) { GUI.Label(_windowRect, "Draw in play mode is disabled. You can change it on Flux Preferences"); return; } FSequence sequence = _sequenceEditor.Sequence; if (sequence == null) ShowNotification(new GUIContent("Select Or Create Sequeuce")); else if (Event.current.isKey) { if (Event.current.keyCode == KeyCode.Space) { if (Event.current.type == EventType.KeyUp) { if (_sequenceEditor.IsPlaying) { if (Event.current.shift) Stop(); else Pause(); } else Play(Event.current.shift); Repaint(); } Event.current.Use(); } if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return) { EditorGUIUtility.keyboardControl = 0; Event.current.Use(); Repaint(); } } // header _windowHeader.OnGUI(); if (sequence == null) return; // toolbar _toolbar.OnGUI(); switch (Event.current.type) { case EventType.KeyDown: if (Event.current.keyCode == KeyCode.Backspace || Event.current.keyCode == KeyCode.Delete) { _sequenceEditor.DestroyEvents(_sequenceEditor.EventSelection.Editors); Event.current.Use(); } else if (Event.current.keyCode == KeyCode.K && _sequenceEditor.Sequence.CurrentFrame >= 0) { _sequenceEditor.AddEvent(_sequenceEditor.Sequence.CurrentFrame); Event.current.Use(); } // else if( Event.current.keyCode == KeyCode.C && _sequenceEditor.GetSequence().GetCurrentFrame() >= 0 ) // { // _sequenceEditor.AddCommentEvent( _sequenceEditor.GetSequence().GetCurrentFrame() ); // Event.current.Use(); // } break; case EventType.MouseDown: break; case EventType.MouseUp: break; } if (Event.current.type == EventType.ValidateCommand) { Repaint(); } _sequenceEditor.OnGUI(); // because of a bug with windows editor, we have to not catch right button // otherwise ContextClick doesn't get called if (Event.current.type == EventType.MouseUp && Event.current.button != 1) { Event.current.Use(); } if (Event.current.type == EventType.Ignore) { EditorGUIUtility.hotControl = 0; } // // handle drag & drop // if( Event.current.type == EventType.DragUpdated ) // { // if( _windowRect.Contains( Event.current.mousePosition ) ) // { // DragAndDrop.visualMode = DragAndDropVisualMode.Link; // Event.current.Use(); // } // } // else if( Event.current.type == EventType.DragPerform ) // { // if( _windowRect.Contains( Event.current.mousePosition ) ) // { // foreach( UnityEngine.Object obj in DragAndDrop.objectReferences ) // { // if( !(obj is GameObject) ) // { // continue; // } // // PrefabType prefabType = PrefabUtility.GetPrefabType(obj); // if( prefabType == PrefabType.ModelPrefab || prefabType == PrefabType.Prefab ) // continue; // // Undo.IncrementCurrentGroup(); // UnityEngine.Object[] objsToSave = new UnityEngine.Object[]{ sequence, this }; // // Undo.RegisterCompleteObjectUndo( objsToSave, string.Empty ); // // GameObject timelineGO = new GameObject(obj.name); // // TODO //// FTimeline timeline = timelineGO.AddComponent<Flux.FTimeline>(); //// timeline.SetOwner( ((GameObject)obj).transform ); //// sequence.Add( timeline ); // //// Undo.RegisterCompleteObjectUndo( objsToSave, string.Empty ); //// Undo.RegisterCreatedObjectUndo( timeline.gameObject, "create Timeline" ); //// Undo.CollapseUndoOperations( Undo.GetCurrentGroup() ); // } // RemoveNotification(); // Event.current.Use(); // DragAndDrop.AcceptDrag(); // Refresh(); // EditorGUIUtility.ExitGUI(); // } // } if (Event.current.type == EventType.Repaint) { Handles.DrawLine(new Vector3(_windowHeaderRect.xMin, _windowHeaderRect.yMax, 0), new Vector3(_windowHeaderRect.xMax - FSequenceEditor.RIGHT_BORDER, _windowHeaderRect.yMax, 0)); } #if FLUX_PROFILE Profiler.EndSample(); #endif } public float GetXForFrame(int frame) { return _sequenceEditor.GetXForFrame(frame); } public int GetFrameForX(float x) { return _sequenceEditor.GetFrameForX(x); } private string FormatTime(float time) { int timeInInt = (int)time; int minutes = timeInInt / 60; int seconds = timeInInt % 60; int deciSeconds = (int)((time - timeInInt) * 100f); return minutes > 0 ? string.Format("{0}:{1}.{2}", minutes.ToString("00"), seconds.ToString("00"), deciSeconds.ToString("00")) : string.Format("{0}.{1}", seconds.ToString("00"), deciSeconds.ToString("00")); } float timelineViewRectHeight; private void RenderHeader(Rect rect) { FSequence sequence = _sequenceEditor.Sequence; GUI.Label(rect, sequence.name); Rect r = rect; r.xMin = r.xMax - 100; EditorGUI.IntField(r, sequence.Length); GUIContent lengthLabel = new GUIContent("Length"); r.x -= EditorStyles.label.CalcSize(lengthLabel).x + 5; EditorGUI.PrefixLabel(r, lengthLabel); r.x -= 50; r.width = 40; EditorGUI.IntField(r, sequence.FrameRate); GUIContent framerateLabel = new GUIContent("Frame Rate"); r.x -= EditorStyles.label.CalcSize(framerateLabel).x + 5; EditorGUI.PrefixLabel(r, framerateLabel); r.x -= 110; r.width = 100; EditorGUI.EnumPopup(r, sequence.UpdateMode); GUIContent updateModeLabel = new GUIContent("Update Mode"); Vector2 updateModeLabelSize = EditorStyles.label.CalcSize(updateModeLabel); r.x -= updateModeLabelSize.x + 5; r.width = updateModeLabelSize.x; EditorGUI.PrefixLabel(r, updateModeLabel); } } } <file_sep>local Stream = require("Cfg.DataStream") local GetOrCreate = Util.GetOrCreate local meta meta= {} meta.__index = meta meta.class = 'Cfg.AllType.AllClass' meta.ConstString = 'Hello World' meta.ConstFloat = 3.141527 GetOrCreate('Cfg.AllType')['AllClass'] = meta function Stream:GetCfgAllTypeAllClass() local o = {} setmetatable(o, Cfg.AllType.AllClass) o.ID = self:GetInt() o.VarLong = self:GetLong() o.VarFloat = self:GetFloat() o.VarString = self:GetString() o.VarBool = self:GetBool() o.VarEnum = self:GetInt() local _VarClass = 'Cfg' .. self:GetString() o.VarClass = self:GetObject(_VarClass) o.VarListBase = self:GetList('String') o.VarListClass = self:GetList('CfgAllTypeSingleClass') o.VarListCardElem = self:GetList('String') o.VarDictBase = self:GetDict('Int', 'String') o.VarDictEnum = self:GetDict('Long', 'Int') o.VarDictClass = self:GetDict('String', 'CfgAllTypeSingleClass') return o end meta= {} meta.__index = meta meta.class = 'Cfg.AllType.SingleClass' GetOrCreate('Cfg.AllType')['SingleClass'] = meta function Stream:GetCfgAllTypeSingleClass() local o = {} setmetatable(o, Cfg.AllType.SingleClass) o.Var1 = self:GetString() o.Var2 = self:GetFloat() return o end meta= {} meta.__index = meta meta.class = 'Cfg.AllType.M1' GetOrCreate('Cfg.AllType')['M1'] = meta function Stream:GetCfgAllTypeM1() local o = {} setmetatable(o, Cfg.AllType.M1) o.V3 = self:GetLong() return o end meta= {} meta.__index = meta meta.class = 'Cfg.AllType.M2' GetOrCreate('Cfg.AllType')['M2'] = meta function Stream:GetCfgAllTypeM2() local o = {} setmetatable(o, Cfg.AllType.M2) o.V4 = self:GetBool() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Character.Model' GetOrCreate('Cfg.Character')['Model'] = meta function Stream:GetCfgCharacterModel() local o = {} setmetatable(o, Cfg.Character.Model) o.Name = self:GetString() o.GroupType = self:GetInt() o.ModelPath = self:GetString() o.AvatarPath = self:GetString() o.BodyRadius = self:GetFloat() o.BodyHeight = self:GetFloat() o.ModelScale = self:GetFloat() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.ActorConfig' GetOrCreate('Cfg.Skill')['ActorConfig'] = meta function Stream:GetCfgSkillActorConfig() local o = {} setmetatable(o, Cfg.Skill.ActorConfig) o.ModelName = self:GetString() o.BaseModelName = self:GetString() o.GeneralActions = self:GetDict('String', 'CfgSkillGeneralAction') o.SkillActions = self:GetDict('String', 'CfgSkillSkillAction') return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.GeneralAction' GetOrCreate('Cfg.Skill')['GeneralAction'] = meta function Stream:GetCfgSkillGeneralAction() local o = {} setmetatable(o, Cfg.Skill.GeneralAction) o.ActionName = self:GetString() o.OtherModelName = self:GetString() o.ActionClip = self:GetString() o.PreActionFile = self:GetString() o.PostActionFile = self:GetString() o.ActionSpeed = self:GetFloat() o.LoopTimes = self:GetInt() o.Timelines = self:GetList('CfgSkillTimeline') return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.SkillAction' meta.EXPIRE_TIME = 1 GetOrCreate('Cfg.Skill')['SkillAction'] = meta function Stream:GetCfgSkillSkillAction() local o = {} setmetatable(o, Cfg.Skill.SkillAction) o.SkillExpireTime = self:GetFloat() o.SkillEndTime = self:GetFloat() o.CanInterrupt = self:GetBool() o.LockType = self:GetInt() o.SkillRange = self:GetFloat() o.CanShowSkillRange = self:GetBool() o.CanRotate = self:GetBool() o.CanMove = self:GetBool() o.SequenceDict = self:GetDict('Int', 'CfgSkillSequence') return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.Sequence' GetOrCreate('Cfg.Skill')['Sequence'] = meta function Stream:GetCfgSkillSequence() local o = {} setmetatable(o, Cfg.Skill.Sequence) o.Id = self:GetInt() o.HitZones = self:GetList('CfgSkillHitZone') o.Timelines = self:GetList('CfgSkillTimeline') return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.HitZone' GetOrCreate('Cfg.Skill')['HitZone'] = meta function Stream:GetCfgSkillHitZone() local o = {} setmetatable(o, Cfg.Skill.HitZone) o.Id = self:GetInt() o.Sharp = self:GetInt() o.Offset = self:GetObject('CfgVector3') o.MaxNum = self:GetInt() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.CubeZone' GetOrCreate('Cfg.Skill')['CubeZone'] = meta function Stream:GetCfgSkillCubeZone() local o = {} setmetatable(o, Cfg.Skill.CubeZone) o.Scale = self:GetObject('CfgVector3') return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.SphereZone' GetOrCreate('Cfg.Skill')['SphereZone'] = meta function Stream:GetCfgSkillSphereZone() local o = {} setmetatable(o, Cfg.Skill.SphereZone) o.Radius = self:GetFloat() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.CylinderZone' GetOrCreate('Cfg.Skill')['CylinderZone'] = meta function Stream:GetCfgSkillCylinderZone() local o = {} setmetatable(o, Cfg.Skill.CylinderZone) o.Radius = self:GetFloat() o.Height = self:GetFloat() o.Angle = self:GetFloat() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.Timeline' GetOrCreate('Cfg.Skill')['Timeline'] = meta function Stream:GetCfgSkillTimeline() local o = {} setmetatable(o, Cfg.Skill.Timeline) o.Start = self:GetInt() o.End = self:GetInt() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.StaticHit' GetOrCreate('Cfg.Skill')['StaticHit'] = meta function Stream:GetCfgSkillStaticHit() local o = {} setmetatable(o, Cfg.Skill.StaticHit) local _Zone = 'Cfg' .. self:GetString() o.Zone = self:GetObject(_Zone) o.SequeueID = self:GetInt() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.DynamicHit' GetOrCreate('Cfg.Skill')['DynamicHit'] = meta function Stream:GetCfgSkillDynamicHit() local o = {} setmetatable(o, Cfg.Skill.DynamicHit) o.Target = self:GetString() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.Controller' GetOrCreate('Cfg.Skill')['Controller'] = meta function Stream:GetCfgSkillController() local o = {} setmetatable(o, Cfg.Skill.Controller) o.Path = self:GetString() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.Active' GetOrCreate('Cfg.Skill')['Active'] = meta function Stream:GetCfgSkillActive() local o = {} setmetatable(o, Cfg.Skill.Active) o.Enable = self:GetBool() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.ReplaceObject' GetOrCreate('Cfg.Skill')['ReplaceObject'] = meta function Stream:GetCfgSkillReplaceObject() local o = {} setmetatable(o, Cfg.Skill.ReplaceObject) o.NewObject = self:GetString() o.Offset = self:GetObject('CfgVector3') o.EulerAngles = self:GetObject('CfgVector3') return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.Move' GetOrCreate('Cfg.Skill')['Move'] = meta function Stream:GetCfgSkillMove() local o = {} setmetatable(o, Cfg.Skill.Move) o.Type = self:GetInt() o.IsRelateSelf = self:GetBool() o.Offset = self:GetObject('CfgVector3') o.Angle = self:GetFloat() o.Speed = self:GetFloat() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.CastObject' GetOrCreate('Cfg.Skill')['CastObject'] = meta function Stream:GetCfgSkillCastObject() local o = {} setmetatable(o, Cfg.Skill.CastObject) o.IsTraceTarget = self:GetBool() o.CurveId = self:GetInt() o.PassBody = self:GetBool() o.Position = self:GetObject('CfgVector3') o.EulerAngles = self:GetObject('CfgVector3') return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.PlayParticle' GetOrCreate('Cfg.Skill')['PlayParticle'] = meta function Stream:GetCfgSkillPlayParticle() local o = {} setmetatable(o, Cfg.Skill.PlayParticle) o.Path = self:GetString() o.IsRelateSelf = self:GetBool() o.FollowDir = self:GetBool() o.NodeName = self:GetString() o.Position = self:GetObject('CfgVector3') o.EulerAngles = self:GetObject('CfgVector3') o.Scale = self:GetObject('CfgVector3') o.AlignType = self:GetInt() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.Buff' GetOrCreate('Cfg.Skill')['Buff'] = meta function Stream:GetCfgSkillBuff() local o = {} setmetatable(o, Cfg.Skill.Buff) o.Id = self:GetInt() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.PlaySound' GetOrCreate('Cfg.Skill')['PlaySound'] = meta function Stream:GetCfgSkillPlaySound() local o = {} setmetatable(o, Cfg.Skill.PlaySound) o.Path = self:GetString() o.Volume = self:GetFloat() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Skill.ShakeScreen' GetOrCreate('Cfg.Skill')['ShakeScreen'] = meta function Stream:GetCfgSkillShakeScreen() local o = {} setmetatable(o, Cfg.Skill.ShakeScreen) o.Type = self:GetInt() o.Frequency = self:GetInt() o.FrequencyDuration = self:GetFloat() o.FrequencyAtten = self:GetFloat() o.Amplitude = self:GetFloat() o.AmplitudeAtten = self:GetFloat() o.MinRange = self:GetFloat() o.MaxRange = self:GetFloat() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Vector2' GetOrCreate('Cfg.')['Vector2'] = meta function Stream:GetCfgVector2() local o = {} setmetatable(o, Cfg..Vector2) o.X = self:GetFloat() o.Y = self:GetFloat() return o end meta= {} meta.__index = meta meta.class = 'Cfg.Vector3' GetOrCreate('Cfg.')['Vector3'] = meta function Stream:GetCfgVector3() local o = {} setmetatable(o, Cfg..Vector3) o.X = self:GetFloat() o.Y = self:GetFloat() o.Z = self:GetFloat() return o end GetOrCreate('Cfg.AllType')['CardElement'] = { NULL = -9, Attack = 0, Extract = 1, Renounce = 2, Armor = 3, Control = 4, Cure = 5, Oneself = 6, Hand = 7, Brary = 8, Handack = 9, } GetOrCreate('Cfg.Character')['GroupType'] = { NULL = -9, None = 0, Base = 1, Player = 2, Monster = 3, NPC = 4, } GetOrCreate('Cfg.Skill')['ActionSourceType'] = { NULL = -9, SelfModel = 0, OtherModel = 1, } GetOrCreate('Cfg.Skill')['LockObjectType'] = { NULL = -9, None = 0, Enemy = 1, Teammate = 2, Self = 3, Other = 4, } GetOrCreate('Cfg.Skill')['HitSharpType'] = { NULL = -9, Cube = 0, Sphere = 1, Cylinder = 2, } GetOrCreate('Cfg.Skill')['MoveType'] = { NULL = -9, MoveToTarget = 0, MoveInDirection = 1, } GetOrCreate('Cfg.Skill')['BindType'] = { NULL = -9, None = 0, Body = 1, Head = 2, Foot = 3, } GetOrCreate('Cfg.Skill')['EffectAlignType'] = { NULL = -9, None = 0, LeftTop = 1, Left = 2, LeftBottom = 3, Top = 4, Center = 5, Bottom = 6, RightTop = 7, Right = 8, RightBottom = 9, } GetOrCreate('Cfg.Skill')['ShakeType'] = { NULL = -9, Horizontal = 0, Vertical = 1, Mix = 2, } return Stream <file_sep>namespace CS.ActorConfig { using System; using System.IO; using Sirenix.OdinInspector; using System.Collections.Generic; using Sirenix.OdinInspector.Editor; using System.Linq; using UnityEditor; using UnityEngine; using Sirenix.Utilities.Editor; using XmlCfg.Skill; using Cfg.Character; using Cfg; [Serializable] public class ActorConfigEditor { private static readonly List<string> _emptyClips = new List<string>(); private ActorConfig _actorCfg; private string _path; private Model _model; private List<string> _clips; private Dictionary<string, ActorConfigEditor> _childActor = new Dictionary<string, ActorConfigEditor>(); private bool _clearAllSelected = false; public bool IsDirty { get; private set; } public string CharacterPath { get { return HomeConfig.Instance.GetCharacterPath(_model.ModelPath); } } public string AvatarPath { get { return HomeConfig.Instance.GetAvatarPath(_model.AvatarPath); } } public float ModelScale { get { return _model.ModelScale; } } public string Path { get { return _path; } } public string MenuItemName { get { return string.Format("{0}/{1}", ActionHomeConfig.MenuItems[GroupType], ModelName); } } public GroupType GroupType { get { if (_model == null) return GroupType.None; return (GroupType)_model.GroupType; } //set //{ // ActorCfgWindow window = ActorCfgWindow.GetWindow<ActorCfgWindow>(); // OdinMenuItem item = window.MenuTree.Selection.FirstOrDefault(); // if (item != null) // { // ActorConfigEditor model = item.Value as ActorConfigEditor; // HomeConfigPreview.Instance.RemoveActor(model); // item.Parent.ChildMenuItems.Remove(item); // _actorCfg.GroupType = value; // HomeConfigPreview.Instance.AddActor(model); // var group = window.MenuTree.GetMenuItem(Group); // group.ChildMenuItems.Add(item); // item.MenuTree.Selection.Clear(); // item.Select(); // item.MenuTree.UpdateMenuTree(); // item.MenuTree.DrawMenuTree(); // } //} } public string ModelName { get { return _actorCfg == null ? "" : _actorCfg.ModelName; } set { } } [OnValueChanged("OnCfgChange", true)] public string BaseName { get { return _actorCfg == null ? "" : _actorCfg.BaseModelName; } set { } } public string Group { get { return ActionHomeConfig.MenuItems[(GroupType)_model.GroupType]; } } public ActorConfigEditor() { } public ActorConfigEditor(string path, ActorConfig cfg = null) { _path = path; _actorCfg = cfg != null ? cfg : new ActorConfig(); if (File.Exists(path)) _actorCfg.LoadAConfig(path); if (CfgManager.Model.ContainsKey(_actorCfg.ModelName)) _model = CfgManager.Model[_actorCfg.ModelName]; if (_actorCfg != null) { foreach (var item in _actorCfg.GeneralActions) { var action = new ModelActionEditor(this, item.Value, false); action.ActState = ModelActionEditor.ActionState.New; GeneralActions.Add(action); } foreach (var item in _actorCfg.SkillActions) { var action = new ModelActionEditor(this, item.Value, true); action.ActState = ModelActionEditor.ActionState.New; SkillActions.Add(action); } } } public void InitBaseModelAction() { string name = BaseName; if (string.IsNullOrEmpty(name)) { RemoveAllBaseAction(); return; } //--配置基类模型行为 var baseModel = HomeConfig.Instance.GetActorEditor(name); baseModel.AddChildActor(this); } public List<string> GetActionClips() { var clips = HomeConfig.Instance.AllCharacterClips; string assetName = _model.ModelPath; if (clips.ContainsKey(assetName)) { if (_clips == null) _clips = new List<string>(clips[assetName].Keys); return _clips; } else Debug.LogErrorFormat("[获取Clips]{0} 模型资源不存在!", assetName); return _emptyClips; } /// <summary> /// 重置旋转状态 /// </summary> public void ReselectedState() { foreach (var item in GeneralActions) item.IsSelected = false; foreach (var item in SkillActions) item.IsSelected = false; _clearAllSelected = true; } public void SetChildAction(ModelActionEditor action) { foreach (var item in _childActor) { ActorConfigEditor actor = item.Value; List<ModelActionEditor> list = null; if (action.IsSkillAction) list = actor.SkillActions; else list = actor.GeneralActions; int index = list.FindIndex(s => s.ActionName.Equals(action.ActionName)); if (index == -1) { ModelActionEditor add = Clipboard.Paste<ModelActionEditor>(); add.ActState = ModelActionEditor.ActionState.New; list.Add(add); continue; } if (list[index].ActState == ModelActionEditor.ActionState.Override) continue; Clipboard.Copy(action, CopyModes.DeepCopy); ModelActionEditor temp = Clipboard.Paste<ModelActionEditor>(); temp.ResetActorEditor(actor); list[index] = temp; } } Dictionary<string, ModelActionEditor> GetGeneralActionDict() { var pairs = new Dictionary<string, ModelActionEditor>(); foreach (var item in GeneralActions) { pairs.Add(item.ActionName, item); } return pairs; } Dictionary<string, ModelActionEditor> GetSkillActionDict() { var pairs = new Dictionary<string, ModelActionEditor>(); foreach (var item in SkillActions) { pairs.Add(item.ActionName, item); } return pairs; } void AddChildActor(ActorConfigEditor childCfg) { var modelDict = childCfg.GetGeneralActionDict(); foreach (var item in GeneralActions) { if (modelDict.ContainsKey(item.ActionName)) { modelDict[item.ActionName].ActState = ModelActionEditor.ActionState.Override; } else { Clipboard.Copy(item, CopyModes.DeepCopy); ModelActionEditor action = Clipboard.Paste<ModelActionEditor>(); action.ActState = ModelActionEditor.ActionState.Inherit; childCfg.GeneralActions.Add(action); action.ResetActorEditor(childCfg); } } var skillDict = childCfg.GetSkillActionDict(); foreach (var item in SkillActions) { if (skillDict.ContainsKey(item.ActionName)) { skillDict[item.ActionName].ActState = ModelActionEditor.ActionState.Override; } else { Clipboard.Copy(item, CopyModes.DeepCopy); ModelActionEditor action = Clipboard.Paste<ModelActionEditor>(); action.ActState = ModelActionEditor.ActionState.Inherit; childCfg.SkillActions.Add(action); action.ResetActorEditor(childCfg); } } if (!_childActor.ContainsKey(childCfg.ModelName)) _childActor.Add(childCfg.ModelName, childCfg); } void RemoveChildActor(ActorConfigEditor childCfg) { childCfg.RemoveAllBaseAction(); if (_childActor.ContainsKey(childCfg.ModelName)) _childActor.Remove(childCfg.ModelName); } void RemoveAllBaseAction() { var array = GeneralActions.ToArray(); GeneralActions.Clear(); foreach (var item in array) { switch (item.ActState) { case ModelActionEditor.ActionState.New: GeneralActions.Add(item); break; case ModelActionEditor.ActionState.Inherit: break; case ModelActionEditor.ActionState.Override: item.ActState = ModelActionEditor.ActionState.New; GeneralActions.Add(item); break; default: break; } } array = SkillActions.ToArray(); SkillActions.Clear(); foreach (var item in array) { switch (item.ActState) { case ModelActionEditor.ActionState.New: SkillActions.Add(item); break; case ModelActionEditor.ActionState.Inherit: break; case ModelActionEditor.ActionState.Override: item.ActState = ModelActionEditor.ActionState.New; SkillActions.Add(item); break; default: break; } } } #region 界面设计 [OnInspectorGUI, PropertyOrder(-100)] protected void OnInspectorGUI() { SirenixEditorGUI.BeginBox(); { EditorGUILayout.BeginHorizontal(); { EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField("模型名称:", ModelName, SirenixGUIStyles.MessageBox); EditorGUILayout.LabelField("继承模型:", BaseName, SirenixGUIStyles.MessageBox); EditorGUILayout.EndVertical(); if (GUILayout.Button("更换继承", GUILayout.Height(EditorGUIUtility.singleLineHeight * 2 + 10))) ModifyBaseName(); } EditorGUILayout.EndHorizontal(); } SirenixEditorGUI.EndBox(); } [ButtonGroup("Button"), Button("复制", ButtonSizes.Large)] private void CopyActions() { List<ModelActionEditor> copy = new List<ModelActionEditor>(); foreach (var item in GeneralActions) if (item.IsSelected) copy.Add(item); foreach (var item in SkillActions) if (item.IsSelected) copy.Add(item); Clipboard.Copy(copy, CopyModes.DeepCopy); } [ButtonGroup("Button"), Button("粘贴", ButtonSizes.Large)] private void PasteActions() { var generalDict = GetGeneralActionDict(); var skillDict = GetSkillActionDict(); List<ModelActionEditor> paste = new List<ModelActionEditor>(); if (Clipboard.TryPaste(out paste)) { foreach (var item in paste) { if (skillDict.ContainsKey(item.ActionName) || generalDict.ContainsKey(item.ActionName)) { Debug.LogFormat("<color=orange>[粘贴行为]{0} 行为重复!</color>", item.ActionName); continue; } if (item.IsSkillAction) SkillActions.Add(item); else GeneralActions.Add(item); item.ResetActorEditor(this); item.IsSelected = false; } } else { EditorUtility.DisplayDialog("粘贴异常", "行为数据粘贴失败,或者无数据可张贴~~", "确定"); } } [ButtonGroup("Button"), Button("保存文件", ButtonSizes.Large)] public void Save(bool resave = false) { if (!IsDirty && !resave) return; IsDirty = false; _actorCfg.GeneralActions.Clear(); _actorCfg.SkillActions.Clear(); foreach (var item in GeneralActions) { if (item.ActState == ModelActionEditor.ActionState.Inherit) continue; var action = item.ModelAction; _actorCfg.GeneralActions.Add(action.ActionName, action); } foreach (var item in SkillActions) { if (item.ActState == ModelActionEditor.ActionState.Inherit) continue; var action = item.ModelAction as SkillAction; _actorCfg.SkillActions.Add(action.ActionName, action); } _actorCfg.SaveAConfig(_path); } [ButtonGroup("Button"), Button("删除文件", ButtonSizes.Large)] public void Delete() { if (EditorUtility.DisplayDialog("删除操作", "确定要删除文件 -> " + ModelName, "确定", "取消")) { if (File.Exists(_path)) File.Delete(_path); ActorCfgWindow window = ActorCfgWindow.GetWindow<ActorCfgWindow>(); OdinMenuItem item = window.MenuTree.Selection.FirstOrDefault(); if (item != null && item.Value != null) { ActorConfigEditor model = item.Value as ActorConfigEditor; HomeConfig.Instance.RemoveActor(model); item.Parent.ChildMenuItems.Remove(item); item.MenuTree.Selection.Clear(); item.Parent.Select(); item.MenuTree.UpdateMenuTree(); item.MenuTree.DrawMenuTree(); } } } [Title("普通动作列表", bold: true), OnInspectorGUI, PropertyOrder(10)] private void OnModelActionsHeader() { OnHeaderGUI(); } [LabelText(" "), Space(-5f), PropertyOrder(15)] [ListDrawerSettings(OnTitleBarGUI = "OnGUIGeneralAction", CustomAddFunction = "CreateGeneralAction", HideRemoveButton = true)] public List<ModelActionEditor> GeneralActions = new List<ModelActionEditor>(); [Title("技能动作列表", bold: true), OnInspectorGUI, PropertyOrder(20)] private void OnSkillActionsHeader() { OnHeaderGUI(); } [LabelText(" "), Space(-5f), PropertyOrder(25)] [ListDrawerSettings(OnTitleBarGUI = "OnGUISkilllAction", CustomAddFunction = "CreateSkillAction", HideRemoveButton = true)] public List<ModelActionEditor> SkillActions = new List<ModelActionEditor>(); private void OnHeaderGUI() { SirenixEditorGUI.BeginHorizontalToolbar(SirenixGUIStyles.BoxHeaderStyle); GUILayout.Label(" ", GUILayout.Width(17f)); GUILayout.Label("继承", SirenixGUIStyles.LabelCentered, GUILayout.Width(ModelActionEditor.INHERIT_WIDTH)); GUILayout.Label("动作名称", SirenixGUIStyles.LabelCentered, GUILayout.Width(ModelActionEditor.ACT_NAME_WIDTH)); GUILayout.Label("动画来源", SirenixGUIStyles.LabelCentered, GUILayout.Width(ModelActionEditor.ACT_SRC_WIDTH)); GUILayout.Label("动画文件", SirenixGUIStyles.LabelCentered, GUILayout.Width(ModelActionEditor.ACT_CLIP_WIDTH)); GUILayout.Label("操作", SirenixGUIStyles.LabelCentered, GUILayout.ExpandWidth(true)); SirenixEditorGUI.EndHorizontalToolbar(); } private void ModifyModelName() { var models = new List<string>(CfgManager.Model.Keys); models.Remove(ModelName); SimplePopupCreator.ShowDialog(new List<string>(models), (name) => { _actorCfg.ModelName = name; ActorCfgWindow window = ActorCfgWindow.GetWindow<ActorCfgWindow>(); OdinMenuItem item = window.MenuTree.Selection.FirstOrDefault(); item.Name = name; item.SearchString = name; }); } private void ModifyBaseName() { List<string> models = HomeConfig.Instance.GetAllActorList(); string none = "-----None-----"; models.Insert(0, none); models.Remove(ModelName); SimplePopupCreator.ShowDialog(new List<string>(models), (name) => { if (name.Equals(none)) name = ""; string old = _actorCfg.BaseModelName; _actorCfg.BaseModelName = name; bool oldEmpty = string.IsNullOrEmpty(old); bool newEmpty = string.IsNullOrEmpty(name); if (!oldEmpty) { var oldBase = HomeConfig.Instance.GetActorEditor(old); if (!newEmpty && !old.Equals(name)) {//--修改继承 oldBase.RemoveChildActor(this); var newBase = HomeConfig.Instance.GetActorEditor(name); newBase.AddChildActor(this); } else if (newEmpty) { //--移除继承 oldBase.RemoveChildActor(this); } } else if (!newEmpty) { //--添加继承 var newBase = HomeConfig.Instance.GetActorEditor(name); newBase.AddChildActor(this); } }); } bool _isSelected_Model = false; bool _isSelected_Skill = false; private void CreateGeneralAction() { var action = new ModelActionEditor(this, new GeneralAction(), false); action.ActState = ModelActionEditor.ActionState.New; ActionWindow.Init(this, action, true, (act) => { GeneralActions.Add(act); OnCfgChange(); }); } private void CreateSkillAction() { var action = new ModelActionEditor(this, new SkillAction(), true); action.ActState = ModelActionEditor.ActionState.New; ActionWindow.Init(this, action, true, (act) => { SkillActions.Add(act); OnCfgChange(); }); } private void OnGUIGeneralAction() { OnTitleBarGUI(GeneralActions, ref _isSelected_Model); } private void OnGUISkilllAction() { OnTitleBarGUI(SkillActions, ref _isSelected_Skill); } private void OnTitleBarGUI(List<ModelActionEditor> actionEditors, ref bool state) { EditorIcon icon = state ? EditorIcons.X : EditorIcons.Checkmark; if (SirenixEditorGUI.ToolbarButton(icon)) { state = !state; foreach (var item in actionEditors) item.IsSelected = state; } if (_clearAllSelected) { _clearAllSelected = false; state = false; } } public void OnCfgChange() { if (!HomeConfig.Instance.IsInit) return; IsDirty = true; } #endregion } } <file_sep>using System; using UnityEditor; using UnityEngine; using XmlCfg.Skill; namespace FluxEditor { [CustomEditor(typeof(Flux.FHitZone), true)] public class FHitZoneInspector : FEventInspector { private SerializedProperty _sharpType; private SerializedProperty _scale; private SerializedProperty _radius; private SerializedProperty _height; private SerializedProperty _angle; private GUIContent _scaleUI = new GUIContent("缩放"); private GUIContent _radiusUI = new GUIContent("半径"); private GUIContent _heightUI = new GUIContent("高度"); private GUIContent _angleUI = new GUIContent("角度"); protected override void OnEnable() { base.OnEnable(); _sharpType = serializedObject.FindProperty("_sharpType"); _scale = serializedObject.FindProperty("_scale"); _radius = serializedObject.FindProperty("_radius"); _height = serializedObject.FindProperty("_height"); _angle = serializedObject.FindProperty("_angle"); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); _sharpType.enumValueIndex = EditorGUILayout.Popup("碰撞体形状", _sharpType.enumValueIndex, _sharpType.enumDisplayNames); switch ((HitSharpType)_sharpType.enumValueIndex) { case HitSharpType.Cube: EditorGUILayout.PropertyField(_scale, _scaleUI); break; case HitSharpType.Sphere: EditorGUILayout.PropertyField(_radius, _radiusUI); break; case HitSharpType.Cylinder: EditorGUILayout.PropertyField(_radius, _radiusUI); EditorGUILayout.PropertyField(_height, _heightUI); EditorGUILayout.PropertyField(_angle, _angleUI); break; default: break; } serializedObject.ApplyModifiedProperties(); } } } <file_sep>using System.Collections.Generic; using System.IO; using UnityEditor; public partial class ExportResource { static void ExportAllResources(BuildTarget target) { ExportAllAnimationClips(target); ExportAllChars(target); ExportAllAvatars(target); //ExportAllSfx(target); ExportAllAudios(target); ExportAllTextures(target); ExportAllUIs(target); ExportAllScenes(target); } static void ReExportAllResources(BuildTarget target) { RemoveAssetBundles(target); ResetAssetBundleNames(); ExportAllResources(target); } static void ResetAssetBundleNames() { int length = AssetDatabase.GetAllAssetBundleNames().Length; string[] oldAssetBundleNames = new string[length]; for (int i = 0; i < length; i++) { oldAssetBundleNames[i] = AssetDatabase.GetAllAssetBundleNames()[i]; } for (int j = 0; j < oldAssetBundleNames.Length; j++) { AssetDatabase.RemoveAssetBundleName(oldAssetBundleNames[j], true); } } static void RemoveAssetBundles(BuildTarget target) { string path = GetBundleSaveDir(target); foreach (string dir in Directory.GetDirectories(path)) { Directory.Delete(dir, true); } foreach (string file in Directory.GetFiles(path)) { File.Delete(file); } } [MenuItem("Build Windows/Replace Default Mat And Shaders In sfx|UI")] static void ReplaceDefaultMatAndShaderssForWindows() { ReplaceDefaultMatAndShaders(); } [MenuItem("Build Android/Replace Default Mat And Shaders In sfx|UI")] static void ReplaceDefaultMatAndShadersForAndroid() { ReplaceDefaultMatAndShaders(); } [MenuItem("Build iOS/Replace Default Mat And Shaders In sfx|UI")] static void ReplaceDefaultMatAndShadersForiOS() { ReplaceDefaultMatAndShaders(); } [MenuItem("Build Windows/Build All AssetBundles for Windows")] static void ExportAllResourcesForWindows() { ExportAllResources(BuildTarget.StandaloneWindows); } [MenuItem("Build Android/Build All AssetBundles for Android")] static void ExportAllResourcesForAndroid() { ExportAllResources(BuildTarget.Android); } [MenuItem("Build iOS/Build All AssetBundles for iOS")] static void ExportAllResourcesForiOS() { ExportAllResources(BuildTarget.iOS); } [MenuItem("Build Windows/ReBuild All AssetBundles for Windows")] static void ReExportAllResourcesForWindows() { ReExportAllResources(BuildTarget.StandaloneWindows); } [MenuItem("Build Android/ReBuild All AssetBundles for Android")] static void ReExportAllResourcesForAndroid() { ReExportAllResources(BuildTarget.Android); } [MenuItem("Build iOS/ReBuild All AssetBundles for iOS")] static void ReExportAllResourcesForiOS() { ReExportAllResources(BuildTarget.iOS); } [MenuItem("Build Windows/Clean AssetBundle Names")] static void CleanAllAssetBundleNames() { ResetAssetBundleNames(); } [MenuItem("Tools/Clear ProgressBar")] static void ClearProgressBar() { EditorUtility.ClearProgressBar(); } } <file_sep>local setmetatable = setmetatable local Class = {} function Class:new(super) local class = {} class.__index = class--index 是给obj访问元表时使用 local mt = {} setmetatable(class, mt) if super then mt.__index = super end function class:new(...) local obj = {} setmetatable(obj, self) if obj.__new then obj:__new(...) end return obj end return class end return Class <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public enum EffectAlignType { None = 0, LeftTop = 1, Left = 2, LeftBottom = 3, Top = 4, Center = 5, Bottom = 6, RightTop = 7, Right = 8, RightBottom = 9, } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class Sequence : CfgObject { /// <summary> /// 序列ID /// <summary> public readonly int Id; /// <summary> /// 碰撞区域定义列表 /// <summary> public readonly List<HitZone> HitZones = new List<HitZone>(); /// <summary> /// 时间事件列表 /// <summary> public readonly List<Timeline> Timelines = new List<Timeline>(); public Sequence(DataStream data) { this.Id = data.GetInt(); for (int n = data.GetInt(); n-- > 0; ) { this.HitZones.Add((HitZone)data.GetObject(data.GetString())); } for (int n = data.GetInt(); n-- > 0; ) { this.Timelines.Add((Timeline)data.GetObject(data.GetString())); } } } } <file_sep>#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class GameResourceManagerWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(Game.ResourceManager); Utils.BeginObjectRegister(type, L, translator, 0, 11, 1, 1); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Init", _m_Init); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Start", _m_Start); Utils.RegisterFunc(L, Utils.METHOD_IDX, "IsLoading", _m_IsLoading); Utils.RegisterFunc(L, Utils.METHOD_IDX, "RemoveTask", _m_RemoveTask); Utils.RegisterFunc(L, Utils.METHOD_IDX, "AddTask", _m_AddTask); Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetResPath", _m_GetResPath); Utils.RegisterFunc(L, Utils.METHOD_IDX, "CleanupMemoryInterval", _m_CleanupMemoryInterval); Utils.RegisterFunc(L, Utils.METHOD_IDX, "CleanupMemoryNow", _m_CleanupMemoryNow); Utils.RegisterFunc(L, Utils.METHOD_IDX, "CleanupDependenciesInterval", _m_CleanupDependenciesInterval); Utils.RegisterFunc(L, Utils.METHOD_IDX, "CleanupDependenciesNow", _m_CleanupDependenciesNow); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Dispose", _m_Dispose); Utils.RegisterFunc(L, Utils.GETTER_IDX, "MaxTaskCount", _g_get_MaxTaskCount); Utils.RegisterFunc(L, Utils.SETTER_IDX, "MaxTaskCount", _s_set_MaxTaskCount); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 1, 1, 0); Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "Instance", _g_get_Instance); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { return LuaAPI.luaL_error(L, "Game.ResourceManager does not have a constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Init(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Init( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Start(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Start( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_IsLoading(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { uint _taskId = LuaAPI.xlua_touint(L, 2); bool gen_ret = gen_to_be_invoked.IsLoading( _taskId ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_RemoveTask(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { uint _taskId = LuaAPI.xlua_touint(L, 2); System.Action<UnityEngine.Object> _action = translator.GetDelegate<System.Action<UnityEngine.Object>>(L, 3); gen_to_be_invoked.RemoveTask( _taskId, _action ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_AddTask(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); int gen_param_count = LuaAPI.lua_gettop(L); if(gen_param_count == 4&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)&& (LuaAPI.lua_isnil(L, 3) || LuaAPI.lua_type(L, 3) == LuaTypes.LUA_TFUNCTION)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4)) { string _file = LuaAPI.lua_tostring(L, 2); XLua.LuaFunction _action = (XLua.LuaFunction)translator.GetObject(L, 3, typeof(XLua.LuaFunction)); int _loadType = LuaAPI.xlua_tointeger(L, 4); uint gen_ret = gen_to_be_invoked.AddTask( _file, _action, _loadType ); LuaAPI.xlua_pushuint(L, gen_ret); return 1; } if(gen_param_count == 3&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)&& (LuaAPI.lua_isnil(L, 3) || LuaAPI.lua_type(L, 3) == LuaTypes.LUA_TFUNCTION)) { string _file = LuaAPI.lua_tostring(L, 2); XLua.LuaFunction _action = (XLua.LuaFunction)translator.GetObject(L, 3, typeof(XLua.LuaFunction)); uint gen_ret = gen_to_be_invoked.AddTask( _file, _action ); LuaAPI.xlua_pushuint(L, gen_ret); return 1; } if(gen_param_count == 4&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)&& translator.Assignable<System.Action<UnityEngine.Object>>(L, 3)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4)) { string _file = LuaAPI.lua_tostring(L, 2); System.Action<UnityEngine.Object> _action = translator.GetDelegate<System.Action<UnityEngine.Object>>(L, 3); int _loadType = LuaAPI.xlua_tointeger(L, 4); uint gen_ret = gen_to_be_invoked.AddTask( _file, _action, _loadType ); LuaAPI.xlua_pushuint(L, gen_ret); return 1; } if(gen_param_count == 3&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)&& translator.Assignable<System.Action<UnityEngine.Object>>(L, 3)) { string _file = LuaAPI.lua_tostring(L, 2); System.Action<UnityEngine.Object> _action = translator.GetDelegate<System.Action<UnityEngine.Object>>(L, 3); uint gen_ret = gen_to_be_invoked.AddTask( _file, _action ); LuaAPI.xlua_pushuint(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to Game.ResourceManager.AddTask!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_GetResPath(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { string _relative = LuaAPI.lua_tostring(L, 2); string gen_ret = gen_to_be_invoked.GetResPath( _relative ); LuaAPI.lua_pushstring(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_CleanupMemoryInterval(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.CleanupMemoryInterval( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_CleanupMemoryNow(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.CleanupMemoryNow( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_CleanupDependenciesInterval(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.CleanupDependenciesInterval( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_CleanupDependenciesNow(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.CleanupDependenciesNow( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Dispose(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Dispose( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_Instance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); translator.Push(L, Game.ResourceManager.Instance); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_MaxTaskCount(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); LuaAPI.xlua_pushinteger(L, gen_to_be_invoked.MaxTaskCount); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_MaxTaskCount(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Game.ResourceManager gen_to_be_invoked = (Game.ResourceManager)translator.FastGetCSObj(L, 1); gen_to_be_invoked.MaxTaskCount = LuaAPI.xlua_tointeger(L, 2); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 0; } } } <file_sep>using UnityEngine; using System.Collections; namespace Flux { [FEvent("模型控制/冲刺"/*, typeof(FCharacterTrack)*/)] public class FRushEvent : FEvent { [SerializeField, Range(0, 360)] [HideInInspector] [FEventField("角度", "绕Y轴顺时针旋转")] private int _angle; [SerializeField] [HideInInspector] [FEventField("距离", "距离长度")] private float _length; private FTweenVector3 _tween; private Vector3 _startPosition; protected override void OnTrigger(float timeSinceTrigger) { _startPosition = Owner.localPosition; base.OnTrigger(timeSinceTrigger); Owner.Rotate(Vector3.up * _angle); Vector3 from = Owner.position; Vector3 to = Owner.position + Owner.forward * _length; _tween = new FTweenVector3(from, to); } protected override void OnStop() { base.OnStop(); Owner.localPosition = _startPosition; } protected override void OnUpdateEvent(float timeSinceTrigger) { float t = timeSinceTrigger / LengthTime; Owner.position = _tween.GetValue(t); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg { public abstract class CfgObject { } } <file_sep>using UnityEngine; using UnityEditor; using UnityEditor.Animations; //using UnityEditorInternal; using System.Collections.Generic; using Flux; using FluxEditor; namespace FluxEditor { [CustomEditor(typeof(FPlayAnimationEvent))] public class FAnimationEventInspector : FEventInspector { private FPlayAnimationEvent _animEvent = null; private SerializedProperty _animationClip = null; private SerializedProperty _frameRange = null; private SerializedProperty _startOffset = null; private SerializedProperty _blendLength = null; private GUIContent _animationClipUI; private GUIContent _frameRangeUI; private GUIContent _startOffsetUI; private GUIContent _blendLengthUI; protected override void OnEnable() { base.OnEnable(); if (target == null) { DestroyImmediate(this); return; } _animEvent = (FPlayAnimationEvent)target; _animationClip = serializedObject.FindProperty("_animationClip"); _startOffset = serializedObject.FindProperty("_startOffset"); _blendLength = serializedObject.FindProperty("_blendLength"); _frameRange = serializedObject.FindProperty("_frameRange"); _animationClipUI = new GUIContent("动画剪辑"); _frameRangeUI = new GUIContent("偏移+混合"); _startOffsetUI = new GUIContent("偏移帧数"); _blendLengthUI = new GUIContent("混合帧数"); } public override void OnInspectorGUI() { bool rebuildTrack = false; base.OnInspectorGUI(); serializedObject.Update(); if (_animationClip.objectReferenceValue == null) EditorGUILayout.HelpBox("无动画剪辑Clip", MessageType.Warning); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(_animationClip, _animationClipUI); Rect animationClipRect = GUILayoutUtility.GetLastRect(); if (Event.current.type == EventType.DragUpdated && animationClipRect.Contains(Event.current.mousePosition)) { int numAnimations = NumAnimationsDragAndDrop(_animEvent.Sequence.FrameRate); if (numAnimations > 0) DragAndDrop.visualMode = DragAndDropVisualMode.Link; } else if (Event.current.type == EventType.DragPerform && animationClipRect.Contains(Event.current.mousePosition)) { if (NumAnimationsDragAndDrop(_animEvent.Sequence.FrameRate) > 0) { DragAndDrop.AcceptDrag(); AnimationClip clip = GetAnimationClipDragAndDrop(_animEvent.Sequence.FrameRate); if (clip != null) _animationClip.objectReferenceValue = clip; } } if (EditorGUI.EndChangeCheck()) { AnimationClip clip = (AnimationClip)_animationClip.objectReferenceValue; if (clip) { if (clip.frameRate != _animEvent.Track.Container.Sequence.FrameRate) { Debug.LogError(string.Format("Can't add animation, it has a different frame rate from the sequence ({0} vs {1})", clip.frameRate, _animEvent.Track.Container.Sequence.FrameRate)); _animationClip.objectReferenceValue = null; } else { SerializedProperty frameRangeEnd = _frameRange.FindPropertyRelative("_end"); FrameRange maxFrameRange = _animEvent.GetMaxFrameRange(); frameRangeEnd.intValue = Mathf.Min(_animEvent.FrameRange.Start + Mathf.RoundToInt(clip.length * clip.frameRate), maxFrameRange.End); } rebuildTrack = true; } else { CheckDeleteAnimation(_animEvent); } } if (_animEvent.IsBlending()) { int id = _animEvent.GetId(); FPlayAnimationEvent preAnimEvt = _animEvent.Track.Events[id - 1] as FPlayAnimationEvent; if (id > 0) { EditorGUI.BeginChangeCheck(); EditorGUILayout.IntSlider(_startOffset, 0, _animEvent.GetMaxStartOffset(), _startOffsetUI); EditorGUILayout.IntSlider(_blendLength, 0, preAnimEvt.Length > _animEvent.Length ? _animEvent.Length : preAnimEvt.Length, _blendLengthUI); if (EditorGUI.EndChangeCheck()) rebuildTrack = true; } } else { EditorGUI.BeginChangeCheck(); EditorGUILayout.IntSlider(_startOffset, 0, _animEvent.GetMaxStartOffset(), _startOffsetUI); if (EditorGUI.EndChangeCheck()) rebuildTrack = true; } serializedObject.ApplyModifiedProperties(); if (rebuildTrack) FAnimationTrackInspector.RebuildStateMachine((FAnimationTrack)_animEvent.Track); } public static void CheckDeleteAnimation(FPlayAnimationEvent animEvt) { if (animEvt._animationClip != null) Undo.RecordObject(animEvt._animationClip, "DeleteAnimation"); } private static bool _showBlendAndOffsetContent = false; public static int NumAnimationsDragAndDrop() { return NumAnimationsDragAndDrop(-1); } public static int NumAnimationsDragAndDrop(int frameRate) { int numAnimations = 0; if (DragAndDrop.objectReferences.Length == 0) return numAnimations; string pathToAsset = AssetDatabase.GetAssetPath(DragAndDrop.objectReferences[0].GetInstanceID()); if (string.IsNullOrEmpty(pathToAsset)) return numAnimations; if (DragAndDrop.objectReferences[0] is AnimationClip && (frameRate <= 0 || Mathf.Approximately(((AnimationClip)DragAndDrop.objectReferences[0]).frameRate, frameRate))) ++numAnimations; Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath(pathToAsset); foreach (Object obj in objs) { if (obj is AnimationClip && (frameRate <= 0 || Mathf.Approximately(((AnimationClip)obj).frameRate, frameRate))) ++numAnimations; } return numAnimations; } private static AnimationClip _dragAndDropSelectedAnimation = null; public static AnimationClip GetAnimationClipDragAndDrop(int frameRate) { _dragAndDropSelectedAnimation = null; if (DragAndDrop.objectReferences.Length == 0) return null; string pathToAsset = AssetDatabase.GetAssetPath(DragAndDrop.objectReferences[0].GetInstanceID()); if (string.IsNullOrEmpty(pathToAsset)) return null; List<AnimationClip> animationClips = new List<AnimationClip>(); if (DragAndDrop.objectReferences[0] is AnimationClip && (frameRate <= 0 || Mathf.Approximately(((AnimationClip)DragAndDrop.objectReferences[0]).frameRate, frameRate))) animationClips.Add((AnimationClip)DragAndDrop.objectReferences[0]); else { Object[] objs = AssetDatabase.LoadAllAssetRepresentationsAtPath(pathToAsset); foreach (Object obj in objs) { if (obj is AnimationClip && (frameRate <= 0 || Mathf.Approximately(((AnimationClip)obj).frameRate, frameRate))) { animationClips.Add((AnimationClip)obj); } } } if (animationClips.Count == 0) return null; else if (animationClips.Count == 1) return animationClips[0]; GenericMenu menu = new GenericMenu(); for (int i = 0; i != animationClips.Count; ++i) { menu.AddItem(new GUIContent(animationClips[i].name), false, SetAnimationClip, animationClips[i]); } menu.ShowAsContext(); return _dragAndDropSelectedAnimation; } private static void SetAnimationClip(object data) { if (data == null) _dragAndDropSelectedAnimation = null; else _dragAndDropSelectedAnimation = (AnimationClip)data; } private void SetAnimationClip(AnimationClip clip) { _animationClip.objectReferenceValue = clip; serializedObject.ApplyModifiedProperties(); } public static void SetAnimationClip(FPlayAnimationEvent animEvent, AnimationClip animClip) { FAnimationEventInspector editor = (FAnimationEventInspector)CreateEditor(animEvent, typeof(FAnimationEventInspector)); editor.SetAnimationClip(animClip); DestroyImmediate(editor); FAnimationTrackInspector.RebuildStateMachine((FAnimationTrack)animEvent.Track); } // animation editing /// <summary> /// 动画缩放 /// </summary> public static void ScaleAnimationClip(AnimationClip clip, FrameRange range) { if (clip == null) return; float oldLength = clip.length; float newLength = range.Length / clip.frameRate; Undo.RecordObject(clip, "resize Animation"); EditorCurveBinding[] curveBindings = AnimationUtility.GetCurveBindings(clip); // when scaling, we need to adjust the tangents otherwise the curves will get completely distorted float tangentMultiplier = oldLength / newLength; for (int i = 0; i != curveBindings.Length; ++i) { AnimationCurve curve = GetAnimationCurve(clip, ref curveBindings[i]); if (curve == null) continue; if (newLength < oldLength) { for (int j = 0; j < curve.keys.Length; ++j) { // Keyframe newKeyframe = new Keyframe( Mathf.RoundToInt( (curve.keys[j].time / oldLength) * newLength * clip.frameRate) / clip.frameRate, curve.keys[j].value, curve.keys[j].inTangent*tangentMultiplier, curve.keys[j].outTangent*tangentMultiplier ); Keyframe newKeyframe = new Keyframe((curve.keys[j].time / oldLength) * newLength, curve.keys[j].value, curve.keys[j].inTangent * tangentMultiplier, curve.keys[j].outTangent * tangentMultiplier); newKeyframe.tangentMode = curve.keys[j].tangentMode; curve.MoveKey(j, newKeyframe); } } else { for (int j = curve.keys.Length - 1; j >= 0; --j) { // Keyframe newKeyframe = new Keyframe( Mathf.RoundToInt( (curve.keys[j].time / oldLength) * newLength * clip.frameRate ) /clip.frameRate, curve.keys[j].value, curve.keys[j].inTangent*tangentMultiplier, curve.keys[j].outTangent*tangentMultiplier ); Keyframe newKeyframe = new Keyframe((curve.keys[j].time / oldLength) * newLength, curve.keys[j].value, curve.keys[j].inTangent * tangentMultiplier, curve.keys[j].outTangent * tangentMultiplier); newKeyframe.tangentMode = curve.keys[j].tangentMode; curve.MoveKey(j, newKeyframe); } } AnimationUtility.SetEditorCurve(clip, curveBindings[i], curve); } clip.EnsureQuaternionContinuity(); EditorApplication.RepaintAnimationWindow(); EditorUtility.SetDirty(clip); } /// <summary> /// 获取动画曲线信息 /// </summary> private static AnimationCurve GetAnimationCurve(AnimationClip clip, ref EditorCurveBinding curveBinding) { AnimationCurve curve = null; if (curveBinding.propertyName.StartsWith("m_LocalRotation.")) { char axis = curveBinding.propertyName[curveBinding.propertyName.Length - 1]; if (axis == 'w') return curve; // ignore w curveBinding.propertyName = "localEulerAngles." + axis; curve = AnimationUtility.GetEditorCurve(clip, curveBinding); if (curve == null) { curveBinding.propertyName = "localEulerAnglesBaked." + axis; curve = AnimationUtility.GetEditorCurve(clip, curveBinding); } } else { curve = AnimationUtility.GetEditorCurve(clip, curveBinding); } return curve; } /// <summary> /// 创建动画剪辑(不包含缩放数据) /// </summary> public static AnimationClip CreateAnimationClip(FPlayAnimationEvent animEvent) { FAnimationTrack track = (FAnimationTrack)animEvent.Track; string animName = ((FAnimationTrack)animEvent.Track).LayerName + "_" + animEvent.GetId().ToString(); AnimationClip clip = AnimatorController.AllocateAnimatorClip(animName); clip.frameRate = animEvent.Sequence.FrameRate; Transform ownerTransform = animEvent.Owner; Vector3 pos = ownerTransform.localPosition; Vector3 rot = ownerTransform.localRotation.eulerAngles; //ownerTransform.localEulerAngles; Keyframe[] xPosKeys = new Keyframe[] { new Keyframe(0, pos.x), new Keyframe(animEvent.LengthTime, pos.x) }; Keyframe[] yPosKeys = new Keyframe[] { new Keyframe(0, pos.y), new Keyframe(animEvent.LengthTime, pos.y) }; Keyframe[] zPosKeys = new Keyframe[] { new Keyframe(0, pos.z), new Keyframe(animEvent.LengthTime, pos.z) }; Keyframe[] xRotKeys = new Keyframe[] { new Keyframe(0, rot.x), new Keyframe(animEvent.LengthTime, rot.x) }; Keyframe[] yRotKeys = new Keyframe[] { new Keyframe(0, rot.y), new Keyframe(animEvent.LengthTime, rot.y) }; Keyframe[] zRotKeys = new Keyframe[] { new Keyframe(0, rot.z), new Keyframe(animEvent.LengthTime, rot.z) }; // set the tangent mode int tangentMode = 10; // 10 is unity auto tangent mode for (int i = 0; i != xPosKeys.Length; ++i) { xPosKeys[i].tangentMode = tangentMode; yPosKeys[i].tangentMode = tangentMode; zPosKeys[i].tangentMode = tangentMode; xRotKeys[i].tangentMode = tangentMode; yRotKeys[i].tangentMode = tangentMode; zRotKeys[i].tangentMode = tangentMode; } AnimationCurve xPos = new AnimationCurve(xPosKeys); AnimationCurve yPos = new AnimationCurve(yPosKeys); AnimationCurve zPos = new AnimationCurve(zPosKeys); AnimationCurve xRot = new AnimationCurve(xRotKeys); AnimationCurve yRot = new AnimationCurve(yRotKeys); AnimationCurve zRot = new AnimationCurve(zRotKeys); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "m_LocalPosition.x"), xPos); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "m_LocalPosition.y"), yPos); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "m_LocalPosition.z"), zPos); // workaround unity bug of spilling errors if you just set localEulerAngles Quaternion quat = ownerTransform.localRotation; Keyframe[] xQuatKeys = new Keyframe[] { new Keyframe(0, quat.x), new Keyframe(animEvent.LengthTime, quat.x) }; Keyframe[] yQuatKeys = new Keyframe[] { new Keyframe(0, quat.y), new Keyframe(animEvent.LengthTime, quat.y) }; Keyframe[] zQuatKeys = new Keyframe[] { new Keyframe(0, quat.z), new Keyframe(animEvent.LengthTime, quat.z) }; Keyframe[] wQuatKeys = new Keyframe[] { new Keyframe(0, quat.w), new Keyframe(animEvent.LengthTime, quat.w) }; AnimationCurve xQuat = new AnimationCurve(xQuatKeys); AnimationCurve yQuat = new AnimationCurve(yQuatKeys); AnimationCurve zQuat = new AnimationCurve(zQuatKeys); AnimationCurve wQuat = new AnimationCurve(wQuatKeys); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "m_LocalRotation.x"), xQuat); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "m_LocalRotation.y"), yQuat); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "m_LocalRotation.z"), zQuat); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "m_LocalRotation.w"), wQuat); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "localEulerAngles.x"), xRot); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "localEulerAngles.y"), yRot); AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(string.Empty, typeof(Transform), "localEulerAngles.z"), zRot); clip.EnsureQuaternionContinuity(); AssetDatabase.AddObjectToAsset(clip, track.AnimatorController); AnimationClipSettings clipSettings = AnimationUtility.GetAnimationClipSettings(clip); clipSettings.loopTime = false; AnimationUtility.SetAnimationClipSettings(clip, clipSettings); AssetDatabase.SaveAssets(); FAnimationEventInspector.SetAnimationClip(animEvent, clip); return clip; } } }<file_sep>using UnityEngine; using System.Collections; using XmlCfg.Skill; namespace Flux { [FEvent("控制器/直线位移")] public class FMove : FController { [SerializeField, HideInInspector] private MoveType _moveType; [SerializeField, HideInInspector] [FEventField("从释放者位置开始")] private bool _isRelateSelf; [SerializeField, HideInInspector] [FEventField("相对偏移")] private Vector3 _offset; [SerializeField, HideInInspector] [FEventField("Y轴旋转角度")] private float _angle; [SerializeField, HideInInspector] [FEventField("速度", "位移速度m/s"), Range(0f, 999f)] private float _speed; private Transform _targetObj; private float _startTime; protected override void OnTrigger(float timeSinceTrigger) { base.OnTrigger(timeSinceTrigger); var go = FUtility.FindGameObject(_path); if (go != null) { _targetObj = go.transform; _targetObj.localPosition += _offset; Vector3 eulerAngles = _targetObj.localEulerAngles; eulerAngles.y = _angle; _targetObj.localEulerAngles = eulerAngles; } _startTime = timeSinceTrigger; } protected override void OnUpdateEvent(float timeSinceTrigger) { base.OnUpdateEvent(timeSinceTrigger); if (_targetObj == null) return; float t = timeSinceTrigger - _startTime; Vector3 dir = Vector3.zero; switch (_moveType) { case MoveType.MoveToTarget: break; case MoveType.MoveInDirection: dir = _targetObj.forward; break; default: break; } } protected override void OnStop() { base.OnStop(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class SphereZone : Cfg.Skill.HitZone { /// <summary> /// 球半径 /// <summary> public readonly float Radius; public SphereZone(DataStream data) : base(data) { this.Radius = data.GetFloat(); } } } <file_sep>using System.Collections.Generic; using System.IO; using UnityEditor; public partial class ExportResource { } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class Controller : Cfg.Skill.Timeline { /// <summary> /// 资源对象路径 /// <summary> public readonly string Path; public Controller(DataStream data) : base(data) { this.Path = data.GetString(); } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public enum BindType { /// <summary> /// 无 /// <summary> None = 0, /// <summary> /// 身体 /// <summary> Body = 1, /// <summary> /// 头 /// <summary> Head = 2, /// <summary> /// 脚 /// <summary> Foot = 3, } } <file_sep>using System; using System.Collections.Generic; public static class ExtendedIDictionary { public static Value Get<Key, Value>(this IDictionary<Key, Value> dict, Key key) { return dict.Get(key, default(Value)); } public static Value Get<Key, Value>(this IDictionary<Key, Value> dict, Key key, Value defaultValue) { Value v; if(dict.TryGetValue(key, out v)) { return v; } return defaultValue; } public static Value SetDefault<Key, Value>(this IDictionary<Key, Value> dict, Key key) { return dict.SetDefault(key, default(Value)); } public static Value SetDefault<Key, Value>(this IDictionary<Key, Value> dict, Key key, Value defaultValue) { Value v; if (!dict.TryGetValue(key, out v)) { v = defaultValue; dict.Add(key, v); } return v; } public static Value SetDefault<Key, Value>(this IDictionary<Key, Value> dict, Key key, Func<Value> creater) { Value v; if (!dict.TryGetValue(key, out v)) { v = creater(); dict.Add(key, v); } return v; } public static Value SetDefault<Key, Value>(this IDictionary<Key, Value> dict, Key key, Func<Key, Value> creater) { Value v; if (!dict.TryGetValue(key, out v)) { v = creater(key); dict.Add(key, v); } return v; } public static void AddRange<Key, Value>(this IDictionary<Key, Value> dictTo, IDictionary<Key, Value> dictFrom) where Key : IComparable { foreach(var pair in dictFrom) { dictTo[pair.Key] = pair.Value; } } public static string GetDebugContent<Key, Value>(this IDictionary<Key, Value> dict) { string content = "{"; foreach(var pari in dict) { content = content + pari.Key + ":" + pari.Value + ";"; } content = content + "}"; return content; } } <file_sep>using UnityEngine; using UnityEditor; using System; using Flux; namespace FluxEditor { [CustomEditor(typeof(FContainer), true)] public class FContainerInspector : Editor { FContainer _container = null; private SerializedProperty _containerNo; private SerializedProperty _color; private GUIContent _containerNoUI = new GUIContent("编号"); private GUIContent _colorUI = new GUIContent("颜色"); void OnEnable() { _container = (FContainer)target; _containerNo = serializedObject.FindProperty("ContainerNo"); _color = serializedObject.FindProperty("_color"); } public override void OnInspectorGUI () { EditorGUI.BeginChangeCheck(); string name = EditorGUILayout.TextField("名称", _container.gameObject.name); EditorGUILayout.PropertyField(_containerNo, _containerNoUI); EditorGUILayout.PropertyField(_color, _colorUI); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(_container.gameObject, "change name"); _container.gameObject.name = name; EditorUtility.SetDirty(_container.gameObject); } base.DrawDefaultInspector(); } } } <file_sep>using UnityEngine; using UnityEditor.Animations; using UnityEditor; //using UnityEditorInternal; using System; using System.Collections.Generic; using Flux; namespace FluxEditor { [FEditor(typeof(FPlayAnimationEvent))] public class FAnimationEventEditor : FEventEditor { // [SerializeField] protected FPlayAnimationEvent AnimEvt { get { return (FPlayAnimationEvent)Obj; } } // [SerializeField] protected FAnimationTrack AnimTrack { get { return (FAnimationTrack)Owner.Obj; } } protected AnimatorState _animState; protected AnimatorStateTransition _transitionToState; private SerializedObject _animEvtSO; private SerializedProperty _blendLength; private SerializedProperty _startOffset; private SerializedObject _transitionSO; private SerializedProperty _transitionExitTime; private SerializedProperty _transitionDuration; private SerializedProperty _transitionOffset; private static int _mouseDown = int.MinValue; public override void OnDelete() { FAnimationEventInspector.CheckDeleteAnimation(AnimEvt); } private void UpdateEventFromController() { bool isBlending = AnimEvt.IsBlending(); if (isBlending) { if (_transitionToState == null) { _transitionToState = FAnimationTrackInspector.GetTransitionTo(AnimEvt); if (_transitionToState == null || _transitionToState.conditions.Length > 0) { FAnimationTrackInspector.RebuildStateMachine((FAnimationTrack)TrackEditor.Track); _transitionToState = FAnimationTrackInspector.GetTransitionTo(AnimEvt); } } if (_transitionSO == null) { if (_transitionToState != null) { _transitionSO = new SerializedObject(_transitionToState); _transitionExitTime = _transitionSO.FindProperty("m_ExitTime"); _transitionDuration = _transitionSO.FindProperty("m_TransitionDuration"); _transitionOffset = _transitionSO.FindProperty("m_TransitionOffset"); } } else if (_transitionSO.targetObject == null) { _transitionExitTime = null; _transitionDuration = null; _transitionOffset = null; _transitionSO = null; } } else { if (_transitionToState != null || _transitionSO != null) { _transitionToState = null; _transitionSO = null; _transitionExitTime = null; _transitionOffset = null; _transitionDuration = null; } } if (_transitionSO != null) { _transitionSO.Update(); _animEvtSO.Update(); FPlayAnimationEvent prevAnimEvt = (FPlayAnimationEvent)AnimTrack.Events[AnimEvt.GetId() - 1]; AnimationClip prevAnimEvtClip = prevAnimEvt._animationClip; if (prevAnimEvtClip != null) { float blendSeconds = _blendLength.intValue / prevAnimEvtClip.frameRate; if (!Mathf.Approximately(blendSeconds, _transitionDuration.floatValue)) { _transitionDuration.floatValue = blendSeconds; float p = blendSeconds / prevAnimEvtClip.length; _transitionExitTime.floatValue = p > 1f ? 1f : 1f - Mathf.Clamp01(blendSeconds / prevAnimEvtClip.length); _animEvtSO.ApplyModifiedProperties(); } float startOffsetNorm = _startOffset.intValue / AnimEvt._animationClip.frameRate / AnimEvt._animationClip.length; if (!Mathf.Approximately(startOffsetNorm, _transitionOffset.floatValue)) { _transitionOffset.floatValue = startOffsetNorm; _animEvtSO.ApplyModifiedProperties(); } } _transitionSO.ApplyModifiedProperties(); } } protected override void RenderEvent(FrameRange viewRange, FrameRange validKeyframeRange) { if (_animEvtSO == null) { _animEvtSO = new SerializedObject(AnimEvt); _blendLength = _animEvtSO.FindProperty("_blendLength"); _startOffset = _animEvtSO.FindProperty("_startOffset"); } UpdateEventFromController(); _animEvtSO.Update(); FAnimationTrackEditor animTrackEditor = (FAnimationTrackEditor)TrackEditor; Rect transitionOffsetRect = _eventRect; int startOffsetHandleId = EditorGUIUtility.GetControlID(FocusType.Passive); int transitionHandleId = EditorGUIUtility.GetControlID(FocusType.Passive); bool isBlending = AnimEvt.IsBlending(); bool isAnimEditable = Flux.FUtility.IsAnimationEditable(AnimEvt._animationClip); if (isBlending) { transitionOffsetRect.xMin = Rect.xMin + SequenceEditor.GetXForFrame(AnimEvt.Start + AnimEvt._blendLength) - 3; transitionOffsetRect.width = 6; transitionOffsetRect.yMin = transitionOffsetRect.yMax - 8; } switch (Event.current.type) { case EventType.MouseDown: if (EditorGUIUtility.hotControl == 0 && Event.current.alt && !isAnimEditable) { if (isBlending && transitionOffsetRect.Contains(Event.current.mousePosition)) { EditorGUIUtility.hotControl = transitionHandleId; AnimatorWindowProxy.OpenAnimatorWindowWithAnimatorController((AnimatorController)AnimTrack.AnimatorController); if (Selection.activeObject != _transitionToState) Selection.activeObject = _transitionToState; Event.current.Use(); } else if (_eventRect.Contains(Event.current.mousePosition)) { _mouseDown = SequenceEditor.GetFrameForX(Event.current.mousePosition.x) - AnimEvt.Start; EditorGUIUtility.hotControl = startOffsetHandleId; Event.current.Use(); } } break; case EventType.Ignore: case EventType.MouseUp: if (EditorGUIUtility.hotControl == transitionHandleId || EditorGUIUtility.hotControl == startOffsetHandleId) { EditorGUIUtility.hotControl = 0; Event.current.Use(); } break; case EventType.MouseDrag: if (EditorGUIUtility.hotControl == transitionHandleId) { int mouseDragPos = Mathf.Clamp(SequenceEditor.GetFrameForX(Event.current.mousePosition.x - Rect.x) - AnimEvt.Start, 0, AnimEvt.Length); if (_blendLength.intValue != mouseDragPos) { _blendLength.intValue = mouseDragPos; FPlayAnimationEvent prevAnimEvt = (FPlayAnimationEvent)animTrackEditor.Track.GetEvent(AnimEvt.GetId() - 1); float blendSeconds = _blendLength.intValue / prevAnimEvt._animationClip.frameRate; if (_transitionDuration != null) { _transitionDuration.floatValue = blendSeconds; float p = blendSeconds / prevAnimEvt._animationClip.length; _transitionExitTime.floatValue = p > 1f ? 1f : 1f - Mathf.Clamp01(blendSeconds / prevAnimEvt._animationClip.length); } Undo.RecordObject(this, "Animation Blending"); } Event.current.Use(); } else if (EditorGUIUtility.hotControl == startOffsetHandleId) { int mouseDragPos = Mathf.Clamp(SequenceEditor.GetFrameForX(Event.current.mousePosition.x - Rect.x) - AnimEvt.Start, 0, AnimEvt.Length); int delta = _mouseDown - mouseDragPos; _mouseDown = mouseDragPos; _startOffset.intValue = Mathf.Clamp(_startOffset.intValue + delta, 0, AnimEvt._animationClip.isLooping ? AnimEvt.Length : Mathf.RoundToInt(AnimEvt._animationClip.length * AnimEvt._animationClip.frameRate) - AnimEvt.Length); if (_transitionOffset != null) _transitionOffset.floatValue = (_startOffset.intValue / AnimEvt._animationClip.frameRate) / AnimEvt._animationClip.length; Undo.RecordObject(this, "Animation Offset"); Event.current.Use(); } break; } _animEvtSO.ApplyModifiedProperties(); if (_transitionSO != null) _transitionSO.ApplyModifiedProperties(); switch (Event.current.type) { case EventType.DragUpdated: if (_eventRect.Contains(Event.current.mousePosition)) { int numAnimationsDragged = FAnimationEventInspector.NumAnimationsDragAndDrop(Evt.Sequence.FrameRate); DragAndDrop.visualMode = numAnimationsDragged > 0 ? DragAndDropVisualMode.Link : DragAndDropVisualMode.Rejected; Event.current.Use(); } break; case EventType.DragPerform: if (_eventRect.Contains(Event.current.mousePosition)) { AnimationClip animationClipDragged = FAnimationEventInspector.GetAnimationClipDragAndDrop(Evt.Sequence.FrameRate); if (animationClipDragged) { int animFrameLength = Mathf.RoundToInt(animationClipDragged.length * animationClipDragged.frameRate); FAnimationEventInspector.SetAnimationClip(AnimEvt, animationClipDragged); FrameRange maxRange = AnimEvt.GetMaxFrameRange(); SequenceEditor.MoveEvent(AnimEvt, new FrameRange(AnimEvt.Start, Mathf.Min(AnimEvt.Start + animFrameLength, maxRange.End))); DragAndDrop.AcceptDrag(); Event.current.Use(); } else { Event.current.Use(); } } break; } // FrameRange currentRange = Evt.FrameRange; base.RenderEvent(viewRange, validKeyframeRange); // if( isAnimEditable && currentRange.Length != Evt.FrameRange.Length ) // { // FAnimationEventInspector.ScaleAnimationClip( AnimEvt._animationClip, Evt.FrameRange ); // } if (Event.current.type == EventType.Repaint) { if (isBlending && !isAnimEditable && viewRange.Contains(AnimEvt.Start + AnimEvt._blendLength)) { GUISkin skin = FUtility.GetFluxSkin(); GUIStyle transitionOffsetStyle = skin.GetStyle("BlendOffset"); Texture2D t = FUtility.GetFluxAssets<Texture2D>("Blender.png"); float offset = SequenceEditor.PixelsPerFrame * AnimEvt._startOffset; float x = _eventRect.xMin + offset; float maxWidth = SequenceEditor.PixelsPerFrame * AnimEvt.Length - offset; float width = SequenceEditor.PixelsPerFrame * AnimEvt._blendLength; if (width > maxWidth) width = maxWidth; Rect r = new Rect(x, _eventRect.yMin + 1, width, _eventRect.height - 2); Color guiColor = GUI.color; Color c = new Color(1f, 1f, 1f, 0.5f); c.a *= guiColor.a; GUI.color = c; GUI.DrawTexture(r, t); if (Event.current.alt) GUI.color = Color.black; GUI.color = guiColor; } if (EditorGUIUtility.hotControl == transitionHandleId) { Rect transitionOffsetTextRect = transitionOffsetRect; transitionOffsetTextRect.y -= 16; transitionOffsetTextRect.height = 20; transitionOffsetTextRect.width += 50; GUI.Label(transitionOffsetTextRect, AnimEvt._blendLength.ToString(), EditorStyles.label); } if (EditorGUIUtility.hotControl == startOffsetHandleId) { Rect startOffsetTextRect = _eventRect; GUI.Label(startOffsetTextRect, AnimEvt._startOffset.ToString(), EditorStyles.label); } } } public override void OnEventFinishedMoving(FrameRange oldFrameRange) { ////---动画帧数据不做缩放操作 //if (oldFrameRange.Length != AnimEvt.FrameRange.Length && Flux.FUtility.IsAnimationEditable(AnimEvt._animationClip)) //{ // FAnimationEventInspector.ScaleAnimationClip(AnimEvt._animationClip, AnimEvt.FrameRange); //} } } } <file_sep>Local = {} Local.LogManager = true --常规日志开关 Local.LogTraceback = true --日志堆栈信息开关 Local.LogProtocol = false --网络协议日志 Local.Status = false --效率监控开关 Local.HideFPS = true --隐藏FPS Local.LogModuals ={ Moduals = false, -- 当前加载模块日志 Skill = false, -- 技能 Action = false, -- 动作 UIManager = false, -- UI模块 } ------------------------------------ --常驻内存UI列表 ------------------------------------ Local.UIPersistentList = { "dlgjoystick", "dlgloading", } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class Sequence : XmlObject { /// <summary> /// 序列ID /// <summary> public int Id; /// <summary> /// 碰撞区域定义列表 /// <summary> public List<HitZone> HitZones = new List<HitZone>(); /// <summary> /// 时间事件列表 /// <summary> public List<Timeline> Timelines = new List<Timeline>(); public override void Write(TextWriter _1) { Write(_1, "Id", this.Id); Write(_1, "HitZones", this.HitZones); Write(_1, "Timelines", this.Timelines); } public override void Read(XmlNode _1) { foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Id": this.Id = ReadInt(_2); break; case "HitZones": GetChilds(_2).ForEach (_3 => this.HitZones.Add(ReadObject<XmlCfg.Skill.HitZone>(_3, "XmlCfg.Skill.HitZone"))); break; case "Timelines": GetChilds(_2).ForEach (_3 => this.Timelines.Add(ReadObject<XmlCfg.Skill.Timeline>(_3, "XmlCfg.Skill.Timeline"))); break; } } } } <file_sep>-- 1 表示需要递归导出子GameObject的fields -- 2 表示只导到当前GameObject,不再导出子GameObject -- 直接解析指定组件,非GameObject local prefixs = { Text = 1, Image = 1, RawImage = 1, Button = 1, Toggle = 1, Slider = 1, Panel = 1, ScrollView = 1, InputField = 1, Grid = 1, List = 2, } local function CollectExportedGameObject(transform, sets) for i = 0, transform.childCount - 1 do local childT = transform:GetChild(i) ---@type UnityEngine.GameObject local child = childT.gameObject local name = child.name local _, pos = name:find('_', 2, true) local isGroup = false if pos and pos > 1 then local prefix = name:sub(1, pos - 1) local ftype = prefixs[prefix] if ftype then if sets[name] then -- printyellow("warn:" .. name .. " dumplicate! skip!") else local com = child:GetComponent(prefix) if com then sets[name] = com end isGroup = (ftype == 2) end end end if not isGroup then CollectExportedGameObject(childT, sets) end end end local function ExportFields(gameObject) local fields = {} CollectExportedGameObject(gameObject.transform, fields) return fields end return { ExportFields = ExportFields, } <file_sep>using UnityEngine; using UnityEditor; using UnityEditor.Animations; //using UnityEditorInternal; using System.Collections.Generic; using Flux; using FluxEditor; namespace FluxEditor { [CustomEditor(typeof(FCharacterTrack))] public class FRushTrackInspector : FOwnerTrackInspector { } } <file_sep>using UnityEngine; using UnityEditor; using Flux; namespace FluxEditor { [CustomEditor(typeof(Flux.FPlayAudioEvent), true)] public class FPlayAudioEventInspector : FEventInspector { private FPlayAudioEvent _audioEvt = null; private SerializedProperty _audioClip = null; private SerializedProperty _volume = null; private SerializedProperty _loop = null; private SerializedProperty _speedDeterminesPitch = null; private SerializedProperty _startOffset = null; private GUIContent _audioClipUI; private GUIContent _volumeUI; private GUIContent _loopUI; private GUIContent _speedDeterminesPitchUI; private GUIContent _startOffsetUI; protected override void OnEnable () { base.OnEnable(); _audioEvt = (FPlayAudioEvent)target; _audioClip = serializedObject.FindProperty("_audioClip"); _volume = serializedObject.FindProperty("_volume"); _loop = serializedObject.FindProperty("_loop"); _speedDeterminesPitch = serializedObject.FindProperty("_speedDeterminesPitch"); _startOffset = serializedObject.FindProperty("_startOffset"); _audioClipUI = new GUIContent("音频"); _volumeUI = new GUIContent("音量"); _loopUI = new GUIContent("是否循环"); _speedDeterminesPitchUI = new GUIContent("速度决定音高"); _startOffsetUI = new GUIContent("起点偏移"); } public override void OnInspectorGUI () { AudioClip currentClip = _audioEvt.AudioClip; base.OnInspectorGUI(); if ( currentClip != _audioEvt.AudioClip && _audioEvt.AudioClip != null && !_audioEvt.Loop ) { if( _audioEvt.LengthTime > _audioEvt.AudioClip.length ) { Undo.RecordObject( _audioEvt, null ); _audioEvt.Length = Mathf.RoundToInt( _audioEvt.AudioClip.length * _audioEvt.Sequence.FrameRate ); FSequenceEditorWindow.RefreshIfOpen(); } } serializedObject.Update(); EditorGUILayout.PropertyField(_audioClip, _audioClipUI); EditorGUILayout.PropertyField(_volume, _volumeUI); EditorGUILayout.PropertyField(_loop, _loopUI); EditorGUILayout.PropertyField(_speedDeterminesPitch, _speedDeterminesPitchUI); _startOffset.intValue = Mathf.Clamp( _startOffset.intValue, 0, _audioEvt.GetMaxStartOffset() ); EditorGUI.BeginChangeCheck(); EditorGUILayout.IntSlider( _startOffset, 0, _audioEvt.GetMaxStartOffset() , _startOffsetUI); if( EditorGUI.EndChangeCheck() ) { if( FSequenceEditorWindow.instance != null ) FSequenceEditorWindow.instance.Repaint(); } serializedObject.ApplyModifiedProperties(); } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class CubeZone : XmlCfg.Skill.HitZone { /// <summary> /// 方盒缩放大小 /// <summary> public XmlCfg.Vector3 Scale; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Scale", this.Scale); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Scale": this.Scale = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Game { public class SoundManager : IManager { public static SoundManager Instance { get { if (_instance == null) _instance = new SoundManager(); return _instance; } } static SoundManager _instance; protected SoundManager() { } public void Init() { } public void Dispose() { } } } <file_sep>#-----------------------------------CSharp层 #GameManager - 已实现 #LuaManager - 1.连通CS与LUA -OK 2.绑定第三发库 3.统一CS和LUA值类型 #Pools - 1.AnimationClip 2.AudioClip 3.CharacterClip 4.EffectClip #-----------------------------------Lua层 #事件监听系统 - 1.网络事件:消息收发 2.游戏事件:本地自定义事件 -OK #UI流程相关功能 - 1.控件解析工具 2.控件API提示生成工具[CSharp层实现] #常用集合 - OK 1.栈 2.队列 #Class继承机制实现 -OK #游戏输入控制系统 #lua层值类型的重写 - 性能测试时完成 #------------------------------------人物动作技能系统 #动作配置器 -待移植 #技能配置器 1.Timeline开发 2.技能轨道及剪辑开发 3.lua层FSM设计 #------------------------------------模块完成顺序 #xlua框架除网络,部分UI,性能分析等外 #完整UI系统及api提示工具 #Timeline工具以及lua运行时逻辑 #网络系统模块,包括protob集成以及生成工具 #输入控制系统,寻路系统,AI系统 #性能分析 #小工具的整理与封装 <file_sep>local pairs = pairs local require = require local format = string.format local match = string.match local loaded = package.loaded local Time = Time local Local = Local local CfgMgr = CfgMgr local ResMgr = ResMgr local Vector3 = Vector3 local LogError = LogError local LuaUtils = LuaUtils local LuaHelper = LuaHelper local GameObject = GameObject local printt = printt local printcolor = printcolor local ConditionOp = ConditionOp local ViewUtil = require "Common.ViewUtil" local gameEvent = GameEvent local LOAD_ING = 1 --正在加载中 local LOAD_SUCC = 2 --加载成功 local LAYER_UI = 20 --UI Layer层 local MAX_HIDE_VIEW_NUM = 0 local UI_LOAD_TYPE = CS.Game.ResourceLoadType.LoadBundleFromFile -- www方式加载 local NeedRefresh --是否需要刷新 local OnShow --页面显示回调 local OnHide --页面隐藏回调 local ShowLoading --显示加载中提示 local HideLoading --隐藏加载中提示 local ShowLoadedView --显示已经加载的页面 用于弹出堆栈 或者tab页切换 local HideLoadedView --隐藏已经加载的页面 用于弹出堆栈 或者tab页切换 local OnShowTab --显示Tab页 local OnHideTab --隐藏Tab页 local CallBackDestroyAllDlgs --销毁所有界面回调事件 --[[ filename -- 文件名[小写] status -- 加载状态[加载成功/加载中] loaded -- 是否已被加载 gameObject -- 界面游戏对象 isDialog -- 是否为窗口 dialogViewName -- 是带dlgdialog的窗口? tabs -- initedTabs -- tabName,true tabIndex -- tabGroupStates -- tabIndex,map{tabName,isShow} hideTime -- 最后隐藏时刻 isShow -- 是否已显示 needRefresh -- 是否需要刷新 refreshParams -- 刷新界面时所带参数 --]] ---@type Stack local _dialogStack = nil local _dialogConfigs = nil local _views = {} local _isLocked = false local _uiRoot = nil local _playingParticleSystems = {} local UIManager = {} local this = UIManager UIShowType = { Default = 0, --默认策略显示 ShowImmediate = 1, --直接调用show Refresh = 2, --强制调用show RefreshAndShowImmediate = 3, -- bit.bor(UIShowType.ShowImmediate,UIShowType.Refresh) DestroyWhenHide = 4, --Hide时释放资源 } --显示已经加载的页面 用于弹出堆栈 或者tab页切换 ShowLoadedView = function(viewName) if Local.LogModuals.UIManager then print("ShowLoadedView ==>>", viewName) end local data = this.GetViewData(viewName) local params = data.params if not data.isShow and this.HasScript(viewName) then if this.IsUIShowType(viewName, UIShowType.Refresh) then if (this.HasMethod(viewName, "ShowTab")) and not this.IsUIShowType(viewName, UIShowType.ShowImmediate) then this.Call(viewName, "ShowTab", params) else this.Show(viewName, params) end else data.gameObject:SetActive(true) data.isShow = true end end if data.isDialog then this.RefreshDlgdialog(viewName, data.tabIndex) data.dialogViewName = viewName local tabGroup = this.gettabgroup(viewName, data.tabIndex) if tabGroup then for tabName, isShow in pairs(data.tabGroupStates[data.tabIndex]) do if isShow then local tabData = this.GetViewData(tabName) tabData.dialogViewName = viewName this.ShowLoadedView(tabName, tabData.params) end end end end end --隐藏已经加载的页面 用于弹出堆栈 或者tab页切换 HideLoadedView = function(viewName) if Local.LogModuals.UIManager then print("HideLoadedView ==>>", viewName) end local data = this.GetViewData(viewName) if data.isShow and this.HasScript(viewName) then if this.IsUIShowType(viewName, UIShowType.Refresh) then if this.HasMethod(viewName, "HideTab") and not this.IsUIShowType(viewName, UIShowType.ShowImmediate) then this.Call(viewName, "HideTab") else this.Hide(viewName) end else data.hideTime = Time.time data.gameObject:SetActive(false) data.isShow = false end end if data.isDialog then local tabGroup = this.gettabgroup(viewName, data.tabIndex) if tabGroup then for tabName, isShow in pairs(data.tabGroupStates[data.tabIndex]) do if isShow then this.HideLoadedView(tabName) end end end end end function UIManager.Init() _uiRoot = FindObj("/UIRoot/UICamera") if _uiRoot and _uiRoot.transform.parent then GameObject.DontDestroyOnLoad(_uiRoot.transform.parent) end gameEvent.UpdateEvent:Add(this.Update) gameEvent.LateUpdateEvent:Add(this.LateUpdate) _dialogStack = Stack:new() --_dialogConfigs = CfgMgr.GetConfig("dialog") --if Local.LogModuals.UIManager then -- printt(_dialogConfigs or {}) --end end function UIManager.Update() for viewName, info in pairs(_views) do if info.isShow then if (this.HasMethod(viewName, "Update")) then this.Call(viewName, "Update") end end end for i = #_playingParticleSystems, 1, -1 do local particle = _playingParticleSystems[i].particle if not particle.isPlaying then local callback = _playingParticleSystems[i].callback if callback then callback() end table.remove(_playingParticleSystems, i) else _playingParticleSystems[i].time = _playingParticleSystems[i].time + Time.deltaTime end end end function UIManager.LateUpdate() for viewName, info in pairs(_views) do if info.isShow then if (this.HasMethod(viewName, "LateUpdate")) then this.Call(viewName, "LateUpdate") end end if info.needRefresh and NeedRefresh(viewName) then if Local.LogModuals.UIManager then print("LateUpdate Refresh ==>>", viewName) printt(info.refreshparams) end info.needRefresh = false --PrintYellow("ViewName",viewName) this.Call(viewName, "Refresh", info.refreshparams) end end --late_updateCharacterInfoOnUI() end function UIManager.UnloadExpireView(now) local unshowViewNum = 0 local toDestroyViewName local minHideTime = now for name, data in pairs(_views) do if data ~= nil and data.status == LOAD_SUCC and not data.isShow and not this.IsPersistent(name) and not this.IsInStack(name) then unshowViewNum = unshowViewNum + 1 if data.hideTime ~= nil and data.hideTime < minHideTime then toDestroyViewName = name minHideTime = data.hideTime end end end if toDestroyViewName and unshowViewNum > MAX_HIDE_VIEW_NUM then Destroy(toDestroyViewName) end end --未实现 function UIManager.SecondUpdate(now) this.UnloadExpireView(now) for viewName, info in pairs(_views) do if info.isShow and this.HasMethod(viewName, "SecondUpdate") then this.Call(viewName, "SecondUpdate", now) end end end function UIManager.GetViewData(viewName) local data = _views[viewName] if not data then data = { filename = nil, status = nil, loaded = nil, gameObject = nil, isDialog = nil, dialogViewName = nil, tabGroup = nil, isInitedTabs = nil, tabIndex = nil, tabGroupStates = nil, hideTime = nil, isShow = nil, needRefresh = nil, refreshParams = nil, } local _, fileName = match(viewName, "^(.*)%.(.*)$") data.fileName = ConditionOp(fileName, fileName, viewName) _views[viewName] = data end return data end function UIManager.GetModuleName(viewName) return "UI." .. viewName end function UIManager.GetViewModule(viewName) local view = require(this.GetModuleName(viewName)) if not view then LogError("View:%s script file not find!", viewName) end return view end function UIManager.HasScript(viewName) return LuaHelper.ScriptExists(format("UI.%s", viewName)) end function UIManager.HasMethod(viewName, methodName) local view = this.GetViewModule(viewName) if not view then return false end local method = view[methodName] if not method then return false end return true end function UIManager.IsShow(viewName) local data = _views[viewName] if data and data.isShow then return data.isShow end return false end function UIManager.HasLoaded(viewName) local viewData = this.GetViewData(viewName) return viewData.status == LOAD_SUCC end function UIManager.Call(viewName, methodName, params) local view = this.GetViewModule(viewName) if not view then return end local method = view[methodName] if not method then print(format("View. %s.%s not find.", viewName, methodName)) return end local viewData = this.GetViewData(viewName) if viewData.status ~= LOAD_SUCC and methodName ~= "Show" and methodName ~= "ShowDialog" and methodName ~= "ShowTabByIndex" and methodName ~= "ShowTab" then LogError("uimanager. view:%s not loaded! can't call method:%s", viewName, methodName) return end local succ = LuaUtils.Myxpcall(method, params) if succ then return true else LogError("View.call %s.%s fail.", viewName, methodName) return false end end function UIManager.CallWithReturn(viewName, methodName, params) local view = this.GetViewModule(viewName) if not view then return nil end local method = view[methodName] if not method then print(format("View. %s.%s not find.", viewName, methodName)) return nil end return method(params) end function UIManager.GetUIShowType(viewName) local uishowtype = UIShowType.Default if (this.HasMethod(viewName, "UIShowType")) then uishowtype = this.CallWithReturn(viewName, "UIShowType") end return uishowtype end function UIManager.IsUIShowType(viewName, uiShowType) local viewUIShowType = this.GetUIShowType(viewName) return uiShowType & viewUIShowType > 0 end function UIManager.GetDlgsShow() local list = {} for name, data in pairs(_views) do if data.isShow then table.insert(list, name) end end return list end function UIManager.IsPersistent(viewName) return Local.UIPersistentMap[viewName] == true end function UIManager.IsInStack(viewName) if _dialogStack:Count() > 0 then _dialogStack:InitEnumerator() while _dialogStack:MoveNext() do if _dialogStack:Current() == viewName then return true else local data = this.GetViewData(_dialogStack:Current()) if data.isInitedTabs and data.isInitedTabs[viewName] then return true end end end end return false end function UIManager.SetLock(lock) _isLocked = lock end function UIManager.GetIsLock() return _isLocked end ------------------------------------------------------------------ ---普通窗口操作方法 ------------------------------------------------------------------ OnShow = function(viewName, params) if Local.LogModuals.UIManager then printcolor("OnShow ==>>", viewName) end local data = this.GetViewData(viewName) data.params = params if viewName ~= "dlgopenloading" then HideLoading() end if data.dialogViewName ~= nil and data.dialogViewName ~= this.CurrentDialogName() then print("Dialog has been hide", "dialog name:", data.dialogViewName, "current dialog name:", this.CurrentDialogName()) --HideLoadedView(viewName)隐藏界面加载提示界面 elseif this.HasScript(viewName) then this.Refresh(viewName, params) --if data.uifadein ~= nil then -- data.uifadein:Play(true) --end end end OnHide = function(viewName) if Local.LogModuals.UIManager then printcolor("OnHide ==>>", viewName) end local data = this.GetViewData(viewName) if this.Call(viewName, "Hide") then data.isShow = false data.gameObject:SetActive(false) data.dialogViewName = nil if this.IsUIShowType(viewName, UIShowType.DestroyWhenHide) then this.Destroy(viewName, "Destroy") end end end OnShowTab = function(viewName, tabName, params) if Local.LogModuals.UIManager then printcolor("OnShowTab ==>>", viewName, tabName) end local data = this.GetViewData(viewName) local tabData = this.GetViewData(tabName) if tabData.isShow then return end if data.isInitedTabs[tabName] then tabData.params = params ShowLoadedView(tabName, params) else if (this.HasMethod(tabName, "ShowTab")) and not this.IsUIShowType(tabName, UIShowType.ShowImmediate) then this.Call(tabName, "ShowTab", params) else this.Show(tabName, params) end data.isInitedTabs[tabName] = true tabData.dialogViewName = viewName end end OnHideTab = function(viewName, tabName) if Local.LogModuals.UIManager then printcolor("OnHideTab ==>>", viewName, tabName) end local data = this.GetViewData(viewName) if Local.LogModuals.UIManager then printt(data.tabGroupStates) end local tabData = this.GetViewData(tabName) if not tabData.isShow then return end if Local.LogModuals.UIManager then printcolor("TabName:", tabName, "inited:", data.isInitedTabs[tabName]) end if data.isInitedTabs[tabName] then HideLoadedView(tabName) end end NeedRefresh = function(viewName) return this.IsShow(viewName) or this.IsInStack(viewName) end function UIManager.Show(viewName, params) if Local.LogModuals.UIManager then printcolor("Show ==>>", viewName) printt(params) end local data = this.GetViewData(viewName) if data.isShow then return end if data.status ~= LOAD_SUCC then if not data.loaded then print(format("View: %s %s", viewName, "not loaded!\n"), debug.traceback()) data.loaded = LOAD_ING --ShowLoading()--显示界面加载提示界面 ResMgr:AddTask(format("ui/%s.bundle", data.fileName), function(assetObj) if assetObj == nil then return end local viewObj = GameObject.Instantiate(assetObj) GameObject.DontDestroyOnLoad(viewObj) if not viewObj then data.loaded = nil LogError(format("View %s prefab load fail!", viewName)) return end data.status = LOAD_SUCC data.gameObject = viewObj data.fields = ViewUtil.ExportFields(viewObj) local trans = viewObj.transform trans.parent = _uiRoot.transform trans.localPosition = Vector3.zero trans.localScale = Vector3.one viewObj.name = data.fileName viewObj.layer = LAYER_UI viewObj:SetActive(true) if this.Call(viewName, "Init", { viewName, viewObj, data.fields }) and this.Call(viewName, "Show", params) then data.isShow = true OnShow(viewName, params) else viewObj:SetActive(false) end end, UI_LOAD_TYPE) end return end data.gameObject:SetActive(true) if this.Call(viewName, "Show", params) then data.isShow = true OnShow(viewName, params) else data.gameObject:SetActive(false) end end function UIManager.Refresh(viewName, params) if Local.LogModuals.UIManager then printcolor("Refresh ==>>", viewName) end if NeedRefresh(viewName) then local data = this.GetViewData(viewName) data.needRefresh = true data.refreshParams = params end end function UIManager.ShowOrRefresh(viewName, params) if this.IsShow(viewName) then this.Refresh(viewName, params) else this.Show(viewName, params) end end function UIManager.IfShowThenCall(viewName, methodName, params) if this.IsShow(viewName) then this.Call(viewName, methodName, params) end end function UIManager.Hide(viewName) if Local.LogModuals.UIManager then printcolor("Hide ==>>", viewName) end local data = this.GetViewData(viewName) data.hideTime = Time.time if not data.isShow then print(format("View:%s not show!", viewName)) return end if data.uifadeout ~= nil then --local DlgHiding = require "UI.DlgHiding" --UIEventListenerHelper.SetPlayTweenFinish(data.uifadeout, function(uifadeout) -- DlgHiding.OnFadeOutEnd() -- OnHide(viewName) --end) --data.uifadeout:Play(true) --DlgHiding.OnFadeOutBegin() else OnHide(viewName) end --local NoviceGuideTrigger = require "noviceguide.noviceguide_trigger" --NoviceGuideTrigger.HideDialog(viewName) end function UIManager.HideImmediate(viewName) if Local.LogModuals.UIManager then printcolor("HideImmediate ==>>", viewName) end local data = this.GetViewData(viewName) data.hideTime = Time.time if not data.isShow then print(format("View:%s not show!", viewName)) return end OnHide(viewName) end function UIManager.Destroy(viewName) local data = this.GetViewData(viewName) if data.isShow then this.HideImmediate(viewName) end this.Call(viewName, "Destroy") if data.fields then for k, _ in pairs(data.fields) do data.fields[k] = nil end data.fields = nil end _views[viewName] = nil assert(loaded[this.GetModuleName(viewName)]) loaded[this.GetModuleName(viewName)] = nil GameObject.Destroy(data.gameObject) end function UIManager.HideAll() for name, data in pairs(_views) do this.Hide(name) end end function UIManager.RegistCallBackDestroyAllDlgs(callback) printt(CallBackDestroyAllDlgs, "RegistCallBackDestroyAllDlgs") CallBackDestroyAllDlgs = callback end function UIManager.DestroyAllDlgs() local list = this.GetDlgsShow() local d = false for _, name in pairs(list) do d = false for _, persistentName in pairs(Local.UIPersistentList) do if name == persistentName then this.Hide(name) d = true break end end end _dialogStack:Clear() if CallBackDestroyAllDlgs then CallBackDestroyAllDlgs() CallBackDestroyAllDlgs = nil end end function UIManager.OnLogout() this.HideAll() end --Tab类型界面控制 function UIManager.ShowTab(tabName, params) if _dialogStack:Count() > 0 then local viewName = _dialogStack:Peek() if Local.LogModuals.UIManager then print("ShowTab ==>>", viewName, tabName) printt(params) end local data = this.GetViewData(viewName) data.tabGroupStates[data.tabIndex][tabName] = true OnShowTab(viewName, tabName, params) end end function UIManager.HideTab(tabName) if _dialogStack:Count() > 0 then local viewName = _dialogStack:Peek() if Local.LogModuals.UIManager then printcolor("HideTab ==>>", viewName, tabName) end local data = this.GetViewData(viewName) if Local.LogModuals.UIManager then printt(data.tabGroupStates) end data.tabGroupStates[data.tabIndex][tabName] = false OnHideTab(viewName, tabName) end end function UIManager.GetDialog(viewName) if _dialogConfigs == nil then print("GetDialog Error! Dialog CSV Not Loaded!", viewName) return nil end return _dialogConfigs[viewName] end function UIManager.GetTabGroup(viewName, tabIndex) local dialog = this.GetDialog(viewName) if dialog == nil then print("GetTabGroup Error! No TabGroup!", viewName, tabIndex) return nil end return dialog.tabgroups[tabIndex] end function UIManager.ShowTabByIndex(viewName, tabIndex, params) if Local.LogModuals.UIManager then printcolor("ShowTabByIndex ==>>", viewName, tabIndex) end local data = this.GetViewData(viewName) local tabgroup = this.GetTabGroup(viewName, tabIndex) if tabgroup then data.tabIndex = tabIndex if data.tabGroupStates[data.tabIndex] == nil then data.tabGroupStates[data.tabIndex] = {} for _, tab in ipairs(tabgroup.tabs) do data.tabGroupStates[data.tabIndex][tab.tabname] = not tab.hide end end if Local.LogModuals.UIManager then printt(data.tabGroupStates) end for tabName, isShow in pairs(data.tabGroupStates[data.tabIndex]) do if isShow then OnShowTab(viewName, tabName, params) end end end end function UIManager.HideTabByIndex(viewName, tabIndex) if Local.LogModuals.UIManager then print("HideTabByIndex ==>>", viewName, tabIndex) end local tabgroup = this.GetTabGroup(viewName, tabIndex) if tabgroup then for _, tab in ipairs(tabgroup.tabs) do OnHideTab(viewName, tab.tabName) end end --local NoviceGuideTrigger = require "noviceguide.noviceguide_trigger" --NoviceGuideTrigger.HideDialog(viewName) end ------------------------------------------------------------------ ---针对模块操作方法 ------------------------------------------------------------------ function UIManager.ShowMaincityDlgs() if Local.LogModuals.UIManager then print("ShowMaincityDlgs ==>>") end for _, dlg in pairs(Local.MaincityDlgList) do if not this.IsShow(dlg) then this.Show(dlg) end end end function UIManager.HideMainCityDlgs() if Local.LogModuals.UIManager then print("HideMainCityDlgs ==>>") end for _, dlg in pairs(Local.MaincityDlgList) do if this.IsShow(dlg) then this.Hide(dlg) end end end function UIManager.BeforeShowDialog() if this.IsShow("dlgjoystick") then --Game.JoyStickManager.singleton:Reset() printcolor("---------------DlgJoystick 界面未完成") end end function UIManager.RefreshDlgdialog(dialogViewName, tabindex) local dialogData = this.GetViewData("dlgdialog") if dialogData ~= nil and dialogData.uifadeout ~= nil then dialogData.uifadeout:Stop() end this.ShowOrRefresh("dlgdialog", { viewName = dialogViewName, tabIndex = tabindex }) end function UIManager.ShowDialog(viewName, params, tabIndex) if Local.LogModuals.UIManager then print("ShowDialog ==>>", viewName) printt(params) end -- 在showdialog之前隐藏其它窗口 this.BeforeShowDialog() if tabIndex == nil then tabIndex = 1 end local data = this.GetViewData(viewName) data.isDialog = true data.isInitedTabs = {} -- tab_name,true data.tabGroupStates = {} data.dialogViewName = viewName if _dialogStack:Count() > 0 then local lastViewName = _dialogStack:Peek() if lastViewName == viewName then return end HideLoadedView(lastViewName) else this.HideMainCityDlgs() end _dialogStack:Push(viewName) if Local.LogModuals.UIManager then printt(_dialogStack:ToTable()) end if this.HasScript(viewName) then ShowLoading() if (this.HasMethod(viewName, "ShowDialog")) and not this.IsUIShowType(viewName, UIShowType.ShowImmediate) then this.Call(viewName, "ShowDialog", params) else this.Show(viewName, params) end else OnShow(viewName, params) end this.ShowTabByIndex(viewName, tabIndex, params) this.RefreshDlgdialog(viewName, data.tabIndex) end function UIManager.Hidedialog(viewName, isImmediate) if Local.LogModuals.UIManager then print("HideDialog ==>>", viewName) end if _dialogStack:Count() == 0 then return else local currentViewName = _dialogStack:Peek() if currentViewName ~= viewName then return end end local data = this.GetViewData(viewName) local tabGroup = this.gettabgroup(viewName, data.tabIndex) if tabGroup then this.HideTabByIndex(viewName, data.tabIndex) end if this.HasScript(viewName) then if (this.HasMethod(viewName, "HideDialog")) then this.Call(viewName, "HideDialog") else this.Hide(viewName) end end _dialogStack:Pop() if _dialogStack:Count() > 0 then local lastview_name = _dialogStack:Peek() ShowLoadedView(lastview_name) else this.ShowMaincityDlgs() if isImmediate and true == isImmediate then this.HideImmediate("dlgdialog") else this.Hide("dlgdialog") end end if Local.LogModuals.UIManager then printt(_dialogStack:ToTable()) end --local NoviceGuideTrigger = require "noviceguide.noviceguide_trigger" --NoviceGuideTrigger.HideDialog(viewName) end function UIManager.CurrentDialogName() if _dialogStack:Count() == 0 then return "Stack Is Empty!" else return _dialogStack:Peek() end end function UIManager.CloseAllDialog() if _dialogStack:Count() > 0 then local lastViewName = _dialogStack:Peek() if (this.HasMethod(lastViewName, "HideDialog")) then this.Call(lastViewName, "HideDialog") else this.Hide(lastViewName) end _dialogStack:Clear() this.ShowMaincityDlgs() this.Hide("dlgdialog") end end ------------------------------------------------------------------ ---下面是公用弹窗的用法 ------------------------------------------------------------------ ShowLoading = function(beginTime, endTime) if _isLocked == true then return end if Local.LogModuals.UIManager then print("ShowLoading ==>>") end local params = { beginTime = ConditionOp(beginTime, beginTime, 0.5), endTime = ConditionOp(endTime, endTime, 3) } if this.IsShow("dlgopenloading") then this.Refresh("dlgopenloading", params) else this.Show("dlgopenloading", params) end end HideLoading = function() if _isLocked == true then return end if Local.LogModuals.UIManager then print("HideLoading ==>>") end this.Hide("dlgopenloading") end --local function ShowAlertDlg(params) -- local InfoManager = require "assistant.infomanager" -- if isLocked == true then -- return InfoManager.AddInfo(params) -- end -- return InfoManager.ShowInfo(params) --end ------------------------------------------------------------------ ---UI粒子系统操作方法 ------------------------------------------------------------------ -- 播放粒子系统及子节点中粒子系统 function UIManager.PlayUIParticleSystem(go, callback) go:SetActive(false) go:SetActive(true) local particles = go:GetComponentsInChildren(UnityEngine.ParticleSystem) if particles and particles.Length ~= 0 and particles[1] then particles[1]:Stop(true) particles[1]:Play(true) if callback then table.insert(_playingParticleSystems, { particle = particles[1], callback = callback, time = 0 }) end end end -- 停止粒子系统及子节点中粒子系统 function UIManager.StopUIParticleSystem(go) local particle = go:GetComponent("ParticleSystem") if particle then particle:Stop(true) end go:SetActive(false) end -- 遍历子节点中粒子系统 function UIManager.IsPlaying(go) local particles = go:GetComponentsInChildren(UnityEngine.ParticleSystem) for i = 1, particles.Length do local particle = particles[i] if particle.isPlaying then return true end end return false end -- 遍历子节点中粒子系统 function UIManager.IsStopped(go) local particles = go:GetComponentsInChildren(UnityEngine.ParticleSystem) for i = 1, particles.Length do local particle = particles[i] if not particle.isStopped then return false end end return true end return UIManager<file_sep>using UnityEngine; using System.Collections; using XmlCfg.Skill; namespace Flux { [FEvent("播放器/技能特效")] public class FSkillEffectEvent : FPlayParticleEvent { [SerializeField, HideInInspector] [FEventField("资源路径"), FFindPathBtn()] private string _path; //[SerializeField, HideInInspector] //[FEventField("淡出时间")] //private float _fadeOutTime; [SerializeField, HideInInspector] [FEventField("跟随目标")] private bool _followDir; [SerializeField, HideInInspector] [FEventField("节点名称")] private string _nodeName; [SerializeField, HideInInspector] [FEventField("相对于释放者", "选定设置目标,自己或者对方")] private bool _isRelateSelf; [SerializeField, HideInInspector] [FEventField("相对坐标")] private Vector3 _position; [SerializeField, HideInInspector] [FEventField("欧拉角")] private Vector3 _eulerAngles; [SerializeField, HideInInspector] [FEventField("缩放")] private Vector3 _scale; [SerializeField, HideInInspector] [FEventField("屏幕对齐方式")] private EffectAlignType _effectAlignType; //private float _startTime; private Vector3 _fixEulerAngle; protected override void OnTrigger(float timeSinceTrigger) { base.OnTrigger(timeSinceTrigger); //_startTime = timeSinceTrigger; var effect = FUtility.FindGameObject(_path); if (effect != null && _particleSystem == null) _particleSystem = effect.GetComponent<ParticleSystem>(); if (_particleSystem == null) return; if (!string.IsNullOrEmpty(_nodeName)) { //查询目标下的相对节点,再绑定特效到节点 //Transform node = //_particleSystem.transform.parent } _particleSystem.transform.localPosition = _position; _particleSystem.transform.localEulerAngles = _eulerAngles; _particleSystem.transform.localScale = _scale; if (!_followDir) { } } protected override void OnUpdateEvent(float timeSinceTrigger) { base.OnUpdateEvent(timeSinceTrigger); //float t = timeSinceTrigger - _startTime + _fadeOutTime; //if (t < LengthTime) return; if (!_followDir) { } } protected override void OnStop() { base.OnStop(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class Active : Cfg.Skill.Controller { /// <summary> /// 对象激活隐藏控制 /// <summary> public readonly bool Enable; public Active(DataStream data) : base(data) { this.Enable = data.GetBool(); } } } <file_sep>local ipairs = ipairs local setmetatable = setmetatable local print = print local error = error local network = require("network") local m_SCTimeShift = 0 ------------------------------------------------------------------------------------------------------------ --[[ --功能:获取当前时间 --入参:无 --返回值: -- [1] type:number 从1970年到当前时刻的秒数 --]] ------------------------------------------------------------------------------------------------------------ local function getTime() return os.time() end ------------------------------------------------------------------------------------------------------------ --[[ --功能:获取当前时间 --入参:无 --返回值: -- [1] type:table{year = 1998, month = 9, day = 16, yday = 259, wday = 4,hour = 23, min = 48, sec = 10, isdst = false} --]] ------------------------------------------------------------------------------------------------------------ local function getDate() return os.date() end ------------------------------------------------------------------------------------------------------------ --[[ --功能:获取时间段 --入参:seconds type:int 时间段(n秒) --返回值: -- [1] type:table{ days = 1,hours = 23,minutes=59,seconds=59} --]] ------------------------------------------------------------------------------------------------------------ local function getDateTime(seconds) local datetime = {} datetime.days = math.floor(seconds / 86400) datetime.hours = math.floor(seconds % 86400 / 3600) datetime.minutes = math.floor(seconds % 86400 % 3600 / 60) datetime.seconds = math.floor(seconds % 86400 % 3600 % 60) return datetime end ------------------------------------------------------------------------------------------------------------ --[[ -- 功能:获取时间段字符串 -- 入参:seconds type:int 时间段(n秒) -- format type:string "hh:mm:ss" -- 返回值: -- [1] type:string { 11天 23:59:59} --]] ------------------------------------------------------------------------------------------------------------ local function getDateTimeString(seconds,format) local datetime = getDateTime(seconds) local datetimestring = format --printt(datetime) --print(string.format("%2d",datetime.minutes)) --datetimestring = string.gsub(datetimestring, "dd",string.format("%d",datetime.days)) datetimestring = string.gsub(datetimestring, "hh",string.format("%02d",24*datetime.days+datetime.hours)) datetimestring = string.gsub(datetimestring, "mm",string.format("%02d",datetime.minutes)) datetimestring = string.gsub(datetimestring, "ss",string.format("%02d",datetime.seconds)) --printyellow(datetimestring) return datetimestring end ------------------------------------------------------------------------------------------------------------ --[[ --功能:获取时间段 -- 入参:type:table{ days = 1,hours = 23,minutes=59,seconds=59} --返回值: -- [1] seconds type:int 时间段(n秒) --]] ------------------------------------------------------------------------------------------------------------ local function getSeconds(params) local seconds = 0 if params.days then seconds = seconds + params.days * 86400 end if params.hours then seconds = seconds + params.hours * 3600 end if params.minutes then seconds = seconds + params.minutes * 60 end if params.seconds then seconds = seconds + params.seconds end return seconds end ------------------------------------------------------------------------------------------------------------ --[[ -- 功能:获取距离现在时间的时间间隔描述(X分钟/小时/天之前) -- 入参:milisecond type:int 格林威治绝对时间(单位毫秒) -- 返回值: -- [1] type:string {X分钟前} --]] ------------------------------------------------------------------------------------------------------------ local function GetServerTime() return os.time() + m_SCTimeShift end local function GetLocalTime() return os.time() end local function TimeNow() return os.date("*t", os.time()+m_SCTimeShift) end local function PeriodFromNow(serverms) -- printyellow("on periodfromnow, ms =", serverms) if serverms == 0 then return LocalString.Time.Online end local period = getDateTime(os.time()+m_SCTimeShift-serverms/1000) -- printt(period) if period.days > 0 then return string.format(LocalString.Time.TagFromNow, period.days, LocalString.Time.Day) elseif period.hours > 0 then return string.format(LocalString.Time.TagFromNow, period.hours, LocalString.Time.Hour) elseif period.minutes > 0 then return string.format(LocalString.Time.TagFromNow, period.minutes, LocalString.Time.Min) elseif period.seconds > 0 then return string.format(LocalString.Time.TagFromNow, period.seconds, LocalString.Time.Sec) end end local function TimeStr(serverms) return os.date("%c", serverms/1000) end local function init() --计算服务器与客户端时间差 end return { init = init, getTime = getTime, getDate = getDate, getDateTime = getDateTime, getDateTimeString = getDateTimeString, getSeconds = getSeconds, PeriodFromNow = PeriodFromNow, TimeStr = TimeStr, TimeNow = TimeNow, GetServerTime = GetServerTime, GetLocalTime = GetLocalTime, } <file_sep>namespace CS.ActorConfig { using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class ActorHelper { private const string ROOT_BONE = "Bip001"; public static GameObject Instantiate(ActorConfigEditor actorEditor) { GameObject role = Instantiate(actorEditor.CharacterPath); GameObject avatargo = Instantiate(actorEditor.AvatarPath); Debug.Log("骨骼:" + actorEditor.CharacterPath + "\n蒙皮:" + actorEditor.AvatarPath); if (role != null && avatargo != null) { role.SetActive(false); Transform bip = role.transform.Find(ROOT_BONE); if (bip != null) UnityEngine.Object.DestroyImmediate(bip.gameObject, true); while (avatargo.transform.childCount > 0) { Transform trans = avatargo.transform.GetChild(0); trans.parent = role.transform; } UnityEngine.Object.DestroyImmediate(avatargo, true); role.SetActive(true); role.transform.localScale = Vector3.one * actorEditor.ModelScale; role.tag = "Player"; } var mc = role.AddComponent<MecanimControl>(); return role; } public static GameObject Instantiate(string path) { return Instantiate(path, null); } public static GameObject Instantiate(string path, GameObject parent) { return Instantiate(path, parent, Vector3.zero, Vector3.zero, Vector3.one); } public static GameObject Instantiate(string path, GameObject parent, Vector3 pos, Vector3 eularangles, Vector3 scale) { GameObject obj = null; if (!string.IsNullOrEmpty(path)) { var Prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path); if (Prefab != null) { obj = GameObject.Instantiate(Prefab) as GameObject; if (parent != null) { obj.transform.parent = parent.transform; } obj.transform.localPosition = pos; obj.transform.localEulerAngles = eularangles; obj.transform.localScale = scale; } } return obj; } public static GameObject CreateGameObject(string name, string relPath = "/") { string path = relPath + name; GameObject go = GameObject.Find(path); if (go == null) go = new GameObject(name); GameObject parent = GameObject.Find(relPath); if (parent != null) { go.transform.parent = parent.transform; go.transform.localPosition = Vector3.zero; go.transform.localEulerAngles = Vector3.zero; } return go; } } } //if (actorEditor.Weapon != null) //{ // if (!actorEditor.Weapon.lpath.IsNullOrEmpty()) // { // var bone = role.GetChildByName(PlayEffectItem.BoneNames[CinemaDirector.PlayEffectItem.EffectInstanceBindType.LeftWeapon]); // if (bone != null) // { // string path = ActionSettings.GetWeaponPath(actorEditor.Weapon.lpath); // if (!path.IsNullOrEmpty()) // { // Debug.Log("load left weapon:" + path); // SkillEditorHelper.Instantiate(path, bone); // } // } // } // if (!actorEditor.Weapon.rpath.IsNullOrEmpty()) // { // var bone = role.GetChildByName(PlayEffectItem.BoneNames[CinemaDirector.PlayEffectItem.EffectInstanceBindType.RightWeapon]); // if (bone != null) // { // string path = HomeConfig.GetWeaponPath(actorEditor.Weapon.rpath); // if (!path.IsNullOrEmpty()) // { // Debug.Log("load right weapon:" + path); // SkillEditorHelper.Instantiate(path, bone); // } // } // } //}<file_sep>return { "Manager.CfgManager", --"Manager.TouchManager", "Manager.UIManager", }<file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; using Game; [System.Serializable] public class AnimationData { public AnimationClip clip; public string clipName; public float speed = 1; public float transitionDuration = -1; public WrapMode wrapMode; public bool applyRootMotion; [HideInInspector] public int timesPlayed = 0; [HideInInspector] public float secondsPlayed = 0; [HideInInspector] public float length = 0; [HideInInspector] public int stateHash; [HideInInspector] public string stateName; public float NormalizedTime { get { return length == 0 ? 0 : secondsPlayed / length; } } public void Reset() { clip = null; clipName = string.Empty; speed = 1; transitionDuration = -1; applyRootMotion = false; timesPlayed = 0; secondsPlayed = 0; length = 0; stateHash = 0; stateName = string.Empty; } } [RequireComponent(typeof(Animator))] public class MecanimControl : MonoBehaviour { #region ControllerPool static Game.ObjectPool<AnimatorOverrideController> controllerPool = new Game.ObjectPool<AnimatorOverrideController>(50, false); static AnimatorOverrideController GetController() { AnimatorOverrideController overrideController = controllerPool.Get(); if (overrideController == null) { //Util.LogColor("cyan", "new Controller"); var controller1 = (RuntimeAnimatorController)Resources.Load("controller1"); overrideController = new AnimatorOverrideController(); overrideController.runtimeAnimatorController = controller1; } else { //Util.LogColor("yellow", string.Format("get Controller,count:{0}", controllerPool.Count)); } return overrideController; } static void PutController(AnimatorOverrideController overrideController) { if (overrideController != null) { overrideController["State1"] = null; overrideController["State2"] = null; overrideController["State3"] = null; controllerPool.Put(overrideController); Destroy(overrideController); } } public static void ClearControllerPool() { AnimatorOverrideController controller = null; while ((controller = controllerPool.Get()) != null) { Destroy(controller); //Util.LogColor("red", string.Format("clear ControllerPool,count:{0}", controllerPool.Count)); } } #endregion public Dictionary<string, AnimationData> animations = new Dictionary<string, AnimationData>(); public bool debugMode = false; public bool alwaysPlay = false; public bool playOnStart = true; public bool overrideRootMotion = false; public float defaultTransitionDuration = 0f; public WrapMode defaultWrapMode = WrapMode.Default; public AnimationData defaultAnimationData = new AnimationData(); //State3 private AnimationData currentAnimationData; //State private bool currentMirror = false; private float currentBlendingTime = 0f; private float globalSpeed = 1; public float speed { get { return globalSpeed; } set { globalSpeed = value; if (currentAnimationData != null) { animator.speed = globalSpeed * currentAnimationData.speed; } else { animator.speed = globalSpeed; } } } [SerializeField] private string _modelName = ""; public string modelName { get { return _modelName; } set { _modelName = value; } } private Animator animator; private AnimatorOverrideController cachedController = null; //切换动作状态时,省去新增Controller private RuntimeAnimatorController controller1; public delegate void AnimEvent(AnimationData animationData); public static event AnimEvent OnAnimationBegin; public static event AnimEvent OnAnimationEnd; public static event AnimEvent OnAnimationLoop; public void Init() { ////Util.LogColor("red", "MecanimControl Start"); animator = gameObject.GetComponent<Animator>(); animator.cullingMode = AnimatorCullingMode.AlwaysAnimate; controller1 = (RuntimeAnimatorController)Resources.Load("controller1"); animator.runtimeAnimatorController = GetController(); cachedController = GetController(); foreach (var pair in animations) { AnimationData animData = pair.Value; if (animData.wrapMode == WrapMode.Default) animData.wrapMode = defaultWrapMode; animData.clip.wrapMode = animData.wrapMode; } if (defaultAnimationData.clip == null && animations.Count > 0) { var e = animations.GetEnumerator(); if (e.MoveNext()) { var animData = e.Current.Value; SetDefaultClip(animData.clip, "Default", animData.speed, animData.wrapMode); } } if (defaultAnimationData.clip != null) { SetOverrideController(defaultAnimationData, defaultAnimationData, currentMirror); currentAnimationData = defaultAnimationData; if (playOnStart) { AnimatorPlay("State2", 0, 0); if (overrideRootMotion) animator.applyRootMotion = currentAnimationData.applyRootMotion; SetSpeed(currentAnimationData.speed); } } } void OnEnable() { if (currentAnimationData != null) { Play(currentAnimationData, currentBlendingTime, currentAnimationData.NormalizedTime, currentMirror); } } void OnDestroy() { ClearClips(); if (animator != null) { PutController(animator.runtimeAnimatorController as AnimatorOverrideController); animator.runtimeAnimatorController = null; PutController(cachedController); cachedController = null; } } //void FixedUpdate(){ //WrapMode emulator /* if (currentAnimationData == null || currentAnimationData.clip == null) return; var normalizedTime = GetNormalizedTime(); Debug.Log("normalizedTime" + normalizedTime + "Mathf.FloorToInt(normalizedTime)" + Mathf.FloorToInt(normalizedTime)); var timesPlayed = Mathf.FloorToInt(normalizedTime); if (currentAnimationData.timesPlayed > timesPlayed) { currentAnimationData.timesPlayed = timesPlayed; } else if (currentAnimationData.timesPlayed < timesPlayed) { if (currentAnimationData.clip.wrapMode == WrapMode.Loop || currentAnimationData.clip.wrapMode == WrapMode.PingPong) { if (MecanimControl.OnAnimationLoop != null) MecanimControl.OnAnimationLoop(currentAnimationData); currentAnimationData.timesPlayed++; var position = normalizedTime - timesPlayed; if (currentAnimationData.clip.wrapMode == WrapMode.Loop) { //SetCurrentClipPosition(position); currentAnimationData.secondsPlayed = normalizedTime * currentAnimationData.length; } if (currentAnimationData.clip.wrapMode == WrapMode.PingPong) { SetSpeed(currentAnimationData.clipName, -currentAnimationData.speed); SetCurrentClipPosition(position); } } else if (currentAnimationData.timesPlayed == 0) { if (MecanimControl.OnAnimationEnd != null) MecanimControl.OnAnimationEnd(currentAnimationData); currentAnimationData.timesPlayed = 1; if (currentAnimationData.clip.wrapMode == WrapMode.Once && alwaysPlay) { Play(defaultAnimation, currentMirror); } else if (!alwaysPlay) { animator.speed = 0; } } } else { //currentAnimationData.secondsPlayed += Time.deltaTime * animator.speed * Time.timeScale; currentAnimationData.secondsPlayed += (Time.fixedDeltaTime * animator.speed); //if (currentAnimationData.secondsPlayed > currentAnimationData.length) // currentAnimationData.secondsPlayed = currentAnimationData.length; } */ //} //void OnGUI() //{ // //Toggle debug mode to see the live data in action // if (debugMode) // { // GUI.Box(new Rect(Screen.width - 340, 40, 340, 400), "Animation Data"); // GUI.BeginGroup(new Rect(Screen.width - 330, 60, 400, 400)); // { // AnimatorClipInfo[] animationInfoArray = animator.GetCurrentAnimatorClipInfo(0); // foreach (AnimatorClipInfo animationInfo in animationInfoArray) // { // AnimatorStateInfo animatorStateInfo = animator.GetCurrentAnimatorStateInfo(0); // GUILayout.Label(animationInfo.clip.name); // GUILayout.Label("-Wrap Mode: " + animationInfo.clip.wrapMode); // GUILayout.Label("-Is Playing: " + IsPlaying(animationInfo.clip.name)); // GUILayout.Label("-Blend Weight: " + animationInfo.weight); // GUILayout.Label("-Normalized Time: " + animatorStateInfo.normalizedTime); // GUILayout.Label("-Length: " + animationInfo.clip.length); // GUILayout.Label("----"); // } // GUILayout.Label("--Current Animation Data--"); // GUILayout.Label("-Current Clip Name: " + currentAnimationData.clipName); // GUILayout.Label("-Current Speed: " + GetSpeed().ToString()); // GUILayout.Label("-Times Played: " + currentAnimationData.timesPlayed); // GUILayout.Label("-Seconds Played: " + currentAnimationData.secondsPlayed); // GUILayout.Label("-Emul. Normalized: " + (currentAnimationData.secondsPlayed / currentAnimationData.length)); // GUILayout.Label("-Lengh: " + currentAnimationData.length); // GUILayout.Label("-GetNormalizedTime(): " + GetNormalizedTime()); // } // GUI.EndGroup(); // } //} public void ClearClips() { foreach (var name in animations.Keys) { Game.AnimationClipPool.RemoveClipRef(name); } animations.Clear(); defaultAnimationData.Reset(); } public void Copy(MecanimControl original) { ClearClips(); foreach (var pair in original.animations) { var data = pair.Value; AddClip(data.clip, data.clipName, data.speed, data.wrapMode); } Init(); } public void AnimatorPlay(string statename, int layer, float normalizedTime) { //Util.LogColor("green",Time.time+ modelName + "AnimatorPlay:" + statename+ "normalizedTime:"+ normalizedTime); animator.Play(statename, layer, normalizedTime); } // MECANIM CONTROL METHODS public void RemoveClip(string name) { if (animations.ContainsKey(name)) { animations.Remove(name); Game.AnimationClipPool.RemoveClipRef(name); } if (name == defaultAnimationData.clipName) { defaultAnimationData.Reset(); } } public void SetDefaultClip(AnimationClip clip, string name, float speed, WrapMode wrapMode) { defaultAnimationData.clip = clip;// (AnimationClip) Instantiate(clip); defaultAnimationData.clip.wrapMode = wrapMode; defaultAnimationData.clipName = name; defaultAnimationData.speed = speed; defaultAnimationData.transitionDuration = -1; defaultAnimationData.wrapMode = wrapMode; } public void AddClip(AnimationClip clip, string newName) { AddClip(clip, newName, 1, defaultWrapMode); } public void AddClip(AnimationClip clip, string newName, float speed, WrapMode wrapMode) { ////Util.LogColor("green", "AddClip:" + newName+ wrapMode); if (GetAnimationData(newName) != null) { Debug.LogError("An animation with the name '" + newName + "' already exists."); return; } AnimationData animData = new AnimationData(); animData.clip = clip; //Instantiate(clip); if (wrapMode == WrapMode.Default) wrapMode = defaultWrapMode; animData.clip.wrapMode = wrapMode; animData.clip.name = newName; animData.clipName = newName; animData.speed = speed; animData.length = clip.length; animData.wrapMode = wrapMode; animations[newName] = animData; Game.AnimationClipPool.AddClipRef(newName); } public void SetOverrideController(AnimationData currentAnimationData, AnimationData targetAnimationData, bool mirror) { //Util.LogColor("cyan", string.Format("SetOverrideController currentAnimationData:{0} targetAnimationData:{1}", currentAnimationData.clipName, targetAnimationData.clipName)); if (targetAnimationData == null || targetAnimationData.clip == null || currentAnimationData == null || currentAnimationData.clip == null) { return; } this.currentMirror = mirror; AnimatorOverrideController overrideController = cachedController; overrideController["State1"] = currentAnimationData.clip; overrideController["State2"] = targetAnimationData.clip; if (defaultAnimationData != null && defaultAnimationData.clip != null) { overrideController["State3"] = defaultAnimationData.clip; } cachedController = animator.runtimeAnimatorController as AnimatorOverrideController; animator.runtimeAnimatorController = overrideController; animator.Update(0); } private void _playAnimation(AnimationData targetAnimationData, float blendingTime, float normalizedTime, bool mirror) { //The overrite machine. Creates an overrideController, replace its core animations and restate it back in ////("cyan", "_playAnimation:"+targetAnimationData.clipName); if (targetAnimationData == null || targetAnimationData.clip == null) return; if (currentAnimationData == null) { Debug.LogError("_playAnimation :currentAnimationData == null!"); return; } if (currentAnimationData.clipName != targetAnimationData.clipName) { SetOverrideController(currentAnimationData, targetAnimationData, mirror); } float newAnimatorSpeed = Mathf.Abs(targetAnimationData.speed) * speed; float currentNormalizedTime = GetNormalizedTime(); if (blendingTime == -1) blendingTime = currentAnimationData.transitionDuration; if (blendingTime == -1) blendingTime = defaultTransitionDuration; currentBlendingTime = blendingTime; if (blendingTime <= 0 || currentAnimationData.clip == targetAnimationData.clip) { //Util.LogColor("red", modelName + "play:" + targetAnimationData.clipName); //animator.Rebind(); AnimatorPlay("State2", 0, normalizedTime); } else { //Util.LogColor("cyan", modelName + "crossfade:" + targetAnimationData.clipName+ "blendingTime:"+ blendingTime); currentAnimationData.stateName = "State1"; SetCurrentClipPosition(currentNormalizedTime); animator.Update(0); animator.CrossFade("State2", blendingTime / newAnimatorSpeed); } targetAnimationData.timesPlayed = 0; targetAnimationData.secondsPlayed = (normalizedTime * targetAnimationData.clip.length) / newAnimatorSpeed; targetAnimationData.length = targetAnimationData.clip.length; if (overrideRootMotion) animator.applyRootMotion = targetAnimationData.applyRootMotion; SetSpeed(targetAnimationData.speed); currentAnimationData = targetAnimationData; currentAnimationData.stateName = "State2"; //currentAnimationData.stateHash = state2Hash; if (MecanimControl.OnAnimationBegin != null) MecanimControl.OnAnimationBegin(currentAnimationData); } #region Operate Current Clip public string GetCurrentClipName() { return currentAnimationData.clipName; } public AnimationData GetCurrentAnimationData() { return currentAnimationData; } public int GetCurrentClipPlayCount() { return currentAnimationData.timesPlayed; } public float GetCurrentClipTime() { return currentAnimationData.secondsPlayed; } public float GetCurrentClipLength() { return currentAnimationData.length; } public void SetCurrentClipPosition(float normalizedTime) { SetCurrentClipPosition(normalizedTime, false); } public void SetCurrentClipPosition(float normalizedTime, bool pause) { AnimatorPlay(currentAnimationData.stateName, 0, normalizedTime); currentAnimationData.secondsPlayed = normalizedTime * currentAnimationData.length; if (pause) Pause(); } public float GetCurrentClipPosition() { if (currentAnimationData == null || currentAnimationData.length == 0) { return 0f; } return currentAnimationData.secondsPlayed / currentAnimationData.length; } public float GetNormalizedTime() { AnimatorStateInfo animatorStateInfo = animator.GetCurrentAnimatorStateInfo(0); return animatorStateInfo.normalizedTime; } public void Play() { animator.speed = Mathf.Abs(currentAnimationData.speed) * globalSpeed; } public void Stop() { Play(defaultAnimationData.clipName, defaultTransitionDuration, 0, currentMirror); } public void Pause() { animator.speed = 0; } public void SetSpeed(float speed) { animator.speed = Mathf.Abs(speed) * globalSpeed; } public float GetSpeed() { return animator.speed; } public void RestoreSpeed() { //SetCurrentClipPosition(GetCurrentClipPosition()); SetSpeed(currentAnimationData.speed); } public void Rewind() { SetSpeed(-currentAnimationData.speed); } public void SetWrapMode(WrapMode wrapMode) { defaultWrapMode = wrapMode; } public bool GetMirror() { return currentMirror; } public void SetMirror(bool toggle) { SetMirror(toggle, 0, false); } public void SetMirror(bool toggle, float blendingTime) { SetMirror(toggle, blendingTime, false); } public void SetMirror(bool toggle, float blendingTime, bool forceMirror) { if (currentMirror == toggle && !forceMirror) return; if (blendingTime == 0) blendingTime = defaultTransitionDuration; Play(currentAnimationData, blendingTime, GetCurrentClipPosition(), toggle); } #endregion #region Operate By AnimationData public AnimationData GetAnimationData(string clipName) { if (animations.ContainsKey(clipName)) { return animations[clipName]; } if (clipName == defaultAnimationData.clipName) return defaultAnimationData; return null; } public void CrossFade(AnimationData animationData, float blendingTime, float normalizedTime, bool mirror) { Play(animationData, blendingTime, normalizedTime, mirror); } public void Play(AnimationData animationData, bool mirror) { Play(animationData, animationData.transitionDuration, 0, mirror); } public void Play(AnimationData animationData) { Play(animationData, animationData.transitionDuration, 0, currentMirror); } public void Play(AnimationData animationData, float blendingTime, float normalizedTime, bool mirror) { _playAnimation(animationData, blendingTime, normalizedTime, mirror); } public bool IsPlaying(AnimationData animData) { return IsPlaying(animData, 0); } public bool IsPlaying(AnimationData animData, float weight) { if (animData == null) return false; if (currentAnimationData == null) return false; //if (currentAnimationData == animData && animData.wrapMode == WrapMode.Once && animData.timesPlayed > 0) return false; //if (currentAnimationData == animData) return true; //AnimatorClipInfo[] animationInfoArray = animator.GetCurrentAnimatorClipInfo(0); //for (var i = 0;i<animationInfoArray.Length;i++) //{ // AnimatorClipInfo animationInfo = animationInfoArray[i]; // if (animData.clip == animationInfo.clip && animationInfo.weight >= weight) return true; //} if (currentAnimationData == animData) { return animData.wrapMode == WrapMode.Loop || GetNormalizedTime() < 1; } return false; } public bool IsPlayingSkill(AnimationData animData, float loop) { return IsPlaying(animData) && GetNormalizedTime() < loop; } public void SetWrapMode(AnimationData animationData, WrapMode wrapMode) { animationData.wrapMode = wrapMode; animationData.clip.wrapMode = wrapMode; } #endregion #region Operate By String public void CrossFade(string clipName, float blendingTime) { Play(clipName, blendingTime, 0, currentMirror); } public void CrossFade(string clipName, float blendingTime, float normalizedTime, bool mirror) { Play(clipName, blendingTime, normalizedTime, mirror); } public void Play(string clipName, bool mirror) { Play(clipName, 0, 0, mirror); } public void Play(string clipName) { Play(clipName, 0, 0, currentMirror); } public void Play(string clipName, float blendingTime, float normalizedTime, bool mirror) { var animData = GetAnimationData(clipName); if (animData == null) { Debug.LogError(string.Format("model【{0}】 does not have animation state {1},please check!", modelName, clipName)); return; } else if (animData.clip == null) { Debug.LogError(string.Format("model【{0}】 animation clip【{1}】 is null ,please check!", modelName, clipName)); return; } Play(animData, blendingTime, normalizedTime, mirror); } public bool IsPlaying(string clipName) { return IsPlaying(GetAnimationData(clipName)); } public bool IsPlaying(string clipName, float weight) { return IsPlaying(GetAnimationData(clipName), weight); } public bool IsPlayingSkill(string clipName, float loop) { return IsPlayingSkill(GetAnimationData(clipName), loop); } public void SetSpeed(string clipName, float speed) { AnimationData animData = GetAnimationData(clipName); // if (animData.speed == speed && animator.speed == Mathf.Abs(speed)) return; animData.speed = speed; if (IsPlaying(clipName)) { SetSpeed(speed); } } public float GetSpeed(string clipName) { AnimationData animData = GetAnimationData(clipName); return animData.speed; } public void SetWrapMode(string clipName, WrapMode wrapMode) { AnimationData animData = GetAnimationData(clipName); animData.wrapMode = wrapMode; animData.clip.wrapMode = wrapMode; } #endregion /***************************************************************************************** *** 下面为扩展 *****************************************************************************************/ #region Operate By HashCode //public bool IsPlaying(int hashclip) //{ // return IsPlaying(LuaHelper.hash_name_map[hashclip]); //} public void CrossFade(int hashclip, float blendingTime) { CrossFade(LuaHelper.hash_name_map[hashclip], blendingTime, 0, currentMirror); } public void CrossFade(int hashclip, float blendingTime, float normalizedTime, bool mirror) { CrossFade(LuaHelper.hash_name_map[hashclip], blendingTime, normalizedTime, mirror); } public void Play(int hashclip, float blendingTime, float normalizedTime, bool mirror) { Play(LuaHelper.hash_name_map[hashclip], blendingTime, normalizedTime, mirror); } public void Play(int hashclip, bool mirror) { Play(LuaHelper.hash_name_map[hashclip], 0, 0, mirror); } public void Play(int hashclip) { Play(LuaHelper.hash_name_map[hashclip], 0, 0, currentMirror); } public bool IsPlaying(int hashclip) { return IsPlaying(LuaHelper.hash_name_map[hashclip]); } public bool IsPlaying(int hashclip, float weight) { return IsPlaying(LuaHelper.hash_name_map[hashclip], weight); } public bool IsPlayingSkill(int hashclip, float loop) { return IsPlayingSkill(LuaHelper.hash_name_map[hashclip], loop); } public void SetSpeed(int hashclip, float speed) { SetSpeed(LuaHelper.hash_name_map[hashclip], speed); } public float GetSpeed(int hashclip) { return GetSpeed(LuaHelper.hash_name_map[hashclip]); } public void SetWrapMode(int hashclip, WrapMode wrapMode) { SetWrapMode(LuaHelper.hash_name_map[hashclip], wrapMode); } #endregion #region Extend For Editor public float GetAnimationLength(string name) { var animData = GetAnimationData(name); if (animData != null) { return animData.length; } return 0; } public void Bake(string targetAnimation) { AnimationData targetAnimationData = GetAnimationData(targetAnimation); //The overrite machine. Creates an overrideController, replace its core animations and restate it back in if (targetAnimationData == null || targetAnimationData.clip == null) return; currentAnimationData = targetAnimationData; AnimatorOverrideController overrideController = new AnimatorOverrideController(); float newAnimatorSpeed = Mathf.Abs(targetAnimationData.speed); overrideController.runtimeAnimatorController = controller1; overrideController["State1"] = targetAnimationData.clip; animator.runtimeAnimatorController = overrideController; animator.Bake("State1"); } public void Sample(float time) { animator.Sample(time); } #endregion } <file_sep>using UnityEngine; using UnityEditor; using UnityEditor.Animations; //using UnityEditorInternal; using System.Collections.Generic; using Flux; using FluxEditor; namespace FluxEditor { [CustomEditor(typeof(FMove))] public class FMoveEventInspector : FEventInspector { private SerializedProperty _moveType; private SerializedProperty _relateType; private int _selectedMoveIndex; private int _selectedRelateIndex; private GUIContent _moveTypeUI = new GUIContent("位移类型"); //private GUIContent _relateTypeUI = new GUIContent("相对类型"); private GUIContent[] _moveTypes = new GUIContent[] { new GUIContent("向目标移动"), new GUIContent("按当前方向移动"), }; //private GUIContent[] _relateTypes = new GUIContent[] //{ // new GUIContent("相对于自己"), // new GUIContent("相对于目标"), //}; protected override void OnEnable() { base.OnEnable(); _moveType = serializedObject.FindProperty("_moveType"); //_relateType = serializedObject.FindProperty("_relateType"); } public override void OnInspectorGUI() { base.OnInspectorGUI(); EditorGUI.BeginChangeCheck(); int index = EditorGUILayout.Popup(_moveTypeUI, _selectedMoveIndex, _moveTypes); if (EditorGUI.EndChangeCheck()) { _moveType.enumValueIndex = index; _selectedMoveIndex = index; } //EditorGUI.BeginChangeCheck(); //index = EditorGUILayout.Popup(_relateTypeUI, _selectedRelateIndex, _relateTypes); //if (EditorGUI.EndChangeCheck()) //{ // _relateType.enumValueIndex = index; // _selectedRelateIndex = index; //} } } } <file_sep>#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using System; namespace XLua { public partial class DelegateBridge : DelegateBridgeBase { public void __Gen_Delegate_Imp0(System.IAsyncResult p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp1() { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); PCall(L, 0, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp2(string p0, bool p1, string p2) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); LuaAPI.lua_pushstring(L, p0); LuaAPI.lua_pushboolean(L, p1); LuaAPI.lua_pushstring(L, p2); PCall(L, 3, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp3(string p0, string p1, UnityEngine.LogType p2) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; LuaAPI.lua_pushstring(L, p0); LuaAPI.lua_pushstring(L, p1); translator.Push(L, p2); PCall(L, 3, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp4(float[] p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.Push(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp5(int p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); LuaAPI.xlua_pushinteger(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp6(UnityEngine.AsyncOperation p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.Push(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp7(UnityEngine.RectTransform p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.Push(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp8(UnityEngine.Object p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.Push(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public InvokeLua.ICalc __Gen_Delegate_Imp9(int p0, string[] p1) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; LuaAPI.xlua_pushinteger(L, p0); if (p1 != null) { for (int __gen_i = 0; __gen_i < p1.Length; ++__gen_i) LuaAPI.lua_pushstring(L, p1[__gen_i]); }; PCall(L, 1 + (p1 == null ? 0 : p1.Length), 1, errFunc); InvokeLua.ICalc __gen_ret = (InvokeLua.ICalc)translator.GetObject(L, errFunc + 1, typeof(InvokeLua.ICalc)); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public int __Gen_Delegate_Imp10(int p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); LuaAPI.xlua_pushinteger(L, p0); PCall(L, 1, 1, errFunc); int __gen_ret = LuaAPI.xlua_tointeger(L, errFunc + 1); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public UnityEngine.Vector3 __Gen_Delegate_Imp11(UnityEngine.Vector3 p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushUnityEngineVector3(L, p0); PCall(L, 1, 1, errFunc); UnityEngine.Vector3 __gen_ret;translator.Get(L, errFunc + 1, out __gen_ret); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public XLuaTest.MyStruct __Gen_Delegate_Imp12(XLuaTest.MyStruct p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushXLuaTestMyStruct(L, p0); PCall(L, 1, 1, errFunc); XLuaTest.MyStruct __gen_ret;translator.Get(L, errFunc + 1, out __gen_ret); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public XLuaTest.MyEnum __Gen_Delegate_Imp13(XLuaTest.MyEnum p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushXLuaTestMyEnum(L, p0); PCall(L, 1, 1, errFunc); XLuaTest.MyEnum __gen_ret;translator.Get(L, errFunc + 1, out __gen_ret); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public decimal __Gen_Delegate_Imp14(decimal p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushDecimal(L, p0); PCall(L, 1, 1, errFunc); decimal __gen_ret;translator.Get(L, errFunc + 1, out __gen_ret); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp15(System.Array p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.Push(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp16(bool p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); LuaAPI.lua_pushboolean(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp17(float p0, float p1) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); LuaAPI.lua_pushnumber(L, p0); LuaAPI.lua_pushnumber(L, p1); PCall(L, 2, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp18(float p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); LuaAPI.lua_pushnumber(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp19(object p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); PCall(L, 1, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public int __Gen_Delegate_Imp20(object p0, int p1, int p2) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); LuaAPI.xlua_pushinteger(L, p1); LuaAPI.xlua_pushinteger(L, p2); PCall(L, 3, 1, errFunc); int __gen_ret = LuaAPI.xlua_tointeger(L, errFunc + 1); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public UnityEngine.Vector3 __Gen_Delegate_Imp21(object p0, UnityEngine.Vector3 p1, UnityEngine.Vector3 p2) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); translator.PushUnityEngineVector3(L, p1); translator.PushUnityEngineVector3(L, p2); PCall(L, 3, 1, errFunc); UnityEngine.Vector3 __gen_ret;translator.Get(L, errFunc + 1, out __gen_ret); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public int __Gen_Delegate_Imp22(object p0, int p1, out double p2, ref string p3) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); LuaAPI.xlua_pushinteger(L, p1); LuaAPI.lua_pushstring(L, p3); PCall(L, 3, 3, errFunc); p2 = LuaAPI.lua_tonumber(L, errFunc + 2); p3 = LuaAPI.lua_tostring(L, errFunc + 3); int __gen_ret = LuaAPI.xlua_tointeger(L, errFunc + 1); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public int __Gen_Delegate_Imp23(object p0, int p1, out double p2, ref string p3, object p4) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); LuaAPI.xlua_pushinteger(L, p1); LuaAPI.lua_pushstring(L, p3); translator.PushAny(L, p4); PCall(L, 4, 3, errFunc); p2 = LuaAPI.lua_tonumber(L, errFunc + 2); p3 = LuaAPI.lua_tostring(L, errFunc + 3); int __gen_ret = LuaAPI.xlua_tointeger(L, errFunc + 1); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp24(object p0, int p1) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); LuaAPI.xlua_pushinteger(L, p1); PCall(L, 2, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public string __Gen_Delegate_Imp25(object p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); PCall(L, 1, 1, errFunc); string __gen_ret = LuaAPI.lua_tostring(L, errFunc + 1); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public UnityEngine.GameObject __Gen_Delegate_Imp26(StructTest p0, int p1, object p2) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.Push(L, p0); LuaAPI.xlua_pushinteger(L, p1); translator.PushAny(L, p2); PCall(L, 3, 1, errFunc); UnityEngine.GameObject __gen_ret = (UnityEngine.GameObject)translator.GetObject(L, errFunc + 1, typeof(UnityEngine.GameObject)); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public string __Gen_Delegate_Imp27(StructTest p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.Push(L, p0); PCall(L, 1, 1, errFunc); string __gen_ret = LuaAPI.lua_tostring(L, errFunc + 1); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp28(StructTest p0, object p1) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.Push(L, p0); translator.PushAny(L, p1); PCall(L, 2, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public int __Gen_Delegate_Imp29(object p0) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); PCall(L, 1, 1, errFunc); int __gen_ret = LuaAPI.xlua_tointeger(L, errFunc + 1); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp30(object p0, object p1) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); translator.PushAny(L, p1); PCall(L, 2, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public int __Gen_Delegate_Imp31(object p0, object p1) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); translator.PushAny(L, p1); PCall(L, 2, 1, errFunc); int __gen_ret = LuaAPI.xlua_tointeger(L, errFunc + 1); LuaAPI.lua_settop(L, errFunc - 1); return __gen_ret; #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp32(object p0, object p1, int p2) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); translator.PushAny(L, p1); LuaAPI.xlua_pushinteger(L, p2); PCall(L, 3, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp33(int p0, int p1) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); LuaAPI.xlua_pushinteger(L, p0); LuaAPI.xlua_pushinteger(L, p1); PCall(L, 2, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } public void __Gen_Delegate_Imp34(object p0, int p1, int p2) { #if THREAD_SAFE || HOTFIX_ENABLE lock (luaEnv.luaEnvLock) { #endif RealStatePtr L = luaEnv.rawL; int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); ObjectTranslator translator = luaEnv.translator; translator.PushAny(L, p0); LuaAPI.xlua_pushinteger(L, p1); LuaAPI.xlua_pushinteger(L, p2); PCall(L, 3, 0, errFunc); LuaAPI.lua_settop(L, errFunc - 1); #if THREAD_SAFE || HOTFIX_ENABLE } #endif } static DelegateBridge() { Gen_Flag = true; } public override Delegate GetDelegateByType(Type type) { if (type == typeof(System.AsyncCallback)) { return new System.AsyncCallback(__Gen_Delegate_Imp0); } if (type == typeof(UnityEngine.Application.LowMemoryCallback)) { return new UnityEngine.Application.LowMemoryCallback(__Gen_Delegate_Imp1); } if (type == typeof(UnityEngine.Events.UnityAction)) { return new UnityEngine.Events.UnityAction(__Gen_Delegate_Imp1); } if (type == typeof(System.Action)) { return new System.Action(__Gen_Delegate_Imp1); } if (type == typeof(Game.LateUpdateFunc)) { return new Game.LateUpdateFunc(__Gen_Delegate_Imp1); } if (type == typeof(UnityEngine.Application.AdvertisingIdentifierCallback)) { return new UnityEngine.Application.AdvertisingIdentifierCallback(__Gen_Delegate_Imp2); } if (type == typeof(UnityEngine.Application.LogCallback)) { return new UnityEngine.Application.LogCallback(__Gen_Delegate_Imp3); } if (type == typeof(UnityEngine.AudioClip.PCMReaderCallback)) { return new UnityEngine.AudioClip.PCMReaderCallback(__Gen_Delegate_Imp4); } if (type == typeof(UnityEngine.AudioClip.PCMSetPositionCallback)) { return new UnityEngine.AudioClip.PCMSetPositionCallback(__Gen_Delegate_Imp5); } if (type == typeof(System.Action<UnityEngine.AsyncOperation>)) { return new System.Action<UnityEngine.AsyncOperation>(__Gen_Delegate_Imp6); } if (type == typeof(UnityEngine.RectTransform.ReapplyDrivenProperties)) { return new UnityEngine.RectTransform.ReapplyDrivenProperties(__Gen_Delegate_Imp7); } if (type == typeof(System.Action<UnityEngine.Object>)) { return new System.Action<UnityEngine.Object>(__Gen_Delegate_Imp8); } if (type == typeof(InvokeLua.CalcNew)) { return new InvokeLua.CalcNew(__Gen_Delegate_Imp9); } if (type == typeof(XLuaTest.IntParam)) { return new XLuaTest.IntParam(__Gen_Delegate_Imp10); } if (type == typeof(XLuaTest.Vector3Param)) { return new XLuaTest.Vector3Param(__Gen_Delegate_Imp11); } if (type == typeof(XLuaTest.CustomValueTypeParam)) { return new XLuaTest.CustomValueTypeParam(__Gen_Delegate_Imp12); } if (type == typeof(XLuaTest.EnumParam)) { return new XLuaTest.EnumParam(__Gen_Delegate_Imp13); } if (type == typeof(XLuaTest.DecimalParam)) { return new XLuaTest.DecimalParam(__Gen_Delegate_Imp14); } if (type == typeof(XLuaTest.ArrayAccess)) { return new XLuaTest.ArrayAccess(__Gen_Delegate_Imp15); } if (type == typeof(System.Action<bool>)) { return new System.Action<bool>(__Gen_Delegate_Imp16); } if (type == typeof(Game.UpdateFunc)) { return new Game.UpdateFunc(__Gen_Delegate_Imp17); } if (type == typeof(Game.FixedUpdateFunc)) { return new Game.FixedUpdateFunc(__Gen_Delegate_Imp18); } return null; } } }<file_sep>namespace AssetManager { using System; using UnityEngine; using Sirenix.Utilities; using Sirenix.OdinInspector; using UnityEditor; using System.IO; [GlobalConfig("Editor/AssetManager/Config", UseAsset = true)] public class CheckerConfig : GlobalConfig<CheckerConfig> { [ShowInInspector] public string AssetMoveToPath { get { return Application.dataPath + "/../../AssetsBackup"; } } public BitmapCheckerInfo BitmapChecker; public RoleMeshCheckerInfo RoleMeshChecker; public FileNameCheckerInfo FileNameChecker; public TextureStretchCheckerInfo TextureStretchChecker; [Button("Clear Invalid Path", ButtonSizes.Large)] public void ClearInvalidPath() { } [Button("Clear All", ButtonSizes.Large)] public void ClearAll() { BitmapChecker.ClearAsset(); RoleMeshChecker.ClearAsset(); } } [Serializable] public class CheckerInfo : AssetOption { public override string Name { get { return _name; } } public CheckerInfo(string name) { _name = name; } public virtual void CheckAsset() { if (!Directory.Exists(Path)) EditorUtility.DisplayDialog("错误", "目录路径不存在", "确定"); } } }<file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class Timeline : XmlObject { /// <summary> /// 起始帧 /// <summary> public int Start; /// <summary> /// 结束帧 /// <summary> public int End; public override void Write(TextWriter _1) { Write(_1, "Start", this.Start); Write(_1, "End", this.End); } public override void Read(XmlNode _1) { foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Start": this.Start = ReadInt(_2); break; case "End": this.End = ReadInt(_2); break; } } } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public enum LockObjectType { /// <summary> /// 不需要目标 /// <summary> None = 0, /// <summary> /// 敌方目标 /// <summary> Enemy = 1, /// <summary> /// 己方目标 /// <summary> Teammate = 2, /// <summary> /// 自己 /// <summary> Self = 3, /// <summary> /// 中立方 /// <summary> Other = 4, } } <file_sep>local type = type local ipairs = ipairs local tostring = tostring local concat = table.concat local format = string.format local traceback = debug.traceback local collectgarbage = collectgarbage local dump = table.dump local Debug = CS.UnityEngine.Debug local GameObject = GameObject print = function(...) if not Local.LogManager then return end local args = { ... } for k, v in ipairs(args) do args[k] = tostring(v) end if Local.LogTraceback then Debug.Log(concat(args, '\t') .. '\n' .. traceback()) else Debug.Log(concat(args, '\t')) end end local color = "yellow" local dump_level = 3 --输出黄色日志-无格式 function printcolor(...) if not Local.LogManager then return end local args = { ... } for k, v in ipairs(args) do args[k] = tostring(v) end local log = format("<color=%s>%s</color>\t\n", color, concat(args, '\t')) if Local.LogTraceback then Debug.Log(log .. traceback()); else Debug.Log(log); end end function printt(t, des) if not Local.LogManager then return end des = des or '' if type(t) == "table" then print(format("<color=orange>%s</color>\n%s", des, dump(t, dump_level))) else print(format("%s\n%s", des, tostring(t))) end end --unity对象判空-- function IsNull(unity_object) if unity_object == nil then return true end if type(unity_object) == "userdata" and unity_object.IsNull ~= nil then return unity_object:IsNull() end return false end --输出日志-- function Log(...) if not Local.LogManager then return end local str = format(...) if Local.LogTraceback then Debug.Log(str .. "\r\n" .. traceback()); else Debug.Log(str); end end --错误日志-- function LogError(...) if not Local.LogManager then return end local str = format(...) if Local.LogTraceback then Debug.LogError(str .. "\r\n" .. traceback()); else Debug.LogError(str) end end --警告日志-- function LogWarning(...) if not Local.LogManager then return end local str = format(...) if Local.LogTraceback then Debug.LogWarning(str .. "\r\n" .. traceback()); else Debug.LogWarning(str) end end ---@param a 判定条件 ---@param b true返回b ---@param c false返回c function ConditionOp(a, b, c) if a then return b else return c end end function LuaGC() local c1 = collectgarbage("count") collectgarbage("collect") local c2 = collectgarbage("count") Log("=== gc before:%.1fkb, after %.1fkb", c1, c2) end function DontDestroyOnLoad(obj) if not IsNull(obj) then if IsNull(obj.transform.parent) then GameObject.DontDestroyOnLoad(obj) end end return obj end --Unity对象操作-- function FindObj(str) return GameObject.Find(str); end function Destroy(obj) GameObject.Destroy(obj); end function NewObject(prefab) return GameObject.Instantiate(prefab); end<file_sep>using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; public class EUtil { public static string FilePath2UnityPath(string path) { return path.Replace(Application.dataPath, "Assets"); } public static string UnityPath2FilePath(string path) { if (path.IndexOf("Assets") != 0) { Debug.LogError("非UnityPath - " + path); return path; } return Application.dataPath + path.Substring(0, 6); } /// <summary> /// \ 转换 / /// </summary> public static string StandardlizePath(string path) { return path.Replace(@"\", @"/"); } /// <summary> /// 子资源不可重名! key-文件名 value-路径 /// </summary> public static void GetAssetsInSubFolderRecursively(string srcFolder, string searchPattern, ref Dictionary<string, string> fileName2Path, List<string> sb = null) { string searchFolder = StandardlizePath(srcFolder); if (!Directory.Exists(searchFolder)) return; string[] files = Directory.GetFiles(searchFolder, searchPattern); foreach (string oneFile in files) { string srcFile = StandardlizePath(oneFile); if (!File.Exists(srcFile)) continue; string srcFileName = Path.GetFileNameWithoutExtension(srcFile); if (!fileName2Path.ContainsKey(srcFileName)) { fileName2Path.Add(srcFileName, srcFile); } else { string error = "资源名重复 filename:" + srcFileName; UnityEngine.Debug.LogError(error); if (sb != null && !sb.Contains(error)) { sb.Add(error); } } } string[] dirs = Directory.GetDirectories(searchFolder); foreach (string oneDir in dirs) { GetAssetsInSubFolderRecursively(oneDir, searchPattern, ref fileName2Path, sb); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using XLua; namespace Game { public static class LuaHelper { public static LuaTable name_hash_map; public static Dictionary<int, string> hash_name_map = new Dictionary<int, string>(); public static void Init() { name_hash_map = LuaManager.Instance.LuaEnv.NewTable(); } public static void StringToHash(string name) { if (name != null) { var hashcode = Animator.StringToHash(name); name_hash_map[name] = hashcode; hash_name_map[hashcode] = name; } } } } <file_sep>using System; using System.Text; using System.IO; using System.Reflection; namespace Cfg { public class DataStream { public DataStream(string path, Encoding encoding) { _rows = File.ReadAllLines(path, encoding); _rIndex = _cIndex = 0; if (_rows.Length > 0) _columns = _rows[_rIndex].Split("▃".ToCharArray()); } public int Count { get { return _rows.Length; } } public int GetInt() { int result; int.TryParse(Next(), out result); return result; } public long GetLong() { long result; long.TryParse(Next(), out result); return result; } public float GetFloat() { float result; float.TryParse(Next(), out result); return result; } public bool GetBool() { string v = Next(); if (string.IsNullOrEmpty(v)) return false; return !v.Equals("0"); } public string GetString() { return Next(); } /// <summary> /// 支持多态,直接反射类型 /// <summary> public CfgObject GetObject(string fullName) { Type type = Type.GetType(fullName); if (type == null) { UnityEngine.Debug.LogErrorFormat("DataStream 解析{0}类型失败!", fullName); } return (CfgObject)Activator.CreateInstance(type, new object[] { this }); } private int _rIndex; private int _cIndex; private string[] _rows; private string[] _columns; private void NextRow() { if (_rIndex >= _rows.Length) return; _rIndex++; _cIndex = 0; _columns = _rows[_rIndex].Split("▃".ToCharArray()); } private string Next() { if (_cIndex >= _columns.Length) NextRow(); return _columns[_cIndex++]; } } } <file_sep>namespace AssetManager { using System; using System.IO; using UnityEngine; [Serializable] public class AssetOption { [SerializeField, HideInInspector] protected string _path; [SerializeField, HideInInspector] protected string _name; public virtual string Path { get { return _path; } set { _path = value; } } public virtual string Name { get { string n = System.IO.Path.GetFileName(Path); return string.IsNullOrEmpty(n) ? "未命名" : n; } } public bool IncludeSub { get; set; } public virtual void ClearAsset() { } public virtual void RefreshAsset() { } public virtual void ReimportAsset() { } public static string GetUnityPath(string path) { return path.Replace("\\", "/").Replace(Application.dataPath, "Assets"); } public static string GetAbsPath(string path) { return path.Replace("\\", "/").Replace("Assets", Application.dataPath); } public static void CreateFolder(string path) { string folder = System.IO.Path.GetDirectoryName(path); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; using System.IO; using System; using Game.Platform; namespace Game { public class GameManager : IManager { public static GameManager Instance { get { if (_instance == null) _instance = new GameManager(); return _instance; } } static GameManager _instance; protected GameManager() { } enum LaunchState { InitSDK, //SDK初始化完成 DowmloadZip, //下载脚本和配置文件 UnZipFile, //并解压脚本和配置文件 CheckAppVersion, //检查App版本 DowmloadApp, //安装App CheckResVersion, //检查资源版本 DowmloadRes, //热更资源 GetServerList, //更新服务器地址列表 LoadResource, //加载资源,加载完毕进入登入界面 //--错误提示 MemeryNotEnough, //检查设备内存大小 OffLine, //网络断线 ServerListFailed,//获取服务器列表失败 } GameObject _dlgRes; Slider _progress; Text _status; Dictionary<string, string> _launcher = new Dictionary<string, string>(); public void Init() { var canvas = GameObject.Find("/UIRoot/Canvas/").transform; var prafab = Resources.Load<GameObject>("DlgResource"); _dlgRes = GameObject.Instantiate(prafab) as GameObject; _dlgRes.transform.parent = canvas; _dlgRes.transform.localPosition = Vector3.zero; _dlgRes.transform.localScale = Vector3.one; _progress = _dlgRes.transform.Find("Slider_Progress").GetComponent<Slider>(); _status = _dlgRes.transform.Find("Text_Status").GetComponent<Text>(); TextAsset text = (TextAsset)Resources.Load("launcher", typeof(TextAsset)); if (null != text) { using (MemoryStream stream = new MemoryStream(text.bytes)) using (StreamReader r = new StreamReader(stream)) { string line; while ((line = r.ReadLine()) != null) { string[] pair = line.Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (pair != null && pair.Length == 2 && !_launcher.ContainsKey(pair[0])) _launcher.Add(pair[0], pair[1]); } } } } public void Dispose() { _progress = null; _status = null; _dlgRes = null; _launcher.Clear(); _instance = null; Resources.UnloadUnusedAssets(); } public IEnumerator InitSDK() { RefreshLaunch(LaunchState.InitSDK, 0.4f); while (!Interface.Instance.IsSDKFinished()) { yield return new WaitForEndOfFrame(); _progress.value = 0.6f; } _progress.value = 0.8f; //获取设备内存大小,如果不足,则提示内存不足. long memorysize = Interface.Instance.GetMemInfo(); _progress.value = 1f; #if UNITY_ANDROID if (memorysize < 1500000) { _status.text = _launcher[LaunchState.CheckMemerySize.ToString()]; yield return new WaitForSeconds(1); } #elif UNITY_IPHONE if (memorysize < 1000000) { _status.text = _launcher[LaunchState.CheckMemerySize.ToString()]; yield return new WaitForSeconds(1); } #elif UNITY_STANDALONE_WIN yield break; #else yield return new WaitForSeconds(1); #endif } public IEnumerator DowmloadUnZip() { RefreshLaunch(LaunchState.DowmloadZip, 1f); yield return null; } public IEnumerator UnZipFile() { RefreshLaunch(LaunchState.UnZipFile, 1f); yield return null; } public IEnumerator UpdateAppVersion() { RefreshLaunch(LaunchState.CheckAppVersion, 0.2f); //与服务器版本号进行对比 //TODO yield return new WaitForEndOfFrame(); if (true) { //下载资源-安装包 //TODO } RefreshLaunch(LaunchState.CheckAppVersion, 1f); } public IEnumerator UpdateResVersion() { RefreshLaunch(LaunchState.CheckResVersion, 0.2f); //与服务器版本号进行对比 //TODO yield return null; if (true) { //下载资源-数据资源 //TODO } //资源更新列表加快资源存在性检查速度;初始化资源管理器 //TODO;在读写路径下存一个文件 RefreshLaunch(LaunchState.CheckResVersion, 0.2f); } public IEnumerator GetServerList() { //下载服务器url列表 //App地址 //Res地址 //公告地址 //Android/IOS区服列表地址 //TODO yield return null; } public IEnumerator LoadResource() { yield return new WaitForEndOfFrame(); ResourceManager.Instance.Start(); yield return new WaitForEndOfFrame(); //场景加载 //TODO RefreshLaunch(LaunchState.LoadResource, 1f); } public void StartGame() { //GameObject.Destroy(_dlgRes); LuaManager.Instance.Start(); _progress.value = 1f; _status.text = "开始游戏"; } void RefreshLaunch(LaunchState state, float value) { _progress.value = value; _status.text = _launcher[state.ToString()]; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Game { public class NetworkManager : IManager { public static NetworkManager Instance { get { if (_instance == null) _instance = new NetworkManager(); return _instance; } } static NetworkManager _instance; protected NetworkManager() { } public void Init() { } public void Dispose() { } } } <file_sep>namespace CS.ActorConfig { using Sirenix.OdinInspector.Editor; using System; using System.Collections.Generic; using System.Linq; using System.Text; internal class SimplePopupCreator { public static void ShowDialog<T>(List<T> list, Action<T> onSelected = null) { var selector = new SimpleSelector<T>(list, onSelected); if (selector.SelectionTree.EnumerateTree().Count() == 1) { selector.SelectionTree.EnumerateTree().First().Select(); selector.SelectionTree.Selection.ConfirmSelection(); } else { selector.ShowInPopup(200); } } private class SimpleSelector<T> : OdinSelector<T> { private Action<T> _onSelected; private List<T> _list; public SimpleSelector(List<T> list, Action<T> onSelected = null) { this._onSelected = onSelected; this._list = list; this.SelectionConfirmed += this.Confirmed; } private void Confirmed(IEnumerable<T> selection) { if (_onSelected != null) { _onSelected(selection.FirstOrDefault()); } } protected override void BuildSelectionTree(OdinMenuTree tree) { tree.AddRange(_list, x => Convert.ToString(x)); } } } } <file_sep>using System; using UnityEngine; namespace Flux { [FEvent("调用序列", typeof(FSequenceTrack), true)] public class FPlaySequenceEvent : FEvent { private FSequence _sequence = null; /// <summary> /// 触发帧 /// </summary> public int StartOffset { get { return Start; } } public override string Text { get { return _sequence == null ? "Miss" : _sequence.name; } set { } } public int SeqID { get { int index = _sequence.name.IndexOf('_'); int startIndex = index + 1; string num = _sequence.name.Substring(startIndex, _sequence.name.Length - startIndex); return Convert.ToInt32(num); } } public bool HasSequence() { return _sequence != null; } protected override void OnInit() { _sequence = ((FSequenceTrack)Track).OwnerSequence; //if (!HasSequence()) // Debug.LogError("未指定序列对象,无法正常播放."); } protected override void OnTrigger(float timeSinceTrigger) { if (Sequence.IsPlaying && /*Application.isPlaying &&*/ HasSequence()) { _sequence.Play(StartOffset * _sequence.InverseFrameRate + timeSinceTrigger); } } //protected override void OnUpdateEvent(float timeSinceTrigger) //{ // if (HasSequence()) // _sequence.Speed = Mathf.Sign(Sequence.Speed) * Mathf.Abs(_sequence.Speed); //} // protected override void OnUpdateEvent( float timeSinceTrigger ) // { //// if( !Application.isPlaying ) //// _sequence.SetCurrentTime( StartOffset * Sequence.InverseFrameRate + timeSinceTrigger ); // } // // protected override void OnUpdateEventEditor( float timeSinceTrigger ) // { //// _sequence.SetCurrentTime( StartOffset * Sequence.InverseFrameRate + timeSinceTrigger ); //// _sequence.SetCurrentFrameEditor( _startOffset + framesSinceTrigger ); //// _sequence.SetCurrentFrame( _startOffset + framesSinceTrigger ); // } protected override void OnStop() { if (HasSequence()) _sequence.Stop(true); } protected override void OnFinish() { if (HasSequence()) _sequence.Pause(); } protected override void OnPause() { if (HasSequence()) _sequence.Pause(); } protected override void OnResume() { if (HasSequence()) _sequence.Play(_sequence.CurrentTime); // _sequence.Resume(); } } } <file_sep>using System; using System.IO; using System.Text; using UnityEngine; using System.Collections.Generic; using System.Security.Cryptography; using UObject = UnityEngine.Object; namespace Game { public class Util { /// <summary> /// 计算字符串的MD5值 /// </summary> public static string md5(string source) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.UTF8.GetBytes(source); byte[] md5Data = md5.ComputeHash(data, 0, data.Length); md5.Clear(); string destString = ""; for (int i = 0; i < md5Data.Length; i++) { destString += System.Convert.ToString(md5Data[i], 16).PadLeft(2, '0'); } destString = destString.PadLeft(32, '0'); return destString; } /// <summary> /// 计算文件的MD5值 /// </summary> public static string md5file(string file) { try { FileStream fs = new FileStream(file, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("md5file() fail, error:" + ex.Message); } } public static string StandardlizePath(string path) { return path.Replace(@"\", @"/"); } public static void SetResolution(int resolution) { #if UNITY_STANDALONE_WIN Screen.SetResolution(1280, 720, false); #else if (resolution < 720) return; if (resolution > 1080) return; int w = Screen.width; int h = Screen.height; if (h > resolution) { int width = resolution * w / h; int height = resolution; Screen.SetResolution(width, height, true); } #endif } /// <summary> /// 清除所有子节点 /// </summary> public static void ClearChild(Transform go) { if (go == null) return; for (int i = go.childCount - 1; i >= 0; i--) { GameObject.Destroy(go.GetChild(i).gameObject); } } /// <summary> /// 取得数据存放目录-可读写目录(可包含美术资源,脚本,配置) /// </summary> public static string DataPath { get { string path = string.Empty; switch (Application.platform) { case RuntimePlatform.Android: case RuntimePlatform.IPhonePlayer: path = Application.persistentDataPath + "/"; break; case RuntimePlatform.WindowsPlayer: path = "file://" + Application.persistentDataPath + "/"; break; case RuntimePlatform.WindowsEditor: case RuntimePlatform.OSXEditor: path = Application.dataPath + "/../../GamePlayer/"; break; } return path; } } /// <summary> /// 应用程序内容路径(包含首次所有美术资源) /// </summary> public static string StreamingPath { get { string path = string.Empty; switch (Application.platform) { case RuntimePlatform.Android: path = "jar:file://" + Application.dataPath + "!/assets/"; break; case RuntimePlatform.IPhonePlayer: path = Application.dataPath + "/Raw/"; break; case RuntimePlatform.WindowsPlayer: path = "file://" + Application.streamingAssetsPath + "/"; break; case RuntimePlatform.WindowsEditor: case RuntimePlatform.OSXEditor: path = Application.dataPath + "/../../GamePlayer/"; break; } return path; } } /// <summary> /// 网络可用 /// </summary> public static bool NetAvailable { get { return Application.internetReachability != NetworkReachability.NotReachable; } } /// <summary> /// 是否是无线 /// </summary> public static bool IsWifi { get { return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork; } } public static GameObject Instantiate(UObject obj, string path) { var gameObj = UObject.Instantiate(obj) as GameObject; if (gameObj != null && path != null) { var mr = gameObj.SetDefaultComponent<ManagedResource>(); mr.bundlename = path.Replace(@"\", @"/").ToLower(); Game.ResourceManager.Instance.AddRefCount(mr.bundlename); var mc = gameObj.GetComponent<MecanimControl>(); if (mc != null) { var mcold = (obj as GameObject).GetComponent<MecanimControl>(); mc.Copy(mcold); } } return gameObj; } public static GameObject Copy(UObject obj) { var gameObj = UObject.Instantiate(obj) as GameObject; if (gameObj != null) { var mr = gameObj.GetComponent<ManagedResource>(); if (mr != null) { Game.ResourceManager.Instance.AddRefCount(mr.bundlename); } var mc = gameObj.GetComponent<MecanimControl>(); if (mc != null) { var mcold = (obj as GameObject).GetComponent<MecanimControl>(); mc.Copy(mcold); } } return gameObj; } public static void Log(string str) { Debug.Log(str); } public static void LogWarning(string str) { Debug.LogWarning(str); } public static void LogError(string str) { Debug.LogError(str); } #region 本地文件读写 /// <summary> /// 解析成字典.格式:键值对用'='号分离 /// </summary> public static Dictionary<string, string> ReadDict(string filePath) { var dict = new Dictionary<string, string>(); if (File.Exists(filePath)) { string[] lines = File.ReadAllLines(filePath, Encoding.UTF8); for (int i = 0; i < lines.Length; i++) { string[] nodes = lines[i].Split("=".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (nodes.Length == 2 && !dict.ContainsKey(nodes[0])) dict.Add(nodes[0], nodes[1]); else Debug.LogErrorFormat("{0} 文件第{1}行格式错误!", filePath, i + 1); } } return dict; } /// <summary> /// 解析成列表.每行一个数据 /// </summary> public static List<string> ReadList(string filePath) { var list = new List<string>(); if (File.Exists(filePath)) list.AddRange(File.ReadAllLines(filePath, Encoding.UTF8)); return list; } public static void WriteDict(string filePath, Dictionary<string, string> dict) { StringBuilder builder = new StringBuilder(); foreach (var item in dict) builder.AppendFormat("{0}={1}\n", item.Key, item.Value); File.WriteAllText(filePath, builder.ToString(), Encoding.UTF8); } public static void WriteList(string filePath, List<string> list) { File.WriteAllLines(filePath, list.ToArray(), Encoding.UTF8); } #endregion } }<file_sep>local List = List local Class = Class ---@class Stack:List local Stack = Class:new(List) function Stack:Push(item) self:push(item) end function Stack:Peek() return self:head() end function Stack:Pop() return self:pop() end function Stack:Clear() self:clear() end function Stack:Count() return self.length end function Stack:Contains(item) local node = self:find(item) return node ~= nil end function Stack:Clone(item) self:clone() end function Stack:MoveNext() return self:movenext() end function Stack:Current() return self:current() end function Stack:InitEnumerator() self:initenumerator() end function Stack:ToTable() return self:totable() end return Stack<file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public enum ShakeType { /// <summary> /// 水平 /// <summary> Horizontal = 0, /// <summary> /// 垂直 /// <summary> Vertical = 1, /// <summary> /// 混合 /// <summary> Mix = 2, } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public enum HitSharpType { /// <summary> /// 立方体 /// <summary> Cube = 0, /// <summary> /// 球 /// <summary> Sphere = 1, /// <summary> /// 圆柱形 /// <summary> Cylinder = 2, } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class CubeZone : Cfg.Skill.HitZone { /// <summary> /// 方盒缩放大小 /// <summary> public Cfg.Vector3 Scale; public CubeZone(DataStream data) : base(data) { this.Scale = new Vector3(data); } } } <file_sep>local pairs = pairs local error = error local type = type local insert = table.insert local format = string.format local Class = Class local Util = Util local Event = Class:new() function Event:__new(name) self.name = name or "__unknown__" self.eventMap = {} self.statusMap = {} end function Event:Add(event, handler) if not event or type(event) ~= "string" then error("[Event.Add]event has to be string, " .. type(event) .. " not right.") end local handlers = self.eventMap[event] if not handlers then handlers = {} self.eventMap[event] = handlers end insert(handlers, handler) return function() self:Remove(event, handler) end end function Event:Remove(event, handler) --print("[Event:Remove]remove event handler.", self.name, event) if self.eventMap[event] then local handlers = self.eventMap[event] for k, v in pairs(handlers) do if v == handler then self.eventMap[event][k] = nil end end else print("[Event:Remove]event no handler.", self.name) end end function Event:Destroy(event) if self.eventMap[event] then self.eventMap[event] = nil else print("[Event:Destroy]eventlib no event", self.name, event) end end function Event:AddStatusListener(listener) self.statusMap[listener.name] = listener end function Event:Trigger(event, ...) local events = self.eventMap[event] if not events then --error("[Event:Trigger]eventlib no event:" .. event) return end for _, handler in ipairs(events) do --print("[Event:Trigger] ", self.name, target, handler) if self.statusMap[event] then self.statusMap[event]:BeginSample() end Util.Myxpcall(handler, ...) if self.statusMap[event] then self.statusMap[event]:EndSample() end end end function Event:Dump(event) local r = {} if event then if self.eventMap[event] then insert(r,format("%s\t\t\t\t%d", event, #self.eventMap[event])) else printcolor("eventlib no event", event) end else for k, v in pairs(self.eventMap) do insert(r,format("%s\t\t\t\t%d", k, #v)) end end print('dump event list..', '\n' .. table.concat(r, '\n')) end local global = Event:new("__global") -- 如果不指定事件名,则创建一个匿名事件 function Event:NewSimple(name) name = name or {} return { Add = function(self, handler) return global:Add(name, handler) end, Remove = function(self, event, handler) global:Remove(event, handler) end, Trigger = function(self, ...) global:Trigger(name, ...) end, AddStatusListener = function(self, listener) global:AddStatusListener(listener) end, Destroy = function(self) global:Destroy(name) end, Dump = function(self, event) global:Dump(event) end, name = name, } end return Event<file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class ShakeScreen : Cfg.Skill.Timeline { /// <summary> /// 震屏方式:0水平 1垂直 2混合 /// <summary> public readonly int Type; /// <summary> /// 每秒震动的次数 /// <summary> public readonly int Frequency; /// <summary> /// 初始频率维持时间 /// <summary> public readonly float FrequencyDuration; /// <summary> /// 频率衰减 /// <summary> public readonly float FrequencyAtten; /// <summary> /// 单次振幅 /// <summary> public readonly float Amplitude; /// <summary> /// 单次震动的衰减幅度 /// <summary> public readonly float AmplitudeAtten; /// <summary> /// 最小完整影响范围 /// <summary> public readonly float MinRange; /// <summary> /// 最大影响范围 /// <summary> public readonly float MaxRange; public ShakeScreen(DataStream data) : base(data) { this.Type = data.GetInt(); this.Frequency = data.GetInt(); this.FrequencyDuration = data.GetFloat(); this.FrequencyAtten = data.GetFloat(); this.Amplitude = data.GetFloat(); this.AmplitudeAtten = data.GetFloat(); this.MinRange = data.GetFloat(); this.MaxRange = data.GetFloat(); } } } <file_sep>namespace CS.ActorConfig { using UnityEngine; using UnityEditor; using System.Linq; using Sirenix.Utilities; using Sirenix.Utilities.Editor; using Sirenix.OdinInspector.Editor; using Cfg.Character; using System.Collections.Generic; internal class ActorCfgWindow : OdinMenuEditorWindow { [MenuItem("Window/Action Designer/Load Action")] private static void Open() { var window = GetWindow<ActorCfgWindow>("模型配置窗口"); window.position = GUIHelper.GetEditorWindowRect().AlignCenter(800, 500); window.minSize = new Vector2(400, 500); ActionHomeConfig.LoadInstanceIfAssetExists(); HomeConfig.Instance.LoadAll(); } Rect _windowRect = new Rect(100, 100, 200, 200); ActorConfigEditor _actor; List<OdinMenuItem> _currentItems = new List<OdinMenuItem>(); public void RefreshTree() { if (MenuTree == null) return; foreach (var group in HomeConfig.Instance.ModelGroupDict) { foreach (var item in group.Value) { MenuTree.Add(item.MenuItemName, item); } } } protected override OdinMenuTree BuildMenuTree() { OdinMenuTree tree = new OdinMenuTree(supportsMultiSelect: false); tree.Config.DrawSearchToolbar = true; foreach (var item in ActionHomeConfig.MenuItems) { if (item.Key != GroupType.None) tree.Add(item.Value, null, EditorIcons.Table); else tree.Add("主页", HomeConfig.Instance, EditorIcons.House); } foreach (var group in HomeConfig.Instance.ModelGroupDict) { foreach (var item in group.Value) { tree.Add(item.MenuItemName, item); } } tree.Selection.SelectionChanged += OnMenuItemChange; return tree; } protected void OnMenuItemChange(SelectionChangedType state) { foreach (var item in _currentItems) { if (item.Value is ActorConfigEditor) (item.Value as ActorConfigEditor).ReselectedState(); } _currentItems.Clear(); _currentItems.AddRange(MenuTree.Selection); } protected override void OnBeginDrawEditors() { if (MenuTree == null) return; var selected = this.MenuTree.Selection.FirstOrDefault(); var toolbarHeight = this.MenuTree.Config.SearchToolbarHeight; SirenixEditorGUI.BeginHorizontalToolbar(toolbarHeight); { if (selected != null) { var old = GUI.color; GUI.color = Color.cyan; GUILayout.Label(selected.Name, SirenixGUIStyles.BoldLabel); GUI.color = old; } if (SirenixEditorGUI.ToolbarButton("检查")) { HomeConfig.Instance.CheckAll(); } } SirenixEditorGUI.EndHorizontalToolbar(); } protected override void OnDestroy() { base.OnDestroy(); HomeConfig.Instance.Destroy(); Clipboard.Clear(); EditorUtility.UnloadUnusedAssetsImmediate(true); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); Debug.Log("[模型配置窗口]关闭~~"); } } }<file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public enum ActionSourceType { /// <summary> /// 自己模型 /// <summary> SelfModel = 0, /// <summary> /// 其他模型 /// <summary> OtherModel = 1, } } <file_sep>using System; using System.IO; using System.Linq; using System.Xml; using System.Collections.Generic; namespace XmlCfg.Skill { public class PlayParticle : XmlCfg.Skill.Timeline { /// <summary> /// 粒子资源的路径 /// <summary> public string Path = ""; /// <summary> /// 是否相对于自己移动 /// <summary> public bool IsRelateSelf; /// <summary> /// 特效是否始终跟随目标对象方向变化 /// <summary> public bool FollowDir; /// <summary> /// 节点名称,如果有配置则绑定到节点局部空间;反之绑定世界空间 /// <summary> public string NodeName = ""; /// <summary> /// 特效结点偏移;特效世界偏移 /// <summary> public XmlCfg.Vector3 Position; /// <summary> /// 特效结点旋转;特效世界旋转 /// <summary> public XmlCfg.Vector3 EulerAngles; /// <summary> /// 整体缩放大小 /// <summary> public XmlCfg.Vector3 Scale; /// <summary> /// 屏幕对齐类型 /// <summary> public XmlCfg.Skill.EffectAlignType AlignType; public override void Write(TextWriter _1) { base.Write(_1); Write(_1, "Path", this.Path); Write(_1, "IsRelateSelf", this.IsRelateSelf); Write(_1, "FollowDir", this.FollowDir); Write(_1, "NodeName", this.NodeName); Write(_1, "Position", this.Position); Write(_1, "EulerAngles", this.EulerAngles); Write(_1, "Scale", this.Scale); Write(_1, "AlignType", (int)this.AlignType); } public override void Read(XmlNode _1) { base.Read(_1); foreach (System.Xml.XmlNode _2 in GetChilds (_1)) switch (_2.Name) { case "Path": this.Path = ReadString(_2); break; case "IsRelateSelf": this.IsRelateSelf = ReadBool(_2); break; case "FollowDir": this.FollowDir = ReadBool(_2); break; case "NodeName": this.NodeName = ReadString(_2); break; case "Position": this.Position = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; case "EulerAngles": this.EulerAngles = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; case "Scale": this.Scale = ReadObject<XmlCfg.Vector3>(_2, "XmlCfg.Vector3"); break; case "AlignType": this.AlignType = (XmlCfg.Skill.EffectAlignType)ReadInt(_2); break; } } } } <file_sep>local Event = Event local Time = Time local UpdateEvent = Event:NewSimple("Update") local CoUpdateEvent = Event:NewSimple("CoUpdate") local LateUpdateEvent = Event:NewSimple("LateUpdate") local FixedUpdateEvent = Event:NewSimple("FixedUpdate") return { UpdateEvent = UpdateEvent, CoUpdateEvent = CoUpdateEvent, LateUpdateEvent = LateUpdateEvent, FixedUpdateEvent = FixedUpdateEvent, }<file_sep>using UnityEngine; using UnityEditor; using System; using System.Collections.Generic; using Flux; namespace FluxEditor { [Serializable] public class FContainerEditor : FEditorList<FTrackEditor> { public const int CONTAINER_HEIGHT = 25; public FContainer Container { get { return (FContainer)Obj; } } private bool _isDragSelecting = false; private Vector2 _dragSelectingStartPos = Vector2.zero; private float _timelineHeaderWidth = 0; private float _pixelsPerFrame = 0; public void OnStop() { for (int i = 0; i != Editors.Count; ++i) Editors[i].OnStop(); } public void UpdateTracks(int frame, float time) { for (int i = 0; i != Editors.Count; ++i) { if (!Editors[i].Track.enabled) continue; Editors[i].UpdateEventsEditor(frame, time); } } public override void Init(FObject obj, FEditor owner) { base.Init(obj, owner); Editors.Clear(); List<FTrack> tracks = Container.Tracks; for (int i = 0; i < tracks.Count; ++i) { FTrack track = tracks[i]; FTrackEditor trackEditor = SequenceEditor.GetEditor<FTrackEditor>(track); trackEditor.Init(track, this); Editors.Add(trackEditor); } _icon = new GUIContent(FUtility.GetFluxTexture("Plus.png")); } public override FSequenceEditor SequenceEditor { get { return (FSequenceEditor)Owner; } } public override float HeaderHeight { get { return CONTAINER_HEIGHT; } } protected override string HeaderText { get { return Obj.name; } } protected override bool IconOnLeft { get { return false; } } protected override Color BackgroundColor { get { return Container.Color; } } protected override bool CanPaste(FObject obj) { // since Unity Objs can be "fake null" return obj != null && obj is FTrack; } protected override void Paste(object obj) { if (!CanPaste(obj as FObject)) return; Undo.RecordObject(Container, string.Empty); FTrack track = Instantiate<FTrack>((FTrack)obj); track.hideFlags = Container.hideFlags; Container.Add(track); Undo.RegisterCreatedObjectUndo(track.gameObject, "Paste Timeline " + ((FTrack)obj).name); } protected override void Delete() { SequenceEditor.DestroyEditor(this); } protected override void OnHeaderInput(Rect labelRect, Rect iconRect) { if (Event.current.type == EventType.MouseDown && Event.current.clickCount > 1 && labelRect.Contains(Event.current.mousePosition)) { Selection.activeTransform = Container.Owner; Event.current.Use(); } base.OnHeaderInput(labelRect, iconRect); if (Event.current.type == EventType.MouseDown && iconRect.Contains(Event.current.mousePosition)) { FSettings fSettings = FUtility.GetSettings(); FContainerSetting setting = fSettings.ContainerType.Find(c => c._type == Container.ConatinerType); if (setting == null) ShowAddTrackMenu(); else ShowAddTrackMenuBaseOnType(setting); } } private void ShowAddTrackMenuBaseOnType(FContainerSetting setting) { Event.current.Use(); GenericMenu menu = new GenericMenu(); System.Reflection.Assembly fluxAssembly = typeof(FEvent).Assembly; List<KeyValuePair<Type, FEventAttribute>> validTypeList = new List<KeyValuePair<Type, FEventAttribute>>(); for (int i = 0; i < setting._list.Count; i++) { string t = setting._list[i]; if (string.IsNullOrEmpty(t)) continue; Type type = fluxAssembly.GetType(t); if (type == null || !typeof(FEvent).IsAssignableFrom(type)) { Debug.LogErrorFormat("定义{0} 不是事件类型.", t); continue; } object[] attributes = type.GetCustomAttributes(typeof(FEventAttribute), false); if (attributes.Length == 0 || ((FEventAttribute)attributes[0]).menu == null) continue; validTypeList.Add(new KeyValuePair<Type, FEventAttribute>(type, (FEventAttribute)attributes[0])); } validTypeList.Sort(delegate (KeyValuePair<Type, FEventAttribute> x, KeyValuePair<Type, FEventAttribute> y) { return x.Value.menu.CompareTo(y.Value.menu); }); foreach (KeyValuePair<Type, FEventAttribute> kvp in validTypeList) { menu.AddItem(new GUIContent(kvp.Value.menu), false, AddTrackMenu, kvp); } menu.ShowAsContext(); } //--添加所有FTrack private void ShowAddTrackMenu() { Event.current.Use(); GenericMenu menu = new GenericMenu(); System.Reflection.Assembly fluxAssembly = typeof(FEvent).Assembly; Type[] types = typeof(FEvent).Assembly.GetTypes(); if (fluxAssembly.GetName().Name != "Assembly-CSharp") { // if we are in the flux trial, basically allow to get the types in the project assembly ArrayUtility.AddRange<Type>(ref types, System.Reflection.Assembly.Load("Assembly-CSharp").GetTypes()); } List<KeyValuePair<Type, FEventAttribute>> validTypeList = new List<KeyValuePair<Type, FEventAttribute>>(); foreach (Type t in types) { if (!typeof(FEvent).IsAssignableFrom(t)) continue; object[] attributes = t.GetCustomAttributes(typeof(FEventAttribute), false); if (attributes.Length == 0 || ((FEventAttribute)attributes[0]).menu == null) continue; validTypeList.Add(new KeyValuePair<Type, FEventAttribute>(t, (FEventAttribute)attributes[0])); } validTypeList.Sort(delegate (KeyValuePair<Type, FEventAttribute> x, KeyValuePair<Type, FEventAttribute> y) { return x.Value.menu.CompareTo(y.Value.menu); }); foreach (KeyValuePair<Type, FEventAttribute> kvp in validTypeList) { menu.AddItem(new GUIContent(kvp.Value.menu), false, AddTrackMenu, kvp); } menu.ShowAsContext(); } void AddTrackMenu(object param) { KeyValuePair<Type, FEventAttribute> kvp = (KeyValuePair<Type, FEventAttribute>)param; Undo.RecordObjects(new UnityEngine.Object[] { Container, this }, "add Track"); FTrack track = (FTrack)typeof(FContainer).GetMethod("Add", new Type[] { typeof(FrameRange) }).MakeGenericMethod(kvp.Key).Invoke(Container, new object[] { SequenceEditor.ViewRange }); //string evtName = track.gameObject.name; //int nameStart = 0; //int nameEnd = evtName.Length; //if (nameEnd > 2 && evtName[0] == 'F' && char.IsUpper(evtName[1])) // nameStart = 1; //if (evtName.EndsWith("Event")) // nameEnd = evtName.Length - "Event".Length; //evtName = evtName.Substring(nameStart, nameEnd - nameStart); string evtName = kvp.Value.menu; if (!string.IsNullOrEmpty(kvp.Value.menu)) { string[] nodes = kvp.Value.menu.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); evtName = nodes[nodes.Length - 1]; } track.gameObject.name = ObjectNames.NicifyVariableName(evtName); if (!Container.Sequence.IsStopped) track.Init(); SequenceEditor.Refresh(); Undo.RegisterCreatedObjectUndo(track.gameObject, string.Empty); SequenceEditor.SelectExclusive(SequenceEditor.GetEditor<FEventEditor>(track.GetEvent(0))); } public bool HasTrack(FTrackEditor trackEditor) { foreach (FTrackEditor t in Editors) { if (t == trackEditor) return true; } return false; } private void StartDragSelecting(Vector2 mousePos) { _isDragSelecting = true; _dragSelectingStartPos = mousePos; } private void StopDragSelecting(Vector2 mousePos) { if (!_isDragSelecting) return; _isDragSelecting = false; FrameRange selectedRange = new FrameRange(); bool isSelectingTimelines; Rect selectionRect = GetDragSelectionRect(_dragSelectingStartPos, mousePos, out selectedRange, out isSelectingTimelines); if (!Event.current.shift && !Event.current.control) SequenceEditor.DeselectAll(); for (int i = 0; i != Editors.Count; ++i) { Rect trackRect = Editors[i].Rect; if (trackRect.yMin >= selectionRect.yMax) break; if (trackRect.yMax <= selectionRect.yMin) continue; if (Event.current.control) { Editors[i].DeselectEvents(selectedRange); } else { Editors[i].SelectEvents(selectedRange); } } } private void OnDragSelecting(Vector2 mousePos) { if (!_isDragSelecting) return; if (Event.current.shift) { EditorGUIUtility.AddCursorRect(Rect, MouseCursor.ArrowPlus); } else if (Event.current.control) { EditorGUIUtility.AddCursorRect(Rect, MouseCursor.ArrowMinus); } FrameRange selectedRange; bool isSelectingTracks; Rect selectionRect = GetDragSelectionRect(_dragSelectingStartPos, mousePos, out selectedRange, out isSelectingTracks); if (selectionRect.width == 0) selectionRect.width = 1; GUI.color = FGUI.GetSelectionColor(); GUI.DrawTexture(selectionRect, EditorGUIUtility.whiteTexture); GUI.color = Color.white; } private Rect GetDragSelectionRect(Vector2 rawStartPos, Vector2 rawEndPos, out FrameRange selectedRange, out bool isSelectingTracks) { int startFrame = GetFrameForX(rawStartPos.x); int endFrame = GetFrameForX(rawEndPos.x); if (startFrame > endFrame) { int temp = startFrame; startFrame = endFrame; endFrame = temp; } selectedRange = new FrameRange(startFrame, endFrame); Rect rect = new Rect(); Vector2 startPos = new Vector2(GetXForFrame(startFrame), rawStartPos.y); Vector2 endPos = new Vector2(GetXForFrame(endFrame), rawEndPos.y); bool isStartOnHeader; bool isEndOnHeader; FTrackEditor startTrack = GetTrackEditor(startPos, out isStartOnHeader); isSelectingTracks = isStartOnHeader; if (startTrack != null) { FTrackEditor endTrack = GetTrackEditor(endPos, out isEndOnHeader); if (endTrack == null) { endTrack = startTrack; isEndOnHeader = isStartOnHeader; } float xStart = Mathf.Min(startPos.x, endPos.x); float width = Mathf.Abs(startPos.x - endPos.x); float yStart; float height; if (startPos.y <= endPos.y) { yStart = startTrack.Rect.yMin; height = (isStartOnHeader ? endTrack.Rect.yMax : (isEndOnHeader ? endTrack.Rect.yMin + FTrackEditor.DEFAULT_TRACK_HEIGHT : endTrack.Rect.yMax)) - yStart; } else { yStart = isStartOnHeader || isEndOnHeader ? endTrack.Rect.yMin : endTrack.Rect.yMin; height = (isStartOnHeader ? startTrack.Rect.yMax : startTrack.Rect.yMax) - yStart; } rect.x = xStart; rect.y = yStart; rect.width = width; rect.height = height; } return rect; } public float GetXForFrame(int frame) { return _timelineHeaderWidth + frame * _pixelsPerFrame; } public int GetFrameForX(float x) { return Mathf.RoundToInt(((x - _timelineHeaderWidth) / _pixelsPerFrame)); } private FTrackEditor GetTrackEditor(Vector2 pos, out bool isOnHeader) { for (int i = 0; i != Editors.Count; ++i) { if (Editors[i].Rect.Contains(pos)) { isOnHeader = Editors[i].Rect.yMin + FTrackEditor.DEFAULT_TRACK_HEIGHT > pos.y; return Editors[i]; } } isOnHeader = false; return null; } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Character { public enum GroupType { /// <summary> /// 临时组 /// <summary> None = 0, /// <summary> /// 基础类型 /// <summary> Base = 1, /// <summary> /// 玩家 /// <summary> Player = 2, /// <summary> /// 怪物 /// <summary> Monster = 3, /// <summary> /// NPC /// <summary> NPC = 4, } } <file_sep>using UnityEngine; using System.Collections; using XmlCfg.Skill; namespace Flux { [FEvent("碰撞区域")] public class FHitZone : FEvent { [SerializeField, HideInInspector] [FEventField("区域ID")] private int _zoneId; [SerializeField, HideInInspector] private HitSharpType _sharpType; [SerializeField, HideInInspector] [FEventField("偏移量", "相对偏移量")] private Vector3 _offset; [SerializeField, HideInInspector] [FEventField("最大数量", Tip = "可碰撞到对象的最大数量")] private int _maxNum; [SerializeField, HideInInspector] private Vector3 _scale; [SerializeField, HideInInspector] private float _radius; [SerializeField, HideInInspector] private float _height; [SerializeField, HideInInspector] private float _angle; public int ZoneID { get { return _zoneId; } } public HitSharpType SharpType { get { return _sharpType; } } public override string Text { get { return string.Format("区域{0}-{1}", _zoneId, _sharpType); } set { } } } } <file_sep>using Flux; using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace FluxEditor { [CustomEditor(typeof(Flux.FHitCheck), true)] public class FHitCheckInspector : FEventInspector { private SerializedProperty _target; private SerializedProperty _isDynamic; private SerializedProperty _zone; private SerializedProperty _sequence; private GUIContent _targetUI = new GUIContent("目标对象"); private GUIContent _isDynamicUI = new GUIContent("是否动态检测"); private GUIContent _zoneUI = new GUIContent("碰撞区域配置"); private GUIContent _sequenceUI = new GUIContent("动态序列"); private List<string> _paths; private GUIContent[] _pathNames; private int _selectedNodeIndex; private Dictionary<string, Transform> _targetDict = new Dictionary<string, Transform>(); private List<FHitZone> _zones; private GUIContent[] _zoneNames; private int _selectedZoneIndex; private List<FSequence> _sequences; private GUIContent[] _sequenceNames; private int _selectedSequenceIndex; protected override void OnEnable() { base.OnEnable(); _isDynamic = serializedObject.FindProperty("_isDynamic"); _target = serializedObject.FindProperty("_target"); Transform[] objs = FUtility.FindObjects<Transform>(); _paths = new List<string>(); _targetDict.Clear(); for (int i = 0; i < objs.Length; i++) { if (objs[i].parent == null) _paths.AddRange(GetTransformPath(objs[i])); } string path = _paths[_selectedNodeIndex]; if (_selectedNodeIndex < _paths.Count && _targetDict.ContainsKey(path)) _target.objectReferenceValue = _targetDict[path]; _pathNames = new GUIContent[_paths.Count]; for (int i = 0; i < _paths.Count; i++) _pathNames[i] = new GUIContent(_paths[i]); _zone = serializedObject.FindProperty("_zone"); _zones = new List<FHitZone>(FUtility.FindObjects<FHitZone>()); _zones.Sort(delegate (FHitZone a, FHitZone b) { return a.name.CompareTo(b.name); }); if (_zone.objectReferenceValue == null && _zones.Count > 0) { _selectedZoneIndex = 0; _zone.objectReferenceValue = _zones[0]; } else _selectedZoneIndex = _zones.FindIndex((select) => select.name == _zone.objectReferenceValue.name); _zoneNames = new GUIContent[_zones.Count]; for (int i = 0; i != _zones.Count; ++i) _zoneNames[i] = new GUIContent(_zones[i].Text); var staticHit = (FHitCheck)target; _sequence = serializedObject.FindProperty("_sequence"); _sequences = new List<FSequence>(FUtility.FindObjects<FSequence>()); _sequences.Remove(staticHit.Sequence); _sequences.Sort(delegate (FSequence x, FSequence y) { return x.name.CompareTo(y.name); }); if (_sequence.objectReferenceValue == null && _sequences.Count > 0) { _selectedSequenceIndex = 0; _sequence.objectReferenceValue = _sequences[0]; } else _selectedSequenceIndex = _sequences.FindIndex((select) => select.name == _sequence.objectReferenceValue.name); _sequenceNames = new GUIContent[_sequences.Count]; for (int i = 0; i != _sequences.Count; ++i) _sequenceNames[i] = new GUIContent(_sequences[i].name); serializedObject.ApplyModifiedProperties(); } private List<string> GetTransformPath(Transform tran) { List<string> ls = new List<string>(); if (tran.childCount == 0) { Transform node = tran; string path = tran.name; while (tran.parent != null) { path = string.Format("{0}/{1}", tran.parent.name, path); tran = tran.parent; } ls.Add(path); if (!_targetDict.ContainsKey(path)) _targetDict.Add(path, node); } else for (int i = 0; i < tran.childCount; i++) ls.AddRange(GetTransformPath(tran.GetChild(i))); return ls; } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); EditorGUI.BeginChangeCheck(); int index00 = EditorGUILayout.Popup(_targetUI, _selectedNodeIndex, _pathNames); if (EditorGUI.EndChangeCheck()) { _selectedNodeIndex = index00; string path = _paths[_selectedNodeIndex]; if (_targetDict.ContainsKey(path)) _target.objectReferenceValue = _targetDict[path]; else Debug.LogError("场景中不存在目标对象!" + path); } EditorGUILayout.PropertyField(_isDynamic, _isDynamicUI); EditorGUI.BeginChangeCheck(); int index0 = EditorGUILayout.Popup(_zoneUI, _selectedZoneIndex, _zoneNames); if (EditorGUI.EndChangeCheck()) { _selectedZoneIndex = index0; _zone.objectReferenceValue = _zones[index0]; } EditorGUI.BeginChangeCheck(); int index1 = EditorGUILayout.Popup(_sequenceUI, _selectedSequenceIndex, _sequenceNames); if (EditorGUI.EndChangeCheck()) { _selectedSequenceIndex = index1; _sequence.objectReferenceValue = _sequences[index1]; } serializedObject.ApplyModifiedProperties(); } } } <file_sep>using UnityEngine; using System; namespace Game.Platform { public enum NetworkMode { offline, WiFi, Mobile } public abstract class Interface { private static Interface _instance = null; protected Interface() { } public static Interface Instance { get { return _instance; } } public static void Create() { switch (Application.platform) { case RuntimePlatform.Android: { } break; case RuntimePlatform.IPhonePlayer: { } break; case RuntimePlatform.WindowsPlayer: case RuntimePlatform.OSXPlayer: { } break; case RuntimePlatform.WindowsEditor: case RuntimePlatform.OSXEditor: { _instance = new CustomInterface(); } break; default: { _instance = new CustomInterface(); } break; } } public virtual void Init() { throw new ArgumentNullException("interface"); } public virtual void Release() { } public virtual int GetAvailableMemory() { return 1000; } public virtual string Install(string file) { return string.Empty; } // 渠道类型 public virtual int GetSDKPlatform() { return 0; //0 - 测试版 其他平台看枚举 EPlatformType } public virtual string GetSDKPlatformName() { return ""; } public virtual NetworkMode GetNetWorkMode() { return NetworkMode.WiFi; } public virtual void InitSDK() { } public virtual bool EscapeSDK() { return false; } public virtual bool IsSDKFinished() { return true; } public virtual void Login() { } public virtual void Logout() { } public virtual void SubmitUserInfo(string type, string roleid, string rolename, string level, int zoneid, string zonename, string createtime) { } public virtual void Pay(string roleid, string rolename, string level, string vip, string orderId, int serverid, string servername, int cash, string pid, string desc) { } //0:未登录 //1:临时用户登录 //2:正式用户登录 public virtual int GetLoginStatus() { return 1; } public virtual long GetUserId() { return 0; } public virtual string GetUserName() { return ""; } public virtual string GetToken() { return ""; } public virtual void SetToken(string token, int deadline) { } public virtual void SetUserInfo(string userId, string userName) { } public virtual void CheckGuestAccount() { } public virtual void ChangeAccount() { } public virtual void StartAccountHome() { } public virtual void StartForum() { } public virtual void ShowToolBar() { } public virtual void HideToolBar() { } //是否越狱版,1为越狱,只对IOS有效 public virtual bool IsCydia() { return true; } // 是否为平板设备。用来判别显示Pad-UI或Mini-UI // 在iOS上检测准确可靠。Android上不够准确,默认设置为手机版。 public virtual bool IsPad() { return true; } public virtual bool IsHdVersion() { return false; } public virtual void StartWebView(string strURL) { } public virtual void OpenUrl(string url) { } public virtual void SendWeibo(string content) { } public virtual void SendWeChat(string content) { } public virtual long GetMemInfo() { return 0; } public virtual string GetUDID() { return ""; } ///语音小纸条 public virtual int Voice_GetFileLength() { return -1; } public virtual int Voice_GetVolume() { return 0; } public virtual bool Voice_Start(bool record, string filename, bool recognize) { return false; } public virtual void Voice_Stop() { return; } public virtual string Voice_GetAsrText() { return ""; } public virtual void InitLogSystem(string filename) { } public virtual void MonitorBatteryState() { } public virtual void OpenAlbum(string fileNameBig, string fileNameSmall, int scaleFactorBig, int scaleFactorSmall, string resultCode) { } public virtual void StartScanCode() { } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.Skill { public class Buff : Cfg.Skill.PlayParticle { /// <summary> /// Buff参数集合ID /// <summary> public readonly int Id; public Buff(DataStream data) : base(data) { this.Id = data.GetInt(); } } } <file_sep>using System; using System.Collections.Generic; using Cfg; namespace Cfg.AllType { public class AllClass : CfgObject { /// <summary> /// 常量字符串 /// <summary> public const string ConstString = @"Hello World"; /// <summary> /// 常量浮点值 /// <summary> public const float ConstFloat = 3.141527f; /// <summary> /// ID /// <summary> public readonly int ID; /// <summary> /// 长整型 /// <summary> public readonly long VarLong; /// <summary> /// 浮点型 /// <summary> public readonly float VarFloat; /// <summary> /// 字符串 /// <summary> public readonly string VarString; /// <summary> /// 布尔型 /// <summary> public readonly bool VarBool; /// <summary> /// 枚举类型 /// <summary> public readonly int VarEnum; /// <summary> /// 类类型 /// <summary> public Cfg.AllType.SingleClass VarClass; /// <summary> /// 字符串列表 /// <summary> public readonly List<string> VarListBase = new List<string>(); /// <summary> /// Class列表 /// <summary> public readonly List<SingleClass> VarListClass = new List<SingleClass>(); /// <summary> /// 字符串列表 /// <summary> public readonly List<string> VarListCardElem = new List<string>(); /// <summary> /// 基础类型字典 /// <summary> public readonly Dictionary<int, string> VarDictBase = new Dictionary<int, string>(); /// <summary> /// 枚举类型字典 /// <summary> public readonly Dictionary<long, CardElement> VarDictEnum = new Dictionary<long, CardElement>(); /// <summary> /// 类类型字典 /// <summary> public readonly Dictionary<string, SingleClass> VarDictClass = new Dictionary<string, SingleClass>(); public AllClass(DataStream data) { this.ID = data.GetInt(); this.VarLong = data.GetLong(); this.VarFloat = data.GetFloat(); this.VarString = data.GetString(); this.VarBool = data.GetBool(); this.VarEnum = data.GetInt(); this.VarClass = (AllType.SingleClass)data.GetObject(data.GetString()); for (int n = data.GetInt(); n-- > 0; ) { this.VarListBase.Add(data.GetString()); } for (int n = data.GetInt(); n-- > 0; ) { this.VarListClass.Add((SingleClass)data.GetObject(data.GetString())); } for (int n = data.GetInt(); n-- > 0; ) { this.VarListCardElem.Add(data.GetString()); } for (int n = data.GetInt(); n-- > 0;) { int k = data.GetInt(); this.VarDictBase[k] = data.GetString(); } for (int n = data.GetInt(); n-- > 0;) { long k = data.GetLong(); this.VarDictEnum[k] = (AllType.CardElement)data.GetInt(); } for (int n = data.GetInt(); n-- > 0;) { string k = data.GetString(); this.VarDictClass[k] = (SingleClass)data.GetObject(data.GetString()); } } } } <file_sep>using UnityEngine; using System; using System.Collections.Generic; public static class ExtendedGameObject { public static void PrintActiveState(this GameObject gameObject) { Debug.Log ("The active state of " + gameObject.name + ":" + GetActiveState(gameObject)); } public static string GetActiveState(this GameObject gameObject) { string res = ""; res += gameObject.GetPath() + ":[" + gameObject.activeSelf + "];"; foreach(Transform child in gameObject.transform) { res += GetActiveState(child.gameObject); } return res; } public static void ForEach_Depth(this GameObject prefab, System.Action<GameObject> action) { if(null == prefab) { return; } if( action!=null) { action(prefab); } foreach( Transform t in prefab.transform) { ForEach_Depth(t.gameObject,action); } } public static GameObject Clone(this GameObject prefab) { if(null == prefab) { return null; } var cloned = GameObject.Instantiate(prefab) as GameObject; var prefabTransform = prefab.transform; cloned.transform.parent = prefabTransform.parent; // in NGUI, the localScale will be adjusted automatically according to the scale of camera. so restore it. cloned.transform.localScale = prefabTransform.localScale; return cloned; } public static GameObject ReplacedByPrefab(this GameObject go, GameObject prefab) { if(null == go || null == prefab) { return null; } var cloned = GameObject.Instantiate(prefab) as GameObject; var oldTransform = go.transform; cloned.transform.parent = oldTransform.parent; // in NGUI, the localScale will be adjusted automatically according to the scale of camera. so restore it. cloned.transform.localScale = oldTransform.localScale; GameObject.Destroy(go); return cloned; } public static void SetActiveRecursely(this GameObject go, bool tag) { foreach(Transform child in go.transform) { child.gameObject.SetActiveRecursely(tag); } go.SetActive(tag); } public static void SetToLayer(this GameObject go, int layer) { foreach (Transform child in go.transform) { child.gameObject.SetToLayer(layer); } go.layer = layer; } public static void SetParticleSystemScale(this GameObject go, float scale) { foreach (Transform child in go.transform) { child.gameObject.SetParticleSystemScale(scale); } if (go.GetComponent<ParticleSystem>() != null) { go.GetComponent<ParticleSystem>().startSize *= scale; go.GetComponent<ParticleSystem>().startSpeed *= scale; } } public static void SetParticleSystemVisible(this GameObject go, bool bVisible) { foreach (Transform child in go.transform) { child.gameObject.SetParticleSystemVisible(bVisible); } if (go.GetComponent<ParticleSystem>() != null) { if (bVisible) { go.GetComponent<ParticleSystem>().Play(); } else { go.GetComponent<ParticleSystem>().Stop(); } } } public static GameObject GetChildByName(this GameObject go, string name) { if(null != go) { foreach(Transform child in go.transform) { if(child.name == name) { return child.gameObject; } var grandson = child.gameObject.GetChildByName(name); if(null != grandson) { return grandson; } } } return null; } public static GameObject GetChildHasName(this GameObject go, string name) { if (null != go) { foreach (Transform child in go.transform) { if (child.name.Contains(name)) { return child.gameObject; } var grandson = child.gameObject.GetChildHasName(name); if (null != grandson) { return grandson; } } } return null; } public static GameObject[] GetDirectChildren(this GameObject go, string[] names) { if(null != go && null != names) { var goes = new GameObject[names.Length]; for(int i= 0; i< names.Length; ++i) { var name = names[i]; foreach(Transform child in go.transform) { if(child.name == name) { goes[i] = child.gameObject; break; } } } return goes; } return null; } public static GameObject GetRootObject(this GameObject go) { if (go == null) { return null; } var root = go.transform; while (root.parent!=null) { root = root.parent; } return root.gameObject; } public static IEnumerable<GameObject> GetDirectChildren(this GameObject go) { if(null != go) { foreach(Transform child in go.transform) { yield return child.gameObject; } } } public static void DeleteChildren(this GameObject go) { if (go != null) { int count = go.transform.childCount; for (int i = count -1; i >=0; i--) { GameObject.Destroy(go.transform.GetChild(i).gameObject); } } } public static void DeleteChildrenImmediate(this GameObject go) { if (go != null) { int count = go.transform.childCount; for (int i = count - 1; i >= 0; i--) { GameObject.DestroyImmediate(go.transform.GetChild(i).gameObject,true); } } } public static string GetPath(this GameObject go) { GameObject current = go; string path = current.name; while(null != current.transform.parent) { current = current.transform.parent.gameObject; path = current.name + "/" + path; } return path; } public static void SetLayerRecursively(this GameObject go, string layer) { if(null == go) return; go.layer = LayerMask.NameToLayer(layer); foreach(Transform child in go.transform) child.gameObject.SetLayerRecursively(layer); } public static void SetLayerRecursively(this GameObject go, int layer) { if(null == go) return; go.layer = layer; foreach(Transform child in go.transform) child.gameObject.SetLayerRecursively(layer); } public static bool GetActive(this GameObject go) { return go && go.activeInHierarchy; } public static IEnumerable<GameObject> WalkTree(this GameObject root) { if(null != root) { yield return root; foreach(Transform child in root.transform) { foreach(var grandson in child.gameObject.WalkTree()) { yield return grandson; } } } } public static void ReplaceMaterials(this GameObject root, Material material) { foreach(var child in root.WalkTree()) { var childRenderer = child.GetComponent<Renderer>(); if(null == childRenderer || null == childRenderer.sharedMaterials) { continue; } var materials = new Material[childRenderer.sharedMaterials.Length]; for(int i= 0; i< materials.Length; ++i) { materials[i]= material; } childRenderer.sharedMaterials = materials; } } public static void SynchronizeShape(this GameObject destination, GameObject source) { if(null == source || null == destination) { string s = string.Format("source={0}, destination={1}", source, destination); UnityEngine.Debug.LogError(s); return; } destination.transform.SynchronizeShape(source.transform); } public static T SetDefaultComponent<T>(this GameObject go) where T : Component { if(null != go) { var component = go.GetComponent<T>(); if(null == component) { component = go.AddComponent<T>(); } return component; } return null; } public static T GetComponentNull<T>(this Component c, string path) where T : Component { if(c != null) { var t = c.transform; t = t.Find(path); if(t != null) return t.GetComponent<T>(); } return null; } public static T GetComponentNull<T>(this GameObject c, string path) where T : Component { if(c != null) { var t = c.transform; t = t.Find(path); if(t != null) return t.GetComponent<T>(); } return null; } public static T GetComponenetInParents<T>(this GameObject c) where T : Component { T com = null; if (c != null) { Transform t = c.transform.parent; while (t != null) { com = t.GetComponent<T>(); if (com != null) { return com; } t = t.parent; } } return null; } public static bool IsNullOrBeDestroyed(this GameObject go) { return go == null ||go.transform == null; } } <file_sep>using UnityEngine; using UnityEditor; using Flux; namespace FluxEditor { [CustomEditor(typeof(FPlayParticleEvent))] public class FPlayParticleEventInspector : FEventInspector { private FPlayParticleEvent _playParticleEvent = null; private SerializedProperty _randomSeed = null; private SerializedProperty _particleSystem = null; private GUIContent _randomSeedUI; private GUIContent _particleSystemUI; protected override void OnEnable() { base.OnEnable(); _playParticleEvent = (FPlayParticleEvent)target; _randomSeed = serializedObject.FindProperty("_randomSeed"); _particleSystem = serializedObject.FindProperty("_particleSystem"); _randomSeedUI = new GUIContent("随机种子"); _particleSystemUI = new GUIContent("粒子对象"); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PropertyField(_randomSeed, _randomSeedUI); if (GUILayout.Button(new GUIContent("R", "随机获得一个种子"), GUILayout.Width(25))) _randomSeed.intValue = Random.Range(0, int.MaxValue); EditorGUILayout.EndHorizontal(); if (_randomSeed.intValue == 0) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("A random seed of 0 means that it always randomizes the particle system, which breaks backwards play of particle systems", MessageType.Warning); if (GUILayout.Button("Fix", GUILayout.Width(40), GUILayout.Height(40))) _randomSeed.intValue = Random.Range(0, int.MaxValue); EditorGUILayout.EndHorizontal(); } EditorGUILayout.PropertyField(_particleSystem, _particleSystemUI); serializedObject.ApplyModifiedProperties(); ParticleSystem particleSystem = _particleSystem.objectReferenceValue as ParticleSystem; if (particleSystem == null) { EditorGUILayout.HelpBox("粒子事件中未添加粒子对象", MessageType.Warning); return; } if (_playParticleEvent.LengthTime > particleSystem.main.duration || _playParticleEvent.LengthTime > particleSystem.main.startLifetime.constant) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.HelpBox("粒子的持续时间/开始时间小于事件长度,这将与游戏运行时结果不一致", MessageType.Warning); if (GUILayout.Button("Fix", GUILayout.Width(40), GUILayout.Height(40))) { int selectedOption = EditorUtility.DisplayDialogComplex("修正粒子事件?", "不幸的是,Unity的粒子系统并不完全支持向后播放." + "你想怎么纠正这个?" + "\n - 增加粒子持续时间:使粒子持续时间与事件的长度相同" + "\n - 收缩事件:将事件大小调整为粒子系统的长度", "增加粒子持续时间", "取消", "收缩事件"); switch (selectedOption) { case 0: // Increase duration SerializedObject particleSystemSO = new SerializedObject(particleSystem); particleSystemSO.FindProperty("lengthInSec").floatValue = _playParticleEvent.LengthTime; particleSystemSO.FindProperty("InitialModule.startLifetime.scalar").floatValue = _playParticleEvent.LengthTime; particleSystemSO.ApplyModifiedProperties(); break; case 1: // Cancel break; case 2: // Shrink event FUtility.Rescale(_playParticleEvent, new FrameRange(_playParticleEvent.FrameRange.Start, Mathf.RoundToInt(Mathf.Min(particleSystem.main.duration, particleSystem.main.startLifetime.constant) * _playParticleEvent.Sequence.FrameRate))); break; } } EditorGUILayout.EndHorizontal(); } } } }<file_sep>using UnityEngine; using System.Collections; using XmlCfg.Skill; namespace Flux { [FEvent("控制器/投射物体")] public class FCastObject : FController { [SerializeField, HideInInspector] private int _curveId; [SerializeField, HideInInspector] private bool _isTraceTarget; [SerializeField, HideInInspector] private bool _passBody; [SerializeField, HideInInspector] private Vector3 _position; [SerializeField, HideInInspector] private Vector3 _eulerAngles; private Transform _targetObj; private float _startTime; protected override void OnTrigger(float timeSinceTrigger) { base.OnTrigger(timeSinceTrigger); var go = FUtility.FindGameObject(_path); if (go != null) { _targetObj = go.transform; _targetObj.localPosition = _position; _targetObj.localEulerAngles = _eulerAngles; } _startTime = timeSinceTrigger; } protected override void OnUpdateEvent(float timeSinceTrigger) { base.OnUpdateEvent(timeSinceTrigger); if (_targetObj == null) return; } protected override void OnStop() { base.OnStop(); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Flux { public class FEnumField : PropertyAttribute { public Type EnumType; public FEnumField(Type enumType) { EnumType = enumType; } } }
d4b216d868d7c3426bf83c7da0f08bce99ff8ee5
[ "Markdown", "C#", "Lua" ]
191
C#
B-CK/X-lua
68b0f001aefeeebc122f2d0ed23e1ff8f8363191
4b23b23b78630f26314c93ae53042ece9feb9893
refs/heads/master
<repo_name>Mnantier/dana-project<file_sep>/Dana.java package com.mnanti.rdftp; import java.io.InputStream; import org.apache.jena.query.*; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.util.FileManager; public class Dana { static final String file = "rdf.ttl"; public static void main (String args[]) { Model model = ModelFactory.createDefaultModel(); InputStream in = FileManager.get().open( file ); if (in == null) { throw new IllegalArgumentException( "File: " + file + " not found"); } model.read(in, null, "Turtle"); String prefix = "PREFIX dbo: <http://dbpedia.org/ontology/> \n" + "PREFIX eus: <http://ontologycentral.com/2009/01/eurostat/ns#> \n" + "PREFIX sdmx-measure: <http://purl.org/linked-data/sdmx/2009/measure#> \n" + "PREFIX dcterms: <http://purl.org/dc/terms/> \n"+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> \n"; String query1 = prefix+ "SELECT DISTINCT ?pays (MAX(?nb) AS ?max) WHERE {\n" + " ?x eus:geo \"WORLD\"; \n" + " dbo:Country ?pays ; \n" + " sdmx-measure:obsValue ?nb \n" + "} \n" + "GROUP BY ?pays \n"+ "ORDER BY DESC(?max) \n"; String query2 = prefix + "SELECT ?pays ?evolution WHERE {\n" + " ?x eus:geo \"WORLD\";\n" + " dcterms:date 2007;\n" + " dbo:Country ?pays;\n" + " sdmx-measure:obsValue ?nb2007. \n"+ " ?y eus:geo \"WORLD\";\n" + " dcterms:date 2018;\n" + " dbo:Country ?pays;\n" + " sdmx-measure:obsValue ?nb2018 \n"+ " BIND (?nb2018 / ?nb2007 AS ?evolution) \n"+ "}\n" + "GROUP BY ?pays ?evolution \n"+ "ORDER BY ASC(?pays) \n"; Query query = QueryFactory.create(query1) ; try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) { ResultSet results = qexec.execSelect() ; ResultSetFormatter.out(System.out, results, query) ; } query = QueryFactory.create(query2) ; try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) { ResultSet results = qexec.execSelect() ; ResultSetFormatter.out(System.out, results, query) ; } } }
ec36b499495592a8228bc518988cf71d05adac69
[ "Java" ]
1
Java
Mnantier/dana-project
75cdfaba52c5db6382305806efbe210e5232ec08
9910a32da6bb860fb4ed5537b4f30c232d665d88